#![forbid(unsafe_code)]
#![warn(rustdoc::broken_intra_doc_links)]
//! Columnar storage layer for **frankenpandas** — provides the
//! [`Column`] container that backs every `DataFrame` column and
//! `Series` value buffer in fp-frame.
//!
//! A column is a typed value buffer ([`DType`]) plus a separate
//! [`ValidityMask`] tracking which cells are missing. This split
//! mirrors Apache Arrow's storage layout and lets the type system
//! enforce correctness on the dense-value side while keeping
//! pandas-style missing-value semantics ([`NullKind::Null`],
//! [`NullKind::NaN`], [`NullKind::NaT`]) on the validity side.
//!
//! ## Public surface
//!
//! - [`Column`]: the public columnar container. Built from a
//! [`DType`] + a `Vec<Scalar>`. Exposes value access
//! ([`Column::value`], [`Column::values`]), reductions
//! ([`Column::sum`], [`Column::mean`], [`Column::count`], the
//! nan-aware aggregations from fp-types), and typed binary
//! operations dispatched through [`ArithmeticOp`] /
//! [`ComparisonOp`].
//! - [`ColumnData`]: the inner enum holding the dense buffer. Most
//! callers go through `Column` rather than touching this directly.
//! - [`SparseColumn`]: opt-in sparse encoding (paired value buffer +
//! index-of-non-fill positions). Stored alongside the dense
//! `Column` for backwards compat when consumers only need
//! [`Column`].
//! - [`ValidityMask`]: per-cell missing-value bitmap. Stored on
//! [`Column`]; exposed for users that want to compose masks
//! directly (logical masking, conditional updates, etc.).
//! - [`ArithmeticOp`] / [`ComparisonOp`]: enum tags for typed
//! binary-op dispatch (used by fp-frame's expression engine and
//! Series arithmetic).
//! - [`CrackIndex`]: an internal positional index used by the
//! "cracking" optimisation for repeated boolean-mask filters.
//!
//! ## Error reporting
//!
//! [`ColumnError`] enumerates the failure modes (length mismatch,
//! dtype mismatch, missing-value-in-required-slot, etc.). All
//! Column-mutating fns return `Result<_, ColumnError>` so callers
//! get explicit error categories.
//!
//! ## Relationship to other crates
//!
//! - **fp-types** supplies the [`DType`] / [`Scalar`] /
//! [`NullKind`] / `nan*` reduction primitives this crate composes
//! on top of.
//! - **fp-frame** stores a `Vec<Column>` per `DataFrame` (one column
//! per data column) plus a separate `Index` from fp-index for the
//! row labels.
//! - **fp-index** uses [`Column`] internally for some MultiIndex
//! level storage.
use std::sync::{Arc, OnceLock};
use fp_types::{
DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType, Timedelta,
Timestamp, TypeError, cast_scalar, cast_scalar_owned, common_dtype, infer_dtype, nanall,
nanany, nanargmax, nanargmin, nancummax, nancummin, nancumprod, nancumsum, nankurt, nanmax,
nanmean, nanmedian, nanmin, nannunique, nanprod, nanptp, nanquantile, nansem, nanskew, nanstd,
nansum, nanvar,
};
use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize};
use thiserror::Error;
const STRIDED_FLOAT64_MIN_LEN: usize = 1024;
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Utf8LowerHexSequence {
prefix_len: usize,
hex_width: usize,
start: u64,
}
impl Utf8LowerHexSequence {
#[must_use]
pub fn prefix_len(&self) -> usize {
self.prefix_len
}
#[must_use]
pub fn hex_width(&self) -> usize {
self.hex_width
}
#[must_use]
pub fn width(&self) -> usize {
self.prefix_len + self.hex_width
}
#[must_use]
pub fn start(&self) -> u64 {
self.start
}
#[must_use]
pub fn value_at(&self, row: usize) -> Option<u64> {
self.start.checked_add(row as u64)
}
#[must_use]
pub fn same_shape(&self, other: Self) -> bool {
self.prefix_len == other.prefix_len && self.hex_width == other.hex_width
}
}
#[derive(Debug)]
struct Utf8FactorizeDefaultWitness {
codes: Arc<[i64]>,
unique_bytes: Arc<[u8]>,
unique_offsets: Arc<[usize]>,
}
fn fixed_width_utf8_offsets_le16(bytes_len: usize, offsets: &[usize]) -> Option<usize> {
let nrows = offsets.len().checked_sub(1)?;
if nrows == 0 || offsets.first().copied()? != 0 || offsets.get(nrows).copied()? != bytes_len {
return None;
}
let width = bytes_len / nrows;
if width == 0 || width > 16 || width * nrows != bytes_len {
return None;
}
for (row, &offset) in offsets.iter().enumerate() {
if offset != row * width {
return None;
}
}
Some(width)
}
fn pack_fixed_width_utf8_span(span: &[u8]) -> u128 {
debug_assert!(span.len() <= 16);
let mut packed = 0_u128;
for &byte in span {
packed = (packed << 8) | u128::from(byte);
}
packed
}
fn build_utf8_factorize_default_witness(
bytes: &[u8],
offsets: &[usize],
) -> Utf8FactorizeDefaultWitness {
let nrows = offsets.len().saturating_sub(1);
let mut codes: Vec<i64> = Vec::with_capacity(nrows);
let mut unique_bytes: Vec<u8> = Vec::new();
let mut unique_offsets: Vec<usize> = Vec::new();
unique_offsets.push(0);
if let Some(width) = fixed_width_utf8_offsets_le16(bytes.len(), offsets) {
let mut idx_map: FxHashMap<u128, i64> = FxHashMap::default();
for row in 0..nrows {
let start = row * width;
let span = &bytes[start..start + width];
let key = pack_fixed_width_utf8_span(span);
let code = match idx_map.get(&key) {
Some(&code) => code,
None => {
let code = unique_offsets.len() as i64 - 1;
idx_map.insert(key, code);
unique_bytes.extend_from_slice(span);
unique_offsets.push(unique_bytes.len());
code
}
};
codes.push(code);
}
} else {
let mut idx_map: FxHashMap<&[u8], i64> = FxHashMap::default();
for row in 0..nrows {
let span = &bytes[offsets[row]..offsets[row + 1]];
let code = match idx_map.get(span) {
Some(&code) => code,
None => {
let code = unique_offsets.len() as i64 - 1;
idx_map.insert(span, code);
unique_bytes.extend_from_slice(span);
unique_offsets.push(unique_bytes.len());
code
}
};
codes.push(code);
}
}
Utf8FactorizeDefaultWitness {
codes: Arc::from(codes),
unique_bytes: Arc::from(unique_bytes),
unique_offsets: Arc::from(unique_offsets),
}
}
#[derive(Debug, Clone, Eq)]
pub struct ValidityMask {
words: Vec<u64>,
invalid_ranges: Option<Arc<[(usize, usize)]>>,
len: usize,
}
impl ValidityMask {
fn is_all_valid_sentinel(&self) -> bool {
self.len > 0 && self.words.is_empty() && self.invalid_ranges.is_none()
}
fn invalid_ranges_contain(ranges: &[(usize, usize)], idx: usize) -> bool {
let mut lo = 0usize;
let mut hi = ranges.len();
while lo < hi {
let mid = (lo + hi) / 2;
let (start, len) = ranges[mid];
let end = start + len;
if idx < start {
hi = mid;
} else if idx >= end {
lo = mid + 1;
} else {
return true;
}
}
false
}
fn invalid_ranges_len(ranges: &[(usize, usize)]) -> usize {
ranges.iter().map(|&(_, len)| len).sum()
}
fn materialized_all_valid_words(len: usize) -> Vec<u64> {
let word_count = len.div_ceil(64);
let mut words = vec![u64::MAX; word_count];
let remainder = len % 64;
if remainder > 0
&& let Some(last) = words.last_mut()
{
*last = (1_u64 << remainder) - 1;
}
words
}
fn materialized_words(&self) -> Vec<u64> {
if self.is_all_valid_sentinel() {
return Self::materialized_all_valid_words(self.len);
}
if let Some(ranges) = &self.invalid_ranges {
let mut words = Self::materialized_all_valid_words(self.len);
for &(start, len) in ranges.iter() {
for idx in start..start + len {
words[idx / 64] &= !(1_u64 << (idx % 64));
}
}
return words;
}
self.words.clone()
}
/// Return LSB-first packed validity words for hot typed kernels that scan
/// many rows. This preserves the same sentinel and range semantics as
/// [`ValidityMask::get`] while avoiding one branchy call per element.
#[must_use]
#[doc(hidden)]
pub fn packed_words_for_scan(&self) -> Vec<u64> {
self.materialized_words()
}
fn words_are_all_valid(words: &[u64], len: usize) -> bool {
if len == 0 {
return words.is_empty();
}
let word_count = len.div_ceil(64);
if words.len() != word_count {
return false;
}
let full_words = len / 64;
if words.iter().take(full_words).any(|&word| word != u64::MAX) {
return false;
}
let remainder = len % 64;
if remainder == 0 {
return true;
}
words.get(full_words).copied() == Some((1_u64 << remainder) - 1)
}
fn materialize_if_all_valid_sentinel(&mut self) {
if self.is_all_valid_sentinel() || self.invalid_ranges.is_some() {
self.words = self.materialized_words();
self.invalid_ranges = None;
}
}
#[must_use]
pub fn from_values(values: &[Scalar]) -> Self {
let len = values.len();
let word_count = len.div_ceil(64);
let mut words = vec![0_u64; word_count];
let mut all_valid = true;
for (idx, value) in values.iter().enumerate() {
if !value.is_missing() {
words[idx / 64] |= 1_u64 << (idx % 64);
} else {
all_valid = false;
}
}
if all_valid {
return Self::all_valid(len);
}
Self {
words,
invalid_ranges: None,
len,
}
}
/// Build a validity mask from a contiguous `f64` buffer, marking NaN
/// positions invalid. pandas treats float NaN as missing, so this mirrors
/// what `from_values` would produce for the equivalent `Scalar::Float64`
/// values (`Scalar::is_missing` is true for NaN). See
/// [`Column::from_f64_values`].
#[must_use]
pub fn from_f64(data: &[f64]) -> Self {
let len = data.len();
let word_count = len.div_ceil(64);
let mut words = vec![0_u64; word_count];
let mut all_valid = true;
for (idx, &v) in data.iter().enumerate() {
if !v.is_nan() {
words[idx / 64] |= 1_u64 << (idx % 64);
} else {
all_valid = false;
}
}
if all_valid {
return Self::all_valid(len);
}
Self {
words,
invalid_ranges: None,
len,
}
}
#[must_use]
pub fn all_valid(len: usize) -> Self {
Self {
words: Vec::new(),
invalid_ranges: None,
len,
}
}
/// Build a mask from pre-packed validity words (LSB-first within each
/// word, bit `i` of word `i / 64` = row `i` valid). Bits at positions
/// `>= len` must be zero. Public (hidden) for typed builders that compute
/// validity in bulk (br-frankenpandas-7wxoc).
#[must_use]
#[doc(hidden)]
pub fn from_words(words: Vec<u64>, len: usize) -> Self {
debug_assert_eq!(words.len(), len.div_ceil(64));
debug_assert!(
len.is_multiple_of(64) || words.last().is_none_or(|w| w >> (len % 64) == 0),
"validity bits beyond len must be zero"
);
if Self::words_are_all_valid(&words, len) {
return Self::all_valid(len);
}
Self {
words,
invalid_ranges: None,
len,
}
}
#[must_use]
#[doc(hidden)]
pub fn from_invalid_ranges(invalid_ranges: Arc<[(usize, usize)]>, len: usize) -> Self {
debug_assert!(
invalid_ranges.iter().all(|&(start, run_len)| {
start.checked_add(run_len).is_some_and(|end| end <= len)
})
);
debug_assert!(invalid_ranges.windows(2).all(|window| {
let (left_start, left_len) = window[0];
let (right_start, _) = window[1];
left_start + left_len <= right_start
}));
if invalid_ranges.is_empty() {
return Self::all_valid(len);
}
Self {
words: Vec::new(),
invalid_ranges: Some(invalid_ranges),
len,
}
}
#[must_use]
pub fn all_invalid(len: usize) -> Self {
let word_count = len.div_ceil(64);
Self {
words: vec![0_u64; word_count],
invalid_ranges: None,
len,
}
}
#[must_use]
pub fn get(&self, idx: usize) -> bool {
if idx >= self.len {
return false;
}
if self.is_all_valid_sentinel() {
return true;
}
if let Some(ranges) = &self.invalid_ranges {
return !Self::invalid_ranges_contain(ranges, idx);
}
(self.words[idx / 64] >> (idx % 64)) & 1 == 1
}
pub fn set(&mut self, idx: usize, value: bool) {
if idx >= self.len {
return;
}
if self.is_all_valid_sentinel() {
if value {
return;
}
self.materialize_if_all_valid_sentinel();
} else if self.invalid_ranges.is_some() {
self.materialize_if_all_valid_sentinel();
}
if value {
self.words[idx / 64] |= 1_u64 << (idx % 64);
} else {
self.words[idx / 64] &= !(1_u64 << (idx % 64));
}
}
#[must_use]
pub fn count_valid(&self) -> usize {
if self.is_all_valid_sentinel() {
return self.len;
}
if let Some(ranges) = &self.invalid_ranges {
return self.len.saturating_sub(Self::invalid_ranges_len(ranges));
}
let full_words = self.len / 64;
let mut count: u32 = self.words[..full_words]
.iter()
.map(|w| w.count_ones())
.sum();
let remainder = self.len % 64;
if remainder > 0 && full_words < self.words.len() {
let mask = (1_u64 << remainder) - 1;
count += (self.words[full_words] & mask).count_ones();
}
count as usize
}
#[must_use]
pub fn len(&self) -> usize {
self.len
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[must_use]
pub fn and_mask(&self, other: &Self) -> Self {
let len = self.len.min(other.len);
if len == 0 {
return Self::all_invalid(0);
}
if self.is_all_valid_sentinel() && other.is_all_valid_sentinel() {
return Self::all_valid(len);
}
if self.is_all_valid_sentinel() {
return other.slice(0, len);
}
if other.is_all_valid_sentinel() {
return self.slice(0, len);
}
let left_words = self.materialized_words();
let right_words = other.materialized_words();
let word_count = len.div_ceil(64);
let words = left_words[..word_count]
.iter()
.zip(&right_words[..word_count])
.map(|(a, b)| a & b)
.collect();
Self::from_words(words, len)
}
#[must_use]
pub fn or_mask(&self, other: &Self) -> Self {
let len = self.len.min(other.len);
if len == 0 {
return Self::all_invalid(0);
}
if self.is_all_valid_sentinel() || other.is_all_valid_sentinel() {
return Self::all_valid(len);
}
let left_words = self.materialized_words();
let right_words = other.materialized_words();
let word_count = len.div_ceil(64);
let words = left_words[..word_count]
.iter()
.zip(&right_words[..word_count])
.map(|(a, b)| a | b)
.collect();
Self::from_words(words, len)
}
#[must_use]
pub fn not_mask(&self) -> Self {
if self.is_all_valid_sentinel() {
return Self::all_invalid(self.len);
}
let mut words: Vec<u64> = self.materialized_words().iter().map(|w| !w).collect();
let remainder = self.len % 64;
if remainder > 0 && !words.is_empty() {
let last = words.len() - 1;
words[last] &= (1_u64 << remainder) - 1;
}
Self::from_words(words, self.len)
}
/// Returns an iterator yielding bool values, compatible with the previous
/// `&[bool]` API. Materializes from the packed representation.
pub fn bits(&self) -> impl Iterator<Item = bool> + '_ {
(0..self.len).map(|idx| self.get(idx))
}
#[doc(hidden)]
pub fn for_each_invalid_range(&self, mut visit: impl FnMut(usize, usize)) {
if self.len == 0 || self.is_all_valid_sentinel() {
return;
}
if let Some(ranges) = &self.invalid_ranges {
for &(start, len) in ranges.iter() {
visit(start, len);
}
return;
}
let mut pending_start = 0usize;
let mut pending_len = 0usize;
for word_idx in 0..self.len.div_ceil(64) {
let mut invalid_bits = !self.words.get(word_idx).copied().unwrap_or(0);
if word_idx == self.len / 64 {
let remainder = self.len % 64;
if remainder > 0 {
invalid_bits &= (1_u64 << remainder) - 1;
}
}
while invalid_bits != 0 {
let bit_start = invalid_bits.trailing_zeros() as usize;
let shifted = invalid_bits >> bit_start;
let run_len = (!shifted).trailing_zeros() as usize;
let start = word_idx * 64 + bit_start;
if pending_len > 0 && pending_start + pending_len == start {
pending_len += run_len;
} else {
if pending_len > 0 {
visit(pending_start, pending_len);
}
pending_start = start;
pending_len = run_len;
}
let run_mask = if run_len == 64 {
u64::MAX
} else {
((1_u64 << run_len) - 1) << bit_start
};
invalid_bits &= !run_mask;
}
}
if pending_len > 0 {
visit(pending_start, pending_len);
}
}
/// Number of invalid (cleared) positions.
#[must_use]
pub fn count_invalid(&self) -> usize {
self.len.saturating_sub(self.count_valid())
}
/// Whether any bit is set.
#[must_use]
pub fn any(&self) -> bool {
if self.is_all_valid_sentinel() {
return true;
}
if let Some(ranges) = &self.invalid_ranges {
return Self::invalid_ranges_len(ranges) < self.len;
}
self.words.iter().any(|&word| word != 0)
}
/// Whether all bits are set.
#[must_use]
pub fn all(&self) -> bool {
if self.is_all_valid_sentinel() {
return true;
}
// A sparse-range mask is constructed only with at least one invalid
// range, so it can decline immediately. Packed masks need only find
// the first non-full word instead of popcounting every word.
if self.invalid_ranges.is_some() {
return false;
}
Self::words_are_all_valid(&self.words, self.len)
}
/// Bitwise XOR (symmetric difference) with another mask.
///
/// Produced length is `min(self.len, other.len)`.
#[must_use]
pub fn xor_mask(&self, other: &Self) -> Self {
let len = self.len.min(other.len);
if len == 0 {
return Self::all_invalid(0);
}
if self.is_all_valid_sentinel() && other.is_all_valid_sentinel() {
return Self::all_invalid(len);
}
if self.is_all_valid_sentinel() {
return other.slice(0, len).not_mask();
}
if other.is_all_valid_sentinel() {
return self.slice(0, len).not_mask();
}
let left_words = self.materialized_words();
let right_words = other.materialized_words();
let word_count = len.div_ceil(64);
let mut words: Vec<u64> = left_words[..word_count]
.iter()
.zip(&right_words[..word_count])
.map(|(a, b)| a ^ b)
.collect();
let remainder = len % 64;
if remainder > 0 && !words.is_empty() {
let last = words.len() - 1;
words[last] &= (1_u64 << remainder) - 1;
}
Self::from_words(words, len)
}
/// Extract a contiguous sub-range as a new mask.
///
/// `start..start+len` is clamped to the available tail — callers
/// don't need to pre-validate against `self.len`.
#[must_use]
pub fn slice(&self, start: usize, len: usize) -> Self {
if start >= self.len {
return Self::all_invalid(0);
}
let effective_len = len.min(self.len - start);
if self.is_all_valid_sentinel() {
return Self::all_valid(effective_len);
}
// Packed nullable masks are already laid out LSB-first in u64 words.
// Extract each output word from at most two adjacent source words instead
// of probing and setting every bit independently. The sparse-range
// representation keeps its existing path below: materializing it merely
// to make a slice would discard the representation's compactness.
if self.invalid_ranges.is_none() {
let source_word = start / 64;
let shift = start % 64;
let mut words = Vec::with_capacity(effective_len.div_ceil(64));
for output_word in 0..effective_len.div_ceil(64) {
let low = self.words[source_word + output_word] >> shift;
let high = if shift == 0 {
0
} else {
self.words
.get(source_word + output_word + 1)
.copied()
.unwrap_or(0)
<< (64 - shift)
};
words.push(low | high);
}
let remainder = effective_len % 64;
if remainder > 0 {
*words.last_mut().expect("non-empty sliced validity") &= (1_u64 << remainder) - 1;
}
return Self::from_words(words, effective_len);
}
let mut out = Self::all_invalid(effective_len);
for i in 0..effective_len {
if self.get(start + i) {
out.set(i, true);
}
}
out
}
/// Append another mask's bits to the end of this one.
#[must_use]
pub fn concat(&self, other: &Self) -> Self {
let total = self.len + other.len;
if self.all() && other.all() {
return Self::all_valid(total);
}
// Nullable packed masks already store the exact bit stream needed by
// the result. Append whole words, merging only across the one boundary
// word when the left length is not word-aligned. Sparse-range masks
// keep the representation-preserving fallback below, while all-valid
// sentinels retain their existing handling.
if self.invalid_ranges.is_none()
&& other.invalid_ranges.is_none()
&& !self.is_all_valid_sentinel()
&& !other.is_all_valid_sentinel()
{
let word_count = total.div_ceil(64);
let mut words = vec![0_u64; word_count];
words[..self.words.len()].copy_from_slice(&self.words);
let output_word = self.len / 64;
let shift = self.len % 64;
for (idx, &word) in other.words.iter().enumerate() {
words[output_word + idx] |= word << shift;
if shift != 0 && output_word + idx + 1 < word_count {
words[output_word + idx + 1] |= word >> (64 - shift);
}
}
let remainder = total % 64;
if remainder > 0 {
*words.last_mut().expect("non-empty concatenated validity") &=
(1_u64 << remainder) - 1;
}
return Self::from_words(words, total);
}
let mut out = Self::all_invalid(total);
for i in 0..self.len {
if self.get(i) {
out.set(i, true);
}
}
for i in 0..other.len {
if other.get(i) {
out.set(self.len + i, true);
}
}
out
}
/// Position of the first valid bit.
#[must_use]
pub fn first_valid(&self) -> Option<usize> {
if self.is_all_valid_sentinel() {
return Some(0);
}
(0..self.len).find(|&i| self.get(i))
}
/// Position of the last valid bit.
#[must_use]
pub fn last_valid(&self) -> Option<usize> {
if self.is_all_valid_sentinel() {
return Some(self.len - 1);
}
(0..self.len).rev().find(|&i| self.get(i))
}
}
impl PartialEq for ValidityMask {
fn eq(&self, other: &Self) -> bool {
self.len == other.len && self.bits().eq(other.bits())
}
}
impl Serialize for ValidityMask {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let bits: Vec<bool> = self.bits().collect();
let mut state = serializer.serialize_struct("ValidityMask", 1)?;
state.serialize_field("bits", &bits)?;
state.end()
}
}
impl<'de> Deserialize<'de> for ValidityMask {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct Raw {
bits: Vec<bool>,
}
let raw = Raw::deserialize(deserializer)?;
let len = raw.bits.len();
let word_count = len.div_ceil(64);
let mut words = vec![0_u64; word_count];
for (idx, &valid) in raw.bits.iter().enumerate() {
if valid {
words[idx / 64] |= 1_u64 << (idx % 64);
}
}
Ok(Self::from_words(words, len))
}
}
/// AG-10: Typed array representation for vectorized batch execution.
///
/// Stores column data as contiguous typed arrays rather than `Vec<Scalar>`.
/// Validity is tracked by `ValidityMask`; invalid positions hold unspecified
/// values in the typed array (callers must check validity before reading).
///
/// This eliminates per-element enum dispatch for arithmetic operations,
/// enabling SIMD auto-vectorization on `&[f64]` / `&[i64]` slices.
#[derive(Debug, Clone, PartialEq)]
pub enum ColumnData {
Float64(Arc<[f64]>),
Int64(Arc<[i64]>),
Bool(Arc<[bool]>),
Utf8(Vec<String>),
Timedelta64(Vec<i64>),
Datetime64(Vec<i64>),
/// Period column: per-row ordinals plus the column-uniform frequency
/// (a pandas `PeriodArray` carries a single freq for the whole array).
/// `i64::MIN` ordinals are NaT.
Period(Vec<i64>, PeriodFreq),
Interval(Vec<Interval>),
}
/// Exact witness for all-valid Int64 columns whose key at row `i` is
/// `start + (i % period)`.
///
/// The witness is only produced after scanning every row and checking the
/// closed form exactly. Consumers may derive bucket counts and input positions
/// from it, but must fall back to the source slice when the witness is absent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[doc(hidden)]
pub struct Int64DenseCycleWitness {
pub start: i64,
pub period: usize,
pub len: usize,
}
impl Int64DenseCycleWitness {
#[must_use]
pub fn offset_count_for_key(self, key: i64) -> Option<(usize, usize)> {
let offset = usize::try_from(key.checked_sub(self.start)?).ok()?;
if offset >= self.period {
return None;
}
let full_cycles = self.len / self.period;
let tail = self.len % self.period;
let count = full_cycles + usize::from(offset < tail);
(count > 0).then_some((offset, count))
}
}
#[derive(Clone)]
struct Int64Chunk {
data: Arc<[i64]>,
start: usize,
len: usize,
}
impl Int64Chunk {
fn new(data: Arc<[i64]>, start: usize, len: usize) -> Self {
debug_assert!(start.checked_add(len).is_some_and(|end| end <= data.len()));
Self { data, start, len }
}
fn as_slice(&self) -> &[i64] {
&self.data[self.start..self.start + self.len]
}
}
#[derive(Clone)]
struct Float64Chunk {
data: Arc<[f64]>,
start: usize,
len: usize,
}
impl Float64Chunk {
fn new(data: Arc<[f64]>, start: usize, len: usize) -> Self {
debug_assert!(start.checked_add(len).is_some_and(|end| end <= data.len()));
Self { data, start, len }
}
fn as_slice(&self) -> &[f64] {
&self.data[self.start..self.start + self.len]
}
}
#[derive(Clone)]
struct Float64DotInput {
data: Arc<[f64]>,
start: usize,
}
impl Float64DotInput {
fn new(data: Arc<[f64]>, start: usize, len: usize) -> Self {
debug_assert!(start.checked_add(len).is_some_and(|end| end <= data.len()));
Self { data, start }
}
fn value_at(&self, row: usize) -> f64 {
self.data[self.start + row]
}
}
/// A shared left-hand (`A`) panel for `df.dot`: the `k` A-columns built once
/// as `Float64DotInput`s and shared (`Arc`) across all `n` output columns of a
/// single dot product, so construction is O(k) once + O(n) Arc bumps instead
/// of O(n·k). Opaque handle over the crate-private `Float64DotInput`.
#[derive(Clone)]
pub struct Float64DotAPanel(Arc<[Float64DotInput]>);
impl Float64DotAPanel {
/// Build the panel from `(buffer, start)` column views, each of `len` rows.
#[must_use]
pub fn new(a_cols: Vec<(Arc<[f64]>, usize)>, len: usize) -> Self {
let inputs: Vec<Float64DotInput> = a_cols
.into_iter()
.map(|(data, start)| Float64DotInput::new(data, start, len))
.collect();
Self(Arc::from(inputs))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[doc(hidden)]
pub enum PairwiseFloat64Stat {
Corr,
Cov,
}
#[derive(Clone)]
struct Float64PairwiseStatInput {
data: Arc<[f64]>,
start: usize,
}
impl Float64PairwiseStatInput {
fn new(data: Arc<[f64]>, start: usize, len: usize) -> Self {
debug_assert!(start.checked_add(len).is_some_and(|end| end <= data.len()));
Self { data, start }
}
fn value_at(&self, row: usize) -> f64 {
self.data[self.start + row]
}
}
struct Float64PairwiseStatMatrixPlan {
cols: Arc<[Float64PairwiseStatInput]>,
row_len: usize,
stat: PairwiseFloat64Stat,
min_periods: usize,
matrix: OnceLock<Arc<[f64]>>,
}
impl Float64PairwiseStatMatrixPlan {
fn new(
cols: Arc<[Float64PairwiseStatInput]>,
row_len: usize,
stat: PairwiseFloat64Stat,
min_periods: usize,
) -> Self {
Self {
cols,
row_len,
stat,
min_periods,
matrix: OnceLock::new(),
}
}
fn column_len(&self) -> usize {
self.cols.len()
}
fn materialize_column(&self, col: usize) -> Vec<f64> {
let n = self.column_len();
debug_assert!(col < n);
let matrix = self
.matrix
.get_or_init(|| Arc::from(self.compute_matrix_values()));
(0..n).map(|row| matrix[row * n + col]).collect()
}
#[allow(clippy::too_many_arguments)]
fn finalize(
stat: PairwiseFloat64Stat,
min_periods: usize,
count: usize,
sum_x: f64,
sum_y: f64,
sum_xy: f64,
sum_x2: f64,
sum_y2: f64,
) -> f64 {
let threshold = min_periods.max(2);
if count < threshold {
return f64::NAN;
}
let n_f = count as f64;
let mean_x = sum_x / n_f;
let mean_y = sum_y / n_f;
let cov_xy = (sum_xy - n_f * mean_x * mean_y) / (n_f - 1.0);
match stat {
PairwiseFloat64Stat::Cov => cov_xy,
PairwiseFloat64Stat::Corr => {
let var_x = (sum_x2 - n_f * mean_x * mean_x) / (n_f - 1.0);
let var_y = (sum_y2 - n_f * mean_y * mean_y) / (n_f - 1.0);
let denom = (var_x * var_y).sqrt();
if denom < f64::EPSILON {
f64::NAN
} else {
cov_xy / denom
}
}
}
}
fn compute_matrix_values(&self) -> Vec<f64> {
let n = self.column_len();
let len = self.row_len;
let mut mat = vec![0.0_f64; n * n];
if n == 0 {
return mat;
}
let shifted_storage: Vec<Vec<f64>> = self
.cols
.iter()
.map(|col| {
let k = (0..len)
.map(|row| col.value_at(row))
.find(|x| x.is_finite())
.unwrap_or(0.0);
(0..len).map(|row| col.value_at(row) - k).collect()
})
.collect();
let col_data: Vec<&[f64]> = shifted_storage.iter().map(Vec::as_slice).collect();
let mut sum = vec![0.0_f64; n];
let mut sum2 = vec![0.0_f64; n];
let moment = |col: &[f64]| -> (f64, f64) {
let mut s = 0.0_f64;
let mut s2 = 0.0_f64;
for &x in col {
s += x;
s2 += x * x;
}
(s, s2)
};
let moment_workers = std::thread::available_parallelism()
.map_or(1, std::num::NonZeroUsize::get)
.min(64)
.min(n.max(1));
if moment_workers >= 2 && (len as u128) * (n as u128) >= (1u128 << 20) {
let next_col = std::sync::atomic::AtomicUsize::new(0);
let col_data_ref: &[&[f64]] = &col_data;
let parts = std::thread::scope(|scope| {
let mut handles = Vec::with_capacity(moment_workers);
for _ in 0..moment_workers {
let next_col = &next_col;
handles.push(scope.spawn(move || {
let mut out: Vec<(usize, f64, f64)> = Vec::new();
loop {
let idx = next_col.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if idx >= col_data_ref.len() {
break;
}
let (s, s2) = moment(col_data_ref[idx]);
out.push((idx, s, s2));
}
out
}));
}
let mut all = Vec::with_capacity(handles.len());
for handle in handles {
all.push(handle.join().unwrap_or_default());
}
all
});
for part in parts {
for (idx, s, s2) in part {
sum[idx] = s;
sum2[idx] = s2;
}
}
} else {
for (idx, col) in col_data.iter().enumerate() {
let (s, s2) = moment(col);
sum[idx] = s;
sum2[idx] = s2;
}
}
const BT: usize = 4;
const BAND_COUNT: usize = 64;
let mut gram = vec![0.0_f64; n * n];
let big_enough = (len as u128) * (n as u128) * (n as u128) >= (1u128 << 23);
let band_count = BAND_COUNT.min(len);
if band_count >= 2 && big_enough {
let band = len.div_ceil(band_count);
let bands: Vec<(usize, usize)> = (0..band_count)
.map(|b| (b * band, ((b + 1) * band).min(len)))
.filter(|&(a, b)| a < b)
.collect();
let worker_count = std::thread::available_parallelism()
.map_or(1, std::num::NonZeroUsize::get)
.min(64)
.min(bands.len());
let next_band = std::sync::atomic::AtomicUsize::new(0);
let bands_ref: &[(usize, usize)] = &bands;
let cols_ref: &[&[f64]] = &col_data;
let mut partials: Vec<Vec<f64>> = Vec::new();
std::thread::scope(|scope| {
let mut handles = Vec::with_capacity(worker_count);
for _ in 0..worker_count {
let next_band = &next_band;
handles.push(scope.spawn(move || {
let mut out: Vec<(usize, Vec<f64>)> = Vec::new();
loop {
let b = next_band.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if b >= bands_ref.len() {
break;
}
let (r0, r1) = bands_ref[b];
let mut panel = vec![0.0_f64; (r1 - r0) * BT];
let mut gram_out = vec![0.0_f64; n * n];
pairwise_stat_gram_partial_rows(
cols_ref,
n,
r0,
r1,
&mut panel,
&mut gram_out,
);
out.push((b, gram_out));
}
out
}));
}
let mut indexed: Vec<(usize, Vec<f64>)> = Vec::with_capacity(bands.len());
for handle in handles {
if let Ok(mut part) = handle.join() {
indexed.append(&mut part);
}
}
indexed.sort_by_key(|(b, _)| *b);
partials = indexed.into_iter().map(|(_, g)| g).collect();
});
for partial in &partials {
if partial.len() != n * n {
continue;
}
for j in 0..n {
for i in 0..=j {
gram[i * n + j] += partial[i * n + j];
}
}
}
} else {
let mut panel = vec![0.0_f64; len.max(1) * BT];
pairwise_stat_gram_partial_rows(&col_data, n, 0, len, &mut panel, &mut gram);
}
for j in 0..n {
for i in 0..=j {
let g = gram[i * n + j];
mat[i * n + j] = Self::finalize(
self.stat,
self.min_periods,
len,
sum[i],
sum[j],
g,
sum2[i],
sum2[j],
);
if i != j {
mat[j * n + i] = Self::finalize(
self.stat,
self.min_periods,
len,
sum[j],
sum[i],
g,
sum2[j],
sum2[i],
);
}
}
}
mat
}
}
#[derive(Clone)]
struct Float64TransposeInput {
data: Arc<[f64]>,
start: usize,
}
impl Float64TransposeInput {
fn new(data: Arc<[f64]>, start: usize, len: usize) -> Self {
debug_assert!(start.checked_add(len).is_some_and(|end| end <= data.len()));
Self { data, start }
}
fn value_at(&self, row: usize) -> f64 {
self.data[self.start + row]
}
}
struct Float64TransposeRowsPlan {
cols: Arc<[Float64TransposeInput]>,
row_len: usize,
}
impl Float64TransposeRowsPlan {
fn new(cols: Arc<[Float64TransposeInput]>, row_len: usize) -> Self {
Self { cols, row_len }
}
fn column_len(&self) -> usize {
self.cols.len()
}
fn materialize_row(&self, source_row: usize) -> Vec<f64> {
debug_assert!(source_row < self.row_len);
self.cols
.iter()
.map(|col| col.value_at(source_row))
.collect()
}
}
#[derive(Clone)]
#[doc(hidden)]
pub struct Float64TransposeRows {
plan: Arc<Float64TransposeRowsPlan>,
}
fn pairwise_stat_gram_partial_rows(
col_data: &[&[f64]],
n: usize,
r0: usize,
r1: usize,
panel: &mut [f64],
gram_out: &mut [f64],
) {
const BT: usize = 4;
let rows = r1 - r0;
let mut tj = 0;
while tj < n {
let bj = BT.min(n - tj);
for dj in 0..bj {
let cj = col_data[tj + dj];
for lr in 0..rows {
panel[lr * BT + dj] = cj[r0 + lr];
}
}
let mut ti = 0;
while ti <= tj {
let bi = BT.min(n - ti);
let mut acc = [[0.0_f64; BT]; BT];
if bi == BT && bj == BT {
for lr in 0..rows {
let pr = &panel[lr * BT..lr * BT + BT];
for (di, acc_row) in acc.iter_mut().enumerate() {
let av = col_data[ti + di][r0 + lr];
for dj in 0..BT {
acc_row[dj] += av * pr[dj];
}
}
}
} else {
for lr in 0..rows {
for (di, acc_row) in acc.iter_mut().enumerate().take(bi) {
let av = col_data[ti + di][r0 + lr];
for (dj, slot) in acc_row.iter_mut().enumerate().take(bj) {
*slot += av * panel[lr * BT + dj];
}
}
}
}
for (di, acc_row) in acc.iter().enumerate().take(bi) {
let gi = ti + di;
for (dj, slot) in acc_row.iter().enumerate().take(bj) {
let gj = tj + dj;
if gi <= gj {
gram_out[gi * n + gj] += *slot;
}
}
}
ti += BT;
}
tj += BT;
}
}
fn certify_int64_dense_cycle(data: &[i64]) -> Option<Int64DenseCycleWitness> {
let (&start, rest) = data.split_first()?;
let mut period = None;
for (idx, &value) in rest.iter().enumerate() {
let row = idx + 1;
if value == start {
period = Some(row);
break;
}
let row_i64 = i64::try_from(row).ok()?;
if value != start.checked_add(row_i64)? {
return None;
}
}
let period = period.unwrap_or(data.len());
if period == 0 {
return None;
}
let last_offset = i64::try_from(period.checked_sub(1)?).ok()?;
start.checked_add(last_offset)?;
for (row, &value) in data.iter().enumerate() {
let offset = i64::try_from(row % period).ok()?;
if value != start.checked_add(offset)? {
return None;
}
}
Some(Int64DenseCycleWitness {
start,
period,
len: data.len(),
})
}
/// Exact witness for all-valid Bool columns whose true positions are affine.
///
/// The witness is produced only after scanning an immutable bool backing.
/// Consumers can skip rediscovering the same selection vector across repeated
/// filters, but must still validate frame length and bounds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[doc(hidden)]
pub struct BoolAffineSelectionWitness {
pub start: usize,
pub step: usize,
pub len: usize,
}
#[derive(Default)]
struct BoolAffineSelectionBuilder {
first: usize,
previous: usize,
step: usize,
len: usize,
is_affine: bool,
}
impl BoolAffineSelectionBuilder {
fn push(&mut self, position: usize) {
match self.len {
0 => {
self.first = position;
self.previous = position;
self.is_affine = true;
}
1 => {
self.step = position - self.first;
self.is_affine = self.step != 0;
self.previous = position;
}
_ => {
if position - self.previous != self.step {
self.is_affine = false;
}
self.previous = position;
}
}
self.len += 1;
}
fn finish(self) -> Option<BoolAffineSelectionWitness> {
match self.len {
0 => None,
1 => Some(BoolAffineSelectionWitness {
start: self.first,
step: 1,
len: self.len,
}),
_ if self.is_affine => Some(BoolAffineSelectionWitness {
start: self.first,
step: self.step,
len: self.len,
}),
_ => None,
}
}
}
fn certify_bool_affine_selection(data: &[bool]) -> Option<BoolAffineSelectionWitness> {
let mut builder = BoolAffineSelectionBuilder::default();
for (idx, keep) in data.iter().copied().enumerate() {
if keep {
builder.push(idx);
if !builder.is_affine {
return None;
}
}
}
builder.finish()
}
impl ColumnData {
/// Materialize typed array from a `Vec<Scalar>` and its `ValidityMask`.
///
/// Invalid positions get a default sentinel (0 / 0.0 / false / "").
/// The caller must pair this with the corresponding `ValidityMask` to
/// interpret which positions are actually valid.
#[must_use]
pub fn from_scalars(values: &[Scalar], dtype: DType) -> Self {
match dtype {
DType::Float64 => {
let data: Vec<f64> = values
.iter()
.map(|v| match v {
Scalar::Float64(f) => *f,
Scalar::Int64(i) => *i as f64,
Scalar::Bool(true) => 1.0,
Scalar::Bool(false) => 0.0,
_ => 0.0, // sentinel for invalid positions
})
.collect();
Self::Float64(Arc::from(data))
}
DType::Int64 | DType::Int64Nullable => {
let data: Vec<i64> = values
.iter()
.map(|v| match v {
Scalar::Int64(i) => *i,
Scalar::Bool(b) => i64::from(*b),
_ => 0, // sentinel for invalid positions
})
.collect();
Self::Int64(Arc::from(data))
}
DType::Categorical => {
let data: Vec<i64> = values
.iter()
.map(|v| match v {
Scalar::Int64(i) => *i,
_ => -1,
})
.collect();
Self::Int64(Arc::from(data))
}
DType::Bool | DType::BoolNullable => {
let data: Vec<bool> = values
.iter()
.map(|v| match v {
Scalar::Bool(b) => *b,
_ => false,
})
.collect();
Self::Bool(Arc::from(data))
}
DType::Utf8 => {
let data: Vec<String> = values
.iter()
.map(|v| match v {
Scalar::Utf8(s) => s.clone(),
_ => String::new(),
})
.collect();
Self::Utf8(data)
}
DType::Null => Self::Float64(Arc::from(vec![0.0; values.len()])),
DType::Sparse => Self::Utf8(vec![String::new(); values.len()]),
DType::Timedelta64 => {
let data: Vec<i64> = values
.iter()
.map(|v| match v {
Scalar::Timedelta64(n) => *n,
Scalar::Int64(i) => *i,
_ => Timedelta::NAT,
})
.collect();
Self::Timedelta64(data)
}
DType::Datetime64 => {
let data: Vec<i64> = values
.iter()
.map(|v| match v {
Scalar::Datetime64(n) => *n,
Scalar::Int64(i) => *i,
_ => Timestamp::NAT,
})
.collect();
Self::Datetime64(data)
}
DType::Period => {
// A pandas PeriodArray has one freq for the whole column; take
// it from the first non-NaT Period (default Daily if none).
let freq = values
.iter()
.find_map(|v| match v {
Scalar::Period(p) if p.ordinal != i64::MIN => Some(p.freq),
_ => None,
})
.unwrap_or(PeriodFreq::Daily);
let data: Vec<i64> = values
.iter()
.map(|v| match v {
Scalar::Period(p) => p.ordinal,
Scalar::Int64(i) => *i,
_ => i64::MIN, // NaT sentinel for Period
})
.collect();
Self::Period(data, freq)
}
DType::Interval => {
let data: Vec<Interval> = values
.iter()
.map(|v| match v {
Scalar::Interval(interval) => *interval,
_ => Interval::new(0.0, 0.0, IntervalClosed::Right),
})
.collect();
Self::Interval(data)
}
}
}
/// Convert typed array back to `Vec<Scalar>`, respecting `ValidityMask`.
#[must_use]
pub fn to_scalars(&self, dtype: DType, validity: &ValidityMask) -> Vec<Scalar> {
match self {
Self::Float64(data) => data
.iter()
.enumerate()
.map(|(i, v)| {
if !validity.get(i) {
Scalar::missing_for_dtype(dtype)
} else {
Scalar::Float64(*v)
}
})
.collect(),
Self::Int64(data) => data
.iter()
.enumerate()
.map(|(i, v)| {
if !validity.get(i) {
Scalar::missing_for_dtype(dtype)
} else {
Scalar::Int64(*v)
}
})
.collect(),
Self::Bool(data) => data
.iter()
.enumerate()
.map(|(i, v)| {
if !validity.get(i) {
Scalar::missing_for_dtype(dtype)
} else {
Scalar::Bool(*v)
}
})
.collect(),
Self::Utf8(data) => data
.iter()
.enumerate()
.map(|(i, v)| {
if !validity.get(i) {
Scalar::missing_for_dtype(dtype)
} else {
Scalar::Utf8(v.clone())
}
})
.collect(),
Self::Timedelta64(data) => data
.iter()
.enumerate()
.map(|(i, v)| {
if !validity.get(i) || *v == Timedelta::NAT {
Scalar::Timedelta64(Timedelta::NAT)
} else {
Scalar::Timedelta64(*v)
}
})
.collect(),
Self::Datetime64(data) => data
.iter()
.enumerate()
.map(|(i, v)| {
if !validity.get(i) || *v == Timestamp::NAT {
Scalar::Datetime64(Timestamp::NAT)
} else {
Scalar::Datetime64(*v)
}
})
.collect(),
Self::Period(data, freq) => data
.iter()
.enumerate()
.map(|(i, v)| {
if !validity.get(i) || *v == i64::MIN {
Scalar::Period(Period::new(i64::MIN, *freq))
} else {
Scalar::Period(Period::new(*v, *freq))
}
})
.collect(),
Self::Interval(data) => data
.iter()
.enumerate()
.map(|(i, v)| {
if !validity.get(i) {
Scalar::missing_for_dtype(dtype)
} else {
Scalar::Interval(*v)
}
})
.collect(),
}
}
#[must_use]
pub fn len(&self) -> usize {
match self {
Self::Float64(d) => d.len(),
Self::Int64(d) => d.len(),
Self::Bool(d) => d.len(),
Self::Utf8(d) => d.len(),
Self::Timedelta64(d) => d.len(),
Self::Datetime64(d) => d.len(),
Self::Period(d, _) => d.len(),
Self::Interval(d) => d.len(),
}
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
/// Compare two non-missing scalars using the given comparison operator.
///
/// Both scalars are converted to `f64` for comparison. For `Utf8` values,
/// lexicographic ordering is used. Returns `Err` for incompatible types.
fn scalar_compare(left: &Scalar, right: &Scalar, op: ComparisonOp) -> Result<bool, ColumnError> {
// Coerce differing numeric types to avoid precision loss (e.g. Bool vs Int64).
let left_dtype = left.dtype();
let right_dtype = right.dtype();
if left_dtype != right_dtype
&& let Ok(common) = fp_types::common_dtype(left_dtype, right_dtype)
&& common == DType::Int64
{
let l_cast = fp_types::cast_scalar(left, common)?;
let r_cast = fp_types::cast_scalar(right, common)?;
// Handle Int64 comparisons to avoid precision loss in f64 cast.
if let (Scalar::Int64(a), Scalar::Int64(b)) = (&l_cast, &r_cast) {
return Ok(match op {
ComparisonOp::Gt => a > b,
ComparisonOp::Lt => a < b,
ComparisonOp::Eq => a == b,
ComparisonOp::Ne => a != b,
ComparisonOp::Ge => a >= b,
ComparisonOp::Le => a <= b,
});
}
}
// Handle Utf8 comparisons separately (lexicographic).
if let (Scalar::Utf8(a), Scalar::Utf8(b)) = (left, right) {
return Ok(match op {
ComparisonOp::Gt => a > b,
ComparisonOp::Lt => a < b,
ComparisonOp::Eq => a == b,
ComparisonOp::Ne => a != b,
ComparisonOp::Ge => a >= b,
ComparisonOp::Le => a <= b,
});
}
// Handle Bool comparisons (false < true).
if let (Scalar::Bool(a), Scalar::Bool(b)) = (left, right) {
return Ok(match op {
ComparisonOp::Gt => *a && !*b,
ComparisonOp::Lt => !*a && *b,
ComparisonOp::Eq => a == b,
ComparisonOp::Ne => a != b,
ComparisonOp::Ge => *a >= *b,
ComparisonOp::Le => *a <= *b,
});
}
// Handle Int64 comparisons to avoid precision loss in f64 cast.
if let (Scalar::Int64(a), Scalar::Int64(b)) = (left, right) {
return Ok(match op {
ComparisonOp::Gt => a > b,
ComparisonOp::Lt => a < b,
ComparisonOp::Eq => a == b,
ComparisonOp::Ne => a != b,
ComparisonOp::Ge => a >= b,
ComparisonOp::Le => a <= b,
});
}
// Numeric: convert both to f64.
let lhs = left.to_f64()?;
let rhs = right.to_f64()?;
Ok(match op {
ComparisonOp::Gt => lhs > rhs,
ComparisonOp::Lt => lhs < rhs,
ComparisonOp::Eq => lhs == rhs,
ComparisonOp::Ne => lhs != rhs,
ComparisonOp::Ge => lhs >= rhs,
ComparisonOp::Le => lhs <= rhs,
})
}
/// AG-10: Vectorized binary arithmetic on `&[f64]` slices.
///
/// Both inputs must have the same length. The combined validity mask
/// determines which positions produce a valid output; invalid positions
/// get 0.0 as a sentinel. Returns `(result_data, result_validity)`.
fn vectorized_binary_f64(
left: &[f64],
right: &[f64],
left_validity: &ValidityMask,
right_validity: &ValidityMask,
op: ArithmeticOp,
) -> (Vec<f64>, ValidityMask) {
let combined = left_validity.and_mask(right_validity);
// Zip iterators over contiguous slices — auto-vectorizable by LLVM.
let apply = binary_f64_apply(op);
let out: Vec<f64> = left
.iter()
.zip(right.iter())
.enumerate()
.map(|(i, (&l, &r))| {
if combined.get(i) {
apply(l, r)
} else {
0.0 // sentinel for invalid positions
}
})
.collect();
(out, combined)
}
fn binary_f64_apply(op: ArithmeticOp) -> fn(f64, f64) -> f64 {
match op {
ArithmeticOp::Add => |a, b| a + b,
ArithmeticOp::Sub => |a, b| a - b,
ArithmeticOp::Mul => |a, b| a * b,
ArithmeticOp::Div => |a, b| a / b,
ArithmeticOp::Mod => python_mod_f64,
ArithmeticOp::Pow => |a, b| a.powf(b),
ArithmeticOp::FloorDiv => python_floor_div_f64,
}
}
/// Single-pass monomorphized binary f64 kernel that also reports whether any
/// input or output element was NaN (br-frankenpandas-9houf). Each op is
/// monomorphized into its own arm (closed-form for Add/Sub/Mul/Div so LLVM
/// autovectorizes to packed SIMD; scalar helpers for Mod/Pow/FloorDiv), so the
/// `data` vector is element-for-element identical to `binary_f64_apply(op)`
/// applied in order. `input_nan` equals `a.any(is_nan) || b.any(is_nan)` and
/// `output_nan` equals `data.any(is_nan)`.
///
/// This fuses the same-index fast path's two input NaN pre-scans and the
/// `from_f64_values` output re-scan into the single arithmetic sweep, so a
/// fully-valid NaN-free add no longer pays four memory passes (2 input scans +
/// add + output scan) where numpy pays one. The reductions are plain `bool`
/// OR-accumulators alongside a contiguous store.
#[inline]
fn apply_f64_slices_nan_tracked(op: ArithmeticOp, a: &[f64], b: &[f64]) -> (Vec<f64>, bool, bool) {
debug_assert_eq!(a.len(), b.len());
const PARALLEL_MIN_LEN: usize = 1 << 20;
const PARALLEL_MAX_CHUNKS: usize = 8;
let mut data = vec![0.0_f64; a.len()];
let worker_count = std::thread::available_parallelism()
.map_or(1, usize::from)
.min(PARALLEL_MAX_CHUNKS)
.min(a.len().max(1));
if a.len() >= PARALLEL_MIN_LEN && worker_count >= 2 {
let chunk_len = a.len().div_ceil(worker_count);
let mut chunks = Vec::with_capacity(worker_count);
let mut rest = data.as_mut_slice();
let mut start = 0usize;
while start < a.len() {
let end = (start + chunk_len).min(a.len());
let (chunk, tail) = rest.split_at_mut(end - start);
chunks.push((start, chunk));
rest = tail;
start = end;
}
let (input_nan, output_nan) = std::thread::scope(|scope| {
let mut handles = Vec::with_capacity(chunks.len());
for (start, chunk) in chunks {
let end = start + chunk.len();
let a = &a[start..end];
let b = &b[start..end];
handles
.push(scope.spawn(move || apply_f64_slices_nan_tracked_into(op, a, b, chunk)));
}
let mut input_nan = false;
let mut output_nan = false;
for handle in handles {
let (chunk_input_nan, chunk_output_nan) = match handle.join() {
Ok(result) => result,
Err(payload) => std::panic::resume_unwind(payload),
};
input_nan |= chunk_input_nan;
output_nan |= chunk_output_nan;
}
(input_nan, output_nan)
});
return (data, input_nan, output_nan);
}
let (input_nan, output_nan) = apply_f64_slices_nan_tracked_into(op, a, b, &mut data);
(data, input_nan, output_nan)
}
#[inline]
fn apply_f64_slices_nan_tracked_into(
op: ArithmeticOp,
a: &[f64],
b: &[f64],
data: &mut [f64],
) -> (bool, bool) {
debug_assert_eq!(a.len(), b.len());
debug_assert_eq!(a.len(), data.len());
let mut input_nan = false;
let mut output_nan = false;
macro_rules! sweep {
($f:expr) => {{
for ((x, y), d) in a.iter().zip(b).zip(data.iter_mut()) {
let r = $f(*x, *y);
input_nan |= x.is_nan() | y.is_nan();
output_nan |= r.is_nan();
*d = r;
}
}};
}
match op {
ArithmeticOp::Add => sweep!(|x: f64, y: f64| x + y),
ArithmeticOp::Sub => sweep!(|x: f64, y: f64| x - y),
ArithmeticOp::Mul => sweep!(|x: f64, y: f64| x * y),
ArithmeticOp::Div => sweep!(|x: f64, y: f64| x / y),
ArithmeticOp::Mod => sweep!(python_mod_f64),
ArithmeticOp::Pow => sweep!(|x: f64, y: f64| x.powf(y)),
ArithmeticOp::FloorDiv => sweep!(python_floor_div_f64),
}
(input_nan, output_nan)
}
fn unit_range_len(start: i64, end: i64) -> Option<usize> {
usize::try_from(end.checked_sub(start)?.checked_add(1)?).ok()
}
fn python_mod_f64(lhs: f64, rhs: f64) -> f64 {
if lhs.is_nan() || rhs.is_nan() {
return f64::NAN;
}
if rhs.is_infinite() {
if lhs.is_infinite() {
return f64::NAN;
}
if lhs == 0.0 {
return 0.0_f64.copysign(rhs);
}
if lhs.is_sign_positive() == rhs.is_sign_positive() {
lhs
} else {
rhs
}
} else {
lhs - python_floor_div_f64(lhs, rhs) * rhs
}
}
fn python_floor_div_f64(lhs: f64, rhs: f64) -> f64 {
if lhs.is_nan() || rhs.is_nan() {
return f64::NAN;
}
if rhs.is_infinite() {
if lhs.is_infinite() {
return f64::NAN;
}
if lhs == 0.0 {
return (lhs / rhs).floor();
}
if lhs.is_sign_positive() == rhs.is_sign_positive() {
0.0
} else {
-1.0
}
} else if lhs.is_infinite() && rhs != 0.0 {
f64::NAN
} else {
(lhs / rhs).floor()
}
}
fn python_floor_div_i64(lhs: i64, rhs: i64) -> i64 {
debug_assert_ne!(rhs, 0);
if lhs == i64::MIN && rhs == -1 {
return i64::MIN;
}
let quotient = lhs / rhs;
let remainder = lhs % rhs;
if remainder != 0 && ((remainder > 0) != (rhs > 0)) {
quotient - 1
} else {
quotient
}
}
fn python_mod_i64(lhs: i64, rhs: i64) -> i64 {
debug_assert_ne!(rhs, 0);
if lhs == i64::MIN && rhs == -1 {
return 0;
}
let quotient = i128::from(python_floor_div_i64(lhs, rhs));
let remainder = i128::from(lhs) - quotient * i128::from(rhs);
let Ok(value) = i64::try_from(remainder) else {
return 0;
};
value
}
/// AG-10: Vectorized binary arithmetic on `&[i64]` slices.
///
/// Produces `i64` results for Add/Sub/Mul. For Div, returns `None`
/// to signal the caller should use the `f64` path instead.
fn vectorized_binary_i64(
left: &[i64],
right: &[i64],
left_validity: &ValidityMask,
right_validity: &ValidityMask,
op: ArithmeticOp,
) -> Option<(Vec<i64>, ValidityMask)> {
let combined = left_validity.and_mask(right_validity);
// Div and Pow always produce floats
if matches!(op, ArithmeticOp::Div | ArithmeticOp::Pow) {
return None;
}
// For Mod/FloorDiv: if any non-missing right operand is zero, fall back
// to float. We must NOT gate on `combined` (left AND right validity) —
// pandas promotes the entire result dtype to Float64 whenever a zero
// divisor appears in the right operand, regardless of whether the
// matching left position is missing. Gating on combined caused
// promotion to be skipped when the zero divisor's left counterpart
// was Null, drifting the column dtype against the conformance oracle
// (fuzz_column_arith corpus surfaced this on the seed
// [97, 4, 11, 0, 0, 0, 0, 0, 0, 0, 10]).
if matches!(op, ArithmeticOp::Mod | ArithmeticOp::FloorDiv) {
let has_zero_divisor = right
.iter()
.enumerate()
.any(|(i, &r)| right_validity.get(i) && r == 0);
if has_zero_divisor {
return None;
}
}
let apply: fn(i64, i64) -> i64 = match op {
ArithmeticOp::Add => |a, b| a.wrapping_add(b),
ArithmeticOp::Sub => |a, b| a.wrapping_sub(b),
ArithmeticOp::Mul => |a, b| a.wrapping_mul(b),
ArithmeticOp::Mod => python_mod_i64,
ArithmeticOp::FloorDiv => python_floor_div_i64,
ArithmeticOp::Div | ArithmeticOp::Pow => unreachable!("handled by early return above"),
};
// Mod/FloorDiv (python_mod_i64 / python_floor_div_i64) are COMPUTE-bound
// (integer idiv ~20-40 cycles + sign adjustment) → parallelize; add/sub/mul
// are bandwidth-bound → keep serial. Bit-identical (same apply, same combined
// gate, same order; invalid positions sentinel-0 either way).
let out: Vec<i64> = if matches!(op, ArithmeticOp::Mod | ArithmeticOp::FloorDiv) {
par_map_vec_i64(left.len(), |i| {
if combined.get(i) {
apply(left[i], right[i])
} else {
0
}
})
} else {
left.iter()
.zip(right.iter())
.enumerate()
.map(|(i, (&l, &r))| {
if combined.get(i) {
apply(l, r)
} else {
0 // sentinel for invalid positions
}
})
.collect()
};
Some((out, combined))
}
enum ScalarValues {
/// Eager Scalar backing (the general fallback for mixed/typed columns that
/// no lazy variant covers). The Scalar buffer is `Arc`-shared so
/// `Column::clone` shares it in O(1) instead of deep-copying every
/// `Scalar` (br-frankenpandas-cfr08). The backing is immutable after
/// construction — `ScalarValues` exposes only `&[Scalar]` (via `Deref`),
/// never `&mut`; any "mutation" replaces the whole `values` field with a
/// freshly built `ScalarValues`. So the shared `Arc` can never observe a
/// write underneath another reader, making the share observationally a
/// deep copy (identical to the previous `Vec<Scalar>` semantics). This is
/// the same structural-sharing trick already used for the lazy typed and
/// contiguous-Utf8 backings.
Eager(Arc<[Scalar]>),
LazyAllValidInt64 {
data: Arc<[i64]>,
dense_cycle: OnceLock<Option<Int64DenseCycleWitness>>,
values: OnceLock<Vec<Scalar>>,
},
LazyAllValidInt64Chunks {
chunks: Arc<[Int64Chunk]>,
len: usize,
data: OnceLock<Vec<i64>>,
dense_cycle: OnceLock<Option<Int64DenseCycleWitness>>,
values: OnceLock<Vec<Scalar>>,
},
/// Move-not-copy sibling of `LazyAllValidInt64`: stores the owned `Vec<i64>`
/// inside an `Arc` (one tiny `Arc::new`, no element copy) instead of
/// `Arc<[i64]>` (which `Arc::from(Vec)` builds via a fresh alloc + memcpy —
/// the ~28ms/5M cost of every all-valid-Int64-producing op:
/// replace/fillna/bfill/dropna i64). Semantically identical to
/// `LazyAllValidInt64` (all-valid, no missing); consumers read `&data[..]`.
/// (No `dense_cycle` cache — a downstream groupby just recomputes its witness.)
LazyAllValidInt64Vec {
data: Arc<Vec<i64>>,
values: OnceLock<Vec<Scalar>>,
},
/// All-valid Datetime64 (nanosecond epoch) backing — the typed counterpart
/// of `LazyAllValidInt64` for `DType::Datetime64`, so a datetime-producing op
/// (e.g. `to_datetime`) can ingest a `Vec<i64>` of nanos without boxing a
/// `Scalar::Datetime64` per row. Materializes `Scalar::Datetime64(data[i])`.
LazyAllValidDatetime64 {
data: Arc<[i64]>,
values: OnceLock<Vec<Scalar>>,
},
/// Owned (move-not-copy) sibling of `LazyAllValidDatetime64` — boxes a
/// `Vec<i64>` of nanos in an `Arc` without the `Arc::from(Vec)` alloc+memcpy,
/// the datetime mirror of `LazyAllValidInt64Vec`. Semantically identical (all
/// valid; `as_datetime64_slice`/`values()` read `&data[..]`), used by scattered
/// datetime gathers so `take_positions` doesn't triple memory traffic.
LazyAllValidDatetime64Vec {
data: Arc<Vec<i64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Owned all-valid Timedelta64 (nanosecond) backing — the Timedelta sibling of
/// `LazyAllValidDatetime64Vec` (Timedelta64 otherwise has no lazy typed variant,
/// only `ColumnData::Timedelta64`). Lets a scattered timedelta gather move its
/// `Vec<i64>` nanos in instead of boxing a `Scalar::Timedelta64` per row.
/// Materializes `Scalar::Timedelta64(data[i])` (a NaT sentinel is carried
/// through unchanged).
LazyAllValidTimedelta64Vec {
data: Arc<Vec<i64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Owned all-valid Period backing: ordinals plus the column-uniform freq.
/// Mirrors the temporal i64-backed gather variants without boxing
/// `Scalar::Period` per row.
LazyAllValidPeriodVec {
data: Arc<Vec<i64>>,
freq: PeriodFreq,
values: OnceLock<Vec<Scalar>>,
},
/// Nullable Datetime64 backing (the temporal mirror of `LazyNullableInt64`):
/// contiguous ns `data` + `validity`; an invalid slot materializes
/// `Scalar::Null(NullKind::NaT)` (= `missing_for_dtype(Datetime64)`), a valid
/// slot `Scalar::Datetime64(data[i])`. Used by null-introducing datetime
/// gathers (outer join / align / reindex on a datetime column).
LazyNullableDatetime64 {
data: Vec<i64>,
validity: ValidityMask,
values: OnceLock<Vec<Scalar>>,
},
/// Nullable Timedelta64 sibling of `LazyNullableDatetime64`.
LazyNullableTimedelta64 {
data: Vec<i64>,
validity: ValidityMask,
values: OnceLock<Vec<Scalar>>,
},
/// Nullable Period backing. Valid slots materialize with `freq`; invalid
/// slots materialize with `missing_freq` so null-introducing reindex keeps
/// the existing `missing_for_dtype(Period)` contract exactly.
LazyNullablePeriod {
data: Vec<i64>,
freq: PeriodFreq,
missing_freq: PeriodFreq,
validity: ValidityMask,
values: OnceLock<Vec<Scalar>>,
},
LazyAllValidFloat64 {
data: Arc<[f64]>,
all_finite: OnceLock<bool>,
values: OnceLock<Vec<Scalar>>,
},
/// Move-not-copy sibling of `LazyAllValidFloat64`: stores the owned `Vec<f64>`
/// inside an `Arc` (one tiny `Arc::new` box, no element copy) instead of
/// `Arc<[f64]>` (which `Arc::from(Vec)` builds by allocating a fresh n*8+16
/// buffer and memcpy-ing — a cold-page-fault-bound ~5.7ms/1M, the dominant
/// cost of every f64-producing op: abs/cumsum/cummax/cummin/cumprod/diff/clip).
/// Semantically identical to `LazyAllValidFloat64` (all-valid, no missing);
/// consumers read the slice via `&data[..]`.
LazyAllValidFloat64Vec {
data: Arc<Vec<f64>>,
all_finite: OnceLock<bool>,
values: OnceLock<Vec<Scalar>>,
},
LazyAllValidFloat64Chunks {
chunks: Arc<[Float64Chunk]>,
len: usize,
data: OnceLock<Vec<f64>>,
all_finite: OnceLock<bool>,
values: OnceLock<Vec<Scalar>>,
},
/// Zero-copy contiguous row-range view over an `Arc`-shared all-valid
/// Float64 backing (br-frankenpandas-jbyuc.1.1.1.1). Row `i` is
/// `data[start + i]`; `take_positions` returns this in O(1) when a large
/// requested position list is a contiguous ascending range. Floating-point
/// bits are not transformed, so `-0.0`, infinities, and all finite payloads
/// materialize exactly as the copied gather would.
LazyAllValidFloat64Slice {
data: Arc<[f64]>,
start: usize,
len: usize,
all_finite: OnceLock<bool>,
values: OnceLock<Vec<Scalar>>,
},
/// Deferred all-valid Float64 output column for finite `DataFrame::dot`.
///
/// Row `i` materializes the exact left-fold
/// `sum_l a_cols[l][i] * b_col[l]`, preserving the eager dot kernel's
/// per-cell operand order while avoiding output allocation when callers
/// only inspect shape/metadata.
LazyAllValidFloat64Dot {
a_cols: Arc<[Float64DotInput]>,
b_col: Arc<[f64]>,
len: usize,
data: OnceLock<Vec<f64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Deferred all-valid Float64 result column for finite `DataFrame::corr`
/// and `DataFrame::cov` matrices.
///
/// All result columns share one pairwise-stat matrix plan. Shape/metadata
/// reads only touch `len`; scalar or f64-buffer reads materialize the full
/// matrix once and then expose the requested output column `j`.
LazyAllValidFloat64PairwiseStatMatrixColumn {
plan: Arc<Float64PairwiseStatMatrixPlan>,
col: usize,
data: OnceLock<Vec<f64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Deferred all-valid Float64 row produced by a homogeneous transpose.
///
/// All output columns share one plan over the original source columns.
/// Output row `j` materializes `[src_col_0[j], src_col_1[j], ...]`,
/// preserving the eager transpose loop's source-column order while avoiding
/// one tiny `Vec<f64>` allocation and copy for every transposed source row.
LazyAllValidFloat64TransposeRow {
plan: Arc<Float64TransposeRowsPlan>,
source_row: usize,
data: OnceLock<Vec<f64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Deferred all-valid Float64 `combine_first` select.
///
/// Output row `i` is `left[i]` when the left validity bit is set and the
/// left datum is not NaN, otherwise `right[i]`. The caller proves the right
/// side is all-valid/NaN-free, so every output row is valid. This defers the
/// selected output buffer until a consumer asks for a typed slice or scalar
/// values.
LazyCombineFirstFloat64 {
left: Arc<[f64]>,
right: Arc<[f64]>,
left_validity_words: Arc<[u64]>,
len: usize,
data: OnceLock<Vec<f64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Arithmetic-progression view over shared all-valid Float64 data.
///
/// Semantically identical to gathering `data[start + i * step]` for
/// `i in 0..len` and passing the result to [`Column::from_f64_values`].
/// This keeps row filters that reuse one monotone position plan from
/// copying each Float64 column until a consumer asks for contiguous data or
/// scalar values.
LazyStridedFloat64 {
data: Arc<[f64]>,
start: usize,
step: usize,
len: usize,
expanded: OnceLock<Vec<f64>>,
values: OnceLock<Vec<Scalar>>,
},
LazyNullableFloat64 {
data: Vec<f64>,
validity: ValidityMask,
values: OnceLock<Vec<Scalar>>,
},
/// Nullable Int64 mirror of `LazyNullableFloat64`
/// (br-frankenpandas-lt5qx): contiguous `i64` data + validity, where an
/// invalid slot materializes `Scalar::Null(NullKind::Null)` — exactly
/// `Scalar::missing_for_dtype(DType::Int64)`. Unlike Float64 there is no
/// NaN-as-missing ambiguity: missingness is the validity bit alone.
LazyNullableInt64 {
data: Vec<i64>,
validity: ValidityMask,
values: OnceLock<Vec<Scalar>>,
},
/// Nullable Bool mirror of `LazyNullableInt64` (br-frankenpandas-rcvpj):
/// contiguous `bool` data + validity, where an invalid slot materializes
/// `Scalar::Null(NullKind::Null)` — exactly `missing_for_dtype(DType::Bool)`.
/// Backs comparison / where / mask / isin outputs that carry nulls, so the
/// Bool result skips the per-row `Vec<Scalar>` + `Column::from_values`
/// dtype-inference and validity rescan.
LazyNullableBool {
data: Vec<bool>,
validity: ValidityMask,
values: OnceLock<Vec<Scalar>>,
},
LazyAllValidBool {
data: Arc<[bool]>,
affine_selection: OnceLock<Option<BoolAffineSelectionWitness>>,
values: OnceLock<Vec<Scalar>>,
},
/// Deferred all-valid Bool shift.
///
/// Semantically identical to building the shifted Bool buffer eagerly:
/// vacated slots materialize as `fill`, surviving slots read the source
/// row at the positional shift offset. This keeps metadata-only consumers
/// from paying the Bool output allocation while preserving a contiguous
/// `&[bool]` view on first typed read.
LazyShiftedBool {
source: Arc<[bool]>,
periods: i64,
fill: bool,
len: usize,
data: OnceLock<Vec<bool>>,
affine_selection: OnceLock<Option<BoolAffineSelectionWitness>>,
values: OnceLock<Vec<Scalar>>,
},
/// Contiguous backing for all-valid Utf8 columns
/// (br-frankenpandas-2krr0): one rolling byte buffer + n+1 offsets (row
/// `i` = `bytes[offsets[i]..offsets[i+1]]`, always valid UTF-8 by
/// construction — only built from `&str` data). String-output ops write
/// here without a per-row heap `String`; the `Vec<Scalar::Utf8>` view
/// materializes once on demand.
///
/// The byte buffer and offsets are `Arc`-shared (br-frankenpandas-oifvy):
/// the backing is immutable after construction (string ops always build a
/// fresh buffer, never mutate in place), so `Column::clone` shares the
/// `Arc` instead of deep-copying the (often large) byte buffer — O(1)
/// instead of O(n), and observationally a deep copy because the data can
/// never change underneath a shared reader.
LazyContiguousUtf8 {
bytes: Arc<[u8]>,
offsets: Arc<[usize]>,
strictly_increasing: OnceLock<bool>,
fixed_width: OnceLock<Option<usize>>,
// Boxed cold cache: read only on the lower-hex join-key detection path
// (`as_lower_hex_sequence_utf8*`), never on the hot byte-access path. Boxing
// the `Option` payload (40 B -> 16 B) shrinks every `Column`; `Option<Box<_>>`
// uses the null-pointer niche so `None` stays a single word.
lower_hex_sequence: OnceLock<Option<Box<Utf8LowerHexSequence>>>,
// Boxed: this cold factorize cache is the single widest field (56 B) of the
// widest `ScalarValues` variant, so it alone sizes the whole enum. Boxing it
// (56 B -> 16 B) shrinks `ScalarValues`/`Column` for every column in the
// workspace, and the deref it adds falls ONLY on the cold factorize path
// (`utf8_default_factorize_columns`), never on the hot byte-access path
// (`bytes`/`offsets`), so the contiguous-Utf8 wins are untouched.
factorize_default: OnceLock<Box<Utf8FactorizeDefaultWitness>>,
values: OnceLock<Vec<Scalar>>,
},
/// Lazy fixed-width lowercase-hex Utf8 sequence
/// (br-frankenpandas-uza04.47). Row `i` is
/// `prefix || fixed_width_lower_hex(start + i)`, with all construction
/// guards checked up front. Ordered joins can consume the sequence witness
/// directly without first materializing the full byte buffer; consumers
/// that need contiguous spans still get the exact same bytes/offsets via a
/// one-time materialization.
LazyLowerHexSequenceUtf8 {
prefix: Arc<[u8]>,
start: u64,
len: usize,
hex_width: usize,
buffers: OnceLock<Utf8ArcBuffers>,
values: OnceLock<Vec<Scalar>>,
},
/// Nullable counterpart of `LazyContiguousUtf8` (br-frankenpandas-cmxjz):
/// one rolling byte buffer + n+1 offsets like the all-valid variant, plus a
/// validity mask. Row `i` materializes `Scalar::Utf8(bytes[off[i]..off[i+1]])`
/// when `validity.get(i)`, else `Scalar::Null(NullKind::Null)` (=
/// `missing_for_dtype(Utf8)`). A missing slot carries an empty span
/// (`off[i] == off[i+1]`) so empty-string-vs-null is distinguished purely by
/// the validity bit. Built by null-introducing Utf8 gathers (reindex /
/// left·right·outer merge of a string payload column) to skip the per-row
/// `String` Scalar clone + `Column::new` revalidation.
LazyNullableUtf8 {
bytes: Arc<[u8]>,
offsets: Arc<[usize]>,
validity: ValidityMask,
values: OnceLock<Vec<Scalar>>,
},
/// Deferred null-introducing Utf8 gather (br-frankenpandas-yiqv5): the
/// null path of `reindex_by_positions` over an all-valid `Eager` Utf8
/// source — e.g. the value lanes of a null-introducing string join. Shares
/// the source `Scalar` `Arc` (O(1)) and carries only the position plan
/// (`usize::MAX` marks a missing slot -> `missing_for_dtype(Utf8)`); the
/// gathered `Vec<Scalar>` materializes once on demand. Construction is
/// O(output) over the plan (8 bytes/row) plus an O(1) source share — it
/// never copies the gathered string bytes until a consumer reads the
/// column, so a join whose output value lanes are never read (only its
/// shape/index consulted) pays nothing for them. Materialized values are
/// byte-identical to the eager gather: present slots clone the source
/// Scalar, missing slots are `missing_for_dtype(Utf8)`.
LazyGatherUtf8 {
source: Arc<[Scalar]>,
positions: Arc<[usize]>,
values: OnceLock<Vec<Scalar>>,
},
/// Deferred null-introducing Utf8 contiguous-range gather. This is the
/// common ordered-join shape where missing slots form a prefix and/or
/// suffix while present slots read one contiguous source range. It is
/// semantically the same as `LazyGatherUtf8` over
/// `[MAX; prefix] + start..start+len + [MAX; suffix]`, but stores O(1)
/// descriptors instead of an O(output) position tape.
LazyNullableUtf8Range {
source: Arc<[Scalar]>,
null_prefix: usize,
source_start: usize,
source_len: usize,
null_suffix: usize,
values: OnceLock<Vec<Scalar>>,
},
/// Run-length backing for all-valid Int64 columns whose values arrive as
/// repeat runs (br-frankenpandas-3ad4n) — e.g. the left lanes of a dense
/// inner join, where every matched left value repeats `bucket_len` times.
/// Carries O(runs) memory until a consumer asks for the contiguous i64
/// buffer (`as_i64_slice`) or the Scalar view, each expanded once on
/// demand.
LazyRepeatRunsInt64 {
runs: Vec<(i64, usize)>,
total_len: usize,
data: OnceLock<Vec<i64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Repeat-run backing where the per-run values and run lengths are stored
/// separately so multiple dense-join output lanes can share one immutable
/// run-length descriptor.
LazyRepeatValuesInt64 {
run_values: Vec<i64>,
run_lens: Arc<[usize]>,
total_len: usize,
data: OnceLock<Vec<i64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Repeated-slice backing for all-valid Int64 columns whose values arrive
/// as slices of one shared tape (e.g. dense join right lanes). Each
/// segment is `(start, len)` into `data`, and segment order is the
/// observable row order.
LazyRepeatedSlicesInt64 {
data: Vec<i64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
expanded: OnceLock<Vec<i64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Float64 counterpart of [`Self::LazyRepeatValuesInt64`]
/// (br-frankenpandas-jzrem): a dense-join LEFT lane carried as per-run f64
/// values + a shared run-length descriptor, expanded to `Scalar::Float64`
/// only when a consumer reads it. The source values are all-valid (the
/// builder gates on `as_f64_slice`, which requires `validity.all()` and
/// hence no NaN), so the materialized column is all-valid.
LazyRepeatValuesFloat64 {
run_values: Vec<f64>,
run_lens: Arc<[usize]>,
total_len: usize,
values: OnceLock<Vec<Scalar>>,
},
/// Float64 counterpart of [`Self::LazyRepeatedSlicesInt64`]
/// (br-frankenpandas-jzrem): a dense-join RIGHT lane carried as repeated
/// `(start, len)` slices of one shared bucket-order value tape, expanded to
/// `Scalar::Float64` only on read. Segment order is the observable row
/// order; all-valid for the same reason as `LazyRepeatValuesFloat64`.
LazyRepeatedSlicesFloat64 {
data: Vec<f64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
expanded: OnceLock<Vec<f64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Null-introducing counterpart of [`Self::LazyRepeatedSlicesInt64`]
/// (br-frankenpandas-yiqv5): a dense LEFT/RIGHT/OUTER-join RIGHT lane where a
/// segment is EITHER a tape slice `(start, len)` of matched values OR, when
/// `start == usize::MAX`, a run of `len` missing values. Unmatched Int64
/// slots materialize `Scalar::Null(NullKind::Null)` (matching
/// `reindex_by_positions`); the owning column carries a validity mask with
/// those positions cleared.
LazyNullableRepeatedSlicesInt64 {
data: Vec<i64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
values: OnceLock<Vec<Scalar>>,
},
/// Float64 sibling of [`Self::LazyNullableRepeatedSlicesInt64`]
/// (br-frankenpandas-yiqv5). Unmatched slots materialize
/// `Scalar::Null(NullKind::NaN)` — the Float64 missing convention.
LazyNullableRepeatedSlicesFloat64 {
data: Vec<f64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
values: OnceLock<Vec<Scalar>>,
},
/// Null-introducing repeat-VALUES Float64 lane (br-frankenpandas-yiqv5): the
/// BROADCAST counterpart of `LazyNullableRepeatedSlicesFloat64`, for an OUTER
/// merge's promoted LEFT side where each run is either `run_values[k]`
/// repeated `run_lens[k]` times (matched/left-only row) or, when
/// `!run_valid[k]`, a run of `Null(NullKind::NaN)` (right-only row). The
/// `run_valid` / `run_lens` descriptors are shared across all promoted
/// lanes; only `run_values` differs per column.
LazyNullableRepeatValuesFloat64 {
run_values: Vec<f64>,
run_valid: Arc<[bool]>,
run_lens: Arc<[usize]>,
total_len: usize,
values: OnceLock<Vec<Scalar>>,
},
/// Source-position backed sibling of `LazyNullableRepeatedSlicesFloat64`.
/// This carries an all-valid Int64 source plus a bucket-order position tape
/// and casts `i64 -> f64` only if a consumer materializes the Scalar view.
LazyNullableRepeatedPositionsI64AsFloat64 {
source: Arc<[i64]>,
positions: Arc<[usize]>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
values: OnceLock<Vec<Scalar>>,
},
/// Dense-cycle source-position sibling for promoted OUTER-join RIGHT lanes.
/// Stores the certified left/right key witnesses instead of a bucket-order
/// right-position tape; materialization reconstructs the same right
/// positions in bucket order.
LazyNullableDenseCycleRightI64AsFloat64 {
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
min_key: i64,
span: usize,
total_len: usize,
values: OnceLock<Vec<Scalar>>,
},
/// Dense-cycle source-position sibling for promoted OUTER-join LEFT lanes.
/// Stores the certified left/right key witnesses instead of per-run
/// left-position/run-length descriptors; materialization reconstructs the
/// same left broadcast runs in bucket order.
LazyNullableDenseCycleLeftI64AsFloat64 {
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
min_key: i64,
span: usize,
total_len: usize,
values: OnceLock<Vec<Scalar>>,
},
/// Probe-order dense-cycle repeat lane for one-sided joins. Row order is
/// the probe side's original order; matched probe rows repeat once per
/// build-side duplicate and unmatched probe rows repeat once.
LazyDenseCycleProbeRepeatInt64 {
source: Arc<[i64]>,
probe_witness: Int64DenseCycleWitness,
build_witness: Int64DenseCycleWitness,
total_len: usize,
data: OnceLock<Vec<i64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Dense-cycle LEFT-join left lane. Stores the source column and certified
/// key witnesses instead of one `(value, run_len)` descriptor per left row;
/// materialization preserves left-major join order exactly.
LazyLeftJoinDenseCycleLeftInt64 {
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
total_len: usize,
data: OnceLock<Vec<i64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Probe-order dense-cycle nullable build lane for one-sided joins.
/// Matched probe rows replay build-side positions in their original
/// duplicate order; unmatched probe rows materialize `Null`.
LazyNullableDenseCycleProbeBuildInt64 {
source: Arc<[i64]>,
probe_witness: Int64DenseCycleWitness,
build_witness: Int64DenseCycleWitness,
total_len: usize,
values: OnceLock<Vec<Scalar>>,
},
/// Dense-cycle LEFT-join right lane. Reconstructs each matched right
/// position as `offset + k * period`; unmatched left rows materialize as
/// `Null(NullKind::Null)`, matching nullable Int64 reindex semantics.
LazyLeftJoinDenseCycleRightInt64 {
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
total_len: usize,
data: OnceLock<Vec<i64>>,
values: OnceLock<Vec<Scalar>>,
},
/// Source-position backed sibling of `LazyNullableRepeatValuesFloat64`.
/// Each valid run reads `source[run_positions[k]] as f64` lazily; invalid
/// runs materialize `Null(NaN)` under the same validity mask.
LazyNullableRepeatPositionsI64AsFloat64 {
source: Arc<[i64]>,
run_positions: Arc<[usize]>,
run_valid: Arc<[bool]>,
run_lens: Arc<[usize]>,
total_len: usize,
values: OnceLock<Vec<Scalar>>,
},
/// Zero-copy contiguous row-range VIEW over an `Arc`-shared contiguous-Utf8
/// backing (br-frankenpandas-jbyuc.1.1.1). Row `i` (`0..len`) is
/// `bytes[offsets[start + i] .. offsets[start + i + 1]]` — the same shared
/// `bytes`/`offsets` as the source `LazyContiguousUtf8`, with `start`/`len`
/// selecting a contiguous window. `take_positions` returns this in O(1)
/// (two `Arc::clone`s) when the requested positions are a contiguous
/// ascending range, deferring the per-row byte gather until a consumer
/// actually materializes the Scalar view. The byte content is identical to
/// the eager gather: same bytes, same order, all-valid.
LazyUtf8Slice {
bytes: Arc<[u8]>,
offsets: Arc<[usize]>,
start: usize,
len: usize,
values: OnceLock<Vec<Scalar>>,
},
}
type Utf8ArcViewSource = (Arc<[u8]>, Arc<[usize]>, usize);
pub type Utf8ArcBuffers = (Arc<[u8]>, Arc<[usize]>);
impl ScalarValues {
fn from_vec(values: Vec<Scalar>) -> Self {
Self::Eager(Arc::from(values))
}
fn lazy_all_valid_int64(data: Vec<i64>) -> Self {
Self::lazy_all_valid_int64_arc(Arc::from(data))
}
/// Move-not-copy: box the owned `Vec<i64>` in an `Arc` (no element copy),
/// the i64 sibling of `lazy_all_valid_float64_owned`.
fn lazy_all_valid_int64_owned(data: Vec<i64>) -> Self {
Self::LazyAllValidInt64Vec {
data: Arc::new(data),
values: OnceLock::new(),
}
}
/// Share an existing `Arc` i64 buffer in O(1) (used by `Clone`).
/// (br-frankenpandas-tin7r: immutable typed buffers clone by Arc, the
/// numeric mirror of the utf8 oifvy lever.)
fn lazy_all_valid_int64_arc(data: Arc<[i64]>) -> Self {
Self::LazyAllValidInt64 {
data,
dense_cycle: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_all_valid_int64_chunks(chunks: Arc<[Int64Chunk]>, len: usize) -> Self {
Self::LazyAllValidInt64Chunks {
chunks,
len,
data: OnceLock::new(),
dense_cycle: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_all_valid_datetime64(data: Vec<i64>) -> Self {
Self::lazy_all_valid_datetime64_arc(Arc::from(data))
}
/// Move-not-copy datetime backing (the datetime sibling of
/// `lazy_all_valid_int64_owned`): box the owned `Vec<i64>` nanos in an `Arc`
/// with no element copy. Used by the scattered Datetime64 gather.
fn lazy_all_valid_datetime64_owned(data: Vec<i64>) -> Self {
Self::LazyAllValidDatetime64Vec {
data: Arc::new(data),
values: OnceLock::new(),
}
}
/// Move-not-copy Timedelta64 backing (sibling of the datetime owned ctor).
fn lazy_all_valid_timedelta64_owned(data: Vec<i64>) -> Self {
Self::LazyAllValidTimedelta64Vec {
data: Arc::new(data),
values: OnceLock::new(),
}
}
fn lazy_all_valid_period_owned(data: Vec<i64>, freq: PeriodFreq) -> Self {
Self::LazyAllValidPeriodVec {
data: Arc::new(data),
freq,
values: OnceLock::new(),
}
}
fn lazy_nullable_datetime64(data: Vec<i64>, validity: ValidityMask) -> Self {
Self::LazyNullableDatetime64 {
data,
validity,
values: OnceLock::new(),
}
}
fn lazy_nullable_timedelta64(data: Vec<i64>, validity: ValidityMask) -> Self {
Self::LazyNullableTimedelta64 {
data,
validity,
values: OnceLock::new(),
}
}
fn lazy_nullable_period(
data: Vec<i64>,
freq: PeriodFreq,
missing_freq: PeriodFreq,
validity: ValidityMask,
) -> Self {
Self::LazyNullablePeriod {
data,
freq,
missing_freq,
validity,
values: OnceLock::new(),
}
}
fn lazy_all_valid_datetime64_arc(data: Arc<[i64]>) -> Self {
Self::LazyAllValidDatetime64 {
data,
values: OnceLock::new(),
}
}
fn lazy_all_valid_float64(data: Vec<f64>) -> Self {
Self::lazy_all_valid_float64_with_finite(data, None)
}
fn bool_once_lock(value: Option<bool>) -> OnceLock<bool> {
let lock = OnceLock::new();
if let Some(value) = value {
let _ = lock.set(value);
}
lock
}
fn lazy_all_valid_float64_with_finite(data: Vec<f64>, all_finite: Option<bool>) -> Self {
let data = Arc::from(data);
match all_finite {
Some(all_finite) => {
Self::lazy_all_valid_float64_arc_with_finite(data, Some(all_finite))
}
None => Self::lazy_all_valid_float64_arc(data),
}
}
/// MOVE an owned `Vec<f64>` into the all-valid Float64 backing without the
/// `Arc::from(Vec)` realloc-copy (a cold-page-fault-bound ~5.7ms/1M). For
/// op OUTPUTS that produce a fresh owned Vec (cumsum/cummax/cummin/cumprod)
/// where the buffer is hot from the just-completed write — so reusing it
/// (Arc::new, one tiny box) instead of allocating+copying a cold Arc<[f64]>
/// is a 6-8x op-side win. General `from_f64_values` stays on `Arc<[f64]>` so
/// the take_positions/binary/witness zero-copy fast paths (which key on that
/// variant) are unaffected.
fn lazy_all_valid_float64_owned(data: Vec<f64>) -> Self {
Self::lazy_all_valid_float64_owned_with_finite(data, None)
}
/// Witness-carrying [`Self::lazy_all_valid_float64_owned`]: MOVE the owned Vec
/// AND seed the all-finite witness (so abs/round/etc. carry their input
/// finiteness for free, exactly as the `Arc::from` path did).
fn lazy_all_valid_float64_owned_with_finite(data: Vec<f64>, all_finite: Option<bool>) -> Self {
Self::LazyAllValidFloat64Vec {
data: Arc::new(data),
all_finite: Self::bool_once_lock(all_finite),
values: OnceLock::new(),
}
}
/// Read the cached all-finite witness for an all-valid Float64 backing, if
/// one has already been computed. Returns `None` when the variant carries no
/// witness or it has not been resolved yet — never forces a scan.
fn all_valid_float64_finite_witness(&self) -> Option<bool> {
match self {
Self::LazyAllValidFloat64 { all_finite, .. }
| Self::LazyAllValidFloat64Chunks { all_finite, .. }
| Self::LazyAllValidFloat64Slice { all_finite, .. } => all_finite.get().copied(),
_ => None,
}
}
/// Share an existing `Arc` f64 buffer in O(1) (used by `Clone`).
fn lazy_all_valid_float64_arc(data: Arc<[f64]>) -> Self {
Self::lazy_all_valid_float64_arc_with_finite(data, None)
}
fn lazy_all_valid_float64_arc_with_finite(data: Arc<[f64]>, all_finite: Option<bool>) -> Self {
Self::LazyAllValidFloat64 {
data,
all_finite: Self::bool_once_lock(all_finite),
values: OnceLock::new(),
}
}
fn lazy_all_valid_float64_chunks(chunks: Arc<[Float64Chunk]>, len: usize) -> Self {
Self::LazyAllValidFloat64Chunks {
chunks,
len,
data: OnceLock::new(),
all_finite: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_strided_float64(data: Arc<[f64]>, start: usize, step: usize, len: usize) -> Self {
debug_assert!(step > 0);
if len > 0 {
debug_assert!(
start
.checked_add(step.saturating_mul(len.saturating_sub(1)))
.is_some_and(|last| last < data.len())
);
}
Self::LazyStridedFloat64 {
data,
start,
step,
len,
expanded: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_all_valid_float64_slice(data: Arc<[f64]>, start: usize, len: usize) -> Self {
Self::lazy_all_valid_float64_slice_with_finite(data, start, len, None)
}
fn lazy_all_valid_float64_slice_with_finite(
data: Arc<[f64]>,
start: usize,
len: usize,
all_finite: Option<bool>,
) -> Self {
debug_assert!(
start.checked_add(len).is_some_and(|end| end <= data.len()),
"Float64 view window must lie within source data"
);
Self::LazyAllValidFloat64Slice {
data,
start,
len,
all_finite: Self::bool_once_lock(all_finite),
values: OnceLock::new(),
}
}
fn lazy_all_valid_float64_dot(
a_cols: Arc<[Float64DotInput]>,
b_col: Arc<[f64]>,
len: usize,
) -> Self {
debug_assert_eq!(a_cols.len(), b_col.len());
Self::LazyAllValidFloat64Dot {
a_cols,
b_col,
len,
data: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_all_valid_float64_pairwise_stat_matrix_column(
plan: Arc<Float64PairwiseStatMatrixPlan>,
col: usize,
) -> Self {
debug_assert!(col < plan.column_len());
Self::LazyAllValidFloat64PairwiseStatMatrixColumn {
plan,
col,
data: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_all_valid_float64_transpose_row(
plan: Arc<Float64TransposeRowsPlan>,
source_row: usize,
) -> Self {
debug_assert!(source_row < plan.row_len);
Self::LazyAllValidFloat64TransposeRow {
plan,
source_row,
data: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_combine_first_float64(
left: Arc<[f64]>,
right: Arc<[f64]>,
left_validity_words: Arc<[u64]>,
len: usize,
) -> Self {
debug_assert!(left.len() >= len);
debug_assert!(right.len() >= len);
Self::LazyCombineFirstFloat64 {
left,
right,
left_validity_words,
len,
data: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_nullable_float64(data: Vec<f64>, validity: ValidityMask) -> Self {
Self::LazyNullableFloat64 {
data,
validity,
values: OnceLock::new(),
}
}
fn lazy_nullable_int64(data: Vec<i64>, validity: ValidityMask) -> Self {
Self::LazyNullableInt64 {
data,
validity,
values: OnceLock::new(),
}
}
fn lazy_nullable_bool(data: Vec<bool>, validity: ValidityMask) -> Self {
Self::LazyNullableBool {
data,
validity,
values: OnceLock::new(),
}
}
fn lazy_all_valid_bool(data: Vec<bool>) -> Self {
Self::lazy_all_valid_bool_arc(Arc::from(data))
}
/// Share an existing `Arc` bool buffer in O(1) (used by `Clone`).
fn lazy_all_valid_bool_arc(data: Arc<[bool]>) -> Self {
Self::LazyAllValidBool {
data,
affine_selection: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_shifted_bool(source: Arc<[bool]>, periods: i64, fill: bool, len: usize) -> Self {
debug_assert!(source.len() >= len);
Self::LazyShiftedBool {
source,
periods,
fill,
len,
data: OnceLock::new(),
affine_selection: OnceLock::new(),
values: OnceLock::new(),
}
}
fn materialize_shifted_bool(
source: &[bool],
periods: i64,
fill: bool,
len: usize,
) -> Vec<bool> {
let abs = saturating_i64_abs_to_usize(periods);
if abs >= len {
return vec![fill; len];
}
let mut out = Vec::with_capacity(len);
if periods > 0 {
out.resize(abs, fill);
out.extend_from_slice(&source[..len - abs]);
} else {
out.extend_from_slice(&source[abs..len]);
out.resize(len, fill);
}
out
}
fn lazy_contiguous_utf8(bytes: Vec<u8>, offsets: Vec<usize>) -> Self {
debug_assert!(!offsets.is_empty(), "offsets must hold n+1 entries");
debug_assert_eq!(*offsets.last().expect("non-empty"), bytes.len());
Self::lazy_contiguous_utf8_arc(Arc::from(bytes), Arc::from(offsets))
}
fn lazy_lower_hex_sequence_utf8(
prefix: &[u8],
start: u64,
len: usize,
hex_width: usize,
) -> Option<Self> {
if prefix.is_empty() || hex_width == 0 || hex_width > 16 {
return None;
}
if len > 0 {
let last = start.checked_add(u64::try_from(len.checked_sub(1)?).ok()?)?;
if hex_width < 16 && (last >> (hex_width * 4)) != 0 {
return None;
}
}
let _ = prefix.len().checked_add(hex_width)?.checked_mul(len)?;
let _ = len.checked_add(1)?;
Some(Self::LazyLowerHexSequenceUtf8 {
prefix: Arc::from(prefix),
start,
len,
hex_width,
buffers: OnceLock::new(),
values: OnceLock::new(),
})
}
fn materialize_lower_hex_sequence_utf8(
prefix: &[u8],
start: u64,
len: usize,
hex_width: usize,
) -> Utf8ArcBuffers {
let width = prefix.len() + hex_width;
let mut bytes = Vec::with_capacity(width * len);
let mut offsets = Vec::with_capacity(len + 1);
offsets.push(0);
let mut row_key = Vec::with_capacity(width);
row_key.extend_from_slice(prefix);
push_fixed_width_lower_hex(&mut row_key, start, hex_width);
for row in 0..len {
bytes.extend_from_slice(&row_key);
offsets.push(bytes.len());
if row + 1 < len {
increment_fixed_width_lower_hex(&mut row_key[prefix.len()..]);
}
}
(Arc::from(bytes), Arc::from(offsets))
}
fn materialized_lower_hex_buffers<'a>(
prefix: &[u8],
start: u64,
len: usize,
hex_width: usize,
buffers: &'a OnceLock<Utf8ArcBuffers>,
) -> &'a Utf8ArcBuffers {
buffers.get_or_init(|| {
Self::materialize_lower_hex_sequence_utf8(prefix, start, len, hex_width)
})
}
fn lower_hex_sequence_witness(
prefix: &[u8],
start: u64,
len: usize,
hex_width: usize,
) -> (&[u8], Utf8LowerHexSequence, usize) {
(
prefix,
Utf8LowerHexSequence {
prefix_len: prefix.len(),
hex_width,
start,
},
len,
)
}
/// Construct a `LazyContiguousUtf8` from already-`Arc`-shared buffers,
/// sharing them in O(1) instead of re-allocating. Used by `Clone` so two
/// contiguous-Utf8 columns can share one immutable byte buffer
/// (br-frankenpandas-oifvy). The witness caches start fresh — they are pure
/// functions of the (identical) shared buffers, so a clone recomputes the
/// same value lazily if asked.
fn lazy_contiguous_utf8_arc(bytes: Arc<[u8]>, offsets: Arc<[usize]>) -> Self {
debug_assert!(!offsets.is_empty(), "offsets must hold n+1 entries");
debug_assert_eq!(*offsets.last().expect("non-empty"), bytes.len());
Self::LazyContiguousUtf8 {
bytes,
offsets,
strictly_increasing: OnceLock::new(),
fixed_width: OnceLock::new(),
lower_hex_sequence: OnceLock::new(),
factorize_default: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_nullable_utf8(bytes: Vec<u8>, offsets: Vec<usize>, validity: ValidityMask) -> Self {
debug_assert!(!offsets.is_empty(), "offsets must hold n+1 entries");
debug_assert_eq!(*offsets.last().expect("non-empty"), bytes.len());
debug_assert_eq!(offsets.len() - 1, validity.len());
Self::LazyNullableUtf8 {
bytes: Arc::from(bytes),
offsets: Arc::from(offsets),
validity,
values: OnceLock::new(),
}
}
/// Build a `LazyGatherUtf8` (br-frankenpandas-yiqv5): a deferred gather of
/// an all-valid `Eager` Utf8 `source` by `positions` (`usize::MAX` marks a
/// missing slot). Shares `source` in O(1); the gathered Scalar view
/// materializes once on demand.
fn lazy_gather_utf8(source: Arc<[Scalar]>, positions: Arc<[usize]>) -> Self {
Self::LazyGatherUtf8 {
source,
positions,
values: OnceLock::new(),
}
}
fn lazy_nullable_utf8_range(
source: Arc<[Scalar]>,
null_prefix: usize,
source_start: usize,
source_len: usize,
null_suffix: usize,
) -> Self {
debug_assert!(
source_start
.checked_add(source_len)
.is_some_and(|end| end <= source.len())
);
Self::LazyNullableUtf8Range {
source,
null_prefix,
source_start,
source_len,
null_suffix,
values: OnceLock::new(),
}
}
/// Share the underlying `Eager` Scalar `Arc` in O(1), if this backing is
/// eager. Used by the deferred Utf8 gather to capture an immutable source.
fn eager_arc(&self) -> Option<&Arc<[Scalar]>> {
match self {
Self::Eager(values) => Some(values),
_ => None,
}
}
/// Build a zero-copy contiguous row-range view over a shared contiguous-Utf8
/// backing (br-frankenpandas-jbyuc.1.1.1). Rows `start..start+len` of the
/// source become rows `0..len` of the view. Shares `bytes`/`offsets` in
/// O(1); the Scalar view materializes on demand.
fn lazy_utf8_slice(bytes: Arc<[u8]>, offsets: Arc<[usize]>, start: usize, len: usize) -> Self {
debug_assert!(
start + len < offsets.len(),
"view window must lie within the source offsets"
);
Self::LazyUtf8Slice {
bytes,
offsets,
start,
len,
values: OnceLock::new(),
}
}
fn lazy_repeat_runs_int64(runs: Vec<(i64, usize)>, total_len: usize) -> Self {
debug_assert_eq!(
runs.iter().map(|&(_, run_len)| run_len).sum::<usize>(),
total_len
);
Self::LazyRepeatRunsInt64 {
runs,
total_len,
data: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_repeat_values_int64(
run_values: Vec<i64>,
run_lens: Arc<[usize]>,
total_len: usize,
) -> Self {
debug_assert_eq!(run_values.len(), run_lens.len());
debug_assert_eq!(run_lens.iter().sum::<usize>(), total_len);
Self::LazyRepeatValuesInt64 {
run_values,
run_lens,
total_len,
data: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_repeated_slices_int64(
data: Vec<i64>,
segments: Vec<(usize, usize)>,
total_len: usize,
) -> Self {
Self::lazy_repeated_slices_int64_shared(data, Arc::from(segments), total_len)
}
fn lazy_repeated_slices_int64_shared(
data: Vec<i64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
) -> Self {
debug_assert_eq!(
segments.iter().map(|&(_, len)| len).sum::<usize>(),
total_len
);
debug_assert!(
segments
.iter()
.all(|&(start, len)| start.checked_add(len).is_some_and(|end| end <= data.len()))
);
Self::LazyRepeatedSlicesInt64 {
data,
segments,
total_len,
expanded: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_repeat_values_float64(
run_values: Vec<f64>,
run_lens: Arc<[usize]>,
total_len: usize,
) -> Self {
debug_assert_eq!(run_values.len(), run_lens.len());
debug_assert_eq!(run_lens.iter().sum::<usize>(), total_len);
Self::LazyRepeatValuesFloat64 {
run_values,
run_lens,
total_len,
values: OnceLock::new(),
}
}
fn lazy_repeated_slices_float64_shared(
data: Vec<f64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
) -> Self {
debug_assert_eq!(
segments.iter().map(|&(_, len)| len).sum::<usize>(),
total_len
);
debug_assert!(
segments
.iter()
.all(|&(start, len)| start.checked_add(len).is_some_and(|end| end <= data.len()))
);
Self::LazyRepeatedSlicesFloat64 {
data,
segments,
total_len,
expanded: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_nullable_repeated_slices_int64(
data: Vec<i64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
) -> Self {
debug_assert_eq!(
segments.iter().map(|&(_, len)| len).sum::<usize>(),
total_len
);
Self::LazyNullableRepeatedSlicesInt64 {
data,
segments,
total_len,
values: OnceLock::new(),
}
}
fn lazy_nullable_repeated_slices_float64(
data: Vec<f64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
) -> Self {
debug_assert_eq!(
segments.iter().map(|&(_, len)| len).sum::<usize>(),
total_len
);
Self::LazyNullableRepeatedSlicesFloat64 {
data,
segments,
total_len,
values: OnceLock::new(),
}
}
fn lazy_nullable_repeat_values_float64(
run_values: Vec<f64>,
run_valid: Arc<[bool]>,
run_lens: Arc<[usize]>,
total_len: usize,
) -> Self {
debug_assert_eq!(run_values.len(), run_lens.len());
debug_assert_eq!(run_valid.len(), run_lens.len());
debug_assert_eq!(run_lens.iter().sum::<usize>(), total_len);
Self::LazyNullableRepeatValuesFloat64 {
run_values,
run_valid,
run_lens,
total_len,
values: OnceLock::new(),
}
}
fn lazy_nullable_repeated_positions_i64_as_float64(
source: Arc<[i64]>,
positions: Arc<[usize]>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
) -> Self {
debug_assert_eq!(
segments.iter().map(|&(_, len)| len).sum::<usize>(),
total_len
);
debug_assert!(segments.iter().all(|&(start, len)| {
start == usize::MAX
|| start
.checked_add(len)
.is_some_and(|end| end <= positions.len())
}));
debug_assert!(positions.iter().all(|&pos| pos < source.len()));
Self::LazyNullableRepeatedPositionsI64AsFloat64 {
source,
positions,
segments,
total_len,
values: OnceLock::new(),
}
}
fn lazy_nullable_dense_cycle_right_i64_as_float64(
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
min_key: i64,
span: usize,
total_len: usize,
) -> Self {
debug_assert_eq!(source.len(), right_witness.len);
debug_assert!(span > 0 || total_len == 0);
Self::LazyNullableDenseCycleRightI64AsFloat64 {
source,
left_witness,
right_witness,
min_key,
span,
total_len,
values: OnceLock::new(),
}
}
fn lazy_nullable_dense_cycle_left_i64_as_float64(
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
min_key: i64,
span: usize,
total_len: usize,
) -> Self {
debug_assert_eq!(source.len(), left_witness.len);
debug_assert!(span > 0 || total_len == 0);
Self::LazyNullableDenseCycleLeftI64AsFloat64 {
source,
left_witness,
right_witness,
min_key,
span,
total_len,
values: OnceLock::new(),
}
}
fn lazy_dense_cycle_probe_repeat_int64(
source: Arc<[i64]>,
probe_witness: Int64DenseCycleWitness,
build_witness: Int64DenseCycleWitness,
total_len: usize,
) -> Self {
debug_assert_eq!(source.len(), probe_witness.len);
Self::LazyDenseCycleProbeRepeatInt64 {
source,
probe_witness,
build_witness,
total_len,
data: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_left_join_dense_cycle_left_int64(
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
total_len: usize,
) -> Self {
debug_assert_eq!(source.len(), left_witness.len);
Self::LazyLeftJoinDenseCycleLeftInt64 {
source,
left_witness,
right_witness,
total_len,
data: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_nullable_dense_cycle_probe_build_int64(
source: Arc<[i64]>,
probe_witness: Int64DenseCycleWitness,
build_witness: Int64DenseCycleWitness,
total_len: usize,
) -> Self {
debug_assert_eq!(source.len(), build_witness.len);
Self::LazyNullableDenseCycleProbeBuildInt64 {
source,
probe_witness,
build_witness,
total_len,
values: OnceLock::new(),
}
}
fn lazy_left_join_dense_cycle_right_int64(
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
total_len: usize,
) -> Self {
debug_assert_eq!(source.len(), right_witness.len);
Self::LazyLeftJoinDenseCycleRightInt64 {
source,
left_witness,
right_witness,
total_len,
data: OnceLock::new(),
values: OnceLock::new(),
}
}
fn lazy_nullable_repeat_positions_i64_as_float64(
source: Arc<[i64]>,
run_positions: Arc<[usize]>,
run_valid: Arc<[bool]>,
run_lens: Arc<[usize]>,
total_len: usize,
) -> Self {
debug_assert_eq!(run_positions.len(), run_lens.len());
debug_assert_eq!(run_valid.len(), run_lens.len());
debug_assert_eq!(run_lens.iter().sum::<usize>(), total_len);
debug_assert!(
run_positions
.iter()
.zip(run_valid.iter())
.all(|(&pos, &valid)| !valid || pos < source.len())
);
Self::LazyNullableRepeatPositionsI64AsFloat64 {
source,
run_positions,
run_valid,
run_lens,
total_len,
values: OnceLock::new(),
}
}
fn expand_repeat_values_i64(
run_values: &[i64],
run_lens: &[usize],
total_len: usize,
) -> Vec<i64> {
const PARALLEL_MIN_VALUES: usize = 1 << 18;
const PARALLEL_MAX_CHUNKS: usize = 16;
debug_assert_eq!(run_values.len(), run_lens.len());
let thread_count = std::thread::available_parallelism()
.map_or(1, usize::from)
.min(PARALLEL_MAX_CHUNKS);
if total_len < PARALLEL_MIN_VALUES || thread_count < 2 || run_values.is_empty() {
let mut out = Vec::with_capacity(total_len);
for (&value, &run_len) in run_values.iter().zip(run_lens.iter()) {
out.resize(out.len() + run_len, value);
}
return out;
}
let target = total_len.div_ceil(thread_count).max(1);
let mut boundaries = vec![(0usize, 0usize)];
let mut cumulative = 0usize;
let mut next_target = target;
for (run_idx, &run_len) in run_lens.iter().enumerate() {
cumulative += run_len;
if cumulative >= next_target && run_idx + 1 < run_lens.len() {
boundaries.push((run_idx + 1, cumulative));
next_target = cumulative.saturating_add(target);
}
}
debug_assert_eq!(cumulative, total_len);
boundaries.push((run_lens.len(), total_len));
let mut out = vec![0i64; total_len];
let mut chunk_slices = Vec::with_capacity(boundaries.len() - 1);
let mut rest: &mut [i64] = out.as_mut_slice();
let mut prev = 0usize;
for window in boundaries.windows(2) {
let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
prev = window[1].1;
rest = tail;
chunk_slices.push(chunk_slice);
}
std::thread::scope(|scope| {
let mut handles = Vec::with_capacity(chunk_slices.len());
for (chunk_idx, chunk_slice) in chunk_slices.into_iter().enumerate() {
let (run_start, _) = boundaries[chunk_idx];
let (run_end, _) = boundaries[chunk_idx + 1];
let run_values = &run_values[run_start..run_end];
let run_lens = &run_lens[run_start..run_end];
handles.push(scope.spawn(move || {
let mut cursor = 0usize;
for (&value, &run_len) in run_values.iter().zip(run_lens.iter()) {
chunk_slice[cursor..cursor + run_len].fill(value);
cursor += run_len;
}
debug_assert_eq!(cursor, chunk_slice.len());
}));
}
for handle in handles {
handle
.join()
.expect("repeat-value expansion worker must not panic");
}
});
out
}
fn expand_repeated_slices_f64(
data: &[f64],
segments: &[(usize, usize)],
total_len: usize,
) -> Vec<f64> {
const PARALLEL_MIN_VALUES: usize = 1 << 18;
const PARALLEL_MAX_CHUNKS: usize = 16;
if let Some((start, period)) = Self::repeated_prefix_period(segments, total_len, data.len())
{
let mut out = Vec::with_capacity(total_len);
out.extend_from_slice(&data[start..start + period.min(total_len)]);
while out.len() < total_len {
let copy_len = out.len().min(total_len - out.len());
out.extend_from_within(..copy_len);
}
return out;
}
let thread_count = std::thread::available_parallelism()
.map_or(1, usize::from)
.min(PARALLEL_MAX_CHUNKS);
if total_len < PARALLEL_MIN_VALUES || thread_count < 2 || segments.is_empty() {
let mut out = Vec::with_capacity(total_len);
for &(start, len) in segments {
out.extend_from_slice(&data[start..start + len]);
}
return out;
}
let target = total_len.div_ceil(thread_count).max(1);
let mut boundaries = vec![(0usize, 0usize)];
let mut cumulative = 0usize;
let mut next_target = target;
for (segment_idx, &(_, len)) in segments.iter().enumerate() {
cumulative += len;
if cumulative >= next_target && segment_idx + 1 < segments.len() {
boundaries.push((segment_idx + 1, cumulative));
next_target = cumulative.saturating_add(target);
}
}
debug_assert_eq!(cumulative, total_len);
boundaries.push((segments.len(), total_len));
let mut out = vec![0.0f64; total_len];
let mut chunk_slices = Vec::with_capacity(boundaries.len() - 1);
let mut rest: &mut [f64] = out.as_mut_slice();
let mut prev = 0usize;
for window in boundaries.windows(2) {
let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
prev = window[1].1;
rest = tail;
chunk_slices.push(chunk_slice);
}
std::thread::scope(|scope| {
let mut handles = Vec::with_capacity(chunk_slices.len());
for (chunk_idx, chunk_slice) in chunk_slices.into_iter().enumerate() {
let (segment_start, _) = boundaries[chunk_idx];
let (segment_end, _) = boundaries[chunk_idx + 1];
let segments = &segments[segment_start..segment_end];
handles.push(scope.spawn(move || {
let mut cursor = 0usize;
for &(start, len) in segments {
chunk_slice[cursor..cursor + len]
.copy_from_slice(&data[start..start + len]);
cursor += len;
}
debug_assert_eq!(cursor, chunk_slice.len());
}));
}
for handle in handles {
handle
.join()
.expect("repeated-slice expansion worker must not panic");
}
});
out
}
fn repeated_prefix_period(
segments: &[(usize, usize)],
total_len: usize,
data_len: usize,
) -> Option<(usize, usize)> {
if total_len == 0 {
return segments.is_empty().then_some((0, 0));
}
let &(start, period) = segments.first()?;
if period == 0 || start.checked_add(period)? > data_len {
return None;
}
let mut remaining = total_len;
for (idx, &(segment_start, len)) in segments.iter().enumerate() {
if segment_start != start {
return None;
}
if remaining >= period {
if len != period {
return None;
}
remaining -= period;
} else {
if idx + 1 != segments.len() || len != remaining {
return None;
}
remaining = 0;
}
}
(remaining == 0).then_some((start, period))
}
fn expand_repeated_slices_i64(
data: &[i64],
segments: &[(usize, usize)],
total_len: usize,
) -> Vec<i64> {
const PARALLEL_MIN_VALUES: usize = 1 << 18;
const PARALLEL_MAX_CHUNKS: usize = 16;
let thread_count = std::thread::available_parallelism()
.map_or(1, usize::from)
.min(PARALLEL_MAX_CHUNKS);
if total_len < PARALLEL_MIN_VALUES || thread_count < 2 || segments.is_empty() {
let mut out = Vec::with_capacity(total_len);
for &(start, len) in segments {
out.extend_from_slice(&data[start..start + len]);
}
return out;
}
let target = total_len.div_ceil(thread_count).max(1);
let mut boundaries = vec![(0usize, 0usize)];
let mut cumulative = 0usize;
let mut next_target = target;
for (segment_idx, &(_, len)) in segments.iter().enumerate() {
cumulative += len;
if cumulative >= next_target && segment_idx + 1 < segments.len() {
boundaries.push((segment_idx + 1, cumulative));
next_target = cumulative.saturating_add(target);
}
}
debug_assert_eq!(cumulative, total_len);
boundaries.push((segments.len(), total_len));
let mut out = vec![0i64; total_len];
let mut chunk_slices = Vec::with_capacity(boundaries.len() - 1);
let mut rest: &mut [i64] = out.as_mut_slice();
let mut prev = 0usize;
for window in boundaries.windows(2) {
let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
prev = window[1].1;
rest = tail;
chunk_slices.push(chunk_slice);
}
std::thread::scope(|scope| {
let mut handles = Vec::with_capacity(chunk_slices.len());
for (chunk_idx, chunk_slice) in chunk_slices.into_iter().enumerate() {
let (segment_start, _) = boundaries[chunk_idx];
let (segment_end, _) = boundaries[chunk_idx + 1];
let segments = &segments[segment_start..segment_end];
handles.push(scope.spawn(move || {
let mut cursor = 0usize;
for &(start, len) in segments {
chunk_slice[cursor..cursor + len]
.copy_from_slice(&data[start..start + len]);
cursor += len;
}
debug_assert_eq!(cursor, chunk_slice.len());
}));
}
for handle in handles {
handle
.join()
.expect("repeated-slice expansion worker must not panic");
}
});
out
}
/// The expanded contiguous `i64` buffer of a repeat-run backing, built
/// once on first request. `None` for every other representation.
///
/// Large expansions are row-chunked across scoped threads (disjoint
/// `split_at_mut` slices, same scheme as the dense join fill) so a
/// consumer that forces materialization pays the same parallel fill the
/// eager path would have, not a serial one.
fn repeat_runs_i64_data(&self) -> Option<&[i64]> {
const PARALLEL_MIN_VALUES: usize = 1 << 18;
const PARALLEL_MAX_CHUNKS: usize = 16;
if let Self::LazyRepeatRunsInt64 {
runs,
total_len,
data,
..
} = self
{
return Some(
data.get_or_init(|| {
let thread_count = std::thread::available_parallelism()
.map_or(1, usize::from)
.min(PARALLEL_MAX_CHUNKS);
if *total_len < PARALLEL_MIN_VALUES || thread_count < 2 || runs.is_empty() {
let mut out = Vec::with_capacity(*total_len);
for &(value, run_len) in runs {
out.resize(out.len() + run_len, value);
}
return out;
}
// Chunk boundaries (run_idx, out_pos) balanced by output
// size; each worker fills its disjoint output slice.
let target = total_len.div_ceil(thread_count).max(1);
let mut boundaries = vec![(0usize, 0usize)];
let mut cumulative = 0usize;
let mut next_target = target;
for (run_idx, &(_, run_len)) in runs.iter().enumerate() {
cumulative += run_len;
if cumulative >= next_target && run_idx + 1 < runs.len() {
boundaries.push((run_idx + 1, cumulative));
next_target = cumulative.saturating_add(target);
}
}
debug_assert_eq!(cumulative, *total_len);
boundaries.push((runs.len(), *total_len));
let mut out = vec![0i64; *total_len];
let mut chunk_slices = Vec::with_capacity(boundaries.len() - 1);
let mut rest: &mut [i64] = out.as_mut_slice();
let mut prev = 0usize;
for window in boundaries.windows(2) {
let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
prev = window[1].1;
rest = tail;
chunk_slices.push(chunk_slice);
}
std::thread::scope(|scope| {
let mut handles = Vec::with_capacity(chunk_slices.len());
for (chunk_idx, chunk_slice) in chunk_slices.into_iter().enumerate() {
let (run_start, _) = boundaries[chunk_idx];
let (run_end, _) = boundaries[chunk_idx + 1];
let runs = &runs[run_start..run_end];
handles.push(scope.spawn(move || {
let mut cursor = 0usize;
for &(value, run_len) in runs {
chunk_slice[cursor..cursor + run_len].fill(value);
cursor += run_len;
}
debug_assert_eq!(cursor, chunk_slice.len());
}));
}
for handle in handles {
handle
.join()
.expect("repeat-run expansion worker must not panic");
}
});
out
})
.as_slice(),
);
}
if let Self::LazyRepeatValuesInt64 {
run_values,
run_lens,
total_len,
data,
..
} = self
{
return Some(
data.get_or_init(|| {
Self::expand_repeat_values_i64(run_values, run_lens, *total_len)
})
.as_slice(),
);
}
if let Self::LazyDenseCycleProbeRepeatInt64 {
source,
probe_witness,
build_witness,
total_len,
data,
..
} = self
{
return Some(
data.get_or_init(|| {
Self::expand_dense_cycle_probe_repeat_i64(
source,
*probe_witness,
*build_witness,
*total_len,
)
})
.as_slice(),
);
}
None
}
fn repeated_slices_i64_data(&self) -> Option<&[i64]> {
if let Self::LazyRepeatedSlicesInt64 {
data,
segments,
total_len,
expanded,
..
} = self
{
return Some(
expanded
.get_or_init(|| Self::expand_repeated_slices_i64(data, segments, *total_len))
.as_slice(),
);
}
None
}
fn repeated_slices_f64_data(&self) -> Option<&[f64]> {
if let Self::LazyRepeatedSlicesFloat64 {
data,
segments,
total_len,
expanded,
..
} = self
{
return Some(
expanded
.get_or_init(|| Self::expand_repeated_slices_f64(data, segments, *total_len))
.as_slice(),
);
}
None
}
fn dense_cycle_key_at(witness: Int64DenseCycleWitness, row: usize) -> i64 {
witness
.start
.checked_add(
i64::try_from(row % witness.period)
.expect("dense-cycle period offset must fit in i64"),
)
.expect("dense-cycle key offset was prevalidated")
}
fn expand_dense_cycle_probe_repeat_i64(
source: &[i64],
probe_witness: Int64DenseCycleWitness,
build_witness: Int64DenseCycleWitness,
total_len: usize,
) -> Vec<i64> {
let mut out = Vec::with_capacity(total_len);
for (probe_pos, &value) in source.iter().enumerate().take(probe_witness.len) {
let key = Self::dense_cycle_key_at(probe_witness, probe_pos);
let run_len = build_witness
.offset_count_for_key(key)
.map_or(1, |(_, count)| count);
out.resize(out.len() + run_len, value);
}
debug_assert_eq!(out.len(), total_len);
out
}
fn expand_left_join_dense_cycle_left_i64(
source: &[i64],
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
total_len: usize,
) -> Vec<i64> {
let mut out = Vec::with_capacity(total_len);
for (left_pos, &value) in source.iter().enumerate().take(left_witness.len) {
let key = Self::dense_cycle_key_at(left_witness, left_pos);
let run_len = right_witness
.offset_count_for_key(key)
.map_or(1, |(_, count)| count);
out.resize(out.len() + run_len, value);
}
debug_assert_eq!(out.len(), total_len);
out
}
fn expand_left_join_dense_cycle_right_i64(
source: &[i64],
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
total_len: usize,
) -> Vec<i64> {
let mut out = Vec::with_capacity(total_len);
for left_pos in 0..left_witness.len {
let key = Self::dense_cycle_key_at(left_witness, left_pos);
if let Some((mut right_pos, right_count)) = right_witness.offset_count_for_key(key) {
for _ in 0..right_count {
out.push(source[right_pos]);
right_pos += right_witness.period;
}
} else {
out.push(0);
}
}
debug_assert_eq!(out.len(), total_len);
out
}
fn left_join_dense_cycle_i64_data(&self) -> Option<&[i64]> {
match self {
Self::LazyLeftJoinDenseCycleLeftInt64 {
source,
left_witness,
right_witness,
total_len,
data,
..
} => Some(
data.get_or_init(|| {
Self::expand_left_join_dense_cycle_left_i64(
source,
*left_witness,
*right_witness,
*total_len,
)
})
.as_slice(),
),
Self::LazyLeftJoinDenseCycleRightInt64 {
source,
left_witness,
right_witness,
total_len,
data,
..
} => Some(
data.get_or_init(|| {
Self::expand_left_join_dense_cycle_right_i64(
source,
*left_witness,
*right_witness,
*total_len,
)
})
.as_slice(),
),
_ => None,
}
}
fn expand_strided_float64(data: &[f64], start: usize, step: usize, len: usize) -> Vec<f64> {
let mut out = Vec::with_capacity(len);
for idx in 0..len {
let source_idx = start + idx * step;
out.push(data[source_idx]);
}
out
}
fn strided_float64_data(&self) -> Option<&[f64]> {
if let Self::LazyStridedFloat64 {
data,
start,
step,
len,
expanded,
..
} = self
{
return Some(
expanded
.get_or_init(|| Self::expand_strided_float64(data, *start, *step, *len))
.as_slice(),
);
}
None
}
fn materialize_float64_dot(a_cols: &[Float64DotInput], b_col: &[f64], len: usize) -> Vec<f64> {
debug_assert_eq!(a_cols.len(), b_col.len());
// AXPY loop order: outer over the k A-columns, inner streaming over the
// `len` output rows (`out[row] += a_col[row] * b_j`). The prior DOT order
// (outer row, inner column) read `a_cols[j].value_at(row)` — a strided,
// per-access-bounds-checked hop across `k` separate `Arc<[f64]>`
// allocations, one cache miss per (row, col) → 0.59 GFLOP/s / ~3.4 s for
// a 1000×1000 materialize. This order forms each A-column as a
// contiguous slice ONCE and the inner `out += a*b` auto-vectorizes to
// SIMD FMA with unit-stride reads/writes. Bit-identical: the per-output
// summation order is unchanged (each `out[row]` still accumulates
// `j = 0..k` in order).
let mut out = vec![0.0_f64; len];
for (a_col, &b) in a_cols.iter().zip(b_col.iter()) {
let a_slice = &a_col.data[a_col.start..a_col.start + len];
for (o, &a) in out.iter_mut().zip(a_slice.iter()) {
*o += a * b;
}
}
out
}
fn dot_float64_data(&self) -> Option<&[f64]> {
if let Self::LazyAllValidFloat64Dot {
a_cols,
b_col,
len,
data,
..
} = self
{
return Some(
data.get_or_init(|| Self::materialize_float64_dot(a_cols, b_col, *len))
.as_slice(),
);
}
None
}
fn pairwise_stat_float64_data(&self) -> Option<&[f64]> {
if let Self::LazyAllValidFloat64PairwiseStatMatrixColumn {
plan, col, data, ..
} = self
{
return Some(
data.get_or_init(|| plan.materialize_column(*col))
.as_slice(),
);
}
None
}
fn transpose_row_float64_data(&self) -> Option<&[f64]> {
if let Self::LazyAllValidFloat64TransposeRow {
plan,
source_row,
data,
..
} = self
{
return Some(
data.get_or_init(|| plan.materialize_row(*source_row))
.as_slice(),
);
}
None
}
fn materialize_float64_chunks(chunks: &[Float64Chunk], len: usize) -> Vec<f64> {
let mut out = Vec::with_capacity(len);
for chunk in chunks {
out.extend_from_slice(chunk.as_slice());
}
debug_assert_eq!(out.len(), len);
out
}
fn chunks_float64_data(&self) -> Option<&[f64]> {
if let Self::LazyAllValidFloat64Chunks {
chunks, len, data, ..
} = self
{
return Some(
data.get_or_init(|| Self::materialize_float64_chunks(chunks, *len))
.as_slice(),
);
}
None
}
/// Borrow the Float64 chunk views WITHOUT materializing the concatenated
/// buffer (unlike `chunks_float64_data`, which allocates+fills a cold
/// `Vec<f64>` — ~5.7ms/1M of page faults). Lets order-preserving reductions
/// (sum/mean) fold each chunk slice in place, so a `concat(...).sum()` never
/// pays the 40MB materialization pandas' eager concat is forced to.
fn float64_chunks_ref(&self) -> Option<&[Float64Chunk]> {
if let Self::LazyAllValidFloat64Chunks { chunks, .. } = self {
return Some(chunks);
}
None
}
/// Int64 sibling of `float64_chunks_ref` — borrow the concat chunk views
/// without materializing the concatenated `Vec<i64>`.
fn int64_chunks_ref(&self) -> Option<&[Int64Chunk]> {
if let Self::LazyAllValidInt64Chunks { chunks, .. } = self {
return Some(chunks);
}
None
}
fn materialize_int64_chunks(chunks: &[Int64Chunk], len: usize) -> Vec<i64> {
let mut out = Vec::with_capacity(len);
for chunk in chunks {
out.extend_from_slice(chunk.as_slice());
}
debug_assert_eq!(out.len(), len);
out
}
fn chunks_i64_data(&self) -> Option<&[i64]> {
if let Self::LazyAllValidInt64Chunks {
chunks, len, data, ..
} = self
{
return Some(
data.get_or_init(|| Self::materialize_int64_chunks(chunks, *len))
.as_slice(),
);
}
None
}
fn materialize_combine_first_float64(
left: &[f64],
right: &[f64],
left_validity_words: &[u64],
len: usize,
) -> Vec<f64> {
let mut out = left[..len].to_vec();
for (word_idx, out_chunk) in out.chunks_mut(64).enumerate() {
let valid_word = left_validity_words.get(word_idx).copied().unwrap_or(0);
let base = word_idx * 64;
let len_mask = if out_chunk.len() == 64 {
u64::MAX
} else {
(1_u64 << out_chunk.len()) - 1
};
let mut invalid_bits = !valid_word & len_mask;
while invalid_bits != 0 {
let offset = invalid_bits.trailing_zeros() as usize;
out_chunk[offset] = right[base + offset];
invalid_bits &= invalid_bits - 1;
}
let mut valid_bits = valid_word & len_mask;
while valid_bits != 0 {
let offset = valid_bits.trailing_zeros() as usize;
if out_chunk[offset].is_nan() {
out_chunk[offset] = right[base + offset];
}
valid_bits &= valid_bits - 1;
}
}
out
}
fn combine_first_float64_data(&self) -> Option<&[f64]> {
if let Self::LazyCombineFirstFloat64 {
left,
right,
left_validity_words,
len,
data,
..
} = self
{
return Some(
data.get_or_init(|| {
Self::materialize_combine_first_float64(left, right, left_validity_words, *len)
})
.as_slice(),
);
}
None
}
fn as_slice(&self) -> &[Scalar] {
match self {
Self::Eager(values) => values,
Self::LazyAllValidInt64 { data, values, .. } => values
.get_or_init(|| data.iter().copied().map(Scalar::Int64).collect())
.as_slice(),
Self::LazyAllValidInt64Vec { data, values, .. } => values
.get_or_init(|| data.iter().copied().map(Scalar::Int64).collect())
.as_slice(),
Self::LazyAllValidInt64Chunks { chunks, values, .. } => values
.get_or_init(|| {
chunks
.iter()
.flat_map(Int64Chunk::as_slice)
.copied()
.map(Scalar::Int64)
.collect()
})
.as_slice(),
Self::LazyAllValidDatetime64 { data, values } => values
.get_or_init(|| data.iter().copied().map(Scalar::Datetime64).collect())
.as_slice(),
Self::LazyAllValidDatetime64Vec { data, values } => values
.get_or_init(|| data.iter().copied().map(Scalar::Datetime64).collect())
.as_slice(),
Self::LazyAllValidTimedelta64Vec { data, values } => values
.get_or_init(|| data.iter().copied().map(Scalar::Timedelta64).collect())
.as_slice(),
Self::LazyAllValidPeriodVec { data, freq, values } => values
.get_or_init(|| {
data.iter()
.copied()
.map(|ordinal| Scalar::Period(Period::new(ordinal, *freq)))
.collect()
})
.as_slice(),
Self::LazyNullableDatetime64 {
data,
validity,
values,
} => values
.get_or_init(|| {
data.iter()
.enumerate()
.map(|(i, &v)| {
if validity.get(i) {
Scalar::Datetime64(v)
} else {
Scalar::Null(NullKind::NaT)
}
})
.collect()
})
.as_slice(),
Self::LazyNullableTimedelta64 {
data,
validity,
values,
} => values
.get_or_init(|| {
data.iter()
.enumerate()
.map(|(i, &v)| {
if validity.get(i) {
Scalar::Timedelta64(v)
} else {
Scalar::Null(NullKind::NaT)
}
})
.collect()
})
.as_slice(),
Self::LazyNullablePeriod {
data,
freq,
missing_freq,
validity,
values,
} => values
.get_or_init(|| {
data.iter()
.enumerate()
.map(|(i, &ordinal)| {
if validity.get(i) {
Scalar::Period(Period::new(ordinal, *freq))
} else {
Scalar::Period(Period::new(i64::MIN, *missing_freq))
}
})
.collect()
})
.as_slice(),
Self::LazyAllValidFloat64 { data, values, .. } => values
.get_or_init(|| data.iter().copied().map(Scalar::Float64).collect())
.as_slice(),
Self::LazyAllValidFloat64Vec { data, values, .. } => values
.get_or_init(|| data.iter().copied().map(Scalar::Float64).collect())
.as_slice(),
Self::LazyAllValidFloat64Chunks { chunks, values, .. } => values
.get_or_init(|| {
chunks
.iter()
.flat_map(Float64Chunk::as_slice)
.copied()
.map(Scalar::Float64)
.collect()
})
.as_slice(),
Self::LazyAllValidFloat64Slice {
data,
start,
len,
values,
..
} => values
.get_or_init(|| {
data[*start..*start + *len]
.iter()
.copied()
.map(Scalar::Float64)
.collect()
})
.as_slice(),
Self::LazyAllValidFloat64Dot {
a_cols,
b_col,
len,
data,
values,
} => values
.get_or_init(|| {
data.get_or_init(|| Self::materialize_float64_dot(a_cols, b_col, *len))
.iter()
.copied()
.map(Scalar::Float64)
.collect()
})
.as_slice(),
Self::LazyAllValidFloat64PairwiseStatMatrixColumn {
plan,
col,
data,
values,
} => values
.get_or_init(|| {
data.get_or_init(|| plan.materialize_column(*col))
.iter()
.copied()
.map(Scalar::Float64)
.collect()
})
.as_slice(),
Self::LazyAllValidFloat64TransposeRow {
plan,
source_row,
data,
values,
} => values
.get_or_init(|| {
data.get_or_init(|| plan.materialize_row(*source_row))
.iter()
.copied()
.map(Scalar::Float64)
.collect()
})
.as_slice(),
Self::LazyCombineFirstFloat64 {
left,
right,
left_validity_words,
len,
data,
values,
} => values
.get_or_init(|| {
data.get_or_init(|| {
Self::materialize_combine_first_float64(
left,
right,
left_validity_words,
*len,
)
})
.iter()
.copied()
.map(Scalar::Float64)
.collect()
})
.as_slice(),
Self::LazyStridedFloat64 {
data,
start,
step,
len,
expanded,
values,
} => values
.get_or_init(|| {
expanded
.get_or_init(|| Self::expand_strided_float64(data, *start, *step, *len))
.iter()
.copied()
.map(Scalar::Float64)
.collect()
})
.as_slice(),
Self::LazyNullableFloat64 {
data,
validity,
values,
} => values
.get_or_init(|| {
data.iter()
.enumerate()
.map(|(idx, value)| {
if validity.get(idx) || value.is_nan() {
Scalar::Float64(*value)
} else {
Scalar::Null(NullKind::NaN)
}
})
.collect()
})
.as_slice(),
Self::LazyAllValidBool { data, values, .. } => values
.get_or_init(|| data.iter().copied().map(Scalar::Bool).collect())
.as_slice(),
Self::LazyShiftedBool {
source,
periods,
fill,
len,
data,
values,
..
} => values
.get_or_init(|| {
data.get_or_init(|| {
Self::materialize_shifted_bool(source, *periods, *fill, *len)
})
.iter()
.copied()
.map(Scalar::Bool)
.collect()
})
.as_slice(),
Self::LazyContiguousUtf8 {
bytes,
offsets,
values,
..
} => values
.get_or_init(|| {
offsets
.windows(2)
.map(|w| {
Scalar::Utf8(
std::str::from_utf8(&bytes[w[0]..w[1]])
.expect("contiguous utf8 buffer is valid by construction")
.to_owned(),
)
})
.collect()
})
.as_slice(),
Self::LazyLowerHexSequenceUtf8 {
prefix,
start,
len,
hex_width,
buffers,
values,
} => values
.get_or_init(|| {
let (bytes, offsets) = Self::materialized_lower_hex_buffers(
prefix, *start, *len, *hex_width, buffers,
);
offsets
.windows(2)
.map(|w| {
Scalar::Utf8(
std::str::from_utf8(&bytes[w[0]..w[1]])
.expect("lower-hex utf8 buffer is valid by construction")
.to_owned(),
)
})
.collect()
})
.as_slice(),
Self::LazyNullableUtf8 {
bytes,
offsets,
validity,
values,
} => values
.get_or_init(|| {
offsets
.windows(2)
.enumerate()
.map(|(idx, w)| {
if validity.get(idx) {
Scalar::Utf8(
std::str::from_utf8(&bytes[w[0]..w[1]])
.expect("nullable utf8 buffer is valid by construction")
.to_owned(),
)
} else {
Scalar::Null(NullKind::Null)
}
})
.collect()
})
.as_slice(),
Self::LazyGatherUtf8 {
source,
positions,
values,
} => values
.get_or_init(|| {
positions
.iter()
.map(|&pos| {
if pos == usize::MAX {
// Missing slot == missing_for_dtype(Utf8) ==
// Null(NullKind::Null), matching the eager
// null-introducing gather and the
// LazyNullableUtf8 sibling above.
Scalar::Null(NullKind::Null)
} else {
source[pos].clone()
}
})
.collect()
})
.as_slice(),
Self::LazyNullableUtf8Range {
source,
null_prefix,
source_start,
source_len,
null_suffix,
values,
} => values
.get_or_init(|| {
let total_len = null_prefix + source_len + null_suffix;
(0..total_len)
.map(|out_idx| {
if out_idx < *null_prefix
|| out_idx >= null_prefix.saturating_add(*source_len)
{
Scalar::Null(NullKind::Null)
} else {
source[source_start + out_idx - null_prefix].clone()
}
})
.collect()
})
.as_slice(),
Self::LazyNullableInt64 {
data,
validity,
values,
} => values
.get_or_init(|| {
data.iter()
.enumerate()
.map(|(idx, value)| {
if validity.get(idx) {
Scalar::Int64(*value)
} else {
Scalar::Null(NullKind::Null)
}
})
.collect()
})
.as_slice(),
Self::LazyNullableBool {
data,
validity,
values,
} => values
.get_or_init(|| {
data.iter()
.enumerate()
.map(|(idx, value)| {
if validity.get(idx) {
Scalar::Bool(*value)
} else {
Scalar::Null(NullKind::Null)
}
})
.collect()
})
.as_slice(),
Self::LazyRepeatRunsInt64 {
runs,
total_len,
values,
..
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for &(value, run_len) in runs {
out.resize(out.len() + run_len, Scalar::Int64(value));
}
out
})
.as_slice(),
Self::LazyRepeatValuesInt64 {
run_values,
run_lens,
total_len,
values,
..
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for (&value, &run_len) in run_values.iter().zip(run_lens.iter()) {
out.resize(out.len() + run_len, Scalar::Int64(value));
}
out
})
.as_slice(),
Self::LazyRepeatedSlicesInt64 {
data,
segments,
total_len,
values,
..
} => values
.get_or_init(|| {
Self::expand_repeated_slices_i64(data, segments, *total_len)
.into_iter()
.map(Scalar::Int64)
.collect()
})
.as_slice(),
Self::LazyRepeatValuesFloat64 {
run_values,
run_lens,
total_len,
values,
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for (&value, &run_len) in run_values.iter().zip(run_lens.iter()) {
out.resize(out.len() + run_len, Scalar::Float64(value));
}
out
})
.as_slice(),
Self::LazyRepeatedSlicesFloat64 {
data,
segments,
total_len,
values,
..
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for &(start, len) in segments.iter() {
for &value in &data[start..start + len] {
out.push(Scalar::Float64(value));
}
}
out
})
.as_slice(),
Self::LazyNullableRepeatedSlicesInt64 {
data,
segments,
total_len,
values,
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for &(start, len) in segments.iter() {
if start == usize::MAX {
out.resize(out.len() + len, Scalar::Null(NullKind::Null));
} else {
for &value in &data[start..start + len] {
out.push(Scalar::Int64(value));
}
}
}
out
})
.as_slice(),
Self::LazyNullableRepeatedSlicesFloat64 {
data,
segments,
total_len,
values,
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for &(start, len) in segments.iter() {
if start == usize::MAX {
out.resize(out.len() + len, Scalar::Null(NullKind::NaN));
} else {
for &value in &data[start..start + len] {
out.push(Scalar::Float64(value));
}
}
}
out
})
.as_slice(),
Self::LazyNullableRepeatValuesFloat64 {
run_values,
run_valid,
run_lens,
total_len,
values,
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for ((&value, &valid), &run_len) in
run_values.iter().zip(run_valid.iter()).zip(run_lens.iter())
{
if valid {
out.resize(out.len() + run_len, Scalar::Float64(value));
} else {
out.resize(out.len() + run_len, Scalar::Null(NullKind::NaN));
}
}
out
})
.as_slice(),
Self::LazyNullableRepeatedPositionsI64AsFloat64 {
source,
positions,
segments,
total_len,
values,
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for &(start, len) in segments.iter() {
if start == usize::MAX {
out.resize(out.len() + len, Scalar::Null(NullKind::NaN));
} else {
for &source_pos in &positions[start..start + len] {
out.push(Scalar::Float64(source[source_pos] as f64));
}
}
}
out
})
.as_slice(),
Self::LazyNullableDenseCycleRightI64AsFloat64 {
source,
left_witness,
right_witness,
min_key,
span,
total_len,
values,
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for bucket in 0..*span {
let key = min_key
.checked_add(i64::try_from(bucket).expect("bucket fits in i64"))
.expect("dense-cycle key span was prevalidated");
let left_span = left_witness.offset_count_for_key(key);
let right_span = right_witness.offset_count_for_key(key);
match (left_span, right_span) {
(Some((_, left_count)), Some((right_start, right_count))) => {
for _ in 0..left_count {
let mut right_pos = right_start;
for _ in 0..right_count {
out.push(Scalar::Float64(source[right_pos] as f64));
right_pos += right_witness.period;
}
}
}
(Some((_, left_count)), None) => {
out.resize(out.len() + left_count, Scalar::Null(NullKind::NaN));
}
(None, Some((mut right_pos, right_count))) => {
for _ in 0..right_count {
out.push(Scalar::Float64(source[right_pos] as f64));
right_pos += right_witness.period;
}
}
(None, None) => {}
}
}
debug_assert_eq!(out.len(), *total_len);
out
})
.as_slice(),
Self::LazyNullableDenseCycleLeftI64AsFloat64 {
source,
left_witness,
right_witness,
min_key,
span,
total_len,
values,
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for bucket in 0..*span {
let key = min_key
.checked_add(i64::try_from(bucket).expect("bucket fits in i64"))
.expect("dense-cycle key span was prevalidated");
let left_span = left_witness.offset_count_for_key(key);
let right_span = right_witness.offset_count_for_key(key);
match (left_span, right_span) {
(Some((mut left_pos, left_count)), Some((_, right_count))) => {
for _ in 0..left_count {
out.resize(
out.len() + right_count,
Scalar::Float64(source[left_pos] as f64),
);
left_pos += left_witness.period;
}
}
(Some((mut left_pos, left_count)), None) => {
for _ in 0..left_count {
out.push(Scalar::Float64(source[left_pos] as f64));
left_pos += left_witness.period;
}
}
(None, Some((_, right_count))) => {
out.resize(out.len() + right_count, Scalar::Null(NullKind::NaN));
}
(None, None) => {}
}
}
debug_assert_eq!(out.len(), *total_len);
out
})
.as_slice(),
Self::LazyDenseCycleProbeRepeatInt64 {
source,
probe_witness,
build_witness,
total_len,
values,
..
} => values
.get_or_init(|| {
Self::expand_dense_cycle_probe_repeat_i64(
source,
*probe_witness,
*build_witness,
*total_len,
)
.into_iter()
.map(Scalar::Int64)
.collect()
})
.as_slice(),
Self::LazyLeftJoinDenseCycleLeftInt64 {
source,
left_witness,
right_witness,
total_len,
values,
..
} => values
.get_or_init(|| {
Self::expand_left_join_dense_cycle_left_i64(
source,
*left_witness,
*right_witness,
*total_len,
)
.into_iter()
.map(Scalar::Int64)
.collect()
})
.as_slice(),
Self::LazyNullableDenseCycleProbeBuildInt64 {
source,
probe_witness,
build_witness,
total_len,
values,
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for probe_pos in 0..probe_witness.len {
let key = Self::dense_cycle_key_at(*probe_witness, probe_pos);
if let Some((mut build_pos, count)) =
build_witness.offset_count_for_key(key)
{
for _ in 0..count {
out.push(Scalar::Int64(source[build_pos]));
build_pos += build_witness.period;
}
} else {
out.push(Scalar::Null(NullKind::Null));
}
}
debug_assert_eq!(out.len(), *total_len);
out
})
.as_slice(),
Self::LazyLeftJoinDenseCycleRightInt64 {
source,
left_witness,
right_witness,
total_len,
values,
..
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for left_pos in 0..left_witness.len {
let key = Self::dense_cycle_key_at(*left_witness, left_pos);
if let Some((mut right_pos, right_count)) =
right_witness.offset_count_for_key(key)
{
for _ in 0..right_count {
out.push(Scalar::Int64(source[right_pos]));
right_pos += right_witness.period;
}
} else {
out.push(Scalar::Null(NullKind::Null));
}
}
debug_assert_eq!(out.len(), *total_len);
out
})
.as_slice(),
Self::LazyNullableRepeatPositionsI64AsFloat64 {
source,
run_positions,
run_valid,
run_lens,
total_len,
values,
} => values
.get_or_init(|| {
let mut out = Vec::with_capacity(*total_len);
for ((&source_pos, &valid), &run_len) in run_positions
.iter()
.zip(run_valid.iter())
.zip(run_lens.iter())
{
if valid {
out.resize(
out.len() + run_len,
Scalar::Float64(source[source_pos] as f64),
);
} else {
out.resize(out.len() + run_len, Scalar::Null(NullKind::NaN));
}
}
out
})
.as_slice(),
Self::LazyUtf8Slice {
bytes,
offsets,
start,
len,
values,
} => values
.get_or_init(|| {
(0..*len)
.map(|i| {
let lo = offsets[start + i];
let hi = offsets[start + i + 1];
Scalar::Utf8(
std::str::from_utf8(&bytes[lo..hi])
.expect("contiguous utf8 buffer is valid by construction")
.to_owned(),
)
})
.collect()
})
.as_slice(),
}
}
fn len(&self) -> usize {
match self {
Self::Eager(values) => values.len(),
Self::LazyAllValidInt64 { data, .. } => data.len(),
Self::LazyAllValidInt64Vec { data, .. } => data.len(),
Self::LazyAllValidInt64Chunks { len, .. } => *len,
Self::LazyAllValidDatetime64 { data, .. } => data.len(),
Self::LazyAllValidDatetime64Vec { data, .. } => data.len(),
Self::LazyAllValidTimedelta64Vec { data, .. } => data.len(),
Self::LazyAllValidPeriodVec { data, .. } => data.len(),
Self::LazyNullableDatetime64 { data, .. } => data.len(),
Self::LazyNullableTimedelta64 { data, .. } => data.len(),
Self::LazyNullablePeriod { data, .. } => data.len(),
Self::LazyAllValidFloat64 { data, .. } => data.len(),
Self::LazyAllValidFloat64Vec { data, .. } => data.len(),
Self::LazyAllValidFloat64Chunks { len, .. } => *len,
Self::LazyAllValidFloat64Slice { len, .. } => *len,
Self::LazyAllValidFloat64Dot { len, .. } => *len,
Self::LazyAllValidFloat64PairwiseStatMatrixColumn { plan, .. } => plan.column_len(),
Self::LazyAllValidFloat64TransposeRow { plan, .. } => plan.column_len(),
Self::LazyCombineFirstFloat64 { len, .. } => *len,
Self::LazyStridedFloat64 { len, .. } => *len,
Self::LazyNullableFloat64 { data, .. } => data.len(),
Self::LazyAllValidBool { data, .. } => data.len(),
Self::LazyShiftedBool { len, .. } => *len,
Self::LazyContiguousUtf8 { offsets, .. } => offsets.len() - 1,
Self::LazyLowerHexSequenceUtf8 { len, .. } => *len,
Self::LazyNullableUtf8 { offsets, .. } => offsets.len() - 1,
Self::LazyGatherUtf8 { positions, .. } => positions.len(),
Self::LazyNullableUtf8Range {
null_prefix,
source_len,
null_suffix,
..
} => null_prefix + source_len + null_suffix,
Self::LazyNullableInt64 { data, .. } => data.len(),
Self::LazyNullableBool { data, .. } => data.len(),
Self::LazyRepeatRunsInt64 { total_len, .. } => *total_len,
Self::LazyRepeatValuesInt64 { total_len, .. } => *total_len,
Self::LazyRepeatedSlicesInt64 { total_len, .. } => *total_len,
Self::LazyRepeatValuesFloat64 { total_len, .. } => *total_len,
Self::LazyRepeatedSlicesFloat64 { total_len, .. } => *total_len,
Self::LazyNullableRepeatedSlicesInt64 { total_len, .. } => *total_len,
Self::LazyNullableRepeatedSlicesFloat64 { total_len, .. } => *total_len,
Self::LazyNullableRepeatValuesFloat64 { total_len, .. } => *total_len,
Self::LazyNullableRepeatedPositionsI64AsFloat64 { total_len, .. } => *total_len,
Self::LazyNullableDenseCycleRightI64AsFloat64 { total_len, .. } => *total_len,
Self::LazyNullableDenseCycleLeftI64AsFloat64 { total_len, .. } => *total_len,
Self::LazyDenseCycleProbeRepeatInt64 { total_len, .. } => *total_len,
Self::LazyNullableDenseCycleProbeBuildInt64 { total_len, .. } => *total_len,
Self::LazyLeftJoinDenseCycleLeftInt64 { total_len, .. } => *total_len,
Self::LazyLeftJoinDenseCycleRightInt64 { total_len, .. } => *total_len,
Self::LazyNullableRepeatPositionsI64AsFloat64 { total_len, .. } => *total_len,
Self::LazyUtf8Slice { len, .. } => *len,
}
}
fn is_empty(&self) -> bool {
self.len() == 0
}
}
fn contiguous_utf8_offsets_are_strictly_increasing(bytes: &[u8], offsets: &[usize]) -> bool {
let Some(n) = offsets.len().checked_sub(1) else {
return false;
};
if n < 2 {
return true;
}
let mut previous = &bytes[offsets[0]..offsets[1]];
for pos in 1..n {
let current = &bytes[offsets[pos]..offsets[pos + 1]];
if previous >= current {
return false;
}
previous = current;
}
true
}
fn contiguous_utf8_fixed_width(offsets: &[usize]) -> Option<usize> {
let n = offsets.len().checked_sub(1)?;
if n == 0 {
return Some(0);
}
let width = offsets[1].checked_sub(offsets[0])?;
for pos in 1..n {
if offsets[pos + 1].checked_sub(offsets[pos])? != width {
return None;
}
}
Some(width)
}
fn lower_hex_value(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
_ => None,
}
}
fn parse_fixed_width_lower_hex(bytes: &[u8]) -> Option<u64> {
let mut value = 0_u64;
for &byte in bytes {
value = value.checked_mul(16)?;
value = value.checked_add(u64::from(lower_hex_value(byte)?))?;
}
Some(value)
}
fn push_fixed_width_lower_hex(bytes: &mut Vec<u8>, value: u64, width: usize) {
debug_assert!(width <= 16, "u64 lower-hex width cannot exceed 16");
for shift in (0..width).rev() {
let nibble = ((value >> (shift * 4)) & 0x0f) as u8;
bytes.push(if nibble < 10 {
b'0' + nibble
} else {
b'a' + (nibble - 10)
});
}
}
/// Append the plain decimal spelling of `v` (sign + digits, no leading zeros,
/// `0` for zero) straight into a byte buffer — bit-identical to `write!(buf,
/// "{v}")` but without routing through `io::Write::write_fmt`'s Formatter +
/// error-path dispatch (the hot tax in Int64->Utf8 astype). Two-digit lookup
/// table halves the divide/mul count vs a per-digit loop. `unsigned_abs`
/// handles `i64::MIN` without overflow.
#[inline]
fn push_i64_decimal(buf: &mut Vec<u8>, v: i64) {
const LUT: &[u8; 200] = b"0001020304050607080910111213141516171819\
20212223242526272829303132333435363738394041424344454647484950515253545556575859\
60616263646566676869707172737475767778798081828384858687888990919293949596979899";
let mut n: u64 = if v < 0 {
buf.push(b'-');
v.unsigned_abs()
} else {
v as u64
};
// Emit digit PAIRS from least-significant into a 20-byte temp, then copy the
// written suffix in order (max u64 is 20 digits).
let mut tmp = [0u8; 20];
let mut i = 20usize;
while n >= 100 {
let r = (n % 100) as usize * 2;
n /= 100;
i -= 2;
tmp[i] = LUT[r];
tmp[i + 1] = LUT[r + 1];
}
if n >= 10 {
let r = n as usize * 2;
i -= 2;
tmp[i] = LUT[r];
tmp[i + 1] = LUT[r + 1];
} else {
i -= 1;
tmp[i] = b'0' + n as u8;
}
buf.extend_from_slice(&tmp[i..]);
}
fn increment_fixed_width_lower_hex(digits: &mut [u8]) {
for byte in digits.iter_mut().rev() {
match *byte {
b'0'..=b'8' | b'a'..=b'e' => {
*byte += 1;
return;
}
b'9' => {
*byte = b'a';
return;
}
b'f' => *byte = b'0',
_ => return,
}
}
}
fn contiguous_utf8_lower_hex_sequence(
bytes: &[u8],
offsets: &[usize],
width: usize,
) -> Option<Utf8LowerHexSequence> {
let n = offsets.len().checked_sub(1)?;
if n == 0 || width == 0 || width > 64 {
return None;
}
let first = &bytes[offsets[0]..offsets[1]];
let mut hex_start = first.len();
while hex_start > 0 && lower_hex_value(first[hex_start - 1]).is_some() {
hex_start -= 1;
}
let hex_width = first.len().checked_sub(hex_start)?;
if hex_width == 0 || hex_width == first.len() {
return None;
}
let prefix = &first[..hex_start];
let start = parse_fixed_width_lower_hex(&first[hex_start..])?;
for row in 1..n {
let span = &bytes[offsets[row]..offsets[row + 1]];
if span.len() != width || &span[..hex_start] != prefix {
return None;
}
let value = parse_fixed_width_lower_hex(&span[hex_start..])?;
if value != start.checked_add(row as u64)? {
return None;
}
}
Some(Utf8LowerHexSequence {
prefix_len: hex_start,
hex_width,
start,
})
}
/// If `positions` is a non-empty contiguous ascending run
/// (`positions[i] == positions[0] + i`), return its start. Returns `None` for
/// an empty slice or the first out-of-sequence position — so a non-contiguous
/// take pays only until the first gap (typically O(1)).
/// (br-frankenpandas-jbyuc.1.1.1)
fn contiguous_ascending_start(positions: &[usize]) -> Option<usize> {
let first = *positions.first()?;
for (i, &pos) in positions.iter().enumerate() {
if pos != first + i {
return None;
}
}
Some(first)
}
impl Clone for ScalarValues {
fn clone(&self) -> Self {
match self {
Self::Eager(values) => Self::Eager(values.clone()),
Self::LazyAllValidInt64 { data, .. } => {
Self::lazy_all_valid_int64_arc(Arc::clone(data))
}
Self::LazyAllValidInt64Vec { data, .. } => Self::LazyAllValidInt64Vec {
data: Arc::clone(data),
values: OnceLock::new(),
},
Self::LazyAllValidInt64Chunks {
chunks,
len,
dense_cycle,
..
} => {
let cloned = Self::lazy_all_valid_int64_chunks(Arc::clone(chunks), *len);
if let Self::LazyAllValidInt64Chunks {
dense_cycle: cloned_cycle,
..
} = &cloned
&& let Some(value) = dense_cycle.get().copied()
{
let _ = cloned_cycle.set(value);
}
cloned
}
Self::LazyAllValidDatetime64 { data, .. } => {
Self::lazy_all_valid_datetime64_arc(Arc::clone(data))
}
Self::LazyAllValidDatetime64Vec { data, .. } => Self::LazyAllValidDatetime64Vec {
data: Arc::clone(data),
values: OnceLock::new(),
},
Self::LazyAllValidTimedelta64Vec { data, .. } => Self::LazyAllValidTimedelta64Vec {
data: Arc::clone(data),
values: OnceLock::new(),
},
Self::LazyAllValidPeriodVec { data, freq, .. } => Self::LazyAllValidPeriodVec {
data: Arc::clone(data),
freq: *freq,
values: OnceLock::new(),
},
Self::LazyNullableDatetime64 { data, validity, .. } => {
Self::lazy_nullable_datetime64(data.clone(), validity.clone())
}
Self::LazyNullableTimedelta64 { data, validity, .. } => {
Self::lazy_nullable_timedelta64(data.clone(), validity.clone())
}
Self::LazyNullablePeriod {
data,
freq,
missing_freq,
validity,
..
} => Self::lazy_nullable_period(data.clone(), *freq, *missing_freq, validity.clone()),
Self::LazyAllValidFloat64 {
data, all_finite, ..
} => Self::lazy_all_valid_float64_arc_with_finite(
Arc::clone(data),
all_finite.get().copied(),
),
Self::LazyAllValidFloat64Vec {
data, all_finite, ..
} => Self::LazyAllValidFloat64Vec {
data: Arc::clone(data),
all_finite: Self::bool_once_lock(all_finite.get().copied()),
values: OnceLock::new(),
},
Self::LazyAllValidFloat64Chunks {
chunks,
len,
all_finite,
..
} => {
let cloned = Self::lazy_all_valid_float64_chunks(Arc::clone(chunks), *len);
if let Self::LazyAllValidFloat64Chunks {
all_finite: cloned_finite,
..
} = &cloned
&& let Some(value) = all_finite.get().copied()
{
let _ = cloned_finite.set(value);
}
cloned
}
Self::LazyAllValidFloat64Slice {
data,
start,
len,
all_finite,
..
} => Self::lazy_all_valid_float64_slice_with_finite(
Arc::clone(data),
*start,
*len,
all_finite.get().copied(),
),
Self::LazyAllValidFloat64Dot {
a_cols, b_col, len, ..
} => Self::lazy_all_valid_float64_dot(Arc::clone(a_cols), Arc::clone(b_col), *len),
Self::LazyAllValidFloat64PairwiseStatMatrixColumn { plan, col, .. } => {
Self::lazy_all_valid_float64_pairwise_stat_matrix_column(Arc::clone(plan), *col)
}
Self::LazyAllValidFloat64TransposeRow {
plan, source_row, ..
} => Self::lazy_all_valid_float64_transpose_row(Arc::clone(plan), *source_row),
Self::LazyCombineFirstFloat64 {
left,
right,
left_validity_words,
len,
..
} => Self::lazy_combine_first_float64(
Arc::clone(left),
Arc::clone(right),
Arc::clone(left_validity_words),
*len,
),
Self::LazyStridedFloat64 {
data,
start,
step,
len,
..
} => Self::lazy_strided_float64(Arc::clone(data), *start, *step, *len),
Self::LazyNullableFloat64 { data, validity, .. } => {
Self::lazy_nullable_float64(data.clone(), validity.clone())
}
Self::LazyAllValidBool { data, .. } => Self::lazy_all_valid_bool_arc(Arc::clone(data)),
Self::LazyShiftedBool {
source,
periods,
fill,
len,
..
} => Self::lazy_shifted_bool(Arc::clone(source), *periods, *fill, *len),
Self::LazyContiguousUtf8 { bytes, offsets, .. } => {
Self::lazy_contiguous_utf8_arc(Arc::clone(bytes), Arc::clone(offsets))
}
Self::LazyLowerHexSequenceUtf8 {
prefix,
start,
len,
hex_width,
..
} => Self::LazyLowerHexSequenceUtf8 {
prefix: Arc::clone(prefix),
start: *start,
len: *len,
hex_width: *hex_width,
buffers: OnceLock::new(),
values: OnceLock::new(),
},
Self::LazyNullableUtf8 {
bytes,
offsets,
validity,
..
} => Self::LazyNullableUtf8 {
bytes: Arc::clone(bytes),
offsets: Arc::clone(offsets),
validity: validity.clone(),
values: OnceLock::new(),
},
Self::LazyGatherUtf8 {
source, positions, ..
} => Self::lazy_gather_utf8(Arc::clone(source), Arc::clone(positions)),
Self::LazyNullableUtf8Range {
source,
null_prefix,
source_start,
source_len,
null_suffix,
..
} => Self::lazy_nullable_utf8_range(
Arc::clone(source),
*null_prefix,
*source_start,
*source_len,
*null_suffix,
),
Self::LazyNullableInt64 { data, validity, .. } => {
Self::lazy_nullable_int64(data.clone(), validity.clone())
}
Self::LazyNullableBool { data, validity, .. } => {
Self::lazy_nullable_bool(data.clone(), validity.clone())
}
Self::LazyRepeatRunsInt64 {
runs, total_len, ..
} => Self::lazy_repeat_runs_int64(runs.clone(), *total_len),
Self::LazyRepeatValuesInt64 {
run_values,
run_lens,
total_len,
..
} => {
Self::lazy_repeat_values_int64(run_values.clone(), Arc::clone(run_lens), *total_len)
}
Self::LazyRepeatedSlicesInt64 {
data,
segments,
total_len,
..
} => Self::lazy_repeated_slices_int64_shared(
data.clone(),
Arc::clone(segments),
*total_len,
),
Self::LazyRepeatValuesFloat64 {
run_values,
run_lens,
total_len,
..
} => Self::lazy_repeat_values_float64(
run_values.clone(),
Arc::clone(run_lens),
*total_len,
),
Self::LazyRepeatedSlicesFloat64 {
data,
segments,
total_len,
..
} => Self::lazy_repeated_slices_float64_shared(
data.clone(),
Arc::clone(segments),
*total_len,
),
Self::LazyNullableRepeatedSlicesInt64 {
data,
segments,
total_len,
..
} => Self::lazy_nullable_repeated_slices_int64(
data.clone(),
Arc::clone(segments),
*total_len,
),
Self::LazyNullableRepeatedSlicesFloat64 {
data,
segments,
total_len,
..
} => Self::lazy_nullable_repeated_slices_float64(
data.clone(),
Arc::clone(segments),
*total_len,
),
Self::LazyNullableRepeatValuesFloat64 {
run_values,
run_valid,
run_lens,
total_len,
..
} => Self::lazy_nullable_repeat_values_float64(
run_values.clone(),
Arc::clone(run_valid),
Arc::clone(run_lens),
*total_len,
),
Self::LazyNullableRepeatedPositionsI64AsFloat64 {
source,
positions,
segments,
total_len,
..
} => Self::lazy_nullable_repeated_positions_i64_as_float64(
Arc::clone(source),
Arc::clone(positions),
Arc::clone(segments),
*total_len,
),
Self::LazyNullableDenseCycleRightI64AsFloat64 {
source,
left_witness,
right_witness,
min_key,
span,
total_len,
..
} => Self::lazy_nullable_dense_cycle_right_i64_as_float64(
Arc::clone(source),
*left_witness,
*right_witness,
*min_key,
*span,
*total_len,
),
Self::LazyNullableDenseCycleLeftI64AsFloat64 {
source,
left_witness,
right_witness,
min_key,
span,
total_len,
..
} => Self::lazy_nullable_dense_cycle_left_i64_as_float64(
Arc::clone(source),
*left_witness,
*right_witness,
*min_key,
*span,
*total_len,
),
Self::LazyDenseCycleProbeRepeatInt64 {
source,
probe_witness,
build_witness,
total_len,
..
} => Self::lazy_dense_cycle_probe_repeat_int64(
Arc::clone(source),
*probe_witness,
*build_witness,
*total_len,
),
Self::LazyNullableDenseCycleProbeBuildInt64 {
source,
probe_witness,
build_witness,
total_len,
..
} => Self::lazy_nullable_dense_cycle_probe_build_int64(
Arc::clone(source),
*probe_witness,
*build_witness,
*total_len,
),
Self::LazyLeftJoinDenseCycleLeftInt64 {
source,
left_witness,
right_witness,
total_len,
..
} => Self::lazy_left_join_dense_cycle_left_int64(
Arc::clone(source),
*left_witness,
*right_witness,
*total_len,
),
Self::LazyLeftJoinDenseCycleRightInt64 {
source,
left_witness,
right_witness,
total_len,
..
} => Self::lazy_left_join_dense_cycle_right_int64(
Arc::clone(source),
*left_witness,
*right_witness,
*total_len,
),
Self::LazyNullableRepeatPositionsI64AsFloat64 {
source,
run_positions,
run_valid,
run_lens,
total_len,
..
} => Self::lazy_nullable_repeat_positions_i64_as_float64(
Arc::clone(source),
Arc::clone(run_positions),
Arc::clone(run_valid),
Arc::clone(run_lens),
*total_len,
),
Self::LazyUtf8Slice {
bytes,
offsets,
start,
len,
..
} => Self::lazy_utf8_slice(Arc::clone(bytes), Arc::clone(offsets), *start, *len),
}
}
}
impl std::ops::Deref for ScalarValues {
type Target = [Scalar];
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl<'a> IntoIterator for &'a ScalarValues {
type Item = &'a Scalar;
type IntoIter = std::slice::Iter<'a, Scalar>;
fn into_iter(self) -> Self::IntoIter {
self.as_slice().iter()
}
}
impl PartialEq for ScalarValues {
fn eq(&self, other: &Self) -> bool {
self.as_slice() == other.as_slice()
}
}
impl std::fmt::Debug for ScalarValues {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.as_slice().fmt(f)
}
}
impl Serialize for ScalarValues {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.as_slice().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ScalarValues {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Vec::<Scalar>::deserialize(deserializer).map(|v| Self::Eager(Arc::from(v)))
}
}
#[derive(Serialize, Deserialize)]
pub struct Column {
dtype: DType,
values: ScalarValues,
validity: ValidityMask,
#[serde(skip)]
data: Option<ColumnData>,
}
impl Clone for Column {
fn clone(&self) -> Self {
let values = self
.clone_dense_values_from_cache()
.unwrap_or_else(|| self.values.clone());
// Preserve the Arc-backed typed `data` cache through the clone for a
// NULLABLE Int64 column. `clone_dense_values_from_cache` already rescues
// the ALL-VALID case (it converts Eager values to a lazy typed backing,
// so `as_i64_slice` stays available WITHOUT the cache — hence those clones
// keep `data: None`), but it bails for any column with nulls: a nullable
// Int64 column's `values` stay Eager and its `data` cache was dropped, so
// `as_i64_slice_with_validity` returned None on the clone. Since
// Series/DataFrame ops clone columns constantly, that silently degraded
// every dense fast path gated on it (groupby shift/dedup/value_counts/
// joins) to the generic Scalar path. Carrying the `Arc<[i64]>` (an O(1)
// refcount bump) restores typed access. Scoped to Int64 + still-Eager
// values: the all-valid and Float64 clone shapes are untouched (their
// tests assert `data: None`), and Float64's mixed NaN/Null missing —
// where a typed view would canonicalize `Null(Null)`->`Null(NaN)` — is
// deliberately excluded. `values`/`validity`/`dtype` are unchanged and the
// cache is a consistent view of `values` (`PartialEq` ignores `data`).
let data = match &self.data {
Some(d @ ColumnData::Int64(_))
if self.dtype == DType::Int64 && matches!(values, ScalarValues::Eager(_)) =>
{
Some(d.clone())
}
_ => None,
};
Self {
dtype: self.dtype,
values,
validity: self.validity.clone(),
data,
}
}
}
impl PartialEq for Column {
fn eq(&self, other: &Self) -> bool {
self.dtype == other.dtype && self.values == other.values && self.validity == other.validity
}
}
impl std::fmt::Debug for Column {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Column")
.field("dtype", &self.dtype)
.field("values", &self.values)
.field("validity", &self.validity)
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SparseColumn {
dtype: SparseDType,
len: usize,
indices: Vec<usize>,
values: Vec<Scalar>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArithmeticOp {
Add,
Sub,
Mul,
Div,
Mod,
Pow,
FloorDiv,
}
/// Element-wise comparison operations that produce `Bool`-typed columns.
///
/// Null propagation: any missing/NaN input produces a missing output.
/// This matches pandas nullable-integer semantics (`pd.NA` propagation).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComparisonOp {
Gt,
Lt,
Eq,
Ne,
Ge,
Le,
}
/// Largest `k` for which the typed `nkeep` uses a bounded top-`k` linear scan.
/// For small `k` (the dominant case) this is O(n) with a tiny working set and a
/// cheap threshold reject — far better than a full O(n·log n) sort or a
/// `select_nth` that reorders the whole 5M array. Larger `k` falls back to the
/// generic sort.
const NKEEP_BOUNDED_SCAN_MAX_K: usize = 4096;
/// Typed `keep="first"` top-`k` over an all-valid `i64` slice: one sequential
/// pass maintaining the current `k` best in a best-first sorted buffer (binary
/// insert; most elements rejected by the `worst` threshold). Comparator matches
/// `compare_scalars_na_last(ascending)` then position-ascending, so the result
/// is byte-identical to the first `k` of `nkeep_impl`'s full sort.
fn nkeep_typed_i64(data: &[i64], k: usize, ascending: bool) -> Vec<i64> {
use std::cmp::Ordering;
let cmp = |a: (i64, u32), b: (i64, u32)| -> Ordering {
let ord = a.0.cmp(&b.0);
let ord = if ascending { ord } else { ord.reverse() };
ord.then(a.1.cmp(&b.1))
};
let mut top: Vec<(i64, u32)> = Vec::with_capacity(k);
for (i, &v) in data.iter().enumerate() {
let item = (v, i as u32);
if top.len() < k {
let pos = top.partition_point(|&x| cmp(x, item) == Ordering::Less);
top.insert(pos, item);
} else if cmp(item, top[k - 1]) == Ordering::Less {
let pos = top.partition_point(|&x| cmp(x, item) == Ordering::Less);
top.insert(pos, item);
top.pop();
}
}
top.iter().map(|&(v, _)| v).collect()
}
/// Float64 analogue. `as_f64_slice` is NaN-free, so `partial_cmp` never returns
/// `None` — matching `compare_scalars_na_last`'s `partial_cmp` (which treats
/// -0.0 == +0.0, deferring to the position tie-break).
fn nkeep_typed_f64(data: &[f64], k: usize, ascending: bool) -> Vec<f64> {
use std::cmp::Ordering;
let cmp = |a: (f64, u32), b: (f64, u32)| -> Ordering {
let ord = a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal);
let ord = if ascending { ord } else { ord.reverse() };
ord.then(a.1.cmp(&b.1))
};
let mut top: Vec<(f64, u32)> = Vec::with_capacity(k);
for (i, &v) in data.iter().enumerate() {
let item = (v, i as u32);
if top.len() < k {
let pos = top.partition_point(|&x| cmp(x, item) == Ordering::Less);
top.insert(pos, item);
} else if cmp(item, top[k - 1]) == Ordering::Less {
let pos = top.partition_point(|&x| cmp(x, item) == Ordering::Less);
top.insert(pos, item);
top.pop();
}
}
top.iter().map(|&(v, _)| v).collect()
}
/// Nullable Int64 analogue of [`nkeep_typed_i64`]: bounded top-`k` over the
/// PRESENT (validity-set) subset of a nullable i64 buffer, skipping missing
/// slots (Int64 missingness is the validity bit alone — no NaN sentinel). The
/// comparator (value asc/desc then position ascending) matches the stable
/// `compare_scalars_na_last(ascending)`, which sorts every present value ahead
/// of every missing one; so the returned present top-`k` is byte-identical to
/// the first `k` of `sort_values(ascending)` WHEN `k` present values exist.
/// Returns fewer than `k` values only if fewer than `k` present slots exist —
/// the caller uses that to fall back to the generic na-last sort (whose result
/// then carries the missing tail).
fn nkeep_typed_i64_nullable(
data: &[i64],
validity: &ValidityMask,
k: usize,
ascending: bool,
) -> Vec<i64> {
use std::cmp::Ordering;
let cmp = |a: (i64, u32), b: (i64, u32)| -> Ordering {
let ord = a.0.cmp(&b.0);
let ord = if ascending { ord } else { ord.reverse() };
ord.then(a.1.cmp(&b.1))
};
let mut top: Vec<(i64, u32)> = Vec::with_capacity(k);
for (i, &v) in data.iter().enumerate() {
if !validity.get(i) {
continue;
}
let item = (v, i as u32);
if top.len() < k {
let pos = top.partition_point(|&x| cmp(x, item) == Ordering::Less);
top.insert(pos, item);
} else if cmp(item, top[k - 1]) == Ordering::Less {
let pos = top.partition_point(|&x| cmp(x, item) == Ordering::Less);
top.insert(pos, item);
top.pop();
}
}
top.iter().map(|&(v, _)| v).collect()
}
/// Nullable/NaN Float64 analogue of [`nkeep_typed_f64`]: bounded top-`k` over the
/// PRESENT subset, where "present" is validity-set AND non-NaN — a valid-bit NaN
/// is missing per `Scalar::is_missing`, so it joins the na-last group exactly as
/// `compare_scalars_na_last` treats it. Present values are non-NaN, so
/// `partial_cmp` is total, matching the na-last comparator among present values.
/// Same short-return contract as [`nkeep_typed_i64_nullable`].
fn nkeep_typed_f64_nullable(
data: &[f64],
validity: &ValidityMask,
k: usize,
ascending: bool,
) -> Vec<f64> {
use std::cmp::Ordering;
let cmp = |a: (f64, u32), b: (f64, u32)| -> Ordering {
let ord = a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal);
let ord = if ascending { ord } else { ord.reverse() };
ord.then(a.1.cmp(&b.1))
};
let mut top: Vec<(f64, u32)> = Vec::with_capacity(k);
for (i, &v) in data.iter().enumerate() {
if !validity.get(i) || v.is_nan() {
continue;
}
let item = (v, i as u32);
if top.len() < k {
let pos = top.partition_point(|&x| cmp(x, item) == Ordering::Less);
top.insert(pos, item);
} else if cmp(item, top[k - 1]) == Ordering::Less {
let pos = top.partition_point(|&x| cmp(x, item) == Ordering::Less);
top.insert(pos, item);
top.pop();
}
}
top.iter().map(|&(v, _)| v).collect()
}
/// Assign `rank` values over the PRESENT prefix of a na-last permutation of a
/// typed nullable column. `perm` is `[present-sorted…, missing…]` (as produced
/// by [`Column::typed_radix_perm`]); `perm[..present_count]` are the present
/// original indices in value-then-original-index order — bit-identical to the
/// generic path's `non_missing.sort_by(compare_scalars_na_last)`. Tie groups are
/// detected by typed `==` over `data` (present Float64 are non-NaN ⇒ `==` matches
/// `partial_cmp` `Equal`; Int64 `==` is exact). Returns the rank buffer (missing
/// slots left `0.0`, marked invalid in the returned mask) — a Float64 column
/// built from it with `from_f64_values_with_validity` materializes each missing
/// slot as `Null(NullKind::NaN)`, exactly like the generic path's
/// `Scalar::Null(NullKind::NaN)`; present ranks are finite, so they stay
/// `Float64(rank)`.
fn nullable_rank_values<T: PartialEq>(
data: &[T],
perm: &[usize],
present_count: usize,
len: usize,
method: &str,
) -> (Vec<f64>, ValidityMask) {
let mut ranks = vec![0.0_f64; len];
let mut validity = ValidityMask::all_valid(len);
for &orig in &perm[present_count..] {
validity.set(orig, false);
}
let mut cursor = 0usize;
let mut dense_rank = 0.0_f64;
while cursor < present_count {
let mut end = cursor + 1;
while end < present_count && data[perm[end]] == data[perm[cursor]] {
end += 1;
}
let start_rank = cursor as f64 + 1.0;
let end_rank = end as f64;
dense_rank += 1.0;
#[allow(clippy::needless_range_loop)] // group_idx is also the "first" rank
for group_idx in cursor..end {
let original = perm[group_idx];
ranks[original] = match method {
"average" => (start_rank + end_rank) / 2.0,
"min" => start_rank,
"max" => end_rank,
"first" => group_idx as f64 + 1.0,
"dense" => dense_rank,
_ => unreachable!(),
};
}
cursor = end;
}
(ranks, validity)
}
/// Typed nullable cumulative extrema (cummax/cummin) over an f64 slice + validity,
/// reproducing `nancummax`/`nancummin` WITHOUT materializing the `Vec<Scalar>`.
/// A slot is present iff validity-set AND non-NaN (a valid-bit NaN is missing per
/// `Scalar::is_missing`, exactly `nancummax`'s `Ok(x) if !x.is_nan()` gate): a
/// present slot advances `running` (max/min) and emits it; a missing slot emits
/// `Null(NaN)` and leaves `running` unchanged. Output is Float64 with the missing
/// slots invalid — byte-identical to the generic path.
fn cum_extrema_nullable_f64(
data: &[f64],
validity: &ValidityMask,
is_max: bool,
) -> (Vec<f64>, ValidityMask) {
let n = data.len();
let mut out = vec![0.0_f64; n];
let mut out_valid = ValidityMask::all_valid(n);
let mut running: Option<f64> = None;
for i in 0..n {
let x = data[i];
if validity.get(i) && !x.is_nan() {
let nv = match running {
Some(p) => {
if is_max {
p.max(x)
} else {
p.min(x)
}
}
None => x,
};
running = Some(nv);
out[i] = nv;
} else {
out_valid.set(i, false);
}
}
(out, out_valid)
}
/// Int64 sibling of [`cum_extrema_nullable_f64`]: present iff validity-set (Int64
/// has no NaN sentinel), running folds `data[i] as f64` (matching `nancummax`'s
/// `to_f64()` on `Int64(v)`), output Float64 (as the all-valid Int64 arm already
/// emits) with missing slots invalid.
fn cum_extrema_nullable_i64(
data: &[i64],
validity: &ValidityMask,
is_max: bool,
) -> (Vec<f64>, ValidityMask) {
let n = data.len();
let mut out = vec![0.0_f64; n];
let mut out_valid = ValidityMask::all_valid(n);
let mut running: Option<f64> = None;
for i in 0..n {
if validity.get(i) {
let x = data[i] as f64;
let nv = match running {
Some(p) => {
if is_max {
p.max(x)
} else {
p.min(x)
}
}
None => x,
};
running = Some(nv);
out[i] = nv;
} else {
out_valid.set(i, false);
}
}
(out, out_valid)
}
/// Typed nullable cumulative accumulator (cumsum/cumprod) over an f64 slice +
/// validity, reproducing `nancumsum`/`nancumprod` WITHOUT materializing the
/// `Vec<Scalar>`. `running` is SEEDED (0.0 for sum, 1.0 for product) — not the
/// first value — and a present slot (validity-set AND non-NaN, exactly the
/// `Ok(x) if !x.is_nan()` gate) folds it in (`+=`/`*=`) and emits `running`; a
/// missing slot emits `Null(NaN)` and leaves `running` unchanged. Output Float64
/// with missing slots invalid — byte-identical to the generic path.
fn cum_accum_nullable_f64(
data: &[f64],
validity: &ValidityMask,
seed: f64,
is_prod: bool,
) -> (Vec<f64>, ValidityMask) {
let n = data.len();
let mut out = vec![0.0_f64; n];
let mut out_valid = ValidityMask::all_valid(n);
let mut running = seed;
for i in 0..n {
let x = data[i];
if validity.get(i) && !x.is_nan() {
if is_prod {
running *= x;
} else {
running += x;
}
out[i] = running;
} else {
out_valid.set(i, false);
}
}
(out, out_valid)
}
/// Int64 sibling of [`cum_accum_nullable_f64`]: present iff validity-set, folds
/// `data[i] as f64` (matching nancumsum/nancumprod's `to_f64` on `Int64(v)`).
fn cum_accum_nullable_i64(
data: &[i64],
validity: &ValidityMask,
seed: f64,
is_prod: bool,
) -> (Vec<f64>, ValidityMask) {
let n = data.len();
let mut out = vec![0.0_f64; n];
let mut out_valid = ValidityMask::all_valid(n);
let mut running = seed;
for i in 0..n {
if validity.get(i) {
let x = data[i] as f64;
if is_prod {
running *= x;
} else {
running += x;
}
out[i] = running;
} else {
out_valid.set(i, false);
}
}
(out, out_valid)
}
/// Typed nan-argmin/argmax over an f64 slice (+ optional validity), reproducing
/// `nanargmin`/`nanargmax` WITHOUT materializing the `Vec<Scalar>`. A slot is
/// present iff (validity-set, if given) AND non-NaN — exactly `nanargmin`'s
/// `is_missing` + `to_f64` + `if x.is_nan() { continue }` gates. Tracks the extreme
/// by STRICT `<`/`>` so the FIRST original position wins on a tie, and the index is
/// the original 0..n position (the enumerate index of the contiguous slice), byte-
/// identical to the generic path. Empty / all-missing ⇒ `None`.
fn argextreme_nullable_f64(data: &[f64], validity: Option<&ValidityMask>, want_max: bool) -> Option<usize> {
let mut best: Option<(usize, f64)> = None;
for (i, &x) in data.iter().enumerate() {
let present = validity.map_or(true, |v| v.get(i)) && !x.is_nan();
if present {
let better = match best {
None => true,
Some((_, cur)) => {
if want_max {
x > cur
} else {
x < cur
}
}
};
if better {
best = Some((i, x));
}
}
}
best.map(|(i, _)| i)
}
/// Int64 sibling of [`argextreme_nullable_f64`]: present iff validity-set (Int64
/// has no NaN); comparison is on `v as f64` — EXACTLY nanargmin's `to_f64` compare
/// (same >2^53 precision behaviour), so bit-identical.
fn argextreme_nullable_i64(data: &[i64], validity: Option<&ValidityMask>, want_max: bool) -> Option<usize> {
let mut best: Option<(usize, f64)> = None;
for (i, &v) in data.iter().enumerate() {
if validity.map_or(true, |vm| vm.get(i)) {
let x = v as f64;
let better = match best {
None => true,
Some((_, cur)) => {
if want_max {
x > cur
} else {
x < cur
}
}
};
if better {
best = Some((i, x));
}
}
}
best.map(|(i, _)| i)
}
/// Typed nan-ptp (peak-to-peak = max − min over present values) over an f64 slice
/// (+ optional validity), reproducing `nanptp` WITHOUT materializing the
/// `Vec<Scalar>`. Present iff (validity-set) AND non-NaN (a NaN never updates
/// lo/hi via `<`/`>` and — like `nanptp`'s `is_missing` skip — must NOT mark `seen`,
/// else an all-NaN column would return `Float64(NaN)` instead of `Null(NaN)`).
/// All-missing ⇒ `Null(NaN)`; otherwise `Float64(hi − lo)`.
fn ptp_nullable_f64(data: &[f64], validity: Option<&ValidityMask>) -> Scalar {
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
let mut seen = false;
for (i, &x) in data.iter().enumerate() {
if validity.map_or(true, |v| v.get(i)) && !x.is_nan() {
seen = true;
if x < lo {
lo = x;
}
if x > hi {
hi = x;
}
}
}
if !seen {
Scalar::Null(NullKind::NaN)
} else {
Scalar::Float64(hi - lo)
}
}
/// Int64 sibling of [`ptp_nullable_f64`]: present iff validity-set; lo/hi fold
/// `v as f64` (matching nanptp's `to_f64`), output Float64.
fn ptp_nullable_i64(data: &[i64], validity: Option<&ValidityMask>) -> Scalar {
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
let mut seen = false;
for (i, &v) in data.iter().enumerate() {
if validity.map_or(true, |vm| vm.get(i)) {
let x = v as f64;
seen = true;
if x < lo {
lo = x;
}
if x > hi {
hi = x;
}
}
}
if !seen {
Scalar::Null(NullKind::NaN)
} else {
Scalar::Float64(hi - lo)
}
}
/// Two-pass moments over the PRESENT subset of an f64 slice (+ optional validity):
/// returns `(n, mean, sum_sq)` where `n` = present count, `mean = Σ/n`, and
/// `sum_sq = Σ(x − mean)²`. Present iff (validity-set) AND non-NaN — exactly
/// `collect_finite`'s drop-missing. Same values, same order as
/// `collect_finite(..).iter().sum()`, so the f64 accumulation is byte-identical to
/// nanvar/nansem. `n == 0` ⇒ `(0, 0.0, 0.0)` (caller returns Null(NaN)).
fn present_moments_f64(data: &[f64], validity: Option<&ValidityMask>) -> (usize, f64, f64) {
let mut sum = 0.0_f64;
let mut n = 0usize;
for (i, &x) in data.iter().enumerate() {
if validity.map_or(true, |v| v.get(i)) && !x.is_nan() {
sum += x;
n += 1;
}
}
if n == 0 {
return (0, 0.0, 0.0);
}
let mean = sum / n as f64;
let mut sum_sq = 0.0_f64;
for (i, &x) in data.iter().enumerate() {
if validity.map_or(true, |v| v.get(i)) && !x.is_nan() {
sum_sq += (x - mean).powi(2);
}
}
(n, mean, sum_sq)
}
/// Central moments over the PRESENT subset of an f64 slice for skew/kurt:
/// `(n, m2, m3, m4)` = present count and `Σ(x − mean)^{2,3,4}`, matching
/// nanskew/nankurt's `nums.iter().map(|x| (x-mean).powi(k)).sum()` (the k-sums are
/// independent left-folds, so accumulating all three in one pass over the same
/// present values in the same order is byte-identical). Present iff (validity-set)
/// AND non-NaN. `n == 0` ⇒ all-zero.
fn present_central_moments_f64(
data: &[f64],
validity: Option<&ValidityMask>,
) -> (usize, f64, f64, f64) {
let mut sum = 0.0_f64;
let mut n = 0usize;
for (i, &x) in data.iter().enumerate() {
if validity.map_or(true, |v| v.get(i)) && !x.is_nan() {
sum += x;
n += 1;
}
}
if n == 0 {
return (0, 0.0, 0.0, 0.0);
}
let mean = sum / n as f64;
let (mut m2, mut m3, mut m4) = (0.0_f64, 0.0_f64, 0.0_f64);
for (i, &x) in data.iter().enumerate() {
if validity.map_or(true, |v| v.get(i)) && !x.is_nan() {
let d = x - mean;
m2 += d.powi(2);
m3 += d.powi(3);
m4 += d.powi(4);
}
}
(n, m2, m3, m4)
}
/// Int64 sibling of [`present_central_moments_f64`]: present iff validity-set,
/// folds `v as f64` (matching nanskew's `to_f64`).
fn present_central_moments_i64(
data: &[i64],
validity: Option<&ValidityMask>,
) -> (usize, f64, f64, f64) {
let mut sum = 0.0_f64;
let mut n = 0usize;
for (i, &v) in data.iter().enumerate() {
if validity.map_or(true, |vm| vm.get(i)) {
sum += v as f64;
n += 1;
}
}
if n == 0 {
return (0, 0.0, 0.0, 0.0);
}
let mean = sum / n as f64;
let (mut m2, mut m3, mut m4) = (0.0_f64, 0.0_f64, 0.0_f64);
for (i, &v) in data.iter().enumerate() {
if validity.map_or(true, |vm| vm.get(i)) {
let d = v as f64 - mean;
m2 += d.powi(2);
m3 += d.powi(3);
m4 += d.powi(4);
}
}
(n, m2, m3, m4)
}
/// Int64 sibling of [`present_moments_f64`]: present iff validity-set; folds
/// `v as f64` (matching nanvar's `to_f64`), so bit-identical.
fn present_moments_i64(data: &[i64], validity: Option<&ValidityMask>) -> (usize, f64, f64) {
let mut sum = 0.0_f64;
let mut n = 0usize;
for (i, &v) in data.iter().enumerate() {
if validity.map_or(true, |vm| vm.get(i)) {
sum += v as f64;
n += 1;
}
}
if n == 0 {
return (0, 0.0, 0.0);
}
let mean = sum / n as f64;
let mut sum_sq = 0.0_f64;
for (i, &v) in data.iter().enumerate() {
if validity.map_or(true, |vm| vm.get(i)) {
sum_sq += (v as f64 - mean).powi(2);
}
}
(n, mean, sum_sq)
}
/// Borrowed typed view of a numeric column (all-valid OR nullable Float64/Int64)
/// for the pairwise cov/corr fast paths. `get_finite(i)` returns the value at `i`
/// iff it is PRESENT and finite — exactly the `to_f64()` `Ok(v) if v.is_finite()`
/// gate cov/corr apply per Scalar (Float64: validity-set AND finite, i.e. not
/// NaN/±inf; Int64: validity-set, `v as f64` always finite). Avoids materializing
/// the `Vec<Scalar>` of BOTH columns.
enum TypedNumericValues<'a> {
F64(&'a [f64], &'a ValidityMask),
I64(&'a [i64], &'a ValidityMask),
}
impl TypedNumericValues<'_> {
#[inline]
fn len(&self) -> usize {
match self {
Self::F64(d, _) => d.len(),
Self::I64(d, _) => d.len(),
}
}
#[inline]
fn get_finite(&self, i: usize) -> Option<f64> {
match self {
Self::F64(d, v) => {
let x = d[i];
if v.get(i) && x.is_finite() {
Some(x)
} else {
None
}
}
Self::I64(d, v) => {
if v.get(i) {
Some(d[i] as f64)
} else {
None
}
}
}
}
/// Present-value view (== `!Scalar::is_missing() && to_f64().is_ok()` for a
/// Float64/Int64 backing): validity-set AND non-NaN for Float64 (KEEPING ±inf —
/// `is_missing` only drops NaN/null, and `to_f64` accepts ±inf), validity-set for
/// Int64. Unlike `get_finite`, this does NOT drop ±inf, matching reductions
/// (weighted_mean) whose reference filters on `is_missing` + `to_f64`, not
/// `is_finite`.
#[inline]
fn get_present(&self, i: usize) -> Option<f64> {
match self {
Self::F64(d, v) => {
let x = d[i];
if v.get(i) && !x.is_nan() {
Some(x)
} else {
None
}
}
Self::I64(d, v) => {
if v.get(i) {
Some(d[i] as f64)
} else {
None
}
}
}
}
}
fn nkeep_impl(col: &Column, n: usize, keep: &str, ascending: bool) -> Result<Column, ColumnError> {
if !matches!(keep, "first" | "last" | "all") {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: keep.to_string(),
dtype: col.dtype(),
}));
}
// Typed partial-selection fast path for keep="first" with 1 ≤ k < len: a
// typed `select_nth_unstable` over the raw slice is O(n) vs the generic
// full sort's O(n·log n) + per-comparison Scalar dispatch. Bit-identical
// (same comparator + position tie-break, returning the first k in order).
if keep == "first" && (1..=NKEEP_BOUNDED_SCAN_MAX_K).contains(&n) {
if let Some(data) = col.as_i64_slice() {
if n < data.len() {
return Ok(Column::from_i64_values_owned(nkeep_typed_i64(
data, n, ascending,
)));
}
} else if let Some(data) = col.as_f64_slice()
&& n < data.len()
{
return Ok(Column::from_f64_values(nkeep_typed_f64(data, n, ascending)));
}
}
// Annotate each value with its original position, then sort
// (position is the secondary key; Rust's sort_by is stable, so
// "first" falls out for free on equal primary keys).
let mut indexed: Vec<(usize, &Scalar)> = col.values().iter().enumerate().collect();
indexed.sort_by(|a, b| {
let primary = compare_scalars_na_last(a.1, b.1, ascending);
match (primary, keep) {
// "last" policy: on ties, prefer later positions.
(std::cmp::Ordering::Equal, "last") => b.0.cmp(&a.0),
(std::cmp::Ordering::Equal, _) => a.0.cmp(&b.0),
_ => primary,
}
});
let take = n.min(indexed.len());
let mut end = take;
if keep == "all" && take > 0 && take < indexed.len() {
let boundary = indexed[take - 1].1;
while end < indexed.len() {
let same = compare_scalars_na_last(indexed[end].1, boundary, ascending).is_eq();
if !same {
break;
}
end += 1;
}
}
let values: Vec<Scalar> = indexed[..end].iter().map(|(_, v)| (*v).clone()).collect();
Column::new(col.dtype(), values)
}
fn is_monotonic_in_direction(values: &[Scalar], increasing: bool) -> bool {
let mut prev: Option<&Scalar> = None;
for v in values {
if v.is_missing() {
continue;
}
if let Some(p) = prev {
let ord = compare_scalars_na_last(p, v, true);
// `p` should come before `v` in the requested direction. With
// ascending compare: Less/Equal → non-decreasing OK; Greater
// breaks. For decreasing we flip the expectation.
let ok = matches!(
(ord, increasing),
(std::cmp::Ordering::Less, true)
| (std::cmp::Ordering::Equal, _)
| (std::cmp::Ordering::Greater, false)
);
if !ok {
return false;
}
}
prev = Some(v);
}
true
}
fn compare_scalars_na_last(left: &Scalar, right: &Scalar, ascending: bool) -> std::cmp::Ordering {
use std::cmp::Ordering;
match (left.is_missing(), right.is_missing()) {
(true, true) => Ordering::Equal,
// Missing always sorts to the end, regardless of direction.
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => {
let ord = match (left, right) {
(Scalar::Int64(a), Scalar::Int64(b)) => a.cmp(b),
(Scalar::Float64(a), Scalar::Float64(b)) => {
a.partial_cmp(b).unwrap_or(Ordering::Equal)
}
(Scalar::Bool(a), Scalar::Bool(b)) => a.cmp(b),
(Scalar::Utf8(a), Scalar::Utf8(b)) => a.cmp(b),
(Scalar::Timedelta64(a), Scalar::Timedelta64(b)) => a.cmp(b),
// Datetime64/Period order by their i64 ns / ordinal (exact),
// mirroring the Timedelta64 arm. Without these, `to_f64` errors
// for these dtypes (below) so every value compared Equal — making
// sort_values/nlargest/nsmallest/mode on a Datetime64 (or Period)
// column a no-op that returned positional, not value, order.
(Scalar::Datetime64(a), Scalar::Datetime64(b)) => a.cmp(b),
(Scalar::Period(a), Scalar::Period(b)) => a.ordinal.cmp(&b.ordinal),
(a, b) => match (a.to_f64(), b.to_f64()) {
(Ok(af), Ok(bf)) => af.partial_cmp(&bf).unwrap_or(Ordering::Equal),
_ => Ordering::Equal,
},
};
if ascending { ord } else { ord.reverse() }
}
}
}
/// `keep=` policy for `duplicated`/`drop_duplicates`.
#[derive(Clone, Copy)]
enum DupPolicy {
First,
Last,
None,
}
/// Per-element duplicate flags over a contiguous slice of `Copy + Hash + Eq`
/// keys, using a fast (`FxHashSet`) hasher — the typed counterpart to the
/// `Scalar`-enum + SipHash path. Semantics are identical: `First` flags every
/// occurrence after the first; `Last` flags every occurrence before the last;
/// `None` flags every occurrence of any key that appears more than once.
fn duplicated_flags_typed<T>(keys: &[T], policy: DupPolicy) -> Vec<bool>
where
T: std::hash::Hash + Eq + Copy,
{
let n = keys.len();
let mut flags = vec![false; n];
match policy {
DupPolicy::First => {
let mut seen: FxHashSet<T> = FxHashSet::with_capacity_and_hasher(n, Default::default());
for (idx, &k) in keys.iter().enumerate() {
flags[idx] = !seen.insert(k);
}
}
DupPolicy::Last => {
let mut seen: FxHashSet<T> = FxHashSet::with_capacity_and_hasher(n, Default::default());
for (idx, &k) in keys.iter().enumerate().rev() {
flags[idx] = !seen.insert(k);
}
}
DupPolicy::None => {
let mut seen_once: FxHashSet<T> =
FxHashSet::with_capacity_and_hasher(n, Default::default());
let mut seen_multiple: FxHashSet<T> = FxHashSet::default();
for &k in keys {
if !seen_once.insert(k) {
seen_multiple.insert(k);
}
}
for (idx, &k) in keys.iter().enumerate() {
flags[idx] = seen_multiple.contains(&k);
}
}
}
flags
}
/// Largest direct-address table we will allocate for integer dedup (entries).
/// At 16M entries the `seen`/`count` table is ~16MB — L3-resident on a typical
/// server — and dedup becomes a hash-free O(n) scan. Beyond this the table
/// stops being cache-friendly and we fall back to the FxHash set.
const DUP_DIRECT_ADDRESS_CAP: u128 = 1 << 24;
/// Min and table size for a direct-address integer dedup, or `None` when the
/// value span is too wide (sparse) to be worth a dense table. We also require
/// the table to be at most ~16x the row count so a handful of widely-separated
/// values don't trigger a giant allocation.
fn i64_direct_address_range(data: &[i64]) -> Option<(i64, usize)> {
let mut min = data.first().copied()?;
let mut max = min;
for &v in &data[1..] {
if v < min {
min = v;
} else if v > max {
max = v;
}
}
let range = (max as i128 - min as i128 + 1) as u128;
if range <= DUP_DIRECT_ADDRESS_CAP && range <= (data.len() as u128).saturating_mul(16) {
Some((min, range as usize))
} else {
None
}
}
/// Count distinct values in an all-valid `i64` slice that is too wide for the
/// dense direct-address path, via a purpose-built open-addressing hash set
/// (linear probing, inline `i64` keys, ~0.5 load factor) over the raw slice —
/// no `Scalar` materialization and no `FxHashSet` SwissTable/control-byte
/// overhead (the "wide-i64 high-card khash floor" lever). `i64::MIN` is the
/// empty sentinel and is tracked separately so a real `i64::MIN` value still
/// counts. Fibonacci hashing (multiply by the golden-ratio odd constant) spreads
/// sequential/strided keys across the table.
///
/// This is the single-table implementation; [`count_distinct_i64_wide`]
/// dispatches to the radix-partitioned variant when a cheap sample witnesses
/// very-high cardinality (where this table exceeds the LLC and thrashes).
fn count_distinct_i64_singletable(data: &[i64]) -> i64 {
const EMPTY: i64 = i64::MIN;
const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15;
if data.is_empty() {
return 0;
}
// GROWABLE open-addressing + FIBONACCI hashing (wide open-addr vein fix). This
// is the LOW/MID-cardinality distinct-count path (the dispatcher routes truly
// high-card data to the radix variant), which is exactly where the old fixed
// cap ≈ 2·n was a huge SPARSE table — a cache miss per probe — and where the
// low-bit `& mask` hash clustered high-bit-only keys. Grow from small (double
// at load 0.7 ⇒ sizes to the distinct count) and Fibonacci `>> (64 - log2 cap)`
// (HIGH bits). Bit-identical count (table layout doesn't change membership).
// >= 2 so `shift = 64 - log2(cap)` <= 63.
let n = data.len();
let mut cap = 1024usize.min(n.saturating_add(n / 2).next_power_of_two()).max(2);
let mut shift = 64 - cap.trailing_zeros();
let mut keys = vec![EMPTY; cap];
let mut count = 0i64;
let mut has_sentinel = false;
let mut filled = 0usize;
for &v in data {
if v == EMPTY {
has_sentinel = true;
continue;
}
if filled * 10 >= cap * 7 {
let ncap = cap * 2;
let nshift = 64 - ncap.trailing_zeros();
let nmask = ncap - 1;
let mut nkeys = vec![EMPTY; ncap];
for p in 0..cap {
if keys[p] != EMPTY {
let mut q = ((keys[p] as u64).wrapping_mul(GOLDEN) >> nshift) as usize;
while nkeys[q] != EMPTY {
q = (q + 1) & nmask;
}
nkeys[q] = keys[p];
}
}
keys = nkeys;
cap = ncap;
shift = nshift;
}
let mask = cap - 1;
let mut idx = ((v as u64).wrapping_mul(GOLDEN) >> shift) as usize;
loop {
let k = keys[idx];
if k == EMPTY {
keys[idx] = v;
count += 1;
filled += 1;
break;
}
if k == v {
break;
}
idx = (idx + 1) & mask;
}
}
count + i64::from(has_sentinel)
}
/// Radix-partitioned distinct count for a WIDE, HIGH-cardinality `i64` slice.
///
/// The single-table [`count_distinct_i64_wide`] allocates a `2n`-slot probe
/// table (≈16·n bytes); once that exceeds the LLC, every insert on
/// high-cardinality data is a cache miss. This scatters the values into
/// `P = 256` partitions by the TOP hash bits, then counts each partition with a
/// small open-addressing table that stays L2-resident — a vectorized-hash /
/// radix-partition aggregation. Bit-identical to `count_distinct_i64_wide`: each
/// non-sentinel value maps to exactly ONE partition (a partition of the hash
/// space), so no value is split across partitions and the total distinct is the
/// sum of per-partition distincts; the `i64::MIN` sentinel is counted once,
/// globally. Order-independent, so partitioning cannot change the count.
fn count_distinct_i64_radix(data: &[i64]) -> i64 {
const EMPTY: i64 = i64::MIN;
const LOG_P: u32 = 8;
const P: usize = 1 << LOG_P;
let hashv = |v: i64| (v as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
// Pass 1: partition histogram + global sentinel flag.
let mut sizes = vec![0usize; P];
let mut has_sentinel = false;
for &v in data {
if v == EMPTY {
has_sentinel = true;
continue;
}
sizes[(hashv(v) >> (64 - LOG_P)) as usize] += 1;
}
// Exclusive prefix sum -> partition offsets.
let mut offsets = vec![0usize; P + 1];
for i in 0..P {
offsets[i + 1] = offsets[i] + sizes[i];
}
// Pass 2: scatter non-sentinel values into one contiguous buffer.
let mut buf = vec![0i64; offsets[P]];
let mut cursor: Vec<usize> = offsets[..P].to_vec();
for &v in data {
if v == EMPTY {
continue;
}
let p = (hashv(v) >> (64 - LOG_P)) as usize;
buf[cursor[p]] = v;
cursor[p] += 1;
}
// Pass 3: per-partition open-addressing distinct count (L2-resident table).
let mut total = 0i64;
for p in 0..P {
let part = &buf[offsets[p]..offsets[p + 1]];
if part.is_empty() {
continue;
}
let cap = part
.len()
.saturating_mul(2)
.checked_next_power_of_two()
.unwrap_or(0);
if cap == 0 {
let mut set: FxHashSet<i64> = FxHashSet::default();
for &v in part {
set.insert(v);
}
total += set.len() as i64;
continue;
}
let mask = cap - 1;
let cap_bits = cap.trailing_zeros();
let mut keys = vec![EMPTY; cap];
for &v in part {
// No `i64::MIN` in `part` (sentinels excluded), so `EMPTY` is a safe
// empty marker. The per-partition index takes the `cap_bits` hash bits
// JUST BELOW the top `LOG_P` partition bits (shift the partition bits
// out, then Fibonacci-select the next `cap_bits` from the top). The old
// `hashv(v) & mask` (LOW bits) collapsed to ONE bucket for high-bit-only
// keys — e.g. `v = k<<34`, whose `hashv = k·(golden<<34)` has zero low
// bits — turning a whole partition into an O(part.len()²) probe scan
// (measured 17s at 5M/2M-distinct). The below-partition bits vary within
// a partition for such keys, so probing stays well spread; the count is
// probe-order-independent, so this is bit-identical.
let mut idx = ((hashv(v) << LOG_P) >> (64 - cap_bits)) as usize;
loop {
let k = keys[idx];
if k == EMPTY {
keys[idx] = v;
total += 1;
break;
}
if k == v {
break;
}
idx = (idx + 1) & mask;
}
}
}
total + i64::from(has_sentinel)
}
/// Cheap witness that a wide `i64` slice is in the VERY-high-cardinality regime
/// where [`count_distinct_i64_radix`] beats [`count_distinct_i64_singletable`].
///
/// Radix wins only once the single `2n`-slot table exceeds the LLC and its probe
/// working set (≈ `distinct` cache lines) stops fitting — empirically distinct
/// ≳ 1.5M (single-table cap ≳ 96 MB). At LOW cardinality the single table's hot
/// set stays L2/L3-resident and radix's full scatter is pure overhead (measured
/// ~2x SLOWER). A strided sample that is ≥99.5% distinct implies (by the
/// birthday bound over `S=16384` draws) a total distinct far above that
/// crossover, so it is a CONSERVATIVE gate: it fires only where radix is a clear
/// win and never in the low/moderate-card regression zone. The sample is O(S)
/// and negligible against the O(n) count. Requires `n ≥ 2M` (below that the
/// single table already fits the LLC, so radix can never help).
fn count_distinct_i64_high_card(data: &[i64]) -> bool {
const CHUNKS: usize = 8;
const PER: usize = 512; // 8 * 512 = 4096 samples
let n = data.len();
if n < (1 << 21) {
return false;
}
// Sample `CHUNKS` small CONTIGUOUS windows spread evenly across the array:
// near-sequential reads (cheap, prefetched — avoids the TLB/cache-miss cost
// of a fully strided scan) while still spatially spread so a locally-ordered
// region cannot alone decide the estimate.
let mut seen: FxHashSet<i64> = FxHashSet::default();
let mut sampled = 0usize;
let span = n / CHUNKS;
for c in 0..CHUNKS {
let start = c * span;
let end = (start + PER).min(n);
for &v in &data[start..end] {
seen.insert(v);
sampled += 1;
}
}
// seen/sampled >= 0.999 (≤ ~4 collisions in S=4096). By the birthday bound
// that implies total distinct ≳ 2M — safely past the crossover, so the gate
// never mis-fires into the low/moderate-card regression zone (missing a
// genuine high-card case is harmless: it just uses the single table).
seen.len().saturating_mul(1000) >= sampled.saturating_mul(999)
}
/// Distinct count for a wide, all-valid `i64` slice: dispatches to the
/// radix-partitioned aggregation for very-high-cardinality inputs (where the
/// single probe table thrashes the LLC) and to the single-table open-addressing
/// count otherwise. Both produce the identical count (radix is order- and
/// partition-independent), so this is a pure perf dispatch.
fn count_distinct_i64_wide(data: &[i64]) -> i64 {
if count_distinct_i64_high_card(data) {
count_distinct_i64_radix(data)
} else {
count_distinct_i64_singletable(data)
}
}
/// `mode` (most-frequent value(s), ascending) for an all-valid `i64` slice too
/// wide for the dense histogram, via an open-addressing `i64 -> count` map
/// (linear probing, inline keys + parallel `u32` counts, ~0.67 load, Fibonacci
/// hash) over the raw slice — no `Scalar` materialization, no `FxHashMap`
/// overhead (the wide-i64 khash-floor lever; `mode` is tally+argmax, so unlike
/// `value_counts` it has no large sorted output and is purely hash-bound).
/// `i64::MIN` is the empty sentinel, its count tracked separately. Winners are
/// returned ascending (matching the generic path's `compare_scalars_na_last`).
fn mode_i64_wide(data: &[i64]) -> Vec<i64> {
const EMPTY: i64 = i64::MIN;
const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15;
let n = data.len();
if n == 0 {
return Vec::new();
}
if n > u32::MAX as usize {
let mut counts: FxHashMap<i64, u64> = FxHashMap::default();
for &v in data {
*counts.entry(v).or_insert(0) += 1;
}
let max_c = counts.values().copied().max().unwrap_or(0);
let mut winners: Vec<i64> = counts
.iter()
.filter_map(|(&k, &c)| (c == max_c).then_some(k))
.collect();
winners.sort_unstable();
return winners;
}
// GROWABLE open-addressing + FIBONACCI hashing — same fix as `mode_f64_wide`:
// the old fixed cap ≈ 1.5·n is a huge SPARSE table (cache miss per probe) for
// few-distinct data, and `(v·GOLDEN) & mask` keeps the LOW product bits, which
// vanish when keys vary only in high bits (e.g. wide i64 / Datetime64 ns that
// are near-multiples of a large power of two) → one bucket → long probe chains.
// Grow from small (double at load 0.7) to size the table to the actual distinct
// count, and Fibonacci `(v·GOLDEN) >> (64 - log2 cap)` uses the HIGH product
// bits. `i64::MIN` is the empty sentinel, counted separately (`sentinel_cnt`)
// so it never enters the table. Bit-identical: same key→count mapping and
// ascending winners (hashing only moves probe positions).
// >= 2 so `shift = 64 - log2(cap)` <= 63 (a 64-bit `>>` is invalid).
let mut cap = 1024usize.min(n.saturating_add(n / 2).next_power_of_two()).max(2);
let mut shift = 64 - cap.trailing_zeros();
let mut keys = vec![EMPTY; cap];
let mut cnt = vec![0u32; cap];
let mut sentinel_cnt: u64 = 0;
let mut filled = 0usize;
for &v in data {
if v == EMPTY {
sentinel_cnt += 1;
continue;
}
// Grow before load would exceed 0.7 (`filled` only rises on a fresh key).
if filled * 10 >= cap * 7 {
let ncap = cap * 2;
let nshift = 64 - ncap.trailing_zeros();
let nmask = ncap - 1;
let mut nkeys = vec![EMPTY; ncap];
let mut ncnt = vec![0u32; ncap];
for p in 0..cap {
if keys[p] != EMPTY {
let mut q = ((keys[p] as u64).wrapping_mul(GOLDEN) >> nshift) as usize;
while nkeys[q] != EMPTY {
q = (q + 1) & nmask;
}
nkeys[q] = keys[p];
ncnt[q] = cnt[p];
}
}
keys = nkeys;
cnt = ncnt;
cap = ncap;
shift = nshift;
}
let mask = cap - 1;
let mut p = ((v as u64).wrapping_mul(GOLDEN) >> shift) as usize;
loop {
if keys[p] == EMPTY {
keys[p] = v;
cnt[p] = 1;
filled += 1;
break;
}
if keys[p] == v {
cnt[p] += 1;
break;
}
p = (p + 1) & mask;
}
}
let mut max_c: u64 = sentinel_cnt;
for p in 0..cap {
if keys[p] != EMPTY {
max_c = max_c.max(u64::from(cnt[p]));
}
}
let mut winners: Vec<i64> = Vec::new();
if sentinel_cnt > 0 && sentinel_cnt == max_c {
winners.push(EMPTY);
}
for p in 0..cap {
if keys[p] != EMPTY && u64::from(cnt[p]) == max_c {
winners.push(keys[p]);
}
}
winners.sort_unstable();
winners
}
/// `mode` for an all-valid (NaN-free) `f64` slice: most-frequent value(s),
/// ascending. Open-addressing keyed by NORMALIZED float bits (−0.0 == +0.0) with
/// parallel `u32` counts and the first-seen ORIGINAL value (so a `-0.0`-mode
/// keeps `-0.0`), then argmax + ascending winners. Empty sentinel `i64::MIN`
/// (= −0.0 bits) never collides with a normalized key. Bit-identical to the
/// generic `FxHashMap<FloatBits, (count, &Scalar)>` path.
fn mode_f64_wide(data: &[f64]) -> Vec<f64> {
const EMPTY: i64 = i64::MIN;
const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15;
let n = data.len();
if n == 0 {
return Vec::new();
}
// n > u32::MAX ⇒ a single value could appear more than u32 times → keep the
// u64-count FxHashMap fallback.
if n > u32::MAX as usize {
let mut counts: FxHashMap<u64, (u64, f64)> = FxHashMap::default();
for &f in data {
let kb = (if f == 0.0 { 0.0 } else { f }).to_bits();
counts.entry(kb).and_modify(|e| e.0 += 1).or_insert((1, f));
}
let max_c = counts.values().map(|(c, _)| *c).max().unwrap_or(0);
let mut winners: Vec<f64> = counts
.values()
.filter_map(|&(c, f)| (c == max_c).then_some(f))
.collect();
winners.sort_by(|a, b| a.total_cmp(b));
return winners;
}
// GROWABLE open-addressing + FIBONACCI hashing (use the HIGH product bits).
// Two independent bugs made the old fixed-cap `& mask` table ~45x slower than
// FxHashMap at ~2000 distinct / 5M rows (float-of-integer data is common):
// (1) cap ≈ 1.5·n is a huge SPARSE table for few-distinct data → a cache miss
// per probe into a multi-MB array. Fix: grow from small (doubling at load
// 0.7) so the table sizes to the ACTUAL distinct count and stays cache-
// resident for few-distinct data, still ending at the SAME dense table for
// high-card data (its fast domain) — nothing regresses there.
// (2) `(kb·GOLDEN) & mask` keeps the LOW product bits, but float-of-integer
// keys vary in the HIGH bits of `to_bits()` (mantissa of large-exponent
// floats), and `(v<<42)·GOLDEN` has zero low bits → a whole exponent group
// collapses into ONE bucket → probe chains of ~1000. Fix: Fibonacci hash
// `(kb·GOLDEN) >> (64 - log2 cap)` takes the HIGH bits (provably good
// spread even when the key varies in high bits).
// Bit-identical output (hashing only moves probe positions): same keys, counts,
// first-seen originals, ascending total_cmp winners. `EMPTY = i64::MIN` = -0.0
// bits, which normalization maps to +0.0 (key 0), so no real key hits the empty.
// >= 2 so `shift = 64 - log2(cap)` is <= 63 (a 64-bit `>>` shift is invalid).
let mut cap = 1024usize.min(n.saturating_add(n / 2).next_power_of_two()).max(2);
let mut shift = 64 - cap.trailing_zeros();
let mut keys = vec![EMPTY; cap];
let mut cnt = vec![0u32; cap];
let mut first = vec![0.0f64; cap];
let mut filled = 0usize;
for &f in data {
// Grow (rehash into a 2x table) before load would exceed 0.7. `filled` only
// rises on a fresh key, so the live table never passes that load factor.
if filled * 10 >= cap * 7 {
let ncap = cap * 2;
let nshift = 64 - ncap.trailing_zeros();
let nmask = ncap - 1;
let mut nkeys = vec![EMPTY; ncap];
let mut ncnt = vec![0u32; ncap];
let mut nfirst = vec![0.0f64; ncap];
for p in 0..cap {
if keys[p] != EMPTY {
let mut q =
((keys[p] as u64).wrapping_mul(GOLDEN) >> nshift) as usize;
while nkeys[q] != EMPTY {
q = (q + 1) & nmask;
}
nkeys[q] = keys[p];
ncnt[q] = cnt[p];
nfirst[q] = first[p];
}
}
keys = nkeys;
cnt = ncnt;
first = nfirst;
cap = ncap;
shift = nshift;
}
let mask = cap - 1;
let kb = (if f == 0.0 { 0.0 } else { f }).to_bits() as i64;
let mut p = ((kb as u64).wrapping_mul(GOLDEN) >> shift) as usize;
loop {
if keys[p] == EMPTY {
keys[p] = kb;
cnt[p] = 1;
first[p] = f;
filled += 1;
break;
}
if keys[p] == kb {
cnt[p] += 1;
break;
}
p = (p + 1) & mask;
}
}
let mut max_c = 0u32;
for p in 0..cap {
if keys[p] != EMPTY {
max_c = max_c.max(cnt[p]);
}
}
let mut winners: Vec<f64> = Vec::new();
for p in 0..cap {
if keys[p] != EMPTY && cnt[p] == max_c {
winners.push(first[p]);
}
}
winners.sort_by(|a, b| a.total_cmp(b));
winners
}
/// `duplicated(keep="first")` flags for an all-valid `i64` slice too wide for
/// the dense direct-address path, via the same open-addressing set as
/// [`count_distinct_i64_wide`]: flag is `false` on a value's first occurrence
/// (a fresh insert) and `true` on every repeat — bit-identical to
/// [`duplicated_flags_typed`] with `DupPolicy::First`, but beats its
/// `FxHashSet<i64>` on high-cardinality wide keys. `i64::MIN` is the empty
/// sentinel, its duplicate-state tracked via a flag.
fn duplicated_first_i64_wide(data: &[i64]) -> Vec<bool> {
const EMPTY: i64 = i64::MIN;
const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15;
let n = data.len();
let mut flags = vec![false; n];
if n == 0 {
return flags;
}
// GROWABLE open-addressing + FIBONACCI hashing (wide open-addr vein fix): the
// old fixed cap ≈ 1.5·n is a huge SPARSE membership table (cache miss per probe)
// for few-distinct data, and `(v·GOLDEN) & mask` (LOW product bits) clusters
// keys that vary only in HIGH bits. Grow from small (double at load 0.7) and
// Fibonacci `>> (64 - log2 cap)` (HIGH bits). Byte-identical: `flags` is a
// per-row first-seen membership test (independent of table layout).
// >= 2 so `shift = 64 - log2(cap)` <= 63.
let mut cap = 1024usize.min(n.saturating_add(n / 2).next_power_of_two()).max(2);
let mut shift = 64 - cap.trailing_zeros();
let mut keys = vec![EMPTY; cap];
let mut seen_sentinel = false;
let mut filled = 0usize;
for (idx, &v) in data.iter().enumerate() {
if v == EMPTY {
flags[idx] = seen_sentinel;
seen_sentinel = true;
continue;
}
if filled * 10 >= cap * 7 {
let ncap = cap * 2;
let nshift = 64 - ncap.trailing_zeros();
let nmask = ncap - 1;
let mut nkeys = vec![EMPTY; ncap];
for p in 0..cap {
if keys[p] != EMPTY {
let mut q = ((keys[p] as u64).wrapping_mul(GOLDEN) >> nshift) as usize;
while nkeys[q] != EMPTY {
q = (q + 1) & nmask;
}
nkeys[q] = keys[p];
}
}
keys = nkeys;
cap = ncap;
shift = nshift;
}
let mask = cap - 1;
let mut p = ((v as u64).wrapping_mul(GOLDEN) >> shift) as usize;
loop {
let k = keys[p];
if k == EMPTY {
keys[p] = v;
filled += 1;
break; // first occurrence → flag stays false
}
if k == v {
flags[idx] = true;
break;
}
p = (p + 1) & mask;
}
}
flags
}
/// First-seen distinct values of an all-valid `i64` slice too wide for the
/// dense direct-address path, via the same open-addressing set as
/// [`count_distinct_i64_wide`] but COLLECTING each value the first time it is
/// inserted — no `Scalar` materialization, no `FxHashSet` overhead. Output is in
/// first-seen order (bit-identical to the generic `unique` path). `i64::MIN` is
/// the empty sentinel, emitted at its first-seen position via a separate flag.
/// First-seen distinct values of an all-valid (NaN-free) `f64` slice, via an
/// open-addressing set keyed by NORMALIZED float bits (−0.0 → +0.0, exactly as
/// the generic `Key::FloatBits` path) while collecting the ORIGINAL first-seen
/// `f64` for output — so a `-0.0`-first column keeps `-0.0` as its representative,
/// bit-identical to the generic `unique`. The empty sentinel `i64::MIN` is the
/// `-0.0` bit pattern, which no normalized key can equal (−0.0 normalizes to
/// +0.0), so it never collides.
// GROWABLE open-addressing + FIBONACCI hashing (same fix as `mode_f64_wide`): the
// old fixed cap ≈ 1.5·n is a huge SPARSE membership table (cache miss per probe)
// for few-distinct data, and `(kb·GOLDEN) & mask` keeps the LOW product bits,
// which vanish for float-of-integer keys (their variation is in the HIGH to_bits()
// bits) → one bucket → long probe chains. Grow from small (double at load 0.7) so
// the table sizes to the distinct count, and Fibonacci `>> (64 - log2 cap)` uses
// the HIGH bits. Byte-identical output: `out` is the first-seen dedup order, which
// depends only on membership (unaffected by table size), so growth never reorders.
fn unique_f64_wide(data: &[f64]) -> Vec<f64> {
const EMPTY: i64 = i64::MIN;
const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15;
let n = data.len();
let mut out: Vec<f64> = Vec::new();
if n == 0 {
return out;
}
// >= 2 so `shift = 64 - log2(cap)` <= 63 (a 64-bit `>>` is invalid).
let mut cap = 1024usize.min(n.saturating_add(n / 2).next_power_of_two()).max(2);
let mut shift = 64 - cap.trailing_zeros();
let mut keys = vec![EMPTY; cap];
let mut filled = 0usize;
for &f in data {
if filled * 10 >= cap * 7 {
let ncap = cap * 2;
let nshift = 64 - ncap.trailing_zeros();
let nmask = ncap - 1;
let mut nkeys = vec![EMPTY; ncap];
for p in 0..cap {
if keys[p] != EMPTY {
let mut q = ((keys[p] as u64).wrapping_mul(GOLDEN) >> nshift) as usize;
while nkeys[q] != EMPTY {
q = (q + 1) & nmask;
}
nkeys[q] = keys[p];
}
}
keys = nkeys;
cap = ncap;
shift = nshift;
}
let mask = cap - 1;
let kb = (if f == 0.0 { 0.0 } else { f }).to_bits() as i64;
let mut p = ((kb as u64).wrapping_mul(GOLDEN) >> shift) as usize;
loop {
let k = keys[p];
if k == EMPTY {
keys[p] = kb;
out.push(f);
filled += 1;
break;
}
if k == kb {
break;
}
p = (p + 1) & mask;
}
}
out
}
/// Int64 sibling of [`unique_f64_wide`]. `i64::MIN` is the empty sentinel, tracked
/// separately so a real `i64::MIN` dedups correctly (and keeps its first-seen slot).
fn unique_i64_wide(data: &[i64]) -> Vec<i64> {
const EMPTY: i64 = i64::MIN;
const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15;
let n = data.len();
let mut out: Vec<i64> = Vec::new();
if n == 0 {
return out;
}
let mut cap = 1024usize.min(n.saturating_add(n / 2).next_power_of_two()).max(2);
let mut shift = 64 - cap.trailing_zeros();
let mut keys = vec![EMPTY; cap];
let mut seen_sentinel = false;
let mut filled = 0usize;
for &v in data {
if v == EMPTY {
if !seen_sentinel {
seen_sentinel = true;
out.push(EMPTY);
}
continue;
}
if filled * 10 >= cap * 7 {
let ncap = cap * 2;
let nshift = 64 - ncap.trailing_zeros();
let nmask = ncap - 1;
let mut nkeys = vec![EMPTY; ncap];
for p in 0..cap {
if keys[p] != EMPTY {
let mut q = ((keys[p] as u64).wrapping_mul(GOLDEN) >> nshift) as usize;
while nkeys[q] != EMPTY {
q = (q + 1) & nmask;
}
nkeys[q] = keys[p];
}
}
keys = nkeys;
cap = ncap;
shift = nshift;
}
let mask = cap - 1;
let mut idx = ((v as u64).wrapping_mul(GOLDEN) >> shift) as usize;
loop {
let k = keys[idx];
if k == EMPTY {
keys[idx] = v;
out.push(v);
filled += 1;
break;
}
if k == v {
break;
}
idx = (idx + 1) & mask;
}
}
out
}
/// First-seen factorize of an all-valid `i64` slice too wide for the dense
/// direct-address path, via an open-addressing `i64 -> code` map (linear
/// probing, inline keys + parallel `u32` codes, ~0.67 load, Fibonacci hash) over
/// the raw slice — no `Scalar` materialization, no `FxHashMap` overhead (the
/// wide-i64 khash-floor lever, shared shape with [`count_distinct_i64_wide`]).
/// Returns `(codes, uniques)` in first-seen order (raw i64 uniques), byte-
/// identical to the `FxHashMap` path's assignment. `i64::MIN` is the empty
/// sentinel and is tracked separately so a real `i64::MIN` value factorizes
/// correctly.
fn factorize_i64_wide(data: &[i64]) -> (Vec<i64>, Vec<i64>) {
const EMPTY: i64 = i64::MIN;
const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15;
let n = data.len();
let mut codes: Vec<i64> = Vec::with_capacity(n);
let mut uniques: Vec<i64> = Vec::new();
// `code_at` stores codes as u32; only valid when distinct (≤ n) fits u32.
if n > u32::MAX as usize {
let mut map: FxHashMap<i64, i64> = FxHashMap::default();
for &v in data {
match map.get(&v) {
Some(&c) => codes.push(c),
None => {
let c = uniques.len() as i64;
map.insert(v, c);
uniques.push(v);
codes.push(c);
}
}
}
return (codes, uniques);
}
// GROWABLE open-addressing + FIBONACCI hashing (same vein fix as
// `mode_*_wide` / `unique_*_wide`): the old fixed cap ≈ 1.5·n is a huge SPARSE
// (keys, code_at) table (cache miss per probe) for few-distinct data, and
// `(v·GOLDEN) & mask` keeps the LOW product bits, which vanish when keys vary in
// high bits (wide / high-bit-only i64) → clustering. Grow from small (double at
// load 0.7, rehashing BOTH parallel arrays) to size the table to the distinct
// count, and Fibonacci `>> (64 - log2 cap)` uses the HIGH bits. Byte-identical:
// codes/uniques are the first-seen assignment (code = uniques.len() at insert),
// which depends only on order, not table layout. `i64::MIN` sentinel via min_code.
// >= 2 so `shift = 64 - log2(cap)` <= 63 (a 64-bit `>>` is invalid).
let mut cap = 1024usize.min(n.saturating_add(n / 2).next_power_of_two()).max(2);
let mut shift = 64 - cap.trailing_zeros();
let mut keys = vec![EMPTY; cap];
let mut code_at = vec![0u32; cap];
let mut min_code: i64 = -1; // code of the i64::MIN sentinel value; -1 = unseen
let mut filled = 0usize;
for &v in data {
if v == EMPTY {
if min_code < 0 {
let c = uniques.len() as i64;
min_code = c;
uniques.push(EMPTY);
codes.push(c);
} else {
codes.push(min_code);
}
continue;
}
if filled * 10 >= cap * 7 {
let ncap = cap * 2;
let nshift = 64 - ncap.trailing_zeros();
let nmask = ncap - 1;
let mut nkeys = vec![EMPTY; ncap];
let mut ncode = vec![0u32; ncap];
for p in 0..cap {
if keys[p] != EMPTY {
let mut q = ((keys[p] as u64).wrapping_mul(GOLDEN) >> nshift) as usize;
while nkeys[q] != EMPTY {
q = (q + 1) & nmask;
}
nkeys[q] = keys[p];
ncode[q] = code_at[p];
}
}
keys = nkeys;
code_at = ncode;
cap = ncap;
shift = nshift;
}
let mask = cap - 1;
let mut idx = ((v as u64).wrapping_mul(GOLDEN) >> shift) as usize;
loop {
let k = keys[idx];
if k == EMPTY {
let c = uniques.len() as i64;
keys[idx] = v;
code_at[idx] = c as u32;
uniques.push(v);
codes.push(c);
filled += 1;
break;
}
if k == v {
codes.push(i64::from(code_at[idx]));
break;
}
idx = (idx + 1) & mask;
}
}
(codes, uniques)
}
/// Fully-typed factorize of an all-valid `i64` slice: first-seen `(codes,
/// uniques)` as raw `Vec<i64>` (dense direct-address when the value span is
/// bounded, else the open-addressing map), with the optional ascending `sort`
/// remap done on the raw i64 uniques (cheaper than `Scalar` comparison and
/// bit-identical to `compare_scalars_na_last` for all-valid Int64/Datetime64 ns).
/// No `Scalar` boxing on input OR output — the caller wraps via
/// `from_i64_values` / `from_datetime64_values`.
fn factorize_i64_typed(data: &[i64], sort: bool) -> (Vec<i64>, Vec<i64>) {
let (mut codes, mut uniques) = if let Some((min, range)) = i64_direct_address_range(data) {
let mut code_table = vec![-1i64; range];
let mut uniques: Vec<i64> = Vec::new();
let mut codes: Vec<i64> = Vec::with_capacity(data.len());
for &v in data {
let slot = (v as i128 - min as i128) as usize;
let existing = code_table[slot];
if existing < 0 {
let code = uniques.len() as i64;
code_table[slot] = code;
uniques.push(v);
codes.push(code);
} else {
codes.push(existing);
}
}
(codes, uniques)
} else {
factorize_i64_wide(data)
};
if sort && !uniques.is_empty() {
let mut ordering: Vec<usize> = (0..uniques.len()).collect();
ordering.sort_by(|&a, &b| uniques[a].cmp(&uniques[b]));
let mut remap = vec![0i64; uniques.len()];
let sorted: Vec<i64> = ordering
.into_iter()
.enumerate()
.map(|(sorted_pos, orig)| {
remap[orig] = sorted_pos as i64;
uniques[orig]
})
.collect();
for c in &mut codes {
// All-valid typed input ⇒ no -1 sentinel, but keep the guard.
if *c >= 0 {
*c = remap[*c as usize];
}
}
uniques = sorted;
}
(codes, uniques)
}
/// Fully-typed `value_counts` for all-valid Int64 columns. This keeps the
/// tally, optional count-order permutation, values output, and count output in
/// primitive buffers instead of boxing high-cardinality outputs as `Scalar`s.
/// Stable count sorting preserves first-seen order for ties, matching the
/// generic path's pandas-facing contract.
fn value_counts_i64_typed(
data: &[i64],
normalize: bool,
sort: bool,
ascending: bool,
) -> (Column, Column) {
if data.is_empty() {
let values = Column::from_i64_values_owned(Vec::new());
let counts = if normalize {
Column::from_f64_values(Vec::new())
} else {
Column::from_i64_values_owned(Vec::new())
};
return (values, counts);
}
let (mut values, mut counts) = if let Some((min, range)) = i64_direct_address_range(data) {
let mut dense = vec![0usize; range];
let mut first_seen = Vec::new();
for &value in data {
let slot = (value as i128 - min as i128) as usize;
if dense[slot] == 0 {
first_seen.push(value);
}
dense[slot] += 1;
}
let counts: Vec<usize> = first_seen
.iter()
.map(|&value| dense[(value as i128 - min as i128) as usize])
.collect();
(first_seen, counts)
} else {
// Wide path stays on FxHashMap. NEGATIVE LEDGER: converting this to the
// vein's growable+Fibonacci open-addressing (keys + a parallel `slot_at`
// into values/counts) is byte-identical but NOT a net win — measured
// low-card 0.76x, mid-100k 0.91x (regressions), high-card-2M 1.43x. Unlike
// the MEMBERSHIP-only tallies (count_distinct/duplicated, which the open-
// addressing beat at mid card too), value_counts bumps `counts[slot]` on
// every repeat, and that extra slot indirection erodes the open-addressing
// edge at low/mid cardinality — where FxHashMap's tuned get wins. So the
// vein's speedup does NOT extend to counting tallies. DON'T re-attempt.
let mut index: FxHashMap<i64, usize> = FxHashMap::default();
let mut values = Vec::new();
let mut counts = Vec::new();
for &value in data {
if let Some(&slot) = index.get(&value) {
counts[slot] += 1;
} else {
index.insert(value, values.len());
values.push(value);
counts.push(1);
}
}
(values, counts)
};
if sort && counts.len() > 1 {
let first = counts[0];
if counts.iter().any(|&count| count != first) {
let mut order: Vec<usize> = (0..counts.len()).collect();
if ascending {
order.sort_by_key(|&idx| counts[idx]);
} else {
order.sort_by_key(|&idx| std::cmp::Reverse(counts[idx]));
}
values = order.iter().map(|&idx| values[idx]).collect();
counts = order.into_iter().map(|idx| counts[idx]).collect();
}
}
let values = Column::from_i64_values_owned(values);
let counts = if normalize {
let total = data.len() as f64;
Column::from_f64_values(
counts
.into_iter()
.map(|count| count as f64 / total)
.collect(),
)
} else {
Column::from_i64_values_owned(
counts
.into_iter()
.map(|count| i64::try_from(count).unwrap_or(i64::MAX))
.collect(),
)
};
(values, counts)
}
/// Hash-free duplicate flags for a bounded-range `i64` slice via a dense
/// direct-address table (no per-element hashing or `Scalar` enum). Identical
/// semantics to [`duplicated_flags_typed`]. `min`/`range` come from
/// [`i64_direct_address_range`], so `(v - min)` is always in `0..range`.
fn duplicated_flags_i64_direct(
data: &[i64],
min: i64,
range: usize,
policy: DupPolicy,
) -> Vec<bool> {
let n = data.len();
let mut flags = vec![false; n];
let slot = |v: i64| (v as i128 - min as i128) as usize;
match policy {
DupPolicy::First => {
let mut seen = vec![false; range];
for (idx, &v) in data.iter().enumerate() {
let s = slot(v);
flags[idx] = seen[s];
seen[s] = true;
}
}
DupPolicy::Last => {
let mut seen = vec![false; range];
for (idx, &v) in data.iter().enumerate().rev() {
let s = slot(v);
flags[idx] = seen[s];
seen[s] = true;
}
}
DupPolicy::None => {
// Saturating occupancy count (we only care about 1 vs >1).
let mut count = vec![0u8; range];
for &v in data {
let s = slot(v);
if count[s] < 2 {
count[s] += 1;
}
}
for (idx, &v) in data.iter().enumerate() {
flags[idx] = count[slot(v)] > 1;
}
}
}
flags
}
/// Map an `i64` to an order-preserving `u64` radix key (flip the sign bit so
/// two's-complement negatives sort below non-negatives in unsigned order).
#[inline]
fn i64_radix_key(value: i64) -> u64 {
(value as u64) ^ (1u64 << 63)
}
/// Map an `f64` to an order-preserving `u64` radix key. For a non-negative
/// value flip only the sign bit; for a negative value flip every bit. This is
/// the standard IEEE-754 "sortable bits" transform and is monotonic across the
/// whole finite range (callers guarantee no NaN — `as_f64_slice` only yields
/// all-valid buffers and FP models NaN as missing). `-0.0` and `+0.0` map to
/// distinct keys but compare equal under the comparator path; we normalize
/// `-0.0`→`+0.0` first so the radix order matches `partial_cmp` exactly.
#[inline]
fn f64_radix_key(value: f64) -> u64 {
let bits = (if value == 0.0 { 0.0 } else { value }).to_bits();
if bits & (1u64 << 63) != 0 {
!bits
} else {
bits | (1u64 << 63)
}
}
/// Stable LSD radix argsort over pre-computed `u64` keys (8 passes of 8-bit
/// counting sort). Returns the permutation `perm` such that
/// `keys[perm[0]] <= keys[perm[1]] <= ...`, with equal keys keeping their
/// original relative order (stability == the comparator path's tie behavior).
/// Build a `Vec<f64>` of length `n` where slot `i` is `g(i)`, evaluated across
/// scoped threads for COMPUTE-bound `g` (libm transcendentals). Serial below
/// `PAR_MIN` or on single-core hosts. Order-preserving (chunk writes a
/// contiguous global range) → bit-identical to the serial map.
fn par_map_vec_f64<G: Fn(usize) -> f64 + Sync>(n: usize, g: G) -> Vec<f64> {
const PAR_MIN: usize = 200_000;
let mut out = vec![0.0_f64; n];
let workers = std::thread::available_parallelism()
.map(std::num::NonZeroUsize::get)
.unwrap_or(1)
.min(8);
if workers <= 1 || n < PAR_MIN {
for (i, o) in out.iter_mut().enumerate() {
*o = g(i);
}
return out;
}
let chunk = n.div_ceil(workers);
std::thread::scope(|scope| {
for (ci, out_c) in out.chunks_mut(chunk).enumerate() {
let g = &g;
let base = ci * chunk;
scope.spawn(move || {
for (j, o) in out_c.iter_mut().enumerate() {
*o = g(base + j);
}
});
}
});
out
}
/// `i64` sibling of [`par_map_vec_f64`] for compute-bound i64 index maps
/// (python_mod_i64 / python_floor_div_i64 — integer idiv + sign adjustment).
fn par_map_vec_i64<G: Fn(usize) -> i64 + Sync>(n: usize, g: G) -> Vec<i64> {
const PAR_MIN: usize = 200_000;
let mut out = vec![0_i64; n];
let workers = std::thread::available_parallelism()
.map(std::num::NonZeroUsize::get)
.unwrap_or(1)
.min(8);
if workers <= 1 || n < PAR_MIN {
for (i, o) in out.iter_mut().enumerate() {
*o = g(i);
}
return out;
}
let chunk = n.div_ceil(workers);
std::thread::scope(|scope| {
for (ci, out_c) in out.chunks_mut(chunk).enumerate() {
let g = &g;
let base = ci * chunk;
scope.spawn(move || {
for (j, o) in out_c.iter_mut().enumerate() {
*o = g(base + j);
}
});
}
});
out
}
/// Sort an `i64` slice's VALUES directly (no argsort permutation, no final
/// gather) via an 8-pass LSD radix over order-preserving keys in ping-pong
/// buffers. `Column::sort_values` only needs the sorted values (the row
/// permutation, when needed, comes from `argsort_with`), so skipping the
/// `data[perm[i]]` cache-random gather — the bottleneck of the argsort path —
/// is bit-identical: equal i64 values are indistinguishable, so tie order in the
/// output is irrelevant. Descending = ascending reversed (ties are identical
/// values, so the reverse is exact).
fn radix_sort_i64_values(data: &[i64], ascending: bool) -> Vec<i64> {
let n = data.len();
if n < 2 {
return data.to_vec();
}
let mut buf: Vec<u64> = data.iter().map(|&v| i64_radix_key(v)).collect();
let mut scratch: Vec<u64> = vec![0u64; n];
for shift in (0..64).step_by(8) {
let mut count = [0usize; 256];
for &k in &buf {
count[((k >> shift) & 0xff) as usize] += 1;
}
if count.contains(&n) {
continue; // byte constant across column — skip the pass
}
let mut running = 0usize;
for slot in &mut count {
let c = *slot;
*slot = running;
running += c;
}
for &k in &buf {
let b = ((k >> shift) & 0xff) as usize;
scratch[count[b]] = k;
count[b] += 1;
}
std::mem::swap(&mut buf, &mut scratch);
}
let mut out: Vec<i64> = buf.iter().map(|&k| (k ^ (1u64 << 63)) as i64).collect();
if !ascending {
out.reverse();
}
out
}
/// O(n) per pass, comparison-free — replaces the O(n log n) `Scalar`-enum
/// comparator for all-valid numeric columns.
fn radix_argsort_u64(keys: &[u64]) -> Vec<usize> {
let n = keys.len();
let mut idx: Vec<usize> = (0..n).collect();
if n < 2 {
return idx;
}
let mut scratch: Vec<usize> = vec![0; n];
for shift in (0..64).step_by(8) {
let mut count = [0usize; 256];
for &k in keys {
count[((k >> shift) & 0xff) as usize] += 1;
}
// Skip a pass whose byte is constant across the whole column (common
// for clustered / small-magnitude data) — keeps `idx` in place.
if count.contains(&n) {
continue;
}
let mut running = 0usize;
for slot in &mut count {
let c = *slot;
*slot = running;
running += c;
}
for &i in &idx {
let bucket = ((keys[i] >> shift) & 0xff) as usize;
scratch[count[bucket]] = i;
count[bucket] += 1;
}
std::mem::swap(&mut idx, &mut scratch);
}
idx
}
/// Stable LSD radix argsort of an `i64` slice (br-frankenpandas-y5s15): the
/// permutation that orders `values` ascending (or descending), equal values
/// keeping their original order. Bit-identical to a stable `sort_by(i64::cmp)`:
/// `i64_radix_key` is order-preserving and the counting sort is stable;
/// descending flips the key (`!key`) so equal values still keep original order
/// (matching a reversed comparator whose `Equal` arm doesn't reorder). Reusable
/// for any all-Int64 ordering (index labels, single columns).
#[must_use]
pub fn radix_argsort_i64(values: &[i64], ascending: bool) -> Vec<usize> {
let keys: Vec<u64> = if ascending {
values.iter().map(|&v| i64_radix_key(v)).collect()
} else {
values.iter().map(|&v| !i64_radix_key(v)).collect()
};
radix_argsort_u64(&keys)
}
/// Stable LSD radix argsort of an `f64` slice (br-frankenpandas-wgyn4): the
/// permutation ordering `values` ascending (or descending), equal values keeping
/// original order. `f64_radix_key` is order-preserving for finite/inf and the
/// counting sort is stable. CALLER GUARANTEES no NaN (NaN has no radix order) and
/// no `-0.0` when the consumer needs `total_cmp` ordering — `f64_radix_key`
/// normalizes `-0.0`→`+0.0` (matching `partial_cmp`/`==`, NOT `total_cmp`).
#[must_use]
pub fn radix_argsort_f64(values: &[f64], ascending: bool) -> Vec<usize> {
let keys: Vec<u64> = if ascending {
values.iter().map(|&v| f64_radix_key(v)).collect()
} else {
values.iter().map(|&v| !f64_radix_key(v)).collect()
};
radix_argsort_u64(&keys)
}
/// Stable LSD radix lexsort over several `u64` key columns
/// (br-frankenpandas-lnsu6). Returns the permutation that orders rows
/// lexicographically by `keys_by_col[0]`, then `keys_by_col[1]`, …, with equal
/// rows keeping their original order — exactly a stable multi-key `sort_by`.
/// The least-significant digit overall is the last column's low byte, so the
/// columns are processed in reverse (each an 8-pass stable counting sort that
/// threads the running permutation), making the *first* column the most
/// significant. O(n·k) and comparison-free. All key vectors must have the same
/// length; callers bake per-column ascending/descending into the keys.
pub fn radix_argsort_multi_u64(keys_by_col: &[Vec<u64>]) -> Vec<usize> {
let n = keys_by_col.first().map_or(0, Vec::len);
let mut idx: Vec<usize> = (0..n).collect();
if n < 2 || keys_by_col.is_empty() {
return idx;
}
let mut scratch: Vec<usize> = vec![0; n];
for keys in keys_by_col.iter().rev() {
for shift in (0..64).step_by(8) {
let mut count = [0usize; 256];
for &k in keys {
count[((k >> shift) & 0xff) as usize] += 1;
}
if count.contains(&n) {
continue;
}
let mut running = 0usize;
for slot in &mut count {
let c = *slot;
*slot = running;
running += c;
}
for &i in &idx {
let bucket = ((keys[i] >> shift) & 0xff) as usize;
scratch[count[bucket]] = i;
count[bucket] += 1;
}
std::mem::swap(&mut idx, &mut scratch);
}
}
idx
}
/// Stable MSD byte-radix argsort over UTF-8 strings.
///
/// Produces the exact permutation of a stable `sort_by` with `String::cmp`
/// (byte-lexicographic, shorter-prefix-first), comparison-free at scale:
/// each level counting-sorts the bucket by the byte at `depth`, with a
/// virtual end-of-string bucket ordered before every byte (ascending) /
/// after every byte (descending) — exactly `cmp`'s prefix rule. Counting
/// scatters preserve relative order and the small-bucket cutoff uses the
/// stable `sort_by` on the (equal-prefix-stripped) suffix, so ties keep
/// their original order at every level, matching the stable comparison
/// sort bit-for-bit in both directions.
pub fn utf8_msd_argsort(strs: &[&str], ascending: bool) -> Vec<usize> {
let spans: Vec<&[u8]> = strs.iter().map(|s| s.as_bytes()).collect();
utf8_msd_argsort_bytes(&spans, ascending)
}
/// MSD byte-radix argsort over raw byte spans (br-frankenpandas-prk0a). Same
/// stable lexicographic ordering as [`utf8_msd_argsort`] but takes `&[&[u8]]`
/// directly, so callers that already hold validated UTF-8 byte spans (groupby
/// keys, contiguous-Utf8 columns) skip the `from_utf8` re-validation needed to
/// build `&[&str]`. Byte order == UTF-8 lexicographic order, so the permutation
/// is identical.
#[must_use]
pub fn utf8_msd_argsort_bytes(spans: &[&[u8]], ascending: bool) -> Vec<usize> {
let n = spans.len();
let mut idx: Vec<usize> = (0..n).collect();
if n <= 1 {
return idx;
}
let mut aux: Vec<usize> = vec![0; n];
const PAR_MIN: usize = 1 << 15;
let workers = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
if n >= PAR_MIN && workers >= 2 {
utf8_msd_sort_range_par(spans, &mut idx, &mut aux, 0, ascending, workers);
} else {
utf8_msd_sort_range(spans, &mut idx, &mut aux, 0, n, 0, ascending);
}
idx
}
/// Parallel front-end for [`utf8_msd_sort_range`] (br-frankenpandas-qdrp7).
/// Descends single-child levels (shared key prefixes) serially, then at the
/// first byte where the bucket fans out into >= 2 non-empty sub-buckets, sorts
/// those independent, DISJOINT `idx`/`aux` sub-ranges concurrently (each a
/// serial `utf8_msd_sort_range` at `depth+1`). Bit-identical to the serial sort:
/// the per-depth counting scatter is identical (same bucket order, same stable
/// placement) and each sub-bucket is sorted by the same routine — only the order
/// in which independent sub-buckets are processed changes, and they write to
/// disjoint output ranges.
fn utf8_msd_sort_range_par(
spans: &[&[u8]],
idx: &mut [usize],
aux: &mut [usize],
depth: usize,
ascending: bool,
workers: usize,
) {
const CUTOFF: usize = 48;
const MAX_DEPTH: usize = 1024;
const PAR_MIN: usize = 1 << 15;
let n = idx.len();
if n <= CUTOFF || depth >= MAX_DEPTH || n < PAR_MIN {
utf8_msd_sort_range(spans, idx, aux, 0, n, depth, ascending);
return;
}
// Counting scatter at `depth` (identical to utf8_msd_sort_range).
let key = |b: &[u8]| -> usize {
if depth < b.len() {
if ascending {
b[depth] as usize + 1
} else {
255 - b[depth] as usize
}
} else if ascending {
0
} else {
256
}
};
let eos_bucket = if ascending { 0 } else { 256 };
let mut counts = [0usize; 258];
for &i in idx.iter() {
counts[key(spans[i]) + 1] += 1;
}
// LCP fast-skip (br-frankenpandas-msdlcp): a single shared byte at `depth`
// makes the scatter an identity permutation — descend in parallel mode to
// depth+1 directly, skipping the wasted scatter + copy. Same skip the serial
// `utf8_msd_sort_range` applies; bit-identical (one stable bucket preserves
// order). A lone EOS bucket means all spans are equal here — done.
{
let mut only: Option<usize> = None;
let mut multi = false;
for k in 0..=256usize {
if counts[k + 1] != 0 {
if only.is_some() {
multi = true;
break;
}
only = Some(k);
}
}
if !multi {
if let Some(k) = only
&& k != eos_bucket
{
utf8_msd_sort_range_par(spans, idx, aux, depth + 1, ascending, workers);
}
return;
}
}
for k in 1..258 {
counts[k] += counts[k - 1];
}
let mut offsets = counts;
for &i in idx.iter() {
let k = key(spans[i]);
aux[offsets[k]] = i;
offsets[k] += 1;
}
idx.copy_from_slice(aux);
// `counts[k]..counts[k+1]` is bucket k. The EOS bucket (fully-equal at this
// depth) is left as-is. Collect the non-trivial byte buckets.
let mut buckets: Vec<(usize, usize)> = Vec::new();
for k in 0..257 {
if k == eos_bucket {
continue;
}
let lo = counts[k];
let hi = counts[k + 1];
if hi - lo > 1 {
buckets.push((lo, hi));
}
}
if buckets.len() <= 1 {
// Single shared-prefix child: keep descending in parallel mode.
if let Some(&(lo, hi)) = buckets.first() {
utf8_msd_sort_range_par(
spans,
&mut idx[lo..hi],
&mut aux[lo..hi],
depth + 1,
ascending,
workers,
);
}
return;
}
// Fan-out: carve `idx`/`aux` into per-bucket disjoint sub-slices (segments
// between consecutive bucket bounds, including any gaps such as the EOS
// bucket which we keep but never sort), then distribute the non-trivial
// segments across workers by cumulative size.
let mut bounds: Vec<usize> = Vec::with_capacity(buckets.len() * 2 + 2);
bounds.push(0);
for &(lo, hi) in &buckets {
if *bounds.last().expect("non-empty") != lo {
bounds.push(lo);
}
bounds.push(hi);
}
if *bounds.last().expect("non-empty") != n {
bounds.push(n);
}
// Split into contiguous segments matching `bounds`.
let mut seg_idx: Vec<&mut [usize]> = Vec::with_capacity(bounds.len() - 1);
let mut seg_aux: Vec<&mut [usize]> = Vec::with_capacity(bounds.len() - 1);
let mut rem_idx: &mut [usize] = idx;
let mut rem_aux: &mut [usize] = aux;
let mut prev = 0usize;
for &b in &bounds[1..] {
let take = b - prev;
prev = b;
let (a, rest_i) = rem_idx.split_at_mut(take);
rem_idx = rest_i;
let (c, rest_a) = rem_aux.split_at_mut(take);
rem_aux = rest_a;
seg_idx.push(a);
seg_aux.push(c);
}
// Work items: (segment, length) for segments that are a non-trivial bucket.
let sortable: std::collections::HashSet<(usize, usize)> = buckets.iter().copied().collect();
let mut items: Vec<(&mut [usize], &mut [usize])> = Vec::new();
let mut seg_start = 0usize;
for (si, (si_slice, sa_slice)) in seg_idx.into_iter().zip(seg_aux).enumerate() {
let len = bounds[si + 1] - bounds[si];
let span_range = (seg_start, seg_start + len);
seg_start += len;
if sortable.contains(&span_range) {
items.push((si_slice, sa_slice));
}
}
// Distribute items round-robin into worker groups (buckets are ~uniform for
// hex/fixed-width keys, so round-robin balances well).
let wc = workers.min(items.len()).max(1);
let mut groups: Vec<Vec<(&mut [usize], &mut [usize])>> = (0..wc).map(|_| Vec::new()).collect();
for (i, item) in items.into_iter().enumerate() {
groups[i % wc].push(item);
}
std::thread::scope(|scope| {
for group in groups {
scope.spawn(move || {
for (si, sa) in group {
let len = si.len();
utf8_msd_sort_range(spans, si, sa, 0, len, depth + 1, ascending);
}
});
}
});
}
fn utf8_msd_sort_range(
spans: &[&[u8]],
idx: &mut [usize],
aux: &mut [usize],
lo: usize,
hi: usize,
depth: usize,
ascending: bool,
) {
let n = hi - lo;
if n <= 1 {
return;
}
// Small buckets (and pathologically deep shared prefixes, which bound
// recursion depth) finish with the stable comparison sort on the suffix:
// every string in this bucket shares its first `depth` bytes, so suffix
// order equals full-string order.
const CUTOFF: usize = 48;
const MAX_DEPTH: usize = 1024;
if n <= CUTOFF || depth >= MAX_DEPTH {
idx[lo..hi].sort_by(|&a, &b| {
let ord = spans[a][depth..].cmp(&spans[b][depth..]);
if ascending { ord } else { ord.reverse() }
});
return;
}
// Bucket keys ordered so iterating 0..=256 visits buckets in output order:
// ascending — EOS first (0), then bytes 1..=256;
// descending — bytes reversed (255-b), then EOS last (256).
let key = |b: &[u8]| -> usize {
if depth < b.len() {
if ascending {
b[depth] as usize + 1
} else {
255 - b[depth] as usize
}
} else if ascending {
0
} else {
256
}
};
let eos_bucket = if ascending { 0 } else { 256 };
let mut counts = [0usize; 258];
for &i in idx[lo..hi].iter() {
counts[key(spans[i]) + 1] += 1;
}
// LCP fast-skip (br-frankenpandas-msdlcp): when every span shares the same
// byte at `depth` — exactly one non-empty bucket, and it is a real byte
// (not EOS) — the counting scatter is an identity permutation of this
// already-stable range and the `copy_from_slice` is pure waste. Descend to
// depth+1 over the same [lo, hi) directly. This makes the sort cost scale
// with the DISTINGUISHING prefix length rather than the full key width, the
// common case for shared-prefix keys (IDs, paths, URLs, timestamps).
// Bit-identical: a single stable bucket leaves `idx` order exactly as the
// scatter+copy would have written it. A lone EOS bucket means every span is
// fully equal at this depth, so the range is already ordered — return.
{
let mut only: Option<usize> = None;
let mut multi = false;
for k in 0..=256usize {
if counts[k + 1] != 0 {
if only.is_some() {
multi = true;
break;
}
only = Some(k);
}
}
if !multi {
if let Some(k) = only
&& k != eos_bucket
{
utf8_msd_sort_range(spans, idx, aux, lo, hi, depth + 1, ascending);
}
return;
}
}
for k in 1..258 {
counts[k] += counts[k - 1];
}
// counts[k] = start offset of bucket k within [lo, hi).
let mut offsets = counts;
for &i in idx[lo..hi].iter() {
let k = key(spans[i]);
aux[lo + offsets[k]] = i;
offsets[k] += 1;
}
idx[lo..hi].copy_from_slice(&aux[lo..hi]);
// Recurse into byte buckets; the EOS bucket holds fully-equal strings
// (same first `depth` bytes and length == depth) already in original
// relative order — nothing to sort.
for k in 0..257 {
if k == eos_bucket {
continue;
}
let b_lo = lo + counts[k];
let b_hi = lo + counts[k + 1];
if b_hi - b_lo > 1 {
utf8_msd_sort_range(spans, idx, aux, b_lo, b_hi, depth + 1, ascending);
}
}
}
fn normalized_float_bits(value: f64) -> u64 {
let normalized = if value == 0.0 { 0.0 } else { value };
normalized.to_bits()
}
fn interval_key(interval: &Interval) -> (u64, u64, IntervalClosed) {
(
normalized_float_bits(interval.left),
normalized_float_bits(interval.right),
interval.closed,
)
}
/// Hashable membership key for a non-missing scalar — the same equivalence
/// `Column::unique` uses (Float64 ±0.0 normalized to one key). `None` for
/// missing values. Lets the np set-ops (`setdiff1d`/`intersect1d`/`setxor1d`/
/// `in1d`) replace an O(N·M) linear `semantic_eq` scan over the other operand
/// with an O(1) hash-set probe. Because every operand is first passed through
/// `unique()` (which dedups by this exact key) and missing/NaN values are
/// filtered out, key equality matches the `semantic_eq` test on the values that
/// actually flow through.
#[derive(Hash, PartialEq, Eq)]
enum SetMemberKey<'a> {
Bool(bool),
Int64(i64),
FloatBits(u64),
Utf8(&'a str),
Timedelta64(i64),
Datetime64(i64),
Period(i64, PeriodFreq),
Interval(u64, u64, IntervalClosed),
}
fn set_member_key(v: &Scalar) -> Option<SetMemberKey<'_>> {
Some(match v {
Scalar::Bool(b) => SetMemberKey::Bool(*b),
Scalar::Int64(i) => SetMemberKey::Int64(*i),
Scalar::Float64(f) => {
let norm = if *f == 0.0 { 0.0 } else { *f };
SetMemberKey::FloatBits(norm.to_bits())
}
Scalar::Utf8(s) => SetMemberKey::Utf8(s.as_str()),
Scalar::Timedelta64(v) => SetMemberKey::Timedelta64(*v),
Scalar::Datetime64(v) => SetMemberKey::Datetime64(*v),
Scalar::Period(p) => SetMemberKey::Period(p.ordinal, p.freq),
Scalar::Interval(v) => {
let (left, right, closed) = interval_key(v);
SetMemberKey::Interval(left, right, closed)
}
Scalar::Null(_) => return None,
})
}
#[derive(Debug, Error, Clone, PartialEq)]
pub enum ColumnError {
#[error("column length mismatch: left={left}, right={right}")]
LengthMismatch { left: usize, right: usize },
#[error("{operation} requires exactly {expected} element(s), got {actual}")]
InvalidLength {
operation: &'static str,
expected: usize,
actual: usize,
},
#[error("invalid sorter permutation for column of length {len}: {reason}")]
InvalidSorter { len: usize, reason: String },
#[error("mask must be Bool dtype; found {dtype:?}")]
InvalidMaskType { dtype: DType },
#[error("column dtype mismatch: left={left:?}, right={right:?}")]
DTypeMismatch { left: DType, right: DType },
#[error("Integers to negative integer powers are not allowed.")]
NegativeIntegerPower,
#[error(transparent)]
Type(#[from] TypeError),
}
impl SparseColumn {
pub fn from_dense(dtype: SparseDType, values: Vec<Scalar>) -> Result<Self, ColumnError> {
let len = values.len();
let value_dtype = dtype.value_dtype;
let fill_value = dtype.fill_value.clone();
let mut indices = Vec::new();
let mut sparse_values = Vec::new();
for (idx, value) in values.into_iter().enumerate() {
let value = if value.dtype() == value_dtype || value.dtype() == DType::Null {
Column::normalize_missing_for_dtype(value, value_dtype)
} else {
cast_scalar_owned(value, value_dtype)?
};
if !value.semantic_eq(&fill_value) {
indices.push(idx);
sparse_values.push(value);
}
}
Ok(Self {
dtype,
len,
indices,
values: sparse_values,
})
}
pub fn from_dense_column(dtype: SparseDType, column: &Column) -> Result<Self, ColumnError> {
Self::from_dense(dtype, column.values().to_vec())
}
#[must_use]
pub fn sparse_dtype(&self) -> &SparseDType {
&self.dtype
}
#[must_use]
pub fn value_dtype(&self) -> DType {
self.dtype.value_dtype
}
#[must_use]
pub fn fill_value(&self) -> &Scalar {
&self.dtype.fill_value
}
#[must_use]
pub fn len(&self) -> usize {
self.len
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[must_use]
pub fn indices(&self) -> &[usize] {
&self.indices
}
#[must_use]
pub fn stored_values(&self) -> &[Scalar] {
&self.values
}
#[must_use]
pub fn npoints(&self) -> usize {
self.values.len()
}
#[must_use]
pub fn density(&self) -> f64 {
if self.len == 0 {
0.0
} else {
self.values.len() as f64 / self.len as f64
}
}
#[must_use]
pub fn to_dense_values(&self) -> Vec<Scalar> {
let mut values = vec![self.dtype.fill_value.clone(); self.len];
for (&idx, value) in self.indices.iter().zip(self.values.iter()) {
values[idx] = value.clone();
}
values
}
pub fn to_dense_column(&self) -> Result<Column, ColumnError> {
Column::new(self.dtype.value_dtype, self.to_dense_values())
}
}
fn saturating_i64_to_usize(value: i64) -> usize {
if value <= 0 {
0
} else {
usize::try_from(value).unwrap_or(usize::MAX)
}
}
fn saturating_i64_abs_to_usize(value: i64) -> usize {
usize::try_from(value.unsigned_abs()).unwrap_or(usize::MAX)
}
fn normalize_head_take(n: i64, len: usize) -> usize {
if n >= 0 {
saturating_i64_to_usize(n).min(len)
} else {
len.saturating_sub(saturating_i64_abs_to_usize(n))
}
}
fn normalize_tail_window(n: i64, len: usize) -> (usize, usize) {
if n >= 0 {
let take = saturating_i64_to_usize(n).min(len);
(len - take, take)
} else {
let skip = saturating_i64_abs_to_usize(n).min(len);
(skip, len - skip)
}
}
fn round_i64_negative_decimals(value: i64, decimals: i32) -> i64 {
debug_assert!(decimals < 0);
let factor = match 10_i128.checked_pow(decimals.unsigned_abs()) {
Some(factor) => factor,
None => return 0,
};
let magnitude = i128::from(value).abs();
let quotient = magnitude / factor;
let remainder = magnitude % factor;
let rounded_magnitude = match (remainder * 2).cmp(&factor) {
std::cmp::Ordering::Less => quotient * factor,
std::cmp::Ordering::Greater => (quotient + 1) * factor,
std::cmp::Ordering::Equal if quotient % 2 == 0 => quotient * factor,
std::cmp::Ordering::Equal => (quotient + 1) * factor,
};
let rounded = if value < 0 {
-rounded_magnitude
} else {
rounded_magnitude
};
match i64::try_from(rounded) {
Ok(value) => value,
Err(_) if rounded < 0 => i64::MIN,
Err(_) => i64::MAX,
}
}
impl Column {
fn clone_dense_values_from_cache(&self) -> Option<ScalarValues> {
if self.validity.len() != self.values.len()
|| self.validity.count_valid() != self.values.len()
{
return None;
}
match (&self.data, self.dtype) {
(Some(ColumnData::Bool(data)), DType::Bool) if data.len() == self.values.len() => {
// Carry the contiguous bool buffer through the clone as a lazy
// all-valid backing (mirrors the Float64 arm) so `as_bool_slice`
// stays available on the clone — otherwise every bool dense fast
// path (filter masks, duplicated, isin) bails after a clone. The
// Scalar view materializes identically (`map(Scalar::Bool)`) on
// demand. BoolNullable is excluded: an all-valid clone of a
// nullable-bool column must stay Eager so its dtype-tagged Scalar
// view is preserved.
Some(ScalarValues::lazy_all_valid_bool_arc(Arc::clone(data)))
}
(Some(ColumnData::Int64(data)), DType::Int64) if data.len() == self.values.len() => {
// Carry the contiguous i64 buffer through the clone as a lazy
// all-valid backing (mirrors the Float64 arm) so `as_i64_slice`
// stays available on the clone. Previously the clone eagerly
// materialized `Vec<Scalar::Int64>`, which both cost a full
// Scalar build AND dropped slice availability — so cloned Int64
// columns silently missed every dense/direct-address fast path
// (groupby, value_counts, dedup, joins). Bit-identical Scalar
// view (`map(Scalar::Int64)`) materializes on demand.
// Int64Nullable is excluded to preserve its dtype-tagged view.
Some(ScalarValues::lazy_all_valid_int64_arc(Arc::clone(data)))
}
(Some(ColumnData::Float64(data)), DType::Float64)
if data.len() == self.values.len() =>
{
Some(ScalarValues::lazy_all_valid_float64_arc_with_finite(
Arc::clone(data),
Some(data.iter().all(|value| value.is_finite())),
))
}
(Some(ColumnData::Timedelta64(data)), DType::Timedelta64)
if data.len() == self.values.len() =>
{
Some(ScalarValues::from_vec(
data.iter().copied().map(Scalar::Timedelta64).collect(),
))
}
(Some(ColumnData::Datetime64(data)), DType::Datetime64)
if data.len() == self.values.len() =>
{
Some(ScalarValues::from_vec(
data.iter().copied().map(Scalar::Datetime64).collect(),
))
}
(Some(ColumnData::Period(data, freq)), DType::Period)
if data.len() == self.values.len() =>
{
let freq = *freq;
Some(ScalarValues::from_vec(
data.iter()
.copied()
.map(|ord| Scalar::Period(Period::new(ord, freq)))
.collect(),
))
}
_ => None,
}
}
fn cached_data_for_values(dtype: DType, values: &[Scalar]) -> Option<ColumnData> {
match dtype {
DType::Bool
| DType::BoolNullable
| DType::Int64
| DType::Int64Nullable
| DType::Float64
| DType::Timedelta64
| DType::Datetime64
| DType::Period => Some(ColumnData::from_scalars(values, dtype)),
_ => None,
}
}
fn normalize_missing_for_dtype(value: Scalar, dtype: DType) -> Scalar {
match value {
Scalar::Null(NullKind::NaN) => Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaT) => Scalar::Null(NullKind::NaT),
Scalar::Null(_) => Scalar::missing_for_dtype(dtype),
other => other,
}
}
fn from_object_values(values: Vec<Scalar>) -> Self {
let validity = ValidityMask::from_values(&values);
Self {
dtype: DType::Utf8,
values: ScalarValues::from_vec(values),
validity,
data: None,
}
}
/// Construct a column, coercing values to the target dtype.
/// AG-03: takes ownership of the values vec and uses `cast_scalar_owned`
/// to skip cloning when values already have the correct dtype.
pub fn new(dtype: DType, values: Vec<Scalar>) -> Result<Self, ColumnError> {
let preserve_utf8_object_bucket = matches!(dtype, DType::Utf8)
&& values.iter().any(|value| matches!(value, Scalar::Utf8(_)))
&& values
.iter()
.any(|value| !matches!(value, Scalar::Utf8(_) | Scalar::Null(_)));
let needs_coercion = values.iter().any(|v| {
let d = v.dtype();
d != dtype && d != DType::Null
}) && !preserve_utf8_object_bucket;
let coerced = if preserve_utf8_object_bucket {
values
.into_iter()
.map(|value| Self::normalize_missing_for_dtype(value, dtype))
.collect()
} else if needs_coercion {
values
.into_iter()
.map(|value| {
// Constructing a typed column with an explicit dtype is
// STRICT: a non-integer float cannot be coerced to int64
// (pandas DataFrame(dtype='int64') raises "Trying to coerce
// float values to integers"), UNLIKE astype which truncates
// toward zero. astype pre-truncates via cast_scalar, so this
// coercion path only ever sees raw floats from the explicit
// constructor. (br-frankenpandas-8nupg)
if matches!(dtype, DType::Int64 | DType::Int64Nullable)
&& let Scalar::Float64(v) = &value
&& v.is_finite()
&& v.fract() != 0.0
{
return Err(TypeError::LossyFloatToInt { value: *v });
}
cast_scalar_owned(value, dtype)
})
.collect::<Result<Vec<_>, _>>()?
} else {
// No coercion needed: values already match dtype.
// Preserve explicit NaN/NaT markers; remap generic Null to dtype-specific missing.
values
.into_iter()
.map(|value| Self::normalize_missing_for_dtype(value, dtype))
.collect()
};
let validity = ValidityMask::from_values(&coerced);
let data = Self::cached_data_for_values(dtype, &coerced);
let values = match (&data, dtype, validity.all()) {
(Some(ColumnData::Bool(data)), DType::Bool, true) => {
ScalarValues::lazy_all_valid_bool_arc(Arc::clone(data))
}
(Some(ColumnData::Int64(data)), DType::Int64, true) => {
ScalarValues::lazy_all_valid_int64_arc(Arc::clone(data))
}
_ => ScalarValues::from_vec(coerced),
};
Ok(Self {
dtype,
validity,
data,
values,
})
}
fn from_inferred_float64_values(values: Vec<Scalar>) -> Result<Self, ColumnError> {
// Coerce to f64 while tracking whether the column is "canonical NaN-missing"
// (every missing slot is EXACTLY Null(NaN) — no Null(NaT)/Null(Null), and no
// present Float64(NaN) which is `is_missing` yet a distinct Scalar variant).
// This is the pandas-faithful Float64 case (float missing is always NaN).
// When it holds, a raw f64 buffer (with a 0.0 SENTINEL at missing slots) +
// validity fully reproduces every Scalar via the LazyNullableFloat64 backing
// — which every typed fast path (take_positions/sort/dedup/...) recognizes,
// unlike the Eager ColumnData::Float64+from_vec representation whose per-slot
// NullKind forces a per-row Scalar::clone gather (take was 13x slower).
// The 0.0 sentinel is REQUIRED: LazyNullableFloat64.values() emits
// Float64(datum) when `validity || datum.is_nan()`, so a NaN sentinel at a
// missing slot would wrongly materialize Float64(NaN) instead of Null(NaN).
let mut fdata: Vec<f64> = Vec::with_capacity(values.len());
let mut canonical_nan_missing = true;
let mut coerced: Vec<Scalar> = Vec::with_capacity(values.len());
for value in values {
let c = match value {
Scalar::Null(kind) => Scalar::Null(kind),
other => cast_scalar_owned(other, DType::Float64)?,
};
match &c {
Scalar::Float64(x) => {
fdata.push(*x);
if x.is_nan() {
canonical_nan_missing = false; // present Float64(NaN): keep Eager
}
}
Scalar::Null(NullKind::NaN) => fdata.push(0.0), // 0.0 sentinel, NOT NaN
_ => {
fdata.push(0.0);
canonical_nan_missing = false; // Null(NaT)/Null(Null): keep Eager
}
}
coerced.push(c);
}
let validity = ValidityMask::from_values(&coerced);
if canonical_nan_missing {
// Bit-identical: present ⇒ Float64(fdata[i]) == coerced Float64; missing
// ⇒ validity-clear + 0.0 datum ⇒ Null(NaN) == coerced Null(NaN).
return Ok(Self::from_f64_values_with_validity(fdata, validity));
}
let data = Self::cached_data_for_values(DType::Float64, &coerced);
let values = match (&data, validity.all()) {
(Some(ColumnData::Float64(data)), true) => {
ScalarValues::lazy_all_valid_float64_arc_with_finite(
Arc::clone(data),
Some(data.iter().all(|value| value.is_finite())),
)
}
_ => ScalarValues::from_vec(coerced),
};
Ok(Self {
dtype: DType::Float64,
validity,
data,
values,
})
}
pub fn from_values(values: Vec<Scalar>) -> Result<Self, ColumnError> {
if matches!(values.first(), Some(Scalar::Float64(_))) {
let mut data = Vec::with_capacity(values.len());
let mut all_float64 = true;
let mut has_nan = false;
let mut all_finite = true;
for value in &values {
let Scalar::Float64(value) = value else {
all_float64 = false;
break;
};
has_nan |= value.is_nan();
all_finite &= value.is_finite();
data.push(*value);
}
if all_float64 {
return Ok(Self::from_f64_values_with_finite_witness(
data, has_nan, all_finite,
));
}
}
let dtype = match infer_dtype(&values) {
Ok(dtype) => dtype,
Err(TypeError::IncompatibleDtypes { .. }) => {
return Ok(Self::from_object_values(values));
}
Err(err) => return Err(ColumnError::Type(err)),
};
if dtype == DType::Float64 {
return Self::from_inferred_float64_values(values);
}
Self::new(dtype, values)
}
/// Build an all-valid Int64 column from already-typed contiguous values.
///
/// This carries parser/vector-kernel dtype proofs directly into the
/// columnar representation and delays `Scalar` materialization until a
/// caller explicitly asks for scalar values.
#[must_use]
pub fn from_i64_values(data: Vec<i64>) -> Self {
let len = data.len();
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_all_valid_int64(data),
validity: ValidityMask::all_valid(len),
data: None,
}
}
/// Like [`from_i64_values`] but MOVES the `Vec<i64>` into the backing (one
/// `Arc::new`) instead of `Arc::from(Vec)`'s alloc+memcpy (~28ms/5M). The i64
/// sibling of [`from_f64_values_owned`]; all-valid (i64 has no NaN sentinel).
#[must_use]
pub fn from_i64_values_owned(data: Vec<i64>) -> Self {
let len = data.len();
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_all_valid_int64_owned(data),
validity: ValidityMask::all_valid(len),
data: None,
}
}
/// Build an all-valid Int64 column from immutable chunks that are already
/// in output row order. Semantically identical to concatenating the chunks
/// into one `Vec<i64>` and calling [`Self::from_i64_values`], but defers
/// the destination buffer until a typed or scalar consumer needs it.
#[doc(hidden)]
#[must_use]
pub fn from_i64_all_valid_chunks(chunks: Vec<(Arc<[i64]>, usize, usize)>, len: usize) -> Self {
debug_assert_eq!(
chunks
.iter()
.map(|(_, _, chunk_len)| *chunk_len)
.sum::<usize>(),
len
);
let chunks: Vec<Int64Chunk> = chunks
.into_iter()
.map(|(data, start, chunk_len)| Int64Chunk::new(data, start, chunk_len))
.collect();
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_all_valid_int64_chunks(Arc::from(chunks), len),
validity: ValidityMask::all_valid(len),
data: None,
}
}
/// Build an all-valid `Datetime64` column from a `Vec<i64>` of nanosecond
/// epochs (br-frankenpandas-j5150). Caller guarantees no `Timestamp::NAT`
/// sentinel (all rows present); semantically identical to
/// `Column::new(DType::Datetime64, data.map(Scalar::Datetime64))` but defers
/// the per-row `Scalar::Datetime64` boxing until a Scalar view is read.
#[must_use]
#[doc(hidden)]
pub fn from_datetime64_values(data: Vec<i64>) -> Self {
let len = data.len();
Self {
dtype: DType::Datetime64,
values: ScalarValues::lazy_all_valid_datetime64(data),
validity: ValidityMask::all_valid(len),
data: None,
}
}
/// Build an all-valid Period column from ordinals and a uniform frequency,
/// deferring `Scalar::Period` boxing until a scalar view is requested.
#[must_use]
#[doc(hidden)]
pub fn from_period_values_owned(data: Vec<i64>, freq: PeriodFreq) -> Self {
let len = data.len();
Self {
dtype: DType::Period,
values: ScalarValues::lazy_all_valid_period_owned(data, freq),
validity: ValidityMask::all_valid(len),
data: None,
}
}
/// Build an all-valid Utf8 column from a contiguous byte buffer + n+1
/// offsets (br-frankenpandas-2krr0). `bytes[offsets[i]..offsets[i+1]]`
/// must be valid UTF-8 for every row — string-output ops guarantee this
/// by writing only `&str` data. Semantically identical to
/// `Column::new(DType::Utf8, scalars)` over the same strings, but the
/// per-row `String`/`Scalar` boxing is deferred until a consumer reads
/// the Scalar view.
#[must_use]
#[doc(hidden)]
pub fn from_utf8_contiguous(bytes: Vec<u8>, offsets: Vec<usize>) -> Self {
let len = offsets.len().saturating_sub(1);
Self {
dtype: DType::Utf8,
values: ScalarValues::lazy_contiguous_utf8(bytes, offsets),
validity: ValidityMask::all_valid(len),
data: None,
}
}
/// Build an all-valid fixed-width lowercase-hex Utf8 sequence and seed its
/// immutable ordered-join certificate.
///
/// Semantically this is identical to
/// `from_utf8_contiguous(prefix + format!("{start + row:0hex_width$x}"))`
/// for `row in 0..len`, but the producer carries the exact construction
/// witness so ordered joins do not rediscover it by scanning every row.
#[must_use]
#[doc(hidden)]
pub fn from_lower_hex_sequence_utf8(
prefix: &[u8],
start: u64,
len: usize,
hex_width: usize,
) -> Option<Self> {
let values = ScalarValues::lazy_lower_hex_sequence_utf8(prefix, start, len, hex_width)?;
Some(Self {
dtype: DType::Utf8,
values,
validity: ValidityMask::all_valid(len),
data: None,
})
}
/// Build an all-valid Int64 column from `(value, run_len)` repeat runs
/// (br-frankenpandas-3ad4n). Semantically identical to
/// `from_i64_values(expanded)` where `expanded` repeats each `value`
/// `run_len` times, but carries only O(runs) memory until a consumer
/// forces the contiguous buffer or Scalar view.
#[must_use]
#[doc(hidden)]
pub fn from_i64_repeat_runs(runs: Vec<(i64, usize)>) -> Self {
let total_len = runs.iter().map(|&(_, run_len)| run_len).sum();
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_repeat_runs_int64(runs, total_len),
validity: ValidityMask::all_valid(total_len),
data: None,
}
}
/// Build an all-valid Int64 column from per-run values plus a shared
/// run-length descriptor. Semantically identical to
/// [`Column::from_i64_repeat_runs`] over `run_values.zip(run_lens)`, but
/// dense join lanes can share `run_lens` across columns.
#[must_use]
#[doc(hidden)]
pub fn from_i64_repeat_values_run_lengths(
run_values: Vec<i64>,
run_lens: Arc<[usize]>,
) -> Self {
let total_len = run_lens.iter().sum();
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_repeat_values_int64(run_values, run_lens, total_len),
validity: ValidityMask::all_valid(total_len),
data: None,
}
}
/// Build an all-valid Int64 column from repeated slices of one shared
/// tape. Semantically identical to concatenating
/// `data[start..start+len]` for each segment and calling
/// [`Column::from_i64_values`].
#[must_use]
#[doc(hidden)]
pub fn from_i64_repeated_slices(data: Vec<i64>, segments: Vec<(usize, usize)>) -> Self {
let total_len = segments.iter().map(|&(_, len)| len).sum();
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_repeated_slices_int64(data, segments, total_len),
validity: ValidityMask::all_valid(total_len),
data: None,
}
}
/// Shared-descriptor counterpart of [`Column::from_i64_repeated_slices`].
/// `total_len` must equal the sum of all segment lengths.
#[must_use]
#[doc(hidden)]
pub fn from_i64_repeated_slices_shared(
data: Vec<i64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
) -> Self {
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_repeated_slices_int64_shared(data, segments, total_len),
validity: ValidityMask::all_valid(total_len),
data: None,
}
}
/// Float64 counterpart of [`Column::from_i64_repeat_values_run_lengths`]
/// (br-frankenpandas-jzrem): an all-valid Float64 dense-join LEFT lane
/// carried as per-run values + a shared run-length descriptor, materialized
/// to `Scalar::Float64` only on read. `run_values` must be NaN-free (the
/// caller gathers them from an `as_f64_slice` source, which is all-valid).
#[must_use]
#[doc(hidden)]
pub fn from_f64_repeat_values_run_lengths(
run_values: Vec<f64>,
run_lens: Arc<[usize]>,
) -> Self {
let total_len = run_lens.iter().sum();
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_repeat_values_float64(run_values, run_lens, total_len),
validity: ValidityMask::all_valid(total_len),
data: None,
}
}
/// Float64 counterpart of [`Column::from_i64_repeated_slices_shared`]
/// (br-frankenpandas-jzrem): an all-valid Float64 dense-join RIGHT lane
/// carried as repeated slices of one shared bucket-order value tape,
/// materialized to `Scalar::Float64` only on read. `data` must be NaN-free.
#[must_use]
#[doc(hidden)]
pub fn from_f64_repeated_slices_shared(
data: Vec<f64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
) -> Self {
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_repeated_slices_float64_shared(data, segments, total_len),
validity: ValidityMask::all_valid(total_len),
data: None,
}
}
/// Validity mask for a nullable repeated-slices lane. Null runs are stored
/// as sparse invalid ranges, deferring the O(output_len / 64) packed bitmap
/// write until a cold caller needs concrete mask algebra or serialization.
fn nullable_repeated_slices_validity(
segments: &[(usize, usize)],
total_len: usize,
) -> ValidityMask {
let mut invalid_ranges = Vec::new();
let mut pos = 0usize;
for &(start, len) in segments {
if start == usize::MAX && len > 0 {
invalid_ranges.push((pos, len));
}
pos += len;
}
ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), total_len)
}
fn nullable_repeat_values_validity(
run_valid: &[bool],
run_lens: &[usize],
total_len: usize,
) -> ValidityMask {
let mut invalid_ranges = Vec::new();
let mut pos = 0usize;
for (&valid, &run_len) in run_valid.iter().zip(run_lens.iter()) {
if !valid && run_len > 0 {
invalid_ranges.push((pos, run_len));
}
pos += run_len;
}
ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), total_len)
}
/// Null-introducing Int64 dense-join lane (br-frankenpandas-yiqv5): repeated
/// slices of a bucket-order value tape, with `start == usize::MAX` segments
/// marking missing (`Null(NullKind::Null)`) runs. Materializes the same
/// Scalars + validity as the per-row `reindex_by_positions` gather, but
/// carries only an O(matched + nulls) descriptor until read.
#[must_use]
#[doc(hidden)]
pub fn from_i64_nullable_repeated_slices_shared(
data: Vec<i64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
) -> Self {
let validity = Self::nullable_repeated_slices_validity(&segments, total_len);
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_nullable_repeated_slices_int64(data, segments, total_len),
validity,
data: None,
}
}
/// Float64 sibling of [`Column::from_i64_nullable_repeated_slices_shared`]
/// (br-frankenpandas-yiqv5); missing runs are `Null(NullKind::NaN)`.
#[must_use]
#[doc(hidden)]
pub fn from_f64_nullable_repeated_slices_shared(
data: Vec<f64>,
segments: Arc<[(usize, usize)]>,
total_len: usize,
) -> Self {
let validity = Self::nullable_repeated_slices_validity(&segments, total_len);
Self::from_f64_nullable_repeated_slices_shared_with_sparse_validity(
data, segments, validity, total_len,
)
}
/// Variant of [`Column::from_f64_nullable_repeated_slices_shared`] for
/// callers that already computed the sparse null-run witness while building
/// the segment descriptor.
#[must_use]
#[doc(hidden)]
pub fn from_f64_nullable_repeated_slices_shared_with_sparse_validity(
data: Vec<f64>,
segments: Arc<[(usize, usize)]>,
validity: ValidityMask,
total_len: usize,
) -> Self {
debug_assert_eq!(validity.len(), total_len);
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_nullable_repeated_slices_float64(data, segments, total_len),
validity,
data: None,
}
}
/// Null-introducing repeat-VALUES Float64 lane (br-frankenpandas-yiqv5): the
/// broadcast counterpart of [`Column::from_f64_nullable_repeated_slices_shared`]
/// for an outer merge's promoted left lane. `run_valid[k] == false` marks
/// `run_lens[k]` missing rows (`Null(NullKind::NaN)`); the validity mask is
/// rebuilt from the run descriptors.
#[must_use]
#[doc(hidden)]
pub fn from_f64_nullable_repeat_values_run_lengths(
run_values: Vec<f64>,
run_valid: Arc<[bool]>,
run_lens: Arc<[usize]>,
total_len: usize,
) -> Self {
let validity = Self::nullable_repeat_values_validity(&run_valid, &run_lens, total_len);
Self::from_f64_nullable_repeat_values_run_lengths_with_sparse_validity(
run_values, run_valid, run_lens, validity, total_len,
)
}
/// Variant of [`Column::from_f64_nullable_repeat_values_run_lengths`] for
/// dense-join builders that already carry the sparse null-run witness.
#[must_use]
#[doc(hidden)]
pub fn from_f64_nullable_repeat_values_run_lengths_with_sparse_validity(
run_values: Vec<f64>,
run_valid: Arc<[bool]>,
run_lens: Arc<[usize]>,
validity: ValidityMask,
total_len: usize,
) -> Self {
debug_assert_eq!(validity.len(), total_len);
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_nullable_repeat_values_float64(
run_values, run_valid, run_lens, total_len,
),
validity,
data: None,
}
}
/// Source-position backed variant of
/// [`Column::from_f64_nullable_repeated_slices_shared_with_sparse_validity`]
/// for promoted Int64 lanes. Non-null output rows read
/// `source[positions[k]] as f64` lazily, matching the eager bucket-order tape
/// conversion without constructing that `Vec<f64>` in the merge hot path.
#[must_use]
#[doc(hidden)]
pub fn from_i64_nullable_repeated_positions_as_f64_with_sparse_validity(
source: Arc<[i64]>,
positions: Arc<[usize]>,
segments: Arc<[(usize, usize)]>,
validity: ValidityMask,
total_len: usize,
) -> Self {
debug_assert_eq!(validity.len(), total_len);
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_nullable_repeated_positions_i64_as_float64(
source, positions, segments, total_len,
),
validity,
data: None,
}
}
/// Dense-cycle witness variant of
/// [`Column::from_i64_nullable_repeated_positions_as_f64_with_sparse_validity`]
/// for promoted RIGHT lanes in certified dense-cycle OUTER joins. It avoids
/// constructing the bucket-order right-position tape in the join hot path.
#[must_use]
#[doc(hidden)]
pub fn from_i64_nullable_dense_cycle_right_as_f64_with_sparse_validity(
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
min_key: i64,
span: usize,
validity: ValidityMask,
total_len: usize,
) -> Self {
debug_assert_eq!(validity.len(), total_len);
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_nullable_dense_cycle_right_i64_as_float64(
source,
left_witness,
right_witness,
min_key,
span,
total_len,
),
validity,
data: None,
}
}
/// Dense-cycle witness variant of
/// [`Column::from_i64_nullable_repeat_positions_as_f64_with_sparse_validity`]
/// for promoted LEFT lanes in certified dense-cycle OUTER joins. It avoids
/// constructing per-run left-position/run-length descriptors in the join
/// hot path.
#[must_use]
#[doc(hidden)]
pub fn from_i64_nullable_dense_cycle_left_as_f64_with_sparse_validity(
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
min_key: i64,
span: usize,
validity: ValidityMask,
total_len: usize,
) -> Self {
debug_assert_eq!(validity.len(), total_len);
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_nullable_dense_cycle_left_i64_as_float64(
source,
left_witness,
right_witness,
min_key,
span,
total_len,
),
validity,
data: None,
}
}
/// Probe-order dense-cycle repeat lane for one-sided joins. This is the
/// kept side of a LEFT/RIGHT join: row `p` from the probe side is repeated
/// once per matching build-side duplicate, or once when unmatched.
#[must_use]
#[doc(hidden)]
pub fn from_i64_dense_cycle_probe_repeat(
source: Arc<[i64]>,
probe_witness: Int64DenseCycleWitness,
build_witness: Int64DenseCycleWitness,
total_len: usize,
) -> Self {
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_dense_cycle_probe_repeat_int64(
source,
probe_witness,
build_witness,
total_len,
),
validity: ValidityMask::all_valid(total_len),
data: None,
}
}
/// Dense-cycle LEFT-join left lane (all-valid Int64). Equivalent to
/// `from_i64_repeat_runs` over every left row's fanout, but stores only the
/// certified key witnesses and source buffer.
#[must_use]
#[doc(hidden)]
pub fn from_i64_left_join_dense_cycle_left(
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
total_len: usize,
) -> Self {
debug_assert_eq!(source.len(), left_witness.len);
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_left_join_dense_cycle_left_int64(
source,
left_witness,
right_witness,
total_len,
),
validity: ValidityMask::all_valid(total_len),
data: None,
}
}
/// Probe-order dense-cycle nullable build lane for one-sided joins. Matched
/// rows replay the build side in stable duplicate order; unmatched probe
/// rows materialize `Null(NullKind::Null)` under the supplied sparse mask.
#[must_use]
#[doc(hidden)]
pub fn from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
source: Arc<[i64]>,
probe_witness: Int64DenseCycleWitness,
build_witness: Int64DenseCycleWitness,
validity: ValidityMask,
total_len: usize,
) -> Self {
debug_assert_eq!(validity.len(), total_len);
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_nullable_dense_cycle_probe_build_int64(
source,
probe_witness,
build_witness,
total_len,
),
validity,
data: None,
}
}
/// Dense-cycle LEFT-join right lane (nullable Int64). Matched rows replay
/// `offset + k * period` positions from the right source; unmatched left
/// rows materialize as `Null(NullKind::Null)`.
#[must_use]
#[doc(hidden)]
pub fn from_i64_left_join_dense_cycle_right_nullable(
source: Arc<[i64]>,
left_witness: Int64DenseCycleWitness,
right_witness: Int64DenseCycleWitness,
validity: ValidityMask,
total_len: usize,
) -> Self {
debug_assert_eq!(source.len(), right_witness.len);
debug_assert_eq!(validity.len(), total_len);
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_left_join_dense_cycle_right_int64(
source,
left_witness,
right_witness,
total_len,
),
validity,
data: None,
}
}
/// Source-position backed variant of
/// [`Column::from_f64_nullable_repeat_values_run_lengths_with_sparse_validity`]
/// for promoted Int64 left lanes. Valid runs read one source row lazily and
/// repeat the cast Float64 value; invalid runs materialize `Null(NaN)`.
#[must_use]
#[doc(hidden)]
pub fn from_i64_nullable_repeat_positions_as_f64_with_sparse_validity(
source: Arc<[i64]>,
run_positions: Arc<[usize]>,
run_valid: Arc<[bool]>,
run_lens: Arc<[usize]>,
validity: ValidityMask,
total_len: usize,
) -> Self {
debug_assert_eq!(validity.len(), total_len);
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_nullable_repeat_positions_i64_as_float64(
source,
run_positions,
run_valid,
run_lens,
total_len,
),
validity,
data: None,
}
}
/// Build an all-valid Float64 column from already-typed contiguous values.
///
/// This is the typed ingestion counterpart to `Column::new(DType::Float64,
/// Vec<Scalar>)` for sources that have already proven every value is a
/// valid f64.
#[must_use]
/// Build an all-valid Float64 column WITHOUT scanning `data` for NaN. The
/// caller must have already proven `data` is NaN-free (otherwise a NaN slot
/// would wrongly claim valid). Identical to the no-NaN branch of
/// [`Self::from_f64_values`]. (br-frankenpandas-9houf)
#[doc(hidden)]
pub fn from_f64_values_all_valid_unchecked(data: Vec<f64>) -> Self {
let len = data.len();
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64(data),
validity: ValidityMask::all_valid(len),
data: None,
}
}
#[must_use]
#[doc(hidden)]
pub fn from_f64_combine_first_all_valid(
left: Arc<[f64]>,
right: Arc<[f64]>,
left_validity: &ValidityMask,
) -> Self {
let len = left_validity.len();
debug_assert!(left.len() >= len);
debug_assert!(right.len() >= len);
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_combine_first_float64(
left,
right,
Arc::from(left_validity.packed_words_for_scan()),
len,
),
validity: ValidityMask::all_valid(len),
data: None,
}
}
pub fn from_f64_values(data: Vec<f64>) -> Self {
let mut has_nan = false;
let mut all_finite = true;
for value in &data {
has_nan |= value.is_nan();
all_finite &= value.is_finite();
}
Self::from_f64_values_with_finite_witness(data, has_nan, all_finite)
}
/// Like `from_f64_values` but, for the all-valid (no-NaN) case, MOVES the
/// owned `Vec<f64>` into the backing (`Arc::new`, one tiny box) instead of
/// `Arc::from(Vec)`'s cold-buffer realloc-copy (~5.7ms/1M, page-fault-bound).
/// For op OUTPUTS that just wrote a hot Vec (cumsum/cummax/cummin/cumprod)
/// this is a 6-8x op-side win. Bit-identical: the single NaN scan is the same
/// one `from_f64_values` runs, and a NaN-bearing output routes to the
/// identical `from_f64_values` (NaN-as-missing) path. The resulting
/// `LazyAllValidFloat64Vec` backing is semantically identical to
/// `LazyAllValidFloat64` (it just isn't keyed by the Arc<[f64]>-specific
/// take_positions/binary zero-copy fast paths — fine for terminal outputs).
#[must_use]
pub fn from_f64_values_owned(data: Vec<f64>) -> Self {
if data.iter().any(|v| v.is_nan()) {
return Self::from_f64_values(data);
}
let len = data.len();
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64_owned(data),
validity: ValidityMask::all_valid(len),
data: None,
}
}
/// Build a nullable Float64 column from a raw `data` buffer plus an EXPLICIT
/// validity mask, WITHOUT re-deriving validity from NaN. The `LazyNullableFloat64`
/// backing renders each slot as: validity-set ⇒ present `Float64(data)`;
/// cleared-bit-with-NaN-datum ⇒ present `Float64(NaN)`; cleared-bit-with-
/// non-NaN-datum ⇒ `Null(NullKind::NaN)`. This is the only constructor that
/// reproduces the per-element Scalar path's three-way representation for typed
/// nullable arithmetic outputs (a GENERATED NaN must stay a present
/// `Float64(NaN)`, an absent operand must be `Null`). Callers set the validity
/// bit iff the slot is present AND its datum is non-NaN.
#[must_use]
pub fn from_f64_values_nullable(data: Vec<f64>, validity: ValidityMask) -> Self {
debug_assert_eq!(data.len(), validity.len());
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_nullable_float64(data, validity.clone()),
validity,
data: None,
}
}
fn from_f64_values_with_finite_witness(
data: Vec<f64>,
has_nan: bool,
all_finite: bool,
) -> Self {
let len = data.len();
// pandas treats NaN in a float column as MISSING. The Scalar path
// (Column::new -> ValidityMask::from_values) already marks NaN invalid
// via Scalar::is_missing, so this typed-ingestion path must agree —
// otherwise a caller passing NaN gets a column claiming all-valid and
// as_f64_slice would hand the NaN out as a real value. Fast all-valid
// path (cheap u64::MAX fill) when no NaN is present; per-bit mask only
// when one is. (br-frankenpandas-jyhf7)
let validity = if has_nan {
ValidityMask::from_f64(&data)
} else {
ValidityMask::all_valid(len)
};
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64_with_finite(data, Some(all_finite)),
validity,
data: None,
}
}
/// Read the cached all-finite witness of an all-valid Float64 column, if it
/// has already been resolved. Never forces a scan (`None` when unknown).
/// Used by finiteness-preserving maps (e.g. `abs`) to carry the input's
/// witness onto the output for free.
fn f64_finite_witness(&self) -> Option<bool> {
self.values.all_valid_float64_finite_witness()
}
/// Build an all-valid (no-NaN) Float64 column from a values buffer, carrying
/// an optional pre-known all-finite witness WITHOUT scanning. The caller
/// guarantees the buffer has no NaN (NaN ⇒ missing under pandas semantics);
/// `from_f64_values` is the scanning constructor for unproven input.
fn from_f64_all_valid_with_finite_opt(data: Vec<f64>, all_finite: Option<bool>) -> Self {
// Caller has proven all-valid (no NaN), so MOVE the hot output Vec into
// the backing (Arc::new) instead of lazy_all_valid_float64_with_finite's
// Arc::from(Vec) cold-realloc-copy (~5.7ms/1M). Flips abs/fabs/round/neg
// and the other all-valid f64 producers from the arc-copy floor.
let len = data.len();
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64_owned_with_finite(data, all_finite),
validity: ValidityMask::all_valid(len),
data: None,
}
}
fn from_f64_values_owned_with_validity(
data: Vec<f64>,
validity: ValidityMask,
all_finite: Option<bool>,
) -> Self {
debug_assert_eq!(data.len(), validity.len());
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64_owned_with_finite(data, all_finite),
validity,
data: None,
}
}
/// Build an all-valid Float64 column from immutable chunks that are already
/// in output row order. The caller must have proven that every value in
/// every chunk is non-NaN; otherwise pandas missing-value semantics require
/// [`Self::from_f64_values`] instead.
#[doc(hidden)]
#[must_use]
pub fn from_f64_all_valid_chunks(chunks: Vec<(Arc<[f64]>, usize, usize)>, len: usize) -> Self {
debug_assert_eq!(
chunks
.iter()
.map(|(_, _, chunk_len)| *chunk_len)
.sum::<usize>(),
len
);
let chunks: Vec<Float64Chunk> = chunks
.into_iter()
.map(|(data, start, chunk_len)| Float64Chunk::new(data, start, chunk_len))
.collect();
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64_chunks(Arc::from(chunks), len),
validity: ValidityMask::all_valid(len),
data: None,
}
}
/// Build an all-valid Float64 column whose values are the dot product of
/// all-valid finite input columns with one finite right-hand column.
///
/// The caller must prove every operand is finite, so every output slot is
/// valid and NaN-free. Materialization preserves the eager dot kernel's
/// `l = 0..k` accumulation order for each row.
#[doc(hidden)]
#[must_use]
pub fn from_f64_all_valid_dot_product(
a_cols: Vec<(Arc<[f64]>, usize)>,
b_col: Arc<[f64]>,
len: usize,
) -> Self {
debug_assert_eq!(a_cols.len(), b_col.len());
Self::from_f64_all_valid_dot_product_shared(&Float64DotAPanel::new(a_cols, len), b_col, len)
}
/// Build one output column of a dot product against a SHARED left-hand
/// (`A`) panel. `DataFrame::dot` builds the panel ONCE and clones the inner
/// `Arc` per output column (one refcount bump) instead of rebuilding the
/// `k` `Float64DotInput`s + a fresh `Arc<[..]>` for every column — the prior
/// `from_f64_all_valid_dot_product` did the latter `n` times, an O(n·k)
/// Arc-and-alloc construction tax that dominated `df.dot` construction.
#[must_use]
pub fn from_f64_all_valid_dot_product_shared(
a_panel: &Float64DotAPanel,
b_col: Arc<[f64]>,
len: usize,
) -> Self {
debug_assert_eq!(a_panel.0.len(), b_col.len());
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64_dot(Arc::clone(&a_panel.0), b_col, len),
validity: ValidityMask::all_valid(len),
data: None,
}
}
/// Build all columns of a finite all-valid Float64 pairwise corr/cov matrix
/// over a shared lazy plan.
///
/// The caller must prove that every input value is finite and that every
/// output cell is finite under `stat`/`min_periods`. This mirrors the
/// no-NaN branch of `DataFrame`'s eager pairwise matrix kernel, but defers
/// the `O(n_cols^2 * n_rows)` moment/Gram work until a consumer reads the
/// result values.
#[doc(hidden)]
#[must_use]
pub fn from_f64_all_valid_pairwise_stat_matrix_columns(
cols: Vec<(Arc<[f64]>, usize)>,
row_len: usize,
stat: PairwiseFloat64Stat,
min_periods: usize,
) -> Vec<Self> {
let inputs: Vec<Float64PairwiseStatInput> = cols
.into_iter()
.map(|(data, start)| Float64PairwiseStatInput::new(data, start, row_len))
.collect();
let plan = Arc::new(Float64PairwiseStatMatrixPlan::new(
Arc::from(inputs),
row_len,
stat,
min_periods,
));
let n = plan.column_len();
(0..n)
.map(|col| Self {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64_pairwise_stat_matrix_column(
Arc::clone(&plan),
col,
),
validity: ValidityMask::all_valid(n),
data: None,
})
.collect()
}
/// Build a shared lazy row plan for a homogeneous all-valid Float64
/// transpose. Each `(Arc, start)` source is one original column with
/// `row_len` readable rows.
#[doc(hidden)]
#[must_use]
pub fn f64_transpose_rows_plan(
cols: Vec<(Arc<[f64]>, usize)>,
row_len: usize,
) -> Float64TransposeRows {
let inputs: Vec<Float64TransposeInput> = cols
.into_iter()
.map(|(data, start)| Float64TransposeInput::new(data, start, row_len))
.collect();
Float64TransposeRows {
plan: Arc::new(Float64TransposeRowsPlan::new(Arc::from(inputs), row_len)),
}
}
/// Build one all-valid Float64 output row over a shared transpose plan.
/// Scalar and typed reads materialize exactly the eager row-copy order.
#[doc(hidden)]
#[must_use]
pub fn from_f64_transpose_row(plan: &Float64TransposeRows, source_row: usize) -> Self {
debug_assert!(source_row < plan.plan.row_len);
let len = plan.plan.column_len();
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64_transpose_row(
Arc::clone(&plan.plan),
source_row,
),
validity: ValidityMask::all_valid(len),
data: None,
}
}
/// Public (hidden) for fp-join's fused dense outer-merge builder
/// (br-frankenpandas-343ho); invalid slots carry the 0.0-datum convention
/// and materialize `Scalar::Null(NullKind::NaN)`.
#[doc(hidden)]
pub fn from_f64_values_with_validity(data: Vec<f64>, validity: ValidityMask) -> Self {
debug_assert_eq!(data.len(), validity.len());
if validity.all() {
// All-valid → MOVE the Vec into the backing (from_f64_values_owned)
// rather than from_f64_values' Arc::from realloc-copy. Bit-identical:
// _owned falls back to from_f64_values on any stray NaN. Benefits every
// caller whose output happens to carry no missing (bfill/interpolate/…).
return Self::from_f64_values_owned(data);
}
Self {
dtype: DType::Float64,
values: ScalarValues::lazy_nullable_float64(data, validity.clone()),
validity,
data: None,
}
}
/// Nullable Int64 counterpart of `from_f64_values_with_validity`
/// (br-frankenpandas-lt5qx): invalid slots materialize
/// `Scalar::Null(NullKind::Null)` (= `missing_for_dtype(Int64)`), valid
/// slots `Scalar::Int64(data[i])`. Public (hidden) for fp-join's fused
/// dense left-merge builder (br-frankenpandas-7wxoc).
#[doc(hidden)]
pub fn from_i64_values_with_validity(data: Vec<i64>, validity: ValidityMask) -> Self {
debug_assert_eq!(data.len(), validity.len());
if validity.all() {
return Self::from_i64_values_owned(data);
}
Self {
dtype: DType::Int64,
values: ScalarValues::lazy_nullable_int64(data, validity.clone()),
validity,
data: None,
}
}
/// Datetime64 counterpart of [`Self::from_i64_values_with_validity`]: invalid
/// slots materialize `Scalar::Null(NullKind::NaT)` (= `missing_for_dtype`),
/// valid slots `Scalar::Datetime64(data[i])`. All-valid folds to the owned
/// move backing. Used by the null-introducing datetime gather.
#[doc(hidden)]
pub fn from_datetime64_values_with_validity(data: Vec<i64>, validity: ValidityMask) -> Self {
debug_assert_eq!(data.len(), validity.len());
if validity.all() {
return Self {
dtype: DType::Datetime64,
values: ScalarValues::lazy_all_valid_datetime64_owned(data),
validity,
data: None,
};
}
Self {
dtype: DType::Datetime64,
values: ScalarValues::lazy_nullable_datetime64(data, validity.clone()),
validity,
data: None,
}
}
/// Timedelta64 sibling of [`Self::from_datetime64_values_with_validity`].
#[doc(hidden)]
pub fn from_timedelta64_values_with_validity(data: Vec<i64>, validity: ValidityMask) -> Self {
debug_assert_eq!(data.len(), validity.len());
if validity.all() {
return Self {
dtype: DType::Timedelta64,
values: ScalarValues::lazy_all_valid_timedelta64_owned(data),
validity,
data: None,
};
}
Self {
dtype: DType::Timedelta64,
values: ScalarValues::lazy_nullable_timedelta64(data, validity.clone()),
validity,
data: None,
}
}
/// Period sibling of [`Self::from_datetime64_values_with_validity`].
/// Invalid slots materialize as `missing_for_dtype(Period)` (Daily NaT),
/// matching the scalar `reindex_by_positions` fallback.
#[doc(hidden)]
pub fn from_period_values_with_validity(
data: Vec<i64>,
freq: PeriodFreq,
validity: ValidityMask,
) -> Self {
debug_assert_eq!(data.len(), validity.len());
if validity.all() {
return Self::from_period_values_owned(data, freq);
}
Self {
dtype: DType::Period,
values: ScalarValues::lazy_nullable_period(
data,
freq,
PeriodFreq::Daily,
validity.clone(),
),
validity,
data: None,
}
}
/// Build a `Bool` column from already-typed contiguous values plus a
/// validity mask (br-frankenpandas-rcvpj). The nullable counterpart of
/// [`Column::from_bool_values`]: an all-valid mask folds to the contiguous
/// all-valid backing, otherwise invalid slots materialize
/// `Scalar::Null(NullKind::Null)` (= `missing_for_dtype(Bool)`), exactly
/// what `Column::from_values` over the equivalent `[Bool/Null]` scalars
/// produces — but defers the per-row `Scalar` boxing + dtype inference.
/// Used by null-bearing comparison / where / mask / isin outputs.
#[must_use]
pub fn from_bool_values_with_validity(data: Vec<bool>, validity: ValidityMask) -> Self {
debug_assert_eq!(data.len(), validity.len());
if validity.all() {
return Self::from_bool_values(data);
}
Self {
dtype: DType::Bool,
values: ScalarValues::lazy_nullable_bool(data, validity.clone()),
validity,
data: None,
}
}
/// Nullable Utf8 counterpart of `from_f64_values_with_validity`
/// (br-frankenpandas-cmxjz): one rolling byte buffer + n+1 offsets (a valid
/// row `i` is `bytes[offsets[i]..offsets[i+1]]`) + a validity mask; invalid
/// slots materialize `Scalar::Null(NullKind::Null)` (=
/// `missing_for_dtype(Utf8)`) and carry an empty span. An all-valid mask
/// folds to the contiguous all-valid backing. Public (hidden) for fp-join's
/// null-introducing string-column gather (left/right/outer merge, reindex).
#[doc(hidden)]
pub fn from_utf8_values_with_validity(
bytes: Vec<u8>,
offsets: Vec<usize>,
validity: ValidityMask,
) -> Self {
debug_assert_eq!(offsets.len() - 1, validity.len());
if validity.all() {
return Self::from_utf8_contiguous(bytes, offsets);
}
Self {
dtype: DType::Utf8,
values: ScalarValues::lazy_nullable_utf8(bytes, offsets, validity.clone()),
validity,
data: None,
}
}
/// Deferred null-introducing Utf8 gather (br-frankenpandas-yiqv5): wrap an
/// all-valid `Eager` Utf8 `source` plus a `positions` plan (`usize::MAX` ==
/// missing) as a lazy column. The validity mask is built eagerly by the
/// caller (O(output) bits, cheap), but the gathered string `Scalar`s
/// materialize only when a consumer reads the values — so a join output
/// value lane whose bytes are never read costs O(output) plan + O(1) source
/// share and nothing more.
fn from_utf8_lazy_gather(
source: Arc<[Scalar]>,
positions: Arc<[usize]>,
validity: ValidityMask,
) -> Self {
debug_assert_eq!(positions.len(), validity.len());
Self {
dtype: DType::Utf8,
values: ScalarValues::lazy_gather_utf8(source, positions),
validity,
data: None,
}
}
/// Build a deferred null-introducing Utf8 gather from a caller-proven
/// shared position plan. This is the same representation as
/// [`Self::reindex_by_positions`] uses for all-valid eager Utf8 sources,
/// but lets join builders compute the nullable plan once and share it
/// across many output columns with identical row positions.
#[doc(hidden)]
pub fn reindex_eager_utf8_with_shared_plan(
&self,
positions: Arc<[usize]>,
validity: ValidityMask,
) -> Option<Self> {
debug_assert_eq!(positions.len(), validity.len());
if self.dtype != DType::Utf8 || !self.validity.all() {
return None;
}
let source = self.values.eager_arc()?;
debug_assert!(
positions
.iter()
.all(|&pos| pos == usize::MAX || pos < source.len())
);
Some(Self::from_utf8_lazy_gather(
Arc::clone(source),
positions,
validity,
))
}
/// Build a deferred nullable Utf8 gather for the ordered-join shape where
/// valid rows read one contiguous source range and missing rows form only a
/// prefix and/or suffix.
#[doc(hidden)]
pub fn reindex_eager_utf8_with_nullable_range(
&self,
null_prefix: usize,
source_start: usize,
source_len: usize,
null_suffix: usize,
) -> Option<Self> {
if self.dtype != DType::Utf8 || !self.validity.all() {
return None;
}
let source = self.values.eager_arc()?;
source_start
.checked_add(source_len)
.filter(|&end| end <= source.len())?;
let len = null_prefix
.checked_add(source_len)?
.checked_add(null_suffix)?;
let mut invalid_ranges = Vec::with_capacity(2);
if null_prefix > 0 {
invalid_ranges.push((0, null_prefix));
}
if null_suffix > 0 {
invalid_ranges.push((null_prefix + source_len, null_suffix));
}
Some(Self {
dtype: DType::Utf8,
values: ScalarValues::lazy_nullable_utf8_range(
Arc::clone(source),
null_prefix,
source_start,
source_len,
null_suffix,
),
validity: ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), len),
data: None,
})
}
/// Null-introducing positional reindex with Float64 promotion
/// (br-frankenpandas-1bvcl): gather an all-valid Int64/Float64 column by
/// `Option<usize>` positions into a nullable Float64 column without the
/// per-row `Scalar` clone + `cast_scalar_owned` + `Column::new`
/// revalidation. `None` (or out-of-range) slots take the established
/// aligned-binary gap convention — 0.0 datum + invalid bit — which
/// materializes `Scalar::Null(NullKind::NaN)`, exactly what the eager
/// path's `missing_for_dtype(Float64)` cast produces; matched Int64 slots
/// use `v as f64`, the same conversion as the `cast_scalar_owned`
/// Int64->Float64 arm. Returns `None` for any other source (nullable,
/// non-numeric), where the caller's `Scalar` path is the one that must
/// reason about missingness.
#[must_use]
#[doc(hidden)]
pub fn reindex_promote_float64_by_optional_positions(
&self,
positions: &[Option<usize>],
) -> Option<Self> {
enum TypedSource<'a> {
Int64(&'a [i64]),
Float64(&'a [f64]),
}
let source = if let Some(slice) = self.as_i64_slice() {
TypedSource::Int64(slice)
} else {
let slice = self.as_f64_slice()?;
TypedSource::Float64(slice)
};
let n = positions.len();
let len = self.len();
let mut data = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, slot) in positions.iter().enumerate() {
match slot {
Some(idx) if *idx < len => {
let value = match source {
TypedSource::Int64(slice) => slice[*idx] as f64,
TypedSource::Float64(slice) => slice[*idx],
};
data.push(value);
// All-valid sources carry no NaN (from_f64_values marks
// NaN invalid), so every matched slot is valid.
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
_ => data.push(0.0),
}
}
Some(Self::from_f64_values_with_validity(
data,
ValidityMask::from_words(words, n),
))
}
/// Borrow the column's contiguous `f64` buffer when this is an all-valid
/// `Float64` column, enabling typed/SIMD reductions without the per-element
/// `Scalar` match. Returns `None` for any other dtype or when the column
/// has missing values — callers fall back to the `Scalar` path, which is
/// the only path that must reason about missingness. Per
/// br-frankenpandas-lei31.
#[must_use]
/// Borrow the column's contiguous `f64` buffer **and** its validity mask
/// when this is a Float64 column with a directly-addressable backing
/// (all-valid or nullable). Unlike [`Column::as_f64_slice`] this also serves
/// nullable columns, so callers that handle missingness explicitly (e.g.
/// `combine_first`, `fillna`) can read raw `f64` + validity instead of
/// materializing `Vec<Scalar>`. The data for a missing slot is the stored
/// datum (0.0 by the nullable convention); the validity bit is authoritative.
/// Returns `None` for view/run-length/strided backings that are not a single
/// contiguous `[f64]`.
/// Typed view of a CANONICAL nullable-Float64 column: `Some((data,
/// validity))` only for lazy typed backings whose Scalar emission is
/// fully determined by the pair via the shared rule
/// (`validity.get(i) || data[i].is_nan()` → `Float64(data[i])`, else
/// `Null(NaN)`). That covers `LazyNullableFloat64` (0.0 sentinels at
/// missing slots → `Null(NaN)`) and the `LazyAllValidFloat64` family
/// carrying NaN-derived validity (missing slots hold NaN → the `is_nan`
/// escape emits the present `Float64(NaN)` identity). Eager/cached
/// nullable Float64 columns return `None`: their per-slot `NullKind`
/// (Null/NaT vs NaN) is not reconstructible from a raw buffer plus mask.
#[must_use]
#[doc(hidden)]
pub fn as_canonical_nullable_f64(&self) -> Option<(&[f64], &ValidityMask)> {
if self.dtype != DType::Float64 {
return None;
}
let data: &[f64] = match &self.values {
ScalarValues::LazyNullableFloat64 { data, .. } => data.as_slice(),
ScalarValues::LazyAllValidFloat64 { data, .. } => data.as_ref(),
ScalarValues::LazyAllValidFloat64Vec { data, .. } => &data[..],
ScalarValues::LazyAllValidFloat64Slice {
data, start, len, ..
} => &data[*start..*start + *len],
_ => return None,
};
if data.len() != self.validity.len() {
return None;
}
Some((data, &self.validity))
}
pub fn as_f64_slice_with_validity(&self) -> Option<(&[f64], &ValidityMask)> {
if self.dtype != DType::Float64 {
return None;
}
let data: &[f64] = match &self.values {
ScalarValues::LazyAllValidFloat64 { data, .. } => data.as_ref(),
ScalarValues::LazyNullableFloat64 { data, .. } => data.as_slice(),
_ => match &self.data {
Some(ColumnData::Float64(data)) => data.as_ref(),
_ => return None,
},
};
if data.len() != self.validity.len() {
return None;
}
Some((data, &self.validity))
}
/// Int64 analogue of [`Self::as_f64_slice_with_validity`]: the contiguous i64
/// buffer plus its validity (works for an all-valid OR a `LazyNullableInt64`
/// backing). Missingness is the validity bit alone (no NaN sentinel).
pub fn as_i64_slice_with_validity(&self) -> Option<(&[i64], &ValidityMask)> {
if self.dtype != DType::Int64 {
return None;
}
let data: &[i64] = match &self.values {
ScalarValues::LazyAllValidInt64 { data, .. } => data.as_ref(),
ScalarValues::LazyAllValidInt64Vec { data, .. } => data.as_slice(),
ScalarValues::LazyNullableInt64 { data, .. } => data.as_slice(),
_ => match &self.data {
Some(ColumnData::Int64(data)) => data.as_ref(),
_ => return None,
},
};
if data.len() != self.validity.len() {
return None;
}
Some((data, &self.validity))
}
#[must_use]
#[doc(hidden)]
pub fn shared_f64_data_with_validity(&self) -> Option<(Arc<[f64]>, &ValidityMask)> {
if self.dtype != DType::Float64 {
return None;
}
match &self.values {
ScalarValues::LazyAllValidFloat64 { data, .. } if data.len() == self.validity.len() => {
Some((Arc::clone(data), &self.validity))
}
_ => None,
}
}
pub fn as_f64_slice(&self) -> Option<&[f64]> {
if self.dtype == DType::Float64 && self.validity.all() {
if let Some(ColumnData::Float64(data)) = &self.data {
return Some(data.as_ref());
}
if let ScalarValues::LazyAllValidFloat64 { data, .. } = &self.values {
return Some(data.as_ref());
}
if let ScalarValues::LazyAllValidFloat64Vec { data, .. } = &self.values {
return Some(&data[..]);
}
if let ScalarValues::LazyAllValidFloat64Slice {
data, start, len, ..
} = &self.values
{
let end = start.checked_add(*len)?;
return data.get(*start..end);
}
// A transposed row column already computes a typed `Vec<f64>` inside
// its own `data` OnceLock (`plan.materialize_row`); `values()` then
// maps that vector into a `Vec<Scalar>` purely to satisfy the
// `&[Scalar]` return type. Without this arm `Column.data` is `None`
// for the variant, so `as_f64_slice` declined and EVERY consumer of a
// transposed frame was forced through that 32-B/elem boxing. Return
// the typed vector directly: same values, same order, same length,
// and the `Scalar` vector is simply never built.
if let ScalarValues::LazyAllValidFloat64TransposeRow {
plan,
source_row,
data,
..
} = &self.values
{
return Some(
data.get_or_init(|| plan.materialize_row(*source_row))
.as_slice(),
);
}
if let Some(data) = self.values.chunks_float64_data() {
return Some(data);
}
if let Some(data) = self.values.dot_float64_data() {
return Some(data);
}
if let Some(data) = self.values.pairwise_stat_float64_data() {
return Some(data);
}
if let Some(data) = self.values.transpose_row_float64_data() {
return Some(data);
}
if let Some(data) = self.values.combine_first_float64_data() {
return Some(data);
}
if let Some(data) = self.values.strided_float64_data() {
return Some(data);
}
if let Some(data) = self.values.repeated_slices_f64_data() {
return Some(data);
}
}
None
}
#[must_use]
#[doc(hidden)]
pub fn all_valid_f64_to_vec(&self) -> Option<Vec<f64>> {
if self.dtype != DType::Float64 || !self.validity.all() {
return None;
}
if let ScalarValues::LazyRepeatedSlicesFloat64 {
data,
segments,
total_len,
expanded,
..
} = &self.values
{
return Some(expanded.get().map_or_else(
|| ScalarValues::expand_repeated_slices_f64(data, segments, *total_len),
Clone::clone,
));
}
self.as_f64_slice().map(<[f64]>::to_vec)
}
/// Borrow the column's contiguous `i64` buffer when this is an all-valid
/// `Int64` column. See [`Column::as_f64_slice`].
#[must_use]
pub fn as_i64_slice(&self) -> Option<&[i64]> {
if self.dtype == DType::Int64 && self.validity.all() {
if let Some(ColumnData::Int64(data)) = &self.data {
return Some(data.as_ref());
}
if let ScalarValues::LazyAllValidInt64 { data, .. } = &self.values {
return Some(data.as_ref());
}
if let ScalarValues::LazyAllValidInt64Vec { data, .. } = &self.values {
return Some(data.as_slice());
}
if let Some(data) = self.values.chunks_i64_data() {
return Some(data);
}
if let Some(data) = self.values.repeat_runs_i64_data() {
return Some(data);
}
if let Some(data) = self.values.repeated_slices_i64_data() {
return Some(data);
}
if let Some(data) = self.values.left_join_dense_cycle_i64_data() {
return Some(data);
}
}
None
}
/// Borrow the column's contiguous `datetime64[ns]` buffer when available.
#[must_use]
#[doc(hidden)]
pub fn as_datetime64_slice(&self) -> Option<&[i64]> {
if self.dtype != DType::Datetime64 {
return None;
}
// LazyAllValidDatetime64 (br-frankenpandas-j5150, the to_datetime output
// backing) carries the nanos in `values`, not `data`; expose them too so
// the typed dt.year/floor/round fast paths see a from_datetime64_values
// column as typed (otherwise they'd silently fall back to the slow path).
if let ScalarValues::LazyAllValidDatetime64 { data, .. } = &self.values {
return Some(data.as_ref());
}
if let ScalarValues::LazyAllValidDatetime64Vec { data, .. } = &self.values {
return Some(data.as_slice());
}
if let Some(ColumnData::Datetime64(data)) = &self.data {
return Some(data.as_slice());
}
None
}
/// Borrow the raw `&[i64]` nanosecond backing of a `Timedelta64` column.
/// Sibling of [`Self::as_datetime64_slice`] (Timedelta64 stores its nanos in
/// `ColumnData::Timedelta64`; there is no lazy Timedelta64 variant). Missing
/// values are `Timedelta::NAT` in the buffer, so callers handle NaT inline.
/// Returns `None` for any other dtype or a non-materialized column.
pub fn as_timedelta64_slice(&self) -> Option<&[i64]> {
if self.dtype != DType::Timedelta64 {
return None;
}
if let ScalarValues::LazyAllValidTimedelta64Vec { data, .. } = &self.values {
return Some(data.as_slice());
}
if let Some(ColumnData::Timedelta64(data)) = &self.data {
return Some(data.as_slice());
}
None
}
/// Borrow a Period column's contiguous ordinal backing plus its uniform
/// frequency when the column is all-valid.
#[must_use]
#[doc(hidden)]
pub fn as_period_slice(&self) -> Option<(&[i64], PeriodFreq)> {
if self.dtype != DType::Period || !self.validity.all() {
return None;
}
if let ScalarValues::LazyAllValidPeriodVec { data, freq, .. } = &self.values {
return Some((data.as_slice(), *freq));
}
if let Some(ColumnData::Period(data, freq)) = &self.data {
return Some((data.as_slice(), *freq));
}
None
}
/// Return an Arc-backed all-valid Int64 buffer for lazy descriptor builders.
/// Existing Arc-backed columns share in O(1); legacy cached `Vec<i64>`
/// columns are copied once into immutable Arc storage.
#[must_use]
#[doc(hidden)]
pub fn as_i64_arc(&self) -> Option<Arc<[i64]>> {
if self.dtype == DType::Int64 && self.validity.all() {
if let ScalarValues::LazyAllValidInt64 { data, .. } = &self.values {
return Some(Arc::clone(data));
}
if let Some(ColumnData::Int64(data)) = &self.data {
return Some(Arc::clone(data));
}
return self.as_i64_slice().map(Arc::from);
}
None
}
/// Return an all-valid Int64 column's shared contiguous backing and row
/// start offset when the column is represented as an immutable Arc view.
/// Lazy chunk tapes intentionally return `None`: callers that can preserve
/// chunks should carry their existing descriptors rather than flattening.
#[must_use]
#[doc(hidden)]
pub fn as_i64_arc_view_source(&self) -> Option<(Arc<[i64]>, usize)> {
if self.dtype != DType::Int64 || !self.validity.all() {
return None;
}
match &self.values {
ScalarValues::LazyAllValidInt64 { data, .. } => Some((Arc::clone(data), 0)),
_ => match &self.data {
Some(ColumnData::Int64(data)) => Some((Arc::clone(data), 0)),
_ => None,
},
}
}
/// Return a cached exact dense-cycle witness for all-valid Int64 columns.
///
/// The first successful/failed lookup scans the backing once and caches the
/// result. Consumers can then avoid rediscovering `start + (row % period)`
/// shape inside repeated kernels while preserving a generic fallback.
#[must_use]
#[doc(hidden)]
pub fn int64_dense_cycle_witness(&self) -> Option<Int64DenseCycleWitness> {
if self.dtype == DType::Int64
&& self.validity.all()
&& let ScalarValues::LazyAllValidInt64 {
data, dense_cycle, ..
} = &self.values
{
return *dense_cycle.get_or_init(|| certify_int64_dense_cycle(data.as_ref()));
}
if self.dtype == DType::Int64
&& self.validity.all()
&& let ScalarValues::LazyAllValidInt64Chunks {
chunks,
len,
data,
dense_cycle,
..
} = &self.values
{
return *dense_cycle.get_or_init(|| {
let values =
data.get_or_init(|| ScalarValues::materialize_int64_chunks(chunks, *len));
certify_int64_dense_cycle(values.as_slice())
});
}
// Owned move-not-copy variant carries no `dense_cycle` OnceLock (it is built
// for op outputs, not as a cached descriptor source), so certify on the fly.
// Keeps the dense-cycle join/groupby fast path reachable for columns produced
// via `from_i64_values_owned` instead of silently dropping to the generic path.
if self.dtype == DType::Int64
&& self.validity.all()
&& let ScalarValues::LazyAllValidInt64Vec { data, .. } = &self.values
{
return certify_int64_dense_cycle(data.as_slice());
}
None
}
/// Build an all-valid `Bool` column from already-typed contiguous values.
///
/// The typed-ingestion counterpart for boolean results (comparison masks,
/// predicates) — see [`Column::from_f64_values`]. Defers `Scalar`
/// materialization until a caller asks for scalar values.
#[must_use]
pub fn from_bool_values(data: Vec<bool>) -> Self {
let len = data.len();
Self {
dtype: DType::Bool,
values: ScalarValues::lazy_all_valid_bool(data),
validity: ValidityMask::all_valid(len),
data: None,
}
}
/// Borrow the column's contiguous Utf8 backing — `(bytes, offsets)` with
/// row `i` = `bytes[offsets[i]..offsets[i+1]]`, always valid UTF-8 —
/// when this is an all-valid Utf8 column carrying the
/// `LazyContiguousUtf8` representation (br-frankenpandas-2krr0 rung 3).
/// Lets chained string ops read the previous op's output without ever
/// materializing its `Vec<Scalar>` view. Returns `None` for Scalar-backed
/// or nullable columns — callers fall back to `values()`.
#[must_use]
#[doc(hidden)]
pub fn as_utf8_contiguous(&self) -> Option<(&[u8], &[usize])> {
if self.dtype != DType::Utf8 || !self.validity.all() {
return None;
}
match &self.values {
ScalarValues::LazyContiguousUtf8 { bytes, offsets, .. } => {
Some((bytes.as_ref(), offsets.as_ref()))
}
ScalarValues::LazyLowerHexSequenceUtf8 {
prefix,
start,
len,
hex_width,
buffers,
..
} => {
let (bytes, offsets) = ScalarValues::materialized_lower_hex_buffers(
prefix, *start, *len, *hex_width, buffers,
);
Some((bytes.as_ref(), offsets.as_ref()))
}
_ => None,
}
}
/// Raw contiguous byte backing of a NULLABLE Utf8 column (`LazyNullableUtf8` —
/// a string column WITH missing rows). Returns `(bytes, offsets)` where a
/// present row `r` is `bytes[offsets[r]..offsets[r+1]]` and a missing row's
/// span is empty; pair with [`Self::validity`] (`validity.get(r)` is false at
/// missing rows) to distinguish present from missing without materializing the
/// `Vec<Scalar::Utf8>`. `None` for any other backing (all-valid Utf8 uses
/// [`Self::as_utf8_contiguous`]; eager/other dtypes have no contiguous span
/// view). Sibling of `as_utf8_contiguous` for consumers that render/scan a
/// nullable string column by span (e.g. the typed CSV/JSON writers).
#[must_use]
pub fn as_nullable_utf8_contiguous(&self) -> Option<(&[u8], &[usize])> {
if let ScalarValues::LazyNullableUtf8 { bytes, offsets, .. } = &self.values {
Some((bytes.as_ref(), offsets.as_ref()))
} else {
None
}
}
/// Raw packed `&[bool]` backing + validity of a NULLABLE Bool column
/// (`LazyNullableBool` — a boolean column WITH missing rows). A present row
/// `r` (`validity.get(r)`) is `data[r]`; a missing row's datum is arbitrary
/// (masked). `None` for any other backing (all-valid Bool uses
/// [`Self::as_bool_slice`]; eager/other dtypes are excluded). Sibling of
/// `as_nullable_utf8_contiguous` for consumers that render a nullable bool
/// column by raw bit (e.g. the typed CSV/JSON writers).
#[must_use]
pub fn as_nullable_bool_slice(&self) -> Option<(&[bool], &ValidityMask)> {
if let ScalarValues::LazyNullableBool { data, validity, .. } = &self.values {
Some((data.as_slice(), validity))
} else {
None
}
}
/// Share the column's contiguous Utf8 backing as immutable `Arc`s.
///
/// This is the ownership-preserving counterpart to
/// [`Self::as_utf8_contiguous`]: callers that need to store the same label
/// buffer elsewhere can clone the two Arcs instead of allocating
/// `String`s per row.
#[must_use]
#[doc(hidden)]
pub fn utf8_contiguous_arcs(&self) -> Option<Utf8ArcBuffers> {
if self.dtype != DType::Utf8 || !self.validity.all() {
return None;
}
match &self.values {
ScalarValues::LazyContiguousUtf8 { bytes, offsets, .. } => {
Some((Arc::clone(bytes), Arc::clone(offsets)))
}
_ => None,
}
}
/// Return cached default `factorize()` outputs for an all-valid contiguous
/// Utf8 column.
///
/// This is intentionally narrower than the full pandas factorize surface:
/// it covers only `sort=false, use_na_sentinel=true` over immutable
/// all-valid contiguous Utf8 buffers. Other factorize modes keep the
/// existing scalar/fallback paths so missing buckets, sorting, and object
/// semantics remain unchanged.
#[must_use]
#[doc(hidden)]
pub fn utf8_default_factorize_columns(&self) -> Option<(Self, Self)> {
if self.dtype != DType::Utf8 || !self.validity.all() {
return None;
}
let witness = match &self.values {
ScalarValues::LazyContiguousUtf8 {
bytes,
offsets,
factorize_default,
..
} => factorize_default
.get_or_init(|| Box::new(build_utf8_factorize_default_witness(bytes, offsets))),
_ => return None,
};
let codes_len = witness.codes.len();
let unique_len = witness.unique_offsets.len().saturating_sub(1);
let codes = Self {
dtype: DType::Int64,
values: ScalarValues::lazy_all_valid_int64_arc(Arc::clone(&witness.codes)),
validity: ValidityMask::all_valid(codes_len),
data: None,
};
let uniques = Self {
dtype: DType::Utf8,
values: ScalarValues::lazy_contiguous_utf8_arc(
Arc::clone(&witness.unique_bytes),
Arc::clone(&witness.unique_offsets),
),
validity: ValidityMask::all_valid(unique_len),
data: None,
};
Some((codes, uniques))
}
/// Share the `Arc` contiguous-Utf8 backing plus the source-row offset of
/// row 0, for an all-valid `LazyContiguousUtf8` (offset 0) or an existing
/// `LazyUtf8Slice` view (offset `start`). The two `Arc::clone`s are O(1) and
/// let `take_positions` return a contiguous-range view without copying
/// (br-frankenpandas-jbyuc.1.1.1).
fn utf8_arc_view_source(&self) -> Option<Utf8ArcViewSource> {
if self.dtype != DType::Utf8 || !self.validity.all() {
return None;
}
match &self.values {
ScalarValues::LazyContiguousUtf8 { bytes, offsets, .. } => {
Some((Arc::clone(bytes), Arc::clone(offsets), 0))
}
ScalarValues::LazyUtf8Slice {
bytes,
offsets,
start,
..
} => Some((Arc::clone(bytes), Arc::clone(offsets), *start)),
_ => None,
}
}
fn float64_arc_view_source(&self) -> Option<(Arc<[f64]>, usize)> {
if self.dtype != DType::Float64 || !self.validity.all() {
return None;
}
match &self.values {
ScalarValues::LazyAllValidFloat64 { data, .. } => Some((Arc::clone(data), 0)),
ScalarValues::LazyAllValidFloat64Slice { data, start, .. } => {
Some((Arc::clone(data), *start))
}
_ => match &self.data {
Some(ColumnData::Float64(data)) => Some((Arc::clone(data), 0)),
_ => None,
},
}
}
fn finite_float64_arc_view_source(&self, row_len: usize) -> Option<(Arc<[f64]>, usize)> {
if self.dtype != DType::Float64 || !self.validity.all() {
return None;
}
match &self.values {
ScalarValues::LazyAllValidFloat64 {
data, all_finite, ..
} => {
let slice = data.get(..row_len)?;
let finite = if row_len == data.len() {
*all_finite.get_or_init(|| data.iter().all(|value| value.is_finite()))
} else {
slice.iter().all(|value| value.is_finite())
};
finite.then(|| (Arc::clone(data), 0))
}
ScalarValues::LazyAllValidFloat64Slice {
data,
start,
len,
all_finite,
..
} => {
if *len != row_len {
return None;
}
let end = start.checked_add(row_len)?;
let slice = data.get(*start..end)?;
let finite =
*all_finite.get_or_init(|| slice.iter().all(|value| value.is_finite()));
finite.then(|| (Arc::clone(data), *start))
}
ScalarValues::LazyAllValidFloat64Chunks {
chunks,
len,
all_finite,
..
} => {
if *len != row_len {
return None;
}
let finite = *all_finite.get_or_init(|| {
chunks
.iter()
.flat_map(Float64Chunk::as_slice)
.all(|value| value.is_finite())
});
if !finite || chunks.len() != 1 {
return None;
}
let chunk = &chunks[0];
Some((Arc::clone(&chunk.data), chunk.start))
}
_ => match &self.data {
Some(ColumnData::Float64(data)) => {
let slice = data.get(..row_len)?;
slice
.iter()
.all(|value| value.is_finite())
.then(|| (Arc::clone(data), 0))
}
_ => None,
},
}
}
/// Return an all-valid Float64 column's shared contiguous backing and row
/// start offset when the column is represented as an immutable Arc view.
#[must_use]
#[doc(hidden)]
pub fn as_f64_arc_view_source(&self) -> Option<(Arc<[f64]>, usize)> {
self.float64_arc_view_source()
}
/// Return an all-valid finite Float64 column's shared contiguous backing
/// and row start offset when represented as an immutable Arc view.
#[must_use]
#[doc(hidden)]
pub fn as_f64_finite_arc_view_source(&self, row_len: usize) -> Option<(Arc<[f64]>, usize)> {
self.finite_float64_arc_view_source(row_len)
}
/// Borrow the contiguous Utf8 backing only when its byte spans are already
/// strictly increasing. The witness is cached on the immutable contiguous
/// backing so repeated ordered joins do not rescan both key columns.
#[must_use]
#[doc(hidden)]
pub fn as_strictly_increasing_utf8_contiguous(&self) -> Option<(&[u8], &[usize])> {
if self.dtype != DType::Utf8 || !self.validity.all() {
return None;
}
match &self.values {
ScalarValues::LazyContiguousUtf8 {
bytes,
offsets,
strictly_increasing,
..
} if *strictly_increasing.get_or_init(|| {
contiguous_utf8_offsets_are_strictly_increasing(bytes, offsets)
}) =>
{
Some((bytes.as_ref(), offsets.as_ref()))
}
ScalarValues::LazyLowerHexSequenceUtf8 {
prefix,
start,
len,
hex_width,
buffers,
..
} => {
let (bytes, offsets) = ScalarValues::materialized_lower_hex_buffers(
prefix, *start, *len, *hex_width, buffers,
);
Some((bytes.as_ref(), offsets.as_ref()))
}
_ => None,
}
}
/// Borrow a strict contiguous-Utf8 backing and its fixed row byte width.
///
/// The fixed-width witness is cached next to the strict-increasing witness:
/// ordered string joins can then detect a long equal byte window once and
/// emit a whole range of 1:1 matches without per-row byte-span comparisons.
#[must_use]
pub fn as_fixed_width_strictly_increasing_utf8_contiguous(
&self,
) -> Option<(&[u8], &[usize], usize)> {
if self.dtype != DType::Utf8 || !self.validity.all() {
return None;
}
match &self.values {
ScalarValues::LazyContiguousUtf8 {
bytes,
offsets,
strictly_increasing,
fixed_width,
..
} if *strictly_increasing.get_or_init(|| {
contiguous_utf8_offsets_are_strictly_increasing(bytes, offsets)
}) =>
{
let width = fixed_width
.get_or_init(|| contiguous_utf8_fixed_width(offsets))
.as_ref()
.copied()?;
Some((bytes.as_ref(), offsets.as_ref(), width))
}
ScalarValues::LazyLowerHexSequenceUtf8 {
prefix,
start,
len,
hex_width,
buffers,
..
} => {
let (bytes, offsets) = ScalarValues::materialized_lower_hex_buffers(
prefix, *start, *len, *hex_width, buffers,
);
Some((bytes.as_ref(), offsets.as_ref(), prefix.len() + *hex_width))
}
_ => None,
}
}
/// Borrow a strict fixed-width contiguous-Utf8 backing and its cached
/// lower-hex sequence certificate.
///
/// The certificate is deterministic: every row is proven to be
/// `prefix + fixed-width lowercase hex(start + row)`. Ordered joins can use
/// matching certificates to prove a shifted overlap is byte-identical
/// without scanning the whole overlap window.
#[must_use]
#[doc(hidden)]
pub fn as_lower_hex_sequence_utf8_contiguous(
&self,
) -> Option<(&[u8], &[usize], Utf8LowerHexSequence)> {
if self.dtype != DType::Utf8 || !self.validity.all() {
return None;
}
match &self.values {
ScalarValues::LazyContiguousUtf8 {
bytes,
offsets,
strictly_increasing,
fixed_width,
lower_hex_sequence,
..
} if *strictly_increasing.get_or_init(|| {
contiguous_utf8_offsets_are_strictly_increasing(bytes, offsets)
}) =>
{
let width = fixed_width
.get_or_init(|| contiguous_utf8_fixed_width(offsets))
.as_ref()
.copied()?;
let certificate = lower_hex_sequence
.get_or_init(|| {
contiguous_utf8_lower_hex_sequence(bytes, offsets, width).map(Box::new)
})
.as_deref()
.copied()?;
Some((bytes.as_ref(), offsets.as_ref(), certificate))
}
ScalarValues::LazyLowerHexSequenceUtf8 {
prefix,
start,
len,
hex_width,
buffers,
..
} => {
let (bytes, offsets) = ScalarValues::materialized_lower_hex_buffers(
prefix, *start, *len, *hex_width, buffers,
);
if *len == 0 {
return None;
}
let (_, certificate, _) =
ScalarValues::lower_hex_sequence_witness(prefix, *start, *len, *hex_width);
Some((bytes.as_ref(), offsets.as_ref(), certificate))
}
_ => None,
}
}
/// Borrow a lower-hex sequence witness without forcing contiguous byte
/// materialization.
#[must_use]
#[doc(hidden)]
pub fn as_lower_hex_sequence_utf8(&self) -> Option<(&[u8], Utf8LowerHexSequence, usize)> {
if self.dtype != DType::Utf8 || !self.validity.all() {
return None;
}
match &self.values {
ScalarValues::LazyLowerHexSequenceUtf8 {
prefix,
start,
len,
hex_width,
..
} => Some(ScalarValues::lower_hex_sequence_witness(
prefix, *start, *len, *hex_width,
)),
ScalarValues::LazyContiguousUtf8 {
bytes,
offsets,
strictly_increasing,
fixed_width,
lower_hex_sequence,
..
} if *strictly_increasing.get_or_init(|| {
contiguous_utf8_offsets_are_strictly_increasing(bytes, offsets)
}) =>
{
let width = fixed_width
.get_or_init(|| contiguous_utf8_fixed_width(offsets))
.as_ref()
.copied()?;
let certificate = lower_hex_sequence
.get_or_init(|| {
contiguous_utf8_lower_hex_sequence(bytes, offsets, width).map(Box::new)
})
.as_deref()
.copied()?;
let n = offsets.len().checked_sub(1)?;
let first_start = *offsets.first()?;
let prefix_end = first_start.checked_add(certificate.prefix_len())?;
let first_end = *offsets.get(1)?;
(prefix_end <= first_end && first_end <= bytes.len())
.then(|| (&bytes[first_start..prefix_end], certificate, n))
}
_ => None,
}
}
/// Borrow the column's contiguous `bool` buffer when this is an all-valid
/// `Bool` column. See [`Column::as_f64_slice`].
#[must_use]
pub fn as_bool_slice(&self) -> Option<&[bool]> {
if self.dtype == DType::Bool && self.validity.all() {
if let Some(ColumnData::Bool(data)) = &self.data {
return Some(data.as_ref());
}
if let ScalarValues::LazyAllValidBool { data, .. } = &self.values {
return Some(data.as_ref());
}
if let ScalarValues::LazyShiftedBool {
source,
periods,
fill,
len,
data,
..
} = &self.values
{
return Some(
data.get_or_init(|| {
ScalarValues::materialize_shifted_bool(source, *periods, *fill, *len)
})
.as_slice(),
);
}
}
None
}
fn bool_arc_view_source(&self) -> Option<Arc<[bool]>> {
if self.dtype != DType::Bool || !self.validity.all() {
return None;
}
match &self.values {
ScalarValues::LazyAllValidBool { data, .. } => Some(Arc::clone(data)),
_ => match &self.data {
Some(ColumnData::Bool(data)) => Some(Arc::clone(data)),
_ => None,
},
}
}
/// Return a cached affine-selection witness for all-valid Bool masks.
///
/// This is an internal proof-carrying companion to [`Self::as_bool_slice`]:
/// the first query scans the immutable bool backing and subsequent filters
/// reuse the exact certificate instead of rediscovering it in `loc_bool`.
#[must_use]
#[doc(hidden)]
pub fn bool_affine_selection_witness(&self) -> Option<BoolAffineSelectionWitness> {
if self.dtype == DType::Bool
&& self.validity.all()
&& let ScalarValues::LazyAllValidBool {
data,
affine_selection,
..
} = &self.values
{
return *affine_selection.get_or_init(|| certify_bool_affine_selection(data.as_ref()));
}
if self.dtype == DType::Bool
&& self.validity.all()
&& let ScalarValues::LazyShiftedBool {
source,
periods,
fill,
len,
data,
affine_selection,
..
} = &self.values
{
let shifted = data.get_or_init(|| {
ScalarValues::materialize_shifted_bool(source, *periods, *fill, *len)
});
return *affine_selection.get_or_init(|| certify_bool_affine_selection(shifted));
}
None
}
/// Gather a new column from the given row positions of `self`.
///
/// This is the fast path for materialization (`take`, `iloc`, boolean
/// filter, `sort_values`, `drop_duplicates`, `reindex`, `head`/`tail`,
/// groupby row selection). Because every gathered value originates from
/// `self` it already matches `self.dtype` (no coercion needed), so this
/// skips the dtype-coercion and object-bucket detection scans that
/// `Column::new` performs. All-valid source columns clone values directly
/// and emit an all-valid mask; missing-bearing columns clone the stored
/// scalar exactly and rebuild validity from that scalar.
///
/// Row gather is a structural reorder, not a dtype-construction boundary:
/// the output preserves the exact stored scalar/null kind at each selected
/// source row, and recomputes validity from those gathered scalars.
///
/// # Panics
/// Panics if any position is out of bounds (callers materialize from
/// validated index positions; this mirrors the prior `values()[pos]` index).
#[must_use]
pub fn take_positions(&self, positions: &[usize]) -> Self {
let n = positions.len();
if self.validity.all() {
// Zero-copy contiguous-range Float64 view
// (br-frankenpandas-jbyuc.1.1.1.1): ordered unique joins gather
// all-valid Float64 payload columns by sizeable unit-stride row
// ranges after the key column is already a LazyUtf8Slice. Share the
// source `Arc<[f64]>` and defer Scalar materialization instead of
// copying the range into a new Vec<f64>. Bit-identical to the copy
// gather: output row `i` reads `data[start + positions[0] + i]`,
// same order, same all-valid mask, same raw f64 bits. The `n >= 64`
// gate mirrors LazyUtf8Slice so small head/tail/iloc takes do not
// pin a large source buffer for a tiny result.
if n >= 64
&& let Some((src_data, src_start)) = self.float64_arc_view_source()
&& let Some(range_start) = contiguous_ascending_start(positions)
&& let Some(view_start) = src_start.checked_add(range_start)
&& view_start
.checked_add(n)
.is_some_and(|end| end <= src_data.len())
{
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_all_valid_float64_slice(src_data, view_start, n),
validity: ValidityMask::all_valid(n),
data: None,
};
}
if let Some(column) = self.take_strided_all_valid_float64_positions(positions) {
return column;
}
if let Some(data) = self.take_cached_all_valid_float64_positions(positions) {
// MOVE the freshly-gathered Vec<f64> into the owned backing instead
// of `Arc::<[f64]>::from(Vec)` (a 16 MB copy-on-produce — the
// [[f64-arc-copy-on-produce]] tax; col-level take of a 2M f64 was
// ~21 ms of which the copy + Vec churn dominated a 5 ms gather).
// Bit-identical: `LazyAllValidFloat64Vec` is all-valid Float64 and
// `as_f64_slice`/`values()` materialize the same slice + Scalars as
// `LazyAllValidFloat64`. Only the SCATTERED gather switches — the
// contiguous `float64_arc_view_source` / strided views above keep the
// `Arc<[f64]>` backing (their zero-copy row-range views need it, and a
// scattered result can't be viewed anyway).
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_all_valid_float64_owned(data),
validity: ValidityMask::all_valid(n),
data: None,
};
}
// Symmetric to the Float64 path: gather the contiguous i64 buffer and
// keep the output lazily typed instead of materializing a
// Vec<Scalar::Int64> (32 B/elem). Bit-identical — lazy_all_valid_int64
// materializes Scalar::Int64(data[i]) exactly as the primitive path
// would, with the same all-valid mask. (br-frankenpandas-uza04)
if let Some(data) = self.take_cached_all_valid_int64_positions(positions) {
// MOVE the gathered Vec<i64> into the owned backing instead of
// Arc::<[i64]>::from(Vec) (16 MB copy — same [[f64-arc-copy-on-produce]]
// tax the sibling Float64 gather just shed, 8.8× col-side). Bit-identical:
// LazyAllValidInt64Vec is all-valid Int64, as_i64_slice/values() match
// LazyAllValidInt64. Contiguous/strided i64 views keep Arc<[i64]>.
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_all_valid_int64_owned(data),
validity: ValidityMask::all_valid(n),
data: None,
};
}
// Bool sibling of the Int64 gather: gather the raw &[bool] by position
// into a typed all-valid Bool backing instead of the generic per-row
// Vec<Scalar::Bool> materialization (32 B/elem enum boxing vs 1 B/elem).
// Bit-identical: lazy_all_valid_bool materializes Scalar::Bool(data[i])
// exactly as the primitive path would, same all-valid mask.
if let Some(src) = self.as_bool_slice() {
let mut data = Vec::with_capacity(n);
for &pos in positions {
data.push(src[pos]);
}
return Self {
dtype: DType::Bool,
values: ScalarValues::lazy_all_valid_bool(data),
validity: ValidityMask::all_valid(n),
data: None,
};
}
// Datetime64 sibling of the Int64 gather: a Datetime64 column stores
// its ns as an i64 backing (`as_datetime64_slice`), so gather the raw
// ns by position into a typed Datetime64 column instead of the generic
// per-row Vec<Scalar::Datetime64> materialization (~32 B/elem boxing +
// from_values rescan — datetime take/iloc/merge-output/sort was ~8.5×
// slower than the i64 sibling and ~0.12× pandas). Bit-identical:
// `from_datetime64_values` (lazy_all_valid_datetime64) materializes
// `Scalar::Datetime64(ns)` exactly as the primitive path would, same
// all-valid mask, and a NaT sentinel is carried through unchanged.
if self.dtype == DType::Datetime64
&& let Some(src) = self.as_datetime64_slice()
{
let mut data = Vec::with_capacity(n);
for &pos in positions {
data.push(src[pos]);
}
return Self {
dtype: DType::Datetime64,
values: ScalarValues::lazy_all_valid_datetime64_owned(data),
validity: ValidityMask::all_valid(n),
data: None,
};
}
// Timedelta64 sibling of the Datetime64 gather (both store i64 ns).
if self.dtype == DType::Timedelta64
&& let Some(src) = self.as_timedelta64_slice()
{
let mut data = Vec::with_capacity(n);
for &pos in positions {
data.push(src[pos]);
}
return Self {
dtype: DType::Timedelta64,
values: ScalarValues::lazy_all_valid_timedelta64_owned(data),
validity: ValidityMask::all_valid(n),
data: None,
};
}
if self.dtype == DType::Period
&& let Some((src, freq)) = self.as_period_slice()
{
let mut data = Vec::with_capacity(n);
for &pos in positions {
data.push(src[pos]);
}
return Self::from_period_values_owned(data, freq);
}
// Zero-copy contiguous-range view (br-frankenpandas-jbyuc.1.1.1):
// when the requested positions are a contiguous ascending range over
// an Arc-shared contiguous-Utf8 backing, share the source `bytes`/
// `offsets` and defer the per-row byte gather instead of copying.
// Bit-identical to the eager gather below: the view materializes
// `Scalar::Utf8` of `bytes[off[start+i]..off[start+i+1]]` for
// `i in 0..n` — the exact same spans, same order, all-valid mask.
//
// Gated `n >= 64`: a view keeps the *whole* source buffer alive via
// `Arc`, so a tiny contiguous take (head/tail/single-row iloc) would
// pin a potentially large buffer to hold a handful of rows. Small
// takes fall through to the eager gather (a cheap, independent copy);
// only sizeable contiguous ranges — the join-output shape this lever
// targets — take the zero-copy view.
if n >= 64
&& let Some((src_bytes, src_offsets, src_start)) = self.utf8_arc_view_source()
&& let Some(range_start) = contiguous_ascending_start(positions)
{
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_utf8_slice(
src_bytes,
src_offsets,
src_start + range_start,
n,
),
validity: ValidityMask::all_valid(n),
data: None,
};
}
// Contiguous-Utf8 gather (br-frankenpandas-nl1tw): an all-valid
// `LazyContiguousUtf8` column gathers its selected byte spans into one
// fresh `bytes` buffer + `offsets`, keeping the output lazily typed —
// no per-row `String` heap clone and no lazy Scalar re-materialization.
// Bit-identical to the Scalar-clone path: each output slot materializes
// `Scalar::Utf8` of the exact same span bytes in the same order, with an
// all-valid mask (the source is all-valid by the enclosing branch).
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
let total: usize = positions
.iter()
.map(|&pos| offsets[pos + 1] - offsets[pos])
.sum();
let mut new_bytes = Vec::with_capacity(total);
let mut new_offsets = Vec::with_capacity(n + 1);
new_offsets.push(0);
for &pos in positions {
new_bytes.extend_from_slice(&bytes[offsets[pos]..offsets[pos + 1]]);
new_offsets.push(new_bytes.len());
}
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_contiguous_utf8(new_bytes, new_offsets),
validity: ValidityMask::all_valid(n),
data: None,
};
}
// Scalar-backed all-valid Utf8 gather: a Utf8 column whose values
// are eager `Scalar::Utf8` (not a LazyContiguousUtf8 backing) misses
// the contiguous branch above and would otherwise clone one `String`
// per row (n heap allocs — the malloc-bound hotspot of
// Series::sort_values / take / iloc over Scalar-backed text). Gather
// the selected spans into ONE fresh bytes buffer + offsets and emit a
// lazily-typed contiguous column instead. Bit-identical to the
// Scalar-clone path: each output slot materializes `Scalar::Utf8` of
// the exact same span bytes in the same order, all-valid mask
// (enclosing branch). `as_all_valid_str_vec` borrows the &str spans
// without materializing (returns `None` for any non-Utf8 scalar, so
// mixed columns fall through to the clone path unchanged).
if self.dtype == DType::Utf8
&& let Some(strs) = self.as_all_valid_str_vec()
{
let total: usize = positions.iter().map(|&pos| strs[pos].len()).sum();
let mut new_bytes = Vec::with_capacity(total);
let mut new_offsets = Vec::with_capacity(n + 1);
new_offsets.push(0);
for &pos in positions {
new_bytes.extend_from_slice(strs[pos].as_bytes());
new_offsets.push(new_bytes.len());
}
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_contiguous_utf8(new_bytes, new_offsets),
validity: ValidityMask::all_valid(n),
data: None,
};
}
let values = self
.take_all_valid_primitive_positions(positions)
.unwrap_or_else(|| {
positions
.iter()
.map(|&pos| self.values[pos].clone())
.collect()
});
return Self {
dtype: self.dtype,
values: ScalarValues::from_vec(values),
validity: ValidityMask::all_valid(n),
data: None,
};
}
// Typed nullable Float64 gather (br-frankenpandas-s2i37): any typed
// Float64 backing carrying a contiguous f64 buffer (`LazyNullableFloat64`,
// OR `LazyAllValidFloat64`/`ColumnData::Float64` paired with a
// not-all-valid mask — the shape `from_f64_values` produces for a column
// with NaN) gathers the data and validity bits directly instead of
// cloning a Scalar per row. Previously only `LazyNullableFloat64` was
// routed here, so a NaN-bearing `from_f64_values` column (values =
// LazyAllValidFloat64 + NaN-derived mask) fell to the generic per-row
// Scalar gather below — the residual cost behind nullable sort/iloc/dedup
// row reorders. Bit-identical: each such backing materializes
// `Float64(data[i])` when present and `Null(NaN)` when missing, so a
// slot's presence is `validity.get(pos) && !data[pos].is_nan()` (NaN at a
// valid slot normalizes to missing, exactly the generic path's
// `normalize_missing_for_dtype` then `is_missing()`); carrying that bit +
// the raw datum into `from_f64_values_with_validity` reproduces the same
// Scalar at every slot, skipping the 32 B/elem `Vec<Scalar>`.
// Gate on the `values` VARIANT (not `as_f64_slice_with_validity`, which
// also matches a `ColumnData::Float64` paired with NullKind-preserving
// Eager `values`): only the lazy typed Float64 backings canonicalize a
// missing slot to `Null(NaN)` in `values()`, matching
// `from_f64_values_with_validity`. A Float64 column legally holding
// `Null(NaT)`/`Null(Null)` keeps Eager values and must use the generic
// NullKind-faithful gather below.
let typed_f64: Option<&[f64]> = match &self.values {
ScalarValues::LazyNullableFloat64 { data, .. } => Some(data.as_slice()),
ScalarValues::LazyAllValidFloat64 { data, .. } => Some(data.as_ref()),
_ => None,
};
if let Some(src) = typed_f64 {
let mut data = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, &pos) in positions.iter().enumerate() {
let x = src[pos];
data.push(x);
if self.validity.get(pos) && !x.is_nan() {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
}
return Self::from_f64_values_with_validity(data, ValidityMask::from_words(words, n));
}
// Nullable Int64 sibling of the typed_f64 gather: a `LazyNullableInt64`
// (the backing every from_i64_values_with_validity / dense nullable-int op
// produces) otherwise cloned a 32 B Scalar per row in the generic gather
// below. Gate on the VARIANT (not `as_i64_slice_with_validity`, which also
// matches an Eager ColumnData::Int64 whose Scalars may legally hold
// Null(NaT)/Null(Null)); Int64 has no NaN so missingness is the validity
// bit alone. Bit-identical to the generic clone: present ⇒ Int64(data[pos]);
// missing ⇒ Null(Null) == `LazyNullableInt64`'s invalid emission ==
// missing_for_dtype(Int64), and `is_missing(values[pos]) == !validity.get(pos)`
// so the mask matches.
if let ScalarValues::LazyNullableInt64 { data, .. } = &self.values {
let src = data.as_slice();
let mut gathered = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, &pos) in positions.iter().enumerate() {
gathered.push(src[pos]);
if self.validity.get(pos) {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
}
return Self::from_i64_values_with_validity(gathered, ValidityMask::from_words(words, n));
}
// Nullable temporal / Bool siblings of the LazyNullableInt64 gather above.
// Datetime64 & Timedelta64 store i64 ns (invalid ⇒ Null(NaT) ==
// missing_for_dtype), Bool stores raw bits (invalid ⇒ Null(Null)). Each is
// variant-gated to the canonical lazy backing (keeping Eager NullKind columns
// on the generic gather below) and is byte-identical to the Scalar clone:
// present ⇒ the datum Scalar the lazy variant emits; missing ⇒ that variant's
// invalid emission (== missing_for_dtype); is_missing(values[pos]) ==
// !validity.get(pos), so the mask matches.
if let ScalarValues::LazyNullableDatetime64 { data, .. } = &self.values {
let src = data.as_slice();
let mut gathered = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, &pos) in positions.iter().enumerate() {
gathered.push(src[pos]);
if self.validity.get(pos) {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
}
return Self::from_datetime64_values_with_validity(
gathered,
ValidityMask::from_words(words, n),
);
}
if let ScalarValues::LazyNullableTimedelta64 { data, .. } = &self.values {
let src = data.as_slice();
let mut gathered = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, &pos) in positions.iter().enumerate() {
gathered.push(src[pos]);
if self.validity.get(pos) {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
}
return Self::from_timedelta64_values_with_validity(
gathered,
ValidityMask::from_words(words, n),
);
}
if let ScalarValues::LazyNullableBool { data, .. } = &self.values {
let src = data.as_slice();
let mut gathered = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, &pos) in positions.iter().enumerate() {
gathered.push(src[pos]);
if self.validity.get(pos) {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
}
return Self::from_bool_values_with_validity(
gathered,
ValidityMask::from_words(words, n),
);
}
// Nullable contiguous-Utf8 sibling of the typed nullable gathers above: a
// `LazyNullableUtf8` column (a string column WITH missing rows — the shape a
// frame-level `sort_values`/`iloc`/filter/reindex/join gathers per string column)
// otherwise fell to the generic per-row `self.values[pos].clone()` gather below,
// which forces the source into a `Vec<Scalar::Utf8>` (one heap `String` per row)
// AND clones a `String` per OUTPUT row. Gather the selected byte spans into ONE
// fresh contiguous buffer + offsets, carrying the validity bit per output slot —
// no per-row `String` alloc on input or output. Byte-identical to the Scalar-clone
// gather: a present source row (validity-set) materializes `Scalar::Utf8(span)` and
// a missing row (validity-clear, empty span) materializes `Null(Null) ==
// missing_for_dtype(Utf8)` — exactly what `LazyNullableUtf8` emits and what
// `from_utf8_values_with_validity` rebuilds — and the output validity word is set
// iff `validity.get(pos)`, matching the generic `!value.is_missing()`.
if let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
..
} = &self.values
{
let mut new_bytes: Vec<u8> = Vec::new();
let mut new_offsets: Vec<usize> = Vec::with_capacity(n + 1);
new_offsets.push(0);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, &pos) in positions.iter().enumerate() {
new_bytes.extend_from_slice(&bytes[offsets[pos]..offsets[pos + 1]]);
new_offsets.push(new_bytes.len());
if validity.get(pos) {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
}
return Self::from_utf8_values_with_validity(
new_bytes,
new_offsets,
ValidityMask::from_words(words, n),
);
}
let mut values = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, &pos) in positions.iter().enumerate() {
let value = self.values[pos].clone();
if !value.is_missing() {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
values.push(value);
}
Self {
dtype: self.dtype,
values: ScalarValues::from_vec(values),
validity: ValidityMask::from_words(words, n),
data: None,
}
}
/// Whether [`Self::take_position_runs`] can gather this column without
/// expanding the runs back into a per-row positions vector.
#[must_use]
#[doc(hidden)]
pub fn supports_fast_position_run_gather(&self) -> bool {
if self.validity.all()
&& (self.as_f64_slice().is_some()
|| self.as_i64_slice().is_some()
|| self.as_bool_slice().is_some()
|| self.as_period_slice().is_some())
{
return true;
}
matches!(
&self.values,
ScalarValues::LazyNullableFloat64 { .. } | ScalarValues::LazyAllValidFloat64 { .. }
)
}
/// Gather sorted ascending contiguous source runs without materializing a
/// full positions vector first.
///
/// # Panics
/// Panics if any run overflows or extends beyond this column's length.
#[must_use]
#[doc(hidden)]
pub fn take_position_runs(&self, runs: &[(usize, usize)], out_len: usize) -> Self {
debug_assert_eq!(runs.iter().map(|&(_, len)| len).sum::<usize>(), out_len);
for &(start, len) in runs {
let end = start
.checked_add(len)
.expect("position run end must not overflow");
assert!(end <= self.len(), "position run end must be in bounds");
}
if out_len == 0 {
return self.take_positions(&[]);
}
if runs.len() == 1 {
let (start, len) = runs[0];
return self.take_contiguous_range(start, len);
}
if self.validity.all() {
if let Some(src) = self.as_f64_slice() {
let mut data = Vec::with_capacity(out_len);
for &(start, len) in runs {
data.extend_from_slice(&src[start..start + len]);
}
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_all_valid_float64(data),
validity: ValidityMask::all_valid(out_len),
data: None,
};
}
if let Some(src) = self.as_i64_slice() {
let mut data = Vec::with_capacity(out_len);
for &(start, len) in runs {
data.extend_from_slice(&src[start..start + len]);
}
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_all_valid_int64(data),
validity: ValidityMask::all_valid(out_len),
data: None,
};
}
if let Some(src) = self.as_bool_slice() {
let mut data = Vec::with_capacity(out_len);
for &(start, len) in runs {
data.extend_from_slice(&src[start..start + len]);
}
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_all_valid_bool(data),
validity: ValidityMask::all_valid(out_len),
data: None,
};
}
// Datetime64 / Timedelta64 run gather (temporal sibling of the Int64
// arm; both store i64 ns) — MOVE the gathered Vec in via the owned
// backing instead of falling to the per-row Scalar path. Bit-identical.
if self.dtype == DType::Datetime64
&& let Some(src) = self.as_datetime64_slice()
{
let mut data = Vec::with_capacity(out_len);
for &(start, len) in runs {
data.extend_from_slice(&src[start..start + len]);
}
return Self {
dtype: DType::Datetime64,
values: ScalarValues::lazy_all_valid_datetime64_owned(data),
validity: ValidityMask::all_valid(out_len),
data: None,
};
}
if self.dtype == DType::Timedelta64
&& let Some(src) = self.as_timedelta64_slice()
{
let mut data = Vec::with_capacity(out_len);
for &(start, len) in runs {
data.extend_from_slice(&src[start..start + len]);
}
return Self {
dtype: DType::Timedelta64,
values: ScalarValues::lazy_all_valid_timedelta64_owned(data),
validity: ValidityMask::all_valid(out_len),
data: None,
};
}
if self.dtype == DType::Period
&& let Some((src, freq)) = self.as_period_slice()
{
let mut data = Vec::with_capacity(out_len);
for &(start, len) in runs {
data.extend_from_slice(&src[start..start + len]);
}
return Self::from_period_values_owned(data, freq);
}
}
let typed_f64: Option<&[f64]> = match &self.values {
ScalarValues::LazyNullableFloat64 { data, .. } => Some(data.as_slice()),
ScalarValues::LazyAllValidFloat64 { data, .. } => Some(data.as_ref()),
_ => None,
};
if let Some(src) = typed_f64 {
let mut data = Vec::with_capacity(out_len);
let mut words: Option<Vec<u64>> = None;
let mut out_idx = 0usize;
for &(start, len) in runs {
let end = start + len;
data.extend_from_slice(&src[start..end]);
for (offset, &x) in src[start..end].iter().enumerate() {
let pos = start + offset;
let is_valid = self.validity.get(pos) && !x.is_nan();
if let Some(words) = &mut words {
if is_valid {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
} else if !is_valid {
let mut initialized = vec![0_u64; out_len.div_ceil(64)];
let full_words = out_idx / 64;
initialized[..full_words].fill(u64::MAX);
let partial_bits = out_idx % 64;
if partial_bits != 0 {
initialized[full_words] = (1_u64 << partial_bits) - 1;
}
words = Some(initialized);
}
out_idx += 1;
}
}
if let Some(words) = words {
return Self::from_f64_values_with_validity(
data,
ValidityMask::from_words(words, out_len),
);
}
return Self::from_f64_values_all_valid_unchecked(data);
}
let mut positions = Vec::with_capacity(out_len);
for &(start, len) in runs {
positions.extend(start..start + len);
}
self.take_positions(&positions)
}
/// Gather sorted ascending contiguous source runs as an all-valid Float64
/// chunk view when the caller has already proven every selected output slot
/// is present and non-NaN.
#[must_use]
#[doc(hidden)]
pub fn take_position_runs_all_valid_f64_unchecked(
&self,
runs: &[(usize, usize)],
out_len: usize,
) -> Option<Self> {
debug_assert_eq!(runs.iter().map(|&(_, len)| len).sum::<usize>(), out_len);
let (data, base, source_len) = match &self.values {
ScalarValues::LazyAllValidFloat64 { data, .. } => (Arc::clone(data), 0, data.len()),
ScalarValues::LazyAllValidFloat64Slice {
data, start, len, ..
} => (Arc::clone(data), *start, *len),
_ => return None,
};
debug_assert!(
runs.iter()
.all(|&(start, len)| start.checked_add(len).is_some_and(|end| end <= source_len))
);
debug_assert!(runs.iter().all(|&(start, len)| {
(start..start + len).all(|row| self.validity.get(row) && !data[base + row].is_nan())
}));
if out_len == 0 {
return Some(Self::from_f64_values_all_valid_unchecked(Vec::new()));
}
let chunks = runs
.iter()
.map(|&(start, len)| (Arc::clone(&data), base + start, len))
.collect();
Some(Self::from_f64_all_valid_chunks(chunks, out_len))
}
/// Gather a contiguous row range without first materializing
/// `start..start + len` as a positions vector.
///
/// # Panics
/// Panics if the requested range overflows or extends beyond this column.
#[must_use]
pub fn take_contiguous_range(&self, start: usize, len: usize) -> Self {
let end = start
.checked_add(len)
.expect("contiguous range end must not overflow");
assert!(
end <= self.len(),
"contiguous range end must be within column length"
);
if self.validity.all() {
if let Some((src_data, src_start)) = self.float64_arc_view_source()
&& let Some(view_start) = src_start.checked_add(start)
&& view_start
.checked_add(len)
.is_some_and(|view_end| view_end <= src_data.len())
{
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_all_valid_float64_slice(src_data, view_start, len),
validity: ValidityMask::all_valid(len),
data: None,
};
}
if let Some(values) = self.as_f64_slice() {
return Self::from_f64_values(values[start..end].to_vec());
}
if let Some(values) = self.as_i64_slice() {
return Self::from_i64_values_owned(values[start..end].to_vec());
}
if let Some((src_bytes, src_offsets, src_start)) = self.utf8_arc_view_source() {
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_utf8_slice(
src_bytes,
src_offsets,
src_start + start,
len,
),
validity: ValidityMask::all_valid(len),
data: None,
};
}
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
let byte_start = offsets[start];
let byte_end = offsets[end];
let mut new_offsets = Vec::with_capacity(len + 1);
for &offset in &offsets[start..=end] {
new_offsets.push(offset - byte_start);
}
return Self {
dtype: self.dtype,
values: ScalarValues::lazy_contiguous_utf8(
bytes[byte_start..byte_end].to_vec(),
new_offsets,
),
validity: ValidityMask::all_valid(len),
data: None,
};
}
}
let positions: Vec<usize> = (start..end).collect();
self.take_positions(&positions)
}
fn bounded_arithmetic_progression_positions(
positions: &[usize],
source_len: usize,
) -> Option<(usize, usize)> {
match positions {
[] => None,
[start] if *start < source_len => Some((*start, 1)),
[_] => None,
[start, second, rest @ ..] => {
let step = second.checked_sub(*start)?;
if step == 0 {
return None;
}
let last = start.checked_add(step.checked_mul(positions.len() - 1)?)?;
if last >= source_len {
return None;
}
let mut expected = *second;
for &pos in rest {
expected += step;
if pos != expected {
return None;
}
}
Some((*start, step))
}
}
}
/// Internal companion for callers that already proved `positions` are an
/// arithmetic progression while building the selection.
///
/// The accepted Float64 path validates only `{start, step, len}` against
/// the column backing and does not rescan `positions`; all other cases
/// delegate to [`Self::take_positions`].
///
/// # Panics
/// Panics if fallback gathering sees an out-of-bounds position, matching
/// [`Self::take_positions`].
#[must_use]
#[doc(hidden)]
pub fn take_positions_with_affine_certificate(
&self,
positions: &[usize],
start: usize,
step: usize,
) -> Self {
if let Some(column) =
self.take_affine_all_valid_float64_positions(positions.len(), start, step)
{
return column;
}
self.take_positions(positions)
}
/// Internal companion for callers that already proved a positional gather
/// is the arithmetic progression `start + i * step` for `i in 0..len`.
///
/// Returns `None` when this column does not have a descriptor-only affine
/// representation, letting callers fall back to [`Self::take_positions`].
#[must_use]
#[doc(hidden)]
pub fn take_affine_positions_without_materialized_positions(
&self,
start: usize,
step: usize,
len: usize,
) -> Option<Self> {
self.take_affine_all_valid_float64_positions(len, start, step)
}
fn take_affine_all_valid_float64_positions(
&self,
len: usize,
start: usize,
step: usize,
) -> Option<Self> {
if self.dtype != DType::Float64
|| !self.validity.all()
|| len < STRIDED_FLOAT64_MIN_LEN
|| step == 0
{
return None;
}
let data = match &self.values {
ScalarValues::LazyAllValidFloat64 { data, .. } => Arc::clone(data),
_ => match &self.data {
Some(ColumnData::Float64(data)) => Arc::clone(data),
_ => return None,
},
};
let last = start.checked_add(step.checked_mul(len - 1)?)?;
if last >= data.len() {
return None;
}
Some(Self {
dtype: self.dtype,
values: ScalarValues::lazy_strided_float64(data, start, step, len),
validity: ValidityMask::all_valid(len),
data: None,
})
}
fn take_strided_all_valid_float64_positions(&self, positions: &[usize]) -> Option<Self> {
if self.dtype != DType::Float64 || positions.len() < STRIDED_FLOAT64_MIN_LEN {
return None;
}
let data = match &self.values {
ScalarValues::LazyAllValidFloat64 { data, .. } => Arc::clone(data),
_ => match &self.data {
Some(ColumnData::Float64(data)) => Arc::clone(data),
_ => return None,
},
};
let (start, step) = Self::bounded_arithmetic_progression_positions(positions, data.len())?;
Some(Self {
dtype: self.dtype,
values: ScalarValues::lazy_strided_float64(data, start, step, positions.len()),
validity: ValidityMask::all_valid(positions.len()),
data: None,
})
}
fn take_cached_all_valid_float64_positions(&self, positions: &[usize]) -> Option<Vec<f64>> {
let data = self.as_f64_slice()?;
let mut values = Vec::with_capacity(positions.len());
for &pos in positions {
values.push(data[pos]);
}
Some(values)
}
fn take_cached_all_valid_int64_positions(&self, positions: &[usize]) -> Option<Vec<i64>> {
let data = self.as_i64_slice()?;
let mut values = Vec::with_capacity(positions.len());
for &pos in positions {
values.push(data[pos]);
}
Some(values)
}
fn take_all_valid_primitive_positions(&self, positions: &[usize]) -> Option<Vec<Scalar>> {
if let Some(values) = self.take_cached_all_valid_primitive_positions(positions) {
return Some(values);
}
let mut values = Vec::with_capacity(positions.len());
match self.dtype {
DType::Bool | DType::BoolNullable => {
for &pos in positions {
match &self.values[pos] {
Scalar::Bool(value) => values.push(Scalar::Bool(*value)),
_ => return None,
}
}
}
DType::Int64 | DType::Int64Nullable => {
for &pos in positions {
match &self.values[pos] {
Scalar::Int64(value) => values.push(Scalar::Int64(*value)),
_ => return None,
}
}
}
DType::Float64 => {
for &pos in positions {
match &self.values[pos] {
Scalar::Float64(value) => values.push(Scalar::Float64(*value)),
_ => return None,
}
}
}
DType::Timedelta64 => {
for &pos in positions {
match &self.values[pos] {
Scalar::Timedelta64(value) => values.push(Scalar::Timedelta64(*value)),
_ => return None,
}
}
}
DType::Datetime64 => {
for &pos in positions {
match &self.values[pos] {
Scalar::Datetime64(value) => values.push(Scalar::Datetime64(*value)),
_ => return None,
}
}
}
DType::Period => {
for &pos in positions {
match &self.values[pos] {
Scalar::Period(value) => values.push(Scalar::Period(*value)),
_ => return None,
}
}
}
_ => return None,
}
Some(values)
}
fn take_cached_all_valid_primitive_positions(
&self,
positions: &[usize],
) -> Option<Vec<Scalar>> {
match self.dtype {
DType::Bool => {
if let Some(data) = self.as_bool_slice() {
let mut values = Vec::with_capacity(positions.len());
for &pos in positions {
values.push(Scalar::Bool(data[pos]));
}
return Some(values);
}
}
DType::Int64 => {
if let Some(data) = self.as_i64_slice() {
let mut values = Vec::with_capacity(positions.len());
for &pos in positions {
values.push(Scalar::Int64(data[pos]));
}
return Some(values);
}
}
DType::Float64 => {
if let Some(data) = self.as_f64_slice() {
let mut values = Vec::with_capacity(positions.len());
for &pos in positions {
values.push(Scalar::Float64(data[pos]));
}
return Some(values);
}
}
_ => {}
}
let data = self.data.as_ref()?;
let mut values = Vec::with_capacity(positions.len());
match (self.dtype, data) {
(DType::Bool | DType::BoolNullable, ColumnData::Bool(data)) => {
for &pos in positions {
values.push(Scalar::Bool(data[pos]));
}
}
(DType::Int64 | DType::Int64Nullable, ColumnData::Int64(data)) => {
for &pos in positions {
values.push(Scalar::Int64(data[pos]));
}
}
(DType::Float64, ColumnData::Float64(data)) => {
for &pos in positions {
values.push(Scalar::Float64(data[pos]));
}
}
(DType::Timedelta64, ColumnData::Timedelta64(data)) => {
for &pos in positions {
values.push(Scalar::Timedelta64(data[pos]));
}
}
(DType::Datetime64, ColumnData::Datetime64(data)) => {
for &pos in positions {
values.push(Scalar::Datetime64(data[pos]));
}
}
(DType::Period, ColumnData::Period(data, freq)) => {
for &pos in positions {
values.push(Scalar::Period(Period::new(data[pos], *freq)));
}
}
_ => return None,
}
Some(values)
}
/// Create a column filled with zeros.
///
/// Matches np.zeros().
pub fn zeros(n: usize, dtype: DType) -> Result<Self, ColumnError> {
let zero = match dtype {
DType::Int64 => Scalar::Int64(0),
DType::Float64 => Scalar::Float64(0.0),
DType::Bool => Scalar::Bool(false),
_ => Scalar::Int64(0),
};
Self::new(dtype, vec![zero; n])
}
/// Create a column filled with ones.
///
/// Matches np.ones().
pub fn ones(n: usize, dtype: DType) -> Result<Self, ColumnError> {
let one = match dtype {
DType::Int64 => Scalar::Int64(1),
DType::Float64 => Scalar::Float64(1.0),
DType::Bool => Scalar::Bool(true),
_ => Scalar::Int64(1),
};
Self::new(dtype, vec![one; n])
}
/// Create a column filled with a given value.
///
/// Matches np.full().
pub fn full(n: usize, fill_value: Scalar) -> Result<Self, ColumnError> {
let dtype = fill_value.dtype();
Self::new(dtype, vec![fill_value; n])
}
/// Create a zeros column with same shape and dtype as self.
pub fn zeros_like(&self) -> Result<Self, ColumnError> {
Self::zeros(self.len(), self.dtype)
}
/// Create a ones column with same shape and dtype as self.
pub fn ones_like(&self) -> Result<Self, ColumnError> {
Self::ones(self.len(), self.dtype)
}
/// Create a column filled with fill_value with same shape as self.
pub fn full_like(&self, fill_value: Scalar) -> Result<Self, ColumnError> {
Self::new(self.dtype, vec![fill_value; self.len()])
}
/// Create an empty column with same dtype as self.
pub fn empty_like(&self) -> Result<Self, ColumnError> {
Self::new(self.dtype, Vec::new())
}
/// Create a column with evenly spaced values in [start, stop).
///
/// Matches np.arange().
pub fn arange(start: f64, stop: f64, step: f64) -> Result<Self, ColumnError> {
if step == 0.0 {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: "step cannot be zero".to_string(),
dtype: DType::Float64,
}));
}
let mut values = Vec::new();
let mut x = start;
if step > 0.0 {
while x < stop {
values.push(Scalar::Float64(x));
x += step;
}
} else {
while x > stop {
values.push(Scalar::Float64(x));
x += step;
}
}
Self::new(DType::Float64, values)
}
/// Create a column with evenly spaced values over [start, stop].
///
/// Matches np.linspace().
pub fn linspace(start: f64, stop: f64, num: usize) -> Result<Self, ColumnError> {
if num == 0 {
return Self::new(DType::Float64, Vec::new());
}
if num == 1 {
return Self::new(DType::Float64, vec![Scalar::Float64(start)]);
}
let step = (stop - start) / (num - 1) as f64;
let values: Vec<Scalar> = (0..num)
.map(|i| Scalar::Float64(start + step * i as f64))
.collect();
Self::new(DType::Float64, values)
}
/// Create a column with evenly spaced values on a log scale.
///
/// Matches np.logspace().
pub fn logspace(start: f64, stop: f64, num: usize) -> Result<Self, ColumnError> {
let lin = Self::linspace(start, stop, num)?;
let values: Vec<Scalar> = lin
.values()
.iter()
.map(|v| match v {
Scalar::Float64(x) => Scalar::Float64(10.0_f64.powf(*x)),
_ => v.clone(),
})
.collect();
Self::new(DType::Float64, values)
}
/// Create values evenly spaced on a log scale (geometric progression).
///
/// Matches np.geomspace(start, stop, num). Unlike logspace, start and stop
/// are the actual boundary values (not exponents).
pub fn geomspace(start: f64, stop: f64, num: usize) -> Result<Self, ColumnError> {
if num == 0 {
return Self::new(DType::Float64, vec![]);
}
if start == 0.0 || stop == 0.0 {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: "geomspace endpoints cannot be zero".to_owned(),
dtype: DType::Float64,
}));
}
if num == 1 {
return Self::new(DType::Float64, vec![Scalar::Float64(start)]);
}
let log_start = start.ln();
let log_stop = stop.ln();
let step = (log_stop - log_start) / (num - 1) as f64;
let values: Vec<Scalar> = (0..num)
.map(|i| Scalar::Float64((log_start + step * i as f64).exp()))
.collect();
Self::new(DType::Float64, values)
}
/// Generate a Hann (Hanning) window.
///
/// Matches np.hanning(M). Returns a raised cosine window of length M.
pub fn hanning(m: usize) -> Result<Self, ColumnError> {
if m == 0 {
return Self::new(DType::Float64, vec![]);
}
if m == 1 {
return Self::new(DType::Float64, vec![Scalar::Float64(1.0)]);
}
let values: Vec<Scalar> = (0..m)
.map(|n| {
let val =
0.5 - 0.5 * (2.0 * std::f64::consts::PI * n as f64 / (m - 1) as f64).cos();
Scalar::Float64(val)
})
.collect();
Self::new(DType::Float64, values)
}
/// Generate a Hamming window.
///
/// Matches np.hamming(M). Returns a Hamming window of length M.
pub fn hamming(m: usize) -> Result<Self, ColumnError> {
if m == 0 {
return Self::new(DType::Float64, vec![]);
}
if m == 1 {
return Self::new(DType::Float64, vec![Scalar::Float64(1.0)]);
}
let values: Vec<Scalar> = (0..m)
.map(|n| {
let val =
0.54 - 0.46 * (2.0 * std::f64::consts::PI * n as f64 / (m - 1) as f64).cos();
Scalar::Float64(val)
})
.collect();
Self::new(DType::Float64, values)
}
/// Generate a Blackman window.
///
/// Matches np.blackman(M). Returns a Blackman window of length M.
pub fn blackman(m: usize) -> Result<Self, ColumnError> {
if m == 0 {
return Self::new(DType::Float64, vec![]);
}
if m == 1 {
return Self::new(DType::Float64, vec![Scalar::Float64(1.0)]);
}
let values: Vec<Scalar> = (0..m)
.map(|n| {
let x = n as f64 / (m - 1) as f64;
let val = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * x).cos()
+ 0.08 * (4.0 * std::f64::consts::PI * x).cos();
Scalar::Float64(val)
})
.collect();
Self::new(DType::Float64, values)
}
/// Generate a Bartlett (triangular) window.
///
/// Matches np.bartlett(M). Returns a triangular window of length M.
pub fn bartlett(m: usize) -> Result<Self, ColumnError> {
if m == 0 {
return Self::new(DType::Float64, vec![]);
}
if m == 1 {
return Self::new(DType::Float64, vec![Scalar::Float64(1.0)]);
}
let half = (m - 1) as f64 / 2.0;
let values: Vec<Scalar> = (0..m)
.map(|n| {
let val = 1.0 - ((n as f64 - half) / half).abs();
Scalar::Float64(val)
})
.collect();
Self::new(DType::Float64, values)
}
#[must_use]
pub fn dtype(&self) -> DType {
self.dtype
}
/// Returns true if this column contains any null/missing values.
#[must_use]
pub fn has_nulls(&self) -> bool {
self.validity.count_invalid() > 0
}
/// Promote the dtype to its nullable variant if the column has nulls.
///
/// For Int64 with nulls → Int64Nullable, Bool with nulls → BoolNullable.
/// For already-nullable or other dtypes, returns a clone unchanged.
#[must_use]
pub fn promote_to_nullable(&self) -> Self {
if !self.has_nulls() {
return self.clone();
}
let new_dtype = self.dtype.to_nullable();
if new_dtype == self.dtype {
return self.clone();
}
Self {
dtype: new_dtype,
values: self.values.clone(),
validity: self.validity.clone(),
data: self.data.clone(),
}
}
/// Create a new column with a different dtype, preserving the same values.
///
/// This is a low-level operation that only changes the dtype metadata
/// without converting values. Use only when the values are already valid
/// for the target dtype.
#[must_use]
pub fn with_dtype(&self, dtype: DType) -> Self {
Self {
dtype,
values: self.values.clone(),
validity: self.validity.clone(),
data: None,
}
}
#[must_use]
pub fn len(&self) -> usize {
self.values.len()
}
/// Number of elements, matching `pd.Series.size`.
#[must_use]
pub fn size(&self) -> usize {
self.len()
}
/// One-dimensional shape, matching `pd.Series.shape`.
#[must_use]
pub fn shape(&self) -> (usize,) {
(self.len(),)
}
/// Number of array dimensions, matching `pd.Series.ndim`.
#[must_use]
pub fn ndim(&self) -> usize {
1
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
/// Alias for [`is_empty`](Self::is_empty), matching `pd.Series.empty`.
#[must_use]
pub fn empty(&self) -> bool {
self.is_empty()
}
/// Return a deep copy of this column.
///
/// Matches `pd.Series.copy(deep=True)` at the column storage layer.
#[must_use]
pub fn copy(&self) -> Self {
self.clone()
}
/// Return an immutable view-shaped clone of this column.
///
/// Matches `pd.Series.view()` at the column storage layer.
#[must_use]
pub fn view(&self) -> Self {
self.clone()
}
/// One-dimensional transpose is identity.
///
/// Matches `pd.Series.transpose()` at the column storage layer.
#[must_use]
pub fn transpose(&self) -> Self {
self.clone()
}
/// Lowercase alias for [`transpose`](Self::transpose).
#[must_use]
pub fn t(&self) -> Self {
self.transpose()
}
/// Uppercase pandas spelling for [`transpose`](Self::transpose).
#[allow(non_snake_case)]
#[must_use]
pub fn T(&self) -> Self {
self.transpose()
}
#[must_use]
pub fn values(&self) -> &[Scalar] {
&self.values
}
#[must_use]
pub fn value(&self, idx: usize) -> Option<&Scalar> {
self.values.get(idx)
}
/// Extract scalar value from a single-element column.
///
/// Matches `pd.Series.item()` at the column storage layer. Returns an
/// error unless the column has exactly one element.
pub fn item(&self) -> Result<Scalar, ColumnError> {
match self.values.as_slice() {
[value] => Ok(value.clone()),
values => Err(ColumnError::InvalidLength {
operation: "item()",
expected: 1,
actual: values.len(),
}),
}
}
#[must_use]
pub fn validity(&self) -> &ValidityMask {
&self.validity
}
/// Borrow-returning iterator over the column's scalars.
///
/// Convenience over `self.values().iter()` so call sites don't
/// have to reach through the slice accessor. Preserves
/// position order.
pub fn iter_values(&self) -> std::slice::Iter<'_, Scalar> {
self.values.iter()
}
/// Materialize the column's values into an owned `Vec<Scalar>`.
///
/// Matches `pd.Series.to_list()`. Equivalent to
/// `self.values().to_vec()`; the shorthand survives refactors
/// that change the internal storage shape.
#[must_use]
pub fn to_vec(&self) -> Vec<Scalar> {
self.values.to_vec()
}
/// Alias for [`to_vec`](Self::to_vec), matching `pd.Series.to_list()`.
#[must_use]
pub fn to_list(&self) -> Vec<Scalar> {
self.to_vec()
}
/// Alias for [`to_list`](Self::to_list), matching `pd.Series.tolist()`.
#[must_use]
pub fn tolist(&self) -> Vec<Scalar> {
self.to_list()
}
/// Owned scalar materialization, matching `pd.Series.to_numpy()`.
#[must_use]
pub fn to_numpy(&self) -> Vec<Scalar> {
self.to_vec()
}
/// Flatten values to a one-dimensional vector, matching `pd.Series.ravel()`.
#[must_use]
pub fn ravel(&self) -> Vec<Scalar> {
self.to_numpy()
}
/// Flatten values to a copy, matching `np.ndarray.flatten()`.
///
/// For 1D arrays this is equivalent to ravel() but explicitly returns
/// an owned copy rather than potentially a view.
#[must_use]
pub fn flatten(&self) -> Vec<Scalar> {
self.values.to_vec()
}
/// Convert to array, matching `np.asarray()`.
///
/// For Column this returns a clone since we're already array-like.
#[must_use]
pub fn asarray(&self) -> Self {
self.clone()
}
/// Owned scalar materialization, matching `pd.Series.array`.
#[must_use]
pub fn array(&self) -> Vec<Scalar> {
self.to_vec()
}
/// Whether any value in the column is missing.
///
/// Matches `pd.Series.isna().any()` in one pass. Faster than
/// calling `isnull()` and scanning — returns on the first
/// missing value seen.
#[must_use]
pub fn has_any_missing(&self) -> bool {
if self.dtype == DType::Float64 {
if let Some((data, validity)) = self.as_f64_slice_with_validity() {
return data
.iter()
.enumerate()
.any(|(idx, value)| !validity.get(idx) || value.is_nan());
}
if let Some(data) = self.as_f64_slice() {
return data.iter().any(|value| value.is_nan());
}
}
if matches!(
self.dtype,
DType::Bool
| DType::BoolNullable
| DType::Int64
| DType::Int64Nullable
| DType::Utf8
| DType::Interval
) {
return !self.validity.all();
}
self.values.iter().any(Scalar::is_missing)
}
/// Whether any value is missing, matching `pd.Series.hasnans`.
#[must_use]
pub fn hasnans(&self) -> bool {
self.has_any_missing()
}
/// Whether every value in the column is missing.
///
/// Matches `pd.Series.isna().all()`. Empty columns return true
/// (vacuously), mirroring `ValidityMask::all`'s empty-case
/// convention.
#[must_use]
pub fn all_missing(&self) -> bool {
if self.dtype == DType::Float64 {
if let Some((data, validity)) = self.as_f64_slice_with_validity() {
return data
.iter()
.enumerate()
.all(|(idx, value)| !validity.get(idx) || value.is_nan());
}
if let Some(data) = self.as_f64_slice() {
return data.iter().all(|value| value.is_nan());
}
}
if matches!(
self.dtype,
DType::Bool
| DType::BoolNullable
| DType::Int64
| DType::Int64Nullable
| DType::Utf8
| DType::Interval
) {
return self.validity.count_valid() == 0;
}
self.values.iter().all(Scalar::is_missing)
}
/// First value in the column (index 0), or `None` when empty.
///
/// Matches `pd.Series.iloc[0]` shorthand. Returns the raw Scalar
/// including missing markers; callers who want skipna semantics
/// can pair with `has_any_missing`.
#[must_use]
pub fn first(&self) -> Option<&Scalar> {
self.values.first()
}
/// Last value in the column, or `None` when empty.
#[must_use]
pub fn last(&self) -> Option<&Scalar> {
self.values.last()
}
/// Count values for which `predicate` returns true.
///
/// Complement to `apply_bool` that yields only the count rather
/// than materializing a Bool column. Missing inputs are treated
/// as a non-match (consistent with `apply_bool`'s
/// missing→Bool(false) contract).
pub fn count_matching<F>(&self, mut predicate: F) -> usize
where
F: FnMut(&Scalar) -> bool,
{
self.values
.iter()
.filter(|v| !v.is_missing() && predicate(v))
.count()
}
/// Elementwise combine with another column via a user function.
///
/// Matches `pd.Series.combine(other, func)` at the Column layer
/// without the pandas `fill_value=None` null-propagation policy
/// — `zip_with` always invokes `func`, passing through missing
/// values as-is so the caller decides whether to short-circuit
/// nulls. Length mismatch returns `LengthMismatch`.
pub fn zip_with<F>(&self, other: &Self, mut func: F) -> Result<Self, ColumnError>
where
F: FnMut(&Scalar, &Scalar) -> Scalar,
{
if self.values.len() != other.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: other.values.len(),
});
}
let out: Vec<Scalar> = self
.values
.iter()
.zip(other.values.iter())
.map(|(a, b)| func(a, b))
.collect();
let inferred = infer_dtype(&out).unwrap_or(self.dtype);
Self::new(inferred, out)
}
/// `(position, scalar)` iterator.
///
/// Shortcut for `iter_values().enumerate()`. Convenience for
/// callers that need both positions and values and don't want
/// to reach through the slice accessor.
pub fn iter_enumerate(&self) -> std::iter::Enumerate<std::slice::Iter<'_, Scalar>> {
self.values.iter().enumerate()
}
/// Apply a predicate per value and collect the results into a
/// Bool column.
///
/// Like `Column::map` but specialized for predicate functions
/// returning `bool`. Missing inputs produce `Scalar::Bool(false)`
/// by default — callers that need null propagation should use
/// `map` instead so they can emit `Null(NaN)` explicitly.
pub fn apply_bool<F>(&self, mut predicate: F) -> Result<Self, ColumnError>
where
F: FnMut(&Scalar) -> bool,
{
let out: Vec<Scalar> = self
.values
.iter()
.map(|v| {
if v.is_missing() {
Scalar::Bool(false)
} else {
Scalar::Bool(predicate(v))
}
})
.collect();
Self::new(DType::Bool, out)
}
pub fn reindex_by_positions(&self, positions: &[Option<usize>]) -> Result<Self, ColumnError> {
let mut present_positions = Vec::with_capacity(positions.len());
let mut all_present = true;
for position in positions {
match position {
Some(idx) if *idx < self.len() => present_positions.push(*idx),
Some(_) | None => {
all_present = false;
break;
}
}
}
if all_present {
return Ok(self.take_positions(&present_positions));
}
// Typed null-introducing gather (br-frankenpandas-lt5qx): an
// all-valid Int64/Float64 source skips the per-row Scalar clone +
// Column::new revalidation. Missing slots (None or out-of-range)
// produce exactly missing_for_dtype: Null(NullKind::Null) via the
// nullable-Int64 backing, Null(NullKind::NaN) via the 0.0-datum
// nullable-Float64 convention; valid slots clone the raw datum. These
// typed fast paths are all-valid only: nullable eager Float64 columns
// may carry per-position NullKind that must be preserved by the scalar
// fallback below.
let n = positions.len();
if self.validity.all()
&& let Some(slice) = self.as_i64_slice()
{
let mut data = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, slot) in positions.iter().enumerate() {
match slot {
Some(idx) if *idx < slice.len() => {
data.push(slice[*idx]);
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
_ => data.push(0),
}
}
return Ok(Self::from_i64_values_with_validity(
data,
ValidityMask::from_words(words, n),
));
}
// Nullable Int64 source null-introducing gather (variant-gated, sibling of the
// take_positions LazyNullableInt64 gather): the all-valid Int64 arm above requires
// `validity.all()`, so a nullable Int64 source (with some None/out-of-range positions)
// fell to the generic per-row Scalar clone below. Gather the raw i64 + validity:
// a present, in-range Some(idx) keeps `data[idx]` and sets the bit; a missing source
// slot, an out-of-range index, or None clears the bit (⇒ Null(Null) ==
// missing_for_dtype(Int64) — the same value the all-valid arm and the generic clone
// emit). Gate on the VARIANT (not `as_i64_slice_with_validity`, which also matches an
// Eager ColumnData::Int64 whose Scalars may hold Null(NaT)/Null(Null)); Int64 has no
// NaN so missingness is the validity bit alone.
if let ScalarValues::LazyNullableInt64 { data, .. } = &self.values {
let src = data.as_slice();
let mut out = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, slot) in positions.iter().enumerate() {
match slot {
Some(idx) if *idx < src.len() && self.validity.get(*idx) => {
out.push(src[*idx]);
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
_ => out.push(0),
}
}
return Ok(Self::from_i64_values_with_validity(
out,
ValidityMask::from_words(words, n),
));
}
// Nullable Bool source null-introducing gather (sibling of the nullable-Int64 arm).
// Bool has NO sentinel value — every missing slot (validity-clear, None, or
// out-of-range) is the single `Null(Null)` == missing_for_dtype(Bool), and a present
// slot is the validity bit alone (a `false` datum at a valid slot is a legit present
// `false`, never missing). So a uniform validity-bit gather is bit-identical to the
// generic clone. Variant-gated to the canonical `LazyNullableBool` backing (Eager
// NullKind columns keep the generic gather).
if let ScalarValues::LazyNullableBool { data, .. } = &self.values {
let src = data.as_slice();
let mut out = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, slot) in positions.iter().enumerate() {
match slot {
Some(idx) if *idx < src.len() && self.validity.get(*idx) => {
out.push(src[*idx]);
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
_ => out.push(false),
}
}
return Ok(Self::from_bool_values_with_validity(
out,
ValidityMask::from_words(words, n),
));
}
// NOTE (negative evidence, 2026-07-14 cc_fp): a nullable-TEMPORAL sibling here is a
// NullKind TRAP — the generic gather fills None/out-of-range with
// `missing_for_dtype(Datetime64)` == `Datetime64(NAT)` (a present-ish NaT scalar) but
// clones a source-missing slot as `Null(NaT)`; those two missing representations coexist
// in one output and a uniform `from_datetime64_values_with_validity` (all `Null(NaT)`)
// cannot reproduce the mix. Int64/Bool are safe only because both are the single
// `Null(Null)`.
if self.validity.all()
&& let Some(slice) = self.as_f64_slice()
{
let mut data = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, slot) in positions.iter().enumerate() {
match slot {
Some(idx) if *idx < slice.len() => {
data.push(slice[*idx]);
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
_ => data.push(0.0),
}
}
return Ok(Self::from_f64_values_with_validity(
data,
ValidityMask::from_words(words, n),
));
}
// Bool null-introducing gather (sibling of the Int64 arm): a missing slot
// (None / out-of-range) materializes Null(NullKind::Null) = missing_for_dtype
// (via from_bool_values_with_validity's cleared bit), present slots the raw
// bool — skipping the per-row Scalar clone. Bit-identical.
if self.validity.all()
&& let Some(slice) = self.as_bool_slice()
{
let mut data = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, slot) in positions.iter().enumerate() {
match slot {
Some(idx) if *idx < slice.len() => {
data.push(slice[*idx]);
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
_ => data.push(false),
}
}
return Ok(Self::from_bool_values_with_validity(
data,
ValidityMask::from_words(words, n),
));
}
// Datetime64 / Timedelta64 null-introducing gather (temporal sibling of the
// Int64 arm): gather the raw ns by position into a typed nullable backing,
// skipping the per-row Scalar clone + Column::new revalidation. Missing slots
// (None / out-of-range) materialize Null(NaT) = missing_for_dtype; valid slots
// Datetime64/Timedelta64(ns). All-valid source only (a NAT sentinel in a valid
// slot is carried through unchanged, matching the Scalar path).
if self.validity.all()
&& self.dtype == DType::Datetime64
&& let Some(slice) = self.as_datetime64_slice()
{
let mut data = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, slot) in positions.iter().enumerate() {
match slot {
Some(idx) if *idx < slice.len() => {
data.push(slice[*idx]);
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
_ => data.push(Timestamp::NAT),
}
}
return Ok(Self::from_datetime64_values_with_validity(
data,
ValidityMask::from_words(words, n),
));
}
if self.validity.all()
&& self.dtype == DType::Timedelta64
&& let Some(slice) = self.as_timedelta64_slice()
{
let mut data = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, slot) in positions.iter().enumerate() {
match slot {
Some(idx) if *idx < slice.len() => {
data.push(slice[*idx]);
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
_ => data.push(Timedelta::NAT),
}
}
return Ok(Self::from_timedelta64_values_with_validity(
data,
ValidityMask::from_words(words, n),
));
}
if self.validity.all()
&& self.dtype == DType::Period
&& let Some((slice, freq)) = self.as_period_slice()
{
let mut data = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, slot) in positions.iter().enumerate() {
match slot {
Some(idx) if *idx < slice.len() => {
data.push(slice[*idx]);
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
_ => data.push(i64::MIN),
}
}
return Ok(Self::from_period_values_with_validity(
data,
freq,
ValidityMask::from_words(words, n),
));
}
// Deferred null-introducing Utf8 gather (br-frankenpandas-yiqv5): when
// the all-valid source is `Eager` Scalar-backed (e.g. a `from_dict`
// string column feeding a null-introducing join), share its Scalar
// `Arc` and capture only the position plan (`usize::MAX` == missing) +
// an eager validity bitset. The gathered bytes never materialize until
// a consumer reads the column — so a join whose value lanes are only
// counted (index/shape consulted) skips the O(output) byte copy
// entirely. Materialized values are byte-identical to the eager cmxjz
// path below: present slots clone the source Scalar, missing slots are
// Null(NullKind::Null) == missing_for_dtype(Utf8). Gated on an all-valid
// Eager source; contiguous or nullable sources keep the eager paths.
if self.dtype == DType::Utf8
&& self.validity.all()
&& let Some(source) = self.values.eager_arc()
{
let source_len = source.len();
let mut plan = Vec::with_capacity(n);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, slot) in positions.iter().enumerate() {
match slot {
Some(idx) if *idx < source_len => {
plan.push(*idx);
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
_ => plan.push(usize::MAX),
}
}
return Ok(Self::from_utf8_lazy_gather(
Arc::clone(source),
plan.into(),
ValidityMask::from_words(words, n),
));
}
// Typed null-introducing Utf8 gather (br-frankenpandas-cmxjz): an
// all-valid Utf8 source (contiguous OR Scalar-backed) gathers present
// spans into one fresh byte buffer + offsets + validity bitset, emitting
// a nullable-Utf8 backing — no per-row String Scalar clone or Column::new
// revalidation. Missing slots get an empty span + cleared bit, which
// materializes Null(NullKind::Null) (= missing_for_dtype(Utf8)), exactly
// the Scalar fallback. Only fires when the source is all-valid (no NaN/
// null ambiguity); a source with its own nulls keeps the Scalar path.
if self.dtype == DType::Utf8
&& let Some(strs) = self.as_all_valid_str_vec()
{
let mut new_bytes = Vec::new();
let mut new_offsets = Vec::with_capacity(n + 1);
new_offsets.push(0);
let mut words = vec![0_u64; n.div_ceil(64)];
for (out_idx, slot) in positions.iter().enumerate() {
if let Some(idx) = slot
&& *idx < strs.len()
{
new_bytes.extend_from_slice(strs[*idx].as_bytes());
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
new_offsets.push(new_bytes.len());
}
return Ok(Self::from_utf8_values_with_validity(
new_bytes,
new_offsets,
ValidityMask::from_words(words, n),
));
}
let values = positions
.iter()
.map(|slot| match slot {
Some(idx) => self
.values
.get(*idx)
.cloned()
.unwrap_or_else(|| Scalar::missing_for_dtype(self.dtype)),
None => Scalar::missing_for_dtype(self.dtype),
})
.collect::<Vec<_>>();
let validity = ValidityMask::from_values(&values);
Ok(Self {
dtype: self.dtype,
values: ScalarValues::from_vec(values),
validity,
data: None,
})
}
/// Reindex by optional source positions, using `absent` for missing target
/// rows while preserving the exact stored scalar for present source rows.
#[doc(hidden)]
pub fn reindex_by_positions_with_absent_scalar(
&self,
positions: &[Option<usize>],
absent: Scalar,
) -> Result<Self, ColumnError> {
let mut present_positions = Vec::with_capacity(positions.len());
let mut all_present = true;
for position in positions {
match position {
Some(idx) if *idx < self.len() => present_positions.push(*idx),
Some(_) | None => {
all_present = false;
break;
}
}
}
if all_present {
return Ok(self.take_positions(&present_positions));
}
if absent == Scalar::missing_for_dtype(self.dtype) {
return self.reindex_by_positions(positions);
}
let values = positions
.iter()
.map(|slot| match slot {
Some(idx) => self
.values
.get(*idx)
.cloned()
.unwrap_or_else(|| absent.clone()),
None => absent.clone(),
})
.collect::<Vec<_>>();
let validity = ValidityMask::from_values(&values);
Ok(Self {
dtype: self.dtype,
values: ScalarValues::from_vec(values),
validity,
data: None,
})
}
/// AG-10: Attempt vectorized typed-array path for binary arithmetic.
///
/// Preconditions: both columns same length, out_dtype already computed.
/// Returns `Some(Column)` if vectorized path succeeded, `None` to
/// signal fallback to the scalar path.
fn try_vectorized_binary(
&self,
right: &Self,
op: ArithmeticOp,
out_dtype: DType,
) -> Option<Result<Self, ColumnError>> {
// Vectorized path: both sides same numeric dtype, no NaN-vs-Null
// distinction needed (i.e. both Int64, or both Float64 / promoted to Float64).
match out_dtype {
DType::Float64 => {
// Typed-input fast path: both operands are already all-valid
// contiguous Float64 (as_f64_slice => validity.all() AND no NaN),
// so read the buffers directly — no Scalar materialization, no
// from_scalars copy, no nan-aware validity scan. Bit-identical to
// the general arm's all-valid branch: with both inputs valid and
// NaN-free, the combined validity is all-valid, so it returns
// from_f64_values(apply(l,r)) too (and from_f64_values still marks
// any operation-produced NaN missing, identically).
if let (Some(l), Some(r)) = (self.as_f64_slice(), right.as_f64_slice()) {
let apply = binary_f64_apply(op);
// Pow (libm powf ~30ns/elem), Mod (python_mod_f64) and FloorDiv
// (python_floordiv: branches + floor + fdiv, ~7-8ns/elem) are
// COMPUTE-bound → parallelize; add/sub/mul/div are bandwidth-bound
// → keep serial (threads would only contend). Bit-identical
// (same apply, order preserved).
let result: Vec<f64> = if matches!(
op,
ArithmeticOp::Pow | ArithmeticOp::Mod | ArithmeticOp::FloorDiv
) {
par_map_vec_f64(l.len(), |i| apply(l[i], r[i]))
} else {
l.iter().zip(r).map(|(&a, &b)| apply(a, b)).collect()
};
return Some(Ok(Self::from_f64_values_owned(result)));
}
// Typed MIXED / int-promoted fast path: the both-Float64 borrow above
// declined because a side is Int64 (Int64 op Float64, or Int64 / Int64
// which promotes to Float64). Build an f64 view per side — an all-valid
// Float64 borrows its `&[f64]`, an all-valid Int64 maps `v as f64` once —
// and apply the SAME kernel, instead of materializing BOTH columns via
// `from_scalars` below. Bit-identical to the both-Float64 arm on the same
// values: an all-valid column has no present NaN (fp clears the validity
// bit for any NaN; Int64 has none), so `to_f64(Int64(v)) == v as f64` and
// the result is `from_f64_values(apply(l, r))`. A NaN-bearing Float64 or a
// nullable/other-dtype column declines the view and keeps the `from_scalars`
// path below (its nan-aware validity handling). A local `fn` (not a closure)
// so elision ties the `Cow<'_>` output lifetime to the `&Column` argument.
fn f64_view(col: &Column) -> Option<std::borrow::Cow<'_, [f64]>> {
if let Some(d) = col.as_f64_slice() {
Some(std::borrow::Cow::Borrowed(d))
} else {
col.as_i64_slice()
.map(|d| std::borrow::Cow::Owned(d.iter().map(|&v| v as f64).collect()))
}
}
if let (Some(lv), Some(rv)) = (f64_view(self), f64_view(right)) {
let (l, r) = (lv.as_ref(), rv.as_ref());
let apply = binary_f64_apply(op);
let result: Vec<f64> = if matches!(
op,
ArithmeticOp::Pow | ArithmeticOp::Mod | ArithmeticOp::FloorDiv
) {
par_map_vec_f64(l.len(), |i| apply(l[i], r[i]))
} else {
l.iter().zip(r).map(|(&a, &b)| apply(a, b)).collect()
};
return Some(Ok(Self::from_f64_values_owned(result)));
}
// Nullable / mixed-nullable f64-output fast path: generalizes the
// all-valid `f64_view` above to the NULLABLE case (which it declines,
// so a nullable Float64 OR any nullable Int64×Float64 / Int64×Int64-Div
// pair fell to the from_scalars materialization below). Each operand
// yields an f64 view + nan-aware validity: a Float64 borrows its raw
// &[f64] and folds present-NaN into the mask (== nan_aware_validity);
// an Int64 maps `v as f64` (no NaN) and carries its validity as-is
// (== nan_aware_validity for an int column, but WITHOUT the
// Scalar-materialize scan the generic path's nan_aware_validity pays on
// a non-Float64 backing). Byte-identical to the from_scalars arm: the
// views equal from_scalars(&values, Float64) (present ⇒ datum / v as
// f64, missing ⇒ 0.0 sentinel), the masks equal the two
// nan_aware_validity calls, and the kernel + output builder are the
// same. Local `fn` (not a closure) so elision ties the Cow lifetime to
// `col`.
fn f64_view_naw(
col: &Column,
) -> Option<(std::borrow::Cow<'_, [f64]>, ValidityMask)> {
if let Some((d, _)) = col.as_f64_slice_with_validity() {
Some((std::borrow::Cow::Borrowed(d), col.nan_aware_validity()))
} else if let Some((d, v)) = col.as_i64_slice_with_validity() {
Some((
std::borrow::Cow::Owned(d.iter().map(|&x| x as f64).collect()),
v.clone(),
))
} else {
None
}
}
if let (Some((lv, lnaw)), Some((rv, rnaw))) =
(f64_view_naw(self), f64_view_naw(right))
{
let (l, r) = (lv.as_ref(), rv.as_ref());
let (result_data, result_validity) =
vectorized_binary_f64(l, r, &lnaw, &rnaw, op);
if result_validity.all() {
return Some(Ok(Self::from_f64_values_owned(result_data)));
}
let final_validity =
result_validity.and_mask(&ValidityMask::from_f64(&result_data));
return Some(Ok(Self::from_f64_values_nullable(result_data, final_validity)));
}
let left_data = ColumnData::from_scalars(&self.values, DType::Float64);
let right_data = ColumnData::from_scalars(&right.values, DType::Float64);
let (ColumnData::Float64(l), ColumnData::Float64(r)) = (&left_data, &right_data)
else {
return None;
};
// We need NaN-aware validity: original validity + NaN propagation.
// Build validity masks that treat NaN source scalars as invalid.
let left_nan_aware = self.nan_aware_validity();
let right_nan_aware = right.nan_aware_validity();
let (result_data, result_validity) =
vectorized_binary_f64(l, r, &left_nan_aware, &right_nan_aware, op);
// All inputs valid: preserve the typed result buffer directly
// instead of rebuilding Vec<Scalar> and rescanning validity.
// Operation-produced NaN is still marked missing by
// from_f64_values, exactly like the Scalar::Float64(NaN) path.
if result_validity.all() {
return Some(Ok(Self::from_f64_values_owned(result_data)));
}
// Typed nullable output: reproduce the Vec<Scalar> + Self::new
// representation with the purpose-built LazyNullableFloat64
// constructor, skipping the 32-byte-per-cell Vec<Scalar> alloc
// (~160MB/5M rows) and the Self::new validity/data rescan.
// Bit-identical (ScalarValues::eq compares materialized values):
// from_f64_values_nullable renders validity-set ⇒ Float64(data);
// cleared-bit + NaN-datum ⇒ present Float64(NaN) (op-produced NaN,
// = the old Scalar::Float64(NaN) that Self::new marked missing);
// cleared-bit + non-NaN-datum ⇒ Null(NaN) (absent operand — the
// 0.0 sentinel vectorized_binary_f64 stored at combined-invalid
// slots — == missing_for_dtype(Float64), which equals the old
// is_nan_at Null(NaN) arm since both are Null(NaN) for Float64).
// Validity set iff combined-valid AND datum non-NaN: ValidityMask::
// from_f64 clears exactly the NaN slots, AND-ed with combined
// (already false at input-missing slots, whose datum is the 0.0
// sentinel so from_f64 keeps them set — combined does the masking).
let final_validity =
result_validity.and_mask(&ValidityMask::from_f64(&result_data));
Some(Ok(Self::from_f64_values_nullable(result_data, final_validity)))
}
DType::Int64 if !matches!(op, ArithmeticOp::Div) => {
// Both must actually be Int64 for the i64 fast path.
if self.dtype != DType::Int64 || right.dtype != DType::Int64 {
return None;
}
// Typed-input fast path (see the Float64 arm): both operands are
// all-valid contiguous i64 buffers, so feed vectorized_binary_i64
// directly — no from_scalars materialization. All-valid inputs =>
// all-valid result, so from_i64_values, identical to the general
// arm's all-valid branch.
if let (Some(l), Some(r)) = (self.as_i64_slice(), right.as_i64_slice()) {
let (result_data, _validity) =
vectorized_binary_i64(l, r, &self.validity, &right.validity, op)?;
return Some(Ok(Self::from_i64_values_owned(result_data)));
}
// Nullable-input fast path (sibling of the all-valid branch above,
// and of compare_scalar's nullable-Int64 arm): at least one side is
// a nullable Int64 column, so the `as_i64_slice` borrow declined and
// we would otherwise materialize BOTH inputs via `from_scalars`
// (forcing each LazyNullableInt64 to build a 32-byte-per-cell
// Vec<Scalar>) plus a trailing Vec<Scalar> for the nullable result.
// Read the raw &[i64] buffers + validity directly and feed the SAME
// `vectorized_binary_i64` kernel. Bit-identical to the from_scalars
// arm below: identical kernel over the same buffers and the same
// {self,right}.validity (as_i64_slice_with_validity returns
// &self.validity), so identical (result_data, result_validity);
// `from_i64_values_with_validity` reproduces that arm's output
// exactly (all-valid ⇒ from_i64_values_owned; otherwise
// LazyNullableInt64 emits Int64(v) at valid slots and
// Null(Null) == missing_for_dtype(Int64) at invalid slots). A zero
// divisor / Div / Pow still yields None from the kernel → caller
// promotes to Float64, identical to before.
if let (Some((l, lv)), Some((r, rv))) = (
self.as_i64_slice_with_validity(),
right.as_i64_slice_with_validity(),
) {
let (result_data, result_validity) =
vectorized_binary_i64(l, r, lv, rv, op)?;
return Some(Ok(Self::from_i64_values_with_validity(
result_data,
result_validity,
)));
}
let left_data = ColumnData::from_scalars(&self.values, DType::Int64);
let right_data = ColumnData::from_scalars(&right.values, DType::Int64);
let (ColumnData::Int64(l), ColumnData::Int64(r)) = (&left_data, &right_data) else {
return None;
};
let (result_data, result_validity) =
vectorized_binary_i64(l, r, &self.validity, &right.validity, op)?;
// All inputs valid: keep the typed i64 result buffer as the
// column source of truth and skip Scalar materialization.
if result_validity.all() {
return Some(Ok(Self::from_i64_values_owned(result_data)));
}
let values: Vec<Scalar> = result_data
.iter()
.enumerate()
.map(|(i, v)| {
if !result_validity.get(i) {
Scalar::missing_for_dtype(out_dtype)
} else {
Scalar::Int64(*v)
}
})
.collect();
Some(Self::new(out_dtype, values))
}
_ => None, // Bool, Utf8, etc. — use scalar fallback
}
}
/// AG-10 fused outer-alignment arithmetic for two Float64 columns.
///
/// Equivalent to `self.reindex_by_positions(lp)?.binary_numeric(
/// &right.reindex_by_positions(rp)?, op)` for the Float64-output case, but it
/// gathers `f64` directly from the *original* columns into the union layout
/// in one pass instead of materializing two intermediate `Vec<Scalar>` and
/// re-deriving their `f64` views. Provably isomorphic: `from_scalars` is
/// element-wise and `reindex` is a gather, so `gather(from_scalars(src)) ==
/// from_scalars(reindex(src))`; the nan-aware validity gathers identically
/// (a `None` slot reindexes to `missing_for_dtype(Float64) = Null(NaN)`,
/// i.e. invalid, exactly as the gathered mask marks it). For Float64 output
/// every invalid position is `Null(NaN)` — matching both arms of
/// `try_vectorized_binary`'s invalid branch. Caller guarantees both columns
/// are `Float64`.
pub fn aligned_binary_f64(
&self,
right: &Self,
left_positions: &[Option<usize>],
right_positions: &[Option<usize>],
op: ArithmeticOp,
) -> Result<Self, ColumnError> {
debug_assert_eq!(left_positions.len(), right_positions.len());
let out_len = left_positions.len();
let lsrc = self.float64_binary_data();
let rsrc = right.float64_binary_data();
// Fused NaN-tracked gather (br-frankenpandas-419of): rather than two full
// input-column `nan_aware_validity` pre-scans, gate each GATHERED element
// inline. `validity.get(i) && !lsrc[i].is_nan()` equals
// `nan_aware_validity(self).get(i)` (the validity bit already covers Null
// slots; the `is_nan` term covers a still-valid `Float64(NaN)`), but it is
// evaluated only at referenced positions, never the whole column. Because
// `validity.len() == lsrc.len()`, the short-circuit on `validity.get(i)`
// (false when out of range) keeps `lsrc[i]` in bounds, matching the old
// `lvalid.get(i)` OOB-as-invalid behaviour.
let lvalid = &self.validity;
let rvalid = &right.validity;
let apply = binary_f64_apply(op);
let mut data = Vec::with_capacity(out_len);
let mut words = vec![0_u64; out_len.div_ceil(64)];
let mut all_valid = true;
for (k, left_slot) in left_positions.iter().enumerate() {
if let Some(i) = *left_slot
&& let Some(j) = right_positions.get(k).copied().flatten()
&& lvalid.get(i)
&& !lsrc[i].is_nan()
&& rvalid.get(j)
&& !rsrc[j].is_nan()
{
let value = apply(lsrc[i], rsrc[j]);
data.push(value);
if value.is_nan() {
all_valid = false;
} else {
words[k / 64] |= 1_u64 << (k % 64);
}
} else {
data.push(0.0);
all_valid = false;
}
}
if all_valid {
return Ok(Self::from_f64_values_all_valid_unchecked(data));
}
Ok(Self::from_f64_values_with_validity(
data,
ValidityMask::from_words(words, out_len),
))
}
/// Fused Float64 arithmetic for two aligned contiguous `Int64` unit ranges.
///
/// The caller has proven the left and right indexes are `[start, end]`
/// integer ranges and the output index is their contiguous union. This is
/// isomorphic to [`Self::aligned_binary_f64`] with arithmetic positions, but
/// it fills the overlapped span directly and leaves non-overlap slots
/// invalid, avoiding the two `Vec<Option<usize>>` alignment buffers.
pub fn aligned_binary_f64_int64_unit_ranges(
&self,
right: &Self,
left_range: (i64, i64),
right_range: (i64, i64),
union_range: (i64, i64),
op: ArithmeticOp,
) -> Result<Self, ColumnError> {
if !matches!(self.dtype, DType::Float64) || !matches!(right.dtype, DType::Float64) {
return Err(ColumnError::DTypeMismatch {
left: self.dtype,
right: right.dtype,
});
}
let (left_start, left_end) = left_range;
let (right_start, right_end) = right_range;
let (union_start, union_end) = union_range;
let Some(left_len) = unit_range_len(left_start, left_end) else {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: right.len(),
});
};
let Some(right_len) = unit_range_len(right_start, right_end) else {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: right.len(),
});
};
let Some(out_len) = unit_range_len(union_start, union_end) else {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: right.len(),
});
};
if left_len != self.len() || right_len != right.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: right.len(),
});
}
let lsrc = self.float64_binary_data();
let rsrc = right.float64_binary_data();
let lvalid = self.nan_aware_validity();
let rvalid = right.nan_aware_validity();
let apply = binary_f64_apply(op);
let mut data = vec![0.0; out_len];
let mut words = vec![0_u64; out_len.div_ceil(64)];
let overlap_start = left_start.max(right_start);
let overlap_end = left_end.min(right_end);
let mut all_valid = overlap_start == union_start && overlap_end == union_end;
if overlap_start <= overlap_end {
for value in overlap_start..=overlap_end {
let out_idx = (value - union_start) as usize;
let left_idx = (value - left_start) as usize;
let right_idx = (value - right_start) as usize;
if lvalid.get(left_idx) && rvalid.get(right_idx) {
let result = apply(lsrc[left_idx], rsrc[right_idx]);
data[out_idx] = result;
if result.is_nan() {
all_valid = false;
} else {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
} else {
all_valid = false;
}
}
}
if all_valid {
return Ok(Self::from_f64_values(data));
}
Ok(Self::from_f64_values_with_validity(
data,
ValidityMask::from_words(words, out_len),
))
}
/// Same-index Float64 arithmetic fast path.
///
/// Isomorphic to calling [`Self::aligned_binary_f64`] with
/// `Some(i)`/`Some(i)` positions for every row, but avoids allocating and
/// walking the identity alignment vectors.
pub fn aligned_binary_f64_same_positions(
&self,
right: &Self,
op: ArithmeticOp,
) -> Result<Self, ColumnError> {
debug_assert_eq!(self.len(), right.len());
let out_len = self.len();
let lsrc = self.float64_binary_data();
let rsrc = right.float64_binary_data();
// Fully-valid fast path (br-frankenpandas-f64simd): when neither side has
// a null bit or a NaN, every output position is valid, so emit a single
// monomorphized (autovectorizing) slice op and skip both the per-element
// `nan_aware_validity` mask builds and the per-element fn-pointer/validity
// gating. Bit-identical to the general path under all-valid inputs: the
// arithmetic and the typed `from_f64_values` constructor are the same.
//
// The two input NaN pre-scans look redundant (a NaN-bearing Float64 column
// normally has its validity bit cleared, and `from_f64_values` re-derives
// validity from the output anyway) but they are NOT removable: an input
// NaN must route to the general `Scalar::Null(NaN)` arm, whereas
// `from_f64_values` would surface it as `Scalar::Float64(NaN)` — a
// golden-observable variant difference (and `NaN**0 == 1.0` for `Pow`
// diverges outright). Dropping them is a parity break, not a speedup;
// see br-frankenpandas-d3mfh for the rejected variants.
//
// Instead of two separate input scans + the add + the `from_f64_values`
// output re-scan (four memory passes), FUSE all of them into the single
// arithmetic sweep (br-frankenpandas-9houf): `apply_f64_slices_nan_tracked`
// reports `input_nan`/`output_nan` while it stores `data`. The branch
// outcomes are byte-for-byte the prior fast path:
// * `validity.all() && validity.all() && !input_nan` is EXACTLY the old
// gate (`input_nan == lsrc.any(nan) || rsrc.any(nan)`), and it then
// yields `from_f64_values(data)` — split into a no-rescan all-valid
// stamp when `!output_nan` and the identical `from_f64_values(data)`
// when a generated NaN (e.g. inf-inf) is present.
// * any input NaN with all-valid bits falls through to the general
// Scalar path below (so `Scalar::Null(NaN)` and `NaN**0 == 1.0` stay
// correct), unchanged.
// `same_positions == general` parity is locked by
// `aligned_binary_f64_same_positions_matches_general_path_for_all_ops_with_nan_inf`.
if self.validity.all() && right.validity.all() {
let (data, input_nan, output_nan) = apply_f64_slices_nan_tracked(op, &lsrc, &rsrc);
if !input_nan {
if output_nan {
return Ok(Self::from_f64_values(data));
}
return Ok(Self::from_f64_all_valid_with_finite_opt(data, None));
}
}
let lvalid = self.nan_aware_validity();
let rvalid = right.nan_aware_validity();
let apply = binary_f64_apply(op);
let mut data = Vec::with_capacity(out_len);
let mut all_valid = true;
for i in 0..out_len {
if lvalid.get(i) && rvalid.get(i) {
data.push(apply(lsrc[i], rsrc[i]));
} else {
all_valid = false;
break;
}
}
if all_valid {
return Ok(Self::from_f64_values(data));
}
// Typed nullable output via the LazyNullableFloat64 backing, which renders
// a cleared-bit-with-NaN-datum as a PRESENT `Float64(NaN)` and a
// cleared-bit-with-non-NaN-datum as `Null(NaN)`. So: both-valid ⇒ store
// `apply(l,r)` and SET the bit ONLY when the result is non-NaN (a generated
// NaN like inf-inf keeps a cleared bit but its NaN datum ⇒ present
// `Float64(NaN)`, matching the Scalar tail's `Self::new([Float64(NaN)])`);
// either operand missing ⇒ 0.0 datum + cleared bit ⇒ `Null(NaN)`. Replaces
// the per-element Scalar boxing + Self::new revalidation (~419ms / 17x
// slower on nullable f64+f64). Bit-identical (value bits AND validity),
// locked by `aligned_binary_f64_same_positions_matches_general_path`.
let mut data = vec![0.0_f64; out_len];
let mut valid_words = vec![0_u64; out_len.div_ceil(64)];
for i in 0..out_len {
if lvalid.get(i) && rvalid.get(i) {
let r = apply(lsrc[i], rsrc[i]);
data[i] = r;
if !r.is_nan() {
valid_words[i / 64] |= 1_u64 << (i % 64);
}
}
}
let validity = ValidityMask::from_words(valid_words, out_len);
Ok(Self {
dtype: DType::Float64,
values: ScalarValues::lazy_nullable_float64(data, validity.clone()),
validity,
data: None,
})
}
fn cached_float64_data(&self) -> Option<&[f64]> {
match &self.data {
Some(ColumnData::Float64(data)) if data.len() == self.values.len() => {
return Some(data.as_ref());
}
_ => {}
}
match &self.values {
ScalarValues::LazyAllValidFloat64 { data, .. } if data.len() == self.validity.len() => {
Some(data.as_ref())
}
ScalarValues::LazyStridedFloat64 { len, .. } if *len == self.validity.len() => {
self.values.strided_float64_data()
}
ScalarValues::LazyNullableFloat64 { data, .. } if data.len() == self.validity.len() => {
Some(data.as_slice())
}
ScalarValues::LazyCombineFirstFloat64 { len, .. } if *len == self.validity.len() => {
self.values.combine_first_float64_data()
}
ScalarValues::LazyRepeatedSlicesFloat64 { total_len, .. }
if *total_len == self.validity.len() =>
{
self.values.repeated_slices_f64_data()
}
_ => None,
}
}
fn float64_binary_data(&self) -> std::borrow::Cow<'_, [f64]> {
if let Some(data) = self.cached_float64_data() {
return std::borrow::Cow::Borrowed(data);
}
match ColumnData::from_scalars(&self.values, DType::Float64) {
ColumnData::Float64(data) => std::borrow::Cow::Owned(data.to_vec()),
_ => unreachable!("Float64 materialization must produce Float64 data"),
}
}
/// Validity mask that also marks NaN float values as invalid.
#[must_use]
fn nan_aware_validity(&self) -> ValidityMask {
let mut mask = self.validity.clone();
if let Some(data) = self.cached_float64_data() {
for (i, value) in data.iter().enumerate() {
if value.is_nan() {
mask.set(i, false);
}
}
return mask;
}
for (i, value) in self.values.iter().enumerate() {
if matches!(value, Scalar::Float64(f) if f.is_nan()) {
mask.set(i, false);
}
}
mask
}
pub fn binary_numeric(&self, right: &Self, op: ArithmeticOp) -> Result<Self, ColumnError> {
if self.len() != right.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: right.len(),
});
}
// Typed TEMPORAL arithmetic fast path — BEFORE the numeric common_dtype/to_f64
// machinery, which (a) errors: a temporal scalar is not numeric to `to_f64`, so a
// present temporal pair hits `Scalar::to_f64()? => Err(NonNumericValue)`; (b)
// mis-types: common_dtype(Datetime64, Datetime64) = Datetime64, but pandas returns
// Timedelta64 for the difference; and (c) rejects: common_dtype(Datetime64,
// Timedelta64) = Err(IncompatibleDtypes) before the body runs. So all temporal
// arithmetic ERRORS today. Handle every pandas-defined combo (output dtype VARIES):
// Datetime64 - Datetime64 -> Timedelta64 (elapsed ns)
// Timedelta64 ± Timedelta64 -> Timedelta64
// Datetime64 + Timedelta64 -> Datetime64 (shift a timestamp by a duration)
// Timedelta64 + Datetime64 -> Datetime64 (commutative)
// Datetime64 - Timedelta64 -> Datetime64
// The VALUE is uniformly the raw-ns `Timedelta::add`/`Timedelta::sub` (NaT-propagating,
// saturating — the SAME helpers the rest of FP uses in Series.diff / reductions /
// Timestamp::{add,sub}_timedelta, so byte-consistent); only the OUTPUT dtype differs.
// A row is missing iff either operand is missing (validity unset OR the NaT sentinel,
// which add/sub fold into a NaT result). Every OTHER temporal combo — Datetime64 +
// Datetime64 (pandas raises), Timedelta64 - Datetime64 (raises), mul/div/mod/pow/
// floordiv — falls through to the existing path, which errors / rejects via
// IncompatibleDtypes, matching pandas raising.
let temporal_out: Option<DType> = match (self.dtype, right.dtype, op) {
(DType::Datetime64, DType::Datetime64, ArithmeticOp::Sub) => Some(DType::Timedelta64),
(DType::Timedelta64, DType::Timedelta64, ArithmeticOp::Sub | ArithmeticOp::Add) => {
Some(DType::Timedelta64)
}
(DType::Datetime64, DType::Timedelta64, ArithmeticOp::Add | ArithmeticOp::Sub)
| (DType::Timedelta64, DType::Datetime64, ArithmeticOp::Add) => Some(DType::Datetime64),
_ => None,
};
if let Some(out_dtype) = temporal_out
&& let (Some((l, lv, _)), Some((r, rv, _))) =
(self.temporal_i64_backing(), right.temporal_i64_backing())
{
let apply: fn(i64, i64) -> i64 = if matches!(op, ArithmeticOp::Add) {
fp_types::Timedelta::add
} else {
fp_types::Timedelta::sub
};
let data: Vec<i64> = l.iter().zip(r).map(|(&a, &b)| apply(a, b)).collect();
let mut validity = lv.and_mask(rv);
for (i, &v) in data.iter().enumerate() {
if v == Timedelta::NAT {
validity.set(i, false);
}
}
return Ok(match out_dtype {
DType::Datetime64 => Self::from_datetime64_values_with_validity(data, validity),
_ => Self::from_timedelta64_values_with_validity(data, validity),
});
}
let mut out_dtype = common_dtype(self.dtype, right.dtype)?;
if matches!(out_dtype, DType::Bool) {
out_dtype = DType::Int64;
}
// Div always produces Float64. Pow keeps Int64 for int**int (numpy/pandas
// semantics: 2 ** 3 -> int64 8, not float), but promotes to Float64 for any
// float operand. Mod and FloorDiv preserve int if there are no zero divisors.
let int_pow = matches!(op, ArithmeticOp::Pow)
&& self.dtype == DType::Int64
&& right.dtype == DType::Int64;
if matches!(op, ArithmeticOp::Div | ArithmeticOp::Pow) && !int_pow {
out_dtype = DType::Float64;
}
// AG-10: Try vectorized path first; fallback to scalar path.
if let Some(result) = self.try_vectorized_binary(right, op, out_dtype) {
return result;
}
// For Mod/FloorDiv: if vectorized failed (likely due to zero divisors), use Float64
if matches!(op, ArithmeticOp::Mod | ArithmeticOp::FloorDiv)
&& matches!(out_dtype, DType::Int64)
{
out_dtype = DType::Float64;
}
// Scalar fallback path (original implementation).
let values = self
.values
.iter()
.zip(&right.values)
.map(|(left, right)| {
if left.is_missing() || right.is_missing() {
return Ok::<_, ColumnError>(if left.is_nan() || right.is_nan() {
Scalar::Null(NullKind::NaN)
} else {
Scalar::missing_for_dtype(out_dtype)
});
}
if matches!(out_dtype, DType::Int64) {
let lhs_i64 = match cast_scalar(left, DType::Int64)? {
Scalar::Int64(v) => v,
_ => unreachable!(),
};
let rhs_i64 = match cast_scalar(right, DType::Int64)? {
Scalar::Int64(v) => v,
_ => unreachable!(),
};
let result = match op {
ArithmeticOp::Add => lhs_i64.wrapping_add(rhs_i64),
ArithmeticOp::Sub => lhs_i64.wrapping_sub(rhs_i64),
ArithmeticOp::Mul => lhs_i64.wrapping_mul(rhs_i64),
// int ** int stays int64 (numpy/pandas). A negative integer
// exponent raises, matching numpy's "Integers to negative
// integer powers are not allowed." Overflow wraps like int64.
ArithmeticOp::Pow => {
if rhs_i64 < 0 {
return Err(ColumnError::NegativeIntegerPower);
}
lhs_i64.wrapping_pow(u32::try_from(rhs_i64).unwrap_or(u32::MAX))
}
ArithmeticOp::Div | ArithmeticOp::Mod | ArithmeticOp::FloorDiv => {
unreachable!()
}
};
return Ok(Scalar::Int64(result));
}
let lhs = left.to_f64()?;
let rhs = right.to_f64()?;
let result = match op {
ArithmeticOp::Add => lhs + rhs,
ArithmeticOp::Sub => lhs - rhs,
ArithmeticOp::Mul => lhs * rhs,
ArithmeticOp::Div => lhs / rhs,
ArithmeticOp::Mod => python_mod_f64(lhs, rhs),
ArithmeticOp::Pow => lhs.powf(rhs),
ArithmeticOp::FloorDiv => python_floor_div_f64(lhs, rhs),
};
Ok(Scalar::Float64(result))
})
.collect::<Result<Vec<_>, _>>()?;
Self::new(out_dtype, values)
}
/// Element-wise addition, matching `pd.Series.add()`.
pub fn add(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_numeric(right, ArithmeticOp::Add)
}
/// Reverse element-wise addition, matching `pd.Series.radd()`.
pub fn radd(&self, left: &Self) -> Result<Self, ColumnError> {
left.binary_numeric(self, ArithmeticOp::Add)
}
/// Element-wise subtraction, matching `pd.Series.sub()`.
pub fn sub(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_numeric(right, ArithmeticOp::Sub)
}
/// Reverse element-wise subtraction, matching `pd.Series.rsub()`.
pub fn rsub(&self, left: &Self) -> Result<Self, ColumnError> {
left.binary_numeric(self, ArithmeticOp::Sub)
}
/// Alias for [`sub`](Self::sub), matching `pd.Series.subtract()`.
pub fn subtract(&self, right: &Self) -> Result<Self, ColumnError> {
self.sub(right)
}
/// Element-wise multiplication, matching `pd.Series.mul()`.
pub fn mul(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_numeric(right, ArithmeticOp::Mul)
}
/// Reverse element-wise multiplication, matching `pd.Series.rmul()`.
pub fn rmul(&self, left: &Self) -> Result<Self, ColumnError> {
left.binary_numeric(self, ArithmeticOp::Mul)
}
/// Alias for [`mul`](Self::mul), matching `pd.Series.multiply()`.
pub fn multiply(&self, right: &Self) -> Result<Self, ColumnError> {
self.mul(right)
}
/// Element-wise true division, matching `pd.Series.div()`.
pub fn div(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_numeric(right, ArithmeticOp::Div)
}
/// Reverse element-wise true division, matching `pd.Series.rdiv()`.
pub fn rdiv(&self, left: &Self) -> Result<Self, ColumnError> {
left.binary_numeric(self, ArithmeticOp::Div)
}
/// Alias for [`div`](Self::div), matching `pd.Series.divide()`.
pub fn divide(&self, right: &Self) -> Result<Self, ColumnError> {
self.div(right)
}
/// Alias for [`div`](Self::div), matching `pd.Series.truediv()`.
pub fn truediv(&self, right: &Self) -> Result<Self, ColumnError> {
self.div(right)
}
/// Alias for [`rdiv`](Self::rdiv), matching `pd.Series.rtruediv()`.
pub fn rtruediv(&self, left: &Self) -> Result<Self, ColumnError> {
self.rdiv(left)
}
/// Element-wise floor division, matching `pd.Series.floordiv()`.
pub fn floordiv(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_numeric(right, ArithmeticOp::FloorDiv)
}
/// Reverse element-wise floor division, matching `pd.Series.rfloordiv()`.
pub fn rfloordiv(&self, left: &Self) -> Result<Self, ColumnError> {
left.binary_numeric(self, ArithmeticOp::FloorDiv)
}
/// Element-wise modulo, matching `pd.Series.mod()`.
pub fn r#mod(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_numeric(right, ArithmeticOp::Mod)
}
/// Reverse element-wise modulo, matching `pd.Series.rmod()`.
pub fn rmod(&self, left: &Self) -> Result<Self, ColumnError> {
left.binary_numeric(self, ArithmeticOp::Mod)
}
/// Element-wise exponentiation, matching `pd.Series.pow()`.
pub fn pow(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_numeric(right, ArithmeticOp::Pow)
}
/// Reverse element-wise exponentiation, matching `pd.Series.rpow()`.
pub fn rpow(&self, left: &Self) -> Result<Self, ColumnError> {
left.binary_numeric(self, ArithmeticOp::Pow)
}
/// Alias for pow, matching NumPy naming.
pub fn power(&self, right: &Self) -> Result<Self, ColumnError> {
self.pow(right)
}
/// Float power, always returning Float64.
///
/// Matches np.float_power(x, y). Unlike power(), this always returns
/// Float64 and returns NaN for negative bases with non-integer exponents
/// (where the result would be complex).
pub fn float_power(&self, right: &Self) -> Result<Self, ColumnError> {
if self.len() != right.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: right.len(),
});
}
if let Some(out) = self.typed_float_binary_par(right, |b, e| b.powf(e)) {
return Ok(out);
}
// Nullable/mixed: both-present ⇒ b.powf(e), either-missing ⇒ NaN⇒missing. A
// powf-produced NaN (e.g. (-1).powf(0.5)) is marked missing by from_f64_values,
// exactly as the Scalar loop's Float64(NaN) ⇒ Self::new does. Bit-identical.
if let Some(out) = self.typed_nan_propagate_binary(right, |b, e| b.powf(e)) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (base, exp) in self.values.iter().zip(&right.values) {
if base.is_missing() || exp.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let b = base.to_f64().map_err(ColumnError::Type)?;
let e = exp.to_f64().map_err(ColumnError::Type)?;
let result = b.powf(e);
out.push(Scalar::Float64(result));
}
Self::new(DType::Float64, out)
}
/// Alias for mod, matching NumPy naming.
pub fn remainder(&self, right: &Self) -> Result<Self, ColumnError> {
self.r#mod(right)
}
/// Alias for floordiv, matching NumPy naming.
pub fn floor_divide(&self, right: &Self) -> Result<Self, ColumnError> {
self.floordiv(right)
}
/// Alias for div, matching NumPy naming.
pub fn true_divide(&self, right: &Self) -> Result<Self, ColumnError> {
self.div(right)
}
/// Element-wise arctangent of y/x.
pub fn atan2(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_float_binary_par(other, |y, x| y.atan2(x)) {
return Ok(out);
}
// Nullable/mixed: both-present ⇒ y.atan2(x), either-missing ⇒ NaN⇒missing —
// the typed_nan_propagate_binary rule (atan2 of finite/±inf never yields a
// non-input NaN, so bit-identical to the Scalar loop below).
if let Some(out) = self.typed_nan_propagate_binary(other, |y, x| y.atan2(x)) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (y, x) in self.values.iter().zip(&other.values) {
if y.is_missing() || x.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let yf = y.to_f64().map_err(ColumnError::Type)?;
let xf = x.to_f64().map_err(ColumnError::Type)?;
out.push(Scalar::Float64(yf.atan2(xf)));
}
Self::new(DType::Float64, out)
}
/// Element-wise Euclidean distance sqrt(x^2 + y^2).
pub fn hypot(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_float_binary_par(other, |a, b| a.hypot(b)) {
return Ok(out);
}
// Nullable/mixed: hypot of finite/±inf never yields a non-input NaN, so the
// both-present ⇒ f, else NaN⇒missing rule is bit-identical to the Scalar loop.
if let Some(out) = self.typed_nan_propagate_binary(other, |a, b| a.hypot(b)) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let af = a.to_f64().map_err(ColumnError::Type)?;
let bf = b.to_f64().map_err(ColumnError::Type)?;
out.push(Scalar::Float64(af.hypot(bf)));
}
Self::new(DType::Float64, out)
}
/// Element-wise floating-point remainder (fmod).
pub fn fmod(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_float_binary(other, |a, b| a % b) {
return Ok(out);
}
// Nullable/mixed: both-present ⇒ a%b, either-missing ⇒ NaN⇒missing. `a%0` (or
// inf%b) yields NaN, which from_f64_values marks missing — exactly as the
// Scalar loop's Float64(NaN) ⇒ Self::new does. Bit-identical.
if let Some(out) = self.typed_nan_propagate_binary(other, |a, b| a % b) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let af = a.to_f64().map_err(ColumnError::Type)?;
let bf = b.to_f64().map_err(ColumnError::Type)?;
out.push(Scalar::Float64(af % bf));
}
Self::new(DType::Float64, out)
}
/// Element-wise copysign: magnitude of self with sign of other.
pub fn copysign(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_float_binary(other, |m, s| m.copysign(s)) {
return Ok(out);
}
// Nullable/mixed: copysign of finite/±inf magnitude never yields a non-input
// NaN, so both-present ⇒ m.copysign(s), else NaN⇒missing is bit-identical.
if let Some(out) = self.typed_nan_propagate_binary(other, |m, s| m.copysign(s)) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (mag, sign) in self.values.iter().zip(&other.values) {
if mag.is_missing() || sign.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let mf = mag.to_f64().map_err(ColumnError::Type)?;
let sf = sign.to_f64().map_err(ColumnError::Type)?;
out.push(Scalar::Float64(mf.copysign(sf)));
}
Self::new(DType::Float64, out)
}
/// Element-wise sign: -1, 0, or 1.
pub fn sign(&self) -> Result<Self, ColumnError> {
// Typed, dtype-preserving fast path (all-valid only): Int64 -> Int64
// (-1/0/1), Float64 -> Float64. all-valid Float64 has no NaN so the
// is_nan branch never fires; -0.0 -> 0.0 (neither >0.0 nor <0.0), exactly
// as the scalar loop. Bit-identical.
if let Some(data) = self.as_i64_slice() {
return Ok(Self::from_i64_values_owned(
data.iter()
.map(|&x| {
if x > 0 {
1
} else if x < 0 {
-1
} else {
0
}
})
.collect(),
));
}
if let Some(data) = self.as_f64_slice() {
// sign(all-valid) ∈ {-1.0, 0.0, 1.0} — always finite, never NaN — so
// the output is provably all-valid AND all-finite. Skip the
// from_f64_values has_nan/all_finite rescan with a `Some(true)`
// witness (mirror of abs). Bit-identical (same -1/0/1, -0.0→0.0).
let out: Vec<f64> = data
.iter()
.map(|&x| {
if x > 0.0 {
1.0
} else if x < 0.0 {
-1.0
} else {
0.0
}
})
.collect();
return Ok(Self::from_f64_all_valid_with_finite_opt(out, Some(true)));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => {
let s = if *x > 0 {
1
} else if *x < 0 {
-1
} else {
0
};
out.push(Scalar::Int64(s));
}
Scalar::Float64(x) => {
let s = if x.is_nan() {
f64::NAN
} else if *x > 0.0 {
1.0
} else if *x < 0.0 {
-1.0
} else {
0.0
};
out.push(Scalar::Float64(s));
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
let dtype = match self.dtype {
DType::Int64 => DType::Int64,
_ => DType::Float64,
};
Self::new(dtype, out)
}
/// Test element-wise for negative sign bit.
///
/// Matches np.signbit(x). Returns True for negative values including -0.0.
pub fn signbit(&self) -> Result<Self, ColumnError> {
// Typed fast path (all-valid only, output Bool): Int64 sign via x < 0,
// Float64 via is_sign_negative (so -0.0 -> true). Bit-identical; all-valid
// ⇒ the missing -> Bool(false) branch never applies.
if let Some(data) = self.as_i64_slice() {
return Ok(Self::from_bool_values(
data.iter().map(|&x| x < 0).collect(),
));
}
if let Some(data) = self.as_f64_slice() {
return Ok(Self::from_bool_values(
data.iter().map(|&x| x.is_sign_negative()).collect(),
));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Bool(false));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Bool(*x < 0)),
Scalar::Float64(x) => out.push(Scalar::Bool(x.is_sign_negative())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Bool, out)
}
/// Compute the Heaviside step function.
///
/// Matches np.heaviside(x, h0). Returns:
/// - 0 where x < 0
/// - h0 where x == 0
/// - 1 where x > 0
pub fn heaviside(&self, h0: f64) -> Result<Self, ColumnError> {
// Typed fast path (all-valid or nullable Float64/Int64 ⇒ Float64 out): present
// ⇒ x<0?0:x>0?1:h0. The `is_nan ⇒ NaN` guard is REQUIRED: typed_float_unary's
// nullable arm passes a valid-bit-set NaN datum through `f` (it drops only
// validity-unset slots), and heaviside's bare comparisons would fall to the
// `else` (⇒ h0, a finite VALUE) instead of NaN — so the kernel must propagate
// NaN itself, making it match the Scalar loop's is_missing(NaN)⇒NaN (from_f64
// _values then marks it missing). Int64 has no NaN so the guard is inert there.
if let Some(out) = self.typed_float_unary(|x| {
if x.is_nan() {
f64::NAN
} else if x < 0.0 {
0.0
} else if x > 0.0 {
1.0
} else {
h0
}
}) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => {
let val = if *x < 0 {
0.0
} else if *x > 0 {
1.0
} else {
h0
};
out.push(Scalar::Float64(val));
}
Scalar::Float64(x) => {
let val = if x.is_nan() {
f64::NAN
} else if *x < 0.0 {
0.0
} else if *x > 0.0 {
1.0
} else {
h0
};
out.push(Scalar::Float64(val));
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Element-wise greatest common divisor.
///
/// Matches np.gcd(x, y). Works on integer values.
pub fn gcd(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
// Typed Int64 fast path (both-present ⇒ Int64(gcd), else Null(Null)); same
// kernel + missing rule as the Scalar loop below, no Scalar materialization.
if let Some(out) = self.typed_i64_both_present_binary(other, Self::compute_gcd_i64) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
match (a, b) {
(Scalar::Int64(x), Scalar::Int64(y)) => {
out.push(Scalar::Int64(Self::compute_gcd_i64(*x, *y)));
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{a:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Int64, out)
}
/// Element-wise least common multiple.
///
/// Matches np.lcm(x, y). Works on integer values.
pub fn lcm(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
// Typed Int64 fast path (both-present ⇒ Int64(lcm), else Null(Null)); same
// kernel + missing rule as the Scalar loop below, no Scalar materialization.
if let Some(out) = self.typed_i64_both_present_binary(other, Self::compute_lcm_i64) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
match (a, b) {
(Scalar::Int64(x), Scalar::Int64(y)) => {
out.push(Scalar::Int64(Self::compute_lcm_i64(*x, *y)));
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{a:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Int64, out)
}
/// Element-wise bitwise AND.
pub fn bitwise_and(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_bool_binary(other, |left, right| left && right) {
return Ok(out);
}
// Typed Int64 fast path (both-present ⇒ Int64(x & y), else Null(Null)).
if let Some(out) = self.typed_i64_both_present_binary(other, |x, y| x & y) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
match (a, b) {
(Scalar::Int64(x), Scalar::Int64(y)) => out.push(Scalar::Int64(x & y)),
(Scalar::Bool(x), Scalar::Bool(y)) => out.push(Scalar::Bool(*x && *y)),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{a:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(self.dtype, out)
}
/// Element-wise bitwise OR.
pub fn bitwise_or(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_bool_binary(other, |left, right| left || right) {
return Ok(out);
}
// Typed Int64 fast path (both-present ⇒ Int64(x | y), else Null(Null)).
if let Some(out) = self.typed_i64_both_present_binary(other, |x, y| x | y) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
match (a, b) {
(Scalar::Int64(x), Scalar::Int64(y)) => out.push(Scalar::Int64(x | y)),
(Scalar::Bool(x), Scalar::Bool(y)) => out.push(Scalar::Bool(*x || *y)),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{a:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(self.dtype, out)
}
/// Element-wise bitwise XOR.
pub fn bitwise_xor(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_bool_binary(other, |left, right| left ^ right) {
return Ok(out);
}
// Typed Int64 fast path (both-present ⇒ Int64(x ^ y), else Null(Null)).
if let Some(out) = self.typed_i64_both_present_binary(other, |x, y| x ^ y) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
match (a, b) {
(Scalar::Int64(x), Scalar::Int64(y)) => out.push(Scalar::Int64(x ^ y)),
(Scalar::Bool(x), Scalar::Bool(y)) => out.push(Scalar::Bool(*x ^ *y)),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{a:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(self.dtype, out)
}
/// Element-wise left bit shift.
///
/// Matches np.left_shift(x, y). Shifts bits of x left by y positions.
pub fn left_shift(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
// Typed Int64 fast path (both-present ⇒ Int64(x << clamp(y)), else Null(Null));
// same kernel + missing rule as the Scalar loop below, no Scalar materialization.
if let Some(out) = self.typed_i64_both_present_binary(other, |x, y| {
x.wrapping_shl(y.clamp(0, 63) as u32)
}) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
match (a, b) {
(Scalar::Int64(x), Scalar::Int64(y)) => {
let shift = (*y).clamp(0, 63) as u32;
out.push(Scalar::Int64(x.wrapping_shl(shift)));
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{a:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Int64, out)
}
/// Element-wise right bit shift.
///
/// Matches np.right_shift(x, y). Shifts bits of x right by y positions.
pub fn right_shift(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
// Typed Int64 fast path (both-present ⇒ Int64(x >> clamp(y)), else Null(Null));
// same kernel + missing rule as the Scalar loop below, no Scalar materialization.
if let Some(out) = self.typed_i64_both_present_binary(other, |x, y| {
x.wrapping_shr(y.clamp(0, 63) as u32)
}) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
match (a, b) {
(Scalar::Int64(x), Scalar::Int64(y)) => {
let shift = (*y).clamp(0, 63) as u32;
out.push(Scalar::Int64(x.wrapping_shr(shift)));
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{a:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Int64, out)
}
/// Element-wise bitwise NOT (invert).
pub fn bitwise_not(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_bool_unary(|value| !value) {
return Ok(out);
}
// Typed Int64 (all-valid + nullable): `!x` over the raw &[i64], dtype-preserving
// with NO NaN, so it preserves missingness exactly (output validity == input
// validity — a masked slot's `!garbage` is hidden). Bit-identical to the Scalar
// loop: present ⇒ Int64(!x); missing ⇒ Null(Null) == missing_for_dtype(Int64) ==
// from_i64_values_with_validity's cleared bit == the loop's v.clone() of an
// Int64-missing slot. Mirror of the abs/neg nullable-Int64 arms.
if let Some(data) = self.as_i64_slice() {
return Ok(Self::from_i64_values_owned(data.iter().map(|&x| !x).collect()));
}
if self.dtype == DType::Int64
&& let Some((data, _)) = self.as_i64_slice_with_validity()
{
let out: Vec<i64> = data.iter().map(|&x| !x).collect();
return Ok(Self::from_i64_values_with_validity(out, self.validity.clone()));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Int64(!x)),
Scalar::Bool(x) => out.push(Scalar::Bool(!x)),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(self.dtype, out)
}
/// Alias for bitwise_not.
pub fn invert(&self) -> Result<Self, ColumnError> {
self.bitwise_not()
}
/// Element-wise maximum, NaN propagates.
pub fn maximum(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
// all-valid ⇒ no NaN (NaN floats mark the column invalid), so the scalar
// loop's is_nan branch never fires and the result is af.max(bf).
if let Some(out) = self.typed_float_binary(other, f64::max) {
return Ok(out);
}
if let Some(out) = self.typed_nan_propagate_binary(other, f64::max) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let af = a.to_f64().map_err(ColumnError::Type)?;
let bf = b.to_f64().map_err(ColumnError::Type)?;
if af.is_nan() || bf.is_nan() {
out.push(Scalar::Float64(f64::NAN));
} else {
out.push(Scalar::Float64(af.max(bf)));
}
}
Self::new(DType::Float64, out)
}
/// Typed nullable pairwise fast path for the NaN-PROPAGATING element-wise binaries
/// (`maximum`/`minimum`): both columns Float64/Int64 (all-valid or nullable). The
/// result is `f(x, y)` only when BOTH slots are present, else `Float64(NaN)` — bit-
/// identical to the Scalar loop (`a.is_missing() || b.is_missing() ⇒ NaN`, and the
/// redundant `af.is_nan() || bf.is_nan()` check drops nothing for present values,
/// which are non-NaN by is_missing). get_present == !is_missing (validity-set AND
/// non-NaN for Float64, KEEPING ±inf; validity-set for Int64). Output is Float64:
/// from_f64_values marks the either-missing NaN slots missing, exactly as
/// Self::new(Float64, [Float64(NaN)]) does. Covers mixed i64×f64. `None` unless
/// both columns expose a typed numeric view.
/// Euclid GCD of two i64 (non-negative). Shared by `gcd`/`lcm` typed + Scalar arms.
fn compute_gcd_i64(mut a: i64, mut b: i64) -> i64 {
a = a.abs();
b = b.abs();
while b != 0 {
let t = b;
b = a % b;
a = t;
}
a
}
/// Element-wise LCM of two i64. Shared by `lcm`'s typed + Scalar arms.
fn compute_lcm_i64(x: i64, y: i64) -> i64 {
let g = Self::compute_gcd_i64(x, y);
if g == 0 { 0 } else { (x.abs() / g) * y.abs() }
}
/// Typed fast path for Int64-preserving two-column ops whose result is
/// `Int64(f(x,y))` when BOTH slots are present and MISSING (`Null(Null)` ==
/// missing_for_dtype(Int64)) when either is absent — i.e. gcd/lcm/bitwise_&|^ on
/// Int64 inputs. Reads both raw &[i64] + validity and reuses the input-present
/// mask, instead of materializing BOTH columns' Vec<Scalar> + a trailing
/// Vec<Scalar> result + Column::new. Bit-identical to the Scalar loop: same `f`
/// over the same present pairs; a cleared bit in `from_i64_values_with_validity`
/// renders `Null(Null)`, exactly the `Scalar::Null(NullKind::Null)` those loops
/// push. `None` unless BOTH columns are typed Int64 (the loops' non-Int64 arm
/// errors or is a different dtype — kept on the Scalar path).
fn typed_i64_both_present_binary(&self, other: &Self, f: fn(i64, i64) -> i64) -> Option<Self> {
if self.dtype != DType::Int64 || other.dtype != DType::Int64 {
return None;
}
let (l, lv) = self.as_i64_slice_with_validity()?;
let (r, rv) = other.as_i64_slice_with_validity()?;
let n = l.len().min(r.len());
let mut out = vec![0_i64; n];
let mut vmask = ValidityMask::all_valid(n);
for i in 0..n {
if lv.get(i) && rv.get(i) {
out[i] = f(l[i], r[i]);
} else {
vmask.set(i, false);
}
}
Some(Self::from_i64_values_with_validity(out, vmask))
}
fn typed_nan_propagate_binary(
&self,
other: &Self,
f: fn(f64, f64) -> f64,
) -> Option<Self> {
let (sa, sb) = (self.typed_numeric_values()?, other.typed_numeric_values()?);
let n = sa.len().min(sb.len());
let out: Vec<f64> = (0..n)
.map(|i| match (sa.get_present(i), sb.get_present(i)) {
(Some(x), Some(y)) => f(x, y),
_ => f64::NAN,
})
.collect();
Some(Self::from_f64_values(out))
}
/// Typed nullable pairwise fast path for the NaN/missing-IGNORING element-wise
/// binaries (`fmax`/`fmin`): both columns Float64/Int64 (all-valid or nullable).
/// The result is `f(x, y)` when BOTH present, the single present value when only
/// ONE is, else `Float64(NaN)` (both absent) — bit-identical to the Scalar loop,
/// which reads `to_f64().ok()` per side and skips a NaN operand (`if x.is_nan()
/// => y`, `(Some, None) => x`, …): get_present drops exactly the NaN AND null
/// slots that fmax/fmin's is_nan / None arms treat as "not usable", so the four
/// (present, present) cases collapse to this match. get_present KEEPS ±inf.
/// Output is Float64; from_f64_values marks the both-absent NaN slots missing,
/// exactly as Self::new(Float64, [Float64(NaN)]) does. Covers mixed i64×f64.
fn typed_nan_ignore_binary(
&self,
other: &Self,
f: fn(f64, f64) -> f64,
) -> Option<Self> {
let (sa, sb) = (self.typed_numeric_values()?, other.typed_numeric_values()?);
let n = sa.len().min(sb.len());
let out: Vec<f64> = (0..n)
.map(|i| match (sa.get_present(i), sb.get_present(i)) {
(Some(x), Some(y)) => f(x, y),
(Some(x), None) => x,
(None, Some(y)) => y,
(None, None) => f64::NAN,
})
.collect();
Some(Self::from_f64_values(out))
}
/// Element-wise minimum, NaN propagates.
pub fn minimum(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_float_binary(other, f64::min) {
return Ok(out);
}
if let Some(out) = self.typed_nan_propagate_binary(other, f64::min) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let af = a.to_f64().map_err(ColumnError::Type)?;
let bf = b.to_f64().map_err(ColumnError::Type)?;
if af.is_nan() || bf.is_nan() {
out.push(Scalar::Float64(f64::NAN));
} else {
out.push(Scalar::Float64(af.min(bf)));
}
}
Self::new(DType::Float64, out)
}
/// Element-wise maximum, ignoring NaN.
pub fn fmax(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
// all-valid numeric ⇒ both to_f64().ok() are Some(non-NaN), so the result
// is x.max(y) — same as `maximum` on this domain.
if let Some(out) = self.typed_float_binary(other, f64::max) {
return Ok(out);
}
if let Some(out) = self.typed_nan_ignore_binary(other, f64::max) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
let af = a.to_f64().ok();
let bf = b.to_f64().ok();
let result = match (af, bf) {
(Some(x), Some(y)) if x.is_nan() => y,
(Some(x), Some(y)) if y.is_nan() => x,
(Some(x), Some(y)) => x.max(y),
(Some(x), None) => x,
(None, Some(y)) => y,
(None, None) => f64::NAN,
};
out.push(Scalar::Float64(result));
}
Self::new(DType::Float64, out)
}
/// Element-wise minimum, ignoring NaN.
pub fn fmin(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_float_binary(other, f64::min) {
return Ok(out);
}
if let Some(out) = self.typed_nan_ignore_binary(other, f64::min) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
let af = a.to_f64().ok();
let bf = b.to_f64().ok();
let result = match (af, bf) {
(Some(x), Some(y)) if x.is_nan() => y,
(Some(x), Some(y)) if y.is_nan() => x,
(Some(x), Some(y)) => x.min(y),
(Some(x), None) => x,
(None, Some(y)) => y,
(None, None) => f64::NAN,
};
out.push(Scalar::Float64(result));
}
Self::new(DType::Float64, out)
}
fn typed_bool_binary<F>(&self, other: &Self, op: F) -> Option<Self>
where
F: Fn(bool, bool) -> bool,
{
let left = self.as_bool_slice()?;
let right = other.as_bool_slice()?;
(left.len() == right.len()).then(|| {
Self::from_bool_values(
left.iter()
.zip(right)
.map(|(&left_value, &right_value)| op(left_value, right_value))
.collect(),
)
})
}
fn typed_bool_unary<F>(&self, op: F) -> Option<Self>
where
F: Fn(bool) -> bool,
{
let data = self.as_bool_slice()?;
Some(Self::from_bool_values(
data.iter().map(|&value| op(value)).collect(),
))
}
/// Raw packed `&[bool]` backing + validity mask for a Bool column, covering
/// BOTH the all-valid backings (`as_bool_slice`: contiguous / LazyAllValidBool
/// / LazyShiftedBool, whose `self.validity` is the all-valid sentinel) and the
/// `LazyNullableBool` variant (data + its validity). Returns None for non-Bool
/// dtypes and for eager Scalar-backed Bool columns carrying mixed NullKind
/// values (validity not all AND not LazyNullableBool) — those keep the generic
/// Scalar path, mirroring the fillna/dropna variant-gating.
fn bool_data_and_validity(&self) -> Option<(&[bool], &ValidityMask)> {
if self.dtype != DType::Bool {
return None;
}
if let ScalarValues::LazyNullableBool { data, validity, .. } = &self.values {
return Some((data.as_ref(), validity));
}
let slice = self.as_bool_slice()?;
Some((slice, &self.validity))
}
/// Nullable-capable sibling of `typed_bool_binary`: both operands are Bool
/// columns (all-valid OR `LazyNullableBool`). Apply `op` over the raw bool
/// slices — a masked slot computes a throwaway value the combined mask then
/// hides — and AND the two validity masks so the output is missing exactly
/// where either input is missing, matching the Scalar loop's
/// `a.is_missing() || b.is_missing() ⇒ Null(Null)`. Present slots use the same
/// `op(a, b)` on the same bools, and `from_bool_values_with_validity`
/// materializes a missing slot as `Null(Null) == missing_for_dtype(Bool)`, so
/// this is bit-identical to the generic loop for Bool×Bool. Skips the
/// Vec<Scalar> materialization + Column::new. None for non-Bool / mixed
/// operands (generic numeric-coercing path retained) or length mismatch.
fn typed_bool_binary_nullable<F>(&self, other: &Self, op: F) -> Option<Self>
where
F: Fn(bool, bool) -> bool,
{
let (ld, lv) = self.bool_data_and_validity()?;
let (rd, rv) = other.bool_data_and_validity()?;
if ld.len() != rd.len() {
return None;
}
let bools: Vec<bool> = ld
.iter()
.zip(rd)
.map(|(&a, &b)| op(a, b))
.collect();
let out_valid = lv.and_mask(rv);
Some(Self::from_bool_values_with_validity(bools, out_valid))
}
/// Logical AND between two boolean columns.
pub fn logical_and(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_bool_binary(other, |left, right| left && right) {
return Ok(out);
}
if let Some(out) = self.typed_bool_binary_nullable(other, |left, right| left && right) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
let av = match a {
Scalar::Bool(x) => *x,
_ => a.to_f64().map(|v| v != 0.0).unwrap_or(false),
};
let bv = match b {
Scalar::Bool(x) => *x,
_ => b.to_f64().map(|v| v != 0.0).unwrap_or(false),
};
out.push(Scalar::Bool(av && bv));
}
Self::new(DType::Bool, out)
}
/// Logical OR between two boolean columns.
pub fn logical_or(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_bool_binary(other, |left, right| left || right) {
return Ok(out);
}
if let Some(out) = self.typed_bool_binary_nullable(other, |left, right| left || right) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
let av = match a {
Scalar::Bool(x) => *x,
_ => a.to_f64().map(|v| v != 0.0).unwrap_or(false),
};
let bv = match b {
Scalar::Bool(x) => *x,
_ => b.to_f64().map(|v| v != 0.0).unwrap_or(false),
};
out.push(Scalar::Bool(av || bv));
}
Self::new(DType::Bool, out)
}
/// Logical XOR between two boolean columns.
pub fn logical_xor(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
if let Some(out) = self.typed_bool_binary(other, |left, right| left ^ right) {
return Ok(out);
}
if let Some(out) = self.typed_bool_binary_nullable(other, |left, right| left ^ right) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
let av = match a {
Scalar::Bool(x) => *x,
_ => a.to_f64().map(|v| v != 0.0).unwrap_or(false),
};
let bv = match b {
Scalar::Bool(x) => *x,
_ => b.to_f64().map(|v| v != 0.0).unwrap_or(false),
};
out.push(Scalar::Bool(av ^ bv));
}
Self::new(DType::Bool, out)
}
/// Logical NOT (element-wise negation to boolean).
pub fn logical_not(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_bool_unary(|value| !value) {
return Ok(out);
}
// Typed Int64/Float64 (all-valid + nullable ⇒ Bool out): logical_not of a
// numeric is `!(v != 0) == (v == 0)`. Build the Bool buffer straight over the
// raw slice + an explicit validity mask, skipping the Vec<Scalar> materialization
// + Column::new. Bit-identical to the Scalar loop: present ⇒ Bool(v == 0);
// missing (validity-unset, OR a valid-bit-set NaN for Float64 which the loop's
// is_missing() drops) ⇒ Null(Null) == missing_for_dtype(Bool). Int64 has no NaN
// so present == validity-set; Float64 present == validity-set AND non-NaN
// (matching the loop's `to_f64()` on a NON-missing scalar). ±inf ⇒ inf != 0 ⇒
// Bool(false), kept. No from_f64_values NaN-render trap (Bool out + explicit
// mask). Other dtypes / mixed keep the Scalar path.
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let bools: Vec<bool> = data.iter().map(|&x| x == 0).collect();
return Ok(Self::from_bool_values_with_validity(bools, validity.clone()));
}
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let mut bools = vec![false; data.len()];
let mut vmask = ValidityMask::all_valid(data.len());
for i in 0..data.len() {
if validity.get(i) && !data[i].is_nan() {
bools[i] = data[i] == 0.0;
} else {
vmask.set(i, false);
}
}
return Ok(Self::from_bool_values_with_validity(bools, vmask));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Null(NullKind::Null));
continue;
}
let bv = match v {
Scalar::Bool(x) => *x,
_ => v.to_f64().map(|x| x != 0.0).unwrap_or(false),
};
out.push(Scalar::Bool(!bv));
}
Self::new(DType::Bool, out)
}
/// Borrow the raw `&[i64]` nanosecond backing + validity + NaT sentinel for an
/// all-valid or nullable `Datetime64`/`Timedelta64` column. `None` for any other
/// dtype or a non-materialized temporal backing (which keeps the generic Scalar
/// path). Shared by the typed temporal arms of `binary_comparison` and
/// `compare_scalar`; a method (not a closure) so the borrows tie to `self`.
fn temporal_i64_backing(&self) -> Option<(&[i64], &ValidityMask, i64)> {
let (all_valid, nat) = match self.dtype {
DType::Datetime64 => (self.as_datetime64_slice(), Timestamp::NAT),
DType::Timedelta64 => (self.as_timedelta64_slice(), Timedelta::NAT),
_ => return None,
};
if let Some(slice) = all_valid {
return Some((slice, &self.validity, nat));
}
match &self.values {
ScalarValues::LazyNullableDatetime64 { data, validity, .. }
| ScalarValues::LazyNullableTimedelta64 { data, validity, .. } => {
Some((data.as_slice(), validity, nat))
}
_ => None,
}
}
/// Element-wise comparison producing a `Bool`-typed column.
///
/// Both columns must have the same length. Missing values (Null or NaN)
/// propagate: if either operand is missing, the result is missing.
pub fn binary_comparison(&self, right: &Self, op: ComparisonOp) -> Result<Self, ColumnError> {
if self.len() != right.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: right.len(),
});
}
// Typed fast path: both operands are all-valid contiguous Float64,
// Int64, or Bool, so compare over the buffers and build the Bool result via
// from_bool_values — no Scalar materialization or per-element dispatch.
// Bit-identical to scalar_compare's same-dtype arm (the identical `a <op>
// b`); all-valid inputs mean no Null branch, and the comparisons never
// see a NaN (as_f64_slice excludes it).
// Hoist `op` out of the element loop into six monomorphic branchless
// closures so each comparison auto-vectorizes (a per-element `match op`
// is opaque to the vectorizer and serializes the loop — the same lever
// as `Series::between`). Bit-identical: the comparison performed per
// element is unchanged, only the control flow that selects it moves out.
if let (Some(l), Some(r)) = (self.as_f64_slice(), right.as_f64_slice()) {
let zip = || l.iter().zip(r);
let bools: Vec<bool> = match op {
ComparisonOp::Gt => zip().map(|(&a, &b)| a > b).collect(),
ComparisonOp::Lt => zip().map(|(&a, &b)| a < b).collect(),
ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
};
return Ok(Self::from_bool_values(bools));
}
if let (Some(l), Some(r)) = (self.as_i64_slice(), right.as_i64_slice()) {
let zip = || l.iter().zip(r);
let bools: Vec<bool> = match op {
ComparisonOp::Gt => zip().map(|(&a, &b)| a > b).collect(),
ComparisonOp::Lt => zip().map(|(&a, &b)| a < b).collect(),
ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
};
return Ok(Self::from_bool_values(bools));
}
if let (Some(l), Some(r)) = (self.as_bool_slice(), right.as_bool_slice()) {
let zip = || l.iter().zip(r);
let bools: Vec<bool> = match op {
ComparisonOp::Gt => zip().map(|(&a, &b)| a && !b).collect(),
ComparisonOp::Lt => zip().map(|(&a, &b)| !a && b).collect(),
ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
};
return Ok(Self::from_bool_values(bools));
}
// Typed NULLABLE Bool fast path (sister to the all-valid Bool arm above): the
// all-valid arm needs BOTH `as_bool_slice()` (validity.all()), so any pair with a
// nullable Bool operand — (nullable, nullable), (all-valid, nullable), (nullable,
// all-valid) — fell to the generic per-element Scalar loop over Vec<Scalar::Bool>.
// Read the raw `&[bool]` backings + validity and apply the SAME per-op bool
// expressions, carrying the combined validity (present iff BOTH present == the
// generic `!(l.is_missing() || r.is_missing())`; Bool has no NaN sentinel, so
// "missing" is validity-unset only — no buffer scan). Bit-identical to the generic
// path's `scalar_compare` Bool arm. A local `fn` ties the borrows to the `&Column`.
fn bool_backing(col: &Column) -> Option<(&[bool], &ValidityMask)> {
if col.dtype != DType::Bool {
return None;
}
if let Some(slice) = col.as_bool_slice() {
return Some((slice, &col.validity));
}
if let ScalarValues::LazyNullableBool { data, validity, .. } = &col.values {
return Some((data.as_slice(), validity));
}
None
}
if let (Some((l, lv)), Some((r, rv))) = (bool_backing(self), bool_backing(right)) {
let zip = || l.iter().zip(r);
let bools: Vec<bool> = match op {
ComparisonOp::Gt => zip().map(|(&a, &b)| a && !b).collect(),
ComparisonOp::Lt => zip().map(|(&a, &b)| !a && b).collect(),
ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
};
return Ok(Self::from_bool_values_with_validity(bools, lv.and_mask(rv)));
}
// Typed MIXED Int64×Float64 fast path: the both-same-dtype arms above miss a
// mixed numeric pair, dropping it to the generic per-element Scalar
// `scalar_compare`. Build an f64 view per side (an all-valid Float64 borrows its
// `&[f64]`; an all-valid Int64 maps `v as f64` once) and compare with the hoisted
// op. Bit-identical to `scalar_compare`'s Int64/Float64 arm, which promotes both
// to f64 (`a as f64 <op> b`); `as_f64_slice`/`as_i64_slice` are all-valid with no
// present NaN, so there is no Null/NaN branch. Both-Int64 keeps the EXACT i64
// compare arm above (never f64-promoted here — matters for |v| > 2^53). A local
// `fn` (not a closure) so elision ties the `Cow<'_>` output to the `&Column` arg.
fn f64_view(col: &Column) -> Option<std::borrow::Cow<'_, [f64]>> {
if let Some(d) = col.as_f64_slice() {
Some(std::borrow::Cow::Borrowed(d))
} else {
col.as_i64_slice()
.map(|d| std::borrow::Cow::Owned(d.iter().map(|&v| v as f64).collect()))
}
}
if let (Some(lv), Some(rv)) = (f64_view(self), f64_view(right)) {
let (l, r) = (lv.as_ref(), rv.as_ref());
let zip = || l.iter().zip(r);
let bools: Vec<bool> = match op {
ComparisonOp::Gt => zip().map(|(&a, &b)| a > b).collect(),
ComparisonOp::Lt => zip().map(|(&a, &b)| a < b).collect(),
ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
};
return Ok(Self::from_bool_values(bools));
}
// Typed NULLABLE Float64 fast path (sister to the compare_scalar nullable arm):
// the all-valid arms above bail on ANY missing, so a nullable Float64 vs
// nullable Float64 pair fell to the generic per-element Scalar `scalar_compare`
// over `Vec<Scalar>`. Compare over the two raw `&[f64]` (masked slots' bools are
// never observed) and carry the combined validity (present iff BOTH present).
// Bit-identical to the Scalar path: a present pair (both validity-set, so both
// non-NaN — fp clears the validity bit for any NaN) yields `Bool(a <op> b)` (the
// same `scalar_compare` "both to f64" branch), an either-missing slot yields the
// invalid bit == `Null(NullKind::Null)`. `lv AND rv` is exactly the generic
// `!(l.is_missing() || r.is_missing())`.
if let (Some((ld, lv)), Some((rd, rv))) = (
self.as_f64_slice_with_validity(),
right.as_f64_slice_with_validity(),
) {
let zip = || ld.iter().zip(rd);
let bools: Vec<bool> = match op {
ComparisonOp::Gt => zip().map(|(&a, &b)| a > b).collect(),
ComparisonOp::Lt => zip().map(|(&a, &b)| a < b).collect(),
ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
};
return Ok(Self::from_bool_values_with_validity(bools, lv.and_mask(rv)));
}
// Typed NULLABLE Int64 fast path (sister to the nullable Float64 arm above): a
// nullable Int64 vs nullable Int64 pair also fell to the generic Scalar
// `scalar_compare`. Compare the two raw `&[i64]` EXACTLY — never f64-promoted,
// matching `scalar_compare`'s both-Int64 branch (an i64 comparison; matters for
// `|v| > 2^53` where `v as f64` would round) — and carry the combined validity.
// Bit-identical: present pair (both validity-set) => `Bool(a <op> b)`, either
// missing => the invalid bit == `Null(NullKind::Null)`; `lv AND rv` is exactly
// the generic `!(l.is_missing() || r.is_missing())`. All-valid Int64 pairs still
// take the exact-i64 borrow arm higher up (fires first).
if let (Some((ld, lv)), Some((rd, rv))) = (
self.as_i64_slice_with_validity(),
right.as_i64_slice_with_validity(),
) {
let zip = || ld.iter().zip(rd);
let bools: Vec<bool> = match op {
ComparisonOp::Gt => zip().map(|(&a, &b)| a > b).collect(),
ComparisonOp::Lt => zip().map(|(&a, &b)| a < b).collect(),
ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
};
return Ok(Self::from_bool_values_with_validity(bools, lv.and_mask(rv)));
}
// Typed MIXED-NULLABLE fast path: a nullable Int64 vs nullable Float64 pair (either
// side nullable, dtypes differ) matched neither same-dtype nullable arm above and
// fell to the generic Scalar `scalar_compare`. Build a validity-aware f64 view per
// side (an all-valid/nullable Float64 borrows its `&[f64]` + validity; an
// all-valid/nullable Int64 maps `v as f64` + validity) and compare f64-promoted,
// carrying the combined validity. Bit-identical to `scalar_compare`'s Int64/Float64
// arm (which promotes both to f64); present iff both present (`lv AND rv`), masked
// slots' bools never observed. Both-Int64 already took the EXACT-i64 nullable arm
// above (never reaches here), so no Int64 pair is f64-promoted; both-Float64 took
// its arm. A local `fn` so elision ties the outputs' lifetimes to the `&Column`.
fn nullable_f64_view(col: &Column) -> Option<(std::borrow::Cow<'_, [f64]>, &ValidityMask)> {
if let Some((d, v)) = col.as_f64_slice_with_validity() {
Some((std::borrow::Cow::Borrowed(d), v))
} else if let Some((d, v)) = col.as_i64_slice_with_validity() {
Some((
std::borrow::Cow::Owned(d.iter().map(|&x| x as f64).collect()),
v,
))
} else {
None
}
}
if let (Some((lc, lv)), Some((rc, rv))) =
(nullable_f64_view(self), nullable_f64_view(right))
{
let (l, r) = (lc.as_ref(), rc.as_ref());
let zip = || l.iter().zip(r);
let bools: Vec<bool> = match op {
ComparisonOp::Gt => zip().map(|(&a, &b)| a > b).collect(),
ComparisonOp::Lt => zip().map(|(&a, &b)| a < b).collect(),
ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
};
return Ok(Self::from_bool_values_with_validity(bools, lv.and_mask(rv)));
}
// Typed Utf8 fast path (all-valid AND nullable, either side): both operands are
// contiguous-Utf8 (an all-valid `LazyContiguousUtf8`/hex backing, or a
// `LazyNullableUtf8`). The generic loop below materializes BOTH `Vec<Scalar::Utf8>`
// (a heap `String` per row × two columns) just to feed `scalar_compare`, whose
// Utf8 arm is `a <op> b` on the two `String`s == byte-lexicographic `str::cmp`.
// Compare each row's raw `&[u8]` spans directly and combine the validity with
// `and_mask` (present iff BOTH present == the generic `!(l.is_missing() ||
// r.is_missing())`). Bit-identical: `&[u8]` order == `String` order for valid
// UTF-8 (same lever as the typed Utf8 `searchsorted` / `compare_scalar`), a
// present pair ⇒ `Bool(lrow <op> rrow)`, an either-missing slot ⇒ the invalid bit
// == `Null(NullKind::Null)` (its empty-span bool is never observed). A local `fn`
// (not a closure) ties the borrowed spans/validity lifetimes to the `&Column`.
fn utf8_spans(col: &Column) -> Option<(&[u8], &[usize], &ValidityMask)> {
if col.dtype != DType::Utf8 {
return None;
}
if let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
..
} = &col.values
{
return Some((bytes, offsets, validity));
}
let (bytes, offsets) = col.as_utf8_contiguous()?;
Some((bytes, offsets, &col.validity))
}
if let (Some((lb, lo, lv)), Some((rb, ro, rv))) = (utf8_spans(self), utf8_spans(right)) {
let n = lo.len() - 1;
let lrow = |i: usize| &lb[lo[i]..lo[i + 1]];
let rrow = |i: usize| &rb[ro[i]..ro[i + 1]];
let bools: Vec<bool> = match op {
ComparisonOp::Gt => (0..n).map(|i| lrow(i) > rrow(i)).collect(),
ComparisonOp::Lt => (0..n).map(|i| lrow(i) < rrow(i)).collect(),
ComparisonOp::Eq => (0..n).map(|i| lrow(i) == rrow(i)).collect(),
ComparisonOp::Ne => (0..n).map(|i| lrow(i) != rrow(i)).collect(),
ComparisonOp::Ge => (0..n).map(|i| lrow(i) >= rrow(i)).collect(),
ComparisonOp::Le => (0..n).map(|i| lrow(i) <= rrow(i)).collect(),
};
return Ok(Self::from_bool_values_with_validity(bools, lv.and_mask(rv)));
}
// Typed TEMPORAL fast path: both operands are Datetime64, or both are
// Timedelta64 (all-valid OR nullable). Temporal scalars are i64 nanoseconds
// but are NOT numeric to `to_f64`, so the generic loop below routes any
// PRESENT temporal pair through `scalar_compare` -> `Scalar::to_f64()`, which
// returns `Err(NonNumericValue)` — i.e. `s_dt1 < s_dt2` / `s_td1 == s_td2`
// ERROR outright today (only the Series-vs-scalar `compare_scalar` path
// handled temporal). Compare the raw `&[i64]` backings EXACTLY — pandas
// compares datetime64[ns]/timedelta64[ns] as i64; an f64 promotion would
// round for `|ns| > 2^53` (epoch-ns are ~1.6e18) — and mask a row where
// either side is missing: validity bit unset OR the NaT sentinel in the
// buffer, which is EXACTLY the generic path's `l.is_missing() ||
// r.is_missing()` (`Datetime64(NAT)`/`Timedelta64(NAT)` materialize as
// missing). A masked slot's bool (computed over a NaT sentinel) is never
// observed. `temporal_i64_backing` (a Column method, shared with `compare_scalar`)
// borrows the raw ns backing + validity + NaT sentinel for an all-valid or nullable
// Datetime64/Timedelta64 column.
if self.dtype == right.dtype
&& let (Some((l, lv, nat)), Some((r, rv, _))) =
(self.temporal_i64_backing(), right.temporal_i64_backing())
{
let zip = || l.iter().zip(r);
let bools: Vec<bool> = match op {
ComparisonOp::Gt => zip().map(|(&a, &b)| a > b).collect(),
ComparisonOp::Lt => zip().map(|(&a, &b)| a < b).collect(),
ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
};
let mut present = lv.and_mask(rv);
for (i, (&a, &b)) in l.iter().zip(r).enumerate() {
if a == nat || b == nat {
present.set(i, false);
}
}
return Ok(Self::from_bool_values_with_validity(bools, present));
}
let values = self
.values
.iter()
.zip(&right.values)
.map(|(l, r)| -> Result<Scalar, ColumnError> {
if l.is_missing() || r.is_missing() {
return Ok(Scalar::Null(NullKind::Null));
}
let result = scalar_compare(l, r, op)?;
Ok(Scalar::Bool(result))
})
.collect::<Result<Vec<_>, _>>()?;
Self::new(DType::Bool, values)
}
/// Element-wise equality, matching `pd.Series.eq()`.
pub fn eq(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_comparison(right, ComparisonOp::Eq)
}
/// Element-wise inequality, matching `pd.Series.ne()`.
pub fn ne(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_comparison(right, ComparisonOp::Ne)
}
/// Element-wise less-than comparison, matching `pd.Series.lt()`.
pub fn lt(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_comparison(right, ComparisonOp::Lt)
}
/// Element-wise less-than-or-equal comparison, matching `pd.Series.le()`.
pub fn le(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_comparison(right, ComparisonOp::Le)
}
/// Element-wise greater-than comparison, matching `pd.Series.gt()`.
pub fn gt(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_comparison(right, ComparisonOp::Gt)
}
/// Element-wise greater-than-or-equal comparison, matching `pd.Series.ge()`.
pub fn ge(&self, right: &Self) -> Result<Self, ColumnError> {
self.binary_comparison(right, ComparisonOp::Ge)
}
/// Compare every element against a scalar value, producing a `Bool`-typed column.
///
/// Missing values in the column propagate as missing in the result.
pub fn compare_scalar(&self, scalar: &Scalar, op: ComparisonOp) -> Result<Self, ColumnError> {
if scalar.is_missing() {
// Comparing against missing always produces all-missing.
let values = vec![Scalar::Null(NullKind::Null); self.len()];
return Self::new(DType::Bool, values);
}
// Typed fast path (br-frankenpandas-2kpwa): when self is an all-valid
// contiguous numeric buffer, compare against the scalar directly over the
// typed slice and build the Bool result via from_bool_values, skipping the
// per-element Scalar dispatch in scalar_compare and the 32-byte Scalar alloc
// for every output cell. Bit-identical to the scalar path:
// * Float64 self vs any numeric scalar reduces in scalar_compare to the
// final "convert both to f64" branch, i.e. `v <op> scalar.to_f64()`.
// * Int64 self vs Int64 scalar takes scalar_compare's both-Int64 branch,
// i.e. the i64 comparison. (Int64 vs float scalar still uses the AoS
// path so f64-promotion semantics stay identical.)
if let Some(data) = self.as_f64_slice()
&& let Ok(s) = scalar.to_f64()
{
// Hoist the `op` match OUT of the per-element closure: a `match op`
// inside the map body is a loop-invariant branch that blocks SIMD
// (scalar eq was 0.44x pandas). Six monomorphic `v <op> s` loops each
// auto-vectorize to a packed f64 compare. Bit-identical (same per-op
// comparison; only the dispatch moved out of the loop).
let bools: Vec<bool> = match op {
ComparisonOp::Gt => data.iter().map(|&v| v > s).collect(),
ComparisonOp::Lt => data.iter().map(|&v| v < s).collect(),
ComparisonOp::Eq => data.iter().map(|&v| v == s).collect(),
ComparisonOp::Ne => data.iter().map(|&v| v != s).collect(),
ComparisonOp::Ge => data.iter().map(|&v| v >= s).collect(),
ComparisonOp::Le => data.iter().map(|&v| v <= s).collect(),
};
return Ok(Self::from_bool_values(bools));
}
if let Some(data) = self.as_i64_slice()
&& let Scalar::Int64(s) = scalar
{
let s = *s;
// Hoist `op` out of the closure (see the Float64 arm) so each
// monomorphic i64 compare loop auto-vectorizes. Bit-identical.
let bools: Vec<bool> = match op {
ComparisonOp::Gt => data.iter().map(|&v| v > s).collect(),
ComparisonOp::Lt => data.iter().map(|&v| v < s).collect(),
ComparisonOp::Eq => data.iter().map(|&v| v == s).collect(),
ComparisonOp::Ne => data.iter().map(|&v| v != s).collect(),
ComparisonOp::Ge => data.iter().map(|&v| v >= s).collect(),
ComparisonOp::Le => data.iter().map(|&v| v <= s).collect(),
};
return Ok(Self::from_bool_values(bools));
}
// Nullable Float64 fast path: the all-valid `as_f64_slice` above bails on
// ANY NaN/missing, so a nullable Float64 column fell to the generic
// per-element Scalar dispatch + 32-byte Scalar/cell (compare on a 10%-null
// 5M column was ~415ms / 237x slower than pandas). Compare over the raw
// &[f64] and carry the source validity onto a typed nullable Bool result.
// Bit-identical to the Scalar path: present slot ⇒ `Bool(v <op> s)` (same
// `scalar_compare` "convert both to f64" branch for Float64 vs numeric),
// missing slot ⇒ `from_bool_values_with_validity`'s invalid bit, which is
// `Null(NullKind::Null)` (= the Scalar path's missing arm); the bool value
// at a masked slot is never observed.
if let Some((data, validity)) = self.as_f64_slice_with_validity()
&& let Ok(s) = scalar.to_f64()
{
// Hoist `op` out of the closure (see the all-valid Float64 arm): the
// compare over the raw &[f64] vectorizes; masked slots are dropped by
// the carried validity, so the bool value there is never observed.
// Bit-identical.
let bools: Vec<bool> = match op {
ComparisonOp::Gt => data.iter().map(|&v| v > s).collect(),
ComparisonOp::Lt => data.iter().map(|&v| v < s).collect(),
ComparisonOp::Eq => data.iter().map(|&v| v == s).collect(),
ComparisonOp::Ne => data.iter().map(|&v| v != s).collect(),
ComparisonOp::Ge => data.iter().map(|&v| v >= s).collect(),
ComparisonOp::Le => data.iter().map(|&v| v <= s).collect(),
};
return Ok(Self::from_bool_values_with_validity(
bools,
validity.clone(),
));
}
// Nullable Int64 sibling: keep comparisons exact over the raw i64 buffer
// and carry the source validity into the Bool result. The all-valid arm
// above already handles dense Int64; without this nullable arm we fell
// through to `values()` and allocated one 32-byte Scalar per input and
// output cell. This deliberately accepts only an Int64 scalar because
// mixed Int64/Float64 comparison uses scalar_compare's f64-promotion
// semantics. Masked slots' computed bools are never observed.
if let Some((data, validity)) = self.as_i64_slice_with_validity()
&& let Scalar::Int64(s) = scalar
{
let s = *s;
let bools: Vec<bool> = match op {
ComparisonOp::Gt => data.iter().map(|&v| v > s).collect(),
ComparisonOp::Lt => data.iter().map(|&v| v < s).collect(),
ComparisonOp::Eq => data.iter().map(|&v| v == s).collect(),
ComparisonOp::Ne => data.iter().map(|&v| v != s).collect(),
ComparisonOp::Ge => data.iter().map(|&v| v >= s).collect(),
ComparisonOp::Le => data.iter().map(|&v| v <= s).collect(),
};
return Ok(Self::from_bool_values_with_validity(
bools,
validity.clone(),
));
}
// Typed Utf8 fast path: an all-valid contiguous-Utf8 column compared against a
// Utf8 scalar. The generic loop below drives `self.values.iter()`, which
// materializes the WHOLE `Vec<Scalar::Utf8>` — one heap `String` per row (via
// the `get_or_init` OnceCell) — purely to feed `scalar_compare`, whose Utf8 arm
// is `a <op> b` on the two `String`s == byte-lexicographic `str::cmp`. Instead
// compare each row's raw `&[u8]` span (`bytes[offsets[i]..offsets[i+1]]`) against
// the needle bytes directly and build the Bool via `from_bool_values`.
// Bit-identical: `&[u8]` lexicographic order == `&str`/`String` order for valid
// UTF-8 (same lever as the typed Utf8 `searchsorted`), so `row <op> needle`
// matches `scalar_compare(row, needle, op)` for every op. `as_utf8_contiguous`
// gates on an all-valid backing, so the generic path's `is_missing ⇒ Null(Null)`
// branch never applies here; a nullable / Eager / non-contiguous Utf8 column
// declines the accessor and keeps the missing-aware generic path. Hoist `op` out
// of the per-row closure (mirror of the numeric arms) so each row runs one
// monomorphic slice compare.
if let Scalar::Utf8(needle) = scalar
&& let Some((bytes, offsets)) = self.as_utf8_contiguous()
{
let needle = needle.as_bytes();
let n = offsets.len() - 1;
let row = |i: usize| &bytes[offsets[i]..offsets[i + 1]];
let bools: Vec<bool> = match op {
ComparisonOp::Gt => (0..n).map(|i| row(i) > needle).collect(),
ComparisonOp::Lt => (0..n).map(|i| row(i) < needle).collect(),
ComparisonOp::Eq => (0..n).map(|i| row(i) == needle).collect(),
ComparisonOp::Ne => (0..n).map(|i| row(i) != needle).collect(),
ComparisonOp::Ge => (0..n).map(|i| row(i) >= needle).collect(),
ComparisonOp::Le => (0..n).map(|i| row(i) <= needle).collect(),
};
return Ok(Self::from_bool_values(bools));
}
// Nullable sibling of the arm above: a NULLABLE contiguous-Utf8 column
// (`LazyNullableUtf8`, the shape a CSV/parquet load or `from_utf8_values_with
// _validity` produces for a string column WITH missing rows) declined
// `as_utf8_contiguous` (which gates on `validity.all()`), so it fell to the
// generic `Vec<Scalar::Utf8>` materialization. Read the raw `&[u8]` spans +
// validity directly: compare every present row's span against the needle (an
// invalid slot carries an empty span whose computed bool the carried validity
// then hides) and carry the source validity onto a nullable Bool result.
// Bit-identical to the generic path: present ⇒ `Bool(row <op> needle)` (the same
// `scalar_compare` Utf8 arm), missing ⇒ `from_bool_values_with_validity`'s
// invalid bit == `Null(NullKind::Null)` (= the generic `is_missing` arm).
// `LazyNullableUtf8Range` (join-output shape, no contiguous byte backing) and
// Eager nullable Utf8 keep the generic path.
if let Scalar::Utf8(needle) = scalar
&& let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
..
} = &self.values
{
let needle = needle.as_bytes();
let n = offsets.len() - 1;
let row = |i: usize| &bytes[offsets[i]..offsets[i + 1]];
let bools: Vec<bool> = match op {
ComparisonOp::Gt => (0..n).map(|i| row(i) > needle).collect(),
ComparisonOp::Lt => (0..n).map(|i| row(i) < needle).collect(),
ComparisonOp::Eq => (0..n).map(|i| row(i) == needle).collect(),
ComparisonOp::Ne => (0..n).map(|i| row(i) != needle).collect(),
ComparisonOp::Ge => (0..n).map(|i| row(i) >= needle).collect(),
ComparisonOp::Le => (0..n).map(|i| row(i) <= needle).collect(),
};
return Ok(Self::from_bool_values_with_validity(bools, validity.clone()));
}
// Typed TEMPORAL scalar fast path: a Datetime64 column vs a (non-NaT) Datetime64
// scalar, or a Timedelta64 column vs a (non-NaT) Timedelta64 scalar. Temporal
// scalars are i64 nanoseconds but are NOT numeric to `to_f64`, so the generic loop
// below routes a PRESENT row through `scalar_compare` -> `Scalar::to_f64()`, which
// returns `Err(NonNumericValue)` — i.e. `df["date"] > threshold` (the canonical
// time-series filter) ERRORS today. Compare the raw `&[i64]` backing to the
// scalar's ns EXACTLY — pandas compares datetime64[ns]/timedelta64[ns] as i64; an
// f64 promotion would round for `|ns| > 2^53` (epoch-ns are ~1.6e18) — and mask a
// row whose column value is missing (validity bit unset OR the NaT sentinel in the
// buffer, == the generic `v.is_missing()`). A NaT scalar keeps the generic path.
let temporal_needle = match (self.dtype, scalar) {
(DType::Datetime64, Scalar::Datetime64(s)) if *s != Timestamp::NAT => Some(*s),
(DType::Timedelta64, Scalar::Timedelta64(s)) if *s != Timedelta::NAT => Some(*s),
_ => None,
};
if let Some(needle) = temporal_needle
&& let Some((data, validity, nat)) = self.temporal_i64_backing()
{
let bools: Vec<bool> = match op {
ComparisonOp::Gt => data.iter().map(|&v| v > needle).collect(),
ComparisonOp::Lt => data.iter().map(|&v| v < needle).collect(),
ComparisonOp::Eq => data.iter().map(|&v| v == needle).collect(),
ComparisonOp::Ne => data.iter().map(|&v| v != needle).collect(),
ComparisonOp::Ge => data.iter().map(|&v| v >= needle).collect(),
ComparisonOp::Le => data.iter().map(|&v| v <= needle).collect(),
};
let mut present = validity.clone();
for (i, &v) in data.iter().enumerate() {
if v == nat {
present.set(i, false);
}
}
return Ok(Self::from_bool_values_with_validity(bools, present));
}
let values = self
.values
.iter()
.map(|v| -> Result<Scalar, ColumnError> {
if v.is_missing() {
return Ok(Scalar::Null(NullKind::Null));
}
let result = scalar_compare(v, scalar, op)?;
Ok(Scalar::Bool(result))
})
.collect::<Result<Vec<_>, _>>()?;
Self::new(DType::Bool, values)
}
/// Select elements where `mask` is `true`, producing a new column.
///
/// The mask must be a `Bool`-typed column of the same length.
/// Missing values in the mask are treated as `false` (not selected).
pub fn filter_by_mask(&self, mask: &Self) -> Result<Self, ColumnError> {
if mask.dtype == DType::Null {
if self.len() != mask.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: mask.len(),
});
}
return Self::new(self.dtype, Vec::new());
}
if mask.dtype != DType::Bool {
return Err(ColumnError::InvalidMaskType { dtype: mask.dtype });
}
if self.len() != mask.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: mask.len(),
});
}
// Typed fast path (br-frankenpandas-lei31 family): gather the contiguous
// f64/i64 buffer by the mask directly, skipping the 32-byte Scalar clone
// and the dtype-coercion scan in Column::new. Bit-identical — selects the
// same positions in the same order, and an all-valid source yields an
// all-valid result, exactly as the Scalar path + Column::new would.
//
// When the mask is an all-valid Bool column (the usual shape — it just
// came out of a comparison), read its contiguous `bool` buffer instead of
// `mask.values` (which would force the lazy-bool mask to materialize a
// full Vec<Scalar::Bool>). `as_bool_slice` returns the raw bits, and for
// an all-valid bool column `bits[i] == matches!(values[i],
// Scalar::Bool(true))`, so selection is identical.
if let Some(mask_bits) = mask.as_bool_slice() {
if let Some(data) = self.as_f64_slice() {
let gathered: Vec<f64> = data
.iter()
.zip(mask_bits)
.filter_map(|(&v, &m)| m.then_some(v))
.collect();
return Ok(Self::from_f64_values_owned(gathered));
}
if let Some(data) = self.as_i64_slice() {
let gathered: Vec<i64> = data
.iter()
.zip(mask_bits)
.filter_map(|(&v, &m)| m.then_some(v))
.collect();
return Ok(Self::from_i64_values_owned(gathered));
}
// Nullable typed gathers (mirror take_positions' variant-gated nullable
// path): a nullable Int64/Float64 column declined the all-valid
// as_i64/f64_slice gathers above and would otherwise clone a 32-byte
// Scalar per selected row + rescan in Self::new. Gate on the VALUES
// VARIANT — NOT as_*_slice_with_validity, which also matches an Eager
// ColumnData::Float64 whose Scalar values legally hold Null(NaT)/Null(Null)
// — so only the canonical-missing lazy backings take this path. Gather the
// raw datum by mask and carry the (NaN-folded) validity into the typed
// nullable constructor. Bit-identical to the Scalar-clone + Self::new path
// (present ⇒ same datum Scalar; missing ⇒ Null(NaN)/Null(Null) ==
// missing_for_dtype; Column::eq compares materialized values).
let typed_f64: Option<&[f64]> = match &self.values {
ScalarValues::LazyNullableFloat64 { data, .. } => Some(data.as_slice()),
ScalarValues::LazyAllValidFloat64 { data, .. } => Some(data.as_ref()),
_ => None,
};
if let Some(src) = typed_f64 {
let count = mask_bits.iter().filter(|&&m| m).count();
let mut gathered = Vec::with_capacity(count);
let mut words = vec![0_u64; count.div_ceil(64)];
let mut out_idx = 0usize;
for (i, &m) in mask_bits.iter().enumerate() {
if m {
let x = src[i];
gathered.push(x);
if self.validity.get(i) && !x.is_nan() {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
out_idx += 1;
}
}
return Ok(Self::from_f64_values_with_validity(
gathered,
ValidityMask::from_words(words, count),
));
}
if let ScalarValues::LazyNullableInt64 { data, .. } = &self.values {
let src = data.as_slice();
let count = mask_bits.iter().filter(|&&m| m).count();
let mut gathered = Vec::with_capacity(count);
let mut words = vec![0_u64; count.div_ceil(64)];
let mut out_idx = 0usize;
for (i, &m) in mask_bits.iter().enumerate() {
if m {
gathered.push(src[i]);
if self.validity.get(i) {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
out_idx += 1;
}
}
return Ok(Self::from_i64_values_with_validity(
gathered,
ValidityMask::from_words(words, count),
));
}
// Nullable temporal / Bool siblings (mirror the take_positions gathers):
// Datetime64/Timedelta64 store i64 ns (missing ⇒ Null(NaT)), Bool raw
// bits (missing ⇒ Null(Null)). Variant-gated to the canonical lazy
// backing; byte-identical to the Scalar-clone path (present ⇒ datum
// Scalar; missing ⇒ the variant's invalid emission == missing_for_dtype).
if let ScalarValues::LazyNullableDatetime64 { data, .. } = &self.values {
let src = data.as_slice();
let count = mask_bits.iter().filter(|&&m| m).count();
let mut gathered = Vec::with_capacity(count);
let mut words = vec![0_u64; count.div_ceil(64)];
let mut out_idx = 0usize;
for (i, &m) in mask_bits.iter().enumerate() {
if m {
gathered.push(src[i]);
if self.validity.get(i) {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
out_idx += 1;
}
}
return Ok(Self::from_datetime64_values_with_validity(
gathered,
ValidityMask::from_words(words, count),
));
}
if let ScalarValues::LazyNullableTimedelta64 { data, .. } = &self.values {
let src = data.as_slice();
let count = mask_bits.iter().filter(|&&m| m).count();
let mut gathered = Vec::with_capacity(count);
let mut words = vec![0_u64; count.div_ceil(64)];
let mut out_idx = 0usize;
for (i, &m) in mask_bits.iter().enumerate() {
if m {
gathered.push(src[i]);
if self.validity.get(i) {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
out_idx += 1;
}
}
return Ok(Self::from_timedelta64_values_with_validity(
gathered,
ValidityMask::from_words(words, count),
));
}
if let ScalarValues::LazyNullableBool { data, .. } = &self.values {
let src = data.as_slice();
let count = mask_bits.iter().filter(|&&m| m).count();
let mut gathered = Vec::with_capacity(count);
let mut words = vec![0_u64; count.div_ceil(64)];
let mut out_idx = 0usize;
for (i, &m) in mask_bits.iter().enumerate() {
if m {
gathered.push(src[i]);
if self.validity.get(i) {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
out_idx += 1;
}
}
return Ok(Self::from_bool_values_with_validity(
gathered,
ValidityMask::from_words(words, count),
));
}
let values = self
.values
.iter()
.zip(mask_bits)
.filter_map(|(val, &m)| m.then_some(val.clone()))
.collect::<Vec<_>>();
return Self::new(self.dtype, values);
}
if let Some(data) = self.as_f64_slice() {
let gathered: Vec<f64> = data
.iter()
.zip(mask.values.iter())
.filter_map(|(&v, m)| matches!(m, Scalar::Bool(true)).then_some(v))
.collect();
return Ok(Self::from_f64_values_owned(gathered));
}
if let Some(data) = self.as_i64_slice() {
let gathered: Vec<i64> = data
.iter()
.zip(mask.values.iter())
.filter_map(|(&v, m)| matches!(m, Scalar::Bool(true)).then_some(v))
.collect();
return Ok(Self::from_i64_values_owned(gathered));
}
// Nullable Int64 gather (mirror of the Bool-self path above): the all-valid
// `as_i64_slice` arm bails on ANY missing, so a nullable Int64 column fell to the
// generic per-element `Vec<Scalar>` gather. Compact the raw buffer at the mask-true
// positions AND gather the validity bit into the output — no Scalar materialization.
// Bit-identical to the generic clone: a kept present slot keeps its datum, a kept
// missing slot stays missing (Int64 has no NaN, so present = the validity bit alone).
// A missing/non-Bool mask slot is never kept (== the generic `matches!(m, Bool(true))`).
// (Nullable Float64 stays on the generic path: its three-way NaN rep — a validity-clear
// slot whose datum materializes as a PRESENT Float64(NaN) — is not reproducible by a
// simple validity-bit gather; see filter_by_mask_nullable_typed_gather_matches_reference_cf.)
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let count = mask
.values
.iter()
.filter(|m| matches!(m, Scalar::Bool(true)))
.count();
let mut gathered = Vec::with_capacity(count);
let mut words = vec![0_u64; count.div_ceil(64)];
let mut out_idx = 0usize;
for (i, m) in mask.values.iter().enumerate() {
if matches!(m, Scalar::Bool(true)) {
gathered.push(data[i]);
if validity.get(i) {
words[out_idx / 64] |= 1_u64 << (out_idx % 64);
}
out_idx += 1;
}
}
return Ok(Self::from_i64_values_with_validity(
gathered,
ValidityMask::from_words(words, count),
));
}
let values = self
.values
.iter()
.zip(mask.values.iter())
.filter_map(|(val, mask_val)| match mask_val {
Scalar::Bool(true) => Some(val.clone()),
_ => None,
})
.collect::<Vec<_>>();
Self::new(self.dtype, values)
}
/// Fill missing values with a replacement scalar.
///
/// Returns a new column where every missing position is replaced
/// by `fill_value`. The fill value is cast to the column's dtype.
pub fn fillna(&self, fill_value: &Scalar) -> Result<Self, ColumnError> {
if self.dtype == DType::Null {
let replacement_dtype = if fill_value.is_missing() {
DType::Null
} else {
fill_value.dtype()
};
let values = self
.values
.iter()
.map(|value| {
if value.is_missing() {
fill_value.clone()
} else {
value.clone()
}
})
.collect();
return Self::new(replacement_dtype, values);
}
let cast_fill = cast_scalar(fill_value, self.dtype)?;
// Typed Float64 fast path (br-frankenpandas-e8vzt): fill every missing
// slot with the finite f64 fill into an all-valid typed buffer, skipping
// the per-element Scalar clone, the Vec<Scalar>, and the Self::new
// revalidation. Bit-identical: a present slot (validity set AND datum not
// NaN — a valid-bit NaN is missing per Scalar::is_missing) keeps its f64;
// a missing slot takes `fv`; every result is finite, so the column is
// all-valid exactly as Self::new would derive from the Float64 scalars.
if self.dtype == DType::Float64
&& let Scalar::Float64(fv) = &cast_fill
&& fv.is_finite()
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
// Nothing-to-fill short-circuit: every slot present (validity set) AND
// no NaN datum (a valid-bit NaN counts as missing per Scalar::is_missing)
// ⇒ output == input, so share the backing in O(1) instead of rebuilding
// a fresh n*8 buffer. Bit-identical (clone preserves values + dtype +
// validity), and returns self's own representation rather than minting a
// new variant. The NaN scan is a cheap sequential read vs the alloc+copy.
if validity.all() && !data.iter().any(|d| d.is_nan()) {
return Ok(self.clone());
}
// Iterate the PACKED validity words instead of `validity.get(i)` per
// element (a ~4-branch, non-inlined call ×n): an all-invalid word fills
// 64 slots with `fv` outright; an all-valid word copies its 64 data
// slots (still NaN-checked — a valid-bit NaN counts as missing per
// Scalar::is_missing, so it takes `fv`); a partial word tests only its
// bits. Bit-identical to the `validity.get(i) && !d.is_nan()` select.
let n = data.len();
let words = validity.packed_words_for_scan();
let mut out = Vec::with_capacity(n);
for (w, &word) in words.iter().enumerate() {
let base = w * 64;
let upto = 64.min(n - base);
if word == 0 {
out.extend(std::iter::repeat_n(*fv, upto));
} else {
for b in 0..upto {
let d = data[base + b];
if (word >> b) & 1 == 1 && !d.is_nan() {
out.push(d);
} else {
out.push(*fv);
}
}
}
}
// Output is all-valid and NaN-free (present non-NaN values or the
// finite fill) → MOVE into the backing (no Arc::from realloc).
return Ok(Self::from_f64_values_owned(out));
}
// Typed nullable Int64 fast path: fill each missing slot (validity bit
// alone — no NaN sentinel for Int64) with the i64 fill into an all-valid
// i64 buffer, skipping the per-element Scalar clone + Self::new revalidation.
// Bit-identical to the loop below: present → data[i], missing → fv, output
// all-valid Int64. Gated on a real Int64 fill (a missing fill keeps nulls,
// so it falls through to the generic path).
if self.dtype == DType::Int64
&& let Scalar::Int64(fv) = &cast_fill
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
// Nothing-to-fill short-circuit: all slots present (Int64 missing is
// validity-bit only, no NaN sentinel) ⇒ output == input, O(1) share.
if validity.all() {
return Ok(self.clone());
}
let mut out = Vec::with_capacity(data.len());
for (i, &d) in data.iter().enumerate() {
out.push(if validity.get(i) { d } else { *fv });
}
return Ok(Self::from_i64_values_owned(out));
}
// Typed Int64 fast path (br-frankenpandas-3llep): as_i64_slice returns
// Some only for an all-valid Int64 backing, which has nothing to fill — so
// fillna is a copy of the existing values. Re-ingest the contiguous i64
// buffer typed, skipping the per-element Scalar clone + Self::new
// revalidation the loop below would run on every all-valid Int64 column.
// Bit-identical: every value is present (cast_fill is never applied) and
// the output is the same all-valid Int64 column. cast_scalar above has
// already validated/errored on the fill value.
if self.dtype == DType::Int64 && self.as_i64_slice().is_some() {
// `as_i64_slice` is Some only for an all-valid Int64 backing → nothing
// to fill, output == input. Share in O(1) instead of `to_vec`-copying
// the whole buffer.
return Ok(self.clone());
}
// Typed nullable Bool fast path: `LazyNullableBool` materializes valid
// slots as the raw bool and invalid slots as `Null(Null)`. A post-cast
// Bool fill therefore makes every output slot valid, so select directly
// from the packed Bool data + validity and skip the Vec<Scalar> rebuild.
// Variant-gating preserves the generic path for eager Bool columns that
// may carry distinct NullKind values; a missing fill also remains generic
// because its post-cast scalar does not match `Scalar::Bool`.
if let Scalar::Bool(fv) = &cast_fill
&& let ScalarValues::LazyNullableBool { data, validity, .. } = &self.values
{
let out = data
.iter()
.enumerate()
.map(|(i, &value)| if validity.get(i) { value } else { *fv })
.collect();
return Ok(Self::from_bool_values(out));
}
// Typed nullable Utf8 fast path: a `LazyNullableUtf8` column (a string column
// WITH missing rows — the common `df[col].fillna("x")` shape) with a Utf8 fill.
// The generic loop below materializes a `Vec<Scalar::Utf8>` and clones a heap
// `String` per PRESENT row plus the fill per MISSING row. Build the filled output
// as ONE contiguous byte buffer from the raw spans (present) / fill bytes
// (missing) — no per-row `String` alloc. Every output slot is filled, so the
// result is all-valid contiguous Utf8. Bit-identical to the loop: present ⇒
// `Scalar::Utf8(span)`, missing ⇒ `Scalar::Utf8(fill)`. No cold-cache gate — the
// contiguous build beats the per-row `String` clones even on a warm column (like
// take_positions / sort_values), not just materialization avoidance. A missing
// fill keeps nulls, so its post-cast scalar is not `Scalar::Utf8` and it falls to
// the generic path.
if let Scalar::Utf8(fill) = &cast_fill
&& let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
..
} = &self.values
{
let fill_bytes = fill.as_bytes();
let n = offsets.len().saturating_sub(1);
let mut out_bytes: Vec<u8> = Vec::with_capacity(bytes.len() + fill_bytes.len() * n);
let mut out_offsets: Vec<usize> = Vec::with_capacity(n + 1);
out_offsets.push(0);
for (i, w) in offsets.windows(2).enumerate() {
if validity.get(i) {
out_bytes.extend_from_slice(&bytes[w[0]..w[1]]);
} else {
out_bytes.extend_from_slice(fill_bytes);
}
out_offsets.push(out_bytes.len());
}
return Ok(Self::from_utf8_contiguous(out_bytes, out_offsets));
}
// Typed nullable temporal fillna: a `LazyNullableDatetime64` / `LazyNullableTimedelta64`
// column (the common `df["date"].fillna(default)` shape — a temporal column WITH missing
// rows) and a matching NON-NaT temporal fill. The generic loop below materializes a
// `Vec<Scalar::Datetime64/Timedelta64>` (32 B/row) just to clone present values + the fill
// for missing. Build the filled i64-ns buffer directly: a present slot (validity set AND
// not the NaT sentinel — exactly the materialized `!is_missing`) keeps `data[i]`, a missing
// slot takes the fill ns. Every slot is filled ⇒ all-valid output. Bit-identical to the
// loop: present ⇒ the same value, missing ⇒ the fill, dtype unchanged. A NaT fill keeps
// nulls (its post-cast scalar IS missing) so it falls to the generic path.
if let (Scalar::Datetime64(fill), ScalarValues::LazyNullableDatetime64 { data, validity, .. }) =
(&cast_fill, &self.values)
&& *fill != Timestamp::NAT
{
let out: Vec<i64> = data
.iter()
.enumerate()
.map(|(i, &v)| if validity.get(i) && v != Timestamp::NAT { v } else { *fill })
.collect();
return Ok(Self::from_datetime64_values(out));
}
if let (Scalar::Timedelta64(fill), ScalarValues::LazyNullableTimedelta64 { data, validity, .. }) =
(&cast_fill, &self.values)
&& *fill != Timedelta::NAT
{
let n = data.len();
let out: Vec<i64> = data
.iter()
.enumerate()
.map(|(i, &v)| if validity.get(i) && v != Timedelta::NAT { v } else { *fill })
.collect();
return Ok(Self::from_timedelta64_values_with_validity(
out,
ValidityMask::all_valid(n),
));
}
let values = self
.values
.iter()
.map(|v| {
if v.is_missing() {
cast_fill.clone()
} else {
v.clone()
}
})
.collect();
Self::new(self.dtype, values)
}
/// Remove missing values, returning a shorter column.
pub fn dropna(&self) -> Result<Self, ColumnError> {
// Typed fast paths: compact the present values from the raw buffer +
// validity, no per-element Scalar materialization. Bit-identical to the
// Scalar filter: a present slot keeps its value in order; a Float64 valid
// slot whose datum is NaN is dropped (Scalar::Float64(NaN).is_missing()),
// and Int64/Bool missingness is the validity bit alone. Output is
// all-valid. Bool is deliberately variant-gated: Scalar-backed Bool
// columns may preserve mixed NullKind values and retain the generic path.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let mut out = Vec::with_capacity(data.len());
for (i, &d) in data.iter().enumerate() {
if validity.get(i) && !d.is_nan() {
out.push(d);
}
}
return Ok(Self::from_f64_values_owned(out));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut out = Vec::with_capacity(data.len());
for (i, &d) in data.iter().enumerate() {
if validity.get(i) {
out.push(d);
}
}
return Ok(Self::from_i64_values_owned(out));
}
if self.dtype == DType::Bool
&& let ScalarValues::LazyNullableBool { data, validity, .. } = &self.values
{
let mut out = Vec::with_capacity(data.len());
for (i, &d) in data.iter().enumerate() {
if validity.get(i) {
out.push(d);
}
}
return Ok(Self::from_bool_values(out));
}
let values = self
.values
.iter()
.filter(|v| !v.is_missing())
.cloned()
.collect();
Self::new(self.dtype, values)
}
/// Gather rows by integer position.
///
/// Matches `pd.Series.take(indices)`. Each index must fall within
/// `0..len()`; out-of-range positions return
/// `ColumnError::LengthMismatch` (left=length, right=offending
/// index).
pub fn take(&self, indices: &[usize]) -> Result<Self, ColumnError> {
let mut out = Vec::with_capacity(indices.len());
for &i in indices {
match self.values.get(i) {
Some(v) => out.push(v.clone()),
None => {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: i,
});
}
}
}
Self::new(self.dtype, out)
}
/// Replace elements at specified indices with given values.
///
/// Matches np.put(). Returns a new column with values replaced at indices.
pub fn put(&self, indices: &[usize], values: &[Scalar]) -> Result<Self, ColumnError> {
if indices.len() != values.len() {
return Err(ColumnError::LengthMismatch {
left: indices.len(),
right: values.len(),
});
}
let mut out = self.values.to_vec();
for (&i, v) in indices.iter().zip(values) {
if i >= out.len() {
return Err(ColumnError::LengthMismatch {
left: out.len(),
right: i,
});
}
out[i] = v.clone();
}
Self::new(self.dtype, out)
}
/// Contiguous slice by positional range `start..start+len`.
///
/// Out-of-range requests are clamped to the available tail so a
/// start past `len()` yields an empty column with the same dtype,
/// matching pandas' permissive slice semantics.
pub fn slice(&self, start: usize, len: usize) -> Result<Self, ColumnError> {
if start >= self.values.len() {
return Self::new(self.dtype, Vec::new());
}
let end = start.saturating_add(len).min(self.values.len());
Ok(self.take_contiguous_range(start, end - start))
}
/// Return the first `n` values.
///
/// Matches pandas `head(n)` semantics on a 1-D array-like surface.
/// Negative `n` returns all values except the last `-n`.
pub fn head(&self, n: i64) -> Result<Self, ColumnError> {
let take = normalize_head_take(n, self.len());
self.slice(0, take)
}
/// Return the last `n` values.
///
/// Matches pandas `tail(n)` semantics on a 1-D array-like surface.
/// Negative `n` returns all values except the first `-n`.
pub fn tail(&self, n: i64) -> Result<Self, ColumnError> {
let (start, len) = normalize_tail_window(n, self.len());
self.slice(start, len)
}
/// Split column into n equal-ish parts.
///
/// Matches np.array_split(). Returns Vec of Columns.
pub fn array_split(&self, n: usize) -> Result<Vec<Self>, ColumnError> {
if n == 0 {
return Ok(Vec::new());
}
let len = self.values.len();
let base_size = len / n;
let remainder = len % n;
let mut result = Vec::with_capacity(n);
let mut start = 0;
for i in 0..n {
let size = base_size + if i < remainder { 1 } else { 0 };
let part = self.slice(start, size)?;
result.push(part);
start += size;
}
Ok(result)
}
/// Alias for array_split.
pub fn split(&self, n: usize) -> Result<Vec<Self>, ColumnError> {
self.array_split(n)
}
/// Concatenate `other` onto `self`, preserving dtype.
///
/// Returns `ColumnError::DTypeMismatch` when `other.dtype()` differs
/// from `self.dtype()`.
pub fn concat(&self, other: &Self) -> Result<Self, ColumnError> {
if self.dtype != other.dtype {
return Err(ColumnError::DTypeMismatch {
left: self.dtype,
right: other.dtype,
});
}
// perf: typed buffer concat for the ubiquitous all-valid Int64/Float64
// case — extend the contiguous i64/f64 buffers directly instead of cloning
// a 32 B Scalar per row through `self.values` + re-validating in `Self::new`.
// as_i64_slice/as_f64_slice are Some only when BOTH columns are all-valid of
// that dtype, so from_i64_values/from_f64_values are bit-identical to the
// Scalar path (same dtype + no missing => same logical values).
if let (Some((a, a_start)), Some((b, b_start))) = (
self.as_i64_arc_view_source(),
other.as_i64_arc_view_source(),
) {
return Ok(Self::from_i64_all_valid_chunks(
vec![(a, a_start, self.len()), (b, b_start, other.len())],
self.len() + other.len(),
));
}
if let (Some(a), Some(b)) = (self.as_f64_slice(), other.as_f64_slice()) {
let mut out = Vec::with_capacity(a.len() + b.len());
out.extend_from_slice(a);
out.extend_from_slice(b);
return Ok(Self::from_f64_values(out));
}
let mut values = Vec::with_capacity(self.values.len() + other.values.len());
values.extend_from_slice(&self.values);
values.extend_from_slice(&other.values);
Self::new(self.dtype, values)
}
/// Alias for concat, matching np.append.
pub fn append(&self, other: &Self) -> Result<Self, ColumnError> {
self.concat(other)
}
/// Insert values at given index.
///
/// Matches np.insert(). Returns new column with values inserted.
pub fn insert(&self, index: usize, values: &[Scalar]) -> Result<Self, ColumnError> {
let idx = index.min(self.values.len());
let mut out = Vec::with_capacity(self.values.len() + values.len());
out.extend_from_slice(&self.values[..idx]);
out.extend_from_slice(values);
out.extend_from_slice(&self.values[idx..]);
Self::new(self.dtype, out)
}
/// Delete values at given indices.
///
/// Matches np.delete(). Returns new column with values removed.
pub fn delete(&self, indices: &[usize]) -> Result<Self, ColumnError> {
let mut to_delete: FxHashSet<usize> = FxHashSet::default();
for &i in indices {
to_delete.insert(i);
}
let out: Vec<Scalar> = self
.values
.iter()
.enumerate()
.filter(|(i, _)| !to_delete.contains(i))
.map(|(_, v)| v.clone())
.collect();
Self::new(self.dtype, out)
}
/// Resize column to new size, padding or truncating as needed.
///
/// Matches np.resize(). If new size is larger, values cycle from beginning.
pub fn resize(&self, new_size: usize) -> Result<Self, ColumnError> {
if new_size == 0 || self.values.is_empty() {
return Self::new(self.dtype, Vec::new());
}
let mut out = Vec::with_capacity(new_size);
let mut i = 0;
while out.len() < new_size {
out.push(self.values[i % self.values.len()].clone());
i += 1;
}
Self::new(self.dtype, out)
}
/// Repeat each value `repeats` times contiguously.
///
/// Matches `pd.Series.repeat(n)`. `repeats=0` yields an empty
/// column; `repeats=1` is a clone.
pub fn repeat(&self, repeats: usize) -> Result<Self, ColumnError> {
if repeats == 0 {
return Self::new(self.dtype, Vec::new());
}
if repeats == 1 {
return Ok(self.clone());
}
let mut out = Vec::with_capacity(self.values.len() * repeats);
for v in &self.values {
for _ in 0..repeats {
out.push(v.clone());
}
}
Self::new(self.dtype, out)
}
/// Tile (repeat) the entire column n times.
///
/// Matches `np.tile()`. Unlike repeat which duplicates each element,
/// tile duplicates the entire array.
pub fn tile(&self, reps: usize) -> Result<Self, ColumnError> {
if reps == 0 {
return Self::new(self.dtype, Vec::new());
}
if reps == 1 {
return Ok(self.clone());
}
let mut out = Vec::with_capacity(self.values.len() * reps);
for _ in 0..reps {
out.extend_from_slice(&self.values);
}
Self::new(self.dtype, out)
}
/// Reverse the row order of the column.
///
/// Matches `pd.Series[::-1]` / `iloc[::-1]`. Dtype is preserved.
pub fn reverse(&self) -> Result<Self, ColumnError> {
let mut values = self.values.to_vec();
values.reverse();
Self::new(self.dtype, values)
}
/// Alias for reverse, matching np.flip.
pub fn flip(&self) -> Result<Self, ColumnError> {
self.reverse()
}
/// Roll array elements along the axis.
///
/// Matches np.roll(a, shift). Elements that roll beyond the last position
/// are re-introduced at the first, and vice versa. Positive shift rolls
/// elements to higher indices (right), negative to lower (left).
pub fn roll(&self, shift: i64) -> Result<Self, ColumnError> {
let len = self.len();
if len == 0 {
return Ok(self.clone());
}
let shift = ((shift % len as i64) + len as i64) as usize % len;
if shift == 0 {
return Ok(self.clone());
}
let mut out = Vec::with_capacity(len);
let split = len - shift;
out.extend_from_slice(&self.values[split..]);
out.extend_from_slice(&self.values[..split]);
Self::new(self.dtype, out)
}
/// Filter values based on a boolean condition column.
///
/// Matches `np.compress()`. Returns only values where condition is True.
pub fn compress(&self, condition: &Self) -> Result<Self, ColumnError> {
if self.len() != condition.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: condition.len(),
});
}
let mut out = Vec::new();
for (v, c) in self.values.iter().zip(&condition.values) {
match c {
Scalar::Bool(true) => out.push(v.clone()),
Scalar::Bool(false) => {}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{c:?}"),
dtype: condition.dtype,
}));
}
}
}
Self::new(self.dtype, out)
}
/// Cumulative sum, null-propagating per fp-types::nancumsum.
///
/// Matches `pd.Series.cumsum()`. The resulting column is always
/// Float64 (matching the numeric accumulator type used in
/// nancumsum).
pub fn cumsum(&self) -> Result<Self, ColumnError> {
// Typed prefix scan: an all-valid Float64 column scans its contiguous
// buffer, no Scalar materialization in or out. Bit-identical to
// nancumsum's Float64 arm — the same `running += x` left-fold seeded at
// 0.0 in the same order; an operation-produced NaN (inf - inf) is flagged
// missing by from_f64_values, exactly as Self::new(Float64, ...) does.
if let Some(data) = self.as_f64_slice() {
let mut running = 0.0_f64;
let out: Vec<f64> = data
.iter()
.map(|&x| {
running += x;
running
})
.collect();
return Ok(Self::from_f64_values_owned(out));
}
// Typed all-valid Int64: fold as f64 (matching nancumsum's `to_f64`),
// emit Float64 — bit-identical to the nancumsum path, no Scalar
// materialization of the lazy i64 column.
if let Some(data) = self.as_i64_slice() {
let mut running = 0.0_f64;
let out: Vec<f64> = data
.iter()
.map(|&x| {
running += x as f64;
running
})
.collect();
return Ok(Self::from_f64_values_owned(out));
}
// Nullable Int64/Float64: the all-valid arms above bailed on the missing
// bit, so these fell to nancumsum over the materialized Vec<Scalar>. Fold
// the raw slice + validity typed (running seeded 0.0, present ⇒ += x, emit;
// missing/NaN ⇒ Null(NaN), running unchanged). Bit-identical to nancumsum.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let (out, out_valid) = cum_accum_nullable_f64(data, validity, 0.0, false);
return Ok(Self::from_f64_values_with_validity(out, out_valid));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let (out, out_valid) = cum_accum_nullable_i64(data, validity, 0.0, false);
return Ok(Self::from_f64_values_with_validity(out, out_valid));
}
let out = nancumsum(&self.values);
Self::new(DType::Float64, out)
}
/// Cumulative product, null-propagating per fp-types::nancumprod.
pub fn cumprod(&self) -> Result<Self, ColumnError> {
// Typed prefix scan (see cumsum): nancumprod seeds `running` at 1.0.
if let Some(data) = self.as_f64_slice() {
let mut running = 1.0_f64;
let out: Vec<f64> = data
.iter()
.map(|&x| {
running *= x;
running
})
.collect();
return Ok(Self::from_f64_values_owned(out));
}
// NB: no typed i64 fast path — an i64 product can overflow the f64 to
// ±inf→NaN, where from_f64_values (NaN→missing) diverges from nancumprod's
// Scalar::Float64(NaN); kept on the exact nancumprod path for bit-identity.
// Nullable Int64/Float64 (seed 1.0, product): typed fold, skipping the
// Scalar materialization. Bit-identical to nancumprod.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let (out, out_valid) = cum_accum_nullable_f64(data, validity, 1.0, true);
return Ok(Self::from_f64_values_with_validity(out, out_valid));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let (out, out_valid) = cum_accum_nullable_i64(data, validity, 1.0, true);
return Ok(Self::from_f64_values_with_validity(out, out_valid));
}
let out = nancumprod(&self.values);
Self::new(DType::Float64, out)
}
/// Cumulative maximum, null-propagating per fp-types::nancummax.
pub fn cummax(&self) -> Result<Self, ColumnError> {
// Typed running maximum: nancummax takes the first non-missing value
// then `prev.max(x)` (std f64::max semantics) — reproduced over the
// contiguous buffer for an all-valid Float64 column.
if let Some(data) = self.as_f64_slice() {
if let Some((&first, rest)) = data.split_first() {
let mut running = first;
let mut out = Vec::with_capacity(data.len());
out.push(running);
for &x in rest {
running = running.max(x);
out.push(running);
}
return Ok(Self::from_f64_values_owned(out));
}
return Ok(Self::from_f64_values(Vec::new()));
}
if let Some(data) = self.as_i64_slice() {
if let Some((&first, rest)) = data.split_first() {
let mut running = first as f64;
let mut out = Vec::with_capacity(data.len());
out.push(running);
for &x in rest {
running = running.max(x as f64);
out.push(running);
}
return Ok(Self::from_f64_values_owned(out));
}
return Ok(Self::from_f64_values(Vec::new()));
}
// Nullable Int64/Float64: the all-valid arms above bailed on the missing
// bit, so these fell to nancummax over the materialized Vec<Scalar>. Fold
// the raw slice + validity typed (present ⇒ running max, missing/NaN ⇒
// Null(NaN)), skipping the input Scalar materialization AND the Scalar
// output. Bit-identical to nancummax.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let (out, out_valid) = cum_extrema_nullable_f64(data, validity, true);
return Ok(Self::from_f64_values_with_validity(out, out_valid));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let (out, out_valid) = cum_extrema_nullable_i64(data, validity, true);
return Ok(Self::from_f64_values_with_validity(out, out_valid));
}
let out = nancummax(&self.values);
Self::new(DType::Float64, out)
}
/// Cumulative minimum, null-propagating per fp-types::nancummin.
pub fn cummin(&self) -> Result<Self, ColumnError> {
// Typed running minimum (see cummax).
if let Some(data) = self.as_f64_slice() {
if let Some((&first, rest)) = data.split_first() {
let mut running = first;
let mut out = Vec::with_capacity(data.len());
out.push(running);
for &x in rest {
running = running.min(x);
out.push(running);
}
return Ok(Self::from_f64_values_owned(out));
}
return Ok(Self::from_f64_values(Vec::new()));
}
if let Some(data) = self.as_i64_slice() {
if let Some((&first, rest)) = data.split_first() {
let mut running = first as f64;
let mut out = Vec::with_capacity(data.len());
out.push(running);
for &x in rest {
running = running.min(x as f64);
out.push(running);
}
return Ok(Self::from_f64_values_owned(out));
}
return Ok(Self::from_f64_values(Vec::new()));
}
// Nullable Int64/Float64 (symmetric to cummax): typed running min over the
// raw slice + validity, skipping the Scalar materialization.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let (out, out_valid) = cum_extrema_nullable_f64(data, validity, false);
return Ok(Self::from_f64_values_with_validity(out, out_valid));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let (out, out_valid) = cum_extrema_nullable_i64(data, validity, false);
return Ok(Self::from_f64_values_with_validity(out, out_valid));
}
let out = nancummin(&self.values);
Self::new(DType::Float64, out)
}
/// Sum of non-missing values.
///
/// Sum an all-valid Float64 `concat(...)` output (`LazyAllValidFloat64Chunks`)
/// by folding each chunk slice in place with ONE 0.0-seeded accumulator in
/// 0..n order — BIT-IDENTICAL to `as_f64_slice().iter().sum()` over the
/// materialized buffer (same values, same order, same sequential left-fold)
/// — but WITHOUT allocating+filling the cold concatenated `Vec<f64>` (the
/// [[f64-arc-copy-on-produce]] ~5.7 ms/1M page-fault cost). `None` for any
/// non-chunked / nullable / non-Float64 column (caller keeps its normal path).
#[must_use]
pub fn all_valid_f64_chunk_sum(&self) -> Option<f64> {
if self.dtype != DType::Float64 || !self.validity.all() {
return None;
}
let chunks = self.values.float64_chunks_ref()?;
let mut s = 0.0_f64;
for chunk in chunks {
for &x in chunk.as_slice() {
s += x;
}
}
Some(s)
}
/// Mean of an all-valid Float64 chunks column (see `all_valid_f64_chunk_sum`):
/// `Σ / len` with the in-place chunk fold; `None` for empty or non-chunked.
#[must_use]
pub fn all_valid_f64_chunk_mean(&self) -> Option<f64> {
if self.dtype != DType::Float64 || !self.validity.all() {
return None;
}
let chunks = self.values.float64_chunks_ref()?;
let mut s = 0.0_f64;
let mut count = 0usize;
for chunk in chunks {
let slice = chunk.as_slice();
for &x in slice {
s += x;
}
count += slice.len();
}
if count == 0 {
return None;
}
Some(s / count as f64)
}
/// Sum an all-valid Int64 `concat(...)` output by folding each chunk slice
/// in place with `wrapping_add` (0-seeded, 0..n order) — BIT-IDENTICAL to the
/// materialized `as_i64_slice` wrapping sum (wrapping_add is associative mod
/// 2^64, so chunk grouping can't change the result) — without the cold Vec.
#[must_use]
pub fn all_valid_i64_chunk_sum(&self) -> Option<i64> {
if self.dtype != DType::Int64 || !self.validity.all() {
return None;
}
let chunks = self.values.int64_chunks_ref()?;
let mut total: i64 = 0;
for chunk in chunks {
for &x in chunk.as_slice() {
total = total.wrapping_add(x);
}
}
Some(total)
}
/// Min/max of an all-valid Int64 concat output via in-place chunk fold
/// (order-independent — `i64::min`/`max` is associative+commutative — so
/// bit-identical to the materialized reduction). `None` if empty/non-chunked.
#[must_use]
pub fn all_valid_i64_chunk_extreme(&self, want_max: bool) -> Option<i64> {
if self.dtype != DType::Int64 || !self.validity.all() {
return None;
}
let chunks = self.values.int64_chunks_ref()?;
let mut best: Option<i64> = None;
for chunk in chunks {
for &x in chunk.as_slice() {
best = Some(match best {
None => x,
Some(b) => {
if want_max {
b.max(x)
} else {
b.min(x)
}
}
});
}
}
best
}
/// Min/max of an all-valid Float64 concat output via in-place chunk fold,
/// replicating `Series::max`/`min`'s EXACT reduction — `if v > result`
/// (seed −∞) / `if v < result` (seed +∞), NOT `f64::max`/`min` (which would
/// flip ±0.0) — in 0..n order, so the ±0.0-first-seen tie is preserved
/// bit-for-bit. Chunks are all-valid (no NaN), so no missing/NaN branch.
/// `None` when empty/non-chunked (caller keeps its normal empty handling).
#[must_use]
pub fn all_valid_f64_chunk_extreme(&self, want_max: bool) -> Option<f64> {
if self.dtype != DType::Float64 || !self.validity.all() {
return None;
}
let chunks = self.values.float64_chunks_ref()?;
let mut result = if want_max {
f64::NEG_INFINITY
} else {
f64::INFINITY
};
let mut any = false;
for chunk in chunks {
for &v in chunk.as_slice() {
any = true;
if want_max {
if v > result {
result = v;
}
} else if v < result {
result = v;
}
}
}
if any { Some(result) } else { None }
}
/// Σ(v−mean)² over an all-valid Float64 concat output, folding each chunk
/// slice in place in 0..n order — bit-identical to the materialized
/// `Σ(v−mean)²` second pass in `Series::var` (same values, order, 0.0 seed),
/// without the cold materialization. Completes the concat→reduce vein (var/std).
#[must_use]
pub fn all_valid_f64_chunk_sq_dev_sum(&self, mean: f64) -> Option<f64> {
if self.dtype != DType::Float64 || !self.validity.all() {
return None;
}
let chunks = self.values.float64_chunks_ref()?;
let mut s = 0.0_f64;
for chunk in chunks {
for &v in chunk.as_slice() {
let d = v - mean;
s += d * d;
}
}
Some(s)
}
/// Int64 sibling of `all_valid_f64_chunk_sq_dev_sum` (`(v as f64 − mean)²`).
#[must_use]
pub fn all_valid_i64_chunk_sq_dev_sum(&self, mean: f64) -> Option<f64> {
if self.dtype != DType::Int64 || !self.validity.all() {
return None;
}
let chunks = self.values.int64_chunks_ref()?;
let mut s = 0.0_f64;
for chunk in chunks {
for &v in chunk.as_slice() {
let d = v as f64 - mean;
s += d * d;
}
}
Some(s)
}
/// Product of an all-valid Float64 concat output, folding each chunk slice
/// in place with a 1.0-seeded `*` in 0..n order — bit-identical to
/// `as_f64_slice().iter().product()` (also a 1.0-seeded sequential left-fold)
/// — without materializing the cold concat buffer.
#[must_use]
pub fn all_valid_f64_chunk_product(&self) -> Option<f64> {
if self.dtype != DType::Float64 || !self.validity.all() {
return None;
}
let chunks = self.values.float64_chunks_ref()?;
let mut p = 1.0_f64;
for chunk in chunks {
for &v in chunk.as_slice() {
p *= v;
}
}
Some(p)
}
/// Int64 product sibling (`wrapping_mul`, associative mod 2^64 ⇒ grouping-
/// invariant, bit-identical to the materialized `fold(1, wrapping_mul)`).
#[must_use]
pub fn all_valid_i64_chunk_product(&self) -> Option<i64> {
if self.dtype != DType::Int64 || !self.validity.all() {
return None;
}
let chunks = self.values.int64_chunks_ref()?;
let mut p = 1_i64;
for chunk in chunks {
for &v in chunk.as_slice() {
p = p.wrapping_mul(v);
}
}
Some(p)
}
/// Argmax/argmin (first-occurrence index) over an all-valid Float64 concat
/// output, folding chunks in place. BIT-IDENTICAL to running
/// `f64_argmax_first_index`/`_min` on the materialized buffer: that routine
/// keeps an 8-lane running extreme where `lane = position % 8`, so iterating
/// the chunks in 0..n order and updating `lane[pos % 8]` reproduces the exact
/// same per-lane state, and the identical cross-lane reduction (max value,
/// smallest index on ties = first occurrence) yields the same index — without
/// materializing the cold buffer. `None` for empty/non-chunked.
#[must_use]
pub fn all_valid_f64_chunk_argextreme(&self, want_max: bool) -> Option<usize> {
if self.dtype != DType::Float64 || !self.validity.all() {
return None;
}
let chunks = self.values.float64_chunks_ref()?;
let seed = if want_max {
f64::NEG_INFINITY
} else {
f64::INFINITY
};
let mut lane_values = [seed; 8];
let mut lane_indices = [0_usize; 8];
let mut pos = 0_usize;
for chunk in chunks {
for &v in chunk.as_slice() {
let lane = pos & 7;
let better = if want_max {
v > lane_values[lane]
} else {
v < lane_values[lane]
};
if better {
lane_values[lane] = v;
lane_indices[lane] = pos;
}
pos += 1;
}
}
if pos == 0 {
return None;
}
let mut best_value = lane_values[0];
let mut best_index = lane_indices[0];
for lane in 1..8 {
let value = lane_values[lane];
let index = lane_indices[lane];
let better = if want_max {
value > best_value
} else {
value < best_value
};
if better || (value == best_value && index < best_index) {
best_value = value;
best_index = index;
}
}
Some(best_index)
}
/// Matches `pd.Series.sum()` in skipna=True mode via fp-types::nansum.
/// Empty column returns 0.0 (matching pandas).
#[must_use]
pub fn sum(&self) -> Scalar {
// Typed reduction: an all-valid Float64 column sums straight over its
// contiguous buffer instead of materializing/iterating a Vec<Scalar>.
// Bit-identical to nansum's Float64 arm: a sequential left-fold seeded
// at 0.0 over the same values in the same order (no Timedelta/missing
// branch applies to an all-valid Float64 column).
// Chunk fast path: a `concat(...)` output is a lazy
// `LazyAllValidFloat64Chunks`; fold each chunk slice in place (see
// `all_valid_f64_chunk_sum`) instead of materializing the cold 40MB
// concat buffer, so `concat(...).sum()` beats pandas' copy-then-sum.
if let Some(s) = self.all_valid_f64_chunk_sum() {
return Scalar::Float64(s);
}
if let Some(data) = self.as_f64_slice() {
let mut s = 0.0_f64;
for &x in data {
s += x;
}
return Scalar::Float64(s);
}
// Timedelta64 (i64-ns): an all-valid, non-empty, no-NAT column sums exactly
// in i128 over the raw &[i64] and clamps to i64 — the same accumulation and
// clamp as nansum's `collect_timedelta_ns` arm, without materializing the
// `Scalar` Vec. Empty / NAT / nullable falls to `nansum` (whose empty arm
// returns `Float64(0.0)` and whose fold skips missing).
if self.validity.all()
&& let Some(data) = self.as_timedelta64_slice()
&& !data.is_empty()
&& !data.contains(&i64::MIN)
{
let sum: i128 = data.iter().map(|&v| i128::from(v)).sum();
let clamped = sum.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
return Scalar::Timedelta64(clamped as i64);
}
// Typed Bool reduction: sum of an all-valid Bool column is the count of
// trues, over the raw &[bool] (a branchless count LLVM autovectorizes)
// instead of materializing a Vec<Scalar> and per-Scalar `to_f64`.
// Bit-identical to nansum's Bool arm: `Bool.to_f64()` is exactly 1.0/0.0,
// so nansum returns `Float64(Σ)`; a sequential f64 fold of 0.0/1.0 values
// is EXACT (each partial sum is an integer < 2^53), so `Σ == count`, and
// `count as f64` is that same exact value.
if let Some(data) = self.as_bool_slice() {
let trues = data.iter().filter(|&&b| b).count();
return Scalar::Float64(trues as f64);
}
// Typed Int64 sum: fold `v as f64` over the raw &[i64] (all-valid), matching
// nansum's per-Scalar `to_f64` + f64 fold in the SAME order — bit-identical
// (both lose precision above 2^53 identically) — without materializing the
// Scalar Vec. Empty ⇒ 0.0, exactly nansum's empty arm.
if let Some(data) = self.as_i64_slice() {
let mut s = 0.0_f64;
for &x in data {
s += x as f64;
}
return Scalar::Float64(s);
}
// Nullable Float64 sum: fold PRESENT values (validity-set AND non-NaN, the
// `Ok(x) if ...` / skip-missing behaviour of nansum). Bit-identical.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let mut s = 0.0_f64;
for (i, &x) in data.iter().enumerate() {
if validity.get(i) && !x.is_nan() {
s += x;
}
}
return Scalar::Float64(s);
}
// Nullable Int64 sum: fold present `v as f64` (Int64 missingness is the
// validity bit alone).
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut s = 0.0_f64;
for (i, &x) in data.iter().enumerate() {
if validity.get(i) {
s += x as f64;
}
}
return Scalar::Float64(s);
}
nansum(&self.values)
}
/// Arithmetic mean of non-missing values.
///
/// Matches `pd.Series.mean()` via fp-types::nanmean. Empty column
/// returns Null(NaN).
#[must_use]
pub fn mean(&self) -> Scalar {
// Typed reduction (see `sum`): for an all-valid Float64 column nanmean
// is `Σ / count` with count == len; an empty column stays Null(NaN).
// Chunk fast path (see `all_valid_f64_chunk_mean`): fold the concat
// chunks in place instead of materializing the cold buffer.
if let Some(m) = self.all_valid_f64_chunk_mean() {
return Scalar::Float64(m);
}
if let Some(data) = self.as_f64_slice() {
if data.is_empty() {
return Scalar::Null(NullKind::NaN);
}
let mut s = 0.0_f64;
for &x in data {
s += x;
}
return Scalar::Float64(s / data.len() as f64);
}
// Timedelta64 (see `sum`): all-valid, non-empty, no-NAT -> i128 `sum / len`
// (count == len), clamped, dtype-preserved. Bit-identical to nanmean's
// `collect_timedelta_ns` arm; empty / NAT / nullable falls to `nanmean`.
if self.validity.all()
&& let Some(data) = self.as_timedelta64_slice()
&& !data.is_empty()
&& !data.contains(&i64::MIN)
{
let sum: i128 = data.iter().map(|&v| i128::from(v)).sum();
let mean = sum / data.len() as i128;
let clamped = mean.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
return Scalar::Timedelta64(clamped as i64);
}
// Typed Int64 mean: Σ(v as f64)/len (all-valid, count == len), matching
// nanmean; empty ⇒ Null(NaN). No Scalar materialization of the lazy column.
if let Some(data) = self.as_i64_slice() {
if data.is_empty() {
return Scalar::Null(NullKind::NaN);
}
let mut s = 0.0_f64;
for &x in data {
s += x as f64;
}
return Scalar::Float64(s / data.len() as f64);
}
// Nullable Float64/Int64 mean: Σ present / count present (present = validity
// -set AND non-NaN for Float64; validity-set for Int64), matching nanmean's
// sum+count of finite values. count 0 ⇒ Null(NaN).
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let mut s = 0.0_f64;
let mut count = 0usize;
for (i, &x) in data.iter().enumerate() {
if validity.get(i) && !x.is_nan() {
s += x;
count += 1;
}
}
return if count == 0 {
Scalar::Null(NullKind::NaN)
} else {
Scalar::Float64(s / count as f64)
};
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut s = 0.0_f64;
let mut count = 0usize;
for (i, &x) in data.iter().enumerate() {
if validity.get(i) {
s += x as f64;
count += 1;
}
}
return if count == 0 {
Scalar::Null(NullKind::NaN)
} else {
Scalar::Float64(s / count as f64)
};
}
nanmean(&self.values)
}
/// Weighted average of non-missing values.
///
/// Matches np.average(a, weights=w). Returns NaN if weights sum to zero.
#[must_use]
pub fn weighted_mean(&self, weights: &Self) -> Scalar {
if self.len() != weights.len() {
return Scalar::Null(NullKind::NaN);
}
// Typed pairwise fast path (sibling of cov/corr): when BOTH columns are
// Float64/Int64 (all-valid or nullable) fold straight off the raw slices via
// get_present, skipping the Vec<Scalar> materialization of BOTH columns +
// per-Scalar is_missing/to_f64. Bit-identical: get_present == the reference's
// `!v.is_missing() && v.to_f64().is_ok()` gate (validity-set AND non-NaN for
// Float64, KEEPING ±inf; validity-set for Int64), so the same pairwise-present
// (v,w) pairs accumulate sum += vf*wf / weight_sum += wf in the same 0..n
// order, and the `weight_sum == 0.0 ⇒ Null(NaN)` guard is unchanged.
if let (Some(sv), Some(sw)) = (self.typed_numeric_values(), weights.typed_numeric_values()) {
let n = sv.len().min(sw.len());
let mut sum = 0.0_f64;
let mut weight_sum = 0.0_f64;
for i in 0..n {
if let (Some(vf), Some(wf)) = (sv.get_present(i), sw.get_present(i)) {
sum += vf * wf;
weight_sum += wf;
}
}
if weight_sum == 0.0 {
return Scalar::Null(NullKind::NaN);
}
return Scalar::Float64(sum / weight_sum);
}
let mut sum = 0.0;
let mut weight_sum = 0.0;
for (v, w) in self.values.iter().zip(weights.values()) {
if v.is_missing() || w.is_missing() {
continue;
}
let vf = match v.to_f64() {
Ok(x) => x,
Err(_) => continue,
};
let wf = match w.to_f64() {
Ok(x) => x,
Err(_) => continue,
};
sum += vf * wf;
weight_sum += wf;
}
if weight_sum == 0.0 {
return Scalar::Null(NullKind::NaN);
}
Scalar::Float64(sum / weight_sum)
}
/// Alias for weighted_mean, matching np.average naming.
#[must_use]
pub fn average(&self, weights: &Self) -> Scalar {
self.weighted_mean(weights)
}
/// Minimum non-missing value.
///
/// Matches `pd.Series.min()` via fp-types::nanmin. Preserves dtype
/// for homogeneous inputs.
#[must_use]
pub fn min(&self) -> Scalar {
// Typed reduction: an all-valid numeric column folds the minimum straight
// over its contiguous buffer (an associative reduction the compiler can
// vectorize), skipping the Vec<Scalar> materialization. Bit-identical to
// nanmin: it keeps the first element on a tie via strict `<` (so -0.0 vs
// 0.0 ordering is preserved), and returns it dtype-preserved.
if let Some(data) = self.as_f64_slice()
&& let Some((&first, rest)) = data.split_first()
{
let mut m = first;
for &x in rest {
if x < m {
m = x;
}
}
return Scalar::Float64(m);
}
if let Some(data) = self.as_i64_slice()
&& let Some((&first, rest)) = data.split_first()
{
let mut m = first;
for &x in rest {
if x < m {
m = x;
}
}
return Scalar::Int64(m);
}
// Datetime64 / Timedelta64 (i64-ns) reduce like Int64. Gate on all-valid +
// no NAT (`i64::MIN`): `nanmin` SKIPS missing, so a NAT-bearing column must
// stay on the `nanmin` path. For all-valid, no-NAT input the strict-`<` fold
// (keeps the first on a tie, exactly like `nanmin`) returns the same min,
// dtype-preserved — bit-identical, without materializing the `Scalar` Vec.
if self.validity.all() {
if let Some(data) = self.as_datetime64_slice()
&& let Some((&first, rest)) = data.split_first()
&& !data.contains(&i64::MIN)
{
let mut m = first;
for &x in rest {
if x < m {
m = x;
}
}
return Scalar::Datetime64(m);
}
if let Some(data) = self.as_timedelta64_slice()
&& let Some((&first, rest)) = data.split_first()
&& !data.contains(&i64::MIN)
{
let mut m = first;
for &x in rest {
if x < m {
m = x;
}
}
return Scalar::Timedelta64(m);
}
}
// Contiguous-Utf8 fast path (byte-span sibling of unique/value_counts):
// a Utf8 column's min otherwise falls to `nanmin`, which materializes a
// `Vec<Scalar::Utf8>` (one heap `String` per row) then folds the
// lexicographic minimum. Track the min byte span directly over the
// contiguous buffer instead. Bit-identical to `nanmin`'s Utf8 arm: `&[u8]`
// ordering equals `&str`/`String` ordering for valid UTF-8, and strict `<`
// keeps the FIRST occurrence on a tie exactly as `nanmin` does.
// `as_utf8_contiguous` matches only an all-valid backing (no missing to
// skip); an empty column has no spans, so it falls through to `nanmin`
// (→ `Null(NaN)`, unchanged).
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
let mut spans = offsets.windows(2);
if let Some(first) = spans.next() {
let mut best = &bytes[first[0]..first[1]];
for w in spans {
let span = &bytes[w[0]..w[1]];
if span < best {
best = span;
}
}
let s = std::str::from_utf8(best).expect("contiguous-Utf8 spans are valid UTF-8");
return Scalar::Utf8(s.to_owned());
}
}
// Nullable Float64/Int64 (sibling of nullable `median`/`quantile`): fold the
// minimum over the PRESENT values straight off the raw slice + validity,
// skipping `nanmin`'s Scalar-Vec materialization + per-Scalar is_missing/
// enum-match. Bit-identical to nanmin's numeric arms: present == not-missing
// (validity-set AND non-NaN for Float64 — nanmin's is_missing treats a
// valid-bit-set NaN as missing; validity bit for Int64), strict `<` keeps the
// FIRST occurrence on a tie (so -0.0/0.0 order matches), all-missing/empty ⇒
// Null(NaN). The dtype gates leave nanmin's Timedelta64/Datetime64 arms
// (nullable temporal) untouched.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let mut m: Option<f64> = None;
for (i, &x) in data.iter().enumerate() {
if validity.get(i) && !x.is_nan() && m.is_none_or(|cur| x < cur) {
m = Some(x);
}
}
return m.map_or(Scalar::Null(NullKind::NaN), Scalar::Float64);
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut m: Option<i64> = None;
for (i, &x) in data.iter().enumerate() {
if validity.get(i) && m.is_none_or(|cur| x < cur) {
m = Some(x);
}
}
return m.map_or(Scalar::Null(NullKind::NaN), Scalar::Int64);
}
nanmin(&self.values)
}
/// Maximum non-missing value.
///
/// Matches `pd.Series.max()` via fp-types::nanmax.
#[must_use]
pub fn max(&self) -> Scalar {
// Typed reduction (see `min`); nanmax keeps the first element on a tie
// via strict `>`, dtype-preserved.
if let Some(data) = self.as_f64_slice()
&& let Some((&first, rest)) = data.split_first()
{
let mut m = first;
for &x in rest {
if x > m {
m = x;
}
}
return Scalar::Float64(m);
}
if let Some(data) = self.as_i64_slice()
&& let Some((&first, rest)) = data.split_first()
{
let mut m = first;
for &x in rest {
if x > m {
m = x;
}
}
return Scalar::Int64(m);
}
// Datetime64 / Timedelta64 (i64-ns) reduce like Int64; see `min`. Gate on
// all-valid + no NAT so `nanmax`'s skip-missing behavior is preserved;
// strict-`>` keeps the first on a tie exactly like `nanmax`. Bit-identical,
// dtype-preserved, no `Scalar` materialization.
if self.validity.all() {
if let Some(data) = self.as_datetime64_slice()
&& let Some((&first, rest)) = data.split_first()
&& !data.contains(&i64::MIN)
{
let mut m = first;
for &x in rest {
if x > m {
m = x;
}
}
return Scalar::Datetime64(m);
}
if let Some(data) = self.as_timedelta64_slice()
&& let Some((&first, rest)) = data.split_first()
&& !data.contains(&i64::MIN)
{
let mut m = first;
for &x in rest {
if x > m {
m = x;
}
}
return Scalar::Timedelta64(m);
}
}
// Contiguous-Utf8 fast path (symmetric to `min`): track the max byte span
// directly over the contiguous buffer via strict `>` (keeps the FIRST on a
// tie exactly like `nanmax`; `&[u8]` order == `&str` order for valid UTF-8)
// instead of materializing a `Vec<Scalar::Utf8>`. All-valid only; empty
// falls through to `nanmax` (→ `Null(NaN)`, unchanged).
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
let mut spans = offsets.windows(2);
if let Some(first) = spans.next() {
let mut best = &bytes[first[0]..first[1]];
for w in spans {
let span = &bytes[w[0]..w[1]];
if span > best {
best = span;
}
}
let s = std::str::from_utf8(best).expect("contiguous-Utf8 spans are valid UTF-8");
return Scalar::Utf8(s.to_owned());
}
}
// Nullable Float64/Int64 (symmetric to `min`): fold the maximum over the
// PRESENT values straight off the raw slice + validity, skipping nanmax's
// Scalar-Vec materialization + per-Scalar is_missing/enum-match. Bit-identical
// to nanmax's numeric arms: present == not-missing (validity-set AND non-NaN
// for Float64; validity bit for Int64), strict `>` keeps the FIRST occurrence
// on a tie, all-missing/empty ⇒ Null(NaN). dtype gates leave nanmax's
// temporal arms untouched.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let mut m: Option<f64> = None;
for (i, &x) in data.iter().enumerate() {
if validity.get(i) && !x.is_nan() && m.is_none_or(|cur| x > cur) {
m = Some(x);
}
}
return m.map_or(Scalar::Null(NullKind::NaN), Scalar::Float64);
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut m: Option<i64> = None;
for (i, &x) in data.iter().enumerate() {
if validity.get(i) && m.is_none_or(|cur| x > cur) {
m = Some(x);
}
}
return m.map_or(Scalar::Null(NullKind::NaN), Scalar::Int64);
}
nanmax(&self.values)
}
/// Median of non-missing values.
///
/// Matches `pd.Series.median()` via fp-types::nanmedian.
/// Median over an all-valid `f64` buffer already extracted from the column:
/// empty ⇒ `Null(NaN)`, else O(n) `select_nth_unstable_by(mid, partial_cmp)`
/// then an odd/even midpoint (for even `n` the lower-middle is the MAX of the left
/// partition). Shared by the Float64 and Int64 typed fast paths so both run
/// the SAME computation `nanmedian`'s numeric arm performs after
/// `collect_finite`; `select_nth_unstable_by` is deterministic, so identical
/// input yields the identical `nums[mid-1]`/`nums[mid]`.
fn median_from_f64_vec(mut nums: Vec<f64>) -> Scalar {
if nums.is_empty() {
return Scalar::Null(NullKind::NaN);
}
let n = nums.len();
let mid = n / 2;
let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
let (left, mid_ref, _right) = nums.select_nth_unstable_by(mid, cmp);
let mid_val = *mid_ref;
if n.is_multiple_of(2) {
let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
Scalar::Float64((lower + mid_val) / 2.0)
} else {
Scalar::Float64(mid_val)
}
}
#[must_use]
pub fn median(&self) -> Scalar {
// Typed Float64 fast path: order statistics straight over the contiguous
// f64 buffer instead of materializing `Vec<Scalar>` then `collect_finite`'s
// per-Scalar `to_f64`. `as_f64_slice` yields an all-valid buffer, so
// `collect_finite` (which drops only MISSING, keeping every `to_f64`-able
// value including NaN/inf) copies exactly these values in this order —
// `data.to_vec()`.
if let Some(data) = self.as_f64_slice() {
return Self::median_from_f64_vec(data.to_vec());
}
// Typed Int64 fast path: `nanmedian`'s numeric arm maps each Scalar::Int64
// through `collect_finite`'s `to_f64` (`v as f64`, exact for |v| < 2^53 and
// identically lossy above it) then runs the SAME select_nth. An all-valid
// i64 buffer converted the same way is bit-identical — no missing to drop,
// no NaN introduced. Datetime64/Timedelta64 are excluded (`as_i64_slice`
// gates dtype==Int64) so Timedelta64's dtype-preserving median is untouched.
if let Some(data) = self.as_i64_slice() {
return Self::median_from_f64_vec(data.iter().map(|&v| v as f64).collect());
}
// Nullable Float64/Int64: collect the PRESENT values (validity-set AND
// non-NaN for Float64 — exactly collect_finite's drop-missing; validity bit
// for Int64) into an f64 Vec and run the SAME median_from_f64_vec, skipping
// nanmedian's Vec<Scalar> materialization + per-Scalar to_f64. Bit-identical:
// the median is order-independent (select_nth), so the present multiset alone
// determines it; empty present ⇒ median_from_f64_vec's empty ⇒ Null(NaN),
// matching nanmedian.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let present: Vec<f64> = data
.iter()
.enumerate()
.filter_map(|(i, &x)| (validity.get(i) && !x.is_nan()).then_some(x))
.collect();
return Self::median_from_f64_vec(present);
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let present: Vec<f64> = data
.iter()
.enumerate()
.filter_map(|(i, &v)| validity.get(i).then_some(v as f64))
.collect();
return Self::median_from_f64_vec(present);
}
nanmedian(&self.values)
}
/// Product of non-missing values.
///
/// Matches `pd.Series.prod()` via fp-types::nanprod. Empty column
/// returns 1.0 (matching pandas).
#[must_use]
pub fn prod(&self) -> Scalar {
// Typed reduction (mirror of `sum`): an all-valid Float64 column
// multiplies straight over its contiguous buffer instead of iterating a
// Vec<Scalar>. Bit-identical to nanprod's Float64 arm: a sequential
// left-fold seeded at 1.0 over the same values in the same order. all-
// valid ⇒ nothing is filtered and the all-missing→Null branch can't fire,
// so empty folds to Float64(1.0) exactly as nanprod returns for empty.
if let Some(data) = self.as_f64_slice() {
let mut p = 1.0_f64;
for &x in data {
p *= x;
}
return Scalar::Float64(p);
}
// Typed Int64 product: Π(v as f64) seeded 1.0 (all-valid), matching nanprod;
// empty ⇒ Float64(1.0). No Scalar materialization.
if let Some(data) = self.as_i64_slice() {
let mut p = 1.0_f64;
for &x in data {
p *= x as f64;
}
return Scalar::Float64(p);
}
// Nullable Float64/Int64 product: Π PRESENT values (validity-set AND non-NaN
// for Float64 — a valid-bit NaN is missing, exactly nanprod's skip; validity
// bit alone for Int64). All-missing ⇒ the 1.0 seed unchanged ⇒ Float64(1.0),
// exactly nanprod's empty behaviour.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let mut p = 1.0_f64;
for (i, &x) in data.iter().enumerate() {
if validity.get(i) && !x.is_nan() {
p *= x;
}
}
return Scalar::Float64(p);
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut p = 1.0_f64;
for (i, &x) in data.iter().enumerate() {
if validity.get(i) {
p *= x as f64;
}
}
return Scalar::Float64(p);
}
nanprod(&self.values)
}
/// Alias for [`prod`](Self::prod), matching `pd.Series.product()`.
#[must_use]
pub fn product(&self) -> Scalar {
self.prod()
}
/// Alias for sum, matching np.nansum.
#[must_use]
pub fn nansum(&self) -> Scalar {
self.sum()
}
/// Alias for mean, matching np.nanmean.
#[must_use]
pub fn nanmean(&self) -> Scalar {
self.mean()
}
/// Alias for min, matching np.nanmin.
#[must_use]
pub fn nanmin(&self) -> Scalar {
self.min()
}
/// Alias for max, matching np.nanmax.
#[must_use]
pub fn nanmax(&self) -> Scalar {
self.max()
}
/// Alias for prod, matching np.nanprod.
#[must_use]
pub fn nanprod(&self) -> Scalar {
self.prod()
}
/// Alias for std, matching np.nanstd.
#[must_use]
pub fn nanstd(&self, ddof: usize) -> Scalar {
self.std(ddof)
}
/// Alias for var, matching np.nanvar.
#[must_use]
pub fn nanvar(&self, ddof: usize) -> Scalar {
self.var(ddof)
}
/// Alias for median, matching np.nanmedian.
#[must_use]
pub fn nanmedian(&self) -> Scalar {
self.median()
}
fn skipna_false_missing_result(&self, skipna: bool) -> Option<Scalar> {
if skipna || !self.values.iter().any(Scalar::is_missing) {
return None;
}
Some(if matches!(self.dtype, DType::Timedelta64) {
Scalar::Timedelta64(Timedelta::NAT)
} else {
Scalar::Float64(f64::NAN)
})
}
/// Sum with explicit pandas `skipna=` control.
///
/// Matches `pd.Series.sum(skipna=...)`.
#[must_use]
pub fn sum_skipna(&self, skipna: bool) -> Scalar {
self.skipna_false_missing_result(skipna)
.unwrap_or_else(|| self.sum())
}
/// Mean with explicit pandas `skipna=` control.
#[must_use]
pub fn mean_skipna(&self, skipna: bool) -> Scalar {
self.skipna_false_missing_result(skipna)
.unwrap_or_else(|| self.mean())
}
/// Minimum with explicit pandas `skipna=` control.
#[must_use]
pub fn min_skipna(&self, skipna: bool) -> Scalar {
self.skipna_false_missing_result(skipna)
.unwrap_or_else(|| self.min())
}
/// Maximum with explicit pandas `skipna=` control.
#[must_use]
pub fn max_skipna(&self, skipna: bool) -> Scalar {
self.skipna_false_missing_result(skipna)
.unwrap_or_else(|| self.max())
}
/// Median with explicit pandas `skipna=` control.
#[must_use]
pub fn median_skipna(&self, skipna: bool) -> Scalar {
self.skipna_false_missing_result(skipna)
.unwrap_or_else(|| self.median())
}
/// Product with explicit pandas `skipna=` control.
#[must_use]
pub fn prod_skipna(&self, skipna: bool) -> Scalar {
self.skipna_false_missing_result(skipna)
.unwrap_or_else(|| self.prod())
}
/// Variance with explicit pandas `skipna=` control.
#[must_use]
pub fn var_skipna(&self, ddof: usize, skipna: bool) -> Scalar {
self.skipna_false_missing_result(skipna)
.unwrap_or_else(|| self.var(ddof))
}
/// Standard deviation with explicit pandas `skipna=` control.
#[must_use]
pub fn std_skipna(&self, ddof: usize, skipna: bool) -> Scalar {
self.skipna_false_missing_result(skipna)
.unwrap_or_else(|| self.std(ddof))
}
/// Standard error of the mean with explicit pandas `skipna=` control.
#[must_use]
pub fn sem_skipna(&self, ddof: usize, skipna: bool) -> Scalar {
self.skipna_false_missing_result(skipna)
.unwrap_or_else(|| self.sem(ddof))
}
/// Count of non-missing values.
///
/// Matches `pd.Series.count()`.
#[must_use]
pub fn count(&self) -> usize {
if self.dtype == DType::Float64 {
if let Some((data, validity)) = self.as_f64_slice_with_validity() {
if validity.all() {
return data.iter().filter(|value| !value.is_nan()).count();
}
return data
.iter()
.enumerate()
.filter(|(idx, value)| validity.get(*idx) && !value.is_nan())
.count();
}
if let Some(data) = self.as_f64_slice() {
return data.iter().filter(|value| !value.is_nan()).count();
}
}
if matches!(
self.dtype,
DType::Bool
| DType::BoolNullable
| DType::Int64
| DType::Int64Nullable
| DType::Utf8
| DType::Interval
) {
return self.validity.count_valid();
}
self.values.iter().filter(|v| !v.is_missing()).count()
}
/// Forward-fill missing values with the most recent non-missing
/// value, optionally capped by `limit` consecutive fills.
///
/// Matches `pd.Series.ffill(limit=None)`. Leading nulls stay null
/// until the first non-missing value is seen. `limit=None` means
/// unbounded; `limit=Some(k)` caps each missing run to `k` fills.
pub fn ffill(&self, limit: Option<usize>) -> Result<Self, ColumnError> {
let len = self.values.len();
// Typed fast paths: carry the last present value forward over the raw
// buffer + validity, no Scalar materialization. A still-missing slot (no
// prior value, or limit exceeded) stays missing via the validity mask,
// which materializes the SAME null the Scalar path pushes via v.clone():
// Float64 → Null(NaN), Int64 → Null(Null) (= missing_for_dtype). Bit-identical.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let mut out = vec![0.0_f64; len];
let mut vmask = ValidityMask::all_valid(len);
let mut last: Option<f64> = None;
let mut run = 0usize;
for i in 0..len {
if validity.get(i) && !data[i].is_nan() {
out[i] = data[i];
last = Some(data[i]);
run = 0;
} else {
match (last, limit) {
(Some(p), None) => out[i] = p,
(Some(p), Some(cap)) if run < cap => {
out[i] = p;
run += 1;
}
_ => vmask.set(i, false),
}
}
}
return Ok(Self::from_f64_values_with_validity(out, vmask));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut out = vec![0_i64; len];
let mut vmask = ValidityMask::all_valid(len);
let mut last: Option<i64> = None;
let mut run = 0usize;
for i in 0..len {
if validity.get(i) {
out[i] = data[i];
last = Some(data[i]);
run = 0;
} else {
match (last, limit) {
(Some(p), None) => out[i] = p,
(Some(p), Some(cap)) if run < cap => {
out[i] = p;
run += 1;
}
_ => vmask.set(i, false),
}
}
}
return Ok(Self::from_i64_values_with_validity(out, vmask));
}
let mut out = Vec::with_capacity(self.values.len());
let mut last: Option<Scalar> = None;
let mut run = 0usize;
for v in &self.values {
if !v.is_missing() {
out.push(v.clone());
last = Some(v.clone());
run = 0;
continue;
}
match (&last, limit) {
(Some(prev), None) => out.push(prev.clone()),
(Some(prev), Some(cap)) if run < cap => {
out.push(prev.clone());
run += 1;
}
_ => out.push(v.clone()),
}
}
Self::new(self.dtype, out)
}
/// Alias for [`ffill`](Self::ffill), matching deprecated `pd.Series.pad()`.
pub fn pad(&self, limit: Option<usize>) -> Result<Self, ColumnError> {
self.ffill(limit)
}
/// Backward-fill missing values with the next non-missing value,
/// optionally capped by `limit` consecutive fills.
///
/// Matches `pd.Series.bfill(limit=None)`. Trailing nulls stay null
/// if no subsequent non-missing value is observed.
pub fn bfill(&self, limit: Option<usize>) -> Result<Self, ColumnError> {
let len = self.values.len();
// Typed fast paths: carry the next present value backward over the raw
// buffer + validity (the Scalar loop's `Null(NaN)` init is dead — every
// slot is overwritten, missing ones via `v.clone()`), so a still-missing
// slot materializes the SAME null from the validity mask: Float64 →
// Null(NaN), Int64 → Null(Null). Bit-identical, no Scalar materialization.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let mut out = vec![0.0_f64; len];
let mut vmask = ValidityMask::all_valid(len);
let mut next: Option<f64> = None;
let mut run = 0usize;
for i in (0..len).rev() {
if validity.get(i) && !data[i].is_nan() {
out[i] = data[i];
next = Some(data[i]);
run = 0;
} else {
match (next, limit) {
(Some(p), None) => out[i] = p,
(Some(p), Some(cap)) if run < cap => {
out[i] = p;
run += 1;
}
_ => vmask.set(i, false),
}
}
}
return Ok(Self::from_f64_values_with_validity(out, vmask));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut out = vec![0_i64; len];
let mut vmask = ValidityMask::all_valid(len);
let mut next: Option<i64> = None;
let mut run = 0usize;
for i in (0..len).rev() {
if validity.get(i) {
out[i] = data[i];
next = Some(data[i]);
run = 0;
} else {
match (next, limit) {
(Some(p), None) => out[i] = p,
(Some(p), Some(cap)) if run < cap => {
out[i] = p;
run += 1;
}
_ => vmask.set(i, false),
}
}
}
return Ok(Self::from_i64_values_with_validity(out, vmask));
}
let mut out = vec![Scalar::Null(NullKind::NaN); self.values.len()];
let mut next: Option<Scalar> = None;
let mut run = 0usize;
for (i, v) in self.values.iter().enumerate().rev() {
if !v.is_missing() {
out[i] = v.clone();
next = Some(v.clone());
run = 0;
continue;
}
match (&next, limit) {
(Some(nxt), None) => out[i] = nxt.clone(),
(Some(nxt), Some(cap)) if run < cap => {
out[i] = nxt.clone();
run += 1;
}
_ => out[i] = v.clone(),
}
}
Self::new(self.dtype, out)
}
/// Alias for [`bfill`](Self::bfill), matching deprecated `pd.Series.backfill()`.
pub fn backfill(&self, limit: Option<usize>) -> Result<Self, ColumnError> {
self.bfill(limit)
}
/// Count of distinct non-missing values.
///
/// Matches `pd.Series.nunique(dropna=True)`.
#[must_use]
pub fn nunique(&self) -> Scalar {
self.nunique_with_dropna(true)
}
/// Count of distinct values with explicit missing-value handling.
///
/// Matches `pd.Series.nunique(dropna=...)`. When `dropna=false`,
/// all missing values contribute a single extra distinct bucket.
#[must_use]
pub fn nunique_with_dropna(&self, dropna: bool) -> Scalar {
// Dense direct-address fast path: an all-valid, bounded-range Int64
// column counts distinct values via a seen-bitset indexed by (v-min) —
// hash-free, no Scalar enum. All-valid ⇒ no missing, so dropna does not
// add a bucket; bit-identical to nannunique's distinct count. Same gate
// as unique/isin/duplicated.
if let Some(data) = self.as_i64_slice() {
if let Some((min, range)) = i64_direct_address_range(data) {
let mut seen = vec![false; range];
let mut distinct = 0i64;
for &v in data {
let slot = (v as i128 - min as i128) as usize;
if !seen[slot] {
seen[slot] = true;
distinct += 1;
}
}
return Scalar::Int64(distinct);
}
// Wide / sparse all-valid Int64: out of dense-bitset range, but the
// raw &[i64] still avoids Scalar materialization — count distinct via
// the purpose-built open-addressing set (beats the FxHashSet floor).
return Scalar::Int64(count_distinct_i64_wide(data));
}
// Datetime64 / Timedelta64 (i64-ns-backed): an all-valid, no-NaT column
// reuses the Int64 distinct-count machinery over the raw ns. The count is
// dtype-independent — no re-tag. Bit-identical to `nannunique`: a non-NaT
// temporal value's key is its ns, so the distinct count of ns equals the
// distinct count of timestamps; all-valid ⇒ no missing, so `dropna` does
// not add a bucket (identical for BOTH dropna values). NaT (`i64::MIN`) /
// nullable falls through to `nannunique` (which skips missing and the
// `!dropna` branch adds one bucket). Mirrors the same routing already used
// by `unique`/`value_counts`/`duplicated`.
if !self.has_nulls()
&& let Some(data) = self
.as_datetime64_slice()
.or_else(|| self.as_timedelta64_slice())
&& !data.contains(&i64::MIN)
{
return Scalar::Int64(count_distinct_i64_wide(data));
}
// Nullable Bool has only two present-value buckets plus, when requested,
// one missing bucket. Scan the raw bits and validity instead of forcing
// `LazyNullableBool` to materialize a `Vec<Scalar>` and hash every row.
// The variant guarantees every invalid slot observes `Null(Null)`, so all
// missing rows collapse to the same bucket exactly as `nannunique` does.
if let ScalarValues::LazyNullableBool { data, validity, .. } = &self.values {
let mut seen_false = false;
let mut seen_true = false;
let mut seen_missing = false;
let maximum = if dropna { 2 } else { 3 };
for (i, &value) in data.iter().enumerate() {
if validity.get(i) {
if value {
seen_true = true;
} else {
seen_false = true;
}
} else {
seen_missing = true;
}
let distinct = i64::from(seen_false)
+ i64::from(seen_true)
+ i64::from(!dropna && seen_missing);
if distinct == maximum {
return Scalar::Int64(distinct);
}
}
return Scalar::Int64(
i64::from(seen_false)
+ i64::from(seen_true)
+ i64::from(!dropna && seen_missing),
);
}
// Contiguous-Utf8 fast path (sibling of `unique`/`value_counts`'s byte-span
// dedup): `nannunique(&self.values)` forces `as_slice()` to materialize a
// `Vec<Scalar::Utf8>` -- one heap `String` per row -- then keys each by
// `&str`. Count distinct byte spans directly via `FxHashSet<&[u8]>`
// (byte-equality is exactly `&str`-equality for valid UTF-8) with ZERO
// per-row `String` alloc. `as_utf8_contiguous` only matches an all-valid
// backing, so there are no missing values: `nannunique` skips missing (none
// here) and the `!dropna` branch below adds a bucket only when a missing
// value exists (none here) -- so the distinct count is identical for BOTH
// `dropna` values, matching this fast path's single return.
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
let mut seen: FxHashSet<&[u8]> = FxHashSet::default();
for w in offsets.windows(2) {
seen.insert(&bytes[w[0]..w[1]]);
}
return Scalar::Int64(seen.len() as i64);
}
// Nullable contiguous-Utf8 fast path (COLD cache): the all-valid arm above gates
// on `as_utf8_contiguous` (validity.all()), so a `LazyNullableUtf8` column — a
// string column WITH missing rows, the common CSV/parquet shape — fell to
// `nannunique(&self.values)` which materializes a `Vec<Scalar::Utf8>` (one heap
// `String` per row). Count distinct PRESENT byte spans via `FxHashSet<&[u8]>`
// (byte-eq == `&str`-eq for valid UTF-8), tracking whether any missing exists.
// Bit-identical to the generic path: `nannunique` skips missing (== my
// validity-gated insert) and `!dropna` adds exactly one bucket when any missing
// row exists (a `LazyNullableUtf8` missing slot is `Null(Null)`, all one kind).
// Gated on a COLD `values` cache: the win is skipping the materialization the cold
// generic path pays (~5x on a fresh column, the usual `df[col].nunique()` shape);
// a warm/already-materialized column defers to `nannunique` over the cached Scalar
// Vec (whose per-row hash beats the typed `validity.get` scan) — no regression.
if let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
values,
} = &self.values
&& values.get().is_none()
{
let mut seen: FxHashSet<&[u8]> = FxHashSet::default();
let mut any_missing = false;
for (i, w) in offsets.windows(2).enumerate() {
if validity.get(i) {
seen.insert(&bytes[w[0]..w[1]]);
} else {
any_missing = true;
}
}
let mut distinct = seen.len() as i64;
if !dropna && any_missing {
distinct += 1;
}
return Scalar::Int64(distinct);
}
let mut distinct = match nannunique(&self.values) {
Scalar::Int64(count) => count,
_ => 0,
};
if !dropna && self.values.iter().any(Scalar::is_missing) {
distinct += 1;
}
Scalar::Int64(distinct)
}
/// Truthiness reduction: whether any non-missing value is truthy.
///
/// Matches `pd.Series.any()` in skipna=True mode. Empty column
/// returns false (pandas convention).
#[must_use]
pub fn any(&self) -> Scalar {
// Typed Bool reduction: `as_bool_slice()` is Some only for an all-valid
// Bool column, so `nanany` (which merely skips missing) reduces to a
// plain `.any()` over the raw `&[bool]` -- early-exit preserved, no
// `Vec<Scalar>` materialization or per-Scalar dispatch. Bit-identical.
if let Some(data) = self.as_bool_slice() {
return Scalar::Bool(data.iter().any(|&b| b));
}
nanany(&self.values)
}
/// Truthiness reduction: whether all non-missing values are truthy.
///
/// Matches `pd.Series.all()` in skipna=True mode. Empty column
/// returns true.
#[must_use]
pub fn all(&self) -> Scalar {
// Symmetric to `any`: for an all-valid Bool column `nanall` reduces to a
// plain `.all()` over the raw `&[bool]`. Bit-identical, early-exit kept.
if let Some(data) = self.as_bool_slice() {
return Scalar::Bool(data.iter().all(|&b| b));
}
nanall(&self.values)
}
/// Element-wise difference between consecutive non-missing values.
///
/// Unlike `diff(1)` — which inserts Null(NaN) for every missing
/// input — this walker-style helper skips nulls when picking the
/// "previous" value. Positions whose nearest preceding non-missing
/// neighbor lies before the start of the column (i.e. the first
/// non-missing value itself, or a missing input) emit Null(NaN).
/// Matches the common pandas idiom `s.dropna().diff().reindex(s.index)`.
pub fn diff_valid(&self) -> Result<Self, ColumnError> {
let mut prev: Option<f64> = None;
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Null(NullKind::NaN));
continue;
}
match v.to_f64() {
Ok(x) if !x.is_nan() => match prev {
Some(p) => {
out.push(Scalar::Float64(x - p));
prev = Some(x);
}
None => {
out.push(Scalar::Null(NullKind::NaN));
prev = Some(x);
}
},
Ok(_) => out.push(Scalar::Null(NullKind::NaN)),
Err(err) => return Err(ColumnError::Type(err)),
}
}
Self::new(DType::Float64, out)
}
/// Deterministic uniform sampling of `n` rows with a caller-supplied
/// seed.
///
/// Matches the no-replacement subset of `pd.Series.sample(n,
/// random_state=seed)`. `n >= len()` returns a clone. Uses an
/// in-place partial Fisher-Yates shuffle driven by a stateless
/// LCG so callers can reproduce samples without dragging in
/// `rand`. Result dtype matches `self`.
pub fn sample(&self, n: usize, seed: u64) -> Result<Self, ColumnError> {
let len = self.values.len();
if n >= len {
return Ok(self.clone());
}
let mut indices: Vec<usize> = (0..len).collect();
let mut state = seed.wrapping_add(0x9E3779B97F4A7C15);
for i in 0..n {
// Standard LCG constants from Knuth (MMIX).
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
let bound = (len - i) as u64;
let pick = i + (state.wrapping_shr(33) % bound) as usize;
indices.swap(i, pick);
}
let values: Vec<Scalar> = indices[..n]
.iter()
.map(|&idx| self.values[idx].clone())
.collect();
Self::new(self.dtype, values)
}
/// Position of the first non-missing value, or None when every
/// value is missing.
///
/// Matches `pd.Series.first_valid_index()` for positional
/// indices — callers can map the returned position through their
/// own Index to recover a label.
#[must_use]
pub fn first_valid(&self) -> Option<usize> {
self.values.iter().position(|v| !v.is_missing())
}
/// Alias for [`first_valid`](Self::first_valid), matching
/// `pd.Series.first_valid_index()` for positional indices.
#[must_use]
pub fn first_valid_index(&self) -> Option<usize> {
self.first_valid()
}
/// Position of the last non-missing value, or None when every
/// value is missing.
///
/// Matches `pd.Series.last_valid_index()` for positional indices.
#[must_use]
pub fn last_valid(&self) -> Option<usize> {
self.values.iter().rposition(|v| !v.is_missing())
}
/// Alias for [`last_valid`](Self::last_valid), matching
/// `pd.Series.last_valid_index()` for positional indices.
#[must_use]
pub fn last_valid_index(&self) -> Option<usize> {
self.last_valid()
}
/// Sliding-window sum over `window` consecutive positions.
///
/// Matches `pd.Series.rolling(window).sum()`. Positions with fewer
/// than `min_periods` non-missing values in the window emit
/// `Null(NaN)`. `min_periods=0` preserves pandas' convention that
/// an empty window sums to 0.0. Result dtype is always Float64.
/// `window=0` returns an all-null Float64 column the same length
/// as self.
pub fn rolling_window_sum(
&self,
window: usize,
min_periods: usize,
) -> Result<Self, ColumnError> {
let len = self.values.len();
if window == 0 {
return Self::new(DType::Float64, vec![Scalar::Null(NullKind::NaN); len]);
}
let mut out = Vec::with_capacity(len);
for i in 0..len {
let start = (i + 1).saturating_sub(window);
let end = i + 1;
let mut sum = 0.0_f64;
let mut observed = 0usize;
for v in &self.values[start..end] {
if v.is_missing() {
continue;
}
match v.to_f64() {
Ok(x) if !x.is_nan() => {
sum += x;
observed += 1;
}
Ok(_) => {}
Err(err) => return Err(ColumnError::Type(err)),
}
}
if observed >= min_periods.max(1) || (min_periods == 0 && end - start > 0) {
out.push(Scalar::Float64(sum));
} else {
out.push(Scalar::Null(NullKind::NaN));
}
}
Self::new(DType::Float64, out)
}
/// Per-row missing-value flag (Bool column).
///
/// Matches `pd.Series.isna()` / `isnull()`.
pub fn isnull(&self) -> Result<Self, ColumnError> {
if self.dtype == DType::Float64 {
if let Some((data, validity)) = self.as_f64_slice_with_validity() {
let out: Vec<bool> = data
.iter()
.enumerate()
.map(|(idx, value)| !validity.get(idx) || value.is_nan())
.collect();
return Ok(Self::from_bool_values(out));
}
if let Some(data) = self.as_f64_slice() {
let out: Vec<bool> = data.iter().map(|value| value.is_nan()).collect();
return Ok(Self::from_bool_values(out));
}
}
if self.missingness_is_validity_only() {
let out = Self::bool_values_from_validity(&self.validity, false, true);
return Ok(Self::from_bool_values(out));
}
let out: Vec<Scalar> = self
.values
.iter()
.map(|v| Scalar::Bool(v.is_missing()))
.collect();
Self::new(DType::Bool, out)
}
/// Alias for [`isnull`](Self::isnull), matching `pd.Series.isna()`.
pub fn isna(&self) -> Result<Self, ColumnError> {
self.isnull()
}
/// Per-row non-missing flag (Bool column).
///
/// Matches `pd.Series.notna()` / `notnull()`.
pub fn notnull(&self) -> Result<Self, ColumnError> {
if self.dtype == DType::Float64 {
if let Some((data, validity)) = self.as_f64_slice_with_validity() {
let out: Vec<bool> = data
.iter()
.enumerate()
.map(|(idx, value)| validity.get(idx) && !value.is_nan())
.collect();
return Ok(Self::from_bool_values(out));
}
if let Some(data) = self.as_f64_slice() {
let out: Vec<bool> = data.iter().map(|value| !value.is_nan()).collect();
return Ok(Self::from_bool_values(out));
}
}
if self.missingness_is_validity_only() {
let out = Self::bool_values_from_validity(&self.validity, true, false);
return Ok(Self::from_bool_values(out));
}
let out: Vec<Scalar> = self
.values
.iter()
.map(|v| Scalar::Bool(!v.is_missing()))
.collect();
Self::new(DType::Bool, out)
}
/// Alias for [`notnull`](Self::notnull), matching `pd.Series.notna()`.
pub fn notna(&self) -> Result<Self, ColumnError> {
self.notnull()
}
fn missingness_is_validity_only(&self) -> bool {
matches!(
self.dtype,
DType::Bool
| DType::BoolNullable
| DType::Int64
| DType::Int64Nullable
| DType::Utf8
| DType::Interval
)
}
fn bool_values_from_validity(
validity: &ValidityMask,
valid_value: bool,
invalid_value: bool,
) -> Vec<bool> {
let len = validity.len();
if validity.all() {
return vec![valid_value; len];
}
if let Some(ranges) = &validity.invalid_ranges {
let mut out = vec![valid_value; len];
for &(start, run_len) in ranges.iter() {
if let Some(end) = start.checked_add(run_len)
&& let Some(span) = out.get_mut(start..end)
{
span.fill(invalid_value);
}
}
return out;
}
validity
.bits()
.map(|valid| if valid { valid_value } else { invalid_value })
.collect()
}
/// Per-row check for finite values (not NaN or infinity).
pub fn isfinite(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.bool_values_from_f64(false, f64::is_finite) {
return Ok(Self::from_bool_values(out));
}
let out: Vec<Scalar> = self
.values
.iter()
.map(|v| match v {
Scalar::Float64(f) => Scalar::Bool(f.is_finite()),
Scalar::Int64(_) => Scalar::Bool(true),
_ if v.is_missing() => Scalar::Bool(false),
_ => Scalar::Bool(true),
})
.collect();
Self::new(DType::Bool, out)
}
/// Per-row check for infinite values.
pub fn isinf(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.bool_values_from_f64(false, f64::is_infinite) {
return Ok(Self::from_bool_values(out));
}
let out: Vec<Scalar> = self
.values
.iter()
.map(|v| match v {
Scalar::Float64(f) => Scalar::Bool(f.is_infinite()),
_ => Scalar::Bool(false),
})
.collect();
Self::new(DType::Bool, out)
}
/// Per-row check for NaN values.
pub fn isnan(&self) -> Result<Self, ColumnError> {
if self.dtype == DType::Float64 && matches!(&self.values, ScalarValues::Eager(_)) {
let out: Vec<Scalar> = self
.values
.iter()
.map(|v| match v {
Scalar::Float64(f) => Scalar::Bool(f.is_nan()),
Scalar::Null(NullKind::NaN) => Scalar::Bool(true),
_ => Scalar::Bool(false),
})
.collect();
return Self::new(DType::Bool, out);
}
if let Some(out) = self.bool_values_from_f64(true, f64::is_nan) {
return Ok(Self::from_bool_values(out));
}
let out: Vec<Scalar> = self
.values
.iter()
.map(|v| match v {
Scalar::Float64(f) => Scalar::Bool(f.is_nan()),
Scalar::Null(NullKind::NaN) => Scalar::Bool(true),
_ => Scalar::Bool(false),
})
.collect();
Self::new(DType::Bool, out)
}
fn bool_values_from_f64<F>(&self, invalid_value: bool, predicate: F) -> Option<Vec<bool>>
where
F: Fn(f64) -> bool,
{
if self.dtype != DType::Float64 {
return None;
}
if let Some((data, validity)) = self.as_f64_slice_with_validity() {
return Some(
data.iter()
.enumerate()
.map(|(idx, value)| {
if validity.get(idx) {
predicate(*value)
} else {
invalid_value
}
})
.collect(),
);
}
self.as_f64_slice()
.map(|data| data.iter().map(|&value| predicate(value)).collect())
}
/// Sample variance (ddof-parameterized).
///
/// Matches `pd.Series.var(ddof=1)`.
#[must_use]
pub fn var(&self, ddof: usize) -> Scalar {
// Typed two-pass reduction: an all-valid Float64 column computes the
// mean then the sum of squared deviations straight over its contiguous
// buffer, skipping the Vec<Scalar> materialization. Bit-identical to
// nanvar's numeric arm — the exact same `Iterator::sum::<f64>()`
// constructs over the same values in the same order (so seed/ordering
// match), `Null(NaN)` when count <= ddof.
if let Some(data) = self.as_f64_slice() {
let n = data.len();
if n <= ddof {
return Scalar::Null(NullKind::NaN);
}
let mean: f64 = data.iter().sum::<f64>() / n as f64;
let sum_sq: f64 = data.iter().map(|&x| (x - mean).powi(2)).sum::<f64>();
return Scalar::Float64(sum_sq / (n - ddof) as f64);
}
// Int64 analogue: an all-valid Int64 column runs the SAME two-pass over
// `v as f64` straight off the raw `&[i64]`, skipping nanvar's
// `Vec<Scalar::Int64>` materialization AND its per-Scalar `to_f64` in
// `collect_finite`. Bit-identical: `as_i64_slice` gates dtype==Int64 &&
// all-valid, so `collect_finite` (drop-missing + `to_f64`) reduces to
// `[v as f64]` in the same order, and `n == nums.len()` (no missing) so the
// `n <= ddof -> Null(NaN)` guard matches. dtype==Int64 gate keeps
// Timedelta64's dtype-preserving nanvar arm untouched.
if let Some(data) = self.as_i64_slice() {
let n = data.len();
if n <= ddof {
return Scalar::Null(NullKind::NaN);
}
let mean: f64 = data.iter().map(|&v| v as f64).sum::<f64>() / n as f64;
let sum_sq: f64 = data.iter().map(|&v| (v as f64 - mean).powi(2)).sum::<f64>();
return Scalar::Float64(sum_sq / (n - ddof) as f64);
}
// Nullable Float64/Int64: two-pass moments over the PRESENT subset, skipping
// nanvar's Vec<Scalar> materialization + collect_finite. Bit-identical (same
// present values, same order ⇒ same n/mean/sum_sq; n <= ddof ⇒ Null(NaN)).
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let (n, _mean, sum_sq) = present_moments_f64(data, Some(validity));
return if n <= ddof {
Scalar::Null(NullKind::NaN)
} else {
Scalar::Float64(sum_sq / (n - ddof) as f64)
};
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let (n, _mean, sum_sq) = present_moments_i64(data, Some(validity));
return if n <= ddof {
Scalar::Null(NullKind::NaN)
} else {
Scalar::Float64(sum_sq / (n - ddof) as f64)
};
}
nanvar(&self.values, ddof)
}
/// Sample standard deviation (ddof-parameterized).
///
/// Matches `pd.Series.std(ddof=1)`.
#[must_use]
pub fn std(&self, ddof: usize) -> Scalar {
// For an all-valid Float64 OR Int64 column nanstd is sqrt(nanvar) (the
// non-Timedelta arm); reuse the typed var (which has both fast paths),
// skipping nanstd's Vec<Scalar> materialization (and, for Int64, its extra
// collect_finite f64 buffer). Bit-identical: nanstd's numeric arm is
// literally `match nanvar(..) { Float64(v) => Float64(v.sqrt()), other =>
// other }`, and typed var == nanvar for these dtypes, so the same var bits
// are sqrt'd (and a n<=ddof Null(NaN) passes through unchanged). Non-Float64
// /non-Int64 (e.g. Timedelta) keep nanstd's dtype-preserving path.
// Delegate to typed var for any Float64/Int64 column (all-valid OR nullable
// — var now has both). nanstd's numeric arm is literally sqrt(nanvar), and
// typed var == nanvar for these dtypes, so this is bit-identical. Timedelta
// and other dtypes keep nanstd's dtype-preserving path.
if matches!(self.dtype, DType::Float64 | DType::Int64) {
return match self.var(ddof) {
Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
other => other,
};
}
nanstd(&self.values, ddof)
}
/// Standard error of the mean (ddof-parameterized).
///
/// Matches `pd.Series.sem(ddof=1)`.
#[must_use]
pub fn sem(&self, ddof: usize) -> Scalar {
// sem = std / sqrt(n) over the PRESENT subset (n = present count). The
// as_*_with_validity two-pass handles all-valid AND nullable Float64/Int64
// (for all-valid, validity.get is always true, so present == non-NaN,
// exactly collect_finite's finite filter) — a SINGLE two-pass, vs nansem's
// DOUBLE collect_finite (once for `n`, again in nanstd->nanvar) AND its
// Vec<Scalar> materialization. Bit-identical: same present values, same
// order ⇒ same n/mean/sum_sq, same `n <= ddof -> Null(NaN)` guard.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let (n, _mean, sum_sq) = present_moments_f64(data, Some(validity));
if n <= ddof {
return Scalar::Null(NullKind::NaN);
}
let std = (sum_sq / (n - ddof) as f64).sqrt();
return Scalar::Float64(std / (n as f64).sqrt());
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let (n, _mean, sum_sq) = present_moments_i64(data, Some(validity));
if n <= ddof {
return Scalar::Null(NullKind::NaN);
}
let std = (sum_sq / (n - ddof) as f64).sqrt();
return Scalar::Float64(std / (n as f64).sqrt());
}
// Fallback for all-valid Float64/Int64 backings the two accessors above do
// NOT expose (chunked / transposed / strided variants that as_f64_slice
// reaches but as_f64_slice_with_validity does not). Bit-identical Vec path.
if let Some(nums) = self.typed_collect_finite_f64() {
let n = nums.len();
if n <= ddof {
return Scalar::Null(NullKind::NaN);
}
let nf = n as f64;
let mean = nums.iter().sum::<f64>() / nf;
let sum_sq: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
let std = (sum_sq / (n - ddof) as f64).sqrt();
return Scalar::Float64(std / nf.sqrt());
}
nansem(&self.values, ddof)
}
/// Sample covariance between this column and another.
///
/// Matches `pd.Series.cov(other)`. Uses ddof=1 by default.
/// Returns NaN if fewer than 2 valid pairs.
#[must_use]
pub fn cov(&self, other: &Self) -> Scalar {
self.cov_ddof(other, 1)
}
/// Borrowed typed numeric view for the pairwise cov/corr fast paths — `Some`
/// only for an all-valid or nullable Float64/Int64 column with a slice-exposing
/// backing.
fn typed_numeric_values(&self) -> Option<TypedNumericValues<'_>> {
match self.dtype {
DType::Float64 => self
.as_f64_slice_with_validity()
.map(|(d, v)| TypedNumericValues::F64(d, v)),
DType::Int64 => self
.as_i64_slice_with_validity()
.map(|(d, v)| TypedNumericValues::I64(d, v)),
_ => None,
}
}
/// Sample covariance with custom ddof.
#[must_use]
pub fn cov_ddof(&self, other: &Self, ddof: usize) -> Scalar {
let n = self.values.len().min(other.values.len());
if n == 0 {
return Scalar::Null(NullKind::NaN);
}
// Typed pairwise fast path: both columns Float64/Int64 (all-valid or
// nullable) fold straight off the raw slices via `get_finite`, skipping the
// Vec<Scalar> materialization of BOTH columns + per-Scalar to_f64. Bit-
// identical: `get_finite` == the `to_f64() Ok(v) if v.is_finite()` gate, and
// the two passes sum the same pairwise-present values in the same 0..n order.
if let (Some(sx), Some(sy)) = (self.typed_numeric_values(), other.typed_numeric_values()) {
let n = sx.len().min(sy.len());
let (mut sum_x, mut sum_y, mut count) = (0.0_f64, 0.0_f64, 0usize);
for i in 0..n {
if let (Some(x), Some(y)) = (sx.get_finite(i), sy.get_finite(i)) {
sum_x += x;
sum_y += y;
count += 1;
}
}
if count <= ddof {
return Scalar::Null(NullKind::NaN);
}
let mean_x = sum_x / count as f64;
let mean_y = sum_y / count as f64;
let mut cov_sum = 0.0_f64;
for i in 0..n {
if let (Some(x), Some(y)) = (sx.get_finite(i), sy.get_finite(i)) {
cov_sum += (x - mean_x) * (y - mean_y);
}
}
return Scalar::Float64(cov_sum / (count - ddof) as f64);
}
let mut sum_x = 0.0;
let mut sum_y = 0.0;
let mut count = 0usize;
for i in 0..n {
let x = match self.values[i].to_f64() {
Ok(v) if v.is_finite() => v,
_ => continue,
};
let y = match other.values[i].to_f64() {
Ok(v) if v.is_finite() => v,
_ => continue,
};
sum_x += x;
sum_y += y;
count += 1;
}
if count <= ddof {
return Scalar::Null(NullKind::NaN);
}
let mean_x = sum_x / count as f64;
let mean_y = sum_y / count as f64;
let mut cov_sum = 0.0;
for i in 0..n {
let x = match self.values[i].to_f64() {
Ok(v) if v.is_finite() => v,
_ => continue,
};
let y = match other.values[i].to_f64() {
Ok(v) if v.is_finite() => v,
_ => continue,
};
cov_sum += (x - mean_x) * (y - mean_y);
}
Scalar::Float64(cov_sum / (count - ddof) as f64)
}
/// Pearson correlation coefficient between this column and another.
///
/// Matches `pd.Series.corr(other)`. Returns NaN if fewer than 2 valid pairs.
#[must_use]
pub fn corr(&self, other: &Self) -> Scalar {
let n = self.values.len().min(other.values.len());
if n == 0 {
return Scalar::Null(NullKind::NaN);
}
// Typed pairwise fast path (single pass, mirror of cov): fold the 5 sums
// straight off both raw slices via `get_finite`, skipping the Vec<Scalar>
// materialization of BOTH columns. Bit-identical (same present pairs, same
// 0..n order ⇒ same sums; same count<2 / denom==0 guards).
if let (Some(sx), Some(sy)) = (self.typed_numeric_values(), other.typed_numeric_values()) {
let m = sx.len().min(sy.len());
let (mut sum_x, mut sum_y, mut sum_xx, mut sum_yy, mut sum_xy) =
(0.0_f64, 0.0_f64, 0.0_f64, 0.0_f64, 0.0_f64);
let mut count = 0usize;
for i in 0..m {
if let (Some(x), Some(y)) = (sx.get_finite(i), sy.get_finite(i)) {
sum_x += x;
sum_y += y;
sum_xx += x * x;
sum_yy += y * y;
sum_xy += x * y;
count += 1;
}
}
if count < 2 {
return Scalar::Null(NullKind::NaN);
}
let n_f = count as f64;
let numerator = n_f * sum_xy - sum_x * sum_y;
let denom_x = (n_f * sum_xx - sum_x * sum_x).sqrt();
let denom_y = (n_f * sum_yy - sum_y * sum_y).sqrt();
if denom_x == 0.0 || denom_y == 0.0 {
return Scalar::Null(NullKind::NaN);
}
return Scalar::Float64(numerator / (denom_x * denom_y));
}
let mut sum_x = 0.0;
let mut sum_y = 0.0;
let mut sum_xx = 0.0;
let mut sum_yy = 0.0;
let mut sum_xy = 0.0;
let mut count = 0usize;
for i in 0..n {
let x = match self.values[i].to_f64() {
Ok(v) if v.is_finite() => v,
_ => continue,
};
let y = match other.values[i].to_f64() {
Ok(v) if v.is_finite() => v,
_ => continue,
};
sum_x += x;
sum_y += y;
sum_xx += x * x;
sum_yy += y * y;
sum_xy += x * y;
count += 1;
}
if count < 2 {
return Scalar::Null(NullKind::NaN);
}
let n_f = count as f64;
let numerator = n_f * sum_xy - sum_x * sum_y;
let denom_x = (n_f * sum_xx - sum_x * sum_x).sqrt();
let denom_y = (n_f * sum_yy - sum_y * sum_y).sqrt();
if denom_x == 0.0 || denom_y == 0.0 {
return Scalar::Null(NullKind::NaN);
}
Scalar::Float64(numerator / (denom_x * denom_y))
}
/// Autocorrelation at a given lag.
///
/// Matches `pd.Series.autocorr(lag)`. Returns NaN if fewer than 2 valid pairs.
#[must_use]
pub fn autocorr(&self, lag: usize) -> Scalar {
if lag >= self.values.len() {
return Scalar::Null(NullKind::NaN);
}
let shifted = match self.shift(lag as i64, Scalar::Null(NullKind::NaN)) {
Ok(s) => s,
Err(_) => return Scalar::Null(NullKind::NaN),
};
self.corr(&shifted)
}
/// Sample skewness (bias-corrected, Fisher-Pearson).
///
/// Matches `pd.Series.skew()`. Requires at least 3 non-missing
/// values; returns `Null(NaN)` otherwise.
#[must_use]
/// Collect the non-missing values of an all-valid typed numeric column as
/// f64, exactly as `collect_finite` would over the Scalar view (Float64: drop
/// NaN, keep ±inf; Int64: all values as f64) — but straight off the contiguous
/// buffer, with no Scalar materialization. `None` for other backings.
fn typed_collect_finite_f64(&self) -> Option<Vec<f64>> {
if let Some(data) = self.as_f64_slice() {
return Some(data.iter().copied().filter(|x| !x.is_nan()).collect());
}
if let Some(data) = self.as_i64_slice() {
return Some(data.iter().map(|&x| x as f64).collect());
}
None
}
pub fn skew(&self) -> Scalar {
// Present central moments via a no-alloc two-pass over the raw slice +
// validity — handles ALL-VALID and nullable Float64/Int64 (for all-valid,
// validity.get is always true ⇒ present == non-NaN, exactly collect_finite's
// filter). Verbatim nanskew math. Bit-identical (same present values/order ⇒
// same n/m2/m3). This runs BEFORE the Vec-collecting fallback so the common
// all-valid case skips the Vec<f64> alloc + separate .map().sum() passes.
let moments = if self.dtype == DType::Float64 {
self.as_f64_slice_with_validity()
.map(|(d, v)| present_central_moments_f64(d, Some(v)))
} else if self.dtype == DType::Int64 {
self.as_i64_slice_with_validity()
.map(|(d, v)| present_central_moments_i64(d, Some(v)))
} else {
None
};
if let Some((cnt, m2, m3, _m4)) = moments {
let n = cnt as f64;
if n < 3.0 {
return Scalar::Null(NullKind::NaN);
}
let s2 = m2 / (n - 1.0);
if s2 == 0.0 {
return Scalar::Float64(0.0);
}
let s3 = s2.powf(1.5);
return Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3));
}
// Fallback for all-valid backings the accessors above don't expose (chunked/
// transposed/strided variants as_f64_slice reaches). Bit-identical Vec path.
if let Some(nums) = self.typed_collect_finite_f64() {
let n = nums.len() as f64;
if n < 3.0 {
return Scalar::Null(NullKind::NaN);
}
let mean = nums.iter().sum::<f64>() / n;
let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
let s2 = m2 / (n - 1.0);
if s2 == 0.0 {
return Scalar::Float64(0.0);
}
let s3 = s2.powf(1.5);
return Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3));
}
nanskew(&self.values)
}
/// Excess sample kurtosis (Fisher's definition, bias-corrected).
///
/// Matches `pd.Series.kurt()`. Requires at least 4 non-missing
/// values; returns `Null(NaN)` otherwise.
#[must_use]
pub fn kurt(&self) -> Scalar {
// Present central moments via a no-alloc two-pass (handles ALL-VALID and
// nullable Float64/Int64), BEFORE the Vec-collecting fallback. Verbatim
// nankurt math, bit-identical (same present values/order ⇒ same n/m2/m4).
let moments = if self.dtype == DType::Float64 {
self.as_f64_slice_with_validity()
.map(|(d, v)| present_central_moments_f64(d, Some(v)))
} else if self.dtype == DType::Int64 {
self.as_i64_slice_with_validity()
.map(|(d, v)| present_central_moments_i64(d, Some(v)))
} else {
None
};
if let Some((cnt, m2, _m3, m4)) = moments {
let n = cnt as f64;
if n < 4.0 {
return Scalar::Null(NullKind::NaN);
}
let s2 = m2 / (n - 1.0);
if s2 == 0.0 {
return Scalar::Float64(0.0);
}
let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
return Scalar::Float64(adj * (m4 / (s2 * s2)) - sub);
}
// Fallback for all-valid backings the accessors above don't expose. Vec path.
if let Some(nums) = self.typed_collect_finite_f64() {
let n = nums.len() as f64;
if n < 4.0 {
return Scalar::Null(NullKind::NaN);
}
let mean = nums.iter().sum::<f64>() / n;
let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
let s2 = m2 / (n - 1.0);
if s2 == 0.0 {
return Scalar::Float64(0.0);
}
let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
return Scalar::Float64(adj * (m4 / (s2 * s2)) - sub);
}
nankurt(&self.values)
}
/// Alias for [`kurt`](Self::kurt), matching `pd.Series.kurtosis()`.
#[must_use]
pub fn kurtosis(&self) -> Scalar {
self.kurt()
}
/// Peak-to-peak range (max − min) over non-missing values.
///
/// Matches `np.ptp`. Returns `Null(NaN)` for empty or all-missing
/// columns.
#[must_use]
pub fn ptp(&self) -> Scalar {
// Typed Float64/Int64 (all-valid + nullable): single-pass lo/hi over the
// raw slice + validity, instead of nanptp materializing the Vec<Scalar>.
// Bit-identical (skip missing/NaN, Float64(hi-lo), all-missing ⇒ Null(NaN)).
if let Some(data) = self.as_f64_slice() {
return ptp_nullable_f64(data, None);
}
if let Some(data) = self.as_i64_slice() {
return ptp_nullable_i64(data, None);
}
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
return ptp_nullable_f64(data, Some(validity));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
return ptp_nullable_i64(data, Some(validity));
}
nanptp(&self.values)
}
/// Whether every non-missing value is distinct.
///
/// Matches `pd.Series.is_unique`.
#[must_use]
pub fn is_unique(&self) -> bool {
!self.has_duplicates()
}
/// Whether any non-missing value repeats.
///
/// Matches `pd.Series.has_duplicates`.
#[must_use]
pub fn has_duplicates(&self) -> bool {
// All-valid typed Int64 columns can hash their borrowed primitive
// backing directly. The generic path below first materializes a
// Scalar array and hashes the wider tagged `Key` enum for every row.
// Equality is still exact i64 equality, and duplicate detection does
// not expose insertion order, so this is behavior-identical for the
// admitted representation.
if let Some(data) = self.as_i64_slice() {
let mut seen = FxHashSet::<i64>::default();
for &value in data {
if !seen.insert(value) {
return true;
}
}
return false;
}
#[derive(Hash, PartialEq, Eq)]
enum Key<'a> {
Bool(bool),
Int64(i64),
FloatBits(u64),
Utf8(&'a str),
Timedelta64(i64),
Datetime64(i64),
Period(i64),
Interval(u64, u64, IntervalClosed),
}
let mut seen: FxHashSet<Key<'_>> = FxHashSet::default();
for v in &self.values {
if v.is_missing() {
continue;
}
let key = match v {
Scalar::Bool(b) => Key::Bool(*b),
Scalar::Int64(i) => Key::Int64(*i),
Scalar::Float64(f) => {
let norm = if *f == 0.0 { 0.0 } else { *f };
Key::FloatBits(norm.to_bits())
}
Scalar::Utf8(s) => Key::Utf8(s.as_str()),
Scalar::Timedelta64(v) => Key::Timedelta64(*v),
Scalar::Datetime64(v) => Key::Datetime64(*v),
Scalar::Period(p) => Key::Period(p.ordinal),
Scalar::Interval(v) => {
let (left, right, closed) = interval_key(v);
Key::Interval(left, right, closed)
}
Scalar::Null(_) => continue,
};
if !seen.insert(key) {
return true;
}
}
false
}
/// Percent change between consecutive non-missing values.
///
/// Matches `pd.Series.pct_change(periods=1)` (fill_method defaults
/// to None on pandas 2.2+, so nulls propagate without forward fill).
/// Result dtype Float64. Non-numeric inputs return TypeError. The
/// leading `|periods|` positions are Null(NaN).
pub fn pct_change(&self, periods: i64) -> Result<Self, ColumnError> {
let len = self.values.len();
if len == 0 || periods == 0 {
return Self::new(DType::Float64, vec![Scalar::Null(NullKind::NaN); len]);
}
let abs = periods.unsigned_abs() as usize;
// Typed Float64-output fast paths (i64 / f64). Compute (cur−prev)/prev into
// an f64 buffer: NaN at the boundary AND where prev == 0.0 (the Scalar
// path's `p == 0.0` → Null guard; −0.0 == 0.0 so it's covered), let
// from_f64_values mark those missing. Bit-identical to the Scalar loop's
// `Float64((c−p)/p)` for all-valid columns (no NaN/missing input): a valid
// body value is finite or an overflow ±inf (never NaN, since prev ≠ 0),
// so only the boundary/zero-prev NaNs become missing. No Scalar materialization.
if abs < len {
// Build the body + an explicit validity mask: a slot is missing at the
// boundary OR where prev == 0.0 (the Scalar path's `p == 0.0` → Null
// guard; −0.0 == 0.0 so it's covered). from_f64_values_with_validity
// moves the body into a LazyNullableFloat64 backing → an invalid slot
// materializes Null(NaN) (= the Scalar Null), a valid slot Float64((c−p)/p)
// which is finite or an overflow ±inf but never NaN since prev ≠ 0.
// (from_f64_values would instead KEEP a NaN as Float64(NaN), not Null.)
if let Some(data) = self.as_f64_slice() {
let mut out = vec![0.0_f64; len];
let mut validity = ValidityMask::all_valid(len);
if periods > 0 {
for i in 0..abs {
validity.set(i, false);
}
for i in abs..len {
let p = data[i - abs];
if p != 0.0 {
out[i] = (data[i] - p) / p;
} else {
validity.set(i, false);
}
}
} else {
for i in (len - abs)..len {
validity.set(i, false);
}
for i in 0..len - abs {
let p = data[i + abs];
if p != 0.0 {
out[i] = (data[i] - p) / p;
} else {
validity.set(i, false);
}
}
}
return Ok(Self::from_f64_values_with_validity(out, validity));
}
if let Some(data) = self.as_i64_slice() {
let mut out = vec![0.0_f64; len];
let mut validity = ValidityMask::all_valid(len);
if periods > 0 {
for i in 0..abs {
validity.set(i, false);
}
for i in abs..len {
let p = data[i - abs] as f64;
if p != 0.0 {
out[i] = (data[i] as f64 - p) / p;
} else {
validity.set(i, false);
}
}
} else {
for i in (len - abs)..len {
validity.set(i, false);
}
for i in 0..len - abs {
let p = data[i + abs] as f64;
if p != 0.0 {
out[i] = (data[i] as f64 - p) / p;
} else {
validity.set(i, false);
}
}
}
return Ok(Self::from_f64_values_with_validity(out, validity));
}
}
let mut out: Vec<Scalar> = Vec::with_capacity(len);
for i in 0..len {
let prev_idx = if periods > 0 {
i.checked_sub(abs)
} else if i + abs < len {
Some(i + abs)
} else {
None
};
let Some(pi) = prev_idx else {
out.push(Scalar::Null(NullKind::NaN));
continue;
};
let cur = &self.values[i];
let prev = &self.values[pi];
if cur.is_missing() || prev.is_missing() {
out.push(Scalar::Null(NullKind::NaN));
continue;
}
// Per br-frankenpandas-mcu90: Timedelta64 pct_change matches
// pandas — ns deltas divide as dimensionless f64. Was silently
// NaN before via the catch-all (Timedelta64.to_f64() errors).
if let (Scalar::Timedelta64(cur_ns), Scalar::Timedelta64(prev_ns)) = (cur, prev) {
if *cur_ns == Timedelta::NAT || *prev_ns == Timedelta::NAT {
out.push(Scalar::Null(NullKind::NaN));
continue;
}
let prev_f = *prev_ns as f64;
if prev_f.abs() < f64::EPSILON {
out.push(Scalar::Null(NullKind::NaN));
} else {
out.push(Scalar::Float64((*cur_ns as f64 - prev_f) / prev_f));
}
continue;
}
match (cur.to_f64(), prev.to_f64()) {
(Ok(c), Ok(p)) => {
if p == 0.0 || p.is_nan() || c.is_nan() {
out.push(Scalar::Null(NullKind::NaN));
} else {
out.push(Scalar::Float64((c - p) / p));
}
}
_ => out.push(Scalar::Null(NullKind::NaN)),
}
}
Self::new(DType::Float64, out)
}
/// Percentage change with optional null fill before computation.
///
/// Matches `pd.Series.pct_change(periods, fill_method=..., limit=...)`.
/// `fill_method=None` preserves pandas 2.2 default behavior (no fill).
/// `"ffill"` / `"pad"` forward-fill missing values first, while
/// `"bfill"` / `"backfill"` backward-fill first. `limit` caps
/// consecutive fills and is ignored when `fill_method` is `None`.
pub fn pct_change_with_fill(
&self,
periods: i64,
fill_method: Option<&str>,
limit: Option<usize>,
) -> Result<Self, ColumnError> {
let filled = match fill_method {
None => self.clone(),
Some(method) => match method {
"ffill" | "pad" => self.ffill(limit)?,
"bfill" | "backfill" => self.bfill(limit)?,
other => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: other.to_string(),
dtype: self.dtype,
}));
}
},
};
filled.pct_change(periods)
}
/// Summary descriptive statistics.
///
/// Matches `pd.Series.describe()` for numeric columns: returns the
/// seven-value tuple (count, mean, std, min, q25, q50, q75, max)
/// as a `Vec<(&'static str, Scalar)>` in pandas order. Non-numeric
/// columns return TypeError. Empty or fully-missing columns
/// produce Null(NaN) for the moment-based stats and Int64(0) for
/// count.
pub fn describe(&self) -> Result<Vec<(&'static str, Scalar)>, ColumnError> {
if !matches!(
self.dtype,
DType::Int64 | DType::Float64 | DType::Timedelta64
) {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{:?}", self.dtype),
dtype: self.dtype,
}));
}
let count = Scalar::Int64(self.count() as i64);
let mean = self.mean();
let std = {
// Typed present-collect (Float64/Int64, all-valid or nullable): gather the
// present values off the raw slice + validity instead of materializing the
// Vec<Scalar> — the ONLY Scalar materialization left in describe (count/
// mean/quantile/min/max are all typed), so this lets describe() run without
// ever building the Scalar Vec. SAFE (missing-FILTERED, unlike trapz): the
// generic filter drops any missing/NaN, so present == validity-set AND
// non-NaN (Float64, ±inf kept) / validity-set (Int64) — the exact set
// `!is_missing() → to_f64().ok()` yields, in the same 0..n order, so the
// two-pass mean/ss/std below is bit-identical. Timedelta64 + exotic
// backings fall to the generic collect (dtype gate / accessor returns None).
let nums: Vec<f64> = if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
data.iter()
.enumerate()
.filter_map(|(i, &x)| (validity.get(i) && !x.is_nan()).then_some(x))
.collect()
} else if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
data.iter()
.enumerate()
.filter_map(|(i, &v)| validity.get(i).then_some(v as f64))
.collect()
} else {
self.values
.iter()
.filter(|v| !v.is_missing())
.filter_map(|v| v.to_f64().ok())
.collect()
};
if nums.len() < 2 {
Scalar::Null(NullKind::NaN)
} else {
let mu = nums.iter().sum::<f64>() / nums.len() as f64;
let ss: f64 = nums.iter().map(|x| (x - mu).powi(2)).sum();
Scalar::Float64((ss / (nums.len() as f64 - 1.0)).sqrt())
}
};
let q25 = self.quantile(0.25);
let q50 = self.quantile(0.5);
let q75 = self.quantile(0.75);
let min = self.min();
let max = self.max();
Ok(vec![
("count", count),
("mean", mean),
("std", std),
("min", min),
("25%", q25),
("50%", q50),
("75%", q75),
("max", max),
])
}
/// Combine two columns element-wise via `func`, using `fill` where
/// either input is missing.
///
/// Matches `pd.Series.combine(other, func, fill_value=...)`. Result
/// length is the min of the two inputs (pandas aligns by position
/// when inputs are the same length; longer inputs are truncated).
/// Length mismatch returns `LengthMismatch`.
pub fn combine<F>(
&self,
other: &Self,
mut func: F,
fill: Option<Scalar>,
) -> Result<Self, ColumnError>
where
F: FnMut(&Scalar, &Scalar) -> Scalar,
{
if self.values.len() != other.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: other.values.len(),
});
}
let out: Vec<Scalar> = self
.values
.iter()
.zip(other.values.iter())
.map(|(a, b)| {
let a_miss = a.is_missing();
let b_miss = b.is_missing();
match (a_miss || b_miss, fill.as_ref()) {
// pandas fill_value=None: propagate null, do not invoke func.
(true, None) => Scalar::Null(NullKind::NaN),
(_, fill_opt) => {
let default = fill_opt.unwrap_or(a);
let left = if a_miss { default } else { a };
let right = if b_miss { fill_opt.unwrap_or(b) } else { b };
func(left, right)
}
}
})
.collect();
let inferred = infer_dtype(&out).unwrap_or(self.dtype);
Self::new(inferred, out)
}
/// Numeric-only `map` that converts each non-missing value to f64,
/// applies `func`, and collects the result.
///
/// Matches the common pattern `pd.Series.apply(lambda x: f(x))`
/// for numeric-only transforms. Missing values pass through as
/// Null(NaN) without invoking `func`. Non-numeric inputs return a
/// type error on the first failing element. Result dtype is
/// Float64.
pub fn apply_float<F>(&self, mut func: F) -> Result<Self, ColumnError>
where
F: FnMut(f64) -> f64,
{
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Null(NullKind::NaN));
continue;
}
match v.to_f64() {
Ok(x) => {
let y = func(x);
if y.is_nan() {
out.push(Scalar::Null(NullKind::NaN));
} else {
out.push(Scalar::Float64(y));
}
}
Err(err) => return Err(ColumnError::Type(err)),
}
}
Self::new(DType::Float64, out)
}
/// Bin non-missing values into `bins` equal-width buckets covering
/// `[min, max]` and return the count per bin.
///
/// Matches the `bins=n` histogram path behind `pd.Series.hist` (or
/// `numpy.histogram(bins=n)[0]`). Bucket boundaries are inclusive on
/// the low side except for the final bucket, which is inclusive on
/// both sides. Empty columns / bins=0 yield an empty Vec.
#[must_use]
pub fn hist_counts(&self, bins: usize) -> Vec<usize> {
if bins == 0 {
return Vec::new();
}
// Typed present-collect (Float64/Int64, all-valid or nullable): gather present
// values off the raw slice + validity, skipping the Vec<Scalar> materialization
// + per-Scalar to_f64 (the ONLY Scalar materialization in hist_counts). SAFE
// (missing-FILTERED, like describe's std, unlike trapz): the generic chain
// `!is_missing() → to_f64().ok() → !is_nan()` drops every missing/NaN, so
// present == validity-set AND non-NaN (Float64, ±inf kept) / validity-set
// (Int64) in the same 0..n order — identical nums ⇒ identical bucketing/counts.
// Timedelta64 + exotic backings fall to the generic collect.
let nums: Vec<f64> = if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
data.iter()
.enumerate()
.filter_map(|(i, &x)| (validity.get(i) && !x.is_nan()).then_some(x))
.collect()
} else if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
data.iter()
.enumerate()
.filter_map(|(i, &v)| validity.get(i).then_some(v as f64))
.collect()
} else {
self.values
.iter()
.filter(|v| !v.is_missing())
.filter_map(|v| v.to_f64().ok())
.filter(|f| !f.is_nan())
.collect()
};
if nums.is_empty() {
return vec![0; bins];
}
let (min, max) = nums
.iter()
.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| {
(lo.min(x), hi.max(x))
});
if (max - min).abs() < f64::EPSILON {
// All values collapse into the first bin.
let mut counts = vec![0; bins];
counts[0] = nums.len();
return counts;
}
let width = (max - min) / bins as f64;
let mut counts = vec![0usize; bins];
for x in &nums {
let mut idx = ((x - min) / width) as usize;
if idx >= bins {
idx = bins - 1;
}
counts[idx] += 1;
}
counts
}
/// Position of the smallest non-missing value, or None when every
/// value is missing.
///
/// Matches `pd.Series.argmin()` (skipna=True). Ties resolve to the
/// first position seen.
#[must_use]
pub fn argmin(&self) -> Option<usize> {
// Typed Timedelta64 fast path: `nanargmin` compares Timedelta by EXACT i64
// ns (its dedicated `is_timedelta_input` arm), so scan the raw `&[i64]`
// instead of materializing a `Vec<Scalar::Timedelta64>`. Gate all-valid +
// no-NaT (`nanargmin` SKIPS missing; for an all-valid column the original-
// array index equals the slice index, and the `i64::MIN` NaT sentinel is
// reserved so it never appears — the belt-and-suspenders `!contains` keeps
// a malformed column on the exact `nanargmin` path). Strict `<` keeps the
// FIRST position on a tie, exactly as `nanargmin`. Empty ⇒ `None`.
if self.validity.all()
&& let Some(data) = self.as_timedelta64_slice()
&& !data.contains(&i64::MIN)
{
let mut best: Option<(usize, i64)> = None;
for (i, &ns) in data.iter().enumerate() {
match best {
None => best = Some((i, ns)),
Some((_, cur)) if ns < cur => best = Some((i, ns)),
_ => {}
}
}
return best.map(|(i, _)| i);
}
// Typed Float64/Int64 (all-valid + nullable): scan the raw slice + validity
// instead of nanargmin materializing the Vec<Scalar>. Bit-identical (f64
// compare, strict `<` first-on-tie, skip missing/NaN).
if let Some(data) = self.as_f64_slice() {
return argextreme_nullable_f64(data, None, false);
}
if let Some(data) = self.as_i64_slice() {
return argextreme_nullable_i64(data, None, false);
}
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
return argextreme_nullable_f64(data, Some(validity), false);
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
return argextreme_nullable_i64(data, Some(validity), false);
}
nanargmin(&self.values)
}
/// Alias for [`argmin`](Self::argmin), matching `pd.Series.idxmin()`
/// for positional indices.
#[must_use]
pub fn idxmin(&self) -> Option<usize> {
self.argmin()
}
/// Position of the largest non-missing value, or None when every
/// value is missing.
///
/// Matches `pd.Series.argmax()`.
#[must_use]
pub fn argmax(&self) -> Option<usize> {
// Typed Timedelta64 fast path (symmetric to `argmin`): scan the raw `&[i64]`
// ns and track the max via strict `>` (keeps the FIRST position on a tie
// exactly as `nanargmax`) instead of materializing `Vec<Scalar::Timedelta64>`.
// All-valid + no-NaT gate; empty ⇒ `None`.
if self.validity.all()
&& let Some(data) = self.as_timedelta64_slice()
&& !data.contains(&i64::MIN)
{
let mut best: Option<(usize, i64)> = None;
for (i, &ns) in data.iter().enumerate() {
match best {
None => best = Some((i, ns)),
Some((_, cur)) if ns > cur => best = Some((i, ns)),
_ => {}
}
}
return best.map(|(i, _)| i);
}
// Typed Float64/Int64 (all-valid + nullable), symmetric to argmin: strict
// `>` keeps the FIRST position on a tie, exactly as nanargmax.
if let Some(data) = self.as_f64_slice() {
return argextreme_nullable_f64(data, None, true);
}
if let Some(data) = self.as_i64_slice() {
return argextreme_nullable_i64(data, None, true);
}
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
return argextreme_nullable_f64(data, Some(validity), true);
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
return argextreme_nullable_i64(data, Some(validity), true);
}
nanargmax(&self.values)
}
/// Alias for [`argmax`](Self::argmax), matching `pd.Series.idxmax()`
/// for positional indices.
#[must_use]
pub fn idxmax(&self) -> Option<usize> {
self.argmax()
}
/// Alias for argmin, matching np.nanargmin.
#[must_use]
pub fn nanargmin(&self) -> Option<usize> {
self.argmin()
}
/// Alias for argmax, matching np.nanargmax.
#[must_use]
pub fn nanargmax(&self) -> Option<usize> {
self.argmax()
}
/// Whether non-missing values are non-decreasing.
///
/// Matches `pd.Series.is_monotonic_increasing`. An empty column or
/// a column with a single non-missing value returns true. Missing
/// values are skipped when comparing neighbors.
#[must_use]
pub fn is_monotonic_increasing(&self) -> bool {
is_monotonic_in_direction(&self.values, true)
}
/// Whether non-missing values are non-increasing.
///
/// Matches `pd.Series.is_monotonic_decreasing`.
#[must_use]
pub fn is_monotonic_decreasing(&self) -> bool {
is_monotonic_in_direction(&self.values, false)
}
/// Combine two columns, taking `self` where present and `other`
/// otherwise.
///
/// Matches `pd.Series.combine_first(other)`. For each aligned
/// position, the result is `self` when `self` is non-missing, else
/// `other`. Length mismatch returns `LengthMismatch`. Result
/// dtype follows `self`.
pub fn combine_first(&self, other: &Self) -> Result<Self, ColumnError> {
if self.values.len() != other.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: other.values.len(),
});
}
let out: Vec<Scalar> = self
.values
.iter()
.zip(other.values.iter())
.map(|(a, b)| if a.is_missing() { b.clone() } else { a.clone() })
.collect();
Self::new(self.dtype, out)
}
/// Clip values below `lower`, leaving the upper bound free.
///
/// Matches `pd.Series.clip(lower=...)`. Thin wrapper over
/// `clip(Some(lower), None)` that preserves the shortcut reading
/// convention of pandas.
pub fn clip_lower(&self, lower: f64) -> Result<Self, ColumnError> {
self.clip(Some(lower), None)
}
/// Clip values above `upper`, leaving the lower bound free.
///
/// Matches `pd.Series.clip(upper=...)`.
pub fn clip_upper(&self, upper: f64) -> Result<Self, ColumnError> {
self.clip(None, Some(upper))
}
/// Remove duplicated values, keeping the first occurrence.
///
/// Matches `pd.Series.drop_duplicates(keep='first')`.
pub fn drop_duplicates(&self) -> Result<Self, ColumnError> {
self.drop_duplicates_keep("first")
}
/// Remove duplicated values with explicit pandas `keep=` semantics.
///
/// Supported policies are `"first"`, `"last"`, and `"false"` /
/// `"none"` for pandas `keep=False`.
pub fn drop_duplicates_keep(&self, keep: &str) -> Result<Self, ColumnError> {
let dup = self.duplicated_keep(keep)?;
let mut out = Vec::with_capacity(self.values.len());
for (v, keep_flag) in self.values.iter().zip(dup.values.iter()) {
if matches!(keep_flag, Scalar::Bool(false)) {
out.push(v.clone());
}
}
Self::new(self.dtype, out)
}
/// Element-wise comparison against `other`, emitting a 2-column
/// report of differences.
///
/// Matches `pd.Series.compare(other)` — returns two Columns
/// `(self_values, other_values)` containing only the positions
/// where the two differ. Missing entries compare equal to each
/// other. Length-mismatched inputs return `LengthMismatch`.
pub fn compare(&self, other: &Self) -> Result<(Self, Self), ColumnError> {
if self.values.len() != other.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: other.values.len(),
});
}
let mut left = Vec::new();
let mut right = Vec::new();
for (a, b) in self.values.iter().zip(other.values.iter()) {
let equal = match (a.is_missing(), b.is_missing()) {
(true, true) => true,
(true, false) | (false, true) => false,
(false, false) => a.semantic_eq(b),
};
if !equal {
left.push(a.clone());
right.push(b.clone());
}
}
Ok((Self::new(self.dtype, left)?, Self::new(other.dtype, right)?))
}
/// Apply a unary function over each value.
///
/// Matches `pd.Series.map(func)`. Missing values are passed to the
/// user function (callers can decide whether to propagate NaN);
/// result dtype is inferred via `infer_dtype` over the outputs,
/// falling back to `self.dtype` when inference fails (e.g. empty
/// or all-null output).
pub fn map<F>(&self, mut func: F) -> Result<Self, ColumnError>
where
F: FnMut(&Scalar) -> Scalar,
{
let out: Vec<Scalar> = self.values.iter().map(&mut func).collect();
let target = infer_dtype(&out).unwrap_or(self.dtype);
Self::new(target, out)
}
/// Shared linear-interpolation fill used by the typed Float64/Int64 fast paths.
/// `present(i)` returns the present value at index `i` (None ⇒ missing), matching
/// the generic path's `!is_missing() → to_f64() → !is_nan()` filter. Interior gaps
/// between the first and last present are linearly interpolated; trailing nulls are
/// forward-filled with the last present value; leading nulls stay missing. Output
/// is a nullable Float64 column (leading nulls ⇒ Null(NaN)).
fn interpolate_linear_from_present(len: usize, present: impl Fn(usize) -> Option<f64>) -> Self {
let mut out = vec![0.0_f64; len];
let mut valid = vec![false; len];
for (i, slot) in out.iter_mut().enumerate() {
if let Some(v) = present(i) {
*slot = v;
valid[i] = true;
}
}
let first = valid.iter().position(|&b| b);
let last = valid.iter().rposition(|&b| b);
if let (Some(start), Some(end)) = (first, last) {
let mut i = start;
while i < end {
if valid[i] {
i += 1;
continue;
}
let gap_start = i;
while i < end && !valid[i] {
i += 1;
}
let before = out[gap_start - 1];
let after = out[i];
let span = (i - gap_start + 1) as f64;
for (k, j) in (gap_start..i).enumerate() {
let step = (k + 1) as f64;
out[j] = before + (after - before) * (step / span);
valid[j] = true;
}
}
let last_valid = out[end];
for j in (end + 1)..len {
out[j] = last_valid;
valid[j] = true;
}
}
let mut vmask = ValidityMask::all_valid(len);
for (j, &ok) in valid.iter().enumerate() {
if !ok {
vmask.set(j, false);
}
}
Self::from_f64_values_with_validity(out, vmask)
}
/// Linearly interpolate missing numeric values.
///
/// Matches `pd.Series.interpolate(method='linear')` with the
/// default `limit_direction='forward'`: interior missing runs are
/// linearly interpolated, LEADING nulls stay null (forward fill
/// cannot reach them), and TRAILING nulls are forward-filled with
/// the last valid value (pandas does not extrapolate). Non-numeric
/// columns return a type error. Result dtype is always Float64.
pub fn interpolate_linear(&self) -> Result<Self, ColumnError> {
let len = self.values.len();
// Typed Float64/Int64 fast path: source the present values from the contiguous
// buffer + validity (no per-element Scalar/ to_f64 materialization), run the
// identical interior-gap + trailing-ffill fill into an f64 buffer, and MOVE it
// out with a validity mask (leading nulls stay missing). Bit-identical to the
// Scalar path below: present == validity-set AND non-NaN (Float64) / validity-
// set (Int64, `v as f64` == the generic to_f64), a filled/present slot →
// Float64(value), a remaining (leading) null → Null(NaN); same fill arithmetic.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
return Ok(Self::interpolate_linear_from_present(len, |i| {
(validity.get(i) && !data[i].is_nan()).then_some(data[i])
}));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
return Ok(Self::interpolate_linear_from_present(len, |i| {
validity.get(i).then_some(data[i] as f64)
}));
}
// Convert to f64 once; missing → None.
let mut floats: Vec<Option<f64>> = Vec::with_capacity(len);
for v in &self.values {
if v.is_missing() {
floats.push(None);
continue;
}
match v.to_f64() {
Ok(x) if !x.is_nan() => floats.push(Some(x)),
Ok(_) => floats.push(None),
Err(err) => return Err(ColumnError::Type(err)),
}
}
// Walk interior gaps between the first and last non-null.
let first = floats.iter().position(Option::is_some);
let last = floats.iter().rposition(Option::is_some);
if let (Some(start), Some(end)) = (first, last) {
let mut i = start;
while i < end {
if floats[i].is_some() {
i += 1;
continue;
}
let gap_start = i;
while i < end && floats[i].is_none() {
i += 1;
}
let before = floats[gap_start - 1].expect("anchor");
let after = floats[i].expect("anchor");
let span = (i - gap_start + 1) as f64;
for (k, j) in (gap_start..i).enumerate() {
let step = (k + 1) as f64;
floats[j] = Some(before + (after - before) * (step / span));
}
}
// Trailing nulls (after the last valid value) are forward-filled
// with that value — pandas' default limit_direction='forward' carries
// it forward rather than extrapolating. Leading nulls (before `start`)
// are intentionally left null. (br-frankenpandas-8ic7c)
let last_valid = floats[end].expect("last valid anchor");
for slot in floats.iter_mut().skip(end + 1) {
*slot = Some(last_valid);
}
}
let out: Vec<Scalar> = floats
.into_iter()
.map(|opt| match opt {
Some(x) => Scalar::Float64(x),
None => Scalar::Null(NullKind::NaN),
})
.collect();
Self::new(DType::Float64, out)
}
/// Alias for [`interpolate_linear`](Self::interpolate_linear), matching
/// the default `pd.Series.interpolate()` behavior.
pub fn interpolate(&self) -> Result<Self, ColumnError> {
self.interpolate_linear()
}
/// Linear-interpolation quantile at `q ∈ [0.0, 1.0]`.
///
/// Matches `pd.Series.quantile(q, interpolation='linear')`.
/// Missing values are skipped (skipna=True). Returns
/// `Null(NaN)` for empty columns or `q` outside `[0.0, 1.0]`.
/// Linear-interpolated quantile at `q` over an all-valid `f64` buffer already
/// extracted from the column: q-range guard (`Null(NaN)` outside `[0,1]`),
/// empty ⇒ `Null(NaN)`, `n==1` shortcut, then `select_nth_unstable_by(lo, ..)`
/// plus lo/hi linear interpolation (the `hi`-th order statistic is the MIN of the
/// right partition). Shared by the Float64 and Int64 typed fast paths so both
/// run the SAME computation `nanquantile`'s numeric arm performs after
/// `collect_finite`; `select_nth_unstable_by` is deterministic.
fn quantile_from_f64_vec(mut nums: Vec<f64>, q: f64) -> Scalar {
if !(0.0..=1.0).contains(&q) {
return Scalar::Null(NullKind::NaN);
}
if nums.is_empty() {
return Scalar::Null(NullKind::NaN);
}
let n = nums.len();
if n == 1 {
return Scalar::Float64(nums[0]);
}
let pos = q * (n - 1) as f64;
let lo = pos.floor() as usize;
let hi = pos.ceil() as usize;
let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
let (_left, lo_ref, right) = nums.select_nth_unstable_by(lo, cmp);
let lo_val = *lo_ref;
if lo == hi {
return Scalar::Float64(lo_val);
}
let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
let weight = pos - lo as f64;
Scalar::Float64(lo_val + (hi_val - lo_val) * weight)
}
#[must_use]
pub fn quantile(&self, q: f64) -> Scalar {
// Typed Float64 fast path (sibling of `median`): linear-interpolated order
// statistic straight over the contiguous f64 buffer instead of
// materializing `Vec<Scalar>` then `collect_finite`'s per-Scalar `to_f64`.
// `as_f64_slice` is all-valid, so `collect_finite` (drops only MISSING,
// keeps every `to_f64`-able value incl. NaN/inf) equals `data.to_vec()`.
if let Some(data) = self.as_f64_slice() {
return Self::quantile_from_f64_vec(data.to_vec(), q);
}
// Typed Int64 fast path (sibling of Int64 `median`): `nanquantile`'s
// numeric arm maps each Scalar::Int64 through `collect_finite`'s `to_f64`
// (`v as f64`, exact for |v| < 2^53 and identically lossy above it) then
// runs the SAME select/interpolate. An all-valid i64 buffer converted the
// same way is bit-identical. Datetime64/Timedelta64 are excluded
// (`as_i64_slice` gates dtype==Int64) so `nanquantile`'s dtype-preserving
// Timedelta64 arm still runs for those.
if let Some(data) = self.as_i64_slice() {
return Self::quantile_from_f64_vec(data.iter().map(|&v| v as f64).collect(), q);
}
// Nullable Float64/Int64 (sibling of nullable `median`): collect the PRESENT
// values (validity-set AND non-NaN for Float64 — exactly collect_finite's
// drop-missing; validity bit for Int64) into an f64 Vec and run the SAME
// quantile_from_f64_vec, skipping nanquantile's Vec<Scalar> materialization +
// per-Scalar to_f64. Bit-identical: quantile is order-independent (select_nth),
// so the present multiset alone determines it; empty present ⇒
// quantile_from_f64_vec's empty ⇒ Null(NaN), matching nanquantile. The
// dtype gates leave Timedelta64's dtype-preserving nanquantile arm untouched.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let present: Vec<f64> = data
.iter()
.enumerate()
.filter_map(|(i, &x)| (validity.get(i) && !x.is_nan()).then_some(x))
.collect();
return Self::quantile_from_f64_vec(present, q);
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let present: Vec<f64> = data
.iter()
.enumerate()
.filter_map(|(i, &v)| validity.get(i).then_some(v as f64))
.collect();
return Self::quantile_from_f64_vec(present, q);
}
nanquantile(&self.values, q)
}
/// Percentile of non-missing values.
///
/// Matches np.percentile(). Takes percentile p in [0, 100].
#[must_use]
pub fn percentile(&self, p: f64) -> Scalar {
self.quantile(p / 100.0)
}
/// Alias for quantile, matching np.nanquantile.
#[must_use]
pub fn nanquantile(&self, q: f64) -> Scalar {
self.quantile(q)
}
/// Alias for percentile, matching np.nanpercentile.
#[must_use]
pub fn nanpercentile(&self, p: f64) -> Scalar {
self.percentile(p)
}
/// Most frequent non-missing values, ascending-sorted.
///
/// Matches `pd.Series.mode()`. Ties are all returned; missing
/// values are ignored. For empty or all-missing columns the
/// result is an empty same-dtype column.
pub fn mode(&self) -> Result<Self, ColumnError> {
// Counting-sort fast path: an all-valid, bounded-range Int64 column
// tallies in O(n) via a dense direct-address histogram instead of the
// SipHash `HashMap` below, and emits the winners with NO sort. Walking
// the slots in ascending value order (slot s ↔ value `min + s`) yields
// the most-frequent values already ascending — identical to the
// `HashMap` path's `winners.sort_by(compare_scalars_na_last(.., true))`,
// which orders Int64 by exact `i64::cmp`. `as_i64_slice` is `Some` only
// for a fully-valid Int64 column, so there are no missing values to skip
// (matching `key_of`'s `None`-on-missing), and an empty column makes
// `i64_direct_address_range` return `None` → the `HashMap` path returns
// the empty same-dtype column exactly as before.
if let Some(data) = self.as_i64_slice() {
if let Some((min, range)) = i64_direct_address_range(data) {
let mut count = vec![0i64; range];
for &v in data {
count[(v as i128 - min as i128) as usize] += 1;
}
let max_count = count.iter().copied().max().unwrap_or(0);
let mut winners = Vec::new();
for (s, &c) in count.iter().enumerate() {
if c == max_count {
winners.push(Scalar::Int64(min + s as i64));
}
}
return Self::new(self.dtype, winners);
}
// Wide/sparse all-valid Int64: out of dense-histogram range, but the
// raw &[i64] avoids Scalar materialization — tally+argmax via the
// open-addressing map (breaks the FxHashMap khash floor; mode is
// hash-bound with a tiny output). Bit-identical: winners are the
// max-count values, ascending, same as the generic path.
if !data.is_empty() {
return Ok(Self::from_i64_values_owned(mode_i64_wide(data)));
}
}
// All-valid (NaN-free) Float64: tally+argmax via open-addressing over
// normalized float bits (first-seen original kept for output, -0.0
// preserved). Avoids the FxHashMap<FloatBits> + Scalar floor.
if let Some(data) = self.as_f64_slice()
&& !data.is_empty()
{
return Ok(Self::from_f64_values(mode_f64_wide(data)));
}
// Datetime64 / Timedelta64 (i64-ns-backed): an all-valid, no-NaT column
// reuses the Int64 wide mode helper over the raw ns, then re-wraps the
// winners as the temporal dtype. Bit-identical to the generic `Key` path:
// a non-NaT temporal value's key is its ns, `mode_i64_wide` returns the
// max-count ns sorted ascending, and `compare_scalars_na_last(.., true)`
// orders Datetime64/Timedelta64 by exact `i64::cmp` on the ns -- so the
// winner set and order match. The no-NaT gate is REQUIRED: `mode_i64_wide`
// treats `i64::MIN` as a countable value (its EMPTY sentinel is handled via
// `sentinel_cnt`), but the generic `key_of` SKIPS NaT as missing, so a
// NaT-bearing column must fall through. Mirrors `unique`/`value_counts`.
if !self.has_nulls()
&& let Some(data) = self
.as_datetime64_slice()
.or_else(|| self.as_timedelta64_slice())
&& !data.contains(&i64::MIN)
{
let winners = mode_i64_wide(data);
let len = winners.len();
return Ok(if self.dtype == DType::Timedelta64 {
Self::from_timedelta64_values_with_validity(winners, ValidityMask::all_valid(len))
} else {
Self::from_datetime64_values(winners)
});
}
// Contiguous-Utf8 fast path (sibling of `unique`/`value_counts`/`nunique`'s
// byte-span dedup): the generic tally below iterates `&self.values`,
// forcing `as_slice()` to materialize a `Vec<Scalar::Utf8>` -- one heap
// `String` per row -- then keys each by `Key::Utf8(&str)`. Tally the byte
// spans directly via `FxHashMap<&[u8], usize>` (byte-equality is exactly
// `&str`-equality for valid UTF-8) with ZERO per-row `String` alloc,
// collect the max-count winners, and rebuild a contiguous output.
// `as_utf8_contiguous` matches only an all-valid backing, so nothing is
// skipped as missing. Bit-identical: the winners are the same set of
// max-count strings, and sorting the distinct winner spans by
// `<[u8]>::cmp` ascending equals the generic
// `winners.sort_by(compare_scalars_na_last(.., true))` for Utf8
// (`str::cmp` is byte-lexicographic); the empty column returns the same
// empty same-dtype column.
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
let mut counts: FxHashMap<&[u8], usize> = FxHashMap::default();
for w in offsets.windows(2) {
*counts.entry(&bytes[w[0]..w[1]]).or_insert(0) += 1;
}
if counts.is_empty() {
return Self::new(self.dtype, Vec::new());
}
let max_count = counts.values().copied().max().unwrap_or(0);
let mut winners: Vec<&[u8]> = counts
.iter()
.filter_map(|(span, c)| if *c == max_count { Some(*span) } else { None })
.collect();
// Distinct HashMap keys => no ties; unstable sort matches the generic
// ascending byte-lexicographic winner order exactly.
winners.sort_unstable();
let mut out_bytes: Vec<u8> = Vec::new();
let mut out_offsets: Vec<usize> = Vec::with_capacity(winners.len() + 1);
out_offsets.push(0);
for span in &winners {
out_bytes.extend_from_slice(span);
out_offsets.push(out_bytes.len());
}
return Ok(Self::from_utf8_contiguous(out_bytes, out_offsets));
}
// Nullable contiguous-Utf8 fast path (COLD cache): the all-valid arm above gates
// on `as_utf8_contiguous` (validity.all()), so a `LazyNullableUtf8` column — a
// string column WITH missing rows — fell to the generic `Key`-tally below, which
// materializes a `Vec<Scalar::Utf8>` (one heap `String` per row). mode DROPS nulls
// (`key_of` is `None` on missing), so tally ONLY the present byte spans
// (validity-set) via `FxHashMap<&[u8], usize>`, collect the max-count winners, sort
// ascending, and rebuild a contiguous output — the winners are all present strings,
// so the output is all-valid exactly like the generic path's. Bit-identical: same
// present-only tally (byte-eq == `Key::Utf8` eq), same max-count winner set, and
// `<[u8]>::sort_unstable` == `compare_scalars_na_last(.., true)` for distinct Utf8
// winners (str::cmp is byte-lexicographic; distinct HashMap keys ⇒ no ties). An
// all-missing / empty column ⇒ empty counts ⇒ empty same-dtype column, matching.
// Unlike the Int64/Float64 nullable mode below (their generic path reads raw
// slices, nothing to bypass), the Utf8 generic path pays the String
// materialization, so this wins on a cold column. Gated on a COLD `values` cache: a
// warm/already-materialized column defers to the generic `Key` tally — no
// regression from the per-row `validity.get`.
if let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
values,
} = &self.values
&& values.get().is_none()
{
let mut counts: FxHashMap<&[u8], usize> = FxHashMap::default();
for (idx, w) in offsets.windows(2).enumerate() {
if validity.get(idx) {
*counts.entry(&bytes[w[0]..w[1]]).or_insert(0) += 1;
}
}
if counts.is_empty() {
return Self::new(self.dtype, Vec::new());
}
let max_count = counts.values().copied().max().unwrap_or(0);
let mut winners: Vec<&[u8]> = counts
.iter()
.filter_map(|(span, c)| if *c == max_count { Some(*span) } else { None })
.collect();
winners.sort_unstable();
let mut out_bytes: Vec<u8> = Vec::new();
let mut out_offsets: Vec<usize> = Vec::with_capacity(winners.len() + 1);
out_offsets.push(0);
for span in &winners {
out_bytes.extend_from_slice(span);
out_offsets.push(out_bytes.len());
}
return Ok(Self::from_utf8_contiguous(out_bytes, out_offsets));
}
// NEGATIVE LEDGER (do not re-attempt without a new idea): rerouting a
// nullable Int64/Float64 mode through the typed present-subset tally does
// NOT beat the generic FxHashMap<Key> path here.
// - Int64 dense: gathering present into a raw i64 Vec (an O(n) 32-MB alloc +
// copy) then a second histogram pass loses to FxHash's SINGLE pass into a
// tiny L1-resident map — measured 0.44x at ~2000 distinct/5M (fair FxHash
// control), and low cardinality is where dense should win MOST, so higher
// cardinality only widens the gap. An inline no-alloc 2-pass variant would
// still add a validity-gated pass over the generic 1-pass, unlikely to win.
// - Float64: mode_f64_wide's open-addressing degrades ~45x on low-cardinality
// float-of-integer data (a latent all-valid-path issue too — a real bug
// worth fixing SEPARATELY, which would then also enable a nullable arm).
// The generic mode path (Fx hashing, key_of skips missing, tiny winner set)
// is already the floor for these dtypes.
#[derive(Hash, PartialEq, Eq)]
enum Key<'a> {
Bool(bool),
Int64(i64),
FloatBits(u64),
Utf8(&'a str),
Timedelta64(i64),
Datetime64(i64),
Period(i64),
Interval(u64, u64, IntervalClosed),
}
fn key_of(v: &Scalar) -> Option<Key<'_>> {
if v.is_missing() {
return None;
}
Some(match v {
Scalar::Bool(b) => Key::Bool(*b),
Scalar::Int64(i) => Key::Int64(*i),
Scalar::Float64(f) => {
let norm = if *f == 0.0 { 0.0 } else { *f };
Key::FloatBits(norm.to_bits())
}
Scalar::Utf8(s) => Key::Utf8(s.as_str()),
Scalar::Timedelta64(v) => Key::Timedelta64(*v),
Scalar::Datetime64(v) => Key::Datetime64(*v),
Scalar::Period(p) => Key::Period(p.ordinal),
Scalar::Interval(v) => {
let (left, right, closed) = interval_key(v);
Key::Interval(left, right, closed)
}
Scalar::Null(_) => return None,
})
}
let mut counts: FxHashMap<Key<'_>, (usize, &Scalar)> = FxHashMap::default();
for v in &self.values {
if let Some(k) = key_of(v) {
counts
.entry(k)
.and_modify(|entry| entry.0 += 1)
.or_insert((1, v));
}
}
if counts.is_empty() {
return Self::new(self.dtype, Vec::new());
}
let max_count = counts.values().map(|(c, _)| *c).max().unwrap_or(0);
let mut winners: Vec<Scalar> = counts
.values()
.filter_map(|(c, v)| {
if *c == max_count {
Some((*v).clone())
} else {
None
}
})
.collect();
winners.sort_by(|a, b| compare_scalars_na_last(a, b, true));
Self::new(self.dtype, winners)
}
/// Approximate memory footprint in bytes.
///
/// Matches `pd.Series.memory_usage(deep=...)`. When `deep` is true
/// and the column contains Utf8 values, each string's byte length
/// is counted; otherwise a fixed per-element width is used
/// (8 bytes for numeric/timedelta, 1 for Bool, pointer-sized for
/// Utf8, 0 for Null). The ValidityMask is counted separately.
#[must_use]
pub fn memory_usage(&self, deep: bool) -> usize {
let element_bytes = match self.dtype {
DType::Bool => 1,
DType::Int64 | DType::Float64 | DType::Timedelta64 => 8,
DType::Utf8 => std::mem::size_of::<usize>(),
_ => 0,
};
let base = element_bytes * self.values.len();
let deep_extra = if deep && self.dtype == DType::Utf8 {
self.values
.iter()
.map(|v| match v {
Scalar::Utf8(s) => s.len(),
_ => 0,
})
.sum::<usize>()
} else {
0
};
// One bit per element, rounded up to whole bytes.
let validity_bytes = self.values.len().div_ceil(8);
base + deep_extra + validity_bytes
}
/// Approximate value-buffer footprint, matching `pd.Series.nbytes`.
#[must_use]
pub fn nbytes(&self) -> usize {
self.memory_usage(false)
}
/// Return the size in bytes of a single element.
///
/// Matches `pd.Series.dtype.itemsize`. Returns 8 for Int64/Float64/Datetime64/Timedelta64,
/// 1 for Bool, and an estimate for variable-length types.
#[must_use]
pub fn itemsize(&self) -> usize {
match self.dtype() {
DType::Bool | DType::BoolNullable => 1,
DType::Int64
| DType::Int64Nullable
| DType::Float64
| DType::Datetime64
| DType::Timedelta64
| DType::Period => 8,
DType::Utf8 => {
if self.values.is_empty() {
0
} else {
self.memory_usage(true) / self.values.len()
}
}
DType::Null | DType::Categorical | DType::Interval | DType::Sparse => 8,
}
}
/// Element-wise equality into a Bool column.
///
/// Matches `pd.Series.eq(other)`. Both inputs must have the same
/// length. Missing-on-either-side positions produce `false`
/// (pandas semantics: NaN != anything, including NaN).
pub fn equals(&self, other: &Self) -> Result<Self, ColumnError> {
if self.values.len() != other.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: other.values.len(),
});
}
let out: Vec<Scalar> = self
.values
.iter()
.zip(other.values.iter())
.map(|(a, b)| {
if a.is_missing() || b.is_missing() {
Scalar::Bool(false)
} else {
Scalar::Bool(a.semantic_eq(b))
}
})
.collect();
Self::new(DType::Bool, out)
}
/// Scalar dot product against another column.
///
/// Matches `pd.Series.dot(other)` for numeric columns. Missing
/// entries on either side contribute zero (consistent with
/// fp-types nan-aware sums). Length mismatch returns
/// `LengthMismatch`; non-numeric inputs return a type error on
/// the first offending value.
pub fn dot(&self, other: &Self) -> Result<f64, ColumnError> {
if self.values.len() != other.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: other.values.len(),
});
}
// Typed pairwise fast path (sibling of weighted_mean/cov/corr): when BOTH
// columns are Float64/Int64 (all-valid or nullable) fold sum += av*bv straight
// off the raw slices via get_present, skipping the Vec<Scalar> materialization
// of BOTH columns + per-Scalar is_missing/to_f64. Bit-identical: get_present ==
// dot's effective present filter — `!is_missing` (drops null AND the NaN that
// the redundant `av.is_nan()||bv.is_nan()` also drops) with to_f64 Ok, KEEPING
// ±inf — so the same pairwise-present products accumulate in the same 0..n
// order. Both typed ⇒ to_f64 never errors, so the `?` Err path is unreachable
// here; the generic loop below still handles mixed/non-numeric dtypes.
if let (Some(sx), Some(sy)) = (self.typed_numeric_values(), other.typed_numeric_values()) {
let n = sx.len().min(sy.len());
let mut sum = 0.0_f64;
for i in 0..n {
if let (Some(av), Some(bv)) = (sx.get_present(i), sy.get_present(i)) {
sum += av * bv;
}
}
return Ok(sum);
}
let mut sum = 0.0_f64;
for (a, b) in self.values.iter().zip(other.values.iter()) {
if a.is_missing() || b.is_missing() {
continue;
}
let av = a.to_f64().map_err(ColumnError::Type)?;
let bv = b.to_f64().map_err(ColumnError::Type)?;
if av.is_nan() || bv.is_nan() {
continue;
}
sum += av * bv;
}
Ok(sum)
}
/// Discrete linear convolution of two 1D sequences.
///
/// Matches np.convolve(a, v, mode). Modes:
/// - "full": output length = len(a) + len(v) - 1
/// - "same": output length = max(len(a), len(v))
/// - "valid": output length = max(len(a), len(v)) - min(len(a), len(v)) + 1
pub fn convolve(&self, kernel: &Self, mode: &str) -> Result<Self, ColumnError> {
let a: Vec<f64> = self
.values
.iter()
.map(|v| v.to_f64().unwrap_or(0.0))
.collect();
let v: Vec<f64> = kernel
.values
.iter()
.map(|v| v.to_f64().unwrap_or(0.0))
.collect();
if a.is_empty() || v.is_empty() {
return Self::new(DType::Float64, vec![]);
}
let full_len = a.len() + v.len() - 1;
let mut full: Vec<f64> = vec![0.0; full_len];
for (i, &ai) in a.iter().enumerate() {
for (j, &vj) in v.iter().enumerate() {
full[i + j] += ai * vj;
}
}
let out: Vec<f64> = match mode {
"full" => full,
"same" => {
let target_len = a.len().max(v.len());
let start = (full_len - target_len) / 2;
full[start..start + target_len].to_vec()
}
"valid" => {
let min_len = a.len().min(v.len());
let valid_len = a.len().max(v.len()) - min_len + 1;
let start = min_len - 1;
full[start..start + valid_len].to_vec()
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("invalid mode '{mode}', expected 'full', 'same', or 'valid'"),
dtype: self.dtype,
}));
}
};
let scalars: Vec<Scalar> = out.into_iter().map(Scalar::Float64).collect();
Self::new(DType::Float64, scalars)
}
/// Cross-correlation of two 1D sequences.
///
/// Matches np.correlate(a, v, mode). This is convolve(a, reverse(v), mode).
pub fn correlate(&self, other: &Self, mode: &str) -> Result<Self, ColumnError> {
let reversed = other.reverse()?;
self.convolve(&reversed, mode)
}
/// Fill missing values in `self` with aligned values from `other`.
///
/// Matches `pd.Series.fillna(other)` when `other` is a Series. Only
/// positions missing in `self` are replaced. Length mismatch
/// returns `LengthMismatch`. Values from `other` are cast into
/// `self.dtype`.
pub fn fillna_with_column(&self, other: &Self) -> Result<Self, ColumnError> {
if self.values.len() != other.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: other.values.len(),
});
}
let out: Vec<Scalar> = self
.values
.iter()
.zip(other.values.iter())
.map(|(v, o)| {
if v.is_missing() {
cast_scalar(o, self.dtype)
} else {
Ok(v.clone())
}
})
.collect::<Result<Vec<_>, _>>()
.map_err(ColumnError::Type)?;
Self::new(self.dtype, out)
}
/// Element-wise quotient and remainder against `divisor`.
///
/// Matches `pd.Series.divmod(other)`: returns
/// `(self // other, self % other)`. Division by zero, missing
/// inputs, or non-numeric values yield `Null(NaN)` in both
/// outputs at that position. Length mismatch returns
/// `LengthMismatch`. Both result columns are Float64.
pub fn divmod(&self, divisor: &Self) -> Result<(Self, Self), ColumnError> {
if self.values.len() != divisor.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: divisor.values.len(),
});
}
let mut quotient = Vec::with_capacity(self.values.len());
let mut remainder = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(divisor.values.iter()) {
if a.is_missing() || b.is_missing() {
quotient.push(Scalar::Null(NullKind::NaN));
remainder.push(Scalar::Null(NullKind::NaN));
continue;
}
let num = match a.to_f64() {
Ok(x) if !x.is_nan() => x,
_ => {
quotient.push(Scalar::Null(NullKind::NaN));
remainder.push(Scalar::Null(NullKind::NaN));
continue;
}
};
let den = match b.to_f64() {
Ok(x) if !x.is_nan() => x,
_ => {
quotient.push(Scalar::Null(NullKind::NaN));
remainder.push(Scalar::Null(NullKind::NaN));
continue;
}
};
if den == 0.0 {
quotient.push(Scalar::Null(NullKind::NaN));
remainder.push(Scalar::Null(NullKind::NaN));
continue;
}
// Floor-division and Python-style modulo, including pandas' signed
// zero and infinity behavior.
let q = python_floor_div_f64(num, den);
let r = python_mod_f64(num, den);
quotient.push(Scalar::Float64(q));
remainder.push(Scalar::Float64(r));
}
Ok((
Self::new(DType::Float64, quotient)?,
Self::new(DType::Float64, remainder)?,
))
}
/// Keep values where `cond` is true; replace false positions with
/// values from an `other` Column (element-wise).
///
/// Matches `pd.Series.where(cond, other)` when `other` is a Series
/// aligned by position. All three inputs must have the same
/// length. Cond must be Bool. Missing cond entries propagate as
/// Null(NaN). The result dtype is `self.dtype`; if `other`'s dtype
/// differs, values coming from `other` are cast via `cast_scalar`.
pub fn where_cond_series(&self, cond: &Self, other: &Self) -> Result<Self, ColumnError> {
if cond.dtype != DType::Bool {
return Err(ColumnError::InvalidMaskType { dtype: cond.dtype });
}
if self.values.len() != cond.values.len() || self.values.len() != other.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: cond.values.len().max(other.values.len()),
});
}
// Typed branchless select: all-valid Bool cond and same-typed all-valid
// numeric self/other compute the result straight over the contiguous
// buffers, with no per-element Scalar dispatch/clone or output Vec<Scalar>.
// Bit-identical — with an all-valid cond there is no missing branch, and
// for matching dtypes cast_scalar(o, self.dtype) is the identity, so each
// slot is cond[i] ? self[i] : other[i]. Mixed/nullable inputs fall back.
if let Some(cb) = cond.as_bool_slice() {
if let (Some(s), Some(o)) = (self.as_f64_slice(), other.as_f64_slice()) {
let out: Vec<f64> = (0..s.len())
.map(|i| if cb[i] { s[i] } else { o[i] })
.collect();
// all-valid select of two NaN-free buffers → MOVE (no realloc).
return Ok(Self::from_f64_values_owned(out));
}
if let (Some(s), Some(o)) = (self.as_i64_slice(), other.as_i64_slice()) {
let out: Vec<i64> = (0..s.len())
.map(|i| if cb[i] { s[i] } else { o[i] })
.collect();
return Ok(Self::from_i64_values_owned(out));
}
// Nullable Int64 self+other (all-valid cond): the all-valid `as_i64_slice` arm
// above needs BOTH sides all-valid, so any nullable Int64 operand fell to the
// Scalar loop. Read both raw i64 buffers + validity: cond-true ⇒ self[i], false ⇒
// other[i]; a taken present slot keeps its datum, a taken missing slot clears the
// bit. Int64 has no NaN so "present" is the validity bit alone; all-valid cond ⇒
// no cond-missing. Bit-identical (missing Int64 ⇒ Null(Null) in both paths).
if self.dtype == DType::Int64
&& other.dtype == DType::Int64
&& let (Some((sd, sv)), Some((od, ov))) =
(self.as_i64_slice_with_validity(), other.as_i64_slice_with_validity())
{
let n = sd.len();
let mut out = vec![0_i64; n];
let mut vmask = ValidityMask::all_valid(n);
for i in 0..n {
let (d, v) = if cb[i] { (sd, sv) } else { (od, ov) };
if v.get(i) {
out[i] = d[i];
} else {
vmask.set(i, false);
}
}
return Ok(Self::from_i64_values_with_validity(out, vmask));
}
// Typed temporal self+other of the SAME dtype (all-valid OR nullable), all-valid
// cond. Generic loop materializes Vec<Scalar> + a cast_scalar per row. Select over
// the raw &[i64] ns via temporal_i64_backing: cond-true ⇒ self[i], cond-false ⇒
// other[i]; a taken slot present (validity set AND not the NaT sentinel) keeps its
// ns, else clears the bit. All-valid cond ⇒ the only missing source is a taken +
// missing slot, whose cleared bit materializes exactly as the generic clone/cast of
// a missing temporal slot (same-dtype cast_scalar is identity). Bit-identical.
if self.dtype == other.dtype
&& let (Some((sd, sv, nat)), Some((od, ov, _))) =
(self.temporal_i64_backing(), other.temporal_i64_backing())
{
let n = sd.len();
let mut out = vec![0_i64; n];
let mut vmask = ValidityMask::all_valid(n);
for i in 0..n {
let (d, v) = if cb[i] { (sd, sv) } else { (od, ov) };
if v.get(i) && d[i] != nat {
out[i] = d[i];
} else {
vmask.set(i, false);
}
}
return Ok(if self.dtype == DType::Datetime64 {
Self::from_datetime64_values_with_validity(out, vmask)
} else {
Self::from_timedelta64_values_with_validity(out, vmask)
});
}
}
let out: Vec<Scalar> = self
.values
.iter()
.zip(cond.values.iter().zip(other.values.iter()))
.map(|(v, (c, o))| match c {
Scalar::Bool(true) => Ok(v.clone()),
Scalar::Bool(false) => cast_scalar(o, self.dtype),
_ => Ok(Scalar::Null(NullKind::NaN)),
})
.collect::<Result<Vec<_>, _>>()
.map_err(ColumnError::Type)?;
Self::new(self.dtype, out)
}
/// Replace values where `cond` is true with values from `other`
/// (element-wise); otherwise keep.
///
/// Matches `pd.Series.mask(cond, other)` when `other` is a Series.
pub fn mask_series(&self, cond: &Self, other: &Self) -> Result<Self, ColumnError> {
if cond.dtype != DType::Bool {
return Err(ColumnError::InvalidMaskType { dtype: cond.dtype });
}
if self.values.len() != cond.values.len() || self.values.len() != other.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: cond.values.len().max(other.values.len()),
});
}
// Typed branchless select (inverse of where_cond_series): cond true picks
// other, false picks self. Same isomorphism argument.
if let Some(cb) = cond.as_bool_slice() {
if let (Some(s), Some(o)) = (self.as_f64_slice(), other.as_f64_slice()) {
let out: Vec<f64> = (0..s.len())
.map(|i| if cb[i] { o[i] } else { s[i] })
.collect();
return Ok(Self::from_f64_values_owned(out));
}
if let (Some(s), Some(o)) = (self.as_i64_slice(), other.as_i64_slice()) {
let out: Vec<i64> = (0..s.len())
.map(|i| if cb[i] { o[i] } else { s[i] })
.collect();
return Ok(Self::from_i64_values_owned(out));
}
// Nullable Int64 self+other (all-valid cond) — inverse of the where_cond_series
// nullable-Int64 arm: cond-true ⇒ other[i], cond-false ⇒ self[i]; a taken present
// slot keeps its datum, a taken missing slot clears the bit. Bit-identical.
if self.dtype == DType::Int64
&& other.dtype == DType::Int64
&& let (Some((sd, sv)), Some((od, ov))) =
(self.as_i64_slice_with_validity(), other.as_i64_slice_with_validity())
{
let n = sd.len();
let mut out = vec![0_i64; n];
let mut vmask = ValidityMask::all_valid(n);
for i in 0..n {
let (d, v) = if cb[i] { (od, ov) } else { (sd, sv) };
if v.get(i) {
out[i] = d[i];
} else {
vmask.set(i, false);
}
}
return Ok(Self::from_i64_values_with_validity(out, vmask));
}
// Typed temporal self+other same dtype (all-valid OR nullable), all-valid cond —
// inverse of the where_cond_series temporal arm: cond-true ⇒ other[i], cond-false ⇒
// self[i]; a taken slot present (validity set AND not NaT) keeps its ns else clears
// the bit. Bit-identical to the generic clone/cast select.
if self.dtype == other.dtype
&& let (Some((sd, sv, nat)), Some((od, ov, _))) =
(self.temporal_i64_backing(), other.temporal_i64_backing())
{
let n = sd.len();
let mut out = vec![0_i64; n];
let mut vmask = ValidityMask::all_valid(n);
for i in 0..n {
let (d, v) = if cb[i] { (od, ov) } else { (sd, sv) };
if v.get(i) && d[i] != nat {
out[i] = d[i];
} else {
vmask.set(i, false);
}
}
return Ok(if self.dtype == DType::Datetime64 {
Self::from_datetime64_values_with_validity(out, vmask)
} else {
Self::from_timedelta64_values_with_validity(out, vmask)
});
}
}
let out: Vec<Scalar> = self
.values
.iter()
.zip(cond.values.iter().zip(other.values.iter()))
.map(|(v, (c, o))| match c {
Scalar::Bool(true) => cast_scalar(o, self.dtype),
Scalar::Bool(false) => Ok(v.clone()),
_ => Ok(Scalar::Null(NullKind::NaN)),
})
.collect::<Result<Vec<_>, _>>()
.map_err(ColumnError::Type)?;
Self::new(self.dtype, out)
}
/// Pairwise value substitution.
///
/// Matches `pd.Series.replace(to_replace, value)` when both
/// arguments are scalar lists of equal length. For each value in
/// the column, the first (to_replace, replacement) pair that
/// matches via `Scalar::semantic_eq` is applied. Missing inputs
/// can be replaced by listing `Scalar::Null(...)` in `to_replace`.
/// Length mismatch between `to_replace` and `values` returns
/// `ColumnError::LengthMismatch`.
pub fn replace_values(
&self,
to_replace: &[Scalar],
replacement: &[Scalar],
) -> Result<Self, ColumnError> {
if to_replace.len() != replacement.len() {
return Err(ColumnError::LengthMismatch {
left: to_replace.len(),
right: replacement.len(),
});
}
// Typed Int64 fast path: all-valid Int64 column with all-Int64 (non-missing)
// targets AND replacements → the output stays Int64 (infer_dtype of all-Int64),
// so scan the raw &[i64] with integer equality (= semantic_eq for Int64),
// first-match-wins (same target order), no per-element Scalar/semantic_eq
// dispatch or infer_dtype. Bit-identical.
if self.dtype == DType::Int64
&& to_replace.iter().all(|s| matches!(s, Scalar::Int64(_)))
&& replacement.iter().all(|s| matches!(s, Scalar::Int64(_)))
&& let Some(data) = self.as_i64_slice()
{
let targets: Vec<i64> = to_replace
.iter()
.map(|s| match s {
Scalar::Int64(v) => *v,
_ => unreachable!(),
})
.collect();
let reps: Vec<i64> = replacement
.iter()
.map(|s| match s {
Scalar::Int64(v) => *v,
_ => unreachable!(),
})
.collect();
let out: Vec<i64> = data
.iter()
.map(|&x| {
for (t, r) in targets.iter().zip(reps.iter()) {
if x == *t {
return *r;
}
}
x
})
.collect();
return Ok(Self::from_i64_values_owned(out));
}
// Typed Utf8 fast path (sibling of the Int64 arm above; cardinality-vein
// relative): an all-valid contiguous-Utf8 column with all-Utf8 targets AND
// replacements keeps the output Utf8 (`infer_dtype` of all-Utf8 is Utf8), so
// build a first-match-wins `&[u8] -> &[u8]` map (byte-equality == `&str`
// -equality for valid UTF-8) and emit each row's mapped or original span
// into ONE contiguous buffer. This bypasses BOTH the per-row
// `Vec<Scalar::Utf8>` materialization AND the generic path's O(k)
// per-row linear `semantic_eq` scan over targets (O(N·k) -> O(N)).
// Bit-identical: `map.entry(..).or_insert` keeps the first replacement for
// a repeated target (first-match-wins, exactly the linear scan's order); a
// row matches at most the one target equal to it; all-valid ⇒ the missing
// arms never fire; empty output infers Utf8 just like `unwrap_or(self.dtype)`.
if self.dtype == DType::Utf8
&& to_replace.iter().all(|s| matches!(s, Scalar::Utf8(_)))
&& replacement.iter().all(|s| matches!(s, Scalar::Utf8(_)))
&& let Some((bytes, offsets)) = self.as_utf8_contiguous()
{
let mut map: FxHashMap<&[u8], &[u8]> = FxHashMap::default();
for (t, r) in to_replace.iter().zip(replacement.iter()) {
if let (Scalar::Utf8(ts), Scalar::Utf8(rs)) = (t, r) {
map.entry(ts.as_bytes()).or_insert(rs.as_bytes());
}
}
let mut out_bytes: Vec<u8> = Vec::with_capacity(bytes.len());
let mut out_offsets: Vec<usize> = Vec::with_capacity(offsets.len());
out_offsets.push(0);
for w in offsets.windows(2) {
let span = &bytes[w[0]..w[1]];
let emit = map.get(span).copied().unwrap_or(span);
out_bytes.extend_from_slice(emit);
out_offsets.push(out_bytes.len());
}
return Ok(Self::from_utf8_contiguous(out_bytes, out_offsets));
}
// Nullable sibling of the arm above: a `LazyNullableUtf8` column (a string column
// WITH missing rows) with all-Utf8 targets AND replacements. The generic loop
// materializes a `Vec<Scalar::Utf8>` AND does an O(k) per-row linear `semantic_eq`
// scan over targets (O(N·k)). Build the same first-match-wins `&[u8] -> &[u8]` map
// (O(1) probe) and emit each PRESENT row's mapped-or-original span into ONE
// contiguous buffer, carrying the source validity so MISSING rows stay missing.
// Bit-identical: all targets are Utf8 (never missing), so a missing value matches
// no target ⇒ the generic keeps it (`v.clone()` of a missing ⇒ Null) — mirrored
// here by the carried validity bit; all replacements are Utf8 (never null), so a
// present row's output is a present string ⇒ output validity == input validity,
// and `infer_dtype` of the (Utf8 | Null) generic output is Utf8. No cold-cache gate
// — the O(N) map + contiguous build beats the O(N·k) scan + per-row String clones
// even warm.
if self.dtype == DType::Utf8
&& to_replace.iter().all(|s| matches!(s, Scalar::Utf8(_)))
&& replacement.iter().all(|s| matches!(s, Scalar::Utf8(_)))
&& let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
..
} = &self.values
{
let mut map: FxHashMap<&[u8], &[u8]> = FxHashMap::default();
for (t, r) in to_replace.iter().zip(replacement.iter()) {
if let (Scalar::Utf8(ts), Scalar::Utf8(rs)) = (t, r) {
map.entry(ts.as_bytes()).or_insert(rs.as_bytes());
}
}
let n = offsets.len().saturating_sub(1);
let mut out_bytes: Vec<u8> = Vec::with_capacity(bytes.len());
let mut out_offsets: Vec<usize> = Vec::with_capacity(n + 1);
out_offsets.push(0);
for (i, w) in offsets.windows(2).enumerate() {
let span = &bytes[w[0]..w[1]];
// A missing row's span is empty and is masked out by the carried validity;
// only present rows consult the replacement map.
let emit = if validity.get(i) {
map.get(span).copied().unwrap_or(span)
} else {
span
};
out_bytes.extend_from_slice(emit);
out_offsets.push(out_bytes.len());
}
return Ok(Self::from_utf8_values_with_validity(
out_bytes,
out_offsets,
validity.clone(),
));
}
let out: Vec<Scalar> = self
.values
.iter()
.map(|v| {
for (target, replacement_val) in to_replace.iter().zip(replacement.iter()) {
// Treat all missing variants as matching to_replace = Null.
let matches = if target.is_missing() && v.is_missing() {
true
} else if target.is_missing() || v.is_missing() {
false
} else {
v.semantic_eq(target)
};
if matches {
return replacement_val.clone();
}
}
v.clone()
})
.collect();
let inferred = infer_dtype(&out).unwrap_or(self.dtype);
Self::new(inferred, out)
}
/// Alias for [`replace_values`](Self::replace_values), matching
/// `pd.Series.replace(to_replace, value)` for equal-length scalar
/// list replacements.
pub fn replace(
&self,
to_replace: &[Scalar],
replacement: &[Scalar],
) -> Result<Self, ColumnError> {
self.replace_values(to_replace, replacement)
}
/// Positions where the value is truthy and non-missing.
///
/// Matches `np.nonzero` / `pd.Series.to_numpy().nonzero()` style
/// behavior. Useful for turning a Bool mask column into explicit
/// index positions. Non-missing zero-like values (Int64 0,
/// Float64 0.0, Bool false, empty Utf8) are excluded.
#[must_use]
pub fn nonzero(&self) -> Vec<usize> {
let mut out = Vec::new();
for (i, v) in self.values.iter().enumerate() {
if v.is_missing() {
continue;
}
let truthy = match v {
Scalar::Bool(b) => *b,
Scalar::Int64(x) => *x != 0,
Scalar::Float64(x) => *x != 0.0 && !x.is_nan(),
Scalar::Utf8(s) => !s.is_empty(),
Scalar::Timedelta64(x) => *x != 0,
Scalar::Datetime64(x) => *x != Timestamp::NAT,
Scalar::Period(p) => p.ordinal != i64::MIN,
Scalar::Interval(_) => true,
Scalar::Null(_) => false,
};
if truthy {
out.push(i);
}
}
out
}
/// Count number of non-zero elements.
///
/// Matches np.count_nonzero().
#[must_use]
pub fn count_nonzero(&self) -> usize {
// A nullable Bool reduction only needs the number of validity-set true
// slots. Scanning the canonical raw backing avoids materializing one
// Scalar per row and avoids allocating every matching row position via
// `nonzero()`. Invalid raw values are masked, exactly as the generic
// `is_missing()` guard; false values remain zero-like.
if let ScalarValues::LazyNullableBool { data, validity, .. } = &self.values {
let mut count = 0usize;
for (idx, &value) in data.iter().enumerate() {
if value && validity.get(idx) {
count += 1;
}
}
return count;
}
self.nonzero().len()
}
/// Indices of non-zero elements as a column.
///
/// Matches np.flatnonzero(). Returns Int64 column of indices.
pub fn flatnonzero(&self) -> Result<Self, ColumnError> {
let indices: Vec<Scalar> = self
.nonzero()
.into_iter()
.map(|i| Scalar::Int64(i as i64))
.collect();
Self::new(DType::Int64, indices)
}
/// Keep values where `cond` is true; replace false positions with
/// `other`.
///
/// Matches `pd.Series.where(cond, other)`. `cond` must be a Bool
/// column of the same length (otherwise `LengthMismatch`). Missing
/// positions in `cond` propagate as Null(NaN) in the result.
pub fn where_cond(&self, cond: &Self, other: &Scalar) -> Result<Self, ColumnError> {
if cond.dtype != DType::Bool {
return Err(ColumnError::InvalidMaskType { dtype: cond.dtype });
}
if self.values.len() != cond.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: cond.values.len(),
});
}
// Typed branchless select against a scalar `other`. For Float64 self,
// Column::new coerces other to Float64, so other.to_f64() (non-missing)
// is the exact false-branch value; for Int64 self only an Int64 other
// stays lossless, so that path requires Scalar::Int64. All-valid cond =>
// no missing branch. Bit-identical; other cases fall back.
if !other.is_missing()
&& let Some(cb) = cond.as_bool_slice()
{
if let Some(s) = self.as_f64_slice()
&& let Ok(o) = other.to_f64()
{
let out: Vec<f64> = (0..s.len()).map(|i| if cb[i] { s[i] } else { o }).collect();
return Ok(Self::from_f64_values_owned(out));
}
if let Some(s) = self.as_i64_slice()
&& let Scalar::Int64(o) = other
{
let o = *o;
let out: Vec<i64> = (0..s.len()).map(|i| if cb[i] { s[i] } else { o }).collect();
return Ok(Self::from_i64_values_owned(out));
}
// Nullable Int64 self (all-valid cond): the all-valid `as_i64_slice` arm
// above bails on ANY missing self slot, so a nullable Int64 self fell to the
// Scalar loop. With an ALL-VALID cond there is NO cond-missing, so the only
// missing source is a cond-true+self-missing slot ⇒ Null(Null) ==
// missing_for_dtype(Int64) in BOTH paths (from_i64_values_with_validity's
// cleared bit == the Scalar loop's v.clone() of an Int64-missing slot). Int64
// has no NaN, so — unlike a nullable FLOAT64 self, which is EXCLUDED because
// a validity-set NaN datum renders Float64(NaN) via from_f64_values but
// Null(NaN) via Self::new — there is no NaN/validity ambiguity. Bit-identical:
// cond[i] ? self[i] (present ⇒ Int64, missing ⇒ Null(Null)) : Int64(other).
if self.dtype == DType::Int64
&& let Some((sd, sv)) = self.as_i64_slice_with_validity()
&& let Scalar::Int64(o) = other
{
let o = *o;
let mut out = vec![0_i64; sd.len()];
let mut vmask = ValidityMask::all_valid(sd.len());
for i in 0..sd.len() {
if cb[i] {
if sv.get(i) {
out[i] = sd[i];
} else {
vmask.set(i, false);
}
} else {
out[i] = o;
}
}
return Ok(Self::from_i64_values_with_validity(out, vmask));
}
// Utf8 self (all-valid OR nullable `LazyNullableUtf8`) + Utf8 other, all-valid
// cond: the generic loop below materializes a `Vec<Scalar::Utf8>` and clones a
// heap `String` per row. Build the select output as ONE contiguous buffer —
// cond-true ⇒ the self span (present) or a null (self missing), cond-false ⇒
// the `other` bytes — carrying validity. `self.validity` is the right mask for
// both backings (all-true for a contiguous all-valid column, the null mask for
// `LazyNullableUtf8`). Bit-identical to the loop: cond[i] ? self[i] (present ⇒
// Utf8(span), missing ⇒ Null(Null)) : Utf8(other); all-valid cond ⇒ the
// cond-missing → Null arm never fires. Ungated (contiguous build beats per-row
// String clones warm too).
if let Scalar::Utf8(o) = other
&& let Some((bytes, offsets)) = self
.as_utf8_contiguous()
.or_else(|| self.as_nullable_utf8_contiguous())
{
let o_bytes = o.as_bytes();
let sv = &self.validity;
let n = offsets.len().saturating_sub(1);
let mut out_bytes: Vec<u8> = Vec::with_capacity(bytes.len());
let mut out_offsets: Vec<usize> = Vec::with_capacity(n + 1);
out_offsets.push(0);
let mut vmask = ValidityMask::all_valid(n);
for i in 0..n {
if cb[i] {
if sv.get(i) {
out_bytes.extend_from_slice(&bytes[offsets[i]..offsets[i + 1]]);
} else {
vmask.set(i, false);
}
} else {
out_bytes.extend_from_slice(o_bytes);
}
out_offsets.push(out_bytes.len());
}
return Ok(Self::from_utf8_values_with_validity(
out_bytes,
out_offsets,
vmask,
));
}
// Typed temporal self (all-valid OR nullable) + matching NON-NaT temporal other,
// all-valid cond (mirror of the nullable-Int64 arm above). The generic loop below
// materializes a `Vec<Scalar::Datetime64/Timedelta64>` (32 B/row). Select over the
// raw `&[i64]` ns: cond-true ⇒ self[i] (present ⇒ its ns, missing=`!validity ||
// NaT` ⇒ cleared bit), cond-false ⇒ the `other` ns. All-valid cond ⇒ the only
// missing source is cond-true+self-missing, whose cleared bit materializes exactly
// as the generic loop's `v.clone()` of a missing temporal slot. Bit-identical.
let temporal_other = match (self.dtype, other) {
(DType::Datetime64, Scalar::Datetime64(o)) if *o != Timestamp::NAT => Some(*o),
(DType::Timedelta64, Scalar::Timedelta64(o)) if *o != Timedelta::NAT => Some(*o),
_ => None,
};
if let Some(o) = temporal_other
&& let Some((sd, sv, nat)) = self.temporal_i64_backing()
{
let n = sd.len();
let mut out = vec![0_i64; n];
let mut vmask = ValidityMask::all_valid(n);
for i in 0..n {
if cb[i] {
if sv.get(i) && sd[i] != nat {
out[i] = sd[i];
} else {
vmask.set(i, false);
}
} else {
out[i] = o;
}
}
return Ok(if self.dtype == DType::Datetime64 {
Self::from_datetime64_values_with_validity(out, vmask)
} else {
Self::from_timedelta64_values_with_validity(out, vmask)
});
}
}
let out: Vec<Scalar> = self
.values
.iter()
.zip(cond.values.iter())
.map(|(v, c)| match c {
Scalar::Bool(true) => v.clone(),
Scalar::Bool(false) => other.clone(),
_ => Scalar::Null(NullKind::NaN),
})
.collect();
Self::new(self.dtype, out)
}
/// Alias for [`where_cond`](Self::where_cond), matching
/// `pd.Series.where(cond, other)` for scalar `other` values.
pub fn r#where(&self, cond: &Self, other: &Scalar) -> Result<Self, ColumnError> {
self.where_cond(cond, other)
}
/// Rank the values of the column.
///
/// Matches `pd.Series.rank(method=..., ascending=..., na_option='keep')`.
/// Supported `method` values are `"average"` (pandas default,
/// ties → average of tied ranks), `"min"` (ties → smallest tied
/// rank), `"max"` (ties → largest tied rank), `"first"` (ties →
/// appearance order), and `"dense"` (ties → consecutive integers
/// with no gaps between distinct groups).
///
/// Missing input positions stay missing in the output (matching
/// pandas `na_option='keep'`). The result dtype is always Float64
/// so `"average"` can produce non-integer ranks.
pub fn rank(&self, method: &str, ascending: bool) -> Result<Self, ColumnError> {
let valid_method = matches!(method, "average" | "min" | "max" | "first" | "dense");
if !valid_method {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: method.to_string(),
dtype: self.dtype,
}));
}
let len = self.values.len();
// Counting-sort fast path: an all-valid, bounded-range Int64 column ranks
// in O(n) via a value histogram + prefix sums instead of the O(n log n)
// sort below. Bit-identical: compare_scalars_na_last compares Int64 with
// exact `i64::cmp` (no f64 coercion), so grouping by exact value matches
// the sort's tie groups; the stable sort's within-tie order ("first")
// is the original order, reproduced by a per-value occurrence counter
// walked in original order. The rank f64 expressions mirror the sort
// path's exactly (start_rank/end_rank), so every method/direction agrees.
if let Some(data) = self.as_i64_slice()
&& let Some((min, range)) = i64_direct_address_range(data)
{
let total = data.len() as i64;
let mut count = vec![0i64; range];
for &v in data {
count[(v as i128 - min as i128) as usize] += 1;
}
// c_less[s] = # values < value-at-slot-s; dense_asc[s] = 1-based
// ascending ordinal among present distinct values.
let mut c_less = vec![0i64; range];
let mut dense_asc = vec![0i64; range];
let mut acc = 0i64;
let mut ord = 0i64;
for s in 0..range {
c_less[s] = acc;
if count[s] > 0 {
ord += 1;
dense_asc[s] = ord;
}
acc += count[s];
}
let n_distinct = ord;
let mut occ = vec![0i64; range];
// Typed rank output (br-frankenpandas-dwmu9): every row of an
// all-valid Int64 column gets a finite f64 rank, so build a contiguous
// Vec<f64> and hand it to from_f64_values instead of boxing 1 Scalar
// per row and re-validating through Self::new. Bit-identical: ranks are
// never NaN (1-based ordinals / their averages), so from_f64_values
// marks every slot valid, exactly like Self::new over Scalar::Float64.
let mut ranks = vec![0.0_f64; len];
for (i, &v) in data.iter().enumerate() {
let s = (v as i128 - min as i128) as usize;
let c = count[s];
// `before` = sorted-position offset of this value's tie group
// (values that sort before it): `c_less` ascending, the
// complement `total - c_less - c` descending.
let before = if ascending {
c_less[s]
} else {
total - c_less[s] - c
};
let start_rank = before as f64 + 1.0;
let end_rank = (before + c) as f64;
let value = match method {
"average" => (start_rank + end_rank) / 2.0,
"min" => start_rank,
"max" => end_rank,
"first" => {
let k = occ[s];
occ[s] += 1;
(before + k) as f64 + 1.0
}
"dense" => {
let d = if ascending {
dense_asc[s]
} else {
n_distinct - dense_asc[s] + 1
};
d as f64
}
_ => unreachable!(),
};
ranks[i] = value;
}
return Ok(Self::from_f64_values(ranks));
}
// Radix fast path: an all-valid, NaN-free Float64 column ranks in O(n)
// via the stable LSD radix permutation (the same one `sort_values`/
// `argsort` use) instead of the O(n log n) `Scalar` comparison sort
// below. Bit-identical: `f64_radix_key` normalizes `-0.0` to `0.0`
// (exactly as `compare_scalars_na_last`'s `partial_cmp` treats `-0.0 ==
// 0.0`), `radix_argsort_u64` is stable (ties keep original order, like
// the stable `sort_by`), and tie groups are detected with f64 `==`
// (which is `Equal` under `partial_cmp` for the same finite values). A
// NaN would diverge — `partial_cmp(NaN, _) -> Equal` collapses ties in
// the comparator path while the radix key sorts NaN to one end, and a
// NaN value is also `is_missing()` so the comparator path drops it — so
// any NaN routes to the unchanged comparator fallback. All-valid +
// NaN-free means every row is ranked (no nulls), so the output is built
// typed via `from_f64_values`.
if let Some(data) = self.as_f64_slice()
&& !data.iter().any(|x| x.is_nan())
{
let perm = self
.typed_radix_perm(ascending)
.expect("f64 slice yields radix perm");
let n = perm.len();
let mut ranks = vec![0.0_f64; len];
let mut cursor = 0usize;
let mut dense_rank = 0f64;
while cursor < n {
let mut end = cursor + 1;
while end < n && data[perm[end]] == data[perm[cursor]] {
end += 1;
}
let start_rank = cursor as f64 + 1.0;
let end_rank = end as f64;
dense_rank += 1.0;
#[allow(clippy::needless_range_loop)] // group_idx is also the "first" rank value
for group_idx in cursor..end {
let original = perm[group_idx];
ranks[original] = match method {
"average" => (start_rank + end_rank) / 2.0,
"min" => start_rank,
"max" => end_rank,
"first" => group_idx as f64 + 1.0,
"dense" => dense_rank,
_ => unreachable!(),
};
}
cursor = end;
}
return Ok(Self::from_f64_values(ranks));
}
// Nullable/NaN typed Int64/Float64 (and wide-range all-valid Int64 that
// the bounded counting path above declined): the generic na-last Scalar
// comparator sort below is O(n log n) over boxed Scalars. typed_radix_perm
// reproduces that exact na-last order in O(n) (it backs the nullable
// argsort, proven bit-identical to compare_scalars_na_last), and its
// PRESENT prefix equals `non_missing` sorted (same stable value+index
// order). Walk that prefix typed and build the Float64 output directly with
// its validity, skipping the Scalar box on both the sort keys and the
// result. `Some(perm)` for these dtypes ⇒ nothing all-valid-and-fast is
// rerouted (those arms returned earlier). present_count uses the SAME
// present definition as typed_radix_perm so the prefix/suffix split aligns.
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
&& let Some(perm) = self.typed_radix_perm(ascending)
{
let present_count = validity.count_valid();
let (ranks, out_valid) =
nullable_rank_values(data, &perm, present_count, len, method);
return Ok(Self::from_f64_values_with_validity(ranks, out_valid));
}
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
&& let Some(perm) = self.typed_radix_perm(ascending)
{
let present_count = (0..len)
.filter(|&i| validity.get(i) && !data[i].is_nan())
.count();
let (ranks, out_valid) =
nullable_rank_values(data, &perm, present_count, len, method);
return Ok(Self::from_f64_values_with_validity(ranks, out_valid));
}
// Temporal Datetime64/Timedelta64 (all-valid no-NaT, or nullable/NaT): rank
// had NO typed path — as_i64_slice/as_f64_slice both decline these dtypes,
// so every temporal column ranked via the generic O(n log n) Scalar
// comparator. Both store i64 ns ordering as i64, and typed_radix_perm has a
// temporal na-last arm. Because rank's OUTPUT is always Float64, there is no
// NaT-materialization subtlety (unlike a temporal sort_values): a slot is
// present iff validity-set AND datum != i64::MIN (the NaT sentinel;
// is_missing(Datetime64/Timedelta64(v)) == (v == i64::MIN)) — the same split
// the generic non_missing filter AND typed_radix_perm use — so the present
// prefix + typed i64 `==` tie-walk are bit-identical to the comparator rank.
if matches!(self.dtype, DType::Datetime64 | DType::Timedelta64) {
let ns: Option<&[i64]> = match self.dtype {
DType::Datetime64 => self.as_datetime64_slice().or_else(|| match &self.values {
ScalarValues::LazyNullableDatetime64 { data, .. } => Some(data.as_slice()),
_ => None,
}),
DType::Timedelta64 => self.as_timedelta64_slice().or_else(|| match &self.values {
ScalarValues::LazyNullableTimedelta64 { data, .. } => Some(data.as_slice()),
_ => None,
}),
_ => None,
};
if let Some(data) = ns
&& let Some(perm) = self.typed_radix_perm(ascending)
{
let present_count = (0..len)
.filter(|&i| self.validity.get(i) && data[i] != i64::MIN)
.count();
let (ranks, out_valid) =
nullable_rank_values(data, &perm, present_count, len, method);
return Ok(Self::from_f64_values_with_validity(ranks, out_valid));
}
}
// Typed Utf8 rank (contiguous all-valid + nullable `LazyNullableUtf8`): rank had
// NO Utf8 typed path — the generic O(n log n) `compare_scalars_na_last` Scalar
// sort below first materializes the whole `Vec<Scalar::Utf8>` (a heap `String`
// per row). Rank over the raw `&[u8]` row spans instead: sort the PRESENT rows
// with the stable MSD byte radix (`utf8_msd_argsort_bytes`, the same permutation
// `argsort`/`sort_values` use — byte order == `String::cmp` == the Utf8 arm of
// `compare_scalars_na_last` for valid UTF-8), place missing rows in the na-last
// suffix, and walk that permutation with `nullable_rank_values` (tie groups by
// byte-span `==`, `T = &[u8]`). Bit-identical to the generic path: identical
// present-row sorted order + stable within-tie order ("first"), the SAME rank
// formulas (`nullable_rank_values` mirrors the Scalar walk below), and missing ⇒
// `Null(NaN)` (cleared validity bit over a 0.0 datum). Output is always Float64.
// Non-contiguous (Eager) Utf8 keeps the generic path.
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
// `as_utf8_contiguous` gates on `validity.all()` ⇒ every row present.
let spans: Vec<&[u8]> = offsets.windows(2).map(|w| &bytes[w[0]..w[1]]).collect();
let perm = utf8_msd_argsort_bytes(&spans, ascending);
let (ranks, _valid) = nullable_rank_values(&spans, &perm, len, len, method);
return Ok(Self::from_f64_values(ranks));
}
if let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
..
} = &self.values
{
let spans: Vec<&[u8]> = offsets.windows(2).map(|w| &bytes[w[0]..w[1]]).collect();
let present_idx: Vec<usize> = (0..len).filter(|&i| validity.get(i)).collect();
let present_count = present_idx.len();
// Radix-sort ONLY the present spans (perm over 0..present_count), then map
// back to original row indices; missing rows follow in the na-last suffix.
// Stable ⇒ equal spans keep ascending original-index order (== the generic
// stable sort's original order), so "first" ranks match.
let present_spans: Vec<&[u8]> = present_idx.iter().map(|&i| spans[i]).collect();
let sub = utf8_msd_argsort_bytes(&present_spans, ascending);
let mut perm: Vec<usize> = sub.iter().map(|&p| present_idx[p]).collect();
perm.extend((0..len).filter(|&i| !validity.get(i)));
let (ranks, out_valid) =
nullable_rank_values(&spans, &perm, present_count, len, method);
return Ok(Self::from_f64_values_with_validity(ranks, out_valid));
}
let mut non_missing: Vec<(usize, &Scalar)> = Vec::with_capacity(len);
for (i, v) in self.values.iter().enumerate() {
if !v.is_missing() {
non_missing.push((i, v));
}
}
non_missing.sort_by(|a, b| compare_scalars_na_last(a.1, b.1, ascending));
let mut ranks = vec![Scalar::Null(NullKind::NaN); len];
let n = non_missing.len();
let mut cursor = 0usize;
let mut dense_rank = 0f64;
while cursor < n {
let mut end = cursor + 1;
while end < n {
let same =
compare_scalars_na_last(non_missing[cursor].1, non_missing[end].1, ascending)
.is_eq();
if !same {
break;
}
end += 1;
}
let start_rank = cursor as f64 + 1.0;
let end_rank = end as f64;
dense_rank += 1.0;
for (group_idx, entry) in non_missing.iter().enumerate().take(end).skip(cursor) {
let original = entry.0;
let value = match method {
"average" => (start_rank + end_rank) / 2.0,
"min" => start_rank,
"max" => end_rank,
"first" => group_idx as f64 + 1.0,
"dense" => dense_rank,
_ => unreachable!(),
};
ranks[original] = Scalar::Float64(value);
}
cursor = end;
}
Self::new(DType::Float64, ranks)
}
/// Position where `needle` would be inserted to preserve sort order.
///
/// Matches `pd.Series.searchsorted(value, side)`. `side` is
/// `"left"` (first valid insertion position) or `"right"` (last).
/// The column is assumed sorted ascending with missing values at
/// the end (consistent with `sort_values(true)`). Missing
/// `needle` is rejected with a type error.
pub fn searchsorted(&self, needle: &Scalar, side: &str) -> Result<usize, ColumnError> {
self.searchsorted_position(needle, side, None)
}
/// Position where `needle` would be inserted using an explicit sorter.
///
/// Matches `pd.Series.searchsorted(value, side, sorter=...)` where
/// `sorter` is a permutation that sorts the column ascending.
pub fn searchsorted_with_sorter(
&self,
needle: &Scalar,
side: &str,
sorter: &[usize],
) -> Result<usize, ColumnError> {
self.searchsorted_position(needle, side, Some(sorter))
}
/// Positions where `needles` would be inserted to preserve sort order.
///
/// Matches `pd.Series.searchsorted(values, side)` for array-like
/// inputs. Returns an `Int64` column of insertion positions.
/// Missing needles are rejected with the same error as the scalar path.
pub fn searchsorted_values(&self, needles: &[Scalar], side: &str) -> Result<Self, ColumnError> {
// Typed fast path: an all-valid (sorted) Int64 column with all-Int64
// needles runs `partition_point` over the raw `&[i64]` — no per-comparison
// `Scalar` access or `compare_scalars_na_last` dispatch. Bit-identical to
// the binary search below: side="left" inserts before equals
// (first v >= needle = `v < needle` partition), "right" after equals
// (first v > needle = `v <= needle` partition). Output is the same Int64
// position column. Any non-Int64 needle (incl. missing) or other side
// falls through to the generic path (which errors on missing/bad side).
if (side == "left" || side == "right")
&& let Some(data) = self.as_i64_slice()
&& needles.iter().all(|n| matches!(n, Scalar::Int64(_)))
{
let left = side == "left";
let out: Vec<i64> = needles
.iter()
.map(|n| {
let nv = match n {
Scalar::Int64(v) => *v,
_ => unreachable!("guarded all-Int64 above"),
};
let pos = if left {
data.partition_point(|&v| v < nv)
} else {
data.partition_point(|&v| v <= nv)
};
pos as i64
})
.collect();
return Ok(Self::from_i64_values_owned(out));
}
// Float64 analogue: an all-valid (sorted, NaN-last) Float64 column with all
// NON-NaN Float64 needles runs `partition_point` over the raw `&[f64]`,
// instead of `searchsorted_position` materializing the whole
// `Vec<Scalar::Float64>` (via `as_slice`'s `get_or_init`) just to serve `k`
// searches. Bit-identical under searchsorted's sorted precondition: a sorted
// Float64 column sorts NaN LAST, so for a non-NaN needle the predicate
// `v < nv` is `[< nv | >= nv | NaN]` (partitioned — `NaN < nv` is false, so
// NaN lands in the `>=` tail exactly where `compare_scalars_na_last` places
// it), yielding the same first-`>=` (left) / first-`>` (right) index the
// generic binary search returns; -0.0/+0.0 compare equal on both paths. A
// NaN needle is EXCLUDED from the guard (partition_point would place it at 0,
// but NaN-last inserts it at the end) and a non-Float64 needle falls through
// to the generic cross-dtype comparator.
if (side == "left" || side == "right")
&& let Some(data) = self.as_f64_slice()
&& needles
.iter()
.all(|n| matches!(n, Scalar::Float64(v) if !v.is_nan()))
{
let left = side == "left";
let out: Vec<i64> = needles
.iter()
.map(|n| {
let nv = match n {
Scalar::Float64(v) => *v,
_ => unreachable!("guarded all-non-NaN-Float64 above"),
};
let pos = if left {
data.partition_point(|&v| v < nv)
} else {
data.partition_point(|&v| v <= nv)
};
pos as i64
})
.collect();
return Ok(Self::from_i64_values_owned(out));
}
// Datetime64 analogue: all-valid no-NaT sorted ns + all-(non-NaT)-Datetime64
// needles → partition_point over the raw ns. The generic comparator is now
// exact for Datetime64 (a.cmp(b)), so this is bit-identical. NaT (i64::MIN)
// in self or a needle falls through (NaT is missing → generic errors/handles).
if (side == "left" || side == "right")
&& !self.has_nulls()
&& let Some(data) = self.as_datetime64_slice()
&& !data.contains(&i64::MIN)
&& needles
.iter()
.all(|n| matches!(n, Scalar::Datetime64(v) if *v != i64::MIN))
{
let left = side == "left";
let out: Vec<i64> = needles
.iter()
.map(|n| {
let nv = match n {
Scalar::Datetime64(v) => *v,
_ => unreachable!("guarded all-Datetime64 above"),
};
let pos = if left {
data.partition_point(|&v| v < nv)
} else {
data.partition_point(|&v| v <= nv)
};
pos as i64
})
.collect();
return Ok(Self::from_i64_values_owned(out));
}
// Timedelta64 analogue: all-valid no-NaT sorted ns + all-(non-NaT)-Timedelta64
// needles → partition_point over the raw ns. `compare_scalars_na_last` has an
// EXACT `Timedelta64(a).cmp(b)` arm, so this is bit-identical to the generic
// binary search. NaT (i64::MIN) in self or a needle falls through (NaT is
// missing → generic errors/handles), exactly mirroring the Datetime64 arm.
if (side == "left" || side == "right")
&& !self.has_nulls()
&& let Some(data) = self.as_timedelta64_slice()
&& !data.contains(&i64::MIN)
&& needles
.iter()
.all(|n| matches!(n, Scalar::Timedelta64(v) if *v != i64::MIN))
{
let left = side == "left";
let out: Vec<i64> = needles
.iter()
.map(|n| {
let nv = match n {
Scalar::Timedelta64(v) => *v,
_ => unreachable!("guarded all-Timedelta64 above"),
};
let pos = if left {
data.partition_point(|&v| v < nv)
} else {
data.partition_point(|&v| v <= nv)
};
pos as i64
})
.collect();
return Ok(Self::from_i64_values_owned(out));
}
// Contiguous-Utf8 analogue: an all-valid (sorted) Utf8 column with all-Utf8
// needles binary-searches over the byte spans directly, instead of
// `searchsorted_position` accessing `&self.values[mid]` -- which forces
// `as_slice()` to materialize the WHOLE `Vec<Scalar::Utf8>` (one heap
// `String` per row) just to serve `k` searches. Bit-identical: same
// lo/hi/mid probe sequence and the same go-right rule (mid < needle for
// "left", mid <= needle for "right") as `searchsorted_position`, with
// `&[u8]` order == `&str`/`String` order for valid UTF-8. `as_utf8_contiguous`
// matches only an all-valid backing, so the "missing sorts last" branch
// never fires (no sorter here either). Any non-Utf8 needle falls through to
// the generic cross-dtype comparator.
if (side == "left" || side == "right")
&& needles.iter().all(|n| matches!(n, Scalar::Utf8(_)))
&& let Some((bytes, offsets)) = self.as_utf8_contiguous()
{
let left = side == "left";
let n_spans = offsets.len().saturating_sub(1);
let out: Vec<i64> = needles
.iter()
.map(|n| {
let nb = match n {
Scalar::Utf8(s) => s.as_bytes(),
_ => unreachable!("guarded all-Utf8 above"),
};
let (mut lo, mut hi) = (0usize, n_spans);
while lo < hi {
let mid = lo + (hi - lo) / 2;
let span = &bytes[offsets[mid]..offsets[mid + 1]];
let go_right = if left { span < nb } else { span <= nb };
if go_right {
lo = mid + 1;
} else {
hi = mid;
}
}
lo as i64
})
.collect();
return Ok(Self::from_i64_values_owned(out));
}
let positions: Vec<Scalar> = needles
.iter()
.map(|needle| self.searchsorted_position(needle, side, None))
.map(|result| result.map(|position| Scalar::Int64(position as i64)))
.collect::<Result<Vec<_>, _>>()?;
Self::new(DType::Int64, positions)
}
/// Positions where `needles` would be inserted using an explicit sorter.
///
/// Matches `pd.Series.searchsorted(values, side, sorter=...)` for
/// array-like inputs. Returns an `Int64` column of insertion positions.
pub fn searchsorted_values_with_sorter(
&self,
needles: &[Scalar],
side: &str,
sorter: &[usize],
) -> Result<Self, ColumnError> {
// Hoist the O(N) sorter validation OUT of the per-needle loop. The pre-lever
// path called `searchsorted_position` per needle, which validated the sorter
// EVERY time (O(k·N)). Validate at most ONCE (lazily, on the first needle
// that clears the side + non-missing checks) and reuse it. Bit-identical:
// the per-needle side/missing checks and their order are unchanged, and
// validating on the first passing needle raises the exact same error the
// pre-lever's first `searchsorted_position` raised (empty needles never
// validate, exactly as before, since the loop body never runs).
// Typed fast paths (sorter analogue of the no-sorter `searchsorted_values`):
// an all-valid Int64/Float64 column with all-matching needles binary-searches
// over `data[sorter[mid]]` typed, instead of `searchsorted_binary_core`
// materializing the whole `Vec<Scalar>` (via `self.values`) and running
// `compare_scalars_na_last` per step for every one of `k` needles. Gated on
// NON-EMPTY needles so the empty case keeps the original behaviour (no sorter
// validation, returns empty). Bit-identical: the sorter defines the sorted
// view, all values are present (so `compare_scalars_na_last` == typed cmp),
// and the go-right rule is identical (mid < needle for "left", mid <= needle
// for "right"). Float64 excludes NaN needles (NaN sorts last, not via `<`).
if !needles.is_empty() && (side == "left" || side == "right") {
if let Some(data) = self.as_i64_slice()
&& needles.iter().all(|n| matches!(n, Scalar::Int64(_)))
{
let sorter = self
.validate_searchsorted_sorter(Some(sorter))?
.expect("Some(sorter) validates to Some");
let left = side == "left";
let out: Vec<i64> = needles
.iter()
.map(|n| {
let nv = match n {
Scalar::Int64(v) => *v,
_ => unreachable!("guarded all-Int64"),
};
let (mut lo, mut hi) = (0usize, sorter.len());
while lo < hi {
let mid = lo + (hi - lo) / 2;
let mv = data[sorter[mid]];
let go_right = if left { mv < nv } else { mv <= nv };
if go_right {
lo = mid + 1;
} else {
hi = mid;
}
}
lo as i64
})
.collect();
return Ok(Self::from_i64_values_owned(out));
}
if let Some(data) = self.as_f64_slice()
&& needles
.iter()
.all(|n| matches!(n, Scalar::Float64(v) if !v.is_nan()))
{
let sorter = self
.validate_searchsorted_sorter(Some(sorter))?
.expect("Some(sorter) validates to Some");
let left = side == "left";
let out: Vec<i64> = needles
.iter()
.map(|n| {
let nv = match n {
Scalar::Float64(v) => *v,
_ => unreachable!("guarded all-non-NaN-Float64"),
};
let (mut lo, mut hi) = (0usize, sorter.len());
while lo < hi {
let mid = lo + (hi - lo) / 2;
let mv = data[sorter[mid]];
let go_right = if left { mv < nv } else { mv <= nv };
if go_right {
lo = mid + 1;
} else {
hi = mid;
}
}
lo as i64
})
.collect();
return Ok(Self::from_i64_values_owned(out));
}
}
let mut positions: Vec<Scalar> = Vec::with_capacity(needles.len());
let mut validated: Option<Option<&[usize]>> = None;
for needle in needles {
if side != "left" && side != "right" {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: side.to_string(),
dtype: self.dtype,
}));
}
if needle.is_missing() {
return Err(ColumnError::Type(TypeError::ValueIsMissing {
kind: NullKind::NaN,
}));
}
let v = match validated {
Some(v) => v,
None => {
let v = self.validate_searchsorted_sorter(Some(sorter))?;
validated = Some(v);
v
}
};
positions.push(Scalar::Int64(
self.searchsorted_binary_core(needle, side, v) as i64,
));
}
Self::new(DType::Int64, positions)
}
fn searchsorted_position(
&self,
needle: &Scalar,
side: &str,
sorter: Option<&[usize]>,
) -> Result<usize, ColumnError> {
if side != "left" && side != "right" {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: side.to_string(),
dtype: self.dtype,
}));
}
if needle.is_missing() {
return Err(ColumnError::Type(TypeError::ValueIsMissing {
kind: NullKind::NaN,
}));
}
let sorter = self.validate_searchsorted_sorter(sorter)?;
Ok(self.searchsorted_binary_core(needle, side, sorter))
}
/// Binary-search core shared by `searchsorted_position` (single needle) and
/// `searchsorted_values_with_sorter` (bulk). Assumes `side` is valid, `needle`
/// is non-missing, and `sorter` (if `Some`) is ALREADY validated — so the bulk
/// caller can validate the sorter ONCE rather than once per needle.
fn searchsorted_binary_core(
&self,
needle: &Scalar,
side: &str,
sorter: Option<&[usize]>,
) -> usize {
let len = sorter.map_or(self.values.len(), <[usize]>::len);
let mut lo = 0usize;
let mut hi = len;
while lo < hi {
let mid = lo + (hi - lo) / 2;
let mid_idx = sorter.map_or(mid, |indices| indices[mid]);
let mid_val = &self.values[mid_idx];
// Values that are "missing" sort to the end; treat needle as
// less than any missing slot.
let ord = if mid_val.is_missing() {
std::cmp::Ordering::Greater
} else {
compare_scalars_na_last(mid_val, needle, true)
};
use std::cmp::Ordering;
let go_right = match (ord, side) {
(Ordering::Less, _) => true,
(Ordering::Equal, "left") => false,
(Ordering::Equal, "right") => true,
(Ordering::Greater, _) => false,
_ => unreachable!(),
};
if go_right {
lo = mid + 1;
} else {
hi = mid;
}
}
lo
}
fn validate_searchsorted_sorter<'a>(
&self,
sorter: Option<&'a [usize]>,
) -> Result<Option<&'a [usize]>, ColumnError> {
let Some(sorter) = sorter else {
return Ok(None);
};
let len = self.values.len();
if sorter.len() != len {
return Err(ColumnError::LengthMismatch {
left: len,
right: sorter.len(),
});
}
let mut seen = vec![false; len];
for &idx in sorter {
if idx >= len {
return Err(ColumnError::InvalidSorter {
len,
reason: format!("index {idx} out of bounds"),
});
}
if std::mem::replace(&mut seen[idx], true) {
return Err(ColumnError::InvalidSorter {
len,
reason: format!("index {idx} appears more than once"),
});
}
}
Ok(Some(sorter))
}
/// Return bin indices for values given sorted bin edges.
///
/// Matches np.digitize(). Returns indices such that bins[i-1] <= x < bins[i].
pub fn digitize(&self, bins: &Self, right: bool) -> Result<Self, ColumnError> {
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Int64(0));
continue;
}
let vf = v.to_f64().map_err(ColumnError::Type)?;
let side = if right { "right" } else { "left" };
let pos = bins.searchsorted(&Scalar::Float64(vf), side)?;
out.push(Scalar::Int64(pos as i64));
}
Self::new(DType::Int64, out)
}
/// Count occurrences of each non-negative integer value.
///
/// Matches np.bincount(). Returns array where output[i] = count of i in input.
/// Requires non-negative Int64 values.
pub fn bincount(&self, minlength: usize) -> Result<Self, ColumnError> {
let mut max_val = 0i64;
for v in &self.values {
if v.is_missing() {
continue;
}
match v {
Scalar::Int64(x) if *x >= 0 => {
if *x > max_val {
max_val = *x;
}
}
Scalar::Int64(x) => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("negative value {x}"),
dtype: self.dtype,
}));
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
let len = (max_val as usize + 1).max(minlength);
let mut counts = vec![0i64; len];
for v in &self.values {
if v.is_missing() {
continue;
}
if let Scalar::Int64(x) = v {
counts[*x as usize] += 1;
}
}
let out: Vec<Scalar> = counts.into_iter().map(Scalar::Int64).collect();
Self::new(DType::Int64, out)
}
/// Compute histogram using provided bin edges.
///
/// Matches np.histogram(a, bins=edges). Returns counts for each bin.
/// Bins are [edges[i], edges[i+1]) except the last which is [edges[n-1], edges[n]].
pub fn histogram(&self, bin_edges: &[f64]) -> Result<Self, ColumnError> {
if bin_edges.len() < 2 {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: "histogram requires at least 2 bin edges".to_owned(),
dtype: self.dtype,
}));
}
let n_bins = bin_edges.len() - 1;
let mut counts = vec![0i64; n_bins];
// Fast path: strictly-increasing edges admit an O(log n_bins) binary
// search for each value's bin instead of the O(n_bins) linear scan
// below — O(N·log B) vs O(N·B). Bins are right-open [e_i, e_{i+1}) with
// an inclusive final right edge, so for x in [e_0, e_last] the bin is
// `partition_point(|e| e <= x) - 1` clamped to the last bin (so a value
// exactly at e_last lands in bin n_bins-1); values outside [e_0, e_last]
// are dropped — bit-identical to the linear scan. Non-strict (duplicate)
// edges create zero-width bins where the two scans can disagree, so they
// take the original linear path.
let strict = bin_edges.windows(2).all(|w| w[0] < w[1]);
{
let mut tally = |x: f64| {
if strict {
if x >= bin_edges[0] && x <= bin_edges[n_bins] {
let bin =
(bin_edges.partition_point(|&edge| edge <= x) - 1).min(n_bins - 1);
counts[bin] += 1;
}
return;
}
// Linear scan (non-strict edges fallback).
for i in 0..n_bins {
let in_bin = if i == n_bins - 1 {
// Last bin is inclusive on right
x >= bin_edges[i] && x <= bin_edges[i + 1]
} else {
x >= bin_edges[i] && x < bin_edges[i + 1]
};
if in_bin {
counts[i] += 1;
break;
}
}
// Values outside all bins are not counted (matches numpy).
};
// A cold nullable Float64 column otherwise materializes one Scalar per
// row before reaching the already-optimized bin search. Read the raw
// f64 buffer plus validity directly: the generic path accepts exactly
// validity-set finite values (missing/NaN/inf are skipped). A warm or
// different backing retains the generic path, avoiding a regression
// when its Scalar cache has already been paid for.
if let ScalarValues::LazyNullableFloat64 {
data,
validity,
values,
} = &self.values
&& values.get().is_none()
{
for (idx, &x) in data.iter().enumerate() {
if validity.get(idx) && x.is_finite() {
tally(x);
}
}
} else {
for v in &self.values {
if v.is_missing() {
continue;
}
if let Ok(x) = v.to_f64()
&& x.is_finite()
{
tally(x);
}
}
}
}
let out: Vec<Scalar> = counts.into_iter().map(Scalar::Int64).collect();
Self::new(DType::Int64, out)
}
/// Compute histogram with auto-generated bins.
///
/// Matches np.histogram(a, bins=n_bins). Returns (counts, bin_edges).
/// Bins are evenly spaced between min and max of the data.
pub fn histogram_auto(&self, n_bins: usize) -> Result<(Self, Vec<f64>), ColumnError> {
if n_bins == 0 {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: "histogram requires at least 1 bin".to_owned(),
dtype: self.dtype,
}));
}
// Find min and max
let mut min_val = f64::INFINITY;
let mut max_val = f64::NEG_INFINITY;
for v in &self.values {
if v.is_missing() {
continue;
}
if let Ok(x) = v.to_f64()
&& x.is_finite()
{
min_val = min_val.min(x);
max_val = max_val.max(x);
}
}
if !min_val.is_finite() || !max_val.is_finite() || min_val > max_val {
// No valid data
let counts: Vec<Scalar> = vec![Scalar::Int64(0); n_bins];
let edges = vec![0.0; n_bins + 1];
return Ok((Self::new(DType::Int64, counts)?, edges));
}
// Generate bin edges
let range = max_val - min_val;
let (adj_min, adj_max) = if range == 0.0 {
// All values are the same - numpy extends by 0.5 on each side
(min_val - 0.5, max_val + 0.5)
} else {
(min_val, max_val)
};
let adj_range = adj_max - adj_min;
let step = adj_range / n_bins as f64;
let bin_edges: Vec<f64> = (0..=n_bins).map(|i| adj_min + step * i as f64).collect();
let counts = self.histogram(&bin_edges)?;
Ok((counts, bin_edges))
}
/// Cast the column to a target dtype.
///
/// Matches `pd.Series.astype(dtype)`. Each value is routed through
/// `fp_types::cast_scalar`, so coercion rules (Int64↔Float64,
/// Bool→Int64, Utf8 parsing, etc.) match the existing cast table.
/// Cast failures on any element return `ColumnError::Type` wrapping
/// the underlying TypeError so the caller can attribute the
/// failing conversion. Missing values pass through as the
/// target dtype's canonical missing representation.
pub fn astype(&self, target: DType) -> Result<Self, ColumnError> {
if self.dtype == target {
return Ok(self.clone());
}
// Typed fast paths for the two ubiquitous all-valid numeric casts:
// Int64 -> Float64 is exactly `x as f64` (the cast_scalar branch), and
// Float64 -> Int64 truncates a finite in-range float toward zero via
// `v as i64`. NaN floats mark the column invalid so as_f64_slice
// declines; an out-of-range float makes cast_scalar error, so we only
// take the typed path when every value is in range (otherwise the
// Scalar path below reproduces that exact error). Bit-identical.
if target == DType::Float64
&& let Some(data) = self.as_i64_slice()
{
let out: Vec<f64> = data.iter().map(|&x| x as f64).collect();
// `x as f64` is always finite → all-valid output → MOVE (no realloc).
return Ok(Self::from_f64_values_owned(out));
}
if target == DType::Int64
&& let Some(data) = self.as_f64_slice()
&& data
.iter()
.all(|&v| v >= i64::MIN as f64 && v < 9_223_372_036_854_775_808.0)
{
let out: Vec<i64> = data.iter().map(|&v| v as i64).collect();
// all-valid output → MOVE (no Arc::from realloc).
return Ok(Self::from_i64_values_owned(out));
}
// Utf8 -> Float64: parse each field's bytes straight from the contiguous
// buffer into a typed Vec<f64>, skipping the per-cell Scalar map +
// cast_scalar dispatch + Self::new revalidation the generic tail pays
// (astype(f64) on a string column was ~3.3x slower than to_numeric on the
// same data). cast_scalar(Utf8(s), Float64) is exactly `s.parse::<f64>()`
// (NO trim — Rust f64::from_str rejects surrounding whitespace, matching),
// so this is bit-identical. `as_utf8_contiguous` is all-valid, so every
// cell is present; a value parsing to NaN (e.g. "nan") or a parse failure
// BAILS to the generic Scalar path, which reproduces the exact
// NaN-is-missing / raise-error behavior. All-valid non-NaN output ⇒
// from_f64_values_owned MOVEs (no realloc). (br-frankenpandas utf8-f64-astype)
if target == DType::Float64
&& let Some((bytes, offsets)) = self.as_utf8_contiguous()
{
let n = offsets.len() - 1;
let mut out: Vec<f64> = Vec::with_capacity(n);
let mut ok = true;
for i in 0..n {
let Ok(s) = std::str::from_utf8(&bytes[offsets[i]..offsets[i + 1]]) else {
ok = false;
break;
};
match s.parse::<f64>() {
Ok(v) if !v.is_nan() => out.push(v),
_ => {
ok = false;
break;
}
}
}
if ok {
return Ok(Self::from_f64_values_owned(out));
}
}
// Utf8 -> Int64: sister of the Utf8->Float64 path (astype(int64) on a
// string column was 0.65x pandas via the generic Scalar tail). cast_scalar(
// Utf8(s), Int64) is exactly: try `s.parse::<i64>()`; else `s.parse::<f64>()`
// accepted only when finite, integer-valued, and in i64 range (pandas takes
// "1.0" as int via a float intermediate); else raise. Reproduced verbatim
// here over the contiguous buffer into a typed Vec<i64>. `as_utf8_contiguous`
// is all-valid ⇒ every cell present; any field that fails BOTH parses BAILS
// to the generic Scalar path, which raises the identical InvalidCast. All
// present ⇒ from_i64_values_owned MOVEs. Bit-identical. (br-frankenpandas utf8-i64-astype)
if target == DType::Int64
&& let Some((bytes, offsets)) = self.as_utf8_contiguous()
{
let n = offsets.len() - 1;
let mut out: Vec<i64> = Vec::with_capacity(n);
let mut ok = true;
for i in 0..n {
let Ok(s) = std::str::from_utf8(&bytes[offsets[i]..offsets[i + 1]]) else {
ok = false;
break;
};
if let Ok(v) = s.parse::<i64>() {
out.push(v);
} else if let Ok(f) = s.parse::<f64>()
&& f.is_finite()
&& f.fract() == 0.0
&& f >= i64::MIN as f64
&& f < 9_223_372_036_854_775_808.0
{
out.push(f as i64);
} else {
ok = false;
break;
}
}
if ok {
return Ok(Self::from_i64_values_owned(out));
}
}
// Int64 -> Utf8: hand-rolled decimal itoa straight into a contiguous
// byte buffer (br-frankenpandas-itoa). cast_scalar(Int64(v), Utf8) is
// exactly `v.to_string()` (pandas spells ints plainly — unlike floats
// "1.0" and bools "True"/"False", which this path deliberately does NOT
// take), so `push_i64_decimal` is bit-identical to the Scalar map below
// while skipping the Vec<Scalar::Utf8> + per-row String AND the
// `write!`/`io::Write::write_fmt` Formatter dispatch the prior path paid
// per row. as_i64_slice is all-valid (no null spelling needed).
if target == DType::Utf8
&& let Some(data) = self.as_i64_slice()
{
let mut bytes: Vec<u8> = Vec::with_capacity(data.len() * 4);
let mut offsets: Vec<usize> = Vec::with_capacity(data.len() + 1);
offsets.push(0);
for &v in data {
push_i64_decimal(&mut bytes, v);
offsets.push(bytes.len());
}
return Ok(Self::from_utf8_contiguous(bytes, offsets));
}
// Bool -> Utf8: emit the pandas spellings "True"/"False" straight into a
// contiguous byte buffer. cast_scalar(Bool(b), Utf8) is exactly those two
// (verified by cast_scalar_to_utf8_uses_pandas_string_spellings); all-valid
// (as_bool_slice), bit-identical, skips the Vec<Scalar::Utf8>.
if target == DType::Utf8
&& let Some(data) = self.as_bool_slice()
{
let mut bytes: Vec<u8> = Vec::with_capacity(data.len() * 5);
let mut offsets: Vec<usize> = Vec::with_capacity(data.len() + 1);
offsets.push(0);
for &b in data {
bytes.extend_from_slice(if b { b"True" } else { b"False" });
offsets.push(bytes.len());
}
return Ok(Self::from_utf8_contiguous(bytes, offsets));
}
// Float64 -> Utf8: CALL the exact pandas float formatter
// (`fp_types::float_to_string_for_astype` — the very fn cast_scalar uses,
// so the complex "1.0"/shortest-round-trip/scientific spelling is NOT
// replicated) on each value, extending its bytes into a contiguous
// buffer. Skips the source Scalar::Float64 Vec + the output Scalar::Utf8
// Vec + from_values (the formatter's own String alloc remains).
// Bit-identical. as_f64_slice is all-valid AND no-NaN, so the formatter's
// NaN branch is never reached here (a NaN column declines as_f64_slice and
// takes the Scalar map, which renders "nan"); inf is still handled.
if target == DType::Utf8
&& let Some(data) = self.as_f64_slice()
{
// PARALLEL contiguous-Utf8 build. The serial fallback below is
// CPU-BOUND in the formatter itself (grisu shortest-round-trip
// float->decimal ~12% self-time, core::fmt ~6%, the exponent
// `split_once('e')` scan ~3%), not in the byte copy — so the whole
// per-row format+append is parallelized, output materialization
// included. Each worker formats its own contiguous row range into a
// LOCAL byte buffer plus LOCAL end offsets; the chunks are then
// concatenated in row order with each chunk's offsets shifted by the
// running byte base. Bit-identical to the serial build: same
// formatter on the same values in the same order, so the same bytes
// and the same offsets. (Parallelizing the compute WITHOUT the
// output build would be ~0-gain here, exactly as it was for the
// arg-extrema axis=1 family.)
const PAR_MIN_ROWS: usize = 200_000;
let n = data.len();
let workers = std::thread::available_parallelism()
.map_or(1, std::num::NonZeroUsize::get)
.min(8);
if workers > 1 && n >= PAR_MIN_ROWS {
let chunk = n.div_ceil(workers);
let mut parts: Vec<(Vec<u8>, Vec<usize>)> = (0..n.div_ceil(chunk))
.map(|_| (Vec::new(), Vec::new()))
.collect();
std::thread::scope(|scope| {
for (src, part) in data.chunks(chunk).zip(parts.iter_mut()) {
scope.spawn(move || {
let mut local_bytes: Vec<u8> = Vec::with_capacity(src.len() * 6);
let mut local_ends: Vec<usize> = Vec::with_capacity(src.len());
for &v in src {
local_bytes.extend_from_slice(
fp_types::float_to_string_for_astype(v).as_bytes(),
);
local_ends.push(local_bytes.len());
}
*part = (local_bytes, local_ends);
});
}
});
let total: usize = parts.iter().map(|(b, _)| b.len()).sum();
let mut bytes: Vec<u8> = Vec::with_capacity(total);
let mut offsets: Vec<usize> = Vec::with_capacity(n + 1);
offsets.push(0);
for (local_bytes, local_ends) in &parts {
let base = bytes.len();
bytes.extend_from_slice(local_bytes);
offsets.extend(local_ends.iter().map(|end| end + base));
}
return Ok(Self::from_utf8_contiguous(bytes, offsets));
}
let mut bytes: Vec<u8> = Vec::with_capacity(data.len() * 6);
let mut offsets: Vec<usize> = Vec::with_capacity(data.len() + 1);
offsets.push(0);
for &v in data {
bytes.extend_from_slice(fp_types::float_to_string_for_astype(v).as_bytes());
offsets.push(bytes.len());
}
return Ok(Self::from_utf8_contiguous(bytes, offsets));
}
let out: Vec<Scalar> = self
.values
.iter()
.map(|v| cast_scalar(v, target))
.collect::<Result<Vec<_>, _>>()
.map_err(ColumnError::Type)?;
Self::new(target, out)
}
/// Return the `n` smallest values with explicit keep policy for
/// ties.
///
/// Matches `pd.Series.nsmallest(n, keep=...)`:
/// - `"first"`: take the first `n` rows in ascending order, break
/// ties by original position (stable).
/// - `"last"`: on ties, prefer later-appearing rows.
/// - `"all"`: include every row tied with the `n`-th smallest, so
/// the returned column can exceed `n`.
pub fn nsmallest_keep(&self, n: usize, keep: &str) -> Result<Self, ColumnError> {
nkeep_impl(self, n, keep, true)
}
/// Return the `n` largest values with explicit keep policy for
/// ties.
///
/// Matches `pd.Series.nlargest(n, keep=...)` — see `nsmallest_keep`
/// for the shared semantics.
pub fn nlargest_keep(&self, n: usize, keep: &str) -> Result<Self, ColumnError> {
nkeep_impl(self, n, keep, false)
}
/// Return the `n` largest values.
///
/// Matches `pd.Series.nlargest(n)` with `keep='first'` — ties are
/// broken by first-seen order via a stable descending sort.
/// Missing values are placed at the end of the sorted view and
/// therefore excluded from the top-n when `n` fits within the
/// non-missing count. `n > len()` clamps to the full column.
pub fn nlargest(&self, n: usize) -> Result<Self, ColumnError> {
// Typed bounded top-k scan for small n: O(n) single pass vs a full radix
// sort of the whole column. Bit-identical to `sort_values(false)` (stable:
// ties first-seen) + take. Int64: i64 cmp + position. Float64: the f64
// radix key CANONICALIZES ±0.0 to +0.0 and is stable, so its order ==
// `partial_cmp` (−0.0 == +0.0) + position — exactly `nkeep_typed_f64`.
if (1..=NKEEP_BOUNDED_SCAN_MAX_K).contains(&n) {
if let Some(data) = self.as_i64_slice() {
if n < data.len() {
return Ok(Self::from_i64_values_owned(nkeep_typed_i64(data, n, false)));
}
} else if let Some(data) = self.as_f64_slice() {
if n < data.len() {
return Ok(Self::from_f64_values(nkeep_typed_f64(data, n, false)));
}
} else if !self.has_nulls()
&& let Some(data) = self.as_datetime64_slice()
&& !data.contains(&i64::MIN)
&& n < data.len()
{
// Datetime64 is i64-ns; with the exact Datetime64 comparator,
// sort_values+take == i64 cmp + position. No-NaT (NaT=i64::MIN is
// missing → would sort to the end / be excluded) routes here.
return Ok(Self::from_datetime64_values(nkeep_typed_i64(
data, n, false,
)));
} else if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
// Nullable Int64 (the all-valid `as_i64_slice` arm bailed on the
// missing bit): bounded top-k over the PRESENT subset. Missing
// sorts na-last, so with `n` present values the top-n are all
// present ⇒ all-valid typed output, bit-identical to
// sort_values(false)[..n]. `n < count_valid()` guarantees ≥ n
// present (Int64 missingness is the validity bit alone).
if n < validity.count_valid() {
return Ok(Self::from_i64_values_owned(nkeep_typed_i64_nullable(
data, validity, n, false,
)));
}
} else if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
// Nullable/NaN Float64: present = validity-set AND non-NaN. The
// scan returns up to n present values; if it fills exactly n they
// are the top-n present ⇒ all-valid output. Fewer than n present ⇒
// the na-last result would carry a null tail, so fall through to
// the generic sort (which materializes that tail).
let top = nkeep_typed_f64_nullable(data, validity, n, false);
if top.len() == n {
return Ok(Self::from_f64_values(top));
}
}
}
// Contiguous-Utf8: reuse sort_values' EXACT stable MSD permutation but
// gather ONLY the first `n` rows, avoiding sort_values' full 2N-String
// materialize+clone of every row (`self.values[i].clone()`). Bit-identical:
// `utf8_msd_argsort(&strs, false)` is the same permutation sort_values(false)
// uses, so `perm[..take]` indexes the same `n` largest strings in the same
// order; gathering their spans yields the same `Scalar::Utf8` sequence as
// `sort_values(false).values[..take]`.
if let Some(strs) = self.as_all_valid_str_vec() {
let perm = utf8_msd_argsort(&strs, false);
let take = n.min(perm.len());
let total: usize = perm[..take].iter().map(|&i| strs[i].len()).sum();
let mut new_bytes = Vec::with_capacity(total);
let mut new_offsets = Vec::with_capacity(take + 1);
new_offsets.push(0);
for &i in &perm[..take] {
new_bytes.extend_from_slice(strs[i].as_bytes());
new_offsets.push(new_bytes.len());
}
return Ok(Self::from_utf8_contiguous(new_bytes, new_offsets));
}
let sorted = self.sort_values(false)?;
let take = n.min(sorted.values.len());
let values: Vec<Scalar> = sorted.values[..take].to_vec();
Self::new(self.dtype, values)
}
/// Return the `n` smallest values.
///
/// Matches `pd.Series.nsmallest(n)` with `keep='first'`.
pub fn nsmallest(&self, n: usize) -> Result<Self, ColumnError> {
if (1..=NKEEP_BOUNDED_SCAN_MAX_K).contains(&n) {
if let Some(data) = self.as_i64_slice() {
if n < data.len() {
return Ok(Self::from_i64_values_owned(nkeep_typed_i64(data, n, true)));
}
} else if let Some(data) = self.as_f64_slice() {
if n < data.len() {
return Ok(Self::from_f64_values(nkeep_typed_f64(data, n, true)));
}
} else if !self.has_nulls()
&& let Some(data) = self.as_datetime64_slice()
&& !data.contains(&i64::MIN)
&& n < data.len()
{
return Ok(Self::from_datetime64_values(nkeep_typed_i64(data, n, true)));
} else if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
// Nullable Int64, symmetric to `nlargest` (ascending): bounded
// bottom-k over the present subset. Missing sorts na-last, so with
// `n` present the bottom-n are all present ⇒ all-valid output,
// bit-identical to sort_values(true)[..n].
if n < validity.count_valid() {
return Ok(Self::from_i64_values_owned(nkeep_typed_i64_nullable(
data, validity, n, true,
)));
}
} else if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
// Nullable/NaN Float64, symmetric to `nlargest`.
let bot = nkeep_typed_f64_nullable(data, validity, n, true);
if bot.len() == n {
return Ok(Self::from_f64_values(bot));
}
}
}
// Contiguous-Utf8 (symmetric to `nlargest`): reuse sort_values(true)'s
// ascending MSD permutation, gather only the first `n` spans.
if let Some(strs) = self.as_all_valid_str_vec() {
let perm = utf8_msd_argsort(&strs, true);
let take = n.min(perm.len());
let total: usize = perm[..take].iter().map(|&i| strs[i].len()).sum();
let mut new_bytes = Vec::with_capacity(total);
let mut new_offsets = Vec::with_capacity(take + 1);
new_offsets.push(0);
for &i in &perm[..take] {
new_bytes.extend_from_slice(strs[i].as_bytes());
new_offsets.push(new_bytes.len());
}
return Ok(Self::from_utf8_contiguous(new_bytes, new_offsets));
}
let sorted = self.sort_values(true)?;
let take = n.min(sorted.values.len());
let values: Vec<Scalar> = sorted.values[..take].to_vec();
Self::new(self.dtype, values)
}
/// Replace values where `cond` is true with `other`; otherwise keep.
///
/// Matches `pd.Series.mask(cond, other)` — the logical inverse of
/// `where_cond`. Same validation rules apply.
pub fn mask(&self, cond: &Self, other: &Scalar) -> Result<Self, ColumnError> {
if cond.dtype != DType::Bool {
return Err(ColumnError::InvalidMaskType { dtype: cond.dtype });
}
if self.values.len() != cond.values.len() {
return Err(ColumnError::LengthMismatch {
left: self.values.len(),
right: cond.values.len(),
});
}
// Typed branchless select (inverse of where_cond scalar): cond true picks
// the scalar other, false picks self. Same isomorphism argument.
if !other.is_missing()
&& let Some(cb) = cond.as_bool_slice()
{
if let Some(s) = self.as_f64_slice()
&& let Ok(o) = other.to_f64()
{
let out: Vec<f64> = (0..s.len()).map(|i| if cb[i] { o } else { s[i] }).collect();
return Ok(Self::from_f64_values(out));
}
if let Some(s) = self.as_i64_slice()
&& let Scalar::Int64(o) = other
{
let o = *o;
let out: Vec<i64> = (0..s.len()).map(|i| if cb[i] { o } else { s[i] }).collect();
return Ok(Self::from_i64_values_owned(out));
}
// Nullable Int64 self (all-valid cond) — mirror of the where_cond nullable
// Int64 arm (inverse: cond-true ⇒ other, cond-false ⇒ self). With an
// ALL-VALID cond there is no cond-missing, so the only missing source is a
// cond-false+self-missing slot ⇒ Null(Null) == missing_for_dtype(Int64) in
// both paths. Int64 has no NaN so no NaN/validity ambiguity. (Nullable
// FLOAT64 self is EXCLUDED — a validity-set NaN datum renders present
// Float64(NaN) via from_f64_values but Null(NaN) via Self::new; it keeps the
// generic path.) Bit-identical: cond[i] ? Int64(other) : self[i].
if self.dtype == DType::Int64
&& let Some((sd, sv)) = self.as_i64_slice_with_validity()
&& let Scalar::Int64(o) = other
{
let o = *o;
let mut out = vec![0_i64; sd.len()];
let mut vmask = ValidityMask::all_valid(sd.len());
for i in 0..sd.len() {
if cb[i] {
out[i] = o;
} else if sv.get(i) {
out[i] = sd[i];
} else {
vmask.set(i, false);
}
}
return Ok(Self::from_i64_values_with_validity(out, vmask));
}
// Utf8 self (all-valid OR nullable) + Utf8 other, all-valid cond — inverse of
// the where_cond Utf8 arm: cond-true ⇒ the `other` bytes, cond-false ⇒ the self
// span (present) or a null (self missing). Bit-identical to the loop below
// (cond[i] ? Utf8(other) : self[i]); `self.validity` masks self-missing;
// all-valid cond ⇒ no cond-missing. Ungated (contiguous build vs per-row clones).
if let Scalar::Utf8(o) = other
&& let Some((bytes, offsets)) = self
.as_utf8_contiguous()
.or_else(|| self.as_nullable_utf8_contiguous())
{
let o_bytes = o.as_bytes();
let sv = &self.validity;
let n = offsets.len().saturating_sub(1);
let mut out_bytes: Vec<u8> = Vec::with_capacity(bytes.len());
let mut out_offsets: Vec<usize> = Vec::with_capacity(n + 1);
out_offsets.push(0);
let mut vmask = ValidityMask::all_valid(n);
for i in 0..n {
if cb[i] {
out_bytes.extend_from_slice(o_bytes);
} else if sv.get(i) {
out_bytes.extend_from_slice(&bytes[offsets[i]..offsets[i + 1]]);
} else {
vmask.set(i, false);
}
out_offsets.push(out_bytes.len());
}
return Ok(Self::from_utf8_values_with_validity(
out_bytes,
out_offsets,
vmask,
));
}
// Typed temporal self (all-valid OR nullable) + matching NON-NaT temporal other,
// all-valid cond — inverse of the where_cond temporal arm: cond-true ⇒ the `other`
// ns, cond-false ⇒ self[i] (present ⇒ its ns, missing=`!validity || NaT` ⇒ cleared
// bit). All-valid cond ⇒ the only missing source is cond-false+self-missing.
// Bit-identical to the generic loop (cond[i] ? other : self[i]).
let temporal_other = match (self.dtype, other) {
(DType::Datetime64, Scalar::Datetime64(o)) if *o != Timestamp::NAT => Some(*o),
(DType::Timedelta64, Scalar::Timedelta64(o)) if *o != Timedelta::NAT => Some(*o),
_ => None,
};
if let Some(o) = temporal_other
&& let Some((sd, sv, nat)) = self.temporal_i64_backing()
{
let n = sd.len();
let mut out = vec![0_i64; n];
let mut vmask = ValidityMask::all_valid(n);
for i in 0..n {
if cb[i] {
out[i] = o;
} else if sv.get(i) && sd[i] != nat {
out[i] = sd[i];
} else {
vmask.set(i, false);
}
}
return Ok(if self.dtype == DType::Datetime64 {
Self::from_datetime64_values_with_validity(out, vmask)
} else {
Self::from_timedelta64_values_with_validity(out, vmask)
});
}
}
let out: Vec<Scalar> = self
.values
.iter()
.zip(cond.values.iter())
.map(|(v, c)| match c {
Scalar::Bool(true) => other.clone(),
Scalar::Bool(false) => v.clone(),
_ => Scalar::Null(NullKind::NaN),
})
.collect();
Self::new(self.dtype, out)
}
/// Sort values in ascending or descending order.
///
/// Matches `pd.Series.sort_values(ascending=...)`. Missing values
/// are placed at the end (pandas `na_position='last'` default).
/// Stable sort.
/// Stable sorting permutation for an all-valid numeric column via radix
/// sort over the typed buffer, or `None` when the typed fast path does not
/// apply (non-numeric dtype, or any missing value — those go through the
/// `Scalar` comparator which alone reasons about na-last placement). The
/// permutation is bit-identical to the stable comparator path: monotonic
/// radix keys preserve `<` order and stable counting-sort preserves ties.
/// Borrowed `&str` view of an all-valid Utf8 column, `None` when the
/// column has any missing slot or any non-Utf8 scalar (those need the
/// na-last / mixed-dtype comparator).
fn as_all_valid_str_vec(&self) -> Option<Vec<&str>> {
if self.dtype != DType::Utf8 || !self.validity.all() {
return None;
}
// Contiguous fast path (br-frankenpandas-vecff): when the column
// carries the LazyContiguousUtf8 backing (output of a string op),
// slice each row's &str straight from the byte buffer instead of
// forcing the whole Vec<Scalar> to materialize just to read it.
// Bit-identical: the same &str values in the same order; argsort /
// group keys only ever borrow them.
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
let mut strs = Vec::with_capacity(offsets.len() - 1);
for w in offsets.windows(2) {
strs.push(
std::str::from_utf8(&bytes[w[0]..w[1]])
.expect("contiguous utf8 buffer is valid by construction"),
);
}
return Some(strs);
}
let mut strs = Vec::with_capacity(self.len());
for v in self.values.iter() {
match v {
Scalar::Utf8(s) => strs.push(s.as_str()),
_ => return None,
}
}
Some(strs)
}
fn typed_radix_perm(&self, ascending: bool) -> Option<Vec<usize>> {
if let Some(data) = self.as_i64_slice() {
let keys: Vec<u64> = if ascending {
data.iter().map(|&v| i64_radix_key(v)).collect()
} else {
data.iter().map(|&v| !i64_radix_key(v)).collect()
};
return Some(radix_argsort_u64(&keys));
}
if let Some(data) = self.as_f64_slice() {
let keys: Vec<u64> = if ascending {
data.iter().map(|&v| f64_radix_key(v)).collect()
} else {
data.iter().map(|&v| !f64_radix_key(v)).collect()
};
return Some(radix_argsort_u64(&keys));
}
// Nullable Int64: na-last radix (the all-valid `as_i64_slice` arm above
// bailed on the missing bit, so a nullable Int64 column fell to the
// O(n log n) Scalar comparator). `compare_scalars_na_last` sorts every
// MISSING slot to the END regardless of direction (Equal among themselves ⇒
// original order), and the PRESENT values by i64 order (reversed for
// descending). Reproduce it: radix-sort the present subset by the SAME
// i64_radix_key the all-valid arm uses (LSD radix is stable ⇒ present ties
// keep original order), map back to original indices, then append the
// missing indices in original order. Bit-identical to the stable Scalar
// na-last sort. Int64 has no NaN, so present keys are exact. Gated on Int64
// dtype so Datetime/Timedelta (whose i64::MIN NAT would radix-sort FIRST,
// not last) keep the Scalar route below.
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let n = data.len();
let mut present_keys: Vec<u64> = Vec::with_capacity(n);
let mut present_idx: Vec<usize> = Vec::with_capacity(n);
let mut missing_idx: Vec<usize> = Vec::new();
for i in 0..n {
if validity.get(i) {
let key = i64_radix_key(data[i]);
present_keys.push(if ascending { key } else { !key });
present_idx.push(i);
} else {
missing_idx.push(i);
}
}
let perm = radix_argsort_u64(&present_keys);
let mut out = Vec::with_capacity(n);
for &p in &perm {
out.push(present_idx[p]);
}
out.extend(missing_idx);
return Some(out);
}
// Nullable / NaN-bearing Float64: na-last radix mirroring the Int64 arm. A
// slot is "present" iff validity-set AND non-NaN — `compare_scalars_na_last`
// treats a present `Float64(NaN)` as missing (`Scalar::is_missing` is true
// for NaN) too, so a NaN slot joins the na-last group (which sorts Equal ⇒
// original order) rather than sorting by NaN's radix key. Present finite/inf
// sort by the SAME `f64_radix_key` the all-valid arm uses (`-0.0` ties `+0.0`
// via partial_cmp; reversed for descending). Bit-identical to the stable
// Scalar na-last comparator. (The all-valid, no-NaN Float64 arm above fires
// first, so this only sees nullable OR NaN-bearing columns. Unlike the
// multi-key `typed_radix_keys` — which returns None on any NaN because its
// comparator treats NaN as compare-Equal, not na-last — single-key sort's
// na-last semantics ARE reproducible here.)
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let n = data.len();
let mut present_keys: Vec<u64> = Vec::with_capacity(n);
let mut present_idx: Vec<usize> = Vec::with_capacity(n);
let mut missing_idx: Vec<usize> = Vec::new();
for i in 0..n {
if validity.get(i) && !data[i].is_nan() {
let key = f64_radix_key(data[i]);
present_keys.push(if ascending { key } else { !key });
present_idx.push(i);
} else {
missing_idx.push(i);
}
}
let perm = radix_argsort_u64(&present_keys);
let mut out = Vec::with_capacity(n);
for &p in &perm {
out.push(present_idx[p]);
}
out.extend(missing_idx);
return Some(out);
}
// Datetime64 / Timedelta64 store i64 nanoseconds that sort identically to
// Int64, so route them through the same radix. Gated on all-valid + no NAT:
// the NAT sentinel is `i64::MIN`, which the radix would sort FIRST but the
// `Scalar` na-last comparator sorts LAST, so any NAT-bearing column stays on
// the Scalar route. For all-valid, no-NAT input the stable ascending-i64
// permutation is bit-identical to the `Scalar` comparison sort (the same
// guarantee the Int64 branch above already relies on).
if self.validity.all()
&& let Some(data) = self
.as_datetime64_slice()
.or_else(|| self.as_timedelta64_slice())
&& !data.contains(&i64::MIN)
{
let keys: Vec<u64> = if ascending {
data.iter().map(|&v| i64_radix_key(v)).collect()
} else {
data.iter().map(|&v| !i64_radix_key(v)).collect()
};
return Some(radix_argsort_u64(&keys));
}
// Nullable / NaT-bearing Datetime64 & Timedelta64: na-last radix (the
// all-valid no-NAT arm above bailed). Both store i64 ns sorting as i64, and
// both use i64::MIN as the NaT sentinel — is_missing(Datetime64/Timedelta64
// (v)) == (v == i64::MIN) — so a slot is na-last iff validity-clear OR its
// datum is the NaT sentinel (mirroring the Float64 `!is_nan` split). Present
// slots sort by i64_radix_key (ns order, reversed for descending); missing/
// NaT indices append in original order. Bit-identical to the stable Scalar
// na-last comparator. The buffer accessor also reaches the LazyNullable*
// backing (as_datetime64_slice only exposes the all-valid backings).
let temporal_ns: Option<&[i64]> = match self.dtype {
DType::Datetime64 => self.as_datetime64_slice().or_else(|| match &self.values {
ScalarValues::LazyNullableDatetime64 { data, .. } => Some(data.as_slice()),
_ => None,
}),
DType::Timedelta64 => self.as_timedelta64_slice().or_else(|| match &self.values {
ScalarValues::LazyNullableTimedelta64 { data, .. } => Some(data.as_slice()),
_ => None,
}),
_ => None,
};
if let Some(data) = temporal_ns {
let n = data.len();
let mut present_keys: Vec<u64> = Vec::with_capacity(n);
let mut present_idx: Vec<usize> = Vec::with_capacity(n);
let mut missing_idx: Vec<usize> = Vec::new();
for i in 0..n {
if self.validity.get(i) && data[i] != i64::MIN {
let key = i64_radix_key(data[i]);
present_keys.push(if ascending { key } else { !key });
present_idx.push(i);
} else {
missing_idx.push(i);
}
}
let perm = radix_argsort_u64(&present_keys);
let mut out = Vec::with_capacity(n);
for &p in &perm {
out.push(present_idx[p]);
}
out.extend(missing_idx);
return Some(out);
}
None
}
/// Order-preserving `u64` radix keys for this column (per-column ascending/
/// descending baked in), for the multi-key lexsort
/// (`radix_argsort_multi_u64`, br-frankenpandas-lnsu6). `Some` only for an
/// all-valid Int64 or all-valid **no-NaN** Float64 column — the cases where
/// the radix order is bit-identical to the stable comparator: Int64 `cmp`,
/// finite-Float64 `partial_cmp` (`-0.0` normalized to `+0.0`). A Float64
/// column with any NaN returns `None` so the caller keeps the `Scalar`
/// comparator (which, in the multi-key path, treats `NaN` as compare-Equal —
/// a semantics the monotonic radix key cannot reproduce).
#[must_use]
pub fn typed_radix_keys(&self, ascending: bool) -> Option<Vec<u64>> {
if let Some(data) = self.as_i64_slice() {
return Some(if ascending {
data.iter().map(|&v| i64_radix_key(v)).collect()
} else {
data.iter().map(|&v| !i64_radix_key(v)).collect()
});
}
if let Some(data) = self.as_f64_slice() {
if data.iter().any(|x| x.is_nan()) {
return None;
}
return Some(if ascending {
data.iter().map(|&v| f64_radix_key(v)).collect()
} else {
data.iter().map(|&v| !f64_radix_key(v)).collect()
});
}
None
}
pub fn sort_values(&self, ascending: bool) -> Result<Self, ColumnError> {
// Typed radix fast path: all-valid Int64/Float64 columns sort their
// contiguous buffer comparison-free, then re-ingest typed (no 32B
// Scalar clone or enum-match per comparison).
if let Some(data) = self.as_i64_slice() {
// Direct VALUE radix (no perm, no gather) — bit-identical sorted
// values, far faster than argsort+gather for sort_values.
return Ok(Self::from_i64_values_owned(radix_sort_i64_values(
data, ascending,
)));
}
if let Some(data) = self.as_f64_slice() {
let perm = self
.typed_radix_perm(ascending)
.expect("f64 slice yields perm");
let sorted: Vec<f64> = perm.iter().map(|&i| data[i]).collect();
return Ok(Self::from_f64_values(sorted));
}
// Datetime64 with NO NaT (i64::MIN): direct VALUE radix over the ns (no
// gather — the prior argsort+gather attempt was gather-bound). Bit-identical
// to the generic exact-Datetime64-comparator sort (equal ns indistinguishable).
// NaT is missing → must sort to the END, so NaT-bearing columns fall through.
if !self.has_nulls()
&& let Some(data) = self.as_datetime64_slice()
&& !data.contains(&i64::MIN)
{
return Ok(Self::from_datetime64_values(radix_sort_i64_values(
data, ascending,
)));
}
// All-valid Utf8: gather by the stable MSD radix permutation. The
// fallback below sorts (idx, &Scalar) pairs stably with the same
// ordering, so cloning in permutation order yields the identical
// value sequence.
if let Some(strs) = self.as_all_valid_str_vec() {
let perm = utf8_msd_argsort(&strs, ascending);
let sorted: Vec<Scalar> = perm.iter().map(|&i| self.values[i].clone()).collect();
return Self::new(self.dtype, sorted);
}
// Nullable contiguous-Utf8 (`LazyNullableUtf8`): the all-valid Utf8 arm above
// bailed on the missing bit and `typed_radix_perm` is numeric-only, so a nullable
// string column fell to the O(n log n) na-last Scalar comparator below, which
// materializes a `Vec<Scalar::Utf8>` (one heap `String` per row) AND clones a
// `String` per output row. Sort the PRESENT rows with the stable MSD byte radix
// (`utf8_msd_argsort_bytes` — byte order == `String::cmp` == the Utf8 arm of
// `compare_scalars_na_last` for valid UTF-8), then gather the sorted present spans
// into ONE contiguous byte buffer followed by the missing rows (na-last). Zero
// per-row `String` alloc on either input or output. Bit-identical to the comparator
// fallback: present values sort ascending/descending exactly as
// `compare_scalars_na_last(.., ascending)` orders two Utf8 (byte-lexicographic),
// stable ties keep original order (radix is stable; missing kept in original order
// in the na-last suffix), and `from_utf8_values_with_validity` materializes a
// present slot as `Scalar::Utf8(span)` and a missing slot as
// `Null(Null) == missing_for_dtype(Utf8)` — exactly the comparator path's clone of
// a sorted present value / a na-last `Null(Null)`.
if let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
..
} = &self.values
{
let n = offsets.len().saturating_sub(1);
let present_idx: Vec<usize> = (0..n).filter(|&i| validity.get(i)).collect();
let present_count = present_idx.len();
let present_spans: Vec<&[u8]> = present_idx
.iter()
.map(|&i| &bytes[offsets[i]..offsets[i + 1]])
.collect();
let sub = utf8_msd_argsort_bytes(&present_spans, ascending);
let mut out_bytes: Vec<u8> = Vec::with_capacity(bytes.len());
let mut out_offsets: Vec<usize> = Vec::with_capacity(n + 1);
out_offsets.push(0);
let mut out_valid = ValidityMask::all_valid(n);
for &p in &sub {
out_bytes.extend_from_slice(present_spans[p]);
out_offsets.push(out_bytes.len());
}
// na-last suffix: the missing rows — empty spans, validity cleared.
for j in present_count..n {
out_offsets.push(out_bytes.len());
out_valid.set(j, false);
}
return Ok(Self::from_utf8_values_with_validity(
out_bytes,
out_offsets,
out_valid,
));
}
// Nullable / NaN / NaT typed columns (Int64, Float64, Datetime64,
// Timedelta64): the all-valid radix arms above bailed on the missing bit,
// so these fell to the O(n log n) na-last Scalar comparator below.
// `typed_radix_perm` already reproduces that EXACT na-last order in O(n) —
// it is the permutation behind the nullable `argsort`, proven bit-identical
// to the stable `compare_scalars_na_last` sort (its per-dtype na-last splits
// are asserted against that comparator in the nullable-sort tests). `Some`
// here implies a nullable/NaN/NaT typed column (the all-valid variants
// returned earlier), so no all-valid column is rerouted.
if let Some(perm) = self.typed_radix_perm(ascending) {
// Typed gather for the two hot lazy-nullable numeric backings: rebuild
// the sorted column straight from the raw (datum, validity) pairs
// permuted by `perm`, skipping the source's Vec<Scalar> materialize and
// the n 32-byte Scalar clones the fallthrough pays. `from_*_with_validity`
// rebuilds the SAME variant with the SAME per-slot materialization rule
// (LazyNullableInt64: valid⇒Int64 else Null(Null); LazyNullableFloat64:
// valid|NaN⇒Float64 else Null(NaN)), and I copy (datum, validity)
// verbatim, so slot j materializes exactly as source slot perm[j] — i.e.
// bit-identical to cloning self.values[perm[j]] (incl. every NaN/±0/Null
// edge). Gated on the concrete variant so any other nullable
// representation keeps the still-bit-identical scalar gather below.
match &self.values {
ScalarValues::LazyNullableInt64 { data, validity, .. } => {
let mut out = Vec::with_capacity(perm.len());
let mut out_valid = ValidityMask::all_valid(perm.len());
for (j, &i) in perm.iter().enumerate() {
out.push(data[i]);
if !validity.get(i) {
out_valid.set(j, false);
}
}
return Ok(Self::from_i64_values_with_validity(out, out_valid));
}
ScalarValues::LazyNullableFloat64 { data, validity, .. } => {
let mut out = Vec::with_capacity(perm.len());
let mut out_valid = ValidityMask::all_valid(perm.len());
for (j, &i) in perm.iter().enumerate() {
out.push(data[i]);
if !validity.get(i) {
out_valid.set(j, false);
}
}
return Ok(Self::from_f64_values_with_validity(out, out_valid));
}
// Temporal (Datetime64/Timedelta64) & any other nullable backing:
// clone the source's own scalars in permutation order — identical
// gather to the fallthrough, only the comparison sort is replaced.
// NOTE: a typed gather (rebuild via from_datetime64/timedelta64_
// values_with_validity) IS bit-identical here (those variants and the
// constructors share the pure-validity materialization rule, so
// present-NaT round-trips), but it is NOT a win: temporal already has
// the radix order on this path, so the change would only trade the
// Scalar-clone gather for a typed one — and when the output is
// materialized back to scalars (the common case) that rebuilds the
// Scalar Vec anyway PLUS an extra i64 buffer, measuring 0.86-1.14x
// (a wash / slight regression). See negative-ledger note.
_ => {
let src = self.values.as_slice();
let sorted: Vec<Scalar> = perm.iter().map(|&i| src[i].clone()).collect();
return Self::new(self.dtype, sorted);
}
}
}
let mut indexed: Vec<(usize, &Scalar)> = self.values.iter().enumerate().collect();
indexed.sort_by(|a, b| compare_scalars_na_last(a.1, b.1, ascending));
let sorted: Vec<Scalar> = indexed.into_iter().map(|(_, v)| v.clone()).collect();
Self::new(self.dtype, sorted)
}
/// Positions that would sort the column ascending.
///
/// Matches `pd.Series.argsort()`. Returns a `Vec<usize>` such that
/// `take(&argsort)` equals `sort_values(true)`. Missing values
/// sort to the end; stable.
#[must_use]
pub fn argsort(&self) -> Vec<usize> {
self.argsort_with(true)
}
/// Stable sorting permutation in either direction. Uses the typed radix
/// fast path for all-valid Int64/Float64 columns (comparison-free) and the
/// `Scalar` na-last comparator otherwise. `take(&argsort_with(asc))` equals
/// `sort_values(asc)`. Missing values sort to the end regardless of `asc`.
#[must_use]
pub fn argsort_with(&self, ascending: bool) -> Vec<usize> {
if let Some(perm) = self.typed_radix_perm(ascending) {
return perm;
}
// All-valid contiguous Utf8: feed the MSD byte radix the raw `&[u8]`
// row spans straight from the backing buffer, skipping the `Vec<&str>`
// build + per-row `from_utf8` re-validation (the bytes are valid UTF-8
// by construction) and the radix's own `&str -> &[u8]` remap. Byte order
// == UTF-8 lexicographic order, so the permutation is identical.
if self.validity.all()
&& let Some((bytes, offsets)) = self.as_utf8_contiguous()
{
let spans: Vec<&[u8]> = offsets.windows(2).map(|w| &bytes[w[0]..w[1]]).collect();
return utf8_msd_argsort_bytes(&spans, ascending);
}
// All-valid Utf8 (non-contiguous backing): stable MSD byte radix replaces
// the O(n log n) Scalar-comparator sort. Bit-identical — `String::cmp` is
// exactly byte order with shorter-prefix-first, no value is missing (so
// the na-last arms never fire), and both sorts are stable.
if let Some(strs) = self.as_all_valid_str_vec() {
return utf8_msd_argsort(&strs, ascending);
}
// Nullable contiguous Utf8 (`LazyNullableUtf8`): the all-valid Utf8 arms above
// bail on the missing bit, so a nullable string key fell to the O(n log n) na-last
// `Scalar` comparator. Radix-sort the PRESENT spans (`utf8_msd_argsort_bytes` —
// byte order == the Utf8 arm of `compare_scalars_na_last`), map to original row
// indices, then append the missing rows in original order (na-last). Bit-identical
// to the stable comparator: present rows sort asc/desc with stable ties (the radix
// is stable and present_idx is ascending original order), and missing rows keep
// their original relative order in the na-last suffix. Backs Series/DataFrame
// `sort_values`/`sort_index`/`argsort` on a nullable string column (all route
// through `argsort_with`, not `Column::sort_values`).
if let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
..
} = &self.values
{
let n = offsets.len().saturating_sub(1);
let present_idx: Vec<usize> = (0..n).filter(|&i| validity.get(i)).collect();
let present_spans: Vec<&[u8]> = present_idx
.iter()
.map(|&i| &bytes[offsets[i]..offsets[i + 1]])
.collect();
let sub = utf8_msd_argsort_bytes(&present_spans, ascending);
let mut perm: Vec<usize> = Vec::with_capacity(n);
perm.extend(sub.iter().map(|&p| present_idx[p]));
perm.extend((0..n).filter(|&i| !validity.get(i)));
return perm;
}
let mut indexed: Vec<(usize, &Scalar)> = self.values.iter().enumerate().collect();
indexed.sort_by(|a, b| compare_scalars_na_last(a.1, b.1, ascending));
indexed.into_iter().map(|(i, _)| i).collect()
}
/// Return indices that partition the array around kth element.
///
/// Matches np.argpartition(). After partition, element at kth position
/// is in its sorted position, elements before are <= kth element,
/// elements after are >= kth element.
pub fn argpartition(&self, kth: usize) -> Result<Vec<usize>, ColumnError> {
if kth >= self.len() {
return Err(ColumnError::InvalidLength {
operation: "argpartition",
expected: kth + 1,
actual: self.len(),
});
}
let mut indexed: Vec<(usize, &Scalar)> = self.values.iter().enumerate().collect();
indexed.select_nth_unstable_by(kth, |a, b| compare_scalars_na_last(a.1, b.1, true));
Ok(indexed.into_iter().map(|(i, _)| i).collect())
}
/// Partition array around kth smallest element.
///
/// Matches np.partition(). Returns a partially sorted array where
/// element at kth position is in its final sorted position.
pub fn partition(&self, kth: usize) -> Result<Self, ColumnError> {
let indices = self.argpartition(kth)?;
let out: Vec<Scalar> = indices.iter().map(|&i| self.values[i].clone()).collect();
Self::new(self.dtype, out)
}
/// First-order difference: `values[i] - values[i - periods]`.
///
/// Matches `pd.Series.diff(periods)`. The leading `|periods|`
/// positions are Null(NaN). Negative periods compute
/// `values[i] - values[i + |periods|]`. Non-numeric inputs return
/// a type error. Result dtype is always Float64.
pub fn diff(&self, periods: i64) -> Result<Self, ColumnError> {
let len = self.values.len();
// Per br-frankenpandas-e607u: Timedelta64 diff preserves dtype
// matching pandas, instead of forcing Float64 output and NaN-ing
// via the to_f64-else catch-all.
// Per pandas 2.2.3: Bool.diff() is XOR (cur != prev), yielding a bool
// result with a missing leading element — NOT numeric subtraction
// (older pandas gave [-1, 0, 1]). Timedelta64 keeps its dtype; all other
// numeric types diff as Float64.
let out_dtype = match self.dtype {
DType::Timedelta64 => DType::Timedelta64,
DType::Bool => DType::Bool,
_ => DType::Float64,
};
if len == 0 || periods == 0 {
let null = if out_dtype == DType::Timedelta64 {
Scalar::Null(NullKind::NaT)
} else {
Scalar::Null(NullKind::NaN)
};
return Self::new(out_dtype, vec![null; len]);
}
let abs = periods.unsigned_abs() as usize;
// Typed Float64-output fast paths (i64 / f64 inputs): fill an f64 body
// buffer, mark the vacated boundary as a single invalid range, and MOVE it
// into a LazyNullableFloat64 backing via from_f64_values_with_validity (no
// NaN scan, no Arc::from realloc). Bit-identical to the Scalar loop: that
// backing materializes a valid slot as Float64(a−b) and an invalid slot as
// Null(NaN) — exactly the body and the boundary `null_scalar` below. (The
// OWNED-with-validity ctor cannot be used: its backing is all-valid and
// ignores a partial mask — see NEGATIVE_EVIDENCE.)
if abs < len {
// Leading (periods>0) or trailing (periods<0) `abs` slots are vacated.
let boundary: (usize, usize) = if periods > 0 {
(0, abs)
} else {
(len - abs, abs)
};
let validity = ValidityMask::from_invalid_ranges(
Arc::from(vec![boundary].into_boxed_slice()),
len,
);
// Int64: (x as f64) − (y as f64) is always finite (|i64 as f64| ≤ 9.2e18,
// difference ≤ 1.8e19) so the body carries no NaN.
if let Some(data) = self.as_i64_slice() {
let mut out = vec![0.0_f64; len];
if periods > 0 {
for i in abs..len {
out[i] = data[i] as f64 - data[i - abs] as f64;
}
} else {
for i in 0..len - abs {
out[i] = data[i] as f64 - data[i + abs] as f64;
}
}
return Ok(Self::from_f64_values_with_validity(out, validity));
}
// Float64: only safe when inf-free — finite−finite is never NaN (only
// finite or an overflow ±inf, both valid). An inf INPUT could yield
// inf−inf = NaN at a VALID slot, which LazyNullableFloat64 keeps as
// Float64(NaN) rather than the Scalar path's Null — so inf-bearing
// columns fall to the Scalar path. `as_f64_slice` is already NaN-free.
if let Some(data) = self.as_f64_slice()
&& data.iter().all(|x| x.is_finite())
{
let mut out = vec![0.0_f64; len];
if periods > 0 {
for i in abs..len {
out[i] = data[i] - data[i - abs];
}
} else {
for i in 0..len - abs {
out[i] = data[i] - data[i + abs];
}
}
return Ok(Self::from_f64_values_with_validity(out, validity));
}
}
let mut out: Vec<Scalar> = Vec::with_capacity(len);
let null_scalar = if out_dtype == DType::Timedelta64 {
Scalar::Null(NullKind::NaT)
} else {
Scalar::Null(NullKind::NaN)
};
for i in 0..len {
if (periods > 0 && i < abs) || (periods < 0 && i + abs >= len) {
out.push(null_scalar.clone());
continue;
}
let (cur, prev) = if periods > 0 {
(&self.values[i], &self.values[i - abs])
} else {
(&self.values[i], &self.values[i + abs])
};
if cur.is_missing() || prev.is_missing() {
out.push(null_scalar.clone());
continue;
}
if let (Scalar::Timedelta64(cur_ns), Scalar::Timedelta64(prev_ns)) = (cur, prev) {
if *cur_ns == Timedelta::NAT || *prev_ns == Timedelta::NAT {
out.push(Scalar::Null(NullKind::NaT));
} else {
out.push(Scalar::Timedelta64(cur_ns.saturating_sub(*prev_ns)));
}
continue;
}
if let (Scalar::Bool(cur_b), Scalar::Bool(prev_b)) = (cur, prev) {
// pandas 2.2.3 Bool.diff() == (cur XOR prev).
out.push(Scalar::Bool(cur_b != prev_b));
continue;
}
match (cur.to_f64(), prev.to_f64()) {
(Ok(a), Ok(b)) => out.push(Scalar::Float64(a - b)),
_ => out.push(Scalar::Null(NullKind::NaN)),
}
}
Self::new(out_dtype, out)
}
/// Consecutive differences with optional prepend/append values.
///
/// Matches np.ediff1d(). Prepend/append scalars are added at boundaries.
pub fn ediff1d(
&self,
to_begin: Option<Scalar>,
to_end: Option<Scalar>,
) -> Result<Self, ColumnError> {
let mut out = Vec::new();
if let Some(v) = to_begin {
out.push(v);
}
for i in 1..self.values.len() {
let cur = &self.values[i];
let prev = &self.values[i - 1];
if cur.is_missing() || prev.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let cf = cur.to_f64().map_err(ColumnError::Type)?;
let pf = prev.to_f64().map_err(ColumnError::Type)?;
out.push(Scalar::Float64(cf - pf));
}
if let Some(v) = to_end {
out.push(v);
}
Self::new(DType::Float64, out)
}
/// Numerical gradient using central differences.
///
/// Matches np.gradient() with uniform spacing.
pub fn gradient(&self) -> Result<Self, ColumnError> {
let n = self.values.len();
if n == 0 {
return Self::new(DType::Float64, Vec::new());
}
if n == 1 {
return Self::new(DType::Float64, vec![Scalar::Float64(0.0)]);
}
let vals: Vec<f64> = self
.values
.iter()
.map(|v| v.to_f64().unwrap_or(f64::NAN))
.collect();
let mut out = Vec::with_capacity(n);
out.push(Scalar::Float64(vals[1] - vals[0]));
for i in 1..n - 1 {
out.push(Scalar::Float64((vals[i + 1] - vals[i - 1]) / 2.0));
}
out.push(Scalar::Float64(vals[n - 1] - vals[n - 2]));
Self::new(DType::Float64, out)
}
/// Trapezoidal numerical integration.
///
/// Matches np.trapz(). Returns scalar result of integral.
pub fn trapz(&self, dx: f64) -> Result<Scalar, ColumnError> {
let n = self.values.len();
if n < 2 {
return Ok(Scalar::Float64(0.0));
}
if let Some(vals) = self.as_f64_slice() {
let mut sum = 0.0;
for i in 1..n {
sum += (vals[i - 1] + vals[i]) / 2.0 * dx;
}
return Ok(Scalar::Float64(sum));
}
let vals: Vec<f64> = self
.values
.iter()
.map(|v| v.to_f64().unwrap_or(0.0))
.collect();
let mut sum = 0.0;
for i in 1..n {
sum += (vals[i - 1] + vals[i]) / 2.0 * dx;
}
Ok(Scalar::Float64(sum))
}
/// Per-row boolean flag for duplicated values (keep='first').
///
/// Matches `pd.Series.duplicated()` — all but the first occurrence
/// of each value is flagged true. Missing values are treated as a
/// single bucket (pandas equates NaN for this purpose).
pub fn duplicated(&self) -> Result<Self, ColumnError> {
self.duplicated_keep("first")
}
/// Per-row boolean flag for duplicated values with explicit keep policy.
///
/// Matches `pd.Series.duplicated(keep=...)`. Supported policies
/// are `"first"`, `"last"`, and `"false"` / `"none"` for pandas
/// `keep=False`.
pub fn duplicated_keep(&self, keep: &str) -> Result<Self, ColumnError> {
#[derive(Hash, PartialEq, Eq)]
enum Key<'a> {
Null,
Bool(bool),
Int64(i64),
FloatBits(u64),
Utf8(&'a str),
Timedelta64(i64),
Datetime64(i64),
Period(i64),
Interval(u64, u64, IntervalClosed),
}
fn key_of(v: &Scalar) -> Key<'_> {
if v.is_missing() {
return Key::Null;
}
match v {
Scalar::Bool(b) => Key::Bool(*b),
Scalar::Int64(i) => Key::Int64(*i),
Scalar::Float64(f) => {
let norm = if *f == 0.0 { 0.0 } else { *f };
Key::FloatBits(norm.to_bits())
}
Scalar::Utf8(s) => Key::Utf8(s.as_str()),
Scalar::Timedelta64(v) => Key::Timedelta64(*v),
Scalar::Datetime64(v) => Key::Datetime64(*v),
Scalar::Period(p) => Key::Period(p.ordinal),
Scalar::Interval(v) => {
let (left, right, closed) = interval_key(v);
Key::Interval(left, right, closed)
}
Scalar::Null(_) => Key::Null,
}
}
let policy = match keep {
"first" => DupPolicy::First,
"last" => DupPolicy::Last,
"false" | "False" | "none" => DupPolicy::None,
other => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: other.to_string(),
dtype: self.dtype,
}));
}
};
// Typed fast paths: all-valid Int64/Float64 hash their contiguous
// buffer directly with FxHash, skipping the per-value `Key` enum and
// SipHash. `as_*_slice` only yields all-valid buffers, so the `Null`
// bucket never arises; Float64 normalizes -0.0→+0.0 before `to_bits`
// exactly as `key_of` does, keeping dedup semantics bit-identical.
if let Some(data) = self.as_i64_slice() {
// Bounded value span → hash-free direct-address table (O(n), no
// probing); otherwise the FxHash typed set.
if let Some((min, range)) = i64_direct_address_range(data) {
return Ok(Self::from_bool_values(duplicated_flags_i64_direct(
data, min, range, policy,
)));
}
// Wide/sparse: the default "first" policy uses the open-addressing set
// (beats FxHashSet on high-card wide i64); last/none keep FxHashSet.
if matches!(policy, DupPolicy::First) {
return Ok(Self::from_bool_values(duplicated_first_i64_wide(data)));
}
return Ok(Self::from_bool_values(duplicated_flags_typed(data, policy)));
}
// Nullable Int64, "first" policy (the default of `duplicated()` / `drop_duplicates()`
// — by far the hottest case): the all-valid `as_i64_slice` arm above bails on ANY
// missing, so a nullable Int64 column fell to the generic `Vec<Scalar>` + `key_of` +
// `Key`-hashset scan. Scan the raw `&[i64]` + validity: a PRESENT value is a duplicate
// iff its i64 was seen earlier (FxHashSet<i64>); a MISSING value is a duplicate iff any
// earlier row was also missing (single `seen_null` bucket == the generic grouping all
// missing under `Key::Null`). Output all-valid Bool. Bit-identical to the generic
// "first" pass. The reverse-scan "last" and keep=False siblings follow below.
if matches!(policy, DupPolicy::First)
&& self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut seen: FxHashSet<i64> = FxHashSet::default();
let mut seen_null = false;
let out: Vec<bool> = (0..data.len())
.map(|i| {
if validity.get(i) {
!seen.insert(data[i])
} else {
let dup = seen_null;
seen_null = true;
dup
}
})
.collect();
return Ok(Self::from_bool_values(out));
}
// Nullable Int64, "last" policy: mirror the typed first-seen scan above
// in reverse. Present values share their raw i64 bucket, while every
// missing row shares one null bucket, exactly as the generic Key scan.
if matches!(policy, DupPolicy::Last)
&& self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut seen: FxHashSet<i64> = FxHashSet::default();
let mut seen_null = false;
let mut out = vec![false; data.len()];
for idx in (0..data.len()).rev() {
out[idx] = if validity.get(idx) {
!seen.insert(data[idx])
} else {
let dup = seen_null;
seen_null = true;
dup
};
}
return Ok(Self::from_bool_values(out));
}
// Nullable Int64, keep=False: find repeated PRESENT values with raw i64
// sets and track the shared missing bucket separately, then flag every
// occurrence in a second raw scan. This mirrors the generic two-set Key
// path without materializing `Vec<Scalar>` or hashing the Key enum.
if matches!(policy, DupPolicy::None)
&& self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut seen_once: FxHashSet<i64> = FxHashSet::default();
let mut seen_multiple: FxHashSet<i64> = FxHashSet::default();
let mut seen_null = false;
let mut repeated_null = false;
for (idx, &value) in data.iter().enumerate() {
if validity.get(idx) {
if !seen_once.insert(value) {
seen_multiple.insert(value);
}
} else if seen_null {
repeated_null = true;
} else {
seen_null = true;
}
}
let out = data
.iter()
.enumerate()
.map(|(idx, value)| {
if validity.get(idx) {
seen_multiple.contains(value)
} else {
repeated_null
}
})
.collect();
return Ok(Self::from_bool_values(out));
}
// Datetime64 / Timedelta64 (i64-ns-backed): an all-valid, no-NaT column
// reuses the Int64 duplicate-flag machinery over the raw ns. The Bool
// output is dtype-independent (no re-tag). Bit-identical to the generic
// `Key` path: a non-NaT temporal value's key is its ns, and the i64 dedup
// produces the same first/last/none flags. NaT (`i64::MIN`) / nullable
// falls through (the generic path groups all missing under `Key::Null`).
// Mirrors the same routing already used by `unique`/`value_counts`.
if !self.has_nulls()
&& let Some(data) = self
.as_datetime64_slice()
.or_else(|| self.as_timedelta64_slice())
&& !data.contains(&i64::MIN)
{
if let Some((min, range)) = i64_direct_address_range(data) {
return Ok(Self::from_bool_values(duplicated_flags_i64_direct(
data, min, range, policy,
)));
}
if matches!(policy, DupPolicy::First) {
return Ok(Self::from_bool_values(duplicated_first_i64_wide(data)));
}
return Ok(Self::from_bool_values(duplicated_flags_typed(data, policy)));
}
if let Some(data) = self.as_f64_slice() {
let keys: Vec<u64> = data
.iter()
.map(|&f| (if f == 0.0 { 0.0 } else { f }).to_bits())
.collect();
return Ok(Self::from_bool_values(duplicated_flags_typed(
&keys, policy,
)));
}
// Contiguous-Utf8 fast path (cardinality-vein sibling of
// unique/value_counts/nunique/mode): the generic loops below iterate
// `&self.values`, forcing `as_slice()` to materialize a `Vec<Scalar::Utf8>`
// -- one heap `String` per row -- then key each by `Key::Utf8(&str)`.
// Compute the duplicate flags directly over `&[u8]` byte spans
// (byte-equality is exactly `&str`-equality for valid UTF-8) with ZERO
// per-row `String` alloc. `as_utf8_contiguous` matches only an all-valid
// backing, so the `Key::Null` bucket never arises -- bit-identical to the
// generic `Key` path for every policy. Also speeds `drop_duplicates`,
// which is `duplicated_keep` + a filter.
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
let n = offsets.len().saturating_sub(1);
let mut flags = vec![false; n];
match policy {
DupPolicy::First => {
let mut seen: FxHashSet<&[u8]> = FxHashSet::default();
for (idx, flag) in flags.iter_mut().enumerate() {
*flag = !seen.insert(&bytes[offsets[idx]..offsets[idx + 1]]);
}
}
DupPolicy::Last => {
let mut seen: FxHashSet<&[u8]> = FxHashSet::default();
for idx in (0..n).rev() {
flags[idx] = !seen.insert(&bytes[offsets[idx]..offsets[idx + 1]]);
}
}
DupPolicy::None => {
let mut seen_once: FxHashSet<&[u8]> = FxHashSet::default();
let mut seen_multiple: FxHashSet<&[u8]> = FxHashSet::default();
for idx in 0..n {
let span = &bytes[offsets[idx]..offsets[idx + 1]];
if !seen_once.insert(span) {
seen_multiple.insert(span);
}
}
for (idx, flag) in flags.iter_mut().enumerate() {
*flag = seen_multiple.contains(&bytes[offsets[idx]..offsets[idx + 1]]);
}
}
}
return Ok(Self::from_bool_values(flags));
}
// Nullable contiguous-Utf8 fast path (COLD cache): the all-valid arm above gates
// on `as_utf8_contiguous` (validity.all()), so a `LazyNullableUtf8` column — a
// string column WITH missing rows — fell to the generic `Key`-keyed loops below,
// which materialize a `Vec<Scalar::Utf8>` (one heap `String` per row). Unlike
// value_counts/nunique, `duplicated` does NOT drop nulls: `key_of` maps every
// missing value to a shared `Key::Null`, so all missing rows are equal to each
// other (a NaN row duplicates an earlier NaN row). Build a `Vec<Option<&[u8]>>`
// key vector — `Some(span)` for a present row, `None` (shared) for a missing row —
// exactly mirroring `Key::Utf8(str)` / `Key::Null`, and reuse the same tested
// `duplicated_flags_typed` helper the numeric arms use. Bit-identical for every
// policy (byte-eq == `&str`-eq; the None bucket == Key::Null bucket). Output is
// all-valid Bool (duplicated never yields a null). Gated on a COLD `values` cache:
// the win is skipping the materialization on a fresh column (the usual
// `df[col].duplicated()` / `drop_duplicates()` shape); a warm/already-materialized
// column defers to the generic `Key` loops over the cached Scalar Vec — no
// regression from the per-row `validity.get` + key-vector build.
if let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
values,
} = &self.values
&& values.get().is_none()
{
let n = offsets.len().saturating_sub(1);
let keys: Vec<Option<&[u8]>> = (0..n)
.map(|idx| {
if validity.get(idx) {
Some(&bytes[offsets[idx]..offsets[idx + 1]])
} else {
None
}
})
.collect();
return Ok(Self::from_bool_values(duplicated_flags_typed(&keys, policy)));
}
let mut flags = vec![false; self.values.len()];
match policy {
DupPolicy::First => {
let mut seen: FxHashSet<Key<'_>> = FxHashSet::default();
for (idx, value) in self.values.iter().enumerate() {
flags[idx] = !seen.insert(key_of(value));
}
}
DupPolicy::Last => {
let mut seen: FxHashSet<Key<'_>> = FxHashSet::default();
for (idx, value) in self.values.iter().enumerate().rev() {
flags[idx] = !seen.insert(key_of(value));
}
}
DupPolicy::None => {
let mut seen_once: FxHashSet<Key<'_>> = FxHashSet::default();
let mut seen_multiple: FxHashSet<Key<'_>> = FxHashSet::default();
for value in &self.values {
let key = key_of(value);
if !seen_once.insert(key_of(value)) {
seen_multiple.insert(key);
}
}
for (idx, value) in self.values.iter().enumerate() {
flags[idx] = seen_multiple.contains(&key_of(value));
}
}
}
let out: Vec<Scalar> = flags.into_iter().map(Scalar::Bool).collect();
Self::new(DType::Bool, out)
}
/// Bool column indicating whether each value lies in `[lower, upper]`
/// (or the open interval when `inclusive=false`).
///
/// Matches `pd.Series.between(left, right, inclusive='both'|'neither')`.
/// Missing values map to false. Non-numeric inputs return a type
/// error.
pub fn between(&self, lower: f64, upper: f64, inclusive: bool) -> Result<Self, ColumnError> {
let policy = if inclusive { "both" } else { "neither" };
self.between_inclusive(lower, upper, policy)
}
/// Bool column indicating whether each value lies between bounds
/// with pandas string-valued side-inclusion semantics.
///
/// Matches `pd.Series.between(inclusive=...)` for `"both"`,
/// `"left"`, `"right"`, and `"neither"`.
pub fn between_inclusive(
&self,
lower: f64,
upper: f64,
inclusive: &str,
) -> Result<Self, ColumnError> {
let (include_left, include_right) = match inclusive {
"both" => (true, true),
"left" => (true, false),
"right" => (false, true),
"neither" => (false, false),
other => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: other.to_string(),
dtype: self.dtype,
}));
}
};
// Typed fast paths: compute the predicate over the raw buffer + validity
// into a Vec<bool> (missing / NaN → false, matching the Scalar branch),
// then from_bool_values (all-valid Bool — between never yields a null).
// Bit-identical: same predicate, same to_f64 (x / x as f64).
let pred = |x: f64| -> bool {
let lower_ok = if include_left { x >= lower } else { x > lower };
let upper_ok = if include_right { x <= upper } else { x < upper };
lower_ok && upper_ok
};
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
let out: Vec<bool> = data
.iter()
.enumerate()
.map(|(i, &x)| validity.get(i) && !x.is_nan() && pred(x))
.collect();
return Ok(Self::from_bool_values(out));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let out: Vec<bool> = data
.iter()
.enumerate()
.map(|(i, &x)| validity.get(i) && pred(x as f64))
.collect();
return Ok(Self::from_bool_values(out));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Bool(false));
continue;
}
match v.to_f64() {
Ok(x) => {
let lower_ok = if include_left { x >= lower } else { x > lower };
let upper_ok = if include_right { x <= upper } else { x < upper };
out.push(Scalar::Bool(lower_ok && upper_ok));
}
Err(err) => return Err(ColumnError::Type(err)),
}
}
Self::new(DType::Bool, out)
}
/// Encode the column as integer codes plus unique values.
///
/// Matches `pd.Series.factorize()` default behavior: missing values
/// map to `-1`, and uniques preserve first-seen order.
pub fn factorize(&self) -> Result<(Self, Self), ColumnError> {
self.factorize_with_options(false, true)
}
/// Encode the column as integer codes plus unique values.
///
/// Matches `pd.Series.factorize(sort=..., use_na_sentinel=...)`.
/// When `sort=true`, uniques are sorted and codes are remapped to the
/// sorted positions. When `use_na_sentinel=false`, missing values are
/// emitted as a regular unique bucket instead of `-1`.
pub fn factorize_with_options(
&self,
sort: bool,
use_na_sentinel: bool,
) -> Result<(Self, Self), ColumnError> {
if !sort
&& use_na_sentinel
&& let Some(cached) = self.utf8_default_factorize_columns()
{
return Ok(cached);
}
// Nullable contiguous-Utf8 default factorize (sort=false, use_na_sentinel=true,
// COLD cache): the `utf8_default_factorize_columns` witness above gates on
// `validity.all()` + `LazyContiguousUtf8`, so a `LazyNullableUtf8` column — a
// string column WITH missing rows — fell to the generic `LocalKey` loop below,
// which materializes a `Vec<Scalar::Utf8>` (one heap `String` per row). Assign
// codes over the raw `&[u8]` present spans via `FxHashMap<&[u8], i64>` (byte-eq ==
// `&str`-eq for valid UTF-8): a MISSING row ⇒ code -1 (use_na_sentinel), a present
// row ⇒ its first-seen code, and the uniques are the first-seen distinct present
// spans built into ONE contiguous all-valid Utf8 column. Bit-identical to the
// generic default arm: same first-seen codes (0,1,2,…), same -1 for missing, same
// distinct-present uniques sequence; `from_i64_values_owned`/`from_utf8_contiguous`
// build the same logical columns as `from_i64_values` / `Self::new(Utf8, uniques)`.
// Only the DEFAULT config (sort remaps codes; use_na_sentinel=false makes missing a
// bucket — both keep the generic path). Gated on a COLD `values` cache: the win is
// skipping the materialization on a fresh column (the usual `factorize()` /
// categorical-encode shape); a warm column defers to the generic `LocalKey` loop
// over the cached Scalar Vec — no regression from the per-row `validity.get`.
if !sort
&& use_na_sentinel
&& let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
values,
} = &self.values
&& values.get().is_none()
{
let n = offsets.len().saturating_sub(1);
let mut idx_map: FxHashMap<&[u8], i64> = FxHashMap::default();
let mut codes: Vec<i64> = Vec::with_capacity(n);
let mut uniq_bytes: Vec<u8> = Vec::new();
let mut uniq_offsets: Vec<usize> = vec![0];
for (i, w) in offsets.windows(2).enumerate() {
if !validity.get(i) {
codes.push(-1);
continue;
}
let span = &bytes[w[0]..w[1]];
if let Some(&c) = idx_map.get(span) {
codes.push(c);
} else {
let c = (uniq_offsets.len() - 1) as i64; // # uniques so far
idx_map.insert(span, c);
uniq_bytes.extend_from_slice(span);
uniq_offsets.push(uniq_bytes.len());
codes.push(c);
}
}
return Ok((
Self::from_i64_values_owned(codes),
Self::from_utf8_contiguous(uniq_bytes, uniq_offsets),
));
}
// Per br-frankenpandas-9433f: HashMap-based code lookup mirrors
// fp-frame's Series::factorize fix (br-78d0c). fp-columnar can't
// import fp-frame's ScalarKey (cycle), so define a local
// hashable wrapper. missing_position tracker handles the
// use_na_sentinel=false branch separately so multiple null
// kinds collapse to the same code (matches the existing
// is_missing-based check).
#[derive(Hash, PartialEq, Eq, Clone, Copy)]
enum LocalKey<'a> {
Bool(bool),
Int64(i64),
FloatBits(u64),
Utf8(&'a str),
Timedelta64(i64),
Datetime64(i64),
Period(i64),
Interval(u64, u64, IntervalClosed),
}
fn key_of(s: &Scalar) -> Option<LocalKey<'_>> {
match s {
Scalar::Null(_) => None,
Scalar::Bool(b) => Some(LocalKey::Bool(*b)),
Scalar::Int64(i) => Some(LocalKey::Int64(*i)),
Scalar::Float64(f) => {
if f.is_nan() {
None
} else {
let normalized = if *f == 0.0 { 0.0 } else { *f };
Some(LocalKey::FloatBits(normalized.to_bits()))
}
}
Scalar::Utf8(s) => Some(LocalKey::Utf8(s.as_str())),
Scalar::Timedelta64(t) => {
if *t == Timedelta::NAT {
None
} else {
Some(LocalKey::Timedelta64(*t))
}
}
Scalar::Datetime64(t) => {
if *t == Timestamp::NAT {
None
} else {
Some(LocalKey::Datetime64(*t))
}
}
Scalar::Period(p) => {
if p.ordinal == i64::MIN {
None
} else {
Some(LocalKey::Period(p.ordinal))
}
}
Scalar::Interval(interval) => {
let (left, right, closed) = interval_key(interval);
Some(LocalKey::Interval(left, right, closed))
}
}
}
// Fully-typed fast paths emit BOTH codes and uniques as typed columns
// (no Scalar boxing on input or output, raw-i64 sort) and return early —
// bypassing the Scalar `uniques` Vec + the Scalar sort below.
// * all-valid Int64 → codes + uniques as Int64.
if let Some(data) = self.as_i64_slice() {
let (codes, uniques) = factorize_i64_typed(data, sort);
return Ok((
Self::from_i64_values_owned(codes),
Self::from_i64_values_owned(uniques),
));
}
// * all-valid Datetime64 with NO NaT (i64::MIN) → codes as Int64,
// uniques re-wrapped as Datetime64. The generic path codes NaT as
// -1 / a first-seen bucket (use_na_sentinel-dependent), so any NaT
// (validity-null or an i64::MIN datum) falls through to the Scalar arm.
if !self.has_nulls()
&& let Some(data) = self.as_datetime64_slice()
&& !data.contains(&i64::MIN)
{
let (codes, uniques) = factorize_i64_typed(data, sort);
return Ok((
Self::from_i64_values_owned(codes),
Self::from_datetime64_values(uniques),
));
}
// `codes` is a typed `Vec<i64>` (factorize codes are always plain Int64,
// -1 for NA) — built directly and emitted via `from_i64_values`, skipping
// the n × 32 B `Scalar::Int64` output boxing the old path paid.
let (mut codes, mut uniques): (Vec<i64>, Vec<Scalar>) = {
let mut uniques: Vec<Scalar> = Vec::new();
let mut idx_map: FxHashMap<LocalKey<'_>, i64> = FxHashMap::default();
let mut missing_position: Option<i64> = None;
let mut codes: Vec<i64> = Vec::with_capacity(self.values.len());
for value in &self.values {
if value.is_missing() {
if use_na_sentinel {
codes.push(-1);
} else if let Some(p) = missing_position {
codes.push(p);
} else {
let code = uniques.len() as i64;
missing_position = Some(code);
uniques.push(value.clone());
codes.push(code);
}
continue;
}
let Some(key) = key_of(value) else {
// Defensive: non-missing value that maps to no key
// (shouldn't happen for valid Scalar variants).
codes.push(-1);
continue;
};
match idx_map.get(&key) {
Some(&p) => codes.push(p),
None => {
let code = uniques.len() as i64;
idx_map.insert(key, code);
uniques.push(value.clone());
codes.push(code);
}
}
}
drop(idx_map);
(codes, uniques)
};
if sort && !uniques.is_empty() {
let mut ordering: Vec<usize> = (0..uniques.len()).collect();
ordering.sort_by(|left, right| {
compare_scalars_na_last(&uniques[*left], &uniques[*right], true)
});
let mut remap = vec![0usize; uniques.len()];
let sorted_uniques: Vec<Scalar> = ordering
.into_iter()
.enumerate()
.map(|(sorted_position, original_position)| {
remap[original_position] = sorted_position;
uniques[original_position].clone()
})
.collect();
for code in &mut codes {
if *code >= 0 {
*code = remap[*code as usize] as i64;
}
}
uniques = sorted_uniques;
}
let codes_col = Self::from_i64_values_owned(codes);
let uniques_col = Self::new(self.dtype, uniques)?;
Ok((codes_col, uniques_col))
}
/// Element-wise absolute value.
///
/// Matches `pd.Series.abs()`. Int/Float/Bool/Timedelta paths preserve
/// dtype; Utf8 inputs return `ColumnError::Type` because pandas raises
/// TypeError on non-numeric .abs().
pub fn abs(&self) -> Result<Self, ColumnError> {
// Typed fast path: all-valid Int64/Float64 take abs over the contiguous
// buffer and re-ingest typed (same dtype preserved), skipping the lazy
// Scalar materialization and the 32B-per-cell Vec<Scalar>. Bit-identical
// to the loop below (Int64 wrapping_abs incl i64::MIN; Float64 .abs()
// incl -0.0→0.0; all-valid ⇒ no missing branch).
if let Some(data) = self.as_i64_slice() {
// all-valid i64 output → MOVE (no Arc::from realloc).
return Ok(Self::from_i64_values_owned(
data.iter().map(|&x| x.wrapping_abs()).collect(),
));
}
if let Some(data) = self.as_f64_slice() {
// `as_f64_slice` is all-valid (no NaN — NaN ⇒ missing ⇒ None), and
// |x| never introduces NaN and preserves finiteness EXACTLY
// (|finite|=finite, |±inf|=+inf). So the output is all-valid, its
// has_nan is provably false, and its all_finite equals the input's.
// Carry the input's cached finiteness witness onto the output for
// free (no scan) and run abs as one clean autovectorizable pass —
// skipping both `from_f64_values`' has_nan/all_finite rescan and any
// separate finiteness reduction. Bit-identical to
// `from_f64_values(map(abs))` (same values, same all-valid mask;
// the witness is only a perf hint and is exact here).
let witness = self.f64_finite_witness();
let out: Vec<f64> = data.iter().map(|&x| x.abs()).collect();
return Ok(Self::from_f64_all_valid_with_finite_opt(out, witness));
}
// Nullable Float64 fast path: the all-valid `as_f64_slice` above bails on
// ANY NaN/missing, so a nullable Float64 column fell to the per-element
// Scalar loop (~384ms / 18x slower than pandas on a 10%-null 5M column).
// Abs the present slots over the raw &[f64], write NaN at invalid slots,
// and re-ingest via the canonical `from_f64_values` (which re-derives the
// validity from NaN). Bit-identical to the loop for a Float64 column:
// present ⇒ `Float64(x.abs())`; missing ⇒ NaN ⇒ `from_f64_values` marks it
// missing exactly as `Self::new(Float64, [Null(NaN)])` does, and abs never
// turns a present (non-NaN, valid) value into NaN, so the NaN set == the
// original missing set.
if self.dtype == DType::Float64
&& let Some((data, _)) = self.as_f64_slice_with_validity()
{
// abs PRESERVES missingness exactly (|present| is never NaN —
// |finite|=finite, |±inf|=+inf — and a missing slot stays missing), so
// OUTPUT validity == INPUT validity. Like the round fix: (1) drop the
// per-element `validity.get(i)` branch — abs EVERY slot over the raw
// &[f64] (a masked slot's datum abs's to a finite value the mask then
// hides), giving a branch-free vectorizable + parallel map; (2) reuse
// the input mask via `from_f64_values_with_validity` instead of writing
// NaN and having `from_f64_values` RE-SCAN the output to rebuild it.
// Bit-identical: valid slots use the SAME `data[i].abs()`; missing
// slots view as `missing_for_dtype(Float64)` either way.
let out = par_map_vec_f64(data.len(), |i| data[i].abs());
return Ok(Self::from_f64_values_with_validity(
out,
self.validity.clone(),
));
}
// Nullable Int64 fast path (sibling of the nullable Float64 arm): the
// all-valid `as_i64_slice` above bails on ANY missing slot, so a nullable
// Int64 column fell to the per-element Scalar loop below. Int64 abs is
// dtype-preserving with NO NaN — `wrapping_abs` of any i64 (incl i64::MIN)
// is an i64 — so abs PRESERVES missingness exactly (output validity ==
// input validity). Abs every slot over the raw &[i64] (a masked slot's
// sentinel abs's to some i64 the carried validity then hides) and re-ingest
// via `from_i64_values_with_validity`. Bit-identical to the loop:
// present ⇒ Int64(x.wrapping_abs()); missing ⇒ Null(Null) ==
// missing_for_dtype(Int64) == the loop's `v.clone()` of a nullable-Int64
// missing slot; validity == input validity == the loop's is_missing derivation.
if self.dtype == DType::Int64
&& let Some((data, _)) = self.as_i64_slice_with_validity()
{
let out: Vec<i64> = data.iter().map(|&x| x.wrapping_abs()).collect();
return Ok(Self::from_i64_values_with_validity(
out,
self.validity.clone(),
));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(v.clone());
continue;
}
match v {
Scalar::Bool(x) => out.push(Scalar::Bool(*x)),
Scalar::Int64(x) => out.push(Scalar::Int64(x.wrapping_abs())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.abs())),
Scalar::Timedelta64(x) if *x != Timedelta::NAT => {
out.push(Scalar::Timedelta64(x.wrapping_abs()))
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(self.dtype, out)
}
/// Alias for abs, matching np.fabs.
pub fn fabs(&self) -> Result<Self, ColumnError> {
self.abs()
}
/// Alias for abs, matching np.absolute.
pub fn absolute(&self) -> Result<Self, ColumnError> {
self.abs()
}
/// Negate numeric values. Matches numpy's negative ufunc.
pub fn neg(&self) -> Result<Self, ColumnError> {
// Typed, dtype-preserving fast path (all-valid only): Int64 negates over
// the i64 buffer (wrapping, incl i64::MIN) and stays Int64; Float64
// negates over the f64 buffer. Bit-identical to the scalar loop.
if let Some(data) = self.as_i64_slice() {
return Ok(Self::from_i64_values_owned(
data.iter().map(|&x| x.wrapping_neg()).collect(),
));
}
if let Some(data) = self.as_f64_slice() {
// -x preserves finiteness exactly (-finite=finite, -±inf=∓inf) and
// never makes NaN on an all-valid input, so carry the input's
// finiteness witness and skip the from_f64_values rescan (mirror of
// `abs`). Bit-identical to `from_f64_values(map(-x))`.
let witness = self.f64_finite_witness();
let out: Vec<f64> = data.iter().map(|&x| -x).collect();
return Ok(Self::from_f64_all_valid_with_finite_opt(out, witness));
}
// Nullable Float64 fast path (mirror of abs): neg preserves missingness
// exactly, so negate every raw slot branchlessly and carry the input
// validity mask onto the output. Invalid slot data is hidden by the mask;
// valid slots use the same `-x` as the scalar loop.
if self.dtype == DType::Float64
&& let Some((data, _)) = self.as_f64_slice_with_validity()
{
let out = par_map_vec_f64(data.len(), |i| -data[i]);
return Ok(Self::from_f64_values_with_validity(
out,
self.validity.clone(),
));
}
// Nullable Int64 fast path (sibling of the nullable Float64 arm, mirror of
// the abs fix): the all-valid `as_i64_slice` above bails on ANY missing
// slot, so a nullable Int64 column fell to the per-element Scalar loop.
// Int64 neg is dtype-preserving with NO NaN (`wrapping_neg` of any i64,
// incl i64::MIN, is an i64) so it preserves missingness exactly (output
// validity == input validity). Bit-identical to the loop: present ⇒
// Int64(x.wrapping_neg()); missing ⇒ Null(Null) == missing_for_dtype(Int64)
// == the loop's `v.clone()` of a nullable-Int64 missing slot.
if self.dtype == DType::Int64
&& let Some((data, _)) = self.as_i64_slice_with_validity()
{
let out: Vec<i64> = data.iter().map(|&x| x.wrapping_neg()).collect();
return Ok(Self::from_i64_values_with_validity(
out,
self.validity.clone(),
));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(v.clone());
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Int64(x.wrapping_neg())),
Scalar::Float64(x) => out.push(Scalar::Float64(-x)),
Scalar::Timedelta64(x) if *x != Timedelta::NAT => {
out.push(Scalar::Timedelta64(x.wrapping_neg()))
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(self.dtype, out)
}
/// Unary positive (identity for numeric, error for non-numeric).
pub fn positive(&self) -> Result<Self, ColumnError> {
for v in &self.values {
if v.is_missing() {
continue;
}
match v {
Scalar::Int64(_) | Scalar::Float64(_) | Scalar::Timedelta64(_) => {}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Ok(self.clone())
}
/// Alias for positive.
pub fn negative(&self) -> Result<Self, ColumnError> {
self.neg()
}
/// Square root of numeric values. Matches numpy's sqrt ufunc.
pub fn sqrt(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_nullable_owned_par(f64::sqrt) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).sqrt())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.sqrt())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Exponential (e^x) of numeric values. Matches numpy's exp ufunc.
pub fn exp(&self) -> Result<Self, ColumnError> {
// Use the nullable-capable helper (mirror of log) so a nullable Float64
// input gets the typed path too (the all-valid `typed_float_unary_par`
// bailed on any NaN → Scalar loop). Bit-identical for all-valid input
// (exp of finite is finite/inf, never NaN ⇒ same all-valid output).
if let Some(out) = self.typed_float_unary_nullable_owned_par(f64::exp) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).exp())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.exp())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Natural logarithm of numeric values. Matches numpy's log ufunc.
pub fn log(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_nullable_owned_par(f64::ln) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).ln())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.ln())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Base-10 logarithm of numeric values. Matches numpy's log10 ufunc.
pub fn log10(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::log10) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).log10())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.log10())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Base-2 logarithm of numeric values. Matches numpy's log2 ufunc.
pub fn log2(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::log2) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).log2())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.log2())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise sine.
pub fn sin(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::sin) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).sin())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.sin())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise cosine.
pub fn cos(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::cos) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).cos())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.cos())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise tangent.
pub fn tan(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::tan) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).tan())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.tan())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise arcsine.
pub fn asin(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::asin) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).asin())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.asin())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise arccosine.
pub fn acos(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::acos) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).acos())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.acos())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise arctangent.
pub fn atan(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::atan) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).atan())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.atan())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise hyperbolic sine.
pub fn sinh(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::sinh) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).sinh())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.sinh())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise hyperbolic cosine.
pub fn cosh(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::cosh) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).cosh())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.cosh())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise hyperbolic tangent.
pub fn tanh(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::tanh) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).tanh())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.tanh())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise inverse hyperbolic sine.
pub fn asinh(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::asinh) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).asinh())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.asinh())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise inverse hyperbolic cosine.
pub fn acosh(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::acosh) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).acosh())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.acosh())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise inverse hyperbolic tangent.
pub fn atanh(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::atanh) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).atanh())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.atanh())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Numpy-style alias for asin.
///
/// Matches np.arcsin(x).
pub fn arcsin(&self) -> Result<Self, ColumnError> {
self.asin()
}
/// Numpy-style alias for acos.
///
/// Matches np.arccos(x).
pub fn arccos(&self) -> Result<Self, ColumnError> {
self.acos()
}
/// Numpy-style alias for atan.
///
/// Matches np.arctan(x).
pub fn arctan(&self) -> Result<Self, ColumnError> {
self.atan()
}
/// Numpy-style alias for atan2.
///
/// Matches np.arctan2(y, x).
pub fn arctan2(&self, other: &Self) -> Result<Self, ColumnError> {
self.atan2(other)
}
/// Numpy-style alias for asinh.
///
/// Matches np.arcsinh(x).
pub fn arcsinh(&self) -> Result<Self, ColumnError> {
self.asinh()
}
/// Numpy-style alias for acosh.
///
/// Matches np.arccosh(x).
pub fn arccosh(&self) -> Result<Self, ColumnError> {
self.acosh()
}
/// Numpy-style alias for atanh.
///
/// Matches np.arctanh(x).
pub fn arctanh(&self) -> Result<Self, ColumnError> {
self.atanh()
}
/// Compute element-wise floor.
/// Typed fast path shared by floor/ceil/trunc: an all-valid Float64 (or
/// Int64) column maps `f` over its contiguous buffer and re-ingests via
/// `from_f64_values`, skipping lazy Scalar materialization + the 32 B/cell
/// Vec<Scalar> + Column::new revalidation. Returns `None` (fall back to the
/// scalar loop) for nullable / non-numeric columns. Bit-identical: all-valid
/// ⇒ the `is_missing → NaN` branch never fires; for Int64 the scalar path
/// casts `x as f64` and `f(x as f64) == x as f64` since the cast is integral;
/// floor/ceil/trunc of finite/Inf inputs never synthesize a NaN, and
/// from_f64_values re-marks any NaN exactly as Self::new would.
// Generic over `F` (not a `fn` pointer) so each call site monomorphizes and
// `f` INLINES — letting LLVM lower e.g. `f64::sqrt` to a vectorized `sqrtpd`
// (SSE2) instead of a per-element indirect call (sqrt was 12.78ms = indirect
// call + arc-copy). Also moves the output Vec (from_f64_values_owned) off the
// Arc::from(Vec) cold-realloc-copy. Bit-identical: `f` may produce NaN
// (sqrt/log of negatives), and from_f64_values_owned routes any NaN output to
// the identical from_f64_values (NaN-as-missing) path.
fn typed_float_unary<F: Fn(f64) -> f64>(&self, f: F) -> Option<Self> {
if let Some(data) = self.as_f64_slice() {
return Some(Self::from_f64_values_owned(
data.iter().map(|&x| f(x)).collect(),
));
}
if let Some(data) = self.as_i64_slice() {
return Some(Self::from_f64_values_owned(
data.iter().map(|&x| f(x as f64)).collect(),
));
}
// Nullable Float64/Int64 INPUT: the all-valid accessors above bail on ANY
// missing, so the bandwidth-bound ops routing here (rint/sinc/radians/degrees/
// reciprocal) fell to their per-element Scalar loop + Column::new. Map an
// invalid slot to NaN and each present value through `f` (which may itself
// yield NaN); `from_f64_values_owned` re-derives the output validity from NaN —
// bit-identical to those ops' Scalar arm: missing ⇒ Float64(NaN) ⇒ missing (via
// Self::new), present ⇒ f(v as f64) (a NaN result ⇒ missing). Same output ctor
// as the all-valid arms above; kept serial (these maps are cheap, so the math
// does not dominate — cf. the parallel `typed_float_unary_par`).
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
return Some(Self::from_f64_values_owned(
(0..data.len())
.map(|i| if validity.get(i) { f(data[i]) } else { f64::NAN })
.collect(),
));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
return Some(Self::from_f64_values_owned(
(0..data.len())
.map(|i| {
if validity.get(i) {
f(data[i] as f64)
} else {
f64::NAN
}
})
.collect(),
));
}
None
}
/// Parallel sibling of [`typed_float_unary`] for COMPUTE-bound element maps
/// (libm transcendentals: exp/log/sin/cos/tan/…). Each `f(x)` is ~10-30ns of
/// scalar libm, so the math dominates the load and chunked scoped threads
/// scale near-linearly (unlike the bandwidth-bound cheap maps — reciprocal,
/// to_degrees — which keep the serial path). Bit-identical: same `f`, same
/// order (chunk base+j → global index), same from_f64_values_owned output.
fn typed_float_unary_par<F: Fn(f64) -> f64 + Sync>(&self, f: F) -> Option<Self> {
if let Some(data) = self.as_f64_slice() {
return Some(Self::from_f64_values_owned(par_map_vec_f64(
data.len(),
|i| f(data[i]),
)));
}
if let Some(data) = self.as_i64_slice() {
return Some(Self::from_f64_values_owned(par_map_vec_f64(
data.len(),
|i| f(data[i] as f64),
)));
}
// Nullable Float64/Int64 INPUT: the all-valid accessors above bail on ANY
// missing, so the 17 ops routing here (log10/log2/trig/asinh/expm1/log1p/cbrt/
// …) fell to their per-element Scalar loop + Column::new. Map an invalid slot
// to NaN and each present value through `f` (which may itself yield NaN, e.g.
// log10 of a negative); `from_f64_values_owned` then re-derives the output
// validity from NaN — bit-identical to those ops' Scalar arm: missing ⇒
// Float64(NaN) ⇒ missing (via Self::new), present ⇒ f(v as f64), a NaN result
// ⇒ missing. Same output ctor as the all-valid arms above (proven bit-identical
// to Self::new), now parallel + no Vec<Scalar> boxing for nullable input too.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
return Some(Self::from_f64_values_owned(par_map_vec_f64(
data.len(),
|i| if validity.get(i) { f(data[i]) } else { f64::NAN },
)));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
return Some(Self::from_f64_values_owned(par_map_vec_f64(
data.len(),
|i| if validity.get(i) { f(data[i] as f64) } else { f64::NAN },
)));
}
None
}
/// `typed_float_unary`, but fuses output validity construction with the map
/// and moves the hot output Vec even when the operation creates NaNs.
///
/// This targets operations like `sqrt`/`log` on mixed-sign inputs: the
/// ordinary owned path writes the Vec, scans for NaN, falls back to
/// `from_f64_values`, scans again, then copies into `Arc<[f64]>`. Here the
/// same NaN-as-missing mask is built while writing the output, and the Vec is
/// kept in the move-backed Float64 representation.
#[allow(dead_code)]
fn typed_float_unary_nullable_owned<F: Fn(f64) -> f64>(&self, f: F) -> Option<Self> {
let len = self.len();
let mut out = Vec::with_capacity(len);
let mut validity_words = vec![0_u64; len.div_ceil(64)];
let mut all_valid = true;
let mut all_finite = true;
if let Some(data) = self.as_f64_slice() {
for (idx, &x) in data.iter().enumerate() {
let y = f(x);
all_finite &= y.is_finite();
if y.is_nan() {
all_valid = false;
} else {
validity_words[idx / 64] |= 1_u64 << (idx % 64);
}
out.push(y);
}
} else {
let data = self.as_i64_slice()?;
for (idx, &x) in data.iter().enumerate() {
let y = f(x as f64);
all_finite &= y.is_finite();
if y.is_nan() {
all_valid = false;
} else {
validity_words[idx / 64] |= 1_u64 << (idx % 64);
}
out.push(y);
}
}
let validity = if all_valid {
ValidityMask::all_valid(len)
} else {
ValidityMask::from_words(validity_words, len)
};
Some(Self::from_f64_values_owned_with_validity(
out,
validity,
Some(all_finite),
))
}
/// Parallel sibling of [`typed_float_unary_nullable_owned`] for compute-bound
/// maps that may yield NaN (sqrt/ln of negatives → NaN → missing). The
/// expensive `f(x)` runs in parallel (par_map_vec_f64); the validity/finiteness
/// scan stays a single cheap serial pass over the result. Bit-identical to the
/// serial helper (same `f`, same NaN→invalid rule, same order/witness).
fn typed_float_unary_nullable_owned_par<F: Fn(f64) -> f64 + Sync>(&self, f: F) -> Option<Self> {
let len = self.len();
let out = if let Some(data) = self.as_f64_slice() {
par_map_vec_f64(len, |i| f(data[i]))
} else if let Some(data) = self.as_i64_slice() {
par_map_vec_f64(len, |i| f(data[i] as f64))
} else if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
// Nullable Float64 INPUT (the all-valid `as_f64_slice` above bails on
// any NaN, so nullable sqrt/exp/log fell to the per-element Scalar
// loop, ~400ms / 7-16x slower than pandas). Invalid slot ⇒ NaN, which
// the validity scan below marks missing — bit-identical to those ops'
// Scalar arm (`missing ⇒ Float64(NaN)`); valid slot ⇒ f(v), itself NaN
// for e.g. sqrt(negative), also ⇒ missing (same as the Scalar path).
par_map_vec_f64(len, |i| {
if validity.get(i) {
f(data[i])
} else {
f64::NAN
}
})
} else if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
// Nullable Int64 INPUT (sibling of the nullable Float64 arm): the all-valid
// `as_i64_slice` above bails on any missing, so nullable Int64 sqrt/exp/log
// fell to the per-element Scalar loop. Invalid slot ⇒ NaN, which the
// validity scan below marks missing — bit-identical to those ops' Scalar
// arm (`missing ⇒ Float64(NaN)`); valid slot ⇒ f(v as f64) (== the Scalar
// arm's f(x as f64)), itself NaN for e.g. sqrt(negative) ⇒ also missing.
par_map_vec_f64(len, |i| {
if validity.get(i) {
f(data[i] as f64)
} else {
f64::NAN
}
})
} else {
return None;
};
let mut validity_words = vec![0_u64; len.div_ceil(64)];
let mut all_valid = true;
let mut all_finite = true;
for (idx, &y) in out.iter().enumerate() {
all_finite &= y.is_finite();
if y.is_nan() {
all_valid = false;
} else {
validity_words[idx / 64] |= 1_u64 << (idx % 64);
}
}
let validity = if all_valid {
ValidityMask::all_valid(len)
} else {
ValidityMask::from_words(validity_words, len)
};
Some(Self::from_f64_values_owned_with_validity(
out,
validity,
Some(all_finite),
))
}
/// `typed_float_unary` for maps that NEVER introduce NaN and preserve
/// finiteness EXACTLY (floor/ceil/trunc — `f(finite)` is finite and never
/// overflows, `f(±inf)=±inf`). The caller MUST only pass such `f`; passing
/// e.g. sqrt/exp/recip here would mis-witness the output. Skips
/// `from_f64_values`' has_nan/all_finite rescan: an all-valid input has no
/// NaN so the output has none either, and the all-finite witness equals the
/// input's (carried for free; the i64→f64 cast is always finite ⇒ `true`).
/// Bit-identical to `typed_float_unary(f)` (same values, all-valid mask).
/// Generic over `F` (not a `fn` pointer) so each call site monomorphizes
/// and `f` inlines — letting LLVM lower `f64::floor`/`ceil`/`trunc` to a
/// vectorized `roundpd` instead of a per-element indirect call.
fn typed_float_unary_finite_preserving<F: Fn(f64) -> f64>(&self, f: F) -> Option<Self> {
if let Some(data) = self.as_f64_slice() {
let witness = self.f64_finite_witness();
let out: Vec<f64> = data.iter().map(|&x| f(x)).collect();
return Some(Self::from_f64_all_valid_with_finite_opt(out, witness));
}
if let Some(data) = self.as_i64_slice() {
let out: Vec<f64> = data.iter().map(|&x| f(x as f64)).collect();
// i64→f64 is always finite and floor/ceil/trunc keep it finite.
return Some(Self::from_f64_all_valid_with_finite_opt(out, Some(true)));
}
// Nullable Float64/Int64 INPUT (Float64-output ops floor/ceil/trunc): the all-
// valid arms above bail on ANY missing, so nullable input fell to the per-
// element Scalar loop. Invalid slot ⇒ NaN; a present slot ⇒ f(v) which is
// finite (f preserves finiteness) UNLESS the input datum was itself NaN, and
// f(NaN)=NaN for floor/ceil/trunc — so from_f64_values (which re-derives
// validity from NaN) marks both the absent slots AND a valid-bit-set-NaN datum
// missing, exactly as the Scalar loop's is_missing does. Bit-identical: present
// Float64 ⇒ Float64(f(x)); present Int64 ⇒ Float64(f(x as f64)) (== x as f64,
// integral); missing ⇒ Null(NaN). Cannot carry the all-finite witness (the
// output has NaN at missing slots), so this scans — still far cheaper than the
// Vec<Scalar> Scalar loop.
if self.dtype == DType::Float64
&& let Some((data, validity)) = self.as_f64_slice_with_validity()
{
return Some(Self::from_f64_values(
(0..data.len())
.map(|i| if validity.get(i) { f(data[i]) } else { f64::NAN })
.collect(),
));
}
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
return Some(Self::from_f64_values(
(0..data.len())
.map(|i| if validity.get(i) { f(data[i] as f64) } else { f64::NAN })
.collect(),
));
}
None
}
fn f64_integral_or_infinite_identity(x: f64) -> bool {
const SIGN_MASK: u64 = 0x8000_0000_0000_0000;
const EXP_MASK: u64 = 0x7ff0_0000_0000_0000;
const FRAC_MASK: u64 = 0x000f_ffff_ffff_ffff;
const EXP_BIAS: i32 = 1023;
const FRAC_BITS: i32 = 52;
let bits = x.to_bits();
let abs_bits = bits & !SIGN_MASK;
let exp = ((bits & EXP_MASK) >> FRAC_BITS) as i32;
let frac = bits & FRAC_MASK;
if exp == 0x7ff {
return frac == 0;
}
let unbiased = exp - EXP_BIAS;
if unbiased < 0 {
return abs_bits == 0;
}
if unbiased >= FRAC_BITS {
return true;
}
let fractional_mask = (1_u64 << (FRAC_BITS - unbiased)) - 1;
bits & fractional_mask == 0
}
fn typed_float_integral_identity(&self) -> Option<Self> {
let data = self.as_f64_slice()?;
if data
.iter()
.all(|&x| Self::f64_integral_or_infinite_identity(x))
{
return Some(self.clone());
}
None
}
fn f64_round_nonnegative_decimals_identity(x: f64, factor: f64) -> bool {
const SIGN_MASK: u64 = 0x8000_0000_0000_0000;
const EXP_MASK: u64 = 0x7ff0_0000_0000_0000;
const FRAC_MASK: u64 = 0x000f_ffff_ffff_ffff;
const FRAC_BITS: i32 = 52;
if !factor.is_finite() {
return false;
}
let bits = x.to_bits();
let exp = (bits & EXP_MASK) >> FRAC_BITS;
let frac = bits & FRAC_MASK;
if exp == 0x7ff {
return frac == 0;
}
let abs_bits = bits & !SIGN_MASK;
if abs_bits != 0 && x.abs() > f64::MAX / factor {
return false;
}
Self::f64_integral_or_infinite_identity(x)
}
fn typed_float_round_nonnegative_decimals_identity(&self, factor: f64) -> Option<Self> {
let data = self.as_f64_slice()?;
if data
.iter()
.all(|&x| Self::f64_round_nonnegative_decimals_identity(x, factor))
{
return Some(self.clone());
}
None
}
#[inline]
fn round_ties_even_fast(value: f64) -> f64 {
// Magic-number ties-to-even: `(|x|+2^52)-2^52` uses only SSE2
// add/sub/abs/compare, so it stays cheap on the BASELINE x86-64 target
// (SSE2, no SSE4.1). NOTE (negative result 2026-07-02): swapping this for
// the `f64::round_ties_even()` intrinsic REGRESSED round(2) 3.4→11.9ms —
// without `+sse4.1` the intrinsic lowers to a libm `roundeven` CALL per
// element (no `roundpd`), un-vectorizable. Keep the magic trick.
const TWO_POW_52: f64 = 4_503_599_627_370_496.0;
let abs = value.abs();
if abs < TWO_POW_52 {
let rounded = (abs + TWO_POW_52) - TWO_POW_52;
if value.is_sign_negative() {
-rounded
} else {
rounded
}
} else {
value
}
}
#[inline]
fn round_scaled_ties_even_fast(value: f64, factor: f64) -> f64 {
Self::round_ties_even_fast(value * factor) / factor
}
/// All-valid numeric column → an owned `f64` view (Float64 copied, Int64 cast
/// `x as f64`), exactly as `Scalar::to_f64` would. `None` for nullable /
/// non-numeric columns (so binary ufuncs fall back to the scalar loop).
fn all_valid_as_f64(&self) -> Option<Vec<f64>> {
if let Some(s) = self.as_f64_slice() {
return Some(s.to_vec());
}
if let Some(s) = self.as_i64_slice() {
return Some(s.iter().map(|&x| x as f64).collect());
}
None
}
/// Typed fast path for a Float64-output binary ufunc: when both columns are
/// all-valid numeric, map `f` over the two contiguous buffers and re-ingest
/// via `from_f64_values`, skipping per-element Scalar dispatch/clone on both
/// sides. Caller must have validated equal length. Bit-identical: all-valid
/// ⇒ no missing→NaN branch; `f(a,b)` is the scalar loop's `f(a.to_f64(),
/// b.to_f64())`; from_f64_values re-marks any NaN result missing as Self::new
/// would. Returns `None` to fall back when either side is nullable/non-numeric.
fn typed_float_binary(&self, other: &Self, f: fn(f64, f64) -> f64) -> Option<Self> {
// Fast path: both inputs are typed f64 → read the buffers DIRECTLY (no
// all_valid_as_f64 to_vec copy of each operand) and MOVE the result out
// (from_f64_values_owned, no Arc::from realloc). For cheap ops like
// maximum/minimum/copysign those two copies + the realloc dominated the op.
// Bit-identical to the copy path: same f(x,y) in the same order.
if let (Some(a), Some(b)) = (self.as_f64_slice(), other.as_f64_slice()) {
if a.len() != b.len() {
return None;
}
return Some(Self::from_f64_values_owned(
a.iter().zip(b.iter()).map(|(&x, &y)| f(x, y)).collect(),
));
}
// Int64 (or mixed) inputs are rare for these ops — keep the converting path.
let a = self.all_valid_as_f64()?;
let b = other.all_valid_as_f64()?;
if a.len() != b.len() {
return None;
}
Some(Self::from_f64_values_owned(
a.iter().zip(b.iter()).map(|(&x, &y)| f(x, y)).collect(),
))
}
/// Parallel sibling of [`typed_float_binary`] for COMPUTE-bound libm binaries
/// (pow/atan2/hypot — each `f(x,y)` is ~20-40ns). Reads both f64 buffers
/// directly (no `all_valid_as_f64` copy) when both are typed f64, evaluates in
/// parallel (par_map_vec_f64), and MOVEs the result out. Bit-identical to
/// `typed_float_binary` (same `f`, same order; from_f64_values_owned falls back
/// to from_f64_values on an op-produced NaN, keeping Float64(NaN) identically).
fn typed_float_binary_par(&self, other: &Self, f: fn(f64, f64) -> f64) -> Option<Self> {
if let (Some(a), Some(b)) = (self.as_f64_slice(), other.as_f64_slice()) {
if a.len() != b.len() {
return None;
}
return Some(Self::from_f64_values_owned(par_map_vec_f64(a.len(), |i| {
f(a[i], b[i])
})));
}
let a = self.all_valid_as_f64()?;
let b = other.all_valid_as_f64()?;
if a.len() != b.len() {
return None;
}
Some(Self::from_f64_values_owned(par_map_vec_f64(a.len(), |i| {
f(a[i], b[i])
})))
}
pub fn floor(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_integral_identity() {
return Ok(out);
}
if let Some(out) = self.typed_float_unary_finite_preserving(f64::floor) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
Scalar::Float64(x) => out.push(Scalar::Float64(x.floor())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise ceiling.
pub fn ceil(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_integral_identity() {
return Ok(out);
}
if let Some(out) = self.typed_float_unary_finite_preserving(f64::ceil) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
Scalar::Float64(x) => out.push(Scalar::Float64(x.ceil())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise truncation toward zero.
pub fn trunc(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_integral_identity() {
return Ok(out);
}
if let Some(out) = self.typed_float_unary_finite_preserving(f64::trunc) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
Scalar::Float64(x) => out.push(Scalar::Float64(x.trunc())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Replace NaN with zero and infinity with large finite numbers.
///
/// Matches np.nan_to_num(x). NaN becomes 0, positive infinity becomes
/// a large positive number, negative infinity becomes a large negative number.
pub fn nan_to_num(&self) -> Result<Self, ColumnError> {
self.nan_to_num_with_values(0.0, f64::MAX, f64::MIN)
}
/// Replace NaN and infinity with specified values.
///
/// Matches np.nan_to_num(x, nan=nan, posinf=posinf, neginf=neginf).
pub fn nan_to_num_with_values(
&self,
nan: f64,
posinf: f64,
neginf: f64,
) -> Result<Self, ColumnError> {
// Typed fast path (all-valid only, output Float64). all-valid Float64 has
// no NaN (NaN marks a column invalid), so only the ±Inf replacements can
// fire; the Int64 branch is a plain x as f64. Bit-identical to the scalar
// loop; from_f64_values re-marks a NaN replacement (e.g. posinf=NaN)
// missing exactly as Self::new would.
if let Some(data) = self.as_f64_slice() {
return Ok(Self::from_f64_values(
data.iter()
.map(|&x| {
if x == f64::INFINITY {
posinf
} else if x == f64::NEG_INFINITY {
neginf
} else {
x
}
})
.collect(),
));
}
if let Some(data) = self.as_i64_slice() {
return Ok(Self::from_f64_values(
data.iter().map(|&x| x as f64).collect(),
));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
let result = match v {
Scalar::Float64(x) => {
if x.is_nan() {
nan
} else if *x == f64::INFINITY {
posinf
} else if *x == f64::NEG_INFINITY {
neginf
} else {
*x
}
}
Scalar::Int64(x) => *x as f64,
Scalar::Null(_) => nan,
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
};
out.push(Scalar::Float64(result));
}
Self::new(DType::Float64, out)
}
/// Round to nearest even integer (banker's rounding).
///
/// Matches np.rint(x). Values exactly halfway between integers round to
/// the nearest even integer.
pub fn rint(&self) -> Result<Self, ColumnError> {
// round-half-to-even; for Int64 round_ties_even(x as f64) == x as f64
// (integral), matching the scalar Float64(x as f64) branch. Output Float64.
if let Some(out) = self.typed_float_unary(f64::round_ties_even) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
Scalar::Float64(x) => out.push(Scalar::Float64(x.round_ties_even())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Round toward zero (same as trunc).
///
/// Matches np.fix(x). Alias for trunc().
pub fn fix(&self) -> Result<Self, ColumnError> {
self.trunc()
}
/// Trim leading and/or trailing zeros from a 1-D array.
///
/// Matches np.trim_zeros(). The `trim` parameter specifies:
/// - "f" or "fb": trim from front (leading zeros)
/// - "b" or "fb": trim from back (trailing zeros)
/// - "fb" (default): trim both
pub fn trim_zeros(&self, trim: &str) -> Result<Self, ColumnError> {
let values = &self.values;
if values.is_empty() {
return Self::new(self.dtype, vec![]);
}
let is_zero = |s: &Scalar| -> bool {
match s {
Scalar::Int64(x) => *x == 0,
Scalar::Float64(x) => *x == 0.0,
Scalar::Bool(b) => !*b,
_ => false,
}
};
let mut start = 0;
let mut end = values.len();
if trim.contains('f') {
while start < end && is_zero(&values[start]) {
start += 1;
}
}
if trim.contains('b') {
while end > start && is_zero(&values[end - 1]) {
end -= 1;
}
}
Self::new(self.dtype, values[start..end].to_vec())
}
/// Round to the given number of decimals.
///
/// Matches np.around(a, decimals). For negative decimals, rounds to
/// the left of the decimal point (e.g., decimals=-1 rounds to tens).
pub fn around(&self, decimals: i32) -> Result<Self, ColumnError> {
let factor = 10.0_f64.powi(decimals);
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => {
if decimals >= 0 {
out.push(Scalar::Int64(*x));
} else {
// np.around uses round-half-to-even (banker's), e.g.
// around([25], -1) -> 20, not 30.
let rounded = ((*x as f64) * factor).round_ties_even() / factor;
out.push(Scalar::Int64(rounded as i64));
}
}
Scalar::Float64(x) => {
let rounded = (*x * factor).round_ties_even() / factor;
out.push(Scalar::Float64(rounded));
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
if decimals >= 0 && self.dtype == DType::Int64 {
Self::new(DType::Int64, out)
} else {
Self::new(DType::Float64, out)
}
}
/// Unwrap by changing deltas between values to their 2*pi complements.
///
/// Matches np.unwrap(). Unwraps radian phase values by adding multiples
/// of 2*pi when the absolute difference from the previous value exceeds
/// the discontinuity threshold (default: pi).
pub fn unwrap(&self, discont: Option<f64>) -> Result<Self, ColumnError> {
let threshold = discont.unwrap_or(std::f64::consts::PI);
let two_pi = 2.0 * std::f64::consts::PI;
let mut out = Vec::with_capacity(self.values.len());
let mut offset = 0.0;
for (i, v) in self.values.iter().enumerate() {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let x = match v {
Scalar::Int64(x) => *x as f64,
Scalar::Float64(x) => *x,
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
};
if i == 0 {
out.push(Scalar::Float64(x));
} else {
let prev = match &out[out.len() - 1] {
Scalar::Float64(p) if !p.is_nan() => *p,
_ => {
out.push(Scalar::Float64(x + offset));
continue;
}
};
let diff = x + offset - prev;
if diff > threshold {
offset -= two_pi * ((diff + std::f64::consts::PI) / two_pi).floor();
} else if diff < -threshold {
offset += two_pi * ((-diff + std::f64::consts::PI) / two_pi).floor();
}
out.push(Scalar::Float64(x + offset));
}
}
Self::new(DType::Float64, out)
}
/// Compute exp(x) - 1 with improved precision for small x.
pub fn expm1(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::exp_m1) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).exp_m1())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.exp_m1())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute ln(1 + x) with improved precision for small x.
pub fn log1p(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::ln_1p) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).ln_1p())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.ln_1p())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise cube root.
pub fn cbrt(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary_par(f64::cbrt) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).cbrt())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.cbrt())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Multiply by 2 raised to an integer power.
///
/// Matches np.ldexp(x, exp). Computes x * 2^exp for each element.
pub fn ldexp(&self, exp: i32) -> Result<Self, ColumnError> {
let multiplier = 2.0_f64.powi(exp);
// Typed fast path (all-valid or nullable Float64/Int64 ⇒ Float64 out): present
// ⇒ x*multiplier, missing/NaN ⇒ NaN⇒missing. Bit-identical to the Scalar loop.
if let Some(out) = self.typed_float_unary(|x| x * multiplier) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64 * multiplier)),
Scalar::Float64(x) => out.push(Scalar::Float64(x * multiplier)),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Split into integer and fractional parts.
///
/// Matches np.modf(x). Returns (fractional_part, integer_part) as two columns.
/// The fractional part has the same sign as the input.
pub fn modf(&self) -> Result<(Self, Self), ColumnError> {
let mut frac = Vec::with_capacity(self.values.len());
let mut int = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
frac.push(Scalar::Float64(f64::NAN));
int.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => {
frac.push(Scalar::Float64(0.0));
int.push(Scalar::Float64(*x as f64));
}
Scalar::Float64(x) => {
let i = x.trunc();
let f = x - i;
frac.push(Scalar::Float64(f));
int.push(Scalar::Float64(i));
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Ok((
Self::new(DType::Float64, frac)?,
Self::new(DType::Float64, int)?,
))
}
/// Decompose float into mantissa and exponent.
///
/// Matches np.frexp(x). Returns (mantissa, exponent) where:
/// - mantissa is in [0.5, 1.0) or exactly 0.0
/// - exponent is an integer
/// - x = mantissa * 2^exponent
pub fn frexp(&self) -> Result<(Self, Self), ColumnError> {
let mut mantissa = Vec::with_capacity(self.values.len());
let mut exponent = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
mantissa.push(Scalar::Float64(f64::NAN));
exponent.push(Scalar::Int64(0));
continue;
}
match v {
Scalar::Int64(x) => {
let f = *x as f64;
if f == 0.0 {
mantissa.push(Scalar::Float64(0.0));
exponent.push(Scalar::Int64(0));
} else {
let bits = f.abs().to_bits();
let exp_bits = ((bits >> 52) & 0x7ff) as i64;
let exp = exp_bits - 1022; // normalized mantissa is in [0.5, 1.0)
let mant_bits = (bits & 0x000f_ffff_ffff_ffff) | 0x3fe0_0000_0000_0000;
let mant = f64::from_bits(mant_bits);
let mant = if f < 0.0 { -mant } else { mant };
mantissa.push(Scalar::Float64(mant));
exponent.push(Scalar::Int64(exp));
}
}
Scalar::Float64(x) => {
if x.is_nan() {
mantissa.push(Scalar::Float64(f64::NAN));
exponent.push(Scalar::Int64(0));
} else if x.is_infinite() {
mantissa.push(Scalar::Float64(*x));
exponent.push(Scalar::Int64(0));
} else if *x == 0.0 {
mantissa.push(Scalar::Float64(*x)); // preserves sign of zero
exponent.push(Scalar::Int64(0));
} else {
let bits = x.abs().to_bits();
let exp_bits = ((bits >> 52) & 0x7ff) as i64;
if exp_bits == 0 {
// denormalized number - scale up and extract
let scaled = x.abs() * 2.0_f64.powi(64);
let sbits = scaled.to_bits();
let sexp_bits = ((sbits >> 52) & 0x7ff) as i64;
let exp = sexp_bits - 1022 - 64;
let mant_bits = (sbits & 0x000f_ffff_ffff_ffff) | 0x3fe0_0000_0000_0000;
let mant = f64::from_bits(mant_bits);
let mant = if *x < 0.0 { -mant } else { mant };
mantissa.push(Scalar::Float64(mant));
exponent.push(Scalar::Int64(exp));
} else {
let exp = exp_bits - 1022;
let mant_bits = (bits & 0x000f_ffff_ffff_ffff) | 0x3fe0_0000_0000_0000;
let mant = f64::from_bits(mant_bits);
let mant = if *x < 0.0 { -mant } else { mant };
mantissa.push(Scalar::Float64(mant));
exponent.push(Scalar::Int64(exp));
}
}
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Ok((
Self::new(DType::Float64, mantissa)?,
Self::new(DType::Int64, exponent)?,
))
}
/// Return the next representable floating-point value after x toward y.
///
/// Matches np.nextafter(x, y). For each pair of elements, returns the
/// next representable float after x in the direction of y.
/// Per-element kernel for `nextafter` (next representable f64 after `x` toward
/// `y`). Shared by the typed fast path and the Scalar fallback so both compute
/// the identical result.
fn nextafter_kernel(x: f64, y: f64) -> f64 {
if x.is_nan() || y.is_nan() {
f64::NAN
} else if x == y {
x
} else if x == 0.0 {
// Smallest positive/negative denormal, not MIN_POSITIVE (normalized)
if y > 0.0 {
f64::from_bits(1) // smallest positive denormal ≈ 5e-324
} else {
-f64::from_bits(1) // smallest negative denormal ≈ -5e-324
}
} else {
let bits = x.to_bits() as i64;
let next_bits = if (x > 0.0) == (y > x) { bits + 1 } else { bits - 1 };
f64::from_bits(next_bits as u64)
}
}
/// Per-element kernel for `logaddexp` (log(e^x + e^y), numerically stable).
fn logaddexp_kernel(x: f64, y: f64) -> f64 {
if x.is_nan() || y.is_nan() {
f64::NAN
} else if x == f64::NEG_INFINITY {
y
} else if y == f64::NEG_INFINITY {
x
} else if x == f64::INFINITY || y == f64::INFINITY {
f64::INFINITY
} else if x >= y {
x + (y - x).exp().ln_1p()
} else {
y + (x - y).exp().ln_1p()
}
}
/// Per-element kernel for `logaddexp2` (log2(2^x + 2^y), numerically stable).
fn logaddexp2_kernel(x: f64, y: f64) -> f64 {
let ln2 = std::f64::consts::LN_2;
if x.is_nan() || y.is_nan() {
f64::NAN
} else if x == f64::NEG_INFINITY {
y
} else if y == f64::NEG_INFINITY {
x
} else if x == f64::INFINITY || y == f64::INFINITY {
f64::INFINITY
} else if x >= y {
x + ((y - x) * ln2).exp().ln_1p() / ln2
} else {
y + ((x - y) * ln2).exp().ln_1p() / ln2
}
}
pub fn nextafter(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
// Typed fast path (all-valid or nullable Float64/Int64): both-present ⇒
// nextafter_kernel, either-missing ⇒ NaN⇒missing. Bit-identical to the Scalar
// loop below — SAME kernel, and get_present drops exactly the is_missing slots.
if let Some(out) = self.typed_nan_propagate_binary(other, Self::nextafter_kernel) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (v1, v2) in self.values.iter().zip(other.values.iter()) {
if v1.is_missing() || v2.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let x = v1.to_f64().map_err(ColumnError::Type)?;
let y = v2.to_f64().map_err(ColumnError::Type)?;
out.push(Scalar::Float64(Self::nextafter_kernel(x, y)));
}
Self::new(DType::Float64, out)
}
/// Check if values are negative infinity.
///
/// Matches np.isneginf(x). Returns a Bool column that is True where
/// the value is negative infinity.
pub fn isneginf(&self) -> Result<Self, ColumnError> {
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Bool(false));
continue;
}
match v {
Scalar::Int64(_) => out.push(Scalar::Bool(false)),
Scalar::Float64(x) => out.push(Scalar::Bool(*x == f64::NEG_INFINITY)),
_ => out.push(Scalar::Bool(false)),
}
}
Self::new(DType::Bool, out)
}
/// Check if values are positive infinity.
///
/// Matches np.isposinf(x). Returns a Bool column that is True where
/// the value is positive infinity.
pub fn isposinf(&self) -> Result<Self, ColumnError> {
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Bool(false));
continue;
}
match v {
Scalar::Int64(_) => out.push(Scalar::Bool(false)),
Scalar::Float64(x) => out.push(Scalar::Bool(*x == f64::INFINITY)),
_ => out.push(Scalar::Bool(false)),
}
}
Self::new(DType::Bool, out)
}
/// Compute 2 raised to the power of each element.
///
/// Matches np.exp2(x). Returns 2^x for each element.
pub fn exp2(&self) -> Result<Self, ColumnError> {
// Typed fast path (all-valid only, output Float64). The Int64 branch must
// keep `2.0.powi(x as i32)` (NOT (x as f64).exp2()) to match the scalar
// loop's exact rounding; Float64 uses x.exp2(). Bit-identical.
if let Some(data) = self.as_f64_slice() {
return Ok(Self::from_f64_values(
data.iter().map(|&x| x.exp2()).collect(),
));
}
if let Some(data) = self.as_i64_slice() {
return Ok(Self::from_f64_values(
data.iter().map(|&x| 2.0_f64.powi(x as i32)).collect(),
));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64(2.0_f64.powi(*x as i32))),
Scalar::Float64(x) => out.push(Scalar::Float64(x.exp2())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute the sinc function.
///
/// Matches np.sinc(x). Returns sin(pi*x) / (pi*x), with sinc(0) = 1.
pub fn sinc(&self) -> Result<Self, ColumnError> {
// all-valid ⇒ no NaN, so the scalar formula reduces to 0->1 else
// sin(πx)/(πx) for both Float64 and Int64 (x as f64). Bit-identical.
if let Some(out) = self.typed_float_unary(|x| {
if x == 0.0 {
1.0
} else {
let px = std::f64::consts::PI * x;
px.sin() / px
}
}) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => {
if *x == 0 {
out.push(Scalar::Float64(1.0));
} else {
let px = std::f64::consts::PI * (*x as f64);
out.push(Scalar::Float64(px.sin() / px));
}
}
Scalar::Float64(x) => {
if *x == 0.0 {
out.push(Scalar::Float64(1.0));
} else if x.is_nan() {
out.push(Scalar::Float64(f64::NAN));
} else {
let px = std::f64::consts::PI * x;
out.push(Scalar::Float64(px.sin() / px));
}
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute log(exp(x) + exp(y)) in a numerically stable way.
///
/// Matches np.logaddexp(x, y). Useful for log-domain arithmetic
/// where direct computation would overflow/underflow.
pub fn logaddexp(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
// Typed fast path (all-valid or nullable): both-present ⇒ logaddexp_kernel,
// either-missing ⇒ NaN⇒missing. Bit-identical to the Scalar loop — SAME kernel.
if let Some(out) = self.typed_nan_propagate_binary(other, Self::logaddexp_kernel) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (v1, v2) in self.values.iter().zip(other.values.iter()) {
if v1.is_missing() || v2.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let x = v1.to_f64().map_err(ColumnError::Type)?;
let y = v2.to_f64().map_err(ColumnError::Type)?;
out.push(Scalar::Float64(Self::logaddexp_kernel(x, y)));
}
Self::new(DType::Float64, out)
}
/// Compute log2(2**x + 2**y) in a numerically stable way.
///
/// Matches np.logaddexp2(x, y). Like logaddexp but using base 2.
pub fn logaddexp2(&self, other: &Self) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
// Typed fast path (all-valid or nullable): both-present ⇒ logaddexp2_kernel,
// either-missing ⇒ NaN⇒missing. Bit-identical to the Scalar loop — SAME kernel.
if let Some(out) = self.typed_nan_propagate_binary(other, Self::logaddexp2_kernel) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for (v1, v2) in self.values.iter().zip(other.values.iter()) {
if v1.is_missing() || v2.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
let x = v1.to_f64().map_err(ColumnError::Type)?;
let y = v2.to_f64().map_err(ColumnError::Type)?;
out.push(Scalar::Float64(Self::logaddexp2_kernel(x, y)));
}
Self::new(DType::Float64, out)
}
/// Compute spacing between this value and the next representable float.
///
/// Matches np.spacing(x). Returns the ULP (unit in last place) - the
/// distance to the next representable float away from zero.
pub fn spacing(&self) -> Result<Self, ColumnError> {
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => {
let f = (*x as f64).abs();
if f == 0.0 {
out.push(Scalar::Float64(f64::from_bits(1)));
} else {
let bits = f.to_bits();
let next = f64::from_bits(bits + 1);
out.push(Scalar::Float64(next - f));
}
}
Scalar::Float64(x) => {
if x.is_nan() || x.is_infinite() {
out.push(Scalar::Float64(f64::NAN));
} else {
let f = x.abs();
if f == 0.0 {
out.push(Scalar::Float64(f64::from_bits(1)));
} else {
let bits = f.to_bits();
let next = f64::from_bits(bits + 1);
out.push(Scalar::Float64(next - f));
}
}
}
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Convert angles from degrees to radians.
pub fn radians(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary(f64::to_radians) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).to_radians())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.to_radians())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Alias for radians.
pub fn deg2rad(&self) -> Result<Self, ColumnError> {
self.radians()
}
/// Convert angles from radians to degrees.
pub fn degrees(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary(f64::to_degrees) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).to_degrees())),
Scalar::Float64(x) => out.push(Scalar::Float64(x.to_degrees())),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Alias for degrees.
pub fn rad2deg(&self) -> Result<Self, ColumnError> {
self.degrees()
}
/// Compute element-wise reciprocal (1/x).
pub fn reciprocal(&self) -> Result<Self, ColumnError> {
if let Some(out) = self.typed_float_unary(|x| 1.0 / x) {
return Ok(out);
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Float64(1.0 / (*x as f64))),
Scalar::Float64(x) => out.push(Scalar::Float64(1.0 / x)),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
Self::new(DType::Float64, out)
}
/// Compute element-wise square (x^2).
pub fn square(&self) -> Result<Self, ColumnError> {
// Typed, dtype-preserving fast path (all-valid only): Int64 stays Int64
// (`x * x`, same overflow behavior as the scalar loop); Float64 squares
// over the f64 buffer. Bit-identical.
if let Some(data) = self.as_i64_slice() {
return Ok(Self::from_i64_values_owned(
data.iter().map(|&x| x * x).collect(),
));
}
if let Some(data) = self.as_f64_slice() {
return Ok(Self::from_f64_values(data.iter().map(|&x| x * x).collect()));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(Scalar::Float64(f64::NAN));
continue;
}
match v {
Scalar::Int64(x) => out.push(Scalar::Int64(x * x)),
Scalar::Float64(x) => out.push(Scalar::Float64(x * x)),
_ => {
return Err(ColumnError::Type(TypeError::NonNumericValue {
value: format!("{v:?}"),
dtype: self.dtype,
}));
}
}
}
let dtype = match self.dtype {
DType::Int64 => DType::Int64,
_ => DType::Float64,
};
Self::new(dtype, out)
}
/// Shift column values by `periods` positions, filling vacated slots
/// with `fill`.
///
/// Matches `pd.Series.shift(periods, fill_value)` for the positional
/// form. Positive periods shift right (vacates the head); negative
/// periods shift left (vacates the tail).
pub fn shift(&self, periods: i64, fill: Scalar) -> Result<Self, ColumnError> {
let len = self.values.len();
if len == 0 || periods == 0 {
return Ok(self.clone());
}
let abs = periods.unsigned_abs() as usize;
// Typed all-valid-Float64 fast path with a MISSING fill (the default
// shift, which vacates slots to NaN/missing): build the output f64
// buffer directly — NaN in the vacated slots, the contiguous source run
// copied into place — and let from_f64_values mark the NaN slots
// missing. No per-element Scalar clone, no Self::new revalidation.
// Bit-identical to the scalar loop for an all-valid f64 column + missing
// fill: the source values are finite (as_f64_slice ⇒ no NaN) so only the
// vacated slots are missing, exactly as `fill.clone()` placed them.
if fill.is_missing()
&& let Some(data) = self.as_f64_slice()
{
// Copy the surviving run into an f64 body and mark the vacated slots as
// one invalid range, then MOVE into a LazyNullableFloat64 backing
// (from_f64_values_with_validity) — no NaN scan, no Arc::from realloc.
// Bit-identical to the prior from_f64_values(NaN-vacated) path: an
// invalid slot materializes Null(NaN) = the missing fill; the copied
// body (as_f64_slice is NaN-free) materializes Float64(src).
let mut out = vec![0.0_f64; len];
let vacated: (usize, usize) = if abs >= len {
(0, len)
} else if periods > 0 {
out[abs..].copy_from_slice(&data[..len - abs]);
(0, abs)
} else {
out[..len - abs].copy_from_slice(&data[abs..]);
(len - abs, abs)
};
let validity =
ValidityMask::from_invalid_ranges(Arc::from(vec![vacated].into_boxed_slice()), len);
return Ok(Self::from_f64_values_with_validity(out, validity));
}
// Typed all-valid-Int64 fast path for an Int64 fill. This is the
// dtype-preserving `shift(..., fill_value=0)` shape: the scalar path emits
// only Int64 values and `Column::new(Int64, ...)` rebuilds an all-valid
// Int64 column, so a direct memmove into an owned i64 buffer is
// bit-identical while skipping Vec<Scalar> construction.
if let (Some(data), Scalar::Int64(fill_i)) = (self.as_i64_slice(), &fill) {
let mut out = vec![*fill_i; len];
if abs < len {
if periods > 0 {
out[abs..].copy_from_slice(&data[..len - abs]);
} else {
out[..len - abs].copy_from_slice(&data[abs..]);
}
}
return Ok(Self::from_i64_values_owned(out));
}
// Bool sibling of the Int64 path: `shift(..., fill_value=false/true)`
// over an all-valid Bool column emits only present Bool values. Carry a
// proof-carrying shifted view so metadata-only consumers pay O(1), while
// typed/scalar readers materialize the exact same bool buffer on demand.
if let (Some(data), Scalar::Bool(fill_b)) = (self.bool_arc_view_source(), &fill) {
return Ok(Self {
dtype: DType::Bool,
values: ScalarValues::lazy_shifted_bool(data, periods, *fill_b, len),
validity: ValidityMask::all_valid(len),
data: None,
});
}
let mut out: Vec<Scalar> = Vec::with_capacity(len);
if abs >= len {
for _ in 0..len {
out.push(fill.clone());
}
} else if periods > 0 {
for _ in 0..abs {
out.push(fill.clone());
}
out.extend_from_slice(&self.values[..len - abs]);
} else {
out.extend_from_slice(&self.values[abs..]);
for _ in 0..abs {
out.push(fill.clone());
}
}
Self::new(self.dtype, out)
}
/// Clip numeric values to `[lower, upper]`.
///
/// Matches `pd.Series.clip(lower, upper)`. `None` on either bound
/// disables that side. Non-numeric inputs return a type error.
/// Missing values pass through unchanged. Result dtype is Float64
/// (via `infer_dtype`) to accommodate fractional clipping.
pub fn clip(&self, lower: Option<f64>, upper: Option<f64>) -> Result<Self, ColumnError> {
let lower = lower.filter(|v| !v.is_nan());
let upper = upper.filter(|v| !v.is_nan());
// Typed fast path: an all-valid numeric column clamps straight over its
// contiguous buffer (output is always Float64), with no per-element
// Scalar dispatch/clone or output Vec<Scalar>. Bit-identical — the scalar
// loop applies the lower bound then the upper bound to v.to_f64(), which
// for an all-valid Float64/Int64 column is exactly data[i] (as f64). NaN
// floats mark the column invalid (validity.all() false), so as_*_slice
// declines and missing values keep the Scalar path.
let clamp = |mut x: f64| {
if let Some(lo) = lower
&& x < lo
{
x = lo;
}
if let Some(hi) = upper
&& x > hi
{
x = hi;
}
x
};
if let Some(data) = self.as_f64_slice() {
let out: Vec<f64> = data.iter().map(|&x| clamp(x)).collect();
// clamp of a finite/inf input is never NaN (bounds are NaN-filtered),
// so the output is all-valid → MOVE the Vec (no Arc::from realloc).
return Ok(Self::from_f64_values_owned(out));
}
if let Some(data) = self.as_i64_slice() {
let out: Vec<f64> = data.iter().map(|&x| clamp(x as f64)).collect();
return Ok(Self::from_f64_values_owned(out));
}
// Nullable Float64 fast path (corr/round/abs reuse-validity vein): the
// all-valid `as_f64_slice` above bails on ANY missing, so a nullable
// Float64 column fell to the per-element `values()` Scalar loop below.
// clip PRESERVES missingness exactly (clamp of a present finite/inf value
// is never NaN — bounds are NaN-filtered — and a missing slot stays
// missing), so OUTPUT validity == INPUT validity: clamp EVERY slot over the
// raw &[f64] (a masked slot's datum clamps harmlessly, the mask hides it)
// in parallel, and reuse the input mask via `from_f64_values_with_validity`
// — no `Vec<Scalar>` materialization, no NaN rescan. Bit-identical to the
// loop: present ⇒ same lower-then-upper clamp on `data[i]`; missing ⇒
// `missing_for_dtype(Float64)` either way. Unlike abs/round, pandas' clip is
// itself bandwidth-bound (~8.7ms/2M), so this flips a 0.93× near-loss.
if self.dtype == DType::Float64
&& let Some((data, _)) = self.as_f64_slice_with_validity()
{
let out = par_map_vec_f64(data.len(), |i| clamp(data[i]));
return Ok(Self::from_f64_values_with_validity(
out,
self.validity.clone(),
));
}
// Nullable Int64 fast path (sibling of the nullable Float64 arm): the all-valid
// `as_i64_slice` above bails on ANY missing, so a nullable Int64 column fell to
// the per-element `values()` Scalar loop below. clip's output is always Float64
// and PRESERVES missingness (clamp of a present `v as f64` is finite/inf, never
// NaN — bounds are NaN-filtered — and a missing slot stays missing), so OUTPUT
// validity == INPUT validity: clamp EVERY slot over the raw &[i64] in parallel
// and reuse the input mask via `from_f64_values_with_validity`. Bit-identical to
// the loop: present ⇒ same lower-then-upper clamp on `data[i] as f64` (== the
// generic `to_f64`); missing ⇒ `Null(NaN)` either way — the loop pushes the
// input's `Null(Null)` which `Self::new(Float64,…)` normalizes to `Null(NaN)`,
// exactly what the nullable-Float64 backing renders for a cleared bit.
if self.dtype == DType::Int64
&& let Some((data, _)) = self.as_i64_slice_with_validity()
{
let out = par_map_vec_f64(data.len(), |i| clamp(data[i] as f64));
return Ok(Self::from_f64_values_with_validity(
out,
self.validity.clone(),
));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(v.clone());
continue;
}
let numeric = match v.to_f64() {
Ok(x) => x,
Err(err) => return Err(ColumnError::Type(err)),
};
let mut clipped = numeric;
if let Some(lo) = lower
&& clipped < lo
{
clipped = lo;
}
if let Some(hi) = upper
&& clipped > hi
{
clipped = hi;
}
out.push(Scalar::Float64(clipped));
}
Self::new(DType::Float64, out)
}
/// Round numeric values to `decimals` decimal places.
///
/// Matches `pd.Series.round(decimals)`. Negative `decimals` rounds
/// to the left of the decimal point. Int columns pass through
/// unchanged for decimals >= 0 and retain Int64 dtype for negative
/// decimals. Bool columns pass through unchanged. Missing values are
/// preserved.
pub fn round(&self, decimals: i32) -> Result<Self, ColumnError> {
if matches!(self.dtype, DType::Bool) || (self.dtype == DType::Int64 && decimals >= 0) {
return Ok(self.clone());
}
if self.dtype == DType::Int64 {
let out = self
.values
.iter()
.map(|v| match v {
Scalar::Int64(value) => {
Scalar::Int64(round_i64_negative_decimals(*value, decimals))
}
Scalar::Null(kind) => Scalar::Null(*kind),
other => other.clone(),
})
.collect();
return Self::new(DType::Int64, out);
}
let factor = 10f64.powi(decimals);
if decimals >= 0
&& let Some(out) = self.typed_float_round_nonnegative_decimals_identity(factor)
{
return Ok(out);
}
// Typed fast path (mirror of `abs`): an all-valid Float64 column rounds
// over its contiguous buffer and re-ingests typed, skipping the lazy
// Scalar materialization, the 32 B/cell Vec<Scalar>, and Column::new's
// revalidation passes. Bit-identical to the scalar loop below: the
// formula is the same `(x*factor).round_ties_even()/factor`, and
// from_f64_values re-marks any NaN result as missing exactly as
// `Self::new(Float64, ..)` would (all-valid ⇒ no is_missing branch).
if let Some(data) = self.as_f64_slice() {
// Move the rounded output Vec into the backing (Arc::new) instead of
// from_f64_values' Arc::from(Vec) cold-realloc-copy (~5.7ms/1M).
// round of all-valid finite/inf never yields NaN, so owned (all-valid)
// is bit-identical; from_f64_values_owned's NaN scan routes any stray
// NaN to the identical Arc path.
if factor.is_finite() && factor != 0.0 {
return Ok(Self::from_f64_values_owned(
data.iter()
.map(|&x| Self::round_scaled_ties_even_fast(x, factor))
.collect(),
));
}
return Ok(Self::from_f64_values_owned(
data.iter()
.map(|&x| (x * factor).round_ties_even() / factor)
.collect(),
));
}
// Nullable Float64 fast path (mirror of abs): round present slots over the
// raw &[f64] with the IDENTICAL formula as the loop, write NaN at invalid
// slots, re-ingest via `from_f64_values`. Bit-identical for a Float64
// column: present ⇒ same `(x*factor).round_ties_even()/factor`; missing ⇒
// NaN ⇒ marked missing; round of a present value never yields the only-at-
// -missing NaN (finite/inf round stays finite/inf), so the NaN set ==
// original missing set. (~403ms / 15x slower than pandas on a 10%-null 5M.)
if self.dtype == DType::Float64
&& let Some((data, _)) = self.as_f64_slice_with_validity()
{
// round PRESERVES missingness exactly (a present value never rounds to
// NaN — finite/inf stay finite/inf — and a missing slot stays missing),
// so the OUTPUT validity == the INPUT validity. Two consequences vs the
// old `validity.get(i)`-per-element + `from_f64_values` form:
// (1) drop the per-element validity branch — round EVERY slot over the
// raw &[f64] (a masked slot's datum rounds to some finite value
// that `from_f64_values_with_validity` then masks away, so the
// logical result is identical to writing NaN there), giving the
// branch-free, vectorizable map instead of a mispredicting scan.
// (2) reuse the input validity mask directly instead of re-scanning
// the whole output Vec for NaN inside `from_f64_values`.
// Bit-identical: valid slots use the SAME `(x*factor).round_ties_even()
// /factor`; missing slots view as `missing_for_dtype(Float64)` either
// way (~15x-slower nullable round was this get()+rescan tax).
// Elementwise + independent → fan out (par_map_vec_f64 self-gates on
// n and core count). Bit-identical: each slot's `(x*factor)
// .round_ties_even()/factor` is order-independent.
let out = par_map_vec_f64(data.len(), |i| {
(data[i] * factor).round_ties_even() / factor
});
return Ok(Self::from_f64_values_with_validity(
out,
self.validity.clone(),
));
}
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
if v.is_missing() {
out.push(v.clone());
continue;
}
match v.to_f64() {
Ok(x) => out.push(Scalar::Float64((x * factor).round_ties_even() / factor)),
Err(err) => return Err(ColumnError::Type(err)),
}
}
Self::new(DType::Float64, out)
}
/// Per-row boolean membership test against `needles`.
///
/// Matches `pd.Series.isin(values)`. The result is always a Bool
/// column the same length as `self`. Missing input positions map
/// to `false` (pandas convention — NaN is never "in" a set).
pub fn isin(&self, needles: &[Scalar]) -> Result<Self, ColumnError> {
#[derive(Hash, PartialEq, Eq)]
enum Key<'a> {
Bool(bool),
Int64(i64),
FloatBits(u64),
Utf8(&'a str),
Timedelta64(i64),
Datetime64(i64),
Period(i64),
Interval(u64, u64, IntervalClosed),
}
fn key_of(v: &Scalar) -> Option<Key<'_>> {
if v.is_missing() {
return None;
}
Some(match v {
Scalar::Bool(b) => Key::Bool(*b),
Scalar::Int64(i) => Key::Int64(*i),
Scalar::Float64(f) => {
let norm = if *f == 0.0 { 0.0 } else { *f };
Key::FloatBits(norm.to_bits())
}
Scalar::Utf8(s) => Key::Utf8(s.as_str()),
Scalar::Timedelta64(v) => Key::Timedelta64(*v),
Scalar::Datetime64(v) => Key::Datetime64(*v),
Scalar::Period(p) => Key::Period(p.ordinal),
Scalar::Interval(v) => {
let (left, right, closed) = interval_key(v);
Key::Interval(left, right, closed)
}
Scalar::Null(_) => return None,
})
}
// Typed dense-membership fast path: an all-valid Int64 column tested
// against bounded Int64 needles uses a direct-address presence bitset
// (indexed by `needle - min`) scanned over the contiguous i64 buffer,
// instead of a per-element HashSet probe over materialized Scalars.
// Bit-identical: an Int64 value's key is `Key::Int64`, which only ever
// matches an Int64 needle (a Float64 5.0 needle is `Key::FloatBits`, a
// distinct key), so the membership answer is exactly "is this i64 one of
// the Int64 needles". Falls back for non-Int64 self/needle spans.
if let Some(data) = self.as_i64_slice() {
let mut n_min = i64::MAX;
let mut n_max = i64::MIN;
let mut saw_int_needle = false;
for needle in needles {
if let Scalar::Int64(v) = needle {
saw_int_needle = true;
n_min = n_min.min(*v);
n_max = n_max.max(*v);
}
}
if !saw_int_needle {
return Ok(Self::from_bool_values(vec![false; data.len()]));
}
let span = i128::from(n_max) - i128::from(n_min) + 1;
if span > 0 && span <= (1i128 << 24) {
let mut present = vec![false; span as usize];
for needle in needles {
if let Scalar::Int64(v) = needle {
present[(v - n_min) as usize] = true;
}
}
let out: Vec<bool> = data
.iter()
.map(|&v| v >= n_min && v <= n_max && present[(v - n_min) as usize])
.collect();
return Ok(Self::from_bool_values(out));
}
}
// Typed i64-hashset membership for the cases the dense Int64 bitset above
// does NOT cover: a WIDE-range all-valid Int64 column (span > 2^24, which
// falls through the dense block), and all-valid Datetime64/Timedelta64
// columns (i64-ns-backed, which `as_i64_slice`'s Int64 gate rejects). Probe
// the raw `&[i64]` buffer against an `FxHashSet<i64>` of the SAME-dtype
// needles' i64 payloads, bypassing the generic `Vec<Scalar>` materialization
// + per-row `key_of` + `Key`-hashset probe below.
//
// Bit-identical: a value's generic `Key` is dtype-tagged (`Key::Int64` /
// `Key::Datetime64` / `Key::Timedelta64`), so it matches ONLY a needle of
// its own dtype and the raw i64 payload IS that key's discriminant. The
// all-valid gate means there is no missing value (which the generic path
// maps to false), so direct probing introduces no spurious match; missing
// needles are skipped exactly as `key_of` skips them.
let i64_raw: Option<&[i64]> = match self.dtype {
DType::Int64 => self.as_i64_slice(),
DType::Datetime64 if self.validity.all() => self.as_datetime64_slice(),
DType::Timedelta64 if self.validity.all() => self.as_timedelta64_slice(),
_ => None,
};
if let Some(data) = i64_raw {
let mut set: FxHashSet<i64> = FxHashSet::default();
for n in needles {
if n.is_missing() {
continue;
}
match (self.dtype, n) {
(DType::Int64, Scalar::Int64(v))
| (DType::Datetime64, Scalar::Datetime64(v))
| (DType::Timedelta64, Scalar::Timedelta64(v)) => {
set.insert(*v);
}
_ => {}
}
}
let out: Vec<bool> = data.iter().map(|v| set.contains(v)).collect();
return Ok(Self::from_bool_values(out));
}
// Nullable Int64 isin (sibling of the nullable-Utf8 arm below): the all-valid
// `as_i64_slice` arms above bail on ANY missing, so a nullable Int64 column
// (`df["id"].isin(ids)` over a column WITH nulls) fell to the generic `Vec<Scalar>` +
// per-row `key_of` + `Key`-hashset scan. Probe each PRESENT value against an
// `FxHashSet<i64>` of the Int64 needles; a missing value ⇒ false (== the generic
// `key_of` of a missing value being `None` ⇒ not-in-set; this impl treats
// `missing.isin(..)` as false regardless of the needles, matching the other typed
// arms, NOT pandas' NaN-in-list rule). Output is all-valid Bool. `validity.get` false
// short-circuits without probing.
if self.dtype == DType::Int64
&& let Some((data, validity)) = self.as_i64_slice_with_validity()
{
let mut set: FxHashSet<i64> = FxHashSet::default();
for n in needles {
if let Scalar::Int64(v) = n {
set.insert(*v);
}
}
let out: Vec<bool> = (0..data.len())
.map(|i| validity.get(i) && set.contains(&data[i]))
.collect();
return Ok(Self::from_bool_values(out));
}
// Contiguous-Utf8 fast path (cardinality/dedup-vein sibling of
// unique/value_counts/nunique/mode/duplicated): the generic scan below
// iterates `&self.values`, forcing `as_slice()` to materialize a
// `Vec<Scalar::Utf8>` (one heap `String` per row) then per row calls
// `key_of` + `lookup.contains`. Test membership directly over `&[u8]`
// byte spans with ZERO per-row `String` alloc. The needle set keys on
// each Utf8 needle's bytes: a Utf8 value's generic key is `Key::Utf8`,
// which only matches a Utf8 needle (other-dtype needles carry a distinct
// dtype-tagged key), so non-Utf8 needles are inert here exactly as they
// are inert against a Utf8 value in the generic path. `as_utf8_contiguous`
// matches only all-valid, so no missing value maps to false spuriously.
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
let mut lookup: FxHashSet<&[u8]> = FxHashSet::default();
for n in needles {
if let Scalar::Utf8(s) = n {
lookup.insert(s.as_bytes());
}
}
let out: Vec<bool> = offsets
.windows(2)
.map(|w| lookup.contains(&bytes[w[0]..w[1]]))
.collect();
return Ok(Self::from_bool_values(out));
}
// Nullable contiguous-Utf8 fast path (COLD cache): the all-valid arm above gates
// on `as_utf8_contiguous` (validity.all()), so a `LazyNullableUtf8` column — a
// string column WITH missing rows — fell to the generic scan below, which
// materializes a `Vec<Scalar::Utf8>` (one heap `String` per row). Probe each
// PRESENT row's `&[u8]` span against the same Utf8-needle byte set; a MISSING row
// maps to false. Bit-identical to the generic path: `key_of` of a missing value is
// `None` ⇒ false (this impl treats `missing.isin(..)` as false regardless of the
// needles — matching, NOT pandas' NaN-in-list rule), and a present Utf8 value's
// `Key::Utf8` matches only Utf8 needles (others inert either way). `validity.get`
// false ⇒ the `&&` short-circuits to false without probing. Output all-valid Bool.
// Gated on a COLD `values` cache: the win is skipping the materialization on a
// fresh column (the usual `df[col].isin(..)` shape); a warm/already-materialized
// column defers to the generic `Key` probe over the cached Scalar Vec — no
// regression from the per-row `validity.get`.
if let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
values,
} = &self.values
&& values.get().is_none()
{
let mut lookup: FxHashSet<&[u8]> = FxHashSet::default();
for n in needles {
if let Scalar::Utf8(s) = n {
lookup.insert(s.as_bytes());
}
}
let out: Vec<bool> = (0..offsets.len().saturating_sub(1))
.map(|idx| {
validity.get(idx) && lookup.contains(&bytes[offsets[idx]..offsets[idx + 1]])
})
.collect();
return Ok(Self::from_bool_values(out));
}
let mut lookup: FxHashSet<Key<'_>> = FxHashSet::default();
for n in needles {
if let Some(k) = key_of(n) {
lookup.insert(k);
}
}
// Typed all-valid Bool output — every slot is a definite true/false
// (missing input maps to false, never to a missing output), so this is
// the same column `Self::new(DType::Bool, Vec<Scalar::Bool>)` builds,
// minus the 32 B/elem Scalar wrap and the validity scan (the Int64
// dense path above already emits this way).
let out: Vec<bool> = self
.values
.iter()
.map(|v| match key_of(v) {
Some(k) => lookup.contains(&k),
None => false,
})
.collect();
Ok(Self::from_bool_values(out))
}
/// Unique values in first-seen order, missing values dropped.
///
/// Matches `pd.Series.unique()` (pandas returns values in order of
/// appearance and drops NaN/NA). Float NaN is deduplicated on bit
/// pattern; +0.0 / -0.0 fold to the same key.
pub fn unique(&self) -> Result<Self, ColumnError> {
// Dense direct-address fast path: an all-valid, bounded-range Int64
// column dedups via a seen-bitset indexed by `v - min` — hash-free, no
// per-element Scalar enum — preserving first-seen order. Bit-identical to
// the HashSet path below (all-valid ⇒ nothing missing to skip; output is
// the same first-seen distinct Int64 values). Same gate as isin/dense
// duplicated (`i64_direct_address_range`).
if let Some(data) = self.as_i64_slice() {
if let Some((min, range)) = i64_direct_address_range(data) {
let mut seen = vec![false; range];
let mut out: Vec<i64> = Vec::new();
for &v in data {
let slot = (v as i128 - min as i128) as usize;
if !seen[slot] {
seen[slot] = true;
out.push(v);
}
}
return Ok(Self::from_i64_values_owned(out));
}
// Wide/sparse all-valid Int64: out of dense-bitset range, but the raw
// &[i64] avoids Scalar materialization — first-seen dedup via the
// open-addressing set (breaks the FxHashSet khash floor). Bit-identical
// to the generic path's first-seen distinct Int64 values.
return Ok(Self::from_i64_values_owned(unique_i64_wide(data)));
}
// Datetime64 is i64-ns-backed: an all-valid column with NO NaT (i64::MIN)
// can reuse the open-addressing i64 dedup over the raw ns, then re-wrap as
// Datetime64 — no Scalar materialization. The generic path SKIPS NaT, so a
// NaT-bearing column (validity-null OR an i64::MIN datum) must fall through.
// Bit-identical: a non-NaT Datetime64's key is the ns value, and first-seen
// order + re-wrapped Scalar::Datetime64 match the generic arm exactly.
if !self.has_nulls()
&& let Some(data) = self.as_datetime64_slice()
&& !data.contains(&i64::MIN)
{
return Ok(Self::from_datetime64_values(unique_i64_wide(data)));
}
// Timedelta64 sibling of the Datetime64 branch above: an all-valid, no-NAT
// column reuses the open-addressing i64 dedup over the raw ns, then re-wraps
// as Timedelta64 -- no Scalar materialization. Bit-identical: a non-NaT
// Timedelta64's key is its ns value, so first-seen order + re-wrapped
// Scalar::Timedelta64 match the generic Key::Timedelta64 arm exactly.
if !self.has_nulls()
&& let Some(data) = self.as_timedelta64_slice()
&& !data.contains(&i64::MIN)
{
let uniq = unique_i64_wide(data);
let len = uniq.len();
return Ok(Self::from_timedelta64_values_with_validity(
uniq,
ValidityMask::all_valid(len),
));
}
// All-valid (NaN-free) Float64: open-addressing over normalized float
// bits, collecting first-seen originals (preserves -0.0). Avoids the
// FxHashSet<FloatBits> + 5M-Scalar materialization of the generic path.
if let Some(data) = self.as_f64_slice() {
return Ok(Self::from_f64_values(unique_f64_wide(data)));
}
// Contiguous-Utf8 fast path: the generic path below iterates
// `&self.values`, which forces `as_slice()` to materialize a
// `Vec<Scalar::Utf8>` -- one heap `String` per row -- then hashes each
// `&str` and clones the first-seen `Scalar`s. Reading the byte buffer
// directly lets us dedup over `&[u8]` spans (byte-equality is exactly
// `&str`-equality for valid UTF-8) with ZERO per-row `String` alloc, then
// rebuild ONE contiguous output buffer. Bit-identical: all-valid means
// nothing is skipped as missing, first-seen order is preserved, and
// `from_utf8_contiguous` yields the same distinct `Scalar::Utf8` sequence
// the generic arm produces (`as_utf8_contiguous` only matches all-valid
// Utf8 backings).
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
// Grow the seen-set and the output buffers on demand (like the generic
// path's `Vec::new()`): the distinct count is unknown, and reserving
// for all `n` rows builds a huge, mostly-empty hash table that thrashes
// cache on every probe when the cardinality is low.
let mut seen: FxHashSet<&[u8]> = FxHashSet::default();
let mut out_bytes: Vec<u8> = Vec::new();
let mut out_offsets: Vec<usize> = Vec::new();
out_offsets.push(0);
for w in offsets.windows(2) {
let span = &bytes[w[0]..w[1]];
if seen.insert(span) {
out_bytes.extend_from_slice(span);
out_offsets.push(out_bytes.len());
}
}
return Ok(Self::from_utf8_contiguous(out_bytes, out_offsets));
}
// Nullable contiguous-Utf8 fast path (COLD cache): the all-valid arm above gates
// on `as_utf8_contiguous` (validity.all()), so a `LazyNullableUtf8` column — a
// string column WITH missing rows — fell to the generic `Key` loop below, which
// materializes a `Vec<Scalar::Utf8>` (one heap `String` per row). FP's `unique`
// DROPS missing (the generic loop's `is_missing ⇒ continue` / `Null ⇒ continue`),
// so dedup ONLY the PRESENT byte spans (validity-set) in first-seen order and
// rebuild ONE contiguous output — every distinct value is a present string, so the
// output is all-valid exactly like the generic path's (which never pushes a null).
// Bit-identical to the generic arm: same present-only first-seen distinct set
// (byte-eq == `Key::Utf8` eq), same order, and `from_utf8_contiguous` yields the
// same `Scalar::Utf8` sequence. Gated on a COLD `values` cache: the win is skipping
// the materialization on a fresh column (the usual `df[col].unique()` shape); a
// warm/already-materialized column defers to the generic `Key` loop over the cached
// Scalar Vec — no regression from the per-row `validity.get`.
if let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
values,
} = &self.values
&& values.get().is_none()
{
let mut seen: FxHashSet<&[u8]> = FxHashSet::default();
let mut out_bytes: Vec<u8> = Vec::new();
let mut out_offsets: Vec<usize> = Vec::new();
out_offsets.push(0);
for (idx, w) in offsets.windows(2).enumerate() {
if !validity.get(idx) {
continue; // unique drops missing (matches the generic loop)
}
let span = &bytes[w[0]..w[1]];
if seen.insert(span) {
out_bytes.extend_from_slice(span);
out_offsets.push(out_bytes.len());
}
}
return Ok(Self::from_utf8_contiguous(out_bytes, out_offsets));
}
#[derive(Hash, PartialEq, Eq)]
enum Key<'a> {
Bool(bool),
Int64(i64),
FloatBits(u64),
Utf8(&'a str),
Timedelta64(i64),
Datetime64(i64),
Period(i64),
Interval(u64, u64, IntervalClosed),
}
let mut seen: FxHashSet<Key<'_>> = FxHashSet::default();
let mut out = Vec::new();
for v in &self.values {
if v.is_missing() {
continue;
}
let key = match v {
Scalar::Bool(b) => Key::Bool(*b),
Scalar::Int64(i) => Key::Int64(*i),
Scalar::Float64(f) => {
let norm = if *f == 0.0 { 0.0 } else { *f };
Key::FloatBits(norm.to_bits())
}
Scalar::Utf8(s) => Key::Utf8(s.as_str()),
Scalar::Timedelta64(v) => Key::Timedelta64(*v),
Scalar::Datetime64(v) => Key::Datetime64(*v),
Scalar::Period(p) => Key::Period(p.ordinal),
Scalar::Interval(v) => {
let (left, right, closed) = interval_key(v);
Key::Interval(left, right, closed)
}
Scalar::Null(_) => continue,
};
if seen.insert(key) {
out.push(v.clone());
}
}
Self::new(self.dtype, out)
}
/// Set difference: values in self that are not in other.
///
/// Matches np.setdiff1d().
pub fn setdiff1d(&self, other: &Self) -> Result<Self, ColumnError> {
let other_unique = other.unique()?;
// O(N+M): hash-set membership for `other`, plus a `seen` set replacing
// the O(N²) `out.any(...)` first-seen dedup.
let other_set: FxHashSet<SetMemberKey<'_>> = other_unique
.values()
.iter()
.filter_map(set_member_key)
.collect();
let mut seen: FxHashSet<SetMemberKey<'_>> = FxHashSet::default();
let mut out = Vec::new();
for v in &self.values {
let Some(key) = set_member_key(v) else {
continue;
};
if !other_set.contains(&key) && seen.insert(key) {
out.push(v.clone());
}
}
Self::new(self.dtype, out)
}
/// Set intersection: values common to both columns.
///
/// Matches np.intersect1d().
pub fn intersect1d(&self, other: &Self) -> Result<Self, ColumnError> {
let self_unique = self.unique()?;
let other_unique = other.unique()?;
let other_set: FxHashSet<SetMemberKey<'_>> = other_unique
.values()
.iter()
.filter_map(set_member_key)
.collect();
let mut out = Vec::new();
for v in self_unique.values() {
let Some(key) = set_member_key(v) else {
continue;
};
if other_set.contains(&key) {
out.push(v.clone());
}
}
Self::new(self.dtype, out)
}
/// Set union: unique values from both columns.
///
/// Matches np.union1d().
pub fn union1d(&self, other: &Self) -> Result<Self, ColumnError> {
let mut combined = self.values.to_vec();
combined.extend(other.values().iter().cloned());
let temp = Self::new(self.dtype, combined)?;
temp.unique()
}
/// Set symmetric difference: unique values in either but not both.
///
/// Matches np.setxor1d(). Returns unique values that are in exactly
/// one of the input arrays.
pub fn setxor1d(&self, other: &Self) -> Result<Self, ColumnError> {
let a_unique = self.unique()?;
let b_unique = other.unique()?;
let a_set: FxHashSet<SetMemberKey<'_>> = a_unique
.values()
.iter()
.filter_map(set_member_key)
.collect();
let b_set: FxHashSet<SetMemberKey<'_>> = b_unique
.values()
.iter()
.filter_map(set_member_key)
.collect();
let mut out = Vec::new();
// Values in a but not in b
for v in a_unique.values() {
let Some(key) = set_member_key(v) else {
continue;
};
if !b_set.contains(&key) {
out.push(v.clone());
}
}
// Values in b but not in a
for v in b_unique.values() {
let Some(key) = set_member_key(v) else {
continue;
};
if !a_set.contains(&key) {
out.push(v.clone());
}
}
Self::new(self.dtype, out)
}
/// Test whether each element is contained in other.
///
/// Matches np.in1d(). Returns Bool column.
pub fn in1d(&self, other: &Self) -> Result<Self, ColumnError> {
let other_unique = other.unique()?;
let other_set: FxHashSet<SetMemberKey<'_>> = other_unique
.values()
.iter()
.filter_map(set_member_key)
.collect();
// Typed all-valid Bool output — same equivalence as isin above.
let mut out = Vec::with_capacity(self.values.len());
for v in &self.values {
let found = match set_member_key(v) {
Some(key) => other_set.contains(&key),
None => false, // missing is never "in" the set (matches the scan)
};
out.push(found);
}
Ok(Self::from_bool_values(out))
}
/// Count occurrences of each distinct value.
///
/// Matches `pd.Series.value_counts()` default behavior at the
/// columnar level: missing values are dropped, counts are sorted
/// descending, and first-seen order breaks ties.
pub fn value_counts(&self) -> Result<(Self, Self), ColumnError> {
self.value_counts_with_options(false, true, false, true)
}
/// Count occurrences of each distinct value with pandas-style options.
///
/// Returns a pair of columns `(values, counts)`. The `values`
/// column preserves the source dtype; the `counts` column is Int64
/// unless `normalize=true`, in which case it is Float64.
pub fn value_counts_with_options(
&self,
normalize: bool,
sort: bool,
ascending: bool,
dropna: bool,
) -> Result<(Self, Self), ColumnError> {
if let Some(data) = self.as_i64_slice() {
return Ok(value_counts_i64_typed(data, normalize, sort, ascending));
}
// Datetime64 / Timedelta64 (i64-ns): an all-valid, no-NAT column reuses the
// typed i64 tally, then re-tags the distinct-VALUES column as the temporal
// dtype (counts are dtype-independent). Bit-identical to the generic path:
// the i64 tally has the same first-seen order + count-sort tie-break, and
// `set_member_key` keys a temporal Scalar by its ns, so the distinct set +
// counts match; only the values column's dtype tag differs, which the
// re-wrap restores. NaT (`i64::MIN`) / nullable falls through (the generic
// path drops missing per `dropna`).
if !self.has_nulls() {
if let Some(data) = self.as_datetime64_slice()
&& !data.contains(&i64::MIN)
{
let (values, counts) = value_counts_i64_typed(data, normalize, sort, ascending);
let ns = values.as_i64_slice().expect("typed i64 values").to_vec();
return Ok((Column::from_datetime64_values(ns), counts));
}
if let Some(data) = self.as_timedelta64_slice()
&& !data.contains(&i64::MIN)
{
let (values, counts) = value_counts_i64_typed(data, normalize, sort, ascending);
let ns = values.as_i64_slice().expect("typed i64 values").to_vec();
let len = ns.len();
return Ok((
Column::from_timedelta64_values_with_validity(ns, ValidityMask::all_valid(len)),
counts,
));
}
}
// Contiguous-Utf8 fast path (sibling of `Column::unique`'s byte-span
// dedup): the generic tally below iterates `&self.values`, forcing
// `as_slice()` to materialize a `Vec<Scalar::Utf8>` -- one heap `String`
// per row -- then keys each row with `set_member_key`. Tally the byte
// spans directly via `FxHashMap<&[u8], usize>` (byte-equality is exactly
// `&str`-equality for valid UTF-8) with ZERO per-row `String` alloc, keep
// the first-seen counts order, and build a CONTIGUOUS distinct-values
// column. `as_utf8_contiguous` only matches an all-valid backing, so
// `missing_count` stays 0 and `dropna` is a no-op. Bit-identical to the
// generic arm: same first-seen distinct set, same counts, the same stable
// count-sort tie-break, and the same normalize/Int64 counts column.
if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
// `index` and `tally` grow on demand (distinct count unknown): sizing
// them to the row count would build a huge mostly-empty table that
// thrashes cache when cardinality is low.
let mut index: rustc_hash::FxHashMap<&[u8], usize> = rustc_hash::FxHashMap::default();
let mut tally: Vec<(&[u8], usize)> = Vec::new();
for w in offsets.windows(2) {
let span = &bytes[w[0]..w[1]];
if let Some(&i) = index.get(span) {
tally[i].1 += 1;
} else {
index.insert(span, tally.len());
tally.push((span, 1));
}
}
if sort {
if ascending {
tally.sort_by_key(|(_, count)| *count);
} else {
tally.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
}
}
let total = if normalize {
tally.iter().map(|(_, count)| *count).sum::<usize>() as f64
} else {
1.0
};
let mut values_bytes: Vec<u8> = Vec::new();
let mut values_offsets: Vec<usize> = Vec::with_capacity(tally.len() + 1);
values_offsets.push(0);
let mut counts_out: Vec<Scalar> = Vec::with_capacity(tally.len());
for (span, count) in &tally {
values_bytes.extend_from_slice(span);
values_offsets.push(values_bytes.len());
if normalize {
let normalized = if total == 0.0 {
0.0
} else {
*count as f64 / total
};
counts_out.push(Scalar::Float64(normalized));
} else {
counts_out.push(Scalar::Int64(i64::try_from(*count).unwrap_or(i64::MAX)));
}
}
let values = Self::from_utf8_contiguous(values_bytes, values_offsets);
let counts = Self::new(
if normalize {
DType::Float64
} else {
DType::Int64
},
counts_out,
)?;
return Ok((values, counts));
}
// Nullable contiguous-Utf8 fast path (dropna=true, COLD cache): the all-valid arm
// above gates on `as_utf8_contiguous` (validity.all()), so a `LazyNullableUtf8`
// column — a string column WITH missing rows, the common CSV/parquet shape — fell
// to the generic `Vec<Scalar::Utf8>` + `set_member_key` tally below. Under the
// default `dropna=true`, missing rows are dropped, so tally ONLY the present byte
// spans (validity-set) via `FxHashMap<&[u8], usize>` and build a CONTIGUOUS
// distinct-values column — every distinct value is a present string, so the output
// is all-valid exactly like the generic path's (which drops missing before
// building values_out). Bit-identical: same present-only first-seen distinct set
// (byte-eq == set_member_key Utf8 eq), same counts, same stable count-sort
// tie-break, same normalize/Int64 counts.
//
// Gated on a COLD `values` cache: the whole win is skipping the ~30 B/row
// `Vec<Scalar::Utf8>` materialization the generic path pays on first touch (~5x on
// a fresh column, the usual `df[col].value_counts()` shape). If that cache is
// ALREADY populated (a prior op materialized it), the per-row `validity.get`
// typed tally is marginally slower than the generic tally over the warm Scalar
// Vec, so we defer to it — no regression. `dropna=false` (which would append a
// `Null(NaN)` count category, making the values column non-contiguous) also keeps
// the generic path.
if dropna
&& let ScalarValues::LazyNullableUtf8 {
bytes,
offsets,
validity,
values,
} = &self.values
&& values.get().is_none()
{
let mut index: rustc_hash::FxHashMap<&[u8], usize> = rustc_hash::FxHashMap::default();
let mut tally: Vec<(&[u8], usize)> = Vec::new();
for (i, w) in offsets.windows(2).enumerate() {
if !validity.get(i) {
continue; // dropna: skip missing rows
}
let span = &bytes[w[0]..w[1]];
if let Some(&j) = index.get(span) {
tally[j].1 += 1;
} else {
index.insert(span, tally.len());
tally.push((span, 1));
}
}
if sort {
if ascending {
tally.sort_by_key(|(_, count)| *count);
} else {
tally.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
}
}
let total = if normalize {
tally.iter().map(|(_, count)| *count).sum::<usize>() as f64
} else {
1.0
};
let mut values_bytes: Vec<u8> = Vec::new();
let mut values_offsets: Vec<usize> = Vec::with_capacity(tally.len() + 1);
values_offsets.push(0);
let mut counts_out: Vec<Scalar> = Vec::with_capacity(tally.len());
for (span, count) in &tally {
values_bytes.extend_from_slice(span);
values_offsets.push(values_bytes.len());
if normalize {
let normalized = if total == 0.0 {
0.0
} else {
*count as f64 / total
};
counts_out.push(Scalar::Float64(normalized));
} else {
counts_out.push(Scalar::Int64(i64::try_from(*count).unwrap_or(i64::MAX)));
}
}
let values = Self::from_utf8_contiguous(values_bytes, values_offsets);
let counts = Self::new(
if normalize {
DType::Float64
} else {
DType::Int64
},
counts_out,
)?;
return Ok((values, counts));
}
// O(N) tally: a `set_member_key`-keyed hash map gives O(1) lookup
// instead of the old O(distinct) linear `counts.iter().find(semantic_eq)`
// per value (O(N·distinct), quadratic for high-cardinality data). The
// `counts` Vec is still built in first-seen order, so the later
// stable count-sort breaks ties identically. Bit-identical: is_missing()
// is tested first (so NaN/NAT sentinels stay in missing_count exactly as
// before), and for the remaining values set_member_key equality matches
// semantic_eq (the same key Column::unique uses; ±0.0 normalized).
let mut counts: Vec<(Scalar, usize)> = Vec::new();
let mut missing_count = 0_usize;
// Dense-int64 fast path: an all-valid Int64 column with a bounded value
// range -> O(1) direct-address counting (no hashing, no set_member_key,
// no Scalar materialization) — beats the khash-class hash tally. Pushes
// into `counts` in FIRST-SEEN order so the stable count-sort below breaks
// ties identically to the hash path. Bit-identical: all-valid => no
// missing (missing_count stays 0), and Scalar::Int64(v) is the same value
// the hash path stores. Falls back when range is too large (sparse keys).
let dense_done = 'dense: {
let Some(vals) = self.as_i64_slice() else {
break 'dense false;
};
if vals.is_empty() {
break 'dense false;
}
let (mut lo, mut hi) = (vals[0], vals[0]);
for &v in vals {
if v < lo {
lo = v;
}
if v > hi {
hi = v;
}
}
let range = (hi as i128) - (lo as i128) + 1;
let cap = ((vals.len() as i128) * 4).max(1 << 16);
if range <= 0 || range > cap {
break 'dense false;
}
let mut dense = vec![0_usize; range as usize];
let mut first_seen: Vec<i64> = Vec::new();
for &v in vals {
let idx = (v - lo) as usize;
if dense[idx] == 0 {
first_seen.push(v);
}
dense[idx] += 1;
}
for v in first_seen {
counts.push((Scalar::Int64(v), dense[(v - lo) as usize]));
}
true
};
if !dense_done {
let mut index: rustc_hash::FxHashMap<SetMemberKey<'_>, usize> =
rustc_hash::FxHashMap::default();
for value in &self.values {
if value.is_missing() {
missing_count += 1;
continue;
}
let Some(key) = set_member_key(value) else {
// Unreachable: every non-missing scalar has a key.
counts.push((value.clone(), 1));
continue;
};
if let Some(&i) = index.get(&key) {
counts[i].1 += 1;
} else {
index.insert(key, counts.len());
counts.push((value.clone(), 1));
}
}
}
if !dropna && missing_count > 0 {
counts.push((Scalar::Null(NullKind::NaN), missing_count));
}
if sort {
if ascending {
counts.sort_by_key(|(_, count)| *count);
} else {
counts.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
}
}
let total = if normalize {
counts.iter().map(|(_, count)| *count).sum::<usize>() as f64
} else {
1.0
};
let mut values_out = Vec::with_capacity(counts.len());
let mut counts_out = Vec::with_capacity(counts.len());
for (value, count) in counts {
values_out.push(value);
if normalize {
let normalized = if total == 0.0 {
0.0
} else {
count as f64 / total
};
counts_out.push(Scalar::Float64(normalized));
} else {
counts_out.push(Scalar::Int64(i64::try_from(count).unwrap_or(i64::MAX)));
}
}
let values = Self::new(self.dtype, values_out)?;
let counts = Self::new(
if normalize {
DType::Float64
} else {
DType::Int64
},
counts_out,
)?;
Ok((values, counts))
}
#[must_use]
pub fn semantic_eq(&self, other: &Self) -> bool {
self.dtype == other.dtype
&& self.values.len() == other.values.len()
&& self
.values
.iter()
.zip(&other.values)
.all(|(left, right)| left.semantic_eq(right))
}
/// Element-wise comparison for approximate equality.
///
/// Matches np.isclose(). Returns True where |a - b| <= atol + rtol * |b|.
pub fn isclose(&self, other: &Self, rtol: f64, atol: f64) -> Result<Self, ColumnError> {
if self.len() != other.len() {
return Err(ColumnError::LengthMismatch {
left: self.len(),
right: other.len(),
});
}
// Typed pairwise fast path: both columns Float64/Int64 (all-valid or nullable).
// Both-present ⇒ (af−bf).abs() <= atol + rtol*bf.abs(); either-missing ⇒ false.
// Output is an ALL-VALID Bool column (isclose maps missing→Bool(false), not
// Null). Bit-identical to the Scalar loop: get_present == !is_missing (validity
// -set AND non-NaN for Float64, KEEPING ±inf — matching to_f64 which keeps ±inf
// and is_missing which drops NaN; validity-set for Int64), and the closeness
// arithmetic + comparison is the same. Covers mixed i64×f64.
if let (Some(sa), Some(sb)) = (self.typed_numeric_values(), other.typed_numeric_values()) {
let n = sa.len().min(sb.len());
let bools: Vec<bool> = (0..n)
.map(|i| match (sa.get_present(i), sb.get_present(i)) {
(Some(af), Some(bf)) => (af - bf).abs() <= atol + rtol * bf.abs(),
_ => false,
})
.collect();
return Ok(Self::from_bool_values(bools));
}
let mut out = Vec::with_capacity(self.values.len());
for (a, b) in self.values.iter().zip(&other.values) {
if a.is_missing() || b.is_missing() {
out.push(Scalar::Bool(false));
continue;
}
let af = a.to_f64().map_err(ColumnError::Type)?;
let bf = b.to_f64().map_err(ColumnError::Type)?;
let close = (af - bf).abs() <= atol + rtol * bf.abs();
out.push(Scalar::Bool(close));
}
Self::new(DType::Bool, out)
}
/// Check if all elements are approximately equal.
///
/// Matches np.allclose(). Returns True if all pairs satisfy isclose.
pub fn allclose(&self, other: &Self, rtol: f64, atol: f64) -> Result<bool, ColumnError> {
let close = self.isclose(other, rtol, atol)?;
for v in close.values() {
match v {
Scalar::Bool(true) => continue,
Scalar::Bool(false) => return Ok(false),
_ => return Ok(false),
}
}
Ok(true)
}
}
// ---------------------------------------------------------------------------
// AG-14: Database Cracking — Adaptive Column Sorting
// ---------------------------------------------------------------------------
/// Adaptive crack index for progressive column partitioning.
///
/// Maintains a permutation of row indices and a sorted set of crack points.
/// Each filter operation partitions the relevant region around the predicate
/// pivot, progressively sorting the column across repeated queries.
///
/// Only works with numeric columns (values convertible to f64).
///
/// # Example
/// ```ignore
/// let mut crack = CrackIndex::new(column.len());
/// let gt5 = crack.filter_gt(&column, 5.0); // partitions around 5.0
/// let gt3 = crack.filter_gt(&column, 3.0); // refines: only re-scans [0, 5.0] region
/// ```
pub struct CrackIndex {
/// Permuted row indices. Between consecutive crack points,
/// elements are unsorted but bounded by the crack values.
perm: Vec<usize>,
/// Sorted crack points: (pivot_value, split_position_in_perm).
/// All perm[..split] map to values <= pivot, perm[split..] map to values > pivot
/// (within the containing region).
cracks: Vec<(f64, usize)>,
}
impl CrackIndex {
/// Create a new crack index for a column of `len` rows.
#[must_use]
pub fn new(len: usize) -> Self {
Self {
perm: (0..len).collect(),
cracks: Vec::new(),
}
}
/// Number of crack points recorded so far.
#[must_use]
pub fn num_cracks(&self) -> usize {
self.cracks.len()
}
/// Return row indices where `column[row] > value`.
pub fn filter_gt(&mut self, column: &Column, value: f64) -> Vec<usize> {
let split = self.crack_at(column, value);
self.perm[split..].to_vec()
}
/// Return row indices where `column[row] <= value`.
pub fn filter_lte(&mut self, column: &Column, value: f64) -> Vec<usize> {
let split = self.crack_at(column, value);
self.perm[..split]
.iter()
.copied()
.filter(|&idx| {
column
.value(idx)
.and_then(|v| v.to_f64().ok())
.is_some_and(|f| f <= value)
})
.collect()
}
/// Return row indices where `column[row] >= value`.
pub fn filter_gte(&mut self, column: &Column, value: f64) -> Vec<usize> {
// Crack just below value: use value - epsilon conceptually.
// We crack at value, then scan the <= region for exact matches.
let split = self.crack_at(column, value);
// Everything in perm[split..] is > value.
// Also include exact matches from perm[..split].
let mut result: Vec<usize> = self.perm[split..].to_vec();
for &idx in &self.perm[..split] {
if let Some(v) = column.value(idx)
&& let Ok(f) = v.to_f64()
&& f == value
{
result.push(idx);
}
}
result
}
/// Return row indices where `column[row] < value`.
pub fn filter_lt(&mut self, column: &Column, value: f64) -> Vec<usize> {
let split = self.crack_at(column, value);
// perm[..split] has values <= value. Filter out exact matches.
self.perm[..split]
.iter()
.copied()
.filter(|&idx| {
column
.value(idx)
.and_then(|v| v.to_f64().ok())
.is_some_and(|f| f < value)
})
.collect()
}
/// Return row indices where `column[row] == value`.
pub fn filter_eq(&mut self, column: &Column, value: f64) -> Vec<usize> {
let split = self.crack_at(column, value);
// Exact matches are all in perm[..split] (the <= region).
self.perm[..split]
.iter()
.copied()
.filter(|&idx| {
column
.value(idx)
.and_then(|v| v.to_f64().ok())
.is_some_and(|f| f == value)
})
.collect()
}
/// Ensure a crack point exists at `value`. Returns the split position
/// such that perm[..split] are all <= value and perm[split..] are all > value.
fn crack_at(&mut self, column: &Column, value: f64) -> usize {
// Check if we already have this exact crack point.
if let Ok(pos) = self.cracks.binary_search_by(|probe| {
probe
.0
.partial_cmp(&value)
.unwrap_or(std::cmp::Ordering::Equal)
}) {
return self.cracks[pos].1;
}
// Find the region to partition: between the nearest crack points.
let (region_start, region_end) = self.find_region(value);
// Partition perm[region_start..region_end] around `value`.
// Move indices with column[idx] <= value to the left, > value to the right.
let split = self.partition_region(column, region_start, region_end, value);
// Insert the new crack point, maintaining sorted order.
let insert_pos = self
.cracks
.binary_search_by(|probe| {
probe
.0
.partial_cmp(&value)
.unwrap_or(std::cmp::Ordering::Equal)
})
.unwrap_or_else(|pos| pos);
self.cracks.insert(insert_pos, (value, split));
split
}
/// Find the region [start, end) in `perm` that contains `value`.
fn find_region(&self, value: f64) -> (usize, usize) {
let mut start = 0;
let mut end = self.perm.len();
for &(crack_val, crack_pos) in &self.cracks {
if crack_val < value {
start = start.max(crack_pos);
} else {
end = end.min(crack_pos);
break;
}
}
(start, end)
}
/// Partition perm[start..end] so that indices with column values <= pivot
/// come first. Returns the split position (absolute index in perm).
fn partition_region(&mut self, column: &Column, start: usize, end: usize, pivot: f64) -> usize {
// Simple two-pointer partition (like quicksort partition).
let region = &mut self.perm[start..end];
let mut write = 0;
for read in 0..region.len() {
let idx = region[read];
let val = column
.value(idx)
.and_then(|v| v.to_f64().ok())
.unwrap_or(f64::NEG_INFINITY); // missing values sort to left
if val <= pivot {
region.swap(write, read);
write += 1;
}
}
start + write
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use fp_types::{
DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
};
use super::{
ArithmeticOp, BoolAffineSelectionWitness, Column, ColumnData, ColumnError, ScalarValues,
SparseColumn, ValidityMask,
};
#[test]
#[ignore = "foreground profile-first A/B"]
fn trapz_raw_float64_profile_gc20b() {
use std::{hint::black_box, time::Instant};
fn former(column: &Column, dx: f64) -> Scalar {
let n = column.values.len();
if n < 2 {
return Scalar::Float64(0.0);
}
let vals = column
.values
.iter()
.map(|value| value.to_f64().unwrap_or(0.0))
.collect::<Vec<_>>();
let mut sum = 0.0;
for i in 1..n {
sum += (vals[i - 1] + vals[i]) / 2.0 * dx;
}
Scalar::Float64(sum)
}
fn float_bits(value: Scalar) -> u64 {
match value {
Scalar::Float64(value) => value.to_bits(),
other => panic!("expected Float64 trapz result, got {other:?}"),
}
}
fn elapsed(input: &[f64], dx: f64, candidate_arm: bool) -> u128 {
let column = Column::from_f64_values(input.to_vec());
let started = Instant::now();
let result = if candidate_arm {
black_box(&column)
.trapz(dx)
.expect("public candidate trapz")
} else {
former(black_box(&column), dx)
};
black_box(float_bits(result));
started.elapsed().as_nanos()
}
fn percentile(samples: &mut [u128], percent: usize) -> u128 {
samples.sort_unstable();
samples[(samples.len().saturating_sub(1) * percent) / 100]
}
for (values, dx) in [
(Vec::new(), 1.0),
(vec![-0.0], -0.0),
(vec![-0.0, 0.0], 1.0),
(vec![f64::NEG_INFINITY, -1.0, 1.0], 0.5),
(vec![-f64::MAX, f64::MAX], f64::INFINITY),
(vec![1.0, 2.0, 4.0, 8.0], f64::NAN),
] {
let column = Column::from_f64_values(values);
assert_eq!(
float_bits(former(&column, dx)),
float_bits(column.trapz(dx).expect("public candidate trapz")),
);
}
const ROWS: usize = 262_144;
const SAMPLES: usize = 16;
let input = (0..ROWS)
.map(|index| ((index % 1_009) as f64 - 504.0) * 0.25)
.collect::<Vec<_>>();
let dx = 0.125;
let column = Column::from_f64_values(input.clone());
assert_eq!(
float_bits(former(&column, dx)),
float_bits(column.trapz(dx).expect("public candidate trapz")),
);
for _ in 0..2 {
black_box(elapsed(&input, dx, false));
black_box(elapsed(&input, dx, true));
}
let mut former_ns = Vec::with_capacity(SAMPLES);
let mut candidate_ns = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample % 2 == 0 {
former_ns.push(elapsed(&input, dx, false));
candidate_ns.push(elapsed(&input, dx, true));
} else {
candidate_ns.push(elapsed(&input, dx, true));
former_ns.push(elapsed(&input, dx, false));
}
}
let mut former_sorted = former_ns.clone();
let mut candidate_sorted = candidate_ns.clone();
let former_p50 = percentile(&mut former_sorted, 50);
let former_p95 = percentile(&mut former_sorted, 95);
let candidate_p50 = percentile(&mut candidate_sorted, 50);
let candidate_p95 = percentile(&mut candidate_sorted, 95);
println!(
"TRAPZ_RAW_FLOAT64_PROFILE rows={ROWS} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup_p50={:.6} former_p95_ns={former_p95} candidate_p95_ns={candidate_p95} speedup_p95={:.6} former_samples={former_ns:?} candidate_samples={candidate_ns:?}",
former_p50 as f64 / candidate_p50 as f64,
former_p95 as f64 / candidate_p95 as f64,
);
}
#[test]
fn trapz_raw_float64_matches_scalar_path_gc20b() {
fn former(column: &Column, dx: f64) -> Scalar {
let n = column.values.len();
if n < 2 {
return Scalar::Float64(0.0);
}
let vals = column
.values
.iter()
.map(|value| value.to_f64().unwrap_or(0.0))
.collect::<Vec<_>>();
let mut sum = 0.0;
for i in 1..n {
sum += (vals[i - 1] + vals[i]) / 2.0 * dx;
}
Scalar::Float64(sum)
}
fn float_bits(value: Scalar) -> u64 {
match value {
Scalar::Float64(value) => value.to_bits(),
other => panic!("expected Float64 trapz result, got {other:?}"),
}
}
for (values, dx) in [
(Vec::new(), 1.0),
(vec![-0.0], -0.0),
(vec![-0.0, 0.0], 1.0),
(vec![f64::NEG_INFINITY, -1.0, 1.0], 0.5),
(vec![-f64::MAX, f64::MAX], f64::INFINITY),
(vec![1.0, 2.0, 4.0, 8.0], f64::NAN),
] {
let column = Column::from_f64_values(values);
assert_eq!(
float_bits(column.trapz(dx).expect("public candidate trapz")),
float_bits(former(&column, dx)),
);
}
}
#[test]
fn validity_mask_slice_packed_matches_bit_reference_y7i9g() {
for source_len in [0, 1, 2, 63, 64, 65, 127, 128, 129, 257] {
let mut mask = ValidityMask::all_valid(source_len);
if source_len > 0 {
mask.set(source_len / 2, false);
for position in (3..source_len).step_by(11) {
mask.set(position, false);
}
}
for start in [
0,
1,
63,
64,
65,
source_len.saturating_sub(1),
source_len,
source_len.saturating_add(1),
] {
for take_len in [0, 1, 2, 63, 64, 65, 129, usize::MAX] {
let expected = if start >= source_len {
Vec::new()
} else {
(start..start.saturating_add(take_len).min(source_len))
.map(|position| mask.get(position))
.collect::<Vec<_>>()
};
let actual = mask.slice(start, take_len);
assert_eq!(actual.len(), expected.len());
assert_eq!(actual.bits().collect::<Vec<_>>(), expected);
}
}
}
}
#[test]
#[ignore = "foreground release attribution harness"]
fn validity_mask_slice_packed_ab_y7i9g() {
const ROWS: usize = 1_000_003;
const START: usize = 37;
const SLICE_LEN: usize = 900_001;
const SAMPLES: usize = 10;
fn former(mask: &ValidityMask, start: usize, len: usize) -> ValidityMask {
if start >= mask.len {
return ValidityMask::all_invalid(0);
}
let effective_len = len.min(mask.len - start);
if mask.is_all_valid_sentinel() {
return ValidityMask::all_valid(effective_len);
}
let mut out = ValidityMask::all_invalid(effective_len);
for i in 0..effective_len {
if mask.get(start + i) {
out.set(i, true);
}
}
out
}
fn elapsed(
mask: &ValidityMask,
slice: fn(&ValidityMask, usize, usize) -> ValidityMask,
) -> u128 {
let started = std::time::Instant::now();
let output = std::hint::black_box(slice(std::hint::black_box(mask), START, SLICE_LEN));
std::hint::black_box(output.len());
drop(output);
started.elapsed().as_nanos()
}
let mut packed = ValidityMask::all_valid(ROWS);
for position in (3..ROWS).step_by(97) {
packed.set(position, false);
}
let sparse = ValidityMask::from_invalid_ranges(
Arc::from(vec![(0, 3), (65, 2), (777, 99)].into_boxed_slice()),
1_024,
);
let parity_masks = [
ValidityMask::all_valid(0),
ValidityMask::all_valid(130),
ValidityMask::all_invalid(130),
packed.clone(),
sparse,
];
for mask in &parity_masks {
for &(start, len) in &[
(0, 0),
(0, 1),
(0, 64),
(1, 65),
(63, 130),
(64, 129),
(65, usize::MAX),
(mask.len(), 1),
(mask.len().saturating_add(1), 5),
] {
assert_eq!(mask.slice(start, len), former(mask, start, len));
}
}
let expected = former(&packed, START, SLICE_LEN);
assert_eq!(packed.slice(START, SLICE_LEN), expected);
for _ in 0..2 {
std::hint::black_box(elapsed(&packed, former));
std::hint::black_box(elapsed(&packed, ValidityMask::slice));
}
let mut former_samples = Vec::with_capacity(SAMPLES);
let mut candidate_samples = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample.is_multiple_of(2) {
former_samples.push(elapsed(&packed, former));
candidate_samples.push(elapsed(&packed, ValidityMask::slice));
} else {
candidate_samples.push(elapsed(&packed, ValidityMask::slice));
former_samples.push(elapsed(&packed, former));
}
}
former_samples.sort_unstable();
candidate_samples.sort_unstable();
let former_p50 = former_samples[SAMPLES / 2];
let candidate_p50 = candidate_samples[SAMPLES / 2];
eprintln!(
"VALIDITY_SLICE_PACKED_AB rows={ROWS} start={START} len={SLICE_LEN} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
former_p50 as f64 / candidate_p50 as f64,
);
eprintln!("VALIDITY_SLICE_PACKED_AB former_samples_ns={former_samples:?}");
eprintln!("VALIDITY_SLICE_PACKED_AB candidate_samples_ns={candidate_samples:?}");
}
#[test]
#[ignore = "foreground release attribution harness"]
fn validity_mask_all_short_circuit_ab_x7u6w() {
const ROWS: usize = 1_000_003;
const BATCH: usize = 256;
fn former(mask: &ValidityMask) -> bool {
if mask.is_all_valid_sentinel() {
return true;
}
mask.count_valid() == mask.len
}
fn elapsed(mask: &ValidityMask, check: fn(&ValidityMask) -> bool) -> u128 {
std::hint::black_box(check(std::hint::black_box(mask)));
let started = std::time::Instant::now();
for _ in 0..BATCH {
std::hint::black_box(check(std::hint::black_box(mask)));
}
started.elapsed().as_nanos()
}
fn median(samples: &mut [u128]) -> u128 {
samples.sort_unstable();
samples[samples.len() / 2]
}
let mut restored = ValidityMask::all_valid(70);
restored.set(5, false);
restored.set(5, true);
let cases = [
ValidityMask::all_valid(0),
ValidityMask::all_valid(70),
ValidityMask::all_invalid(70),
restored,
ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 2), (65, 1)]), 70),
];
for mask in &cases {
assert_eq!(former(mask), mask.all());
}
let mut mask = ValidityMask::all_valid(ROWS);
mask.set(257, false);
assert!(!former(&mask));
assert_eq!(former(&mask), mask.all());
for _ in 0..2 {
std::hint::black_box(elapsed(&mask, former));
std::hint::black_box(elapsed(&mask, ValidityMask::all));
}
let mut former_samples = Vec::with_capacity(18);
let mut candidate_samples = Vec::with_capacity(18);
for block in 0_usize..9 {
if block.is_multiple_of(2) {
former_samples.push(elapsed(&mask, former));
candidate_samples.push(elapsed(&mask, ValidityMask::all));
candidate_samples.push(elapsed(&mask, ValidityMask::all));
former_samples.push(elapsed(&mask, former));
} else {
candidate_samples.push(elapsed(&mask, ValidityMask::all));
former_samples.push(elapsed(&mask, former));
former_samples.push(elapsed(&mask, former));
candidate_samples.push(elapsed(&mask, ValidityMask::all));
}
}
let former_p50 = median(&mut former_samples);
let candidate_p50 = median(&mut candidate_samples);
eprintln!(
"VALIDITY_ALL_SHORT_CIRCUIT_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
former_p50 as f64 / candidate_p50 as f64,
);
eprintln!("VALIDITY_ALL_SHORT_CIRCUIT_AB former_samples_ns={former_samples:?}");
eprintln!("VALIDITY_ALL_SHORT_CIRCUIT_AB candidate_samples_ns={candidate_samples:?}");
}
#[test]
#[ignore = "foreground release attribution harness"]
fn validity_mask_any_short_circuit_ab_dbtw5() {
const ROWS: usize = 1_000_003;
const BATCH: usize = 4_096;
fn former(mask: &ValidityMask) -> bool {
if mask.is_all_valid_sentinel() {
return true;
}
mask.count_valid() > 0
}
fn candidate(mask: &ValidityMask) -> bool {
mask.any()
}
fn elapsed(mask: &ValidityMask, check: fn(&ValidityMask) -> bool) -> u128 {
std::hint::black_box(check(std::hint::black_box(mask)));
let started = std::time::Instant::now();
for _ in 0..BATCH {
std::hint::black_box(check(std::hint::black_box(mask)));
}
started.elapsed().as_nanos()
}
fn median(samples: &mut [u128]) -> u128 {
samples.sort_unstable();
samples[samples.len() / 2]
}
let mut restored = ValidityMask::all_valid(70);
restored.set(5, false);
restored.set(5, true);
let mut early_valid = ValidityMask::all_invalid(70);
early_valid.set(1, true);
let mut late_valid = ValidityMask::all_invalid(70);
late_valid.set(69, true);
let cases = [
ValidityMask::all_valid(0),
ValidityMask::all_valid(70),
ValidityMask::all_invalid(70),
restored,
early_valid,
late_valid,
ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 2), (65, 1)]), 70),
ValidityMask::from_invalid_ranges(Arc::from(vec![(0, 70)]), 70),
];
for mask in &cases {
assert_eq!(former(mask), candidate(mask));
}
let mut mask = ValidityMask::all_invalid(ROWS);
mask.set(257, true);
assert!(former(&mask));
assert_eq!(former(&mask), candidate(&mask));
for _ in 0..2 {
std::hint::black_box(elapsed(&mask, former));
std::hint::black_box(elapsed(&mask, candidate));
}
let mut former_samples = Vec::with_capacity(18);
let mut candidate_samples = Vec::with_capacity(18);
let mut null_ratios = Vec::with_capacity(9);
for block in 0_usize..9 {
let (former_a, candidate_a, candidate_b, former_b) = if block.is_multiple_of(2) {
(
elapsed(&mask, former),
elapsed(&mask, candidate),
elapsed(&mask, candidate),
elapsed(&mask, former),
)
} else {
let candidate_a = elapsed(&mask, candidate);
let former_a = elapsed(&mask, former);
let former_b = elapsed(&mask, former);
let candidate_b = elapsed(&mask, candidate);
(former_a, candidate_a, candidate_b, former_b)
};
former_samples.extend([former_a, former_b]);
candidate_samples.extend([candidate_a, candidate_b]);
let lo = candidate_a.min(candidate_b).max(1);
null_ratios.push(candidate_a.max(candidate_b) as f64 / lo as f64);
}
let former_p50 = median(&mut former_samples);
let candidate_p50 = median(&mut candidate_samples);
null_ratios.sort_by(f64::total_cmp);
let null_p50 = null_ratios[null_ratios.len() / 2];
eprintln!(
"VALIDITY_ANY_SHORT_CIRCUIT_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6} null_p50={null_p50:.6}",
former_p50 as f64 / candidate_p50 as f64,
);
eprintln!("VALIDITY_ANY_SHORT_CIRCUIT_AB former_samples_ns={former_samples:?}");
eprintln!("VALIDITY_ANY_SHORT_CIRCUIT_AB candidate_samples_ns={candidate_samples:?}");
}
#[test]
#[ignore = "foreground release attribution harness"]
fn has_any_missing_first_invalid_word_ab_m32bh() {
const ROWS: usize = 1_000_003;
const BATCH: usize = 256;
fn former(column: &Column) -> bool {
if column.dtype == DType::Float64 {
if let Some((data, validity)) = column.as_f64_slice_with_validity() {
return data
.iter()
.enumerate()
.any(|(idx, value)| !validity.get(idx) || value.is_nan());
}
if let Some(data) = column.as_f64_slice() {
return data.iter().any(|value| value.is_nan());
}
}
if matches!(
column.dtype,
DType::Bool
| DType::BoolNullable
| DType::Int64
| DType::Int64Nullable
| DType::Utf8
| DType::Interval
) {
return column.validity.count_invalid() > 0;
}
column.values.iter().any(Scalar::is_missing)
}
fn candidate(column: &Column) -> bool {
column.has_any_missing()
}
fn elapsed(column: &Column, check: fn(&Column) -> bool) -> u128 {
std::hint::black_box(check(std::hint::black_box(column)));
let started = std::time::Instant::now();
for _ in 0..BATCH {
std::hint::black_box(check(std::hint::black_box(column)));
}
started.elapsed().as_nanos()
}
fn median(samples: &mut [u128]) -> u128 {
samples.sort_unstable();
samples[samples.len() / 2]
}
let parity_cases = [
Column::from_values(Vec::<Scalar>::new()).expect("empty column"),
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("all-valid int64"),
Column::from_i64_values_with_validity(vec![0, 0, 0], ValidityMask::all_invalid(3)),
Column::from_i64_values_with_validity(
vec![1, 2, 3, 4, 5, 6],
ValidityMask::from_invalid_ranges(Arc::from(vec![(0, 2), (5, 1)]), 6),
),
Column::from_values(vec![Scalar::Bool(true), Scalar::Null(NullKind::Null)])
.expect("nullable bool"),
Column::from_values(vec![
Scalar::Utf8("x".to_owned()),
Scalar::Null(NullKind::Null),
])
.expect("nullable utf8"),
Column::from_f64_values(vec![1.0, f64::NAN, 3.0]),
Column::from_values(vec![Scalar::Datetime64(1), Scalar::Datetime64(i64::MIN)])
.expect("datetime fallback"),
];
for column in &parity_cases {
assert_eq!(former(column), candidate(column));
}
let mut validity = ValidityMask::all_valid(ROWS);
validity.set(257, false);
let column = Column::from_i64_values_with_validity(vec![7; ROWS], validity);
assert!(former(&column));
assert_eq!(former(&column), candidate(&column));
for _ in 0..2 {
std::hint::black_box(elapsed(&column, former));
std::hint::black_box(elapsed(&column, candidate));
}
let mut former_samples = Vec::with_capacity(18);
let mut candidate_samples = Vec::with_capacity(18);
for block in 0_usize..9 {
if block.is_multiple_of(2) {
former_samples.push(elapsed(&column, former));
candidate_samples.push(elapsed(&column, candidate));
candidate_samples.push(elapsed(&column, candidate));
former_samples.push(elapsed(&column, former));
} else {
candidate_samples.push(elapsed(&column, candidate));
former_samples.push(elapsed(&column, former));
former_samples.push(elapsed(&column, former));
candidate_samples.push(elapsed(&column, candidate));
}
}
let former_p50 = median(&mut former_samples);
let candidate_p50 = median(&mut candidate_samples);
eprintln!(
"HAS_ANY_MISSING_FIRST_INVALID_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
former_p50 as f64 / candidate_p50 as f64,
);
eprintln!("HAS_ANY_MISSING_FIRST_INVALID_AB former_samples_ns={former_samples:?}");
eprintln!("HAS_ANY_MISSING_FIRST_INVALID_AB candidate_samples_ns={candidate_samples:?}");
}
#[test]
fn reindex_injects_missing_values() {
let column = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)])
.expect("column should build");
let out = column
.reindex_by_positions(&[Some(1), None, Some(0)])
.expect("reindex should work");
assert_eq!(
out.values(),
&[
Scalar::Int64(20),
Scalar::Null(NullKind::Null),
Scalar::Int64(10)
]
);
}
#[test]
fn take_positions_matches_validated_materialization() {
let column = Column::new(
DType::Float64,
vec![
Scalar::Float64(1.5),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.5),
],
)
.expect("column should build");
let positions = [2, 1, 0, 2];
let gathered = column.take_positions(&positions);
let expected_values = positions
.iter()
.map(|&position| column.values()[position].clone())
.collect::<Vec<_>>();
let expected =
Column::new(column.dtype(), expected_values).expect("validated materialization");
assert_eq!(gathered.dtype(), expected.dtype());
assert_eq!(gathered.values(), expected.values());
assert_eq!(gathered.validity(), expected.validity());
let empty = column.take_positions(&[]);
assert_eq!(empty.dtype(), column.dtype());
assert!(empty.values().is_empty());
assert_eq!(empty.validity(), &ValidityMask::all_invalid(0));
}
#[test]
fn take_position_runs_nullable_float64_matches_take_positions() {
let column =
Column::from_f64_values(vec![1.0, 2.0, f64::NAN, 4.0, 5.0, 6.0, f64::NAN, 8.0]);
let runs = [(0, 2), (3, 3), (7, 1)];
let positions = [0, 1, 3, 4, 5, 7];
assert!(column.supports_fast_position_run_gather());
let gathered = column.take_position_runs(&runs, positions.len());
let expected = column.take_positions(&positions);
assert_eq!(gathered.dtype(), expected.dtype());
assert_eq!(gathered.values(), expected.values());
assert_eq!(gathered.validity(), expected.validity());
assert!(matches!(
&gathered.values,
ScalarValues::LazyAllValidFloat64 { .. } | ScalarValues::LazyNullableFloat64 { .. }
));
}
#[test]
fn take_positions_all_valid_primitives_match_validated_materialization() {
let cases = [
(
DType::Bool,
vec![Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(false)],
),
(
DType::Int64,
vec![Scalar::Int64(10), Scalar::Int64(-5), Scalar::Int64(42)],
),
(
DType::Float64,
vec![
Scalar::Float64(1.25),
Scalar::Float64(-0.0),
Scalar::Float64(9.5),
],
),
(
DType::Timedelta64,
vec![
Scalar::Timedelta64(10),
Scalar::Timedelta64(-5),
Scalar::Timedelta64(42),
],
),
(
DType::Datetime64,
vec![
Scalar::Datetime64(10),
Scalar::Datetime64(-5),
Scalar::Datetime64(42),
],
),
(
DType::Period,
vec![
Scalar::Period(Period::new(10, PeriodFreq::Daily)),
Scalar::Period(Period::new(-5, PeriodFreq::Daily)),
Scalar::Period(Period::new(42, PeriodFreq::Daily)),
],
),
];
let positions = [2, 0, 2, 1];
for (dtype, values) in cases {
let column = Column::new(dtype, values).expect("column should build");
let gathered = column.take_positions(&positions);
let expected_values = positions
.iter()
.map(|&position| column.values()[position].clone())
.collect::<Vec<_>>();
let expected =
Column::new(column.dtype(), expected_values).expect("validated materialization");
assert_eq!(gathered.dtype(), expected.dtype());
assert_eq!(gathered.values(), expected.values());
assert_eq!(gathered.validity(), expected.validity());
}
}
#[test]
fn period_take_positions_defers_scalar_materialization() {
let column = Column::new(
DType::Period,
vec![
Scalar::Period(Period::new(10, PeriodFreq::Monthly)),
Scalar::Period(Period::new(-5, PeriodFreq::Monthly)),
Scalar::Period(Period::new(42, PeriodFreq::Monthly)),
],
)
.expect("column should build");
let positions = [2, 0, 1, 2];
let gathered = column.take_positions(&positions);
assert!(
matches!(&gathered.values, ScalarValues::LazyAllValidPeriodVec { .. }),
"Period scattered gather should defer scalar materialization"
);
if let ScalarValues::LazyAllValidPeriodVec {
data, freq, values, ..
} = &gathered.values
{
assert_eq!(*freq, PeriodFreq::Monthly);
assert_eq!(data.as_slice(), &[42, 10, -5, 42]);
assert!(values.get().is_none());
}
let expected = Column::new(
DType::Period,
positions
.iter()
.map(|&position| column.values()[position].clone())
.collect(),
)
.expect("validated materialization");
assert_eq!(gathered.values(), expected.values());
assert_eq!(gathered.validity(), expected.validity());
if let ScalarValues::LazyAllValidPeriodVec { values, .. } = &gathered.values {
assert!(values.get().is_some());
}
}
#[test]
fn period_reindex_by_positions_uses_nullable_lazy_backing() {
let column = Column::new(
DType::Period,
vec![
Scalar::Period(Period::new(10, PeriodFreq::Monthly)),
Scalar::Period(Period::new(20, PeriodFreq::Monthly)),
Scalar::Period(Period::new(30, PeriodFreq::Monthly)),
],
)
.expect("column should build");
let gathered = column
.reindex_by_positions(&[Some(2), None, Some(0), Some(99)])
.expect("reindex should work");
assert!(
matches!(&gathered.values, ScalarValues::LazyNullablePeriod { .. }),
"Period null-fill gather should defer scalar materialization"
);
if let ScalarValues::LazyNullablePeriod {
data,
freq,
missing_freq,
validity,
values,
..
} = &gathered.values
{
assert_eq!(*freq, PeriodFreq::Monthly);
assert_eq!(*missing_freq, PeriodFreq::Daily);
assert_eq!(data, &[30, i64::MIN, 10, i64::MIN]);
assert_eq!(validity.count_valid(), 2);
assert!(values.get().is_none());
}
assert_eq!(
gathered.values(),
&[
Scalar::Period(Period::new(30, PeriodFreq::Monthly)),
Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
Scalar::Period(Period::new(10, PeriodFreq::Monthly)),
Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
]
);
assert!(gathered.validity().get(0));
assert!(!gathered.validity().get(1));
assert!(gathered.validity().get(2));
assert!(!gathered.validity().get(3));
}
#[test]
fn take_positions_preserves_exact_null_kind_contract() {
// Isomorphism contract for the typed-columnar storage epic
// (br-frankenpandas-typed-columnar-storage-epic): `take_positions`
// reproduces the EXACT scalar stored at each source position, including
// the precise `NullKind` at invalid positions — not merely a
// valid/invalid bit. `normalize_missing_for_dtype` preserves NaN/NaT
// null kinds regardless of dtype, so a Float64/Int64 column can legally
// hold `Null(NaT)`. A future migration to typed `ColumnData` +
// `ValidityMask` that canonicalizes nulls per dtype would silently
// break `values()` parity for such columns; this test must keep passing
// through that migration (the typed store must carry per-position null
// kind, e.g. a 2-bit NaN/NaT/Null code, not just a validity bit).
for (dtype, real) in [
(DType::Float64, Scalar::Float64(2.5)),
(DType::Int64, Scalar::Int64(7)),
] {
let source = Column::new(
dtype,
vec![
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaT),
Scalar::Null(NullKind::Null),
real,
],
)
.expect("column builds");
// Compare against what the column actually stored, so the test is
// robust to constructor canonicalization yet still pins that the
// gather is byte-for-byte faithful to the stored representation.
let stored = source.values().to_vec();
let positions = [3, 2, 1, 0, 1];
let gathered = source.take_positions(&positions);
for (out_idx, &pos) in positions.iter().enumerate() {
assert_eq!(
gathered.values()[out_idx],
stored[pos],
"dtype {dtype:?}: take_positions must reproduce the exact stored scalar \
(incl. NullKind) for source position {pos}",
);
// Invalid source positions must stay invalid after the gather.
assert_eq!(
gathered.validity().get(out_idx),
source.validity().get(pos),
"dtype {dtype:?}: validity must follow the gathered position {pos}",
);
}
}
}
#[test]
fn take_positions_nullable_int64_typed_gather_matches_reference_cf() {
// A LazyNullableInt64 take routes through the typed nullable-Int64 gather.
// Result must equal the Scalar-clone reference: a present source position
// ⇒ Int64(datum); a missing one ⇒ Null(Null); order follows `positions`
// (repeats allowed), and validity follows the gathered position.
let mut validity = ValidityMask::all_valid(6);
validity.set(1, false);
validity.set(4, false);
let col = Column::from_i64_values_with_validity(vec![10, 0, 30, -5, 0, 7], validity);
let positions = [5usize, 4, 0, 1, 3, 4, 2];
let taken = col.take_positions(&positions);
assert_eq!(taken.dtype(), DType::Int64);
assert_eq!(
taken.values(),
&[
Scalar::Int64(7),
Scalar::Null(NullKind::Null),
Scalar::Int64(10),
Scalar::Null(NullKind::Null),
Scalar::Int64(-5),
Scalar::Null(NullKind::Null),
Scalar::Int64(30),
]
);
for (out_idx, &pos) in positions.iter().enumerate() {
assert_eq!(
taken.validity().get(out_idx),
col.validity().get(pos),
"validity must follow gathered position {pos}",
);
}
}
#[test]
fn take_positions_nullable_utf8_typed_gather_matches_reference() {
// The typed nullable-Utf8 gather (LazyNullableUtf8) must be BIT-EXACT to the
// Scalar-clone reference for arbitrary position vectors (permutation, subset,
// repeats, out-of-order): present source ⇒ Scalar::Utf8(span), missing ⇒
// Null(Null), order follows positions, validity follows the gathered position.
// Independent oracle = clone over col.values() (the generic gather algorithm).
let mut state: u64 = 0x7A4E_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..150 {
let n = (next() % 200) as usize + 1;
let mut validity = ValidityMask::all_valid(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..n {
if next() % 4 == 0 {
validity.set(i, false);
} else {
let len = (next() % 5) as usize;
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
}
offsets.push(bytes.len());
}
let col = Column::from_utf8_values_with_validity(bytes, offsets, validity);
let vals = col.values().to_vec();
// Random positions with repeats + out-of-order (m in 0..2n).
let m = (next() % (2 * n as u64)) as usize;
let positions: Vec<usize> = (0..m).map(|_| (next() as usize) % n).collect();
let want: Vec<Scalar> = positions.iter().map(|&p| vals[p].clone()).collect();
let taken = col.take_positions(&positions);
assert_eq!(taken.values(), want.as_slice(), "trial {trial}");
for (out_idx, &pos) in positions.iter().enumerate() {
assert_eq!(
taken.validity().get(out_idx),
col.validity().get(pos),
"trial {trial} validity at {out_idx} must follow position {pos}",
);
}
}
}
#[test]
fn take_positions_nullable_temporal_bool_typed_gather_matches_reference_cf() {
// Datetime64/Timedelta64/Bool nullable gathers (variant-gated siblings of
// the Int64 gather). Present ⇒ the datum Scalar; missing ⇒ Null(NaT) for the
// temporal dtypes, Null(Null) for Bool; order follows positions.
let mut v = ValidityMask::all_valid(4);
v.set(1, false);
let positions = [3usize, 1, 2, 0, 1];
let dt = Column::from_datetime64_values_with_validity(vec![100, 0, 300, 400], v.clone());
let dtr = dt.take_positions(&positions);
assert_eq!(dtr.dtype(), DType::Datetime64);
assert_eq!(
dtr.values(),
&[
Scalar::Datetime64(400),
Scalar::Null(NullKind::NaT),
Scalar::Datetime64(300),
Scalar::Datetime64(100),
Scalar::Null(NullKind::NaT),
]
);
let td = Column::from_timedelta64_values_with_validity(vec![10, 0, 30, 40], v.clone());
let tdr = td.take_positions(&positions);
assert_eq!(tdr.dtype(), DType::Timedelta64);
assert_eq!(
tdr.values(),
&[
Scalar::Timedelta64(40),
Scalar::Null(NullKind::NaT),
Scalar::Timedelta64(30),
Scalar::Timedelta64(10),
Scalar::Null(NullKind::NaT),
]
);
let b = Column::from_bool_values_with_validity(vec![true, false, false, true], v.clone());
let br = b.take_positions(&positions);
assert_eq!(br.dtype(), DType::Bool);
assert_eq!(
br.values(),
&[
Scalar::Bool(true),
Scalar::Null(NullKind::Null),
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Null(NullKind::Null),
]
);
}
#[test]
fn primitive_columns_cache_typed_data_for_take_positions() {
let column = Column::new(
DType::Float64,
vec![
Scalar::Float64(1.25),
Scalar::Float64(-0.0),
Scalar::Float64(9.5),
],
)
.expect("column should build");
assert!(matches!(column.data, Some(ColumnData::Float64(_))));
let positions = [2, 0, 1, 2];
let gathered = column.take_positions(&positions);
let expected = Column::new(
DType::Float64,
positions
.iter()
.map(|&position| column.values()[position].clone())
.collect(),
)
.expect("validated materialization");
assert_eq!(gathered.values(), expected.values());
assert_eq!(gathered.validity(), expected.validity());
}
#[test]
fn float64_take_positions_defers_scalar_materialization() {
let column = Column::new(
DType::Float64,
vec![
Scalar::Float64(1.25),
Scalar::Float64(-0.0),
Scalar::Float64(9.5),
],
)
.expect("column should build");
let positions = [2, 0, 1, 2];
let gathered = column.take_positions(&positions);
// A scattered Float64 gather now MOVES its freshly-built Vec into the
// owned `LazyAllValidFloat64Vec` backing (no `Arc::<[f64]>::from` copy —
// [[f64-arc-copy-on-produce]]); it still defers Scalar materialization.
assert!(
matches!(
&gathered.values,
ScalarValues::LazyAllValidFloat64Vec { .. }
),
"Float64 scattered gather should defer scalar materialization (owned-move backing)"
);
if let ScalarValues::LazyAllValidFloat64Vec { data, values, .. } = &gathered.values {
assert_eq!(
data.iter().map(|value| value.to_bits()).collect::<Vec<_>>(),
vec![
9.5f64.to_bits(),
1.25f64.to_bits(),
(-0.0f64).to_bits(),
9.5f64.to_bits(),
]
);
assert!(values.get().is_none());
}
assert_eq!(gathered.len(), positions.len());
assert_eq!(
gathered.validity(),
&ValidityMask::all_valid(positions.len())
);
let expected = Column::new(
DType::Float64,
positions
.iter()
.map(|&position| column.values()[position].clone())
.collect(),
)
.expect("validated materialization");
assert_eq!(gathered.values(), expected.values());
assert!(
matches!(
&gathered.values,
ScalarValues::LazyAllValidFloat64Vec { .. }
),
"Float64 gather should stay lazy (owned-move backing) after read"
);
if let ScalarValues::LazyAllValidFloat64Vec { values, .. } = &gathered.values {
assert!(values.get().is_some());
}
assert_eq!(gathered.validity(), expected.validity());
}
#[test]
fn float64_take_positions_contiguous_range_returns_slice_view() {
let data: Vec<f64> = (0..160)
.map(|i| match i {
40 => -0.0,
41 => f64::INFINITY,
42 => f64::from_bits(1),
_ => i as f64 + 0.5,
})
.collect();
let expected_bits: Vec<u64> = data[32..112].iter().map(|value| value.to_bits()).collect();
let column = Column::from_f64_values(data);
let positions: Vec<usize> = (32..112).collect();
let gathered = column.take_positions(&positions);
assert!(
matches!(
&gathered.values,
ScalarValues::LazyAllValidFloat64Slice { .. }
),
"large contiguous Float64 takes should share the source buffer"
);
if let ScalarValues::LazyAllValidFloat64Slice {
start, len, values, ..
} = &gathered.values
{
assert_eq!((*start, *len), (32, 80));
assert!(values.get().is_none());
}
assert_eq!(
gathered.as_f64_slice().map(|values| {
values
.iter()
.map(|value| value.to_bits())
.collect::<Vec<_>>()
}),
Some(expected_bits)
);
let expected = Column::from_f64_values(
column.as_f64_slice().expect("source stays typed")[32..112].to_vec(),
);
assert_eq!(gathered.values(), expected.values());
assert_eq!(gathered.validity(), expected.validity());
if let ScalarValues::LazyAllValidFloat64Slice { values, .. } = &gathered.values {
assert!(values.get().is_some());
}
}
#[test]
fn float64_take_positions_contiguous_range_slices_existing_slice_view() {
let data: Vec<f64> = (0..192).map(|i| (i as f64).mul_add(0.25, -7.0)).collect();
let column = Column::from_f64_values(data);
let first_positions: Vec<usize> = (20..128).collect();
let first = column.take_positions(&first_positions);
let second_positions: Vec<usize> = (10..74).collect();
let second = first.take_positions(&second_positions);
assert!(
matches!(
&second.values,
ScalarValues::LazyAllValidFloat64Slice { .. }
),
"nested contiguous Float64 take should remain a slice view"
);
if let ScalarValues::LazyAllValidFloat64Slice {
start, len, values, ..
} = &second.values
{
assert_eq!((*start, *len), (30, 64));
assert!(values.get().is_none());
}
let expected = Column::from_f64_values(
column.as_f64_slice().expect("source stays typed")[30..94].to_vec(),
);
assert_eq!(second.as_f64_slice(), expected.as_f64_slice());
assert_eq!(second.values(), expected.values());
}
#[test]
fn take_contiguous_range_uses_typed_views_without_positions() {
let f64_data: Vec<f64> = (0..160)
.map(|i| if i == 72 { -0.0 } else { i as f64 * 0.5 })
.collect();
let f64_column = Column::from_f64_values(f64_data);
let f64_range = f64_column.take_contiguous_range(64, 80);
assert!(
matches!(
&f64_range.values,
ScalarValues::LazyAllValidFloat64Slice { .. }
),
"Float64 range gather should be a zero-copy slice view"
);
assert_eq!(
f64_range.as_f64_slice().map(|values| {
values
.iter()
.map(|value| value.to_bits())
.collect::<Vec<_>>()
}),
f64_column.as_f64_slice().map(|values| values[64..144]
.iter()
.map(|value| value.to_bits())
.collect::<Vec<_>>())
);
let mut bytes = Vec::new();
let mut offsets = Vec::with_capacity(6);
offsets.push(0);
for value in ["k000", "k001", "k002", "k003", "k004"] {
bytes.extend_from_slice(value.as_bytes());
offsets.push(bytes.len());
}
let utf8_column = Column::from_utf8_contiguous(bytes, offsets);
let utf8_range = utf8_column.take_contiguous_range(1, 3);
assert!(
matches!(&utf8_range.values, ScalarValues::LazyUtf8Slice { .. }),
"Utf8 range gather should be a zero-copy slice view"
);
assert_eq!(
utf8_range.values(),
&[
Scalar::Utf8("k001".to_owned()),
Scalar::Utf8("k002".to_owned()),
Scalar::Utf8("k003".to_owned())
]
);
}
#[test]
fn float64_take_positions_regular_stride_defers_contiguous_gather() {
let data: Vec<f64> = (0..4096)
.map(|i| match i {
4 => -0.0,
19 => f64::INFINITY,
_ => i as f64 * 0.25,
})
.collect();
let column = Column::from_f64_values(data.clone());
let positions: Vec<usize> = (0..1024).map(|i| 3 + i * 4).collect();
let gathered = column.take_positions(&positions);
assert!(
matches!(&gathered.values, ScalarValues::LazyStridedFloat64 { .. }),
"wide regular Float64 gather should carry a strided view"
);
if let ScalarValues::LazyStridedFloat64 {
start,
step,
len,
expanded,
values,
..
} = &gathered.values
{
assert_eq!((*start, *step, *len), (3, 4, positions.len()));
assert!(expanded.get().is_none());
assert!(values.get().is_none());
}
let expected_bits: Vec<u64> = positions.iter().map(|&pos| data[pos].to_bits()).collect();
let gathered_bits: Vec<u64> = gathered
.as_f64_slice()
.expect("strided Float64 view must expose a contiguous typed view")
.iter()
.map(|value| value.to_bits())
.collect();
assert_eq!(gathered_bits, expected_bits);
assert_eq!(
gathered.validity(),
&ValidityMask::all_valid(positions.len())
);
let expected = Column::new(
DType::Float64,
positions
.iter()
.map(|&position| column.values()[position].clone())
.collect(),
)
.expect("validated materialization");
assert_eq!(gathered.values(), expected.values());
assert_eq!(gathered.validity(), expected.validity());
}
#[test]
fn take_positions_with_affine_certificate_uses_lazy_strided_float64() {
let data: Vec<f64> = (0..4096)
.map(|i| match i {
8 => -0.0,
23 => f64::NEG_INFINITY,
_ => i as f64 * 0.5,
})
.collect();
let column = Column::from_f64_values(data.clone());
let positions: Vec<usize> = (0..1024).map(|i| 2 + i * 3).collect();
let gathered = column.take_positions_with_affine_certificate(&positions, 2, 3);
assert!(
matches!(&gathered.values, ScalarValues::LazyStridedFloat64 { .. }),
"certified wide regular Float64 gather should carry a strided view"
);
if let ScalarValues::LazyStridedFloat64 {
start,
step,
len,
expanded,
values,
..
} = &gathered.values
{
assert_eq!((*start, *step, *len), (2, 3, positions.len()));
assert!(expanded.get().is_none());
assert!(values.get().is_none());
}
let expected_bits: Vec<u64> = positions.iter().map(|&pos| data[pos].to_bits()).collect();
let gathered_bits: Vec<u64> = gathered
.as_f64_slice()
.expect("certified strided Float64 view must expose typed data")
.iter()
.map(|value| value.to_bits())
.collect();
assert_eq!(gathered_bits, expected_bits);
assert_eq!(
gathered.validity(),
&ValidityMask::all_valid(positions.len())
);
}
#[test]
fn bounded_arithmetic_progression_positions_rejects_non_affine_or_oob() {
assert_eq!(
Column::bounded_arithmetic_progression_positions(&[3, 7, 11, 15], 16),
Some((3, 4))
);
assert_eq!(
Column::bounded_arithmetic_progression_positions(&[3, 7, 12], 16),
None
);
assert_eq!(
Column::bounded_arithmetic_progression_positions(&[3, 3, 3], 16),
None
);
assert_eq!(
Column::bounded_arithmetic_progression_positions(&[3, 7, 11, 15], 15),
None
);
assert_eq!(
Column::bounded_arithmetic_progression_positions(&[usize::MAX - 1, usize::MAX], 8),
None
);
}
#[test]
fn reindex_all_present_matches_materialization_and_keeps_float64_lazy() {
let column = Column::from_f64_values(vec![1.25, -0.0, f64::INFINITY]);
let positions = [Some(2), Some(0), Some(1), Some(2)];
let gathered = column
.reindex_by_positions(&positions)
.expect("all-present reindex should gather");
// Scattered all-present reindex gathers through the same owned-move path
// as take_positions (no Arc<[f64]> copy); still defers materialization.
assert!(
matches!(
&gathered.values,
ScalarValues::LazyAllValidFloat64Vec { .. }
),
"all-present Float64 reindex should defer scalar materialization (owned-move backing)"
);
if let ScalarValues::LazyAllValidFloat64Vec { data, values, .. } = &gathered.values {
assert_eq!(
data.iter().map(|value| value.to_bits()).collect::<Vec<_>>(),
vec![
f64::INFINITY.to_bits(),
1.25f64.to_bits(),
(-0.0f64).to_bits(),
f64::INFINITY.to_bits(),
]
);
assert!(values.get().is_none());
}
let expected = Column::new(
DType::Float64,
positions
.iter()
.map(|&position| column.values()[position.expect("present position")].clone())
.collect(),
)
.expect("validated scalar materialization");
assert_eq!(gathered.dtype(), expected.dtype());
assert_eq!(gathered.values(), expected.values());
assert_eq!(gathered.validity(), expected.validity());
}
#[test]
fn reindex_nullable_i64_null_introducing_typed_matches_generic() {
// The typed nullable-Int64 null-introducing reindex arm (LazyNullableInt64 source +
// some None/out-of-range positions) must be BIT-EXACT to the generic Scalar-clone
// gather. A/B: col_typed (from_i64_values_with_validity => LazyNullableInt64) hits the
// typed arm; col_eager (Column::new, Eager) hits the generic path. Positions mix
// Some(present), Some(missing-source), Some(out-of-range), and None.
let mut state: u64 = 0x2E1D_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let src_n = (next() % 120) as usize;
let mut data = vec![0i64; src_n];
let mut validity = crate::ValidityMask::all_valid(src_n);
let mut eager: Vec<Scalar> = Vec::with_capacity(src_n);
let mut some_missing = false;
for i in 0..src_n {
if next() % 3 == 0 {
validity.set(i, false);
eager.push(Scalar::Null(NullKind::Null));
some_missing = true;
} else {
let v = (next() % 20_000) as i64 - 10_000;
data[i] = v;
eager.push(Scalar::Int64(v));
}
}
// Force nullable backing: if the source happened to be all-valid, skip (the
// all-valid arm covers it and col_typed would be LazyAllValidInt64, not this arm).
if !some_missing || src_n == 0 {
continue;
}
let col_typed = Column::from_i64_values_with_validity(data, validity);
let col_eager = Column::new(DType::Int64, eager).expect("eager i64");
// Build positions: mix present, out-of-range, and None (null-introducing).
let plen = (next() % 200) as usize;
let positions: Vec<Option<usize>> = (0..plen)
.map(|_| match next() % 4 {
0 => None,
1 => Some((next() % (src_n as u64 + 5)) as usize), // may be out-of-range
_ => Some((next() % src_n as u64) as usize),
})
.collect();
let a = col_typed.reindex_by_positions(&positions).expect("typed reindex");
let b = col_eager.reindex_by_positions(&positions).expect("eager reindex");
assert_eq!(a.values(), b.values(), "reindex trial {trial}");
assert_eq!(a.validity(), b.validity(), "reindex validity trial {trial}");
}
}
#[test]
fn reindex_nullable_bool_null_introducing_typed_matches_generic() {
// The typed nullable-Bool null-introducing reindex arm (LazyNullableBool source +
// some None/out-of-range positions) must be BIT-EXACT to the generic Scalar-clone
// gather. A/B: col_typed (from_bool_values_with_validity => LazyNullableBool) hits the
// typed arm; col_eager (Column::new from col_typed's values) hits the generic path.
// Bool has no sentinel, so every missing is the single Null(Null) — no NullKind trap.
let mut state: u64 = 0xB001_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let src_n = (next() % 120) as usize;
let mut data = vec![false; src_n];
let mut validity = crate::ValidityMask::all_valid(src_n);
let mut nullable = false;
for i in 0..src_n {
if next() % 3 == 0 {
validity.set(i, false);
nullable = true;
} else {
data[i] = next() % 2 == 0;
}
}
if !nullable || src_n == 0 {
continue;
}
let col_typed = Column::from_bool_values_with_validity(data, validity);
let col_eager =
Column::new(DType::Bool, col_typed.values().to_vec()).expect("eager bool");
let plen = (next() % 200) as usize;
let positions: Vec<Option<usize>> = (0..plen)
.map(|_| match next() % 4 {
0 => None,
1 => Some((next() % (src_n as u64 + 5)) as usize),
_ => Some((next() % src_n as u64) as usize),
})
.collect();
let a = col_typed.reindex_by_positions(&positions).expect("typed reindex");
let b = col_eager.reindex_by_positions(&positions).expect("eager reindex");
assert_eq!(a.values(), b.values(), "bool reindex trial {trial}");
assert_eq!(a.validity(), b.validity(), "bool reindex validity trial {trial}");
}
}
#[test]
fn column_equality_ignores_skipped_typed_cache() {
let column = Column::new(
DType::Int64,
vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
)
.expect("column should build");
let json = serde_json::to_string(&column).expect("serialize");
let roundtrip: Column = serde_json::from_str(&json).expect("deserialize");
assert!(column.data.is_some());
assert!(roundtrip.data.is_none());
assert_eq!(column, roundtrip);
}
#[test]
fn column_clone_preserves_values_without_copying_private_cache() {
let column = Column::new(
DType::Int64,
vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
)
.expect("column should build");
let cloned = column.clone();
assert!(column.data.is_some());
assert!(cloned.data.is_none());
assert_eq!(column, cloned);
}
#[test]
fn dense_primitive_clone_defers_float64_scalar_materialization_from_typed_cache() {
let column = Column::new(
DType::Float64,
vec![
Scalar::Float64(1.5),
Scalar::Float64(-0.0),
Scalar::Float64(3.25),
],
)
.expect("column should build");
let cloned_values = column
.clone_dense_values_from_cache()
.expect("all-valid Float64 typed cache should clone");
assert!(
matches!(&cloned_values, ScalarValues::LazyAllValidFloat64 { .. }),
"Float64 clone should defer scalar materialization"
);
if let ScalarValues::LazyAllValidFloat64 { data, values, .. } = &cloned_values {
assert_eq!(
data.iter().map(|value| value.to_bits()).collect::<Vec<_>>(),
vec![1.5f64.to_bits(), (-0.0f64).to_bits(), 3.25f64.to_bits()]
);
assert!(values.get().is_none());
}
let cloned = column.clone();
assert!(
matches!(&cloned.values, ScalarValues::LazyAllValidFloat64 { .. }),
"Column::clone should keep all-valid Float64 clone values lazy"
);
if let ScalarValues::LazyAllValidFloat64 { values, .. } = &cloned.values {
assert!(values.get().is_none());
}
assert_eq!(cloned.values(), column.values());
if let ScalarValues::LazyAllValidFloat64 { values, .. } = &cloned.values {
assert!(values.get().is_some());
}
assert_eq!(cloned.validity(), column.validity());
assert!(cloned.data.is_none());
}
#[test]
fn dense_primitive_clone_falls_back_for_missing_values() {
let column = Column::new(
DType::Float64,
vec![
Scalar::Float64(1.5),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::Null),
],
)
.expect("column should build");
assert!(column.clone_dense_values_from_cache().is_none());
let cloned = column.clone();
assert_eq!(cloned.values(), column.values());
assert_eq!(cloned.validity(), column.validity());
assert!(cloned.data.is_none());
}
#[test]
fn numeric_addition_propagates_missing() {
let left = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Float64(f64::NAN),
])
.expect("left");
let right = Column::from_values(vec![Scalar::Int64(2), Scalar::Int64(5), Scalar::Int64(3)])
.expect("right");
let out = left
.binary_numeric(&right, ArithmeticOp::Add)
.expect("add should pass");
assert_eq!(out.values()[0], Scalar::Float64(3.0));
assert_eq!(out.values()[1], Scalar::Null(NullKind::NaN));
assert_eq!(out.values()[2], Scalar::Null(NullKind::NaN));
}
#[test]
fn sparse_column_omits_fill_values_and_materializes_dense() {
let dtype = SparseDType::new(DType::Int64, Scalar::Int64(0)).expect("sparse dtype");
let sparse = SparseColumn::from_dense(
dtype,
vec![
Scalar::Int64(0),
Scalar::Int64(5),
Scalar::Int64(0),
Scalar::Int64(-2),
],
)
.expect("sparse column");
assert_eq!(sparse.value_dtype(), DType::Int64);
assert_eq!(sparse.fill_value(), &Scalar::Int64(0));
assert_eq!(sparse.len(), 4);
assert_eq!(sparse.npoints(), 2);
assert_eq!(sparse.indices(), &[1, 3]);
assert_eq!(
sparse.stored_values(),
&[Scalar::Int64(5), Scalar::Int64(-2)]
);
let dense = sparse.to_dense_column().expect("dense column");
assert_eq!(dense.dtype(), DType::Int64);
assert_eq!(
dense.values(),
&[
Scalar::Int64(0),
Scalar::Int64(5),
Scalar::Int64(0),
Scalar::Int64(-2),
]
);
}
#[test]
fn sparse_column_preserves_nulls_when_fill_is_not_missing() {
let dtype = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).expect("sparse dtype");
let sparse = SparseColumn::from_dense(
dtype,
vec![
Scalar::Float64(0.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(2.5),
],
)
.expect("sparse column");
assert_eq!(sparse.indices(), &[1, 2]);
assert_eq!(sparse.npoints(), 2);
assert!((sparse.density() - (2.0 / 3.0)).abs() < f64::EPSILON);
assert!(sparse.stored_values()[0].is_missing());
assert_eq!(sparse.stored_values()[1], Scalar::Float64(2.5));
let dense = sparse.to_dense_column().expect("dense column");
assert_eq!(
dense.values(),
&[
Scalar::Float64(0.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(2.5),
]
);
}
#[test]
fn sparse_column_missing_fill_omits_missing_values() {
let dtype =
SparseDType::new(DType::Float64, Scalar::Null(NullKind::NaN)).expect("sparse dtype");
let sparse = SparseColumn::from_dense(
dtype,
vec![
Scalar::Null(NullKind::Null),
Scalar::Float64(1.5),
Scalar::Float64(f64::NAN),
],
)
.expect("sparse column");
assert_eq!(sparse.fill_value(), &Scalar::Null(NullKind::NaN));
assert_eq!(sparse.indices(), &[1]);
assert_eq!(sparse.stored_values(), &[Scalar::Float64(1.5)]);
assert_eq!(
sparse.to_dense_values(),
vec![
Scalar::Null(NullKind::NaN),
Scalar::Float64(1.5),
Scalar::Null(NullKind::NaN),
]
);
}
// === Packed Bitvec ValidityMask Tests ===
#[test]
fn validity_mask_from_values_packs_correctly() {
let values = vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
];
let mask = ValidityMask::from_values(&values);
assert_eq!(mask.len(), 3);
assert!(mask.get(0));
assert!(!mask.get(1));
assert!(mask.get(2));
assert_eq!(mask.count_valid(), 2);
}
#[test]
fn validity_mask_all_valid() {
let mask = ValidityMask::all_valid(100);
assert_eq!(mask.len(), 100);
assert_eq!(mask.count_valid(), 100);
assert!(
mask.words.is_empty(),
"all-valid masks store only the logical length"
);
for i in 0..100 {
assert!(mask.get(i), "bit {i} should be valid");
}
}
#[test]
fn validity_mask_all_valid_sentinel_matches_explicit_words() {
for len in [1, 2, 63, 64, 65, 127, 128, 129] {
let sentinel = ValidityMask::all_valid(len);
let explicit =
ValidityMask::from_words(ValidityMask::materialized_all_valid_words(len), len);
assert_eq!(sentinel, explicit, "len {len}");
assert_eq!(
sentinel.bits().collect::<Vec<_>>(),
explicit.bits().collect::<Vec<_>>(),
"len {len}"
);
assert!(sentinel.all(), "len {len}");
assert_eq!(sentinel.count_invalid(), 0, "len {len}");
}
}
#[test]
fn validity_mask_all_valid_sentinel_materializes_on_clear() {
let mut mask = ValidityMask::all_valid(130);
mask.set(64, true);
assert!(
mask.words.is_empty(),
"setting a valid bit preserves the sentinel"
);
mask.set(64, false);
assert!(!mask.words.is_empty(), "clearing a bit materializes words");
assert_eq!(mask.len(), 130);
assert_eq!(mask.count_valid(), 129);
assert!(!mask.get(64));
assert!(mask.get(63));
assert!(mask.get(65));
assert_eq!(mask.bits().filter(|valid| *valid).count(), 129);
mask.set(64, true);
assert!(mask.all(), "restored packed words must report all-valid");
}
#[test]
fn validity_mask_sparse_invalid_ranges_match_explicit_bitmap() {
let sparse = ValidityMask::from_invalid_ranges(Arc::from(vec![(2, 3), (9, 2)]), 12);
let mut explicit = ValidityMask::all_valid(12);
for idx in [2, 3, 4, 9, 10] {
explicit.set(idx, false);
}
assert!(sparse.words.is_empty());
assert!(sparse.invalid_ranges.is_some());
assert_eq!(sparse, explicit);
assert_eq!(sparse.count_valid(), 7);
assert_eq!(sparse.count_invalid(), 5);
assert!(!sparse.all());
assert!(sparse.get(1));
assert!(!sparse.get(3));
assert!(sparse.get(8));
assert!(!sparse.get(10));
assert_eq!(sparse.slice(1, 6), explicit.slice(1, 6));
assert_eq!(sparse.not_mask(), explicit.not_mask());
let mut mutated = sparse.clone();
mutated.set(2, true);
explicit.set(2, true);
assert_eq!(mutated, explicit);
assert!(mutated.invalid_ranges.is_none());
}
#[test]
fn validity_mask_invalid_range_visitor_merges_word_boundaries() {
let mut mask = ValidityMask::all_valid(140);
for idx in 60..68 {
mask.set(idx, false);
}
for idx in [3, 90, 91, 139] {
mask.set(idx, false);
}
let mut ranges = Vec::new();
mask.for_each_invalid_range(|start, len| ranges.push((start, len)));
assert_eq!(ranges, vec![(3, 1), (60, 8), (90, 2), (139, 1)]);
let sparse = ValidityMask::from_invalid_ranges(Arc::from(ranges.clone()), 140);
let mut sparse_ranges = Vec::new();
sparse.for_each_invalid_range(|start, len| sparse_ranges.push((start, len)));
assert_eq!(sparse_ranges, ranges);
}
#[test]
fn validity_mask_all_invalid() {
let mask = ValidityMask::all_invalid(100);
assert_eq!(mask.len(), 100);
assert_eq!(mask.count_valid(), 0);
assert!(!mask.any());
for i in 0..100 {
assert!(!mask.get(i), "bit {i} should be invalid");
}
}
#[test]
fn validity_mask_any_covers_all_backings_dbtw5() {
// Preserve the historical empty-mask behavior as well as the ordinary
// non-empty all-valid sentinel.
assert!(!ValidityMask::all_valid(0).any());
assert!(ValidityMask::all_valid(70).any());
let mut early_valid = ValidityMask::all_invalid(130);
early_valid.set(1, true);
assert!(early_valid.any());
let mut tail_valid = ValidityMask::all_invalid(130);
tail_valid.set(129, true);
assert!(tail_valid.any());
let partly_invalid =
ValidityMask::from_invalid_ranges(Arc::from(vec![(0, 64), (66, 4)]), 70);
assert!(partly_invalid.any());
let wholly_invalid = ValidityMask::from_invalid_ranges(Arc::from(vec![(0, 70)]), 70);
assert!(!wholly_invalid.any());
}
#[test]
fn validity_mask_set_and_get() {
let mut mask = ValidityMask::all_invalid(128);
mask.set(0, true);
mask.set(63, true);
mask.set(64, true);
mask.set(127, true);
assert!(mask.get(0));
assert!(mask.get(63));
assert!(mask.get(64));
assert!(mask.get(127));
assert!(!mask.get(1));
assert_eq!(mask.count_valid(), 4);
mask.set(63, false);
assert!(!mask.get(63));
assert_eq!(mask.count_valid(), 3);
}
#[test]
fn validity_mask_and_or_not() {
let mut a = ValidityMask::all_invalid(4);
a.set(0, true);
a.set(1, true);
let mut b = ValidityMask::all_invalid(4);
b.set(1, true);
b.set(2, true);
let and = a.and_mask(&b);
assert!(and.get(1));
assert!(!and.get(0));
assert!(!and.get(2));
assert_eq!(and.count_valid(), 1);
let or = a.or_mask(&b);
assert!(or.get(0));
assert!(or.get(1));
assert!(or.get(2));
assert!(!or.get(3));
assert_eq!(or.count_valid(), 3);
let not_a = a.not_mask();
assert!(!not_a.get(0));
assert!(!not_a.get(1));
assert!(not_a.get(2));
assert!(not_a.get(3));
assert_eq!(not_a.count_valid(), 2);
}
#[test]
fn validity_mask_sentinel_mask_algebra_matches_explicit_bitmap() {
let all = ValidityMask::all_valid(5);
let nullable = ValidityMask::from_values(&[
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
Scalar::Null(NullKind::NaN),
Scalar::Int64(5),
]);
assert_eq!(all.and_mask(&nullable), nullable);
assert_eq!(nullable.and_mask(&all), nullable);
assert_eq!(all.or_mask(&nullable), all);
assert_eq!(nullable.or_mask(&all), all);
assert_eq!(
all.xor_mask(&nullable).bits().collect::<Vec<_>>(),
vec![false, true, false, true, false]
);
assert_eq!(
all.not_mask().bits().collect::<Vec<_>>(),
vec![false, false, false, false, false]
);
assert_eq!(
all.slice(1, 3).bits().collect::<Vec<_>>(),
vec![true, true, true]
);
assert_eq!(
all.concat(&ValidityMask::all_valid(2)),
ValidityMask::all_valid(7)
);
}
#[test]
fn validity_mask_bits_iterator() {
let values = vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
Scalar::Float64(f64::NAN),
];
let mask = ValidityMask::from_values(&values);
let bits: Vec<bool> = mask.bits().collect();
assert_eq!(bits, vec![true, false, true, false]);
}
#[test]
fn validity_mask_serde_round_trip() {
let values = vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
];
let mask = ValidityMask::from_values(&values);
let json = serde_json::to_string(&mask).expect("serialize");
let back: ValidityMask = serde_json::from_str(&json).expect("deserialize");
assert_eq!(mask, back);
// Verify backward-compatible format
assert!(json.contains("\"bits\""), "should serialize as bits field");
}
#[test]
fn validity_mask_empty() {
let mask = ValidityMask::from_values(&[]);
assert!(mask.is_empty());
assert_eq!(mask.len(), 0);
assert_eq!(mask.count_valid(), 0);
assert_eq!(mask.bits().count(), 0);
}
#[test]
fn validity_mask_count_invalid_matches_complement() {
let mask = ValidityMask::from_values(&[
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(2),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
]);
assert_eq!(mask.count_valid(), 3);
assert_eq!(mask.count_invalid(), 2);
assert_eq!(mask.count_valid() + mask.count_invalid(), mask.len());
}
#[test]
fn validity_mask_any_and_all() {
let all_set = ValidityMask::all_valid(4);
assert!(all_set.any());
assert!(all_set.all());
let none_set = ValidityMask::all_invalid(4);
assert!(!none_set.any());
assert!(!none_set.all());
let mixed = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::NaN)]);
assert!(mixed.any());
assert!(!mixed.all());
let empty = ValidityMask::all_invalid(0);
assert!(!empty.any());
assert!(empty.all()); // vacuously true
}
#[test]
fn validity_mask_xor_finds_differences() {
let a = ValidityMask::from_values(&[
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Null(NullKind::NaN),
Scalar::Int64(4),
]);
let b = ValidityMask::from_values(&[
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Int64(4),
]);
let diff = a.xor_mask(&b);
assert_eq!(diff.len(), 4);
// position 0: both valid → 0
// position 1: a valid, b invalid → 1
// position 2: both invalid → 0
// position 3: both valid → 0
assert!(!diff.get(0));
assert!(diff.get(1));
assert!(!diff.get(2));
assert!(!diff.get(3));
}
#[test]
fn validity_mask_slice_extracts_range() {
let mask = ValidityMask::from_values(&[
Scalar::Int64(1), // valid
Scalar::Null(NullKind::NaN), // invalid
Scalar::Int64(3), // valid
Scalar::Int64(4), // valid
Scalar::Null(NullKind::NaN), // invalid
]);
let sub = mask.slice(1, 3);
assert_eq!(sub.len(), 3);
assert!(!sub.get(0));
assert!(sub.get(1));
assert!(sub.get(2));
}
#[test]
fn validity_mask_slice_past_end_clamps() {
let mask = ValidityMask::all_valid(3);
let sub = mask.slice(2, 10);
assert_eq!(sub.len(), 1);
assert!(sub.get(0));
let empty = mask.slice(100, 5);
assert!(empty.is_empty());
}
#[test]
fn validity_mask_concat_appends() {
let a = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::NaN)]);
let b = ValidityMask::from_values(&[Scalar::Int64(2), Scalar::Int64(3)]);
let merged = a.concat(&b);
assert_eq!(merged.len(), 4);
assert!(merged.get(0));
assert!(!merged.get(1));
assert!(merged.get(2));
assert!(merged.get(3));
}
fn former_validity_mask_concat(left: &ValidityMask, right: &ValidityMask) -> ValidityMask {
let mut out = ValidityMask::all_invalid(left.len() + right.len());
for idx in 0..left.len() {
if left.get(idx) {
out.set(idx, true);
}
}
for idx in 0..right.len() {
if right.get(idx) {
out.set(left.len() + idx, true);
}
}
out
}
fn patterned_validity_mask(len: usize, salt: u64) -> ValidityMask {
let mut words = Vec::with_capacity(len.div_ceil(64));
for idx in 0..len.div_ceil(64) {
words.push(0xd6b5_8a3c_79e1_4f20_u64.rotate_left((idx as u32) ^ salt as u32));
}
if !len.is_multiple_of(64) {
*words.last_mut().expect("non-empty patterned validity") &= (1_u64 << (len % 64)) - 1;
}
ValidityMask::from_words(words, len)
}
#[test]
fn validity_mask_concat_packed_boundaries_match_former_path() {
for left_len in [1, 2, 63, 64, 65, 127, 128, 129] {
for right_len in [1, 3, 63, 64, 65, 130] {
let left = patterned_validity_mask(left_len, left_len as u64);
let right = patterned_validity_mask(right_len, right_len as u64 + 19);
assert_eq!(
left.concat(&right),
former_validity_mask_concat(&left, &right)
);
}
}
}
#[test]
#[ignore = "foreground release A/B only"]
fn validity_mask_concat_packed_ab() {
use std::{hint::black_box, time::Instant};
const LEFT_LEN: usize = 1_000_003;
const RIGHT_LEN: usize = 1_000_061;
const SAMPLES: usize = 10;
let left = patterned_validity_mask(LEFT_LEN, 7);
let right = patterned_validity_mask(RIGHT_LEN, 29);
let expected = former_validity_mask_concat(&left, &right);
assert_eq!(left.concat(&right), expected);
let mut former_ns = Vec::with_capacity(SAMPLES);
let mut packed_ns = Vec::with_capacity(SAMPLES);
let measure_former = || {
let start = Instant::now();
let output = former_validity_mask_concat(black_box(&left), black_box(&right));
black_box(output.count_valid());
start.elapsed().as_nanos()
};
let measure_packed = || {
let start = Instant::now();
let output = black_box(&left).concat(black_box(&right));
black_box(output.count_valid());
start.elapsed().as_nanos()
};
for sample in 0..SAMPLES {
if sample.is_multiple_of(2) {
former_ns.push(measure_former());
packed_ns.push(measure_packed());
} else {
packed_ns.push(measure_packed());
former_ns.push(measure_former());
}
}
former_ns.sort_unstable();
packed_ns.sort_unstable();
let former_p50 = former_ns[SAMPLES / 2];
let packed_p50 = packed_ns[SAMPLES / 2];
println!(
"validity_mask_concat_packed_ab left={LEFT_LEN} right={RIGHT_LEN} samples={SAMPLES} former_p50_ns={former_p50} packed_p50_ns={packed_p50} speedup={:.6}x",
former_p50 as f64 / packed_p50 as f64
);
println!("former_samples_ns={former_ns:?}");
println!("packed_samples_ns={packed_ns:?}");
}
#[test]
fn validity_mask_first_last_valid() {
let mask = ValidityMask::from_values(&[
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Null(NullKind::NaN),
]);
assert_eq!(mask.first_valid(), Some(2));
assert_eq!(mask.last_valid(), Some(3));
let none_set = ValidityMask::all_invalid(3);
assert_eq!(none_set.first_valid(), None);
assert_eq!(none_set.last_valid(), None);
}
#[test]
fn validity_mask_boundary_65_elements() {
let mut values = vec![Scalar::Int64(1); 65];
values[64] = Scalar::Null(NullKind::Null);
let mask = ValidityMask::from_values(&values);
assert_eq!(mask.len(), 65);
assert_eq!(mask.count_valid(), 64);
assert!(mask.get(63));
assert!(!mask.get(64));
}
#[test]
fn validity_mask_equality() {
let a = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::Null)]);
let b = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::Null)]);
let c = ValidityMask::from_values(&[Scalar::Null(NullKind::Null), Scalar::Int64(1)]);
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn validity_mask_nan_is_invalid() {
let values = vec![
Scalar::Float64(1.0),
Scalar::Float64(f64::NAN),
Scalar::Null(NullKind::NaN),
];
let mask = ValidityMask::from_values(&values);
assert!(mask.get(0));
assert!(!mask.get(1), "Float64(NaN) should be invalid");
assert!(!mask.get(2), "Null(NaN) should be invalid");
assert_eq!(mask.count_valid(), 1);
}
#[test]
fn validity_mask_dense_null_half() {
let values: Vec<Scalar> = (0..1000)
.map(|i| {
if i % 2 == 0 {
Scalar::Int64(i)
} else {
Scalar::Null(NullKind::Null)
}
})
.collect();
let mask = ValidityMask::from_values(&values);
assert_eq!(mask.len(), 1000);
assert_eq!(mask.count_valid(), 500);
}
// === AG-10: ColumnData and Vectorized Path Tests ===
#[test]
fn column_data_float64_roundtrip() {
let values = vec![
Scalar::Float64(1.5),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
];
let validity = ValidityMask::from_values(&values);
let data = super::ColumnData::from_scalars(&values, fp_types::DType::Float64);
let back = data.to_scalars(fp_types::DType::Float64, &validity);
assert_eq!(back.len(), 3);
assert_eq!(back[0], Scalar::Float64(1.5));
assert!(back[1].is_nan(), "position 1 should be NaN-missing");
assert_eq!(back[2], Scalar::Float64(3.0));
}
#[test]
fn column_data_int64_roundtrip() {
let values = vec![
Scalar::Int64(10),
Scalar::Null(NullKind::Null),
Scalar::Int64(30),
];
let validity = ValidityMask::from_values(&values);
let data = super::ColumnData::from_scalars(&values, fp_types::DType::Int64);
assert_eq!(data.len(), 3);
let back = data.to_scalars(fp_types::DType::Int64, &validity);
assert_eq!(back[0], Scalar::Int64(10));
assert!(back[1].is_missing());
assert_eq!(back[2], Scalar::Int64(30));
}
#[test]
fn column_data_interval_roundtrip_and_column_uniques_5g5uj() {
let first = Interval::new(0.0, 1.0, IntervalClosed::Right);
let second = Interval::new(1.0, 2.0, IntervalClosed::Right);
let values = vec![
Scalar::Interval(first),
Scalar::Null(NullKind::Null),
Scalar::Interval(second),
Scalar::Interval(first),
];
let validity = ValidityMask::from_values(&values);
let data = super::ColumnData::from_scalars(&values, DType::Interval);
assert_eq!(data.len(), 4);
let back = data.to_scalars(DType::Interval, &validity);
assert_eq!(back[0], Scalar::Interval(first));
assert!(back[1].is_missing());
assert_eq!(back[2], Scalar::Interval(second));
assert_eq!(back[3], Scalar::Interval(first));
let column = Column::new(DType::Interval, values).expect("interval column");
assert_eq!(column.dtype(), DType::Interval);
assert!(column.has_duplicates());
let uniques = column.unique().expect("unique intervals");
assert_eq!(
uniques.values(),
&[Scalar::Interval(first), Scalar::Interval(second)]
);
}
#[test]
fn vectorized_f64_addition_matches_scalar() {
let left = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
])
.expect("left");
let right = Column::from_values(vec![
Scalar::Float64(10.0),
Scalar::Float64(20.0),
Scalar::Float64(30.0),
])
.expect("right");
let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
assert_eq!(result.values()[0], Scalar::Float64(11.0));
assert_eq!(result.values()[1], Scalar::Float64(22.0));
assert_eq!(result.values()[2], Scalar::Float64(33.0));
}
#[test]
fn vectorized_i64_addition_matches_scalar() {
let left = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("left");
let right = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
])
.expect("right");
let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
assert_eq!(result.values()[0], Scalar::Int64(11));
assert_eq!(result.values()[1], Scalar::Int64(22));
assert_eq!(result.values()[2], Scalar::Int64(33));
}
#[test]
fn vectorized_binary_all_valid_keeps_typed_output_lazy() {
let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
assert!(result.validity().all());
assert_eq!(result.as_f64_slice(), Some([11.0, 22.0, 33.0].as_slice()));
// Output stays a lazy all-valid typed Float64 backing (not Scalar-
// materialized). The owned move-not-realloc path uses the `Vec` variant;
// accept either it or the `Arc<[f64]>` variant.
assert!(
matches!(
&result.values,
ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
) || matches!(
&result.values,
ScalarValues::LazyAllValidFloat64Vec { values, .. } if values.get().is_none()
)
);
}
#[test]
fn vectorized_binary_operation_nan_matches_scalar_validity() {
let left = Column::from_f64_values(vec![f64::INFINITY]);
let right = Column::from_f64_values(vec![f64::INFINITY]);
let result = left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub");
assert!(!result.validity().get(0));
assert!(matches!(result.values()[0], Scalar::Float64(v) if v.is_nan()));
}
#[test]
fn vectorized_f64_with_nulls_propagates_missing() {
let left = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
])
.expect("left");
let right = Column::from_values(vec![
Scalar::Float64(10.0),
Scalar::Float64(20.0),
Scalar::Null(NullKind::NaN),
])
.expect("right");
let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
assert_eq!(result.values()[0], Scalar::Float64(11.0));
assert!(result.values()[1].is_nan(), "null+valid should be NaN");
assert!(result.values()[2].is_nan(), "valid+null should be NaN");
}
#[test]
fn aligned_binary_f64_matches_reindex_then_binary_numeric() {
let left = Column::new(
DType::Float64,
vec![
Scalar::Float64(1.0),
Scalar::Float64(f64::NAN),
Scalar::Float64(3.5),
],
)
.expect("left");
let right = Column::new(
DType::Float64,
vec![
Scalar::Float64(10.0),
Scalar::Float64(20.0),
Scalar::Null(NullKind::NaN),
],
)
.expect("right");
let left_positions = [Some(2), None, Some(1), Some(0)];
let right_positions = [None, Some(0), Some(2), Some(1)];
let expected_left = left
.reindex_by_positions(&left_positions)
.expect("left reindex");
let expected_right = right
.reindex_by_positions(&right_positions)
.expect("right reindex");
let expected = expected_left
.binary_numeric(&expected_right, ArithmeticOp::Add)
.expect("generic add");
let actual = left
.aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
.expect("aligned add");
assert_eq!(actual.dtype(), expected.dtype());
assert_eq!(actual.values(), expected.values());
assert_eq!(actual.validity().len(), expected.validity().len());
for idx in 0..actual.len() {
assert_eq!(actual.validity().get(idx), expected.validity().get(idx));
}
}
#[test]
fn aligned_binary_f64_all_valid_keeps_typed_output_lazy() {
let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
let left_positions = [Some(0), Some(1), Some(2)];
let right_positions = [Some(0), Some(1), Some(2)];
let actual = left
.aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
.expect("aligned add");
assert!(actual.validity().all());
assert_eq!(actual.as_f64_slice(), Some([11.0, 22.0, 33.0].as_slice()));
assert!(matches!(
&actual.values,
ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
));
}
#[test]
fn aligned_binary_f64_nullable_gaps_keep_typed_output_lazy() {
let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
let left_positions = [Some(0), Some(1), Some(2), None];
let right_positions = [None, Some(0), Some(1), Some(2)];
let expected_left = left
.reindex_by_positions(&left_positions)
.expect("left reindex");
let expected_right = right
.reindex_by_positions(&right_positions)
.expect("right reindex");
let expected = expected_left
.binary_numeric(&expected_right, ArithmeticOp::Add)
.expect("generic add");
let actual = left
.aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
.expect("aligned add");
assert_eq!(actual.dtype(), expected.dtype());
assert_eq!(actual.validity(), expected.validity());
assert!(matches!(
&actual.values,
ScalarValues::LazyNullableFloat64 { values, .. } if values.get().is_none()
));
assert_eq!(actual.values(), expected.values());
}
#[test]
fn aligned_binary_f64_int64_unit_ranges_matches_position_alignment() {
let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
let left_positions = [Some(0), Some(1), Some(2), None];
let right_positions = [None, Some(0), Some(1), Some(2)];
let expected = left
.aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
.expect("position aligned add");
let actual = left
.aligned_binary_f64_int64_unit_ranges(&right, (0, 2), (1, 3), (0, 3), ArithmeticOp::Add)
.expect("unit range aligned add");
assert_eq!(actual.dtype(), expected.dtype());
assert_eq!(actual.validity(), expected.validity());
assert!(matches!(
&actual.values,
ScalarValues::LazyNullableFloat64 { values, .. } if values.get().is_none()
));
assert_eq!(actual.values(), expected.values());
}
#[test]
fn aligned_binary_f64_operation_nan_keeps_float_nan_materialization() {
let left = Column::from_f64_values(vec![f64::INFINITY]);
let right = Column::from_f64_values(vec![f64::INFINITY]);
let positions = [Some(0)];
let actual = left
.aligned_binary_f64(&right, &positions, &positions, ArithmeticOp::Sub)
.expect("aligned sub");
assert!(!actual.validity().get(0));
assert!(matches!(
&actual.values,
ScalarValues::LazyNullableFloat64 { values, .. } if values.get().is_none()
));
assert!(matches!(actual.values()[0], Scalar::Float64(value) if value.is_nan()));
}
#[test]
fn apply_f64_slices_matches_fn_pointer_per_element_f64simd() {
// The monomorphized slice op must be bit-for-bit identical to the
// per-element fn pointer across every op and tricky operand
// (NaN/inf/-0.0/zero divisor/negative base). Compared via raw bits so
// NaN payloads must also match.
let vals = [
0.0_f64,
-0.0,
1.0,
-1.0,
2.5,
-3.0,
4.0,
0.5,
f64::NAN,
f64::INFINITY,
f64::NEG_INFINITY,
1e300,
-1e-300,
];
let a: Vec<f64> = vals.to_vec();
for op in [
ArithmeticOp::Add,
ArithmeticOp::Sub,
ArithmeticOp::Mul,
ArithmeticOp::Div,
ArithmeticOp::Mod,
ArithmeticOp::Pow,
ArithmeticOp::FloorDiv,
] {
for shift in 0..vals.len() {
let b: Vec<f64> = (0..vals.len())
.map(|i| vals[(i + shift) % vals.len()])
.collect();
let got = super::apply_f64_slices_nan_tracked(op, &a, &b).0;
let apply = super::binary_f64_apply(op);
let expected: Vec<f64> = a.iter().zip(&b).map(|(x, y)| apply(*x, *y)).collect();
for i in 0..a.len() {
assert_eq!(
got[i].to_bits(),
expected[i].to_bits(),
"op={op:?} a={} b={}",
a[i],
b[i]
);
}
}
}
}
#[test]
fn apply_f64_slices_parallel_matches_serial_nan_tracking() {
let n = (1usize << 20) + 17;
let mut a: Vec<f64> = (0..n).map(|i| i as f64 * 0.25 + 1.0).collect();
let mut b: Vec<f64> = (0..n).map(|i| i as f64 * 0.125 - 7.0).collect();
a[1024] = f64::NAN;
a[n - 3] = f64::INFINITY;
b[n - 3] = f64::INFINITY;
let (got, got_input_nan, got_output_nan) =
super::apply_f64_slices_nan_tracked(ArithmeticOp::Sub, &a, &b);
let mut expected = vec![0.0_f64; n];
let (expected_input_nan, expected_output_nan) =
super::apply_f64_slices_nan_tracked_into(ArithmeticOp::Sub, &a, &b, &mut expected);
assert_eq!(got_input_nan, expected_input_nan);
assert_eq!(got_output_nan, expected_output_nan);
for i in 0..n {
assert_eq!(got[i].to_bits(), expected[i].to_bits(), "i={i}");
}
}
#[test]
fn aligned_binary_f64_same_positions_matches_identity_alignment() {
let left = Column::new(
DType::Float64,
vec![
Scalar::Float64(1.0),
Scalar::Float64(f64::NAN),
Scalar::Float64(3.0),
],
)
.expect("left");
let right = Column::new(
DType::Float64,
vec![
Scalar::Float64(10.0),
Scalar::Float64(20.0),
Scalar::Null(NullKind::NaN),
],
)
.expect("right");
let positions = [Some(0), Some(1), Some(2)];
let expected = left
.aligned_binary_f64(&right, &positions, &positions, ArithmeticOp::Add)
.expect("identity aligned add");
let actual = left
.aligned_binary_f64_same_positions(&right, ArithmeticOp::Add)
.expect("same-position add");
assert_eq!(actual.dtype(), expected.dtype());
assert_eq!(actual.values(), expected.values());
for idx in 0..actual.len() {
assert_eq!(actual.validity().get(idx), expected.validity().get(idx));
}
}
#[test]
fn aligned_binary_f64_same_positions_keeps_hot_owned_buffer_all_valid() {
let left = Column::from_f64_values(vec![1.0, 2.0, 3.0, 4.0]);
let right = Column::from_f64_values(vec![10.0, 20.0, 30.0, 40.0]);
let actual = left
.aligned_binary_f64_same_positions(&right, ArithmeticOp::Add)
.expect("same-position add");
assert_eq!(
actual.as_f64_slice().expect("all-valid typed output"),
&[11.0, 22.0, 33.0, 44.0]
);
assert!(matches!(
&actual.values,
ScalarValues::LazyAllValidFloat64Vec { values, .. } if values.get().is_none()
));
}
#[test]
fn aligned_binary_f64_same_positions_matches_general_path_for_all_ops_with_nan_inf() {
// br-frankenpandas-d3mfh: lock the same-positions f64 fast path
// byte-identical to the general alignment path (the reference) for every
// op across NaN inputs, inf±inf generated NaN, and the `Pow` identity
// slots (`NaN**0`, `1**NaN`). This pins the parity that makes the two
// input NaN pre-scans NON-removable: an input NaN must surface as
// `Scalar::Null(NaN)` (not `Float64(NaN)`), and `NaN**0 == 1.0` must stay
// missing — exactly what routing NaN inputs to the general arm preserves.
// Build pathological all-valid columns whose f64 data still contains NaN.
// (Normal constructors mark a NaN slot invalid, so the `validity.all()`
// fast path would never see a NaN; a strided/aliased lazy view can,
// however, present `validity.all()` over NaN-bearing data — that is the
// exact case the dropped input pre-scan must remain correct for.)
let make = |data: Vec<f64>| -> Column {
let len = data.len();
Column {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64(data),
validity: ValidityMask::all_valid(len),
data: None,
}
};
let left = make(vec![1.0, f64::NAN, 2.0, f64::INFINITY, 1.0, f64::NAN, -3.5]);
let right = make(vec![10.0, 3.0, f64::NAN, f64::INFINITY, f64::NAN, 0.0, 2.0]);
assert!(left.validity().all());
assert!(right.validity().all());
let n = left.len();
let positions: Vec<Option<usize>> = (0..n).map(Some).collect();
for op in [
ArithmeticOp::Add,
ArithmeticOp::Sub,
ArithmeticOp::Mul,
ArithmeticOp::Div,
ArithmeticOp::Mod,
ArithmeticOp::Pow,
ArithmeticOp::FloorDiv,
] {
let expected = left
.aligned_binary_f64(&right, &positions, &positions, op)
.expect("general aligned path");
let actual = left
.aligned_binary_f64_same_positions(&right, op)
.expect("same-position fast path");
assert_eq!(actual.dtype(), expected.dtype(), "dtype op={op:?}");
assert_eq!(actual.len(), expected.len(), "len op={op:?}");
let got = actual.values();
let want = expected.values();
for i in 0..n {
// Raw-bit scalar equality (covers NaN payloads + missing kind).
match (&got[i], &want[i]) {
(Scalar::Float64(g), Scalar::Float64(w)) => {
assert_eq!(g.to_bits(), w.to_bits(), "value bits op={op:?} slot={i}")
}
(g, w) => assert_eq!(g, w, "scalar op={op:?} slot={i}"),
}
assert_eq!(
actual.validity().get(i),
expected.validity().get(i),
"validity op={op:?} slot={i}"
);
}
}
}
#[test]
fn aligned_binary_f64_borrows_lazy_float64_clone_data() {
let left = Column::from_f64_values(vec![1.0, f64::NAN, 4.0]).clone();
let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]).clone();
assert!(left.data.is_none());
assert!(right.data.is_none());
assert!(matches!(
&left.values,
ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
));
assert!(matches!(
&right.values,
ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
));
let left_positions = [Some(0), Some(1), Some(2), None];
let right_positions = [Some(2), Some(1), None, Some(0)];
let actual = left
.aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
.expect("aligned add");
assert_eq!(
actual.values(),
&[
Scalar::Float64(31.0),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
]
);
if let ScalarValues::LazyAllValidFloat64 { values, .. } = &left.values {
assert!(values.get().is_none());
}
if let ScalarValues::LazyAllValidFloat64 { values, .. } = &right.values {
assert!(values.get().is_none());
}
}
#[test]
fn from_f64_values_marks_nan_missing_like_scalar_path() {
// br-frankenpandas-jyhf7: typed ingestion must treat NaN as missing,
// matching Column::new(Float64, scalars). Otherwise a NaN-bearing column
// claims all-valid and as_f64_slice leaks the NaN as a real value.
let typed = Column::from_f64_values(vec![1.0, f64::NAN, 3.0, f64::NAN]);
let scalar = Column::new(
DType::Float64,
vec![
Scalar::Float64(1.0),
Scalar::Float64(f64::NAN),
Scalar::Float64(3.0),
Scalar::Float64(f64::NAN),
],
)
.expect("scalar col");
// Per-position validity agrees with the Scalar path.
for idx in 0..typed.len() {
assert_eq!(
typed.validity().get(idx),
scalar.validity().get(idx),
"validity mismatch at {idx}"
);
}
assert!(typed.validity().get(0));
assert!(!typed.validity().get(1));
assert!(typed.validity().get(2));
assert!(!typed.validity().get(3));
assert_eq!(typed.validity().count_valid(), 2);
// A NaN-bearing column must NOT expose its raw f64 slice (the typed
// fast path is only valid when every value is present).
assert!(typed.as_f64_slice().is_none());
// No-NaN columns keep the all-valid fast path and expose the slice.
let clean = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
assert!(clean.validity().all());
assert_eq!(clean.as_f64_slice(), Some([1.0, 2.0, 3.0].as_slice()));
}
#[test]
fn repeated_slices_float64_exposes_cached_typed_slice() {
let column = Column::from_f64_repeated_slices_shared(
vec![11.0, 22.0, 33.0, 44.0],
Arc::from([(1usize, 2usize), (0, 3), (3, 1)].as_slice()),
6,
);
let expected = [22.0, 33.0, 11.0, 22.0, 33.0, 44.0];
assert_eq!(column.as_f64_slice(), Some(expected.as_slice()));
assert_eq!(column.as_f64_slice(), Some(expected.as_slice()));
assert_eq!(column.all_valid_f64_to_vec(), Some(expected.to_vec()));
assert_eq!(
column.values(),
&[
Scalar::Float64(22.0),
Scalar::Float64(33.0),
Scalar::Float64(11.0),
Scalar::Float64(22.0),
Scalar::Float64(33.0),
Scalar::Float64(44.0),
]
);
}
#[test]
fn repeated_slices_float64_expands_periodic_prefix() {
let column = Column::from_f64_repeated_slices_shared(
vec![1.0, 2.0, 3.0],
Arc::from([(0usize, 3usize), (0, 3), (0, 2)].as_slice()),
8,
);
assert_eq!(
column.as_f64_slice(),
Some([1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0].as_slice())
);
assert_eq!(
column.all_valid_f64_to_vec(),
Some(vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0])
);
}
#[test]
fn finite_float64_arc_view_uses_constructor_witness() {
let finite = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(-0.0),
Scalar::Float64(3.5),
])
.expect("finite float column");
assert!(
finite.as_f64_finite_arc_view_source(3).is_some(),
"all-finite Float64 columns should expose the finite Arc view"
);
assert!(
finite.clone().as_f64_finite_arc_view_source(3).is_some(),
"finite witness should survive Column::clone"
);
let with_infinity =
Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(f64::INFINITY)])
.expect("infinite float column");
assert!(
with_infinity.as_f64_finite_arc_view_source(2).is_none(),
"infinity is valid Float64 data but must not enter finite dot fast paths"
);
let with_nan = Column::from_f64_values(vec![1.0, f64::NAN]);
assert!(
with_nan.as_f64_finite_arc_view_source(2).is_none(),
"NaN-bearing Float64 columns are nullable and must not expose all-valid views"
);
}
#[test]
fn from_f64_all_valid_chunks_materializes_in_chunk_order() {
let first: Arc<[f64]> = Arc::from(vec![9.0, 1.0, 2.0, 8.0]);
let second: Arc<[f64]> = Arc::from(vec![3.0, 4.0, 5.0]);
let column = Column::from_f64_all_valid_chunks(
vec![(Arc::clone(&first), 1, 2), (Arc::clone(&second), 0, 3)],
5,
);
assert_eq!(column.len(), 5);
assert!(column.validity().all());
assert_eq!(
column.as_f64_slice(),
Some([1.0, 2.0, 3.0, 4.0, 5.0].as_slice())
);
assert_eq!(
column.values(),
&[
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
Scalar::Float64(4.0),
Scalar::Float64(5.0),
]
);
}
#[test]
fn from_i64_all_valid_chunks_materializes_in_chunk_order() {
let first: Arc<[i64]> = Arc::from(vec![99, 1, 2, 88]);
let second: Arc<[i64]> = Arc::from(vec![3, 4, 5]);
let column = Column::from_i64_all_valid_chunks(
vec![(Arc::clone(&first), 1, 2), (Arc::clone(&second), 0, 3)],
5,
);
assert_eq!(column.len(), 5);
assert!(column.validity().all());
assert_eq!(column.as_i64_slice(), Some([1, 2, 3, 4, 5].as_slice()));
assert_eq!(
column.values(),
&[
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
Scalar::Int64(5),
]
);
assert_eq!(
column.clone(),
Column::from_i64_values_owned(vec![1, 2, 3, 4, 5])
);
}
#[test]
fn from_f64_all_valid_dot_product_materializes_left_fold_rows() {
let a0: Arc<[f64]> = Arc::from(vec![99.0, 1.0, 3.0, 5.0]);
let a1: Arc<[f64]> = Arc::from(vec![2.0, 4.0, 6.0]);
let b: Arc<[f64]> = Arc::from(vec![10.0, 0.5]);
let column = Column::from_f64_all_valid_dot_product(
vec![(Arc::clone(&a0), 1), (Arc::clone(&a1), 0)],
b,
3,
);
assert_eq!(column.len(), 3);
assert!(column.validity().all());
assert_eq!(column.as_f64_slice(), Some([11.0, 32.0, 53.0].as_slice()));
assert_eq!(
column.values(),
&[
Scalar::Float64(11.0),
Scalar::Float64(32.0),
Scalar::Float64(53.0),
]
);
}
#[test]
fn vectorized_i64_with_nulls_propagates_missing() {
let left = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
])
.expect("left");
let right = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Null(NullKind::Null),
])
.expect("right");
let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
assert_eq!(result.values()[0], Scalar::Int64(11));
assert!(result.values()[1].is_missing());
assert!(result.values()[2].is_missing());
}
// Feasibility probe (br-frankenpandas dot GEMM epic): can safe-Rust
// autovectorization keep an MR×NR accumulator micro-tile in SIMD registers
// and hit BLAS-competitive GFLOP/s? The current AXPY dot is ~9.5 GFLOP/s
// (memory-traffic-bound); OpenBLAS is ~118. If a register-tiled microkernel
// over PACKED contiguous panels stays near 9.5, the epic is not worth
// building in safe Rust; if it approaches 40-70, it is. Run with:
// cargo test -p fp-columnar --release microkernel_gflops_feasibility -- --ignored --nocapture
#[test]
#[ignore = "perf feasibility probe; run with --release --ignored --nocapture"]
fn microkernel_gflops_feasibility_dustysummit() {
use std::time::Instant;
// Square GEMM C(m×n) = A(m×k)·B(k×n), all contiguous row-major, packed
// so the microkernel sees unit-stride A-rows and B-rows.
const DIM: usize = 1000;
let (m, k, n) = (DIM, DIM, DIM);
// A row-major: a[i*k + l]. B row-major: b[l*n + c] (already "packed" for
// the kernel's B access b[l*n + c0..c0+NR] contiguous per l).
let mut state = 0x1234_5678_9abc_def0u64;
let mut next = || {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
((state >> 11) as f64) / ((1u64 << 53) as f64)
};
let a: Vec<f64> = (0..m * k).map(|_| next()).collect();
let b: Vec<f64> = (0..k * n).map(|_| next()).collect();
// MR×NR = 4×8 register micro-tile. acc holds MR rows × NR cols; the NR=8
// inner arrays are the vectorization target (2 ymm each under AVX2).
const MR: usize = 4;
const NR: usize = 8;
let gemm = |c: &mut [f64]| {
let mut i0 = 0;
while i0 + MR <= m {
let mut c0 = 0;
while c0 + NR <= n {
let mut acc = [[0.0f64; NR]; MR];
for l in 0..k {
let bl = &b[l * n + c0..l * n + c0 + NR];
for ii in 0..MR {
let a_il = a[(i0 + ii) * k + l];
let acc_ii = &mut acc[ii];
for jj in 0..NR {
acc_ii[jj] += a_il * bl[jj];
}
}
}
for ii in 0..MR {
let row = &mut c[(i0 + ii) * n + c0..(i0 + ii) * n + c0 + NR];
row.copy_from_slice(&acc[ii]);
}
c0 += NR;
}
i0 += MR;
}
};
let mut c = vec![0.0f64; m * n];
gemm(&mut c); // warm
let reps = 5;
let mut best = f64::INFINITY;
for _ in 0..reps {
let t = Instant::now();
gemm(&mut c);
best = best.min(t.elapsed().as_secs_f64());
}
let gflops = 2.0 * (m as f64) * (n as f64) * (k as f64) / best / 1e9;
println!(
"microkernel {MR}x{NR} {DIM}^3: best {:.2} ms = {gflops:.1} GFLOP/s (AXPY dot ~9.5, OpenBLAS ~118)",
best * 1e3
);
std::hint::black_box(&c);
assert!(gflops.is_finite());
}
#[test]
fn column_from_values_preserves_mixed_utf8_numeric_scalars() {
let column = Column::from_values(vec![Scalar::Utf8("x".into()), Scalar::Int64(1)])
.expect("mixed object-like constructor should succeed");
assert_eq!(column.dtype(), DType::Utf8);
assert_eq!(
column.values(),
&[Scalar::Utf8("x".into()), Scalar::Int64(1)]
);
}
#[test]
fn vectorized_division_promotes_to_float64() {
let left = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(21)]).expect("left");
let right = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(7)]).expect("right");
let result = left.binary_numeric(&right, ArithmeticOp::Div).expect("div");
// Division always promotes to Float64.
assert_eq!(result.dtype(), fp_types::DType::Float64);
assert!(matches!(result.values()[0], Scalar::Float64(v) if (v - 10.0/3.0).abs() < 1e-10));
assert_eq!(result.values()[1], Scalar::Float64(3.0));
}
#[test]
fn vectorized_all_four_ops_f64() {
let left = Column::from_values(vec![Scalar::Float64(10.0)]).expect("left");
let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
let add = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
let sub = left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub");
let mul = left.binary_numeric(&right, ArithmeticOp::Mul).expect("mul");
let div = left.binary_numeric(&right, ArithmeticOp::Div).expect("div");
assert_eq!(add.values()[0], Scalar::Float64(13.0));
assert_eq!(sub.values()[0], Scalar::Float64(7.0));
assert_eq!(mul.values()[0], Scalar::Float64(30.0));
assert!(matches!(div.values()[0], Scalar::Float64(v) if (v - 10.0/3.0).abs() < 1e-10));
}
#[test]
fn pandas_arithmetic_aliases_match_binary_numeric() {
let left = Column::from_values(vec![Scalar::Float64(10.0)]).expect("left");
let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
assert_eq!(
left.add(&right).expect("add"),
left.binary_numeric(&right, ArithmeticOp::Add).expect("add")
);
assert_eq!(
left.sub(&right).expect("sub"),
left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub")
);
assert_eq!(
left.mul(&right).expect("mul"),
left.binary_numeric(&right, ArithmeticOp::Mul).expect("mul")
);
assert_eq!(
left.div(&right).expect("div"),
left.binary_numeric(&right, ArithmeticOp::Div).expect("div")
);
assert_eq!(
left.divide(&right).expect("divide"),
left.div(&right).expect("div")
);
}
#[test]
fn remaining_pandas_arithmetic_aliases_match_binary_numeric() {
let left = Column::from_values(vec![Scalar::Float64(10.0)]).expect("left");
let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
assert_eq!(
left.subtract(&right).expect("subtract"),
left.sub(&right).expect("sub")
);
assert_eq!(
left.multiply(&right).expect("multiply"),
left.mul(&right).expect("mul")
);
assert_eq!(
left.truediv(&right).expect("truediv"),
left.div(&right).expect("div")
);
assert_eq!(
left.floordiv(&right).expect("floordiv"),
left.binary_numeric(&right, ArithmeticOp::FloorDiv)
.expect("floordiv")
);
assert_eq!(
left.r#mod(&right).expect("mod"),
left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod")
);
assert_eq!(
left.pow(&right).expect("pow"),
left.binary_numeric(&right, ArithmeticOp::Pow).expect("pow")
);
}
#[test]
fn temporal_two_col_arith_exact_masks_missing_and_rejects_bad_combos() {
// Typed temporal arm in binary_numeric: dt - dt -> Timedelta64 (elapsed ns),
// td - td / td + td -> Timedelta64, over raw i64 ns with the saturating/
// NaT-propagating Timedelta::sub/add the rest of FP uses. A row is missing iff
// either operand is missing (validity unset OR NaT sentinel) => Timedelta64(NaT).
// Was erroring (to_f64 rejects a temporal scalar). Reference mirrors the arm
// exactly; values near 1.6e18 >> 2^53 prove exactness. Also asserts the combos
// that must STILL error: dt + dt (pandas raises), dt * dt, mixed dt - td.
let mut state: u64 = 0x7EA0_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let build = |n: usize,
nullable: bool,
nat: i64,
is_dt: bool,
next: &mut dyn FnMut() -> u64|
-> (Column, Vec<i64>, Vec<bool>) {
let base: i64 = if is_dt { 1_600_000_000_000_000_000 } else { 0 };
let mut data = Vec::with_capacity(n);
let mut validity = ValidityMask::all_valid(n);
let mut vbits = vec![true; n];
for i in 0..n {
if nullable && next() % 4 == 0 {
validity.set(i, false);
vbits[i] = false;
data.push(base + (next() % 1000) as i64);
} else if next() % 6 == 0 {
data.push(nat);
} else {
data.push(base + (next() % 100_000) as i64 - 50_000);
}
}
let col = if is_dt {
Column::from_datetime64_values_with_validity(data.clone(), validity)
} else {
Column::from_timedelta64_values_with_validity(data.clone(), validity)
};
(col, data, vbits)
};
// Every pandas-defined combo: (left_is_dt, right_is_dt, is_add, out_is_dt).
let combos: [(bool, bool, bool, bool); 6] = [
(true, true, false, false), // dt - dt -> td
(false, false, false, false), // td - td -> td
(false, false, true, false), // td + td -> td
(true, false, true, true), // dt + td -> dt
(true, false, false, true), // dt - td -> dt
(false, true, true, true), // td + dt -> dt
];
// NaT sentinel is i64::MIN for both temporal dtypes.
let nat = fp_types::Timedelta::NAT;
for (l_dt, r_dt, is_add, out_dt) in combos {
for trial in 0..60 {
let n = (next() % 200) as usize;
for nullable in [false, true] {
let (lc, ld, lv) = build(n, nullable, nat, l_dt, &mut next);
let (rc, rd, rv) = build(n, nullable, nat, r_dt, &mut next);
let got = if is_add { lc.add(&rc) } else { lc.sub(&rc) }
.expect("temporal arith must not error");
assert_eq!(
got.dtype(),
if out_dt { DType::Datetime64 } else { DType::Timedelta64 }
);
let expected: Vec<Scalar> = (0..n)
.map(|i| {
let v = if is_add {
fp_types::Timedelta::add(ld[i], rd[i])
} else {
fp_types::Timedelta::sub(ld[i], rd[i])
};
if !(lv[i] && rv[i]) || v == fp_types::Timedelta::NAT {
Scalar::Null(NullKind::NaT)
} else if out_dt {
Scalar::Datetime64(v)
} else {
Scalar::Timedelta64(v)
}
})
.collect();
assert_eq!(
got.values(),
expected,
"l_dt={l_dt} r_dt={r_dt} is_add={is_add} trial {trial} nullable={nullable}"
);
}
}
}
// Combos that must keep rejecting (match pandas raising / IncompatibleDtypes).
let dt = Column::from_datetime64_values(vec![10, 20]);
let dt2 = Column::from_datetime64_values(vec![1, 2]);
let td = Column::from_timedelta64_values_with_validity(
vec![3, 4],
ValidityMask::all_valid(2),
);
assert!(dt.add(&dt2).is_err(), "dt + dt must raise");
assert!(dt.mul(&dt2).is_err(), "dt * dt must raise");
assert!(td.sub(&dt).is_err(), "td - dt must raise (can't subtract a datetime from a duration)");
assert!(td.mul(&dt).is_err(), "td * dt must raise");
}
#[test]
fn nullable_i64_two_col_arith_matches_scalar_reference_cf() {
// Nullable Int64 × Int64 elementwise arithmetic routes through the typed
// `as_i64_slice_with_validity` fast path in `try_vectorized_binary` and
// must stay bit-identical to a hand reference: both-valid ⇒ wrapping op;
// either operand missing ⇒ Null(Null). i64::MAX + 1 exercises wrapping.
let build = |vals: &[Option<i64>]| {
let data: Vec<i64> = vals.iter().map(|v| v.unwrap_or(0)).collect();
let mut validity = ValidityMask::all_valid(vals.len());
for (i, v) in vals.iter().enumerate() {
if v.is_none() {
validity.set(i, false);
}
}
Column::from_i64_values_with_validity(data, validity)
};
let lv = [Some(5_i64), Some(-3), None, Some(i64::MAX), Some(0), None, Some(7)];
let rv = [Some(2_i64), None, Some(9), Some(1), Some(-8), None, Some(-7)];
let left = build(&lv);
let right = build(&rv);
assert!(
left.as_i64_slice_with_validity().is_some()
&& right.as_i64_slice_with_validity().is_some(),
"fixture must exercise the typed nullable backing"
);
let reference = |op: fn(i64, i64) -> i64| -> Vec<Scalar> {
lv.iter()
.zip(rv.iter())
.map(|(a, b)| match (a, b) {
(Some(x), Some(y)) => Scalar::Int64(op(*x, *y)),
_ => Scalar::Null(NullKind::Null),
})
.collect()
};
assert_eq!(
left.add(&right).expect("add").values(),
reference(|a, b| a.wrapping_add(b)),
"nullable Int64 add"
);
assert_eq!(
left.sub(&right).expect("sub").values(),
reference(|a, b| a.wrapping_sub(b)),
"nullable Int64 sub"
);
assert_eq!(
left.mul(&right).expect("mul").values(),
reference(|a, b| a.wrapping_mul(b)),
"nullable Int64 mul"
);
}
#[test]
fn nullable_f64_two_col_arith_matches_reference_cf() {
// Nullable Float64 × Float64 arithmetic routes through the typed
// from_f64_values_nullable output path. Bit-identical to the old
// Vec<Scalar>+Self::new: both-valid ⇒ Float64(op); either missing ⇒
// Null(NaN); op-produced NaN (0/0) ⇒ present Float64(NaN) with validity
// cleared. add/sub/mul over finite inputs never produce NaN → clean
// assert_eq; div's 0/0 exercises the op-NaN three-way slot.
let build = |vals: &[Option<f64>]| {
let data: Vec<f64> = vals.iter().map(|v| v.unwrap_or(0.0)).collect();
let mut validity = ValidityMask::all_valid(vals.len());
for (i, v) in vals.iter().enumerate() {
if v.is_none() {
validity.set(i, false);
}
}
Column::from_f64_values_with_validity(data, validity)
};
let lv = [Some(5.0), Some(-3.5), None, Some(2.0), Some(0.0), None, Some(7.25)];
let rv = [Some(2.0), None, Some(9.0), Some(4.0), Some(0.0), None, Some(-1.5)];
let left = build(&lv);
let right = build(&rv);
let reference = |op: fn(f64, f64) -> f64| -> Vec<Scalar> {
lv.iter()
.zip(rv.iter())
.map(|(a, b)| match (a, b) {
(Some(x), Some(y)) => Scalar::Float64(op(*x, *y)),
_ => Scalar::Null(NullKind::NaN),
})
.collect()
};
assert_eq!(left.add(&right).expect("add").values(), reference(|a, b| a + b), "add");
assert_eq!(left.sub(&right).expect("sub").values(), reference(|a, b| a - b), "sub");
assert_eq!(left.mul(&right).expect("mul").values(), reference(|a, b| a * b), "mul");
// div: op-produced NaN (0/0 at idx 4) stays a present Float64(NaN); the
// absent-operand slots stay Null. NaN needs a bit-compare, not ==.
let d = left.div(&right).expect("div");
let dv = d.values();
match &dv[0] {
Scalar::Float64(x) => assert_eq!(*x, 2.5),
o => panic!("div[0]={o:?}"),
}
assert!(matches!(dv[1], Scalar::Null(_)), "div[1] null (rhs null)");
assert!(matches!(dv[2], Scalar::Null(_)), "div[2] null (lhs null)");
match &dv[3] {
Scalar::Float64(x) => assert_eq!(*x, 0.5),
o => panic!("div[3]={o:?}"),
}
match &dv[4] {
Scalar::Float64(x) => assert!(x.is_nan(), "0/0 ⇒ present NaN"),
o => panic!("div[4]={o:?}"),
}
assert!(matches!(dv[5], Scalar::Null(_)), "div[5] null (both null)");
}
#[test]
fn nullable_mixed_i64_f64_arith_matches_reference_cf() {
// Mixed nullable Int64 × nullable Float64 (→ Float64) routes through the
// generalized f64_view_naw arm (Int64 mapped `v as f64`, Float64 borrowed).
// Both-valid ⇒ Float64(op(x as f64, y)); either missing ⇒ Null(NaN). Finite
// inputs ⇒ no op-NaN ⇒ clean assert_eq vs a hand reference.
let ldata = [Some(5_i64), Some(-3), None, Some(7), Some(0), None];
let rdata = [Some(2.0_f64), None, Some(9.5), Some(4.0), Some(-1.5), None];
let build_i64 = |vals: &[Option<i64>]| {
let data: Vec<i64> = vals.iter().map(|v| v.unwrap_or(0)).collect();
let mut validity = ValidityMask::all_valid(vals.len());
for (i, v) in vals.iter().enumerate() {
if v.is_none() {
validity.set(i, false);
}
}
Column::from_i64_values_with_validity(data, validity)
};
let build_f64 = |vals: &[Option<f64>]| {
let data: Vec<f64> = vals.iter().map(|v| v.unwrap_or(0.0)).collect();
let mut validity = ValidityMask::all_valid(vals.len());
for (i, v) in vals.iter().enumerate() {
if v.is_none() {
validity.set(i, false);
}
}
Column::from_f64_values_with_validity(data, validity)
};
let left = build_i64(&ldata);
let right = build_f64(&rdata);
assert!(
left.as_i64_slice_with_validity().is_some()
&& right.as_f64_slice_with_validity().is_some(),
"fixture must exercise the mixed typed backings"
);
let reference = |op: fn(f64, f64) -> f64| -> Vec<Scalar> {
ldata
.iter()
.zip(rdata.iter())
.map(|(a, b)| match (a, b) {
(Some(x), Some(y)) => Scalar::Float64(op(*x as f64, *y)),
_ => Scalar::Null(NullKind::NaN),
})
.collect()
};
// Int64 (left) op Float64 (right).
assert_eq!(left.add(&right).expect("add").values(), reference(|a, b| a + b), "i64+f64");
assert_eq!(left.sub(&right).expect("sub").values(), reference(|a, b| a - b), "i64-f64");
assert_eq!(left.mul(&right).expect("mul").values(), reference(|a, b| a * b), "i64*f64");
// Float64 (left) op Int64 (right): exercises the reverse view combo.
assert_eq!(right.add(&left).expect("radd").values(), reference(|a, b| b + a), "f64+i64");
assert_eq!(right.sub(&left).expect("rsub").values(), reference(|a, b| b - a), "f64-i64");
}
#[test]
fn pandas_reverse_arithmetic_aliases_swap_operands() {
let series = Column::from_values(vec![Scalar::Float64(10.0)]).expect("series");
let other = Column::from_values(vec![Scalar::Float64(3.0)]).expect("other");
assert_eq!(
series.radd(&other).expect("radd"),
other
.binary_numeric(&series, ArithmeticOp::Add)
.expect("add")
);
assert_eq!(
series.rsub(&other).expect("rsub"),
other
.binary_numeric(&series, ArithmeticOp::Sub)
.expect("sub")
);
assert_eq!(
series.rmul(&other).expect("rmul"),
other
.binary_numeric(&series, ArithmeticOp::Mul)
.expect("mul")
);
assert_eq!(
series.rdiv(&other).expect("rdiv"),
other
.binary_numeric(&series, ArithmeticOp::Div)
.expect("div")
);
assert_eq!(
series.rtruediv(&other).expect("rtruediv"),
series.rdiv(&other).expect("rdiv")
);
assert_eq!(
series.rfloordiv(&other).expect("rfloordiv"),
other
.binary_numeric(&series, ArithmeticOp::FloorDiv)
.expect("floordiv")
);
assert_eq!(
series.rmod(&other).expect("rmod"),
other
.binary_numeric(&series, ArithmeticOp::Mod)
.expect("mod")
);
assert_eq!(
series.rpow(&other).expect("rpow"),
other
.binary_numeric(&series, ArithmeticOp::Pow)
.expect("pow")
);
}
#[test]
fn vectorized_f64_mod_pow_floordiv() {
let left = Column::from_values(vec![
Scalar::Float64(10.0),
Scalar::Float64(2.0),
Scalar::Float64(-3.0),
])
.expect("left");
let right = Column::from_values(vec![
Scalar::Float64(3.0),
Scalar::Float64(3.0),
Scalar::Float64(2.0),
])
.expect("right");
let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
assert_eq!(modulo.dtype(), DType::Float64);
assert!(matches!(modulo.values()[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
assert!(matches!(modulo.values()[1], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
assert!(matches!(modulo.values()[2], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
let pow = left.binary_numeric(&right, ArithmeticOp::Pow).expect("pow");
assert_eq!(pow.dtype(), DType::Float64);
assert!(matches!(pow.values()[0], Scalar::Float64(v) if (v - 1000.0).abs() < 1e-10));
assert!(matches!(pow.values()[1], Scalar::Float64(v) if (v - 8.0).abs() < 1e-10));
assert!(matches!(pow.values()[2], Scalar::Float64(v) if (v - 9.0).abs() < 1e-10));
let floordiv = left
.binary_numeric(&right, ArithmeticOp::FloorDiv)
.expect("floordiv");
assert_eq!(floordiv.dtype(), DType::Float64);
assert!(matches!(floordiv.values()[0], Scalar::Float64(v) if (v - 3.0).abs() < 1e-10));
assert!(matches!(floordiv.values()[1], Scalar::Float64(v) if (v - 0.0).abs() < 1e-10));
assert!(matches!(floordiv.values()[2], Scalar::Float64(v) if (v - -2.0).abs() < 1e-10));
}
#[test]
fn int_pow_stays_int64_and_negative_exponent_raises_3w0xn() {
// br-frankenpandas-3w0xn: int ** int stays int64 (numpy/pandas: 2 ** 3
// == 8, not 8.0), and a negative integer exponent raises.
let base = Column::from_values(vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(10)])
.expect("base");
let exp = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(2), Scalar::Int64(2)])
.expect("exp");
let pow = base
.binary_numeric(&exp, ArithmeticOp::Pow)
.expect("int pow");
assert_eq!(pow.dtype(), DType::Int64);
assert_eq!(pow.values()[0], Scalar::Int64(8));
assert_eq!(pow.values()[1], Scalar::Int64(9));
assert_eq!(pow.values()[2], Scalar::Int64(100));
// Negative integer exponent raises (numpy ValueError analogue).
let neg_exp =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(-1), Scalar::Int64(2)])
.expect("neg_exp");
let err = base
.binary_numeric(&neg_exp, ArithmeticOp::Pow)
.expect_err("negative integer power must raise");
assert!(matches!(err, ColumnError::NegativeIntegerPower));
// A float operand promotes the whole op to Float64.
let exp_f = Column::from_values(vec![
Scalar::Float64(3.0),
Scalar::Float64(2.0),
Scalar::Float64(2.0),
])
.expect("exp_f");
let pow_f = base
.binary_numeric(&exp_f, ArithmeticOp::Pow)
.expect("mixed int/float pow");
assert_eq!(pow_f.dtype(), DType::Float64);
assert!(matches!(pow_f.values()[0], Scalar::Float64(v) if (v - 8.0).abs() < 1e-10));
}
#[test]
fn int64_mod_floordiv_preserves_dtype() {
// Test that int % int and int // int stay Int64 (pandas parity)
let left = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
])
.expect("left");
let right = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(7), Scalar::Int64(4)])
.expect("right");
let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
assert_eq!(modulo.dtype(), DType::Int64, "mod should preserve Int64");
assert_eq!(modulo.values()[0], Scalar::Int64(1));
assert_eq!(modulo.values()[1], Scalar::Int64(6));
assert_eq!(modulo.values()[2], Scalar::Int64(2));
let floordiv = left
.binary_numeric(&right, ArithmeticOp::FloorDiv)
.expect("floordiv");
assert_eq!(
floordiv.dtype(),
DType::Int64,
"floordiv should preserve Int64"
);
assert_eq!(floordiv.values()[0], Scalar::Int64(3));
assert_eq!(floordiv.values()[1], Scalar::Int64(2));
assert_eq!(floordiv.values()[2], Scalar::Int64(7));
}
#[test]
fn int64_mod_floordiv_match_pandas_negative_operand_signs() {
let left = Column::from_values(vec![
Scalar::Int64(7),
Scalar::Int64(-7),
Scalar::Int64(-7),
Scalar::Int64(7),
])
.expect("left");
let right = Column::from_values(vec![
Scalar::Int64(-3),
Scalar::Int64(3),
Scalar::Int64(-3),
Scalar::Int64(3),
])
.expect("right");
let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
assert_eq!(modulo.dtype(), DType::Int64);
assert_eq!(
modulo.values(),
&[
Scalar::Int64(-2),
Scalar::Int64(2),
Scalar::Int64(-1),
Scalar::Int64(1)
]
);
let floordiv = left
.binary_numeric(&right, ArithmeticOp::FloorDiv)
.expect("floordiv");
assert_eq!(floordiv.dtype(), DType::Int64);
assert_eq!(
floordiv.values(),
&[
Scalar::Int64(-3),
Scalar::Int64(-3),
Scalar::Int64(2),
Scalar::Int64(2)
]
);
}
#[test]
fn float64_mod_floordiv_match_pandas_negative_operand_signs() {
let left = Column::from_values(vec![
Scalar::Float64(7.0),
Scalar::Float64(-7.0),
Scalar::Float64(-7.0),
Scalar::Float64(7.0),
])
.expect("left");
let right = Column::from_values(vec![
Scalar::Float64(-3.0),
Scalar::Float64(3.0),
Scalar::Float64(-3.0),
Scalar::Float64(3.0),
])
.expect("right");
let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
assert_eq!(modulo.dtype(), DType::Float64);
assert!(matches!(modulo.values()[0], Scalar::Float64(v) if (v + 2.0).abs() < 1e-10));
assert!(matches!(modulo.values()[1], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
assert!(matches!(modulo.values()[2], Scalar::Float64(v) if (v + 1.0).abs() < 1e-10));
assert!(matches!(modulo.values()[3], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
let floordiv = left
.binary_numeric(&right, ArithmeticOp::FloorDiv)
.expect("floordiv");
assert_eq!(floordiv.dtype(), DType::Float64);
assert!(matches!(floordiv.values()[0], Scalar::Float64(v) if (v + 3.0).abs() < 1e-10));
assert!(matches!(floordiv.values()[1], Scalar::Float64(v) if (v + 3.0).abs() < 1e-10));
assert!(matches!(floordiv.values()[2], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
assert!(matches!(floordiv.values()[3], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
}
#[test]
fn int64_mod_floordiv_with_zero_promotes_to_float() {
// Test that int % 0 and int // 0 promote to Float64 (pandas parity)
let left = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
])
.expect("left");
let right = Column::from_values(vec![
Scalar::Int64(3),
Scalar::Int64(0), // Zero divisor
Scalar::Int64(4),
])
.expect("right");
let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
assert_eq!(
modulo.dtype(),
DType::Float64,
"mod with zero should promote to Float64"
);
assert!(matches!(modulo.values()[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
assert!(matches!(modulo.values()[1], Scalar::Float64(v) if v.is_nan()));
assert!(matches!(modulo.values()[2], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
let floordiv = left
.binary_numeric(&right, ArithmeticOp::FloorDiv)
.expect("floordiv");
assert_eq!(
floordiv.dtype(),
DType::Float64,
"floordiv with zero should promote to Float64"
);
assert!(matches!(floordiv.values()[0], Scalar::Float64(v) if (v - 3.0).abs() < 1e-10));
assert!(matches!(floordiv.values()[1], Scalar::Float64(v) if v.is_infinite()));
assert!(matches!(floordiv.values()[2], Scalar::Float64(v) if (v - 7.0).abs() < 1e-10));
}
#[test]
fn vectorized_empty_columns() {
let left = Column::from_values(vec![]).expect("left");
let right = Column::from_values(vec![]).expect("right");
let result = left
.binary_numeric(&right, ArithmeticOp::Add)
.expect("add empty");
assert!(result.is_empty());
}
#[test]
fn vectorized_large_column_matches_scalar_semantics() {
// Build large columns to exercise batch processing.
let n = 4096;
let left_values: Vec<Scalar> = (0..n).map(|i| Scalar::Float64(i as f64)).collect();
let right_values: Vec<Scalar> = (0..n).map(|i| Scalar::Float64((n - i) as f64)).collect();
let left = Column::from_values(left_values).expect("left");
let right = Column::from_values(right_values).expect("right");
let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
// Every position should sum to n.
for (i, v) in result.values().iter().enumerate() {
assert_eq!(*v, Scalar::Float64(n as f64), "position {i} should be {n}");
}
}
#[test]
fn vectorized_nan_vs_null_distinction_preserved() {
// Float64 column: NaN is a specific kind of missing.
let left =
Column::from_values(vec![Scalar::Float64(f64::NAN), Scalar::Null(NullKind::NaN)])
.expect("left");
let right =
Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("right");
let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
// Both positions should be NaN-missing (not generic Null).
assert!(result.values()[0].is_nan(), "NaN + valid = NaN");
assert!(result.values()[1].is_nan(), "NaN-null + valid = NaN");
}
#[test]
fn vectorized_mixed_type_falls_back_to_scalar() {
// Int64 + Float64 promotes to Float64 — vectorized path handles this.
let left = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("left");
let right =
Column::from_values(vec![Scalar::Float64(0.5), Scalar::Float64(1.5)]).expect("right");
let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
assert_eq!(result.dtype(), fp_types::DType::Float64);
assert_eq!(result.values()[0], Scalar::Float64(1.5));
assert_eq!(result.values()[1], Scalar::Float64(3.5));
}
#[test]
fn vectorized_i64_sub_and_mul() {
let left = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("left");
let right = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(5)]).expect("right");
let sub = left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub");
assert_eq!(sub.values()[0], Scalar::Int64(7));
assert_eq!(sub.values()[1], Scalar::Int64(15));
let mul = left.binary_numeric(&right, ArithmeticOp::Mul).expect("mul");
assert_eq!(mul.values()[0], Scalar::Int64(30));
assert_eq!(mul.values()[1], Scalar::Int64(100));
}
// === AG-14: Database Cracking Tests ===
mod crack_tests {
use fp_types::Scalar;
use super::super::*;
fn make_column(values: &[f64]) -> Column {
Column::from_values(values.iter().map(|&v| Scalar::Float64(v)).collect()).expect("col")
}
#[test]
fn crack_filter_gt_basic() {
let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
let mut crack = CrackIndex::new(col.len());
let gt3 = crack.filter_gt(&col, 3.0);
let mut gt3_vals: Vec<f64> = gt3
.iter()
.map(|&i| col.values()[i].to_f64().unwrap())
.collect();
gt3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(gt3_vals, vec![5.0, 7.0]);
assert_eq!(crack.num_cracks(), 1);
}
#[test]
fn crack_filter_lte_basic() {
let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
let mut crack = CrackIndex::new(col.len());
let lte3 = crack.filter_lte(&col, 3.0);
let mut lte3_vals: Vec<f64> = lte3
.iter()
.map(|&i| col.values()[i].to_f64().unwrap())
.collect();
lte3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(lte3_vals, vec![1.0, 2.0, 3.0]);
}
#[test]
fn crack_filter_eq() {
let col = make_column(&[1.0, 3.0, 3.0, 7.0, 3.0]);
let mut crack = CrackIndex::new(col.len());
let eq3 = crack.filter_eq(&col, 3.0);
assert_eq!(eq3.len(), 3, "three values equal to 3.0");
for &idx in &eq3 {
assert_eq!(col.values()[idx].to_f64().unwrap(), 3.0);
}
}
#[test]
fn crack_filter_lt() {
let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
let mut crack = CrackIndex::new(col.len());
let lt3 = crack.filter_lt(&col, 3.0);
let mut lt3_vals: Vec<f64> = lt3
.iter()
.map(|&i| col.values()[i].to_f64().unwrap())
.collect();
lt3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(lt3_vals, vec![1.0, 2.0]);
}
#[test]
fn crack_filter_gte() {
let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
let mut crack = CrackIndex::new(col.len());
let gte3 = crack.filter_gte(&col, 3.0);
let mut gte3_vals: Vec<f64> = gte3
.iter()
.map(|&i| col.values()[i].to_f64().unwrap())
.collect();
gte3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(gte3_vals, vec![3.0, 5.0, 7.0]);
}
#[test]
fn crack_progressive_refinement() {
let col = make_column(&[10.0, 2.0, 8.0, 4.0, 6.0, 1.0, 9.0, 3.0, 7.0, 5.0]);
let mut crack = CrackIndex::new(col.len());
// First crack at 5.0
let gt5 = crack.filter_gt(&col, 5.0);
assert_eq!(gt5.len(), 5);
assert_eq!(crack.num_cracks(), 1);
// Second crack at 3.0 — only re-partitions the [<=5.0] region
let gt3 = crack.filter_gt(&col, 3.0);
assert_eq!(gt3.len(), 7); // 4,5,6,7,8,9,10
assert_eq!(crack.num_cracks(), 2);
// Third crack at 7.0 — only re-partitions the [>5.0] region
let gt7 = crack.filter_gt(&col, 7.0);
assert_eq!(gt7.len(), 3); // 8,9,10
assert_eq!(crack.num_cracks(), 3);
}
#[test]
fn crack_duplicate_crack_point_is_idempotent() {
let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
let mut crack = CrackIndex::new(col.len());
let gt3_first = crack.filter_gt(&col, 3.0);
let gt3_second = crack.filter_gt(&col, 3.0);
// Same results both times
let mut a: Vec<usize> = gt3_first;
let mut b: Vec<usize> = gt3_second;
a.sort_unstable();
b.sort_unstable();
assert_eq!(a, b);
assert_eq!(crack.num_cracks(), 1, "no duplicate crack point");
}
#[test]
fn crack_empty_column() {
let col = make_column(&[]);
let mut crack = CrackIndex::new(col.len());
assert!(crack.filter_gt(&col, 5.0).is_empty());
assert!(crack.filter_lte(&col, 5.0).is_empty());
}
#[test]
fn crack_single_element() {
let col = make_column(&[42.0]);
let mut crack = CrackIndex::new(col.len());
assert!(crack.filter_gt(&col, 42.0).is_empty());
assert_eq!(crack.filter_lte(&col, 42.0).len(), 1);
assert_eq!(crack.filter_eq(&col, 42.0).len(), 1);
}
#[test]
fn crack_all_same_values() {
let col = make_column(&[5.0, 5.0, 5.0, 5.0]);
let mut crack = CrackIndex::new(col.len());
assert!(crack.filter_gt(&col, 5.0).is_empty());
assert_eq!(crack.filter_lte(&col, 5.0).len(), 4);
assert_eq!(crack.filter_eq(&col, 5.0).len(), 4);
}
#[test]
fn crack_isomorphism_with_full_scan() {
// Cracked filter must return identical results to naive full scan.
let col = make_column(&[10.0, 2.0, 8.0, 4.0, 6.0, 1.0, 9.0, 3.0, 7.0, 5.0]);
let mut crack = CrackIndex::new(col.len());
for pivot in [1.0, 3.0, 5.0, 7.0, 9.0, 0.0, 11.0] {
let mut cracked: Vec<usize> = crack.filter_gt(&col, pivot);
cracked.sort_unstable();
let mut naive: Vec<usize> = (0..col.len())
.filter(|&i| col.values()[i].to_f64().unwrap() > pivot)
.collect();
naive.sort_unstable();
assert_eq!(
cracked, naive,
"cracked vs naive mismatch for pivot={pivot}"
);
}
}
#[test]
fn crack_int64_column() {
let col = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(5),
Scalar::Int64(3),
Scalar::Int64(8),
Scalar::Int64(1),
])
.expect("col");
let mut crack = CrackIndex::new(col.len());
let gt5 = crack.filter_gt(&col, 5.0);
let mut gt5_vals: Vec<i64> = gt5
.iter()
.filter_map(|&i| match &col.values()[i] {
Scalar::Int64(v) => Some(*v),
_ => None,
})
.collect();
assert_eq!(gt5_vals.len(), gt5.len(), "expected Int64 values");
gt5_vals.sort_unstable();
assert_eq!(gt5_vals, vec![8, 10]);
}
#[test]
fn crack_large_column_correctness() {
let n = 1000;
let values: Vec<f64> = (0..n).map(|i| ((i * 7 + 13) % n) as f64).collect();
let col = make_column(&values);
let mut crack = CrackIndex::new(col.len());
// Multiple cracks at different points
for pivot in [100.0, 500.0, 250.0, 750.0, 50.0, 900.0] {
let mut cracked: Vec<usize> = crack.filter_gt(&col, pivot);
cracked.sort_unstable();
let mut naive: Vec<usize> =
(0..n as usize).filter(|&i| values[i] > pivot).collect();
naive.sort_unstable();
assert_eq!(cracked, naive, "large column mismatch for pivot={pivot}");
}
}
}
// === Comparison, Filter, and Missing-Data Operation Tests ===
mod comparison_tests {
use fp_types::{NullKind, Scalar};
use super::super::*;
#[test]
fn comparison_gt_int64() {
let left =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(3)])
.expect("left");
let right =
Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(3), Scalar::Int64(3)])
.expect("right");
let result = left
.binary_comparison(&right, ComparisonOp::Gt)
.expect("gt");
assert_eq!(result.dtype(), fp_types::DType::Bool);
assert_eq!(result.values()[0], Scalar::Bool(false));
assert_eq!(result.values()[1], Scalar::Bool(true));
assert_eq!(result.values()[2], Scalar::Bool(false));
}
#[test]
fn comparison_all_ops_numeric() {
let left = Column::from_values(vec![Scalar::Float64(5.0)]).expect("left");
let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
let gt = left
.binary_comparison(&right, ComparisonOp::Gt)
.expect("gt");
let lt = left
.binary_comparison(&right, ComparisonOp::Lt)
.expect("lt");
let eq = left
.binary_comparison(&right, ComparisonOp::Eq)
.expect("eq");
let ne = left
.binary_comparison(&right, ComparisonOp::Ne)
.expect("ne");
let ge = left
.binary_comparison(&right, ComparisonOp::Ge)
.expect("ge");
let le = left
.binary_comparison(&right, ComparisonOp::Le)
.expect("le");
assert_eq!(gt.values()[0], Scalar::Bool(true));
assert_eq!(lt.values()[0], Scalar::Bool(false));
assert_eq!(eq.values()[0], Scalar::Bool(false));
assert_eq!(ne.values()[0], Scalar::Bool(true));
assert_eq!(ge.values()[0], Scalar::Bool(true));
assert_eq!(le.values()[0], Scalar::Bool(false));
}
#[test]
fn pandas_comparison_aliases_match_binary_comparison() {
let left = Column::from_values(vec![Scalar::Float64(5.0)]).expect("left");
let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
assert_eq!(
left.eq(&right).expect("eq"),
left.binary_comparison(&right, ComparisonOp::Eq)
.expect("eq")
);
assert_eq!(
left.ne(&right).expect("ne"),
left.binary_comparison(&right, ComparisonOp::Ne)
.expect("ne")
);
assert_eq!(
left.lt(&right).expect("lt"),
left.binary_comparison(&right, ComparisonOp::Lt)
.expect("lt")
);
assert_eq!(
left.le(&right).expect("le"),
left.binary_comparison(&right, ComparisonOp::Le)
.expect("le")
);
assert_eq!(
left.gt(&right).expect("gt"),
left.binary_comparison(&right, ComparisonOp::Gt)
.expect("gt")
);
assert_eq!(
left.ge(&right).expect("ge"),
left.binary_comparison(&right, ComparisonOp::Ge)
.expect("ge")
);
}
#[test]
fn comparison_equality_equal_values() {
let col = Column::from_values(vec![Scalar::Int64(42)]).expect("col");
let result = col.binary_comparison(&col, ComparisonOp::Eq).expect("eq");
assert_eq!(result.values()[0], Scalar::Bool(true));
let ne = col.binary_comparison(&col, ComparisonOp::Ne).expect("ne");
assert_eq!(ne.values()[0], Scalar::Bool(false));
}
#[test]
fn comparison_null_propagation() {
let left = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
])
.expect("left");
let right = Column::from_values(vec![
Scalar::Int64(2),
Scalar::Int64(2),
Scalar::Null(NullKind::Null),
])
.expect("right");
let result = left
.binary_comparison(&right, ComparisonOp::Gt)
.expect("gt");
assert_eq!(result.values()[0], Scalar::Bool(false));
assert!(result.values()[1].is_missing(), "null op valid = null");
assert!(result.values()[2].is_missing(), "valid op null = null");
}
#[test]
fn comparison_utf8_lexicographic() {
let left = Column::from_values(vec![
Scalar::Utf8("banana".to_string()),
Scalar::Utf8("apple".to_string()),
])
.expect("left");
let right = Column::from_values(vec![
Scalar::Utf8("apple".to_string()),
Scalar::Utf8("cherry".to_string()),
])
.expect("right");
let gt = left
.binary_comparison(&right, ComparisonOp::Gt)
.expect("gt");
assert_eq!(gt.values()[0], Scalar::Bool(true));
assert_eq!(gt.values()[1], Scalar::Bool(false));
}
#[test]
fn compare_scalar_gt() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(5),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
])
.expect("col");
let result = col
.compare_scalar(&Scalar::Int64(3), ComparisonOp::Gt)
.expect("gt");
assert_eq!(result.values()[0], Scalar::Bool(false));
assert_eq!(result.values()[1], Scalar::Bool(true));
assert!(result.values()[2].is_missing());
assert_eq!(result.values()[3], Scalar::Bool(false));
}
#[test]
fn compare_scalar_with_missing_scalar() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let result = col
.compare_scalar(&Scalar::Null(NullKind::Null), ComparisonOp::Eq)
.expect("eq");
assert!(result.values()[0].is_missing());
assert!(result.values()[1].is_missing());
}
#[test]
fn filter_by_mask_basic() {
let col = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
Scalar::Int64(40),
])
.expect("col");
let mask = Column::from_values(vec![
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(false),
])
.expect("mask");
let result = col.filter_by_mask(&mask).expect("filter");
assert_eq!(result.len(), 2);
assert_eq!(result.values()[0], Scalar::Int64(10));
assert_eq!(result.values()[1], Scalar::Int64(30));
}
#[test]
fn filter_by_mask_float64_typed_path_matches_scalar() {
// The Float64 typed gather (as_f64_slice + from_f64_values) must be
// bit-identical to the Scalar clone path: same selected values, same
// order, all-valid result.
let col = Column::from_f64_values(vec![1.5, -0.0, 2.5, f64::INFINITY, 0.0]);
let mask = Column::from_values(vec![
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Null(NullKind::Null), // missing -> not selected
])
.expect("mask");
let result = col.filter_by_mask(&mask).expect("filter");
assert_eq!(result.dtype(), DType::Float64);
assert_eq!(
result.values(),
&[
Scalar::Float64(1.5),
Scalar::Float64(-0.0),
Scalar::Float64(f64::INFINITY),
]
);
}
#[test]
fn filter_by_mask_nullable_typed_gather_matches_reference_cf() {
// Variant-gated nullable typed gather must equal the Scalar-clone
// reference: a selected present slot keeps its datum; a selected
// missing slot stays missing; a NaN in a LazyAllValidFloat64 source
// folds to missing. mask-true positions: 0, 2, 3, 5, 6.
let mask =
Column::from_bool_values(vec![true, false, true, true, false, true, true]);
// (a) LazyNullableInt64 (missing ⇒ Null(Null)).
let mut ival = ValidityMask::all_valid(7);
ival.set(2, false);
ival.set(5, false);
let icol = Column::from_i64_values_with_validity(vec![10, 20, 0, -5, 7, 0, 3], ival);
let ir = icol.filter_by_mask(&mask).expect("i64 filter");
assert_eq!(ir.dtype(), DType::Int64);
assert_eq!(
ir.values(),
&[
Scalar::Int64(10),
Scalar::Null(NullKind::Null),
Scalar::Int64(-5),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
]
);
// (b) LazyNullableFloat64.
let mut fval = ValidityMask::all_valid(7);
fval.set(2, false);
fval.set(5, false);
let fcol =
Column::from_f64_values_with_validity(vec![1.5, 2.0, 0.0, -3.5, 7.0, 0.0, 9.25], fval);
let fr = fcol.filter_by_mask(&mask).expect("f64 filter");
assert_eq!(fr.dtype(), DType::Float64);
let fv = fr.values();
assert_eq!(fv.len(), 5);
match &fv[0] {
Scalar::Float64(x) => assert_eq!(*x, 1.5),
o => panic!("fv0={o:?}"),
}
assert!(matches!(fv[1], Scalar::Null(_)), "pos2 missing");
match &fv[2] {
Scalar::Float64(x) => assert_eq!(*x, -3.5),
o => panic!("fv2={o:?}"),
}
assert!(matches!(fv[3], Scalar::Null(_)), "pos5 missing");
match &fv[4] {
Scalar::Float64(x) => assert_eq!(*x, 9.25),
o => panic!("fv4={o:?}"),
}
// (c) NaN-bearing LazyAllValidFloat64 (from_f64_values). A source NaN is
// validity-cleared (missing) but its datum stays a PRESENT Float64(NaN)
// in values() — the three-way rep — so the filtered slot must too (the
// Scalar-clone path clones Float64(NaN) and Self::new re-marks it missing).
let ncol =
Column::from_f64_values(vec![1.0, 2.0, f64::NAN, 4.0, 5.0, f64::NAN, 7.0]);
let nr = ncol.filter_by_mask(&mask).expect("nan filter");
let nv = nr.values();
match &nv[0] {
Scalar::Float64(x) => assert_eq!(*x, 1.0),
o => panic!("nv0={o:?}"),
}
match &nv[1] {
Scalar::Float64(x) => assert!(x.is_nan(), "pos2 stays present-NaN"),
o => panic!("nv1={o:?}"),
}
match &nv[2] {
Scalar::Float64(x) => assert_eq!(*x, 4.0),
o => panic!("nv2={o:?}"),
}
match &nv[3] {
Scalar::Float64(x) => assert!(x.is_nan(), "pos5 stays present-NaN"),
o => panic!("nv3={o:?}"),
}
match &nv[4] {
Scalar::Float64(x) => assert_eq!(*x, 7.0),
o => panic!("nv4={o:?}"),
}
}
#[test]
fn filter_by_mask_nullable_i64_typed_matches_generic() {
// The typed nullable-Int64 filter_by_mask arm (compact raw i64 + validity at
// mask-true positions) must be BIT-EXACT to the generic Scalar-clone gather. A/B:
// col_typed (from_i64_values_with_validity => LazyNullableInt64) hits the typed
// arm; col_eager (Column::new, Eager) hits the generic path. ~30% nulls; the mask
// is a seeded bool with ~15% missing (missing mask slot ⇒ not selected).
let mut state: u64 = 0x1717_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let n = (next() % 300) as usize;
let mut data = vec![0i64; n];
let mut validity = crate::ValidityMask::all_valid(n);
let mut eager: Vec<Scalar> = Vec::with_capacity(n);
let mut mask_scalars: Vec<Scalar> = Vec::with_capacity(n);
for i in 0..n {
if next() % 3 == 0 {
validity.set(i, false);
eager.push(Scalar::Null(NullKind::Null));
} else {
let v = (next() % 20_000) as i64 - 10_000;
data[i] = v;
eager.push(Scalar::Int64(v));
}
// ~15% missing mask, else a seeded bool.
if next() % 7 == 0 {
mask_scalars.push(Scalar::Null(NullKind::NaN));
} else {
mask_scalars.push(Scalar::Bool(next() % 2 == 0));
}
}
let col_typed = Column::from_i64_values_with_validity(data, validity);
let col_eager = Column::new(DType::Int64, eager).expect("eager i64");
let mask = Column::new(DType::Bool, mask_scalars).expect("mask");
let a = col_typed.filter_by_mask(&mask).expect("typed filter");
let b = col_eager.filter_by_mask(&mask).expect("eager filter");
assert_eq!(a.values(), b.values(), "filter trial {trial}");
}
}
#[test]
fn filter_by_mask_nullable_temporal_bool_matches_reference_cf() {
// Datetime64/Timedelta64/Bool nullable filter arms. mask-true: 0,2,3,5.
let mask = Column::from_bool_values(vec![true, false, true, true, false, true]);
let mut v = ValidityMask::all_valid(6);
v.set(2, false);
v.set(5, false);
let dt = Column::from_datetime64_values_with_validity(
vec![100, 200, 0, 400, 500, 0],
v.clone(),
);
let dtr = dt.filter_by_mask(&mask).expect("dt filter");
assert_eq!(dtr.dtype(), DType::Datetime64);
assert_eq!(
dtr.values(),
&[
Scalar::Datetime64(100),
Scalar::Null(NullKind::NaT),
Scalar::Datetime64(400),
Scalar::Null(NullKind::NaT),
]
);
let td = Column::from_timedelta64_values_with_validity(
vec![10, 20, 0, 40, 50, 0],
v.clone(),
);
let tdr = td.filter_by_mask(&mask).expect("td filter");
assert_eq!(tdr.dtype(), DType::Timedelta64);
assert_eq!(
tdr.values(),
&[
Scalar::Timedelta64(10),
Scalar::Null(NullKind::NaT),
Scalar::Timedelta64(40),
Scalar::Null(NullKind::NaT),
]
);
let b = Column::from_bool_values_with_validity(
vec![true, false, false, true, true, false],
v.clone(),
);
let br = b.filter_by_mask(&mask).expect("bool filter");
assert_eq!(br.dtype(), DType::Bool);
assert_eq!(
br.values(),
&[
Scalar::Bool(true),
Scalar::Null(NullKind::Null),
Scalar::Bool(true),
Scalar::Null(NullKind::Null),
]
);
}
#[test]
fn compare_scalar_typed_path_matches_scalar_compare() {
// Isomorphism proof for br-frankenpandas-2kpwa: the typed f64/i64
// compare_scalar fast paths must be bit-identical to the per-element
// scalar_compare reference for every op and operand combination.
let f64_vals = vec![1.5f64, -0.0, 0.0, 2.5, -3.0, f64::INFINITY, 100.0];
let i64_vals = vec![1i64, -2, 0, 5, 100, -7];
let ops = [
ComparisonOp::Gt,
ComparisonOp::Lt,
ComparisonOp::Eq,
ComparisonOp::Ne,
ComparisonOp::Ge,
ComparisonOp::Le,
];
for op in ops {
// Float64 column vs Float64 scalar.
for &probe in &[0.0f64, 1.5, 2.5, -3.0, f64::INFINITY] {
let got = Column::from_f64_values(f64_vals.clone())
.compare_scalar(&Scalar::Float64(probe), op)
.expect("f64 cmp");
let expected: Vec<Scalar> = f64_vals
.iter()
.map(|&v| {
Scalar::Bool(
scalar_compare(&Scalar::Float64(v), &Scalar::Float64(probe), op)
.unwrap(),
)
})
.collect();
assert_eq!(
got.values(),
expected.as_slice(),
"f64 op {op:?} probe {probe}"
);
}
// Float64 column vs Int64 scalar (f64-promotion branch).
let got = Column::from_f64_values(f64_vals.clone())
.compare_scalar(&Scalar::Int64(2), op)
.expect("f64-vs-i64 cmp");
let expected: Vec<Scalar> = f64_vals
.iter()
.map(|&v| {
Scalar::Bool(
scalar_compare(&Scalar::Float64(v), &Scalar::Int64(2), op).unwrap(),
)
})
.collect();
assert_eq!(got.values(), expected.as_slice(), "f64-vs-i64 op {op:?}");
// Int64 column vs Int64 scalar (both-Int64 branch).
let got = Column::from_i64_values_owned(i64_vals.clone())
.compare_scalar(&Scalar::Int64(0), op)
.expect("i64 cmp");
let expected: Vec<Scalar> = i64_vals
.iter()
.map(|&v| {
Scalar::Bool(
scalar_compare(&Scalar::Int64(v), &Scalar::Int64(0), op).unwrap(),
)
})
.collect();
assert_eq!(got.values(), expected.as_slice(), "i64 op {op:?}");
}
}
#[test]
fn compare_scalar_nullable_i64_matches_exact_scalar_reference_k5xf3() {
let values = vec![
Scalar::Int64(i64::MIN),
Scalar::Int64(-1),
Scalar::Null(NullKind::Null),
Scalar::Int64(0),
Scalar::Int64(9_007_199_254_740_992),
Scalar::Int64(9_007_199_254_740_993),
Scalar::Int64(i64::MAX),
];
let column = Column::new(DType::Int64, values.clone()).expect("nullable Int64");
assert!(
column.as_i64_slice_with_validity().is_some(),
"fixture must exercise the typed nullable backing"
);
let probe = Scalar::Int64(9_007_199_254_740_992);
for op in [
ComparisonOp::Gt,
ComparisonOp::Lt,
ComparisonOp::Eq,
ComparisonOp::Ne,
ComparisonOp::Ge,
ComparisonOp::Le,
] {
let got = column
.compare_scalar(&probe, op)
.expect("nullable Int64 scalar comparison");
let expected: Vec<Scalar> = values
.iter()
.map(|value| {
if value.is_missing() {
Scalar::Null(NullKind::Null)
} else {
Scalar::Bool(scalar_compare(value, &probe, op).expect("reference"))
}
})
.collect();
assert_eq!(got.values(), expected, "nullable Int64 op {op:?}");
}
}
#[test]
fn compare_scalar_utf8_contiguous_matches_scalar_reference() {
// The typed Utf8 arm in compare_scalar (all-valid contiguous-Utf8 vs a Utf8
// scalar, comparing raw &[u8] spans) must be BIT-EXACT to the generic
// scalar_compare path for every op. Uses seeded short strings over a tiny
// alphabet so prefixes / ties / varied lengths ("a" vs "ab", "" empty) all
// occur, and probes needles before-all / after-all / equal-to-a-row / prefix.
let mut state: u64 = 0x5712_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 200) as usize;
let strings: Vec<String> = (0..n)
.map(|_| {
let len = (next() % 6) as usize; // 0..5 chars incl empty
(0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char) // {a,b,c,d}
.collect()
})
.collect();
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for s in &strings {
bytes.extend_from_slice(s.as_bytes());
offsets.push(bytes.len());
}
let column = Column::from_utf8_contiguous(bytes, offsets);
assert!(
column.as_utf8_contiguous().is_some(),
"fixture must exercise the typed contiguous-Utf8 backing"
);
let needles = [
String::new(), // empty ⇒ before-all non-empty
"a".to_string(), // prefix / short
"abc".to_string(), // mid
"cc".to_string(), // mid
"dddddd".to_string(), // after-all (len 6 > max 5)
strings.first().cloned().unwrap_or_default(), // equal-to-a-row
];
for needle_str in &needles {
let needle = Scalar::Utf8(needle_str.clone());
for op in [
ComparisonOp::Gt,
ComparisonOp::Lt,
ComparisonOp::Eq,
ComparisonOp::Ne,
ComparisonOp::Ge,
ComparisonOp::Le,
] {
let got = column.compare_scalar(&needle, op).expect("utf8 compare");
let expected: Vec<Scalar> = strings
.iter()
.map(|s| {
Scalar::Bool(
scalar_compare(
&Scalar::Utf8(s.clone()),
&needle,
op,
)
.expect("reference"),
)
})
.collect();
assert_eq!(
got.values(),
expected,
"trial {trial} needle {needle_str:?} op {op:?}"
);
}
}
}
}
#[test]
fn compare_scalar_nullable_utf8_matches_scalar_reference() {
// The nullable Utf8 arm in compare_scalar (LazyNullableUtf8 vs a Utf8 scalar)
// must be BIT-EXACT to the generic path: present ⇒ Bool(row <op> needle),
// missing ⇒ Null(Null). Seeded short strings over {a,b,c,d} with ~25% nulls
// (empty spans); probes before-all / after-all / equal-to-a-row / prefix.
let mut state: u64 = 0x00F5_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 200) as usize;
let mut validity = crate::ValidityMask::all_valid(n);
let mut opt_strings: Vec<Option<String>> = Vec::with_capacity(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..n {
if next() % 4 == 0 {
validity.set(i, false); // missing ⇒ empty span
opt_strings.push(None);
} else {
let len = (next() % 6) as usize;
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
opt_strings.push(Some(s));
}
offsets.push(bytes.len());
}
let column = Column::from_utf8_values_with_validity(bytes, offsets, validity);
// A column with ≥1 null must NOT expose an all-valid contiguous backing,
// proving the nullable arm (not the all-valid arm) is exercised.
if opt_strings.iter().any(|s| s.is_none()) {
assert!(
column.as_utf8_contiguous().is_none(),
"nullable fixture must decline the all-valid accessor"
);
}
let needles = [
String::new(),
"a".to_string(),
"abc".to_string(),
"cc".to_string(),
"dddddd".to_string(),
opt_strings
.iter()
.find_map(|s| s.clone())
.unwrap_or_default(),
];
for needle_str in &needles {
let needle = Scalar::Utf8(needle_str.clone());
for op in [
ComparisonOp::Gt,
ComparisonOp::Lt,
ComparisonOp::Eq,
ComparisonOp::Ne,
ComparisonOp::Ge,
ComparisonOp::Le,
] {
let got = column.compare_scalar(&needle, op).expect("utf8 compare");
let expected: Vec<Scalar> = opt_strings
.iter()
.map(|os| match os {
None => Scalar::Null(NullKind::Null),
Some(s) => Scalar::Bool(
scalar_compare(&Scalar::Utf8(s.clone()), &needle, op)
.expect("reference"),
),
})
.collect();
assert_eq!(
got.values(),
expected,
"trial {trial} needle {needle_str:?} op {op:?}"
);
}
}
}
}
#[test]
fn binary_comparison_utf8_col_vs_col_matches_scalar_reference() {
// The typed Utf8 arm in binary_comparison (two contiguous-Utf8 columns, any mix
// of all-valid / nullable) must be BIT-EXACT to the generic path: both present
// ⇒ Bool(lrow <op> rrow), either missing ⇒ Null(Null). Covers the 4 combos
// (all-valid, nullable)² with seeded short strings over {a,b,c,d}, ~25% nulls.
let mut state: u64 = 0xC01C_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
// Build a contiguous-Utf8 column of `n` rows; `nullable` ⇒ ~25% missing.
let mut build =
|n: usize, nullable: bool, next: &mut dyn FnMut() -> u64| -> (Column, Vec<Option<String>>) {
let mut validity = crate::ValidityMask::all_valid(n);
let mut opt: Vec<Option<String>> = Vec::with_capacity(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..n {
if nullable && next() % 4 == 0 {
validity.set(i, false);
opt.push(None);
} else {
let len = (next() % 6) as usize;
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
opt.push(Some(s));
}
offsets.push(bytes.len());
}
(
Column::from_utf8_values_with_validity(bytes, offsets, validity),
opt,
)
};
for trial in 0..150 {
let n = (next() % 200) as usize;
for (ln, rn) in [(false, false), (true, false), (false, true), (true, true)] {
let (lcol, lopt) = build(n, ln, &mut next);
let (rcol, ropt) = build(n, rn, &mut next);
for op in [
ComparisonOp::Gt,
ComparisonOp::Lt,
ComparisonOp::Eq,
ComparisonOp::Ne,
ComparisonOp::Ge,
ComparisonOp::Le,
] {
let got = lcol.binary_comparison(&rcol, op).expect("utf8 col compare");
let expected: Vec<Scalar> = lopt
.iter()
.zip(&ropt)
.map(|(l, r)| match (l, r) {
(Some(a), Some(b)) => Scalar::Bool(
scalar_compare(
&Scalar::Utf8(a.clone()),
&Scalar::Utf8(b.clone()),
op,
)
.expect("reference"),
),
_ => Scalar::Null(NullKind::Null),
})
.collect();
assert_eq!(
got.values(),
expected,
"trial {trial} ln={ln} rn={rn} op {op:?}"
);
}
}
}
}
#[test]
fn binary_comparison_temporal_col_vs_col_exact_i64_ns_masks_missing() {
// The typed temporal arm in binary_comparison (Datetime64-vs-Datetime64 or
// Timedelta64-vs-Timedelta64, all-valid OR nullable) makes an op that the
// generic path ERRORS on (scalar_compare -> to_f64 rejects a non-NaT
// temporal scalar) both WORK and be EXACT: present pair ⇒ Bool(a <op> b) on
// the raw i64 nanoseconds (NOT f64-promoted — the values live near 1.6e18 >>
// 2^53, where f64 would round), either missing ⇒ Null. "Missing" is validity
// bit unset OR the NaT sentinel embedded in the buffer (an all-valid-validity
// column can still hold NaT), matching the generic `l.is_missing() ||
// r.is_missing()`. Covers the 4 (all-valid, nullable)² combos for both dtypes.
let mut state: u64 = 0x7E11_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
// Build a temporal column of `n` rows around `base` ns. `nullable` ⇒ ~25% of
// rows carry a false validity bit; ~1/6 of the OTHERWISE-valid rows get a NaT
// sentinel in the buffer (validity still set) to exercise NaT masking in both
// the all-valid and nullable branches. Returns (column, data, validity_bits).
let build = |n: usize,
nullable: bool,
nat: i64,
is_dt: bool,
next: &mut dyn FnMut() -> u64|
-> (Column, Vec<i64>, Vec<bool>) {
let base: i64 = if is_dt { 1_600_000_000_000_000_000 } else { 0 };
let mut data = Vec::with_capacity(n);
let mut validity = crate::ValidityMask::all_valid(n);
let mut vbits = vec![true; n];
for i in 0..n {
if nullable && next() % 4 == 0 {
validity.set(i, false);
vbits[i] = false;
data.push(base + (next() % 1000) as i64);
} else if next() % 6 == 0 {
data.push(nat);
} else {
// Small alphabet of magnitudes ⇒ frequent ties across columns.
data.push(base + (next() % 8) as i64);
}
}
let col = if is_dt {
Column::from_datetime64_values_with_validity(data.clone(), validity)
} else {
Column::from_timedelta64_values_with_validity(data.clone(), validity)
};
(col, data, vbits)
};
for (is_dt, nat) in [
(true, fp_types::Timestamp::NAT),
(false, fp_types::Timedelta::NAT),
] {
for trial in 0..120 {
let n = (next() % 200) as usize;
for (ln, rn) in [(false, false), (true, false), (false, true), (true, true)] {
let (lcol, ld, lv) = build(n, ln, nat, is_dt, &mut next);
let (rcol, rd, rv) = build(n, rn, nat, is_dt, &mut next);
for op in [
ComparisonOp::Gt,
ComparisonOp::Lt,
ComparisonOp::Eq,
ComparisonOp::Ne,
ComparisonOp::Ge,
ComparisonOp::Le,
] {
let got = lcol
.binary_comparison(&rcol, op)
.expect("temporal col compare must not error");
let expected: Vec<Scalar> = (0..n)
.map(|i| {
let l_missing = !lv[i] || ld[i] == nat;
let r_missing = !rv[i] || rd[i] == nat;
if l_missing || r_missing {
Scalar::Null(NullKind::Null)
} else {
let (a, b) = (ld[i], rd[i]);
Scalar::Bool(match op {
ComparisonOp::Gt => a > b,
ComparisonOp::Lt => a < b,
ComparisonOp::Eq => a == b,
ComparisonOp::Ne => a != b,
ComparisonOp::Ge => a >= b,
ComparisonOp::Le => a <= b,
})
}
})
.collect();
assert_eq!(
got.values(),
expected,
"is_dt={is_dt} trial {trial} ln={ln} rn={rn} op {op:?}"
);
}
}
}
}
}
#[test]
fn binary_comparison_nullable_bool_col_vs_col_matches_scalar_reference() {
// The typed nullable-Bool arm in binary_comparison (any pair with a nullable
// Bool operand — the all-valid arm needs BOTH as_bool_slice) must be BIT-EXACT
// to the generic path: both present ⇒ Bool(a <op> b), either missing ⇒ Null.
// Covers the 4 (all-valid, nullable)² combos; ~30% nulls; all 6 ops.
let mut state: u64 = 0xB001_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let build = |n: usize,
nullable: bool,
next: &mut dyn FnMut() -> u64|
-> (Column, Vec<Option<bool>>) {
let mut validity = crate::ValidityMask::all_valid(n);
let mut opt: Vec<Option<bool>> = Vec::with_capacity(n);
let mut data: Vec<bool> = Vec::with_capacity(n);
for i in 0..n {
if nullable && next() % 3 == 0 {
validity.set(i, false);
opt.push(None);
data.push(false);
} else {
let b = next() % 2 == 0;
opt.push(Some(b));
data.push(b);
}
}
(Column::from_bool_values_with_validity(data, validity), opt)
};
for trial in 0..200 {
let n = (next() % 300) as usize;
for (ln, rn) in [(false, false), (true, false), (false, true), (true, true)] {
let (lcol, lopt) = build(n, ln, &mut next);
let (rcol, ropt) = build(n, rn, &mut next);
for op in [
ComparisonOp::Gt,
ComparisonOp::Lt,
ComparisonOp::Eq,
ComparisonOp::Ne,
ComparisonOp::Ge,
ComparisonOp::Le,
] {
let got = lcol.binary_comparison(&rcol, op).expect("bool col compare");
let expected: Vec<Scalar> = lopt
.iter()
.zip(&ropt)
.map(|(l, r)| match (l, r) {
(Some(a), Some(b)) => Scalar::Bool(
scalar_compare(&Scalar::Bool(*a), &Scalar::Bool(*b), op)
.expect("reference"),
),
_ => Scalar::Null(NullKind::Null),
})
.collect();
assert_eq!(
got.values(),
expected,
"trial {trial} ln={ln} rn={rn} op {op:?}"
);
}
}
}
}
#[test]
fn compare_scalar_temporal_exact_i64_ns_masks_missing() {
// The typed temporal arm in compare_scalar (Datetime64/Timedelta64 column vs a
// non-NaT temporal scalar) makes `df["date"] > threshold` — which the generic
// path ERRORS on (scalar_compare -> to_f64 rejects a temporal scalar) — both
// WORK and be EXACT: present row ⇒ Bool(v <op> needle) on raw i64 ns (values
// near 1.6e18 >> 2^53, where f64 rounds), a missing row (validity unset OR NaT
// sentinel) ⇒ Null, matching the generic `v.is_missing()`. Both dtypes, both
// all-valid (with embedded NaT) and nullable columns, several needles, all ops.
let mut state: u64 = 0x5CA1_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let build = |n: usize,
nullable: bool,
nat: i64,
is_dt: bool,
next: &mut dyn FnMut() -> u64|
-> (Column, Vec<i64>, Vec<bool>) {
let base: i64 = if is_dt { 1_600_000_000_000_000_000 } else { 0 };
let mut data = Vec::with_capacity(n);
let mut validity = crate::ValidityMask::all_valid(n);
let mut vbits = vec![true; n];
for i in 0..n {
if nullable && next() % 4 == 0 {
validity.set(i, false);
vbits[i] = false;
data.push(base + (next() % 1000) as i64);
} else if next() % 6 == 0 {
data.push(nat);
} else {
data.push(base + (next() % 8) as i64);
}
}
let col = if is_dt {
Column::from_datetime64_values_with_validity(data.clone(), validity)
} else {
Column::from_timedelta64_values_with_validity(data.clone(), validity)
};
(col, data, vbits)
};
for (is_dt, nat) in [
(true, fp_types::Timestamp::NAT),
(false, fp_types::Timedelta::NAT),
] {
let base: i64 = if is_dt { 1_600_000_000_000_000_000 } else { 0 };
for trial in 0..120 {
let n = (next() % 200) as usize;
for nullable in [false, true] {
let (col, data, vbits) = build(n, nullable, nat, is_dt, &mut next);
for needle in [base, base + 3, base + 7] {
let scalar = if is_dt {
Scalar::Datetime64(needle)
} else {
Scalar::Timedelta64(needle)
};
for op in [
ComparisonOp::Gt,
ComparisonOp::Lt,
ComparisonOp::Eq,
ComparisonOp::Ne,
ComparisonOp::Ge,
ComparisonOp::Le,
] {
let got = col
.compare_scalar(&scalar, op)
.expect("temporal scalar compare must not error");
let expected: Vec<Scalar> = (0..n)
.map(|i| {
if !vbits[i] || data[i] == nat {
Scalar::Null(NullKind::Null)
} else {
let v = data[i];
Scalar::Bool(match op {
ComparisonOp::Gt => v > needle,
ComparisonOp::Lt => v < needle,
ComparisonOp::Eq => v == needle,
ComparisonOp::Ne => v != needle,
ComparisonOp::Ge => v >= needle,
ComparisonOp::Le => v <= needle,
})
}
})
.collect();
assert_eq!(
got.values(),
expected,
"is_dt={is_dt} trial {trial} nullable={nullable} needle={needle} op {op:?}"
);
}
}
}
}
}
}
#[test]
#[ignore = "perf timing harness, run with --ignored"]
fn compare_scalar_typed_vs_aos_timing() {
use std::time::Instant;
let n = 5_000_000usize;
let raw: Vec<f64> = (0..n).map(|i| (i % 1000) as f64 - 500.0).collect();
let scalars: Vec<Scalar> = raw.iter().map(|&v| Scalar::Float64(v)).collect();
let probe = Scalar::Float64(0.0);
let op = ComparisonOp::Gt;
// AoS reference: per-element scalar_compare + Scalar::Bool alloc.
let t = Instant::now();
let aos: Vec<Scalar> = scalars
.iter()
.map(|v| Scalar::Bool(scalar_compare(v, &probe, op).unwrap()))
.collect();
let aos_ns = t.elapsed().as_nanos();
std::hint::black_box(&aos);
// Typed path through compare_scalar (as_f64_slice -> from_bool_values).
let col = Column::from_f64_values(raw.clone());
let t = Instant::now();
let typed = col.compare_scalar(&probe, op).expect("typed cmp");
let typed_ns = t.elapsed().as_nanos();
std::hint::black_box(&typed);
assert_eq!(typed.values(), aos.as_slice(), "typed must match AoS");
let ratio = aos_ns as f64 / typed_ns as f64;
println!(
"compare_scalar Gt n={n}: AoS {aos_ns}ns typed {typed_ns}ns Score={ratio:.2}x"
);
}
#[test]
fn filter_by_mask_null_treated_as_false() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let mask = Column::from_values(vec![Scalar::Bool(true), Scalar::Null(NullKind::Null)])
.expect("mask");
let result = col.filter_by_mask(&mask).expect("filter");
assert_eq!(result.len(), 1);
assert_eq!(result.values()[0], Scalar::Int64(1));
}
#[test]
fn filter_by_mask_rejects_non_boolean_mask() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let mask = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(0)]).expect("mask");
let err = col.filter_by_mask(&mask).expect_err("non-bool mask");
assert!(matches!(err, ColumnError::InvalidMaskType { .. }));
}
#[test]
fn filter_by_mask_empty_result() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let mask =
Column::from_values(vec![Scalar::Bool(false), Scalar::Bool(false)]).expect("mask");
let result = col.filter_by_mask(&mask).expect("filter");
assert!(result.is_empty());
}
#[test]
fn filter_by_mask_matches_scalar_oracle_7mlq1() {
// Differential vs scalar mask oracle (br-frankenpandas-7mlq1).
// Seeded LCG, no mocks.
fn next(seed: &mut u64) -> u64 {
*seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
*seed
}
fn mask_values(seed: &mut u64, len: usize) -> Vec<Scalar> {
let mut mask = Vec::with_capacity(len);
for _ in 0..len {
mask.push(match next(seed) % 5 {
0 => Scalar::Null(NullKind::Null),
1 | 2 => Scalar::Bool(false),
_ => Scalar::Bool(true),
});
}
mask
}
fn assert_filter(case: usize, family: &str, values: Vec<Scalar>, mask: Vec<Scalar>) {
let input = Column::from_values(values).expect("column");
let mask = Column::from_values(mask).expect("mask");
let expected = input
.values()
.iter()
.zip(mask.values().iter())
.filter_map(|(value, mask_value)| {
matches!(mask_value, Scalar::Bool(true)).then_some(value.clone())
})
.collect::<Vec<_>>();
let filtered = input.filter_by_mask(&mask).expect("filter_by_mask");
assert_eq!(
filtered.dtype(),
input.dtype(),
"case={case} family={family}: dtype changed"
);
assert_eq!(
filtered.len(),
expected.len(),
"case={case} family={family}: length mismatch"
);
for (pos, (actual, expected)) in filtered.values().iter().zip(&expected).enumerate()
{
assert!(
actual.semantic_eq(expected),
"case={case} family={family} pos={pos}: expected {expected:?}, got {actual:?}"
);
}
}
let mut seed = 0x7f11_7e12_5ca1_ab1e_u64;
for case in 0..180 {
let len = (next(&mut seed) % 79 + 1) as usize;
let mut floats = Vec::with_capacity(len);
floats.push(Scalar::Float64(case as f64 / 7.0));
for _ in 1..len {
let raw = (next(&mut seed) % 12_001) as i64 - 6_000;
floats.push(match next(&mut seed) % 8 {
0 => Scalar::Float64(f64::NAN),
1 => Scalar::Float64(f64::INFINITY),
2 => Scalar::Float64(f64::NEG_INFINITY),
3 => Scalar::Float64(-0.0),
_ => Scalar::Float64(raw as f64 / 31.0),
});
}
assert_filter(case, "float", floats, mask_values(&mut seed, len));
let mut ints = Vec::with_capacity(len);
ints.push(Scalar::Int64(case as i64));
for _ in 1..len {
let raw = (next(&mut seed) % 67) as i64 - 33;
ints.push(match next(&mut seed) % 6 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
_ => Scalar::Int64(raw),
});
}
assert_filter(case, "int", ints, mask_values(&mut seed, len));
let mut bools = Vec::with_capacity(len);
bools.push(Scalar::Bool(case & 1 == 0));
for _ in 1..len {
bools.push(match next(&mut seed) % 5 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
raw => Scalar::Bool(raw & 1 == 0),
});
}
assert_filter(case, "bool", bools, mask_values(&mut seed, len));
let mut utf8 = Vec::with_capacity(len);
utf8.push(Scalar::Utf8(format!("mask{}", case % 23)));
for pos in 1..len {
utf8.push(match next(&mut seed) % 7 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
raw => Scalar::Utf8(format!("mask{}_{}", raw, pos % 17)),
});
}
assert_filter(case, "utf8", utf8, mask_values(&mut seed, len));
let mut timedeltas = Vec::with_capacity(len);
timedeltas.push(Scalar::Timedelta64(case as i64 - 45));
for _ in 1..len {
let raw = (next(&mut seed) % 181) as i64 - 90;
timedeltas.push(match next(&mut seed) % 7 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Timedelta64(i64::MIN),
_ => Scalar::Timedelta64(raw),
});
}
assert_filter(case, "timedelta", timedeltas, mask_values(&mut seed, len));
}
}
#[test]
fn fillna_typed_nullable_matches_oracle() {
// Typed nullable i64/f64 fillna == an independent oracle (present → value,
// missing → fill) over random validity. Exercises the as_*_with_validity
// typed paths (built via from_*_values_with_validity, which a from_values
// twin would not reproduce).
let mut state: u64 = 0x2C7E_91A0_B3D5_46F8;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..200 {
let n = (next() % 200) as usize + 1;
let ivals: Vec<i64> = (0..n).map(|_| (next() % 1000) as i64 - 500).collect();
let fvals: Vec<f64> = ivals.iter().map(|&v| v as f64 + 0.25).collect();
let mut vmask = ValidityMask::all_valid(n);
let mut valid = vec![true; n];
for (i, vf) in valid.iter_mut().enumerate() {
if next() % 3 == 0 {
vmask.set(i, false);
*vf = false;
}
}
let icol = Column::from_i64_values_with_validity(ivals.clone(), vmask.clone());
let fcol = Column::from_f64_values_with_validity(fvals.clone(), vmask.clone());
let bvals: Vec<bool> = (0..n).map(|_| next() & 1 == 0).collect();
let bcol = Column::from_bool_values_with_validity(bvals.clone(), vmask.clone());
let ifill = 7_i64;
let ffill = 7.0_f64;
let bfill = next() & 1 == 0;
let igot = icol.fillna(&Scalar::Int64(ifill)).unwrap();
let fgot = fcol.fillna(&Scalar::Float64(ffill)).unwrap();
let bgot = bcol.fillna(&Scalar::Bool(bfill)).unwrap();
for i in 0..n {
let iexp = if valid[i] {
Scalar::Int64(ivals[i])
} else {
Scalar::Int64(ifill)
};
let fexp = if valid[i] {
Scalar::Float64(fvals[i])
} else {
Scalar::Float64(ffill)
};
assert_eq!(igot.values()[i], iexp, "i64 idx {i}");
assert_eq!(fgot.values()[i], fexp, "f64 idx {i}");
assert_eq!(
bgot.values()[i],
Scalar::Bool(if valid[i] { bvals[i] } else { bfill }),
"bool idx {i}"
);
}
assert_eq!(bgot.dtype(), DType::Bool);
assert_eq!(bgot.validity().count_valid(), n);
}
}
#[test]
fn fillna_replaces_missing() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
Scalar::Null(NullKind::Null),
])
.expect("col");
let result = col.fillna(&Scalar::Int64(0)).expect("fillna");
assert_eq!(result.values()[0], Scalar::Int64(1));
assert_eq!(result.values()[1], Scalar::Int64(0));
assert_eq!(result.values()[2], Scalar::Int64(3));
assert_eq!(result.values()[3], Scalar::Int64(0));
assert_eq!(result.validity().count_valid(), 4);
}
#[test]
fn fillna_nullable_utf8_typed_matches_generic() {
// The typed nullable-Utf8 fillna arm (LazyNullableUtf8 + Utf8 fill) must be
// BIT-EXACT to the generic clone-fill path. A/B on identical data: col_typed
// (LazyNullableUtf8) exercises the typed arm; col_eager (from_values, Eager)
// falls to the generic path. Seeded short strings over {a,b,c,d} + ~25% nulls;
// fill values incl. empty string; also a missing fill (keeps nulls, generic).
let mut state: u64 = 0xF117_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 250) as usize;
let mut validity = crate::ValidityMask::all_valid(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
let mut eager: Vec<Scalar> = Vec::with_capacity(n);
for i in 0..n {
if next() % 4 == 0 {
validity.set(i, false);
eager.push(Scalar::Null(NullKind::Null));
} else {
let len = (next() % 5) as usize;
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
eager.push(Scalar::Utf8(s));
}
offsets.push(bytes.len());
}
let col_typed = Column::from_utf8_values_with_validity(bytes, offsets, validity);
let col_eager = Column::new(DType::Utf8, eager).expect("eager utf8");
// Confirm the eager column is OFF the typed path (generic oracle).
if col_typed.as_nullable_utf8_contiguous().is_some() {
assert!(
col_eager.as_nullable_utf8_contiguous().is_none(),
"eager fixture must be on the generic fillna path"
);
}
for fill in [
Scalar::Utf8("Unknown".to_string()),
Scalar::Utf8(String::new()),
Scalar::Null(NullKind::Null), // keeps nulls; both paths generic
] {
let a = col_typed.fillna(&fill).expect("typed fillna");
let b = col_eager.fillna(&fill).expect("eager fillna");
assert_eq!(a.values(), b.values(), "trial {trial} fill {fill:?}");
}
}
}
#[test]
fn fillna_nullable_temporal_typed_matches_generic() {
// The typed nullable-temporal fillna arm (LazyNullableDatetime64/Timedelta64 +
// matching temporal fill) must be BIT-EXACT to the generic clone-fill path. A/B
// on identical data: col_typed (from_*_with_validity => LazyNullable) exercises
// the typed arm; col_eager (Column::new, Eager) falls to the generic path.
// ~25% validity-null + ~10% NaT-in-buffer (validity-true) => both are "missing"
// and get filled. NaT fill keeps nulls (both generic). Values near 1.6e18.
let mut state: u64 = 0xF117_DA7E_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for is_dt in [true, false] {
let base: i64 = if is_dt { 1_600_000_000_000_000_000 } else { 0 };
let nat = if is_dt {
fp_types::Timestamp::NAT
} else {
fp_types::Timedelta::NAT
};
for trial in 0..120 {
let n = (next() % 250) as usize;
let mut data = vec![0i64; n];
let mut validity = crate::ValidityMask::all_valid(n);
let mut eager: Vec<Scalar> = Vec::with_capacity(n);
for i in 0..n {
let r = next() % 10;
if r < 3 {
validity.set(i, false);
eager.push(Scalar::Null(NullKind::NaT));
} else if r == 3 {
data[i] = nat; // NaT in buffer with validity TRUE
eager.push(if is_dt {
Scalar::Datetime64(nat)
} else {
Scalar::Timedelta64(nat)
});
} else {
data[i] = base + (next() % 1_000_000) as i64;
eager.push(if is_dt {
Scalar::Datetime64(data[i])
} else {
Scalar::Timedelta64(data[i])
});
}
}
let dtype = if is_dt { DType::Datetime64 } else { DType::Timedelta64 };
let col_typed = if is_dt {
Column::from_datetime64_values_with_validity(data.clone(), validity)
} else {
Column::from_timedelta64_values_with_validity(data.clone(), validity)
};
let col_eager = Column::new(dtype, eager).expect("eager temporal");
let fills = if is_dt {
[Scalar::Datetime64(base + 42), Scalar::Datetime64(nat)]
} else {
[Scalar::Timedelta64(42), Scalar::Timedelta64(nat)]
};
for fill in fills {
let a = col_typed.fillna(&fill).expect("typed fillna");
let b = col_eager.fillna(&fill).expect("eager fillna");
assert_eq!(
a.values(),
b.values(),
"is_dt={is_dt} trial {trial} fill {fill:?}"
);
}
}
}
}
#[test]
fn fillna_matches_scalar_replacement_oracle_56isx() {
// Differential vs scalar replacement oracle (br-frankenpandas-56isx).
// Seeded LCG, no mocks.
fn next(seed: &mut u64) -> u64 {
*seed = seed
.wrapping_mul(3202034522624059733)
.wrapping_add(4354685564936845319);
*seed
}
fn assert_fillna(case: usize, family: &str, values: Vec<Scalar>, fill: Scalar) {
let input = Column::from_values(values).expect("column");
let expected = input
.values()
.iter()
.map(|value| {
if value.is_missing() {
fill.clone()
} else {
value.clone()
}
})
.collect::<Vec<_>>();
let filled = input.fillna(&fill).expect("fillna");
assert_eq!(
filled.dtype(),
input.dtype(),
"case={case} family={family}: dtype changed"
);
assert_eq!(
filled.len(),
input.len(),
"case={case} family={family}: length changed"
);
assert_eq!(
filled.values(),
expected.as_slice(),
"case={case} family={family}: replacement mismatch"
);
assert_eq!(
filled.validity().count_valid(),
filled.len(),
"case={case} family={family}: fillna left invalid positions"
);
}
let mut seed = 0xf111_ca5c_a1a5_56a1_u64;
for case in 0..180 {
let len = (next(&mut seed) % 73 + 1) as usize;
let mut floats = Vec::with_capacity(len);
floats.push(Scalar::Float64(case as f64 / 5.0));
for _ in 1..len {
let raw = (next(&mut seed) % 16_001) as i64 - 8_000;
floats.push(match next(&mut seed) % 7 {
0 | 1 => Scalar::Float64(f64::NAN),
2 => Scalar::Float64(f64::INFINITY),
3 => Scalar::Float64(f64::NEG_INFINITY),
_ => Scalar::Float64(raw as f64 / 37.0),
});
}
assert_fillna(case, "float", floats, Scalar::Float64(-123.5));
let mut ints = Vec::with_capacity(len);
ints.push(Scalar::Int64(case as i64 - 90));
for _ in 1..len {
let raw = (next(&mut seed) % 101) as i64 - 50;
ints.push(match next(&mut seed) % 6 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
_ => Scalar::Int64(raw),
});
}
assert_fillna(case, "int", ints, Scalar::Int64(-777));
let mut bools = Vec::with_capacity(len);
bools.push(Scalar::Bool(case & 1 == 0));
for _ in 1..len {
bools.push(match next(&mut seed) % 5 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
raw => Scalar::Bool(raw & 1 == 0),
});
}
assert_fillna(case, "bool", bools, Scalar::Bool(true));
let mut utf8 = Vec::with_capacity(len);
utf8.push(Scalar::Utf8(format!("fill{}", case % 19)));
for pos in 1..len {
utf8.push(match next(&mut seed) % 7 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
raw => Scalar::Utf8(format!("fill{}_{}", raw, pos % 13)),
});
}
assert_fillna(case, "utf8", utf8, Scalar::Utf8("filled".into()));
let mut timedeltas = Vec::with_capacity(len);
timedeltas.push(Scalar::Timedelta64(case as i64));
for _ in 1..len {
let raw = (next(&mut seed) % 149) as i64 - 74;
timedeltas.push(match next(&mut seed) % 7 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Timedelta64(i64::MIN),
_ => Scalar::Timedelta64(raw),
});
}
assert_fillna(case, "timedelta", timedeltas, Scalar::Timedelta64(123_456));
}
}
#[test]
fn dropna_typed_matches_oracle() {
// Typed nullable i64/f64/bool dropna == an independent order-preserving
// filter. Built via from_*_values_with_validity to drive the typed path.
let mut state: u64 = 0x6BD3_27F1_0A95_CC48;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..200 {
let n = (next() % 200) as usize + 1;
let ivals: Vec<i64> = (0..n).map(|_| (next() % 1000) as i64).collect();
let fvals: Vec<f64> = ivals.iter().map(|&v| v as f64 + 0.5).collect();
let bvals: Vec<bool> = ivals.iter().map(|&v| v & 1 == 0).collect();
let mut vmask = ValidityMask::all_valid(n);
let mut present = vec![true; n];
for (i, p) in present.iter_mut().enumerate() {
if next() % 3 == 0 {
vmask.set(i, false);
*p = false;
}
}
let icol = Column::from_i64_values_with_validity(ivals.clone(), vmask.clone());
let fcol = Column::from_f64_values_with_validity(fvals.clone(), vmask.clone());
let bcol = Column::from_bool_values_with_validity(bvals.clone(), vmask.clone());
let iexp: Vec<Scalar> = (0..n)
.filter(|&i| present[i])
.map(|i| Scalar::Int64(ivals[i]))
.collect();
let fexp: Vec<Scalar> = (0..n)
.filter(|&i| present[i])
.map(|i| Scalar::Float64(fvals[i]))
.collect();
let bexp: Vec<Scalar> = (0..n)
.filter(|&i| present[i])
.map(|i| Scalar::Bool(bvals[i]))
.collect();
assert_eq!(icol.dropna().unwrap().values(), iexp);
assert_eq!(fcol.dropna().unwrap().values(), fexp);
let bdropped = bcol.dropna().unwrap();
assert_eq!(bdropped.dtype(), DType::Bool);
assert_eq!(bdropped.values(), bexp);
}
}
#[test]
fn dropna_removes_missing() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let result = col.dropna().expect("dropna");
assert_eq!(result.len(), 2);
assert_eq!(result.values()[0], Scalar::Int64(1));
assert_eq!(result.values()[1], Scalar::Int64(3));
}
#[test]
fn dropna_matches_order_preserving_scalar_oracle_vbbe4() {
// Differential vs scalar filter oracle (br-frankenpandas-vbbe4).
// Seeded LCG, no mocks.
fn next(seed: &mut u64) -> u64 {
*seed = seed
.wrapping_mul(2862933555777941757)
.wrapping_add(3037000493);
*seed
}
fn assert_dropna(case: usize, family: &str, values: Vec<Scalar>) {
let input = Column::from_values(values).expect("column");
let expected = input
.values()
.iter()
.filter(|value| !value.is_missing())
.cloned()
.collect::<Vec<_>>();
let dropped = input.dropna().expect("dropna");
assert_eq!(
dropped.dtype(),
input.dtype(),
"case={case} family={family}: dtype changed"
);
assert_eq!(
dropped.len(),
expected.len(),
"case={case} family={family}: length mismatch"
);
assert_eq!(
dropped.count(),
expected.len(),
"case={case} family={family}: count mismatch"
);
assert!(
dropped.values().iter().all(|value| !value.is_missing()),
"case={case} family={family}: dropna left missing values in {:?}",
dropped.values()
);
assert_eq!(
dropped.values(),
expected.as_slice(),
"case={case} family={family}: order/value mismatch"
);
}
assert_dropna(
usize::MAX,
"all_float_missing",
vec![Scalar::Float64(f64::NAN), Scalar::Float64(f64::NAN)],
);
assert_dropna(
usize::MAX - 1,
"all_timedelta_missing",
vec![
Scalar::Timedelta64(i64::MIN),
Scalar::Null(NullKind::Null),
Scalar::Timedelta64(i64::MIN),
],
);
let mut seed = 0xd20f_ca55_0b5e_7a11_u64;
for case in 0..180 {
let len = (next(&mut seed) % 71 + 1) as usize;
let mut floats = Vec::with_capacity(len);
floats.push(Scalar::Float64(case as f64 / 3.0));
for _ in 1..len {
let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
floats.push(match next(&mut seed) % 8 {
0 | 1 => Scalar::Float64(f64::NAN),
2 => Scalar::Float64(f64::INFINITY),
3 => Scalar::Float64(f64::NEG_INFINITY),
4 => Scalar::Float64(-0.0),
_ => Scalar::Float64(raw as f64 / 29.0),
});
}
assert_dropna(case, "float", floats);
let mut ints = Vec::with_capacity(len);
ints.push(Scalar::Int64(case as i64));
for _ in 1..len {
let raw = (next(&mut seed) % 59) as i64 - 29;
ints.push(match next(&mut seed) % 6 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
_ => Scalar::Int64(raw),
});
}
assert_dropna(case, "int", ints);
let mut bools = Vec::with_capacity(len);
bools.push(Scalar::Bool(case & 1 == 0));
for _ in 1..len {
bools.push(match next(&mut seed) % 5 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
raw => Scalar::Bool(raw & 1 == 1),
});
}
assert_dropna(case, "bool", bools);
let mut utf8 = Vec::with_capacity(len);
utf8.push(Scalar::Utf8(format!("u{}", case % 17)));
for pos in 1..len {
utf8.push(match next(&mut seed) % 7 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
raw => Scalar::Utf8(format!("u{}_{}", raw, pos % 11)),
});
}
assert_dropna(case, "utf8", utf8);
let mut timedeltas = Vec::with_capacity(len);
timedeltas.push(Scalar::Timedelta64(case as i64 - 90));
for _ in 1..len {
let raw = (next(&mut seed) % 123) as i64 - 61;
timedeltas.push(match next(&mut seed) % 7 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Timedelta64(i64::MIN),
_ => Scalar::Timedelta64(raw),
});
}
assert_dropna(case, "timedelta", timedeltas);
}
}
#[test]
fn comparison_empty_columns() {
let left = Column::from_values(vec![]).expect("left");
let right = Column::from_values(vec![]).expect("right");
let result = left
.binary_comparison(&right, ComparisonOp::Eq)
.expect("eq");
assert!(result.is_empty());
}
#[test]
fn comparison_length_mismatch_error() {
let left = Column::from_values(vec![Scalar::Int64(1)]).expect("left");
let right =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("right");
assert!(left.binary_comparison(&right, ComparisonOp::Eq).is_err());
}
#[test]
fn comparison_bool_ordering() {
let left =
Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("left");
let right =
Column::from_values(vec![Scalar::Bool(false), Scalar::Bool(true)]).expect("right");
let gt = left
.binary_comparison(&right, ComparisonOp::Gt)
.expect("gt");
assert_eq!(gt.values()[0], Scalar::Bool(true));
assert_eq!(gt.values()[1], Scalar::Bool(false));
}
}
mod iter_and_predicates {
use fp_types::NullKind;
use super::*;
#[test]
fn iter_values_preserves_order() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let collected: Vec<_> = col.iter_values().cloned().collect();
assert_eq!(collected, col.values());
}
#[test]
fn to_vec_returns_owned_clone() {
let col = Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(6)]).expect("col");
let v = col.to_vec();
assert_eq!(v, vec![Scalar::Int64(5), Scalar::Int64(6)]);
// Column still owns its values; to_vec was a clone.
assert_eq!(col.len(), 2);
}
#[test]
fn copy_returns_independent_clone() {
let col = Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(6)]).expect("col");
let copied = col.copy();
let viewed = col.view();
let transposed = col.transpose();
assert_eq!(copied, col);
assert_eq!(viewed, col);
assert_eq!(transposed, col);
assert_eq!(col.t(), transposed);
assert_eq!(col.T(), transposed);
assert_ne!(copied.values().as_ptr(), col.values().as_ptr());
assert_ne!(viewed.values().as_ptr(), col.values().as_ptr());
assert_ne!(transposed.values().as_ptr(), col.values().as_ptr());
}
#[test]
fn item_extracts_single_value_and_rejects_other_lengths() {
let single = Column::from_values(vec![Scalar::Int64(5)]).expect("col");
assert_eq!(single.item(), Ok(Scalar::Int64(5)));
let empty = Column::from_values(Vec::<Scalar>::new()).expect("col");
assert_eq!(
empty.item(),
Err(crate::ColumnError::InvalidLength {
operation: "item()",
expected: 1,
actual: 0,
})
);
let multi = Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(6)]).expect("col");
assert_eq!(
multi.item(),
Err(crate::ColumnError::InvalidLength {
operation: "item()",
expected: 1,
actual: 2,
})
);
}
#[test]
fn has_any_missing_detects_null() {
let populated =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
assert!(!populated.has_any_missing());
assert_eq!(populated.hasnans(), populated.has_any_missing());
assert_eq!(populated.nbytes(), populated.memory_usage(false));
let with_null =
Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
.expect("col");
assert!(with_null.has_any_missing());
assert_eq!(with_null.hasnans(), with_null.has_any_missing());
assert_eq!(with_null.nbytes(), with_null.memory_usage(false));
}
#[test]
fn missingness_probes_use_nullable_int64_validity_without_scalar_materialization_eo8jv() {
let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(0, 2), (5, 1)]), 6);
let mixed = Column::from_i64_values_with_validity((10_i64..16).collect(), validity);
assert!(mixed.has_any_missing());
assert_eq!(mixed.hasnans(), mixed.has_any_missing());
assert!(!mixed.all_missing());
if let ScalarValues::LazyNullableInt64 { values, .. } = &mixed.values {
assert!(values.get().is_none());
}
let all_invalid =
Column::from_i64_values_with_validity(vec![0, 0, 0], ValidityMask::all_invalid(3));
assert!(all_invalid.has_any_missing());
assert!(all_invalid.all_missing());
if let ScalarValues::LazyNullableInt64 { values, .. } = &all_invalid.values {
assert!(values.get().is_none());
}
}
#[test]
fn missingness_probes_float64_raw_path_checks_nan_eo8jv() {
let mixed = Column {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64(vec![1.0, f64::NAN, f64::INFINITY]),
validity: ValidityMask::all_valid(3),
data: None,
};
assert!(mixed.has_any_missing());
assert!(!mixed.all_missing());
if let ScalarValues::LazyAllValidFloat64 { values, .. } = &mixed.values {
assert!(values.get().is_none());
}
let all_nan = Column {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64(vec![f64::NAN, f64::NAN]),
validity: ValidityMask::all_valid(2),
data: None,
};
assert!(all_nan.has_any_missing());
assert!(all_nan.all_missing());
if let ScalarValues::LazyAllValidFloat64 { values, .. } = &all_nan.values {
assert!(values.get().is_none());
}
}
#[test]
fn all_missing_empty_is_true() {
let empty = Column::from_values(Vec::<Scalar>::new()).expect("col");
assert!(empty.all_missing());
let all_null = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::Null),
])
.expect("col");
assert!(all_null.all_missing());
let mixed = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
.expect("col");
assert!(!mixed.all_missing());
}
#[test]
fn apply_bool_positive_predicate() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
])
.expect("col");
let even = col
.apply_bool(|v| v.to_f64().map(|f| f as i64 % 2 == 0).unwrap_or(false))
.expect("apply_bool");
assert_eq!(even.dtype(), DType::Bool);
assert_eq!(even.values()[0], Scalar::Bool(false));
assert_eq!(even.values()[1], Scalar::Bool(true));
assert_eq!(even.values()[2], Scalar::Bool(false));
assert_eq!(even.values()[3], Scalar::Bool(true));
}
#[test]
fn first_and_last_return_endpoints() {
let col = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
])
.expect("col");
assert_eq!(col.first(), Some(&Scalar::Int64(10)));
assert_eq!(col.last(), Some(&Scalar::Int64(30)));
let empty = Column::from_values(Vec::<Scalar>::new()).expect("col");
assert_eq!(empty.first(), None);
assert_eq!(empty.last(), None);
}
#[test]
fn count_matching_ignores_missing_and_mismatches() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Null(NullKind::NaN),
Scalar::Int64(4),
Scalar::Int64(6),
])
.expect("col");
let evens =
col.count_matching(|v| v.to_f64().map(|f| f as i64 % 2 == 0).unwrap_or(false));
assert_eq!(evens, 3); // 2, 4, 6 — missing not counted.
}
#[test]
fn zip_with_elementwise_combine() {
let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("a");
let b = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
])
.expect("b");
let sum = a
.zip_with(&b, |l, r| match (l.to_f64(), r.to_f64()) {
(Ok(lf), Ok(rf)) => Scalar::Float64(lf + rf),
_ => Scalar::Null(NullKind::NaN),
})
.expect("zip_with");
assert_eq!(sum.values()[0], Scalar::Float64(11.0));
assert_eq!(sum.values()[1], Scalar::Float64(22.0));
assert_eq!(sum.values()[2], Scalar::Float64(33.0));
}
#[test]
fn zip_with_length_mismatch_errors() {
let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
assert!(a.zip_with(&b, |l, _| l.clone()).is_err());
}
#[test]
fn iter_enumerate_yields_positions() {
let col = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("col");
let collected: Vec<_> = col.iter_enumerate().map(|(i, v)| (i, v.clone())).collect();
assert_eq!(
collected,
vec![(0, Scalar::Int64(10)), (1, Scalar::Int64(20))]
);
}
#[test]
fn apply_bool_missing_maps_to_false() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
.expect("col");
let result = col.apply_bool(|_| true).expect("apply_bool");
assert_eq!(result.values()[0], Scalar::Bool(true));
// Missing input → false (per doc contract).
assert_eq!(result.values()[1], Scalar::Bool(false));
}
}
mod take_slice_concat_repeat {
use super::*;
#[test]
fn take_reorders_rows() {
let col = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
])
.expect("col");
let picked = col.take(&[2, 0, 1]).expect("take");
assert_eq!(picked.values()[0], Scalar::Int64(30));
assert_eq!(picked.values()[1], Scalar::Int64(10));
assert_eq!(picked.values()[2], Scalar::Int64(20));
}
#[test]
fn take_out_of_bounds_errors() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let err = col.take(&[5]).unwrap_err();
assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
}
#[test]
fn slice_returns_contiguous_range() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
])
.expect("col");
let middle = col.slice(1, 2).expect("slice");
assert_eq!(middle.len(), 2);
assert_eq!(middle.values()[0], Scalar::Int64(2));
assert_eq!(middle.values()[1], Scalar::Int64(3));
}
#[test]
fn slice_past_end_yields_empty() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let empty = col.slice(10, 5).expect("slice");
assert!(empty.is_empty());
assert_eq!(empty.dtype(), DType::Int64);
}
#[test]
fn slice_len_clamps_to_tail() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
])
.expect("col");
let tail = col.slice(2, 100).expect("slice");
assert_eq!(tail.len(), 1);
assert_eq!(tail.values()[0], Scalar::Float64(3.0));
}
#[test]
fn slice_huge_len_clamps_without_overflow() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let tail = col.slice(1, usize::MAX).expect("slice");
assert_eq!(tail.values(), &[Scalar::Int64(2), Scalar::Int64(3)]);
}
#[test]
fn head_returns_first_n_values() {
let col = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
Scalar::Int64(40),
])
.expect("col");
let out = col.head(2).expect("head");
assert_eq!(out.values(), &[Scalar::Int64(10), Scalar::Int64(20)]);
}
#[test]
fn tail_returns_last_n_values() {
let col = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
Scalar::Int64(40),
])
.expect("col");
let out = col.tail(2).expect("tail");
assert_eq!(out.values(), &[Scalar::Int64(30), Scalar::Int64(40)]);
}
#[test]
fn head_tail_negative_n_match_pandas_style() {
let col = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
Scalar::Int64(40),
Scalar::Int64(50),
])
.expect("col");
let head = col.head(-2).expect("head");
let tail = col.tail(-2).expect("tail");
assert_eq!(
head.values(),
&[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
);
assert_eq!(
tail.values(),
&[Scalar::Int64(30), Scalar::Int64(40), Scalar::Int64(50)]
);
}
#[test]
fn head_tail_large_negative_n_saturate_to_empty() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
])
.expect("col");
let head = col.head(-10).expect("head");
let tail = col.tail(-10).expect("tail");
assert!(head.is_empty());
assert!(tail.is_empty());
assert_eq!(head.dtype(), DType::Float64);
assert_eq!(tail.dtype(), DType::Float64);
}
#[test]
fn concat_appends_same_dtype() {
let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("a");
let b = Column::from_values(vec![Scalar::Int64(3)]).expect("b");
let combined = a.concat(&b).expect("concat");
assert_eq!(combined.len(), 3);
assert_eq!(combined.values()[2], Scalar::Int64(3));
}
#[test]
fn concat_different_dtypes_errors() {
let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
let b = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("b");
let err = a.concat(&b).unwrap_err();
assert!(matches!(err, crate::ColumnError::DTypeMismatch { .. }));
}
#[test]
fn repeat_duplicates_contiguously() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let out = col.repeat(3).expect("repeat");
assert_eq!(out.len(), 6);
assert_eq!(out.values()[0], Scalar::Int64(1));
assert_eq!(out.values()[1], Scalar::Int64(1));
assert_eq!(out.values()[2], Scalar::Int64(1));
assert_eq!(out.values()[3], Scalar::Int64(2));
}
#[test]
fn repeat_zero_is_empty_same_dtype() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let out = col.repeat(0).expect("repeat");
assert!(out.is_empty());
assert_eq!(out.dtype(), DType::Int64);
}
#[test]
fn repeat_one_is_clone() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let out = col.repeat(1).expect("repeat");
assert_eq!(out.values(), col.values());
}
}
mod reverse_head_tail_cumulatives_unique {
use fp_types::NullKind;
use super::*;
#[test]
fn reverse_swaps_order_and_preserves_dtype() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let r = col.reverse().expect("reverse");
assert_eq!(r.values()[0], Scalar::Int64(3));
assert_eq!(r.values()[2], Scalar::Int64(1));
assert_eq!(r.dtype(), DType::Int64);
}
#[test]
fn head_positive_takes_first_n() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
])
.expect("col");
let h = col.head(2).expect("head");
assert_eq!(h.len(), 2);
assert_eq!(h.values()[0], Scalar::Int64(1));
assert_eq!(h.values()[1], Scalar::Int64(2));
}
#[test]
fn head_negative_drops_last_n() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let h = col.head(-1).expect("head");
assert_eq!(h.len(), 2);
assert_eq!(h.values()[1], Scalar::Int64(2));
}
#[test]
fn tail_positive_takes_last_n() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
])
.expect("col");
let t = col.tail(2).expect("tail");
assert_eq!(t.len(), 2);
assert_eq!(t.values()[0], Scalar::Int64(3));
assert_eq!(t.values()[1], Scalar::Int64(4));
}
#[test]
fn tail_negative_drops_first_n() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let t = col.tail(-1).expect("tail");
assert_eq!(t.len(), 2);
assert_eq!(t.values()[0], Scalar::Int64(2));
}
#[test]
fn head_tail_out_of_range_clamps() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
assert_eq!(col.head(10).expect("head").len(), 1);
assert_eq!(col.tail(10).expect("tail").len(), 1);
assert_eq!(col.head(-10).expect("head").len(), 0);
assert_eq!(col.tail(-10).expect("tail").len(), 0);
}
#[test]
fn cum_typed_i64_matches_scalar_path() {
// Typed all-valid i64 cum{sum,prod,max,min} == the Scalar/nan* path
// (fold as f64 -> Float64), incl. negatives and large magnitudes.
let mut state: u64 = 0x33CC_55AA_77EE_99BB;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..150 {
let n = (next() % 300) as usize + 1;
let vals: Vec<i64> = (0..n)
.map(|_| match next() % 5 {
0 => (next() % 7) as i64 - 3,
1 => next() as i64, // wide
_ => (next() % 100) as i64,
})
.collect();
let typed = Column::from_i64_values_owned(vals.clone());
let scalar = Column::from_values(vals.iter().map(|&v| Scalar::Int64(v)).collect())
.expect("scalar col");
// NaN-bit-aware equality: cumprod can overflow to NaN, and
// NaN != NaN would fail a plain assert_eq even when identical;
// compare Float64 by bits while still catching Null-vs-NaN drift.
let vals_eq = |a: &[Scalar], b: &[Scalar]| -> bool {
a.len() == b.len()
&& a.iter().zip(b).all(|(x, y)| match (x, y) {
(Scalar::Float64(p), Scalar::Float64(q)) => p.to_bits() == q.to_bits(),
_ => x == y,
})
};
assert!(vals_eq(
typed.cumsum().unwrap().values(),
scalar.cumsum().unwrap().values()
));
assert!(vals_eq(
typed.cumprod().unwrap().values(),
scalar.cumprod().unwrap().values()
));
assert!(vals_eq(
typed.cummax().unwrap().values(),
scalar.cummax().unwrap().values()
));
assert!(vals_eq(
typed.cummin().unwrap().values(),
scalar.cummin().unwrap().values()
));
}
}
#[test]
fn cumsum_produces_float64_running_sum() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
])
.expect("col");
let c = col.cumsum().expect("cumsum");
assert_eq!(c.dtype(), DType::Float64);
assert_eq!(c.values()[0], Scalar::Float64(1.0));
assert!(c.values()[1].is_missing());
assert_eq!(c.values()[2], Scalar::Float64(4.0));
}
#[test]
fn cumprod_running_product() {
let col = Column::from_values(vec![
Scalar::Float64(2.0),
Scalar::Float64(3.0),
Scalar::Float64(4.0),
])
.expect("col");
let c = col.cumprod().expect("cumprod");
assert_eq!(c.values()[2], Scalar::Float64(24.0));
}
#[test]
fn cummax_cummin_running_extrema() {
let col = Column::from_values(vec![
Scalar::Float64(3.0),
Scalar::Float64(1.0),
Scalar::Float64(4.0),
Scalar::Float64(1.0),
Scalar::Float64(5.0),
])
.expect("col");
let mx = col.cummax().expect("cummax");
assert_eq!(mx.values()[4], Scalar::Float64(5.0));
let mn = col.cummin().expect("cummin");
assert_eq!(mn.values()[4], Scalar::Float64(1.0));
}
#[test]
fn cummax_cummin_nullable_typed_matches_nancum_reference() {
// The nullable Int64/Float64 cummax/cummin typed paths must be
// BYTE-IDENTICAL to the generic nancummax/nancummin (running extremum
// over present values, Null(NaN) at missing). Null-missing only (no
// present-NaN) so the Scalars compare structurally. Typed backings via
// from_*_with_validity ⇒ the typed arm fires. Deterministic LCG.
fn reference(vals: &[Scalar], is_max: bool) -> Vec<Scalar> {
let mut running: Option<f64> = None;
vals.iter()
.map(|v| {
if v.is_missing() {
return Scalar::Null(fp_types::NullKind::NaN);
}
match v.to_f64() {
Ok(x) if !x.is_nan() => {
let nv = match running {
Some(p) => {
if is_max {
p.max(x)
} else {
p.min(x)
}
}
None => x,
};
running = Some(nv);
Scalar::Float64(nv)
}
_ => Scalar::Null(fp_types::NullKind::NaN),
}
})
.collect()
}
let mut state: u64 = 0xCADE_1357_2468_ABCD;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..150 {
let n = (next() % 300) as usize + 1;
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 41) as i64 - 20
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vf.set(i, false);
0.0
} else {
((r % 41) as f64 - 20.0) / 3.0
}
})
.collect();
let icol = Column::from_i64_values_with_validity(idata, vi);
let fcol = Column::from_f64_values_with_validity(fdata, vf);
for (col, tag) in [(&icol, "i64"), (&fcol, "f64")] {
let vals = col.values().to_vec();
assert_eq!(
col.cummax().expect("cummax").values(),
reference(&vals, true).as_slice(),
"{tag} cummax trial {trial}"
);
assert_eq!(
col.cummin().expect("cummin").values(),
reference(&vals, false).as_slice(),
"{tag} cummin trial {trial}"
);
}
}
}
#[test]
fn cumsum_cumprod_nullable_typed_matches_nancum_reference() {
// Nullable Int64/Float64 cumsum/cumprod typed paths must be BYTE-
// IDENTICAL to nancumsum/nancumprod (running seeded 0.0/1.0, folded over
// present values, Null(NaN) at missing). Null-missing only. Product uses
// a NARROW value range near ±1 so the running product stays finite (no
// inf → NaN divergence between paths). Deterministic LCG.
fn reference(vals: &[Scalar], seed: f64, is_prod: bool) -> Vec<Scalar> {
let mut running = seed;
vals.iter()
.map(|v| {
if v.is_missing() {
return Scalar::Null(fp_types::NullKind::NaN);
}
match v.to_f64() {
Ok(x) if !x.is_nan() => {
if is_prod {
running *= x;
} else {
running += x;
}
Scalar::Float64(running)
}
_ => Scalar::Null(fp_types::NullKind::NaN),
}
})
.collect()
}
let mut state: u64 = 0x5023_9ABC_1234_DEF0;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..150 {
let n = (next() % 300) as usize + 1;
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
// Small integer magnitudes so cumsum stays exact and cumprod finite.
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 3) as i64 - 1 // {-1, 0, 1}
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vf.set(i, false);
0.0
} else {
0.5 + (r % 3) as f64 * 0.5 // {0.5, 1.0, 1.5}
}
})
.collect();
let icol = Column::from_i64_values_with_validity(idata, vi);
let fcol = Column::from_f64_values_with_validity(fdata, vf);
for (col, tag) in [(&icol, "i64"), (&fcol, "f64")] {
let vals = col.values().to_vec();
assert_eq!(
col.cumsum().expect("cumsum").values(),
reference(&vals, 0.0, false).as_slice(),
"{tag} cumsum trial {trial}"
);
assert_eq!(
col.cumprod().expect("cumprod").values(),
reference(&vals, 1.0, true).as_slice(),
"{tag} cumprod trial {trial}"
);
}
}
}
#[test]
fn unique_preserves_first_seen_order() {
let col = Column::from_values(vec![
Scalar::Int64(3),
Scalar::Int64(1),
Scalar::Int64(3),
Scalar::Int64(2),
Scalar::Int64(1),
])
.expect("col");
let u = col.unique().expect("unique");
assert_eq!(u.len(), 3);
assert_eq!(u.values()[0], Scalar::Int64(3));
assert_eq!(u.values()[1], Scalar::Int64(1));
assert_eq!(u.values()[2], Scalar::Int64(2));
}
#[test]
fn unique_f64_open_addressing_matches_reference_and_signed_zero() {
// Float64 wide path keys on NORMALIZED bits (−0.0 == +0.0) but keeps
// the first-seen original — so -0.0-first stays -0.0.
let col = Column::from_f64_values(vec![-0.0, 1.5, 0.0, 1.5, f64::INFINITY, -0.0]);
let u = col.unique().expect("unique");
let got: Vec<f64> = u
.values()
.iter()
.map(|v| match v {
Scalar::Float64(x) => *x,
o => panic!("not f64: {o:?}"),
})
.collect();
assert_eq!(got.len(), 3);
assert!(
got[0] == 0.0 && got[0].is_sign_negative(),
"first unique is -0.0"
);
assert_eq!(got[1], 1.5);
assert_eq!(got[2], f64::INFINITY);
// Differential vs a first-seen HashSet<u64 normalized-bits> reference.
use std::collections::HashSet;
let mut state: u64 = 0x0F1E_2D3C_4B5A_6978;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..120 {
let n = (next() % 400) as usize + 1;
let data: Vec<f64> = (0..n)
.map(|_| {
// mix of a few repeated buckets to force duplicates
let pick = next() % 7;
match pick {
0 => -0.0,
1 => 0.0,
2 => 1.0,
3 => -2.5,
4 => f64::INFINITY,
5 => (next() % 50) as f64,
_ => (next() >> 11) as f64 / (1u64 << 53) as f64,
}
})
.collect();
let mut seen = HashSet::new();
let expected: Vec<u64> = data
.iter()
.filter_map(|&f| {
let kb = (if f == 0.0 { 0.0 } else { f }).to_bits();
seen.insert(kb).then_some(f.to_bits())
})
.collect();
let col = Column::from_f64_values(data);
let got: Vec<u64> = col
.unique()
.expect("unique")
.values()
.iter()
.map(|v| match v {
Scalar::Float64(x) => x.to_bits(),
o => panic!("not f64: {o:?}"),
})
.collect();
assert_eq!(got, expected);
}
}
#[test]
fn unique_wide_growable_fibonacci_rehash_matches_first_seen_reference() {
// Regression for the unique_{f64,i64}_wide fix: many distinct WIDE /
// high-bit-varying keys (> 1024 ⇒ multiple growable-table rehashes) — the
// case the old low-bit `& mask` hash clustered — must keep BYTE-IDENTICAL
// first-seen dedup order vs a HashSet reference. i64 also mixes i64::MIN.
use std::collections::HashSet;
let mut state: u64 = 0x2468_ACE0_1357_9BDF;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..40 {
let distinct = 2000 + (next() % 800) as i64;
let n = 12_000usize;
// i64: high-bit-only variation (k << 34), plus i64::MIN sentinel.
let idata: Vec<i64> = (0..n)
.map(|i| {
if i % 500 == 0 {
i64::MIN
} else {
(((next() % distinct as u64) as i64) - distinct / 2) << 34
}
})
.collect();
// f64: float-of-integer (variation in the HIGH to_bits() bits).
let fdata: Vec<f64> = (0..n)
.map(|_| (next() % distinct as u64) as f64)
.collect();
assert!(crate::i64_direct_address_range(&idata).is_none());
let mut iseen: HashSet<i64> = HashSet::new();
let iexp: Vec<i64> = idata
.iter()
.filter_map(|&v| iseen.insert(v).then_some(v))
.collect();
let mut fseen: HashSet<u64> = HashSet::new();
let fexp: Vec<u64> = fdata
.iter()
.filter_map(|&f| {
let kb = (if f == 0.0 { 0.0 } else { f }).to_bits();
fseen.insert(kb).then_some(f.to_bits())
})
.collect();
let igot: Vec<i64> = Column::from_i64_values_owned(idata)
.unique()
.expect("unique")
.values()
.iter()
.map(|v| match v {
Scalar::Int64(x) => *x,
o => panic!("not i64: {o:?}"),
})
.collect();
let fgot: Vec<u64> = Column::from_f64_values(fdata)
.unique()
.expect("unique")
.values()
.iter()
.map(|v| match v {
Scalar::Float64(x) => x.to_bits(),
o => panic!("not f64: {o:?}"),
})
.collect();
assert_eq!(igot, iexp, "i64 trial {trial}");
assert_eq!(fgot, fexp, "f64 trial {trial}");
}
}
#[test]
fn unique_datetime64_open_addressing_and_nat_fallthrough() {
// All-valid, no-NaT Datetime64 takes the open-addressing ns path;
// first-seen distinct timestamps, re-wrapped as Datetime64.
let ns = vec![
946_684_800_000_000_000i64,
946_684_800_000_000_000,
946_684_837_000_000_000,
100,
946_684_837_000_000_000,
100,
];
let col = Column::from_datetime64_values(ns);
let u = col.unique().expect("unique");
let got: Vec<i64> = u
.values()
.iter()
.map(|v| match v {
Scalar::Datetime64(x) => *x,
other => panic!("expected Datetime64, got {other:?}"),
})
.collect();
assert_eq!(
got,
vec![946_684_800_000_000_000, 946_684_837_000_000_000, 100]
);
// A NaT datum (i64::MIN) must fall through to the generic path, which
// DROPS NaT — so the open-addressing shortcut must NOT emit it.
let with_nat = Column::from_datetime64_values(vec![
i64::MIN, // NaT sentinel
5,
5,
i64::MIN,
7,
]);
let u2 = with_nat.unique().expect("unique nat");
let got2: Vec<i64> = u2
.values()
.iter()
.filter_map(|v| match v {
Scalar::Datetime64(x) => Some(*x),
_ => None,
})
.collect();
assert_eq!(got2, vec![5, 7], "NaT must be dropped, not emitted");
}
#[test]
fn unique_wide_i64_open_addressing_matches_reference() {
// Wide/sparse all-valid Int64 uses unique_i64_wide (open-addressing
// set). First-seen distinct must equal an insertion-ordered reference
// across full-range data incl. the i64::MIN empty-sentinel.
use std::collections::HashSet;
let pool: [i64; 6] = [
i64::MIN,
i64::MAX,
7_000_000_000_000_000_000,
-7_000_000_000_000_000_000,
42,
-42,
];
let mut state: u64 = 0xC0FF_EE00_1122_3344;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 400) as usize + 2;
let mut data: Vec<i64> = (0..n)
.map(|_| pool[(next() as usize) % pool.len()])
.collect();
data[0] = i64::MIN;
data[1] = i64::MAX;
assert!(
crate::i64_direct_address_range(&data).is_none(),
"trial {trial}: expected wide data"
);
// First-seen reference.
let mut seen = HashSet::new();
let mut expected: Vec<i64> = Vec::new();
for &v in &data {
if seen.insert(v) {
expected.push(v);
}
}
let col = Column::from_i64_values_owned(data);
let got: Vec<i64> = col
.unique()
.expect("unique")
.values()
.iter()
.filter_map(|v| match v {
Scalar::Int64(x) => Some(*x),
_ => None,
})
.collect();
assert_eq!(got, expected, "trial {trial}");
}
}
#[test]
fn unique_drops_nulls() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let u = col.unique().expect("unique");
assert_eq!(u.len(), 1);
assert_eq!(u.values()[0], Scalar::Int64(1));
}
#[test]
fn unique_nullable_utf8_typed_matches_generic() {
// The typed nullable-Utf8 unique arm (cold cache) must be BIT-EXACT to the
// generic Key path: FP drops nulls, keeps distinct present values in first-seen
// order. A/B on identical LazyNullableUtf8 data: `col_cold` (fresh, cold cache)
// exercises the typed arm; `col_warm` has its Scalar cache pre-materialized so
// the cold-cache gate defers it to the generic path. Seeded short strings over
// {a,b,c,d} + varied null densities (incl. all-null ⇒ empty).
let mut state: u64 = 0x0417_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..150 {
let n = (next() % 250) as usize;
let null_mode = next() % 3; // 0=none, 2=all-null, else ~25%
let mut validity = crate::ValidityMask::all_valid(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..n {
let is_null = match null_mode {
0 => false,
2 => true,
_ => next() % 4 == 0,
};
if is_null {
validity.set(i, false);
} else {
let len = (next() % 4) as usize;
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
}
offsets.push(bytes.len());
}
let col_cold = Column::from_utf8_values_with_validity(
bytes.clone(),
offsets.clone(),
validity.clone(),
);
let col_warm =
Column::from_utf8_values_with_validity(bytes, offsets, validity);
let _ = col_warm.values(); // warm cache ⇒ generic path (oracle)
let cold = col_cold.unique().expect("cold unique");
let warm = col_warm.unique().expect("warm unique");
assert_eq!(
cold.values(),
warm.values(),
"trial {trial} null_mode={null_mode}"
);
}
}
}
mod abs_shift_clip_round_isin {
use fp_types::NullKind;
use super::*;
#[test]
fn abs_int_and_float() {
let int_col =
Column::from_values(vec![Scalar::Int64(-3), Scalar::Int64(0), Scalar::Int64(5)])
.expect("int");
let a = int_col.abs().expect("abs");
assert_eq!(a.values()[0], Scalar::Int64(3));
assert_eq!(a.values()[1], Scalar::Int64(0));
let float_col =
Column::from_values(vec![Scalar::Float64(-1.5), Scalar::Null(NullKind::NaN)])
.expect("float");
let b = float_col.abs().expect("abs");
assert_eq!(b.values()[0], Scalar::Float64(1.5));
assert!(b.values()[1].is_missing());
}
#[test]
fn abs_nullable_int64_typed_matches_reference_cf() {
// Nullable Int64 abs routes through the typed as_i64_slice_with_validity
// arm: present ⇒ Int64(wrapping_abs); missing ⇒ Null; dtype preserved;
// i64::MIN abs wraps to i64::MIN (matching the scalar loop's wrapping_abs).
let mut validity = ValidityMask::all_valid(5);
validity.set(1, false);
validity.set(3, false);
let col =
Column::from_i64_values_with_validity(vec![-3, 0, i64::MIN, 7, -5], validity);
let r = col.abs().expect("abs");
assert_eq!(r.dtype(), DType::Int64);
let v = r.values();
assert_eq!(v[0], Scalar::Int64(3));
assert!(matches!(v[1], Scalar::Null(_)), "missing stays missing");
assert_eq!(v[2], Scalar::Int64(i64::MIN.wrapping_abs()));
assert!(matches!(v[3], Scalar::Null(_)));
assert_eq!(v[4], Scalar::Int64(5));
}
#[test]
fn abs_bool_preserves_dtype() {
let bool_col =
Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("bool");
let result = bool_col.abs().expect("abs");
assert_eq!(result.dtype(), DType::Bool);
assert_eq!(result.values(), &[Scalar::Bool(true), Scalar::Bool(false)]);
}
#[test]
fn abs_utf8_errors() {
let col = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("col");
assert!(col.abs().is_err());
}
#[test]
fn shift_typed_f64_missing_fill_matches_scalar_path() {
// The typed f64 (missing-fill) shift via from_f64_values_with_validity
// == the generic Scalar shift: vacated slots Null(NaN), body Float64(src),
// across +/- periods incl. abs >= len (all vacated).
let mut state: u64 = 0x7A1C_3E5F_90B2_D4C6;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..200 {
let n = (next() % 50) as usize + 1;
let fvals: Vec<f64> = (0..n)
.map(|_| (next() % 1000) as f64 * 0.5 - 250.0)
.collect();
let typed = Column::from_f64_values(fvals.clone());
for p in [1i64, 2, -1, -3, n as i64, n as i64 + 5, -(n as i64) - 2] {
let t = typed.shift(p, Scalar::Null(NullKind::NaN)).unwrap();
let abs = p.unsigned_abs() as usize;
// Independent oracle (NOT the Scalar shift, which a Float64
// from_values twin would also route through the typed path).
let expected: Vec<Scalar> = (0..n)
.map(|i| {
let vacated = if abs >= n {
true
} else if p > 0 {
i < abs
} else {
i >= n - abs
};
if vacated {
Scalar::Null(NullKind::NaN)
} else if p > 0 {
Scalar::Float64(fvals[i - abs])
} else {
Scalar::Float64(fvals[i + abs])
}
})
.collect();
assert_eq!(t.values(), expected, "period {p}");
}
}
}
#[test]
fn shift_typed_i64_valid_fill_matches_positional_oracle() {
let vals = vec![10_i64, 20, 30, 40, 50];
let typed = Column::from_i64_values(vals.clone());
for p in [1_i64, 2, -1, -3, 5, 9, -8] {
let shifted = typed.shift(p, Scalar::Int64(-7)).unwrap();
let abs = p.unsigned_abs() as usize;
let expected: Vec<Scalar> = (0..vals.len())
.map(|i| {
let vacated = if abs >= vals.len() {
true
} else if p > 0 {
i < abs
} else {
i >= vals.len() - abs
};
if vacated {
Scalar::Int64(-7)
} else if p > 0 {
Scalar::Int64(vals[i - abs])
} else {
Scalar::Int64(vals[i + abs])
}
})
.collect();
assert_eq!(shifted.dtype(), DType::Int64);
assert_eq!(shifted.values(), expected, "period {p}");
}
}
#[test]
fn shift_typed_bool_valid_fill_matches_positional_oracle() {
let vals = vec![true, false, true, true, false, false];
let typed = Column::from_bool_values(vals.clone());
for p in [1_i64, 2, -1, -4, 6, 10, -9] {
let shifted = typed.shift(p, Scalar::Bool(false)).unwrap();
let abs = p.unsigned_abs() as usize;
let expected: Vec<Scalar> = (0..vals.len())
.map(|i| {
let vacated = if abs >= vals.len() {
true
} else if p > 0 {
i < abs
} else {
i >= vals.len() - abs
};
if vacated {
Scalar::Bool(false)
} else if p > 0 {
Scalar::Bool(vals[i - abs])
} else {
Scalar::Bool(vals[i + abs])
}
})
.collect();
assert_eq!(shifted.dtype(), DType::Bool);
assert_eq!(shifted.values(), expected, "period {p}");
}
}
#[test]
fn shift_typed_bool_valid_fill_defers_materialization_until_read() {
let typed = Column::from_bool_values(vec![true, false, true, false]);
let shifted = typed.shift(1, Scalar::Bool(false)).unwrap();
assert!(matches!(
&shifted.values,
ScalarValues::LazyShiftedBool { data, values, .. }
if data.get().is_none() && values.get().is_none()
));
assert_eq!(shifted.len(), 4);
assert!(matches!(
&shifted.values,
ScalarValues::LazyShiftedBool { data, values, .. }
if data.get().is_none() && values.get().is_none()
));
assert_eq!(
shifted.as_bool_slice(),
Some(&[false, true, false, true][..])
);
assert!(matches!(
&shifted.values,
ScalarValues::LazyShiftedBool { data, values, .. }
if data.get().is_some() && values.get().is_none()
));
}
#[test]
fn shift_positive_pads_left_with_fill() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let s = col.shift(1, Scalar::Null(NullKind::NaN)).expect("shift");
assert!(s.values()[0].is_missing());
assert_eq!(s.values()[1], Scalar::Int64(1));
assert_eq!(s.values()[2], Scalar::Int64(2));
}
#[test]
fn shift_negative_pads_right() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let s = col.shift(-1, Scalar::Int64(0)).expect("shift");
assert_eq!(s.values()[0], Scalar::Int64(2));
assert_eq!(s.values()[1], Scalar::Int64(3));
assert_eq!(s.values()[2], Scalar::Int64(0));
}
#[test]
fn shift_zero_is_clone() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let s = col.shift(0, Scalar::Int64(-1)).expect("shift");
assert_eq!(s.values(), col.values());
}
#[test]
fn clip_both_bounds() {
let col = Column::from_values(vec![
Scalar::Float64(-5.0),
Scalar::Float64(3.0),
Scalar::Float64(10.0),
])
.expect("col");
let c = col.clip(Some(0.0), Some(5.0)).expect("clip");
assert_eq!(c.values()[0], Scalar::Float64(0.0));
assert_eq!(c.values()[1], Scalar::Float64(3.0));
assert_eq!(c.values()[2], Scalar::Float64(5.0));
}
#[test]
fn clip_none_bounds_are_noop() {
let col = Column::from_values(vec![Scalar::Float64(-5.0), Scalar::Float64(10.0)])
.expect("col");
let c = col.clip(None, None).expect("clip");
assert_eq!(c.values()[0], Scalar::Float64(-5.0));
assert_eq!(c.values()[1], Scalar::Float64(10.0));
}
#[test]
fn clip_scalar_bounds_match_clamp_oracle_t3idc() {
// Differential vs clamp oracle (br-frankenpandas-t3idc). NaN bounds
// are absent bounds. Seeded LCG, no mocks.
fn next(seed: &mut u64) -> u64 {
*seed = seed
.wrapping_mul(1181783497276652981)
.wrapping_add(1013904223);
*seed
}
fn bound(seed: &mut u64) -> Option<f64> {
match next(seed) % 7 {
0 => None,
1 => Some(f64::NAN),
_ => {
let raw = (next(seed) % 20_001) as i64 - 10_000;
Some(raw as f64 / 17.0)
}
}
}
fn normalize(bound: Option<f64>) -> Option<f64> {
bound.filter(|v| !v.is_nan())
}
fn clamp_oracle(mut value: f64, lower: Option<f64>, upper: Option<f64>) -> f64 {
if let Some(lo) = lower
&& value < lo
{
value = lo;
}
if let Some(hi) = upper
&& value > hi
{
value = hi;
}
value
}
let mut seed = 0x0c11_f0b0_a7e5_d1dc_u64;
for case in 0..220 {
let len = (next(&mut seed) % 61 + 1) as usize;
let mut lower = bound(&mut seed);
let mut upper = bound(&mut seed);
if let (Some(lo), Some(hi)) = (normalize(lower), normalize(upper))
&& lo > hi
{
lower = Some(hi);
upper = Some(lo);
}
let expected_lower = normalize(lower);
let expected_upper = normalize(upper);
let mut values = Vec::with_capacity(len);
for _ in 0..len {
let selector = next(&mut seed) % 43;
let whole = (next(&mut seed) % 100_001) as i64 - 50_000;
let frac = (next(&mut seed) % 1000) as f64 / 1000.0;
values.push(match selector {
0 => Scalar::Null(NullKind::NaN),
1 => Scalar::Float64(f64::NAN),
_ => Scalar::Float64(whole as f64 / 19.0 + frac),
});
}
let input = Column::from_values(values.clone()).expect("column");
let clipped = input.clip(lower, upper).expect("clip");
assert_eq!(clipped.dtype(), DType::Float64);
assert_eq!(clipped.values().len(), values.len());
for (pos, (before, after)) in values.iter().zip(clipped.values()).enumerate() {
if before.is_missing() {
assert!(
after.is_missing(),
"case={case} pos={pos}: missing became {after:?}"
);
continue;
}
let expected = match before {
Scalar::Float64(v) => clamp_oracle(*v, expected_lower, expected_upper),
other => panic!("unexpected non-float value: {other:?}"),
};
match after {
Scalar::Float64(got) => assert_eq!(
*got, expected,
"case={case} pos={pos}: got {got}, expected {expected}"
),
other => panic!("case={case} pos={pos}: expected Float64, got {other:?}"),
}
}
}
}
#[test]
fn round_rounds_floats() {
let col = Column::from_values(vec![
Scalar::Float64(1.234),
Scalar::Float64(5.678),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let r = col.round(1).expect("round");
assert_eq!(r.values()[0], Scalar::Float64(1.2));
assert_eq!(r.values()[1], Scalar::Float64(5.7));
assert!(r.values()[2].is_missing());
}
#[test]
fn round_int_nonnegative_decimals_is_noop() {
let col = Column::from_values(vec![Scalar::Int64(12), Scalar::Int64(34)]).expect("col");
let r = col.round(2).expect("round");
assert_eq!(r.values(), col.values());
assert_eq!(r.dtype(), DType::Int64);
}
#[test]
fn round_int_negative_decimals_preserves_dtype() {
let col = Column::from_values(vec![
Scalar::Int64(15),
Scalar::Int64(25),
Scalar::Int64(35),
Scalar::Int64(-15),
])
.expect("col");
let r = col.round(-1).expect("round");
assert_eq!(r.dtype(), DType::Int64);
assert_eq!(
r.values(),
&[
Scalar::Int64(20),
Scalar::Int64(20),
Scalar::Int64(40),
Scalar::Int64(-20)
]
);
}
#[test]
fn round_bool_is_noop() {
let col =
Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("col");
let r = col.round(-2).expect("round");
assert_eq!(r.dtype(), DType::Bool);
assert_eq!(r.values(), col.values());
}
#[test]
fn round_negative_decimals_rounds_left() {
let col = Column::from_values(vec![Scalar::Float64(1234.0)]).expect("col");
let r = col.round(-2).expect("round");
assert_eq!(r.values()[0], Scalar::Float64(1200.0));
}
#[test]
fn round_uses_pandas_half_even_ties() {
let col = Column::from_values(vec![
Scalar::Float64(1.5),
Scalar::Float64(2.5),
Scalar::Float64(-1.5),
Scalar::Float64(3.5),
])
.expect("col");
let r = col.round(0).expect("round");
assert_eq!(
r.values(),
&[
Scalar::Float64(2.0),
Scalar::Float64(2.0),
Scalar::Float64(-2.0),
Scalar::Float64(4.0)
]
);
}
#[test]
fn round_negative_decimals_uses_half_even_ties() {
let col = Column::from_values(vec![
Scalar::Float64(15.0),
Scalar::Float64(25.0),
Scalar::Float64(35.0),
Scalar::Float64(-15.0),
])
.expect("col");
let r = col.round(-1).expect("round");
assert_eq!(
r.values(),
&[
Scalar::Float64(20.0),
Scalar::Float64(20.0),
Scalar::Float64(40.0),
Scalar::Float64(-20.0)
]
);
}
#[test]
fn round_nonnegative_decimals_integral_float_identity_preserves_edges_blackthrush() {
let expected = vec![
f64::NEG_INFINITY,
-9.0,
-0.0,
0.0,
7.0,
4_503_599_627_370_496.0,
f64::INFINITY,
];
let input = Column::from_f64_values(expected.clone());
let output = input.round(2).expect("round");
let got = output.as_f64_slice().expect("all-valid float output");
assert_eq!(got.len(), expected.len(), "round length drift");
for (pos, (&got, &expected)) in got.iter().zip(&expected).enumerate() {
assert_eq!(
got.to_bits(),
expected.to_bits(),
"round pos={pos}: got {got:?}, expected {expected:?}"
);
}
let huge = Column::from_f64_values(vec![f64::MAX]);
let rounded = huge.round(2).expect("round huge");
assert_eq!(
rounded.as_f64_slice().expect("all-valid huge output")[0],
f64::INFINITY
);
let fractional = Column::from_f64_values(vec![1.234]);
let rounded = fractional.round(2).expect("round fractional");
assert_eq!(
rounded.as_f64_slice().expect("all-valid fractional output")[0],
1.23
);
let infinite_factor = Column::from_f64_values(vec![f64::INFINITY]);
let rounded = infinite_factor.round(400).expect("round infinite factor");
assert!(rounded.values()[0].is_missing());
}
#[test]
fn round_fast_scaled_matches_round_ties_even_reference_blackthrush() {
let mut values = vec![
f64::NEG_INFINITY,
-4_503_599_627_370_496.0,
-4_503_599_627_370_495.5,
-12_345.675,
-2.5,
-1.5,
-0.015,
-0.005,
-0.0,
0.0,
0.005,
0.015,
1.5,
2.5,
12_345.675,
4_503_599_627_370_495.5,
4_503_599_627_370_496.0,
f64::INFINITY,
f64::MAX,
-f64::MAX,
];
let mut state = 0x9e37_79b9_7f4a_7c15_u64;
for _ in 0..20_000 {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1);
let exponent = ((state >> 48) % 1200) + 1;
let sign = state & (1_u64 << 63);
let mantissa = state & 0x000f_ffff_ffff_ffff;
values.push(f64::from_bits(sign | (exponent << 52) | mantissa));
}
for decimals in [-6, -2, 0, 2, 6, 12] {
let factor = 10.0_f64.powi(decimals);
let col = Column::from_f64_values(values.clone());
let got = col.round(decimals).expect("round");
let got = got.as_f64_slice().expect("typed round");
for (pos, (&x, &rounded)) in values.iter().zip(got).enumerate() {
let expected = (x * factor).round_ties_even() / factor;
assert_eq!(
rounded.to_bits(),
expected.to_bits(),
"decimals={decimals} pos={pos} x={x:?}: got {rounded:?}, expected {expected:?}"
);
}
}
}
#[test]
fn sqrt_nullable_owned_preserves_nan_missing_semantics_blackthrush() {
let input = Column::from_f64_values(vec![4.0, -1.0, -0.0, 0.0, f64::INFINITY]);
let output = input.sqrt().expect("sqrt");
assert_eq!(output.dtype(), DType::Float64);
assert_eq!(output.values().len(), 5);
assert!(
output.as_f64_slice().is_none(),
"NaN output must be nullable"
);
assert!(output.validity().get(0));
assert!(!output.validity().get(1));
assert!(output.validity().get(2));
assert!(output.validity().get(3));
assert!(output.validity().get(4));
assert_eq!(output.values()[0], Scalar::Float64(2.0));
assert!(output.values()[1].is_missing());
assert_eq!(
output.values()[2].to_f64().map(f64::to_bits),
Ok((-0.0_f64).to_bits())
);
assert_eq!(output.values()[3], Scalar::Float64(0.0));
assert_eq!(output.values()[4], Scalar::Float64(f64::INFINITY));
let ints = Column::from_i64_values_owned(vec![9, -1]);
let ints_out = ints.sqrt().expect("int sqrt");
assert_eq!(ints_out.values()[0], Scalar::Float64(3.0));
assert!(ints_out.values()[1].is_missing());
assert!(!ints_out.validity().get(1));
}
#[test]
fn log_nullable_owned_preserves_nan_missing_semantics_blackthrush()
-> Result<(), ColumnError> {
let input = Column::from_f64_values(vec![1.0, -1.0, 0.0, f64::INFINITY]);
let output = input.log()?;
assert_eq!(output.dtype(), DType::Float64);
assert_eq!(output.values().len(), 4);
assert!(
output.as_f64_slice().is_none(),
"NaN output must be nullable"
);
assert!(output.validity().get(0));
assert!(!output.validity().get(1));
assert!(output.validity().get(2));
assert!(output.validity().get(3));
assert_eq!(output.values()[0], Scalar::Float64(0.0));
assert!(output.values()[1].is_missing());
assert_eq!(output.values()[2], Scalar::Float64(f64::NEG_INFINITY));
assert_eq!(output.values()[3], Scalar::Float64(f64::INFINITY));
let ints = Column::from_i64_values_owned(vec![1, -1]);
let ints_out = ints.log()?;
assert_eq!(ints_out.values()[0], Scalar::Float64(0.0));
assert!(ints_out.values()[1].is_missing());
assert!(!ints_out.validity().get(1));
Ok(())
}
#[test]
fn floor_ceil_trunc_match_scalar_oracle_61try() {
// Differential vs scalar f64 oracles (br-frankenpandas-61try).
// Seeded LCG, no mocks.
fn next(seed: &mut u64) -> u64 {
*seed = seed
.wrapping_mul(3202034522624059733)
.wrapping_add(4354685564936845319);
*seed
}
fn floor_oracle(v: f64) -> f64 {
v.floor()
}
fn ceil_oracle(v: f64) -> f64 {
v.ceil()
}
fn trunc_oracle(v: f64) -> f64 {
v.trunc()
}
let mut seed = 0x61d1_ff10_0ce1_cafe_u64;
for case in 0..240 {
let len = (next(&mut seed) % 59 + 1) as usize;
let mut values = Vec::with_capacity(len);
for _ in 0..len {
let selector = next(&mut seed) % 37;
let whole = (next(&mut seed) % 500_001) as i64 - 250_000;
let frac = (next(&mut seed) % 100_000) as f64 / 100_000.0;
let sign = if next(&mut seed) & 1 == 0 { 1.0 } else { -1.0 };
let value = sign * (whole as f64 / 13.0 + frac);
values.push(match selector {
0 => Scalar::Null(NullKind::NaN),
1 => Scalar::Float64(f64::NAN),
_ => Scalar::Float64(value),
});
}
let input = Column::from_values(values.clone()).expect("column");
type UnaryFloatOutput = (&'static str, Column, fn(f64) -> f64);
let outputs: [UnaryFloatOutput; 3] = [
("floor", input.floor().expect("floor"), floor_oracle),
("ceil", input.ceil().expect("ceil"), ceil_oracle),
("trunc", input.trunc().expect("trunc"), trunc_oracle),
];
for (op, output, oracle) in outputs {
assert_eq!(output.dtype(), DType::Float64, "{op} dtype drift");
assert_eq!(output.values().len(), values.len(), "{op} length drift");
for (pos, (before, after)) in values.iter().zip(output.values()).enumerate() {
if before.is_missing() {
assert!(
after.is_missing(),
"{op} case={case} pos={pos}: missing became {after:?}"
);
continue;
}
let expected = match before {
Scalar::Float64(v) => oracle(*v),
other => panic!("{op} unexpected non-float value: {other:?}"),
};
match after {
Scalar::Float64(got) => assert_eq!(
*got, expected,
"{op} case={case} pos={pos}: got {got}, expected {expected}"
),
other => panic!(
"{op} case={case} pos={pos}: expected Float64, got {other:?}"
),
}
}
}
}
}
#[test]
fn floor_ceil_trunc_integral_identity_preserves_edges_blackthrush() {
let expected = vec![
f64::NEG_INFINITY,
-9.0,
-0.0,
0.0,
7.0,
4_503_599_627_370_496.0,
f64::INFINITY,
];
let input = Column::from_f64_values(expected.clone());
let outputs = [
("floor", input.floor().expect("floor")),
("ceil", input.ceil().expect("ceil")),
("trunc", input.trunc().expect("trunc")),
];
for (op, output) in outputs {
let got = output.as_f64_slice().expect("all-valid float output");
assert_eq!(got.len(), expected.len(), "{op} length drift");
for (pos, (&got, &expected)) in got.iter().zip(&expected).enumerate() {
assert_eq!(
got.to_bits(),
expected.to_bits(),
"{op} pos={pos}: got {got:?}, expected {expected:?}"
);
}
}
}
#[test]
fn isin_returns_bool_column() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let needles = vec![Scalar::Int64(1), Scalar::Int64(3)];
let r = col.isin(&needles).expect("isin");
assert_eq!(r.dtype(), DType::Bool);
assert_eq!(r.values()[0], Scalar::Bool(true));
assert_eq!(r.values()[1], Scalar::Bool(false));
assert_eq!(r.values()[2], Scalar::Bool(true));
assert_eq!(r.values()[3], Scalar::Bool(false));
}
#[test]
fn isin_empty_needles_yields_all_false() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let r = col.isin(&[]).expect("isin");
assert_eq!(r.values()[0], Scalar::Bool(false));
assert_eq!(r.values()[1], Scalar::Bool(false));
}
#[test]
fn isin_nullable_utf8_typed_matches_generic() {
// The typed nullable-Utf8 isin arm (cold cache) must be BIT-EXACT to the
// generic Key path: a present row probes the Utf8-needle set, a MISSING row is
// false (this impl ignores null needles). A/B on identical LazyNullableUtf8
// data: `col_cold` (fresh, cold cache) exercises the typed arm; `col_warm` has
// its Scalar cache pre-materialized so the cold-cache gate defers to the
// generic path. Needles include a null (must NOT flip missing rows to true) and
// a non-Utf8 Int64 (inert). Seeded short strings over {a,b,c,d} + ~25% nulls.
let mut state: u64 = 0x1519_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 300) as usize;
let mut validity = crate::ValidityMask::all_valid(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..n {
if next() % 4 == 0 {
validity.set(i, false);
} else {
let len = (next() % 4) as usize;
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
}
offsets.push(bytes.len());
}
let col_cold = Column::from_utf8_values_with_validity(
bytes.clone(),
offsets.clone(),
validity.clone(),
);
let col_warm =
Column::from_utf8_values_with_validity(bytes, offsets, validity);
let _ = col_warm.values(); // warm cache ⇒ generic path (oracle)
// Needle sets: subset of {a,b,c,d} short strings + a null + an Int64.
let needle_variants: [Vec<Scalar>; 3] = [
vec![],
vec![
Scalar::Utf8("a".to_string()),
Scalar::Utf8("bb".to_string()),
Scalar::Null(NullKind::Null),
Scalar::Int64(7),
],
vec![
Scalar::Utf8(String::new()),
Scalar::Utf8("cd".to_string()),
Scalar::Utf8("ab".to_string()),
],
];
for needles in &needle_variants {
let cold = col_cold.isin(needles).expect("cold isin");
let warm = col_warm.isin(needles).expect("warm isin");
assert_eq!(cold.values(), warm.values(), "trial {trial}");
}
}
}
#[test]
fn isin_nullable_i64_typed_matches_reference() {
// The typed nullable-Int64 isin arm must match FP's isin spec exactly: output is
// all-valid Bool; a PRESENT value is `true` iff its i64 is one of the Int64 needles;
// a MISSING value is `false` regardless of the needles (this impl, not pandas'
// NaN-in-list rule). Null / Float64(int-valued) / Utf8 needles are inert against an
// Int64 value. ~30% nulls; i64::MIN/MAX included. Reference is hand-computed.
let mut state: u64 = 0x1519_15EE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let n = (next() % 300) as usize;
let mut data = vec![0i64; n];
let mut validity = crate::ValidityMask::all_valid(n);
let mut vbits = vec![true; n];
for i in 0..n {
if next() % 3 == 0 {
validity.set(i, false);
vbits[i] = false;
} else {
// small alphabet ⇒ frequent membership hits
data[i] = (next() % 40) as i64 - 20;
}
}
let col = Column::from_i64_values_with_validity(data.clone(), validity);
let needle_variants: [Vec<Scalar>; 3] = [
vec![],
vec![
Scalar::Int64(0),
Scalar::Int64(5),
Scalar::Int64(-10),
Scalar::Null(NullKind::Null),
Scalar::Float64(5.0), // inert vs Int64 value
Scalar::Utf8("5".to_string()), // inert
],
vec![Scalar::Int64(-20), Scalar::Int64(19)],
];
for needles in &needle_variants {
let int_needles: Vec<i64> = needles
.iter()
.filter_map(|s| if let Scalar::Int64(v) = s { Some(*v) } else { None })
.collect();
let expected: Vec<Scalar> = (0..n)
.map(|i| Scalar::Bool(vbits[i] && int_needles.contains(&data[i])))
.collect();
let got = col.isin(needles).expect("isin");
assert_eq!(got.values(), expected, "trial {trial} needles {needles:?}");
}
}
}
}
mod sort_diff_duplicated_between {
use fp_types::NullKind;
use super::*;
#[test]
fn sort_values_ascending_puts_nulls_last() {
let col = Column::from_values(vec![
Scalar::Int64(3),
Scalar::Null(NullKind::NaN),
Scalar::Int64(1),
Scalar::Int64(2),
])
.expect("col");
let s = col.sort_values(true).expect("sort");
assert_eq!(s.values()[0], Scalar::Int64(1));
assert_eq!(s.values()[1], Scalar::Int64(2));
assert_eq!(s.values()[2], Scalar::Int64(3));
assert!(s.values()[3].is_missing());
}
#[test]
fn sort_values_descending_keeps_nulls_last() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(3),
Scalar::Int64(2),
])
.expect("col");
let s = col.sort_values(false).expect("sort");
assert_eq!(s.values()[0], Scalar::Int64(3));
assert_eq!(s.values()[1], Scalar::Int64(2));
assert_eq!(s.values()[2], Scalar::Int64(1));
assert!(s.values()[3].is_missing());
}
#[test]
fn argsort_matches_take_sort_values() {
let col =
Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(1), Scalar::Int64(2)])
.expect("col");
let positions = col.argsort();
assert_eq!(positions, vec![1, 2, 0]);
let via_take = col.take(&positions).expect("take");
let via_sort = col.sort_values(true).expect("sort");
assert_eq!(via_take.values(), via_sort.values());
}
// Naive comparator reference (the pre-radix Scalar path) for isomorphism
// proofs: rebuilds the sorted Scalar vec exactly as the old code did.
fn scalar_sort_reference(values: &[Scalar], ascending: bool) -> Vec<Scalar> {
let mut indexed: Vec<(usize, &Scalar)> = values.iter().enumerate().collect();
indexed.sort_by(|a, b| crate::compare_scalars_na_last(a.1, b.1, ascending));
indexed.into_iter().map(|(_, v)| v.clone()).collect()
}
#[test]
fn datetime64_sort_values_matches_scalar_reference() {
// Datetime64 sort_values: the no-NaT radix path AND the NaT-bearing
// fallback must both equal the stable scalar comparator reference
// (exact ns order, first-seen ties, NaT→end), both directions.
let mut state: u64 = 0x5151_2626_3737_4848;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let n = (next() % 400) as usize + 1;
let ns: Vec<i64> = (0..n)
.map(|_| match next() % 9 {
0 => i64::MIN, // NaT (only some trials → exercises fallback)
1 => (next() % 5) as i64, // ties
_ => (next() % 1_000_000) as i64 * 1_000_000,
})
.collect();
let col = Column::from_datetime64_values(ns.clone());
let scalars: Vec<Scalar> = ns.iter().map(|&v| Scalar::Datetime64(v)).collect();
for asc in [true, false] {
let got = col.sort_values(asc).expect("sort").values().to_vec();
let expected = scalar_sort_reference(&scalars, asc);
assert_eq!(got, expected, "trial {trial} asc={asc}");
}
}
}
#[test]
fn radix_sort_matches_scalar_reference_i64_and_f64() {
// Deterministic LCG covering negatives, zero, duplicates (tie
// stability), and large magnitudes — the typed radix path must be
// BIT-IDENTICAL to the stable Scalar comparator path, both orders.
let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let n = (next() % 400) as usize + 1;
let i64_vals: Vec<Scalar> = (0..n)
.map(|_| {
// Narrow range forces frequent ties; occasional wide value.
let r = next();
let v = if r % 7 == 0 {
r as i64 // full-width incl negatives via wraparound
} else {
(r % 11) as i64 - 5
};
Scalar::Int64(v)
})
.collect();
let f64_vals: Vec<Scalar> = i64_vals
.iter()
.map(|s| match s {
Scalar::Int64(v) => {
// Map into floats incl negatives, zero, fractional ties.
let f = (*v as f64) / 4.0;
Scalar::Float64(if f == 0.0 { 0.0 } else { f })
}
_ => unreachable!(),
})
.collect();
for (vals, label) in [(&i64_vals, "i64"), (&f64_vals, "f64")] {
let col = Column::from_values(vals.clone()).expect("col");
// Skip if any value became missing (NaN guard not exercised here).
assert!(
col.validity.all(),
"{label} trial {trial}: unexpected missing"
);
for ascending in [true, false] {
let got = col.sort_values(ascending).expect("sort").values().to_vec();
let want = scalar_sort_reference(vals, ascending);
assert_eq!(
got, want,
"{label} trial {trial} asc={ascending} sort mismatch"
);
}
// argsort (ascending) must reproduce the stable permutation.
let perm = col.argsort();
let via_perm: Vec<Scalar> = perm.iter().map(|&i| vals[i].clone()).collect();
assert_eq!(
via_perm,
scalar_sort_reference(vals, true),
"{label} trial {trial} argsort mismatch"
);
}
}
}
#[test]
fn sort_values_nullable_i64_f64_matches_na_last_scalar_reference() {
// sort_values on a nullable Int64/Float64 column now routes through the
// O(n) typed_radix_perm + scalar gather instead of the O(n log n) na-last
// Scalar comparator. The RESULT VALUES must stay bit-identical to that
// comparator's stable sort. Null-missing only (no present-NaN) so the
// gathered scalars compare with structural eq. Deterministic LCG.
let mut state: u64 = 0x7EED_1234_ABCD_5678;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let len = (next() % 300) as usize + 1;
let mut vi = crate::ValidityMask::all_valid(len);
let mut vf = crate::ValidityMask::all_valid(len);
let idata: Vec<i64> = (0..len)
.map(|i| {
let r = next();
if r % 5 == 0 {
vi.set(i, false);
}
(r % 11) as i64 - 5
})
.collect();
let fdata: Vec<f64> = (0..len)
.map(|i| {
let r = next();
if r % 5 == 0 {
vf.set(i, false);
0.0
} else {
((r % 11) as f64 - 5.0) / 2.0
}
})
.collect();
let icol = Column::from_i64_values_with_validity(idata, vi);
let fcol = Column::from_f64_values_with_validity(fdata, vf);
for (col, tag) in [(&icol, "i64"), (&fcol, "f64")] {
let vals = col.values().to_vec();
for ascending in [true, false] {
// Reference == the pre-change generic fallthrough.
let mut want: Vec<&Scalar> = vals.iter().collect();
want.sort_by(|a, b| {
crate::compare_scalars_na_last(a, b, ascending)
});
let want: Vec<Scalar> = want.into_iter().cloned().collect();
assert_eq!(
col.sort_values(ascending).expect("sort_values").values(),
want.as_slice(),
"{tag} trial {trial} asc={ascending}"
);
}
}
}
}
#[test]
fn argsort_with_nullable_utf8_matches_na_last_scalar_reference() {
// argsort_with on a nullable contiguous-Utf8 column now uses the MSD byte radix
// over present spans + na-last suffix. The PERMUTATION must be bit-identical to
// the stable na-last Scalar comparator (compare_scalars_na_last) — which backs
// Series/DataFrame sort_values/sort_index/argsort on a nullable string key.
// Tiny alphabet {a,b,c,d} + short lengths ⇒ frequent ties (stability matters);
// ~25% nulls; both directions. Deterministic LCG.
let mut state: u64 = 0xA5C0_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let len = (next() % 300) as usize + 1;
let mut v = crate::ValidityMask::all_valid(len);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..len {
if next() % 4 == 0 {
v.set(i, false);
} else {
let slen = (next() % 4) as usize;
let s: String = (0..slen)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
}
offsets.push(bytes.len());
}
let col = Column::from_utf8_values_with_validity(bytes, offsets, v);
let vals = col.values().to_vec();
for ascending in [true, false] {
let mut want: Vec<usize> = (0..vals.len()).collect();
// Stable sort_by == the generic argsort_with fallthrough.
want.sort_by(|&a, &b| {
crate::compare_scalars_na_last(&vals[a], &vals[b], ascending)
});
assert_eq!(
col.argsort_with(ascending),
want,
"argsort perm trial {trial} asc={ascending}"
);
}
}
}
#[test]
fn sort_values_nullable_utf8_matches_na_last_scalar_reference() {
// sort_values on a nullable contiguous-Utf8 column now routes through the MSD
// byte radix over present spans + a na-last contiguous gather instead of the
// O(n log n) na-last Scalar comparator. The RESULT VALUES must stay
// bit-identical to that comparator's stable sort for BOTH directions. Tiny
// alphabet {a,b,c,d} + short lengths ⇒ frequent ties (stability matters);
// ~25% nulls (na-last). Deterministic LCG.
let mut state: u64 = 0x5027_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let len = (next() % 300) as usize + 1;
let mut v = crate::ValidityMask::all_valid(len);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..len {
if next() % 4 == 0 {
v.set(i, false);
} else {
let slen = (next() % 4) as usize;
let s: String = (0..slen)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
}
offsets.push(bytes.len());
}
let col = Column::from_utf8_values_with_validity(bytes, offsets, v);
let vals = col.values().to_vec();
for ascending in [true, false] {
let mut want: Vec<&Scalar> = vals.iter().collect();
want.sort_by(|a, b| crate::compare_scalars_na_last(a, b, ascending));
let want: Vec<Scalar> = want.into_iter().cloned().collect();
assert_eq!(
col.sort_values(ascending).expect("sort_values").values(),
want.as_slice(),
"utf8 trial {trial} asc={ascending}"
);
}
}
}
#[test]
fn sort_values_temporal_dt64_td64_matches_na_last_scalar_reference() {
// sort_values on a nullable Datetime64/Timedelta64 column now typed-
// gathers via from_*_with_validity. Result must stay bit-identical to
// the na-last Scalar comparator, INCLUDING present-NaT (i64::MIN at a
// valid slot ⇒ Datetime64/Timedelta64(i64::MIN), is_missing ⇒ na-last).
// Integer/Null scalars only ⇒ structural eq is well-defined.
let mut state: u64 = 0x7104_DA7E_9001_4242;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let len = (next() % 300) as usize + 1;
let mut vd = crate::ValidityMask::all_valid(len);
let mut vt = crate::ValidityMask::all_valid(len);
let ddata: Vec<i64> = (0..len)
.map(|i| {
let r = next();
match r % 6 {
0 => {
vd.set(i, false);
55
}
1 => i64::MIN, // present-NaT
_ => (r % 8) as i64 * 100, // ties
}
})
.collect();
let tdata: Vec<i64> = (0..len)
.map(|i| {
let r = next();
match r % 6 {
0 => {
vt.set(i, false);
66
}
1 => i64::MIN,
_ => (r % 8) as i64 * 50,
}
})
.collect();
let dcol = Column::from_datetime64_values_with_validity(ddata, vd);
let tcol = Column::from_timedelta64_values_with_validity(tdata, vt);
for (col, tag) in [(&dcol, "dt64"), (&tcol, "td64")] {
let vals = col.values().to_vec();
for ascending in [true, false] {
let mut want: Vec<&Scalar> = vals.iter().collect();
want.sort_by(|a, b| crate::compare_scalars_na_last(a, b, ascending));
let want: Vec<Scalar> = want.into_iter().cloned().collect();
assert_eq!(
col.sort_values(ascending).expect("sort_values").values(),
want.as_slice(),
"{tag} trial {trial} asc={ascending}"
);
}
}
}
}
#[test]
fn nullable_int64_sort_na_last_radix_matches_scalar_reference_cf() {
// Nullable Int64 na-last radix permutation must be BIT-IDENTICAL to the
// stable `compare_scalars_na_last` comparator, both orders: present
// values by i64 order (ties keep original index order), every missing
// slot LAST in original order. Deterministic LCG with ~20% missing and
// a narrow value range to force ties.
let mut state: u64 = 0x1357_9BDF_2468_ACE0;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let n = (next() % 300) as usize + 1;
let data: Vec<i64> = (0..n)
.map(|_| {
let r = next();
if r % 7 == 0 {
r as i64
} else {
(r % 11) as i64 - 5
}
})
.collect();
let mut validity = ValidityMask::all_valid(n);
for i in 0..n {
if next() % 5 == 0 {
validity.set(i, false);
}
}
let col = Column::from_i64_values_with_validity(data, validity);
let vals = col.values();
for ascending in [true, false] {
let mut want: Vec<usize> = (0..vals.len()).collect();
want.sort_by(|&a, &b| {
crate::compare_scalars_na_last(&vals[a], &vals[b], ascending)
});
assert_eq!(
col.argsort_with(ascending),
want,
"trial {trial} asc={ascending}"
);
}
}
}
#[test]
fn nullable_float64_sort_na_last_radix_matches_scalar_reference_cf() {
// Nullable / NaN-bearing Float64 na-last radix permutation must be
// BIT-IDENTICAL to the stable compare_scalars_na_last comparator, both
// orders. A slot is na-last iff missing OR present-NaN (both is_missing).
// Mixes Null-missing (from_f64_values_with_validity) and present-NaN
// (raw NaN in the buffer), plus ±inf, -0.0/+0.0 ties, and value ties.
let mut state: u64 = 0x2468_ACE0_1357_9BDF;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let n = (next() % 300) as usize + 1;
let mut validity = ValidityMask::all_valid(n);
let data: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 13 {
0 => {
validity.set(i, false);
0.0 // Null-missing slot (sentinel)
}
1 => f64::NAN, // present-NaN ⇒ na-last too
2 => f64::INFINITY,
3 => f64::NEG_INFINITY,
4 => -0.0,
_ => ((r % 11) as f64 - 5.0) / 2.0, // ties + negatives
}
})
.collect();
let col = Column::from_f64_values_with_validity(data, validity);
let vals = col.values();
for ascending in [true, false] {
let mut want: Vec<usize> = (0..vals.len()).collect();
want.sort_by(|&a, &b| {
crate::compare_scalars_na_last(&vals[a], &vals[b], ascending)
});
assert_eq!(
col.argsort_with(ascending),
want,
"trial {trial} asc={ascending}"
);
}
}
}
#[test]
fn nullable_temporal_sort_na_last_radix_matches_scalar_reference_cf() {
// Nullable / NaT-bearing Datetime64 & Timedelta64 na-last radix
// permutation must be BIT-IDENTICAL to the stable compare_scalars_na_last
// comparator, both orders. na-last iff validity-clear OR datum == i64::MIN
// (NaT sentinel). Mixes Null-missing (validity false) and present-NaT
// (i64::MIN at a valid slot) plus ns ties.
let mut state: u64 = 0x0F1E_2D3C_4B5A_6978;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let n = (next() % 300) as usize + 1;
let mut validity = ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
match r % 11 {
0 => {
validity.set(i, false);
12_345 // Null-missing (validity false)
}
1 => i64::MIN, // present-NaT (validity true, sentinel)
_ => 1_600_000_000_000i64 + ((r % 17) as i64) * 1_000,
}
})
.collect();
for dt64 in [true, false] {
let col = if dt64 {
Column::from_datetime64_values_with_validity(data.clone(), validity.clone())
} else {
Column::from_timedelta64_values_with_validity(data.clone(), validity.clone())
};
let vals = col.values();
for ascending in [true, false] {
let mut want: Vec<usize> = (0..vals.len()).collect();
want.sort_by(|&a, &b| {
crate::compare_scalars_na_last(&vals[a], &vals[b], ascending)
});
assert_eq!(
col.argsort_with(ascending),
want,
"dt64={dt64} trial {trial} asc={ascending}"
);
}
}
}
}
#[test]
fn contiguous_utf8_argsort_matches_scalar_reference() {
let raw = ["bee", "alpha", "bee", "alphabet", "", "zulu"];
let scalars: Vec<Scalar> = raw
.iter()
.map(|value| Scalar::Utf8((*value).to_owned()))
.collect();
let scalar_col = Column::from_values(scalars.clone()).expect("scalar col");
let mut bytes = Vec::new();
let mut offsets = Vec::with_capacity(raw.len() + 1);
offsets.push(0);
for value in raw {
bytes.extend_from_slice(value.as_bytes());
offsets.push(bytes.len());
}
let contiguous_col = Column::from_utf8_contiguous(bytes, offsets);
assert_eq!(contiguous_col.argsort_with(true), vec![4, 1, 3, 0, 2, 5]);
assert_eq!(contiguous_col.argsort_with(false), vec![5, 0, 2, 3, 1, 4]);
for ascending in [true, false] {
let got = contiguous_col
.sort_values(ascending)
.expect("contiguous sort")
.values()
.to_vec();
let want = scalar_col
.sort_values(ascending)
.expect("scalar sort")
.values()
.to_vec();
assert_eq!(got, want, "ascending={ascending}");
}
}
#[test]
fn parallel_msd_radix_matches_serial_reference_qdrp7() {
// n above PAR_MIN (1<<15) exercises the parallel fan-out path.
// Common "key_" prefix forces serial descent before the fan-out
// (the bench shape). Compare to a stable byte-lexicographic sort.
let n = 40_000usize;
let strings: Vec<String> = (0..n)
.map(|i| {
let mixed = (i as u64)
.wrapping_mul(0x9E37_79B9_7F4A_7C15)
.rotate_left(17)
^ (i as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9);
format!("key_{mixed:016x}_{:04}", i % 97)
})
.collect();
let spans: Vec<&[u8]> = strings.iter().map(|s| s.as_bytes()).collect();
for ascending in [true, false] {
let got = crate::utf8_msd_argsort_bytes(&spans, ascending);
let mut want: Vec<usize> = (0..n).collect();
want.sort_by(|&a, &b| {
let ord = spans[a].cmp(spans[b]);
if ascending { ord } else { ord.reverse() }
});
assert_eq!(
got, want,
"parallel radix != stable byte sort (asc={ascending})"
);
}
}
#[test]
fn contiguous_utf8_strict_witness_matches_byte_order_483i5() {
fn contiguous(values: &[&str]) -> Column {
let mut bytes = Vec::new();
let mut offsets = Vec::with_capacity(values.len() + 1);
offsets.push(0);
for value in values {
bytes.extend_from_slice(value.as_bytes());
offsets.push(bytes.len());
}
Column::from_utf8_contiguous(bytes, offsets)
}
assert!(
contiguous(&["a", "b", "c"])
.as_strictly_increasing_utf8_contiguous()
.is_some()
);
assert!(
contiguous(&[])
.as_strictly_increasing_utf8_contiguous()
.is_some()
);
assert!(
contiguous(&["only"])
.as_strictly_increasing_utf8_contiguous()
.is_some()
);
assert!(
contiguous(&["a", "a"])
.as_strictly_increasing_utf8_contiguous()
.is_none()
);
assert!(
contiguous(&["b", "a"])
.as_strictly_increasing_utf8_contiguous()
.is_none()
);
let scalar_backed = Column::from_values(vec![
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
])
.expect("scalar-backed utf8");
assert!(
scalar_backed
.as_strictly_increasing_utf8_contiguous()
.is_none()
);
}
#[test]
fn contiguous_utf8_lower_hex_sequence_certificate_jbyuc111111() {
fn contiguous(values: &[&str]) -> Column {
let mut bytes = Vec::new();
let mut offsets = Vec::with_capacity(values.len() + 1);
offsets.push(0);
for value in values {
bytes.extend_from_slice(value.as_bytes());
offsets.push(bytes.len());
}
Column::from_utf8_contiguous(bytes, offsets)
}
let certified = contiguous(&["id_0000000a", "id_0000000b", "id_0000000c"]);
let (_, _, certificate) = certified
.as_lower_hex_sequence_utf8_contiguous()
.expect("lower-hex sequence certificate");
assert_eq!(certificate.prefix_len(), 3);
assert_eq!(certificate.hex_width(), 8);
assert_eq!(certificate.width(), 11);
assert_eq!(certificate.start(), 10);
assert_eq!(certificate.value_at(2), Some(12));
assert!(
contiguous(&["id_0000000a", "id_0000000c"])
.as_lower_hex_sequence_utf8_contiguous()
.is_none(),
"gapped sequences are not certified"
);
assert!(
contiguous(&["id_0000000a", "id_0000000B"])
.as_lower_hex_sequence_utf8_contiguous()
.is_none(),
"uppercase hex is not certified by the lowercase witness"
);
assert!(
contiguous(&["0000000a", "0000000b"])
.as_lower_hex_sequence_utf8_contiguous()
.is_none(),
"a prefix is required so arbitrary all-hex strings fall back"
);
}
#[test]
fn lower_hex_sequence_constructor_matches_contiguous_utf8_3wo1d() {
let seeded =
Column::from_lower_hex_sequence_utf8(b"id_", 0x0a, 3, 8).expect("seeded column");
let manual = {
let values = ["id_0000000a", "id_0000000b", "id_0000000c"];
let mut bytes = Vec::new();
let mut offsets = Vec::with_capacity(values.len() + 1);
offsets.push(0);
for value in values {
bytes.extend_from_slice(value.as_bytes());
offsets.push(bytes.len());
}
Column::from_utf8_contiguous(bytes, offsets)
};
assert_eq!(seeded.values(), manual.values());
let (_, _, certificate) = seeded
.as_lower_hex_sequence_utf8_contiguous()
.expect("seeded certificate");
assert_eq!(certificate.prefix_len(), 3);
assert_eq!(certificate.hex_width(), 8);
assert_eq!(certificate.width(), 11);
assert_eq!(certificate.start(), 10);
assert_eq!(certificate.value_at(2), Some(12));
let empty =
Column::from_lower_hex_sequence_utf8(b"id_", 0x0a, 0, 8).expect("empty column");
assert!(empty.values().is_empty());
assert!(empty.as_lower_hex_sequence_utf8_contiguous().is_none());
let (empty_prefix, empty_certificate, empty_len) = empty
.as_lower_hex_sequence_utf8()
.expect("empty direct witness");
assert_eq!(empty_prefix, b"id_");
assert_eq!(empty_certificate.start(), 10);
assert_eq!(empty_len, 0);
assert!(Column::from_lower_hex_sequence_utf8(b"id_", 0x0e, 3, 1).is_none());
assert!(Column::from_lower_hex_sequence_utf8(b"", 0x0a, 3, 8).is_none());
}
#[test]
fn lower_hex_sequence_witness_stays_lazy_uza0447() {
let column =
Column::from_lower_hex_sequence_utf8(b"id_", 0x0a, 3, 8).expect("seeded column");
assert!(matches!(
&column.values,
ScalarValues::LazyLowerHexSequenceUtf8 { .. }
));
let ScalarValues::LazyLowerHexSequenceUtf8 { buffers, .. } = &column.values else {
return;
};
assert!(buffers.get().is_none());
let (prefix, certificate, len) =
column.as_lower_hex_sequence_utf8().expect("direct witness");
assert_eq!(prefix, b"id_");
assert_eq!(certificate.prefix_len(), 3);
assert_eq!(certificate.hex_width(), 8);
assert_eq!(certificate.start(), 10);
assert_eq!(len, 3);
assert!(
buffers.get().is_none(),
"direct witness must not materialize bytes"
);
let (_, _, contiguous_certificate) = column
.as_lower_hex_sequence_utf8_contiguous()
.expect("contiguous materialization");
assert_eq!(contiguous_certificate, certificate);
assert!(
buffers.get().is_some(),
"contiguous accessor materializes exact old byte layout"
);
}
#[test]
fn lower_hex_sequence_constructor_preserves_carry_uza0446() {
let seeded =
Column::from_lower_hex_sequence_utf8(b"id_", 0x0e, 4, 2).expect("seeded column");
let manual = {
let values = ["id_0e", "id_0f", "id_10", "id_11"];
let mut bytes = Vec::new();
let mut offsets = Vec::with_capacity(values.len() + 1);
offsets.push(0);
for value in values {
bytes.extend_from_slice(value.as_bytes());
offsets.push(bytes.len());
}
Column::from_utf8_contiguous(bytes, offsets)
};
assert_eq!(seeded.values(), manual.values());
let (_, _, certificate) = seeded
.as_lower_hex_sequence_utf8_contiguous()
.expect("seeded certificate");
assert_eq!(certificate.prefix_len(), 3);
assert_eq!(certificate.hex_width(), 2);
assert_eq!(certificate.width(), 5);
assert_eq!(certificate.start(), 14);
assert_eq!(certificate.value_at(3), Some(17));
}
#[test]
fn abs_typed_matches_scalar_reference() {
// The typed abs fast path must be bit-identical to the Scalar loop
// for all-valid Int64/Float64, incl i64::MIN (wrapping_abs) and
// -0.0/large floats.
let mut state: u64 = 0x2545_F491_4F6C_DD1D;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..150 {
let n = (next() % 300) as usize + 1;
let i64_vals: Vec<Scalar> = (0..n)
.map(|_| {
let r = next();
if r % 50 == 0 {
Scalar::Int64(i64::MIN)
} else {
Scalar::Int64((r % 2000) as i64 - 1000)
}
})
.collect();
let f64_vals: Vec<Scalar> = i64_vals
.iter()
.map(|s| match s {
Scalar::Int64(v) => {
let f = if *v == i64::MIN {
-0.0
} else {
*v as f64 / 4.0
};
Scalar::Float64(f)
}
_ => unreachable!(),
})
.collect();
for vals in [&i64_vals, &f64_vals] {
let col = Column::from_values(vals.clone()).expect("col");
let got = col.abs().expect("abs").values().to_vec();
let want: Vec<Scalar> = vals
.iter()
.map(|v| match v {
Scalar::Int64(x) => Scalar::Int64(x.wrapping_abs()),
Scalar::Float64(x) => Scalar::Float64(x.abs()),
other => other.clone(),
})
.collect();
// Float abs of -0.0 → 0.0; compare by bits for floats.
for (g, w) in got.iter().zip(&want) {
match (g, w) {
(Scalar::Float64(a), Scalar::Float64(b)) => {
assert_eq!(a.to_bits(), b.to_bits(), "trial {trial} float abs")
}
_ => assert_eq!(g, w, "trial {trial} abs"),
}
}
}
}
}
#[test]
fn neg_nullable_f64_preserves_mask_and_scalar_view() {
let data = vec![1.25, -0.0, 5.0, f64::INFINITY, -7.5, f64::NEG_INFINITY];
let valid = [true, false, true, true, false, true];
let mut mask = ValidityMask::all_valid(data.len());
for (idx, is_valid) in valid.iter().copied().enumerate() {
if !is_valid {
mask.set(idx, false);
}
}
let col = Column::from_f64_values_with_validity(data.clone(), mask);
let got = col.neg().expect("nullable neg");
let values = got.values();
for (idx, is_valid) in valid.iter().copied().enumerate() {
if is_valid {
match &values[idx] {
Scalar::Float64(value) => {
assert_eq!(value.to_bits(), (-data[idx]).to_bits(), "idx {idx}");
}
other => panic!("expected Float64 at {idx}, got {other:?}"),
}
} else {
assert!(values[idx].is_missing(), "idx {idx} must stay missing");
}
}
let (_, out_mask) = got
.as_f64_slice_with_validity()
.expect("typed nullable output");
for (idx, is_valid) in valid.iter().copied().enumerate() {
assert_eq!(out_mask.get(idx), is_valid, "validity idx {idx}");
}
}
#[test]
fn neg_nullable_int64_typed_matches_reference_cf() {
// Nullable Int64 neg routes through the typed as_i64_slice_with_validity
// arm: present ⇒ Int64(wrapping_neg); missing ⇒ Null; dtype preserved;
// i64::MIN neg wraps to i64::MIN (matching the loop's wrapping_neg).
let mut validity = ValidityMask::all_valid(5);
validity.set(1, false);
validity.set(3, false);
let col =
Column::from_i64_values_with_validity(vec![-3, 0, i64::MIN, 7, -5], validity);
let r = col.neg().expect("neg");
assert_eq!(r.dtype(), DType::Int64);
let v = r.values();
assert_eq!(v[0], Scalar::Int64(3));
assert!(matches!(v[1], Scalar::Null(_)), "missing stays missing");
assert_eq!(v[2], Scalar::Int64(i64::MIN.wrapping_neg()));
assert!(matches!(v[3], Scalar::Null(_)));
assert_eq!(v[4], Scalar::Int64(5));
}
#[test]
#[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
fn abs_typed_timing_vs_scalar() {
use std::time::Instant;
let n = 5_000_000usize;
let iters = 10;
let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let data: Vec<f64> = (0..n)
.map(|_| (next() % 2_000_000) as f64 - 1_000_000.0)
.collect();
let mk = || Column::from_f64_values(data.clone());
let t0 = Instant::now();
let mut chk = 0usize;
for _ in 0..iters {
chk ^= mk().abs().unwrap().len();
}
let typed = t0.elapsed();
let t1 = Instant::now();
let mut chk2 = 0usize;
for _ in 0..iters {
let col = mk();
let out: Vec<Scalar> = col
.values()
.iter()
.map(|v| match v {
Scalar::Float64(x) => Scalar::Float64(x.abs()),
other => other.clone(),
})
.collect();
chk2 ^= Column::new(DType::Float64, out).unwrap().len();
}
let scalar = t1.elapsed();
let t2 = Instant::now();
let mut sink = 0usize;
for _ in 0..iters {
sink ^= mk().len();
}
let build = t2.elapsed();
let typed_op = typed.saturating_sub(build).as_secs_f64();
let scalar_op = scalar.saturating_sub(build).as_secs_f64();
eprintln!(
"abs 5M f64 x{iters}: typed={typed:?} scalar={scalar:?} build={build:?} \
op-only ratio={:.2}x (full {:.2}x, chk {chk}/{chk2}/{sink})",
scalar_op / typed_op,
scalar.as_secs_f64() / typed.as_secs_f64()
);
}
#[test]
fn factorize_direct_address_matches_reference() {
// Independent O(n^2) first-seen reference (linear position scan, no
// hashing/direct-address) for bounded-range all-valid Int64. The
// direct-address fast path must be bit-identical for codes AND
// uniques, both sort modes (use_na_sentinel is moot — all valid).
let mut state: u64 = 0x51A4_3C29_7E10_BB67;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..150 {
let n = (next() % 300) as usize + 1;
let data: Vec<i64> = (0..n).map(|_| (next() % 13) as i64 - 6).collect();
for sort in [false, true] {
// Reference: first-seen codes via linear scan, then optional
// stable sort of uniques + code remap.
let mut uniques: Vec<i64> = Vec::new();
let mut codes: Vec<i64> = Vec::with_capacity(n);
for &v in &data {
match uniques.iter().position(|&u| u == v) {
Some(p) => codes.push(p as i64),
None => {
codes.push(uniques.len() as i64);
uniques.push(v);
}
}
}
if sort {
let mut order: Vec<usize> = (0..uniques.len()).collect();
order.sort_by(|&a, &b| uniques[a].cmp(&uniques[b]));
let mut remap = vec![0i64; uniques.len()];
let sorted: Vec<i64> = order
.iter()
.enumerate()
.map(|(new_pos, &orig)| {
remap[orig] = new_pos as i64;
uniques[orig]
})
.collect();
for c in &mut codes {
*c = remap[*c as usize];
}
uniques = sorted;
}
let col = Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
.expect("col");
let (code_col, uniq_col) =
col.factorize_with_options(sort, true).expect("factorize");
let got_codes: Vec<i64> = code_col
.values()
.iter()
.filter_map(|v| match v {
Scalar::Int64(c) => Some(*c),
_ => None,
})
.collect();
let got_uniques: Vec<i64> = uniq_col
.values()
.iter()
.filter_map(|v| match v {
Scalar::Int64(c) => Some(*c),
_ => None,
})
.collect();
assert_eq!(got_codes.len(), code_col.len(), "non-int code");
assert_eq!(got_uniques.len(), uniq_col.len(), "non-int unique");
assert_eq!(got_codes, codes, "trial {trial} sort={sort} codes");
assert_eq!(got_uniques, uniques, "trial {trial} sort={sort} uniques");
}
}
}
#[test]
fn factorize_datetime64_open_addressing_and_nat_fallthrough() {
// All-valid, no-NaT Datetime64 takes the open-addressing ns factorize,
// re-tagging uniques as Datetime64. Codes = first-seen; uniques carry
// the ns. (default factorize: sort=false, use_na_sentinel=true.)
let ns = vec![
100i64,
100,
7_000_000_000_000_000_000,
5,
7_000_000_000_000_000_000,
5,
];
let col = Column::from_datetime64_values(ns);
let (codes, uniques) = col.factorize().expect("factorize");
let got_codes: Vec<i64> = codes
.values()
.iter()
.map(|v| match v {
Scalar::Int64(c) => *c,
o => panic!("code not int: {o:?}"),
})
.collect();
assert_eq!(got_codes, vec![0, 0, 1, 2, 1, 2]);
let got_uniques: Vec<i64> = uniques
.values()
.iter()
.map(|v| match v {
Scalar::Datetime64(x) => *x,
o => panic!("unique not datetime: {o:?}"),
})
.collect();
assert_eq!(got_uniques, vec![100, 7_000_000_000_000_000_000, 5]);
// NaT (i64::MIN) datum must fall through to the generic path, which
// codes NaT as -1 under use_na_sentinel=true (NOT a real unique).
let with_nat = Column::from_datetime64_values(vec![i64::MIN, 5, 5, i64::MIN, 7]);
let (codes2, uniques2) = with_nat.factorize().expect("factorize nat");
let got_codes2: Vec<i64> = codes2
.values()
.iter()
.map(|v| match v {
Scalar::Int64(c) => *c,
o => panic!("code not int: {o:?}"),
})
.collect();
assert_eq!(got_codes2, vec![-1, 0, 0, -1, 1], "NaT -> -1 sentinel");
assert_eq!(uniques2.len(), 2, "NaT must not become a unique");
}
#[test]
fn factorize_wide_i64_open_addressing_matches_reference() {
// Force the wide/sparse open-addressing path (range >> n*16, so
// i64_direct_address_range declines) and check codes + uniques vs the
// O(n^2) first-seen reference, both sort modes, with the i64::MIN
// empty-sentinel value present and duplicated.
let pool: [i64; 7] = [
i64::MIN,
i64::MAX,
5_000_000_000_000_000_000,
-5_000_000_000_000_000_000,
0,
1,
-1,
];
let mut state: u64 = 0x1357_9BDF_2468_ACE0;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 250) as usize + 2;
let mut data: Vec<i64> = (0..n)
.map(|_| pool[(next() as usize) % pool.len()])
.collect();
// Guarantee a full-range span so i64_direct_address_range declines
// and the wide open-addressing path always runs.
data[0] = i64::MIN;
data[1] = i64::MAX;
// Confirm the wide path is actually exercised (not dense).
let col = Column::from_i64_values_owned(data.clone());
assert!(
crate::i64_direct_address_range(col.as_i64_slice().unwrap()).is_none(),
"trial {trial}: expected wide (non-direct-address) data"
);
for sort in [false, true] {
let mut uniques: Vec<i64> = Vec::new();
let mut codes: Vec<i64> = Vec::with_capacity(n);
for &v in &data {
match uniques.iter().position(|&u| u == v) {
Some(p) => codes.push(p as i64),
None => {
codes.push(uniques.len() as i64);
uniques.push(v);
}
}
}
if sort {
let mut order: Vec<usize> = (0..uniques.len()).collect();
order.sort_by(|&a, &b| uniques[a].cmp(&uniques[b]));
let mut remap = vec![0i64; uniques.len()];
let sorted: Vec<i64> = order
.iter()
.enumerate()
.map(|(new_pos, &orig)| {
remap[orig] = new_pos as i64;
uniques[orig]
})
.collect();
for c in &mut codes {
*c = remap[*c as usize];
}
uniques = sorted;
}
let (code_col, uniq_col) =
col.factorize_with_options(sort, true).expect("factorize");
let got_codes: Vec<i64> = code_col
.values()
.iter()
.filter_map(|v| match v {
Scalar::Int64(c) => Some(*c),
_ => None,
})
.collect();
let got_uniques: Vec<i64> = uniq_col
.values()
.iter()
.filter_map(|v| match v {
Scalar::Int64(c) => Some(*c),
_ => None,
})
.collect();
assert_eq!(got_codes, codes, "trial {trial} sort={sort} codes");
assert_eq!(got_uniques, uniques, "trial {trial} sort={sort} uniques");
}
}
}
#[test]
fn factorize_wide_i64_growable_fibonacci_rehash_matches_reference() {
// Regression for the factorize_i64_wide fix: many distinct WIDE keys
// varying only in HIGH bits (k << 34, the case the old low-bit `& mask`
// hash clustered) over enough rows (> 1024 distinct) to force growable-
// table rehashes, plus the i64::MIN sentinel. (codes, uniques) must stay
// byte-identical (first-seen, unsorted) to a first-seen reference.
let mut state: u64 = 0x0BAD_F00D_C0FF_EE11;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..40 {
let distinct = 2000 + (next() % 800) as i64;
let n = 12_000usize;
let data: Vec<i64> = (0..n)
.map(|i| {
if i % 500 == 0 {
i64::MIN
} else {
(((next() % distinct as u64) as i64) - distinct / 2) << 34
}
})
.collect();
assert!(crate::i64_direct_address_range(&data).is_none());
let mut uniques: Vec<i64> = Vec::new();
let mut pos: std::collections::HashMap<i64, i64> = std::collections::HashMap::new();
let codes: Vec<i64> = data
.iter()
.map(|&v| {
*pos.entry(v).or_insert_with(|| {
let c = uniques.len() as i64;
uniques.push(v);
c
})
})
.collect();
let (code_col, uniq_col) = Column::from_i64_values_owned(data)
.factorize_with_options(false, true)
.expect("factorize");
let got_codes: Vec<i64> = code_col
.values()
.iter()
.filter_map(|v| match v {
Scalar::Int64(c) => Some(*c),
_ => None,
})
.collect();
let got_uniques: Vec<i64> = uniq_col
.values()
.iter()
.filter_map(|v| match v {
Scalar::Int64(c) => Some(*c),
_ => None,
})
.collect();
assert_eq!(got_codes, codes, "trial {trial} codes");
assert_eq!(got_uniques, uniques, "trial {trial} uniques");
}
}
#[test]
#[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
fn factorize_direct_address_timing_vs_hashmap() {
use std::{collections::HashMap, time::Instant};
let n = 5_000_000usize;
let iters = 10;
for cardinality in [1_000u64, 2_000_000u64] {
let mut state: u64 = 0x2468_ACE0_1357_9BDF ^ cardinality;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let data: Vec<i64> = (0..n).map(|_| (next() % cardinality) as i64).collect();
let col = Column::from_i64_values_owned(data.clone());
let t0 = Instant::now();
let mut chk = 0i64;
for _ in 0..iters {
let (codes, _u) = col.factorize_with_options(false, true).expect("da");
if let Scalar::Int64(c) = &codes.values()[n - 1] {
chk ^= *c;
}
}
let direct = t0.elapsed();
// OLD: HashMap<i64,i64> first-seen code assignment over &[Scalar].
let scalar_col =
Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
.expect("col");
let t1 = Instant::now();
let mut chk2 = 0i64;
for _ in 0..iters {
let mut map: HashMap<i64, i64> = HashMap::new();
let mut uniques = 0i64;
let mut last = 0i64;
for v in scalar_col.values() {
if let Scalar::Int64(i) = v {
let code = *map.entry(*i).or_insert_with(|| {
let c = uniques;
uniques += 1;
c
});
last = code;
}
}
chk2 ^= last;
}
let scalar = t1.elapsed();
eprintln!(
"factorize 5M i64 card={cardinality} x{iters}: direct={direct:?} hashmap={scalar:?} ratio={:.2}x (chk {chk}/{chk2})",
scalar.as_secs_f64() / direct.as_secs_f64()
);
}
}
#[test]
fn duplicated_typed_matches_bruteforce_reference() {
// Independent O(n^2) reference: for keep=first a value is a dup iff
// an equal value occurs earlier; last iff later; none iff any other
// position is equal. Float keys compare on normalized to_bits (so
// -0.0==+0.0) — matching key_of. Proves the typed FxHash fast path
// is bit-identical for all-valid Int64/Float64 columns.
let mut state: u64 = 0xD1B5_4A32_D192_ED03;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let fbits = |f: f64| (if f == 0.0 { 0.0 } else { f }).to_bits();
for trial in 0..150 {
let n = (next() % 300) as usize + 1;
// Narrow value range → many duplicates / ties.
let raw: Vec<i64> = (0..n).map(|_| (next() % 9) as i64 - 4).collect();
let i64_vals: Vec<Scalar> = raw.iter().map(|&v| Scalar::Int64(v)).collect();
let f64_vals: Vec<Scalar> = raw
.iter()
.map(|&v| Scalar::Float64(v as f64 / 2.0))
.collect();
let i64_keys: Vec<i64> = raw.clone();
let f64_keys: Vec<u64> = raw.iter().map(|&v| fbits(v as f64 / 2.0)).collect();
for keep in ["first", "last", "false"] {
// Brute-force references over both key representations.
let bf = |eq_keys: &dyn Fn(usize, usize) -> bool| -> Vec<bool> {
(0..n)
.map(|i| match keep {
"first" => (0..i).any(|j| eq_keys(i, j)),
"last" => (i + 1..n).any(|j| eq_keys(i, j)),
_ => (0..n).any(|j| j != i && eq_keys(i, j)),
})
.collect()
};
let want_i = bf(&|a, b| i64_keys[a] == i64_keys[b]);
let want_f = bf(&|a, b| f64_keys[a] == f64_keys[b]);
let col_i = Column::from_values(i64_vals.clone()).expect("i64 col");
let got_i: Vec<bool> = col_i
.duplicated_keep(keep)
.expect("dup i64")
.values()
.iter()
.map(|v| matches!(v, Scalar::Bool(true)))
.collect();
assert_eq!(got_i, want_i, "i64 trial {trial} keep={keep}");
let col_f = Column::from_values(f64_vals.clone()).expect("f64 col");
let got_f: Vec<bool> = col_f
.duplicated_keep(keep)
.expect("dup f64")
.values()
.iter()
.map(|v| matches!(v, Scalar::Bool(true)))
.collect();
assert_eq!(got_f, want_f, "f64 trial {trial} keep={keep}");
}
}
}
#[test]
#[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
fn duplicated_typed_timing_vs_scalar() {
use std::{collections::HashSet, time::Instant};
let n = 5_000_000usize;
let iters = 10;
// Faithful replica of the OLD path: build the per-value Key enum
// over &[Scalar] and insert into a std (SipHash) HashSet.
#[derive(Hash, PartialEq, Eq)]
enum OldKey {
Int64(i64),
Null,
}
for cardinality in [1_000u64, 2_000_000u64] {
let mut state: u64 = 0x0FED_CBA9_8765_4321 ^ cardinality;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let data: Vec<i64> = (0..n).map(|_| (next() % cardinality) as i64).collect();
let col = Column::from_i64_values_owned(data.clone());
let t0 = Instant::now();
let mut chk = 0usize;
for _ in 0..iters {
let d = col.duplicated_keep("first").expect("typed");
chk ^= d
.values()
.iter()
.filter(|v| matches!(v, Scalar::Bool(true)))
.count();
}
let typed = t0.elapsed();
let scalar_col =
Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
.expect("col");
let t1 = Instant::now();
let mut chk2 = 0usize;
for _ in 0..iters {
let mut seen: HashSet<OldKey> = HashSet::new();
let mut count = 0usize;
for v in scalar_col.values() {
let key = if v.is_missing() {
OldKey::Null
} else if let Scalar::Int64(i) = v {
OldKey::Int64(*i)
} else {
OldKey::Null
};
if !seen.insert(key) {
count += 1;
}
}
chk2 ^= count;
}
let scalar = t1.elapsed();
eprintln!(
"duplicated 5M i64 card={cardinality} x{iters}: typed={typed:?} old_keyenum_siphash={scalar:?} ratio={:.2}x (chk {chk}/{chk2})",
scalar.as_secs_f64() / typed.as_secs_f64()
);
}
}
#[test]
#[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
fn radix_sort_timing_vs_scalar() {
use std::time::Instant;
let n = 5_000_000usize;
let mut state: u64 = 0x1234_5678_9ABC_DEF0;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let data: Vec<i64> = (0..n).map(|_| next() as i64).collect();
let col = Column::from_i64_values_owned(data.clone());
let iters = 10;
let t0 = Instant::now();
let mut checksum = 0i64;
for _ in 0..iters {
let sorted = col.sort_values(true).expect("radix");
checksum ^= match &sorted.values()[0] {
Scalar::Int64(v) => *v,
_ => 0,
};
}
let radix = t0.elapsed();
// Old Scalar comparator path, reproduced inline for the A/B.
let scalar_col = Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
.expect("scalar col");
let t1 = Instant::now();
let mut checksum2 = 0i64;
for _ in 0..iters {
let mut indexed: Vec<(usize, &Scalar)> =
scalar_col.values().iter().enumerate().collect();
indexed.sort_by(|a, b| crate::compare_scalars_na_last(a.1, b.1, true));
if let Scalar::Int64(v) = indexed[0].1 {
checksum2 ^= *v;
}
}
let scalar = t1.elapsed();
eprintln!(
"sort_single 5M i64 x{iters}: radix={radix:?} scalar={scalar:?} ratio={:.2}x (chk {checksum}/{checksum2})",
scalar.as_secs_f64() / radix.as_secs_f64()
);
}
#[test]
fn diff_typed_matches_scalar_path() {
// Typed i64/f64 diff == the Scalar generic path over random data,
// multiple periods (incl. negative), incl. f64 inf (which must fall
// back to the Scalar path, not the typed inf-gated one).
let mut state: u64 = 0x44BB_22DD_66FF_8800;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let vals_eq = |a: &[Scalar], b: &[Scalar]| -> bool {
a.len() == b.len()
&& a.iter().zip(b).all(|(x, y)| match (x, y) {
(Scalar::Float64(p), Scalar::Float64(q)) => p.to_bits() == q.to_bits(),
_ => x == y,
})
};
for _ in 0..200 {
let n = (next() % 300) as usize + 1;
let ivals: Vec<i64> = (0..n).map(|_| (next() % 1000) as i64 - 500).collect();
let ityped = Column::from_i64_values_owned(ivals.clone());
let iscalar =
Column::from_values(ivals.iter().map(|&v| Scalar::Int64(v)).collect())
.expect("i col");
let fvals: Vec<f64> = (0..n)
.map(|_| match next() % 9 {
0 => f64::INFINITY,
1 => f64::NEG_INFINITY,
_ => (next() % 2000) as f64 * 0.25 - 250.0,
})
.collect();
let ftyped = Column::from_f64_values(fvals.clone());
let fscalar =
Column::from_values(fvals.iter().map(|&v| Scalar::Float64(v)).collect())
.expect("f col");
for &p in &[1i64, 2, -1, 3] {
assert!(vals_eq(
ityped.diff(p).unwrap().values(),
iscalar.diff(p).unwrap().values()
));
assert!(vals_eq(
ftyped.diff(p).unwrap().values(),
fscalar.diff(p).unwrap().values()
));
}
}
}
#[test]
fn diff_periods_one_subtracts_prev() {
let col =
Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(8), Scalar::Int64(10)])
.expect("col");
let d = col.diff(1).expect("diff");
assert!(d.values()[0].is_missing());
assert_eq!(d.values()[1], Scalar::Float64(3.0));
assert_eq!(d.values()[2], Scalar::Float64(2.0));
assert_eq!(d.dtype(), DType::Float64);
}
#[test]
fn diff_negative_period_looks_ahead() {
let col =
Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(8), Scalar::Int64(10)])
.expect("col");
let d = col.diff(-1).expect("diff");
assert_eq!(d.values()[0], Scalar::Float64(-3.0));
assert_eq!(d.values()[1], Scalar::Float64(-2.0));
assert!(d.values()[2].is_missing());
}
#[test]
fn diff_timedelta64_returns_timedelta_e607u() {
// Per br-frankenpandas-e607u: Column::diff on Timedelta64 preserves
// Timedelta dtype (was forced to Float64 NaN before via to_f64 catch-all).
let one_hour = 3_600 * 1_000_000_000_i64;
let col = Column::from_values(vec![
Scalar::Timedelta64(one_hour),
Scalar::Timedelta64(3 * one_hour),
Scalar::Timedelta64(2 * one_hour),
])
.expect("col");
let d = col.diff(1).expect("diff");
assert_eq!(d.dtype(), DType::Timedelta64);
assert!(d.values()[0].is_missing()); // first row → NaT
assert_eq!(d.values()[1], Scalar::Timedelta64(2 * one_hour));
assert_eq!(d.values()[2], Scalar::Timedelta64(-one_hour));
}
#[test]
fn diff_timedelta64_nat_propagates_e607u() {
use fp_types::Timedelta;
let one_hour = 3_600 * 1_000_000_000_i64;
let col = Column::from_values(vec![
Scalar::Timedelta64(one_hour),
Scalar::Timedelta64(Timedelta::NAT),
Scalar::Timedelta64(2 * one_hour),
])
.expect("col");
let d = col.diff(1).expect("diff");
assert_eq!(d.dtype(), DType::Timedelta64);
assert!(d.values()[0].is_missing());
assert!(d.values()[1].is_missing()); // NaT current → NaT
assert!(d.values()[2].is_missing()); // NaT previous → NaT
}
#[test]
fn duplicated_wide_i64_first_open_addressing_matches_reference() {
// Wide/sparse all-valid Int64 "first" policy uses
// duplicated_first_i64_wide (open-addressing). Flags must equal a
// HashSet-insert reference across full-range data incl. i64::MIN.
use std::collections::HashSet;
let pool: [i64; 6] = [
i64::MIN,
i64::MAX,
3_000_000_000_000_000_000,
-3_000_000_000_000_000_000,
9,
-9,
];
let mut state: u64 = 0x2468_ACE0_1357_9BDF;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 400) as usize + 2;
let mut data: Vec<i64> = (0..n)
.map(|_| pool[(next() as usize) % pool.len()])
.collect();
data[0] = i64::MIN;
data[1] = i64::MAX;
assert!(
crate::i64_direct_address_range(&data).is_none(),
"trial {trial}: expected wide data"
);
let mut seen = HashSet::new();
let expected: Vec<bool> = data.iter().map(|&v| !seen.insert(v)).collect();
let col = Column::from_i64_values_owned(data);
let got: Vec<bool> = col
.duplicated()
.expect("duplicated")
.values()
.iter()
.map(|v| match v {
Scalar::Bool(b) => *b,
o => panic!("not bool: {o:?}"),
})
.collect();
assert_eq!(got, expected, "trial {trial}");
}
}
#[test]
fn duplicated_and_nunique_wide_growable_fibonacci_rehash_matches_reference() {
// Regression for the duplicated_first_i64_wide + count_distinct_i64_
// singletable fixes: many distinct WIDE keys varying only in HIGH bits
// (k << 34) over enough rows (> 1024 distinct) to force growable-table
// rehashes, plus i64::MIN. `duplicated()` flags and `nunique()` count
// must match HashSet references.
use std::collections::HashSet;
let mut state: u64 = 0x9E37_79B9_1234_5678;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..40 {
let distinct = 2000 + (next() % 800) as i64;
let n = 12_000usize;
let data: Vec<i64> = (0..n)
.map(|i| {
if i % 500 == 0 {
i64::MIN
} else {
(((next() % distinct as u64) as i64) - distinct / 2) << 34
}
})
.collect();
assert!(crate::i64_direct_address_range(&data).is_none());
let mut seen = HashSet::new();
let exp_flags: Vec<bool> = data.iter().map(|&v| !seen.insert(v)).collect();
let exp_nunique = seen.len() as i64;
let col = Column::from_i64_values_owned(data);
let got_flags: Vec<bool> = col
.duplicated()
.expect("duplicated")
.values()
.iter()
.map(|v| match v {
Scalar::Bool(b) => *b,
o => panic!("not bool: {o:?}"),
})
.collect();
assert_eq!(got_flags, exp_flags, "duplicated trial {trial}");
assert_eq!(col.nunique(), Scalar::Int64(exp_nunique), "nunique trial {trial}");
}
}
#[test]
fn duplicated_keep_first() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Int64(3),
Scalar::Int64(2),
])
.expect("col");
let d = col.duplicated().expect("duplicated");
assert_eq!(d.values()[0], Scalar::Bool(false));
assert_eq!(d.values()[1], Scalar::Bool(false));
assert_eq!(d.values()[2], Scalar::Bool(true));
assert_eq!(d.values()[3], Scalar::Bool(false));
assert_eq!(d.values()[4], Scalar::Bool(true));
}
#[test]
fn duplicated_treats_nulls_as_one_bucket() {
let col = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Int64(1),
])
.expect("col");
let d = col.duplicated().expect("duplicated");
assert_eq!(d.values()[0], Scalar::Bool(false));
assert_eq!(d.values()[1], Scalar::Bool(true));
assert_eq!(d.values()[2], Scalar::Bool(false));
}
#[test]
fn duplicated_nullable_i64_first_typed_matches_reference() {
// The typed nullable-Int64 duplicated("first") arm must match the spec: a PRESENT
// value is a duplicate iff its i64 was seen earlier; all MISSING rows share ONE
// bucket (a null duplicates an earlier null). Output all-valid Bool. Hand-computed
// reference over Option<i64> keys (None == the shared null bucket); ~30% nulls +
// small alphabet ⇒ frequent ties and repeated nulls. i64::MIN/MAX included.
let mut state: u64 = 0xD0B1_15EE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let n = (next() % 300) as usize;
let mut data = vec![0i64; n];
let mut validity = crate::ValidityMask::all_valid(n);
let mut vbits = vec![true; n];
for i in 0..n {
if next() % 3 == 0 {
validity.set(i, false);
vbits[i] = false;
} else if next() % 20 == 0 {
data[i] = if next() % 2 == 0 { i64::MIN } else { i64::MAX };
} else {
data[i] = (next() % 30) as i64 - 15;
}
}
let col = Column::from_i64_values_with_validity(data.clone(), validity);
let got = col.duplicated().expect("duplicated");
let mut seen: std::collections::HashSet<Option<i64>> =
std::collections::HashSet::new();
let expected: Vec<Scalar> = (0..n)
.map(|i| {
let key = if vbits[i] { Some(data[i]) } else { None };
Scalar::Bool(!seen.insert(key))
})
.collect();
assert_eq!(got.values(), expected, "trial {trial}");
}
}
#[test]
fn duplicated_nullable_i64_last_typed_matches_reference_a9zs0() {
let cases = [
vec![None],
vec![None, None],
vec![Some(4), None, Some(4), None, Some(-2), Some(4)],
vec![
Some(i64::MIN),
Some(i64::MAX),
None,
Some(i64::MIN),
None,
Some(i64::MAX),
],
];
for (case_idx, case) in cases.into_iter().enumerate() {
let mut data = vec![0; case.len()];
let mut validity = crate::ValidityMask::all_valid(case.len());
for (idx, value) in case.iter().enumerate() {
if let Some(value) = value {
data[idx] = *value;
} else {
validity.set(idx, false);
}
}
let col = Column::from_i64_values_with_validity(data, validity);
let got = col
.duplicated_keep("last")
.expect("nullable Int64 last-duplicate flags");
let mut seen = std::collections::HashSet::new();
let mut expected = vec![Scalar::Bool(false); case.len()];
for idx in (0..case.len()).rev() {
expected[idx] = Scalar::Bool(!seen.insert(case[idx]));
}
assert_eq!(got.values(), expected, "case {case_idx}");
assert!(matches!(
&col.values,
ScalarValues::LazyNullableInt64 { .. }
));
if let ScalarValues::LazyNullableInt64 { values, .. } = &col.values {
assert!(
values.get().is_none(),
"case {case_idx}: typed last scan must not materialize Scalar values",
);
}
}
}
#[test]
fn duplicated_nullable_i64_none_typed_matches_reference_dxh4b() {
let cases = [
vec![None],
vec![None, None],
vec![Some(4), None, Some(4), None, Some(-2), Some(4)],
vec![
Some(i64::MIN),
Some(i64::MAX),
None,
Some(i64::MIN),
None,
Some(i64::MAX),
],
];
for (case_idx, case) in cases.into_iter().enumerate() {
let mut data = vec![0; case.len()];
let mut validity = crate::ValidityMask::all_valid(case.len());
let mut counts = std::collections::HashMap::new();
for (idx, value) in case.iter().enumerate() {
*counts.entry(*value).or_insert(0usize) += 1;
if let Some(value) = value {
data[idx] = *value;
} else {
validity.set(idx, false);
}
}
let col = Column::from_i64_values_with_validity(data, validity);
let got = col
.duplicated_keep("false")
.expect("nullable Int64 keep=False duplicate flags");
let expected = case
.iter()
.map(|value| {
Scalar::Bool(matches!(counts.get(value), Some(count) if *count > 1))
})
.collect::<Vec<_>>();
assert_eq!(got.values(), expected, "case {case_idx}");
assert_nullable_i64_unmaterialized_a9zs0(&col);
}
}
#[derive(Hash, PartialEq, Eq)]
enum NullableI64DupKeyA9zs0 {
Null,
Int64(i64),
}
fn duplicated_nullable_i64_last_former_body_a9zs0(col: &Column) -> Column {
let mut flags = vec![false; col.values.len()];
let mut seen: rustc_hash::FxHashSet<NullableI64DupKeyA9zs0> =
rustc_hash::FxHashSet::default();
for (idx, value) in col.values.iter().enumerate().rev() {
let key = if value.is_missing() {
NullableI64DupKeyA9zs0::Null
} else {
match value {
Scalar::Int64(value) => NullableI64DupKeyA9zs0::Int64(*value),
_ => NullableI64DupKeyA9zs0::Null,
}
};
flags[idx] = !seen.insert(key);
}
let out = flags.into_iter().map(Scalar::Bool).collect();
Column::new(DType::Bool, out).expect("former duplicate flags")
}
fn nullable_i64_dup_key_dxh4b(value: &Scalar) -> NullableI64DupKeyA9zs0 {
if value.is_missing() {
NullableI64DupKeyA9zs0::Null
} else {
match value {
Scalar::Int64(value) => NullableI64DupKeyA9zs0::Int64(*value),
_ => NullableI64DupKeyA9zs0::Null,
}
}
}
fn duplicated_nullable_i64_none_former_body_dxh4b(col: &Column) -> Column {
let mut seen_once: rustc_hash::FxHashSet<NullableI64DupKeyA9zs0> =
rustc_hash::FxHashSet::default();
let mut seen_multiple: rustc_hash::FxHashSet<NullableI64DupKeyA9zs0> =
rustc_hash::FxHashSet::default();
for value in &col.values {
let key = nullable_i64_dup_key_dxh4b(value);
if !seen_once.insert(nullable_i64_dup_key_dxh4b(value)) {
seen_multiple.insert(key);
}
}
let out = col
.values
.iter()
.map(|value| {
Scalar::Bool(seen_multiple.contains(&nullable_i64_dup_key_dxh4b(value)))
})
.collect();
Column::new(DType::Bool, out).expect("former duplicate flags")
}
fn nullable_i64_dup_input_a9zs0(len: usize) -> (Vec<i64>, ValidityMask) {
let mut state = 0xA9_2507_1A57_D0B1u64;
let mut data = vec![0; len];
let mut validity = ValidityMask::all_valid(len);
for (idx, value) in data.iter_mut().enumerate() {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
if (state >> 40).is_multiple_of(3) {
validity.set(idx, false);
} else {
*value = ((state >> 20) % 250_000) as i64 - 125_000;
}
}
if len > 0 {
validity.set(0, false);
}
(data, validity)
}
fn assert_nullable_i64_unmaterialized_a9zs0(col: &Column) {
assert!(matches!(
&col.values,
ScalarValues::LazyNullableInt64 { .. }
));
if let ScalarValues::LazyNullableInt64 { values, .. } = &col.values {
assert!(values.get().is_none());
}
}
fn median_nanos_a9zs0(samples: &mut [u128]) -> u128 {
samples.sort_unstable();
samples[samples.len() / 2]
}
fn measure_nanos_a9zs0<T>(f: impl FnOnce() -> T) -> u128 {
let start = std::time::Instant::now();
std::hint::black_box(f());
start.elapsed().as_nanos()
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn duplicated_nullable_i64_last_ab_a9zs0() {
const LEN: usize = 1_000_000;
const SAMPLES: usize = 15;
let (data, validity) = nullable_i64_dup_input_a9zs0(LEN);
let reference_a =
Column::from_i64_values_with_validity(data.clone(), validity.clone());
let reference_b =
Column::from_i64_values_with_validity(data.clone(), validity.clone());
let candidate_a =
Column::from_i64_values_with_validity(data.clone(), validity.clone());
let candidate_b = Column::from_i64_values_with_validity(data, validity);
let former = duplicated_nullable_i64_last_former_body_a9zs0(&reference_a);
let witness = candidate_a
.duplicated_keep("last")
.expect("typed last-duplicate flags");
assert_eq!(former.values(), witness.values());
assert_nullable_i64_unmaterialized_a9zs0(&candidate_a);
for _ in 0..3 {
std::hint::black_box(duplicated_nullable_i64_last_former_body_a9zs0(
&reference_a,
));
std::hint::black_box(duplicated_nullable_i64_last_former_body_a9zs0(
&reference_b,
));
std::hint::black_box(candidate_a.duplicated_keep("last").unwrap());
std::hint::black_box(candidate_b.duplicated_keep("last").unwrap());
}
let mut former_a = Vec::with_capacity(SAMPLES);
let mut former_b = Vec::with_capacity(SAMPLES);
let mut typed_a = Vec::with_capacity(SAMPLES);
let mut typed_b = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample.is_multiple_of(2) {
former_a.push(measure_nanos_a9zs0(|| {
duplicated_nullable_i64_last_former_body_a9zs0(&reference_a)
}));
typed_a.push(measure_nanos_a9zs0(|| {
candidate_a.duplicated_keep("last").unwrap()
}));
typed_b.push(measure_nanos_a9zs0(|| {
candidate_b.duplicated_keep("last").unwrap()
}));
former_b.push(measure_nanos_a9zs0(|| {
duplicated_nullable_i64_last_former_body_a9zs0(&reference_b)
}));
} else {
former_b.push(measure_nanos_a9zs0(|| {
duplicated_nullable_i64_last_former_body_a9zs0(&reference_b)
}));
typed_b.push(measure_nanos_a9zs0(|| {
candidate_b.duplicated_keep("last").unwrap()
}));
typed_a.push(measure_nanos_a9zs0(|| {
candidate_a.duplicated_keep("last").unwrap()
}));
former_a.push(measure_nanos_a9zs0(|| {
duplicated_nullable_i64_last_former_body_a9zs0(&reference_a)
}));
}
}
let former_a_p50 = median_nanos_a9zs0(&mut former_a);
let former_b_p50 = median_nanos_a9zs0(&mut former_b);
let typed_a_p50 = median_nanos_a9zs0(&mut typed_a);
let typed_b_p50 = median_nanos_a9zs0(&mut typed_b);
let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
let typed_mean = (typed_a_p50 + typed_b_p50) as f64 / 2.0;
println!("nullable Int64 duplicated(last), len={LEN}, samples={SAMPLES}");
println!("former generic p50 A/B: {former_a_p50} / {former_b_p50} ns");
println!("typed reverse p50 A/B: {typed_a_p50} / {typed_b_p50} ns");
println!("former/typed p50 ratio: {:.3}x", former_mean / typed_mean);
assert_nullable_i64_unmaterialized_a9zs0(&candidate_a);
assert_nullable_i64_unmaterialized_a9zs0(&candidate_b);
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn duplicated_nullable_i64_none_ab_dxh4b() {
const LEN: usize = 1_000_000;
const SAMPLES: usize = 15;
let (data, validity) = nullable_i64_dup_input_a9zs0(LEN);
let reference_a =
Column::from_i64_values_with_validity(data.clone(), validity.clone());
let reference_b =
Column::from_i64_values_with_validity(data.clone(), validity.clone());
let candidate_a =
Column::from_i64_values_with_validity(data.clone(), validity.clone());
let candidate_b = Column::from_i64_values_with_validity(data, validity);
let former = duplicated_nullable_i64_none_former_body_dxh4b(&reference_a);
let witness = candidate_a
.duplicated_keep("false")
.expect("typed keep=False duplicate flags");
assert_eq!(former.values(), witness.values());
assert_nullable_i64_unmaterialized_a9zs0(&candidate_a);
for _ in 0..3 {
std::hint::black_box(duplicated_nullable_i64_none_former_body_dxh4b(
&reference_a,
));
std::hint::black_box(duplicated_nullable_i64_none_former_body_dxh4b(
&reference_b,
));
let _ = std::hint::black_box(candidate_a.duplicated_keep("false"));
let _ = std::hint::black_box(candidate_b.duplicated_keep("false"));
}
let mut former_a = Vec::with_capacity(SAMPLES);
let mut former_b = Vec::with_capacity(SAMPLES);
let mut typed_a = Vec::with_capacity(SAMPLES);
let mut typed_b = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample.is_multiple_of(2) {
former_a.push(measure_nanos_a9zs0(|| {
duplicated_nullable_i64_none_former_body_dxh4b(&reference_a)
}));
typed_a.push(measure_nanos_a9zs0(|| {
candidate_a.duplicated_keep("false")
}));
typed_b.push(measure_nanos_a9zs0(|| {
candidate_b.duplicated_keep("false")
}));
former_b.push(measure_nanos_a9zs0(|| {
duplicated_nullable_i64_none_former_body_dxh4b(&reference_b)
}));
} else {
former_b.push(measure_nanos_a9zs0(|| {
duplicated_nullable_i64_none_former_body_dxh4b(&reference_b)
}));
typed_b.push(measure_nanos_a9zs0(|| {
candidate_b.duplicated_keep("false")
}));
typed_a.push(measure_nanos_a9zs0(|| {
candidate_a.duplicated_keep("false")
}));
former_a.push(measure_nanos_a9zs0(|| {
duplicated_nullable_i64_none_former_body_dxh4b(&reference_a)
}));
}
}
let former_a_p50 = median_nanos_a9zs0(&mut former_a);
let former_b_p50 = median_nanos_a9zs0(&mut former_b);
let typed_a_p50 = median_nanos_a9zs0(&mut typed_a);
let typed_b_p50 = median_nanos_a9zs0(&mut typed_b);
let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
let typed_mean = (typed_a_p50 + typed_b_p50) as f64 / 2.0;
println!(
"nullable Int64 duplicated(keep=False), len={LEN}, samples={SAMPLES}"
);
println!("former generic p50 A/B: {former_a_p50} / {former_b_p50} ns");
println!("typed raw p50 A/B: {typed_a_p50} / {typed_b_p50} ns");
println!("former/typed p50 ratio: {:.3}x", former_mean / typed_mean);
assert_nullable_i64_unmaterialized_a9zs0(&candidate_a);
assert_nullable_i64_unmaterialized_a9zs0(&candidate_b);
}
#[test]
fn duplicated_nullable_utf8_typed_matches_generic() {
// The typed nullable-Utf8 duplicated arm (cold cache) must be BIT-EXACT to the
// generic Key path for every keep policy. Nulls are NOT dropped — all missing
// rows share one bucket (a NaN row duplicates an earlier NaN). A/B on identical
// LazyNullableUtf8 data: `col_cold` (fresh, cold cache) exercises the typed
// arm; `col_warm` has its Scalar cache pre-materialized so the cold-cache gate
// defers it to the generic path. Seeded short strings over {a,b,c,d} + ~25%
// nulls (ties + repeated nulls guaranteed).
let mut state: u64 = 0xD0B1_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 300) as usize;
let mut validity = crate::ValidityMask::all_valid(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..n {
if next() % 4 == 0 {
validity.set(i, false);
} else {
let len = (next() % 4) as usize; // small ⇒ many ties
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
}
offsets.push(bytes.len());
}
let col_cold = Column::from_utf8_values_with_validity(
bytes.clone(),
offsets.clone(),
validity.clone(),
);
let col_warm =
Column::from_utf8_values_with_validity(bytes, offsets, validity);
let _ = col_warm.values(); // warm cache ⇒ generic path (oracle)
for keep in ["first", "last", "false"] {
let cold = col_cold.duplicated_keep(keep).expect("cold duplicated");
let warm = col_warm.duplicated_keep(keep).expect("warm duplicated");
assert_eq!(
cold.values(),
warm.values(),
"trial {trial} keep={keep}"
);
}
}
}
#[test]
fn duplicated_keep_variants_match_pandas() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Int64(1),
Scalar::Int64(3),
Scalar::Int64(2),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let last = col.duplicated_keep("last").expect("duplicated last");
assert_eq!(
last.values(),
&[
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(false),
]
);
let none = col.duplicated_keep("false").expect("duplicated none");
assert_eq!(
none.values(),
&[
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(true),
]
);
}
#[test]
fn between_typed_matches_oracle() {
// Typed i64/f64 between == an independent oracle (missing/NaN → false),
// all four inclusive policies. Built via from_*_values_with_validity to
// drive the typed paths.
let mut state: u64 = 0x71E0_3B9D_2C84_A5F6;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..150 {
let n = (next() % 200) as usize + 1;
let ivals: Vec<i64> = (0..n).map(|_| (next() % 20) as i64).collect();
let fvals: Vec<f64> = ivals.iter().map(|&v| v as f64).collect();
let mut vmask = ValidityMask::all_valid(n);
let mut present = vec![true; n];
for (i, p) in present.iter_mut().enumerate() {
if next() % 4 == 0 {
vmask.set(i, false);
*p = false;
}
}
let icol = Column::from_i64_values_with_validity(ivals.clone(), vmask.clone());
let fcol = Column::from_f64_values_with_validity(fvals.clone(), vmask.clone());
let (lo, hi) = (5.0_f64, 15.0_f64);
for pol in ["both", "left", "right", "neither"] {
let (il, ir) = match pol {
"both" => (true, true),
"left" => (true, false),
"right" => (false, true),
_ => (false, false),
};
let exp: Vec<Scalar> = (0..n)
.map(|i| {
let ok = if present[i] {
let x = fvals[i];
(if il { x >= lo } else { x > lo })
&& (if ir { x <= hi } else { x < hi })
} else {
false
};
Scalar::Bool(ok)
})
.collect();
assert_eq!(icol.between_inclusive(lo, hi, pol).unwrap().values(), exp);
assert_eq!(fcol.between_inclusive(lo, hi, pol).unwrap().values(), exp);
}
}
}
#[test]
fn between_inclusive_both() {
let col = Column::from_values(vec![
Scalar::Float64(0.5),
Scalar::Float64(1.0),
Scalar::Float64(5.0),
Scalar::Float64(6.0),
])
.expect("col");
let b = col.between(1.0, 5.0, true).expect("between");
assert_eq!(b.values()[0], Scalar::Bool(false));
assert_eq!(b.values()[1], Scalar::Bool(true));
assert_eq!(b.values()[2], Scalar::Bool(true));
assert_eq!(b.values()[3], Scalar::Bool(false));
}
#[test]
fn between_exclusive() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(3.0),
Scalar::Float64(5.0),
])
.expect("col");
let b = col.between(1.0, 5.0, false).expect("between");
assert_eq!(b.values()[0], Scalar::Bool(false));
assert_eq!(b.values()[1], Scalar::Bool(true));
assert_eq!(b.values()[2], Scalar::Bool(false));
}
#[test]
fn between_left_and_right_inclusive_edges() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(3.0),
Scalar::Float64(5.0),
])
.expect("col");
let left = col
.between_inclusive(1.0, 5.0, "left")
.expect("between left");
assert_eq!(
left.values(),
&[Scalar::Bool(true), Scalar::Bool(true), Scalar::Bool(false),]
);
let right = col
.between_inclusive(1.0, 5.0, "right")
.expect("between right");
assert_eq!(
right.values(),
&[Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(true),]
);
}
#[test]
fn between_missing_maps_to_false() {
let col = Column::from_values(vec![Scalar::Null(NullKind::NaN), Scalar::Float64(3.0)])
.expect("col");
let b = col.between(1.0, 5.0, true).expect("between");
assert_eq!(b.values()[0], Scalar::Bool(false));
assert_eq!(b.values()[1], Scalar::Bool(true));
}
}
mod factorize {
use fp_types::NullKind;
use super::*;
#[test]
fn factorize_preserves_first_seen_order() {
let col = Column::from_values(vec![
Scalar::Utf8("b".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("c".into()),
Scalar::Utf8("a".into()),
])
.expect("col");
let (codes, uniques) = col.factorize().expect("factorize");
assert_eq!(codes.dtype(), DType::Int64);
assert_eq!(
codes.values(),
&[
Scalar::Int64(0),
Scalar::Int64(1),
Scalar::Int64(0),
Scalar::Int64(2),
Scalar::Int64(1),
]
);
assert_eq!(
uniques.values(),
&[
Scalar::Utf8("b".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("c".into()),
]
);
}
#[test]
fn factorize_nullable_utf8_typed_matches_generic() {
// The typed nullable-Utf8 default factorize arm (cold cache) must be BIT-EXACT
// to the generic LocalKey path: first-seen codes over present values, -1 for
// missing, uniques = distinct present in first-seen order. A/B on identical
// LazyNullableUtf8 data: `col_cold` (fresh, cold cache) exercises the typed
// arm; `col_warm` has its Scalar cache pre-materialized so the cold-cache gate
// defers it to the generic path. Seeded short strings over {a,b,c,d} + varied
// null densities (incl. all-null ⇒ all codes -1, empty uniques).
let mut state: u64 = 0xFAC7_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 300) as usize;
let null_mode = next() % 3; // 0=none, 2=all-null, else ~25%
let mut validity = crate::ValidityMask::all_valid(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..n {
let is_null = match null_mode {
0 => false,
2 => true,
_ => next() % 4 == 0,
};
if is_null {
validity.set(i, false);
} else {
let len = (next() % 4) as usize;
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
}
offsets.push(bytes.len());
}
let col_cold = Column::from_utf8_values_with_validity(
bytes.clone(),
offsets.clone(),
validity.clone(),
);
let col_warm =
Column::from_utf8_values_with_validity(bytes, offsets, validity);
let _ = col_warm.values(); // warm cache ⇒ generic path (oracle)
let (cc, cu) = col_cold.factorize().expect("cold factorize");
let (wc, wu) = col_warm.factorize().expect("warm factorize");
assert_eq!(cc.values(), wc.values(), "codes trial {trial} null_mode={null_mode}");
assert_eq!(cu.values(), wu.values(), "uniques trial {trial} null_mode={null_mode}");
}
}
#[test]
fn factorize_lazy_contiguous_utf8_default_witness_preserves_order() {
let col = Column {
dtype: DType::Utf8,
values: ScalarValues::lazy_contiguous_utf8_arc(
Arc::from(&b"baacaab"[..]),
Arc::from([0_usize, 1, 3, 4, 6, 7]),
),
validity: ValidityMask::all_valid(5),
data: None,
};
let (codes, uniques) = col.factorize().expect("factorize");
assert_eq!(
codes.values(),
&[
Scalar::Int64(0),
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Int64(0),
]
);
assert_eq!(
uniques.values(),
&[
Scalar::Utf8("b".into()),
Scalar::Utf8("aa".into()),
Scalar::Utf8("c".into()),
]
);
let (sorted_codes, sorted_uniques) =
col.factorize_with_options(true, true).expect("factorize");
assert_eq!(
sorted_codes.values(),
&[
Scalar::Int64(1),
Scalar::Int64(0),
Scalar::Int64(2),
Scalar::Int64(0),
Scalar::Int64(1),
]
);
assert_eq!(
sorted_uniques.values(),
&[
Scalar::Utf8("aa".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("c".into()),
]
);
}
#[test]
fn factorize_fixed_width_contiguous_utf8_witness_preserves_order() {
let col = Column {
dtype: DType::Utf8,
values: ScalarValues::lazy_contiguous_utf8_arc(
Arc::from(&b"aabbccaa"[..]),
Arc::from([0_usize, 2, 4, 6, 8]),
),
validity: ValidityMask::all_valid(4),
data: None,
};
let (codes, uniques) = col.factorize().expect("factorize");
assert_eq!(
codes.values(),
&[
Scalar::Int64(0),
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(0),
]
);
assert_eq!(
uniques.values(),
&[
Scalar::Utf8("aa".into()),
Scalar::Utf8("bb".into()),
Scalar::Utf8("cc".into()),
]
);
}
#[test]
fn factorize_missing_values_map_to_negative_one() {
let col = Column::from_values(vec![
Scalar::Float64(1.5),
Scalar::Null(NullKind::NaN),
Scalar::Float64(2.5),
Scalar::Null(NullKind::Null),
Scalar::Float64(1.5),
])
.expect("col");
let (codes, uniques) = col.factorize().expect("factorize");
assert_eq!(
codes.values(),
&[
Scalar::Int64(0),
Scalar::Int64(-1),
Scalar::Int64(1),
Scalar::Int64(-1),
Scalar::Int64(0),
]
);
assert_eq!(uniques.dtype(), DType::Float64);
assert_eq!(
uniques.values(),
&[Scalar::Float64(1.5), Scalar::Float64(2.5)]
);
}
#[test]
fn factorize_empty_column_returns_empty_outputs() {
let col = Column::new(DType::Int64, Vec::new()).expect("col");
let (codes, uniques) = col.factorize().expect("factorize");
assert!(codes.is_empty());
assert!(uniques.is_empty());
assert_eq!(codes.dtype(), DType::Int64);
assert_eq!(uniques.dtype(), DType::Int64);
}
#[test]
fn factorize_with_sort_sorts_uniques_and_relabels_codes() {
let col = Column::from_values(vec![
Scalar::Utf8("b".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("c".into()),
Scalar::Utf8("a".into()),
])
.expect("col");
let (codes, uniques) = col.factorize_with_options(true, true).expect("factorize");
assert_eq!(
codes.values(),
&[
Scalar::Int64(1),
Scalar::Int64(0),
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(0),
]
);
assert_eq!(
uniques.values(),
&[
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("c".into()),
]
);
}
#[test]
fn factorize_with_use_na_sentinel_false_keeps_missing_in_uniques() {
let col = Column::from_values(vec![
Scalar::Float64(1.5),
Scalar::Null(NullKind::NaN),
Scalar::Float64(2.5),
Scalar::Null(NullKind::Null),
Scalar::Float64(1.5),
])
.expect("col");
let (codes, uniques) = col.factorize_with_options(false, false).expect("factorize");
assert_eq!(
codes.values(),
&[
Scalar::Int64(0),
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Int64(0),
]
);
assert_eq!(uniques.dtype(), DType::Float64);
assert_eq!(
uniques.values(),
&[
Scalar::Float64(1.5),
Scalar::Null(NullKind::NaN),
Scalar::Float64(2.5),
]
);
}
#[test]
fn factorize_with_sort_and_use_na_sentinel_false_sorts_missing_last() {
let col = Column::from_values(vec![
Scalar::Utf8("b".into()),
Scalar::Null(NullKind::Null),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let (codes, uniques) = col.factorize_with_options(true, false).expect("factorize");
assert_eq!(
codes.values(),
&[
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(0),
Scalar::Int64(1),
Scalar::Int64(2),
]
);
assert_eq!(
uniques.values(),
&[
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Null(NullKind::Null),
]
);
}
}
mod aggregation_helpers {
use fp_types::{NullKind, Timedelta};
use super::*;
fn assert_float_nan(value: Scalar) {
assert!(
matches!(value, Scalar::Float64(v) if v.is_nan()),
"expected Float64(NaN), got {value:?}"
);
}
#[test]
fn sum_skips_nulls() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
])
.expect("col");
let sum = col.sum();
assert!(matches!(sum, Scalar::Float64(_)), "expected Float64 result");
if let Scalar::Float64(v) = sum {
assert!((v - 6.0).abs() < 1e-9);
}
}
#[test]
fn sum_empty_is_zero() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
assert_eq!(col.sum(), Scalar::Float64(0.0));
}
#[test]
fn mean_matches_sum_over_count() {
let col = Column::from_values(vec![
Scalar::Float64(2.0),
Scalar::Float64(4.0),
Scalar::Float64(6.0),
])
.expect("col");
let mean = col.mean();
assert!(
matches!(mean, Scalar::Float64(_)),
"expected Float64 result"
);
if let Scalar::Float64(v) = mean {
assert!((v - 4.0).abs() < 1e-9);
}
}
#[test]
fn mean_empty_is_null() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
assert!(col.mean().is_missing());
}
#[test]
fn sum_mean_typed_int64_and_nullable_match_nan_reference() {
// The typed Int64 + nullable Int64/Float64 sum/mean paths must be
// BIT-IDENTICAL to the generic nansum/nanmean. Same fold order (0..n,
// skipping missing) ⇒ identical f64 accumulation. Null-missing only.
let mut state: u64 = 0x5000_1234_ABCD_9999;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let n = (next() % 300) as usize; // include n=0 (empty)
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 1000) as i64 - 500
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vf.set(i, false);
0.0
} else {
(r % 1000) as f64 - 500.0
}
})
.collect();
// all-valid Int64, nullable Int64, nullable Float64 (+ all-valid f64)
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
let f_null = Column::from_f64_values_with_validity(fdata, vf);
for col in [&i_all, &i_null, &f_null] {
let vals = col.values().to_vec();
assert_eq!(col.sum(), fp_types::nansum(&vals), "sum trial {trial}");
assert_eq!(col.mean(), fp_types::nanmean(&vals), "mean trial {trial}");
}
}
}
#[test]
fn prod_ptp_typed_int64_and_nullable_match_nan_reference() {
// Typed Int64 + nullable Int64/Float64 prod/ptp must be BIT-IDENTICAL to
// nanprod/nanptp. prod: seed 1.0, all-missing ⇒ Float64(1.0); ptp:
// max-min, all-missing ⇒ Null(NaN). Narrow value range (near ±1 for
// prod so the product stays finite). Null-missing only.
let mut state: u64 = 0x9A0D_1234_5678_ABCD;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let n = (next() % 250) as usize; // include n=0
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 3) as i64 - 1 // {-1, 0, 1} — product stays bounded
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vf.set(i, false);
0.0
} else {
0.5 + (r % 3) as f64 * 0.5 // {0.5, 1.0, 1.5}
}
})
.collect();
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
let f_null = Column::from_f64_values_with_validity(fdata, vf);
for col in [&i_all, &i_null, &f_null] {
let vals = col.values().to_vec();
assert_eq!(col.prod(), fp_types::nanprod(&vals), "prod trial {trial}");
assert_eq!(col.ptp(), fp_types::nanptp(&vals), "ptp trial {trial}");
}
}
}
#[test]
fn var_std_sem_nullable_typed_match_nan_reference() {
// Typed nullable Int64/Float64 var/std/sem (two-pass moments over the
// present subset) must be BIT-IDENTICAL to nanvar/nanstd/nansem, across
// ddof in {0, 1, 2}. Null-missing only. All-valid Int64 also exercised
// (the pre-existing arm). n<=ddof ⇒ Null(NaN).
let mut state: u64 = 0x7A21_1234_5678_9ABC;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let approx_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
for trial in 0..200 {
let n = (next() % 250) as usize; // include small n (n<=ddof edges)
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 200) as i64 - 100
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vf.set(i, false);
0.0
} else {
(r % 200) as f64 - 100.0
}
})
.collect();
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
let f_null = Column::from_f64_values_with_validity(fdata, vf);
for col in [&i_all, &i_null, &f_null] {
let vals = col.values().to_vec();
for ddof in [0usize, 1, 2] {
assert!(
approx_eq(&col.var(ddof), &fp_types::nanvar(&vals, ddof)),
"var trial {trial} ddof {ddof}"
);
assert!(
approx_eq(&col.std(ddof), &fp_types::nanstd(&vals, ddof)),
"std trial {trial} ddof {ddof}"
);
assert!(
approx_eq(&col.sem(ddof), &fp_types::nansem(&vals, ddof)),
"sem trial {trial} ddof {ddof}"
);
}
}
}
}
#[test]
fn skew_kurt_nullable_typed_match_nan_reference() {
// Typed nullable Int64/Float64 skew/kurt (present central moments) must
// be BIT-EXACT to nanskew/nankurt. Null-missing only. Small n exercises
// the n<3 (skew) / n<4 (kurt) Null edges; a constant-ish tail exercises
// the s2==0 ⇒ 0.0 branch occasionally.
let mut state: u64 = 0x3C0F_2468_ACE0_1357;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
for trial in 0..200 {
let n = (next() % 250) as usize;
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 100) as i64 - 50
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vf.set(i, false);
0.0
} else {
(r % 100) as f64 - 50.0
}
})
.collect();
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
let f_null = Column::from_f64_values_with_validity(fdata, vf);
for col in [&i_all, &i_null, &f_null] {
let vals = col.values().to_vec();
assert!(
bit_eq(&col.skew(), &fp_types::nanskew(&vals)),
"skew trial {trial}"
);
assert!(
bit_eq(&col.kurt(), &fp_types::nankurt(&vals)),
"kurt trial {trial}"
);
}
}
}
#[test]
fn median_nullable_typed_match_nan_reference() {
// Typed nullable Int64/Float64 median (collect present ⇒ median_from_
// f64_vec) must be BIT-EXACT to nanmedian. Even n exercises the 2-element
// average; all-missing/empty ⇒ Null(NaN). Null-missing only.
let mut state: u64 = 0x0DDE_1234_ABCD_2468;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
for trial in 0..250 {
let n = (next() % 250) as usize;
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 500) as i64 - 250
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vf.set(i, false);
0.0
} else {
(r % 500) as f64 - 250.0
}
})
.collect();
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
let f_null = Column::from_f64_values_with_validity(fdata, vf);
for col in [&i_all, &i_null, &f_null] {
let vals = col.values().to_vec();
assert!(
bit_eq(&col.median(), &fp_types::nanmedian(&vals)),
"median trial {trial}"
);
}
}
}
#[test]
fn quantile_nullable_typed_match_nan_reference() {
// Typed nullable Int64/Float64 quantile (collect present ⇒ quantile_from_
// f64_vec) must be BIT-EXACT to nanquantile across q values. Float64 also
// carries valid-bit-set NaN (dropped by the `!x.is_nan()` filter, exactly
// collect_finite's is_missing-drops-NaN). all-missing/empty ⇒ Null(NaN);
// out-of-range q ⇒ Null(NaN). Interpolation exercised via non-boundary q.
let mut state: u64 = 0x5EED_9A1C_0FF1_3357;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
let qs = [0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0, 0.333, -0.1, 1.5];
for trial in 0..250 {
let n = (next() % 250) as usize;
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 500) as i64 - 250
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
vf.set(i, false);
0.0
} else if r % 5 == 1 {
// valid-bit-set NaN: present per validity, dropped as
// non-finite by both collect_finite and the typed filter.
f64::NAN
} else {
(r % 500) as f64 - 250.0
}
})
.collect();
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
let f_null = Column::from_f64_values_with_validity(fdata, vf);
for col in [&i_all, &i_null, &f_null] {
let vals = col.values().to_vec();
for &q in &qs {
assert!(
bit_eq(&col.quantile(q), &fp_types::nanquantile(&vals, q)),
"quantile trial {trial} q {q}"
);
}
}
}
}
#[test]
fn logical_not_numeric_nullable_typed_match_scalar_reference() {
// The typed Int64/Float64 arms for logical_not (Bool output) must be
// BIT-EXACT to the Scalar loop: present ⇒ Bool(v == 0); missing / valid-bit
// -set NaN ⇒ Null(Null). Covers 0, ±inf (⇒ Bool(false)), negatives, gaps.
let mut state: u64 = 0x106_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Bool(x), Scalar::Bool(y)) => x == y,
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
fn ref_lognot(vals: &[Scalar]) -> Column {
let out: Vec<Scalar> = vals
.iter()
.map(|v| {
if v.is_missing() {
Scalar::Null(NullKind::Null)
} else {
let bv = match v {
Scalar::Bool(x) => *x,
_ => v.to_f64().map(|x| x != 0.0).unwrap_or(false),
};
Scalar::Bool(!bv)
}
})
.collect();
Column::new(DType::Bool, out).unwrap()
}
for trial in 0..300 {
let n = (next() % 250) as usize;
let mut vf = crate::ValidityMask::all_valid(n);
let mut vi = crate::ValidityMask::all_valid(n);
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 7 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
3 => 0.0, // ⇒ Bool(true)
_ => ((r % 400) as f64 - 200.0) * 0.5,
}
})
.collect();
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
vi.set(i, false);
}
(r % 5) as i64 - 2 // -2..2 incl 0
})
.collect();
let f_null = Column::from_f64_values_with_validity(fdata, vf);
let i_null = Column::from_i64_values_with_validity(idata, vi);
let i_all = Column::from_i64_values_owned((0..n).map(|i| (i % 3) as i64 - 1).collect());
for col in [&f_null, &i_null, &i_all] {
let vals = col.values().to_vec();
let got = col.logical_not().unwrap();
let want = ref_lognot(&vals);
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "lognot len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "lognot trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
}
#[test]
fn logical_binop_bool_nullable_typed_match_scalar_reference() {
// The typed_bool_binary_nullable arm for logical_and/or/xor must be
// BIT-EXACT to the Scalar loop over nullable Bool operands: present∧present
// ⇒ Bool(op); either missing ⇒ Null(Null). Covers nullable×nullable,
// all-valid×nullable, nullable×all-valid, and all-valid×all-valid (which
// takes the earlier typed_bool_binary path). AND/OR/XOR each checked.
let mut state: u64 = 0xB001_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Bool(x), Scalar::Bool(y)) => x == y,
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
fn ref_binop(a: &[Scalar], b: &[Scalar], op: fn(bool, bool) -> bool) -> Column {
let out: Vec<Scalar> = a
.iter()
.zip(b)
.map(|(x, y)| {
if x.is_missing() || y.is_missing() {
Scalar::Null(NullKind::Null)
} else {
let xv = match x {
Scalar::Bool(v) => *v,
_ => x.to_f64().map(|v| v != 0.0).unwrap_or(false),
};
let yv = match y {
Scalar::Bool(v) => *v,
_ => y.to_f64().map(|v| v != 0.0).unwrap_or(false),
};
Scalar::Bool(op(xv, yv))
}
})
.collect();
Column::new(DType::Bool, out).unwrap()
}
// Build a Bool column: `nullable`=false ⇒ all-valid (from_bool_values via
// the folding constructor); true ⇒ some slots masked out.
let mut build = |n: usize, nullable: bool, next: &mut dyn FnMut() -> u64| -> Column {
let mut validity = crate::ValidityMask::all_valid(n);
let data: Vec<bool> = (0..n)
.map(|i| {
let r = next();
if nullable && r % 4 == 0 {
validity.set(i, false);
}
(r >> 19) & 1 == 1
})
.collect();
Column::from_bool_values_with_validity(data, validity)
};
let ops: [(fn(bool, bool) -> bool, fn(&Column, &Column) -> Result<Column, ColumnError>); 3] = [
(|a, b| a && b, |a, b| a.logical_and(b)),
(|a, b| a || b, |a, b| a.logical_or(b)),
(|a, b| a ^ b, |a, b| a.logical_xor(b)),
];
for trial in 0..250 {
let n = (next() % 200) as usize;
for (ln, rn) in [(true, true), (false, true), (true, false), (false, false)] {
let a = build(n, ln, &mut next);
let b = build(n, rn, &mut next);
let av = a.values().to_vec();
let bv = b.values().to_vec();
for (ref_op, col_op) in ops.iter() {
let got = col_op(&a, &b).unwrap();
let want = ref_binop(&av, &bv, *ref_op);
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "binop len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(
bit_eq(g, w),
"binop trial {trial} ln={ln} rn={rn} idx {k}: {g:?} != {w:?}"
);
}
}
}
}
}
#[test]
fn floor_ceil_trunc_nullable_typed_match_scalar_reference() {
// The new nullable Float64/Int64 arms in typed_float_unary_finite_preserving
// must make floor/ceil/trunc BIT-EXACT to their Scalar path on nullable
// input (missing/valid-bit-set-NaN ⇒ NaN⇒missing; present ⇒ f). Covers
// fractional values, negatives, ±inf, x==0.5/-0.5 (ties differ per op).
let mut state: u64 = 0xF100_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
// Replica of floor/ceil/trunc's Scalar path (always Float64 output).
fn ref_op(vals: &[Scalar], f: impl Fn(f64) -> f64) -> Column {
let out: Vec<Scalar> = vals
.iter()
.map(|v| {
if v.is_missing() {
Scalar::Float64(f64::NAN)
} else {
match v {
Scalar::Int64(x) => Scalar::Float64(*x as f64),
Scalar::Float64(x) => Scalar::Float64(f(*x)),
_ => unreachable!(),
}
}
})
.collect();
Column::new(DType::Float64, out).unwrap()
}
for trial in 0..300 {
let n = (next() % 200) as usize;
let mut vf = crate::ValidityMask::all_valid(n);
let mut vi = crate::ValidityMask::all_valid(n);
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 8 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
3 => f64::NEG_INFINITY,
_ => ((r % 4000) as f64 - 2000.0) * 0.013, // fractional, +/-
}
})
.collect();
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
let f_null = Column::from_f64_values_with_validity(fdata, vf);
let i_null = Column::from_i64_values_with_validity(idata, vi);
for col in [&f_null, &i_null] {
let vals = col.values().to_vec();
for (name, got, want) in [
("floor", col.floor().unwrap(), ref_op(&vals, f64::floor)),
("ceil", col.ceil().unwrap(), ref_op(&vals, f64::ceil)),
("trunc", col.trunc().unwrap(), ref_op(&vals, f64::trunc)),
] {
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "{name} len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "{name} trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
}
}
#[test]
fn bitwise_not_int64_typed_match_scalar_reference() {
// The typed Int64 arms (all-valid + nullable) for bitwise_not must be
// BIT-EXACT to the Scalar loop: present ⇒ Int64(!x); missing ⇒ Null(Null).
// Covers negatives, i64::MIN/MAX, gaps.
let mut state: u64 = 0xB17_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Int64(x), Scalar::Int64(y)) => x == y,
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
fn ref_not(vals: &[Scalar]) -> Column {
let out: Vec<Scalar> = vals
.iter()
.map(|v| {
if v.is_missing() {
Scalar::Null(NullKind::Null)
} else {
match v {
Scalar::Int64(x) => Scalar::Int64(!x),
_ => unreachable!(),
}
}
})
.collect();
Column::new(DType::Int64, out).unwrap()
}
for trial in 0..300 {
let n = (next() % 250) as usize;
let mut vi = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
match r % 11 {
0 => i64::MIN,
1 => i64::MAX,
2 => 0,
_ => (r as i64).wrapping_sub(i64::MAX / 2),
}
})
.collect();
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
for col in [&i_all, &i_null] {
let vals = col.values().to_vec();
let got = col.bitwise_not().unwrap();
let want = ref_not(&vals);
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "not len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "not trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
}
#[test]
fn mask_nullable_int64_self_typed_match_scalar_reference() {
// The typed nullable-Int64-self arm for mask (all-valid Bool cond) must be
// BIT-EXACT to the generic Scalar loop: cond[i] ? other : self[i] (inverse
// of where_cond). self missing at cond-false ⇒ Null(Null); cond-true ⇒ other.
let mut state: u64 = 0x11A5_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Int64(x), Scalar::Int64(y)) => x == y,
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
fn ref_mask(vals: &[Scalar], cb: &[bool], other: &Scalar) -> Column {
let out: Vec<Scalar> = vals
.iter()
.zip(cb.iter())
.map(|(v, &c)| if c { other.clone() } else { v.clone() })
.collect();
Column::new(DType::Int64, out).unwrap()
}
let other = Scalar::Int64(-99);
for trial in 0..300 {
let n = (next() % 200) as usize;
let cb: Vec<bool> = (0..n).map(|_| next() % 2 == 0).collect();
let cond = Column::from_bool_values(cb.clone());
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
let col = Column::from_i64_values_with_validity(data, vi);
let vals = col.values().to_vec();
let got = col.mask(&cond, &other).unwrap();
let want = ref_mask(&vals, &cb, &other);
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "mask len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "mask trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
#[test]
fn where_cond_nullable_self_typed_match_scalar_reference() {
// The typed nullable-self arms for where_cond (all-valid Bool cond) must be
// BIT-EXACT to the generic Scalar loop: cond[i] ? self[i] : other. Covers
// Float64 self (with valid-bit-set NaN + ±inf) and Int64 self, self missing
// at cond-true (⇒ dtype-correct null) and cond-false, gaps.
let mut state: u64 = 0x3E4E_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Int64(x), Scalar::Int64(y)) => x == y,
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
// Replica of the generic loop for an ALL-VALID cond (no cond-missing branch).
fn ref_where(vals: &[Scalar], cb: &[bool], other: &Scalar, dtype: DType) -> Column {
let out: Vec<Scalar> = vals
.iter()
.zip(cb.iter())
.map(|(v, &c)| if c { v.clone() } else { other.clone() })
.collect();
Column::new(dtype, out).unwrap()
}
for trial in 0..300 {
let n = (next() % 200) as usize;
let cb: Vec<bool> = (0..n).map(|_| next() % 2 == 0).collect();
let cond = Column::from_bool_values(cb.clone());
let is_f64 = trial % 2 == 0;
let (col, other) = if is_f64 {
let mut vf = crate::ValidityMask::all_valid(n);
let data: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 7 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
_ => ((r % 400) as f64 - 200.0) * 0.25,
}
})
.collect();
(
Column::from_f64_values_with_validity(data, vf),
Scalar::Float64(-7.5),
)
} else {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
(
Column::from_i64_values_with_validity(data, vi),
Scalar::Int64(-99),
)
};
let vals = col.values().to_vec();
let got = col.where_cond(&cond, &other).unwrap();
let dt = if is_f64 { DType::Float64 } else { DType::Int64 };
let want = ref_where(&vals, &cb, &other, dt);
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "where len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "where trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
#[test]
fn isclose_nullable_typed_match_scalar_reference() {
// The typed pairwise isclose arm must be BIT-EXACT to the generic Scalar
// loop (either-missing ⇒ Bool(false); else (af-bf).abs() <= atol+rtol*|bf|).
// Reference off the MATERIALIZED values(). MIXED dtypes, nullable at
// DIFFERENT positions, ±inf (kept ⇒ inf comparisons ⇒ false), valid-bit-set
// NaN (⇒ missing ⇒ false), across several (rtol, atol).
let mut state: u64 = 0xC105_E1DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Bool(x), Scalar::Bool(y)) => x == y,
_ => false,
}
};
fn ref_isclose(a: &[Scalar], b: &[Scalar], rtol: f64, atol: f64) -> Column {
let out: Vec<Scalar> = a
.iter()
.zip(b.iter())
.map(|(x, y)| {
if x.is_missing() || y.is_missing() {
Scalar::Bool(false)
} else {
let af = x.to_f64().unwrap();
let bf = y.to_f64().unwrap();
Scalar::Bool((af - bf).abs() <= atol + rtol * bf.abs())
}
})
.collect();
Column::new(DType::Bool, out).unwrap()
}
let mk_f64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vf = crate::ValidityMask::all_valid(n);
let data: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 8 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
3 => f64::NEG_INFINITY,
_ => ((r % 400) as f64 - 200.0) * 0.25,
}
})
.collect();
Column::from_f64_values_with_validity(data, vf)
};
let mk_i64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
Column::from_i64_values_with_validity(data, vi)
};
let tols = [(1e-5f64, 1e-8f64), (0.0, 0.0), (1e9, 1e9), (0.1, 1.0)];
for trial in 0..300 {
let n = (next() % 200) as usize;
let (a, b) = match trial % 4 {
0 => (mk_i64(n, &mut next), mk_f64(n, &mut next)),
1 => (mk_f64(n, &mut next), mk_i64(n, &mut next)),
2 => (mk_f64(n, &mut next), mk_f64(n, &mut next)),
_ => (mk_i64(n, &mut next), mk_i64(n, &mut next)),
};
let av = a.values().to_vec();
let bv = b.values().to_vec();
let (rtol, atol) = tols[trial % tols.len()];
let got = a.isclose(&b, rtol, atol).unwrap();
let want = ref_isclose(&av, &bv, rtol, atol);
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "isclose len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "isclose trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
#[test]
fn heaviside_ldexp_nullable_typed_match_scalar_reference() {
// heaviside(h0)/ldexp(exp) now route through typed_float_unary. Must be
// BIT-EXACT to their generic Scalar loop (missing/NaN ⇒ NaN⇒missing; present
// ⇒ kernel). Covers x==0 (⇒ h0), ±inf, valid-bit-set NaN, negatives, gaps,
// and h0==NaN (heaviside(0) ⇒ NaN⇒missing).
let mut state: u64 = 0x4EA0_51DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
fn ref_heaviside(vals: &[Scalar], h0: f64) -> Column {
let out: Vec<Scalar> = vals
.iter()
.map(|v| {
if v.is_missing() {
return Scalar::Float64(f64::NAN);
}
match v {
Scalar::Int64(x) => Scalar::Float64(if *x < 0 {
0.0
} else if *x > 0 {
1.0
} else {
h0
}),
Scalar::Float64(x) => Scalar::Float64(if x.is_nan() {
f64::NAN
} else if *x < 0.0 {
0.0
} else if *x > 0.0 {
1.0
} else {
h0
}),
_ => unreachable!(),
}
})
.collect();
Column::new(DType::Float64, out).unwrap()
}
fn ref_ldexp(vals: &[Scalar], exp: i32) -> Column {
let m = 2.0_f64.powi(exp);
let out: Vec<Scalar> = vals
.iter()
.map(|v| {
if v.is_missing() {
return Scalar::Float64(f64::NAN);
}
match v {
Scalar::Int64(x) => Scalar::Float64(*x as f64 * m),
Scalar::Float64(x) => Scalar::Float64(x * m),
_ => unreachable!(),
}
})
.collect();
Column::new(DType::Float64, out).unwrap()
}
let mk_f64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vf = crate::ValidityMask::all_valid(n);
let data: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 8 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
3 => f64::NEG_INFINITY,
4 => 0.0, // heaviside ⇒ h0
_ => ((r % 400) as f64 - 200.0) * 0.25,
}
})
.collect();
Column::from_f64_values_with_validity(data, vf)
};
let mk_i64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 5) as i64 - 2 // -2..2 incl 0
})
.collect();
Column::from_i64_values_with_validity(data, vi)
};
let h0s = [0.5f64, 0.0, 1.0, f64::NAN];
let exps = [0i32, 3, -2, 10];
for trial in 0..300 {
let n = (next() % 200) as usize;
let col = if trial % 2 == 0 {
mk_f64(n, &mut next)
} else {
mk_i64(n, &mut next)
};
let vals = col.values().to_vec();
let h0 = h0s[trial % h0s.len()];
let exp = exps[trial % exps.len()];
let hv = col.heaviside(h0).unwrap();
let want_h = ref_heaviside(&vals, h0);
let lv = col.ldexp(exp).unwrap();
let want_l = ref_ldexp(&vals, exp);
for (name, got, want) in
[("heaviside", &hv, &want_h), ("ldexp", &lv, &want_l)]
{
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "{name} len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "{name} trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
}
#[test]
fn shift_i64_both_present_nullable_match_scalar_reference() {
// left_shift/right_shift now route Int64 input through
// typed_i64_both_present_binary. Must be BIT-EXACT to the generic Scalar
// loop (both-present ⇒ Int64(x <</>> clamp(y,0,63)), else Null(Null)).
// Covers shift counts >63 and <0 (clamped), negative x (arithmetic >>), gaps.
let mut state: u64 = 0x5417_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Int64(x), Scalar::Int64(y)) => x == y,
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
fn ref_binop(a: &[Scalar], b: &[Scalar], f: fn(i64, i64) -> i64) -> Column {
let out: Vec<Scalar> = a
.iter()
.zip(b.iter())
.map(|(x, y)| {
if x.is_missing() || y.is_missing() {
Scalar::Null(NullKind::Null)
} else {
match (x, y) {
(Scalar::Int64(xi), Scalar::Int64(yi)) => Scalar::Int64(f(*xi, *yi)),
_ => unreachable!(),
}
}
})
.collect();
Column::new(DType::Int64, out).unwrap()
}
// Values column: full-range i64 incl negatives. Shift-count column: incl
// out-of-range (>63) and negative (clamp to 0).
let mk_vals = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
r as i64
})
.collect();
Column::from_i64_values_with_validity(data, vi)
};
let mk_shifts = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
vi.set(i, false);
}
(r % 140) as i64 - 10 // range [-10, 129] ⇒ exercises clamp both ends
})
.collect();
Column::from_i64_values_with_validity(data, vi)
};
for trial in 0..300 {
let n = (next() % 200) as usize;
let a = mk_vals(n, &mut next);
let b = mk_shifts(n, &mut next);
let av = a.values().to_vec();
let bv = b.values().to_vec();
let cases: [(&str, Column, Column); 2] = [
(
"shl",
a.left_shift(&b).unwrap(),
ref_binop(&av, &bv, |x, y| x.wrapping_shl(y.clamp(0, 63) as u32)),
),
(
"shr",
a.right_shift(&b).unwrap(),
ref_binop(&av, &bv, |x, y| x.wrapping_shr(y.clamp(0, 63) as u32)),
),
];
for (name, got, want) in cases {
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "{name} len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "{name} trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
}
#[test]
fn i64_both_present_binary_nullable_match_scalar_reference() {
// gcd/lcm/bitwise_and/or/xor now route Int64 input through
// typed_i64_both_present_binary (both-present ⇒ Int64(f), either-missing ⇒
// Null(Null)). Must be BIT-EXACT to their generic Scalar loop. Covers
// negatives, zeros (gcd(0,0)=0, lcm×0), all-valid + nullable at DIFFERENT
// positions.
let mut state: u64 = 0x6CD1_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Int64(x), Scalar::Int64(y)) => x == y,
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
fn ref_binop(a: &[Scalar], b: &[Scalar], f: fn(i64, i64) -> i64) -> Column {
let out: Vec<Scalar> = a
.iter()
.zip(b.iter())
.map(|(x, y)| {
if x.is_missing() || y.is_missing() {
Scalar::Null(NullKind::Null)
} else {
match (x, y) {
(Scalar::Int64(xi), Scalar::Int64(yi)) => Scalar::Int64(f(*xi, *yi)),
_ => unreachable!(),
}
}
})
.collect();
Column::new(DType::Int64, out).unwrap()
}
let mk_i64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 40) as i64 - 20 // negatives + zeros
})
.collect();
Column::from_i64_values_with_validity(data, vi)
};
for trial in 0..300 {
let n = (next() % 200) as usize;
let a = mk_i64(n, &mut next);
let b = mk_i64(n, &mut next);
let av = a.values().to_vec();
let bv = b.values().to_vec();
let cases: [(&str, Column, Column); 5] = [
("gcd", a.gcd(&b).unwrap(), ref_binop(&av, &bv, Column::compute_gcd_i64)),
("lcm", a.lcm(&b).unwrap(), ref_binop(&av, &bv, Column::compute_lcm_i64)),
("and", a.bitwise_and(&b).unwrap(), ref_binop(&av, &bv, |x, y| x & y)),
("or", a.bitwise_or(&b).unwrap(), ref_binop(&av, &bv, |x, y| x | y)),
("xor", a.bitwise_xor(&b).unwrap(), ref_binop(&av, &bv, |x, y| x ^ y)),
];
for (name, got, want) in cases {
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "{name} len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "{name} trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
}
#[test]
fn twocol_nan_propagate_batch2_nullable_match_scalar_reference() {
// float_power/logaddexp/logaddexp2/nextafter now route through
// typed_nan_propagate_binary. Must be BIT-EXACT to their generic Scalar
// loop (both-present ⇒ kernel, else NaN⇒missing). float_power exercises a
// negative base + fractional exp ⇒ NaN ⇒ missing; logaddexp* exercise
// ±inf special cases; nextafter exercises x==0 / x==y. Mixed dtypes,
// nullable, valid-bit-set NaN.
let mut state: u64 = 0x77E5_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
fn ref_binop(a: &[Scalar], b: &[Scalar], f: fn(f64, f64) -> f64) -> Column {
let out: Vec<Scalar> = a
.iter()
.zip(b.iter())
.map(|(x, y)| {
if x.is_missing() || y.is_missing() {
Scalar::Float64(f64::NAN)
} else {
Scalar::Float64(f(x.to_f64().unwrap(), y.to_f64().unwrap()))
}
})
.collect();
Column::new(DType::Float64, out).unwrap()
}
let mk_f64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vf = crate::ValidityMask::all_valid(n);
let data: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 9 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
3 => f64::NEG_INFINITY,
4 => 0.0, // nextafter x==0
_ => ((r % 400) as f64 - 200.0) * 0.25, // includes negatives (float_power ⇒ NaN)
}
})
.collect();
Column::from_f64_values_with_validity(data, vf)
};
let mk_i64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
vi.set(i, false);
}
(r % 20) as i64 - 8
})
.collect();
Column::from_i64_values_with_validity(data, vi)
};
for trial in 0..300 {
let n = (next() % 200) as usize;
let (a, b) = match trial % 4 {
0 => (mk_i64(n, &mut next), mk_f64(n, &mut next)),
1 => (mk_f64(n, &mut next), mk_i64(n, &mut next)),
2 => (mk_f64(n, &mut next), mk_f64(n, &mut next)),
_ => (mk_i64(n, &mut next), mk_i64(n, &mut next)),
};
let av = a.values().to_vec();
let bv = b.values().to_vec();
let cases: [(&str, Column, Column); 4] = [
("float_power", a.float_power(&b).unwrap(), ref_binop(&av, &bv, |x, y| x.powf(y))),
("logaddexp", a.logaddexp(&b).unwrap(), ref_binop(&av, &bv, Column::logaddexp_kernel)),
("logaddexp2", a.logaddexp2(&b).unwrap(), ref_binop(&av, &bv, Column::logaddexp2_kernel)),
("nextafter", a.nextafter(&b).unwrap(), ref_binop(&av, &bv, Column::nextafter_kernel)),
];
for (name, got, want) in cases {
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "{name} len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "{name} trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
}
#[test]
fn twocol_nan_propagate_nullable_match_scalar_reference() {
// atan2/hypot/fmod/copysign now route nullable input through
// typed_nan_propagate_binary (both-present ⇒ f, either-missing ⇒
// NaN⇒missing). Must be BIT-EXACT to their generic Scalar loop. fmod
// exercises a%0 ⇒ NaN ⇒ missing; copysign exercises ±0.0 sign; all cover
// mixed dtypes, nullable, ±inf, valid-bit-set NaN.
let mut state: u64 = 0x2C01_9ABE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
fn ref_binop(a: &[Scalar], b: &[Scalar], f: fn(f64, f64) -> f64) -> Column {
let out: Vec<Scalar> = a
.iter()
.zip(b.iter())
.map(|(x, y)| {
if x.is_missing() || y.is_missing() {
Scalar::Float64(f64::NAN)
} else {
Scalar::Float64(f(x.to_f64().unwrap(), y.to_f64().unwrap()))
}
})
.collect();
Column::new(DType::Float64, out).unwrap()
}
let mk_f64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vf = crate::ValidityMask::all_valid(n);
let data: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 9 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
3 => 0.0, // fmod divisor 0 ⇒ NaN
_ => ((r % 400) as f64 - 200.0) * 0.25,
}
})
.collect();
Column::from_f64_values_with_validity(data, vf)
};
let mk_i64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
Column::from_i64_values_with_validity(data, vi)
};
for trial in 0..300 {
let n = (next() % 200) as usize;
let (a, b) = match trial % 4 {
0 => (mk_i64(n, &mut next), mk_f64(n, &mut next)),
1 => (mk_f64(n, &mut next), mk_i64(n, &mut next)),
2 => (mk_f64(n, &mut next), mk_f64(n, &mut next)),
_ => (mk_i64(n, &mut next), mk_i64(n, &mut next)),
};
let av = a.values().to_vec();
let bv = b.values().to_vec();
let cases: [(&str, Column, Column); 4] = [
("atan2", a.atan2(&b).unwrap(), ref_binop(&av, &bv, |y, x| y.atan2(x))),
("hypot", a.hypot(&b).unwrap(), ref_binop(&av, &bv, |x, y| x.hypot(y))),
("fmod", a.fmod(&b).unwrap(), ref_binop(&av, &bv, |x, y| x % y)),
("copysign", a.copysign(&b).unwrap(), ref_binop(&av, &bv, |m, s| m.copysign(s))),
];
for (name, got, want) in cases {
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "{name} len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "{name} trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
}
#[test]
fn fmax_fmin_nullable_typed_match_scalar_reference() {
// The typed nullable pairwise arm for fmax/fmin (NaN/missing-IGNORING) must
// be BIT-EXACT to the generic Scalar loop (to_f64().ok() + is_nan/None arms).
// Reference off the MATERIALIZED values(). MIXED dtypes, nullable at DIFFERENT
// positions, ±inf (kept), valid-bit-set NaN (IGNORED, not propagated — the
// key difference from maximum/minimum).
let mut state: u64 = 0xF0AE_C1DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
// Exact replica of the generic fmax/fmin Scalar loop + Self::new.
fn ref_fbinop(a: &[Scalar], b: &[Scalar], f: fn(f64, f64) -> f64) -> Column {
let out: Vec<Scalar> = a
.iter()
.zip(b.iter())
.map(|(x, y)| {
let af = x.to_f64().ok();
let bf = y.to_f64().ok();
let r = match (af, bf) {
(Some(x), Some(y)) if x.is_nan() => y,
(Some(x), Some(y)) if y.is_nan() => x,
(Some(x), Some(y)) => f(x, y),
(Some(x), None) => x,
(None, Some(y)) => y,
(None, None) => f64::NAN,
};
Scalar::Float64(r)
})
.collect();
Column::new(DType::Float64, out).unwrap()
}
let mk_f64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vf = crate::ValidityMask::all_valid(n);
let data: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 8 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
3 => f64::NEG_INFINITY,
_ => ((r % 400) as f64 - 200.0) * 0.25,
}
})
.collect();
Column::from_f64_values_with_validity(data, vf)
};
let mk_i64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
Column::from_i64_values_with_validity(data, vi)
};
for trial in 0..300 {
let n = (next() % 200) as usize;
let (a, b) = match trial % 4 {
0 => (mk_i64(n, &mut next), mk_f64(n, &mut next)),
1 => (mk_f64(n, &mut next), mk_i64(n, &mut next)),
2 => (mk_f64(n, &mut next), mk_f64(n, &mut next)),
_ => (mk_i64(n, &mut next), mk_i64(n, &mut next)),
};
let av = a.values().to_vec();
let bv = b.values().to_vec();
for (name, got, want) in [
("fmax", a.fmax(&b).unwrap(), ref_fbinop(&av, &bv, f64::max)),
("fmin", a.fmin(&b).unwrap(), ref_fbinop(&av, &bv, f64::min)),
] {
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "{name} len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "{name} trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
}
#[test]
fn maximum_minimum_nullable_typed_match_scalar_reference() {
// The typed nullable pairwise arm for maximum/minimum must be BIT-EXACT to
// the generic Scalar loop (either-missing ⇒ NaN⇒missing; else f(af,bf)).
// Reference off the MATERIALIZED values(). MIXED dtypes (i64×f64 + swaps),
// nullable at DIFFERENT positions, ±inf (kept), valid-bit-set NaN (⇒ missing).
let mut state: u64 = 0x9AC0_51DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
// Exact replica of the generic maximum/minimum Scalar loop + Self::new.
fn ref_binop(a: &[Scalar], b: &[Scalar], f: fn(f64, f64) -> f64) -> Column {
let out: Vec<Scalar> = a
.iter()
.zip(b.iter())
.map(|(x, y)| {
if x.is_missing() || y.is_missing() {
return Scalar::Float64(f64::NAN);
}
let xf = x.to_f64().unwrap();
let yf = y.to_f64().unwrap();
if xf.is_nan() || yf.is_nan() {
Scalar::Float64(f64::NAN)
} else {
Scalar::Float64(f(xf, yf))
}
})
.collect();
Column::new(DType::Float64, out).unwrap()
}
let mk_f64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vf = crate::ValidityMask::all_valid(n);
let data: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 8 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
3 => f64::NEG_INFINITY,
_ => ((r % 400) as f64 - 200.0) * 0.25,
}
})
.collect();
Column::from_f64_values_with_validity(data, vf)
};
let mk_i64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
Column::from_i64_values_with_validity(data, vi)
};
for trial in 0..300 {
let n = (next() % 200) as usize;
let (a, b) = match trial % 4 {
0 => (mk_i64(n, &mut next), mk_f64(n, &mut next)),
1 => (mk_f64(n, &mut next), mk_i64(n, &mut next)),
2 => (mk_f64(n, &mut next), mk_f64(n, &mut next)),
_ => (mk_i64(n, &mut next), mk_i64(n, &mut next)),
};
let av = a.values().to_vec();
let bv = b.values().to_vec();
for (name, got, want) in [
("max", a.maximum(&b).unwrap(), ref_binop(&av, &bv, f64::max)),
("min", a.minimum(&b).unwrap(), ref_binop(&av, &bv, f64::min)),
] {
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "{name} len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "{name} trial {trial} idx {k}: {g:?} != {w:?}");
}
}
}
}
#[test]
fn typed_float_unary_serial_nullable_match_scalar_reference() {
// The new nullable Float64/Int64 arms in typed_float_unary (serial) must
// make the ops routing through it (rint/sinc/radians/degrees/reciprocal)
// BIT-EXACT to their Scalar path on nullable input. Representative: rint,
// radians, degrees, reciprocal (inf on 0, not NaN). Covers valid-bit-set
// NaN (Float64), zero (reciprocal ⇒ ±inf, still valid), gaps.
let mut state: u64 = 0x3EC1_9AFE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
fn ref_op(vals: &[Scalar], f: impl Fn(f64) -> f64) -> Column {
let out: Vec<Scalar> = vals
.iter()
.map(|v| {
if v.is_missing() {
Scalar::Float64(f64::NAN)
} else {
match v {
Scalar::Int64(x) => Scalar::Float64(f(*x as f64)),
Scalar::Float64(x) => Scalar::Float64(f(*x)),
_ => unreachable!(),
}
}
})
.collect();
Column::new(DType::Float64, out).unwrap()
}
let check = |got: &Column, want: &Column, name: &str, trial: usize| {
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "{name} len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "{name} trial {trial} idx {k}: {g:?} != {w:?}");
}
};
for trial in 0..250 {
let n = (next() % 200) as usize;
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 300) as i64 - 100 // includes 0 (reciprocal ⇒ inf) + negatives
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 5 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
_ => (r % 300) as f64 - 100.0,
}
})
.collect();
let i_null = Column::from_i64_values_with_validity(idata, vi);
let f_null = Column::from_f64_values_with_validity(fdata, vf);
for col in [&i_null, &f_null] {
let vals = col.values().to_vec();
check(&col.rint().unwrap(), &ref_op(&vals, f64::round_ties_even), "rint", trial);
check(&col.radians().unwrap(), &ref_op(&vals, f64::to_radians), "radians", trial);
check(&col.degrees().unwrap(), &ref_op(&vals, f64::to_degrees), "degrees", trial);
check(&col.reciprocal().unwrap(), &ref_op(&vals, |x| 1.0 / x), "reciprocal", trial);
}
}
}
#[test]
fn typed_float_unary_par_nullable_match_scalar_reference() {
// The new nullable Float64/Int64 arms in typed_float_unary_par must make
// the 17 ops routing through it (log10/log2/trig/cbrt/…) BIT-EXACT to their
// Scalar path on nullable input. Representative: log10 (NaN on ≤0), sin
// (bounded), cbrt (defined on negatives), atan. Covers valid-bit-set NaN
// (Float64), negatives, gaps.
let mut state: u64 = 0x7A1F_B0CD_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
// Replica of the ops' Scalar path + Self::new.
fn ref_op(vals: &[Scalar], f: impl Fn(f64) -> f64) -> Column {
let out: Vec<Scalar> = vals
.iter()
.map(|v| {
if v.is_missing() {
Scalar::Float64(f64::NAN)
} else {
match v {
Scalar::Int64(x) => Scalar::Float64(f(*x as f64)),
Scalar::Float64(x) => Scalar::Float64(f(*x)),
_ => unreachable!(),
}
}
})
.collect();
Column::new(DType::Float64, out).unwrap()
}
let check = |got: &Column, want: &Column, name: &str, trial: usize| {
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "{name} len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(bit_eq(g, w), "{name} trial {trial} idx {k}: {g:?} != {w:?}");
}
};
for trial in 0..250 {
let n = (next() % 200) as usize;
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 300) as i64 - 100 // includes negatives + zero
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 5 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
_ => (r % 300) as f64 - 100.0,
}
})
.collect();
let i_null = Column::from_i64_values_with_validity(idata, vi);
let f_null = Column::from_f64_values_with_validity(fdata, vf);
for col in [&i_null, &f_null] {
let vals = col.values().to_vec();
check(&col.log10().unwrap(), &ref_op(&vals, f64::log10), "log10", trial);
check(&col.sin().unwrap(), &ref_op(&vals, f64::sin), "sin", trial);
check(&col.cbrt().unwrap(), &ref_op(&vals, f64::cbrt), "cbrt", trial);
check(&col.arctan().unwrap(), &ref_op(&vals, f64::atan), "atan", trial);
}
}
}
#[test]
fn unary_float_nullable_int64_match_scalar_reference() {
// The new nullable Int64 arm in typed_float_unary_nullable_owned_par must
// make sqrt/exp/log on a nullable Int64 column BIT-EXACT to their Scalar
// path (missing ⇒ Float64(NaN)⇒missing; present ⇒ f(x as f64), itself NaN
// ⇒ missing). Covers negatives (sqrt/log ⇒ NaN⇒missing) + gaps + all-valid.
let mut state: u64 = 0x59A2_10AF_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
// Replica of the Scalar path + Self::new for an Int64 column.
fn ref_op(vals: &[Scalar], f: impl Fn(f64) -> f64) -> Column {
let out: Vec<Scalar> = vals
.iter()
.map(|v| {
if v.is_missing() {
Scalar::Float64(f64::NAN)
} else {
match v {
Scalar::Int64(x) => Scalar::Float64(f(*x as f64)),
Scalar::Float64(x) => Scalar::Float64(f(*x)),
_ => unreachable!(),
}
}
})
.collect();
Column::new(DType::Float64, out).unwrap()
}
for trial in 0..300 {
let n = (next() % 200) as usize;
let mut vi = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 150 // includes negatives (sqrt/log ⇒ NaN)
})
.collect();
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
for col in [&i_all, &i_null] {
let vals = col.values().to_vec();
let cases: [(&str, Column, Column); 3] = [
("sqrt", col.sqrt().unwrap(), ref_op(&vals, f64::sqrt)),
("exp", col.exp().unwrap(), ref_op(&vals, f64::exp)),
("log", col.log().unwrap(), ref_op(&vals, f64::ln)),
];
for (name, got, want) in cases {
let gv = got.values();
let wv = want.values();
assert_eq!(gv.len(), wv.len(), "{name} len trial {trial}");
for (k, (g, w)) in gv.iter().zip(wv.iter()).enumerate() {
assert!(
bit_eq(g, w),
"{name} trial {trial} n {n} idx {k}: {g:?} != {w:?}"
);
}
}
}
}
}
#[test]
fn clip_nullable_int64_typed_match_scalar_reference() {
// The typed nullable Int64 clip arm (new) must produce output BIT-EXACT to
// the generic Scalar loop + Self::new normalization. clip output is always
// Float64: present ⇒ Float64(clamp(v as f64)); missing ⇒ Null(NaN) (the loop
// pushes the input Null(Null) which Self::new normalizes to Null(NaN)).
// Also checks nullable Float64 (existing arm) and all-valid.
let mut state: u64 = 0xC117_9A00_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
// Replica of the generic loop + Self::new's Float64 null normalization.
fn ref_clip(vals: &[Scalar], lo: Option<f64>, hi: Option<f64>) -> Vec<Scalar> {
let lo = lo.filter(|v| !v.is_nan());
let hi = hi.filter(|v| !v.is_nan());
vals.iter()
.map(|v| {
if v.is_missing() {
return Scalar::Null(NullKind::NaN);
}
let mut x = v.to_f64().unwrap();
if let Some(l) = lo
&& x < l
{
x = l;
}
if let Some(h) = hi
&& x > h
{
x = h;
}
Scalar::Float64(x)
})
.collect()
}
let bounds = [
(Some(-50.0), Some(50.0)),
(Some(0.0), None),
(None, Some(10.0)),
(None, None),
(Some(100.0), Some(-100.0)),
];
for trial in 0..300 {
let n = (next() % 200) as usize;
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vf.set(i, false);
0.0
} else {
(r % 400) as f64 - 200.0
}
})
.collect();
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
let f_null = Column::from_f64_values_with_validity(fdata, vf);
for col in [&i_all, &i_null, &f_null] {
let vals = col.values().to_vec();
for &(lo, hi) in &bounds {
let got = col.clip(lo, hi).unwrap();
let want = ref_clip(&vals, lo, hi);
let gv = got.values();
assert_eq!(gv.len(), want.len(), "clip len trial {trial}");
for (k, (g, w)) in gv.iter().zip(want.iter()).enumerate() {
assert!(
bit_eq(g, w),
"clip trial {trial} n {n} idx {k} lo {lo:?} hi {hi:?}: {g:?} != {w:?}"
);
}
}
}
}
}
#[test]
fn interpolate_linear_typed_match_scalar_reference() {
// The typed Int64 arm (new) + the refactored Float64 arm must produce
// output BIT-EXACT to the generic Scalar path (to_f64 walk). Reference
// replicates that path over the materialized values(). Exercises interior
// gaps, leading nulls (stay null), trailing nulls (ffill), all-missing,
// single-valid; Float64 also carries valid-bit-set NaN (treated as missing).
let mut state: u64 = 0x1017_E4B0_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
// Exact replica of the generic Scalar interpolation path.
fn ref_interp(vals: &[Scalar]) -> Vec<Scalar> {
let len = vals.len();
let mut floats: Vec<Option<f64>> = Vec::with_capacity(len);
for v in vals {
if v.is_missing() {
floats.push(None);
continue;
}
match v.to_f64() {
Ok(x) if !x.is_nan() => floats.push(Some(x)),
Ok(_) => floats.push(None),
Err(_) => floats.push(None),
}
}
let first = floats.iter().position(Option::is_some);
let last = floats.iter().rposition(Option::is_some);
if let (Some(start), Some(end)) = (first, last) {
let mut i = start;
while i < end {
if floats[i].is_some() {
i += 1;
continue;
}
let gap_start = i;
while i < end && floats[i].is_none() {
i += 1;
}
let before = floats[gap_start - 1].unwrap();
let after = floats[i].unwrap();
let span = (i - gap_start + 1) as f64;
for (k, j) in (gap_start..i).enumerate() {
let step = (k + 1) as f64;
floats[j] = Some(before + (after - before) * (step / span));
}
}
let last_valid = floats[end].unwrap();
for slot in floats.iter_mut().skip(end + 1) {
*slot = Some(last_valid);
}
}
floats
.into_iter()
.map(|opt| match opt {
Some(x) => Scalar::Float64(x),
None => Scalar::Null(NullKind::NaN),
})
.collect()
}
for trial in 0..400 {
let n = (next() % 200) as usize;
let mut vf = crate::ValidityMask::all_valid(n);
let mut vi = crate::ValidityMask::all_valid(n);
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 5 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN, // valid-bit-set NaN ⇒ treated as missing
_ => ((r % 400) as f64 - 200.0) * 0.5,
}
})
.collect();
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 3 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
let f_all = Column::from_f64_values_owned(fdata.clone());
let f_null = Column::from_f64_values_with_validity(fdata, vf);
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
for col in [&f_all, &f_null, &i_all, &i_null] {
let vals = col.values().to_vec();
let got = col.interpolate_linear().unwrap();
let got_vals = got.values();
let want = ref_interp(&vals);
assert_eq!(got_vals.len(), want.len(), "interp len trial {trial}");
for (k, (g, w)) in got_vals.iter().zip(want.iter()).enumerate() {
assert!(
bit_eq(g, w),
"interp trial {trial} n {n} idx {k}: {g:?} != {w:?}"
);
}
}
}
}
#[test]
fn hist_counts_typed_collect_match_scalar_reference() {
// hist_counts now collects present values off the raw slice + validity
// instead of materializing Vec<Scalar>. The full Vec<usize> counts must be
// IDENTICAL to the old generic collect + bucketing over materialized
// values(). Float64 carries valid-bit-set NaN (dropped) + ±inf (kept),
// Int64 all-valid + nullable, across several bin counts incl. 0.
let mut state: u64 = 0x81A3_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
// Exact replica of the pre-typed generic hist_counts.
fn ref_hist(vals: &[Scalar], bins: usize) -> Vec<usize> {
if bins == 0 {
return Vec::new();
}
let nums: Vec<f64> = vals
.iter()
.filter(|v| !v.is_missing())
.filter_map(|v| v.to_f64().ok())
.filter(|f| !f.is_nan())
.collect();
if nums.is_empty() {
return vec![0; bins];
}
let (min, max) = nums
.iter()
.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| {
(lo.min(x), hi.max(x))
});
if (max - min).abs() < f64::EPSILON {
let mut counts = vec![0; bins];
counts[0] = nums.len();
return counts;
}
let width = (max - min) / bins as f64;
let mut counts = vec![0usize; bins];
for x in &nums {
let mut idx = ((x - min) / width) as usize;
if idx >= bins {
idx = bins - 1;
}
counts[idx] += 1;
}
counts
}
let bins_list = [0usize, 1, 4, 10, 37];
for trial in 0..300 {
let n = (next() % 250) as usize;
let mut vf = crate::ValidityMask::all_valid(n);
let mut vi = crate::ValidityMask::all_valid(n);
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 10 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
_ => ((r % 400) as f64 - 200.0) * 0.25,
}
})
.collect();
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
let f_all = Column::from_f64_values_owned(fdata.clone());
let f_null = Column::from_f64_values_with_validity(fdata, vf);
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
for col in [&f_all, &f_null, &i_all, &i_null] {
let vals = col.values().to_vec();
for &bins in &bins_list {
assert_eq!(
col.hist_counts(bins),
ref_hist(&vals, bins),
"hist_counts trial {trial} n {n} bins {bins}"
);
}
}
}
}
#[test]
fn describe_std_typed_collect_match_scalar_reference() {
// describe()'s std now collects present values off the raw slice + validity
// instead of materializing Vec<Scalar>. The std field must be BIT-EXACT to
// the old generic collect + two-pass math over the MATERIALIZED values().
// Float64 carries valid-bit-set NaN (dropped) + ±inf (kept); nullable at
// various positions; Int64 all-valid + nullable.
let mut state: u64 = 0xDE5C_71BE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
// Exact replica of the pre-typed generic std block.
fn ref_std(vals: &[Scalar]) -> Scalar {
let nums: Vec<f64> = vals
.iter()
.filter(|v| !v.is_missing())
.filter_map(|v| v.to_f64().ok())
.collect();
if nums.len() < 2 {
return Scalar::Null(NullKind::NaN);
}
let mu = nums.iter().sum::<f64>() / nums.len() as f64;
let ss: f64 = nums.iter().map(|x| (x - mu).powi(2)).sum();
Scalar::Float64((ss / (nums.len() as f64 - 1.0)).sqrt())
}
let std_of = |d: &[(&'static str, Scalar)]| -> Scalar {
d.iter().find(|(k, _)| *k == "std").map(|(_, v)| v.clone()).unwrap()
};
for trial in 0..300 {
let n = (next() % 250) as usize;
let mut vf = crate::ValidityMask::all_valid(n);
let mut vi = crate::ValidityMask::all_valid(n);
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 9 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
_ => ((r % 400) as f64 - 200.0) * 0.25,
}
})
.collect();
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
let f_all = Column::from_f64_values_owned(fdata.clone());
let f_null = Column::from_f64_values_with_validity(fdata, vf);
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
for col in [&f_all, &f_null, &i_all, &i_null] {
let vals = col.values().to_vec();
let got = std_of(&col.describe().unwrap());
assert!(
bit_eq(&got, &ref_std(&vals)),
"describe std trial {trial} n {n}"
);
}
}
}
#[test]
fn dot_typed_pairwise_match_scalar_reference() {
// The typed pairwise dot fast path must be BIT-EXACT to the Scalar loop it
// replaces (!is_missing + to_f64 Ok + skip-NaN, same 0..n order). Reference
// computed off the MATERIALIZED values() = the exact old code. MIXED dtypes
// (i64xf64 + swap), all-valid + nullable at DIFFERENT positions, ±inf (kept)
// and NaN (dropped) in both.
let mut state: u64 = 0xD07C_0FFE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
// Exact replica of the pre-typed generic loop (typed inputs never Err).
fn ref_dot(v: &[Scalar], w: &[Scalar]) -> f64 {
let mut sum = 0.0_f64;
for (a, b) in v.iter().zip(w.iter()) {
if a.is_missing() || b.is_missing() {
continue;
}
let av = a.to_f64().unwrap();
let bv = b.to_f64().unwrap();
if av.is_nan() || bv.is_nan() {
continue;
}
sum += av * bv;
}
sum
}
let mk_f64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vf = crate::ValidityMask::all_valid(n);
let data: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 8 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
3 => f64::NEG_INFINITY,
_ => ((r % 400) as f64 - 200.0) * 0.25,
}
})
.collect();
Column::from_f64_values_with_validity(data, vf)
};
let mk_i64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 6 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
Column::from_i64_values_with_validity(data, vi)
};
for trial in 0..300 {
let n = (next() % 200) as usize;
let (vcol, wcol) = match trial % 4 {
0 => (mk_i64(n, &mut next), mk_f64(n, &mut next)),
1 => (mk_f64(n, &mut next), mk_i64(n, &mut next)),
2 => (mk_f64(n, &mut next), mk_f64(n, &mut next)),
_ => (mk_i64(n, &mut next), mk_i64(n, &mut next)),
};
let vv = vcol.values().to_vec();
let wv = wcol.values().to_vec();
let got = vcol.dot(&wcol).unwrap();
let want = ref_dot(&vv, &wv);
assert_eq!(
got.to_bits(),
want.to_bits(),
"dot trial {trial} n {n}: {got} != {want}"
);
}
}
#[test]
fn weighted_mean_typed_pairwise_match_scalar_reference() {
// The typed pairwise weighted_mean fast path must be BIT-EXACT to the
// Scalar loop it replaces (!is_missing && to_f64 Ok, same 0..n order,
// same weight_sum==0 ⇒ Null(NaN) guard). Reference computed off the
// MATERIALIZED values() = the exact old code. MIXED dtypes (i64 val x f64
// weights + swap), all-valid + nullable at DIFFERENT positions, with ±inf
// (kept — is_missing drops only NaN) and NaN (dropped) in both.
let mut state: u64 = 0xA5A5_7EED_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
// Exact replica of the pre-typed generic loop.
fn ref_wmean(v: &[Scalar], w: &[Scalar]) -> Scalar {
let mut sum = 0.0;
let mut weight_sum = 0.0;
for (a, b) in v.iter().zip(w.iter()) {
if a.is_missing() || b.is_missing() {
continue;
}
let vf = match a.to_f64() {
Ok(x) => x,
Err(_) => continue,
};
let wf = match b.to_f64() {
Ok(x) => x,
Err(_) => continue,
};
sum += vf * wf;
weight_sum += wf;
}
if weight_sum == 0.0 {
return Scalar::Null(NullKind::NaN);
}
Scalar::Float64(sum / weight_sum)
}
let mk_f64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vf = crate::ValidityMask::all_valid(n);
let data: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 8 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN,
2 => f64::INFINITY,
3 => f64::NEG_INFINITY,
_ => ((r % 400) as f64 - 200.0) * 0.25,
}
})
.collect();
Column::from_f64_values_with_validity(data, vf)
};
let mk_i64 = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut vi = crate::ValidityMask::all_valid(n);
let data: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 6 == 0 {
vi.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
Column::from_i64_values_with_validity(data, vi)
};
for trial in 0..300 {
let n = (next() % 200) as usize;
// Cover i64xf64, f64xi64, f64xf64, i64xi64.
let (vcol, wcol) = match trial % 4 {
0 => (mk_i64(n, &mut next), mk_f64(n, &mut next)),
1 => (mk_f64(n, &mut next), mk_i64(n, &mut next)),
2 => (mk_f64(n, &mut next), mk_f64(n, &mut next)),
_ => (mk_i64(n, &mut next), mk_i64(n, &mut next)),
};
let vv = vcol.values().to_vec();
let wv = wcol.values().to_vec();
assert!(
bit_eq(&vcol.weighted_mean(&wcol), &ref_wmean(&vv, &wv)),
"weighted_mean trial {trial} n {n}"
);
}
}
#[test]
fn minmax_nullable_typed_match_nan_reference() {
// Typed nullable Int64/Float64 min/max (fold present ⇒ dtype-preserved
// Scalar) must be BIT-EXACT to nanmin/nanmax. Float64 carries valid-bit-set
// NaN (skipped, exactly nanmin's is_missing-drops-NaN) plus -0.0/0.0 pairs
// (tie keeps FIRST via strict </>). all-missing/empty ⇒ Null(NaN).
let mut state: u64 = 0x1234_F00D_CAFE_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Int64(x), Scalar::Int64(y)) => x == y,
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
for trial in 0..300 {
let n = (next() % 250) as usize;
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 500) as i64 - 250
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
match r % 6 {
0 => {
vf.set(i, false);
0.0
}
1 => f64::NAN, // valid-bit-set NaN: skipped by both paths
2 => 0.0, // tie fodder for -0.0/0.0 first-on-tie check
3 => -0.0,
_ => (r % 500) as f64 - 250.0,
}
})
.collect();
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
let f_null = Column::from_f64_values_with_validity(fdata, vf);
for col in [&i_all, &i_null, &f_null] {
let vals = col.values().to_vec();
assert!(
bit_eq(&col.min(), &fp_types::nanmin(&vals)),
"min trial {trial}"
);
assert!(
bit_eq(&col.max(), &fp_types::nanmax(&vals)),
"max trial {trial}"
);
}
}
}
#[test]
fn cov_corr_typed_pairwise_match_scalar_reference() {
// The typed pairwise cov/corr fast paths must be BIT-EXACT to the
// Scalar loop they replace (to_f64() Ok(v) if v.is_finite(), same 0..n
// order). Reference computed off the MATERIALIZED values() = the exact
// old code. Mixed dtypes (i64 vs f64), all-valid + nullable, with the
// two columns' missing bits at DIFFERENT positions (pairwise present).
let mut state: u64 = 0xC02C_0221_1234_5678;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let bit_eq = |a: &Scalar, b: &Scalar| -> bool {
match (a, b) {
(Scalar::Float64(x), Scalar::Float64(y)) => x.to_bits() == y.to_bits(),
(Scalar::Null(_), Scalar::Null(_)) => true,
_ => false,
}
};
// Old Scalar-loop reference for cov (ddof=1) and corr over values().
fn ref_cov(a: &[Scalar], b: &[Scalar], ddof: usize) -> Scalar {
let n = a.len().min(b.len());
if n == 0 {
return Scalar::Null(NullKind::NaN);
}
let (mut sx, mut sy, mut c) = (0.0f64, 0.0f64, 0usize);
let present = |v: &Scalar| -> Option<f64> {
match v.to_f64() {
Ok(x) if x.is_finite() => Some(x),
_ => None,
}
};
for i in 0..n {
if let (Some(x), Some(y)) = (present(&a[i]), present(&b[i])) {
sx += x;
sy += y;
c += 1;
}
}
if c <= ddof {
return Scalar::Null(NullKind::NaN);
}
let (mx, my) = (sx / c as f64, sy / c as f64);
let mut cs = 0.0f64;
for i in 0..n {
if let (Some(x), Some(y)) = (present(&a[i]), present(&b[i])) {
cs += (x - mx) * (y - my);
}
}
Scalar::Float64(cs / (c - ddof) as f64)
}
fn ref_corr(a: &[Scalar], b: &[Scalar]) -> Scalar {
let n = a.len().min(b.len());
if n == 0 {
return Scalar::Null(NullKind::NaN);
}
let present = |v: &Scalar| -> Option<f64> {
match v.to_f64() {
Ok(x) if x.is_finite() => Some(x),
_ => None,
}
};
let (mut sx, mut sy, mut sxx, mut syy, mut sxy, mut c) =
(0.0f64, 0.0f64, 0.0f64, 0.0f64, 0.0f64, 0usize);
for i in 0..n {
if let (Some(x), Some(y)) = (present(&a[i]), present(&b[i])) {
sx += x;
sy += y;
sxx += x * x;
syy += y * y;
sxy += x * y;
c += 1;
}
}
if c < 2 {
return Scalar::Null(NullKind::NaN);
}
let nf = c as f64;
let num = nf * sxy - sx * sy;
let dx = (nf * sxx - sx * sx).sqrt();
let dy = (nf * syy - sy * sy).sqrt();
if dx == 0.0 || dy == 0.0 {
return Scalar::Null(NullKind::NaN);
}
Scalar::Float64(num / (dx * dy))
}
let mk_i = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut v = crate::ValidityMask::all_valid(n);
let d: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
v.set(i, false);
}
(r % 400) as i64 - 200
})
.collect();
Column::from_i64_values_with_validity(d, v)
};
let mk_f = |n: usize, next: &mut dyn FnMut() -> u64| -> Column {
let mut v = crate::ValidityMask::all_valid(n);
let d: Vec<f64> = (0..n)
.map(|i| {
let r = next();
if r % 5 == 0 {
v.set(i, false);
0.0
} else {
(r % 400) as f64 - 200.0
}
})
.collect();
Column::from_f64_values_with_validity(d, v)
};
for trial in 0..150 {
let n = (next() % 250) as usize + 1;
let a = if next() % 2 == 0 {
mk_i(n, &mut next)
} else {
mk_f(n, &mut next)
};
let b = if next() % 2 == 0 {
mk_i(n, &mut next)
} else {
mk_f(n, &mut next)
};
let (av, bv) = (a.values().to_vec(), b.values().to_vec());
assert!(
bit_eq(&a.cov(&b), &ref_cov(&av, &bv, 1)),
"cov trial {trial}"
);
assert!(
bit_eq(&a.corr(&b), &ref_corr(&av, &bv)),
"corr trial {trial}"
);
}
}
#[test]
fn min_max_extrema_skip_nulls() {
let col = Column::from_values(vec![
Scalar::Int64(3),
Scalar::Null(NullKind::NaN),
Scalar::Int64(1),
Scalar::Int64(5),
Scalar::Int64(2),
])
.expect("col");
assert_eq!(col.min(), Scalar::Int64(1));
assert_eq!(col.max(), Scalar::Int64(5));
}
#[test]
fn median_of_odd_count() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(5.0),
Scalar::Float64(3.0),
])
.expect("col");
let median = col.median();
assert!(
matches!(median, Scalar::Float64(_)),
"expected Float64 result"
);
if let Scalar::Float64(v) = median {
assert!((v - 3.0).abs() < 1e-9);
}
}
#[test]
fn prod_multiplies_non_nulls() {
let col = Column::from_values(vec![
Scalar::Float64(2.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
Scalar::Float64(4.0),
])
.expect("col");
let prod = col.prod();
assert!(
matches!(prod, Scalar::Float64(_)),
"expected Float64 result"
);
if let Scalar::Float64(v) = prod {
assert!((v - 24.0).abs() < 1e-9);
}
}
#[test]
fn prod_empty_is_one() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
assert_eq!(col.prod(), Scalar::Float64(1.0));
}
#[test]
fn product_alias_matches_prod() {
let col = Column::from_values(vec![
Scalar::Float64(2.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
])
.expect("col");
assert_eq!(col.product(), col.prod());
}
#[test]
fn skipna_false_aggregate_variants_propagate_nan() {
let col = Column::from_values(vec![
Scalar::Float64(2.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(4.0),
])
.expect("col");
assert_eq!(col.sum_skipna(true), col.sum());
assert_float_nan(col.sum_skipna(false));
assert_float_nan(col.mean_skipna(false));
assert_float_nan(col.min_skipna(false));
assert_float_nan(col.max_skipna(false));
assert_float_nan(col.median_skipna(false));
assert_float_nan(col.prod_skipna(false));
assert_float_nan(col.var_skipna(1, false));
assert_float_nan(col.std_skipna(1, false));
assert_float_nan(col.sem_skipna(1, false));
}
#[test]
fn skipna_false_timedelta_aggregate_variants_propagate_nat() {
let col = Column::from_values(vec![
Scalar::Timedelta64(Timedelta::NANOS_PER_SEC),
Scalar::Timedelta64(Timedelta::NAT),
])
.expect("col");
assert_eq!(col.sum_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
assert_eq!(col.mean_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
assert_eq!(col.min_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
assert_eq!(col.max_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
}
#[test]
fn quantile_median_of_sorted_values() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
Scalar::Float64(4.0),
Scalar::Float64(5.0),
])
.expect("col");
let quantile = col.quantile(0.5);
assert!(
matches!(quantile, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9),
"expected Float64 median, got {quantile:?}"
);
}
#[test]
fn quantile_empty_is_null() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
assert!(col.quantile(0.5).is_missing());
}
#[test]
fn quantile_out_of_range_is_null() {
let col = Column::from_values(vec![Scalar::Float64(1.0)]).expect("col");
assert!(col.quantile(1.5).is_missing());
assert!(col.quantile(-0.1).is_missing());
}
#[test]
fn mode_f64_open_addressing_matches_reference() {
use std::collections::HashMap;
// Signed-zero: -0.0 first → mode keeps -0.0 representation.
let col = Column::from_f64_values(vec![-0.0, 1.0, 0.0, 1.0, 0.0]);
let m = col.mode().expect("mode");
let got: Vec<f64> = m
.values()
.iter()
.map(|v| match v {
Scalar::Float64(x) => *x,
o => panic!("{o:?}"),
})
.collect();
// 0-class count 3 (>1's count 2) → single winner, the first-seen -0.0.
assert_eq!(got.len(), 1);
assert!(got[0] == 0.0 && got[0].is_sign_negative());
let mut state: u64 = 0x7777_3333_CCCC_1111;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..150 {
let n = (next() % 400) as usize + 1;
let data: Vec<f64> = (0..n)
.map(|_| match next() % 6 {
0 => -0.0,
1 => 0.0,
2 => 2.0,
3 => -3.5,
4 => f64::INFINITY,
_ => (next() % 30) as f64,
})
.collect();
let mut counts: HashMap<u64, (u64, f64)> = HashMap::new();
for &f in &data {
let kb = (if f == 0.0 { 0.0 } else { f }).to_bits();
counts.entry(kb).and_modify(|e| e.0 += 1).or_insert((1, f));
}
let max_c = counts.values().map(|(c, _)| *c).max().unwrap();
let mut expected: Vec<f64> = counts
.values()
.filter_map(|&(c, f)| (c == max_c).then_some(f))
.collect();
expected.sort_by(|a, b| a.total_cmp(b));
let col = Column::from_f64_values(data);
let got: Vec<f64> = col
.mode()
.expect("mode")
.values()
.iter()
.map(|v| match v {
Scalar::Float64(x) => *x,
o => panic!("{o:?}"),
})
.collect();
assert_eq!(
got.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
expected.iter().map(|x| x.to_bits()).collect::<Vec<_>>()
);
}
}
#[test]
fn mode_f64_growable_fibonacci_float_of_integer_matches_reference() {
// Regression for the mode_f64_wide fix: float-of-integer keys span many
// exponents (their variation is in the HIGH to_bits() bits), which the
// old low-bit `& mask` hash collapsed into per-exponent buckets (probe
// chains), and n large enough (> 1024 distinct) forces the growable
// table to rehash. Winners must stay bit-identical to a HashMap
// reference. Engineered ties: every value duplicated, one boosted.
use std::collections::HashMap;
let mut state: u64 = 0x0F1E_2D3C_4B5A_6978;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..40 {
// ~2500 distinct integer values as f64 (exponents 2^0..2^11), each
// appearing several times, over ~12k rows ⇒ multiple table grows.
let distinct = 2000 + (next() % 800) as i64;
let n = 12_000usize;
let boosted = (next() % distinct as u64) as i64;
let data: Vec<f64> = (0..n)
.map(|i| {
// Bias toward `boosted` so there is a clear unique winner.
let v = if i % 9 == 0 {
boosted
} else {
(next() % distinct as u64) as i64
};
v as f64
})
.collect();
let mut counts: HashMap<u64, (u64, f64)> = HashMap::new();
for &f in &data {
let kb = (if f == 0.0 { 0.0 } else { f }).to_bits();
counts.entry(kb).and_modify(|e| e.0 += 1).or_insert((1, f));
}
let max_c = counts.values().map(|(c, _)| *c).max().unwrap();
let mut expected: Vec<f64> = counts
.values()
.filter_map(|&(c, f)| (c == max_c).then_some(f))
.collect();
expected.sort_by(|a, b| a.total_cmp(b));
let col = Column::from_f64_values(data);
let got: Vec<f64> = col
.mode()
.expect("mode")
.values()
.iter()
.map(|v| match v {
Scalar::Float64(x) => *x,
o => panic!("not float: {o:?}"),
})
.collect();
assert_eq!(
got.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
expected.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
"trial {trial}"
);
}
}
#[test]
fn mode_wide_i64_open_addressing_matches_reference() {
// Wide/sparse all-valid Int64 uses mode_i64_wide (open-addressing
// tally). Winners (max-count values, ascending) must equal a HashMap
// reference across full-range data incl. i64::MIN, with engineered ties.
use std::collections::HashMap;
let pool: [i64; 6] = [
i64::MIN,
i64::MAX,
4_000_000_000_000_000_000,
-4_000_000_000_000_000_000,
11,
-11,
];
let mut state: u64 = 0x9988_7766_5544_3322;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..150 {
let n = (next() % 400) as usize + 2;
let mut data: Vec<i64> = (0..n)
.map(|_| pool[(next() as usize) % pool.len()])
.collect();
data[0] = i64::MIN;
data[1] = i64::MAX;
assert!(
crate::i64_direct_address_range(&data).is_none(),
"trial {trial}: expected wide data"
);
let mut counts: HashMap<i64, u64> = HashMap::new();
for &v in &data {
*counts.entry(v).or_insert(0) += 1;
}
let max_c = counts.values().copied().max().unwrap();
let mut expected: Vec<i64> = counts
.iter()
.filter_map(|(&k, &c)| (c == max_c).then_some(k))
.collect();
expected.sort_unstable();
let col = Column::from_i64_values_owned(data);
let got: Vec<i64> = col
.mode()
.expect("mode")
.values()
.iter()
.map(|v| match v {
Scalar::Int64(x) => *x,
o => panic!("not int: {o:?}"),
})
.collect();
assert_eq!(got, expected, "trial {trial}");
}
}
#[test]
fn mode_wide_i64_growable_fibonacci_rehash_matches_reference() {
// Regression for the mode_i64_wide fix: many distinct WIDE values
// (> 1024 ⇒ multiple growable-table rehashes) that vary only in HIGH
// bits (k << 34, the case the old low-bit `& mask` hash clustered),
// plus the i64::MIN sentinel, with engineered ties. Winners must stay
// bit-identical to a HashMap reference.
use std::collections::HashMap;
let mut state: u64 = 0x1234_5678_9ABC_DEF0;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..40 {
let distinct = 2000 + (next() % 800) as i64;
let n = 12_000usize;
let boosted = ((next() % distinct as u64) as i64) << 34;
let data: Vec<i64> = (0..n)
.map(|i| {
if i % 400 == 0 {
i64::MIN // sentinel path
} else if i % 9 == 0 {
boosted // clear unique-winner bias
} else {
(((next() % distinct as u64) as i64) - distinct / 2) << 34
}
})
.collect();
assert!(
crate::i64_direct_address_range(&data).is_none(),
"trial {trial}: expected wide data"
);
let mut counts: HashMap<i64, u64> = HashMap::new();
for &v in &data {
*counts.entry(v).or_insert(0) += 1;
}
let max_c = counts.values().copied().max().unwrap();
let mut expected: Vec<i64> = counts
.iter()
.filter_map(|(&k, &c)| (c == max_c).then_some(k))
.collect();
expected.sort_unstable();
let col = Column::from_i64_values_owned(data);
let got: Vec<i64> = col
.mode()
.expect("mode")
.values()
.iter()
.map(|v| match v {
Scalar::Int64(x) => *x,
o => panic!("not int: {o:?}"),
})
.collect();
assert_eq!(got, expected, "trial {trial}");
}
}
#[test]
fn mode_nullable_i64_f64_matches_present_reference() {
// mode on a nullable Int64/Float64 column now tallies the PRESENT subset
// via the dense/wide typed helpers instead of the generic Scalar+Key
// HashMap. Winners (max-count present values, ascending) must equal a
// HashMap reference over the present values. Narrow ranges force ties;
// ~25% missing; no -0.0 so normalized bits == value (first-seen moot).
use std::collections::HashMap;
let mut state: u64 = 0xB0DE_1234_ABCD_9AB0;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let len = (next() % 300) as usize + 1;
let mut vi = crate::ValidityMask::all_valid(len);
let mut vf = crate::ValidityMask::all_valid(len);
let idata: Vec<i64> = (0..len)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 7) as i64 - 3
})
.collect();
let fdata: Vec<f64> = (0..len)
.map(|i| {
let r = next();
if r % 4 == 0 {
vf.set(i, false);
0.0
} else {
(r % 7) as f64 - 3.0
}
})
.collect();
// Int64 reference over present.
let mut ic: HashMap<i64, u64> = HashMap::new();
for i in 0..len {
if vi.get(i) {
*ic.entry(idata[i]).or_insert(0) += 1;
}
}
let mut iwant: Vec<i64> = if ic.is_empty() {
Vec::new()
} else {
let m = ic.values().copied().max().unwrap();
ic.iter().filter_map(|(&k, &c)| (c == m).then_some(k)).collect()
};
iwant.sort_unstable();
// Float64 reference over present (by bits; no -0.0 in data).
let mut fc: HashMap<u64, u64> = HashMap::new();
for i in 0..len {
if vf.get(i) && !fdata[i].is_nan() {
*fc.entry(fdata[i].to_bits()).or_insert(0) += 1;
}
}
let mut fwant: Vec<f64> = if fc.is_empty() {
Vec::new()
} else {
let m = fc.values().copied().max().unwrap();
fc.iter()
.filter_map(|(&k, &c)| (c == m).then_some(f64::from_bits(k)))
.collect()
};
fwant.sort_by(|a, b| a.partial_cmp(b).unwrap());
let icol = Column::from_i64_values_with_validity(idata, vi);
let fcol = Column::from_f64_values_with_validity(fdata, vf);
let igot: Vec<i64> = icol
.mode()
.expect("mode")
.values()
.iter()
.map(|v| match v {
Scalar::Int64(x) => *x,
o => panic!("not int: {o:?}"),
})
.collect();
let fgot: Vec<f64> = fcol
.mode()
.expect("mode")
.values()
.iter()
.map(|v| match v {
Scalar::Float64(x) => *x,
o => panic!("not float: {o:?}"),
})
.collect();
assert_eq!(igot, iwant, "i64 trial {trial}");
assert_eq!(fgot, fwant, "f64 trial {trial}");
}
}
#[test]
fn mode_returns_tied_max_frequency() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(3),
])
.expect("col");
let m = col.mode().expect("mode");
assert_eq!(m.values(), &[Scalar::Int64(2), Scalar::Int64(3)]);
}
#[test]
fn mode_ignores_missing_values() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let m = col.mode().expect("mode");
assert_eq!(m.values(), &[Scalar::Int64(1)]);
}
#[test]
fn mode_empty_is_empty_same_dtype() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
let m = col.mode().expect("mode");
assert!(m.is_empty());
}
#[test]
fn mode_nullable_utf8_typed_matches_generic() {
// The typed nullable-Utf8 mode arm (cold cache) must be BIT-EXACT to the
// generic Key path: drops nulls, returns max-count winners sorted ascending.
// A/B on identical LazyNullableUtf8 data: `col_cold` (fresh, cold cache)
// exercises the typed arm; `col_warm` has its Scalar cache pre-materialized so
// the cold-cache gate defers it to the generic path. Tiny alphabet {a,b,c} +
// short lengths ⇒ frequent multi-winner ties; some trials all-null (empty mode).
let mut state: u64 = 0x30DE_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..150 {
let n = (next() % 120) as usize;
let null_mode = next() % 3; // 0=none, 2=all-null, else ~25%
let mut validity = crate::ValidityMask::all_valid(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..n {
let is_null = match null_mode {
0 => false,
2 => true,
_ => next() % 4 == 0,
};
if is_null {
validity.set(i, false);
} else {
let len = (next() % 3) as usize; // 0..2 ⇒ tiny domain, many ties
let s: String = (0..len)
.map(|_| (b'a' + (next() % 3) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
}
offsets.push(bytes.len());
}
let col_cold = Column::from_utf8_values_with_validity(
bytes.clone(),
offsets.clone(),
validity.clone(),
);
let col_warm =
Column::from_utf8_values_with_validity(bytes, offsets, validity);
let _ = col_warm.values(); // warm cache ⇒ generic path (oracle)
let cold = col_cold.mode().expect("cold mode");
let warm = col_warm.mode().expect("warm mode");
assert_eq!(
cold.values(),
warm.values(),
"trial {trial} null_mode={null_mode}"
);
}
}
#[test]
fn memory_usage_fixed_width_for_numeric() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let usage = col.memory_usage(false);
// 3 * 8 + ceil(3/8) = 24 + 1
assert_eq!(usage, 25);
}
#[test]
fn memory_usage_deep_counts_utf8_bytes() {
let col = Column::from_values(vec![
Scalar::Utf8("hi".into()),
Scalar::Utf8("world".into()),
])
.expect("col");
let shallow = col.memory_usage(false);
let deep = col.memory_usage(true);
assert!(deep > shallow);
// deep_extra = "hi".len() + "world".len() = 2 + 5 = 7
assert_eq!(deep - shallow, 7);
}
#[test]
fn interpolate_typed_f64_backing_matches_expected() {
// Drives the typed path explicitly (from_f64_values_with_validity →
// LazyNullableFloat64, which as_f64_slice_with_validity recognizes).
// Leading null stays null; interior gap linearly filled; trailing
// forward-fills the last valid value.
let mut vmask = ValidityMask::all_valid(7);
for j in [0usize, 2, 3, 6] {
vmask.set(j, false);
}
// values: [_, 10, _, _, 40, 50, _] (underscores invalid)
let data = vec![0.0, 10.0, 0.0, 0.0, 40.0, 50.0, 0.0];
let col = Column::from_f64_values_with_validity(data, vmask);
let r = col.interpolate_linear().expect("interp");
let v = r.values();
assert!(v[0].is_missing(), "leading null stays null: {:?}", v[0]);
assert_eq!(v[1], Scalar::Float64(10.0));
// gap between 10 (idx1) and 40 (idx4): span=3 → 20, 30
assert_eq!(v[2], Scalar::Float64(20.0));
assert_eq!(v[3], Scalar::Float64(30.0));
assert_eq!(v[4], Scalar::Float64(40.0));
assert_eq!(v[5], Scalar::Float64(50.0));
// trailing forward-fill of last valid (50)
assert_eq!(v[6], Scalar::Float64(50.0));
}
#[test]
fn interpolate_fills_interior_gaps() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Float64(4.0),
])
.expect("col");
let r = col.interpolate_linear().expect("interpolate");
assert_eq!(r.values()[0], Scalar::Float64(1.0));
assert!(
matches!(&r.values()[1], Scalar::Float64(v) if (*v - 2.0).abs() < 1e-9),
"expected Float64, got {:?}",
r.values()[1]
);
assert!(
matches!(&r.values()[2], Scalar::Float64(v) if (*v - 3.0).abs() < 1e-9),
"expected Float64, got {:?}",
r.values()[2]
);
assert_eq!(r.values()[3], Scalar::Float64(4.0));
}
#[test]
fn interpolate_leading_null_stays_null_trailing_forward_fills() {
// pandas Series.interpolate(method='linear') default
// limit_direction='forward': leading NaN stays NaN, interior is
// interpolated, trailing NaN is forward-filled with the last valid
// value (NOT extrapolated). [nan,2,nan,4,nan] -> [nan,2,3,4,4].
// (br-frankenpandas-8ic7c)
let col = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Float64(2.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(4.0),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let r = col.interpolate_linear().expect("interpolate");
assert!(r.values()[0].is_missing());
assert_eq!(r.values()[1], Scalar::Float64(2.0));
assert!(
matches!(&r.values()[2], Scalar::Float64(v) if (*v - 3.0).abs() < 1e-9),
"expected Float64, got {:?}",
r.values()[2]
);
assert_eq!(r.values()[3], Scalar::Float64(4.0));
// Trailing NaN forward-filled with the last valid value (4.0).
assert_eq!(r.values()[4], Scalar::Float64(4.0));
}
#[test]
fn interpolate_trailing_run_forward_fills_without_extrapolating() {
// [2,4,nan,nan] -> [2,4,4,4] (ffill), NOT [2,4,6,8] (extrapolation).
let col = Column::from_values(vec![
Scalar::Float64(2.0),
Scalar::Float64(4.0),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let r = col.interpolate_linear().expect("interpolate");
assert_eq!(
r.values(),
&[
Scalar::Float64(2.0),
Scalar::Float64(4.0),
Scalar::Float64(4.0),
Scalar::Float64(4.0),
]
);
}
#[test]
fn interpolate_empty_is_empty_float64() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
let r = col.interpolate_linear().expect("interpolate");
assert!(r.is_empty());
assert_eq!(r.dtype(), DType::Float64);
}
#[test]
fn interpolate_alias_matches_default_linear_interpolation() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
])
.expect("col");
assert_eq!(
col.interpolate().expect("interpolate"),
col.interpolate_linear().expect("interpolate_linear")
);
}
#[test]
fn drop_duplicates_keeps_first_occurrence() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Int64(3),
Scalar::Int64(2),
])
.expect("col");
let d = col.drop_duplicates().expect("drop_duplicates");
assert_eq!(
d.values(),
&[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
);
}
#[test]
fn drop_duplicates_treats_nulls_as_one_bucket() {
let col = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let d = col.drop_duplicates().expect("drop_duplicates");
// First null is kept; subsequent null is dropped.
assert_eq!(d.len(), 2);
assert!(d.values()[0].is_missing());
assert_eq!(d.values()[1], Scalar::Int64(1));
}
#[test]
fn drop_duplicates_keep_variants_match_pandas() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Int64(1),
Scalar::Int64(3),
Scalar::Int64(2),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let last = col.drop_duplicates_keep("last").expect("drop last");
assert_eq!(last.len(), 4);
assert_eq!(last.values()[0], Scalar::Int64(1));
assert_eq!(last.values()[1], Scalar::Int64(3));
assert_eq!(last.values()[2], Scalar::Int64(2));
assert!(last.values()[3].is_missing());
let none = col.drop_duplicates_keep("false").expect("drop none");
assert_eq!(none.values(), &[Scalar::Int64(3)]);
}
#[test]
fn compare_returns_only_differences() {
let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("a");
let b =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(20), Scalar::Int64(3)])
.expect("b");
let (left, right) = a.compare(&b).expect("compare");
assert_eq!(left.values(), &[Scalar::Int64(2)]);
assert_eq!(right.values(), &[Scalar::Int64(20)]);
}
#[test]
fn compare_treats_matching_nulls_as_equal() {
let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
.expect("a");
let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
.expect("b");
let (left, right) = a.compare(&b).expect("compare");
assert!(left.is_empty());
assert!(right.is_empty());
}
#[test]
fn compare_length_mismatch_errors() {
let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("a");
let b = Column::from_values(vec![Scalar::Int64(1)]).expect("b");
let err = a.compare(&b).unwrap_err();
assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
}
#[test]
fn map_applies_unary_function() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let doubled = col
.map(|v| match v {
Scalar::Int64(i) => Scalar::Int64(i * 2),
other => other.clone(),
})
.expect("map");
assert_eq!(doubled.values()[0], Scalar::Int64(2));
assert_eq!(doubled.values()[1], Scalar::Int64(4));
assert_eq!(doubled.values()[2], Scalar::Int64(6));
}
#[test]
fn map_can_change_dtype() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let as_str = col
.map(|v| match v {
Scalar::Int64(i) => Scalar::Utf8(i.to_string()),
other => other.clone(),
})
.expect("map");
assert_eq!(as_str.dtype(), DType::Utf8);
assert_eq!(as_str.values()[0], Scalar::Utf8("1".into()));
}
#[test]
fn argmin_argmax_skip_missing() {
let col = Column::from_values(vec![
Scalar::Int64(3),
Scalar::Null(NullKind::NaN),
Scalar::Int64(1),
Scalar::Int64(5),
Scalar::Int64(2),
])
.expect("col");
assert_eq!(col.argmin(), Some(2));
assert_eq!(col.argmax(), Some(3));
assert_eq!(col.idxmin(), Some(2));
assert_eq!(col.idxmax(), Some(3));
}
#[test]
fn argmin_argmax_all_missing_returns_none() {
let col = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::Null),
])
.expect("col");
assert!(col.argmin().is_none());
assert!(col.argmax().is_none());
assert!(col.idxmin().is_none());
assert!(col.idxmax().is_none());
}
#[test]
fn argmin_argmax_typed_int64_and_nullable_match_nan_reference() {
// The typed Float64/Int64 (all-valid + nullable) argmin/argmax paths must
// be BIT-IDENTICAL to nanargmin/nanargmax — same first-on-tie (strict
// </>), same skip-missing, same f64 compare. NARROW value range forces
// TIES so tie-breaking (first position) is exercised. Null-missing only.
let mut state: u64 = 0xA6E1_1234_9876_5432;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..250 {
let n = (next() % 250) as usize; // include n=0
let mut vi = crate::ValidityMask::all_valid(n);
let mut vf = crate::ValidityMask::all_valid(n);
let idata: Vec<i64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 7) as i64 - 3 // narrow ⇒ ties
})
.collect();
let fdata: Vec<f64> = (0..n)
.map(|i| {
let r = next();
if r % 4 == 0 {
vf.set(i, false);
0.0
} else {
(r % 7) as f64 - 3.0
}
})
.collect();
let i_all = Column::from_i64_values_owned(idata.clone());
let i_null = Column::from_i64_values_with_validity(idata, vi);
let f_null = Column::from_f64_values_with_validity(fdata, vf);
for col in [&i_all, &i_null, &f_null] {
let vals = col.values().to_vec();
assert_eq!(
col.argmin(),
fp_types::nanargmin(&vals),
"argmin trial {trial}"
);
assert_eq!(
col.argmax(),
fp_types::nanargmax(&vals),
"argmax trial {trial}"
);
}
}
}
#[test]
fn is_monotonic_increasing_detects_ascending() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(2),
Scalar::Int64(5),
])
.expect("col");
assert!(col.is_monotonic_increasing());
assert!(!col.is_monotonic_decreasing());
}
#[test]
fn is_monotonic_decreasing_detects_descending() {
let col =
Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(3), Scalar::Int64(1)])
.expect("col");
assert!(col.is_monotonic_decreasing());
assert!(!col.is_monotonic_increasing());
}
#[test]
fn is_monotonic_skips_missing_values() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(3),
Scalar::Int64(5),
])
.expect("col");
assert!(col.is_monotonic_increasing());
}
#[test]
fn is_monotonic_empty_is_true() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
assert!(col.is_monotonic_increasing());
assert!(col.is_monotonic_decreasing());
}
#[test]
fn combine_first_fills_missing_from_other() {
let a = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(3),
])
.expect("a");
let b = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
])
.expect("b");
let c = a.combine_first(&b).expect("combine_first");
assert_eq!(c.values()[0], Scalar::Int64(1));
assert_eq!(c.values()[1], Scalar::Int64(20));
assert_eq!(c.values()[2], Scalar::Int64(3));
}
#[test]
fn combine_first_length_mismatch_errors() {
let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
let err = a.combine_first(&b).unwrap_err();
assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
}
#[test]
fn clip_lower_only() {
let col = Column::from_values(vec![
Scalar::Float64(-2.0),
Scalar::Float64(0.0),
Scalar::Float64(5.0),
])
.expect("col");
let c = col.clip_lower(0.0).expect("clip_lower");
assert_eq!(c.values()[0], Scalar::Float64(0.0));
assert_eq!(c.values()[1], Scalar::Float64(0.0));
assert_eq!(c.values()[2], Scalar::Float64(5.0));
}
#[test]
fn clip_upper_only() {
let col = Column::from_values(vec![
Scalar::Float64(-2.0),
Scalar::Float64(0.0),
Scalar::Float64(5.0),
])
.expect("col");
let c = col.clip_upper(1.0).expect("clip_upper");
assert_eq!(c.values()[0], Scalar::Float64(-2.0));
assert_eq!(c.values()[1], Scalar::Float64(0.0));
assert_eq!(c.values()[2], Scalar::Float64(1.0));
}
#[test]
fn describe_returns_pandas_order() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
Scalar::Float64(4.0),
Scalar::Float64(5.0),
])
.expect("col");
let stats = col.describe().expect("describe");
let names: Vec<&str> = stats.iter().map(|(k, _)| *k).collect();
assert_eq!(
names,
vec!["count", "mean", "std", "min", "25%", "50%", "75%", "max"]
);
assert_eq!(stats[0].1, Scalar::Int64(5));
assert!(
matches!(&stats[1].1, Scalar::Float64(v) if (*v - 3.0).abs() < 1e-9),
"expected Float64, got {:?}",
stats[1].1
);
assert_eq!(stats[3].1, Scalar::Float64(1.0));
assert_eq!(stats[7].1, Scalar::Float64(5.0));
}
#[test]
fn describe_rejects_utf8_column() {
let col = Column::from_values(vec![Scalar::Utf8("a".into())]).expect("col");
assert!(col.describe().is_err());
}
#[test]
fn combine_uses_fill_for_missing() {
let a = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(3),
])
.expect("a");
let b = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Null(NullKind::NaN),
])
.expect("b");
let out = a
.combine(
&b,
|l, r| {
if let (Ok(lf), Ok(rf)) = (l.to_f64(), r.to_f64()) {
Scalar::Float64(lf + rf)
} else {
Scalar::Null(NullKind::NaN)
}
},
Some(Scalar::Int64(0)),
)
.expect("combine");
assert_eq!(out.values()[0], Scalar::Float64(11.0));
assert_eq!(out.values()[1], Scalar::Float64(20.0));
assert_eq!(out.values()[2], Scalar::Float64(3.0));
}
#[test]
fn combine_length_mismatch_errors() {
let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
let err = a
.combine(&b, |l, _| l.clone(), Some(Scalar::Int64(0)))
.unwrap_err();
assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
}
#[test]
fn combine_fill_none_propagates_nulls_without_invoking_func() {
let a = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
])
.expect("a");
let b = Column::from_values(vec![
Scalar::Float64(10.0),
Scalar::Float64(20.0),
Scalar::Null(NullKind::NaN),
])
.expect("b");
let mut calls = 0usize;
let out = a
.combine(
&b,
|l, r| {
calls += 1;
Scalar::Float64(l.to_f64().unwrap() + r.to_f64().unwrap())
},
None,
)
.expect("combine");
// Only the position with both non-null invokes func.
assert_eq!(calls, 1);
assert_eq!(out.values()[0], Scalar::Float64(11.0));
assert!(out.values()[1].is_missing());
assert!(out.values()[2].is_missing());
}
#[test]
fn combine_fill_none_all_present_matches_elementwise_apply() {
let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("a");
let b = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("b");
let out = a
.combine(
&b,
|l, r| Scalar::Int64(l.to_f64().unwrap() as i64 + r.to_f64().unwrap() as i64),
None,
)
.expect("combine");
assert_eq!(out.values()[0], Scalar::Int64(11));
assert_eq!(out.values()[1], Scalar::Int64(22));
}
#[test]
fn apply_float_applies_numeric_fn() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(4.0),
])
.expect("col");
let out = col.apply_float(|x| x.sqrt()).expect("apply_float");
assert_eq!(out.values()[0], Scalar::Float64(1.0));
assert!(out.values()[1].is_missing());
assert_eq!(out.values()[2], Scalar::Float64(2.0));
assert_eq!(out.dtype(), DType::Float64);
}
#[test]
fn apply_float_rejects_non_numeric() {
let col = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("col");
assert!(col.apply_float(|x| x + 1.0).is_err());
}
#[test]
fn hist_counts_equal_width_bins() {
let col = Column::from_values(vec![
Scalar::Float64(0.0),
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
Scalar::Float64(9.0),
])
.expect("col");
let counts = col.hist_counts(3);
// Bin width = 3, buckets [0,3), [3,6), [6,9]
assert_eq!(counts.len(), 3);
assert_eq!(counts[0], 3); // 0,1,2
assert_eq!(counts[1], 1); // 3
assert_eq!(counts[2], 1); // 9 clamps into last bin
}
#[test]
fn hist_counts_zero_bins_is_empty() {
let col = Column::from_values(vec![Scalar::Float64(1.0)]).expect("col");
assert!(col.hist_counts(0).is_empty());
}
#[test]
fn hist_counts_constant_column_puts_all_in_first_bin() {
let col = Column::from_values(vec![
Scalar::Float64(5.0),
Scalar::Float64(5.0),
Scalar::Float64(5.0),
])
.expect("col");
let counts = col.hist_counts(3);
assert_eq!(counts[0], 3);
assert_eq!(counts[1], 0);
assert_eq!(counts[2], 0);
}
#[test]
fn nunique_drops_nulls() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
])
.expect("col");
assert_eq!(col.nunique(), Scalar::Int64(2));
}
#[test]
fn nunique_wide_i64_open_addressing_matches_reference() {
// The wide/sparse all-valid Int64 path uses count_distinct_i64_wide
// (open-addressing set). Must equal a HashSet reference across random
// wide data AND the i64::MIN empty-sentinel edge.
use std::collections::HashSet;
// Deterministic LCG, sparse full-range values + forced duplicates +
// both i64::MIN and i64::MAX present.
let mut state: u64 = 0xDEAD_BEEF_1234_5678;
let mut data: Vec<i64> = Vec::with_capacity(20_000);
for _ in 0..10_000 {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
let v = (state >> 1) as i64;
data.push(v);
data.push(v); // duplicate every value
}
data.push(i64::MIN);
data.push(i64::MIN); // sentinel value, duplicated
data.push(i64::MAX);
let expected = data.iter().copied().collect::<HashSet<i64>>().len() as i64;
let col = Column::from_i64_values_owned(data);
assert!(
col.as_i64_slice().is_some(),
"from_i64_values must expose a typed slice so the wide path runs"
);
assert_eq!(col.nunique(), Scalar::Int64(expected));
assert_eq!(col.nunique_with_dropna(false), Scalar::Int64(expected));
}
#[test]
fn count_distinct_radix_high_bit_shifted_keys_matches_reference() {
// Regression for the count_distinct_i64_radix per-partition hash fix:
// HIGH-bit-only-varying keys (k << 34) whose hashv has ZERO low bits —
// the old `hashv & mask` collapsed each partition to one bucket. The
// radix count must equal a HashSet reference AND the single-table count,
// across shifts that (do/don't) zero the low bits, plus i64::MIN.
use std::collections::HashSet;
let mut state: u64 = 0xF00D_CAFE_1357_2468;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for &sh in &[34u32, 40, 20, 0] {
for trial in 0..15 {
let n = 6000 + (next() % 4000) as usize;
let distinct = 800 + (next() % 3000) as i64;
let mut data: Vec<i64> = (0..n)
.map(|i| {
if i % 700 == 0 {
i64::MIN
} else {
(((next() % distinct as u64) as i64) - distinct / 2) << sh
}
})
.collect();
data.push(i64::MIN);
let want = data.iter().copied().collect::<HashSet<i64>>().len() as i64;
assert_eq!(
crate::count_distinct_i64_radix(&data),
want,
"radix sh={sh} trial {trial}"
);
assert_eq!(
crate::count_distinct_i64_singletable(&data),
want,
"singletable sh={sh} trial {trial}"
);
}
}
}
#[test]
fn nunique_with_dropna_false_counts_missing_once() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::Null),
])
.expect("col");
assert_eq!(col.nunique_with_dropna(false), Scalar::Int64(3));
}
#[test]
fn nunique_with_dropna_false_all_missing_is_one() {
let col = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::Null),
Scalar::Null(NullKind::NaN),
])
.expect("col");
assert_eq!(col.nunique(), Scalar::Int64(0));
assert_eq!(col.nunique_with_dropna(false), Scalar::Int64(1));
}
#[test]
fn nunique_nullable_bool_typed_matches_scalar_oracle() {
let mut state = 0xB001_5EED_1234_5678_u64;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..200 {
let n = (next() % 400) as usize;
let null_mode = next() % 3;
let mut data = Vec::with_capacity(n);
let mut validity = ValidityMask::all_valid(n);
let mut scalar_oracle = Vec::with_capacity(n);
for i in 0..n {
let value = next() & 1 == 1;
let missing = match null_mode {
0 => false,
2 => true,
_ => next().is_multiple_of(4),
};
data.push(value);
if missing {
validity.set(i, false);
scalar_oracle.push(Scalar::Null(NullKind::Null));
} else {
scalar_oracle.push(Scalar::Bool(value));
}
}
let column = Column::from_bool_values_with_validity(data, validity);
for dropna in [true, false] {
let mut expected = match fp_types::nannunique(&scalar_oracle) {
Scalar::Int64(count) => count,
_ => unreachable!("nannunique count must be Int64"),
};
if !dropna && scalar_oracle.iter().any(Scalar::is_missing) {
expected += 1;
}
assert_eq!(
column.nunique_with_dropna(dropna),
Scalar::Int64(expected),
"trial={trial} null_mode={null_mode} dropna={dropna}"
);
}
}
}
#[test]
fn nunique_nullable_utf8_typed_matches_generic() {
// The typed nullable-Utf8 nunique arm (cold cache) must be BIT-EXACT to the
// generic nannunique path for BOTH dropna values. A/B on identical
// LazyNullableUtf8 data: `col_cold` (fresh, cold cache) exercises the typed
// arm; `col_warm` has its Scalar cache pre-materialized so the cold-cache gate
// defers it to the generic path. Seeded short strings over {a,b,c,d} + ~25%
// nulls; some trials fully-null (distinct present = 0), some no-null.
let mut state: u64 = 0x4E17_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 300) as usize;
// Vary null density per trial: 0 (none), 1 (~25%), 2 (all-null).
let null_mode = next() % 3;
let mut validity = crate::ValidityMask::all_valid(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..n {
let is_null = match null_mode {
0 => false,
2 => true,
_ => next() % 4 == 0,
};
if is_null {
validity.set(i, false);
} else {
let len = (next() % 5) as usize;
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
}
offsets.push(bytes.len());
}
let col_cold = Column::from_utf8_values_with_validity(
bytes.clone(),
offsets.clone(),
validity.clone(),
);
let col_warm =
Column::from_utf8_values_with_validity(bytes, offsets, validity);
let _ = col_warm.values(); // warm cache ⇒ generic path (oracle)
for dropna in [true, false] {
assert_eq!(
col_cold.nunique_with_dropna(dropna),
col_warm.nunique_with_dropna(dropna),
"trial {trial} null_mode={null_mode} dropna={dropna}"
);
}
}
}
#[test]
fn any_all_reductions() {
let col = Column::from_values(vec![Scalar::Int64(0), Scalar::Int64(0)]).expect("col");
assert_eq!(col.any(), Scalar::Bool(false));
assert_eq!(col.all(), Scalar::Bool(false));
let mixed = Column::from_values(vec![Scalar::Int64(0), Scalar::Int64(1)]).expect("col");
assert_eq!(mixed.any(), Scalar::Bool(true));
assert_eq!(mixed.all(), Scalar::Bool(false));
let all_true =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
assert_eq!(all_true.all(), Scalar::Bool(true));
}
#[test]
fn is_unique_true_when_no_repeats() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
assert!(col.is_unique());
assert!(!col.has_duplicates());
}
#[test]
fn has_duplicates_true_when_repeats_present() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(1)]).expect("col");
assert!(col.has_duplicates());
assert!(!col.is_unique());
}
#[test]
fn has_duplicates_typed_int64_matches_reference_without_materializing_zny9w() {
let cases = [
Vec::new(),
vec![7],
vec![3, -1, 8, i64::MIN, i64::MAX],
vec![4, 4],
vec![i64::MIN, 0, i64::MAX, i64::MIN],
vec![9, 3, 1, 0, -7, 9],
];
for values in cases {
let mut seen = rustc_hash::FxHashSet::<i64>::default();
let expected = values.iter().any(|value| !seen.insert(*value));
let column = Column::from_i64_values_owned(values);
assert!(matches!(
&column.values,
ScalarValues::LazyAllValidInt64Vec { .. }
));
if let ScalarValues::LazyAllValidInt64Vec {
values: scalar_cache,
..
} = &column.values
{
assert!(scalar_cache.get().is_none());
assert_eq!(column.has_duplicates(), expected);
assert_eq!(column.is_unique(), !expected);
assert!(scalar_cache.get().is_none());
}
}
}
#[test]
fn is_unique_ignores_nulls() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
])
.expect("col");
assert!(col.is_unique());
}
#[test]
fn pct_change_typed_matches_independent_oracle() {
// Typed i64/f64 pct_change == a hand oracle: boundary & zero-prev → Null,
// else Float64((c−p)/p). ± periods incl. negative. (A Scalar-backed twin
// would also route through the typed path, so use an independent oracle.)
let mut state: u64 = 0x13F9_AC02_55E1_77B3;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let vals_eq = |a: &[Scalar], b: &[Scalar]| -> bool {
a.len() == b.len()
&& a.iter().zip(b).all(|(x, y)| match (x, y) {
(Scalar::Float64(p), Scalar::Float64(q)) => p.to_bits() == q.to_bits(),
_ => x == y,
})
};
for _ in 0..200 {
let n = (next() % 80) as usize + 1;
// include zeros (→ zero-prev Null) and negatives
let fvals: Vec<f64> = (0..n).map(|_| (next() % 9) as f64 - 4.0).collect();
let ivals: Vec<i64> = fvals.iter().map(|&v| v as i64).collect();
let fcol = Column::from_f64_values(fvals.clone());
let icol = Column::from_i64_values_owned(ivals.clone());
for p in [1i64, 2, -1, -2] {
let abs = p.unsigned_abs() as usize;
let oracle = |get: &dyn Fn(usize) -> f64| -> Vec<Scalar> {
(0..n)
.map(|i| {
let pi = if p > 0 {
i.checked_sub(abs)
} else if i + abs < n {
Some(i + abs)
} else {
None
};
match pi {
Some(j) if get(j) != 0.0 => {
Scalar::Float64((get(i) - get(j)) / get(j))
}
_ => Scalar::Null(NullKind::NaN),
}
})
.collect()
};
assert!(vals_eq(
fcol.pct_change(p).unwrap().values(),
&oracle(&|i| fvals[i])
));
assert!(vals_eq(
icol.pct_change(p).unwrap().values(),
&oracle(&|i| ivals[i] as f64)
));
}
}
}
#[test]
fn pct_change_periods_one() {
let col = Column::from_values(vec![
Scalar::Float64(10.0),
Scalar::Float64(12.0),
Scalar::Float64(9.0),
])
.expect("col");
let r = col.pct_change(1).expect("pct_change");
assert!(r.values()[0].is_missing());
assert!(
matches!(&r.values()[1], Scalar::Float64(v) if (*v - 0.2).abs() < 1e-9),
"expected Float64, got {:?}",
r.values()[1]
);
assert!(
matches!(&r.values()[2], Scalar::Float64(v) if (*v + 0.25).abs() < 1e-9),
"expected Float64, got {:?}",
r.values()[2]
);
}
#[test]
fn pct_change_zero_prev_yields_null() {
let col =
Column::from_values(vec![Scalar::Float64(0.0), Scalar::Float64(5.0)]).expect("col");
let r = col.pct_change(1).expect("pct_change");
assert!(r.values()[1].is_missing());
}
#[test]
fn pct_change_timedelta64_matches_pandas_mcu90() {
// Per br-frankenpandas-mcu90: pct_change on Timedelta64 returns
// dimensionless f64 ratios; was silently NaN before via the
// to_f64-else catch-all (Timedelta64.to_f64() errors).
let one_hour = 3_600 * 1_000_000_000_i64;
let col = Column::from_values(vec![
Scalar::Timedelta64(one_hour),
Scalar::Timedelta64(2 * one_hour),
Scalar::Timedelta64(4 * one_hour),
])
.expect("col");
let r = col.pct_change(1).expect("pct_change");
assert!(r.values()[0].is_missing());
assert!(
matches!(&r.values()[1], Scalar::Float64(v) if (*v - 1.0).abs() < 1e-10),
"expected Float64(1.0), got {:?}",
r.values()[1]
);
assert!(
matches!(&r.values()[2], Scalar::Float64(v) if (*v - 1.0).abs() < 1e-10),
"expected Float64(1.0), got {:?}",
r.values()[2]
);
}
#[test]
fn pct_change_timedelta64_nat_propagates_mcu90() {
use fp_types::Timedelta;
let one_hour = 3_600 * 1_000_000_000_i64;
let col = Column::from_values(vec![
Scalar::Timedelta64(one_hour),
Scalar::Timedelta64(Timedelta::NAT),
Scalar::Timedelta64(2 * one_hour),
])
.expect("col");
let r = col.pct_change(1).expect("pct_change");
assert!(r.values()[0].is_missing());
assert!(r.values()[1].is_missing()); // NaT current → NaN
assert!(r.values()[2].is_missing()); // NaT previous → NaN
}
#[test]
fn pct_change_with_fill_ffill_uses_filled_previous_value() {
let col = Column::from_values(vec![
Scalar::Float64(10.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(12.0),
])
.expect("col");
let r = col
.pct_change_with_fill(1, Some("ffill"), None)
.expect("pct_change_with_fill");
assert!(r.values()[0].is_missing());
assert!(
matches!(&r.values()[1], Scalar::Float64(v) if v.abs() < 1e-9),
"expected Float64, got {:?}",
r.values()[1]
);
assert!(
matches!(&r.values()[2], Scalar::Float64(v) if (*v - 0.2).abs() < 1e-9),
"expected Float64, got {:?}",
r.values()[2]
);
}
#[test]
fn pct_change_with_fill_limit_caps_forward_fill_runs() {
let col = Column::from_values(vec![
Scalar::Float64(10.0),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Float64(20.0),
])
.expect("col");
let r = col
.pct_change_with_fill(1, Some("ffill"), Some(1))
.expect("pct_change_with_fill");
assert!(r.values()[0].is_missing());
assert!(
matches!(&r.values()[1], Scalar::Float64(v) if v.abs() < 1e-9),
"expected Float64, got {:?}",
r.values()[1]
);
assert!(r.values()[2].is_missing());
assert!(r.values()[3].is_missing());
}
#[test]
fn pct_change_with_fill_bfill_aliases_backward_fill() {
let col = Column::from_values(vec![
Scalar::Float64(10.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(20.0),
])
.expect("col");
let r = col
.pct_change_with_fill(1, Some("backfill"), None)
.expect("pct_change_with_fill");
assert!(r.values()[0].is_missing());
assert!(
matches!(&r.values()[1], Scalar::Float64(v) if (*v - 1.0).abs() < 1e-9),
"expected Float64, got {:?}",
r.values()[1]
);
assert!(
matches!(&r.values()[2], Scalar::Float64(v) if v.abs() < 1e-9),
"expected Float64, got {:?}",
r.values()[2]
);
}
#[test]
fn pct_change_with_fill_rejects_invalid_method() {
let col =
Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("col");
let err = col
.pct_change_with_fill(1, Some("nearest"), None)
.expect_err("invalid fill_method should error");
assert!(matches!(
err,
crate::ColumnError::Type(fp_types::TypeError::NonNumericValue { .. })
));
}
#[test]
fn ffill_bfill_typed_match_independent_oracle() {
// Typed nullable i64/f64 ffill+bfill (limit None & Some) == an
// independent oracle. Built via from_*_values_with_validity to drive
// the typed paths. i64 missing → Null(Null), f64 missing → Null(NaN).
let mut state: u64 = 0x9F1D_0E2A_57C4_BB36;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..200 {
let n = (next() % 120) as usize + 1;
let ivals: Vec<i64> = (0..n).map(|_| (next() % 1000) as i64).collect();
let fvals: Vec<f64> = ivals.iter().map(|&v| v as f64 + 0.5).collect();
let mut vmask = ValidityMask::all_valid(n);
let mut present = vec![true; n];
for (i, p) in present.iter_mut().enumerate() {
if next() % 3 == 0 {
vmask.set(i, false);
*p = false;
}
}
let icol = Column::from_i64_values_with_validity(ivals.clone(), vmask.clone());
let fcol = Column::from_f64_values_with_validity(fvals.clone(), vmask.clone());
for limit in [None, Some(1usize), Some(2)] {
// ffill oracle
let oracle = |fwd: bool| -> Vec<Option<usize>> {
let mut src: Vec<Option<usize>> = vec![None; n];
let mut anchor: Option<usize> = None;
let mut run = 0usize;
let idxs: Vec<usize> = if fwd {
(0..n).collect()
} else {
(0..n).rev().collect()
};
for &i in &idxs {
if present[i] {
src[i] = Some(i);
anchor = Some(i);
run = 0;
} else {
match (anchor, limit) {
(Some(a), None) => src[i] = Some(a),
(Some(a), Some(cap)) if run < cap => {
src[i] = Some(a);
run += 1;
}
_ => {}
}
}
}
src
};
for (fwd, got_i, got_f) in [
(true, icol.ffill(limit).unwrap(), fcol.ffill(limit).unwrap()),
(
false,
icol.bfill(limit).unwrap(),
fcol.bfill(limit).unwrap(),
),
] {
let src = oracle(fwd);
for (i, slot) in src.iter().enumerate().take(n) {
match *slot {
Some(a) => {
assert_eq!(got_i.values()[i], Scalar::Int64(ivals[a]));
assert_eq!(got_f.values()[i], Scalar::Float64(fvals[a]));
}
None => {
assert!(got_i.values()[i].is_missing());
assert!(got_f.values()[i].is_missing());
}
}
}
}
}
}
}
#[test]
fn ffill_fills_trailing_missing_runs() {
let col = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Int64(5),
])
.expect("col");
let r = col.ffill(None).expect("ffill");
assert!(r.values()[0].is_missing());
assert_eq!(r.values()[1], Scalar::Int64(1));
assert_eq!(r.values()[2], Scalar::Int64(1));
assert_eq!(r.values()[3], Scalar::Int64(1));
assert_eq!(r.values()[4], Scalar::Int64(5));
}
#[test]
fn ffill_respects_limit_per_run() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Int64(9),
])
.expect("col");
let r = col.ffill(Some(2)).expect("ffill");
assert_eq!(r.values()[0], Scalar::Int64(1));
assert_eq!(r.values()[1], Scalar::Int64(1));
assert_eq!(r.values()[2], Scalar::Int64(1));
assert!(r.values()[3].is_missing());
assert_eq!(r.values()[4], Scalar::Int64(9));
assert_eq!(col.pad(Some(2)), col.ffill(Some(2)));
}
#[test]
fn bfill_fills_leading_missing_runs() {
let col = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Int64(3),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let r = col.bfill(None).expect("bfill");
assert_eq!(r.values()[0], Scalar::Int64(3));
assert_eq!(r.values()[1], Scalar::Int64(3));
assert_eq!(r.values()[2], Scalar::Int64(3));
// Trailing null stays null (no next value).
assert!(r.values()[3].is_missing());
}
#[test]
fn bfill_respects_limit_per_run() {
let col = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Int64(7),
])
.expect("col");
let r = col.bfill(Some(1)).expect("bfill");
assert!(r.values()[0].is_missing());
assert!(r.values()[1].is_missing());
assert_eq!(r.values()[2], Scalar::Int64(7));
assert_eq!(r.values()[3], Scalar::Int64(7));
assert_eq!(col.backfill(Some(1)), col.bfill(Some(1)));
}
#[test]
fn ffill_empty_is_empty_same_dtype() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
let r = col.ffill(None).expect("ffill");
assert!(r.is_empty());
assert_eq!(r.dtype(), DType::Null);
}
#[test]
fn pandas_metadata_and_materialization_aliases_match_core_methods()
-> Result<(), crate::ColumnError> {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(2),
])?;
assert_eq!(col.size(), col.len());
assert_eq!(col.shape(), (col.len(),));
assert_eq!(col.ndim(), 1);
assert_eq!(col.empty(), col.is_empty());
assert_eq!(col.to_list(), col.to_vec());
assert_eq!(col.tolist(), col.to_vec());
assert_eq!(col.to_numpy(), col.to_vec());
assert_eq!(col.ravel(), col.to_numpy());
assert_eq!(col.array(), col.to_vec());
Ok(())
}
#[test]
fn isnull_notnull_flag_missing_positions() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(2),
])
.expect("col");
let is_null = col.isnull().expect("isnull");
let not_null = col.notnull().expect("notnull");
assert_eq!(is_null.dtype(), DType::Bool);
assert_eq!(
is_null.values(),
&[Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(false),]
);
assert_eq!(col.isna(), col.isnull());
assert_eq!(
not_null.values(),
&[Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true),]
);
assert_eq!(col.notna(), col.notnull());
}
#[test]
fn null_predicates_match_scalar_oracle_zvykt() {
// Differential vs Scalar::is_missing oracle (br-frankenpandas-zvykt).
// Seeded LCG, no mocks.
fn next(seed: &mut u64) -> u64 {
*seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
*seed
}
let mut seed = 0x5a17_1e55_0b5e_7a11_u64;
for case in 0..260 {
let len = (next(&mut seed) % 73 + 1) as usize;
let mut values = Vec::with_capacity(len);
for pos in 0..len {
let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
values.push(match next(&mut seed) % 10 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
2 => Scalar::Float64(f64::NAN),
3 => Scalar::Float64(f64::INFINITY),
4 => Scalar::Float64(f64::NEG_INFINITY),
5 => Scalar::Float64(raw as f64 / 41.0 + frac),
6 => Scalar::Int64(raw),
7 => Scalar::Bool(raw & 1 == 0),
8 => Scalar::Utf8(format!("v{case}_{pos}")),
_ => Scalar::Timedelta64(raw),
});
}
let input = Column::from_values(values.clone()).expect("column");
let is_null = input.isnull().expect("isnull");
let is_na = input.isna().expect("isna");
let not_null = input.notnull().expect("notnull");
let not_na = input.notna().expect("notna");
assert_eq!(is_null.dtype(), DType::Bool);
assert_eq!(is_na.values(), is_null.values());
assert_eq!(not_na.values(), not_null.values());
assert_eq!(is_null.values().len(), values.len());
assert_eq!(not_null.values().len(), values.len());
for (pos, value) in values.iter().enumerate() {
let missing = value.is_missing();
assert_eq!(
is_null.values()[pos],
Scalar::Bool(missing),
"case={case} pos={pos}: isnull mismatch for {value:?}"
);
assert_eq!(
not_null.values()[pos],
Scalar::Bool(!missing),
"case={case} pos={pos}: notnull mismatch for {value:?}"
);
}
}
}
#[test]
fn missing_reducers_match_scalar_oracle_8n9cp() {
// Differential vs any/all over Scalar::is_missing
// (br-frankenpandas-8n9cp). Seeded LCG, no mocks.
fn next(seed: &mut u64) -> u64 {
*seed = seed
.wrapping_mul(2862933555777941757)
.wrapping_add(3037000493);
*seed
}
let empty = Column::new(DType::Float64, Vec::new()).expect("empty");
assert!(!empty.has_any_missing());
assert!(!empty.hasnans());
assert!(empty.all_missing());
let mut seed = 0x8a11_a115_1d5d_0a7a_u64;
for case in 0..260 {
let len = (next(&mut seed) % 79 + 1) as usize;
let mut values = Vec::with_capacity(len);
for pos in 0..len {
let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
values.push(match next(&mut seed) % 10 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
2 => Scalar::Float64(f64::NAN),
3 => Scalar::Float64(f64::INFINITY),
4 => Scalar::Float64(f64::NEG_INFINITY),
5 => Scalar::Float64(raw as f64 / 43.0 + frac),
6 => Scalar::Int64(raw),
7 => Scalar::Bool(raw & 1 == 0),
8 => Scalar::Utf8(format!("m{case}_{pos}")),
_ => Scalar::Timedelta64(raw),
});
}
let input = Column::from_values(values.clone()).expect("column");
let any_missing = values.iter().any(Scalar::is_missing);
let all_missing = values.iter().all(Scalar::is_missing);
assert_eq!(
input.has_any_missing(),
any_missing,
"case={case}: has_any_missing mismatch for {values:?}"
);
assert_eq!(
input.hasnans(),
any_missing,
"case={case}: hasnans mismatch for {values:?}"
);
assert_eq!(
input.all_missing(),
all_missing,
"case={case}: all_missing mismatch for {values:?}"
);
}
}
#[test]
fn isnull_notnull_use_nullable_int64_validity_without_scalar_materialization_nakgb() {
let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 2), (5, 1)]), 6);
let col = Column::from_i64_values_with_validity((0_i64..6).collect(), validity);
let is_null = col.isnull().expect("isnull");
let not_null = col.notnull().expect("notnull");
assert_eq!(
is_null.values(),
&[
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(true),
]
);
assert_eq!(
not_null.values(),
&[
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(false),
]
);
assert!(matches!(
&col.values,
ScalarValues::LazyNullableInt64 { .. }
));
if let ScalarValues::LazyNullableInt64 { values, .. } = &col.values {
assert!(values.get().is_none());
}
}
#[test]
fn isnull_notnull_float64_raw_path_checks_nan_without_scalar_materialization_nakgb() {
let col = Column {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64(vec![1.0, f64::NAN, f64::INFINITY]),
validity: ValidityMask::all_valid(3),
data: None,
};
let is_null = col.isnull().expect("isnull");
let not_null = col.notnull().expect("notnull");
assert_eq!(
is_null.values(),
&[Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(false),]
);
assert_eq!(
not_null.values(),
&[Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true),]
);
assert!(matches!(
&col.values,
ScalarValues::LazyAllValidFloat64 { .. }
));
if let ScalarValues::LazyAllValidFloat64 { values, .. } = &col.values {
assert!(values.get().is_none());
}
}
#[test]
fn float64_predicate_masks_use_raw_validity_without_scalar_materialization_ti9f1() {
let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 1)]), 4);
let col = Column::from_f64_values_with_validity(
vec![1.0, 0.0, f64::NAN, f64::INFINITY],
validity,
);
assert_eq!(
col.isfinite().expect("isfinite").values(),
&[
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(false),
]
);
assert_eq!(
col.isinf().expect("isinf").values(),
&[
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(true),
]
);
assert_eq!(
col.isnan().expect("isnan").values(),
&[
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(false),
]
);
assert!(matches!(
&col.values,
ScalarValues::LazyNullableFloat64 { .. }
));
if let ScalarValues::LazyNullableFloat64 { values, .. } = &col.values {
assert!(values.get().is_none());
}
}
#[test]
fn finite_predicates_match_scalar_oracle_dknku() {
// Differential vs scalar predicate oracle (br-frankenpandas-dknku).
// Seeded LCG, no mocks.
fn next(seed: &mut u64) -> u64 {
*seed = seed
.wrapping_mul(1442695040888963407)
.wrapping_add(6364136223846793005);
*seed
}
fn oracle(value: &Scalar) -> (bool, bool, bool) {
let isfinite = match value {
Scalar::Float64(v) => v.is_finite(),
Scalar::Int64(_) => true,
_ if value.is_missing() => false,
_ => true,
};
let isinf = matches!(value, Scalar::Float64(v) if v.is_infinite());
let isnan = match value {
Scalar::Float64(v) => v.is_nan(),
Scalar::Null(NullKind::NaN) => true,
_ => false,
};
(isfinite, isinf, isnan)
}
let mut seed = 0xd1ff_1e5d_f1a7_00c5_u64;
for case in 0..240 {
let len = (next(&mut seed) % 71 + 1) as usize;
let mut values = Vec::with_capacity(len);
for pos in 0..len {
let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
values.push(match next(&mut seed) % 9 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
2 => Scalar::Float64(f64::NAN),
3 => Scalar::Float64(f64::INFINITY),
4 => Scalar::Float64(f64::NEG_INFINITY),
5 => Scalar::Int64(raw),
6 => Scalar::Utf8(format!("s{case}_{pos}")),
_ => Scalar::Float64(raw as f64 / 37.0 + frac),
});
}
let input = Column::from_values(values.clone()).expect("column");
let finite = input.isfinite().expect("isfinite");
let infinite = input.isinf().expect("isinf");
let nan = input.isnan().expect("isnan");
assert_eq!(finite.dtype(), DType::Bool);
assert_eq!(infinite.dtype(), DType::Bool);
assert_eq!(nan.dtype(), DType::Bool);
assert_eq!(finite.values().len(), values.len());
assert_eq!(infinite.values().len(), values.len());
assert_eq!(nan.values().len(), values.len());
for (pos, value) in values.iter().enumerate() {
let (expected_finite, expected_inf, expected_nan) = oracle(value);
assert_eq!(
finite.values()[pos],
Scalar::Bool(expected_finite),
"case={case} pos={pos}: isfinite mismatch for {value:?}"
);
assert_eq!(
infinite.values()[pos],
Scalar::Bool(expected_inf),
"case={case} pos={pos}: isinf mismatch for {value:?}"
);
assert_eq!(
nan.values()[pos],
Scalar::Bool(expected_nan),
"case={case} pos={pos}: isnan mismatch for {value:?}"
);
}
}
}
#[test]
fn logical_bool_ops_use_raw_buffers_without_scalar_materialization_el0g2() {
let left = Column {
dtype: DType::Bool,
values: ScalarValues::lazy_all_valid_bool(vec![true, false, true, false]),
validity: ValidityMask::all_valid(4),
data: None,
};
let right = Column {
dtype: DType::Bool,
values: ScalarValues::lazy_all_valid_bool(vec![true, true, false, false]),
validity: ValidityMask::all_valid(4),
data: None,
};
assert_eq!(
left.logical_and(&right).expect("and").values(),
&[
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(false),
]
);
assert_eq!(
left.logical_or(&right).expect("or").values(),
&[
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(false),
]
);
assert_eq!(
left.logical_xor(&right).expect("xor").values(),
&[
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(false),
]
);
assert_eq!(
left.logical_not().expect("not").values(),
&[
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
]
);
assert!(matches!(
&left.values,
ScalarValues::LazyAllValidBool { .. }
));
assert!(matches!(
&right.values,
ScalarValues::LazyAllValidBool { .. }
));
if let ScalarValues::LazyAllValidBool { values, .. } = &left.values {
assert!(values.get().is_none());
}
if let ScalarValues::LazyAllValidBool { values, .. } = &right.values {
assert!(values.get().is_none());
}
}
#[test]
fn bitwise_bool_ops_use_raw_buffers_without_scalar_materialization_ffoy7() {
let left = Column {
dtype: DType::Bool,
values: ScalarValues::lazy_all_valid_bool(vec![true, false, true, false]),
validity: ValidityMask::all_valid(4),
data: None,
};
let right = Column {
dtype: DType::Bool,
values: ScalarValues::lazy_all_valid_bool(vec![false, false, true, true]),
validity: ValidityMask::all_valid(4),
data: None,
};
assert_eq!(
left.bitwise_and(&right).expect("and").values(),
&[
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(false),
]
);
assert_eq!(
left.bitwise_or(&right).expect("or").values(),
&[
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(true),
]
);
assert_eq!(
left.bitwise_xor(&right).expect("xor").values(),
&[
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(true),
]
);
assert_eq!(
left.bitwise_not().expect("not").values(),
&[
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
]
);
assert!(matches!(
&left.values,
ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
));
assert!(matches!(
&right.values,
ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
));
}
#[test]
fn bool_comparison_ops_use_raw_buffers_without_scalar_materialization_v7rko() {
let left = Column {
dtype: DType::Bool,
values: ScalarValues::lazy_all_valid_bool(vec![false, false, true, true]),
validity: ValidityMask::all_valid(4),
data: None,
};
let right = Column {
dtype: DType::Bool,
values: ScalarValues::lazy_all_valid_bool(vec![false, true, false, true]),
validity: ValidityMask::all_valid(4),
data: None,
};
assert_eq!(
left.eq(&right).expect("eq").values(),
&[
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(true),
]
);
assert_eq!(
left.ne(&right).expect("ne").values(),
&[
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(false),
]
);
assert_eq!(
left.gt(&right).expect("gt").values(),
&[
Scalar::Bool(false),
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(false),
]
);
assert_eq!(
left.lt(&right).expect("lt").values(),
&[
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(false),
]
);
assert_eq!(
left.ge(&right).expect("ge").values(),
&[
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(true),
]
);
assert_eq!(
left.le(&right).expect("le").values(),
&[
Scalar::Bool(true),
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
]
);
assert!(matches!(
&left.values,
ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
));
assert!(matches!(
&right.values,
ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
));
}
#[test]
fn var_std_sem_ddof_one() {
let col = Column::from_values(vec![
Scalar::Float64(2.0),
Scalar::Float64(4.0),
Scalar::Float64(4.0),
Scalar::Float64(4.0),
Scalar::Float64(5.0),
Scalar::Float64(5.0),
Scalar::Float64(7.0),
Scalar::Float64(9.0),
])
.expect("col");
match col.var(1) {
Scalar::Float64(v) => assert!((v - 4.571428571428571).abs() < 1e-9),
other => unreachable!("expected Float64, got {other:?}"),
}
match col.std(1) {
Scalar::Float64(v) => assert!((v - 2.138089935299395).abs() < 1e-9),
other => unreachable!("expected Float64, got {other:?}"),
}
match col.sem(1) {
Scalar::Float64(v) => assert!((v - 0.7559289460184544).abs() < 1e-9),
other => unreachable!("expected Float64, got {other:?}"),
}
}
#[test]
fn skew_symmetric_is_zero() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
Scalar::Float64(4.0),
Scalar::Float64(5.0),
])
.expect("col");
match col.skew() {
Scalar::Float64(v) => assert!(v.abs() < 1e-9),
other => unreachable!("expected Float64, got {other:?}"),
}
}
#[test]
fn kurt_uniform_five_values_is_minus_one_point_two() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
Scalar::Float64(4.0),
Scalar::Float64(5.0),
])
.expect("col");
match col.kurt() {
Scalar::Float64(v) => assert!((v + 1.2).abs() < 1e-9),
other => unreachable!("expected Float64, got {other:?}"),
}
}
#[test]
fn kurtosis_alias_matches_kurt() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
Scalar::Float64(4.0),
Scalar::Float64(5.0),
])
.expect("col");
assert_eq!(col.kurtosis(), col.kurt());
}
#[test]
fn ptp_returns_max_minus_min() {
let col = Column::from_values(vec![
Scalar::Float64(3.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(7.0),
Scalar::Float64(1.0),
])
.expect("col");
assert_eq!(col.ptp(), Scalar::Float64(6.0));
}
#[test]
fn ptp_empty_is_null() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
assert!(col.ptp().is_missing());
}
#[test]
fn skew_too_few_values_returns_null() {
let col =
Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("col");
assert!(col.skew().is_missing());
}
#[test]
fn rolling_window_sum_full_window() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
Scalar::Float64(4.0),
Scalar::Float64(5.0),
])
.expect("col");
// window=3, min_periods=3 -> [NaN, NaN, 6, 9, 12]
let r = col.rolling_window_sum(3, 3).expect("rolling");
assert!(r.values()[0].is_missing());
assert!(r.values()[1].is_missing());
assert_eq!(r.values()[2], Scalar::Float64(6.0));
assert_eq!(r.values()[3], Scalar::Float64(9.0));
assert_eq!(r.values()[4], Scalar::Float64(12.0));
}
#[test]
fn rolling_window_sum_min_periods_relaxed() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
])
.expect("col");
// window=3, min_periods=1 -> [1, 3, 6]
let r = col.rolling_window_sum(3, 1).expect("rolling");
assert_eq!(r.values()[0], Scalar::Float64(1.0));
assert_eq!(r.values()[1], Scalar::Float64(3.0));
assert_eq!(r.values()[2], Scalar::Float64(6.0));
}
#[test]
fn rolling_window_sum_skips_missing() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
Scalar::Float64(4.0),
])
.expect("col");
// window=3, min_periods=2:
// i=0: {1.0} observed=1 → NaN (below min_periods)
// i=1: {1.0, NaN} observed=1 → NaN
// i=2: {1.0, NaN, 3.0} observed=2 → 4.0
// i=3: {NaN, 3.0, 4.0} observed=2 → 7.0
let r = col.rolling_window_sum(3, 2).expect("rolling");
assert!(r.values()[0].is_missing());
assert!(r.values()[1].is_missing());
assert_eq!(r.values()[2], Scalar::Float64(4.0));
assert_eq!(r.values()[3], Scalar::Float64(7.0));
}
#[test]
fn rolling_window_sum_window_zero_is_all_null() {
let col =
Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("col");
let r = col.rolling_window_sum(0, 0).expect("rolling");
assert!(r.values()[0].is_missing());
assert!(r.values()[1].is_missing());
assert_eq!(r.dtype(), DType::Float64);
}
#[test]
fn diff_valid_skips_missing_predecessors() {
let col = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(4.0),
Scalar::Float64(7.0),
])
.expect("col");
let r = col.diff_valid().expect("diff_valid");
assert!(r.values()[0].is_missing()); // null in, null out
assert!(r.values()[1].is_missing()); // first non-missing -> no prev
assert!(r.values()[2].is_missing()); // null in
assert_eq!(r.values()[3], Scalar::Float64(3.0)); // 4 - 1
assert_eq!(r.values()[4], Scalar::Float64(3.0)); // 7 - 4
}
#[test]
fn diff_valid_empty_column() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
let r = col.diff_valid().expect("diff_valid");
assert!(r.is_empty());
assert_eq!(r.dtype(), DType::Float64);
}
#[test]
fn sample_without_replacement_deterministic_by_seed() {
let col =
Column::from_values((0..10).map(Scalar::Int64).collect::<Vec<_>>()).expect("col");
let a = col.sample(3, 42).expect("sample");
let b = col.sample(3, 42).expect("sample");
// Same seed → identical ordering.
assert_eq!(a.values(), b.values());
assert_eq!(a.len(), 3);
// All picks lie within the original range.
for v in a.values() {
match v {
Scalar::Int64(x) => assert!((0..10).contains(x)),
other => unreachable!("unexpected value {other:?}"),
}
}
}
#[test]
fn sample_different_seeds_likely_differ() {
let col =
Column::from_values((0..100).map(Scalar::Int64).collect::<Vec<_>>()).expect("col");
let a = col.sample(5, 1).expect("sample");
let b = col.sample(5, 2).expect("sample");
// Two independent seeds on a 100-element population: collision
// probability of the full 5-pick tuple is astronomically low.
assert_ne!(a.values(), b.values());
}
#[test]
fn sample_n_at_or_above_len_returns_clone() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let r = col.sample(10, 42).expect("sample");
assert_eq!(r.values(), col.values());
}
#[test]
fn first_valid_last_valid_skip_nulls() {
let col = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Int64(5),
Scalar::Int64(7),
Scalar::Null(NullKind::NaN),
])
.expect("col");
assert_eq!(col.first_valid(), Some(2));
assert_eq!(col.last_valid(), Some(3));
assert_eq!(col.first_valid_index(), Some(2));
assert_eq!(col.last_valid_index(), Some(3));
}
#[test]
fn nsmallest_keep_first_breaks_ties_by_earlier_position() {
let col = Column::from_values(vec![
Scalar::Int64(2), // pos 0
Scalar::Int64(1), // pos 1
Scalar::Int64(1), // pos 2
Scalar::Int64(3), // pos 3
Scalar::Int64(1), // pos 4
])
.expect("col");
let r = col.nsmallest_keep(2, "first").expect("nsmallest_keep");
// Two 1s: ties broken by earliest position → positions 1,2 → values [1, 1].
assert_eq!(r.len(), 2);
assert_eq!(r.values()[0], Scalar::Int64(1));
assert_eq!(r.values()[1], Scalar::Int64(1));
}
#[test]
fn nsmallest_keep_last_breaks_ties_by_later_position() {
let col = Column::from_values(vec![
Scalar::Int64(1), // pos 0
Scalar::Int64(2),
Scalar::Int64(1), // pos 2
Scalar::Int64(3),
Scalar::Int64(1), // pos 4
])
.expect("col");
// Three tied 1s; keep=last picks positions 4, 2 (latest two).
let r = col.nsmallest_keep(2, "last").expect("nsmallest_keep");
assert_eq!(r.len(), 2);
assert_eq!(r.values()[0], Scalar::Int64(1));
assert_eq!(r.values()[1], Scalar::Int64(1));
}
#[test]
fn nlargest_keep_f64_bounded_scan_matches_partial_cmp_reference() {
// nkeep_impl's f64 bounded scan must match a stable (partial_cmp,
// position-asc) reference — the compare_scalars_na_last semantics
// (−0.0 == +0.0, position tie-break), including signed-zero data.
use std::cmp::Ordering;
let mut state: u64 = 0xABCD_1234_9876_FEDC;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..150 {
let len = (next() % 400) as usize + 1;
let data: Vec<f64> = (0..len)
.map(|_| match next() % 8 {
0 => -0.0,
1 => 0.0,
2 => 1.0,
3 => -1.0,
4 => f64::INFINITY,
5 => f64::NEG_INFINITY,
_ => (next() % 15) as f64,
})
.collect();
let col = Column::from_f64_values(data.clone());
for &k in &[1usize, 5, 10] {
let got: Vec<u64> = col
.nlargest_keep(k, "first")
.expect("nlk")
.values()
.iter()
.map(|v| match v {
Scalar::Float64(x) => x.to_bits(),
o => panic!("{o:?}"),
})
.collect();
let mut idx: Vec<usize> = (0..len).collect();
idx.sort_by(|&a, &b| {
data[b]
.partial_cmp(&data[a])
.unwrap_or(Ordering::Equal)
.then(a.cmp(&b))
});
let take = k.min(len);
let expected: Vec<u64> =
idx[..take].iter().map(|&i| data[i].to_bits()).collect();
assert_eq!(got, expected, "k={k}");
}
}
}
#[test]
fn nlargest_nsmallest_i64_bounded_scan_matches_sort_take() {
// The typed bounded-scan nlargest/nsmallest must equal the reference
// sort_values(±)+take[..n] over random i64 WITH heavy ties (so the
// first-seen position tie-break is exercised at the boundary).
let mut state: u64 = 0x1122_3344_5566_7788;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..200 {
let len = (next() % 500) as usize + 1;
// small value range => many ties
let data: Vec<i64> = (0..len).map(|_| (next() % 20) as i64 - 10).collect();
let col = Column::from_i64_values_owned(data);
for &k in &[1usize, 3, 10, len.saturating_sub(1).max(1)] {
let large = col.nlargest(k).expect("nlargest");
let small = col.nsmallest(k).expect("nsmallest");
let take = k.min(col.len());
let ref_large: Vec<Scalar> =
col.sort_values(false).unwrap().values()[..take].to_vec();
let ref_small: Vec<Scalar> =
col.sort_values(true).unwrap().values()[..take].to_vec();
assert_eq!(large.values(), ref_large.as_slice(), "nlargest k={k}");
assert_eq!(small.values(), ref_small.as_slice(), "nsmallest k={k}");
}
// Float64: same shape vs sort_values+take, incl. ±0.0/±Inf — the
// partial_cmp bounded scan must match the (±0.0-canonicalizing,
// stable) radix. Compare bit patterns to catch any -0.0 drift.
let fdata: Vec<f64> = (0..len)
.map(|_| match next() % 8 {
0 => -0.0,
1 => 0.0,
2 => f64::INFINITY,
3 => f64::NEG_INFINITY,
_ => (next() % 20) as f64 - 10.0,
})
.collect();
let fcol = Column::from_f64_values(fdata);
let bits = |c: &Column, take: usize| -> Vec<u64> {
c.values()[..take]
.iter()
.map(|v| match v {
Scalar::Float64(x) => x.to_bits(),
o => panic!("{o:?}"),
})
.collect()
};
for &k in &[1usize, 3, 10, len.saturating_sub(1).max(1)] {
let take = k.min(fcol.len());
assert_eq!(
bits(&fcol.nlargest(k).unwrap(), take),
bits(&fcol.sort_values(false).unwrap(), take),
"f64 nlargest k={k}"
);
assert_eq!(
bits(&fcol.nsmallest(k).unwrap(), take),
bits(&fcol.sort_values(true).unwrap(), take),
"f64 nsmallest k={k}"
);
}
// Datetime64 (no NaT): exact i64-ns order. vs sort_values+take
// (now exact via the Datetime64 comparator arm).
let dts: Vec<i64> = (0..len)
.map(|_| (next() % 1000) as i64 * 86_400_000_000_000)
.collect();
let dcol = Column::from_datetime64_values(dts);
let dbits = |c: &Column, take: usize| -> Vec<i64> {
c.values()[..take]
.iter()
.map(|v| match v {
Scalar::Datetime64(x) => *x,
o => panic!("{o:?}"),
})
.collect()
};
for &k in &[1usize, 3, 10, len.saturating_sub(1).max(1)] {
let take = k.min(dcol.len());
assert_eq!(
dbits(&dcol.nlargest(k).unwrap(), take),
dbits(&dcol.sort_values(false).unwrap(), take),
"dt nlargest k={k}"
);
assert_eq!(
dbits(&dcol.nsmallest(k).unwrap(), take),
dbits(&dcol.sort_values(true).unwrap(), take),
"dt nsmallest k={k}"
);
}
}
}
#[test]
fn nsmallest_keep_all_expands_beyond_n_on_ties() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(1),
Scalar::Int64(1),
Scalar::Int64(2),
])
.expect("col");
// n=1 but three 1s tied for smallest; keep='all' returns them all.
let r = col.nsmallest_keep(1, "all").expect("nsmallest_keep");
assert_eq!(r.len(), 3);
assert_eq!(r.values()[0], Scalar::Int64(1));
assert_eq!(r.values()[1], Scalar::Int64(1));
assert_eq!(r.values()[2], Scalar::Int64(1));
}
#[test]
fn nlargest_keep_mirror_symmetry() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(3),
Scalar::Int64(3),
Scalar::Int64(2),
])
.expect("col");
let r = col.nlargest_keep(1, "all").expect("nlargest_keep");
assert_eq!(r.len(), 2);
assert_eq!(r.values()[0], Scalar::Int64(3));
assert_eq!(r.values()[1], Scalar::Int64(3));
}
#[test]
fn nkeep_invalid_keep_errors() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
assert!(col.nsmallest_keep(1, "middle").is_err());
assert!(col.nlargest_keep(1, "middle").is_err());
}
#[test]
fn nkeep_zero_is_empty_same_dtype() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let r = col.nsmallest_keep(0, "first").expect("nsmallest_keep");
assert!(r.is_empty());
assert_eq!(r.dtype(), DType::Int64);
}
#[test]
fn first_valid_last_valid_all_missing_is_none() {
let col = Column::from_values(vec![
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::Null),
])
.expect("col");
assert_eq!(col.first_valid(), None);
assert_eq!(col.last_valid(), None);
assert_eq!(col.first_valid_index(), None);
assert_eq!(col.last_valid_index(), None);
}
#[test]
fn rolling_window_sum_empty_column() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
let r = col.rolling_window_sum(3, 1).expect("rolling");
assert!(r.is_empty());
assert_eq!(r.dtype(), DType::Float64);
}
#[test]
fn pct_change_negative_periods() {
let col = Column::from_values(vec![Scalar::Float64(10.0), Scalar::Float64(15.0)])
.expect("col");
let r = col.pct_change(-1).expect("pct_change");
// (10 - 15) / 15 = -1/3
assert!(
matches!(&r.values()[0], Scalar::Float64(v) if (*v + 1.0 / 3.0).abs() < 1e-9),
"expected Float64, got {:?}",
r.values()[0]
);
assert!(r.values()[1].is_missing());
}
#[test]
fn count_excludes_nulls() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(2),
Scalar::Null(NullKind::Null),
])
.expect("col");
assert_eq!(col.count(), 2);
}
#[test]
fn count_and_nunique_match_scalar_oracle_05112() {
// Differential vs independent Scalar scan oracle
// (br-frankenpandas-05112). Seeded LCG, no mocks.
fn next(seed: &mut u64) -> u64 {
*seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
*seed
}
fn same_unique_bucket(left: &Scalar, right: &Scalar) -> bool {
match (left, right) {
(Scalar::Float64(left), Scalar::Float64(right)) => {
let left = if *left == 0.0 { 0.0 } else { *left };
let right = if *right == 0.0 { 0.0 } else { *right };
left.to_bits() == right.to_bits()
}
_ => left == right,
}
}
fn expected_nunique(values: &[Scalar], dropna: bool) -> i64 {
let mut seen = Vec::<Scalar>::new();
let mut saw_missing = false;
for value in values {
if value.is_missing() {
saw_missing = true;
continue;
}
if !seen
.iter()
.any(|existing| same_unique_bucket(existing, value))
{
seen.push(value.clone());
}
}
let missing_bucket = i64::from(!dropna && saw_missing);
seen.len() as i64 + missing_bucket
}
fn assert_reducers(case: usize, family: &str, values: Vec<Scalar>) {
let input = Column::from_values(values.clone()).expect("column");
let expected_count = values.iter().filter(|value| !value.is_missing()).count();
assert_eq!(
input.count(),
expected_count,
"case={case} family={family}: count mismatch for {values:?}"
);
assert_eq!(
input.nunique(),
Scalar::Int64(expected_nunique(&values, true)),
"case={case} family={family}: nunique(dropna=true) mismatch for {values:?}"
);
assert_eq!(
input.nunique_with_dropna(false),
Scalar::Int64(expected_nunique(&values, false)),
"case={case} family={family}: nunique(dropna=false) mismatch for {values:?}"
);
}
let all_missing = vec![
Scalar::Null(NullKind::Null),
Scalar::Null(NullKind::NaN),
Scalar::Float64(f64::NAN),
Scalar::Timedelta64(i64::MIN),
];
assert_reducers(usize::MAX, "all_missing", all_missing);
let mut seed = 0x0511_2c0a_1e5c_a1a5_u64;
for case in 0..180 {
let len = (next(&mut seed) % 67 + 1) as usize;
let mut floats = Vec::with_capacity(len);
floats.push(Scalar::Float64(0.0));
for _ in 1..len {
let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
let value = match next(&mut seed) % 9 {
0 => f64::NAN,
1 => f64::INFINITY,
2 => f64::NEG_INFINITY,
3 => -0.0,
4 => 0.0,
_ => raw as f64 / 17.0,
};
floats.push(Scalar::Float64(value));
}
assert_reducers(case, "float", floats);
let mut ints = Vec::with_capacity(len);
ints.push(Scalar::Int64(case as i64 % 11 - 5));
for _ in 1..len {
let raw = (next(&mut seed) % 41) as i64 - 20;
ints.push(match next(&mut seed) % 6 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
_ => Scalar::Int64(raw),
});
}
assert_reducers(case, "int", ints);
let mut bools = Vec::with_capacity(len);
bools.push(Scalar::Bool(case & 1 == 0));
for _ in 1..len {
bools.push(match next(&mut seed) % 5 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
raw => Scalar::Bool(raw & 1 == 0),
});
}
assert_reducers(case, "bool", bools);
let mut utf8 = Vec::with_capacity(len);
utf8.push(Scalar::Utf8(format!("s{}", case % 13)));
for pos in 1..len {
utf8.push(match next(&mut seed) % 7 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Null(NullKind::NaN),
raw => Scalar::Utf8(format!("s{}_{}", raw, pos % 5)),
});
}
assert_reducers(case, "utf8", utf8);
let mut timedeltas = Vec::with_capacity(len);
timedeltas.push(Scalar::Timedelta64(case as i64));
for _ in 1..len {
let raw = (next(&mut seed) % 97) as i64 - 48;
timedeltas.push(match next(&mut seed) % 7 {
0 => Scalar::Null(NullKind::Null),
1 => Scalar::Timedelta64(i64::MIN),
_ => Scalar::Timedelta64(raw),
});
}
assert_reducers(case, "timedelta", timedeltas);
}
}
#[test]
fn count_uses_nullable_int64_validity_without_scalar_materialization_aed6d() {
let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 3), (7, 1)]), 10);
let col = Column::from_i64_values_with_validity((0_i64..10).collect(), validity);
assert_eq!(col.count(), 6);
assert!(matches!(
&col.values,
ScalarValues::LazyNullableInt64 { .. }
));
if let ScalarValues::LazyNullableInt64 { values, .. } = &col.values {
assert!(values.get().is_none());
}
}
#[test]
fn count_float64_raw_path_still_excludes_nan_aed6d() {
let col = Column {
dtype: DType::Float64,
values: ScalarValues::lazy_all_valid_float64(vec![
1.0,
f64::NAN,
f64::INFINITY,
-0.0,
]),
validity: ValidityMask::all_valid(4),
data: None,
};
assert_eq!(col.count(), 3);
assert!(matches!(
&col.values,
ScalarValues::LazyAllValidFloat64 { .. }
));
if let ScalarValues::LazyAllValidFloat64 { values, .. } = &col.values {
assert!(values.get().is_none());
}
}
}
mod where_mask {
use fp_types::NullKind;
use super::*;
#[test]
fn where_cond_keeps_true_positions() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let cond = Column::from_values(vec![
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
])
.expect("cond");
let fill = Scalar::Int64(-1);
let out = col.where_cond(&cond, &fill).expect("where");
assert_eq!(col.r#where(&cond, &fill).expect("where"), out);
assert_eq!(out.values()[0], Scalar::Int64(1));
assert_eq!(out.values()[1], Scalar::Int64(-1));
assert_eq!(out.values()[2], Scalar::Int64(3));
}
#[test]
fn where_mask_utf8_typed_matches_generic() {
// The typed Utf8 where_cond/mask arms (all-valid contiguous + nullable
// LazyNullableUtf8 self, Utf8 scalar other, all-valid cond) must be BIT-EXACT
// to the generic clone-select path. A/B: col_typed (contiguous/nullable) hits
// the typed arm; col_eager (from_values, Eager) hits the generic path. Seeded
// short strings over {a,b,c,d}, some trials all-valid, some ~25% null; cond a
// seeded bool mask. Missing self at a self-taking position ⇒ Null.
let mut state: u64 = 0x9E7E_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 250) as usize;
let nullable = trial % 2 == 0;
let mut validity = crate::ValidityMask::all_valid(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
let mut eager: Vec<Scalar> = Vec::with_capacity(n);
let mut cbits: Vec<bool> = Vec::with_capacity(n);
for i in 0..n {
if nullable && next() % 4 == 0 {
validity.set(i, false);
eager.push(Scalar::Null(NullKind::Null));
} else {
let len = (next() % 4) as usize;
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
eager.push(Scalar::Utf8(s));
}
cbits.push(next() % 2 == 0);
offsets.push(bytes.len());
}
let col_typed = Column::from_utf8_values_with_validity(bytes, offsets, validity);
let col_eager = Column::new(DType::Utf8, eager).expect("eager utf8");
// col_eager (from_values) must be on the generic path.
assert!(
col_eager.as_utf8_contiguous().is_none()
&& col_eager.as_nullable_utf8_contiguous().is_none(),
"eager fixture must be on the generic where/mask path"
);
let cond = Column::from_bool_values(cbits);
let other = Scalar::Utf8("DEF".to_string());
let wt = col_typed.where_cond(&cond, &other).expect("typed where");
let we = col_eager.where_cond(&cond, &other).expect("eager where");
assert_eq!(wt.values(), we.values(), "where trial {trial}");
let mt = col_typed.mask(&cond, &other).expect("typed mask");
let me = col_eager.mask(&cond, &other).expect("eager mask");
assert_eq!(mt.values(), me.values(), "mask trial {trial}");
}
}
#[test]
fn where_mask_temporal_typed_matches_generic() {
// The typed temporal where_cond/mask arms (all-valid OR nullable Datetime64/
// Timedelta64 self, matching temporal scalar other, all-valid cond) must be
// BIT-EXACT to the generic clone-select path. A/B: col_typed (from_*_with_validity
// => LazyNullable/AllValid) hits the typed arm; col_eager (Column::new, Eager)
// hits the generic path. ~25% validity-null + ~10% NaT-in-buffer (validity-true);
// a cond-taking-self position at a missing self ⇒ Null. Values near 1.6e18.
let mut state: u64 = 0x9E7E_DA7E_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for is_dt in [true, false] {
let base: i64 = if is_dt { 1_600_000_000_000_000_000 } else { 0 };
let nat = if is_dt {
fp_types::Timestamp::NAT
} else {
fp_types::Timedelta::NAT
};
for trial in 0..120 {
let n = (next() % 250) as usize;
let mut data = vec![0i64; n];
let mut validity = crate::ValidityMask::all_valid(n);
let mut eager: Vec<Scalar> = Vec::with_capacity(n);
let mut cbits: Vec<bool> = Vec::with_capacity(n);
for i in 0..n {
let r = next() % 10;
if r < 3 {
validity.set(i, false);
eager.push(Scalar::Null(NullKind::NaT));
} else if r == 3 {
data[i] = nat;
eager.push(if is_dt {
Scalar::Datetime64(nat)
} else {
Scalar::Timedelta64(nat)
});
} else {
data[i] = base + (next() % 1_000_000) as i64;
eager.push(if is_dt {
Scalar::Datetime64(data[i])
} else {
Scalar::Timedelta64(data[i])
});
}
cbits.push(next() % 2 == 0);
}
let dtype = if is_dt { DType::Datetime64 } else { DType::Timedelta64 };
let col_typed = if is_dt {
Column::from_datetime64_values_with_validity(data.clone(), validity)
} else {
Column::from_timedelta64_values_with_validity(data.clone(), validity)
};
let col_eager = Column::new(dtype, eager).expect("eager temporal");
let cond = Column::from_bool_values(cbits);
let other = if is_dt {
Scalar::Datetime64(base + 777)
} else {
Scalar::Timedelta64(777)
};
let wt = col_typed.where_cond(&cond, &other).expect("typed where");
let we = col_eager.where_cond(&cond, &other).expect("eager where");
assert_eq!(wt.values(), we.values(), "is_dt={is_dt} where trial {trial}");
let mt = col_typed.mask(&cond, &other).expect("typed mask");
let me = col_eager.mask(&cond, &other).expect("eager mask");
assert_eq!(mt.values(), me.values(), "is_dt={is_dt} mask trial {trial}");
}
}
}
#[test]
fn where_mask_series_temporal_typed_matches_generic() {
// Typed temporal where_cond_series/mask_series arms (col-vs-col `other`, all-valid
// OR nullable Datetime64/Timedelta64 self+other, all-valid cond) must be BIT-EXACT
// to the generic clone/cast select. A/B: typed self+other (from_*_with_validity) vs
// eager (Column::new). ~25% validity-null + ~10% NaT-in-buffer on BOTH sides.
let mut state: u64 = 0x5E12_DA7E_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
// Build a (typed, eager, ) pair for one side.
let build = |n: usize,
is_dt: bool,
nat: i64,
next: &mut dyn FnMut() -> u64|
-> (Column, Column) {
let base: i64 = if is_dt { 1_600_000_000_000_000_000 } else { 0 };
let mut data = vec![0i64; n];
let mut validity = crate::ValidityMask::all_valid(n);
let mut eager: Vec<Scalar> = Vec::with_capacity(n);
for i in 0..n {
let r = next() % 10;
if r < 3 {
validity.set(i, false);
eager.push(Scalar::Null(NullKind::NaT));
} else if r == 3 {
data[i] = nat;
eager.push(if is_dt {
Scalar::Datetime64(nat)
} else {
Scalar::Timedelta64(nat)
});
} else {
data[i] = base + (next() % 1_000_000) as i64;
eager.push(if is_dt {
Scalar::Datetime64(data[i])
} else {
Scalar::Timedelta64(data[i])
});
}
}
let dtype = if is_dt { DType::Datetime64 } else { DType::Timedelta64 };
let typed = if is_dt {
Column::from_datetime64_values_with_validity(data.clone(), validity)
} else {
Column::from_timedelta64_values_with_validity(data.clone(), validity)
};
(typed, Column::new(dtype, eager).expect("eager temporal"))
};
for is_dt in [true, false] {
let nat = if is_dt {
fp_types::Timestamp::NAT
} else {
fp_types::Timedelta::NAT
};
for trial in 0..120 {
let n = (next() % 250) as usize;
let (s_typed, s_eager) = build(n, is_dt, nat, &mut next);
let (o_typed, o_eager) = build(n, is_dt, nat, &mut next);
let cbits: Vec<bool> = (0..n).map(|_| next() % 2 == 0).collect();
let cond = Column::from_bool_values(cbits);
let wt = s_typed.where_cond_series(&cond, &o_typed).expect("typed where_series");
let we = s_eager.where_cond_series(&cond, &o_eager).expect("eager where_series");
assert_eq!(wt.values(), we.values(), "is_dt={is_dt} where_series trial {trial}");
let mt = s_typed.mask_series(&cond, &o_typed).expect("typed mask_series");
let me = s_eager.mask_series(&cond, &o_eager).expect("eager mask_series");
assert_eq!(mt.values(), me.values(), "is_dt={is_dt} mask_series trial {trial}");
}
}
}
#[test]
fn where_mask_series_nullable_i64_typed_matches_generic() {
// The typed nullable-Int64 where_cond_series/mask_series arms (col-vs-col other,
// any nullable Int64 operand, all-valid cond) must be BIT-EXACT to the generic
// clone/cast select. A/B: typed self+other (from_i64_values_with_validity) vs
// eager (Column::new). ~30% nulls each side; i64::MIN/MAX exercise extremes.
let mut state: u64 = 0x171E_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let build = |n: usize, next: &mut dyn FnMut() -> u64| -> (Column, Column) {
let mut data = vec![0i64; n];
let mut validity = crate::ValidityMask::all_valid(n);
let mut eager: Vec<Scalar> = Vec::with_capacity(n);
for i in 0..n {
if next() % 3 == 0 {
validity.set(i, false);
eager.push(Scalar::Null(NullKind::Null));
} else {
let v = (next() % 10_000) as i64 - 5000;
data[i] = v;
eager.push(Scalar::Int64(v));
}
}
(
Column::from_i64_values_with_validity(data, validity),
Column::new(DType::Int64, eager).expect("eager i64"),
)
};
for trial in 0..150 {
let n = (next() % 250) as usize;
let (s_typed, s_eager) = build(n, &mut next);
let (o_typed, o_eager) = build(n, &mut next);
let cbits: Vec<bool> = (0..n).map(|_| next() % 2 == 0).collect();
let cond = Column::from_bool_values(cbits);
let wt = s_typed.where_cond_series(&cond, &o_typed).expect("typed where");
let we = s_eager.where_cond_series(&cond, &o_eager).expect("eager where");
assert_eq!(wt.values(), we.values(), "where_series i64 trial {trial}");
let mt = s_typed.mask_series(&cond, &o_typed).expect("typed mask");
let me = s_eager.mask_series(&cond, &o_eager).expect("eager mask");
assert_eq!(mt.values(), me.values(), "mask_series i64 trial {trial}");
}
}
#[test]
fn mask_inverts_where_cond() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let cond = Column::from_values(vec![
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
])
.expect("cond");
let fill = Scalar::Int64(0);
let out = col.mask(&cond, &fill).expect("mask");
assert_eq!(out.values()[0], Scalar::Int64(0));
assert_eq!(out.values()[1], Scalar::Int64(2));
assert_eq!(out.values()[2], Scalar::Int64(0));
}
#[test]
fn where_missing_cond_propagates_null() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let cond = Column::from_values(vec![Scalar::Bool(true), Scalar::Null(NullKind::NaN)])
.expect("cond");
let fill = Scalar::Int64(-1);
let out = col.where_cond(&cond, &fill).expect("where");
assert_eq!(out.values()[0], Scalar::Int64(1));
assert!(out.values()[1].is_missing());
}
#[test]
fn where_rejects_non_bool_cond() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let cond = Column::from_values(vec![Scalar::Int64(1)]).expect("cond");
let err = col.where_cond(&cond, &Scalar::Int64(0)).unwrap_err();
assert!(matches!(err, crate::ColumnError::InvalidMaskType { .. }));
}
#[test]
fn equals_elementwise_matches_semantic_eq() {
let a = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Null(NullKind::NaN),
])
.expect("a");
let b = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(3),
Scalar::Null(NullKind::NaN),
])
.expect("b");
let r = a.equals(&b).expect("equals");
assert_eq!(r.dtype(), DType::Bool);
assert_eq!(r.values()[0], Scalar::Bool(true));
assert_eq!(r.values()[1], Scalar::Bool(false));
// NaN vs NaN → false (pandas semantics)
assert_eq!(r.values()[2], Scalar::Bool(false));
}
#[test]
fn equals_length_mismatch_errors() {
let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
assert!(a.equals(&b).is_err());
}
#[test]
fn dot_ignores_missing() {
let a = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
])
.expect("a");
let b = Column::from_values(vec![
Scalar::Float64(2.0),
Scalar::Float64(4.0),
Scalar::Float64(5.0),
])
.expect("b");
let r = a.dot(&b).expect("dot");
// 1*2 + skip + 3*5 = 17
assert!((r - 17.0).abs() < 1e-9);
}
#[test]
fn dot_non_numeric_errors() {
let a = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("a");
let b = Column::from_values(vec![Scalar::Float64(1.0)]).expect("b");
assert!(a.dot(&b).is_err());
}
#[test]
fn fillna_with_column_fills_missing_positions() {
let a = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(3),
])
.expect("a");
let b = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
])
.expect("b");
let r = a.fillna_with_column(&b).expect("fillna_with_column");
assert_eq!(r.values()[0], Scalar::Int64(1));
assert_eq!(r.values()[1], Scalar::Int64(20));
assert_eq!(r.values()[2], Scalar::Int64(3));
}
#[test]
fn divmod_returns_quotient_and_remainder() {
let a = Column::from_values(vec![
Scalar::Float64(10.0),
Scalar::Float64(7.0),
Scalar::Float64(-5.0),
])
.expect("a");
let b = Column::from_values(vec![
Scalar::Float64(3.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
])
.expect("b");
let (q, r) = a.divmod(&b).expect("divmod");
// Python-style: floor(10/3)=3, 10 - 3*3 = 1
match (&q.values()[0], &r.values()[0]) {
(Scalar::Float64(qv), Scalar::Float64(rv)) => {
assert!((qv - 3.0).abs() < 1e-9);
assert!((rv - 1.0).abs() < 1e-9);
}
other => unreachable!("unexpected {other:?}"),
}
// 7 / 2 → q=3, r=1
match (&q.values()[1], &r.values()[1]) {
(Scalar::Float64(qv), Scalar::Float64(rv)) => {
assert!((qv - 3.0).abs() < 1e-9);
assert!((rv - 1.0).abs() < 1e-9);
}
other => unreachable!("unexpected {other:?}"),
}
// -5 / 3 → q=-2 (floor), r = -5 - (-2*3) = 1
match (&q.values()[2], &r.values()[2]) {
(Scalar::Float64(qv), Scalar::Float64(rv)) => {
assert!((qv + 2.0).abs() < 1e-9);
assert!((rv - 1.0).abs() < 1e-9);
}
other => unreachable!("unexpected {other:?}"),
}
}
#[test]
fn divmod_zero_divisor_yields_null() {
let a = Column::from_values(vec![Scalar::Float64(10.0)]).expect("a");
let b = Column::from_values(vec![Scalar::Float64(0.0)]).expect("b");
let (q, r) = a.divmod(&b).expect("divmod");
assert!(q.values()[0].is_missing());
assert!(r.values()[0].is_missing());
}
#[test]
fn divmod_infinite_operands_match_pandas_float_semantics() {
let a = Column::from_values(vec![
Scalar::Float64(f64::INFINITY),
Scalar::Float64(f64::NEG_INFINITY),
Scalar::Float64(5.0),
Scalar::Float64(-5.0),
Scalar::Float64(f64::INFINITY),
])
.expect("a");
let b = Column::from_values(vec![
Scalar::Float64(2.0),
Scalar::Float64(-2.0),
Scalar::Float64(f64::INFINITY),
Scalar::Float64(f64::INFINITY),
Scalar::Float64(f64::INFINITY),
])
.expect("b");
let (q, r) = a.divmod(&b).expect("divmod");
assert!(matches!(q.values()[0], Scalar::Float64(v) if v.is_nan()));
assert!(matches!(r.values()[0], Scalar::Float64(v) if v.is_nan()));
assert!(matches!(q.values()[1], Scalar::Float64(v) if v.is_nan()));
assert!(matches!(r.values()[1], Scalar::Float64(v) if v.is_nan()));
assert_eq!(q.values()[2], Scalar::Float64(0.0));
assert_eq!(r.values()[2], Scalar::Float64(5.0));
assert_eq!(q.values()[3], Scalar::Float64(-1.0));
assert_eq!(r.values()[3], Scalar::Float64(f64::INFINITY));
assert!(matches!(q.values()[4], Scalar::Float64(v) if v.is_nan()));
assert!(matches!(r.values()[4], Scalar::Float64(v) if v.is_nan()));
}
#[test]
fn where_cond_series_fills_from_other_column() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let cond = Column::from_values(vec![
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
])
.expect("cond");
let other = Column::from_values(vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
])
.expect("other");
let out = col.where_cond_series(&cond, &other).expect("where_series");
assert_eq!(out.values()[0], Scalar::Int64(1));
assert_eq!(out.values()[1], Scalar::Int64(20));
assert_eq!(out.values()[2], Scalar::Int64(3));
}
#[test]
fn mask_series_fills_from_other_column() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let cond = Column::from_values(vec![
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
])
.expect("cond");
let other =
Column::from_values(vec![Scalar::Int64(0), Scalar::Int64(0), Scalar::Int64(0)])
.expect("other");
let out = col.mask_series(&cond, &other).expect("mask_series");
assert_eq!(out.values()[0], Scalar::Int64(0));
assert_eq!(out.values()[1], Scalar::Int64(2));
assert_eq!(out.values()[2], Scalar::Int64(0));
}
#[test]
fn where_cond_series_rejects_non_bool_cond() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let cond = Column::from_values(vec![Scalar::Int64(1)]).expect("cond");
let other = Column::from_values(vec![Scalar::Int64(0)]).expect("other");
let err = col.where_cond_series(&cond, &other).unwrap_err();
assert!(matches!(err, crate::ColumnError::InvalidMaskType { .. }));
}
#[test]
fn replace_typed_i64_matches_oracle() {
// Typed i64 replace == an independent first-match-wins oracle, with
// multiple (incl. overlapping/duplicate) targets. Built via
// from_i64_values to drive the typed path.
let mut state: u64 = 0x51A2_C7E3_4F08_9DB1;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..200 {
let n = (next() % 300) as usize + 1;
let data: Vec<i64> = (0..n).map(|_| (next() % 10) as i64).collect();
let col = Column::from_i64_values_owned(data.clone());
let k = (next() % 4) as usize + 1;
let targets: Vec<i64> = (0..k).map(|_| (next() % 12) as i64).collect();
let reps: Vec<i64> = (0..k).map(|_| (next() % 100) as i64 - 50).collect();
let to_rep: Vec<Scalar> = targets.iter().map(|&v| Scalar::Int64(v)).collect();
let repl: Vec<Scalar> = reps.iter().map(|&v| Scalar::Int64(v)).collect();
let got = col.replace(&to_rep, &repl).unwrap();
let exp: Vec<Scalar> = data
.iter()
.map(|&x| {
for (t, r) in targets.iter().zip(reps.iter()) {
if x == *t {
return Scalar::Int64(*r);
}
}
Scalar::Int64(x)
})
.collect();
assert_eq!(got.values(), exp);
}
}
#[test]
fn replace_values_applies_first_match() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(2),
])
.expect("col");
let to_replace = vec![Scalar::Int64(2), Scalar::Int64(3)];
let replacement = vec![Scalar::Int64(20), Scalar::Int64(30)];
let out = col
.replace_values(&to_replace, &replacement)
.expect("replace");
let alias = col
.replace(&to_replace, &replacement)
.expect("replace alias");
assert_eq!(alias, out);
assert_eq!(out.values()[0], Scalar::Int64(1));
assert_eq!(out.values()[1], Scalar::Int64(20));
assert_eq!(out.values()[2], Scalar::Int64(30));
assert_eq!(out.values()[3], Scalar::Int64(20));
}
#[test]
fn replace_nullable_utf8_typed_matches_generic() {
// The typed nullable-Utf8 replace arm (LazyNullableUtf8 + all-Utf8
// targets/replacements) must be BIT-EXACT to the generic clone+scan path.
// A/B: col_typed (LazyNullableUtf8) hits the typed arm; col_eager (from_values,
// Eager) hits the generic path. Seeded short strings over {a,b,c,d} + ~25%
// nulls; targets incl. a duplicate (first-match-wins), an empty-string target,
// and a target that maps to empty. Missing rows must stay Null.
let mut state: u64 = 0x2E91_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
let to_replace = vec![
Scalar::Utf8("a".to_string()),
Scalar::Utf8("bb".to_string()),
Scalar::Utf8("a".to_string()), // dup ⇒ first-match-wins (X, not Z)
Scalar::Utf8(String::new()), // empty-string target
Scalar::Utf8("cd".to_string()),
];
let replacement = vec![
Scalar::Utf8("X".to_string()),
Scalar::Utf8("Y".to_string()),
Scalar::Utf8("Z".to_string()),
Scalar::Utf8("EMPTY".to_string()),
Scalar::Utf8(String::new()), // maps to empty
];
for trial in 0..120 {
let n = (next() % 250) as usize;
let mut validity = crate::ValidityMask::all_valid(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
let mut eager: Vec<Scalar> = Vec::with_capacity(n);
for i in 0..n {
if next() % 4 == 0 {
validity.set(i, false);
eager.push(Scalar::Null(NullKind::Null));
} else {
let len = (next() % 4) as usize; // 0..3 ⇒ incl empty string
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
eager.push(Scalar::Utf8(s));
}
offsets.push(bytes.len());
}
let col_typed = Column::from_utf8_values_with_validity(bytes, offsets, validity);
let col_eager = Column::new(DType::Utf8, eager).expect("eager utf8");
if col_typed.as_nullable_utf8_contiguous().is_some() {
assert!(
col_eager.as_nullable_utf8_contiguous().is_none(),
"eager fixture must be on the generic replace path"
);
}
let a = col_typed
.replace_values(&to_replace, &replacement)
.expect("typed replace");
let b = col_eager
.replace_values(&to_replace, &replacement)
.expect("eager replace");
assert_eq!(a.values(), b.values(), "trial {trial}");
}
}
#[test]
fn replace_values_can_replace_nulls() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(2),
])
.expect("col");
let to_replace = vec![Scalar::Null(NullKind::NaN)];
let replacement = vec![Scalar::Int64(-1)];
let out = col
.replace_values(&to_replace, &replacement)
.expect("replace");
assert_eq!(out.values()[0], Scalar::Int64(1));
assert_eq!(out.values()[1], Scalar::Int64(-1));
assert_eq!(out.values()[2], Scalar::Int64(2));
}
#[test]
fn replace_values_length_mismatch_errors() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let err = col
.replace_values(&[Scalar::Int64(1)], &[Scalar::Int64(2), Scalar::Int64(3)])
.unwrap_err();
assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
}
#[test]
fn nonzero_returns_truthy_positions() {
let col = Column::from_values(vec![
Scalar::Int64(0),
Scalar::Int64(5),
Scalar::Null(NullKind::NaN),
Scalar::Int64(-3),
Scalar::Int64(0),
])
.expect("col");
assert_eq!(col.nonzero(), vec![1, 3]);
}
#[test]
fn nonzero_empty_column_is_empty() {
let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
assert!(col.nonzero().is_empty());
}
#[test]
fn where_rejects_length_mismatch() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let cond = Column::from_values(vec![Scalar::Bool(true)]).expect("cond");
let err = col.where_cond(&cond, &Scalar::Int64(0)).unwrap_err();
assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
}
}
mod nlargest_nsmallest {
use fp_types::NullKind;
use super::*;
#[test]
fn nlargest_returns_top_n_descending() {
let col = Column::from_values(vec![
Scalar::Int64(3),
Scalar::Int64(1),
Scalar::Int64(5),
Scalar::Int64(2),
Scalar::Int64(4),
])
.expect("col");
let top = col.nlargest(3).expect("nlargest");
assert_eq!(top.len(), 3);
assert_eq!(top.values()[0], Scalar::Int64(5));
assert_eq!(top.values()[1], Scalar::Int64(4));
assert_eq!(top.values()[2], Scalar::Int64(3));
}
#[test]
fn nsmallest_returns_bottom_n_ascending() {
let col = Column::from_values(vec![
Scalar::Int64(3),
Scalar::Int64(1),
Scalar::Int64(5),
Scalar::Int64(2),
Scalar::Int64(4),
])
.expect("col");
let bot = col.nsmallest(2).expect("nsmallest");
assert_eq!(bot.len(), 2);
assert_eq!(bot.values()[0], Scalar::Int64(1));
assert_eq!(bot.values()[1], Scalar::Int64(2));
}
#[test]
fn nlargest_excludes_missing_when_n_fits() {
let col = Column::from_values(vec![
Scalar::Int64(5),
Scalar::Null(NullKind::NaN),
Scalar::Int64(3),
Scalar::Int64(7),
])
.expect("col");
let top = col.nlargest(2).expect("nlargest");
assert_eq!(top.len(), 2);
assert_eq!(top.values()[0], Scalar::Int64(7));
assert_eq!(top.values()[1], Scalar::Int64(5));
}
#[test]
fn nlargest_n_larger_than_length_clamps() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let top = col.nlargest(100).expect("nlargest");
assert_eq!(top.len(), 2);
}
#[test]
fn nlargest_zero_is_empty_same_dtype() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let top = col.nlargest(0).expect("nlargest");
assert!(top.is_empty());
assert_eq!(top.dtype(), DType::Int64);
}
// Reference nlargest/nsmallest via the stable na-last Scalar comparator
// (the exact semantics the typed fast paths must reproduce): sort a
// position permutation, take the first `n`, gather the scalars.
fn nkeep_reference(vals: &[Scalar], n: usize, ascending: bool) -> Vec<Scalar> {
let mut idx: Vec<usize> = (0..vals.len()).collect();
idx.sort_by(|&a, &b| crate::compare_scalars_na_last(&vals[a], &vals[b], ascending));
let take = n.min(idx.len());
idx[..take].iter().map(|&i| vals[i].clone()).collect()
}
#[test]
fn nlargest_nsmallest_nullable_i64_matches_na_last_reference() {
// Typed nullable Int64 bounded top/bottom-k must be BIT-IDENTICAL to
// the na-last Scalar sort + take, across n that both fit within the
// present count (fast path) and exceed it (fall-through carries the
// null tail). Deterministic LCG, ~25% missing, narrow range for ties.
let mut state: u64 = 0x51ED_270B_1234_5678;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..150 {
let len = (next() % 260) as usize + 1;
let data: Vec<i64> = (0..len).map(|_| (next() % 13) as i64 - 6).collect();
let mut validity = crate::ValidityMask::all_valid(len);
for i in 0..len {
if next() % 4 == 0 {
validity.set(i, false);
}
}
let col = Column::from_i64_values_with_validity(data, validity);
let vals = col.values().to_vec();
for &n in &[1usize, 3, 7, len / 2, len, len + 5] {
assert_eq!(
col.nlargest(n).expect("nlargest").values(),
nkeep_reference(&vals, n, false).as_slice(),
"nlargest trial {trial} n={n}"
);
assert_eq!(
col.nsmallest(n).expect("nsmallest").values(),
nkeep_reference(&vals, n, true).as_slice(),
"nsmallest trial {trial} n={n}"
);
}
}
}
#[test]
fn nlargest_nsmallest_nullable_f64_matches_na_last_reference() {
// Typed nullable Float64 counterpart. Null-missing only (no present-NaN)
// so gathered Scalars are Float64|Null and compare with structural eq;
// the fast path's `present = valid && !NaN` split is still exercised —
// its NaN handling is covered by the sort na-last tests.
let mut state: u64 = 0x0BAD_C0DE_FEED_9001;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..150 {
let len = (next() % 260) as usize + 1;
let mut validity = crate::ValidityMask::all_valid(len);
let data: Vec<f64> = (0..len)
.map(|i| {
let r = next();
if r % 4 == 0 {
validity.set(i, false);
0.0
} else {
((r % 13) as f64 - 6.0) / 2.0
}
})
.collect();
let col = Column::from_f64_values_with_validity(data, validity);
let vals = col.values().to_vec();
for &n in &[1usize, 3, 7, len / 2, len, len + 5] {
assert_eq!(
col.nlargest(n).expect("nlargest").values(),
nkeep_reference(&vals, n, false).as_slice(),
"nlargest trial {trial} n={n}"
);
assert_eq!(
col.nsmallest(n).expect("nsmallest").values(),
nkeep_reference(&vals, n, true).as_slice(),
"nsmallest trial {trial} n={n}"
);
}
}
}
}
mod astype {
use fp_types::NullKind;
use super::*;
#[test]
fn astype_int_to_float_preserves_values() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let out = col.astype(DType::Float64).expect("astype");
assert_eq!(out.dtype(), DType::Float64);
assert_eq!(out.values()[0], Scalar::Float64(1.0));
assert_eq!(out.values()[1], Scalar::Float64(2.0));
}
#[test]
fn astype_same_dtype_is_noop_clone() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let out = col.astype(DType::Int64).expect("astype");
assert_eq!(out.values(), col.values());
}
#[test]
fn astype_bool_to_int() {
let col =
Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("col");
let out = col.astype(DType::Int64).expect("astype");
assert_eq!(out.dtype(), DType::Int64);
assert_eq!(out.values()[0], Scalar::Int64(1));
assert_eq!(out.values()[1], Scalar::Int64(0));
}
#[test]
fn astype_to_utf8_uses_pandas_string_spellings() {
let bool_col = Column::new(DType::Bool, vec![Scalar::Bool(true), Scalar::Bool(false)])
.expect("bool col");
let int_col = Column::new(DType::Int64, vec![Scalar::Int64(-7)]).expect("int col");
let float_col = Column::new(
DType::Float64,
vec![Scalar::Float64(1.0), Scalar::Null(NullKind::NaN)],
)
.expect("float col");
let bool_out = bool_col.astype(DType::Utf8).expect("astype bool");
let int_out = int_col.astype(DType::Utf8).expect("astype int");
let float_out = float_col.astype(DType::Utf8).expect("astype float");
assert_eq!(bool_out.dtype(), DType::Utf8);
assert_eq!(
bool_out.values(),
&[
Scalar::Utf8("True".to_owned()),
Scalar::Utf8("False".to_owned()),
]
);
assert_eq!(int_out.values(), &[Scalar::Utf8("-7".to_owned())]);
assert_eq!(
float_out.values(),
&[
Scalar::Utf8("1.0".to_owned()),
Scalar::Utf8("nan".to_owned()),
]
);
}
/// The Float64 -> Utf8 astype above the `PAR_MIN_ROWS` gate builds its
/// contiguous Utf8 output in parallel workers (per-thread byte buffers +
/// local end offsets, concatenated with a running byte base). Prove it is
/// bit-identical to the serial formatter over a row count that is NOT a
/// multiple of the worker count, so every chunk boundary is ragged, and
/// over values whose rendered widths differ (whole ".0", shortest decimal,
/// negative, and both scientific spellings) so a mis-shifted offset would
/// corrupt a neighbouring row rather than cancel out.
#[test]
fn astype_float_to_utf8_parallel_matches_serial_ccfp() {
// > PAR_MIN_ROWS (200_000) with a ragged final chunk.
let n = 200_003_usize;
// Widths differ per arm (whole ".0", shortest decimal, negative,
// and both scientific spellings) so a mis-shifted chunk offset
// corrupts a neighbouring row instead of cancelling out.
let values: Vec<f64> = (0..n)
.map(|i| match i % 5 {
0 => i as f64,
1 => i as f64 * 1.5,
2 => -(i as f64) / 3.0,
3 => 1e16 + i as f64,
_ => 1e-5 / (i + 1) as f64,
})
.collect();
let col = Column::from_f64_values(values.clone());
let out = col.astype(DType::Utf8).expect("astype float->utf8");
assert_eq!(out.dtype(), DType::Utf8);
assert_eq!(out.len(), n);
let got = out.values();
for (i, &v) in values.iter().enumerate() {
let expected = Scalar::Utf8(fp_types::float_to_string_for_astype(v));
assert_eq!(
got[i], expected,
"row {i} diverged from the serial formatter"
);
}
}
#[test]
fn astype_propagates_missing() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
.expect("col");
let out = col.astype(DType::Float64).expect("astype");
assert_eq!(out.values()[0], Scalar::Float64(1.0));
assert!(out.values()[1].is_missing());
}
#[test]
fn astype_finite_float_to_int_truncates_toward_zero() {
// pandas astype(int64) truncates finite floats toward zero
// (br-frankenpandas-qcutc); only non-finite values raise.
let col = Column::from_values(vec![
Scalar::Float64(1.5),
Scalar::Float64(2.9),
Scalar::Float64(-1.5),
Scalar::Float64(-2.9),
Scalar::Float64(0.4),
])
.expect("col");
let out = col.astype(DType::Int64).expect("truncating cast");
assert_eq!(
out.values(),
&[
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(-1),
Scalar::Int64(-2),
Scalar::Int64(0),
]
);
// Non-finite still raises.
let inf = Column::from_values(vec![Scalar::Float64(f64::INFINITY)]).expect("col");
assert!(matches!(
inf.astype(DType::Int64).unwrap_err(),
crate::ColumnError::Type(_)
));
}
#[test]
fn new_int64_from_lossy_float_errors_unlike_astype() {
// The typed constructor with an explicit dtype is STRICT, matching
// pandas DataFrame(dtype='int64') which raises on a non-integer
// float — unlike astype which truncates. (br-frankenpandas-8nupg)
let err = Column::new(DType::Int64, vec![Scalar::Float64(1.5)]).unwrap_err();
assert!(matches!(
err,
crate::ColumnError::Type(fp_types::TypeError::LossyFloatToInt { .. })
));
// Integer-valued floats still coerce fine (1.0 -> 1).
let ok = Column::new(DType::Int64, vec![Scalar::Float64(2.0)]).expect("integer float");
assert_eq!(ok.values(), &[Scalar::Int64(2)]);
}
}
mod rank_searchsorted {
use fp_types::NullKind;
use super::*;
#[test]
fn rank_average_ties_get_midpoint() {
let col = Column::from_values(vec![
Scalar::Float64(10.0),
Scalar::Float64(20.0),
Scalar::Float64(20.0),
Scalar::Float64(30.0),
])
.expect("col");
let r = col.rank("average", true).expect("rank");
assert_eq!(r.values()[0], Scalar::Float64(1.0));
// Two tied values occupy positions 2 and 3 → avg = 2.5
assert_eq!(r.values()[1], Scalar::Float64(2.5));
assert_eq!(r.values()[2], Scalar::Float64(2.5));
assert_eq!(r.values()[3], Scalar::Float64(4.0));
}
#[test]
fn rank_utf8_typed_matches_scalar_reference() {
// The typed Utf8 rank arms (all-valid contiguous + nullable LazyNullableUtf8)
// must be BIT-EXACT to the generic compare_scalars_na_last path for every
// method × direction. Oracle replicates the generic algorithm directly over a
// Vec<Scalar> (independent of the typed nullable_rank_values walk). Seeded
// short strings over {a,b,c,d} (ties + varied lengths), ~25% nulls in the
// nullable variant.
fn ref_rank(vals: &[Scalar], method: &str, ascending: bool) -> Vec<Scalar> {
let len = vals.len();
let mut non_missing: Vec<(usize, &Scalar)> = Vec::new();
for (i, v) in vals.iter().enumerate() {
if !v.is_missing() {
non_missing.push((i, v));
}
}
non_missing
.sort_by(|a, b| crate::compare_scalars_na_last(a.1, b.1, ascending));
let mut ranks = vec![Scalar::Null(NullKind::NaN); len];
let n = non_missing.len();
let mut cursor = 0usize;
let mut dense_rank = 0f64;
while cursor < n {
let mut end = cursor + 1;
while end < n
&& crate::compare_scalars_na_last(
non_missing[cursor].1,
non_missing[end].1,
ascending,
)
.is_eq()
{
end += 1;
}
let start_rank = cursor as f64 + 1.0;
let end_rank = end as f64;
dense_rank += 1.0;
for (group_idx, entry) in non_missing.iter().enumerate().take(end).skip(cursor)
{
let value = match method {
"average" => (start_rank + end_rank) / 2.0,
"min" => start_rank,
"max" => end_rank,
"first" => group_idx as f64 + 1.0,
"dense" => dense_rank,
_ => unreachable!(),
};
ranks[entry.0] = Scalar::Float64(value);
}
cursor = end;
}
ranks
}
let mut state: u64 = 0x9A17_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..120 {
let n = (next() % 200) as usize;
for nullable in [false, true] {
let mut validity = crate::ValidityMask::all_valid(n);
let mut scalars: Vec<Scalar> = Vec::with_capacity(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..n {
if nullable && next() % 4 == 0 {
validity.set(i, false);
scalars.push(Scalar::Null(NullKind::Null));
} else {
let len = (next() % 6) as usize;
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
scalars.push(Scalar::Utf8(s));
}
offsets.push(bytes.len());
}
let col = Column::from_utf8_values_with_validity(bytes, offsets, validity);
// Confirm the fixture exercises a typed contiguous arm, not generic.
let has_null = scalars.iter().any(|s| s.is_missing());
assert_eq!(
col.as_utf8_contiguous().is_some(),
!has_null,
"trial {trial} nullable={nullable}: backing gate"
);
for method in ["average", "min", "max", "first", "dense"] {
for ascending in [true, false] {
let got = col.rank(method, ascending).expect("utf8 rank");
let want = ref_rank(&scalars, method, ascending);
assert_eq!(
got.values(),
want,
"trial {trial} nullable={nullable} method={method} asc={ascending}"
);
}
}
}
}
}
#[test]
fn rank_min_assigns_lowest_tied_rank() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(2),
Scalar::Int64(3),
])
.expect("col");
let r = col.rank("min", true).expect("rank");
assert_eq!(r.values()[1], Scalar::Float64(2.0));
assert_eq!(r.values()[2], Scalar::Float64(2.0));
assert_eq!(r.values()[3], Scalar::Float64(4.0));
}
#[test]
fn rank_max_assigns_highest_tied_rank() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(2),
Scalar::Int64(3),
])
.expect("col");
let r = col.rank("max", true).expect("rank");
assert_eq!(r.values()[1], Scalar::Float64(3.0));
assert_eq!(r.values()[2], Scalar::Float64(3.0));
assert_eq!(r.values()[3], Scalar::Float64(4.0));
}
#[test]
fn rank_first_breaks_ties_by_appearance_order() {
let col =
Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(3), Scalar::Int64(3)])
.expect("col");
let r = col.rank("first", true).expect("rank");
// Sorted positions: (1,3), (2,3), (0,5) → ranks 1,2,3
assert_eq!(r.values()[0], Scalar::Float64(3.0));
assert_eq!(r.values()[1], Scalar::Float64(1.0));
assert_eq!(r.values()[2], Scalar::Float64(2.0));
}
#[test]
fn rank_dense_has_no_gaps() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(2),
Scalar::Int64(3),
])
.expect("col");
let r = col.rank("dense", true).expect("rank");
assert_eq!(r.values()[0], Scalar::Float64(1.0));
assert_eq!(r.values()[1], Scalar::Float64(2.0));
assert_eq!(r.values()[2], Scalar::Float64(2.0));
assert_eq!(r.values()[3], Scalar::Float64(3.0));
}
#[test]
fn rank_null_inputs_stay_null() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(2.0),
])
.expect("col");
let r = col.rank("average", true).expect("rank");
assert_eq!(r.values()[0], Scalar::Float64(1.0));
assert!(r.values()[1].is_missing());
assert_eq!(r.values()[2], Scalar::Float64(2.0));
}
#[test]
fn rank_descending_reverses_assignment() {
let col =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.expect("col");
let r = col.rank("min", false).expect("rank");
assert_eq!(r.values()[0], Scalar::Float64(3.0));
assert_eq!(r.values()[1], Scalar::Float64(2.0));
assert_eq!(r.values()[2], Scalar::Float64(1.0));
}
#[test]
fn rank_invalid_method_errors() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let err = col.rank("bogus", true).unwrap_err();
assert!(matches!(err, crate::ColumnError::Type(_)));
}
// Inline replica of the generic na-last comparator rank (the pre-change
// path the typed Int64/Float64 fast paths must reproduce).
fn rank_reference(vals: &[Scalar], method: &str, ascending: bool) -> Vec<Scalar> {
let len = vals.len();
let mut nm: Vec<(usize, &Scalar)> = vals
.iter()
.enumerate()
.filter(|(_, v)| !v.is_missing())
.collect();
nm.sort_by(|a, b| crate::compare_scalars_na_last(a.1, b.1, ascending));
let mut ranks = vec![Scalar::Null(NullKind::NaN); len];
let n = nm.len();
let mut cursor = 0usize;
let mut dense = 0.0_f64;
while cursor < n {
let mut end = cursor + 1;
while end < n
&& crate::compare_scalars_na_last(nm[cursor].1, nm[end].1, ascending).is_eq()
{
end += 1;
}
let (start_rank, end_rank) = (cursor as f64 + 1.0, end as f64);
dense += 1.0;
for (gi, entry) in nm.iter().enumerate().take(end).skip(cursor) {
ranks[entry.0] = Scalar::Float64(match method {
"average" => (start_rank + end_rank) / 2.0,
"min" => start_rank,
"max" => end_rank,
"first" => gi as f64 + 1.0,
"dense" => dense,
_ => unreachable!(),
});
}
cursor = end;
}
ranks
}
#[test]
fn rank_nullable_i64_f64_matches_generic_reference() {
// rank on a nullable Int64/Float64 column now routes through
// typed_radix_perm + a typed tie-walk. Results (present ranks + Null
// tail) must stay bit-identical to the generic comparator path across
// every method and direction. Null-missing only (no present-NaN) so the
// output Scalars compare with structural eq. Deterministic LCG.
let methods = ["average", "min", "max", "first", "dense"];
let mut state: u64 = 0x3C3C_A5A5_1234_9999;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..160 {
let len = (next() % 280) as usize + 1;
let mut vi = crate::ValidityMask::all_valid(len);
let mut vf = crate::ValidityMask::all_valid(len);
let idata: Vec<i64> = (0..len)
.map(|i| {
let r = next();
if r % 4 == 0 {
vi.set(i, false);
}
(r % 9) as i64 - 4 // narrow range ⇒ ties
})
.collect();
let fdata: Vec<f64> = (0..len)
.map(|i| {
let r = next();
if r % 4 == 0 {
vf.set(i, false);
0.0
} else {
((r % 9) as f64 - 4.0) / 2.0
}
})
.collect();
let icol = Column::from_i64_values_with_validity(idata, vi);
let fcol = Column::from_f64_values_with_validity(fdata, vf);
for (col, tag) in [(&icol, "i64"), (&fcol, "f64")] {
let vals = col.values().to_vec();
for method in methods {
for ascending in [true, false] {
assert_eq!(
col.rank(method, ascending).expect("rank").values(),
rank_reference(&vals, method, ascending).as_slice(),
"{tag} trial {trial} method={method} asc={ascending}"
);
}
}
}
}
}
#[test]
fn rank_temporal_datetime_timedelta_matches_generic_reference() {
// rank on Datetime64/Timedelta64 (all-valid, nullable, AND present-NaT
// = i64::MIN at a valid slot) now routes through typed_radix_perm + the
// typed tie-walk. The Float64 output (present ranks + Null tail) must
// stay bit-identical to the generic comparator path across every method
// and direction. NaT slots (validity-false OR datum i64::MIN) join the
// na-last group and rank to Null(NaN), like a missing value.
let methods = ["average", "min", "max", "first", "dense"];
let mut state: u64 = 0xDA7E_7104_4242_1001;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..160 {
let len = (next() % 240) as usize + 1;
let mut vd = crate::ValidityMask::all_valid(len);
let mut vt = crate::ValidityMask::all_valid(len);
let ddata: Vec<i64> = (0..len)
.map(|i| {
let r = next();
match r % 6 {
0 => {
vd.set(i, false); // validity-false missing
77
}
1 => i64::MIN, // present-NaT at a valid slot
_ => (r % 7) as i64 * 1_000, // ns, narrow range ⇒ ties
}
})
.collect();
let tdata: Vec<i64> = (0..len)
.map(|i| {
let r = next();
match r % 6 {
0 => {
vt.set(i, false);
88
}
1 => i64::MIN,
_ => (r % 7) as i64 * 500,
}
})
.collect();
let dcol = Column::from_datetime64_values_with_validity(ddata, vd);
let tcol = Column::from_timedelta64_values_with_validity(tdata, vt);
for (col, tag) in [(&dcol, "dt64"), (&tcol, "td64")] {
let vals = col.values().to_vec();
for method in methods {
for ascending in [true, false] {
assert_eq!(
col.rank(method, ascending).expect("rank").values(),
rank_reference(&vals, method, ascending).as_slice(),
"{tag} trial {trial} method={method} asc={ascending}"
);
}
}
}
}
}
#[test]
fn searchsorted_left_finds_first_insertion() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(2),
Scalar::Int64(5),
])
.expect("col");
assert_eq!(col.searchsorted(&Scalar::Int64(2), "left").unwrap(), 1);
assert_eq!(col.searchsorted(&Scalar::Int64(0), "left").unwrap(), 0);
assert_eq!(col.searchsorted(&Scalar::Int64(6), "left").unwrap(), 4);
}
#[test]
fn searchsorted_right_finds_last_insertion() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(2),
Scalar::Int64(5),
])
.expect("col");
assert_eq!(col.searchsorted(&Scalar::Int64(2), "right").unwrap(), 3);
}
#[test]
fn searchsorted_rejects_invalid_side() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let err = col.searchsorted(&Scalar::Int64(0), "middle").unwrap_err();
assert!(matches!(err, crate::ColumnError::Type(_)));
}
#[test]
fn searchsorted_rejects_missing_needle() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let err = col
.searchsorted(&Scalar::Null(NullKind::NaN), "left")
.unwrap_err();
assert!(matches!(err, crate::ColumnError::Type(_)));
}
#[test]
fn searchsorted_treats_trailing_nulls_as_greater() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Null(NullKind::NaN),
])
.expect("col");
// needle=3 should land at position 2 (before trailing null).
assert_eq!(col.searchsorted(&Scalar::Int64(3), "left").unwrap(), 2);
}
#[test]
fn searchsorted_values_typed_i64_matches_scalar_path() {
// The typed i64 partition_point path must equal the generic Scalar
// binary search over random sorted data + needles incl. dup runs,
// out-of-range, and exact hits, both sides.
let mut state: u64 = 0x6E54_3210_FEDC_BA98;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..200 {
let n = (next() % 300) as usize + 1;
let mut vals: Vec<i64> = (0..n).map(|_| (next() % 40) as i64 - 20).collect();
vals.sort_unstable(); // searchsorted requires sorted input
let col = Column::from_i64_values_owned(vals.clone());
// Scalar-backed twin forces the generic path (Vec<Scalar> has no
// as_i64_slice typed view).
let scalar_col =
Column::from_values(vals.iter().map(|&v| Scalar::Int64(v)).collect())
.expect("scalar col");
let m = (next() % 50) as usize + 1;
let needles: Vec<Scalar> = (0..m)
.map(|_| Scalar::Int64((next() % 45) as i64 - 22))
.collect();
for side in ["left", "right"] {
let typed = col.searchsorted_values(&needles, side).expect("typed");
let generic = scalar_col
.searchsorted_values(&needles, side)
.expect("generic");
assert_eq!(typed.values(), generic.values(), "side={side}");
}
}
}
#[test]
fn searchsorted_values_typed_datetime_matches_scalar_path() {
// Typed Datetime64 partition_point path == generic Scalar binary search
// (exact Datetime64 comparator), both sides, dup/oob/exact needles.
let mut state: u64 = 0xDA7E_7100_9911_2233;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for _ in 0..200 {
let n = (next() % 300) as usize + 1;
let mut vals: Vec<i64> = (0..n).map(|_| (next() % 50) as i64 * 1_000_000).collect();
vals.sort_unstable();
let col = Column::from_datetime64_values(vals.clone());
let scalar_col =
Column::from_values(vals.iter().map(|&v| Scalar::Datetime64(v)).collect())
.expect("scalar col");
let m = (next() % 40) as usize + 1;
let needles: Vec<Scalar> = (0..m)
.map(|_| Scalar::Datetime64((next() % 55) as i64 * 1_000_000))
.collect();
for side in ["left", "right"] {
let typed = col.searchsorted_values(&needles, side).expect("typed");
let generic = scalar_col
.searchsorted_values(&needles, side)
.expect("generic");
assert_eq!(typed.values(), generic.values(), "side={side}");
}
}
}
#[test]
fn searchsorted_values_left_returns_positions_column() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(2),
Scalar::Int64(5),
])
.expect("col");
let positions = col
.searchsorted_values(
&[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(6)],
"left",
)
.expect("searchsorted");
assert_eq!(positions.dtype(), DType::Int64);
assert_eq!(
positions.values(),
&[Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(4)]
);
}
#[test]
fn searchsorted_values_right_returns_positions_column() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(2),
Scalar::Int64(5),
])
.expect("col");
let positions = col
.searchsorted_values(
&[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(6)],
"right",
)
.expect("searchsorted");
assert_eq!(
positions.values(),
&[Scalar::Int64(0), Scalar::Int64(3), Scalar::Int64(4)]
);
}
#[test]
fn searchsorted_values_rejects_invalid_side() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let err = col
.searchsorted_values(&[Scalar::Int64(0)], "middle")
.unwrap_err();
assert!(matches!(err, crate::ColumnError::Type(_)));
}
#[test]
fn searchsorted_values_rejects_missing_needles() {
let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
let err = col
.searchsorted_values(&[Scalar::Null(NullKind::NaN)], "left")
.unwrap_err();
assert!(matches!(err, crate::ColumnError::Type(_)));
}
#[test]
fn searchsorted_with_sorter_uses_argsort_permutation() {
let col = Column::from_values(vec![
Scalar::Int64(5),
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(2),
])
.expect("col");
let sorter = col.argsort();
assert_eq!(
col.searchsorted_with_sorter(&Scalar::Int64(2), "left", &sorter)
.unwrap(),
1
);
assert_eq!(
col.searchsorted_with_sorter(&Scalar::Int64(2), "right", &sorter)
.unwrap(),
3
);
assert_eq!(
col.searchsorted_with_sorter(&Scalar::Int64(6), "left", &sorter)
.unwrap(),
4
);
}
#[test]
fn searchsorted_values_with_sorter_returns_positions_column() {
let col = Column::from_values(vec![
Scalar::Int64(5),
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(2),
])
.expect("col");
let sorter = col.argsort();
let positions = col
.searchsorted_values_with_sorter(
&[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(6)],
"left",
&sorter,
)
.expect("searchsorted");
assert_eq!(
positions.values(),
&[Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(4)]
);
}
#[test]
fn searchsorted_values_with_sorter_typed_matches_count_reference() {
// The typed Int64/Float64 sorter fast path (partition over data[sorter[
// mid]]) must equal a count-based reference: for a needle nv over the
// sorted view, left = #(v < nv), right = #(v <= nv). Unsorted all-valid
// columns via from_i64_values_owned/from_f64_values (⇒ as_*_slice ⇒ the
// typed path fires), argsort sorter, ties + out-of-range needles.
let mut state: u64 = 0x5EAF_C0DE_1234_9999;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..80 {
let n = (next() % 300) as usize + 1;
let idata: Vec<i64> = (0..n).map(|_| (next() % 21) as i64 - 10).collect();
let fdata: Vec<f64> = idata.iter().map(|&x| x as f64 * 0.5).collect();
let icol = Column::from_i64_values_owned(idata.clone());
let fcol = Column::from_f64_values(fdata.clone());
let isorter = icol.argsort();
let fsorter = fcol.argsort();
// sorted views
let iview: Vec<i64> = isorter.iter().map(|&i| idata[i]).collect();
let fview: Vec<f64> = fsorter.iter().map(|&i| fdata[i]).collect();
let needles_i: Vec<Scalar> =
(-12..=12).map(Scalar::Int64).collect();
let needles_f: Vec<Scalar> =
(-12..=12).map(|k| Scalar::Float64(k as f64 * 0.5)).collect();
for side in ["left", "right"] {
let left = side == "left";
let iwant: Vec<i64> = needles_i
.iter()
.map(|n| {
let nv = match n {
Scalar::Int64(v) => *v,
_ => unreachable!(),
};
iview
.iter()
.filter(|&&v| if left { v < nv } else { v <= nv })
.count() as i64
})
.collect();
let igot: Vec<i64> = icol
.searchsorted_values_with_sorter(&needles_i, side, &isorter)
.expect("iss")
.values()
.iter()
.map(|v| match v {
Scalar::Int64(x) => *x,
o => panic!("{o:?}"),
})
.collect();
assert_eq!(igot, iwant, "i64 trial {trial} side={side}");
let fwant: Vec<i64> = needles_f
.iter()
.map(|n| {
let nv = match n {
Scalar::Float64(v) => *v,
_ => unreachable!(),
};
fview
.iter()
.filter(|&&v| if left { v < nv } else { v <= nv })
.count() as i64
})
.collect();
let fgot: Vec<i64> = fcol
.searchsorted_values_with_sorter(&needles_f, side, &fsorter)
.expect("fss")
.values()
.iter()
.map(|v| match v {
Scalar::Int64(x) => *x,
o => panic!("{o:?}"),
})
.collect();
assert_eq!(fgot, fwant, "f64 trial {trial} side={side}");
}
}
}
#[test]
fn searchsorted_with_sorter_rejects_length_mismatch() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let err = col
.searchsorted_with_sorter(&Scalar::Int64(1), "left", &[0])
.unwrap_err();
assert!(matches!(
err,
crate::ColumnError::LengthMismatch { left: 2, right: 1 }
));
}
#[test]
fn searchsorted_with_sorter_rejects_duplicate_or_oob_indices() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
let duplicate = col
.searchsorted_with_sorter(&Scalar::Int64(1), "left", &[0, 0])
.unwrap_err();
assert!(matches!(
duplicate,
crate::ColumnError::InvalidSorter { .. }
));
let out_of_bounds = col
.searchsorted_with_sorter(&Scalar::Int64(1), "left", &[0, 2])
.unwrap_err();
assert!(matches!(
out_of_bounds,
crate::ColumnError::InvalidSorter { .. }
));
}
}
mod count_nonzero {
use super::*;
fn former_body_akbew(column: &Column) -> usize {
column.nonzero().len()
}
fn assert_nullable_bool_unmaterialized_akbew(column: &Column) {
assert!(matches!(
&column.values,
ScalarValues::LazyNullableBool { .. }
));
if let ScalarValues::LazyNullableBool { values, .. } = &column.values {
assert!(values.get().is_none());
}
}
fn median_nanos_akbew(samples: &mut [u128]) -> u128 {
samples.sort_unstable();
samples[samples.len() / 2]
}
fn measure_nanos_akbew<T>(f: impl FnOnce() -> T) -> u128 {
let start = std::time::Instant::now();
std::hint::black_box(f());
start.elapsed().as_nanos()
}
#[test]
fn nullable_bool_count_nonzero_raw_matches_former_akbew() {
let data = vec![true, false, true, true, false, true, false, true];
let mut validity = ValidityMask::all_valid(data.len());
validity.set(2, false);
validity.set(4, false);
validity.set(7, false);
let reference =
Column::from_bool_values_with_validity(data.clone(), validity.clone());
let candidate = Column::from_bool_values_with_validity(data, validity);
assert_eq!(former_body_akbew(&reference), 3);
assert_eq!(candidate.count_nonzero(), former_body_akbew(&reference));
assert_nullable_bool_unmaterialized_akbew(&candidate);
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn nullable_bool_count_nonzero_ab_akbew() {
const LEN: usize = 1_000_000;
const SAMPLES: usize = 15;
let mut state = 0xB001_C0A7_5EED_A11Du64;
let mut data = vec![false; LEN];
let mut validity = ValidityMask::all_valid(LEN);
for (idx, value) in data.iter_mut().enumerate() {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
*value = state & 1 == 1;
if (state >> 40).is_multiple_of(5) {
validity.set(idx, false);
}
}
let reference_a =
Column::from_bool_values_with_validity(data.clone(), validity.clone());
let reference_b =
Column::from_bool_values_with_validity(data.clone(), validity.clone());
let candidate_a =
Column::from_bool_values_with_validity(data.clone(), validity.clone());
let candidate_b = Column::from_bool_values_with_validity(data, validity);
let former = former_body_akbew(&reference_a);
let witness = candidate_a.count_nonzero();
assert_eq!(former, witness);
assert_nullable_bool_unmaterialized_akbew(&candidate_a);
for _ in 0..3 {
std::hint::black_box(former_body_akbew(std::hint::black_box(&reference_a)));
std::hint::black_box(former_body_akbew(std::hint::black_box(&reference_b)));
std::hint::black_box(std::hint::black_box(&candidate_a).count_nonzero());
std::hint::black_box(std::hint::black_box(&candidate_b).count_nonzero());
}
let mut former_a = Vec::with_capacity(SAMPLES);
let mut former_b = Vec::with_capacity(SAMPLES);
let mut typed_a = Vec::with_capacity(SAMPLES);
let mut typed_b = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample.is_multiple_of(2) {
former_a.push(measure_nanos_akbew(|| {
former_body_akbew(std::hint::black_box(&reference_a))
}));
typed_a.push(measure_nanos_akbew(|| {
std::hint::black_box(&candidate_a).count_nonzero()
}));
typed_b.push(measure_nanos_akbew(|| {
std::hint::black_box(&candidate_b).count_nonzero()
}));
former_b.push(measure_nanos_akbew(|| {
former_body_akbew(std::hint::black_box(&reference_b))
}));
} else {
former_b.push(measure_nanos_akbew(|| {
former_body_akbew(std::hint::black_box(&reference_b))
}));
typed_b.push(measure_nanos_akbew(|| {
std::hint::black_box(&candidate_b).count_nonzero()
}));
typed_a.push(measure_nanos_akbew(|| {
std::hint::black_box(&candidate_a).count_nonzero()
}));
former_a.push(measure_nanos_akbew(|| {
former_body_akbew(std::hint::black_box(&reference_a))
}));
}
}
let former_a_p50 = median_nanos_akbew(&mut former_a);
let former_b_p50 = median_nanos_akbew(&mut former_b);
let typed_a_p50 = median_nanos_akbew(&mut typed_a);
let typed_b_p50 = median_nanos_akbew(&mut typed_b);
let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
let typed_mean = (typed_a_p50 + typed_b_p50) as f64 / 2.0;
println!(
"nullable Bool count_nonzero, len={LEN}, samples={SAMPLES}, count={witness}"
);
println!(
"former nonzero().len() p50 A/B: {former_a_p50} / {former_b_p50} ns"
);
println!("typed raw count p50 A/B: {typed_a_p50} / {typed_b_p50} ns");
println!("former/typed p50 ratio: {:.3}x", former_mean / typed_mean);
assert_nullable_bool_unmaterialized_akbew(&candidate_a);
assert_nullable_bool_unmaterialized_akbew(&candidate_b);
}
}
mod value_counts {
use fp_types::NullKind;
use super::*;
#[test]
fn value_counts_default_drops_missing_and_sorts_descending() {
let col = Column::from_values(vec![
Scalar::Int64(3),
Scalar::Int64(1),
Scalar::Null(NullKind::NaN),
Scalar::Int64(3),
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Int64(3),
])
.expect("col");
let (values, counts) = col.value_counts().expect("value_counts");
assert_eq!(
values.values(),
&[Scalar::Int64(3), Scalar::Int64(1), Scalar::Int64(2)]
);
assert_eq!(
counts.values(),
&[Scalar::Int64(3), Scalar::Int64(2), Scalar::Int64(1)]
);
}
#[test]
fn value_counts_nullable_utf8_typed_matches_generic() {
// The typed nullable-Utf8 value_counts arm (dropna=true, cold cache) must be
// BIT-EXACT to the generic path. A/B on identical LazyNullableUtf8 data:
// `col_cold` (fresh, cold cache) exercises the typed arm; `col_warm` has its
// Scalar cache pre-materialized so the cold-cache gate defers it to the
// generic tally. Compare (values, counts) across normalize/sort/ascending.
// Seeded short strings over {a,b,c,d} (ties) with ~25% nulls.
let mut state: u64 = 0x77C0_C0DE_1234_9E37;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..80 {
let n = (next() % 300) as usize;
let mut validity = crate::ValidityMask::all_valid(n);
let mut bytes: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0];
for i in 0..n {
if next() % 4 == 0 {
validity.set(i, false);
} else {
let len = (next() % 5) as usize;
let s: String = (0..len)
.map(|_| (b'a' + (next() % 4) as u8) as char)
.collect();
bytes.extend_from_slice(s.as_bytes());
}
offsets.push(bytes.len());
}
let col_cold = Column::from_utf8_values_with_validity(
bytes.clone(),
offsets.clone(),
validity.clone(),
);
let col_warm =
Column::from_utf8_values_with_validity(bytes, offsets, validity);
// Pre-materialize the Scalar cache so the cold-cache gate defers col_warm
// to the generic path (the oracle). col_cold is never touched ⇒ stays cold.
let _ = col_warm.values();
for (normalize, sort, ascending) in [
(false, true, false),
(false, true, true),
(true, true, false),
(false, false, false),
] {
let (cv, cc) = col_cold
.value_counts_with_options(normalize, sort, ascending, true)
.expect("cold value_counts");
let (wv, wc) = col_warm
.value_counts_with_options(normalize, sort, ascending, true)
.expect("warm value_counts");
assert_eq!(
cv.values(),
wv.values(),
"values trial {trial} norm={normalize} sort={sort} asc={ascending}"
);
assert_eq!(
cc.values(),
wc.values(),
"counts trial {trial} norm={normalize} sort={sort} asc={ascending}"
);
}
}
}
#[test]
fn value_counts_sort_false_preserves_first_seen_order() {
let col = Column::from_values(vec![
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(1),
])
.expect("col");
let (values, counts) = col
.value_counts_with_options(false, false, false, true)
.expect("value_counts");
assert_eq!(
values.values(),
&[Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)]
);
assert_eq!(
counts.values(),
&[Scalar::Int64(2), Scalar::Int64(2), Scalar::Int64(1)]
);
}
#[test]
fn value_counts_wide_growable_open_addressing_matches_reference() {
// Regression for the value_counts_i64_typed wide-path conversion
// (FxHashMap → growable open-addressing): WIDE high-bit-only keys
// (k << 34) over enough rows (> 1024 distinct) to force rehashes, plus
// the i64::MIN value (the table's EMPTY sentinel, tracked separately).
// First-seen (value, count) pairs (sort=false) must be byte-identical to
// a first-seen HashMap reference.
use std::collections::HashMap;
let mut state: u64 = 0x1122_3344_5566_7788;
let mut next = || {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
state
};
for trial in 0..30 {
let distinct = 2000 + (next() % 800) as i64;
let n = 12_000usize;
let data: Vec<i64> = (0..n)
.map(|i| {
if i % 400 == 0 {
i64::MIN
} else {
(((next() % distinct as u64) as i64) - distinct / 2) << 34
}
})
.collect();
assert!(crate::i64_direct_address_range(&data).is_none());
// First-seen reference.
let mut order: Vec<i64> = Vec::new();
let mut cnt: HashMap<i64, usize> = HashMap::new();
for &v in &data {
let e = cnt.entry(v).or_insert_with(|| {
order.push(v);
0
});
*e += 1;
}
let exp_vals = order.clone();
let exp_counts: Vec<i64> = order.iter().map(|v| cnt[v] as i64).collect();
let (vals, counts) = Column::from_i64_values_owned(data)
.value_counts_with_options(false, false, false, false)
.expect("value_counts");
let got_vals: Vec<i64> = vals
.values()
.iter()
.map(|v| match v {
Scalar::Int64(x) => *x,
o => panic!("not i64: {o:?}"),
})
.collect();
let got_counts: Vec<i64> = counts
.values()
.iter()
.map(|v| match v {
Scalar::Int64(x) => *x,
o => panic!("not i64: {o:?}"),
})
.collect();
assert_eq!(got_vals, exp_vals, "values trial {trial}");
assert_eq!(got_counts, exp_counts, "counts trial {trial}");
}
}
#[test]
fn value_counts_dropna_false_includes_missing_bucket() {
let col = Column::from_values(vec![
Scalar::Utf8("a".into()),
Scalar::Null(NullKind::NaN),
Scalar::Utf8("a".into()),
Scalar::Null(NullKind::Null),
])
.expect("col");
let (values, counts) = col
.value_counts_with_options(false, true, false, false)
.expect("value_counts");
assert_eq!(values.values()[0], Scalar::Utf8("a".into()));
assert!(values.values()[1].is_missing());
assert_eq!(counts.values(), &[Scalar::Int64(2), Scalar::Int64(2)]);
}
#[test]
fn value_counts_normalize_uses_returned_total() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
])
.expect("col");
let (values, counts) = col
.value_counts_with_options(true, true, false, true)
.expect("value_counts");
assert_eq!(
values.values(),
&[Scalar::Float64(1.0), Scalar::Float64(2.0)]
);
assert_eq!(counts.dtype(), DType::Float64);
assert_eq!(
counts.values(),
&[Scalar::Float64(2.0 / 3.0), Scalar::Float64(1.0 / 3.0)]
);
}
#[test]
fn value_counts_all_valid_int64_keeps_typed_outputs() {
let col = Column::from_i64_values_owned(vec![10, -3, 10, 7, -3, 10]);
let (values, counts) = col.value_counts().expect("value_counts");
assert_eq!(values.as_i64_slice(), Some(&[10, -3, 7][..]));
assert_eq!(counts.as_i64_slice(), Some(&[3, 2, 1][..]));
let (values, counts) = col
.value_counts_with_options(true, true, false, true)
.expect("normalized value_counts");
assert_eq!(values.as_i64_slice(), Some(&[10, -3, 7][..]));
assert_eq!(
counts.as_f64_slice(),
Some(&[3.0 / 6.0, 2.0 / 6.0, 1.0 / 6.0][..])
);
}
#[test]
fn python_mod_f64_handles_infinity_divisor() {
use crate::python_mod_f64;
assert_eq!(python_mod_f64(5.0, f64::INFINITY), 5.0);
assert_eq!(python_mod_f64(-5.0, f64::INFINITY), f64::INFINITY);
assert_eq!(python_mod_f64(5.0, f64::NEG_INFINITY), f64::NEG_INFINITY);
assert_eq!(python_mod_f64(-5.0, f64::NEG_INFINITY), -5.0);
assert_eq!(python_mod_f64(0.0, f64::INFINITY), 0.0);
assert!(python_mod_f64(0.0, f64::NEG_INFINITY).is_sign_negative());
assert_eq!(python_mod_f64(-0.0, f64::INFINITY), 0.0);
assert_eq!(python_mod_f64(-0.0, f64::NEG_INFINITY), -0.0);
assert!(python_mod_f64(f64::NAN, f64::INFINITY).is_nan());
assert!(python_mod_f64(f64::NAN, f64::NEG_INFINITY).is_nan());
assert!(python_mod_f64(f64::INFINITY, f64::INFINITY).is_nan());
assert!(python_mod_f64(f64::NEG_INFINITY, f64::NEG_INFINITY).is_nan());
}
#[test]
fn python_floor_div_f64_handles_infinite_operands() {
use crate::python_floor_div_f64;
assert_eq!(python_floor_div_f64(5.0, f64::INFINITY), 0.0);
assert_eq!(python_floor_div_f64(-5.0, f64::INFINITY), -1.0);
assert_eq!(python_floor_div_f64(5.0, f64::NEG_INFINITY), -1.0);
assert_eq!(python_floor_div_f64(-5.0, f64::NEG_INFINITY), 0.0);
assert_eq!(python_floor_div_f64(0.0, f64::INFINITY), 0.0);
assert!(python_floor_div_f64(-0.0, f64::INFINITY).is_sign_negative());
assert!(python_floor_div_f64(0.0, f64::NEG_INFINITY).is_sign_negative());
assert_eq!(python_floor_div_f64(-0.0, f64::NEG_INFINITY), 0.0);
assert!(python_floor_div_f64(f64::INFINITY, 2.0).is_nan());
assert!(python_floor_div_f64(f64::NEG_INFINITY, -2.0).is_nan());
assert!(python_floor_div_f64(f64::INFINITY, f64::INFINITY).is_nan());
}
fn histogram_former_body_wl4jg(
col: &Column,
bin_edges: &[f64],
) -> Result<Column, ColumnError> {
if bin_edges.len() < 2 {
return Err(ColumnError::Type(crate::TypeError::NonNumericValue {
value: "histogram requires at least 2 bin edges".to_owned(),
dtype: col.dtype,
}));
}
let n_bins = bin_edges.len() - 1;
let mut counts = vec![0i64; n_bins];
let strict = bin_edges.windows(2).all(|w| w[0] < w[1]);
for value in &col.values {
if value.is_missing() {
continue;
}
let x = match value.to_f64() {
Ok(value) if value.is_finite() => value,
_ => continue,
};
if strict {
if x < bin_edges[0] || x > bin_edges[n_bins] {
continue;
}
let bin =
(bin_edges.partition_point(|&edge| edge <= x) - 1).min(n_bins - 1);
counts[bin] += 1;
continue;
}
for i in 0..n_bins {
let in_bin = if i == n_bins - 1 {
x >= bin_edges[i] && x <= bin_edges[i + 1]
} else {
x >= bin_edges[i] && x < bin_edges[i + 1]
};
if in_bin {
counts[i] += 1;
break;
}
}
}
let out = counts.into_iter().map(Scalar::Int64).collect();
Column::new(DType::Int64, out)
}
fn assert_nullable_f64_unmaterialized_wl4jg(col: &Column) {
assert!(matches!(
&col.values,
ScalarValues::LazyNullableFloat64 { .. }
));
if let ScalarValues::LazyNullableFloat64 { values, .. } = &col.values {
assert!(values.get().is_none());
}
}
fn median_nanos_wl4jg(samples: &mut [u128]) -> u128 {
samples.sort_unstable();
samples[samples.len() / 2]
}
fn measure_nanos_wl4jg<T>(f: impl FnOnce() -> T) -> u128 {
let start = std::time::Instant::now();
std::hint::black_box(f());
start.elapsed().as_nanos()
}
#[test]
fn histogram_nullable_f64_raw_matches_former_wl4jg() {
let data = vec![
-2.0,
-1.0,
-0.0,
0.0,
0.5,
1.0,
2.0,
f64::NAN,
f64::INFINITY,
f64::NEG_INFINITY,
1.5,
];
let mut validity = ValidityMask::all_valid(data.len());
validity.set(10, false);
let reference =
Column::from_f64_values_with_validity(data.clone(), validity.clone());
let candidate = Column::from_f64_values_with_validity(data, validity);
for edges in [vec![-1.0, 0.0, 1.0, 2.0], vec![-1.0, 0.0, 0.0, 2.0]] {
let former = histogram_former_body_wl4jg(&reference, &edges)
.expect("former nullable Float64 histogram");
let got = candidate
.histogram(&edges)
.expect("typed nullable Float64 histogram");
assert_eq!(got.values(), former.values(), "edges={edges:?}");
}
assert_nullable_f64_unmaterialized_wl4jg(&candidate);
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn histogram_nullable_f64_ab_wl4jg() {
const LEN: usize = 1_000_000;
const SAMPLES: usize = 15;
let mut state = 0x48_1570_6A4F_6C2Du64;
let mut data = vec![0.0; LEN];
let mut validity = ValidityMask::all_valid(LEN);
for (idx, value) in data.iter_mut().enumerate() {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
if (state >> 40).is_multiple_of(5) {
validity.set(idx, false);
} else {
*value = ((state >> 16) % 2_000_000) as f64 / 1000.0 - 1000.0;
}
}
let edges = (0..=64)
.map(|idx| -1024.0 + idx as f64 * 32.0)
.collect::<Vec<_>>();
let reference_a =
Column::from_f64_values_with_validity(data.clone(), validity.clone());
let reference_b =
Column::from_f64_values_with_validity(data.clone(), validity.clone());
let candidate_a =
Column::from_f64_values_with_validity(data.clone(), validity.clone());
let candidate_b = Column::from_f64_values_with_validity(data, validity);
let former = histogram_former_body_wl4jg(&reference_a, &edges)
.expect("former nullable Float64 histogram");
let witness = candidate_a
.histogram(&edges)
.expect("typed nullable Float64 histogram");
assert_eq!(former.values(), witness.values());
assert_nullable_f64_unmaterialized_wl4jg(&candidate_a);
for _ in 0..3 {
let _ = std::hint::black_box(histogram_former_body_wl4jg(
&reference_a,
&edges,
));
let _ = std::hint::black_box(histogram_former_body_wl4jg(
&reference_b,
&edges,
));
let _ = std::hint::black_box(candidate_a.histogram(&edges));
let _ = std::hint::black_box(candidate_b.histogram(&edges));
}
let mut former_a = Vec::with_capacity(SAMPLES);
let mut former_b = Vec::with_capacity(SAMPLES);
let mut typed_a = Vec::with_capacity(SAMPLES);
let mut typed_b = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample.is_multiple_of(2) {
former_a.push(measure_nanos_wl4jg(|| {
histogram_former_body_wl4jg(&reference_a, &edges)
}));
typed_a.push(measure_nanos_wl4jg(|| candidate_a.histogram(&edges)));
typed_b.push(measure_nanos_wl4jg(|| candidate_b.histogram(&edges)));
former_b.push(measure_nanos_wl4jg(|| {
histogram_former_body_wl4jg(&reference_b, &edges)
}));
} else {
former_b.push(measure_nanos_wl4jg(|| {
histogram_former_body_wl4jg(&reference_b, &edges)
}));
typed_b.push(measure_nanos_wl4jg(|| candidate_b.histogram(&edges)));
typed_a.push(measure_nanos_wl4jg(|| candidate_a.histogram(&edges)));
former_a.push(measure_nanos_wl4jg(|| {
histogram_former_body_wl4jg(&reference_a, &edges)
}));
}
}
let former_a_p50 = median_nanos_wl4jg(&mut former_a);
let former_b_p50 = median_nanos_wl4jg(&mut former_b);
let typed_a_p50 = median_nanos_wl4jg(&mut typed_a);
let typed_b_p50 = median_nanos_wl4jg(&mut typed_b);
let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
let typed_mean = (typed_a_p50 + typed_b_p50) as f64 / 2.0;
println!(
"nullable Float64 histogram, len={LEN}, bins=64, samples={SAMPLES}"
);
println!("former Scalar p50 A/B: {former_a_p50} / {former_b_p50} ns");
println!("typed raw p50 A/B: {typed_a_p50} / {typed_b_p50} ns");
println!("former/typed p50 ratio: {:.3}x", former_mean / typed_mean);
assert_nullable_f64_unmaterialized_wl4jg(&candidate_a);
assert_nullable_f64_unmaterialized_wl4jg(&candidate_b);
}
#[test]
fn histogram_counts_values_in_bins() {
let col = Column::from_values(vec![
Scalar::Float64(0.5),
Scalar::Float64(1.5),
Scalar::Float64(2.5),
Scalar::Float64(1.2),
Scalar::Float64(2.8),
])
.unwrap();
let edges = vec![0.0, 1.0, 2.0, 3.0];
let counts = col.histogram(&edges).unwrap();
assert_eq!(
counts.values(),
&[
Scalar::Int64(1), // [0, 1): 0.5
Scalar::Int64(2), // [1, 2): 1.5, 1.2
Scalar::Int64(2), // [2, 3]: 2.5, 2.8
]
);
}
#[test]
fn histogram_auto_creates_bins() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
Scalar::Float64(4.0),
])
.unwrap();
let (counts, edges) = col.histogram_auto(3).unwrap();
assert_eq!(counts.len(), 3);
assert_eq!(edges.len(), 4);
assert!((edges[0] - 1.0).abs() < 1e-10);
assert!((edges[3] - 4.0).abs() < 1e-10);
}
#[test]
fn histogram_auto_constant_values_extends_range() {
let col = Column::from_values(vec![
Scalar::Float64(5.0),
Scalar::Float64(5.0),
Scalar::Float64(5.0),
])
.unwrap();
let (counts, edges) = col.histogram_auto(2).unwrap();
assert_eq!(counts.len(), 2);
assert!(edges[0] < 5.0);
assert!(edges[2] > 5.0);
}
#[test]
fn hanning_window_shape() {
let win = Column::hanning(5).unwrap();
assert_eq!(win.len(), 5);
// Endpoints should be 0
assert!((win.values()[0].to_f64().unwrap()).abs() < 1e-10);
assert!((win.values()[4].to_f64().unwrap()).abs() < 1e-10);
// Center should be 1
assert!((win.values()[2].to_f64().unwrap() - 1.0).abs() < 1e-10);
}
#[test]
fn hamming_window_shape() {
let win = Column::hamming(5).unwrap();
assert_eq!(win.len(), 5);
// Hamming endpoints are ~0.08, not 0
let v0 = win.values()[0].to_f64().unwrap();
assert!(v0 > 0.07 && v0 < 0.09);
}
#[test]
fn bartlett_window_triangular() {
let win = Column::bartlett(5).unwrap();
assert_eq!(win.len(), 5);
// Endpoints should be 0
assert!((win.values()[0].to_f64().unwrap()).abs() < 1e-10);
assert!((win.values()[4].to_f64().unwrap()).abs() < 1e-10);
// Center should be 1
assert!((win.values()[2].to_f64().unwrap() - 1.0).abs() < 1e-10);
}
#[test]
fn convolve_full_mode() {
let a = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(3.0),
])
.unwrap();
let v = Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(1.0)]).unwrap();
let result = a.convolve(&v, "full").unwrap();
// Full convolution: [1*1, 1*1+2*1, 2*1+3*1, 3*1] = [1, 3, 5, 3]
assert_eq!(result.len(), 4);
assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
assert!((result.values()[1].to_f64().unwrap() - 3.0).abs() < 1e-10);
assert!((result.values()[2].to_f64().unwrap() - 5.0).abs() < 1e-10);
assert!((result.values()[3].to_f64().unwrap() - 3.0).abs() < 1e-10);
}
#[test]
fn geomspace_creates_geometric_progression() {
let col = Column::geomspace(1.0, 1000.0, 4).unwrap();
assert_eq!(col.len(), 4);
assert!((col.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
assert!((col.values()[1].to_f64().unwrap() - 10.0).abs() < 1e-10);
assert!((col.values()[2].to_f64().unwrap() - 100.0).abs() < 1e-10);
assert!((col.values()[3].to_f64().unwrap() - 1000.0).abs() < 1e-10);
}
#[test]
fn nan_to_num_replaces_special_values() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(f64::NAN),
Scalar::Float64(f64::INFINITY),
Scalar::Float64(f64::NEG_INFINITY),
])
.unwrap();
let result = col.nan_to_num().unwrap();
assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
assert!((result.values()[1].to_f64().unwrap() - 0.0).abs() < 1e-10);
assert_eq!(result.values()[2].to_f64().unwrap(), f64::MAX);
assert_eq!(result.values()[3].to_f64().unwrap(), f64::MIN);
}
#[test]
fn nan_to_num_with_values_matches_replacement_oracle_am707() {
// Differential vs replacement oracle (br-frankenpandas-am707).
// Seeded LCG, no mocks.
fn next(seed: &mut u64) -> u64 {
*seed = seed
.wrapping_mul(3935559000370003845)
.wrapping_add(2691343689449507681);
*seed
}
fn replacement(seed: &mut u64) -> f64 {
let raw = (next(seed) % 200_001) as i64 - 100_000;
raw as f64 / 23.0
}
fn expected_value(value: &Scalar, nan: f64, posinf: f64, neginf: f64) -> f64 {
match value {
Scalar::Float64(v) if v.is_nan() => nan,
Scalar::Float64(v) if *v == f64::INFINITY => posinf,
Scalar::Float64(v) if *v == f64::NEG_INFINITY => neginf,
Scalar::Float64(v) => *v,
Scalar::Null(_) => nan,
other => panic!("unexpected value in oracle: {other:?}"),
}
}
let mut seed = 0xa070_7a7e_0f11_ca1e_u64;
for case in 0..260 {
let nan = replacement(&mut seed);
let posinf = replacement(&mut seed);
let neginf = replacement(&mut seed);
let len = (next(&mut seed) % 67 + 1) as usize;
let mut values = Vec::with_capacity(len);
for _ in 0..len {
let selector = next(&mut seed) % 13;
let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
values.push(match selector {
0 => Scalar::Null(NullKind::NaN),
1 => Scalar::Float64(f64::NAN),
2 => Scalar::Float64(f64::INFINITY),
3 => Scalar::Float64(f64::NEG_INFINITY),
_ => Scalar::Float64(raw as f64 / 31.0 + frac),
});
}
let input = Column::from_values(values.clone()).expect("column");
let result = input
.nan_to_num_with_values(nan, posinf, neginf)
.expect("nan_to_num_with_values");
assert_eq!(result.dtype(), DType::Float64);
assert_eq!(result.values().len(), values.len());
for (pos, (before, after)) in values.iter().zip(result.values()).enumerate() {
let expected = expected_value(before, nan, posinf, neginf);
match after {
Scalar::Float64(got) => assert_eq!(
*got, expected,
"case={case} pos={pos}: got {got}, expected {expected}"
),
other => panic!("case={case} pos={pos}: expected Float64, got {other:?}"),
}
}
}
}
#[test]
fn rint_rounds_to_nearest_even() {
let col = Column::from_values(vec![
Scalar::Float64(0.5),
Scalar::Float64(1.5),
Scalar::Float64(2.5),
Scalar::Float64(3.5),
])
.unwrap();
let result = col.rint().unwrap();
// Banker's rounding: 0.5->0, 1.5->2, 2.5->2, 3.5->4
assert!((result.values()[0].to_f64().unwrap() - 0.0).abs() < 1e-10);
assert!((result.values()[1].to_f64().unwrap() - 2.0).abs() < 1e-10);
assert!((result.values()[2].to_f64().unwrap() - 2.0).abs() < 1e-10);
assert!((result.values()[3].to_f64().unwrap() - 4.0).abs() < 1e-10);
}
#[test]
fn ldexp_multiplies_by_power_of_two() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(0.5),
])
.unwrap();
let result = col.ldexp(3).unwrap(); // multiply by 2^3 = 8
assert!((result.values()[0].to_f64().unwrap() - 8.0).abs() < 1e-10);
assert!((result.values()[1].to_f64().unwrap() - 16.0).abs() < 1e-10);
assert!((result.values()[2].to_f64().unwrap() - 4.0).abs() < 1e-10);
}
#[test]
fn modf_splits_integer_and_fraction() {
let col = Column::from_values(vec![
Scalar::Float64(3.5),
Scalar::Float64(-2.25),
Scalar::Float64(1.0),
])
.unwrap();
let (frac, int) = col.modf().unwrap();
assert!((frac.values()[0].to_f64().unwrap() - 0.5).abs() < 1e-10);
assert!((int.values()[0].to_f64().unwrap() - 3.0).abs() < 1e-10);
assert!((frac.values()[1].to_f64().unwrap() - (-0.25)).abs() < 1e-10);
assert!((int.values()[1].to_f64().unwrap() - (-2.0)).abs() < 1e-10);
assert!((frac.values()[2].to_f64().unwrap() - 0.0).abs() < 1e-10);
assert!((int.values()[2].to_f64().unwrap() - 1.0).abs() < 1e-10);
}
#[test]
fn spacing_returns_ulp() {
let col = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(-1.0),
Scalar::Float64(0.0),
])
.unwrap();
let result = col.spacing().unwrap();
// Spacing at 1.0 is about 2.2e-16
let s1 = result.values()[0].to_f64().unwrap();
assert!(s1 > 0.0 && s1 < 1e-15);
// Spacing is symmetric for negative numbers
let s_neg1 = result.values()[1].to_f64().unwrap();
assert!((s1 - s_neg1).abs() < 1e-20);
// Spacing at 0 is smallest denormal (not MIN_POSITIVE which is normalized)
assert_eq!(result.values()[2].to_f64().unwrap(), f64::from_bits(1));
}
#[test]
fn frexp_decomposes_floats() {
let col = Column::from_values(vec![
Scalar::Float64(4.0),
Scalar::Float64(0.5),
Scalar::Float64(-8.0),
Scalar::Float64(0.0),
])
.unwrap();
let (mant, exp) = col.frexp().unwrap();
// 4.0 = 0.5 * 2^3
assert!((mant.values()[0].to_f64().unwrap() - 0.5).abs() < 1e-10);
assert_eq!(exp.values()[0].to_i64().unwrap(), 3);
// 0.5 = 0.5 * 2^0
assert!((mant.values()[1].to_f64().unwrap() - 0.5).abs() < 1e-10);
assert_eq!(exp.values()[1].to_i64().unwrap(), 0);
// -8.0 = -0.5 * 2^4
assert!((mant.values()[2].to_f64().unwrap() - (-0.5)).abs() < 1e-10);
assert_eq!(exp.values()[2].to_i64().unwrap(), 4);
// 0.0 = 0.0 * 2^0
assert!((mant.values()[3].to_f64().unwrap() - 0.0).abs() < 1e-10);
assert_eq!(exp.values()[3].to_i64().unwrap(), 0);
}
#[test]
fn nextafter_returns_adjacent_floats() {
let col = Column::from_values(vec![
Scalar::Float64(0.0),
Scalar::Float64(1.0),
Scalar::Float64(1.0),
])
.unwrap();
let toward = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Float64(0.0),
])
.unwrap();
let result = col.nextafter(&toward).unwrap();
// nextafter(0, 1) = smallest positive denormal (not MIN_POSITIVE which is normalized)
assert_eq!(result.values()[0].to_f64().unwrap(), f64::from_bits(1));
// nextafter(1, 2) > 1
let r1 = result.values()[1].to_f64().unwrap();
assert!(r1 > 1.0 && r1 < 1.0 + 1e-15);
// nextafter(1, 0) < 1
let r2 = result.values()[2].to_f64().unwrap();
assert!(r2 < 1.0 && r2 > 1.0 - 1e-15);
}
#[test]
fn isneginf_isposinf_detect_infinities() {
let col = Column::from_values(vec![
Scalar::Float64(f64::NEG_INFINITY),
Scalar::Float64(f64::INFINITY),
Scalar::Float64(1.0),
Scalar::Float64(f64::NAN),
])
.unwrap();
let neginf = col.isneginf().unwrap();
let posinf = col.isposinf().unwrap();
assert_eq!(neginf.values()[0], Scalar::Bool(true));
assert_eq!(neginf.values()[1], Scalar::Bool(false));
assert_eq!(neginf.values()[2], Scalar::Bool(false));
assert_eq!(neginf.values()[3], Scalar::Bool(false));
assert_eq!(posinf.values()[0], Scalar::Bool(false));
assert_eq!(posinf.values()[1], Scalar::Bool(true));
assert_eq!(posinf.values()[2], Scalar::Bool(false));
assert_eq!(posinf.values()[3], Scalar::Bool(false));
}
#[test]
fn exp2_computes_power_of_two() {
let col = Column::from_values(vec![
Scalar::Float64(0.0),
Scalar::Float64(1.0),
Scalar::Float64(3.0),
Scalar::Float64(-1.0),
])
.unwrap();
let result = col.exp2().unwrap();
assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
assert!((result.values()[1].to_f64().unwrap() - 2.0).abs() < 1e-10);
assert!((result.values()[2].to_f64().unwrap() - 8.0).abs() < 1e-10);
assert!((result.values()[3].to_f64().unwrap() - 0.5).abs() < 1e-10);
}
#[test]
fn sinc_computes_sinc_function() {
let col = Column::from_values(vec![
Scalar::Float64(0.0),
Scalar::Float64(1.0),
Scalar::Float64(0.5),
])
.unwrap();
let result = col.sinc().unwrap();
// sinc(0) = 1
assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
// sinc(1) = sin(pi)/pi = 0
assert!(result.values()[1].to_f64().unwrap().abs() < 1e-10);
// sinc(0.5) = sin(pi/2)/(pi/2) = 2/pi ≈ 0.6366
let expected = 2.0 / std::f64::consts::PI;
assert!((result.values()[2].to_f64().unwrap() - expected).abs() < 1e-10);
}
#[test]
fn logaddexp_computes_stable_log_sum() {
let x = Column::from_values(vec![
Scalar::Float64(0.0),
Scalar::Float64(1.0),
Scalar::Float64(-1000.0),
])
.unwrap();
let y = Column::from_values(vec![
Scalar::Float64(0.0),
Scalar::Float64(2.0),
Scalar::Float64(-1000.0),
])
.unwrap();
let result = x.logaddexp(&y).unwrap();
// log(exp(0) + exp(0)) = log(2) ≈ 0.693
assert!((result.values()[0].to_f64().unwrap() - std::f64::consts::LN_2).abs() < 1e-10);
// log(exp(1) + exp(2)) ≈ 2.313
let expected1 = (1.0_f64.exp() + 2.0_f64.exp()).ln();
assert!((result.values()[1].to_f64().unwrap() - expected1).abs() < 1e-10);
// log(exp(-1000) + exp(-1000)) = -1000 + log(2)
let expected2 = -1000.0 + std::f64::consts::LN_2;
assert!((result.values()[2].to_f64().unwrap() - expected2).abs() < 1e-8);
}
#[test]
fn logaddexp2_computes_stable_log2_sum() {
let x = Column::from_values(vec![Scalar::Float64(0.0), Scalar::Float64(1.0)]).unwrap();
let y = Column::from_values(vec![Scalar::Float64(0.0), Scalar::Float64(1.0)]).unwrap();
let result = x.logaddexp2(&y).unwrap();
// log2(2^0 + 2^0) = log2(2) = 1
assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
// log2(2^1 + 2^1) = log2(4) = 2
assert!((result.values()[1].to_f64().unwrap() - 2.0).abs() < 1e-10);
}
#[test]
fn roll_shifts_elements_circularly() {
let col = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
Scalar::Int64(5),
])
.unwrap();
// Roll right by 2: [4, 5, 1, 2, 3]
let r1 = col.roll(2).unwrap();
assert_eq!(r1.values()[0].to_i64().unwrap(), 4);
assert_eq!(r1.values()[1].to_i64().unwrap(), 5);
assert_eq!(r1.values()[2].to_i64().unwrap(), 1);
// Roll left by 2: [3, 4, 5, 1, 2]
let r2 = col.roll(-2).unwrap();
assert_eq!(r2.values()[0].to_i64().unwrap(), 3);
assert_eq!(r2.values()[1].to_i64().unwrap(), 4);
assert_eq!(r2.values()[2].to_i64().unwrap(), 5);
// Roll by 0 or length is no-op
let r3 = col.roll(0).unwrap();
assert_eq!(r3.values()[0].to_i64().unwrap(), 1);
let r4 = col.roll(5).unwrap();
assert_eq!(r4.values()[0].to_i64().unwrap(), 1);
}
#[test]
fn trim_zeros_removes_leading_trailing() {
let col = Column::from_values(vec![
Scalar::Int64(0),
Scalar::Int64(0),
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(0),
])
.unwrap();
// Trim both
let r1 = col.trim_zeros("fb").unwrap();
assert_eq!(r1.len(), 2);
assert_eq!(r1.values()[0].to_i64().unwrap(), 1);
assert_eq!(r1.values()[1].to_i64().unwrap(), 2);
// Trim front only
let r2 = col.trim_zeros("f").unwrap();
assert_eq!(r2.len(), 3);
assert_eq!(r2.values()[0].to_i64().unwrap(), 1);
// Trim back only
let r3 = col.trim_zeros("b").unwrap();
assert_eq!(r3.len(), 4);
assert_eq!(r3.values()[3].to_i64().unwrap(), 2);
}
#[test]
fn around_rounds_to_decimals() {
let col = Column::from_values(vec![
Scalar::Float64(1.234),
Scalar::Float64(5.678),
Scalar::Float64(3.5),
])
.unwrap();
// Round to 2 decimals
let r1 = col.around(2).unwrap();
assert!((r1.values()[0].to_f64().unwrap() - 1.23).abs() < 1e-10);
assert!((r1.values()[1].to_f64().unwrap() - 5.68).abs() < 1e-10);
assert!((r1.values()[2].to_f64().unwrap() - 3.5).abs() < 1e-10);
// Round to 0 decimals
let r2 = col.around(0).unwrap();
assert!((r2.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
assert!((r2.values()[1].to_f64().unwrap() - 6.0).abs() < 1e-10);
// Round to -1 (tens) - np.around uses round-half-to-even (banker's)
let col2 = Column::from_values(vec![
Scalar::Float64(15.0),
Scalar::Float64(24.0),
Scalar::Float64(35.0),
])
.unwrap();
let r3 = col2.around(-1).unwrap();
assert!((r3.values()[0].to_f64().unwrap() - 20.0).abs() < 1e-10);
assert!((r3.values()[1].to_f64().unwrap() - 20.0).abs() < 1e-10);
assert!((r3.values()[2].to_f64().unwrap() - 40.0).abs() < 1e-10);
}
#[test]
fn around_uses_numpy_half_even_ties() {
// np.around is round-half-to-EVEN, matching pd.Series.round. The old
// implementation used f64::round (half away from zero), diverging on
// exact .5 ties: np.around([0.5,1.5,2.5,3.5]) == [0,2,2,4].
let col = Column::from_values(vec![
Scalar::Float64(0.5),
Scalar::Float64(1.5),
Scalar::Float64(2.5),
Scalar::Float64(3.5),
Scalar::Float64(-2.5),
])
.unwrap();
let r = col.around(0).unwrap();
let got: Vec<f64> = r.values().iter().map(|v| v.to_f64().unwrap()).collect();
assert_eq!(got, vec![0.0, 2.0, 2.0, 4.0, -2.0]);
// Negative decimals: np.around([15,25,35], -1) == [20,20,40] (25->20).
let tens = Column::from_values(vec![
Scalar::Float64(15.0),
Scalar::Float64(25.0),
Scalar::Float64(35.0),
])
.unwrap();
let rt = tens.around(-1).unwrap();
let gott: Vec<f64> = rt.values().iter().map(|v| v.to_f64().unwrap()).collect();
assert_eq!(gott, vec![20.0, 20.0, 40.0]);
// around must agree with round (both banker's).
assert_eq!(
col.around(0).unwrap().values(),
col.round(0).unwrap().values()
);
}
#[test]
fn unwrap_removes_phase_discontinuities() {
use std::f64::consts::PI;
let col = Column::from_values(vec![
Scalar::Float64(0.0),
Scalar::Float64(PI * 0.9),
Scalar::Float64(-PI * 0.9), // jump > PI
Scalar::Float64(0.0),
])
.unwrap();
let result = col.unwrap(None).unwrap();
// After unwrap, the sequence should be continuous
assert!((result.values()[0].to_f64().unwrap() - 0.0).abs() < 1e-10);
// Second value unchanged
assert!((result.values()[1].to_f64().unwrap() - PI * 0.9).abs() < 1e-10);
// Third value should be unwrapped (added 2*PI)
let v2 = result.values()[2].to_f64().unwrap();
let v1 = result.values()[1].to_f64().unwrap();
assert!((v2 - v1).abs() < PI); // difference should now be < PI
}
}
// ── Nullable Int64/Bool column tests (br-frankenpandas-rg8ys.6.4) ────
#[test]
fn column_has_nulls_detects_missing_values() {
let col_with_null = Column::from_values(vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
])
.unwrap();
assert!(col_with_null.has_nulls());
let col_no_null =
Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.unwrap();
assert!(!col_no_null.has_nulls());
}
#[test]
fn column_promote_to_nullable_upgrades_dtype() {
let col = Column::new(
DType::Int64,
vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
],
)
.unwrap();
assert_eq!(col.dtype(), DType::Int64);
assert!(col.has_nulls());
let promoted = col.promote_to_nullable();
assert_eq!(promoted.dtype(), DType::Int64Nullable);
assert_eq!(promoted.len(), 3);
}
#[test]
fn column_promote_to_nullable_noop_without_nulls() {
let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
.unwrap();
let promoted = col.promote_to_nullable();
// No nulls, so dtype stays Int64
assert_eq!(promoted.dtype(), DType::Int64);
}
#[test]
fn column_with_dtype_changes_metadata() {
let col = Column::new(DType::Int64, vec![Scalar::Int64(42)]).unwrap();
let changed = col.with_dtype(DType::Int64Nullable);
assert_eq!(changed.dtype(), DType::Int64Nullable);
assert_eq!(changed.values()[0], Scalar::Int64(42));
}
#[test]
fn nullable_int64_from_scalars_preserves_storage() {
use super::ColumnData;
let values = vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)];
let data = ColumnData::from_scalars(&values, DType::Int64Nullable);
assert!(matches!(&data, ColumnData::Int64(_)));
if let ColumnData::Int64(arr) = data {
assert_eq!(arr.as_ref(), [1, 2, 3]);
}
}
#[test]
fn scalar_int64_cache_arc_provenance_is_shared() {
let col = Column::new(
DType::Int64,
vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
)
.unwrap();
assert!(matches!(&col.data, Some(ColumnData::Int64(_))));
let Some(ColumnData::Int64(cached)) = &col.data else {
return;
};
let source = col.as_i64_arc().expect("all-valid Int64 source");
assert!(Arc::ptr_eq(cached, &source));
let cloned = col.clone();
assert!(matches!(
&cloned.values,
ScalarValues::LazyAllValidInt64 { .. }
));
let ScalarValues::LazyAllValidInt64 { data, .. } = &cloned.values else {
return;
};
assert!(Arc::ptr_eq(cached, data));
}
#[test]
fn int64_dense_cycle_witness_is_exact_and_cached_uza0466() {
let col = Column::new(
DType::Int64,
vec![
Scalar::Int64(5),
Scalar::Int64(6),
Scalar::Int64(7),
Scalar::Int64(5),
Scalar::Int64(6),
Scalar::Int64(7),
Scalar::Int64(5),
],
)
.unwrap();
let witness = col
.int64_dense_cycle_witness()
.expect("dense cycle should certify");
assert_eq!(witness.start, 5);
assert_eq!(witness.period, 3);
assert_eq!(witness.len, 7);
assert_eq!(witness.offset_count_for_key(5), Some((0, 3)));
assert_eq!(witness.offset_count_for_key(6), Some((1, 2)));
assert_eq!(witness.offset_count_for_key(7), Some((2, 2)));
assert_eq!(witness.offset_count_for_key(8), None);
let again = col
.int64_dense_cycle_witness()
.expect("cached dense cycle should be reusable");
assert_eq!(again, witness);
}
#[test]
fn bool_affine_selection_witness_is_exact_and_cached_uza0478() {
let scalar_built = Column::new(
DType::Bool,
vec![
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
Scalar::Bool(false),
Scalar::Bool(true),
],
)
.unwrap();
assert!(matches!(
&scalar_built.values,
ScalarValues::LazyAllValidBool { .. }
));
assert_eq!(
scalar_built.bool_affine_selection_witness(),
Some(BoolAffineSelectionWitness {
start: 0,
step: 2,
len: 3,
})
);
assert_eq!(
scalar_built.bool_affine_selection_witness(),
Some(BoolAffineSelectionWitness {
start: 0,
step: 2,
len: 3,
})
);
let typed_built = Column::from_bool_values(vec![false, true, false, true, false]);
assert_eq!(
typed_built.bool_affine_selection_witness(),
Some(BoolAffineSelectionWitness {
start: 1,
step: 2,
len: 2,
})
);
let non_affine = Column::from_bool_values(vec![true, false, false, true, true]);
assert_eq!(non_affine.bool_affine_selection_witness(), None);
let nullable = Column::from_values(vec![
Scalar::Bool(true),
Scalar::Null(NullKind::Null),
Scalar::Bool(true),
])
.unwrap();
assert_eq!(nullable.bool_affine_selection_witness(), None);
}
#[test]
fn int64_dense_cycle_witness_rejects_gaps_and_nulls_uza0466() {
let gapped = Column::new(
DType::Int64,
vec![
Scalar::Int64(5),
Scalar::Int64(6),
Scalar::Int64(8),
Scalar::Int64(5),
],
)
.unwrap();
assert_eq!(gapped.int64_dense_cycle_witness(), None);
let nullable = Column::new(
DType::Int64,
vec![
Scalar::Int64(5),
Scalar::Null(NullKind::Null),
Scalar::Int64(7),
],
)
.unwrap();
assert_eq!(nullable.int64_dense_cycle_witness(), None);
}
#[test]
fn typed_all_valid_constructors_keep_single_typed_backing() {
let ints = Column::from_i64_values_owned(vec![1, 2, 3]);
assert_eq!(ints.dtype(), DType::Int64);
assert!(ints.validity.all());
assert!(ints.data.is_none());
assert_eq!(ints.as_i64_slice(), Some([1, 2, 3].as_slice()));
assert_eq!(
ints.values(),
&[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
);
let floats = Column::from_f64_values(vec![1.5, -0.0, f64::INFINITY]);
assert_eq!(floats.dtype(), DType::Float64);
assert!(floats.validity.all());
assert!(floats.data.is_none());
assert_eq!(
floats.as_f64_slice().map(|values| {
values
.iter()
.map(|value| value.to_bits())
.collect::<Vec<_>>()
}),
Some(vec![
1.5f64.to_bits(),
(-0.0f64).to_bits(),
f64::INFINITY.to_bits()
])
);
assert_eq!(
floats.values(),
&[
Scalar::Float64(1.5),
Scalar::Float64(-0.0),
Scalar::Float64(f64::INFINITY)
]
);
}
#[test]
fn from_values_float64_fast_path_preserves_surface() {
let nan = f64::from_bits(0x7ff8_0000_0000_1234);
let column = Column::from_values(vec![
Scalar::Float64(1.5),
Scalar::Float64(-0.0),
Scalar::Float64(f64::INFINITY),
Scalar::Float64(nan),
])
.expect("homogeneous float64 column");
assert_eq!(column.dtype(), DType::Float64);
assert!(column.data.is_none());
assert!(column.validity.get(0));
assert!(column.validity.get(1));
assert!(column.validity.get(2));
assert!(!column.validity.get(3));
let bits = column
.values()
.iter()
.map(|value| match value {
Scalar::Float64(value) => Some(value.to_bits()),
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(
bits,
vec![
Some(1.5f64.to_bits()),
Some((-0.0f64).to_bits()),
Some(f64::INFINITY.to_bits()),
Some(nan.to_bits()),
]
);
let mixed = Column::from_values(vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
])
.expect("mixed float/null fallback");
assert_eq!(mixed.dtype(), DType::Float64);
assert_eq!(
mixed.values(),
&[
Scalar::Float64(1.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
]
);
let empty = Column::from_values(Vec::new()).expect("empty fallback");
assert_eq!(empty.dtype(), DType::Null);
assert!(empty.values().is_empty());
}
#[test]
fn repeated_slice_int64_column_matches_eager_materialization() {
let lazy = Column::from_i64_repeated_slices(
vec![10, 11, 12, 20, 21],
vec![(0, 3), (3, 2), (0, 3)],
);
let eager = Column::from_i64_values_owned(vec![10, 11, 12, 20, 21, 10, 11, 12]);
assert_eq!(lazy.dtype(), DType::Int64);
assert!(lazy.validity.all());
assert_eq!(lazy.len(), eager.len());
assert_eq!(lazy.as_i64_slice(), eager.as_i64_slice());
assert_eq!(lazy.values(), eager.values());
assert_eq!(lazy, eager);
}
#[test]
fn nullable_repeated_slices_store_sparse_invalid_ranges() {
let segments: Arc<[(usize, usize)]> = Arc::from(vec![(0, 2), (usize::MAX, 3), (2, 1)]);
let column =
Column::from_f64_nullable_repeated_slices_shared(vec![1.0, 2.0, 3.0], segments, 6);
assert_eq!(column.dtype(), DType::Float64);
assert!(column.validity.words.is_empty());
assert_eq!(
column.validity.invalid_ranges.as_deref(),
Some(&[(2, 3)][..])
);
assert_eq!(
column.values(),
&[
Scalar::Float64(1.0),
Scalar::Float64(2.0),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Float64(3.0),
]
);
}
#[test]
fn nullable_repeated_slices_accept_precomputed_sparse_validity() {
let segments: Arc<[(usize, usize)]> =
Arc::from(vec![(0, 1), (usize::MAX, 1), (usize::MAX, 1), (1, 1)]);
let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 2)]), 4);
let column = Column::from_f64_nullable_repeated_slices_shared_with_sparse_validity(
vec![4.0, -2.0],
segments,
validity,
4,
);
assert_eq!(
column.values(),
&[
Scalar::Float64(4.0),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Float64(-2.0),
]
);
assert_eq!(
column.validity.invalid_ranges.as_deref(),
Some(&[(1, 2)][..])
);
}
#[test]
fn nullable_repeat_values_store_sparse_invalid_ranges() {
let run_valid: Arc<[bool]> = Arc::from(vec![true, false, true]);
let run_lens: Arc<[usize]> = Arc::from(vec![2, 3, 1]);
let column = Column::from_f64_nullable_repeat_values_run_lengths(
vec![7.0, 0.0, -9.0],
run_valid,
run_lens,
6,
);
assert_eq!(column.dtype(), DType::Float64);
assert!(column.validity.words.is_empty());
assert_eq!(
column.validity.invalid_ranges.as_deref(),
Some(&[(2, 3)][..])
);
assert_eq!(
column.values(),
&[
Scalar::Float64(7.0),
Scalar::Float64(7.0),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Float64(-9.0),
]
);
}
#[test]
fn nullable_repeat_values_accept_precomputed_sparse_validity() {
let run_valid: Arc<[bool]> = Arc::from(vec![true, false, true]);
let run_lens: Arc<[usize]> = Arc::from(vec![1, 2, 1]);
let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 2)]), 4);
let column = Column::from_f64_nullable_repeat_values_run_lengths_with_sparse_validity(
vec![8.0, 0.0, -4.0],
run_valid,
run_lens,
validity,
4,
);
assert_eq!(
column.values(),
&[
Scalar::Float64(8.0),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Float64(-4.0),
]
);
assert_eq!(
column.validity.invalid_ranges.as_deref(),
Some(&[(1, 2)][..])
);
}
#[test]
fn nullable_repeated_positions_i64_as_f64_matches_tape_materialization_uza0461() {
let source: Arc<[i64]> = Arc::from(vec![10, 20, 30, 40]);
let positions: Arc<[usize]> = Arc::from(vec![2, 0, 3]);
let segments: Arc<[(usize, usize)]> = Arc::from(vec![(0, 2), (usize::MAX, 1), (2, 1)]);
let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(2, 1)]), 4);
let column = Column::from_i64_nullable_repeated_positions_as_f64_with_sparse_validity(
source, positions, segments, validity, 4,
);
assert_eq!(column.dtype(), DType::Float64);
assert_eq!(
column.values(),
&[
Scalar::Float64(30.0),
Scalar::Float64(10.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(40.0),
]
);
assert_eq!(
column.validity.invalid_ranges.as_deref(),
Some(&[(2, 1)][..])
);
}
#[test]
fn nullable_repeat_positions_i64_as_f64_matches_run_values_uza0461() {
let source: Arc<[i64]> = Arc::from(vec![7, -3, 11]);
let run_positions: Arc<[usize]> = Arc::from(vec![0, 0, 2]);
let run_valid: Arc<[bool]> = Arc::from(vec![true, false, true]);
let run_lens: Arc<[usize]> = Arc::from(vec![2, 3, 1]);
let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(2, 3)]), 6);
let column = Column::from_i64_nullable_repeat_positions_as_f64_with_sparse_validity(
source,
run_positions,
run_valid,
run_lens,
validity,
6,
);
assert_eq!(column.dtype(), DType::Float64);
assert_eq!(
column.values(),
&[
Scalar::Float64(7.0),
Scalar::Float64(7.0),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::NaN),
Scalar::Float64(11.0),
]
);
assert_eq!(
column.validity.invalid_ranges.as_deref(),
Some(&[(2, 3)][..])
);
}
#[test]
fn dense_cycle_probe_repeat_int64_preserves_probe_order_yq96z() {
let probe = Column::from_i64_values_owned(vec![0, 1, 2, 0, 1]);
let build = Column::from_i64_values_owned(vec![1, 2, 1, 2]);
let probe_witness = probe
.int64_dense_cycle_witness()
.expect("probe dense cycle");
let build_witness = build
.int64_dense_cycle_witness()
.expect("build dense cycle");
let column = Column::from_i64_dense_cycle_probe_repeat(
Arc::from(vec![10, 11, 12, 13, 14]),
probe_witness,
build_witness,
8,
);
assert_eq!(column.dtype(), DType::Int64);
assert!(column.validity.all());
assert_eq!(
column.as_i64_slice(),
Some([10, 11, 11, 12, 12, 13, 14, 14].as_slice())
);
assert_eq!(
column.values(),
&[
Scalar::Int64(10),
Scalar::Int64(11),
Scalar::Int64(11),
Scalar::Int64(12),
Scalar::Int64(12),
Scalar::Int64(13),
Scalar::Int64(14),
Scalar::Int64(14),
]
);
}
#[test]
fn nullable_dense_cycle_probe_build_int64_preserves_build_ties_yq96z() {
let probe = Column::from_i64_values_owned(vec![0, 1, 2, 0, 1]);
let build = Column::from_i64_values_owned(vec![1, 2, 1, 2]);
let probe_witness = probe
.int64_dense_cycle_witness()
.expect("probe dense cycle");
let build_witness = build
.int64_dense_cycle_witness()
.expect("build dense cycle");
let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(0, 1), (5, 1)]), 8);
let column = Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
Arc::from(vec![100, 200, 101, 201]),
probe_witness,
build_witness,
validity,
8,
);
assert_eq!(column.dtype(), DType::Int64);
assert_eq!(
column.validity.invalid_ranges.as_deref(),
Some(&[(0, 1), (5, 1)][..])
);
assert_eq!(
column.values(),
&[
Scalar::Null(NullKind::Null),
Scalar::Int64(100),
Scalar::Int64(101),
Scalar::Int64(200),
Scalar::Int64(201),
Scalar::Null(NullKind::Null),
Scalar::Int64(100),
Scalar::Int64(101),
]
);
}
}
/// Provenanced A/B for the `LazyAllValidFloat64TransposeRow` arm of
/// [`Column::as_f64_slice`] (cc_fp).
///
/// Isolated at the `Column` level so the transpose frame's `String` + `BTreeMap`
/// construction cannot dominate the signal: each rep rebuilds the transposed row
/// columns from scratch (their `OnceLock`s start cold), then walks them once.
///
/// ORIG = `values()` -> `plan.materialize_row` + `Vec<Scalar>` boxing (32 B/elem).
/// CAND = `as_f64_slice()` -> `plan.materialize_row` only, returning the cached
/// typed `Vec<f64>` (8 B/elem) that `values()` was about to box.
///
/// Both arms alternate INSIDE one measured routine, in ONE `rch exec` invocation,
/// with `black_box` on inputs and results. Emits binary sha256, worker hostname and
/// per-arm cv_pct so the ledger row is provenanced.
///
/// Run: `RCH_REQUIRE_REMOTE=1 env -u CARGO_TARGET_DIR rch exec -- \
/// cargo test -p fp-columnar --release --lib -- --ignored --nocapture ab_transpose_row_typed`
#[cfg(test)]
mod ab_transpose_row_typed_ccfp {
use std::{process::Command, sync::Arc, time::Instant};
use fp_types::Scalar;
use super::{Column, Float64TransposeInput, Float64TransposeRows, Float64TransposeRowsPlan};
fn binary_sha256() -> String {
let exe = std::env::current_exe().expect("current test binary");
let out = Command::new("sha256sum")
.arg(&exe)
.output()
.expect("sha256sum on worker");
String::from_utf8(out.stdout)
.expect("utf8")
.split_whitespace()
.next()
.expect("digest")
.to_owned()
}
fn worker_hostname() -> String {
Command::new("hostname")
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.map_or_else(|| "unknown".to_owned(), |s| s.trim().to_owned())
}
/// `rows` source rows x `cols` source columns; each transposed row column has
/// length `cols`, and there are `rows` of them -- the shape `df.transpose()` emits.
fn plan_for(rows: usize, cols: usize) -> Float64TransposeRows {
let inputs: Vec<Float64TransposeInput> = (0..cols)
.map(|c| {
let data: Arc<[f64]> = (0..rows)
.map(|r| (r * cols + c) as f64)
.collect::<Vec<_>>()
.into();
Float64TransposeInput::new(data, 0, rows)
})
.collect();
Float64TransposeRows {
plan: Arc::new(Float64TransposeRowsPlan::new(inputs.into(), rows)),
}
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).expect("finite"));
let n = v.len();
if n % 2 == 1 {
v[n / 2]
} else {
0.5 * (v[n / 2 - 1] + v[n / 2])
}
}
fn spread_of(xs: &[f64]) -> (f64, f64) {
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
for &x in xs {
lo = lo.min(x);
hi = hi.max(x);
}
(lo, hi)
}
fn cv_of(xs: &[f64]) -> f64 {
let mean = xs.iter().sum::<f64>() / xs.len() as f64;
let var = xs.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / xs.len() as f64;
100.0 * var.sqrt() / mean
}
/// Prices the ONLY pair-shrink lever available inside fp-columnar (cc_fp): the
/// 93.6%-of-construction cost is owning + re-homing n 312-byte `(String, Column)`
/// pairs, and `Column` is 288 B of that. Both of the obvious representation fixes
/// -- borrowed/interned keys, or one columnar block instead of per-row Columns --
/// change `DataFrame` (cod_fp's `fp-frame` lane; the block IS the lazy view).
/// The one shrink that lives HERE is boxing the `Column` out of the pair, taking
/// it 312 B -> 32 B of move-traffic at the cost of ONE heap alloc per row.
///
/// This ablation answers, decidably, whether that trade wins: does moving 32-byte
/// pairs (plus n allocs) beat moving 312-byte pairs? If yes, shrinking `Column`
/// (box its wide `ScalarValues` variants) is worth a conformance-gated attempt;
/// if no, the alloc eats the move and the only real lever is cod_fp's block view.
/// Per-arm ADJACENT A/A null floor; decide on medians vs spread, not cv.
/// Times a heavily-autovectorizable f64 sum (xmm 2-wide under SSE2, ymm 4-wide
/// under AVX2) so the SAME source, built two ways, shows the ISA gap's cost.
/// Prints the compiled-in avx2 flag + sha256 + worker so a baseline-vs-v3 pair
/// pinned to ONE worker is a valid ratio. blocks x reps, min-of-block, spread.
#[test]
#[ignore = "diagnostic; run with --ignored --nocapture"]
fn isa_sum_kernel_ccfp() {
use std::process::Command;
const N: usize = 20_000_000;
const BLOCKS: usize = 11;
const REPS: usize = 5;
let data: Vec<f64> = (0..N).map(|i| (i as f64).mul_add(1.0000001, 0.5)).collect();
let mut ms = Vec::with_capacity(BLOCKS);
let mut nullr = Vec::with_capacity(BLOCKS);
for _ in 0..BLOCKS {
let (mut a, mut b) = (f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let d = std::hint::black_box(&data[..]);
let t0 = std::time::Instant::now();
let s: f64 = d.iter().copied().sum();
std::hint::black_box(s);
a = a.min(t0.elapsed().as_secs_f64() * 1e3);
let d = std::hint::black_box(&data[..]);
let t0 = std::time::Instant::now();
let s: f64 = d.iter().copied().sum();
std::hint::black_box(s);
b = b.min(t0.elapsed().as_secs_f64() * 1e3);
}
ms.push(a.min(b));
nullr.push(a / b);
}
let med = median_of(&ms);
let (lo, hi) = spread_of(&nullr);
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().expect("exe"))
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.map_or_else(|| "?".to_owned(), |s| s.trim().to_owned());
println!("=== ISA SUM KERNEL ===");
println!(
" compiled avx2 = {} fma = {}",
cfg!(target_feature = "avx2"),
cfg!(target_feature = "fma")
);
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" N={N} sum(f64) median={med:.4} ms cv={:.2}% A/A null spread=[{lo:.4}x,{hi:.4}x]",
cv_of(&ms)
);
println!(" throughput = {:.2} Gelem/s", N as f64 / (med / 1e3) / 1e9);
}
/// Same-binary, worker-invariant measurement of the Column-shrink benefit (cc_fp).
/// The cross-binary pair-shrink ratio is worker-confounded (memory bandwidth
/// differs per worker), so instead compare moving a struct of the CURRENT Column
/// size vs the PRE-SHRINK size (288 B) through the exact `Vec` push + `BTreeMap`
/// collect the transpose finalize uses, BOTH arms in ONE binary on ONE worker.
/// Isolates the size effect. Per-arm ADJACENT A/A null floor; gate on median.
#[test]
#[ignore = "perf ablation; run with --ignored --nocapture"]
fn ab_column_size_move_ccfp() {
use std::collections::BTreeMap;
const N: usize = 200_000;
const BLOCKS: usize = 11;
const REPS: usize = 5;
// Current Column size vs the pre-boxing size (288 B), as opaque blocks so the
// move cost is purely the byte count the BTreeMap re-homes.
const CUR: usize = std::mem::size_of::<Column>();
#[derive(Clone)]
struct Blk<const B: usize>([u8; B]);
let keys: Vec<String> = {
let mut v: Vec<usize> = (0..N).collect();
v.sort_by_key(|r| r.to_string());
v.into_iter().map(|r| r.to_string()).collect()
};
// arm parameterized by block size; returns elapsed ms
macro_rules! run {
($B:expr) => {{
let mut v: Vec<(String, Blk<$B>)> = Vec::with_capacity(N);
for k in &keys {
v.push((k.clone(), Blk::<$B>([0u8; $B])));
}
let m: BTreeMap<String, Blk<$B>> = v.into_iter().collect();
std::hint::black_box(&m);
}};
}
// Compile-time guard: the OLD(288) arm must stay >= the current Column.
const _: () = assert!(CUR <= 288, "Column grew past the pre-shrink 288 B size");
for _ in 0..2 {
run!(232);
run!(288);
}
let (mut cur, mut old, mut ncur) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bc, mut bo) = (f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
// adjacent A/A for CUR(232): two back-to-back timings -> ratio = floor
let t0 = Instant::now();
run!(232);
let a = t0.elapsed().as_secs_f64() * 1e3;
let t0 = Instant::now();
run!(232);
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
ncur.push(a / b);
// OLD(288)
let t0 = Instant::now();
run!(288);
let c = t0.elapsed().as_secs_f64() * 1e3;
let t0 = Instant::now();
run!(288);
let d = t0.elapsed().as_secs_f64() * 1e3;
bo = bo.min(c.min(d));
}
cur.push(bc);
old.push(bo);
}
let (c, o) = (min_of(&cur), min_of(&old));
let (nlo, nhi) = spread_of(&ncur);
let floor = 100.0 * (nhi - 1.0).abs().max((nlo - 1.0).abs());
println!("AB Column-size move (ONE binary, ONE invocation, blocks x reps)");
println!(" binary_sha256 = {}", {
use std::process::Command;
Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default()
});
println!(" worker={} CUR sizeof Column={CUR} B", {
use std::process::Command;
Command::new("hostname")
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned())
});
println!(" CUR(232 B) median={c:.3} ms cv={:.2}%", cv_of(&cur));
println!(" OLD(288 B) median={o:.3} ms cv={:.2}%", cv_of(&old));
println!(" A/A null floor (CUR arm) median-spread=[{nlo:.4},{nhi:.4}] |dev|={floor:.2}%");
println!(
" shrink effect (OLD/CUR) = {:.4}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0).abs() > floor
);
}
/// Size breakdown of the widest ScalarValues variant (cc_fp): finds the single
/// biggest field so a surgical box of ONE cold cache can shrink the 288-byte
/// Column without the whole 47-variant epic.
#[test]
#[ignore = "diagnostic; run with --ignored --nocapture"]
fn scalarvalues_size_breakdown_ccfp() {
use std::sync::OnceLock;
macro_rules! sz {
($t:ty) => {
println!(" {:>4} B {}", std::mem::size_of::<$t>(), stringify!($t));
};
}
println!("=== ScalarValues size breakdown ===");
sz!(super::ScalarValues);
sz!(Column);
println!("--- LazyContiguousUtf8 fields (the widest variant) ---");
sz!(std::sync::Arc<[u8]>);
sz!(OnceLock<bool>);
sz!(OnceLock<Option<usize>>);
sz!(OnceLock<Option<super::Utf8LowerHexSequence>>);
sz!(super::Utf8FactorizeDefaultWitness);
sz!(OnceLock<super::Utf8FactorizeDefaultWitness>);
sz!(OnceLock<Box<super::Utf8FactorizeDefaultWitness>>);
sz!(OnceLock<Vec<fp_types::Scalar>>);
println!("--- sum if factorize_default were boxed ---");
let cur = std::mem::size_of::<OnceLock<super::Utf8FactorizeDefaultWitness>>();
let boxed = std::mem::size_of::<OnceLock<Box<super::Utf8FactorizeDefaultWitness>>>();
println!(
" factorize_default field: {cur} B -> {boxed} B (saves {} B)",
cur - boxed
);
use fp_types::Scalar as Sc;
println!("--- widest-variant field tuples (find the current enum max) ---");
macro_rules! vt {
($n:literal, $t:ty) => {
println!(" {:>4} B {}", std::mem::size_of::<$t>(), $n);
};
}
vt!(
"LazyContiguousUtf8",
(
std::sync::Arc<[u8]>,
std::sync::Arc<[usize]>,
OnceLock<bool>,
OnceLock<Option<usize>>,
OnceLock<Option<Box<super::Utf8LowerHexSequence>>>,
OnceLock<Box<super::Utf8FactorizeDefaultWitness>>,
OnceLock<Vec<Sc>>,
)
);
vt!(
"LazyShiftedBool",
(
std::sync::Arc<[bool]>,
i64,
bool,
usize,
OnceLock<Vec<bool>>,
OnceLock<Option<super::BoolAffineSelectionWitness>>,
OnceLock<Vec<Sc>>,
)
);
vt!(
"LazyAllValidInt64Chunks",
(
std::sync::Arc<[u8]>,
usize,
OnceLock<Vec<i64>>,
OnceLock<Option<super::Int64DenseCycleWitness>>,
OnceLock<Vec<Sc>>,
)
);
vt!(
"OL<Option<BoolAffineSelectionWitness>>",
OnceLock<Option<super::BoolAffineSelectionWitness>>
);
vt!(
"OL<Option<Box<BoolAffineSelectionWitness>>>",
OnceLock<Option<Box<super::BoolAffineSelectionWitness>>>
);
vt!(
"OL<Option<Int64DenseCycleWitness>>",
OnceLock<Option<super::Int64DenseCycleWitness>>
);
// The join dense-cycle lanes carry TWO INLINE 24 B witnesses (not OnceLock
// caches -- always-present join data), so they tie the enum max at ~144 B.
// This is the plateau: shrinking one variant is a no-op while these remain.
vt!(
"LazyLeftJoinDenseCycleLeftInt64",
(
std::sync::Arc<[i64]>,
super::Int64DenseCycleWitness,
super::Int64DenseCycleWitness,
usize,
OnceLock<Vec<i64>>,
OnceLock<Vec<Sc>>,
)
);
}
/// ISA-baseline probe (cc_fp): prints what the CURRENT BINARY was COMPILED for
/// (`cfg!(target_feature=...)`) vs what the RUNTIME worker CPU actually supports
/// (`is_x86_feature_detected!`). A gap (compiled SSE2, worker AVX2) means a whole
/// class of hot loops is leaving 256-bit width on the table. Both macros are safe.
#[test]
#[ignore = "diagnostic; run with --ignored --nocapture"]
fn isa_baseline_probe_ccfp() {
macro_rules! ct {
($f:literal) => {
(cfg!(target_feature = $f), $f)
};
}
let compiled = [
ct!("sse2"),
ct!("sse4.1"),
ct!("avx"),
ct!("avx2"),
ct!("fma"),
ct!("avx512f"),
];
println!("=== ISA BASELINE PROBE ===");
println!("arch = {}", std::env::consts::ARCH);
println!("--- COMPILED (this binary's target-feature) ---");
for (on, name) in compiled {
println!(" {name:8} compiled_in={on}");
}
#[cfg(target_arch = "x86_64")]
{
println!("--- RUNTIME (worker CPU) ---");
for name in ["sse2", "sse4.1", "avx", "avx2", "fma", "avx512f"] {
let has = match name {
"sse2" => is_x86_feature_detected!("sse2"),
"sse4.1" => is_x86_feature_detected!("sse4.1"),
"avx" => is_x86_feature_detected!("avx"),
"avx2" => is_x86_feature_detected!("avx2"),
"fma" => is_x86_feature_detected!("fma"),
"avx512f" => is_x86_feature_detected!("avx512f"),
_ => false,
};
println!(" {name:8} runtime_has={has}");
}
let gap = !cfg!(target_feature = "avx2") && is_x86_feature_detected!("avx2");
println!("--- VERDICT ---");
println!(" AVX2 ISA GAP (compiled SSE2 baseline, worker has AVX2) = {gap}");
}
}
#[test]
#[ignore = "perf ablation; run with --ignored --nocapture"]
fn ab_transpose_pair_shrink_ceiling() {
use std::collections::BTreeMap;
const ROWS: usize = 200_000;
const COLS: usize = 10;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let handle = plan_for(ROWS, COLS);
let mut order: Vec<usize> = (0..ROWS).collect();
order.sort_by_key(|r| r.to_string());
let order = order;
// REAL: Vec<(String, Column)> -> BTreeMap<String, Column> (312-byte pair)
let arm_real = |ord: &[usize], h: &Float64TransposeRows| {
let mut v: Vec<(String, Column)> = Vec::with_capacity(ord.len());
for &r in ord {
v.push((r.to_string(), Column::from_f64_transpose_row(h, r)));
}
let m: BTreeMap<String, Column> = v.into_iter().collect();
std::hint::black_box(m);
};
// BOXED: Vec<(String, Box<Column>)> -> BTreeMap<String, Box<Column>> (32-byte
// pair + one heap alloc per row). Proxy for a 32-B-Column representation.
let arm_boxed = |ord: &[usize], h: &Float64TransposeRows| {
let mut v: Vec<(String, Box<Column>)> = Vec::with_capacity(ord.len());
for &r in ord {
v.push((
r.to_string(),
Box::new(Column::from_f64_transpose_row(h, r)),
));
}
let m: BTreeMap<String, Box<Column>> = v.into_iter().collect();
std::hint::black_box(m);
};
for _ in 0..2 {
let (o, h) = (std::hint::black_box(&order), std::hint::black_box(&handle));
arm_real(o, h);
arm_boxed(o, h);
}
let mut real = Vec::with_capacity(BLOCKS);
let mut boxed = Vec::with_capacity(BLOCKS);
let mut null_real = Vec::with_capacity(BLOCKS);
let mut null_boxed = Vec::with_capacity(BLOCKS);
for _ in 0..BLOCKS {
let (mut br, mut bb) = (f64::INFINITY, f64::INFINITY);
let (mut ra, mut rb, mut ba, mut bb2) =
(f64::INFINITY, f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let (o, h) = (std::hint::black_box(&order), std::hint::black_box(&handle));
// adjacent A/A for REAL
let t0 = Instant::now();
arm_real(o, h);
let a = t0.elapsed().as_secs_f64() * 1e3;
let t0 = Instant::now();
arm_real(o, h);
let b = t0.elapsed().as_secs_f64() * 1e3;
ra = ra.min(a);
rb = rb.min(b);
br = br.min(a.min(b));
// adjacent A/A for BOXED
let t0 = Instant::now();
arm_boxed(o, h);
let a = t0.elapsed().as_secs_f64() * 1e3;
let t0 = Instant::now();
arm_boxed(o, h);
let b = t0.elapsed().as_secs_f64() * 1e3;
ba = ba.min(a);
bb2 = bb2.min(b);
bb = bb.min(a.min(b));
}
real.push(br);
boxed.push(bb);
null_real.push(ra / rb);
null_boxed.push(ba / bb2);
}
let (rm, bm) = (median_of(&real), median_of(&boxed));
let (nr, nb) = (median_of(&null_real), median_of(&null_boxed));
let (rlo, rhi) = spread_of(&null_real);
let (blo, bhi) = spread_of(&null_boxed);
let floor_real = 100.0 * (rhi - 1.0).abs().max((rlo - 1.0).abs());
let floor_boxed = 100.0 * (bhi - 1.0).abs().max((blo - 1.0).abs());
let effect = 100.0 * (rm / bm - 1.0);
println!("AB transpose pair-shrink ceiling (ONE binary, ONE invocation)");
println!(" binary_sha256 = {}", binary_sha256());
println!(" worker = {}", worker_hostname());
println!(
" size_of (String,Column)={} (String,Box<Column>)={}",
std::mem::size_of::<(String, Column)>(),
std::mem::size_of::<(String, Box<Column>)>()
);
println!(
" REAL (String,Column) median={rm:9.3} ms cv={:5.2}% A/A null median={nr:.4}x floor={floor_real:.2}%",
cv_of(&real)
);
println!(
" BOXED (String,Box<Column>) median={bm:9.3} ms cv={:5.2}% A/A null median={nb:.4}x floor={floor_boxed:.2}%",
cv_of(&boxed)
);
println!(" effect (real/boxed) = {:.4}x ({effect:+.1}%)", rm / bm);
let decidable = effect.abs() > floor_real.max(floor_boxed);
println!(
" DECIDABLE: |effect|={:.1}% vs max floor={:.1}% -> {}",
effect.abs(),
floor_real.max(floor_boxed),
decidable
);
}
/// Decomposes the 95.9% of transpose CONSTRUCTION that does NOT live in the
/// per-column ctor (cc_fp). `DataFrame::transpose` finalizes by, per source row:
/// formatting a decimal `String` label, constructing a `Column`, pushing the pair
/// into a `Vec<(String, Column)>` in lexical key order, then `collect()`ing that
/// into `BTreeMap<String, Column>`. Only `Column` is fp-columnar; `String`, `Vec`
/// and `BTreeMap` are std, so the whole shape is reproducible HERE, without
/// touching `crates/fp-frame` (cod_fp's live file).
///
/// Cumulative arms, so each delta attributes one component:
/// L = label `String` only
/// LC = label + `Column::from_f64_transpose_row`
/// LCV = label + ctor + push into `Vec<(String, Column)>`
/// MAP = LCV + `BTreeMap::from_iter` (the sort + bulk build)
/// NULL = MAP again, identical arm -> the A/A floor, measured FIRST in each rep.
///
/// Keys are pre-sorted into lexical order outside the timer, matching
/// `push_lexical_transpose_row_entry`. Drops happen outside the timer, matching how
/// `ab_transpose_materialize`'s construction arm was measured.
#[test]
#[ignore = "perf ablation; run with --ignored --nocapture"]
fn ab_transpose_construction_decomposition() {
use std::collections::BTreeMap;
const ROWS: usize = 200_000;
const COLS: usize = 10;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let handle = plan_for(ROWS, COLS);
// Lexical key order, exactly as push_lexical_transpose_row_entry emits.
let mut order: Vec<usize> = (0..ROWS).collect();
order.sort_by_key(|r| r.to_string());
let order = order;
let arm_l = |ord: &[usize]| {
let mut n = 0usize;
for &r in ord {
n += std::hint::black_box(r.to_string()).len();
}
n
};
let arm_lc = |ord: &[usize], h: &Float64TransposeRows| {
let mut n = 0usize;
for &r in ord {
let k = std::hint::black_box(r.to_string());
let c = Column::from_f64_transpose_row(h, r);
n += k.len() + std::hint::black_box(&c).len();
}
n
};
let arm_lcv = |ord: &[usize], h: &Float64TransposeRows| {
let mut v: Vec<(String, Column)> = Vec::with_capacity(ord.len());
for &r in ord {
v.push((r.to_string(), Column::from_f64_transpose_row(h, r)));
}
std::hint::black_box(v)
};
let arm_map = |ord: &[usize], h: &Float64TransposeRows| {
let mut v: Vec<(String, Column)> = Vec::with_capacity(ord.len());
for &r in ord {
v.push((r.to_string(), Column::from_f64_transpose_row(h, r)));
}
let m: BTreeMap<String, Column> = v.into_iter().collect();
std::hint::black_box(m)
};
for _ in 0..2 {
let (o, h) = (std::hint::black_box(&order), std::hint::black_box(&handle));
std::hint::black_box(arm_l(o));
std::hint::black_box(arm_lc(o, h));
drop(arm_lcv(o, h));
drop(arm_map(o, h));
}
// PER-ARM A/A NULL CONTROL. The null floor is per-FUNCTION, not global
// (frankenlibc), so every arm is run twice per block and its own a/b ratio
// calibrates its own floor. Decisions are made on MEDIANS against the null's
// observed SPREAD, not on a cv threshold (frankenmermaid harness calibration).
// cv is still reported, as information.
let mut t: [Vec<f64>; 4] = [
Vec::with_capacity(BLOCKS),
Vec::with_capacity(BLOCKS),
Vec::with_capacity(BLOCKS),
Vec::with_capacity(BLOCKS),
];
let mut nullr: [Vec<f64>; 4] = [
Vec::with_capacity(BLOCKS),
Vec::with_capacity(BLOCKS),
Vec::with_capacity(BLOCKS),
Vec::with_capacity(BLOCKS),
];
for _ in 0..BLOCKS {
let mut best = [f64::INFINITY; 4];
let mut a_of = [f64::INFINITY; 4];
let mut b_of = [f64::INFINITY; 4];
for _ in 0..REPS {
let (o, h) = (std::hint::black_box(&order), std::hint::black_box(&handle));
// A/A pairs must be ADJACENT: the previous layout separated each
// arm's a and b by ~50 ms of the other arms, so inter-arm drift, not
// the function, set the floor (L read |dev| 61%). Run each arm's two
// passes back-to-back, then move to the next arm.
macro_rules! pair {
($idx:expr, $run:expr) => {{
let t0 = Instant::now();
$run;
let a = t0.elapsed().as_secs_f64() * 1e3;
let t0 = Instant::now();
$run;
let b = t0.elapsed().as_secs_f64() * 1e3;
a_of[$idx] = a_of[$idx].min(a);
b_of[$idx] = b_of[$idx].min(b);
best[$idx] = best[$idx].min(a.min(b));
}};
}
pair!(0, std::hint::black_box(arm_l(o)));
pair!(1, std::hint::black_box(arm_lc(o, h)));
pair!(2, drop(arm_lcv(o, h)));
pair!(3, drop(arm_map(o, h)));
}
for i in 0..4 {
t[i].push(best[i]);
nullr[i].push(a_of[i] / b_of[i]);
}
}
let names = [
"L label String",
"LC +Column ctor",
"LCV +Vec push",
"MAP full finalize",
];
println!("AB transpose construction decomposition (ONE binary, ONE invocation)");
println!(" binary_sha256 = {}", binary_sha256());
println!(" worker = {}", worker_hostname());
println!(" rows={ROWS} cols={COLS} (lexical key order, drops outside timer)");
println!(
" size_of: Column={} ScalarValues={} (String,Column)={} -> Vec bytes={:.1} MB",
std::mem::size_of::<Column>(),
std::mem::size_of::<super::ScalarValues>(),
std::mem::size_of::<(String, Column)>(),
(ROWS * std::mem::size_of::<(String, Column)>()) as f64 / 1e6
);
println!(" --- per-arm A/A NULL FLOOR (median and observed spread of a/b) ---");
for i in 0..4 {
let (lo, hi) = spread_of(&nullr[i]);
println!(
" {:20} null median={:.4}x spread=[{:.4}x, {:.4}x] |dev|max={:.2}% arm median={:8.3} ms cv={:5.2}%",
names[i],
median_of(&nullr[i]),
lo,
hi,
100.0 * (hi - 1.0).abs().max((lo - 1.0).abs()),
median_of(&t[i]),
cv_of(&t[i])
);
}
let (l, c, v, m) = (
median_of(&t[0]),
median_of(&t[1]),
median_of(&t[2]),
median_of(&t[3]),
);
let per = |ms: f64| 1e6 * ms / ROWS as f64;
println!(" --- attributed components (medians, per source row) ---");
println!(
" label String = {:8.3} ms ({:6.2} ns/row, {:5.1}% of MAP)",
l,
per(l),
100.0 * l / m
);
println!(
" Column ctor = {:8.3} ms ({:6.2} ns/row, {:5.1}% of MAP)",
c - l,
per(c - l),
100.0 * (c - l) / m
);
println!(
" Vec<(S,C)> push = {:8.3} ms ({:6.2} ns/row, {:5.1}% of MAP)",
v - c,
per(v - c),
100.0 * (v - c) / m
);
println!(
" BTreeMap collect = {:8.3} ms ({:6.2} ns/row, {:5.1}% of MAP)",
m - v,
per(m - v),
100.0 * (m - v) / m
);
println!(
" DECIDABILITY: each component's share must exceed its arm's max null deviation above."
);
}
/// Localizes the transpose CONSTRUCTION wall (cc_fp). `df.transpose()` construction
/// = per-column `Column::from_f64_transpose_row` (fp-columnar) + the `String` label,
/// the `(String, Column)` stable sort, and the `BTreeMap` bulk build (fp-frame).
/// This prices ONLY the fp-columnar half, so the remainder is attributable to
/// fp-frame. Null control included: the identical arm registered twice.
#[test]
#[ignore = "perf ablation; run with --ignored --nocapture"]
fn ab_transpose_row_ctor_share() {
// First run gave cv 6.06%/9.05% on a 2.87 ms arm -- above the gate, so the
// arm was lengthened rather than the number harvested. Null control was
// already tight (0.9979x), so the harness was sound; only the arm was short.
const ROWS: usize = 500_000;
const COLS: usize = 10;
const BLOCKS: usize = 11;
const REPS: usize = 9;
let handle = plan_for(ROWS, COLS);
for _ in 0..2 {
let h = std::hint::black_box(&handle);
for r in 0..ROWS {
std::hint::black_box(Column::from_f64_transpose_row(h, std::hint::black_box(r)));
}
}
let mut ctor = Vec::with_capacity(BLOCKS);
let mut null = Vec::with_capacity(BLOCKS);
for _ in 0..BLOCKS {
let (mut bc, mut bn) = (f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let h = std::hint::black_box(&handle);
let t0 = Instant::now();
for r in 0..ROWS {
std::hint::black_box(Column::from_f64_transpose_row(
h,
std::hint::black_box(r),
));
}
bc = bc.min(t0.elapsed().as_secs_f64() * 1e3);
// identical arm: the null control
let t0 = Instant::now();
for r in 0..ROWS {
std::hint::black_box(Column::from_f64_transpose_row(
h,
std::hint::black_box(r),
));
}
bn = bn.min(t0.elapsed().as_secs_f64() * 1e3);
}
ctor.push(bc);
null.push(bn);
}
let (c, n) = (min_of(&ctor), min_of(&null));
println!("AB transpose per-column ctor share (ONE binary, ONE invocation)");
println!(" binary_sha256 = {}", binary_sha256());
println!(" worker = {}", worker_hostname());
println!(" columns={ROWS} (each {COLS} cells)");
println!(
" CTOR from_f64_transpose_row min={c:9.3} ms cv={:5.2}%",
cv_of(&ctor)
);
println!(
" NULL identical arm min={n:9.3} ms cv={:5.2}%",
cv_of(&null)
);
println!(" NULL-CONTROL ratio = {:.4}x", c / n);
println!(" per-column ctor = {:.2} ns", 1e6 * c / ROWS as f64);
println!(
" cv<5% both arms: ctor={} null={}",
cv_of(&ctor) < 5.0,
cv_of(&null) < 5.0
);
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_transpose_row_typed() {
// Longer per-rep work + more reps: the first run on a loaded worker gave
// cv 6.81%/11.54%, above the 5% gate, so its 1.715x was not claimable.
const ROWS: usize = 200_000;
const COLS: usize = 10;
const BLOCKS: usize = 11;
const REPS: usize = 5;
let handle = plan_for(ROWS, COLS);
// Parity, same binary, before timing: typed slice == boxed values, every row.
for r in [0usize, 1, ROWS / 2, ROWS - 1] {
let col = Column::from_f64_transpose_row(&handle, r);
let typed: Vec<f64> = col.as_f64_slice().expect("typed arm").to_vec();
let boxed: Vec<f64> = col
.values()
.iter()
.map(|s| match s {
Scalar::Float64(v) => *v,
other => panic!("unexpected {other:?}"),
})
.collect();
assert_eq!(typed, boxed, "row {r}: typed arm diverged from values()");
}
let warm = |h: &Float64TransposeRows| {
let mut acc = 0usize;
for r in 0..1024 {
let col = Column::from_f64_transpose_row(h, r);
acc += col.values().len();
let col = Column::from_f64_transpose_row(h, r);
acc += col.as_f64_slice().expect("typed").len();
}
acc
};
std::hint::black_box(warm(std::hint::black_box(&handle)));
// NULL CONTROL: `null` runs the IDENTICAL arm as `orig` (values()). The ratio
// orig/null is this harness's noise floor -- any effect smaller than that
// deviation is indistinguishable from drift. All three arms alternate inside
// the one measured routine, so they share the same scheduler/thermal history.
let mut orig = Vec::with_capacity(BLOCKS);
let mut null = Vec::with_capacity(BLOCKS);
let mut cand = Vec::with_capacity(BLOCKS);
for _ in 0..BLOCKS {
let (mut bo, mut bn, mut bc) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let h = std::hint::black_box(&handle);
let t0 = Instant::now();
let mut acc = 0usize;
for r in 0..ROWS {
let col = Column::from_f64_transpose_row(h, std::hint::black_box(r));
acc += col.values().len();
}
std::hint::black_box(acc);
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
// Identical to the ORIG arm, on purpose: this is the null control.
let t0 = Instant::now();
let mut acc = 0usize;
for r in 0..ROWS {
let col = Column::from_f64_transpose_row(h, std::hint::black_box(r));
acc += col.values().len();
}
std::hint::black_box(acc);
bn = bn.min(t0.elapsed().as_secs_f64() * 1e3);
let t0 = Instant::now();
let mut acc = 0usize;
for r in 0..ROWS {
let col = Column::from_f64_transpose_row(h, std::hint::black_box(r));
acc += col.as_f64_slice().expect("typed").len();
}
std::hint::black_box(acc);
bc = bc.min(t0.elapsed().as_secs_f64() * 1e3);
}
orig.push(bo);
null.push(bn);
cand.push(bc);
}
let (o, n, c) = (min_of(&orig), min_of(&null), min_of(&cand));
let cells = (ROWS * COLS) as f64;
println!("AB transpose-row typed access (ONE binary, ONE invocation, interleaved)");
println!(" binary_sha256 = {}", binary_sha256());
println!(" worker = {}", worker_hostname());
println!(" rows={ROWS} cols={COLS} cells={}", ROWS * COLS);
println!(
" ORIG values() min={o:9.3} ms cv={:5.2}%",
cv_of(&orig)
);
println!(
" CAND as_f64_slice min={c:9.3} ms cv={:5.2}%",
cv_of(&cand)
);
println!(
" boxing tax (ORIG-CAND) = {:8.3} ms ({:5.2} ns/cell)",
o - c,
1e6 * (o - c) / cells
);
println!(
" NULL values() min={n:9.3} ms cv={:5.2}% <- identical arm",
cv_of(&null)
);
println!(
" NULL-CONTROL ratio (orig/null) = {:.4}x <- noise floor",
o / n
);
println!(" fp-side ratio (orig/cand) = {:.4}x", o / c);
println!(
" effect deviation {:.1}x the null-control deviation",
(o / c - 1.0).abs() / (o / n - 1.0).abs().max(1e-9)
);
println!(
" cv<5% all arms: orig={} null={} cand={}",
cv_of(&orig) < 5.0,
cv_of(&null) < 5.0,
cv_of(&cand) < 5.0
);
}
}
/// A/B for routing all-valid, NaT-free Datetime64/Timedelta64 argsort through the
/// i64 radix instead of the generic `Scalar` na-last comparison sort (cc_fp).
/// ORIG = the exact generic path (materialize `Scalar`s, stable `sort_by`), kept
/// here as a bench-only reference so both arms live in ONE binary; CAND = the new
/// `argsort_with` radix path. Interleaved in a single measured routine with a
/// per-arm adjacent A/A null control; gate on median vs the null floor.
///
/// Run: `RCH_REQUIRE_REMOTE=1 env -u CARGO_TARGET_DIR rch exec -- \
/// cargo test -p fp-columnar --release --lib -- --ignored --nocapture ab_temporal_argsort`
#[cfg(test)]
mod ab_temporal_argsort_ccfp {
use std::{process::Command, time::Instant};
use fp_types::Scalar;
use super::{Column, compare_scalars_na_last};
// Byte-for-byte the generic argsort tail (lib.rs ~17627): the path a Datetime64
// column took before the radix branch. Reference arm only.
fn argsort_scalar_ref(col: &Column, ascending: bool) -> Vec<usize> {
let vals = col.values();
let mut indexed: Vec<(usize, &Scalar)> = vals.iter().enumerate().collect();
indexed.sort_by(|a, b| compare_scalars_na_last(a.1, b.1, ascending));
indexed.into_iter().map(|(i, _)| i).collect()
}
// Deterministic splitmix, no rand dep; nanos kept well away from i64::MIN (NaT).
fn nanos(n: usize) -> Vec<i64> {
let mut s: u64 = 0x9E37_79B9_7F4A_7C15;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
// base 2000-01-01 + up to ~50 years of jitter; always > i64::MIN
946_684_800_000_000_000_i64.wrapping_add((z % 1_600_000_000_000_000_000) as i64)
})
.collect()
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_temporal_argsort() {
const N: usize = 1_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let col = Column::from_datetime64_values(nanos(N));
// Parity in this same binary: radix perm must equal the Scalar-sort perm.
for asc in [true, false] {
assert_eq!(
argsort_scalar_ref(&col, asc),
col.argsort_with(asc),
"radix argsort diverged from the Scalar path (ascending={asc})"
);
}
for _ in 0..2 {
std::hint::black_box(argsort_scalar_ref(std::hint::black_box(&col), true));
std::hint::black_box(col.argsort_with(true));
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let c = std::hint::black_box(&col);
let t0 = Instant::now();
std::hint::black_box(argsort_scalar_ref(c, true));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
// CAND adjacent A/A -> its own null floor
let t0 = Instant::now();
std::hint::black_box(c.argsort_with(true));
let a = t0.elapsed().as_secs_f64() * 1e3;
let t0 = Instant::now();
std::hint::black_box(c.argsort_with(true));
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
println!("AB temporal argsort (ONE binary, ONE invocation) N={N}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG Scalar-sort min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND i64-radix min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
let nullmed = median_of(&null);
println!(
" NULL-CONTROL (CAND A/A) median ratio={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
/// A/B for routing all-valid, NaT-free Datetime64/Timedelta64 min/max through the
/// raw-i64 scan instead of materializing the `Scalar` Vec for `nanmin`/`nanmax`
/// (cc_fp). Fresh column per rep so the ORIG arm pays the materialization it pays
/// in production (min/max is typically called once per built column). ORIG =
/// `nanmin(col.values())`; CAND = `col.min()` (now the i64 scan). Interleaved in
/// one binary, per-arm adjacent A/A null control, median gate.
#[cfg(test)]
mod ab_temporal_minmax_ccfp {
use std::{process::Command, time::Instant};
use super::Column;
fn nanos(n: usize) -> Vec<i64> {
let mut s: u64 = 0x2545_F491_4F6C_DD1D;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
946_684_800_000_000_000_i64.wrapping_add((z % 1_600_000_000_000_000_000) as i64)
})
.collect()
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_temporal_minmax() {
const N: usize = 2_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 5;
let src = nanos(N);
// Correctness: col.min()/max() equal the EXACT i64-nanos extremum. Note the
// OLD path (nanmin) compares Datetime64 via a LOSSY `to_f64()` (nanos > 2^53
// lose precision), so this exact-i64 fold is a correctness FIX for Datetime64
// (and bit-identical for Timedelta64, whose nanmin arm is already exact i64).
{
let exact_min = *src.iter().min().unwrap();
let exact_max = *src.iter().max().unwrap();
let col = Column::from_datetime64_values(src.clone());
assert_eq!(
col.min(),
fp_types::Scalar::Datetime64(exact_min),
"min not exact"
);
assert_eq!(
col.max(),
fp_types::Scalar::Datetime64(exact_max),
"max not exact"
);
}
for _ in 0..2 {
let col = Column::from_datetime64_values(src.clone());
std::hint::black_box(fp_types::nanmin(col.values()));
let col = Column::from_datetime64_values(src.clone());
std::hint::black_box(col.min());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
// ORIG: fresh column, materialize Scalars, nanmin.
let col = Column::from_datetime64_values(src.clone());
let t0 = Instant::now();
std::hint::black_box(fp_types::nanmin(std::hint::black_box(&col).values()));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
// CAND adjacent A/A: fresh column, i64 scan.
let col2 = Column::from_datetime64_values(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&col2).min());
let a = t0.elapsed().as_secs_f64() * 1e3;
let col3 = Column::from_datetime64_values(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&col3).min());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB temporal min (ONE binary, ONE invocation) N={N}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nanmin(materialize) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND i64-scan min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
/// A/B for routing all-valid, non-empty, NaT-free Timedelta64 sum/mean through the
/// raw-i64 i128 fold instead of materializing the `Scalar` Vec for `nansum`/
/// `nanmean` (cc_fp). Bit-identical: `nansum`/`nanmean` already accumulate
/// Timedelta64 in exact i128 via `collect_timedelta_ns`; this reads the same nanos
/// from the raw backing. Fresh column per rep so ORIG pays materialization; per-arm
/// adjacent A/A null control; median gate.
#[cfg(test)]
mod ab_timedelta_sum_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, ValidityMask};
fn ns(n: usize) -> Vec<i64> {
let mut s: u64 = 0xD1B5_4A32_D192_ED03;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
// durations in [-5e11, 5e11) ns (~ +/- 8 minutes), never i64::MIN
(z % 1_000_000_000_000) as i64 - 500_000_000_000
})
.collect()
}
fn mk(src: &[i64]) -> Column {
Column::from_timedelta64_values_with_validity(
src.to_vec(),
ValidityMask::all_valid(src.len()),
)
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_timedelta_sum() {
const N: usize = 2_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 5;
let src = ns(N);
// Parity: col.sum()/mean() == nansum/nanmean over the materialized Scalars.
{
let col = mk(&src);
assert_eq!(col.sum(), fp_types::nansum(col.values()), "sum diverged");
assert_eq!(col.mean(), fp_types::nanmean(col.values()), "mean diverged");
}
for _ in 0..2 {
std::hint::black_box(fp_types::nansum(mk(&src).values()));
std::hint::black_box(mk(&src).sum());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let col = mk(&src);
let t0 = Instant::now();
std::hint::black_box(fp_types::nansum(std::hint::black_box(&col).values()));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let col2 = mk(&src);
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&col2).sum());
let a = t0.elapsed().as_secs_f64() * 1e3;
let col3 = mk(&src);
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&col3).sum());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB timedelta sum (ONE binary, ONE invocation) N={N}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nansum(materialize) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND i128-fold min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
/// A/B for routing all-valid, NaT-free Datetime64/Timedelta64 value_counts through
/// the typed i64 tally (`value_counts_i64_typed`) + a re-tag, instead of the generic
/// `set_member_key` Scalar tally (cc_fp). Parity is proven against the Int64-column
/// value_counts (which shares `value_counts_i64_typed`, documented bit-identical to
/// the generic path) — same counts, same distinct nanos. ORIG timing forces the
/// generic path by planting one NAT sentinel (my branch's `!contains(i64::MIN)` gate
/// skips it); the one dropped value is negligible for timing. Median gate, per-arm
/// adjacent A/A null control.
#[cfg(test)]
mod ab_temporal_value_counts_ccfp {
use std::{process::Command, time::Instant};
use super::Column;
fn nanos(n: usize, distinct: i64) -> Vec<i64> {
let mut s: u64 = 0x7C15_9E37_79B9_4F6C;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
946_684_800_000_000_000_i64 + (z % distinct as u64) as i64
})
.collect()
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_temporal_value_counts() {
const N: usize = 2_000_000;
const DISTINCT: i64 = 50_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let src = nanos(N, DISTINCT);
// Parity: the fast path's (values, counts) equals the Int64-column tally
// (both go through value_counts_i64_typed), re-tagged to Datetime64.
{
let dt = Column::from_datetime64_values(src.clone());
let (dv, dc) = dt.value_counts().expect("dt value_counts");
let iv = Column::from_i64_values_owned(src.clone());
let (ev, ec) = iv.value_counts().expect("i64 value_counts");
assert_eq!(dc.values(), ec.values(), "counts diverged");
assert_eq!(
dv.as_datetime64_slice().expect("dt values"),
ev.as_i64_slice().expect("i64 values"),
"distinct nanos diverged"
);
}
// ORIG timing column: plant one NAT so the fast path's no-NAT gate skips it
// -> generic set_member_key path. CAND: all-valid -> fast path.
let mut src_orig = src.clone();
src_orig[0] = i64::MIN;
for _ in 0..2 {
std::hint::black_box(
Column::from_datetime64_values(src_orig.clone())
.value_counts()
.unwrap(),
);
std::hint::black_box(
Column::from_datetime64_values(src.clone())
.value_counts()
.unwrap(),
);
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = Column::from_datetime64_values(src_orig.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&co).value_counts().unwrap());
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = Column::from_datetime64_values(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).value_counts().unwrap());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = Column::from_datetime64_values(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).value_counts().unwrap());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB temporal value_counts (ONE binary, ONE invocation) N={N} distinct={DISTINCT}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic set_member_key min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND i64 tally + re-tag min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
/// A/B for routing all-valid, NaT-free Timedelta64 unique through the raw-i64
/// open-addressing dedup (`unique_i64_wide`) + re-tag, instead of the generic
/// `Key::Timedelta64` Scalar dedup (cc_fp). Parity vs the Int64-column unique
/// (shared `unique_i64_wide`, first-seen order). ORIG timing forces the generic
/// path via one planted NAT the CAND gate skips. Median gate, per-arm A/A null.
#[cfg(test)]
mod ab_timedelta_unique_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, ValidityMask};
fn ns(n: usize, distinct: i64) -> Vec<i64> {
let mut s: u64 = 0x4F6C_DD1D_2545_F491;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
(z % distinct as u64) as i64 - distinct / 2
})
.collect()
}
fn td(v: Vec<i64>) -> Column {
let n = v.len();
Column::from_timedelta64_values_with_validity(v, ValidityMask::all_valid(n))
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_timedelta_unique() {
const N: usize = 2_000_000;
const DISTINCT: i64 = 50_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let src = ns(N, DISTINCT);
// Parity: Timedelta unique's distinct ns == Int64-column unique (both
// unique_i64_wide, first-seen order), re-tagged to Timedelta64.
{
let u = td(src.clone()).unique().expect("td unique");
let e = Column::from_i64_values_owned(src.clone())
.unique()
.expect("i64 unique");
assert_eq!(
u.as_timedelta64_slice().expect("td values"),
e.as_i64_slice().expect("i64 values"),
"distinct ns diverged"
);
}
// ORIG timing: plant a NAT so the no-NAT gate skips -> generic Key path.
let mut src_orig = src.clone();
src_orig[0] = i64::MIN;
for _ in 0..2 {
std::hint::black_box(td(src_orig.clone()).unique().unwrap());
std::hint::black_box(td(src.clone()).unique().unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = td(src_orig.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&co).unique().unwrap());
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = td(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).unique().unwrap());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = td(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).unique().unwrap());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB timedelta unique (ONE binary, ONE invocation) N={N} distinct={DISTINCT}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic Key dedup min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND i64 open-addr+re-tag min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod ab_utf8_unique_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, FxHashSet, Scalar};
/// Seeded (splitmix64) contiguous-Utf8 buffer: `n` rows drawn from `distinct`
/// fixed-width `"val_{:07}"` labels. Every label is a distinct heap `String`
/// once materialized, so the generic path pays one alloc per row.
fn mk(n: usize, distinct: usize) -> (Vec<u8>, Vec<usize>) {
let mut s: u64 = 0x1234_5678_9ABC_DEF1;
let mut bytes: Vec<u8> = Vec::with_capacity(n * 11);
let mut offsets: Vec<usize> = Vec::with_capacity(n + 1);
offsets.push(0);
for _ in 0..n {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
let key = (z as usize) % distinct;
bytes.extend_from_slice(b"val_");
let mut buf = [0u8; 7];
let mut k = key;
for slot in buf.iter_mut().rev() {
*slot = b'0' + (k % 10) as u8;
k /= 10;
}
bytes.extend_from_slice(&buf);
offsets.push(bytes.len());
}
(bytes, offsets)
}
/// Reference for the pre-lever generic path: force the `Vec<Scalar::Utf8>`
/// materialization (one `String` per row) via `as_slice`, then FxHashSet
/// `&str` first-seen dedup with `Scalar` clone -- byte-for-byte the shipped
/// `Key::Utf8` arm's cost, minus the fast-path interception.
fn orig_unique_utf8(col: &Column) -> Column {
let scalars = col.values.as_slice();
let mut seen: FxHashSet<&str> = FxHashSet::default();
let mut out: Vec<Scalar> = Vec::new();
for v in scalars {
if let Scalar::Utf8(s) = v
&& seen.insert(s.as_str())
{
out.push(v.clone());
}
}
Column::new(DType::Utf8, out).expect("utf8 column")
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_utf8_unique() {
const N: usize = 2_000_000;
const DISTINCT: usize = 50_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let (bytes, offsets) = mk(N, DISTINCT);
// Parity: the fast-path distinct sequence == the generic reference's,
// element-for-element (same first-seen order, same bytes, same dtype).
{
let orig = orig_unique_utf8(&Column::from_utf8_contiguous(
bytes.clone(),
offsets.clone(),
));
let cand = Column::from_utf8_contiguous(bytes.clone(), offsets.clone())
.unique()
.expect("utf8 unique");
assert_eq!(orig.dtype(), cand.dtype(), "dtype diverged");
assert_eq!(
orig.values.as_slice(),
cand.values.as_slice(),
"distinct utf8 sequence diverged"
);
}
for _ in 0..2 {
std::hint::black_box(orig_unique_utf8(&Column::from_utf8_contiguous(
bytes.clone(),
offsets.clone(),
)));
std::hint::black_box(
Column::from_utf8_contiguous(bytes.clone(), offsets.clone())
.unique()
.unwrap(),
);
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
let t0 = Instant::now();
std::hint::black_box(orig_unique_utf8(std::hint::black_box(&co)));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).unique().unwrap());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).unique().unwrap());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB utf8 unique (ONE binary, ONE invocation) N={N} distinct={DISTINCT}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic Scalar::Utf8 dedup min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND contiguous &[u8] dedup min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod ab_utf8_value_counts_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, FxHashMap, Scalar};
/// Seeded (splitmix64) contiguous-Utf8 buffer: `n` rows drawn from `distinct`
/// fixed-width `"val_{:07}"` labels. Every label is a distinct heap `String`
/// once materialized, so the generic tally pays one alloc per row.
fn mk(n: usize, distinct: usize) -> (Vec<u8>, Vec<usize>) {
let mut s: u64 = 0x1234_5678_9ABC_DEF1;
let mut bytes: Vec<u8> = Vec::with_capacity(n * 11);
let mut offsets: Vec<usize> = Vec::with_capacity(n + 1);
offsets.push(0);
for _ in 0..n {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
let key = (z as usize) % distinct;
bytes.extend_from_slice(b"val_");
let mut buf = [0u8; 7];
let mut k = key;
for slot in buf.iter_mut().rev() {
*slot = b'0' + (k % 10) as u8;
k /= 10;
}
bytes.extend_from_slice(&buf);
offsets.push(bytes.len());
}
(bytes, offsets)
}
/// Reference for the pre-lever generic tally: force the `Vec<Scalar::Utf8>`
/// materialization (one `String` per row) via `as_slice`, then FxHashMap
/// `&str` first-seen tally with `Scalar` clone per distinct -- byte-for-byte
/// the shipped `set_member_key` arm's cost, minus the fast-path interception
/// (and minus the per-elem `is_missing()` / `SetMemberKey` enum wrap it also
/// pays, so this is a CONSERVATIVE floor).
fn orig_value_counts_utf8(
col: &Column,
normalize: bool,
sort: bool,
ascending: bool,
) -> (Column, Column) {
let scalars = col.values.as_slice();
let mut index: FxHashMap<&str, usize> = FxHashMap::default();
let mut counts: Vec<(Scalar, usize)> = Vec::new();
for v in scalars {
if let Scalar::Utf8(s) = v {
if let Some(&i) = index.get(s.as_str()) {
counts[i].1 += 1;
} else {
index.insert(s.as_str(), counts.len());
counts.push((v.clone(), 1));
}
}
}
if sort {
if ascending {
counts.sort_by_key(|(_, count)| *count);
} else {
counts.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
}
}
let total = if normalize {
counts.iter().map(|(_, count)| *count).sum::<usize>() as f64
} else {
1.0
};
let mut values_out: Vec<Scalar> = Vec::with_capacity(counts.len());
let mut counts_out: Vec<Scalar> = Vec::with_capacity(counts.len());
for (value, count) in counts {
values_out.push(value);
if normalize {
let n = if total == 0.0 {
0.0
} else {
count as f64 / total
};
counts_out.push(Scalar::Float64(n));
} else {
counts_out.push(Scalar::Int64(i64::try_from(count).unwrap_or(i64::MAX)));
}
}
(
Column::new(DType::Utf8, values_out).expect("utf8 values"),
Column::new(
if normalize {
DType::Float64
} else {
DType::Int64
},
counts_out,
)
.expect("counts"),
)
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_utf8_value_counts() {
const N: usize = 2_000_000;
const DISTINCT: usize = 50_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let (bytes, offsets) = mk(N, DISTINCT);
let mk_col = || Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
// Parity across every branch (sort asc/desc/none, normalize): the fast
// path's (values, counts) pair == the generic reference's, element-for-
// element -- same first-seen order, same stable count-sort tie-break.
for &(normalize, sort, ascending) in &[
(false, true, false),
(false, true, true),
(false, false, false),
(true, true, false),
] {
let (ov, oc) = orig_value_counts_utf8(&mk_col(), normalize, sort, ascending);
let (cv, cc) = mk_col()
.value_counts_with_options(normalize, sort, ascending, true)
.expect("value_counts");
assert_eq!(ov.dtype(), cv.dtype(), "values dtype diverged");
assert_eq!(
ov.values.as_slice(),
cv.values.as_slice(),
"distinct values diverged (normalize={normalize} sort={sort} asc={ascending})"
);
assert_eq!(
oc.values.as_slice(),
cc.values.as_slice(),
"counts diverged (normalize={normalize} sort={sort} asc={ascending})"
);
}
for _ in 0..2 {
std::hint::black_box(orig_value_counts_utf8(&mk_col(), false, true, false));
std::hint::black_box(
mk_col()
.value_counts_with_options(false, true, false, true)
.unwrap(),
);
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_value_counts_utf8(
std::hint::black_box(&co),
false,
true,
false,
));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c1)
.value_counts_with_options(false, true, false, true)
.unwrap(),
);
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c2)
.value_counts_with_options(false, true, false, true)
.unwrap(),
);
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB utf8 value_counts (ONE binary, ONE invocation) N={N} distinct={DISTINCT}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic set_member_key tally min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND contiguous &[u8] tally min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod ab_utf8_nunique_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, FxHashSet, Scalar};
/// Seeded (splitmix64) contiguous-Utf8 buffer: `n` rows drawn from `distinct`
/// fixed-width `"val_{:07}"` labels. Every label is a distinct heap `String`
/// once materialized, so the `nannunique` path pays one alloc per row.
fn mk(n: usize, distinct: usize) -> (Vec<u8>, Vec<usize>) {
let mut s: u64 = 0x1234_5678_9ABC_DEF1;
let mut bytes: Vec<u8> = Vec::with_capacity(n * 11);
let mut offsets: Vec<usize> = Vec::with_capacity(n + 1);
offsets.push(0);
for _ in 0..n {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
let key = (z as usize) % distinct;
bytes.extend_from_slice(b"val_");
let mut buf = [0u8; 7];
let mut k = key;
for slot in buf.iter_mut().rev() {
*slot = b'0' + (k % 10) as u8;
k /= 10;
}
bytes.extend_from_slice(&buf);
offsets.push(bytes.len());
}
(bytes, offsets)
}
/// Reference for the pre-lever generic path: force the `Vec<Scalar::Utf8>`
/// materialization (one `String` per row) via `as_slice`, then FxHashSet
/// `&str` distinct count -- byte-for-byte `nannunique`'s cost for an all-valid
/// Utf8 column, minus the fast-path interception (CONSERVATIVE: omits the
/// per-elem `is_missing()` test and `ScalarKey` enum wrap it also pays).
fn orig_nunique_utf8(col: &Column) -> i64 {
let scalars = col.values.as_slice();
let mut seen: FxHashSet<&str> = FxHashSet::default();
for v in scalars {
if let Scalar::Utf8(s) = v {
seen.insert(s.as_str());
}
}
seen.len() as i64
}
fn as_i64(s: &Scalar) -> i64 {
match s {
Scalar::Int64(v) => *v,
other => panic!("expected Int64, got {other:?}"),
}
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_utf8_nunique() {
const N: usize = 2_000_000;
const DISTINCT: usize = 50_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let (bytes, offsets) = mk(N, DISTINCT);
let mk_col = || Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
// Parity: fast-path count == generic reference AND == DISTINCT; and both
// dropna values agree for an all-valid column (no missing bucket).
{
let expect = orig_nunique_utf8(&mk_col());
assert_eq!(expect, DISTINCT as i64, "reference miscounted");
assert_eq!(expect, as_i64(&mk_col().nunique()), "nunique diverged");
assert_eq!(
expect,
as_i64(&mk_col().nunique_with_dropna(false)),
"nunique(dropna=false) diverged"
);
}
for _ in 0..2 {
std::hint::black_box(orig_nunique_utf8(&mk_col()));
std::hint::black_box(mk_col().nunique());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_nunique_utf8(std::hint::black_box(&co)));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).nunique());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).nunique());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB utf8 nunique (ONE binary, ONE invocation) N={N} distinct={DISTINCT}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nannunique Scalar::Utf8 count min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND contiguous &[u8] count min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod ab_utf8_mode_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, FxHashMap, Scalar, compare_scalars_na_last};
/// Seeded (splitmix64) contiguous-Utf8 buffer: `n` rows drawn from `distinct`
/// fixed-width `"val_{:07}"` labels. Every label is a distinct heap `String`
/// once materialized, so the generic tally pays one alloc per row.
fn mk(n: usize, distinct: usize) -> (Vec<u8>, Vec<usize>) {
let mut s: u64 = 0x1234_5678_9ABC_DEF1;
let mut bytes: Vec<u8> = Vec::with_capacity(n * 11);
let mut offsets: Vec<usize> = Vec::with_capacity(n + 1);
offsets.push(0);
for _ in 0..n {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
let key = (z as usize) % distinct;
bytes.extend_from_slice(b"val_");
let mut buf = [0u8; 7];
let mut k = key;
for slot in buf.iter_mut().rev() {
*slot = b'0' + (k % 10) as u8;
k /= 10;
}
bytes.extend_from_slice(&buf);
offsets.push(bytes.len());
}
(bytes, offsets)
}
fn col_of(strs: &[&str]) -> Column {
let mut b: Vec<u8> = Vec::new();
let mut o: Vec<usize> = vec![0];
for s in strs {
b.extend_from_slice(s.as_bytes());
o.push(b.len());
}
Column::from_utf8_contiguous(b, o)
}
/// Reference for the pre-lever generic mode path over an all-valid Utf8
/// column: force `Vec<Scalar::Utf8>` materialization via `as_slice`, tally
/// into an FxHashMap keyed by `&str` (first-seen `Scalar` kept for output),
/// then the winners = max-count values sorted by the SHIPPED
/// `compare_scalars_na_last(.., true)`. CONSERVATIVE: omits the per-elem
/// `is_missing()` / `key_of` enum wrap the shipped arm also pays.
fn orig_mode_utf8(col: &Column) -> Column {
let scalars = col.values.as_slice();
let mut counts: FxHashMap<&str, (usize, &Scalar)> = FxHashMap::default();
for v in scalars {
if let Scalar::Utf8(s) = v {
counts
.entry(s.as_str())
.and_modify(|entry| entry.0 += 1)
.or_insert((1, v));
}
}
if counts.is_empty() {
return Column::new(DType::Utf8, Vec::new()).expect("empty utf8");
}
let max_count = counts.values().map(|(c, _)| *c).max().unwrap_or(0);
let mut winners: Vec<Scalar> = counts
.values()
.filter_map(|(c, v)| {
if *c == max_count {
Some((*v).clone())
} else {
None
}
})
.collect();
winners.sort_by(|a, b| compare_scalars_na_last(a, b, true));
Column::new(DType::Utf8, winners).expect("utf8 winners")
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_utf8_mode() {
const N: usize = 2_000_000;
const DISTINCT: usize = 50_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let (bytes, offsets) = mk(N, DISTINCT);
let mk_col = || Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
// Parity: fast-path winners == generic reference on the big column.
{
let om = orig_mode_utf8(&mk_col());
let cm = mk_col().mode().expect("mode");
assert_eq!(om.dtype(), cm.dtype(), "dtype diverged");
assert_eq!(
om.values.as_slice(),
cm.values.as_slice(),
"mode winners diverged (big column)"
);
}
// Multi-winner tie exercises the winner sort: a,b both count 2 -> ["a","b"].
{
let tie = col_of(&["b", "a", "b", "a", "c"]);
let cm = tie.mode().expect("tie mode");
assert_eq!(
cm.values.as_slice(),
orig_mode_utf8(&tie).values.as_slice(),
"tie winners diverged vs reference"
);
assert_eq!(
cm.values.as_slice(),
col_of(&["a", "b"]).values.as_slice(),
"tie winners not the expected sorted [a,b]"
);
}
// Empty column -> empty same-dtype column.
{
let empty = col_of(&[]);
assert_eq!(
empty.mode().expect("empty mode").values.as_slice(),
orig_mode_utf8(&empty).values.as_slice(),
"empty mode diverged"
);
}
for _ in 0..2 {
std::hint::black_box(orig_mode_utf8(&mk_col()));
std::hint::black_box(mk_col().mode().unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_mode_utf8(std::hint::black_box(&co)));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).mode().unwrap());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).mode().unwrap());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB utf8 mode (ONE binary, ONE invocation) N={N} distinct={DISTINCT}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic Key::Utf8 tally min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND contiguous &[u8] tally min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod ab_utf8_duplicated_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, FxHashSet, Scalar};
/// Seeded (splitmix64) contiguous-Utf8 buffer: `n` rows drawn from `distinct`
/// fixed-width `"val_{:07}"` labels. Every label is a distinct heap `String`
/// once materialized, so the generic path pays one alloc per row.
fn mk(n: usize, distinct: usize) -> (Vec<u8>, Vec<usize>) {
let mut s: u64 = 0x1234_5678_9ABC_DEF1;
let mut bytes: Vec<u8> = Vec::with_capacity(n * 11);
let mut offsets: Vec<usize> = Vec::with_capacity(n + 1);
offsets.push(0);
for _ in 0..n {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
let key = (z as usize) % distinct;
bytes.extend_from_slice(b"val_");
let mut buf = [0u8; 7];
let mut k = key;
for slot in buf.iter_mut().rev() {
*slot = b'0' + (k % 10) as u8;
k /= 10;
}
bytes.extend_from_slice(&buf);
offsets.push(bytes.len());
}
(bytes, offsets)
}
/// Reference for the pre-lever generic path: force the `Vec<Scalar::Utf8>`
/// materialization (one `String` per row) via `as_slice`, then FxHashSet
/// `&str` duplicate-flag computation per policy -- byte-for-byte the shipped
/// `Key` path's cost for an all-valid Utf8 column, minus the fast-path
/// interception (CONSERVATIVE: omits the per-elem `is_missing()` / `Key` enum
/// wrap it also pays).
fn orig_duplicated_utf8(col: &Column, policy: &str) -> Column {
let scalars = col.values.as_slice();
let n = scalars.len();
let mut flags = vec![false; n];
match policy {
"first" => {
let mut seen: FxHashSet<&str> = FxHashSet::default();
for (idx, v) in scalars.iter().enumerate() {
if let Scalar::Utf8(s) = v {
flags[idx] = !seen.insert(s.as_str());
}
}
}
"last" => {
let mut seen: FxHashSet<&str> = FxHashSet::default();
for idx in (0..n).rev() {
if let Scalar::Utf8(s) = &scalars[idx] {
flags[idx] = !seen.insert(s.as_str());
}
}
}
_ => {
let mut seen_once: FxHashSet<&str> = FxHashSet::default();
let mut seen_multiple: FxHashSet<&str> = FxHashSet::default();
for v in scalars {
if let Scalar::Utf8(s) = v
&& !seen_once.insert(s.as_str())
{
seen_multiple.insert(s.as_str());
}
}
for (idx, v) in scalars.iter().enumerate() {
if let Scalar::Utf8(s) = v {
flags[idx] = seen_multiple.contains(s.as_str());
}
}
}
}
Column::new(DType::Bool, flags.into_iter().map(Scalar::Bool).collect()).expect("bool")
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_utf8_duplicated() {
const N: usize = 2_000_000;
const DISTINCT: usize = 50_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let (bytes, offsets) = mk(N, DISTINCT);
let mk_col = || Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
// Parity across every policy (first/last/none): the fast path's Bool
// flags == the generic reference's, element-for-element. Also checks
// drop_duplicates (= duplicated + filter) agrees for keep="first".
for policy in ["first", "last", "false"] {
let orig = orig_duplicated_utf8(&mk_col(), policy);
let cand = mk_col().duplicated_keep(policy).expect("duplicated");
assert_eq!(orig.dtype(), cand.dtype(), "dtype diverged");
assert_eq!(
orig.values.as_slice(),
cand.values.as_slice(),
"duplicated flags diverged (policy={policy})"
);
}
{
let dd = mk_col().drop_duplicates_keep("first").expect("drop_dup");
// distinct count preserved: drop_duplicates("first") keeps DISTINCT rows.
assert_eq!(dd.len(), DISTINCT, "drop_duplicates kept wrong count");
}
for _ in 0..2 {
std::hint::black_box(orig_duplicated_utf8(&mk_col(), "first"));
std::hint::black_box(mk_col().duplicated_keep("first").unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_duplicated_utf8(std::hint::black_box(&co), "first"));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).duplicated_keep("first").unwrap());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).duplicated_keep("first").unwrap());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!(
"AB utf8 duplicated keep=first (ONE binary, ONE invocation) N={N} distinct={DISTINCT}"
);
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic Key::Utf8 flags min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND contiguous &[u8] flags min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod ab_utf8_isin_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, FxHashSet, Scalar};
/// Seeded (splitmix64) contiguous-Utf8 buffer: `n` rows drawn from `distinct`
/// fixed-width `"val_{:07}"` labels.
fn mk(n: usize, distinct: usize) -> (Vec<u8>, Vec<usize>) {
let mut s: u64 = 0x1234_5678_9ABC_DEF1;
let mut bytes: Vec<u8> = Vec::with_capacity(n * 11);
let mut offsets: Vec<usize> = Vec::with_capacity(n + 1);
offsets.push(0);
for _ in 0..n {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
let key = (z as usize) % distinct;
bytes.extend_from_slice(b"val_");
let mut buf = [0u8; 7];
let mut k = key;
for slot in buf.iter_mut().rev() {
*slot = b'0' + (k % 10) as u8;
k /= 10;
}
bytes.extend_from_slice(&buf);
offsets.push(bytes.len());
}
(bytes, offsets)
}
/// `count` needle labels `"val_{:07}"` for keys `0..count` (same alphabet as
/// `mk`), so ~`count/distinct` of the rows match.
fn needle_scalars(count: usize) -> Vec<Scalar> {
(0..count)
.map(|k| Scalar::Utf8(format!("val_{k:07}")))
.collect()
}
/// Reference for the pre-lever generic scan: build the `&str` needle set,
/// force `Vec<Scalar::Utf8>` materialization via `as_slice`, probe membership
/// per row -- byte-for-byte the shipped `Key::Utf8` scan minus the fast-path
/// interception (CONSERVATIVE: omits the per-elem `key_of` is_missing/enum
/// wrap the shipped arm pays).
fn orig_isin_utf8(col: &Column, needles: &[Scalar]) -> Column {
let mut lookup: FxHashSet<&str> = FxHashSet::default();
for n in needles {
if let Scalar::Utf8(s) = n {
lookup.insert(s.as_str());
}
}
let scalars = col.values.as_slice();
let out: Vec<Scalar> = scalars
.iter()
.map(|v| {
Scalar::Bool(match v {
Scalar::Utf8(s) => lookup.contains(s.as_str()),
_ => false,
})
})
.collect();
Column::new(DType::Bool, out).expect("bool")
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_utf8_isin() {
const N: usize = 2_000_000;
const DISTINCT: usize = 50_000;
const NEEDLES: usize = 5_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let (bytes, offsets) = mk(N, DISTINCT);
let mk_col = || Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
let needles = needle_scalars(NEEDLES);
// Parity: fast path == generic reference (~10% hit); empty needle set =>
// all false; a mixed non-Utf8 (Int64) needle is inert (only Utf8 matches).
{
let orig = orig_isin_utf8(&mk_col(), &needles);
let cand = mk_col().isin(&needles).expect("isin");
assert_eq!(orig.dtype(), cand.dtype(), "dtype diverged");
assert_eq!(
orig.values.as_slice(),
cand.values.as_slice(),
"isin flags diverged"
);
let empty: Vec<Scalar> = Vec::new();
assert_eq!(
mk_col().isin(&empty).expect("isin empty").values.as_slice(),
orig_isin_utf8(&mk_col(), &empty).values.as_slice(),
"empty-needle isin diverged"
);
let mut mixed = needles.clone();
mixed.push(Scalar::Int64(42));
assert_eq!(
mk_col().isin(&mixed).expect("isin mixed").values.as_slice(),
cand.values.as_slice(),
"non-Utf8 needle was not inert"
);
}
for _ in 0..2 {
std::hint::black_box(orig_isin_utf8(&mk_col(), &needles));
std::hint::black_box(mk_col().isin(&needles).unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_isin_utf8(std::hint::black_box(&co), &needles));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).isin(&needles).unwrap());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).isin(&needles).unwrap());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!(
"AB utf8 isin (ONE binary, ONE invocation) N={N} distinct={DISTINCT} needles={NEEDLES}"
);
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic Key::Utf8 probe min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND contiguous &[u8] probe min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
#[allow(clippy::items_after_statements)]
mod ab_utf8_replace_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, Scalar};
/// Seeded (splitmix64) contiguous-Utf8 buffer: `n` rows drawn from `distinct`
/// fixed-width `"val_{:07}"` labels.
fn mk(n: usize, distinct: usize) -> (Vec<u8>, Vec<usize>) {
let mut s: u64 = 0x1234_5678_9ABC_DEF1;
let mut bytes: Vec<u8> = Vec::with_capacity(n * 11);
let mut offsets: Vec<usize> = Vec::with_capacity(n + 1);
offsets.push(0);
for _ in 0..n {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
let key = (z as usize) % distinct;
bytes.extend_from_slice(b"val_");
let mut buf = [0u8; 7];
let mut k = key;
for slot in buf.iter_mut().rev() {
*slot = b'0' + (k % 10) as u8;
k /= 10;
}
bytes.extend_from_slice(&buf);
offsets.push(bytes.len());
}
(bytes, offsets)
}
/// `count` (target, replacement) label pairs: `"val_{:07}"` -> `"REPL_{:05}"`
/// for keys `0..count` (targets are real labels present in `mk`).
fn pairs(count: usize) -> (Vec<Scalar>, Vec<Scalar>) {
let t = (0..count)
.map(|k| Scalar::Utf8(format!("val_{k:07}")))
.collect();
let r = (0..count)
.map(|k| Scalar::Utf8(format!("REPL_{k:05}")))
.collect();
(t, r)
}
/// Reference for the pre-lever generic path: force `Vec<Scalar::Utf8>`
/// materialization via `as_slice`, then the SHIPPED per-row O(k) linear
/// `semantic_eq` scan over targets (byte-for-byte the generic body, minus the
/// fast-path interception).
fn orig_replace_utf8(col: &Column, to_replace: &[Scalar], replacement: &[Scalar]) -> Column {
let scalars = col.values.as_slice();
let out: Vec<Scalar> = scalars
.iter()
.map(|v| {
for (target, rep) in to_replace.iter().zip(replacement.iter()) {
let matches = if target.is_missing() && v.is_missing() {
true
} else if target.is_missing() || v.is_missing() {
false
} else {
v.semantic_eq(target)
};
if matches {
return rep.clone();
}
}
v.clone()
})
.collect();
let inferred = super::infer_dtype(&out).unwrap_or(DType::Utf8);
Column::new(inferred, out).expect("replace out")
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_utf8_replace() {
const N: usize = 2_000_000;
const DISTINCT: usize = 50_000;
const K: usize = 10;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let (bytes, offsets) = mk(N, DISTINCT);
let mk_col = || Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
let (to_replace, replacement) = pairs(K);
// Parity: fast path == generic reference. Also: empty map = identity;
// a target NOT present leaves the column unchanged; duplicate targets are
// first-match-wins.
{
let orig = orig_replace_utf8(&mk_col(), &to_replace, &replacement);
let cand = mk_col()
.replace_values(&to_replace, &replacement)
.expect("replace");
assert_eq!(orig.dtype(), cand.dtype(), "dtype diverged");
assert_eq!(
orig.values.as_slice(),
cand.values.as_slice(),
"replace output diverged"
);
let empty: Vec<Scalar> = Vec::new();
assert_eq!(
mk_col()
.replace_values(&empty, &empty)
.expect("empty replace")
.values
.as_slice(),
mk_col().values.as_slice(),
"empty-map replace was not identity"
);
// Duplicate target, different replacements: first wins.
let dt = vec![
Scalar::Utf8("val_0000000".into()),
Scalar::Utf8("val_0000000".into()),
];
let dr = vec![Scalar::Utf8("FIRST".into()), Scalar::Utf8("SECOND".into())];
let cd = mk_col().replace_values(&dt, &dr).expect("dup replace");
let od = orig_replace_utf8(&mk_col(), &dt, &dr);
assert_eq!(
cd.values.as_slice(),
od.values.as_slice(),
"duplicate-target first-match-wins diverged"
);
}
for _ in 0..2 {
std::hint::black_box(orig_replace_utf8(&mk_col(), &to_replace, &replacement));
std::hint::black_box(mk_col().replace_values(&to_replace, &replacement).unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_replace_utf8(
std::hint::black_box(&co),
&to_replace,
&replacement,
));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c1)
.replace_values(&to_replace, &replacement)
.unwrap(),
);
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c2)
.replace_values(&to_replace, &replacement)
.unwrap(),
);
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB utf8 replace (ONE binary, ONE invocation) N={N} distinct={DISTINCT} k={K}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic O(k) semantic_eq scan min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND contiguous &[u8] map lookup min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_temporal_duplicated_ccfp {
use std::{process::Command, time::Instant};
use super::Column;
/// Seeded (splitmix64) Datetime64 ns: `n` rows drawn from `distinct` distinct
/// 1-second-spaced timestamps around a 2024 base (wide range => the wide
/// open-addressing dedup path, the realistic timestamp case). No `i64::MIN`.
fn ns(n: usize, distinct: i64) -> Vec<i64> {
const BASE: i64 = 1_700_000_000_000_000_000;
let mut s: u64 = 0x51ED_2701_A3B4_C5D6;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
BASE + (z % distinct as u64) as i64 * 1_000_000_000
})
.collect()
}
fn dt(v: Vec<i64>) -> Column {
Column::from_datetime64_values(v)
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_temporal_duplicated() {
const N: usize = 2_000_000;
const DISTINCT: i64 = 50_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let src = ns(N, DISTINCT);
// Parity 1: keep="first" flags == an independent first-seen reference over
// the raw ns (unambiguous ground truth for the generic Key path).
{
use super::FxHashSet;
let mut seen: FxHashSet<i64> = FxHashSet::default();
let expect: Vec<bool> = src.iter().map(|&v| !seen.insert(v)).collect();
let got = dt(src.clone()).duplicated_keep("first").expect("dup first");
let got_bools: Vec<bool> = got
.values
.as_slice()
.iter()
.map(|s| matches!(s, super::Scalar::Bool(true)))
.collect();
assert_eq!(got_bools, expect, "temporal first-seen flags diverged");
}
// Parity 2: all 3 policies match the conformance-verified Int64 path on the
// same raw ns (Bool output is dtype-independent).
for policy in ["first", "last", "false"] {
let temporal = dt(src.clone()).duplicated_keep(policy).expect("dt dup");
let as_i64 = Column::from_i64_values_owned(src.clone())
.duplicated_keep(policy)
.expect("i64 dup");
assert_eq!(
temporal.values.as_slice(),
as_i64.values.as_slice(),
"temporal vs i64 duplicated diverged (policy={policy})"
);
}
// ORIG timing: plant one NaT (i64::MIN) so the CAND no-NaT gate skips ->
// the generic Key path runs (measures the ACTUAL pre-lever cost).
let mut src_orig = src.clone();
src_orig[0] = i64::MIN;
for _ in 0..2 {
std::hint::black_box(dt(src_orig.clone()).duplicated_keep("first").unwrap());
std::hint::black_box(dt(src.clone()).duplicated_keep("first").unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = dt(src_orig.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&co).duplicated_keep("first").unwrap());
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = dt(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).duplicated_keep("first").unwrap());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = dt(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).duplicated_keep("first").unwrap());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!(
"AB temporal duplicated keep=first (ONE binary, ONE invocation) N={N} distinct={DISTINCT}"
);
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic Key::Datetime64 flags min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND raw-i64 ns dedup flags min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_temporal_nunique_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, Scalar};
/// Seeded (splitmix64) Datetime64 ns: `n` rows drawn from `distinct` distinct
/// 1-second-spaced timestamps around a 2024 base (wide range => the wide
/// open-addressing `count_distinct_i64_wide` path). No `i64::MIN`.
fn ns(n: usize, distinct: i64) -> Vec<i64> {
const BASE: i64 = 1_700_000_000_000_000_000;
let mut s: u64 = 0x2C1B_3A9F_77E0_6D15;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
BASE + (z % distinct as u64) as i64 * 1_000_000_000
})
.collect()
}
fn dt(v: Vec<i64>) -> Column {
Column::from_datetime64_values(v)
}
fn as_i64(s: &Scalar) -> i64 {
match s {
Scalar::Int64(v) => *v,
other => panic!("expected Int64, got {other:?}"),
}
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_temporal_nunique() {
const N: usize = 2_000_000;
const DISTINCT: i64 = 50_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let src = ns(N, DISTINCT);
// Parity: temporal count == ground-truth distinct == Int64-column nunique
// (conformance-verified), and both dropna values agree for all-valid.
{
use super::FxHashSet;
let expect = src.iter().copied().collect::<FxHashSet<i64>>().len() as i64;
assert_eq!(
expect,
as_i64(&dt(src.clone()).nunique()),
"temporal nunique diverged"
);
assert_eq!(
expect,
as_i64(&Column::from_i64_values_owned(src.clone()).nunique()),
"temporal vs i64 nunique diverged"
);
assert_eq!(
expect,
as_i64(&dt(src.clone()).nunique_with_dropna(false)),
"temporal nunique(dropna=false) diverged"
);
}
// ORIG timing: plant one NaT (i64::MIN) so the CAND no-NaT gate skips ->
// the generic `nannunique` (materialize) path runs.
let mut src_orig = src.clone();
src_orig[0] = i64::MIN;
for _ in 0..2 {
std::hint::black_box(dt(src_orig.clone()).nunique());
std::hint::black_box(dt(src.clone()).nunique());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = dt(src_orig.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&co).nunique());
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = dt(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).nunique());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = dt(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).nunique());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB temporal nunique (ONE binary, ONE invocation) N={N} distinct={DISTINCT}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic nannunique count min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND raw-i64 ns distinct count min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_temporal_mode_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, ValidityMask};
/// Seeded (splitmix64) Datetime64 ns: `n` rows drawn from `distinct` distinct
/// 1-second-spaced timestamps around a 2024 base (wide range => `mode_i64_wide`
/// open-addressing path). No `i64::MIN`.
fn ns(n: usize, distinct: i64) -> Vec<i64> {
const BASE: i64 = 1_700_000_000_000_000_000;
let mut s: u64 = 0x7F4A_2C19_A3D0_51EB;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
BASE + (z % distinct as u64) as i64 * 1_000_000_000
})
.collect()
}
fn dt(v: Vec<i64>) -> Column {
Column::from_datetime64_values(v)
}
/// Independent ground-truth mode over raw ns: max-count values, ascending.
fn ground_truth_mode(data: &[i64]) -> Vec<i64> {
use super::FxHashMap;
let mut counts: FxHashMap<i64, u64> = FxHashMap::default();
for &v in data {
*counts.entry(v).or_insert(0) += 1;
}
let max_c = counts.values().copied().max().unwrap_or(0);
let mut w: Vec<i64> = counts
.iter()
.filter_map(|(&k, &c)| (c == max_c).then_some(k))
.collect();
w.sort_unstable();
w
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_temporal_mode() {
const N: usize = 2_000_000;
const DISTINCT: i64 = 50_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let src = ns(N, DISTINCT);
// Parity: Datetime64 mode winners (ns) == ground truth AND == the
// conformance-verified Int64-column mode. Timedelta64 re-tag branch too.
{
let expect = ground_truth_mode(&src);
let dt_mode = dt(src.clone()).mode().expect("dt mode");
assert_eq!(
dt_mode.as_datetime64_slice().expect("dt64 winners"),
expect.as_slice(),
"datetime mode diverged from ground truth"
);
assert_eq!(
dt_mode.as_datetime64_slice().expect("dt64 winners"),
Column::from_i64_values_owned(src.clone())
.mode()
.expect("i64 mode")
.as_i64_slice()
.expect("i64 winners"),
"datetime vs i64 mode diverged"
);
let td = Column::from_timedelta64_values_with_validity(
src.clone(),
ValidityMask::all_valid(src.len()),
);
assert_eq!(
td.mode()
.expect("td mode")
.as_timedelta64_slice()
.expect("td winners"),
expect.as_slice(),
"timedelta mode diverged from ground truth"
);
}
// ORIG timing: plant one NaT (i64::MIN) so the CAND no-NaT gate skips ->
// the generic Key path (materialize) runs.
let mut src_orig = src.clone();
src_orig[0] = i64::MIN;
for _ in 0..2 {
std::hint::black_box(dt(src_orig.clone()).mode().unwrap());
std::hint::black_box(dt(src.clone()).mode().unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = dt(src_orig.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&co).mode().unwrap());
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = dt(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).mode().unwrap());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = dt(src.clone());
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).mode().unwrap());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB temporal mode (ONE binary, ONE invocation) N={N} distinct={DISTINCT}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic Key::Datetime64 tally min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND raw-i64 ns mode + re-tag min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_f64_median_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, Scalar, nanmedian};
/// Seeded (splitmix64) finite f64 values in [0, 1e6).
fn f64s(n: usize) -> Vec<f64> {
let mut s: u64 = 0x9B1D_2E4C_75A0_31F7;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
(z >> 11) as f64 / (1u64 << 53) as f64 * 1.0e6
})
.collect()
}
/// Exact pre-lever path: materialize the Scalars then `nanmedian`.
fn orig_median(col: &Column) -> Scalar {
nanmedian(col.values.as_slice())
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_f64_median() {
const N: usize = 4_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let src = f64s(N);
let mk_col = || Column::from_f64_values(src.clone());
// Parity: fast path == the exact Scalar `nanmedian` path (odd AND even n),
// plus the empty column.
{
let a = orig_median(&mk_col());
let b = mk_col().median();
assert_eq!(a, b, "median diverged (even n)");
let odd: Vec<f64> = src[..N - 1].to_vec();
let ao = nanmedian(Column::from_f64_values(odd.clone()).values.as_slice());
let bo = Column::from_f64_values(odd).median();
assert_eq!(ao, bo, "median diverged (odd n)");
let ae = nanmedian(Column::from_f64_values(Vec::new()).values.as_slice());
let be = Column::from_f64_values(Vec::new()).median();
assert_eq!(ae, be, "empty median diverged");
}
for _ in 0..2 {
std::hint::black_box(orig_median(&mk_col()));
std::hint::black_box(mk_col().median());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_median(std::hint::black_box(&co)));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).median());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).median());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB f64 median (ONE binary, ONE invocation) N={N}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nanmedian(Vec<Scalar>) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND typed &[f64] select min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_count_distinct_radix_ccfp {
use std::{process::Command, time::Instant};
use super::{
count_distinct_i64_radix, count_distinct_i64_singletable, count_distinct_i64_wide,
};
/// Seeded (splitmix64) i64. `distinct == 0` => ~all-distinct raw stream
/// (i64::MIN remapped to 0); otherwise values in `0..distinct`.
fn mkdata(n: usize, distinct: u64) -> Vec<i64> {
let mut s: u64 = 0xA5A5_1234_DEAD_BEEF;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
if distinct == 0 {
let v = z as i64;
if v == i64::MIN { 0 } else { v }
} else {
(z % distinct) as i64
}
})
.collect()
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_count_distinct_radix() {
const N: usize = 8_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let src = mkdata(N, 0); // ~all-distinct: worst case for the single table
// Parity: radix == single-table across distributions incl. a planted
// i64::MIN sentinel and a moderate-cardinality case.
{
let base = count_distinct_i64_singletable(&src);
assert_eq!(
count_distinct_i64_radix(&src),
base,
"radix vs single (all-distinct)"
);
assert_eq!(
count_distinct_i64_wide(&src),
base,
"dispatch vs single (all-distinct)"
);
let moderate = mkdata(N, 100_000);
let base_m = count_distinct_i64_singletable(&moderate);
assert_eq!(
count_distinct_i64_radix(&moderate),
base_m,
"radix vs single (moderate)"
);
assert_eq!(
count_distinct_i64_wide(&moderate),
base_m,
"dispatch vs single (moderate)"
);
let mut with_nat = src.clone();
with_nat[0] = i64::MIN;
with_nat[1] = i64::MIN;
let base_n = count_distinct_i64_singletable(&with_nat);
assert_eq!(
count_distinct_i64_radix(&with_nat),
base_n,
"radix vs single (sentinel)"
);
assert_eq!(
count_distinct_i64_wide(&with_nat),
base_n,
"dispatch vs single (sentinel)"
);
assert_eq!(count_distinct_i64_radix(&[]), 0, "empty radix");
}
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let measure = |data: &[i64]| {
for _ in 0..2 {
std::hint::black_box(count_distinct_i64_singletable(std::hint::black_box(data)));
std::hint::black_box(count_distinct_i64_wide(std::hint::black_box(data)));
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let t0 = Instant::now();
std::hint::black_box(count_distinct_i64_singletable(std::hint::black_box(
data,
)));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let t0 = Instant::now();
std::hint::black_box(count_distinct_i64_wide(std::hint::black_box(data)));
let a = t0.elapsed().as_secs_f64() * 1e3;
let t0 = Instant::now();
std::hint::black_box(count_distinct_i64_wide(std::hint::black_box(data)));
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
(
min_of(&orig),
min_of(&cand),
median_of(&null),
cv_of(&orig),
cv_of(&cand),
)
};
let lowcard = mkdata(N, 1000);
println!("AB count_distinct radix (ONE binary, ONE invocation) N={N}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
for (label, data) in [
("~all-distinct (HIGH card)", src.as_slice()),
("1000 distinct (LOW card)", lowcard.as_slice()),
] {
let (o, c, nullmed, cvo, cvc) = measure(data);
println!(" --- {label} ---");
println!(" ORIG single-table 2n probe min={o:8.3} ms cv={cvo:.2}%");
println!(" CAND dispatch (radix|single) min={c:8.3} ms cv={cvc:.2}%");
println!(
" NULL floor={:.2}% ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
100.0 * (nullmed - 1.0),
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
}
#[cfg(test)]
mod ab_f64_quantile_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, Scalar, nanquantile};
/// Seeded (splitmix64) finite f64 values in [0, 1e6).
fn f64s(n: usize) -> Vec<f64> {
let mut s: u64 = 0x3C79_9A1B_D45E_2F08;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
(z >> 11) as f64 / (1u64 << 53) as f64 * 1.0e6
})
.collect()
}
fn orig_quantile(col: &Column, q: f64) -> Scalar {
nanquantile(col.values.as_slice(), q)
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_f64_quantile() {
const N: usize = 4_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let src = f64s(N);
let mk_col = || Column::from_f64_values(src.clone());
// Parity: fast path == the exact Scalar `nanquantile` path across q
// (interpolating + boundary + out-of-range), n==1, and empty.
{
for &q in &[0.0_f64, 0.25, 0.5, 0.75, 0.9, 1.0, -0.1, 1.5] {
assert_eq!(
orig_quantile(&mk_col(), q),
mk_col().quantile(q),
"quantile diverged at q={q}"
);
}
let one = Column::from_f64_values(vec![42.0]);
assert_eq!(
nanquantile(one.values.as_slice(), 0.3),
one.quantile(0.3),
"n=1"
);
let empty = Column::from_f64_values(Vec::new());
assert_eq!(
nanquantile(empty.values.as_slice(), 0.5),
empty.quantile(0.5),
"empty quantile diverged"
);
}
const Q: f64 = 0.25;
for _ in 0..2 {
std::hint::black_box(orig_quantile(&mk_col(), Q));
std::hint::black_box(mk_col().quantile(Q));
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_quantile(std::hint::black_box(&co), Q));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).quantile(Q));
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).quantile(Q));
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB f64 quantile q={Q} (ONE binary, ONE invocation) N={N}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nanquantile(Vec<Scalar>) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND typed &[f64] select min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_bool_sum_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, Scalar, nansum};
/// Seeded (splitmix64) bools, ~50% true.
fn bools(n: usize) -> Vec<bool> {
let mut s: u64 = 0x6D5F_11C3_A780_2E9B;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
z & 1 == 0
})
.collect()
}
fn orig_sum(col: &Column) -> Scalar {
nansum(col.values.as_slice())
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_bool_sum() {
const N: usize = 8_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let src = bools(N);
let mk_col = || Column::from_bool_values(src.clone());
// Parity: fast path == the exact Scalar `nansum` path (mixed, all-true,
// all-false, empty).
{
assert_eq!(
orig_sum(&mk_col()),
mk_col().sum(),
"bool sum diverged (mixed)"
);
for &b in &[true, false] {
let c = Column::from_bool_values(vec![b; 1000]);
assert_eq!(
nansum(c.values.as_slice()),
c.sum(),
"bool sum diverged (all-{b})"
);
}
let empty = Column::from_bool_values(Vec::new());
assert_eq!(
nansum(empty.values.as_slice()),
empty.sum(),
"bool sum diverged (empty)"
);
}
for _ in 0..2 {
std::hint::black_box(orig_sum(&mk_col()));
std::hint::black_box(mk_col().sum());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_sum(std::hint::black_box(&co)));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).sum());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).sum());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB bool sum (ONE binary, ONE invocation) N={N}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nansum(Vec<Scalar>) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND typed &[bool] count min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_bool_anyall_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, Scalar, nanall, nanany};
/// Seeded (splitmix64) bools, ~50% true.
fn bools(n: usize) -> Vec<bool> {
let mut s: u64 = 0x6D5F_11C3_A780_2E9B;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
z & 1 == 0
})
.collect()
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_bool_anyall_parity() {
// Fast path == the exact Scalar nan* path across regimes, for both
// any and all. as_bool_slice is Some only for an all-valid column, so
// the typed .any()/.all() over &[bool] is exactly nanany/nanall.
let mixed = Column::from_bool_values(bools(10_000));
assert_eq!(nanany(mixed.values.as_slice()), mixed.any(), "any mixed");
assert_eq!(nanall(mixed.values.as_slice()), mixed.all(), "all mixed");
for &b in &[true, false] {
let c = Column::from_bool_values(vec![b; 1000]);
assert_eq!(nanany(c.values.as_slice()), c.any(), "any all-{b}");
assert_eq!(nanall(c.values.as_slice()), c.all(), "all all-{b}");
}
let empty = Column::from_bool_values(Vec::new());
assert_eq!(nanany(empty.values.as_slice()), empty.any(), "any empty");
assert_eq!(nanall(empty.values.as_slice()), empty.all(), "all empty");
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_bool_all_alltrue() {
// Worst-case (no early exit) regime: `all` over an all-true column must
// scan every element -- the realistic "does this predicate hold for
// every row" validation case. `any` over an all-false column is
// symmetric. Mixed data early-exits on BOTH paths (no change, no
// regression), so it is not the interesting measurement.
const N: usize = 8_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let mk_col = || Column::from_bool_values(vec![true; N]);
let orig_all = |c: &Column| nanall(c.values.as_slice());
for _ in 0..2 {
std::hint::black_box(orig_all(&mk_col()));
std::hint::black_box(mk_col().all());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_all(std::hint::black_box(&co)));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).all());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).all());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB bool all (all-true, no early exit; ONE binary, ONE invocation) N={N}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nanall(Vec<Scalar>) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND typed &[bool] all min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_dt_isin_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, FxHashSet, Scalar};
/// Seeded (splitmix64) non-negative i64 ns spread across a wide range (well
/// beyond 2^24, so the dense Int64 bitset never applies for the Int64 twin).
fn ns_values(n: usize) -> Vec<i64> {
let mut s: u64 = 0xA13F_C9E7_5B02_16DD;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
(z >> 1) as i64
})
.collect()
}
/// Faithful replica of the pre-change generic isin path for a Datetime64
/// column: materialize `values.as_slice()` (Vec<Scalar::Datetime64>) then
/// probe per-Scalar and build a Vec<Scalar::Bool> output.
fn orig_isin_dt(col: &Column, needles: &[Scalar]) -> Column {
let mut lookup: FxHashSet<i64> = FxHashSet::default();
for n in needles {
if let Scalar::Datetime64(v) = n {
lookup.insert(*v);
}
}
let scalars = col.values.as_slice();
let out: Vec<Scalar> = scalars
.iter()
.map(|v| {
Scalar::Bool(match v {
Scalar::Datetime64(x) => lookup.contains(x),
_ => false,
})
})
.collect();
Column::new(DType::Bool, out).expect("bool")
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_isin_i64_parity() {
let vals = ns_values(20_000);
// (1) Datetime64: fast path == the generic reference across present +
// absent needles, empty needles (all false), and an Int64 needle (inert
// against a Datetime64 value -- dtype-tagged keys never cross).
let dt = || Column::from_datetime64_values(vals.clone());
let mut needles: Vec<Scalar> = vals
.iter()
.step_by(7)
.take(1000)
.map(|&v| Scalar::Datetime64(v))
.collect();
needles.extend((0..500).map(|k| Scalar::Datetime64(-(k as i64) - 1))); // absent
assert_eq!(
orig_isin_dt(&dt(), &needles).values.as_slice(),
dt().isin(&needles).expect("isin").values.as_slice(),
"dt isin diverged"
);
let empty: Vec<Scalar> = Vec::new();
assert_eq!(
orig_isin_dt(&dt(), &empty).values.as_slice(),
dt().isin(&empty).expect("isin").values.as_slice(),
"dt isin empty diverged"
);
let int_needle = vec![Scalar::Int64(vals[0])];
assert_eq!(
orig_isin_dt(&dt(), &int_needle).values.as_slice(),
dt().isin(&int_needle).expect("isin").values.as_slice(),
"dt isin int-needle-inert diverged"
);
// (2) Wide-range Int64 (span > 2^24, so the dense bitset falls through to
// the i64-hashset path) matches a direct i64-set membership truth.
let int_col = || Column::from_i64_values(vals.clone());
let int_needles: Vec<Scalar> = vals
.iter()
.step_by(7)
.take(1000)
.map(|&v| Scalar::Int64(v))
.collect();
let set: FxHashSet<i64> = int_needles
.iter()
.filter_map(|n| match n {
Scalar::Int64(v) => Some(*v),
_ => None,
})
.collect();
let truth: Vec<bool> = vals.iter().map(|v| set.contains(v)).collect();
let cand = int_col().isin(&int_needles).expect("isin");
let cand_bools: Vec<bool> = cand
.values
.as_slice()
.iter()
.map(|s| matches!(s, Scalar::Bool(true)))
.collect();
assert_eq!(truth, cand_bools, "wide-int64 isin diverged");
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_dt_isin() {
const N: usize = 8_000_000;
const NEEDLES: usize = 5_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let vals = ns_values(N);
let mk_col = || Column::from_datetime64_values(vals.clone());
// ~NEEDLES present needles sampled across the column.
let needles: Vec<Scalar> = vals
.iter()
.step_by(N / NEEDLES)
.map(|&v| Scalar::Datetime64(v))
.collect();
// Parity guard inside the perf run too.
assert_eq!(
orig_isin_dt(&mk_col(), &needles).values.as_slice(),
mk_col().isin(&needles).expect("isin").values.as_slice(),
"dt isin diverged (perf parity)"
);
for _ in 0..2 {
std::hint::black_box(orig_isin_dt(&mk_col(), &needles));
std::hint::black_box(mk_col().isin(&needles).unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_isin_dt(std::hint::black_box(&co), &needles));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).isin(&needles).unwrap());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).isin(&needles).unwrap());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB dt isin (ONE binary, ONE invocation) N={N} needles={NEEDLES}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic Vec<Scalar> probe min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND typed &[i64] FxHashSet min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_i64_median_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, Scalar, nanmedian};
/// Seeded (splitmix64) non-negative i64 spread.
fn i64s(n: usize) -> Vec<i64> {
let mut s: u64 = 0x2545_F491_4F6C_DD1D;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
(z >> 1) as i64
})
.collect()
}
fn orig_median(col: &Column) -> Scalar {
nanmedian(col.values.as_slice())
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_i64_median_parity() {
// Typed i64 path == the exact Scalar nanmedian across even/odd/empty
// sizes. `nanmedian`'s numeric arm is collect_finite(v as f64) -> the same
// select_nth, so an all-valid i64 buffer converted the same way matches.
for n in [0usize, 1, 2, 3, 4, 5, 999, 1000, 4097] {
let c = Column::from_i64_values(i64s(n));
assert_eq!(orig_median(&c), c.median(), "i64 median diverged n={n}");
}
// Large-magnitude (> 2^53) confirms the i64->f64 conversion is IDENTICALLY
// lossy on both sides (both use `as f64`), so the order statistics agree.
let big = vec![
i64::MAX,
i64::MAX - 1,
1 << 60,
(1 << 60) + 1,
-(1 << 60),
0,
-5,
];
let c = Column::from_i64_values(big);
assert_eq!(
orig_median(&c),
c.median(),
"i64 median diverged (large-magnitude)"
);
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_i64_median() {
const N: usize = 4_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let src = i64s(N);
let mk_col = || Column::from_i64_values(src.clone());
for _ in 0..2 {
std::hint::black_box(orig_median(&mk_col()));
std::hint::black_box(mk_col().median());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_median(std::hint::black_box(&co)));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).median());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).median());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB i64 median (ONE binary, ONE invocation) N={N}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nanmedian(Vec<Scalar>) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND typed &[i64]->f64 select min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_i64_quantile_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, Scalar, nanquantile};
/// Seeded (splitmix64) non-negative i64 spread.
fn i64s(n: usize) -> Vec<i64> {
let mut s: u64 = 0x9E37_79B9_7F4A_7C15;
(0..n)
.map(|_| {
s = s.wrapping_add(0x2545_F491_4F6C_DD1D);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
(z >> 1) as i64
})
.collect()
}
fn orig_q(col: &Column, q: f64) -> Scalar {
nanquantile(col.values.as_slice(), q)
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_i64_quantile_parity() {
let qs = [0.0, 0.25, 0.5, 0.75, 0.9, 1.0, -0.1, 1.5];
// Typed i64 path == the exact Scalar nanquantile across interpolating +
// boundary + out-of-range q, over even/odd/empty/n==1 sizes.
for n in [0usize, 1, 2, 3, 4, 5, 999, 1000, 4097] {
let c = Column::from_i64_values(i64s(n));
for &q in &qs {
assert_eq!(
orig_q(&c, q),
c.quantile(q),
"i64 quantile diverged n={n} q={q}"
);
}
}
// Large-magnitude (> 2^53) confirms identically-lossy i64->f64 on both
// sides, so the interpolated order statistics agree.
let big = vec![
i64::MAX,
i64::MAX - 1,
1 << 60,
(1 << 60) + 1,
-(1 << 60),
0,
-5,
];
let c = Column::from_i64_values(big);
for &q in &qs {
assert_eq!(
orig_q(&c, q),
c.quantile(q),
"i64 quantile diverged (large-magnitude) q={q}"
);
}
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_i64_quantile() {
const N: usize = 4_000_000;
const Q: f64 = 0.25;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let src = i64s(N);
let mk_col = || Column::from_i64_values(src.clone());
for _ in 0..2 {
std::hint::black_box(orig_q(&mk_col(), Q));
std::hint::black_box(mk_col().quantile(Q));
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_q(std::hint::black_box(&co), Q));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).quantile(Q));
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).quantile(Q));
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB i64 quantile (ONE binary, ONE invocation) N={N} q={Q}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nanquantile(Vec<Scalar>) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND typed &[i64]->f64 select min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_utf8_minmax_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, Scalar, nanmax, nanmin};
/// Seeded (splitmix64) contiguous-Utf8 buffer: `n` rows drawn from `distinct`
/// fixed-width `"val_{:07}"` labels.
fn mk(n: usize, distinct: usize) -> (Vec<u8>, Vec<usize>) {
let mut s: u64 = 0x1234_5678_9ABC_DEF1;
let mut bytes: Vec<u8> = Vec::with_capacity(n * 11);
let mut offsets: Vec<usize> = Vec::with_capacity(n + 1);
offsets.push(0);
for _ in 0..n {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
let key = (z as usize) % distinct;
bytes.extend_from_slice(b"val_");
let mut buf = [0u8; 7];
let mut k = key;
for slot in buf.iter_mut().rev() {
*slot = b'0' + (k % 10) as u8;
k /= 10;
}
bytes.extend_from_slice(&buf);
offsets.push(bytes.len());
}
(bytes, offsets)
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_utf8_minmax_parity() {
// Byte-span min/max == the exact Scalar nanmin/nanmax across a populated
// column (with ties + first-seen tie-break), a single element, and empty
// (no spans → falls through to nanmin/nanmax → Null).
let (b, o) = mk(10_000, 500);
let c = Column::from_utf8_contiguous(b, o);
assert_eq!(nanmin(c.values.as_slice()), c.min(), "utf8 min diverged");
assert_eq!(nanmax(c.values.as_slice()), c.max(), "utf8 max diverged");
let (b1, o1) = mk(1, 1);
let c1 = Column::from_utf8_contiguous(b1, o1);
assert_eq!(nanmin(c1.values.as_slice()), c1.min(), "utf8 min single");
assert_eq!(nanmax(c1.values.as_slice()), c1.max(), "utf8 max single");
let empty = Column::from_utf8_contiguous(Vec::new(), vec![0]);
assert_eq!(
nanmin(empty.values.as_slice()),
empty.min(),
"utf8 min empty"
);
assert_eq!(
nanmax(empty.values.as_slice()),
empty.max(),
"utf8 max empty"
);
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_utf8_min() {
const N: usize = 4_000_000;
const DISTINCT: usize = 100_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let (bytes, offsets) = mk(N, DISTINCT);
let mk_col = || Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
let orig_min = |c: &Column| nanmin(c.values.as_slice());
// Parity guard inside the perf run too.
assert_eq!(
orig_min(&mk_col()),
mk_col().min(),
"utf8 min diverged (perf)"
);
for _ in 0..2 {
std::hint::black_box(orig_min(&mk_col()));
std::hint::black_box(mk_col().min());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_min(std::hint::black_box(&co)));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).min());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).min());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB utf8 min (ONE binary, ONE invocation) N={N} distinct={DISTINCT}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nanmin(Vec<Scalar::Utf8>) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND byte-span min min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_td_argminmax_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, ValidityMask, nanargmax, nanargmin};
/// Seeded (splitmix64) non-negative i64 ns in `[0, span)` (never `i64::MIN`),
/// so ties exist to exercise the first-on-tie rule.
fn ns_values(n: usize, span: i64) -> Vec<i64> {
let mut s: u64 = 0x0F0F_1E2D_3C4B_5A69;
(0..n)
.map(|_| {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
((z >> 1) as i64) % span
})
.collect()
}
fn td_col(ns: Vec<i64>) -> Column {
let len = ns.len();
Column::from_timedelta64_values_with_validity(ns, ValidityMask::all_valid(len))
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_td_argminmax_parity() {
// Typed i64 argmin/argmax == the exact Scalar nanargmin/nanargmax across a
// populated column (with ties → first-on-tie), a single element, and empty
// (→ None), for BOTH ops.
let c = td_col(ns_values(10_000, 500));
assert_eq!(
nanargmin(c.values.as_slice()),
c.argmin(),
"td argmin diverged"
);
assert_eq!(
nanargmax(c.values.as_slice()),
c.argmax(),
"td argmax diverged"
);
// Explicit ties: min (10) and max (99) each appear twice; first wins.
let ties = td_col(vec![50, 10, 99, 10, 99, 30]);
assert_eq!(
nanargmin(ties.values.as_slice()),
ties.argmin(),
"td argmin ties"
);
assert_eq!(
nanargmax(ties.values.as_slice()),
ties.argmax(),
"td argmax ties"
);
let single = td_col(vec![7]);
assert_eq!(
nanargmin(single.values.as_slice()),
single.argmin(),
"td argmin single"
);
assert_eq!(
nanargmax(single.values.as_slice()),
single.argmax(),
"td argmax single"
);
let empty = td_col(Vec::new());
assert_eq!(
nanargmin(empty.values.as_slice()),
empty.argmin(),
"td argmin empty"
);
assert_eq!(
nanargmax(empty.values.as_slice()),
empty.argmax(),
"td argmax empty"
);
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_td_argmin() {
const N: usize = 8_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let ns = ns_values(N, 1_000_000);
let mk_col = || td_col(ns.clone());
let orig_argmin = |c: &Column| nanargmin(c.values.as_slice());
// Parity guard inside the perf run too.
assert_eq!(
orig_argmin(&mk_col()),
mk_col().argmin(),
"td argmin diverged (perf)"
);
for _ in 0..2 {
std::hint::black_box(orig_argmin(&mk_col()));
std::hint::black_box(mk_col().argmin());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_argmin(std::hint::black_box(&co)));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).argmin());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).argmin());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB td argmin (ONE binary, ONE invocation) N={N}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nanargmin(Vec<Scalar>) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND typed &[i64] scan min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_utf8_searchsorted_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, Scalar};
/// SORTED contiguous-Utf8 buffer of fixed-width `"val_{:07}"` labels for
/// `0..n` (zero-padded ⇒ lexicographically sorted, searchsorted's precondition).
fn sorted_utf8(n: usize) -> (Vec<u8>, Vec<usize>) {
let mut bytes = Vec::with_capacity(n * 11);
let mut offsets = Vec::with_capacity(n + 1);
offsets.push(0);
for i in 0..n {
bytes.extend_from_slice(b"val_");
let mut buf = [0u8; 7];
let mut k = i;
for slot in buf.iter_mut().rev() {
*slot = b'0' + (k % 10) as u8;
k /= 10;
}
bytes.extend_from_slice(&buf);
offsets.push(bytes.len());
}
(bytes, offsets)
}
/// Faithful replica of the pre-lever generic path: per-needle
/// `searchsorted_position` (forces the whole `Vec<Scalar::Utf8>` via
/// `&self.values[mid]`), then a Vec<Scalar::Int64> position column.
fn orig_ss(col: &Column, needles: &[Scalar], side: &str) -> Column {
let positions: Vec<Scalar> = needles
.iter()
.map(|needle| col.searchsorted_position(needle, side, None))
.map(|r| r.map(|p| Scalar::Int64(p as i64)))
.collect::<Result<Vec<_>, _>>()
.expect("searchsorted");
Column::new(DType::Int64, positions).expect("int64 col")
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_utf8_searchsorted_parity() {
// Typed byte-span binary search == generic searchsorted_position for
// BOTH sides across before-first / present-first / present-mid /
// present-last / after-last / after-all needles, plus empty needles.
let (b, o) = sorted_utf8(10_000);
let col = || Column::from_utf8_contiguous(b.clone(), o.clone());
let needles: Vec<Scalar> = [
"aaa",
"val_0000000",
"val_0005000",
"val_0009999",
"val_0010000",
"zzz",
]
.iter()
.map(|s| Scalar::Utf8((*s).to_string()))
.collect();
for side in ["left", "right"] {
assert_eq!(
orig_ss(&col(), &needles, side).values.as_slice(),
col()
.searchsorted_values(&needles, side)
.expect("ss")
.values
.as_slice(),
"utf8 searchsorted diverged side={side}"
);
}
let empty: Vec<Scalar> = Vec::new();
assert_eq!(
orig_ss(&col(), &empty, "left").values.as_slice(),
col()
.searchsorted_values(&empty, "left")
.expect("ss")
.values
.as_slice(),
"utf8 searchsorted empty-needles diverged"
);
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_utf8_searchsorted() {
const N: usize = 4_000_000;
const NEEDLES: usize = 1_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let (bytes, offsets) = sorted_utf8(N);
let mk_col = || Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
let needles: Vec<Scalar> = (0..NEEDLES)
.map(|j| Scalar::Utf8(format!("val_{:07}", j * (N / NEEDLES))))
.collect();
// Parity guard inside the perf run too.
assert_eq!(
orig_ss(&mk_col(), &needles, "left").values.as_slice(),
mk_col()
.searchsorted_values(&needles, "left")
.unwrap()
.values
.as_slice(),
"utf8 searchsorted diverged (perf)"
);
for _ in 0..2 {
std::hint::black_box(orig_ss(&mk_col(), &needles, "left"));
std::hint::black_box(mk_col().searchsorted_values(&needles, "left").unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_ss(std::hint::black_box(&co), &needles, "left"));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c1)
.searchsorted_values(&needles, "left")
.unwrap(),
);
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c2)
.searchsorted_values(&needles, "left")
.unwrap(),
);
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB utf8 searchsorted (ONE binary, ONE invocation) N={N} needles={NEEDLES}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic Vec<Scalar> bsearch min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND byte-span bsearch min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_f64_searchsorted_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, Scalar};
/// SORTED all-valid Float64 column `[0.0, 1.0, ..., (n-1) as f64]` — the
/// searchsorted precondition — with the `LazyAllValidFloat64` backing that
/// `as_f64_slice()` returns.
fn sorted_f64(n: usize) -> Column {
let data: Vec<f64> = (0..n).map(|i| i as f64).collect();
Column::from_f64_values_owned(data)
}
/// Faithful replica of the pre-lever generic path: per-needle
/// `searchsorted_position` (accesses `&self.values[mid]`, forcing the whole
/// `Vec<Scalar::Float64>` via `as_slice`'s `get_or_init`), then an Int64
/// position column.
fn orig_ss(col: &Column, needles: &[Scalar], side: &str) -> Column {
let positions: Vec<Scalar> = needles
.iter()
.map(|needle| col.searchsorted_position(needle, side, None))
.map(|r| r.map(|p| Scalar::Int64(p as i64)))
.collect::<Result<Vec<_>, _>>()
.expect("searchsorted");
Column::new(DType::Int64, positions).expect("int64 col")
}
/// Non-panicking sibling of `orig_ss`: propagates the first per-needle error
/// (used to assert the generic path errors on a missing/NaN needle).
fn orig_ss_result(
col: &Column,
needles: &[Scalar],
side: &str,
) -> Result<(), super::ColumnError> {
for needle in needles {
col.searchsorted_position(needle, side, None)?;
}
Ok(())
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_f64_searchsorted_parity() {
// Typed partition_point == generic searchsorted_position for BOTH sides
// across before-first / present-first / present-mid (exact) / just-below /
// just-above / present-last / after-last needles, plus empty needles.
let col = || sorted_f64(10_000);
let needles: Vec<Scalar> = [-1.0, 0.0, 4999.0, 4999.5, 5000.5, 9999.0, 10_000.0]
.iter()
.map(|v| Scalar::Float64(*v))
.collect();
for side in ["left", "right"] {
assert_eq!(
orig_ss(&col(), &needles, side).values.as_slice(),
col()
.searchsorted_values(&needles, side)
.expect("ss")
.values
.as_slice(),
"f64 searchsorted diverged side={side}"
);
}
// A NaN needle is MISSING: the typed guard EXCLUDES it, so the whole batch
// falls through to the generic comparator, which errors ValueIsMissing --
// exactly as the per-needle generic does. (Were NaN NOT excluded, the typed
// partition_point would silently return 0 instead of erroring: divergence.)
let with_nan = vec![Scalar::Float64(5000.0), Scalar::Float64(f64::NAN)];
for side in ["left", "right"] {
assert!(
col().searchsorted_values(&with_nan, side).is_err(),
"f64 searchsorted must error on NaN needle side={side}"
);
assert!(
orig_ss_result(&col(), &with_nan, side).is_err(),
"generic must also error on NaN needle side={side}"
);
}
let empty: Vec<Scalar> = Vec::new();
assert_eq!(
orig_ss(&col(), &empty, "left").values.as_slice(),
col()
.searchsorted_values(&empty, "left")
.expect("ss")
.values
.as_slice(),
"f64 searchsorted empty-needles diverged"
);
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_f64_searchsorted() {
const N: usize = 4_000_000;
const NEEDLES: usize = 1_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let mk_col = || sorted_f64(N);
let needles: Vec<Scalar> = (0..NEEDLES)
.map(|j| Scalar::Float64((j * (N / NEEDLES)) as f64))
.collect();
// Parity guard inside the perf run too.
assert_eq!(
orig_ss(&mk_col(), &needles, "left").values.as_slice(),
mk_col()
.searchsorted_values(&needles, "left")
.unwrap()
.values
.as_slice(),
"f64 searchsorted diverged (perf)"
);
for _ in 0..2 {
std::hint::black_box(orig_ss(&mk_col(), &needles, "left"));
std::hint::black_box(mk_col().searchsorted_values(&needles, "left").unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_ss(std::hint::black_box(&co), &needles, "left"));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c1)
.searchsorted_values(&needles, "left")
.unwrap(),
);
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c2)
.searchsorted_values(&needles, "left")
.unwrap(),
);
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB f64 searchsorted (ONE binary, ONE invocation) N={N} needles={NEEDLES}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic Vec<Scalar> bsearch min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND partition_point &[f64] min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_td64_searchsorted_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, Scalar, ValidityMask};
/// SORTED all-valid Timedelta64 column `[0, 1, ..., n-1]` ns (no NaT, the
/// searchsorted precondition) with the `LazyAllValidTimedelta64Vec` backing
/// that `as_timedelta64_slice()` returns.
fn sorted_td64(n: usize) -> Column {
let data: Vec<i64> = (0..n as i64).collect();
Column::from_timedelta64_values_with_validity(data, ValidityMask::all_valid(n))
}
/// Faithful replica of the pre-lever generic path: per-needle
/// `searchsorted_position` (accesses `&self.values[mid]`, forcing the whole
/// `Vec<Scalar::Timedelta64>` via `as_slice`'s `get_or_init`), then an Int64
/// position column.
fn orig_ss(col: &Column, needles: &[Scalar], side: &str) -> Column {
let positions: Vec<Scalar> = needles
.iter()
.map(|needle| col.searchsorted_position(needle, side, None))
.map(|r| r.map(|p| Scalar::Int64(p as i64)))
.collect::<Result<Vec<_>, _>>()
.expect("searchsorted");
Column::new(DType::Int64, positions).expect("int64 col")
}
/// Non-panicking sibling of `orig_ss`: propagates the first per-needle error
/// (used to assert the generic path errors on a NaT/missing needle).
fn orig_ss_result(
col: &Column,
needles: &[Scalar],
side: &str,
) -> Result<(), super::ColumnError> {
for needle in needles {
col.searchsorted_position(needle, side, None)?;
}
Ok(())
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_td64_searchsorted_parity() {
// Typed partition_point == generic searchsorted_position for BOTH sides
// across before-first / present-first / present-mid / present-last /
// after-last needles, plus empty needles.
let col = || sorted_td64(10_000);
let needles: Vec<Scalar> = [-1_i64, 0, 5000, 9999, 10_000]
.iter()
.map(|v| Scalar::Timedelta64(*v))
.collect();
for side in ["left", "right"] {
assert_eq!(
orig_ss(&col(), &needles, side).values.as_slice(),
col()
.searchsorted_values(&needles, side)
.expect("ss")
.values
.as_slice(),
"td64 searchsorted diverged side={side}"
);
}
// A NaT (i64::MIN) needle is MISSING (Timedelta::NAT): the typed guard
// EXCLUDES it, so the batch falls through to the generic comparator, which
// errors ValueIsMissing -- exactly as the per-needle generic does.
let with_nat = vec![Scalar::Timedelta64(5000), Scalar::Timedelta64(i64::MIN)];
for side in ["left", "right"] {
assert!(
col().searchsorted_values(&with_nat, side).is_err(),
"td64 searchsorted must error on NaT needle side={side}"
);
assert!(
orig_ss_result(&col(), &with_nat, side).is_err(),
"generic must also error on NaT needle side={side}"
);
}
let empty: Vec<Scalar> = Vec::new();
assert_eq!(
orig_ss(&col(), &empty, "left").values.as_slice(),
col()
.searchsorted_values(&empty, "left")
.expect("ss")
.values
.as_slice(),
"td64 searchsorted empty-needles diverged"
);
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_td64_searchsorted() {
const N: usize = 4_000_000;
const NEEDLES: usize = 1_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let mk_col = || sorted_td64(N);
let needles: Vec<Scalar> = (0..NEEDLES)
.map(|j| Scalar::Timedelta64((j * (N / NEEDLES)) as i64))
.collect();
// Parity guard inside the perf run too.
assert_eq!(
orig_ss(&mk_col(), &needles, "left").values.as_slice(),
mk_col()
.searchsorted_values(&needles, "left")
.unwrap()
.values
.as_slice(),
"td64 searchsorted diverged (perf)"
);
for _ in 0..2 {
std::hint::black_box(orig_ss(&mk_col(), &needles, "left"));
std::hint::black_box(mk_col().searchsorted_values(&needles, "left").unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_ss(std::hint::black_box(&co), &needles, "left"));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c1)
.searchsorted_values(&needles, "left")
.unwrap(),
);
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c2)
.searchsorted_values(&needles, "left")
.unwrap(),
);
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB td64 searchsorted (ONE binary, ONE invocation) N={N} needles={NEEDLES}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG generic Vec<Scalar> bsearch min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND partition_point &[i64] min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_i64_var_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, Scalar, nanvar};
/// All-valid Int64 column `[0, 1, ..., n-1]` (the `as_i64_slice` typed path).
fn mk_col(n: usize) -> Column {
Column::from_i64_values_owned((0..n as i64).collect())
}
/// Bit key for a var result: Float64 by its bits; Null (n<=ddof) as a sentinel.
fn var_bits(s: &Scalar) -> u64 {
match s {
Scalar::Float64(v) => v.to_bits(),
Scalar::Null(_) => u64::MAX,
other => panic!("unexpected var result: {other:?}"),
}
}
/// The pre-lever path: nanvar over the materialized `Vec<Scalar::Int64>`.
fn orig_var(col: &Column, ddof: usize) -> Scalar {
nanvar(col.values.as_slice(), ddof)
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_i64_var_parity() {
// Typed i64 two-pass == nanvar (materialized) for ddof 0 and 1, across a
// few shapes incl. the n<=ddof Null(NaN) boundary and a single element.
for n in [0usize, 1, 2, 3, 1000, 4096] {
let col = mk_col(n);
for ddof in [0usize, 1] {
assert_eq!(
var_bits(&orig_var(&col, ddof)),
var_bits(&col.var(ddof)),
"i64 var diverged n={n} ddof={ddof}"
);
}
}
// Negative + large-magnitude values (exercise `v as f64` sign/precision).
let data: Vec<i64> = (0..5000).map(|i| (i as i64 - 2500) * 100_003).collect();
let col = Column::from_i64_values_owned(data);
for ddof in [0usize, 1] {
assert_eq!(
var_bits(&orig_var(&col, ddof)),
var_bits(&col.var(ddof)),
"i64 var diverged (signed) ddof={ddof}"
);
}
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_i64_var() {
const N: usize = 4_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
const DDOF: usize = 1;
// Parity guard inside the perf run too.
assert_eq!(
var_bits(&orig_var(&mk_col(N), DDOF)),
var_bits(&mk_col(N).var(DDOF)),
"i64 var diverged (perf)"
);
for _ in 0..2 {
std::hint::black_box(orig_var(&mk_col(N), DDOF));
std::hint::black_box(mk_col(N).var(DDOF));
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col(N);
let t0 = Instant::now();
std::hint::black_box(orig_var(std::hint::black_box(&co), DDOF));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col(N);
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).var(DDOF));
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col(N);
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).var(DDOF));
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB i64 var (ONE binary, ONE invocation) N={N} ddof={DDOF}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nanvar Vec<Scalar>+collect_finite min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND typed two-pass &[i64] min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_i64_std_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, Scalar, nanstd};
/// All-valid Int64 column `[0, 1, ..., n-1]` (the `as_i64_slice` typed path).
fn mk_col(n: usize) -> Column {
Column::from_i64_values_owned((0..n as i64).collect())
}
/// Bit key for a std result: Float64 by its bits; Null (n<=ddof) as a sentinel.
fn std_bits(s: &Scalar) -> u64 {
match s {
Scalar::Float64(v) => v.to_bits(),
Scalar::Null(_) => u64::MAX,
other => panic!("unexpected std result: {other:?}"),
}
}
/// The pre-lever path: nanstd over the materialized `Vec<Scalar::Int64>`.
fn orig_std(col: &Column, ddof: usize) -> Scalar {
nanstd(col.values.as_slice(), ddof)
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_i64_std_parity() {
// Typed sqrt(var) == nanstd (materialized) for ddof 0 and 1, across shapes
// incl. the n<=ddof Null(NaN) boundary and a single element.
for n in [0usize, 1, 2, 3, 1000, 4096] {
let col = mk_col(n);
for ddof in [0usize, 1] {
assert_eq!(
std_bits(&orig_std(&col, ddof)),
std_bits(&col.std(ddof)),
"i64 std diverged n={n} ddof={ddof}"
);
}
}
// Negative + large-magnitude values.
let data: Vec<i64> = (0..5000).map(|i| (i as i64 - 2500) * 100_003).collect();
let col = Column::from_i64_values_owned(data);
for ddof in [0usize, 1] {
assert_eq!(
std_bits(&orig_std(&col, ddof)),
std_bits(&col.std(ddof)),
"i64 std diverged (signed) ddof={ddof}"
);
}
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_i64_std() {
const N: usize = 4_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
const DDOF: usize = 1;
// Parity guard inside the perf run too.
assert_eq!(
std_bits(&orig_std(&mk_col(N), DDOF)),
std_bits(&mk_col(N).std(DDOF)),
"i64 std diverged (perf)"
);
for _ in 0..2 {
std::hint::black_box(orig_std(&mk_col(N), DDOF));
std::hint::black_box(mk_col(N).std(DDOF));
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col(N);
let t0 = Instant::now();
std::hint::black_box(orig_std(std::hint::black_box(&co), DDOF));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col(N);
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).std(DDOF));
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col(N);
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).std(DDOF));
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB i64 std (ONE binary, ONE invocation) N={N} ddof={DDOF}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nanstd Vec<Scalar>+collect_finite min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND typed sqrt(var) &[i64] min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_i64_sem_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, Scalar, nansem};
/// All-valid Int64 column `[0, 1, ..., n-1]` (the `as_i64_slice` typed path).
fn mk_col(n: usize) -> Column {
Column::from_i64_values_owned((0..n as i64).collect())
}
/// Bit key for a sem result: Float64 by its bits; Null (n<=ddof) as a sentinel.
fn sem_bits(s: &Scalar) -> u64 {
match s {
Scalar::Float64(v) => v.to_bits(),
Scalar::Null(_) => u64::MAX,
other => panic!("unexpected sem result: {other:?}"),
}
}
/// The pre-lever path: nansem over the materialized `Vec<Scalar>`.
fn orig_sem(col: &Column, ddof: usize) -> Scalar {
nansem(col.values.as_slice(), ddof)
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_i64_sem_parity() {
// Typed sem == nansem (materialized) for ddof 0 and 1, across shapes incl.
// the n<=ddof Null(NaN) boundary and a single element -- for BOTH Int64 and
// Float64 (the typed_collect_finite_f64 path covers both dtypes).
for n in [0usize, 1, 2, 3, 1000, 4096] {
let icol = mk_col(n);
let fcol = Column::from_f64_values_owned((0..n).map(|i| i as f64 * 1.5).collect());
for ddof in [0usize, 1] {
assert_eq!(
sem_bits(&orig_sem(&icol, ddof)),
sem_bits(&icol.sem(ddof)),
"i64 sem diverged n={n} ddof={ddof}"
);
assert_eq!(
sem_bits(&orig_sem(&fcol, ddof)),
sem_bits(&fcol.sem(ddof)),
"f64 sem diverged n={n} ddof={ddof}"
);
}
}
// Negative + large-magnitude Int64.
let data: Vec<i64> = (0..5000).map(|i| (i as i64 - 2500) * 100_003).collect();
let col = Column::from_i64_values_owned(data);
for ddof in [0usize, 1] {
assert_eq!(
sem_bits(&orig_sem(&col, ddof)),
sem_bits(&col.sem(ddof)),
"i64 sem diverged (signed) ddof={ddof}"
);
}
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_i64_sem() {
const N: usize = 4_000_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
const DDOF: usize = 1;
// Parity guard inside the perf run too.
assert_eq!(
sem_bits(&orig_sem(&mk_col(N), DDOF)),
sem_bits(&mk_col(N).sem(DDOF)),
"i64 sem diverged (perf)"
);
for _ in 0..2 {
std::hint::black_box(orig_sem(&mk_col(N), DDOF));
std::hint::black_box(mk_col(N).sem(DDOF));
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col(N);
let t0 = Instant::now();
std::hint::black_box(orig_sem(std::hint::black_box(&co), DDOF));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col(N);
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).sem(DDOF));
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col(N);
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).sem(DDOF));
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB i64 sem (ONE binary, ONE invocation) N={N} ddof={DDOF}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG nansem Vec<Scalar>+DOUBLE collect_finite min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND typed std/sqrt(n) &[i64] min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_utf8_nlargest_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, Scalar};
/// Seeded (splitmix64) contiguous-Utf8: `n` rows from `distinct` fixed-width
/// `"val_{:07}"` labels (duplicates ⇒ exercises stable first-seen tie order).
fn mk(n: usize, distinct: usize) -> (Vec<u8>, Vec<usize>) {
let mut s: u64 = 0x51ED_2701_9AB3_44CF;
let mut bytes: Vec<u8> = Vec::with_capacity(n * 11);
let mut offsets: Vec<usize> = Vec::with_capacity(n + 1);
offsets.push(0);
for _ in 0..n {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
let key = (z as usize) % distinct;
bytes.extend_from_slice(b"val_");
let mut buf = [0u8; 7];
let mut k = key;
for slot in buf.iter_mut().rev() {
*slot = b'0' + (k % 10) as u8;
k /= 10;
}
bytes.extend_from_slice(&buf);
offsets.push(bytes.len());
}
(bytes, offsets)
}
/// Faithful replica of the pre-lever fallback: full sort_values then take n.
fn orig_nlargest(col: &Column, n: usize) -> Column {
let sorted = col.sort_values(false).expect("sort");
let take = n.min(sorted.values.as_slice().len());
let values: Vec<Scalar> = sorted.values.as_slice()[..take].to_vec();
Column::new(DType::Utf8, values).expect("new")
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_utf8_nlargest_parity() {
// Typed span-gather == generic sort_values+take across n < len / n == len /
// n > len / n == 1, for BOTH nlargest and nsmallest, over a column with
// heavy duplicates (stable first-seen tie order).
let (b, o) = mk(5_000, 200);
let col = || Column::from_utf8_contiguous(b.clone(), o.clone());
for &n in &[1usize, 10, 137, 5_000, 6_000] {
assert_eq!(
orig_nlargest(&col(), n).values.as_slice(),
col().nlargest(n).expect("nlargest").values.as_slice(),
"utf8 nlargest diverged n={n}"
);
let sm_orig = col().sort_values(true).unwrap();
let take = n.min(sm_orig.values.as_slice().len());
assert_eq!(
&sm_orig.values.as_slice()[..take],
col().nsmallest(n).expect("nsmallest").values.as_slice(),
"utf8 nsmallest diverged n={n}"
);
}
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_utf8_nlargest() {
const N: usize = 4_000_000;
const DISTINCT: usize = 100_000;
const K: usize = 100;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let (bytes, offsets) = mk(N, DISTINCT);
let mk_col = || Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
assert_eq!(
orig_nlargest(&mk_col(), K).values.as_slice(),
mk_col().nlargest(K).unwrap().values.as_slice(),
"utf8 nlargest diverged (perf)"
);
for _ in 0..2 {
std::hint::black_box(orig_nlargest(&mk_col(), K));
std::hint::black_box(mk_col().nlargest(K).unwrap());
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_nlargest(std::hint::black_box(&co), K));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c1).nlargest(K).unwrap());
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(std::hint::black_box(&c2).nlargest(K).unwrap());
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB utf8 nlargest (ONE binary, ONE invocation) N={N} distinct={DISTINCT} k={K}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG sort_values+take (2N Str) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND perm + gather k spans min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}
#[cfg(test)]
mod ab_utf8_ss_sorter_ccfp {
use std::{process::Command, time::Instant};
use super::{Column, DType, Scalar};
/// SORTED contiguous-Utf8 of fixed-width `"val_{:07}"` labels for `0..n`.
fn sorted_utf8(n: usize) -> (Vec<u8>, Vec<usize>) {
let mut bytes = Vec::with_capacity(n * 11);
let mut offsets = Vec::with_capacity(n + 1);
offsets.push(0);
for i in 0..n {
bytes.extend_from_slice(b"val_");
let mut buf = [0u8; 7];
let mut k = i;
for slot in buf.iter_mut().rev() {
*slot = b'0' + (k % 10) as u8;
k /= 10;
}
bytes.extend_from_slice(&buf);
offsets.push(bytes.len());
}
(bytes, offsets)
}
/// Faithful replica of the pre-lever generic `searchsorted_position` per
/// needle (materializes the whole `Vec<Scalar::Utf8>` via `as_slice`), with an
/// explicit sorter. All-valid ⇒ str::cmp == compare_scalars_na_last.
fn orig_ss_sorter(col: &Column, needles: &[Scalar], side: &str, sorter: &[usize]) -> Column {
// Faithful PRE-lever: per-needle `searchsorted_position`, which validated
// the sorter (O(N)) on EVERY needle -- the O(k·N) cost the hoist removes.
let positions: Vec<Scalar> = needles
.iter()
.map(|needle| col.searchsorted_position(needle, side, Some(sorter)))
.map(|r| r.map(|p| Scalar::Int64(p as i64)))
.collect::<Result<Vec<_>, _>>()
.expect("ss");
Column::new(DType::Int64, positions).expect("int64 col")
}
fn min_of(xs: &[f64]) -> f64 {
xs.iter().copied().fold(f64::INFINITY, f64::min)
}
fn median_of(xs: &[f64]) -> f64 {
let mut v = xs.to_vec();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn cv_of(xs: &[f64]) -> f64 {
let m = xs.iter().sum::<f64>() / xs.len() as f64;
100.0 * (xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / xs.len() as f64).sqrt() / m
}
#[test]
fn ab_utf8_ss_sorter_parity() {
// Byte-span searchsorted_position (via the single + sorter variants) ==
// the generic, for both sides + boundary needles + a single searchsorted.
let (b, o) = sorted_utf8(10_000);
let col = || Column::from_utf8_contiguous(b.clone(), o.clone());
let sorter: Vec<usize> = (0..10_000).collect();
let needles: Vec<Scalar> = [
"aaa",
"val_0000000",
"val_0005000",
"val_0009999",
"val_0010000",
"zzz",
]
.iter()
.map(|s| Scalar::Utf8((*s).to_string()))
.collect();
for side in ["left", "right"] {
assert_eq!(
orig_ss_sorter(&col(), &needles, side, &sorter)
.values
.as_slice(),
col()
.searchsorted_values_with_sorter(&needles, side, &sorter)
.expect("ss")
.values
.as_slice(),
"utf8 ss-sorter diverged side={side}"
);
// single searchsorted (no sorter) also routes through the byte-span path
for nd in &needles {
let want_col = orig_ss_sorter(&col(), std::slice::from_ref(nd), side, &sorter);
let want = match &want_col.values.as_slice()[0] {
Scalar::Int64(p) => *p,
_ => unreachable!(),
};
let got = col().searchsorted(nd, side).expect("single") as i64;
assert_eq!(want, got, "single searchsorted diverged side={side}");
}
}
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_utf8_ss_sorter() {
const N: usize = 4_000_000;
const NEEDLES: usize = 1_000;
const BLOCKS: usize = 9;
const REPS: usize = 3;
let (bytes, offsets) = sorted_utf8(N);
let mk_col = || Column::from_utf8_contiguous(bytes.clone(), offsets.clone());
let sorter: Vec<usize> = (0..N).collect();
let needles: Vec<Scalar> = (0..NEEDLES)
.map(|j| Scalar::Utf8(format!("val_{:07}", j * (N / NEEDLES))))
.collect();
assert_eq!(
orig_ss_sorter(&mk_col(), &needles, "left", &sorter)
.values
.as_slice(),
mk_col()
.searchsorted_values_with_sorter(&needles, "left", &sorter)
.unwrap()
.values
.as_slice(),
"utf8 ss-sorter diverged (perf)"
);
for _ in 0..2 {
std::hint::black_box(orig_ss_sorter(&mk_col(), &needles, "left", &sorter));
std::hint::black_box(
mk_col()
.searchsorted_values_with_sorter(&needles, "left", &sorter)
.unwrap(),
);
}
let (mut orig, mut cand, mut null) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..BLOCKS {
let (mut bo, mut bc, mut bn) = (f64::INFINITY, f64::INFINITY, f64::INFINITY);
for _ in 0..REPS {
let co = mk_col();
let t0 = Instant::now();
std::hint::black_box(orig_ss_sorter(
std::hint::black_box(&co),
&needles,
"left",
&sorter,
));
bo = bo.min(t0.elapsed().as_secs_f64() * 1e3);
let c1 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c1)
.searchsorted_values_with_sorter(&needles, "left", &sorter)
.unwrap(),
);
let a = t0.elapsed().as_secs_f64() * 1e3;
let c2 = mk_col();
let t0 = Instant::now();
std::hint::black_box(
std::hint::black_box(&c2)
.searchsorted_values_with_sorter(&needles, "left", &sorter)
.unwrap(),
);
let b = t0.elapsed().as_secs_f64() * 1e3;
bc = bc.min(a.min(b));
bn = bn.min(a.max(b) / a.min(b).max(1e-9));
}
orig.push(bo);
cand.push(bc);
null.push(bn);
}
let (o, c) = (min_of(&orig), min_of(&cand));
let sha = Command::new("sha256sum")
.arg(std::env::current_exe().unwrap())
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.and_then(|s| s.split_whitespace().next().map(str::to_owned))
.unwrap_or_default();
let host = Command::new("hostname")
.output()
.ok()
.and_then(|x| String::from_utf8(x.stdout).ok())
.map_or_else(|| "?".into(), |s| s.trim().to_owned());
let nullmed = median_of(&null);
println!("AB searchsorted_values_with_sorter validation-hoist N={N} needles={NEEDLES}");
println!(" binary_sha256 = {sha}");
println!(" worker = {host}");
println!(
" ORIG per-needle validate (O(k*N)) min={o:8.3} ms cv={:.2}%",
cv_of(&orig)
);
println!(
" CAND validate once (hoisted) min={c:8.3} ms cv={:.2}%",
cv_of(&cand)
);
println!(
" NULL-CONTROL (CAND A/A) median={nullmed:.4}x floor={:.2}%",
100.0 * (nullmed - 1.0)
);
println!(
" fp-side ratio (ORIG/CAND) = {:.3}x ({:+.1}%) DECIDABLE={}",
o / c,
100.0 * (o / c - 1.0),
100.0 * (o / c - 1.0) > 100.0 * (nullmed - 1.0)
);
}
}