Skip to main content

fp_types/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(rustdoc::broken_intra_doc_links)]
3
4//! Foundational value-type abstractions for **frankenpandas** — the
5//! enums, structs, and free functions that every other crate
6//! (fp-columnar, fp-index, fp-frame, fp-io, ...) consumes when
7//! representing scalar data, dtypes, missing values, and time deltas.
8//!
9//! The types here intentionally stay tiny and dependency-light
10//! (`serde`, `thiserror`) so they can sit at the bottom of the
11//! workspace dep graph.
12//!
13//! ## Core value types
14//!
15//! - [`DType`]: the dtype enum — `Null`, `Bool`, `Int64`, `Float64`,
16//!   `Utf8`, `Categorical`, `Timedelta64`, `Datetime64`, `Period`,
17//!   `Interval`, `Sparse`. Drives column / series storage decisions
18//!   across the workspace.
19//! - [`Scalar`]: the per-cell value enum, parameterized by `DType`.
20//!   Each variant holds the actual data (`Int64(i64)`, `Float64(f64)`,
21//!   `Utf8(String)`, ...) plus the `Null(NullKind)` variant for
22//!   missing values.
23//! - [`NullKind`]: distinguishes the three pandas missing-value
24//!   "flavors" — `Null` (Python `None` / SQL NULL), `NaN`
25//!   (floating-point not-a-number), `NaT` (timedelta / datetime
26//!   not-a-time). `Scalar::Null(...)` carries the kind so downstream
27//!   code can preserve pandas semantics.
28//! - [`SparseDType`]: descriptor for sparse-encoded dtypes (paired
29//!   value dtype + fill value).
30//!
31//! ## Time / duration types
32//!
33//! - [`Timedelta`]: nanosecond-precision duration with arithmetic
34//!   helpers ([`Timedelta::add`], [`Timedelta::sub`],
35//!   [`Timedelta::mul_scalar`], [`Timedelta::div_scalar`],
36//!   [`Timedelta::div_timedelta`]) that propagate `NaT` per pandas
37//!   semantics. [`TimedeltaComponents`] breaks a timedelta into
38//!   days/hours/minutes/seconds/nanos for display.
39//! - [`Timestamp`]: nanosecond-precision wall-clock timestamp with
40//!   optional timezone. Includes floor / ceil / round helpers and
41//!   `NaT` propagation.
42//!
43//! ## Dtype inference + casting
44//!
45//! - [`infer_dtype`]: derive a [`DType`] from a slice of scalars
46//!   (used during DataFrame construction).
47//! - [`common_dtype`]: pandas-style dtype promotion for binary ops.
48//! - [`cast_scalar`] / [`cast_scalar_owned`]: convert a scalar to a
49//!   target dtype with explicit error reporting on impossible casts.
50//!
51//! ## Missing-value helpers
52//!
53//! Free fns matching `pd.isna` / `pd.notna` / `pd.fillna` / `pd.dropna`
54//! plus the `nan*` aggregations ([`nansum`], [`nanmean`], [`nancount`],
55//! [`nanmin`], [`nanmax`], [`nanmedian`], [`nanvar`], [`nanstd`])
56//! that mirror pandas' missing-aware reductions.
57//!
58//! ## Error reporting
59//!
60//! Errors are explicit enums via `thiserror`: [`TypeError`] for
61//! dtype-related failures (incompatible-cast, no-common-dtype) and
62//! [`TimedeltaError`] for parse failures.
63
64use serde::{Deserialize, Serialize};
65use thiserror::Error;
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
68#[serde(rename_all = "snake_case")]
69pub enum DType {
70    Null,
71    Bool,
72    /// Nullable boolean extension dtype. Matches pandas `BooleanDtype()`.
73    #[serde(rename = "boolean")]
74    BoolNullable,
75    Int64,
76    /// Nullable Int64 extension dtype. Matches pandas `Int64Dtype()` / `pd.NA`.
77    #[serde(rename = "Int64")]
78    Int64Nullable,
79    Float64,
80    #[serde(alias = "string", alias = "str")]
81    Utf8,
82    Categorical,
83    Timedelta64,
84    /// Nanosecond-precision datetime since Unix epoch. Matches pandas `datetime64[ns]`.
85    Datetime64,
86    /// Period ordinal. Matches pandas `period[freq]`. Stores ordinal + frequency code.
87    Period,
88    /// Numeric interval value. Matches pandas `interval[float64]`.
89    Interval,
90    Sparse,
91}
92
93impl DType {
94    /// Returns true if the dtype is numeric (integer or floating point).
95    #[must_use]
96    pub const fn is_numeric(&self) -> bool {
97        matches!(self, Self::Int64 | Self::Int64Nullable | Self::Float64)
98    }
99
100    /// Returns true if the dtype is an integer type.
101    #[must_use]
102    pub const fn is_integer(&self) -> bool {
103        matches!(self, Self::Int64 | Self::Int64Nullable)
104    }
105
106    /// Returns true if the dtype is a floating point type.
107    #[must_use]
108    pub const fn is_floating(&self) -> bool {
109        matches!(self, Self::Float64)
110    }
111
112    /// Returns true if the dtype is boolean.
113    #[must_use]
114    pub const fn is_bool(&self) -> bool {
115        matches!(self, Self::Bool | Self::BoolNullable)
116    }
117
118    /// Returns true if the dtype is object/string type.
119    #[must_use]
120    pub const fn is_object(&self) -> bool {
121        matches!(self, Self::Utf8)
122    }
123
124    /// Returns true if the dtype is datetime.
125    #[must_use]
126    pub const fn is_datetime(&self) -> bool {
127        matches!(self, Self::Datetime64)
128    }
129
130    /// Returns true if the dtype is timedelta.
131    #[must_use]
132    pub const fn is_timedelta(&self) -> bool {
133        matches!(self, Self::Timedelta64)
134    }
135
136    /// Returns true if the dtype is categorical.
137    #[must_use]
138    pub const fn is_categorical(&self) -> bool {
139        matches!(self, Self::Categorical)
140    }
141
142    /// Returns true if the dtype is sparse.
143    #[must_use]
144    pub const fn is_sparse(&self) -> bool {
145        matches!(self, Self::Sparse)
146    }
147
148    /// Returns true if the dtype is period.
149    #[must_use]
150    pub const fn is_period(&self) -> bool {
151        matches!(self, Self::Period)
152    }
153
154    /// Returns true if the dtype is interval.
155    #[must_use]
156    pub const fn is_interval(&self) -> bool {
157        matches!(self, Self::Interval)
158    }
159
160    /// Return the dtype name as a string.
161    ///
162    /// Matches numpy dtype.name property.
163    #[must_use]
164    pub const fn name(&self) -> &'static str {
165        match self {
166            Self::Bool => "bool",
167            Self::BoolNullable => "boolean",
168            Self::Int64 => "int64",
169            Self::Int64Nullable => "Int64",
170            Self::Float64 => "float64",
171            Self::Utf8 => "object",
172            Self::Datetime64 => "datetime64[ns]",
173            Self::Timedelta64 => "timedelta64[ns]",
174            Self::Categorical => "category",
175            Self::Period => "period",
176            Self::Interval => "interval",
177            Self::Sparse => "Sparse",
178            Self::Null => "object",
179        }
180    }
181
182    /// Return the dtype kind character.
183    ///
184    /// Matches numpy dtype.kind property.
185    #[must_use]
186    pub const fn kind(&self) -> char {
187        match self {
188            Self::Bool | Self::BoolNullable => 'b',
189            Self::Int64 | Self::Int64Nullable => 'i',
190            Self::Float64 => 'f',
191            Self::Utf8 => 'O',
192            Self::Datetime64 => 'M',
193            Self::Timedelta64 => 'm',
194            Self::Categorical => 'O',
195            Self::Period => 'O',
196            Self::Interval => 'O',
197            Self::Sparse => 'O',
198            Self::Null => 'O',
199        }
200    }
201
202    /// Return the dtype itemsize in bytes.
203    ///
204    /// Matches numpy dtype.itemsize property.
205    #[must_use]
206    pub const fn itemsize(&self) -> usize {
207        match self {
208            Self::Bool | Self::BoolNullable => 1,
209            Self::Int64
210            | Self::Int64Nullable
211            | Self::Float64
212            | Self::Datetime64
213            | Self::Timedelta64
214            | Self::Period => 8,
215            Self::Utf8 | Self::Categorical | Self::Interval | Self::Sparse | Self::Null => 8,
216        }
217    }
218
219    /// Returns true if this is an extension dtype (categorical, sparse, period, interval, nullable).
220    ///
221    /// Matches `pd.api.types.is_extension_array_dtype()`.
222    #[must_use]
223    pub const fn is_extension(&self) -> bool {
224        matches!(
225            self,
226            Self::Categorical
227                | Self::Sparse
228                | Self::Period
229                | Self::Interval
230                | Self::Int64Nullable
231                | Self::BoolNullable
232        )
233    }
234
235    /// Returns true if this is a nullable extension dtype (Int64, boolean).
236    ///
237    /// Nullable extension dtypes preserve their dtype when nulls are introduced,
238    /// unlike numpy dtypes which promote to float64.
239    #[must_use]
240    pub const fn is_nullable(&self) -> bool {
241        matches!(self, Self::Int64Nullable | Self::BoolNullable)
242    }
243
244    /// Returns the non-nullable equivalent dtype.
245    ///
246    /// For nullable extension dtypes, returns the numpy equivalent.
247    /// For non-nullable dtypes, returns self.
248    #[must_use]
249    pub const fn to_non_nullable(&self) -> Self {
250        match self {
251            Self::Int64Nullable => Self::Int64,
252            Self::BoolNullable => Self::Bool,
253            other => *other,
254        }
255    }
256
257    /// Returns the nullable equivalent dtype.
258    ///
259    /// For numpy int64/bool, returns the nullable extension dtype.
260    /// For already-nullable or other dtypes, returns self.
261    #[must_use]
262    pub const fn to_nullable(&self) -> Self {
263        match self {
264            Self::Int64 => Self::Int64Nullable,
265            Self::Bool => Self::BoolNullable,
266            other => *other,
267        }
268    }
269
270    /// Returns true if this is a signed integer type.
271    ///
272    /// Matches `pd.api.types.is_signed_integer_dtype()`.
273    #[must_use]
274    pub const fn is_signed_integer(&self) -> bool {
275        matches!(self, Self::Int64 | Self::Int64Nullable)
276    }
277
278    /// Returns true if this is a string/object dtype.
279    ///
280    /// Matches `pd.api.types.is_string_dtype()`.
281    #[must_use]
282    pub const fn is_string_dtype(&self) -> bool {
283        matches!(self, Self::Utf8)
284    }
285
286    /// Returns true for any real numeric dtype (integer or float).
287    ///
288    /// Matches `pd.api.types.is_any_real_numeric_dtype()`.
289    #[must_use]
290    pub const fn is_any_real_numeric(&self) -> bool {
291        self.is_numeric()
292    }
293
294    /// Returns true for datetime-like dtypes (datetime, timedelta, period).
295    ///
296    /// Matches `pd.api.types.is_datetime64_any_dtype()` family.
297    #[must_use]
298    pub const fn is_datetime_like(&self) -> bool {
299        matches!(self, Self::Datetime64 | Self::Timedelta64 | Self::Period)
300    }
301
302    /// Return the numpy dtype character code.
303    ///
304    /// Matches numpy dtype.char property.
305    #[must_use]
306    pub const fn char(&self) -> char {
307        match self {
308            Self::Bool | Self::BoolNullable => '?',
309            Self::Int64 | Self::Int64Nullable => 'l',
310            Self::Float64 => 'd',
311            Self::Utf8 => 'O',
312            Self::Datetime64 => 'M',
313            Self::Timedelta64 => 'm',
314            Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => 'O',
315        }
316    }
317
318    /// Return the numpy type number.
319    ///
320    /// Matches numpy dtype.num property.
321    #[must_use]
322    pub const fn num(&self) -> i32 {
323        match self {
324            Self::Bool | Self::BoolNullable => 0,
325            Self::Int64 | Self::Int64Nullable => 7,
326            Self::Float64 => 12,
327            Self::Utf8 => 17,
328            Self::Datetime64 => 21,
329            Self::Timedelta64 => 22,
330            Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => 17,
331        }
332    }
333
334    /// Return the byte order character.
335    ///
336    /// Matches numpy dtype.byteorder property. Returns '=' (native) for all types.
337    #[must_use]
338    pub const fn byteorder(&self) -> char {
339        '='
340    }
341
342    /// Return the numpy dtype string representation.
343    ///
344    /// Matches numpy dtype.str property.
345    #[must_use]
346    pub const fn str_repr(&self) -> &'static str {
347        match self {
348            Self::Bool | Self::BoolNullable => "|b1",
349            Self::Int64 | Self::Int64Nullable => "<i8",
350            Self::Float64 => "<f8",
351            Self::Utf8 => "|O8",
352            Self::Datetime64 => "<M8[ns]",
353            Self::Timedelta64 => "<m8[ns]",
354            Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => "|O8",
355        }
356    }
357}
358
359#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
360pub struct SparseDType {
361    pub value_dtype: DType,
362    pub fill_value: Scalar,
363}
364
365impl SparseDType {
366    /// Construct a pandas-style sparse dtype descriptor.
367    ///
368    /// This records the logical dense value dtype plus the scalar value that is
369    /// elided from storage. The concrete sparse column representation lives in
370    /// fp-columnar; this descriptor is the shared public contract.
371    pub fn new(value_dtype: DType, fill_value: Scalar) -> Result<Self, TypeError> {
372        if matches!(value_dtype, DType::Null | DType::Sparse) {
373            return Err(TypeError::InvalidSparseValueDType { dtype: value_dtype });
374        }
375
376        let fill_value = if fill_value.is_missing() {
377            Scalar::missing_for_dtype(value_dtype)
378        } else {
379            cast_scalar_owned(fill_value, value_dtype)?
380        };
381
382        Ok(Self {
383            value_dtype,
384            fill_value,
385        })
386    }
387}
388
389#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
390#[serde(rename_all = "snake_case")]
391pub enum NullKind {
392    Null,
393    NaN,
394    NaT,
395}
396
397#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
398#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
399pub enum Scalar {
400    Null(NullKind),
401    Bool(bool),
402    Int64(i64),
403    Float64(f64),
404    #[serde(alias = "string", alias = "str")]
405    Utf8(String),
406    Timedelta64(i64),
407    /// Nanoseconds since Unix epoch. Matches pandas `datetime64[ns]`.
408    /// Uses `Timestamp::NAT` (i64::MIN) for missing values.
409    Datetime64(i64),
410    /// Period value (ordinal + frequency). A `Period` whose `ordinal` is
411    /// `i64::MIN` is NaT (missing). The frequency is carried so writers can
412    /// render the pandas calendar string (`2024Q1`, `2024-03`, ...) — the
413    /// calendar string is not recoverable from the ordinal alone, since
414    /// different frequencies share overlapping ordinal axes.
415    Period(Period),
416    /// Numeric interval value. Missing values remain `Scalar::Null`.
417    Interval(Interval),
418}
419
420impl std::fmt::Display for Scalar {
421    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
422        match self {
423            Self::Null(NullKind::NaN) => write!(f, "NaN"),
424            Self::Null(NullKind::NaT) => write!(f, "NaT"),
425            Self::Null(NullKind::Null) => write!(f, "None"),
426            Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
427            Self::Int64(v) => write!(f, "{v}"),
428            Self::Float64(v) => write!(f, "{v}"),
429            Self::Utf8(s) => write!(f, "{s}"),
430            Self::Timedelta64(nanos) => write!(f, "{}", Timedelta::format(*nanos)),
431            Self::Datetime64(nanos) => {
432                if *nanos == Timestamp::NAT {
433                    write!(f, "NaT")
434                } else {
435                    write!(f, "Timestamp[{nanos}]")
436                }
437            }
438            Self::Period(p) => {
439                if p.ordinal == i64::MIN {
440                    write!(f, "NaT")
441                } else {
442                    write!(f, "{}", p.calendar_string())
443                }
444            }
445            Self::Interval(interval) => write!(f, "{interval}"),
446        }
447    }
448}
449
450// Ergonomic From impls (br-frankenpandas-esjjy / fd90.182). Mirrors
451// IndexLabel's From<i64>/From<&str>/From<String> so users can write
452//   let v: Vec<Scalar> = vec![1i64.into(), 2.0.into(), "three".into()];
453// instead of the explicit Scalar::Int64(...)/Scalar::Float64(...) form.
454//
455// i64 maps to Int64 (more common than Timedelta64 in pandas-style code).
456// Users wanting Timedelta64 should construct it explicitly with
457// Scalar::Timedelta64(nanos) or via Timedelta::parse / to_timedelta.
458
459impl From<bool> for Scalar {
460    fn from(value: bool) -> Self {
461        Self::Bool(value)
462    }
463}
464
465impl From<i64> for Scalar {
466    fn from(value: i64) -> Self {
467        Self::Int64(value)
468    }
469}
470
471impl From<f64> for Scalar {
472    fn from(value: f64) -> Self {
473        Self::Float64(value)
474    }
475}
476
477impl From<&str> for Scalar {
478    fn from(value: &str) -> Self {
479        Self::Utf8(value.to_owned())
480    }
481}
482
483impl From<String> for Scalar {
484    fn from(value: String) -> Self {
485        Self::Utf8(value)
486    }
487}
488
489impl Scalar {
490    #[inline]
491    const fn debug_variant_name(&self) -> &'static str {
492        match self {
493            Self::Null(_) => "Null",
494            Self::Bool(_) => "Bool",
495            Self::Int64(_) => "Int64",
496            Self::Float64(_) => "Float64",
497            Self::Utf8(_) => "Utf8",
498            Self::Timedelta64(_) => "Timedelta64",
499            Self::Datetime64(_) => "Datetime64",
500            Self::Period(_) => "Period",
501            Self::Interval(_) => "Interval",
502        }
503    }
504
505    #[must_use]
506    pub fn dtype(&self) -> DType {
507        match self {
508            Self::Null(_) => DType::Null,
509            Self::Bool(_) => DType::Bool,
510            Self::Int64(_) => DType::Int64,
511            Self::Float64(_) => DType::Float64,
512            Self::Utf8(_) => DType::Utf8,
513            Self::Timedelta64(_) => DType::Timedelta64,
514            Self::Datetime64(_) => DType::Datetime64,
515            Self::Period(_) => DType::Period,
516            Self::Interval(_) => DType::Interval,
517        }
518    }
519
520    #[must_use]
521    pub fn is_missing(&self) -> bool {
522        match self {
523            Self::Null(_) => true,
524            Self::Float64(v) => v.is_nan(),
525            Self::Timedelta64(v) => *v == Timedelta::NAT,
526            Self::Datetime64(v) => *v == Timestamp::NAT,
527            Self::Period(p) => p.ordinal == i64::MIN,
528            _ => false,
529        }
530    }
531
532    #[must_use]
533    pub fn is_nan(&self) -> bool {
534        matches!(self, Self::Null(NullKind::NaN)) || matches!(self, Self::Float64(v) if v.is_nan())
535    }
536
537    /// Returns true if this is a Bool scalar.
538    #[must_use]
539    pub const fn is_bool(&self) -> bool {
540        matches!(self, Self::Bool(_))
541    }
542
543    /// Returns true if this is an Int64 scalar.
544    #[must_use]
545    pub const fn is_integer(&self) -> bool {
546        matches!(self, Self::Int64(_))
547    }
548
549    /// Returns true if this is a Float64 scalar.
550    #[must_use]
551    pub const fn is_float(&self) -> bool {
552        matches!(self, Self::Float64(_))
553    }
554
555    /// Returns true if this is a numeric scalar (Int64 or Float64).
556    #[must_use]
557    pub const fn is_numeric(&self) -> bool {
558        matches!(self, Self::Int64(_) | Self::Float64(_))
559    }
560
561    /// Returns true if this is a Utf8 (string) scalar.
562    #[must_use]
563    pub const fn is_string(&self) -> bool {
564        matches!(self, Self::Utf8(_))
565    }
566
567    /// Returns true if this is a Datetime64 scalar.
568    #[must_use]
569    pub const fn is_datetime(&self) -> bool {
570        matches!(self, Self::Datetime64(_))
571    }
572
573    /// Returns true if this is a Timedelta64 scalar.
574    #[must_use]
575    pub const fn is_timedelta(&self) -> bool {
576        matches!(self, Self::Timedelta64(_))
577    }
578
579    /// Returns true if this is a Period scalar.
580    #[must_use]
581    pub const fn is_period(&self) -> bool {
582        matches!(self, Self::Period(_))
583    }
584
585    /// Returns true if this is an Interval scalar.
586    #[must_use]
587    pub const fn is_interval(&self) -> bool {
588        matches!(self, Self::Interval(_))
589    }
590
591    #[must_use]
592    pub fn missing_for_dtype(dtype: DType) -> Self {
593        match dtype {
594            DType::Float64 => Self::Null(NullKind::NaN),
595            DType::Timedelta64 => Self::Timedelta64(Timedelta::NAT),
596            DType::Datetime64 => Self::Datetime64(Timestamp::NAT),
597            DType::Period => Self::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
598            DType::Null => Self::Null(NullKind::Null),
599            DType::Bool
600            | DType::BoolNullable
601            | DType::Int64
602            | DType::Int64Nullable
603            | DType::Utf8
604            | DType::Categorical
605            | DType::Interval
606            | DType::Sparse => Self::Null(NullKind::Null),
607        }
608    }
609
610    #[must_use]
611    pub fn semantic_eq(&self, other: &Self) -> bool {
612        match (self, other) {
613            (Self::Float64(a), Self::Float64(b)) => {
614                if a.is_nan() && b.is_nan() {
615                    return true;
616                }
617                if *a == *b {
618                    return true;
619                }
620                let diff = (*a - *b).abs();
621                let max_abs = a.abs().max(b.abs());
622                if max_abs == 0.0 {
623                    diff < f64::EPSILON
624                } else {
625                    diff / max_abs < 1e-14
626                }
627            }
628            (Self::Null(_), Self::Float64(v)) | (Self::Float64(v), Self::Null(_)) => v.is_nan(),
629            // All Null kinds (Null / NaN / NaT) mark missingness; they are
630            // semantically indistinguishable for oracle-parity checks even
631            // though derived PartialEq would reject a cross-kind pair.
632            // fp-frame normalizes Float64 column missing cells to
633            // Null(NaN) at Column::new time, while fixture oracles encode
634            // the canonical missing marker as Null(Null).
635            (Self::Null(_), Self::Null(_)) => true,
636            _ => self == other,
637        }
638    }
639
640    #[must_use]
641    pub fn semantic_le(&self, other: &Self) -> bool {
642        match self.semantic_cmp(other) {
643            std::cmp::Ordering::Less | std::cmp::Ordering::Equal => true,
644            std::cmp::Ordering::Greater => false,
645        }
646    }
647
648    #[must_use]
649    pub fn semantic_ge(&self, other: &Self) -> bool {
650        match self.semantic_cmp(other) {
651            std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => true,
652            std::cmp::Ordering::Less => false,
653        }
654    }
655
656    #[must_use]
657    pub fn is_null(&self) -> bool {
658        matches!(self, Self::Null(_))
659    }
660
661    #[must_use]
662    pub fn is_na(&self) -> bool {
663        self.is_missing()
664    }
665
666    #[must_use]
667    pub fn coalesce(&self, other: &Self) -> Self {
668        if self.is_missing() {
669            other.clone()
670        } else {
671            self.clone()
672        }
673    }
674
675    #[must_use]
676    pub fn semantic_cmp(&self, other: &Self) -> std::cmp::Ordering {
677        match (self, other) {
678            (Self::Int64(a), Self::Int64(b)) => a.cmp(b),
679            (Self::Float64(a), Self::Float64(b)) => {
680                a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
681            }
682            (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
683            (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
684            (Self::Null(a), Self::Null(b)) => a.cmp(b),
685            (Self::Timedelta64(a), Self::Timedelta64(b)) => {
686                if *a == Timedelta::NAT || *b == Timedelta::NAT {
687                    std::cmp::Ordering::Equal
688                } else {
689                    a.cmp(b)
690                }
691            }
692            (Self::Datetime64(a), Self::Datetime64(b)) => {
693                if *a == Timestamp::NAT || *b == Timestamp::NAT {
694                    std::cmp::Ordering::Equal
695                } else {
696                    a.cmp(b)
697                }
698            }
699            (Self::Period(a), Self::Period(b)) => {
700                if a.ordinal == i64::MIN || b.ordinal == i64::MIN {
701                    std::cmp::Ordering::Equal
702                } else {
703                    a.ordinal.cmp(&b.ordinal)
704                }
705            }
706            (Self::Interval(a), Self::Interval(b)) => a
707                .left
708                .partial_cmp(&b.left)
709                .unwrap_or(std::cmp::Ordering::Equal)
710                .then_with(|| {
711                    a.right
712                        .partial_cmp(&b.right)
713                        .unwrap_or(std::cmp::Ordering::Equal)
714                })
715                .then_with(|| a.closed.cmp(&b.closed)),
716            // Cross-numeric comparison
717            (Self::Int64(a), Self::Float64(b)) => (*a as f64)
718                .partial_cmp(b)
719                .unwrap_or(std::cmp::Ordering::Equal),
720            (Self::Float64(a), Self::Int64(b)) => a
721                .partial_cmp(&(*b as f64))
722                .unwrap_or(std::cmp::Ordering::Equal),
723            // Derived Debug starts every variant with its static variant name.
724            // Different variants therefore order by that name before either
725            // payload is observed; compare those names without allocating.
726            (a, b) => a.debug_variant_name().cmp(b.debug_variant_name()),
727        }
728    }
729
730    pub fn to_f64(&self) -> Result<f64, TypeError> {
731        match self {
732            Self::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
733            Self::Int64(v) => Ok(*v as f64),
734            Self::Float64(v) => Ok(*v),
735            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
736            Self::Utf8(v) => Err(TypeError::NonNumericValue {
737                value: v.clone(),
738                dtype: DType::Utf8,
739            }),
740            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
741                kind: NullKind::NaT,
742            }),
743            Self::Timedelta64(v) => Err(TypeError::NonNumericValue {
744                value: Timedelta::format(*v),
745                dtype: DType::Timedelta64,
746            }),
747            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
748                kind: NullKind::NaT,
749            }),
750            Self::Datetime64(v) => Err(TypeError::NonNumericValue {
751                value: format!("Timestamp[{v}]"),
752                dtype: DType::Datetime64,
753            }),
754            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
755                kind: NullKind::NaT,
756            }),
757            Self::Period(p) => Err(TypeError::NonNumericValue {
758                value: p.calendar_string(),
759                dtype: DType::Period,
760            }),
761            Self::Interval(v) => Err(TypeError::NonNumericValue {
762                value: v.to_string(),
763                dtype: DType::Interval,
764            }),
765        }
766    }
767
768    /// Try to convert to i64. Returns error for missing or non-numeric values.
769    pub fn to_i64(&self) -> Result<i64, TypeError> {
770        match self {
771            Self::Bool(v) => Ok(if *v { 1 } else { 0 }),
772            Self::Int64(v) => Ok(*v),
773            Self::Float64(v) => Ok(*v as i64),
774            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
775            Self::Utf8(v) => Err(TypeError::NonNumericValue {
776                value: v.clone(),
777                dtype: DType::Utf8,
778            }),
779            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
780                kind: NullKind::NaT,
781            }),
782            Self::Timedelta64(v) => Ok(*v),
783            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
784                kind: NullKind::NaT,
785            }),
786            Self::Datetime64(v) => Ok(*v),
787            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
788                kind: NullKind::NaT,
789            }),
790            Self::Period(p) => Ok(p.ordinal),
791            Self::Interval(v) => Err(TypeError::NonNumericValue {
792                value: v.to_string(),
793                dtype: DType::Interval,
794            }),
795        }
796    }
797
798    /// Try to convert to bool. Returns error for missing values.
799    pub fn to_bool(&self) -> Result<bool, TypeError> {
800        match self {
801            Self::Bool(v) => Ok(*v),
802            Self::Int64(v) => Ok(*v != 0),
803            Self::Float64(v) => Ok(*v != 0.0 && !v.is_nan()),
804            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
805            Self::Utf8(v) => Ok(!v.is_empty()),
806            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
807                kind: NullKind::NaT,
808            }),
809            Self::Timedelta64(v) => Ok(*v != 0),
810            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
811                kind: NullKind::NaT,
812            }),
813            Self::Datetime64(v) => Ok(*v != 0),
814            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
815                kind: NullKind::NaT,
816            }),
817            Self::Period(p) => Ok(p.ordinal != 0),
818            Self::Interval(_) => Ok(true),
819        }
820    }
821
822    /// Try to convert to string representation.
823    pub fn to_str(&self) -> String {
824        match self {
825            Self::Bool(v) => if *v { "True" } else { "False" }.to_string(),
826            Self::Int64(v) => v.to_string(),
827            Self::Float64(v) => {
828                if v.is_nan() {
829                    "nan".to_string()
830                } else if v.is_infinite() {
831                    if *v > 0.0 { "inf" } else { "-inf" }.to_string()
832                } else {
833                    v.to_string()
834                }
835            }
836            Self::Null(_) => "NaN".to_string(),
837            Self::Utf8(v) => v.clone(),
838            Self::Timedelta64(v) => Timedelta::format(*v),
839            Self::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_string(),
840            Self::Datetime64(v) => Timestamp::from_nanos(*v).isoformat(),
841            Self::Period(p) if p.ordinal == i64::MIN => "NaT".to_string(),
842            Self::Period(p) => p.calendar_string(),
843            Self::Interval(v) => v.to_string(),
844        }
845    }
846}
847
848#[derive(Debug, Error, Clone, PartialEq)]
849pub enum TypeError {
850    #[error("dtype coercion from {left:?} to {right:?} has no compatible common type")]
851    IncompatibleDtypes { left: DType, right: DType },
852    #[error("cannot cast scalar of dtype {from:?} to {to:?}")]
853    InvalidCast { from: DType, to: DType },
854    #[error("cannot cast float {value} to int64 without loss")]
855    LossyFloatToInt { value: f64 },
856    #[error("expected 0/1 for bool cast from int64 but found {value}")]
857    InvalidBoolInt { value: i64 },
858    #[error("expected 0.0/1.0 for bool cast from float64 but found {value}")]
859    InvalidBoolFloat { value: f64 },
860    #[error("value {value:?} has non-numeric dtype {dtype:?}")]
861    NonNumericValue { value: String, dtype: DType },
862    #[error("value is missing ({kind:?})")]
863    ValueIsMissing { kind: NullKind },
864    #[error("sparse value dtype cannot be {dtype:?}")]
865    InvalidSparseValueDType { dtype: DType },
866    #[error("interval_range step must be finite, positive, and not NaN (got {step})")]
867    InvalidIntervalStep { step: f64 },
868    #[error("interval_range step {step} does not evenly divide range end-start={span}")]
869    IntervalStepDoesNotDivide { step: f64, span: f64 },
870    #[error("cannot parse '{value}' as {target}")]
871    ValueNotParseable { value: String, target: String },
872}
873
874pub fn common_dtype(left: DType, right: DType) -> Result<DType, TypeError> {
875    use DType::{
876        Bool, BoolNullable, Categorical, Datetime64, Float64, Int64, Int64Nullable, Null, Sparse,
877        Timedelta64,
878    };
879
880    let out = match (left, right) {
881        (a, b) if a == b => a,
882        (Null, other) | (other, Null) => other,
883        (Categorical, Categorical) => Categorical,
884
885        // Bool promotions (nullable absorbs non-nullable)
886        (Bool, Int64) | (Int64, Bool) => Int64,
887        (Bool, Int64Nullable) | (Int64Nullable, Bool) => Int64Nullable,
888        (BoolNullable, Int64) | (Int64, BoolNullable) => Int64Nullable,
889        (BoolNullable, Int64Nullable) | (Int64Nullable, BoolNullable) => Int64Nullable,
890        (Bool, BoolNullable) | (BoolNullable, Bool) => BoolNullable,
891        (Bool, Float64) | (Float64, Bool) => Float64,
892        (BoolNullable, Float64) | (Float64, BoolNullable) => Float64,
893
894        // Int64 promotions (nullable absorbs non-nullable)
895        (Int64, Float64) | (Float64, Int64) => Float64,
896        (Int64Nullable, Float64) | (Float64, Int64Nullable) => Float64,
897        (Int64, Int64Nullable) | (Int64Nullable, Int64) => Int64Nullable,
898
899        // Datetime/Timedelta
900        (Timedelta64, Timedelta64) => Timedelta64,
901        (Datetime64, Datetime64) => Datetime64,
902
903        (Sparse, _) | (_, Sparse) => return Err(TypeError::IncompatibleDtypes { left, right }),
904        _ => return Err(TypeError::IncompatibleDtypes { left, right }),
905    };
906
907    Ok(out)
908}
909
910pub fn infer_dtype(values: &[Scalar]) -> Result<DType, TypeError> {
911    let mut current = DType::Null;
912    let mut saw_utf8 = false;
913    let mut saw_timedelta = false;
914    let mut saw_datetime = false;
915    let mut saw_non_utf8_non_null = false;
916
917    for value in values {
918        match value.dtype() {
919            DType::Null => {}
920            DType::Utf8 => saw_utf8 = true,
921            DType::Timedelta64 => {
922                saw_timedelta = true;
923                if current == DType::Null {
924                    current = DType::Timedelta64;
925                } else if current != DType::Timedelta64 {
926                    return Err(TypeError::IncompatibleDtypes {
927                        left: current,
928                        right: DType::Timedelta64,
929                    });
930                }
931            }
932            DType::Datetime64 => {
933                saw_datetime = true;
934                if current == DType::Null {
935                    current = DType::Datetime64;
936                } else if current != DType::Datetime64 {
937                    return Err(TypeError::IncompatibleDtypes {
938                        left: current,
939                        right: DType::Datetime64,
940                    });
941                }
942            }
943            other => {
944                saw_non_utf8_non_null = true;
945                current = common_dtype(current, other)?;
946            }
947        }
948
949        if saw_utf8 && saw_non_utf8_non_null {
950            // Constructor inference follows pandas object-dtype behavior for
951            // heterogeneous string/scalar payloads while arithmetic coercion
952            // remains governed by the stricter common_dtype lattice.
953            return Ok(DType::Utf8);
954        }
955        if saw_timedelta && saw_non_utf8_non_null {
956            return Err(TypeError::IncompatibleDtypes {
957                left: DType::Timedelta64,
958                right: current,
959            });
960        }
961        if saw_datetime && saw_non_utf8_non_null {
962            return Err(TypeError::IncompatibleDtypes {
963                left: DType::Datetime64,
964                right: current,
965            });
966        }
967    }
968
969    if saw_utf8 {
970        Ok(DType::Utf8)
971    } else {
972        Ok(current)
973    }
974}
975
976/// Cast a scalar to a target dtype, taking ownership to avoid redundant clones
977/// when the value already has the correct type (AG-03: identity-cast skip).
978pub fn cast_scalar_owned(value: Scalar, target: DType) -> Result<Scalar, TypeError> {
979    let from = value.dtype();
980    if from == target {
981        return Ok(value);
982    }
983    // Int64 <-> Int64Nullable: same representation, just different dtype tracking
984    if (from == DType::Int64 && target == DType::Int64Nullable)
985        || (from == DType::Int64Nullable && target == DType::Int64)
986    {
987        return Ok(value);
988    }
989    // Bool <-> BoolNullable: same representation
990    if (from == DType::Bool && target == DType::BoolNullable)
991        || (from == DType::BoolNullable && target == DType::Bool)
992    {
993        return Ok(value);
994    }
995    if target == DType::Utf8 {
996        return Ok(Scalar::Utf8(scalar_to_string_for_astype(value)));
997    }
998    // Per br-frankenpandas-cyi4h: pandas astype(bool) (the numpy bool dtype)
999    // treats a float NaN as truthy -> True (bool(nan) is True), unlike the
1000    // nullable 'boolean' dtype which keeps NA. FP's NaN=missing model would
1001    // otherwise fall through to the missing branch below and yield a null.
1002    // Verified vs live pandas 2.2.3.
1003    if target == DType::Bool
1004        && let Scalar::Float64(v) = &value
1005        && v.is_nan()
1006    {
1007        return Ok(Scalar::Bool(true));
1008    }
1009    if value.is_missing() {
1010        return Ok(Scalar::missing_for_dtype(target));
1011    }
1012
1013    // Note: identity casts (from == target) are handled above, so same-type
1014    // arms are omitted from the match below.
1015    match target {
1016        DType::Null => Ok(Scalar::Null(NullKind::Null)),
1017        DType::Bool => match &value {
1018            // numpy bool: zero -> False, ANY nonzero -> True (it does not
1019            // restrict to 0/1). e.g. bool of -3 / 2.5 is True.
1020            Scalar::Int64(v) => Ok(Scalar::Bool(*v != 0)),
1021            // 0.0 and -0.0 -> False; every other value, INCLUDING NaN, -> True
1022            // (NaN != 0.0 is true), matching numpy/pandas truthiness.
1023            Scalar::Float64(v) => Ok(Scalar::Bool(*v != 0.0)),
1024            _ => Err(TypeError::InvalidCast { from, to: target }),
1025        },
1026        DType::BoolNullable => match &value {
1027            // pandas nullable Boolean ('boolean') is STRICT: only 0/1 (or
1028            // True/False) are accepted — any other value raises "Need to pass
1029            // bool-like values", UNLIKE numpy bool which is nonzero-truthy.
1030            // (br-frankenpandas-tjomg)
1031            Scalar::Bool(b) => Ok(Scalar::Bool(*b)),
1032            Scalar::Int64(0) => Ok(Scalar::Bool(false)),
1033            Scalar::Int64(1) => Ok(Scalar::Bool(true)),
1034            Scalar::Int64(v) => Err(TypeError::InvalidBoolInt { value: *v }),
1035            Scalar::Float64(v) if *v == 0.0 => Ok(Scalar::Bool(false)),
1036            Scalar::Float64(v) if *v == 1.0 => Ok(Scalar::Bool(true)),
1037            Scalar::Float64(v) => Err(TypeError::InvalidBoolFloat { value: *v }),
1038            _ => Err(TypeError::InvalidCast { from, to: target }),
1039        },
1040        DType::Int64 | DType::Int64Nullable => match &value {
1041            Scalar::Bool(v) => Ok(Scalar::Int64(i64::from(*v))),
1042            Scalar::Float64(v) => {
1043                // pandas astype(int64) truncates a finite float toward zero
1044                // (1.9 -> 1, -1.9 -> -1, 2.5 -> 2); only non-finite (NaN/±inf)
1045                // or out-of-i64-range values raise. Verified vs pandas 2.2.3
1046                // (br-frankenpandas-qcutc). NaN is handled as missing above, so
1047                // here non-finite means ±inf. `as i64` performs the toward-zero
1048                // truncation for in-range finite values.
1049                if !v.is_finite() {
1050                    return Err(TypeError::LossyFloatToInt { value: *v });
1051                }
1052                if *v < i64::MIN as f64 || *v >= 9223372036854775808.0 {
1053                    return Err(TypeError::LossyFloatToInt { value: *v });
1054                }
1055                Ok(Scalar::Int64(*v as i64))
1056            }
1057            Scalar::Utf8(s) => {
1058                // Try direct int parse first, then try float parse + truncate
1059                // (pandas accepts "1.0" as valid int via float intermediate)
1060                if let Ok(v) = s.parse::<i64>() {
1061                    return Ok(Scalar::Int64(v));
1062                }
1063                if let Ok(f) = s.parse::<f64>()
1064                    && f.is_finite()
1065                    && f.fract() == 0.0
1066                    && f >= i64::MIN as f64
1067                    && f < 9223372036854775808.0
1068                {
1069                    return Ok(Scalar::Int64(f as i64));
1070                }
1071                Err(TypeError::InvalidCast { from, to: target })
1072            }
1073            _ => Err(TypeError::InvalidCast { from, to: target }),
1074        },
1075        DType::Float64 => match &value {
1076            Scalar::Bool(v) => Ok(Scalar::Float64(if *v { 1.0 } else { 0.0 })),
1077            Scalar::Int64(v) => Ok(Scalar::Float64(*v as f64)),
1078            Scalar::Utf8(s) => s
1079                .parse::<f64>()
1080                .map(Scalar::Float64)
1081                .map_err(|_| TypeError::InvalidCast { from, to: target }),
1082            _ => Err(TypeError::InvalidCast { from, to: target }),
1083        },
1084        DType::Utf8 => Ok(Scalar::Utf8(scalar_to_string_for_astype(value))),
1085        DType::Categorical => Err(TypeError::InvalidCast { from, to: target }),
1086        DType::Timedelta64 => match &value {
1087            Scalar::Int64(v) => Ok(Scalar::Timedelta64(*v)),
1088            Scalar::Utf8(s) => Timedelta::parse(s)
1089                .map(Scalar::Timedelta64)
1090                .map_err(|_| TypeError::InvalidCast { from, to: target }),
1091            _ => Err(TypeError::InvalidCast { from, to: target }),
1092        },
1093        DType::Datetime64 => match &value {
1094            Scalar::Int64(v) => Ok(Scalar::Datetime64(*v)),
1095            Scalar::Utf8(s) => Timestamp::parse(s)
1096                .map(|timestamp| Scalar::Datetime64(timestamp.nanos))
1097                .map_err(|_| TypeError::InvalidCast { from, to: target }),
1098            _ => Err(TypeError::InvalidCast { from, to: target }),
1099        },
1100        DType::Period => match &value {
1101            // Int cast to a freq-less DType::Period: default to Daily (pandas
1102            // requires an explicit freq in the dtype; ours is freq-less).
1103            Scalar::Int64(v) => Ok(Scalar::Period(Period::new(*v, PeriodFreq::Daily))),
1104            Scalar::Utf8(s) => Period::parse(s)
1105                .map(Scalar::Period)
1106                .map_err(|_| TypeError::InvalidCast { from, to: target }),
1107            _ => Err(TypeError::InvalidCast { from, to: target }),
1108        },
1109        DType::Interval => match &value {
1110            Scalar::Utf8(s) => Interval::parse(s)
1111                .map(Scalar::Interval)
1112                .map_err(|_| TypeError::InvalidCast { from, to: target }),
1113            _ => Err(TypeError::InvalidCast { from, to: target }),
1114        },
1115        DType::Sparse => Err(TypeError::InvalidCast { from, to: target }),
1116    }
1117}
1118
1119fn scalar_to_string_for_astype(value: Scalar) -> String {
1120    match value {
1121        Scalar::Null(NullKind::Null) => "None".to_owned(),
1122        Scalar::Null(NullKind::NaN) => "nan".to_owned(),
1123        Scalar::Null(NullKind::NaT) => "NaT".to_owned(),
1124        Scalar::Bool(true) => "True".to_owned(),
1125        Scalar::Bool(false) => "False".to_owned(),
1126        Scalar::Int64(v) => v.to_string(),
1127        Scalar::Float64(v) => float_to_string_for_astype(v),
1128        Scalar::Utf8(s) => s,
1129        Scalar::Timedelta64(v) if v == Timedelta::NAT => "NaT".to_owned(),
1130        Scalar::Timedelta64(v) => Timedelta::format(v),
1131        Scalar::Datetime64(v) if v == Timestamp::NAT => "NaT".to_owned(),
1132        Scalar::Datetime64(v) => format!("Timestamp[{v}]"),
1133        Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
1134        Scalar::Period(p) => p.calendar_string(),
1135        Scalar::Interval(v) => v.to_string(),
1136    }
1137}
1138
1139pub fn float_to_string_for_astype(value: f64) -> String {
1140    use std::fmt::Write as _;
1141
1142    if value.is_nan() {
1143        return "nan".to_owned();
1144    }
1145    if value.is_infinite() {
1146        return value.to_string(); // "inf" / "-inf"
1147    }
1148    // pandas astype(str) renders floats via Python str(float): whole numbers
1149    // keep ".0", decimals use the shortest round-trip, and extreme magnitudes use
1150    // scientific notation ("1e+16", "1e-05"). Rust's Debug formatter matches this
1151    // (shortest round-trip, ".0" on whole numbers, scientific at Python's
1152    // boundaries); only the exponent spelling differs (Rust "1e16"/"1e-5" vs
1153    // Python "1e+16"/"1e-05"), so normalize that. The old `{:.1}` whole / Display
1154    // decimal path lost scientific notation (1e16 -> "10000000000000000.0").
1155    // Leave enough spare capacity for the positive sign and one exponent pad
1156    // digit, then normalize the formatter output in place. The former branch
1157    // allocated a second String and copied the mantissa solely to change
1158    // `e16`/`e-5` into pandas' `e+16`/`e-05` spelling.
1159    let mut rendered = String::with_capacity(32);
1160    let _ = write!(rendered, "{value:?}");
1161    let Some(exponent_marker) = rendered.find('e') else {
1162        return rendered;
1163    };
1164
1165    let sign_position = exponent_marker + 1;
1166    let digits_position = match rendered.as_bytes().get(sign_position) {
1167        Some(b'+' | b'-') => sign_position + 1,
1168        _ => {
1169            rendered.insert(sign_position, '+');
1170            sign_position + 1
1171        }
1172    };
1173    if rendered.len() - digits_position == 1 {
1174        rendered.insert(digits_position, '0');
1175    }
1176    rendered
1177}
1178
1179/// Cast a scalar reference to a target dtype (clones only when conversion is needed).
1180pub fn cast_scalar(value: &Scalar, target: DType) -> Result<Scalar, TypeError> {
1181    cast_scalar_owned(value.clone(), target)
1182}
1183
1184// ── Timedelta support ──────────────────────────────────────────────────
1185
1186#[derive(Debug, Error, Clone, PartialEq)]
1187pub enum TimedeltaError {
1188    #[error("invalid timedelta string: {0}")]
1189    InvalidFormat(String),
1190    #[error("overflow in timedelta computation")]
1191    Overflow,
1192}
1193
1194#[derive(Debug, Clone, Copy, Default)]
1195pub struct TimedeltaComponents {
1196    pub days: i64,
1197    pub hours: i64,
1198    pub minutes: i64,
1199    pub seconds: i64,
1200    pub milliseconds: i64,
1201    pub microseconds: i64,
1202    pub nanoseconds: i64,
1203}
1204
1205pub struct Timedelta;
1206
1207impl Timedelta {
1208    pub const NANOS_PER_MICRO: i64 = 1_000;
1209    pub const NANOS_PER_MILLI: i64 = 1_000_000;
1210    pub const NANOS_PER_SEC: i64 = 1_000_000_000;
1211    pub const NANOS_PER_MIN: i64 = 60 * Self::NANOS_PER_SEC;
1212    pub const NANOS_PER_HOUR: i64 = 60 * Self::NANOS_PER_MIN;
1213    pub const NANOS_PER_DAY: i64 = 24 * Self::NANOS_PER_HOUR;
1214    pub const NANOS_PER_WEEK: i64 = 7 * Self::NANOS_PER_DAY;
1215
1216    pub const NAT: i64 = i64::MIN;
1217
1218    pub fn parse(s: &str) -> Result<i64, TimedeltaError> {
1219        let s = s.trim();
1220
1221        if s.eq_ignore_ascii_case("nat") {
1222            return Ok(Self::NAT);
1223        }
1224
1225        let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
1226            (true, rest.trim())
1227        } else {
1228            (false, s)
1229        };
1230
1231        if let Some(nanos) = Self::try_parse_time_format(s) {
1232            return Ok(if negative { -nanos } else { nanos });
1233        }
1234
1235        if let Some(nanos) = Self::try_parse_iso8601_duration(s) {
1236            return Ok(if negative { -nanos } else { nanos });
1237        }
1238
1239        let nanos = Self::parse_compound(s)?;
1240        Ok(if negative { -nanos } else { nanos })
1241    }
1242
1243    /// Parse an ISO-8601 duration the way pandas `Timedelta` accepts it:
1244    /// a leading uppercase `P`, an optional `T` separator that is otherwise
1245    /// ignored, and unit letters `W`/`D`/`H`/`M`/`S` in any position. `M` is
1246    /// always MINUTES (never months), and only seconds may be fractional —
1247    /// years/months and lowercase units are rejected, matching pandas.
1248    /// (pandas mis-handles fractional non-second components; those are rejected
1249    /// here rather than reproducing the buggy value.) (br-frankenpandas-c3p8b)
1250    fn try_parse_iso8601_duration(s: &str) -> Option<i64> {
1251        let mut rest = s.strip_prefix('P')?;
1252        if rest.is_empty() {
1253            return None;
1254        }
1255        let mut total: i64 = 0;
1256        let mut saw_component = false;
1257        while !rest.is_empty() {
1258            if let Some(after_t) = rest.strip_prefix('T') {
1259                rest = after_t;
1260                continue;
1261            }
1262            let num_end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')?;
1263            if num_end == 0 {
1264                return None;
1265            }
1266            let num_str = &rest[..num_end];
1267            let unit = rest.as_bytes()[num_end];
1268            let is_fractional = num_str.contains('.');
1269            rest = &rest[num_end + 1..];
1270
1271            let (multiplier, frac_ok) = match unit {
1272                b'W' => (Self::NANOS_PER_WEEK, false),
1273                b'D' => (Self::NANOS_PER_DAY, false),
1274                b'H' => (Self::NANOS_PER_HOUR, false),
1275                b'M' => (Self::NANOS_PER_MIN, false),
1276                b'S' => (Self::NANOS_PER_SEC, true),
1277                _ => return None,
1278            };
1279            if is_fractional {
1280                if !frac_ok {
1281                    return None;
1282                }
1283                let value: f64 = num_str.parse().ok()?;
1284                let product = value * multiplier as f64;
1285                if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
1286                    return None;
1287                }
1288                total = total.checked_add(product.round() as i64)?;
1289            } else {
1290                let value: i64 = num_str.parse().ok()?;
1291                total = total.checked_add(value.checked_mul(multiplier)?)?;
1292            }
1293            saw_component = true;
1294        }
1295        saw_component.then_some(total)
1296    }
1297
1298    fn try_parse_time_format(s: &str) -> Option<i64> {
1299        let parts: Vec<&str> = s.split(':').collect();
1300        if parts.len() < 2 || parts.len() > 3 {
1301            return None;
1302        }
1303
1304        let hours: i64 = parts[0].parse().ok()?;
1305        let minutes: i64 = parts[1].parse().ok()?;
1306
1307        let (seconds, frac_nanos) = if parts.len() == 3 {
1308            if let Some((sec_str, frac_str)) = parts[2].split_once('.') {
1309                let sec: i64 = sec_str.parse().ok()?;
1310                if !frac_str.bytes().all(|byte| byte.is_ascii_digit()) {
1311                    return None;
1312                }
1313                let mut frac = 0_i64;
1314                let taken = frac_str.len().min(9);
1315                for byte in frac_str.bytes().take(9) {
1316                    frac = frac * 10 + i64::from(byte - b'0');
1317                }
1318                for _ in taken..9 {
1319                    frac *= 10;
1320                }
1321                (sec, frac)
1322            } else {
1323                let sec: i64 = parts[2].parse().ok()?;
1324                (sec, 0)
1325            }
1326        } else {
1327            (0, 0)
1328        };
1329
1330        hours
1331            .checked_mul(Self::NANOS_PER_HOUR)?
1332            .checked_add(minutes.checked_mul(Self::NANOS_PER_MIN)?)?
1333            .checked_add(seconds.checked_mul(Self::NANOS_PER_SEC)?)?
1334            .checked_add(frac_nanos)
1335    }
1336
1337    fn parse_compound(s: &str) -> Result<i64, TimedeltaError> {
1338        let mut total: i64 = 0;
1339        let mut remaining = s;
1340
1341        while !remaining.is_empty() {
1342            remaining = remaining.trim_start();
1343            if remaining.is_empty() {
1344                break;
1345            }
1346
1347            // Per br-frankenpandas-i9bah: check if remaining is a time format
1348            // (HH:MM:SS) which can appear after "N days " in pandas timedelta strings.
1349            if remaining.contains(':')
1350                && let Some(time_nanos) = Self::try_parse_time_format(remaining)
1351            {
1352                total = total
1353                    .checked_add(time_nanos)
1354                    .ok_or(TimedeltaError::Overflow)?;
1355                break;
1356            }
1357
1358            let num_end = remaining
1359                .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
1360                .unwrap_or(remaining.len());
1361
1362            if num_end == 0 {
1363                return Err(TimedeltaError::InvalidFormat(s.to_string()));
1364            }
1365
1366            let num_str = &remaining[..num_end];
1367            let num: f64 = num_str
1368                .parse()
1369                .map_err(|_| TimedeltaError::InvalidFormat(s.to_string()))?;
1370
1371            remaining = remaining[num_end..].trim_start();
1372
1373            let unit_end = remaining
1374                .find(|c: char| c.is_ascii_digit() || c.is_whitespace())
1375                .unwrap_or(remaining.len());
1376
1377            let unit = &remaining[..unit_end];
1378            remaining = &remaining[unit_end..];
1379
1380            let multiplier = Self::unit_to_nanos(unit)
1381                .ok_or_else(|| TimedeltaError::InvalidFormat(s.to_string()))?;
1382
1383            // Per br-frankenpandas-zw3mg: pandas raises OverflowError on
1384            // huge scientific-notation Timedeltas like "1e100 days". The
1385            // raw `as i64` cast silently saturated to i64::MAX, masking
1386            // overflow before checked_add could catch it.
1387            let product = num * multiplier as f64;
1388            if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
1389                return Err(TimedeltaError::Overflow);
1390            }
1391            let nanos = product.round() as i64;
1392            total = total.checked_add(nanos).ok_or(TimedeltaError::Overflow)?;
1393        }
1394
1395        if total == 0 && !s.trim().is_empty() && s.trim() != "0" {
1396            return Err(TimedeltaError::InvalidFormat(s.to_string()));
1397        }
1398
1399        Ok(total)
1400    }
1401
1402    /// Map a pandas-style frequency-alias string to a nanosecond-count.
1403    ///
1404    /// Recognizes pandas's offset alias core set plus common word forms:
1405    /// W/week(s), D/day(s), H/hr/hour(s), m/T/min/minute(s), s/sec/second(s),
1406    /// ms/milli/millisecond(s)/L, us/µs/micro/microsecond(s)/U, ns/nano/
1407    /// nanosecond(s)/N. Empty string maps to days (matches pandas default).
1408    /// Returns `None` for unrecognized aliases — callers can choose to map
1409    /// that to NaT (consistent with the rest of fp-types) or surface as a
1410    /// typed error.
1411    ///
1412    /// Per br-frankenpandas-lbsx (9p0u Phase 2.6): public surface so
1413    /// downstream crates can consume the same alias map fp-types uses for
1414    /// `Timedelta::from_unit` / `Timestamp::*_to_unit`.
1415    #[must_use]
1416    pub fn unit_to_nanos(unit: &str) -> Option<i64> {
1417        match unit.to_lowercase().as_str() {
1418            "w" | "week" | "weeks" => Some(Self::NANOS_PER_WEEK),
1419            "d" | "day" | "days" => Some(Self::NANOS_PER_DAY),
1420            "h" | "hr" | "hour" | "hours" => Some(Self::NANOS_PER_HOUR),
1421            "m" | "min" | "minute" | "minutes" | "t" => Some(Self::NANOS_PER_MIN),
1422            "s" | "sec" | "second" | "seconds" => Some(Self::NANOS_PER_SEC),
1423            "ms" | "milli" | "millis" | "millisecond" | "milliseconds" | "l" => {
1424                Some(Self::NANOS_PER_MILLI)
1425            }
1426            "us" | "µs" | "micro" | "micros" | "microsecond" | "microseconds" | "u" => {
1427                Some(Self::NANOS_PER_MICRO)
1428            }
1429            "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" | "n" => Some(1),
1430            "" => Some(Self::NANOS_PER_DAY),
1431            _ => None,
1432        }
1433    }
1434
1435    pub fn components(nanos: i64) -> TimedeltaComponents {
1436        if nanos == Self::NAT {
1437            return TimedeltaComponents::default();
1438        }
1439
1440        // pandas/Python normalize via FLOOR division (like format()): the days
1441        // component can be negative while the time-of-day remainder is always in
1442        // [0, 1 day). So pd.Timedelta(-1,'s').components == (-1, 23, 59, 59, 0, 0, 0),
1443        // NOT the abs-based (0, 0, 0, 1, 0, 0, 0).
1444        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
1445        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
1446
1447        let hours = rem / Self::NANOS_PER_HOUR;
1448        let rem = rem % Self::NANOS_PER_HOUR;
1449
1450        let minutes = rem / Self::NANOS_PER_MIN;
1451        let rem = rem % Self::NANOS_PER_MIN;
1452
1453        let seconds = rem / Self::NANOS_PER_SEC;
1454        let rem = rem % Self::NANOS_PER_SEC;
1455
1456        let milliseconds = rem / Self::NANOS_PER_MILLI;
1457        let rem = rem % Self::NANOS_PER_MILLI;
1458
1459        let microseconds = rem / Self::NANOS_PER_MICRO;
1460        let nanoseconds = rem % Self::NANOS_PER_MICRO;
1461
1462        TimedeltaComponents {
1463            days,
1464            hours,
1465            minutes,
1466            seconds,
1467            milliseconds,
1468            microseconds,
1469            nanoseconds,
1470        }
1471    }
1472
1473    pub fn total_seconds(nanos: i64) -> f64 {
1474        if nanos == Self::NAT {
1475            f64::NAN
1476        } else {
1477            nanos as f64 / Self::NANOS_PER_SEC as f64
1478        }
1479    }
1480
1481    /// Convert to specified time unit.
1482    ///
1483    /// Matches pd.Timedelta.as_unit(). Supported units: ns, us, ms, s, m, h, D.
1484    #[must_use]
1485    pub fn as_unit(nanos: i64, unit: &str) -> f64 {
1486        if nanos == Self::NAT {
1487            return f64::NAN;
1488        }
1489        let nanos_f = nanos as f64;
1490        match unit {
1491            "ns" | "nanoseconds" => nanos_f,
1492            "us" | "microseconds" => nanos_f / Self::NANOS_PER_MICRO as f64,
1493            "ms" | "milliseconds" => nanos_f / Self::NANOS_PER_MILLI as f64,
1494            "s" | "seconds" => nanos_f / Self::NANOS_PER_SEC as f64,
1495            "m" | "minutes" => nanos_f / Self::NANOS_PER_MIN as f64,
1496            "h" | "hours" => nanos_f / Self::NANOS_PER_HOUR as f64,
1497            "D" | "days" => nanos_f / Self::NANOS_PER_DAY as f64,
1498            _ => f64::NAN,
1499        }
1500    }
1501
1502    /// Return the days component. Matches `pd.Timedelta.days`.
1503    #[must_use]
1504    pub fn days(nanos: i64) -> i64 {
1505        if nanos == Self::NAT {
1506            return 0; // pandas returns 0 for NaT.days (no error)
1507        }
1508        // FLOOR division like pandas: pd.Timedelta(-1,'s').days == -1, not 0.
1509        nanos.div_euclid(Self::NANOS_PER_DAY)
1510    }
1511
1512    /// Return the seconds component (0-86399). Matches `pd.Timedelta.seconds`.
1513    #[must_use]
1514    pub fn seconds(nanos: i64) -> i64 {
1515        if nanos == Self::NAT {
1516            return 0;
1517        }
1518        // Floor-normalized time-of-day remainder: pd.Timedelta(-1,'s').seconds == 86399.
1519        nanos.rem_euclid(Self::NANOS_PER_DAY) / Self::NANOS_PER_SEC
1520    }
1521
1522    /// Return the microseconds component (0-999999). Matches `pd.Timedelta.microseconds`.
1523    #[must_use]
1524    pub fn microseconds(nanos: i64) -> i64 {
1525        if nanos == Self::NAT {
1526            return 0;
1527        }
1528        nanos.rem_euclid(Self::NANOS_PER_SEC) / Self::NANOS_PER_MICRO
1529    }
1530
1531    /// Return the nanoseconds component (0-999). Matches `pd.Timedelta.nanoseconds`.
1532    #[must_use]
1533    pub fn nanoseconds(nanos: i64) -> i64 {
1534        if nanos == Self::NAT {
1535            return 0;
1536        }
1537        nanos.rem_euclid(Self::NANOS_PER_MICRO)
1538    }
1539
1540    pub fn format(nanos: i64) -> String {
1541        use std::fmt::Write as _;
1542
1543        if nanos == Self::NAT {
1544            return "NaT".to_string();
1545        }
1546
1547        // pandas / Python timedelta normalize via FLOOR division: the days
1548        // component can be negative while the time-of-day remainder is always
1549        // non-negative, and a negative-days value prints a '+' before the time
1550        // (e.g. -1s -> "-1 days +23:59:59", not "-0 days 00:00:01"). Compute the
1551        // components with Euclidean div/rem so the remainder is in [0, 1 day).
1552        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
1553        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
1554        let hours = rem / Self::NANOS_PER_HOUR;
1555        let minutes = (rem % Self::NANOS_PER_HOUR) / Self::NANOS_PER_MIN;
1556        let seconds = (rem % Self::NANOS_PER_MIN) / Self::NANOS_PER_SEC;
1557        let frac = rem % Self::NANOS_PER_SEC;
1558
1559        // Build directly into the returned allocation. The former path first
1560        // allocated an `HH:MM:SS` string, then copied it into the result.
1561        let mut result = String::with_capacity(32);
1562        let _ = write!(result, "{days} days ");
1563        // '+' joins the negative day count to the positive time remainder.
1564        if days < 0 {
1565            result.push('+');
1566        }
1567        let _ = write!(result, "{hours:02}:{minutes:02}:{seconds:02}");
1568        if frac > 0 {
1569            // pandas renders the sub-second part with microsecond precision
1570            // (6 digits) unless a sub-microsecond (nanosecond) component is
1571            // present, in which case it widens to 9 digits.
1572            if frac % 1_000 == 0 {
1573                let _ = write!(result, ".{:06}", frac / 1_000);
1574            } else {
1575                let _ = write!(result, ".{frac:09}");
1576            }
1577        }
1578        result
1579    }
1580
1581    pub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError> {
1582        let multiplier = Self::unit_to_nanos(unit)
1583            .ok_or_else(|| TimedeltaError::InvalidFormat(unit.to_string()))?;
1584        Ok((value * multiplier as f64).round() as i64)
1585    }
1586
1587    // ── Arithmetic (br-frankenpandas-4r56 Phase 1) ──────────────────────
1588    //
1589    // NaT propagation: any arithmetic with `NAT` returns `NAT`. Matches
1590    // pandas `pd.NaT + anything == NaT`, `pd.NaT - anything == NaT`, etc.
1591    // Saturation: i64 overflow clamps to i64::MAX/MIN (never wraps). Matches
1592    // pandas's OverflowError surface at the type-system boundary.
1593
1594    /// Add two Timedelta nanosecond values. NaT propagates; saturates on overflow.
1595    #[must_use]
1596    pub fn add(a: i64, b: i64) -> i64 {
1597        if a == Self::NAT || b == Self::NAT {
1598            return Self::NAT;
1599        }
1600        a.saturating_add(b)
1601    }
1602
1603    /// Subtract two Timedelta nanosecond values. NaT propagates; saturates on overflow.
1604    #[must_use]
1605    pub fn sub(a: i64, b: i64) -> i64 {
1606        if a == Self::NAT || b == Self::NAT {
1607            return Self::NAT;
1608        }
1609        a.saturating_sub(b)
1610    }
1611
1612    /// Negate a Timedelta value. NaT stays NaT. Saturates on overflow
1613    /// (pandas: `-pd.Timedelta.min` is NaT since min == -max - 1 cannot be negated).
1614    #[must_use]
1615    pub fn neg(a: i64) -> i64 {
1616        if a == Self::NAT {
1617            return Self::NAT;
1618        }
1619        a.saturating_neg()
1620    }
1621
1622    /// Absolute value of a Timedelta. NaT stays NaT. Saturates on overflow.
1623    #[must_use]
1624    pub fn abs(a: i64) -> i64 {
1625        if a == Self::NAT {
1626            return Self::NAT;
1627        }
1628        a.saturating_abs()
1629    }
1630
1631    /// Multiply a Timedelta value by an integer factor. NaT propagates;
1632    /// saturates on overflow.
1633    ///
1634    /// Matches pandas `pd.Timedelta(...) * int`.
1635    #[must_use]
1636    pub fn mul_scalar(a: i64, factor: i64) -> i64 {
1637        if a == Self::NAT {
1638            return Self::NAT;
1639        }
1640        a.saturating_mul(factor)
1641    }
1642
1643    /// Floor-divide a Timedelta value by an integer divisor. NaT propagates.
1644    /// Returns NaT on divide-by-zero (matches pandas, which raises, but we
1645    /// surface as NaT to avoid panics at the type-system boundary).
1646    ///
1647    /// Matches pandas / Python `pd.Timedelta(...) // int`: floor division,
1648    /// not truncation toward zero. `-100 // 3 == -34`, and `100 // -3 ==
1649    /// -34`. Rust's `/` truncates toward zero and `div_euclid` keeps the
1650    /// remainder non-negative — neither matches pandas when the divisor is
1651    /// negative. This helper adjusts trunc-toward-zero into floor.
1652    #[must_use]
1653    pub fn div_scalar(a: i64, divisor: i64) -> i64 {
1654        if a == Self::NAT || divisor == 0 {
1655            return Self::NAT;
1656        }
1657        // NAT == i64::MIN so the classic `i64::MIN / -1` overflow path is
1658        // already handled by the NAT check above. `(i64::MIN + 1) / -1`
1659        // equals `i64::MAX` with no overflow, so we never need a
1660        // saturation branch here.
1661        let q = a / divisor;
1662        let r = a % divisor;
1663        // If remainder is non-zero and has opposite sign from divisor,
1664        // Rust's trunc-toward-zero `/` is one step above the floor. Adjust
1665        // down by 1 to match Python/pandas floor division.
1666        if r != 0 && (r < 0) != (divisor < 0) {
1667            q - 1
1668        } else {
1669            q
1670        }
1671    }
1672
1673    /// Divide two Timedelta values, returning the ratio as f64.
1674    /// Matches pandas `pd.Timedelta(...) / pd.Timedelta(...)` → float.
1675    /// NaT in either operand → NaN. Zero divisor → ±Inf (per IEEE 754).
1676    #[must_use]
1677    pub fn div_timedelta(a: i64, b: i64) -> f64 {
1678        if a == Self::NAT || b == Self::NAT {
1679            return f64::NAN;
1680        }
1681        (a as f64) / (b as f64)
1682    }
1683
1684    /// Returns ISO 8601 duration format string.
1685    ///
1686    /// Matches pandas `pd.Timedelta.isoformat()`. Returns format like
1687    /// "P1DT2H3M4.567890123S" for 1 day, 2 hours, 3 minutes, 4.567890123 seconds.
1688    /// NaT returns "NaT".
1689    #[must_use]
1690    pub fn isoformat(nanos: i64) -> String {
1691        use std::fmt::Write as _;
1692
1693        if nanos == Self::NAT {
1694            return "NaT".to_string();
1695        }
1696
1697        let negative = nanos < 0;
1698        let abs_nanos = nanos.saturating_abs();
1699
1700        let days = abs_nanos / Self::NANOS_PER_DAY;
1701        let remaining = abs_nanos % Self::NANOS_PER_DAY;
1702
1703        let hours = remaining / Self::NANOS_PER_HOUR;
1704        let remaining = remaining % Self::NANOS_PER_HOUR;
1705
1706        let minutes = remaining / Self::NANOS_PER_MIN;
1707        let remaining = remaining % Self::NANOS_PER_MIN;
1708
1709        let seconds = remaining / Self::NANOS_PER_SEC;
1710        let sub_sec_nanos = remaining % Self::NANOS_PER_SEC;
1711
1712        // Build directly into the returned allocation. The former sequence of
1713        // `format!` calls allocated two temporary strings for integral values
1714        // and three for fractional values before copying them into `result`.
1715        let mut result = String::with_capacity(40);
1716        if negative {
1717            result.push('-');
1718        }
1719        // `fmt::Write for String` is infallible.
1720        let _ = write!(result, "P{days}DT{hours}H{minutes}M{seconds}");
1721        if sub_sec_nanos != 0 {
1722            result.push('.');
1723            let _ = write!(result, "{sub_sec_nanos:09}");
1724            while result.ends_with('0') {
1725                result.pop();
1726            }
1727        }
1728        result.push('S');
1729        result
1730    }
1731
1732    /// Rounds down to the nearest frequency unit.
1733    ///
1734    /// Matches pandas `pd.Timedelta.floor(freq)`. NaT is preserved.
1735    #[must_use]
1736    pub fn floor(nanos: i64, freq: &str) -> i64 {
1737        if nanos == Self::NAT {
1738            return Self::NAT;
1739        }
1740        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
1741            return Self::NAT;
1742        };
1743        if unit_nanos == 0 {
1744            return Self::NAT;
1745        }
1746        nanos.div_euclid(unit_nanos).saturating_mul(unit_nanos)
1747    }
1748
1749    /// Rounds up to the nearest frequency unit.
1750    ///
1751    /// Matches pandas `pd.Timedelta.ceil(freq)`. NaT is preserved.
1752    #[must_use]
1753    pub fn ceil(nanos: i64, freq: &str) -> i64 {
1754        if nanos == Self::NAT {
1755            return Self::NAT;
1756        }
1757        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
1758            return Self::NAT;
1759        };
1760        if unit_nanos == 0 {
1761            return Self::NAT;
1762        }
1763        let remainder = nanos.rem_euclid(unit_nanos);
1764        if remainder == 0 {
1765            nanos
1766        } else {
1767            nanos.saturating_add(unit_nanos - remainder)
1768        }
1769    }
1770
1771    /// Rounds to the nearest frequency unit.
1772    ///
1773    /// Matches pandas `pd.Timedelta.round(freq)`. Uses banker's rounding
1774    /// (round half to even). NaT is preserved.
1775    #[must_use]
1776    pub fn round(nanos: i64, freq: &str) -> i64 {
1777        if nanos == Self::NAT {
1778            return Self::NAT;
1779        }
1780        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
1781            return Self::NAT;
1782        };
1783        if unit_nanos == 0 {
1784            return Self::NAT;
1785        }
1786        let negative = nanos < 0;
1787        let abs_nanos = nanos.saturating_abs();
1788
1789        let quotient = abs_nanos / unit_nanos;
1790        let remainder = abs_nanos % unit_nanos;
1791        let half = unit_nanos / 2;
1792
1793        let rounded = if remainder > half {
1794            (quotient + 1) * unit_nanos
1795        } else if remainder < half {
1796            quotient * unit_nanos
1797        } else {
1798            // Exactly half: round to even
1799            if quotient % 2 == 0 {
1800                quotient * unit_nanos
1801            } else {
1802                (quotient + 1) * unit_nanos
1803            }
1804        };
1805
1806        if negative { -rounded } else { rounded }
1807    }
1808}
1809
1810// ── Timestamp types (br-frankenpandas-9p0u — 4r56 Phase 2) ─────────────
1811//
1812// Nanosecond-precision i64 since Unix epoch + optional IANA tz name.
1813// TZ-dependent arithmetic (DST transitions, tz conversion) is deferred
1814// to Phase 3 which pulls chrono_tz into fp-types; Phase 2 stores the
1815// tz name as opaque metadata and performs arithmetic on the absolute
1816// nanos axis only.
1817
1818/// Number of days in a given month (1-12) of a given year.
1819fn days_in_month(year: i64, month: u32) -> Option<u32> {
1820    if !(1..=12).contains(&month) {
1821        return None;
1822    }
1823    let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
1824    let days: [u32; 12] = [
1825        31,
1826        if is_leap { 29 } else { 28 },
1827        31,
1828        30,
1829        31,
1830        30,
1831        31,
1832        31,
1833        30,
1834        31,
1835        30,
1836        31,
1837    ];
1838    Some(days[(month - 1) as usize])
1839}
1840
1841/// Number of ISO-8601 weeks in a year (52 or 53).
1842///
1843/// A year has 53 ISO weeks iff its first day falls on a Thursday, or it is a
1844/// leap year whose first day is a Wednesday — captured by the dominical
1845/// closed form `p(year) == 4 || p(year - 1) == 3`, where
1846/// `p(y) = (y + ⌊y/4⌋ − ⌊y/100⌋ + ⌊y/400⌋) mod 7` is the weekday of Dec 31.
1847fn iso_weeks_in_year(year: i64) -> i64 {
1848    fn p(y: i64) -> i64 {
1849        (y + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400)).rem_euclid(7)
1850    }
1851    if p(year) == 4 || p(year - 1) == 3 {
1852        53
1853    } else {
1854        52
1855    }
1856}
1857
1858/// A nanosecond-precision point in time, Unix-epoch anchored.
1859///
1860/// Phase 2 scope: construction, arithmetic, equality, ordering, serde.
1861/// TZ semantics (IANA tz lookup, DST-aware shift) are deferred to Phase
1862/// 3 — see br-frankenpandas-4r56.
1863#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1864pub struct Timestamp {
1865    /// Nanoseconds since Unix epoch. `i64::MIN` is NaT.
1866    pub nanos: i64,
1867    /// Optional IANA time-zone name (e.g. `"US/Eastern"`). `None` means
1868    /// naive / UTC-anchored. Phase 2 treats this as opaque metadata;
1869    /// Phase 3 wires chrono_tz interpretation.
1870    #[serde(default, skip_serializing_if = "Option::is_none")]
1871    pub tz: Option<String>,
1872}
1873
1874impl Timestamp {
1875    /// NaT sentinel, parallel to `Timedelta::NAT`.
1876    pub const NAT: i64 = i64::MIN;
1877
1878    /// Construct a UTC-anchored (tz=None) Timestamp from nanoseconds
1879    /// since Unix epoch.
1880    #[must_use]
1881    pub const fn from_nanos(nanos: i64) -> Self {
1882        Self { nanos, tz: None }
1883    }
1884
1885    /// Construct a Timestamp tagged with an IANA tz name.
1886    ///
1887    /// Phase 2 doesn't interpret the tz — it only carries the name
1888    /// through arithmetic + serde. Phase 3 wires chrono_tz conversion.
1889    #[must_use]
1890    pub fn from_nanos_tz(nanos: i64, tz_name: impl Into<String>) -> Self {
1891        Self {
1892            nanos,
1893            tz: Some(tz_name.into()),
1894        }
1895    }
1896
1897    /// Returns the current UTC timestamp.
1898    ///
1899    /// Matches `pd.Timestamp.now()` / `pd.Timestamp.utcnow()`.
1900    #[must_use]
1901    pub fn now() -> Self {
1902        use std::time::{SystemTime, UNIX_EPOCH};
1903        let duration = SystemTime::now()
1904            .duration_since(UNIX_EPOCH)
1905            .unwrap_or_default();
1906        let nanos = duration.as_nanos() as i64;
1907        Self { nanos, tz: None }
1908    }
1909
1910    /// Alias for `now()`. Matches `pd.Timestamp.utcnow()`.
1911    #[must_use]
1912    pub fn utcnow() -> Self {
1913        Self::now()
1914    }
1915
1916    /// Returns today's date at midnight UTC.
1917    ///
1918    /// Matches `pd.Timestamp.today()`.
1919    #[must_use]
1920    pub fn today() -> Self {
1921        let now = Self::now();
1922        now.normalize()
1923    }
1924
1925    /// The NaT sentinel value for a Timestamp.
1926    #[must_use]
1927    pub const fn nat() -> Self {
1928        Self {
1929            nanos: Self::NAT,
1930            tz: None,
1931        }
1932    }
1933
1934    /// True iff this Timestamp is NaT.
1935    #[must_use]
1936    pub const fn is_nat(&self) -> bool {
1937        self.nanos == Self::NAT
1938    }
1939
1940    /// Nanoseconds since Unix epoch, matching `pd.Timestamp.value`.
1941    #[must_use]
1942    pub const fn value(&self) -> i64 {
1943        self.nanos
1944    }
1945
1946    /// Stored resolution unit, matching `pd.Timestamp.unit`.
1947    ///
1948    /// FrankenPandas `Timestamp` stores nanoseconds internally, so non-NaT
1949    /// values report `ns`. `NaT` has no unit.
1950    #[must_use]
1951    pub const fn unit(&self) -> Option<&'static str> {
1952        if self.is_nat() { None } else { Some("ns") }
1953    }
1954
1955    /// Return the resolution of the timestamp (always "ns" for nanoseconds).
1956    ///
1957    /// Matches `pd.Timestamp.resolution`. Returns None for NaT.
1958    #[must_use]
1959    pub const fn resolution(&self) -> Option<&'static str> {
1960        if self.is_nat() { None } else { Some("ns") }
1961    }
1962
1963    /// Numpy datetime64 scalar payload, matching `pd.Timestamp.asm8`.
1964    #[must_use]
1965    pub const fn asm8(&self) -> i64 {
1966        self.value()
1967    }
1968
1969    /// Convert to a datetime64 payload, matching `pd.Timestamp.to_datetime64()`.
1970    #[must_use]
1971    pub const fn to_datetime64(&self) -> i64 {
1972        self.value()
1973    }
1974
1975    /// Convert to a numpy scalar payload, matching `pd.Timestamp.to_numpy()`.
1976    #[must_use]
1977    pub const fn to_numpy(&self) -> i64 {
1978        self.value()
1979    }
1980
1981    /// POSIX timestamp in seconds, matching `pd.Timestamp.timestamp()`.
1982    ///
1983    /// Pandas exposes this through Python's datetime surface, so sub-microsecond
1984    /// nanoseconds are rounded to six decimal places. `NaT` raises in pandas;
1985    /// fp-types surfaces the same condition as a missing-value error.
1986    pub fn timestamp(&self) -> Result<f64, TypeError> {
1987        if self.is_nat() {
1988            return Err(TypeError::ValueIsMissing {
1989                kind: NullKind::NaT,
1990            });
1991        }
1992        let seconds = self.nanos as f64 / 1_000_000_000.0;
1993        let rounded = format!("{seconds:.6}").parse().unwrap_or(seconds);
1994        Ok(rounded)
1995    }
1996
1997    /// Add a Timedelta. NaT in either operand → NaT; saturates on overflow.
1998    /// TZ is preserved from `self`.
1999    #[must_use]
2000    pub fn add_timedelta(&self, td_nanos: i64) -> Self {
2001        if self.is_nat() || td_nanos == Timedelta::NAT {
2002            return Self::nat();
2003        }
2004        Self {
2005            nanos: self.nanos.saturating_add(td_nanos),
2006            tz: self.tz.clone(),
2007        }
2008    }
2009
2010    /// Subtract a Timedelta. NaT propagation + saturation; TZ preserved.
2011    #[must_use]
2012    pub fn sub_timedelta(&self, td_nanos: i64) -> Self {
2013        if self.is_nat() || td_nanos == Timedelta::NAT {
2014            return Self::nat();
2015        }
2016        Self {
2017            nanos: self.nanos.saturating_sub(td_nanos),
2018            tz: self.tz.clone(),
2019        }
2020    }
2021
2022    /// Subtract another Timestamp. Returns a Timedelta (i64 nanos).
2023    /// NaT in either → `Timedelta::NAT`; saturates on overflow.
2024    #[must_use]
2025    pub fn sub_timestamp(&self, other: &Self) -> i64 {
2026        if self.is_nat() || other.is_nat() {
2027            return Timedelta::NAT;
2028        }
2029        self.nanos.saturating_sub(other.nanos)
2030    }
2031
2032    /// NaT-aware semantic equality: two NaT Timestamps are equal to each
2033    /// other (matches pandas `pd.NaT == pd.NaT` under `equals()`, though
2034    /// pandas's `==` operator returns False for NaT==NaT — we follow the
2035    /// `semantic_eq` convention used elsewhere in fp-types).
2036    #[must_use]
2037    pub fn semantic_eq(&self, other: &Self) -> bool {
2038        if self.is_nat() && other.is_nat() {
2039            return true;
2040        }
2041        if self.is_nat() || other.is_nat() {
2042            return false;
2043        }
2044        self.nanos == other.nanos && self.tz == other.tz
2045    }
2046
2047    // ── Rounding to a Timedelta unit (br-frankenpandas-5h6n) ────────────
2048    //
2049    // Pure i64 arithmetic on the nanos axis. tz is preserved. Phase 3
2050    // chrono_tz integration will add a tz-aware variant that handles DST
2051    // boundaries correctly; these methods operate on the absolute time
2052    // axis, matching pandas's tz-naive `.floor` / `.ceil` / `.round`
2053    // semantics for unit values smaller than a day.
2054
2055    /// Round down to the nearest multiple of `unit_nanos`.
2056    ///
2057    /// Matches `pd.Timestamp(...).floor(unit)`. NaT in `self` or a
2058    /// non-positive `unit_nanos` returns NaT.
2059    #[must_use]
2060    pub fn floor_to(&self, unit_nanos: i64) -> Self {
2061        if self.is_nat() || unit_nanos <= 0 {
2062            return Self::nat();
2063        }
2064        let Some(nanos) = self.nanos.div_euclid(unit_nanos).checked_mul(unit_nanos) else {
2065            return Self::nat();
2066        };
2067        Self {
2068            nanos,
2069            tz: self.tz.clone(),
2070        }
2071    }
2072
2073    /// Round up to the nearest multiple of `unit_nanos`.
2074    ///
2075    /// Matches `pd.Timestamp(...).ceil(unit)`. NaT or non-positive
2076    /// `unit_nanos` returns NaT. Already-multiple inputs return self.
2077    #[must_use]
2078    pub fn ceil_to(&self, unit_nanos: i64) -> Self {
2079        if self.is_nat() || unit_nanos <= 0 {
2080            return Self::nat();
2081        }
2082        let rem = self.nanos.rem_euclid(unit_nanos);
2083        let nanos = if rem == 0 {
2084            self.nanos
2085        } else {
2086            self.nanos.saturating_add(unit_nanos - rem)
2087        };
2088        Self {
2089            nanos,
2090            tz: self.tz.clone(),
2091        }
2092    }
2093
2094    /// Round to the nearest multiple of `unit_nanos`, banker's rounding
2095    /// (half-to-even) on ties.
2096    ///
2097    /// Matches `pd.Timestamp(...).round(unit)`. NaT or non-positive
2098    /// `unit_nanos` returns NaT.
2099    #[must_use]
2100    pub fn round_to(&self, unit_nanos: i64) -> Self {
2101        if self.is_nat() || unit_nanos <= 0 {
2102            return Self::nat();
2103        }
2104        let floor = self.nanos.div_euclid(unit_nanos);
2105        let rem = self.nanos.rem_euclid(unit_nanos);
2106        let half = unit_nanos / 2;
2107        let chosen_floor = if rem < half {
2108            floor
2109        } else if rem > half {
2110            floor + 1
2111        } else if unit_nanos % 2 != 0 {
2112            // Odd unit can't have a true half; treat as round-up.
2113            floor + 1
2114        } else {
2115            // Tie: pick the even multiple.
2116            if floor % 2 == 0 { floor } else { floor + 1 }
2117        };
2118        Self {
2119            nanos: chosen_floor.saturating_mul(unit_nanos),
2120            tz: self.tz.clone(),
2121        }
2122    }
2123
2124    // ── String-unit rounding (br-frankenpandas-lbsx) ────────────────────
2125    //
2126    // Pandas convenience: `.floor('H')` / `.ceil('1D')` / `.round('s')`.
2127    // These delegate to `Timedelta::unit_to_nanos` for unit lookup, then to
2128    // the nanos-based `floor_to`/`ceil_to`/`round_to`. Unknown unit strings
2129    // return NaT, matching the rest of fp-types' "missing-input → missing-
2130    // output" convention.
2131
2132    /// Round down to the nearest multiple of the named unit.
2133    ///
2134    /// Matches `pd.Timestamp(...).floor(unit)`. Unknown unit → NaT.
2135    #[must_use]
2136    pub fn floor_to_unit(&self, unit: &str) -> Self {
2137        match Timedelta::unit_to_nanos(unit) {
2138            Some(unit_nanos) => self.floor_to(unit_nanos),
2139            None => Self::nat(),
2140        }
2141    }
2142
2143    /// Round up to the nearest multiple of the named unit.
2144    ///
2145    /// Matches `pd.Timestamp(...).ceil(unit)`. Unknown unit → NaT.
2146    #[must_use]
2147    pub fn ceil_to_unit(&self, unit: &str) -> Self {
2148        match Timedelta::unit_to_nanos(unit) {
2149            Some(unit_nanos) => self.ceil_to(unit_nanos),
2150            None => Self::nat(),
2151        }
2152    }
2153
2154    /// Round to the nearest multiple of the named unit, banker's rounding.
2155    ///
2156    /// Matches `pd.Timestamp(...).round(unit)`. Unknown unit → NaT.
2157    #[must_use]
2158    pub fn round_to_unit(&self, unit: &str) -> Self {
2159        match Timedelta::unit_to_nanos(unit) {
2160            Some(unit_nanos) => self.round_to(unit_nanos),
2161            None => Self::nat(),
2162        }
2163    }
2164
2165    /// Pandas-named alias for [`floor_to_unit`](Self::floor_to_unit).
2166    #[must_use]
2167    pub fn floor(&self, freq: &str) -> Self {
2168        self.floor_to_unit(freq)
2169    }
2170
2171    /// Pandas-named alias for [`ceil_to_unit`](Self::ceil_to_unit).
2172    #[must_use]
2173    pub fn ceil(&self, freq: &str) -> Self {
2174        self.ceil_to_unit(freq)
2175    }
2176
2177    /// Pandas-named alias for [`round_to_unit`](Self::round_to_unit).
2178    #[must_use]
2179    pub fn round(&self, freq: &str) -> Self {
2180        self.round_to_unit(freq)
2181    }
2182
2183    /// Extract the year component from the timestamp.
2184    ///
2185    /// Matches `pd.Timestamp.year`. Returns None for NaT.
2186    #[must_use]
2187    pub fn year(&self) -> Option<i64> {
2188        if self.is_nat() {
2189            return None;
2190        }
2191        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
2192        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
2193        // for the post-1970 positive case.
2194        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
2195        let days = days_since_epoch + 719_468;
2196        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
2197        let doe = days - era * 146_097;
2198        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
2199        let y = yoe + era * 400;
2200        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2201        let mp = (5 * doy + 2) / 153;
2202        let m = if mp < 10 { mp + 3 } else { mp - 9 };
2203        Some(if m <= 2 { y + 1 } else { y })
2204    }
2205
2206    /// Extract the month component (1-12) from the timestamp.
2207    ///
2208    /// Matches `pd.Timestamp.month`. Returns None for NaT.
2209    #[must_use]
2210    pub fn month(&self) -> Option<i64> {
2211        if self.is_nat() {
2212            return None;
2213        }
2214        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
2215        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
2216        // for the post-1970 positive case.
2217        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
2218        let days = days_since_epoch + 719_468;
2219        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
2220        let doe = days - era * 146_097;
2221        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
2222        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2223        let mp = (5 * doy + 2) / 153;
2224        Some(if mp < 10 { mp + 3 } else { mp - 9 })
2225    }
2226
2227    /// Extract the day component (1-31) from the timestamp.
2228    ///
2229    /// Matches `pd.Timestamp.day`. Returns None for NaT.
2230    #[must_use]
2231    pub fn day(&self) -> Option<i64> {
2232        if self.is_nat() {
2233            return None;
2234        }
2235        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
2236        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
2237        // for the post-1970 positive case.
2238        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
2239        let days = days_since_epoch + 719_468;
2240        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
2241        let doe = days - era * 146_097;
2242        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
2243        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2244        let mp = (5 * doy + 2) / 153;
2245        Some(doy - (153 * mp + 2) / 5 + 1)
2246    }
2247
2248    /// Extract the hour component (0-23) from the timestamp.
2249    ///
2250    /// Matches `pd.Timestamp.hour`. Returns None for NaT.
2251    #[must_use]
2252    pub fn hour(&self) -> Option<i64> {
2253        if self.is_nat() {
2254            return None;
2255        }
2256        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
2257        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
2258        // rem_euclid == `%` for the post-1970 positive case.
2259        let secs_of_day =
2260            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
2261        Some(secs_of_day / 3600)
2262    }
2263
2264    /// Extract the minute component (0-59) from the timestamp.
2265    ///
2266    /// Matches `pd.Timestamp.minute`. Returns None for NaT.
2267    #[must_use]
2268    pub fn minute(&self) -> Option<i64> {
2269        if self.is_nat() {
2270            return None;
2271        }
2272        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
2273        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
2274        // rem_euclid == `%` for the post-1970 positive case.
2275        let secs_of_day =
2276            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
2277        Some((secs_of_day % 3600) / 60)
2278    }
2279
2280    /// Extract the second component (0-59) from the timestamp.
2281    ///
2282    /// Matches `pd.Timestamp.second`. Returns None for NaT.
2283    #[must_use]
2284    pub fn second(&self) -> Option<i64> {
2285        if self.is_nat() {
2286            return None;
2287        }
2288        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
2289        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
2290        // rem_euclid == `%` for the post-1970 positive case.
2291        let secs_of_day =
2292            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
2293        Some(secs_of_day % 60)
2294    }
2295
2296    /// Extract the microsecond component (0-999999) from the timestamp.
2297    ///
2298    /// Matches `pd.Timestamp.microsecond`. Returns None for NaT.
2299    #[must_use]
2300    pub fn microsecond(&self) -> Option<i64> {
2301        if self.is_nat() {
2302            return None;
2303        }
2304        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
2305        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
2306        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
2307        Some((sub_nanos / 1000) as i64)
2308    }
2309
2310    /// Extract the nanosecond component (0-999) from the timestamp.
2311    ///
2312    /// Matches `pd.Timestamp.nanosecond`. Returns None for NaT.
2313    #[must_use]
2314    pub fn nanosecond(&self) -> Option<i64> {
2315        if self.is_nat() {
2316            return None;
2317        }
2318        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
2319        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
2320        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
2321        Some((sub_nanos % 1000) as i64)
2322    }
2323
2324    /// Return the day of the week (Monday=0, Sunday=6).
2325    ///
2326    /// Matches `pd.Timestamp.dayofweek`. Returns None for NaT.
2327    #[must_use]
2328    pub fn dayofweek(&self) -> Option<i64> {
2329        if self.is_nat() {
2330            return None;
2331        }
2332        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
2333        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
2334        let dow = ((days_since_epoch + 3) % 7 + 7) % 7;
2335        Some(dow)
2336    }
2337
2338    /// Alias for dayofweek(). Matches `pd.Timestamp.weekday`.
2339    #[must_use]
2340    pub fn weekday(&self) -> Option<i64> {
2341        self.dayofweek()
2342    }
2343
2344    /// Alias for dayofweek(). Matches `pd.Timestamp.day_of_week`.
2345    #[must_use]
2346    pub fn day_of_week(&self) -> Option<i64> {
2347        self.dayofweek()
2348    }
2349
2350    /// Return the day of the year (1-366).
2351    ///
2352    /// Matches `pd.Timestamp.dayofyear`. Returns None for NaT.
2353    #[must_use]
2354    pub fn dayofyear(&self) -> Option<i64> {
2355        if self.is_nat() {
2356            return None;
2357        }
2358        let m = self.month()?;
2359        let d = self.day()?;
2360        let y = self.year()?;
2361        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
2362        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
2363        let base = days_before[(m - 1) as usize] + d;
2364        if is_leap && m > 2 {
2365            Some(base + 1)
2366        } else {
2367            Some(base)
2368        }
2369    }
2370
2371    /// Alias for dayofyear(). Matches `pd.Timestamp.day_of_year`.
2372    #[must_use]
2373    pub fn day_of_year(&self) -> Option<i64> {
2374        self.dayofyear()
2375    }
2376
2377    /// Return the proleptic Gregorian ordinal (number of days since Jan 1, year 1).
2378    ///
2379    /// Matches `pd.Timestamp.toordinal()`. Returns None for NaT.
2380    #[must_use]
2381    pub fn toordinal(&self) -> Option<i64> {
2382        if self.is_nat() {
2383            return None;
2384        }
2385        let y = self.year()?;
2386        let m = self.month()?;
2387        let d = self.day()?;
2388        // Algorithm: count days from year 1 to the start of the given year,
2389        // add days in the months before the given month, add the day of month.
2390        // Account for leap years.
2391        let y_minus_1 = y - 1;
2392        let mut ordinal = y_minus_1 * 365 + y_minus_1 / 4 - y_minus_1 / 100 + y_minus_1 / 400;
2393        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
2394        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
2395        ordinal += days_before[(m - 1) as usize];
2396        if is_leap && m > 2 {
2397            ordinal += 1;
2398        }
2399        ordinal += d;
2400        Some(ordinal)
2401    }
2402
2403    /// Construct a Timestamp from a proleptic Gregorian ordinal.
2404    ///
2405    /// Matches `pd.Timestamp.fromordinal(ordinal)`. Returns NaT for invalid ordinals.
2406    #[must_use]
2407    pub fn fromordinal(ordinal: i64) -> Self {
2408        if ordinal <= 0 {
2409            return Self {
2410                nanos: Self::NAT,
2411                tz: None,
2412            };
2413        }
2414        // Convert y/m/d to days since Unix epoch, then to nanos
2415        // Unix epoch is 1970-01-01, which is ordinal 719163
2416        let days_since_epoch = ordinal - 719163;
2417        match days_since_epoch.checked_mul(Timedelta::NANOS_PER_DAY) {
2418            Some(nanos) => Self { nanos, tz: None },
2419            None => Self::nat(),
2420        }
2421    }
2422
2423    /// Return the Julian Date (astronomical day number).
2424    ///
2425    /// Matches `pd.Timestamp.to_julian_date()`. Returns NaN for NaT.
2426    /// The Julian Date is the continuous count of days since the beginning
2427    /// of the Julian Period (January 1, 4713 BC in the proleptic Julian calendar).
2428    #[must_use]
2429    pub fn to_julian_date(&self) -> f64 {
2430        if self.is_nat() {
2431            return f64::NAN;
2432        }
2433        // Gregorian ordinal 1 (Jan 1, year 1) corresponds to Julian Day 1721425.5
2434        // (at noon, since JD starts at noon)
2435        // For a timestamp at midnight, we subtract 0.5
2436        let ordinal = match self.toordinal() {
2437            Some(o) => o,
2438            None => return f64::NAN,
2439        };
2440        // Fractional day from time components
2441        let h = self.hour().unwrap_or(0) as f64;
2442        let m = self.minute().unwrap_or(0) as f64;
2443        let s = self.second().unwrap_or(0) as f64;
2444        let us = self.microsecond().unwrap_or(0) as f64;
2445        let ns = self.nanosecond().unwrap_or(0) as f64;
2446        let frac_day =
2447            (h + m / 60.0 + s / 3600.0 + us / 3_600_000_000.0 + ns / 3_600_000_000_000.0) / 24.0;
2448        // Julian day at midnight of ordinal 1 is 1721424.5
2449        1721424.5 + ordinal as f64 + frac_day
2450    }
2451
2452    /// Return the quarter (1-4) of the year.
2453    ///
2454    /// Matches `pd.Timestamp.quarter`. Returns None for NaT.
2455    #[must_use]
2456    pub fn quarter(&self) -> Option<i64> {
2457        self.month().map(|m| (m - 1) / 3 + 1)
2458    }
2459
2460    /// Return the ISO week number (1-53).
2461    ///
2462    /// Matches `pd.Timestamp.week`. Returns None for NaT.
2463    #[must_use]
2464    pub fn weekofyear(&self) -> Option<i64> {
2465        if self.is_nat() {
2466            return None;
2467        }
2468        let doy = self.dayofyear()?;
2469        let dow = self.dayofweek()?;
2470        let year = self.year()?;
2471        let iso_dow = if dow == 6 { 7 } else { dow + 1 };
2472        let week = (doy - iso_dow + 10) / 7;
2473        // ISO-8601 has 53-week years, so the clamps must consult the actual
2474        // week count, not hardcode 52/1: a week<1 belongs to the LAST week of
2475        // the previous year (52 OR 53), and a week beyond this year's count
2476        // wraps to week 1 of the next year. pandas isocalendar().week agrees:
2477        // 2021-01-01 -> 53 (2020 is a 53-week year), 2026-12-31 -> 53.
2478        if week < 1 {
2479            Some(iso_weeks_in_year(year - 1))
2480        } else if week > iso_weeks_in_year(year) {
2481            Some(1)
2482        } else {
2483            Some(week)
2484        }
2485    }
2486
2487    /// Alias for weekofyear(). Matches `pd.Timestamp.week`.
2488    #[must_use]
2489    pub fn week(&self) -> Option<i64> {
2490        self.weekofyear()
2491    }
2492
2493    /// Return the timestamp value in the specified unit.
2494    ///
2495    /// Matches `pd.Timestamp.value` when unit is nanoseconds.
2496    /// Supported units: "ns", "us", "ms", "s".
2497    #[must_use]
2498    pub fn to_unit(&self, unit: &str) -> Option<i64> {
2499        if self.is_nat() {
2500            return None;
2501        }
2502        match unit {
2503            "ns" | "nanosecond" | "nanoseconds" => Some(self.nanos),
2504            "us" | "microsecond" | "microseconds" => Some(self.nanos / 1_000),
2505            "ms" | "millisecond" | "milliseconds" => Some(self.nanos / 1_000_000),
2506            "s" | "second" | "seconds" => Some(self.nanos / 1_000_000_000),
2507            _ => None,
2508        }
2509    }
2510
2511    /// Whether the year is a leap year.
2512    ///
2513    /// Matches `pd.Timestamp.is_leap_year`. Returns None for NaT.
2514    #[must_use]
2515    pub fn is_leap_year(&self) -> Option<bool> {
2516        self.year()
2517            .map(|y| (y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
2518    }
2519
2520    /// Whether the day is the first day of the month.
2521    ///
2522    /// Matches `pd.Timestamp.is_month_start`. Returns None for NaT.
2523    #[must_use]
2524    pub fn is_month_start(&self) -> Option<bool> {
2525        self.day().map(|d| d == 1)
2526    }
2527
2528    /// Whether the day is the last day of the month.
2529    ///
2530    /// Matches `pd.Timestamp.is_month_end`. Returns None for NaT.
2531    #[must_use]
2532    pub fn is_month_end(&self) -> Option<bool> {
2533        let y = self.year()?;
2534        let m = self.month()?;
2535        let d = self.day()?;
2536        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
2537        let days_in_month: [i64; 12] = [
2538            31,
2539            if is_leap { 29 } else { 28 },
2540            31,
2541            30,
2542            31,
2543            30,
2544            31,
2545            31,
2546            30,
2547            31,
2548            30,
2549            31,
2550        ];
2551        Some(d == days_in_month[(m - 1) as usize])
2552    }
2553
2554    /// Whether the day is the first day of a quarter.
2555    ///
2556    /// Matches `pd.Timestamp.is_quarter_start`. Returns None for NaT.
2557    #[must_use]
2558    pub fn is_quarter_start(&self) -> Option<bool> {
2559        let m = self.month()?;
2560        let d = self.day()?;
2561        Some(d == 1 && (m == 1 || m == 4 || m == 7 || m == 10))
2562    }
2563
2564    /// Whether the day is the last day of a quarter.
2565    ///
2566    /// Matches `pd.Timestamp.is_quarter_end`. Returns None for NaT.
2567    #[must_use]
2568    pub fn is_quarter_end(&self) -> Option<bool> {
2569        let m = self.month()?;
2570        let d = self.day()?;
2571        Some(
2572            (m == 3 && d == 31)
2573                || (m == 6 && d == 30)
2574                || (m == 9 && d == 30)
2575                || (m == 12 && d == 31),
2576        )
2577    }
2578
2579    /// Whether the day is the first day of the year (Jan 1).
2580    ///
2581    /// Matches `pd.Timestamp.is_year_start`. Returns None for NaT.
2582    #[must_use]
2583    pub fn is_year_start(&self) -> Option<bool> {
2584        let m = self.month()?;
2585        let d = self.day()?;
2586        Some(m == 1 && d == 1)
2587    }
2588
2589    /// Whether the day is the last day of the year (Dec 31).
2590    ///
2591    /// Matches `pd.Timestamp.is_year_end`. Returns None for NaT.
2592    #[must_use]
2593    pub fn is_year_end(&self) -> Option<bool> {
2594        let m = self.month()?;
2595        let d = self.day()?;
2596        Some(m == 12 && d == 31)
2597    }
2598
2599    /// Return the number of days in the month of this timestamp.
2600    ///
2601    /// Matches `pd.Timestamp.days_in_month`. Returns None for NaT.
2602    #[must_use]
2603    pub fn days_in_month(&self) -> Option<i64> {
2604        let y = self.year()?;
2605        let m = self.month()?;
2606        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
2607        let days: [i64; 12] = [
2608            31,
2609            if is_leap { 29 } else { 28 },
2610            31,
2611            30,
2612            31,
2613            30,
2614            31,
2615            31,
2616            30,
2617            31,
2618            30,
2619            31,
2620        ];
2621        Some(days[(m - 1) as usize])
2622    }
2623
2624    /// Alias for days_in_month(). Matches `pd.Timestamp.daysinmonth`.
2625    #[must_use]
2626    pub fn daysinmonth(&self) -> Option<i64> {
2627        self.days_in_month()
2628    }
2629
2630    /// Normalize to midnight/day boundary, matching `pd.Timestamp.normalize()`.
2631    #[must_use]
2632    pub fn normalize(&self) -> Self {
2633        self.floor_to(Timedelta::NANOS_PER_DAY)
2634    }
2635
2636    /// Replace timestamp components with new values.
2637    ///
2638    /// Matches pd.Timestamp.replace(). None values keep the existing component.
2639    #[must_use]
2640    #[allow(clippy::too_many_arguments)]
2641    pub fn replace(
2642        &self,
2643        year: Option<i64>,
2644        month: Option<i64>,
2645        day: Option<i64>,
2646        hour: Option<i64>,
2647        minute: Option<i64>,
2648        second: Option<i64>,
2649        microsecond: Option<i64>,
2650        nanosecond: Option<i64>,
2651    ) -> Self {
2652        if self.is_nat() {
2653            return self.clone();
2654        }
2655        let cur_year = self.year().unwrap_or(1970);
2656        let cur_month = self.month().unwrap_or(1);
2657        let cur_day = self.day().unwrap_or(1);
2658        let cur_hour = self.hour().unwrap_or(0);
2659        let cur_minute = self.minute().unwrap_or(0);
2660        let cur_second = self.second().unwrap_or(0);
2661        let cur_micro = self.microsecond().unwrap_or(0);
2662        let cur_nano = self.nanosecond().unwrap_or(0);
2663
2664        let y = year.unwrap_or(cur_year);
2665        let mo = month.unwrap_or(cur_month);
2666        let d = day.unwrap_or(cur_day);
2667        let h = hour.unwrap_or(cur_hour);
2668        let mi = minute.unwrap_or(cur_minute);
2669        let s = second.unwrap_or(cur_second);
2670        let us = microsecond.unwrap_or(cur_micro);
2671        let ns = nanosecond.unwrap_or(cur_nano);
2672
2673        if !(1..=12).contains(&mo)
2674            || !(1..=days_in_month(y, mo as u32).unwrap_or(0) as i64).contains(&d)
2675            || !(0..=23).contains(&h)
2676            || !(0..=59).contains(&mi)
2677            || !(0..=59).contains(&s)
2678            || !(0..=999_999).contains(&us)
2679            || !(0..=999).contains(&ns)
2680        {
2681            return Self::nat();
2682        }
2683
2684        let days_from_epoch = Self::days_from_ymd(y, mo, d);
2685        let secs = h * 3600 + mi * 60 + s;
2686        let total_nanos = days_from_epoch * Timedelta::NANOS_PER_DAY
2687            + secs * Timedelta::NANOS_PER_SEC
2688            + us * Timedelta::NANOS_PER_MICRO
2689            + ns;
2690
2691        Self {
2692            nanos: total_nanos,
2693            tz: self.tz.clone(),
2694        }
2695    }
2696
2697    fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
2698        let y = if month <= 2 { year - 1 } else { year };
2699        let era = if y >= 0 { y } else { y - 399 } / 400;
2700        let yoe = y - era * 400;
2701        let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
2702        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
2703        era * 146097 + doe - 719468
2704    }
2705
2706    /// Return an ISO 8601 string representation of the timestamp.
2707    ///
2708    /// Matches `pd.Timestamp.isoformat()`. NaT returns "NaT".
2709    #[must_use]
2710    pub fn isoformat(&self) -> String {
2711        use std::fmt::Write as _;
2712
2713        if self.is_nat() {
2714            return "NaT".to_string();
2715        }
2716        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
2717        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
2718        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
2719        let nanos_of_day = self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
2720        let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
2721        let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
2722
2723        let days = days_since_epoch + 719_468;
2724        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
2725        let doe = days - era * 146_097;
2726        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
2727        let y = yoe + era * 400;
2728        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2729        let mp = (5 * doy + 2) / 153;
2730        let d = doy - (153 * mp + 2) / 5 + 1;
2731        let m = if mp < 10 { mp + 3 } else { mp - 9 };
2732        let year = if m <= 2 { y + 1 } else { y };
2733
2734        let hour = secs_of_day / 3600;
2735        let minute = (secs_of_day % 3600) / 60;
2736        let second = secs_of_day % 60;
2737
2738        // Build the timestamp and its optional timezone suffix in the returned
2739        // allocation. The former timezone-aware path first allocated `base`,
2740        // then allocated again to copy `base` into the suffixed result.
2741        let suffix_capacity = self
2742            .tz
2743            .as_ref()
2744            .map_or(0, |tz| if tz == "UTC" { 6 } else { tz.len() + 2 });
2745        let mut result = String::with_capacity(29 + suffix_capacity);
2746        if sub_nanos == 0 {
2747            let _ = write!(
2748                result,
2749                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}"
2750            );
2751        } else if sub_nanos.is_multiple_of(1_000) {
2752            let _ = write!(
2753                result,
2754                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{:06}",
2755                sub_nanos / 1_000
2756            );
2757        } else {
2758            let _ = write!(
2759                result,
2760                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{sub_nanos:09}"
2761            );
2762        }
2763        match &self.tz {
2764            Some(tz) if tz == "UTC" => result.push_str("+00:00"),
2765            Some(tz) => {
2766                result.push('[');
2767                result.push_str(tz);
2768                result.push(']');
2769            }
2770            None => {}
2771        }
2772        result
2773    }
2774
2775    /// Alias for isoformat.
2776    #[must_use]
2777    pub fn to_iso8601(&self) -> String {
2778        self.isoformat()
2779    }
2780
2781    /// Parse a datetime string into a Timestamp.
2782    ///
2783    /// Supports ISO 8601 formats:
2784    /// - "2024-01-15" (date only, time defaults to 00:00:00)
2785    /// - "2024-01-15T10:30:00" (datetime)
2786    /// - "2024-01-15 10:30:00" (space separator)
2787    /// - "2024-01-15T10:30:00.123456" (with fractional seconds)
2788    /// - "2024-01-15T10:30:00Z" (UTC timezone)
2789    /// - "2024-01-15T10:30:00+05:30" (offset timezone)
2790    /// - "NaT" (Not a Timestamp)
2791    ///
2792    /// Matches `pd.Timestamp()` constructor behavior.
2793    pub fn parse(s: &str) -> Result<Self, TypeError> {
2794        let s = s.trim();
2795
2796        if s.eq_ignore_ascii_case("nat") {
2797            return Ok(Self::nat());
2798        }
2799
2800        let Some((datetime_part, tz)) = Self::split_timezone(s) else {
2801            return Err(TypeError::ValueNotParseable {
2802                value: s.to_string(),
2803                target: "Timestamp".to_string(),
2804            });
2805        };
2806
2807        let (date_part, time_part) = if datetime_part.contains('T') {
2808            datetime_part
2809                .split_once('T')
2810                .ok_or_else(|| TypeError::ValueNotParseable {
2811                    value: s.to_string(),
2812                    target: "Timestamp".to_string(),
2813                })?
2814        } else if datetime_part.contains(' ')
2815            && datetime_part.chars().filter(|&c| c == ' ').count() == 1
2816        {
2817            datetime_part
2818                .split_once(' ')
2819                .ok_or_else(|| TypeError::ValueNotParseable {
2820                    value: s.to_string(),
2821                    target: "Timestamp".to_string(),
2822                })?
2823        } else {
2824            (datetime_part, "00:00:00")
2825        };
2826
2827        let (year, month, day) =
2828            Self::parse_date(date_part).ok_or_else(|| TypeError::ValueNotParseable {
2829                value: s.to_string(),
2830                target: "Timestamp".to_string(),
2831            })?;
2832
2833        let (hour, minute, second, nanos) =
2834            Self::parse_time(time_part).ok_or_else(|| TypeError::ValueNotParseable {
2835                value: s.to_string(),
2836                target: "Timestamp".to_string(),
2837            })?;
2838
2839        let total_nanos = Self::ymd_hms_to_nanos(year, month, day, hour, minute, second, nanos);
2840
2841        Ok(if let Some(tz_name) = tz {
2842            Self::from_nanos_tz(total_nanos, tz_name)
2843        } else {
2844            Self::from_nanos(total_nanos)
2845        })
2846    }
2847
2848    fn split_timezone(s: &str) -> Option<(&str, Option<String>)> {
2849        if let Some(stripped) = s.strip_suffix('Z') {
2850            Some((stripped, Some("UTC".to_string())))
2851        } else if let Some(idx) = s.rfind('+') {
2852            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
2853                Some((&s[..idx], Some(s[idx..].to_string())))
2854            } else if idx > 10 {
2855                None
2856            } else {
2857                Some((s, None))
2858            }
2859        } else if let Some(idx) = s.rfind('-') {
2860            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
2861                Some((&s[..idx], Some(s[idx..].to_string())))
2862            } else if idx > 10 {
2863                None
2864            } else {
2865                Some((s, None))
2866            }
2867        } else {
2868            Some((s, None))
2869        }
2870    }
2871
2872    fn is_timezone_offset(s: &str) -> bool {
2873        let bytes = s.as_bytes();
2874        if bytes.len() != 6 || !matches!(bytes[0], b'+' | b'-') || bytes[3] != b':' {
2875            return false;
2876        }
2877        if !bytes[1..3].iter().all(u8::is_ascii_digit)
2878            || !bytes[4..6].iter().all(u8::is_ascii_digit)
2879        {
2880            return false;
2881        }
2882        let hour = u32::from(bytes[1] - b'0') * 10 + u32::from(bytes[2] - b'0');
2883        let minute = u32::from(bytes[4] - b'0') * 10 + u32::from(bytes[5] - b'0');
2884        hour <= 23 && minute <= 59
2885    }
2886
2887    fn parse_date(s: &str) -> Option<(i64, u32, u32)> {
2888        let parts: Vec<&str> = s.split('-').collect();
2889        if parts.len() != 3 {
2890            return None;
2891        }
2892        let year: i64 = parts[0].parse().ok()?;
2893        let month: u32 = parts[1].parse().ok()?;
2894        let day: u32 = parts[2].parse().ok()?;
2895        if !(1..=days_in_month(year, month)?).contains(&day) {
2896            return None;
2897        }
2898        Some((year, month, day))
2899    }
2900
2901    fn parse_time(s: &str) -> Option<(u32, u32, u32, u64)> {
2902        let (time_str, frac_str) = match s.split_once('.') {
2903            Some((time, frac)) => (time, Some(frac)),
2904            None => (s, None),
2905        };
2906        let parts: Vec<&str> = time_str.split(':').collect();
2907        if parts.is_empty() || parts.len() > 3 {
2908            return None;
2909        }
2910        let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
2911        let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
2912        let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
2913
2914        if hour > 23 || minute > 59 || second > 59 {
2915            return None;
2916        }
2917
2918        let nanos = match frac_str {
2919            None => 0,
2920            Some(frac) => {
2921                if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
2922                    return None;
2923                }
2924                let digits = frac.len().min(9);
2925                let mut nanos = 0_u64;
2926                for byte in frac.bytes().take(digits) {
2927                    nanos = nanos * 10 + u64::from(byte - b'0');
2928                }
2929                for _ in digits..9 {
2930                    nanos *= 10;
2931                }
2932                nanos
2933            }
2934        };
2935
2936        Some((hour, minute, second, nanos))
2937    }
2938
2939    fn ymd_hms_to_nanos(
2940        year: i64,
2941        month: u32,
2942        day: u32,
2943        hour: u32,
2944        minute: u32,
2945        second: u32,
2946        sub_nanos: u64,
2947    ) -> i64 {
2948        let m = month as i64;
2949        let d = day as i64;
2950
2951        let y = if m <= 2 { year - 1 } else { year };
2952        let era = if y >= 0 { y } else { y - 399 } / 400;
2953        let yoe = y - era * 400;
2954        let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
2955        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
2956        let days_since_epoch = era * 146_097 + doe - 719_468;
2957
2958        let total_seconds = days_since_epoch * 86400
2959            + (hour as i64) * 3600
2960            + (minute as i64) * 60
2961            + (second as i64);
2962        total_seconds * Timedelta::NANOS_PER_SEC + sub_nanos as i64
2963    }
2964
2965    /// Format timestamp using strftime directives.
2966    ///
2967    /// Matches `pd.Timestamp.strftime(format)`. Supports: %Y (year), %m (month),
2968    /// %d (day), %H (hour), %M (minute), %S (second), %f (microsecond).
2969    /// NaT returns "NaT".
2970    #[must_use]
2971    pub fn strftime(&self, format: &str) -> String {
2972        use std::fmt::Write as _;
2973
2974        if self.is_nat() {
2975            return "NaT".to_string();
2976        }
2977        let total_secs = self.nanos / Timedelta::NANOS_PER_SEC;
2978        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
2979        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
2980        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
2981
2982        let days_since_epoch = total_secs / 86400;
2983        let secs_of_day = (total_secs % 86400 + 86400) % 86400;
2984
2985        let days = days_since_epoch + 719_468;
2986        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
2987        let doe = days - era * 146_097;
2988        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
2989        let y = yoe + era * 400;
2990        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2991        let mp = (5 * doy + 2) / 153;
2992        let d = doy - (153 * mp + 2) / 5 + 1;
2993        let m = if mp < 10 { mp + 3 } else { mp - 9 };
2994        let year = if m <= 2 { y + 1 } else { y };
2995
2996        let hour = secs_of_day / 3600;
2997        let minute = (secs_of_day % 3600) / 60;
2998        let second = secs_of_day % 60;
2999        let micros = sub_nanos / 1000;
3000
3001        // Write recognized directives directly into the returned allocation.
3002        // The former seven-step replacement chain copied the whole format once
3003        // per directive and allocated a temporary string for every component.
3004        let mut result = String::with_capacity(format.len().saturating_add(32));
3005        let mut rest = format;
3006        while let Some(percent) = rest.find('%') {
3007            result.push_str(&rest[..percent]);
3008            let directive = &rest[percent..];
3009            rest = if let Some(next) = directive.strip_prefix("%Y") {
3010                let _ = write!(result, "{year:04}");
3011                next
3012            } else if let Some(next) = directive.strip_prefix("%m") {
3013                let _ = write!(result, "{m:02}");
3014                next
3015            } else if let Some(next) = directive.strip_prefix("%d") {
3016                let _ = write!(result, "{d:02}");
3017                next
3018            } else if let Some(next) = directive.strip_prefix("%H") {
3019                let _ = write!(result, "{hour:02}");
3020                next
3021            } else if let Some(next) = directive.strip_prefix("%M") {
3022                let _ = write!(result, "{minute:02}");
3023                next
3024            } else if let Some(next) = directive.strip_prefix("%S") {
3025                let _ = write!(result, "{second:02}");
3026                next
3027            } else if let Some(next) = directive.strip_prefix("%f") {
3028                let _ = write!(result, "{micros:06}");
3029                next
3030            } else {
3031                // Preserve the chained `replace` behavior for unknown, escaped,
3032                // and trailing percent signs; the following byte may still begin
3033                // a recognized directive (for example, `%%Y` -> `%2024`).
3034                result.push('%');
3035                &directive[1..]
3036            };
3037        }
3038        result.push_str(rest);
3039        result
3040    }
3041
3042    /// Return the day of the week as a string (e.g., "Monday").
3043    ///
3044    /// Matches `pd.Timestamp.day_name()`. NaT returns "NaT".
3045    #[must_use]
3046    pub fn day_name(&self) -> String {
3047        const NAMES: [&str; 7] = [
3048            "Thursday",
3049            "Friday",
3050            "Saturday",
3051            "Sunday",
3052            "Monday",
3053            "Tuesday",
3054            "Wednesday",
3055        ];
3056        if self.is_nat() {
3057            return "NaT".to_string();
3058        }
3059        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
3060        // Truncating `/` rounds a negative, non-midnight instant TOWARD zero, so
3061        // it lands on the following day and names the wrong weekday: pandas 2.2.3
3062        // gives 1969-07-20T20:17:40 -> "Sunday", truncation gave "Monday". The
3063        // wkjtw fix was applied to `dayofweek` but never here.
3064        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
3065        let dow = ((days_since_epoch % 7) + 7) % 7;
3066        NAMES[dow as usize].to_string()
3067    }
3068
3069    /// Return the month name as a string (e.g., "January").
3070    ///
3071    /// Matches `pd.Timestamp.month_name()`. NaT returns "NaT".
3072    #[must_use]
3073    pub fn month_name(&self) -> String {
3074        const NAMES: [&str; 12] = [
3075            "January",
3076            "February",
3077            "March",
3078            "April",
3079            "May",
3080            "June",
3081            "July",
3082            "August",
3083            "September",
3084            "October",
3085            "November",
3086            "December",
3087        ];
3088        if self.is_nat() {
3089            return "NaT".to_string();
3090        }
3091        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
3092        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
3093        // for the post-1970 positive case.
3094        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
3095        let days = days_since_epoch + 719_468;
3096        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
3097        let doe = days - era * 146_097;
3098        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
3099        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
3100        let mp = (5 * doy + 2) / 153;
3101        let m = if mp < 10 { mp + 3 } else { mp - 9 };
3102        NAMES[(m - 1) as usize].to_string()
3103    }
3104
3105    /// Localize a naive timestamp to a timezone.
3106    ///
3107    /// Matches `pd.Timestamp.tz_localize(tz)`. If `tz` is None, removes the
3108    /// timezone (makes timestamp naive). NaT propagates.
3109    #[must_use]
3110    pub fn tz_localize(&self, tz: Option<&str>) -> Self {
3111        if self.is_nat() {
3112            return Self::nat();
3113        }
3114        Self {
3115            nanos: self.nanos,
3116            tz: tz.map(String::from),
3117        }
3118    }
3119
3120    /// Convert timezone-aware timestamp to another timezone.
3121    ///
3122    /// Matches `pd.Timestamp.tz_convert(tz)`. If timestamp is naive (no tz),
3123    /// the timezone is simply attached without conversion. NaT propagates.
3124    /// Note: actual UTC offset conversion requires chrono-tz (Phase 3).
3125    #[must_use]
3126    pub fn tz_convert(&self, tz: &str) -> Self {
3127        if self.is_nat() {
3128            return Self::nat();
3129        }
3130        Self {
3131            nanos: self.nanos,
3132            tz: Some(tz.to_string()),
3133        }
3134    }
3135
3136    /// Create a Timestamp from a Unix timestamp (seconds since epoch).
3137    ///
3138    /// Matches `pd.Timestamp.fromtimestamp(ts)`. The optional `tz` parameter
3139    /// specifies the timezone to localize to.
3140    #[must_use]
3141    pub fn fromtimestamp(ts: f64, tz: Option<&str>) -> Self {
3142        if ts.is_nan() || ts.is_infinite() {
3143            return Self::nat();
3144        }
3145        let nanos_f64 = ts * 1_000_000_000.0;
3146        // Check for overflow before casting - i64 range is roughly ±9.2e18
3147        const MAX_NANOS: f64 = i64::MAX as f64;
3148        const MIN_NANOS: f64 = i64::MIN as f64;
3149        if !(MIN_NANOS..=MAX_NANOS).contains(&nanos_f64) {
3150            return Self::nat();
3151        }
3152        Self {
3153            nanos: nanos_f64 as i64,
3154            tz: tz.map(String::from),
3155        }
3156    }
3157
3158    /// Create a Timestamp from milliseconds since epoch.
3159    ///
3160    /// Convenience constructor complementing fromtimestamp.
3161    #[must_use]
3162    pub fn from_millis(ms: i64, tz: Option<&str>) -> Self {
3163        Self {
3164            nanos: ms.saturating_mul(1_000_000),
3165            tz: tz.map(String::from),
3166        }
3167    }
3168
3169    /// Create a Timestamp from microseconds since epoch.
3170    ///
3171    /// Convenience constructor complementing fromtimestamp.
3172    #[must_use]
3173    pub fn from_micros(us: i64, tz: Option<&str>) -> Self {
3174        Self {
3175            nanos: us.saturating_mul(1_000),
3176            tz: tz.map(String::from),
3177        }
3178    }
3179
3180    /// Return the timezone string, or None if naive.
3181    #[must_use]
3182    pub fn tzinfo(&self) -> Option<&str> {
3183        self.tz.as_deref()
3184    }
3185
3186    /// Return the timezone name, or None if naive.
3187    ///
3188    /// Alias for tzinfo() matching pandas Timestamp.tzname().
3189    #[must_use]
3190    pub fn tzname(&self) -> Option<&str> {
3191        self.tzinfo()
3192    }
3193}
3194
3195impl std::fmt::Display for Timestamp {
3196    /// Phase 2 debug-style format; Phase 3 replaces with pandas ISO-8601
3197    /// notation once chrono interpretation lands.
3198    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3199        if self.is_nat() {
3200            return f.write_str("NaT");
3201        }
3202        match &self.tz {
3203            Some(tz) => write!(f, "Timestamp[{}, {}]", self.nanos, tz),
3204            None => write!(f, "Timestamp[{}, UTC]", self.nanos),
3205        }
3206    }
3207}
3208
3209impl PartialOrd for Timestamp {
3210    /// Orders by nanos axis; NaT is incomparable (`None`). Tz difference
3211    /// does not affect ordering — two Timestamps at the same absolute
3212    /// nanos compare equal regardless of tz label (Phase 3 will revisit
3213    /// whether tz affects ordering semantics).
3214    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
3215        if self.is_nat() || other.is_nat() {
3216            return None;
3217        }
3218        Some(self.nanos.cmp(&other.nanos))
3219    }
3220}
3221
3222// ── Missingness utilities ──────────────────────────────────────────────
3223
3224pub fn isna(values: &[Scalar]) -> Vec<bool> {
3225    values.iter().map(Scalar::is_missing).collect()
3226}
3227
3228pub fn isnull(values: &[Scalar]) -> Vec<bool> {
3229    isna(values)
3230}
3231
3232pub fn notna(values: &[Scalar]) -> Vec<bool> {
3233    values.iter().map(|v| !v.is_missing()).collect()
3234}
3235
3236pub fn notnull(values: &[Scalar]) -> Vec<bool> {
3237    notna(values)
3238}
3239
3240pub fn count_na(values: &[Scalar]) -> usize {
3241    values.iter().filter(|v| v.is_missing()).count()
3242}
3243
3244pub fn fill_na(values: &[Scalar], fill: &Scalar) -> Vec<Scalar> {
3245    values
3246        .iter()
3247        .map(|v| {
3248            if v.is_missing() {
3249                fill.clone()
3250            } else {
3251                v.clone()
3252            }
3253        })
3254        .collect()
3255}
3256
3257pub fn dropna(values: &[Scalar]) -> Vec<Scalar> {
3258    values.iter().filter(|v| !v.is_missing()).cloned().collect()
3259}
3260
3261// ── Nanops: null-skipping numeric reductions ───────────────────────────
3262
3263fn collect_finite(values: &[Scalar]) -> Vec<f64> {
3264    values
3265        .iter()
3266        .filter(|v| !v.is_missing())
3267        .filter_map(|v| v.to_f64().ok())
3268        .collect()
3269}
3270
3271/// Per br-frankenpandas-620mj: if a column is uniformly Timedelta64
3272/// (with optional NAT/Null missing), sum/mean preserve Timedelta dtype
3273/// matching pandas — instead of silently coercing to Float64(0.0) via
3274/// the collect_finite path (which drops Timedelta64 because to_f64
3275/// errors). Returns Some(sum_in_ns, observed_count) when applicable.
3276fn collect_timedelta_ns(values: &[Scalar]) -> Option<(i128, usize)> {
3277    let mut sum: i128 = 0;
3278    let mut count: usize = 0;
3279    let mut saw_timedelta = false;
3280    for v in values {
3281        if v.is_missing() {
3282            continue;
3283        }
3284        match v {
3285            Scalar::Timedelta64(ns) => {
3286                saw_timedelta = true;
3287                sum += i128::from(*ns);
3288                count += 1;
3289            }
3290            // Any non-Timedelta non-missing value bails out to the
3291            // existing Float64 path, preserving cross-type behavior.
3292            _ => return None,
3293        }
3294    }
3295    if saw_timedelta {
3296        Some((sum, count))
3297    } else {
3298        None
3299    }
3300}
3301
3302pub fn nansum(values: &[Scalar]) -> Scalar {
3303    if let Some((sum, _)) = collect_timedelta_ns(values) {
3304        let clamped = sum.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
3305        return Scalar::Timedelta64(clamped as i64);
3306    }
3307    // Fused single-pass fold: filter missing / non-f64-coercible and accumulate
3308    // in one scan, avoiding the intermediate `collect_finite` Vec<f64> and its
3309    // second pass. Bit-identical to `collect_finite(..).iter().sum()`: same
3310    // finite values in the same order, same left-fold f64 `+` (empty -> 0.0).
3311    let mut sum = 0.0_f64;
3312    for v in values {
3313        if v.is_missing() {
3314            continue;
3315        }
3316        if let Ok(x) = v.to_f64() {
3317            sum += x;
3318        }
3319    }
3320    Scalar::Float64(sum)
3321}
3322
3323pub fn nanmean(values: &[Scalar]) -> Scalar {
3324    if let Some((sum, count)) = collect_timedelta_ns(values) {
3325        if count == 0 {
3326            return Scalar::Timedelta64(Timedelta::NAT);
3327        }
3328        let mean = sum / count as i128;
3329        let clamped = mean.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
3330        return Scalar::Timedelta64(clamped as i64);
3331    }
3332    // Fused single-pass fold (see `nansum`): accumulate sum + count of finite
3333    // values in one scan. Bit-identical to the prior `collect_finite` two-pass:
3334    // count == nums.len(), sum folds the same values in the same order.
3335    let mut sum = 0.0_f64;
3336    let mut count = 0usize;
3337    for v in values {
3338        if v.is_missing() {
3339            continue;
3340        }
3341        if let Ok(x) = v.to_f64() {
3342            sum += x;
3343            count += 1;
3344        }
3345    }
3346    if count == 0 {
3347        return Scalar::Null(NullKind::NaN);
3348    }
3349    Scalar::Float64(sum / count as f64)
3350}
3351
3352pub fn nanany(values: &[Scalar]) -> Scalar {
3353    for v in values {
3354        if v.is_missing() {
3355            continue;
3356        }
3357        match v {
3358            Scalar::Bool(flag) if *flag => return Scalar::Bool(true),
3359            Scalar::Int64(val) if *val != 0 => return Scalar::Bool(true),
3360            Scalar::Float64(val) if !val.is_nan() && *val != 0.0 => return Scalar::Bool(true),
3361            Scalar::Utf8(val) if !val.is_empty() => return Scalar::Bool(true),
3362            // pandas Series([td]).any() returns True for any non-zero
3363            // Timedelta. NaT is already filtered by is_missing() above.
3364            Scalar::Timedelta64(ns) if *ns != 0 => return Scalar::Bool(true),
3365            _ => continue,
3366        }
3367    }
3368    Scalar::Bool(false)
3369}
3370
3371pub fn nanall(values: &[Scalar]) -> Scalar {
3372    for v in values {
3373        if v.is_missing() {
3374            continue;
3375        }
3376        match v {
3377            Scalar::Bool(flag) if !*flag => return Scalar::Bool(false),
3378            Scalar::Int64(val) if *val == 0 => return Scalar::Bool(false),
3379            Scalar::Float64(val) if val.is_nan() || *val == 0.0 => return Scalar::Bool(false),
3380            Scalar::Utf8(val) if val.is_empty() => return Scalar::Bool(false),
3381            // pandas Series([td(0)]).all() returns False; any non-zero
3382            // Timedelta is truthy. NaT is already filtered by is_missing.
3383            Scalar::Timedelta64(ns) if *ns == 0 => return Scalar::Bool(false),
3384            _ => continue,
3385        }
3386    }
3387    Scalar::Bool(true)
3388}
3389
3390pub fn nancount(values: &[Scalar]) -> Scalar {
3391    let n = values.iter().filter(|v| !v.is_missing()).count();
3392    Scalar::Int64(n as i64)
3393}
3394
3395pub fn nanmin(values: &[Scalar]) -> Scalar {
3396    let mut min: Option<&Scalar> = None;
3397    for v in values {
3398        if v.is_missing() {
3399            continue;
3400        }
3401        match (min, v) {
3402            (None, _) => min = Some(v),
3403            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
3404                if b < a {
3405                    min = Some(v)
3406                }
3407            }
3408            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
3409                if *b < *a {
3410                    min = Some(v)
3411                }
3412            }
3413            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
3414                if b < a {
3415                    min = Some(v)
3416                }
3417            }
3418            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
3419                if b < a {
3420                    min = Some(v)
3421                }
3422            }
3423            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
3424            // the catch-all below would silently return NaN. Compare ns
3425            // representations directly; NAT is already filtered by
3426            // is_missing() above.
3427            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
3428                if b < a {
3429                    min = Some(v)
3430                }
3431            }
3432            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
3433                (Ok(af), Ok(bf)) if bf < af => min = Some(v),
3434                (Ok(_), Ok(_)) => {}
3435                _ => return Scalar::Null(NullKind::NaN),
3436            },
3437        }
3438    }
3439    match min {
3440        Some(v) => v.clone(),
3441        None => Scalar::Null(NullKind::NaN),
3442    }
3443}
3444
3445pub fn nanmax(values: &[Scalar]) -> Scalar {
3446    let mut max: Option<&Scalar> = None;
3447    for v in values {
3448        if v.is_missing() {
3449            continue;
3450        }
3451        match (max, v) {
3452            (None, _) => max = Some(v),
3453            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
3454                if b > a {
3455                    max = Some(v)
3456                }
3457            }
3458            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
3459                if *b > *a {
3460                    max = Some(v)
3461                }
3462            }
3463            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
3464                if b > a {
3465                    max = Some(v)
3466                }
3467            }
3468            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
3469                if b > a {
3470                    max = Some(v)
3471                }
3472            }
3473            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
3474            // the catch-all below would silently return NaN. Compare ns
3475            // representations directly; NAT is already filtered above.
3476            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
3477                if b > a {
3478                    max = Some(v)
3479                }
3480            }
3481            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
3482                (Ok(af), Ok(bf)) if bf > af => max = Some(v),
3483                (Ok(_), Ok(_)) => {}
3484                _ => return Scalar::Null(NullKind::NaN),
3485            },
3486        }
3487    }
3488    match max {
3489        Some(v) => v.clone(),
3490        None => Scalar::Null(NullKind::NaN),
3491    }
3492}
3493
3494/// Per br-frankenpandas-j8ntk: harvest ns values from a uniformly-Timedelta64
3495/// input as f64 (the f64 representation has 53 bits of mantissa, sufficient
3496/// for ns spans up to ~104 days exactly; beyond that pandas itself loses
3497/// precision the same way). Returns None if any non-missing value is not
3498/// Timedelta64.
3499fn collect_timedelta_ns_f64(values: &[Scalar]) -> Option<Vec<f64>> {
3500    let mut out = Vec::with_capacity(values.len());
3501    let mut saw_td = false;
3502    for v in values {
3503        if v.is_missing() {
3504            continue;
3505        }
3506        match v {
3507            Scalar::Timedelta64(ns) => {
3508                saw_td = true;
3509                out.push(*ns as f64);
3510            }
3511            _ => return None,
3512        }
3513    }
3514    if saw_td { Some(out) } else { None }
3515}
3516
3517/// Clamp an f64 result into i64 range and wrap as Scalar::Timedelta64.
3518fn float_ns_to_timedelta(value: f64) -> Scalar {
3519    if !value.is_finite() {
3520        return Scalar::Timedelta64(Timedelta::NAT);
3521    }
3522    let clamped = value.clamp(i64::MIN as f64, i64::MAX as f64);
3523    Scalar::Timedelta64(clamped as i64)
3524}
3525
3526pub fn nanmedian(values: &[Scalar]) -> Scalar {
3527    // Per br-frankenpandas-j8ntk: Timedelta64 median preserves dtype.
3528    if let Some(mut td) = collect_timedelta_ns_f64(values) {
3529        if td.is_empty() {
3530            return Scalar::Timedelta64(Timedelta::NAT);
3531        }
3532        // O(n) selection instead of a full sort (see the numeric arm below):
3533        // collect_timedelta_ns_f64 yields finite ns (NaT excluded), so the
3534        // comparator is a total order; order statistics depend only on values,
3535        // so the unstable partition yields the same td[mid-1]/td[mid].
3536        let n = td.len();
3537        let mid = n / 2;
3538        let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
3539        let (left, mid_ref, _right) = td.select_nth_unstable_by(mid, cmp);
3540        let mid_val = *mid_ref;
3541        let median_ns = if n.is_multiple_of(2) {
3542            let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
3543            (lower + mid_val) / 2.0
3544        } else {
3545            mid_val
3546        };
3547        return float_ns_to_timedelta(median_ns);
3548    }
3549    let mut nums = collect_finite(values);
3550    if nums.is_empty() {
3551        return Scalar::Null(NullKind::NaN);
3552    }
3553    // O(n) selection instead of an O(n log n) full sort: select_nth_unstable_by
3554    // places the `mid`-th smallest at index `mid` with all smaller elements
3555    // (unordered) in the left partition. For even n the (mid-1)-th smallest is
3556    // the MAX of that left partition. Bit-identical to the sort path: order
3557    // statistics depend only on VALUES, and ties share a value, so the
3558    // unstable partition yields the same nums[mid-1]/nums[mid] the sort did.
3559    let n = nums.len();
3560    let mid = n / 2;
3561    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
3562    let (left, mid_ref, _right) = nums.select_nth_unstable_by(mid, cmp);
3563    let mid_val = *mid_ref;
3564    if n.is_multiple_of(2) {
3565        let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
3566        Scalar::Float64((lower + mid_val) / 2.0)
3567    } else {
3568        Scalar::Float64(mid_val)
3569    }
3570}
3571
3572pub fn nanvar(values: &[Scalar], ddof: usize) -> Scalar {
3573    // Per br-frankenpandas-j8ntk: Timedelta64 var preserves dtype — pandas
3574    // returns Timedelta even though variance is ns² conceptually; matching.
3575    if let Some(td) = collect_timedelta_ns_f64(values) {
3576        if td.len() <= ddof {
3577            return Scalar::Timedelta64(Timedelta::NAT);
3578        }
3579        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
3580        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
3581        return float_ns_to_timedelta(sum_sq / (td.len() - ddof) as f64);
3582    }
3583    let nums = collect_finite(values);
3584    if nums.len() <= ddof {
3585        return Scalar::Null(NullKind::NaN);
3586    }
3587    let mean: f64 = nums.iter().sum::<f64>() / nums.len() as f64;
3588    let sum_sq: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
3589    Scalar::Float64(sum_sq / (nums.len() - ddof) as f64)
3590}
3591
3592pub fn nanstd(values: &[Scalar], ddof: usize) -> Scalar {
3593    // Per br-frankenpandas-j8ntk: Timedelta64 std preserves dtype.
3594    if let Some(td) = collect_timedelta_ns_f64(values) {
3595        if td.len() <= ddof {
3596            return Scalar::Timedelta64(Timedelta::NAT);
3597        }
3598        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
3599        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
3600        let var = sum_sq / (td.len() - ddof) as f64;
3601        return float_ns_to_timedelta(var.sqrt());
3602    }
3603    match nanvar(values, ddof) {
3604        Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
3605        other => other,
3606    }
3607}
3608
3609/// Standard error of the mean over non-missing values.
3610///
3611/// Matches `pd.Series.sem(ddof=1)` / `scipy.stats.sem`. Computed as
3612/// `std(values, ddof) / sqrt(n)` where `n` is the non-missing count.
3613/// Returns `Null(NaN)` when `n <= ddof`.
3614pub fn nansem(values: &[Scalar], ddof: usize) -> Scalar {
3615    // Per br-frankenpandas-j8ntk: Timedelta64 sem preserves dtype.
3616    if let Some(td) = collect_timedelta_ns_f64(values) {
3617        if td.len() <= ddof {
3618            return Scalar::Timedelta64(Timedelta::NAT);
3619        }
3620        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
3621        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
3622        let var = sum_sq / (td.len() - ddof) as f64;
3623        let std = var.sqrt();
3624        return float_ns_to_timedelta(std / (td.len() as f64).sqrt());
3625    }
3626    let nums = collect_finite(values);
3627    if nums.len() <= ddof {
3628        return Scalar::Null(NullKind::NaN);
3629    }
3630    let n = nums.len();
3631    let mean = nums.iter().sum::<f64>() / n as f64;
3632    let sum_sq = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
3633    let var = sum_sq / (n - ddof) as f64;
3634    let std = var.sqrt();
3635    Scalar::Float64(std / (n as f64).sqrt())
3636}
3637
3638/// Peak-to-peak range of non-missing values (max − min).
3639///
3640/// Matches `np.ptp` behavior on nan-safe inputs. Returns `Null(NaN)`
3641/// for empty or all-missing inputs.
3642pub fn nanptp(values: &[Scalar]) -> Scalar {
3643    // Per br-frankenpandas-u2g0r: Timedelta64 peak-to-peak returns
3644    // Timedelta64 (max - min in ns). collect_timedelta_ns_f64 is defined
3645    // in the cumulative-aggregations section below.
3646    if let Some(td) = collect_timedelta_ns_f64(values) {
3647        if td.is_empty() {
3648            return Scalar::Timedelta64(Timedelta::NAT);
3649        }
3650        let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
3651        for x in &td {
3652            if *x < lo {
3653                lo = *x;
3654            }
3655            if *x > hi {
3656                hi = *x;
3657            }
3658        }
3659        return float_ns_to_timedelta(hi - lo);
3660    }
3661    // Fused single-pass min/max (see `nansum`): track lo/hi while filtering, no
3662    // intermediate Vec<f64>. Bit-identical to the prior collect_finite two-pass:
3663    // `seen` is true exactly when collect_finite would be non-empty, and the
3664    // lo/hi comparisons fold the same finite values in the same order.
3665    let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
3666    let mut seen = false;
3667    for v in values {
3668        if v.is_missing() {
3669            continue;
3670        }
3671        if let Ok(x) = v.to_f64() {
3672            seen = true;
3673            if x < lo {
3674                lo = x;
3675            }
3676            if x > hi {
3677                hi = x;
3678            }
3679        }
3680    }
3681    if !seen {
3682        return Scalar::Null(NullKind::NaN);
3683    }
3684    Scalar::Float64(hi - lo)
3685}
3686
3687/// Sample skewness (bias-corrected, Fisher-Pearson) over non-missing values.
3688///
3689/// Matches `pd.Series.skew()`. Requires at least 3 non-missing values;
3690/// returns `Null(NaN)` otherwise, and when the sample standard deviation
3691/// is zero.
3692pub fn nanskew(values: &[Scalar]) -> Scalar {
3693    let nums = collect_finite(values);
3694    let n = nums.len() as f64;
3695    if n < 3.0 {
3696        return Scalar::Null(NullKind::NaN);
3697    }
3698    let mean = nums.iter().sum::<f64>() / n;
3699    // Accumulate both central moments while the collected values are hot. Each
3700    // sum still observes the same terms in the same order as the former two
3701    // iterator passes, preserving floating-point results bit-for-bit.
3702    let (mut m2, mut m3) = (0.0_f64, 0.0_f64);
3703    for x in nums {
3704        let delta = x - mean;
3705        m2 += delta.powi(2);
3706        m3 += delta.powi(3);
3707    }
3708    let s2 = m2 / (n - 1.0);
3709    if s2 == 0.0 {
3710        return Scalar::Float64(0.0);
3711    }
3712    let s3 = s2.powf(1.5);
3713    Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
3714}
3715
3716/// Excess sample kurtosis (Fisher's definition, bias-corrected) over
3717/// non-missing values.
3718///
3719/// Matches `pd.Series.kurt()`. Requires at least 4 non-missing values;
3720/// returns `Null(NaN)` otherwise, and when the sample standard deviation
3721/// is zero.
3722pub fn nankurt(values: &[Scalar]) -> Scalar {
3723    let nums = collect_finite(values);
3724    let n = nums.len() as f64;
3725    if n < 4.0 {
3726        return Scalar::Null(NullKind::NaN);
3727    }
3728    let mean = nums.iter().sum::<f64>() / n;
3729    // Accumulate both central moments while the collected values are hot. Each
3730    // sum still observes the same terms in the same order as the former two
3731    // iterator passes, preserving floating-point results bit-for-bit.
3732    let (mut m2, mut m4) = (0.0_f64, 0.0_f64);
3733    for x in nums {
3734        let delta = x - mean;
3735        m2 += delta.powi(2);
3736        m4 += delta.powi(4);
3737    }
3738    let s2 = m2 / (n - 1.0);
3739    if s2 == 0.0 {
3740        return Scalar::Float64(0.0);
3741    }
3742    let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
3743    let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
3744    Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
3745}
3746
3747/// Product of non-missing values. Returns 1.0 for empty input (matching pandas).
3748pub fn nanprod(values: &[Scalar]) -> Scalar {
3749    // Per br-frankenpandas-szq6a: pandas raises TypeError on
3750    // td_series.prod() because Timedelta² has no dimension. Returning the
3751    // misleading Float64(1.0) (empty-iterator default after collect_finite
3752    // drops every Timedelta64) is worse than surfacing missing. NaT
3753    // propagates the "type-incompatible" signal in lieu of a Result-level
3754    // error.
3755    if is_timedelta_input(values) {
3756        return Scalar::Null(NullKind::NaN);
3757    }
3758    // Fused single-pass fold (see `nansum`): filter missing / non-coercible and
3759    // multiply in one scan, no intermediate Vec<f64>. Bit-identical to
3760    // `collect_finite(..).iter().product()`: same finite values, same order,
3761    // same f64 `*` (Product for f64 == fold(1.0, *)); empty -> 1.0.
3762    let mut prod = 1.0_f64;
3763    for v in values {
3764        if v.is_missing() {
3765            continue;
3766        }
3767        if let Ok(x) = v.to_f64() {
3768            prod *= x;
3769        }
3770    }
3771    Scalar::Float64(prod)
3772}
3773
3774/// Cumulative sum respecting null propagation.
3775///
3776/// Per br-frankenpandas-x0x91: detect uniformly-Timedelta64 input
3777/// (allowing Null/NAT missing markers). Returns true when at least one
3778/// non-missing value is Timedelta64 and no other dtype appears.
3779fn is_timedelta_input(values: &[Scalar]) -> bool {
3780    let mut saw_td = false;
3781    for v in values {
3782        if v.is_missing() {
3783            continue;
3784        }
3785        match v {
3786            Scalar::Timedelta64(_) => saw_td = true,
3787            _ => return false,
3788        }
3789    }
3790    saw_td
3791}
3792
3793/// Per br-frankenpandas-x0x91: cumulative running aggregation over a
3794/// uniformly-Timedelta64 input. NaT/Null positions emit NaT and skip
3795/// the accumulator. Saturating i128 keeps overflow contained at i64
3796/// bounds when emitting.
3797fn timedelta_cumulative<F>(values: &[Scalar], init: i128, mut step: F) -> Vec<Scalar>
3798where
3799    F: FnMut(i128, i128) -> i128,
3800{
3801    let mut out = Vec::with_capacity(values.len());
3802    let mut running: i128 = init;
3803    for v in values {
3804        if v.is_missing() {
3805            out.push(Scalar::Null(NullKind::NaT));
3806            continue;
3807        }
3808        if let Scalar::Timedelta64(ns) = v {
3809            running = step(running, i128::from(*ns));
3810            let clamped = running.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
3811            out.push(Scalar::Timedelta64(clamped as i64));
3812        } else {
3813            out.push(Scalar::Null(NullKind::NaT));
3814        }
3815    }
3816    out
3817}
3818
3819/// Per br-frankenpandas-x0x91: running extrema (min/max) over a
3820/// uniformly-Timedelta64 input. `sentinel` is the identity element
3821/// (i64::MAX for min, i64::MIN for max) used until the first
3822/// non-missing value initializes the accumulator.
3823fn timedelta_cumulative_extrema<F>(values: &[Scalar], sentinel: i64, mut step: F) -> Vec<Scalar>
3824where
3825    F: FnMut(i64, i64) -> i64,
3826{
3827    let mut out = Vec::with_capacity(values.len());
3828    let mut running: Option<i64> = None;
3829    for v in values {
3830        if v.is_missing() {
3831            out.push(Scalar::Null(NullKind::NaT));
3832            continue;
3833        }
3834        if let Scalar::Timedelta64(ns) = v {
3835            let new_val = match running {
3836                Some(prev) => step(prev, *ns),
3837                None => *ns,
3838            };
3839            running = Some(new_val);
3840            out.push(Scalar::Timedelta64(new_val));
3841        } else {
3842            out.push(Scalar::Null(NullKind::NaT));
3843        }
3844    }
3845    let _ = sentinel; // silence unused warning if closure ignores it
3846    out
3847}
3848
3849/// Matches `np.nancumsum` / `pd.Series.cumsum()`. Missing input positions
3850/// pass through as `Null(NaN)` in the output; the running sum ignores
3851/// those positions when accumulating.
3852pub fn nancumsum(values: &[Scalar]) -> Vec<Scalar> {
3853    // Per br-frankenpandas-x0x91: when input is uniformly Timedelta64 (with
3854    // optional NaT/Null missing markers), preserve Timedelta dtype to match
3855    // pandas td_series.cumsum() returning Timedelta64.
3856    if is_timedelta_input(values) {
3857        return timedelta_cumulative(values, 0_i128, |acc, x| acc.saturating_add(x));
3858    }
3859    let mut out = Vec::with_capacity(values.len());
3860    let mut running = 0.0_f64;
3861    for v in values {
3862        if v.is_missing() {
3863            out.push(Scalar::Null(NullKind::NaN));
3864            continue;
3865        }
3866        match v.to_f64() {
3867            Ok(x) if !x.is_nan() => {
3868                running += x;
3869                out.push(Scalar::Float64(running));
3870            }
3871            _ => out.push(Scalar::Null(NullKind::NaN)),
3872        }
3873    }
3874    out
3875}
3876
3877/// Cumulative product respecting null propagation.
3878///
3879/// Matches `np.nancumprod` / `pd.Series.cumprod()`. Missing positions
3880/// pass through as `Null(NaN)` without advancing the running product.
3881pub fn nancumprod(values: &[Scalar]) -> Vec<Scalar> {
3882    let mut out = Vec::with_capacity(values.len());
3883    let mut running = 1.0_f64;
3884    for v in values {
3885        if v.is_missing() {
3886            out.push(Scalar::Null(NullKind::NaN));
3887            continue;
3888        }
3889        match v.to_f64() {
3890            Ok(x) if !x.is_nan() => {
3891                running *= x;
3892                out.push(Scalar::Float64(running));
3893            }
3894            _ => out.push(Scalar::Null(NullKind::NaN)),
3895        }
3896    }
3897    out
3898}
3899
3900/// Cumulative maximum respecting null propagation.
3901///
3902/// Matches `pd.Series.cummax()`. Missing positions pass through as
3903/// `Null(NaN)` without updating the running maximum. The first
3904/// non-missing value initializes the running maximum.
3905pub fn nancummax(values: &[Scalar]) -> Vec<Scalar> {
3906    // Per br-frankenpandas-x0x91: Timedelta64 preserves dtype.
3907    if is_timedelta_input(values) {
3908        return timedelta_cumulative_extrema(values, i64::MAX, |acc, x| acc.max(x));
3909    }
3910    let mut out = Vec::with_capacity(values.len());
3911    let mut running: Option<f64> = None;
3912    for v in values {
3913        if v.is_missing() {
3914            out.push(Scalar::Null(NullKind::NaN));
3915            continue;
3916        }
3917        match v.to_f64() {
3918            Ok(x) if !x.is_nan() => {
3919                let new_val = match running {
3920                    Some(prev) => prev.max(x),
3921                    None => x,
3922                };
3923                running = Some(new_val);
3924                out.push(Scalar::Float64(new_val));
3925            }
3926            _ => out.push(Scalar::Null(NullKind::NaN)),
3927        }
3928    }
3929    out
3930}
3931
3932/// Cumulative minimum respecting null propagation.
3933///
3934/// Matches `pd.Series.cummin()`. Symmetric to `nancummax`.
3935pub fn nancummin(values: &[Scalar]) -> Vec<Scalar> {
3936    // Per br-frankenpandas-x0x91: Timedelta64 preserves dtype.
3937    if is_timedelta_input(values) {
3938        return timedelta_cumulative_extrema(values, i64::MIN, |acc, x| acc.min(x));
3939    }
3940    let mut out = Vec::with_capacity(values.len());
3941    let mut running: Option<f64> = None;
3942    for v in values {
3943        if v.is_missing() {
3944            out.push(Scalar::Null(NullKind::NaN));
3945            continue;
3946        }
3947        match v.to_f64() {
3948            Ok(x) if !x.is_nan() => {
3949                let new_val = match running {
3950                    Some(prev) => prev.min(x),
3951                    None => x,
3952                };
3953                running = Some(new_val);
3954                out.push(Scalar::Float64(new_val));
3955            }
3956            _ => out.push(Scalar::Null(NullKind::NaN)),
3957        }
3958    }
3959    out
3960}
3961
3962/// Linear-interpolation quantile over non-missing numeric values.
3963///
3964/// Matches `np.nanquantile(values, q)` with `interpolation='linear'`.
3965/// Returns `Null(NaN)` for empty inputs or when `q` is outside
3966/// `[0.0, 1.0]`.
3967pub fn nanquantile(values: &[Scalar], q: f64) -> Scalar {
3968    if !(0.0..=1.0).contains(&q) {
3969        return Scalar::Null(NullKind::NaN);
3970    }
3971    // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
3972    // Timedelta64 with linear-interpolated ns. Was silently NaN before.
3973    if let Some(mut td) = collect_timedelta_ns_f64(values) {
3974        if td.is_empty() {
3975            return Scalar::Timedelta64(Timedelta::NAT);
3976        }
3977        let n = td.len();
3978        if n == 1 {
3979            return float_ns_to_timedelta(td[0]);
3980        }
3981        let pos = q * (n - 1) as f64;
3982        let lo = pos.floor() as usize;
3983        let hi = pos.ceil() as usize;
3984        // O(n) selection instead of a full sort (see the numeric arm below):
3985        // select the lo-th order statistic; the (lo+1)-th is the MIN of the
3986        // right partition. Bit-identical (finite ns, values-only order stats).
3987        let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
3988        let (_left, lo_ref, right) = td.select_nth_unstable_by(lo, cmp);
3989        let lo_val = *lo_ref;
3990        let ns = if lo == hi {
3991            lo_val
3992        } else {
3993            let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
3994            let weight = pos - lo as f64;
3995            lo_val + (hi_val - lo_val) * weight
3996        };
3997        return float_ns_to_timedelta(ns);
3998    }
3999    let mut nums = collect_finite(values);
4000    if nums.is_empty() {
4001        return Scalar::Null(NullKind::NaN);
4002    }
4003    let n = nums.len();
4004    if n == 1 {
4005        return Scalar::Float64(nums[0]);
4006    }
4007    let pos = q * (n - 1) as f64;
4008    let lo = pos.floor() as usize;
4009    let hi = pos.ceil() as usize;
4010    // O(n) selection instead of a full sort: select the `lo`-th order statistic;
4011    // when interpolation is needed (hi == lo+1) the (lo+1)-th smallest is the
4012    // MIN of the right partition. Bit-identical to the sort path (same
4013    // nums[lo]/nums[hi] values, since order statistics depend only on values).
4014    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
4015    let (_left, lo_ref, right) = nums.select_nth_unstable_by(lo, cmp);
4016    let lo_val = *lo_ref;
4017    if lo == hi {
4018        return Scalar::Float64(lo_val);
4019    }
4020    let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
4021    let weight = pos - lo as f64;
4022    Scalar::Float64(lo_val + (hi_val - lo_val) * weight)
4023}
4024
4025/// Position (in the original slice) of the non-missing maximum.
4026///
4027/// Matches `np.nanargmax`. Returns `None` if every value is missing.
4028/// Ties resolve to the first position seen (matching numpy).
4029pub fn nanargmax(values: &[Scalar]) -> Option<usize> {
4030    // Per br-frankenpandas-ql1t5: Timedelta64.to_f64() errors, so the
4031    // generic path would silently skip every Timedelta64 value and
4032    // return None. Pandas td_series.argmax() returns the position of
4033    // the largest Timedelta — compare i64 ns directly.
4034    if is_timedelta_input(values) {
4035        let mut best: Option<(usize, i64)> = None;
4036        for (i, v) in values.iter().enumerate() {
4037            if v.is_missing() {
4038                continue;
4039            }
4040            if let Scalar::Timedelta64(ns) = v {
4041                match best {
4042                    None => best = Some((i, *ns)),
4043                    Some((_, cur)) if *ns > cur => best = Some((i, *ns)),
4044                    _ => {}
4045                }
4046            }
4047        }
4048        return best.map(|(i, _)| i);
4049    }
4050    let mut best: Option<(usize, f64)> = None;
4051    for (i, v) in values.iter().enumerate() {
4052        if v.is_missing() {
4053            continue;
4054        }
4055        if let Ok(x) = v.to_f64() {
4056            if x.is_nan() {
4057                continue;
4058            }
4059            match best {
4060                None => best = Some((i, x)),
4061                Some((_, cur)) if x > cur => best = Some((i, x)),
4062                _ => {}
4063            }
4064        }
4065    }
4066    best.map(|(i, _)| i)
4067}
4068
4069/// Position (in the original slice) of the non-missing minimum.
4070///
4071/// Matches `np.nanargmin`. Returns `None` if every value is missing.
4072pub fn nanargmin(values: &[Scalar]) -> Option<usize> {
4073    // Per br-frankenpandas-ql1t5: Timedelta64 argmin via i64 ns compare.
4074    if is_timedelta_input(values) {
4075        let mut best: Option<(usize, i64)> = None;
4076        for (i, v) in values.iter().enumerate() {
4077            if v.is_missing() {
4078                continue;
4079            }
4080            if let Scalar::Timedelta64(ns) = v {
4081                match best {
4082                    None => best = Some((i, *ns)),
4083                    Some((_, cur)) if *ns < cur => best = Some((i, *ns)),
4084                    _ => {}
4085                }
4086            }
4087        }
4088        return best.map(|(i, _)| i);
4089    }
4090    let mut best: Option<(usize, f64)> = None;
4091    for (i, v) in values.iter().enumerate() {
4092        if v.is_missing() {
4093            continue;
4094        }
4095        if let Ok(x) = v.to_f64() {
4096            if x.is_nan() {
4097                continue;
4098            }
4099            match best {
4100                None => best = Some((i, x)),
4101                Some((_, cur)) if x < cur => best = Some((i, x)),
4102                _ => {}
4103            }
4104        }
4105    }
4106    best.map(|(i, _)| i)
4107}
4108
4109/// Count of unique non-missing values.
4110pub fn nannunique(values: &[Scalar]) -> Scalar {
4111    use rustc_hash::FxHashSet;
4112    #[derive(Hash, PartialEq, Eq)]
4113    enum ScalarKey<'a> {
4114        Bool(bool),
4115        Int64(i64),
4116        FloatBits(u64),
4117        Utf8(&'a str),
4118        Timedelta64(i64),
4119        Datetime64(i64),
4120        Period(i64, PeriodFreq),
4121        Interval(u64, u64, IntervalClosed),
4122    }
4123
4124    let mut seen = FxHashSet::default();
4125    for val in values {
4126        if val.is_missing() {
4127            continue;
4128        }
4129        let key = match val {
4130            Scalar::Bool(v) => ScalarKey::Bool(*v),
4131            Scalar::Int64(v) => ScalarKey::Int64(*v),
4132            Scalar::Float64(v) => {
4133                let normalized = if *v == 0.0 { 0.0 } else { *v };
4134                ScalarKey::FloatBits(normalized.to_bits())
4135            }
4136            Scalar::Utf8(v) => ScalarKey::Utf8(v.as_str()),
4137            Scalar::Timedelta64(v) => ScalarKey::Timedelta64(*v),
4138            Scalar::Datetime64(v) => ScalarKey::Datetime64(*v),
4139            Scalar::Period(p) => ScalarKey::Period(p.ordinal, p.freq),
4140            Scalar::Interval(v) => ScalarKey::Interval(
4141                normalized_float_bits(v.left),
4142                normalized_float_bits(v.right),
4143                v.closed,
4144            ),
4145            Scalar::Null(_) => continue,
4146        };
4147        seen.insert(key);
4148    }
4149    Scalar::Int64(seen.len() as i64)
4150}
4151
4152fn normalized_float_bits(value: f64) -> u64 {
4153    let normalized = if value == 0.0 { 0.0 } else { value };
4154    normalized.to_bits()
4155}
4156
4157// ── Interval types (br-frankenpandas-j8k4 Phase 1) ──────────────────────
4158//
4159// Scaffolding for pandas `pd.Interval` / `pd.IntervalIndex` / `pd.IntervalDtype`.
4160//
4161// Phase 1 ships float-valued intervals only (matches `cut`/`qcut` output on
4162// numeric bins — the dominant pandas use case). Generic-subtype intervals
4163// over Int64 / Timestamp are deferred to Phase 2 alongside the DType::Interval
4164// enum-variant wiring. See br-j8k4 for the phased roadmap.
4165//
4166// Semantics mirror pandas: closed tells which endpoints are included.
4167//   Left    → [left, right)
4168//   Right   → (left, right]       ← pandas default
4169//   Both    → [left, right]
4170//   Neither → (left, right)
4171
4172/// Endpoint-inclusion policy for an `Interval`.
4173///
4174/// Matches pandas `pd.Interval.closed` / `pd.IntervalDtype.closed` string
4175/// values ("left" / "right" / "both" / "neither").
4176#[derive(
4177    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
4178)]
4179#[serde(rename_all = "snake_case")]
4180#[non_exhaustive]
4181pub enum IntervalClosed {
4182    /// `[left, right)` — left-inclusive, right-exclusive.
4183    Left,
4184    /// `(left, right]` — left-exclusive, right-inclusive. Pandas default.
4185    #[default]
4186    Right,
4187    /// `[left, right]` — both endpoints included.
4188    Both,
4189    /// `(left, right)` — neither endpoint included.
4190    Neither,
4191}
4192
4193impl IntervalClosed {
4194    /// Left endpoint included?
4195    #[must_use]
4196    pub fn left_closed(self) -> bool {
4197        matches!(self, Self::Left | Self::Both)
4198    }
4199
4200    /// Right endpoint included?
4201    #[must_use]
4202    pub fn right_closed(self) -> bool {
4203        matches!(self, Self::Right | Self::Both)
4204    }
4205}
4206
4207impl std::fmt::Display for IntervalClosed {
4208    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4209        match self {
4210            Self::Left => write!(f, "left"),
4211            Self::Right => write!(f, "right"),
4212            Self::Both => write!(f, "both"),
4213            Self::Neither => write!(f, "neither"),
4214        }
4215    }
4216}
4217
4218/// A bounded numeric interval between two `f64` endpoints.
4219///
4220/// Matches `pd.Interval(left, right, closed)` on the numeric-subtype path.
4221/// Accessors match pandas: `.left`, `.right`, `.closed`, `.length`, `.mid`,
4222/// `.contains`, `.is_empty`, `.overlaps`.
4223#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
4224pub struct Interval {
4225    pub left: f64,
4226    pub right: f64,
4227    #[serde(default)]
4228    pub closed: IntervalClosed,
4229}
4230
4231impl Interval {
4232    /// Construct an interval. No validation on `left <= right` — pandas also
4233    /// accepts reversed intervals (they're non-empty only if empty-by-design).
4234    #[must_use]
4235    pub const fn new(left: f64, right: f64, closed: IntervalClosed) -> Self {
4236        Self {
4237            left,
4238            right,
4239            closed,
4240        }
4241    }
4242
4243    /// `right - left` (pandas `.length`). Negative for reversed intervals.
4244    #[must_use]
4245    pub fn length(&self) -> f64 {
4246        self.right - self.left
4247    }
4248
4249    /// Midpoint `(left + right) / 2` (pandas `.mid`).
4250    #[must_use]
4251    pub fn mid(&self) -> f64 {
4252        (self.left + self.right) / 2.0
4253    }
4254
4255    /// Empty iff endpoints coincide AND at least one side is open.
4256    /// Pandas semantics: `pd.Interval(3, 3, 'right').is_empty → True`.
4257    #[must_use]
4258    pub fn is_empty(&self) -> bool {
4259        self.left == self.right && !matches!(self.closed, IntervalClosed::Both)
4260    }
4261
4262    /// Does `value` fall inside this interval?
4263    ///
4264    /// NaN always returns false, matching pandas `pd.Interval.__contains__`
4265    /// behavior (NaN doesn't compare equal to anything).
4266    #[must_use]
4267    pub fn contains(&self, value: f64) -> bool {
4268        if value.is_nan() {
4269            return false;
4270        }
4271        let left_ok = if self.closed.left_closed() {
4272            value >= self.left
4273        } else {
4274            value > self.left
4275        };
4276        let right_ok = if self.closed.right_closed() {
4277            value <= self.right
4278        } else {
4279            value < self.right
4280        };
4281        left_ok && right_ok
4282    }
4283
4284    /// Do `self` and `other` share any point?
4285    ///
4286    /// Matches `pd.Interval.overlaps(other)`. Two intervals overlap iff the
4287    /// max of their lefts is less than the min of their rights, with
4288    /// endpoint-inclusion determining the strictness of the comparison when
4289    /// they touch exactly.
4290    #[must_use]
4291    pub fn overlaps(&self, other: &Self) -> bool {
4292        if self.left > other.right || other.left > self.right {
4293            return false;
4294        }
4295        // Touching-at-a-point: overlap iff both sides at that touchpoint are closed.
4296        if self.right == other.left {
4297            return self.closed.right_closed() && other.closed.left_closed();
4298        }
4299        if other.right == self.left {
4300            return other.closed.right_closed() && self.closed.left_closed();
4301        }
4302        true
4303    }
4304
4305    /// Parse an interval string. Supports bracket notation:
4306    /// - '[0, 1]' -> closed on both ends
4307    /// - '(0, 1)' -> open on both ends
4308    /// - '[0, 1)' -> closed left, open right (pandas default)
4309    /// - '(0, 1]' -> open left, closed right
4310    pub fn parse(s: &str) -> Result<Self, TypeError> {
4311        let s = s.trim();
4312        if s.len() < 5 {
4313            return Err(TypeError::ValueNotParseable {
4314                value: s.to_string(),
4315                target: "Interval".to_string(),
4316            });
4317        }
4318
4319        let first_char = s.chars().next().unwrap();
4320        let last_char = s.chars().last().unwrap();
4321
4322        let left_closed = match first_char {
4323            '[' => true,
4324            '(' => false,
4325            _ => {
4326                return Err(TypeError::ValueNotParseable {
4327                    value: s.to_string(),
4328                    target: "Interval".to_string(),
4329                });
4330            }
4331        };
4332
4333        let right_closed = match last_char {
4334            ']' => true,
4335            ')' => false,
4336            _ => {
4337                return Err(TypeError::ValueNotParseable {
4338                    value: s.to_string(),
4339                    target: "Interval".to_string(),
4340                });
4341            }
4342        };
4343
4344        let closed = match (left_closed, right_closed) {
4345            (true, true) => IntervalClosed::Both,
4346            (true, false) => IntervalClosed::Left,
4347            (false, true) => IntervalClosed::Right,
4348            (false, false) => IntervalClosed::Neither,
4349        };
4350
4351        let inner = &s[1..s.len() - 1];
4352        let Some((left_text, right_text)) = inner.split_once(',') else {
4353            return Err(TypeError::ValueNotParseable {
4354                value: s.to_string(),
4355                target: "Interval".to_string(),
4356            });
4357        };
4358        if right_text.contains(',') {
4359            return Err(TypeError::ValueNotParseable {
4360                value: s.to_string(),
4361                target: "Interval".to_string(),
4362            });
4363        }
4364
4365        let left: f64 = left_text
4366            .trim()
4367            .parse()
4368            .map_err(|_| TypeError::ValueNotParseable {
4369                value: s.to_string(),
4370                target: "Interval".to_string(),
4371            })?;
4372
4373        let right: f64 = right_text
4374            .trim()
4375            .parse()
4376            .map_err(|_| TypeError::ValueNotParseable {
4377                value: s.to_string(),
4378                target: "Interval".to_string(),
4379            })?;
4380
4381        Ok(Self::new(left, right, closed))
4382    }
4383}
4384
4385impl std::fmt::Display for Interval {
4386    /// Matches `str(pd.Interval(...))` for the `interval[float64]` subtype, which
4387    /// is the only subtype FrankenPandas stores (f64 endpoints): the endpoints
4388    /// render with Python `str(float)` semantics, so whole numbers KEEP ".0"
4389    /// (`str(pd.Interval(0.0, 5.0, 'right'))` is `"(0.0, 5.0]"`, not `"(0, 5]"`).
4390    /// Verified vs pandas 2.2.3 across whole/fractional/negative/scientific
4391    /// endpoints. (br-frankenpandas-5xw1b)
4392    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4393        let left_bracket = if self.closed.left_closed() { '[' } else { '(' };
4394        let right_bracket = if self.closed.right_closed() { ']' } else { ')' };
4395        write!(
4396            f,
4397            "{left_bracket}{}, {}{right_bracket}",
4398            float_to_string_for_astype(self.left),
4399            float_to_string_for_astype(self.right)
4400        )
4401    }
4402}
4403
4404// ── interval_range builders (br-frankenpandas-xaom — Phase 2 of j8k4) ────
4405
4406/// Build `periods` equal-width intervals spanning `[start, end]`.
4407///
4408/// Matches `pd.interval_range(start, end, periods=N, closed=...)` for the
4409/// numeric-subtype case. Returns exactly `periods` intervals; when
4410/// `periods == 0` or `start >= end`, returns an empty vector (matches
4411/// pandas's empty IntervalIndex).
4412///
4413/// ```
4414/// use fp_types::{interval_range_by_periods, IntervalClosed};
4415/// let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
4416/// assert_eq!(bins.len(), 5);
4417/// assert_eq!(bins[0].left, 0.0);
4418/// assert_eq!(bins[0].right, 2.0);
4419/// assert_eq!(bins[4].right, 10.0);
4420/// ```
4421#[must_use]
4422pub fn interval_range_by_periods(
4423    start: f64,
4424    end: f64,
4425    periods: usize,
4426    closed: IntervalClosed,
4427) -> Vec<Interval> {
4428    if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
4429        return Vec::new();
4430    }
4431    let step = (end - start) / (periods as f64);
4432    let mut out = Vec::with_capacity(periods);
4433    for i in 0..periods {
4434        let left = start + step * (i as f64);
4435        // Use end exactly for the final right edge to avoid float drift.
4436        let right = if i + 1 == periods {
4437            end
4438        } else {
4439            start + step * ((i + 1) as f64)
4440        };
4441        out.push(Interval::new(left, right, closed));
4442    }
4443    out
4444}
4445
4446/// Build equal-`step`-width intervals spanning `[start, end]`.
4447///
4448/// Matches `pd.interval_range(start, end, freq=step, closed=...)` for the
4449/// numeric-subtype case. `step` must be finite and positive; `(end - start)`
4450/// must be an integer multiple of `step` (within float tolerance) — pandas
4451/// raises `ValueError` otherwise; this fn returns `Err(TypeError::IntervalStepDoesNotDivide)`.
4452///
4453/// Returns an empty vector when `start == end` (matches pandas' zero-bin
4454/// IntervalIndex); returns an empty vector when `start > end` (pandas also
4455/// returns empty rather than erroring in this case).
4456pub fn interval_range_by_step(
4457    start: f64,
4458    end: f64,
4459    step: f64,
4460    closed: IntervalClosed,
4461) -> Result<Vec<Interval>, TypeError> {
4462    if !step.is_finite() || !step.is_sign_positive() || step == 0.0 {
4463        return Err(TypeError::InvalidIntervalStep { step });
4464    }
4465    if !start.is_finite() || !end.is_finite() || start >= end {
4466        return Ok(Vec::new());
4467    }
4468    let span = end - start;
4469    let periods_f = span / step;
4470    let periods = periods_f.round() as i64;
4471    if periods <= 0 {
4472        return Ok(Vec::new());
4473    }
4474    let reconstructed = step * (periods as f64);
4475    // Relative tolerance: allow float-rounding noise proportional to span.
4476    if (span - reconstructed).abs() > span.abs() * 1e-9 + 1e-12 {
4477        return Err(TypeError::IntervalStepDoesNotDivide { step, span });
4478    }
4479    let periods = periods as usize;
4480    let mut out = Vec::with_capacity(periods);
4481    for i in 0..periods {
4482        let left = start + step * (i as f64);
4483        let right = if i + 1 == periods {
4484            end
4485        } else {
4486            start + step * ((i + 1) as f64)
4487        };
4488        out.push(Interval::new(left, right, closed));
4489    }
4490    Ok(out)
4491}
4492
4493// ── Period types (br-frankenpandas-epoj Phase 1) ────────────────────────
4494//
4495// Scaffolding for pandas `pd.Period` / `pd.PeriodIndex` / `pd.PeriodDtype`.
4496//
4497// A Period is a calendar *span* (Q1 2024, Jan 2024, 2024-03-15), distinct
4498// from a Timestamp (an instant). Phase 1 ships the PeriodFreq enum +
4499// Period struct with ordinal-based arithmetic (Period + n, Period - Period),
4500// Display in pandas notation, and parse from standard strings. Calendar-
4501// conversion (ordinal ↔ ymd) and DType::Period wiring land in Phase 2.
4502
4503/// Period frequency code. Matches pandas offset alias core set.
4504///
4505/// The ordinal axis is frequency-specific: for Monthly, ordinal 0 is a
4506/// fixed anchor (pandas uses months since 1970-01). Phase 1 doesn't
4507/// commit to a specific epoch yet — the ordinal scheme is opaque until
4508/// Phase 2 wires calendar arithmetic. What Phase 1 DOES nail down is:
4509/// same-freq Periods compare + subtract; Period + i64 shifts by `n`
4510/// periods of the declared frequency.
4511#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
4512#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
4513#[non_exhaustive]
4514pub enum PeriodFreq {
4515    /// `Y-DEC` / `A` / `Y` — annual periods.
4516    Annual,
4517    /// `Q-DEC` / `Q` — quarterly periods.
4518    Quarterly,
4519    /// `M` — monthly periods.
4520    Monthly,
4521    /// `W-SUN` / `W` — weekly periods.
4522    Weekly,
4523    /// `D` — daily periods.
4524    Daily,
4525    /// `B` — business-day periods.
4526    Business,
4527    /// `h` / `H` — hourly periods.
4528    Hourly,
4529    /// `min` / `T` — minutely periods.
4530    Minutely,
4531    /// `s` / `S` — secondly periods.
4532    Secondly,
4533}
4534
4535impl PeriodFreq {
4536    /// Parse a pandas-style frequency alias. Recognizes the common subset
4537    /// (Y-DEC/A/Y, Q-DEC/Q, M, W-SUN/W, D, B, h/H, min/T, s/S).
4538    /// Case-insensitive.
4539    pub fn parse(alias: &str) -> Option<Self> {
4540        match alias.to_ascii_uppercase().as_str() {
4541            "A" | "Y" | "A-DEC" | "Y-DEC" | "ANNUAL" | "YEARLY" => Some(Self::Annual),
4542            "Q" | "Q-DEC" | "QUARTERLY" => Some(Self::Quarterly),
4543            "M" | "MONTHLY" => Some(Self::Monthly),
4544            "W" | "W-SUN" | "WEEKLY" => Some(Self::Weekly),
4545            "D" | "DAILY" => Some(Self::Daily),
4546            "B" | "BUSINESS" => Some(Self::Business),
4547            "H" | "HOURLY" => Some(Self::Hourly),
4548            "T" | "MIN" | "MINUTELY" => Some(Self::Minutely),
4549            "S" | "SECONDLY" => Some(Self::Secondly),
4550            _ => None,
4551        }
4552    }
4553
4554    /// Canonical pandas alias string.
4555    #[must_use]
4556    pub const fn alias(self) -> &'static str {
4557        match self {
4558            Self::Annual => "Y-DEC",
4559            Self::Quarterly => "Q-DEC",
4560            Self::Monthly => "M",
4561            Self::Weekly => "W-SUN",
4562            Self::Daily => "D",
4563            Self::Business => "B",
4564            Self::Hourly => "h",
4565            Self::Minutely => "min",
4566            Self::Secondly => "s",
4567        }
4568    }
4569
4570    /// Per br-frankenpandas-qigpe: resolution string for PeriodIndex.resolution.
4571    #[must_use]
4572    pub const fn resolution(self) -> &'static str {
4573        match self {
4574            Self::Annual => "A-DEC",
4575            Self::Quarterly => "Q-DEC",
4576            Self::Monthly => "M",
4577            Self::Weekly => "W-SUN",
4578            Self::Daily => "D",
4579            Self::Business => "B",
4580            Self::Hourly => "H",
4581            Self::Minutely => "T",
4582            Self::Secondly => "S",
4583        }
4584    }
4585}
4586
4587impl std::fmt::Display for PeriodFreq {
4588    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4589        f.write_str(self.alias())
4590    }
4591}
4592
4593/// A single pandas-style Period value.
4594///
4595/// Stored as an integer ordinal on a frequency-specific axis plus the
4596/// frequency code. Two Periods with different `freq` are incompatible —
4597/// arithmetic and comparison require same-freq operands.
4598#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
4599pub struct Period {
4600    pub ordinal: i64,
4601    pub freq: PeriodFreq,
4602}
4603
4604impl Period {
4605    #[must_use]
4606    pub const fn new(ordinal: i64, freq: PeriodFreq) -> Self {
4607        Self { ordinal, freq }
4608    }
4609
4610    /// Integer position on this period's frequency axis, matching
4611    /// `pd.Period.ordinal`.
4612    #[must_use]
4613    pub const fn ordinal(&self) -> i64 {
4614        self.ordinal
4615    }
4616
4617    /// Frequency code for this period, matching `pd.Period.freq`.
4618    #[must_use]
4619    pub const fn freq(&self) -> PeriodFreq {
4620        self.freq
4621    }
4622
4623    /// Canonical pandas frequency alias, matching `pd.Period.freqstr`.
4624    #[must_use]
4625    pub const fn freqstr(&self) -> &'static str {
4626        self.freq.alias()
4627    }
4628
4629    /// Same-freq ordinal comparison. Returns `None` if `freq` differs —
4630    /// caller decides whether that's an error or a panic site.
4631    #[must_use]
4632    pub fn cmp_same_freq(&self, other: &Self) -> Option<std::cmp::Ordering> {
4633        if self.freq != other.freq {
4634            return None;
4635        }
4636        Some(self.ordinal.cmp(&other.ordinal))
4637    }
4638
4639    /// Shift by `n` periods of the current frequency.
4640    /// Matches `pd.Period + n` and `pd.Period - n`.
4641    #[must_use]
4642    pub fn shift(&self, n: i64) -> Self {
4643        Self {
4644            ordinal: self.ordinal.saturating_add(n),
4645            freq: self.freq,
4646        }
4647    }
4648
4649    /// Period-difference in units of the shared frequency.
4650    /// Returns `None` if `freq` differs (pandas raises IncompatibleFrequency).
4651    #[must_use]
4652    pub fn diff(&self, other: &Self) -> Option<i64> {
4653        if self.freq != other.freq {
4654            return None;
4655        }
4656        Some(self.ordinal.saturating_sub(other.ordinal))
4657    }
4658
4659    /// Parse common pandas `Period(...)` strings and infer the frequency.
4660    ///
4661    /// Supported forms mirror pandas' unambiguous scalar constructor cases:
4662    /// annual (`"2024"`), quarterly (`"2024Q1"`), monthly (`"2024-01"`),
4663    /// and daily (`"2024-01-15"`). The ordinal axes match pandas:
4664    /// 1970, 1970Q1, 1970-01, and 1970-01-01 all have ordinal 0.
4665    pub fn parse(s: &str) -> Result<Self, TypeError> {
4666        let trimmed = s.trim();
4667        if trimmed.eq_ignore_ascii_case("nat") {
4668            return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
4669        }
4670
4671        if let Some((year, quarter)) = parse_quarter_period(trimmed) {
4672            let ordinal = year
4673                .checked_sub(1970)
4674                .and_then(|offset| offset.checked_mul(4))
4675                .and_then(|base| base.checked_add(i64::from(quarter) - 1))
4676                .ok_or_else(|| TypeError::ValueNotParseable {
4677                    value: s.to_owned(),
4678                    target: "Period".to_owned(),
4679                })?;
4680            return Ok(Self::new(ordinal, PeriodFreq::Quarterly));
4681        }
4682
4683        if let Some((year, month, day)) = parse_ymd_period(trimmed) {
4684            let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
4685            return Ok(Self::new(ordinal, PeriodFreq::Daily));
4686        }
4687
4688        if let Some((year, month)) = parse_year_month_period(trimmed) {
4689            let ordinal = year
4690                .checked_sub(1970)
4691                .and_then(|offset| offset.checked_mul(12))
4692                .and_then(|base| base.checked_add(i64::from(month) - 1))
4693                .ok_or_else(|| TypeError::ValueNotParseable {
4694                    value: s.to_owned(),
4695                    target: "Period".to_owned(),
4696                })?;
4697            return Ok(Self::new(ordinal, PeriodFreq::Monthly));
4698        }
4699
4700        if let Some(year) = parse_annual_period(trimmed) {
4701            let ordinal = year
4702                .checked_sub(1970)
4703                .ok_or_else(|| TypeError::ValueNotParseable {
4704                    value: s.to_owned(),
4705                    target: "Period".to_owned(),
4706                })?;
4707            return Ok(Self::new(ordinal, PeriodFreq::Annual));
4708        }
4709
4710        Err(TypeError::ValueNotParseable {
4711            value: s.to_owned(),
4712            target: "Period".to_owned(),
4713        })
4714    }
4715
4716    /// Pandas calendar string for this period, matching `str(pd.Period)`.
4717    ///
4718    /// Inverts the frequency-specific ordinal axes anchored at 1970:
4719    /// `1970`/`1970Q1`/`1970-01`/`1970-01-01`/`1970-01-01 00:00` all have
4720    /// ordinal 0. Returns `"NaT"` for the missing sentinel (`i64::MIN`).
4721    ///
4722    /// Annual/Quarterly/Monthly/Daily and the sub-daily clocks
4723    /// (Hourly/Minutely/Secondly) are exact. Weekly and Business use a
4724    /// best-effort `YYYY-MM-DD` rendering (their pandas axes — a Sunday-ended
4725    /// week range and a business-day count — are not yet wired; neither is
4726    /// reachable through the current parse/cast paths).
4727    #[must_use]
4728    pub fn calendar_string(&self) -> String {
4729        let mut rendered = String::new();
4730        // `fmt::Write for String` is infallible.
4731        let _ = self.write_calendar(&mut rendered);
4732        rendered
4733    }
4734
4735    fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
4736        if self.ordinal == i64::MIN {
4737            return rendered.write_str("NaT");
4738        }
4739        let ord = self.ordinal;
4740        match self.freq {
4741            PeriodFreq::Annual => {
4742                let year = 1970 + ord;
4743                write!(rendered, "{year}")
4744            }
4745            PeriodFreq::Quarterly => {
4746                let year = 1970 + ord.div_euclid(4);
4747                let quarter = ord.rem_euclid(4) + 1;
4748                write!(rendered, "{year}Q{quarter}")
4749            }
4750            PeriodFreq::Monthly => {
4751                let year = 1970 + ord.div_euclid(12);
4752                let month = ord.rem_euclid(12) + 1;
4753                write!(rendered, "{year:04}-{month:02}")
4754            }
4755            PeriodFreq::Daily | PeriodFreq::Business | PeriodFreq::Weekly => {
4756                let (y, m, d) = civil_from_days(ord);
4757                write!(rendered, "{y:04}-{m:02}-{d:02}")
4758            }
4759            PeriodFreq::Hourly => {
4760                let (y, m, d) = civil_from_days(ord.div_euclid(24));
4761                let hour = ord.rem_euclid(24);
4762                write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
4763            }
4764            PeriodFreq::Minutely => {
4765                let day = ord.div_euclid(1440);
4766                let mins = ord.rem_euclid(1440);
4767                let (y, m, d) = civil_from_days(day);
4768                write!(
4769                    rendered,
4770                    "{y:04}-{m:02}-{d:02} {:02}:{:02}",
4771                    mins / 60,
4772                    mins % 60
4773                )
4774            }
4775            PeriodFreq::Secondly => {
4776                let day = ord.div_euclid(86_400);
4777                let secs = ord.rem_euclid(86_400);
4778                let (y, m, d) = civil_from_days(day);
4779                write!(
4780                    rendered,
4781                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
4782                    secs / 3600,
4783                    (secs % 3600) / 60,
4784                    secs % 60
4785                )
4786            }
4787        }
4788    }
4789}
4790
4791/// Convert a day count (days since 1970-01-01) to a proleptic-Gregorian
4792/// `(year, month, day)`, using Howard Hinnant's civil-from-days algorithm
4793/// (same kernel as `Timestamp::isoformat`).
4794fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
4795    let days = days_since_epoch + 719_468;
4796    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
4797    let doe = days - era * 146_097;
4798    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
4799    let y = yoe + era * 400;
4800    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
4801    let mp = (5 * doy + 2) / 153;
4802    let d = doy - (153 * mp + 2) / 5 + 1;
4803    let m = if mp < 10 { mp + 3 } else { mp - 9 };
4804    let year = if m <= 2 { y + 1 } else { y };
4805    (year, m as u32, d as u32)
4806}
4807
4808fn parse_annual_period(value: &str) -> Option<i64> {
4809    (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
4810        .then(|| value.parse::<i64>().ok())
4811        .flatten()
4812}
4813
4814fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
4815    let (year, month) = value.split_once('-')?;
4816    if year.len() != 4 || month.len() != 2 {
4817        return None;
4818    }
4819    let year = year.parse::<i64>().ok()?;
4820    let month = month.parse::<u32>().ok()?;
4821    (1..=12).contains(&month).then_some((year, month))
4822}
4823
4824fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
4825    let mut parts = value.split('-');
4826    let year = parts.next()?;
4827    let month = parts.next()?;
4828    let day = parts.next()?;
4829    if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
4830        return None;
4831    }
4832    let year = year.parse::<i64>().ok()?;
4833    let month = month.parse::<u32>().ok()?;
4834    let day = day.parse::<u32>().ok()?;
4835    (1..=days_in_month(year, month)?)
4836        .contains(&day)
4837        .then_some((year, month, day))
4838}
4839
4840fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
4841    let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
4842    if year.len() != 4 || quarter.len() != 1 {
4843        return None;
4844    }
4845    let year = year.parse::<i64>().ok()?;
4846    let quarter = quarter.parse::<u32>().ok()?;
4847    (1..=4).contains(&quarter).then_some((year, quarter))
4848}
4849
4850impl std::fmt::Display for Period {
4851    /// Pandas `str(Period)` form: the calendar string (`2024`, `2024Q1`,
4852    /// `2024-03`, `2024-01-15`, ...). NaT (ordinal `i64::MIN`) renders `NaT`.
4853    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4854        self.write_calendar(f)
4855    }
4856}
4857
4858/// Build `periods` consecutive Periods starting at `start`.
4859///
4860/// Matches `pd.period_range(start, periods=N, freq=start.freq)` for the
4861/// count-based form. The frequency is taken from `start` — pandas requires
4862/// `freq` to match when both are passed; mismatches are an error in
4863/// pandas, but here we sidestep ambiguity by deriving from `start.freq`.
4864///
4865/// Per br-frankenpandas-2jef (epoj Phase 2). Pure ordinal arithmetic — no
4866/// calendar conversion (Phase 3 wires chrono). `periods=0` returns empty.
4867///
4868/// ```
4869/// use fp_types::{period_range, Period, PeriodFreq};
4870/// let q1 = Period::new(216, PeriodFreq::Quarterly);
4871/// let year = period_range(q1, 4);
4872/// assert_eq!(year.len(), 4);
4873/// assert_eq!(year[0].ordinal, 216);
4874/// assert_eq!(year[3].ordinal, 219);
4875/// ```
4876#[must_use]
4877pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
4878    (0..periods).map(|i| start.shift(i as i64)).collect()
4879}
4880
4881#[cfg(test)]
4882mod tests {
4883    use super::{
4884        DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
4885        cast_scalar, common_dtype, infer_dtype,
4886    };
4887
4888    /// br-frankenpandas-ay8o9: Scalar::semantic_cmp underpins ALL ordering in
4889    /// the library (sort, min/max, is_monotonic, searchsorted, groupby key
4890    /// order) and is the reference the differential harnesses rely on. Property
4891    /// test of its total-order axioms over finite/non-NaT same-dtype scalars,
4892    /// plus the intentional NaN degeneracy. Deterministic seeded LCG — no rand
4893    /// crate, no mocks.
4894    /// br-frankenpandas-767ak: extends ay8o9's NaN pinning to the temporal NAT
4895    /// sentinels (i64::MIN). semantic_cmp treats NAT as degenerate (Equal to all
4896    /// same-dtype), which is why temporal ordering ops must treat NAT as missing.
4897    #[test]
4898    fn semantic_cmp_cross_numeric_int_float_cdpai() {
4899        // Property (br-frankenpandas-cdpai): semantic_cmp compares Int64 vs Float64
4900        // as f64, antisymmetric across the operand order. Seeded LCG, no mocks.
4901        use std::cmp::Ordering;
4902        let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
4903        let mut next = || {
4904            st = st
4905                .wrapping_mul(6_364_136_223_846_793_005)
4906                .wrapping_add(1_442_695_040_888_963_407);
4907            (st >> 33) as u32
4908        };
4909        for _ in 0..3000u32 {
4910            let i = (next() % 21) as i64 - 10;
4911            let f = (next() % 400) as f64 / 20.0 - 10.0; // finite
4912            let exp = (i as f64).partial_cmp(&f).unwrap();
4913            assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
4914            assert_eq!(
4915                Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
4916                exp.reverse()
4917            );
4918        }
4919        // Exact int/float equality compares Equal in both directions.
4920        assert_eq!(
4921            Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
4922            Ordering::Equal
4923        );
4924        assert_eq!(
4925            Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
4926            Ordering::Equal
4927        );
4928        assert_eq!(
4929            Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
4930            Ordering::Less
4931        );
4932        assert_eq!(
4933            Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
4934            Ordering::Greater
4935        );
4936    }
4937
4938    #[test]
4939    fn semantic_cmp_nat_degeneracy_temporal_767ak() {
4940        use std::cmp::Ordering;
4941        const NAT: i64 = i64::MIN;
4942
4943        // Timedelta64 NAT is degenerate (Equal to finite and to itself).
4944        let td_nat = Scalar::Timedelta64(NAT);
4945        for v in [-3i64, 0, 5, 99] {
4946            let td = Scalar::Timedelta64(v);
4947            assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
4948            assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
4949        }
4950        assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
4951
4952        // Datetime64 NAT likewise.
4953        let dt_nat = Scalar::Datetime64(NAT);
4954        for v in [-3i64, 0, 5, 99] {
4955            let dt = Scalar::Datetime64(v);
4956            assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
4957            assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
4958        }
4959        assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
4960
4961        // Non-NAT temporal values order normally (reflexive, antisymmetric, lt).
4962        for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
4963            let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
4964            assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
4965            assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); // a.cmp(b)
4966            assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
4967            let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
4968            assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
4969        }
4970    }
4971
4972    fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
4973        [
4974            Scalar::Null(NullKind::Null),
4975            Scalar::Bool(true),
4976            Scalar::Int64(-7),
4977            Scalar::Float64(3.5),
4978            Scalar::Utf8("mixed".to_owned()),
4979            Scalar::Timedelta64(11),
4980            Scalar::Datetime64(1_735_732_800_123_456_789),
4981            Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
4982            Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
4983        ]
4984    }
4985
4986    fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
4987        !matches!(
4988            (left, right),
4989            (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
4990        )
4991    }
4992
4993    #[test]
4994    fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
4995        let values = semantic_cmp_cross_variant_values_d5ikg();
4996        for (left_index, left) in values.iter().enumerate() {
4997            for (right_index, right) in values.iter().enumerate() {
4998                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
4999                {
5000                    assert_eq!(
5001                        left.semantic_cmp(right),
5002                        format!("{left:?}").cmp(&format!("{right:?}")),
5003                        "cross-variant order mismatch: {left:?} vs {right:?}"
5004                    );
5005                }
5006            }
5007        }
5008    }
5009
5010    #[test]
5011    #[ignore = "foreground release attribution harness"]
5012    fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
5013        use std::cmp::Ordering;
5014
5015        const BATCH: usize = 4_096;
5016        const BLOCKS: usize = 9;
5017
5018        fn former(left: &Scalar, right: &Scalar) -> Ordering {
5019            format!("{left:?}").cmp(&format!("{right:?}"))
5020        }
5021
5022        fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
5023            left.semantic_cmp(right)
5024        }
5025
5026        fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
5027            let mut less = 0usize;
5028            let started = std::time::Instant::now();
5029            for _ in 0..BATCH {
5030                for (left_index, left) in values.iter().enumerate() {
5031                    for (right_index, right) in values.iter().enumerate() {
5032                        if left_index != right_index
5033                            && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
5034                            && compare(std::hint::black_box(left), std::hint::black_box(right))
5035                                == Ordering::Less
5036                        {
5037                            less += 1;
5038                        }
5039                    }
5040                }
5041            }
5042            std::hint::black_box(less);
5043            started.elapsed().as_nanos()
5044        }
5045
5046        fn median(samples: &mut [u128]) -> u128 {
5047            samples.sort_unstable();
5048            samples[samples.len() / 2]
5049        }
5050
5051        let values = semantic_cmp_cross_variant_values_d5ikg();
5052
5053        for (left_index, left) in values.iter().enumerate() {
5054            for (right_index, right) in values.iter().enumerate() {
5055                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
5056                {
5057                    assert_eq!(
5058                        former(left, right),
5059                        candidate(left, right),
5060                        "cross-variant order mismatch: {left:?} vs {right:?}"
5061                    );
5062                }
5063            }
5064        }
5065
5066        std::hint::black_box(elapsed(&values, former));
5067        std::hint::black_box(elapsed(&values, candidate));
5068
5069        let mut former_samples = Vec::with_capacity(BLOCKS * 2);
5070        let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
5071        for block in 0..BLOCKS {
5072            if block.is_multiple_of(2) {
5073                former_samples.push(elapsed(&values, former));
5074                candidate_samples.push(elapsed(&values, candidate));
5075                candidate_samples.push(elapsed(&values, candidate));
5076                former_samples.push(elapsed(&values, former));
5077            } else {
5078                candidate_samples.push(elapsed(&values, candidate));
5079                former_samples.push(elapsed(&values, former));
5080                former_samples.push(elapsed(&values, former));
5081                candidate_samples.push(elapsed(&values, candidate));
5082            }
5083        }
5084
5085        let former_p50 = median(&mut former_samples);
5086        let candidate_p50 = median(&mut candidate_samples);
5087        eprintln!(
5088            "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
5089            former_p50 as f64 / candidate_p50 as f64
5090        );
5091    }
5092
5093    #[test]
5094    fn semantic_cmp_total_order_axioms_ay8o9() {
5095        use std::cmp::Ordering;
5096
5097        let mut state: u64 = 0xc0ff_eeba_df00_d123;
5098        let mut next = || {
5099            state = state
5100                .wrapping_mul(6_364_136_223_846_793_005)
5101                .wrapping_add(1_442_695_040_888_963_407);
5102            (state >> 33) as u32
5103        };
5104
5105        for iter in 0..6000u32 {
5106            let dt = next() % 4;
5107            // Build a same-dtype, finite, non-NaT scalar from a random u32.
5108            let mk = |r: u32| match dt {
5109                0 => Scalar::Int64((r % 11) as i64 - 5),
5110                // finite, in -5.0..=5.0 by 0.5 — no NaN/inf.
5111                1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
5112                2 => Scalar::Utf8(format!("s{}", r % 5)),
5113                _ => Scalar::Bool(r.is_multiple_of(2)),
5114            };
5115            let a = mk(next());
5116            let b = mk(next());
5117            let c = mk(next());
5118            let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
5119
5120            // Reflexivity.
5121            assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
5122            // Antisymmetry.
5123            assert_eq!(
5124                a.semantic_cmp(&b),
5125                b.semantic_cmp(&a).reverse(),
5126                "antisymmetric {ctx}"
5127            );
5128            // le / ge / eq consistency with the ordering.
5129            let ab = a.semantic_cmp(&b);
5130            assert_eq!(
5131                a.semantic_le(&b),
5132                ab != Ordering::Greater,
5133                "le-consistent {ctx}"
5134            );
5135            assert_eq!(
5136                a.semantic_ge(&b),
5137                ab != Ordering::Less,
5138                "ge-consistent {ctx}"
5139            );
5140            assert_eq!(
5141                a.semantic_le(&b) && a.semantic_ge(&b),
5142                ab == Ordering::Equal,
5143                "le&ge<=>eq {ctx}"
5144            );
5145            // Transitivity: a<=b && b<=c  =>  a<=c.
5146            if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
5147                assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
5148            }
5149        }
5150
5151        // Pin the intentional NaN degeneracy: a Float64 NaN compares Equal to
5152        // every finite Float64 (and to itself) — this is why ordering ops must
5153        // treat NaN as missing rather than relying on semantic_cmp to order it.
5154        let nan = Scalar::Float64(f64::NAN);
5155        for v in [
5156            Scalar::Float64(-3.5),
5157            Scalar::Float64(0.0),
5158            Scalar::Float64(7.25),
5159        ] {
5160            assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
5161            assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
5162        }
5163        assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
5164    }
5165
5166    /// br-frankenpandas-be314: common_dtype is the dtype-promotion lattice
5167    /// underpinning every binary op, alignment, and concat (dtype coercion is a
5168    /// crown-jewel correctness area). Exhaustively (all 13x13 DType pairs) assert
5169    /// its lattice axioms — an asymmetric arm would make df1+df2 and df2+df1
5170    /// disagree on dtype.
5171    #[test]
5172    fn common_dtype_lattice_axioms_be314() {
5173        const ALL: [DType; 13] = [
5174            DType::Null,
5175            DType::Bool,
5176            DType::BoolNullable,
5177            DType::Int64,
5178            DType::Int64Nullable,
5179            DType::Float64,
5180            DType::Utf8,
5181            DType::Categorical,
5182            DType::Timedelta64,
5183            DType::Datetime64,
5184            DType::Period,
5185            DType::Interval,
5186            DType::Sparse,
5187        ];
5188
5189        for &a in &ALL {
5190            // Idempotence: a promoted with itself is itself.
5191            assert_eq!(common_dtype(a, a), Ok(a), "idempotent {a:?}");
5192            // Null is the identity element of the promotion lattice.
5193            assert_eq!(
5194                common_dtype(DType::Null, a),
5195                Ok(a),
5196                "null-left identity {a:?}"
5197            );
5198            assert_eq!(
5199                common_dtype(a, DType::Null),
5200                Ok(a),
5201                "null-right identity {a:?}"
5202            );
5203
5204            for &b in &ALL {
5205                // Commutativity: same Ok value AND same ok-ness. An asymmetric
5206                // match arm would make binary-op output dtype order-dependent.
5207                assert_eq!(
5208                    common_dtype(a, b).ok(),
5209                    common_dtype(b, a).ok(),
5210                    "commutative value {a:?},{b:?}"
5211                );
5212                assert_eq!(
5213                    common_dtype(a, b).is_ok(),
5214                    common_dtype(b, a).is_ok(),
5215                    "commutative ok-ness {a:?},{b:?}"
5216                );
5217            }
5218        }
5219
5220        // Associativity over the Ok-closed subset: when both nestings succeed,
5221        // promotion order must not change the result.
5222        for &a in &ALL {
5223            for &b in &ALL {
5224                for &c in &ALL {
5225                    if let (Ok(ab), Ok(bc)) = (common_dtype(a, b), common_dtype(b, c))
5226                        && let (Ok(left), Ok(right)) = (common_dtype(ab, c), common_dtype(a, bc))
5227                    {
5228                        assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
5229                    }
5230                }
5231            }
5232        }
5233    }
5234
5235    /// br-frankenpandas-e3sfq: infer_dtype drives Column/Series construction
5236    /// dtype inference. Assert its homogeneous + mixed-coercion rules.
5237    #[test]
5238    fn infer_dtype_coercion_rules_e3sfq() {
5239        use DType::{Bool, Float64, Int64, Null, Utf8};
5240
5241        // Empty and all-null infer to Null.
5242        assert_eq!(infer_dtype(&[]), Ok(Null));
5243        assert_eq!(
5244            infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
5245            Ok(Null)
5246        );
5247
5248        // Homogeneous slices infer to their own dtype (random, seeded LCG).
5249        let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
5250        let mut next = || {
5251            s = s
5252                .wrapping_mul(6_364_136_223_846_793_005)
5253                .wrapping_add(1_442_695_040_888_963_407);
5254            (s >> 33) as u32
5255        };
5256        for _ in 0..600u32 {
5257            let n = (next() % 6) as usize + 1;
5258            let ints: Vec<Scalar> = (0..n)
5259                .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
5260                .collect();
5261            assert_eq!(infer_dtype(&ints), Ok(Int64));
5262            let floats: Vec<Scalar> = (0..n)
5263                .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
5264                .collect();
5265            assert_eq!(infer_dtype(&floats), Ok(Float64));
5266            let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
5267            assert_eq!(infer_dtype(&bools), Ok(Bool));
5268            let strs: Vec<Scalar> = (0..n)
5269                .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
5270                .collect();
5271            assert_eq!(infer_dtype(&strs), Ok(Utf8));
5272        }
5273
5274        // Mixed-coercion rules.
5275        assert_eq!(
5276            infer_dtype(&[
5277                Scalar::Int64(1),
5278                Scalar::Null(NullKind::Null),
5279                Scalar::Int64(2)
5280            ]),
5281            Ok(Int64),
5282            "Int64 + nulls -> Int64"
5283        );
5284        assert_eq!(
5285            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
5286            Ok(Float64),
5287            "Int64 + Float64 -> Float64"
5288        );
5289        assert_eq!(
5290            infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
5291            Ok(Int64),
5292            "Bool + Int64 -> Int64"
5293        );
5294        assert_eq!(
5295            infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
5296            Ok(Utf8),
5297            "Utf8 + Int64 -> Utf8 (object fallback)"
5298        );
5299    }
5300
5301    /// br-frankenpandas-1ews0: missing_for_dtype is the canonical per-dtype
5302    /// missing sentinel (used by null-fill / with_validity / cast). Exhaustively
5303    /// assert it is always missing, and that casting any missing to any dtype
5304    /// stays missing.
5305    #[test]
5306    fn missing_for_dtype_always_missing_1ews0() {
5307        const ALL: [DType; 13] = [
5308            DType::Null,
5309            DType::Bool,
5310            DType::BoolNullable,
5311            DType::Int64,
5312            DType::Int64Nullable,
5313            DType::Float64,
5314            DType::Utf8,
5315            DType::Categorical,
5316            DType::Timedelta64,
5317            DType::Datetime64,
5318            DType::Period,
5319            DType::Interval,
5320            DType::Sparse,
5321        ];
5322        for &dt in &ALL {
5323            let m = Scalar::missing_for_dtype(dt);
5324            assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
5325            for &target in &ALL {
5326                let cast = cast_scalar(&m, target).expect("cast of missing");
5327                if target == DType::Utf8 {
5328                    // Casting a missing value to string follows pandas astype(str):
5329                    // it yields a string ("None"/"NaN"/"NaT"), NOT a missing value.
5330                    assert!(
5331                        matches!(cast, Scalar::Utf8(_)),
5332                        "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
5333                    );
5334                } else {
5335                    // Every other target preserves missingness via cast_scalar's
5336                    // value.is_missing() -> missing_for_dtype(target) branch.
5337                    assert!(
5338                        cast.is_missing(),
5339                        "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
5340                    );
5341                }
5342            }
5343        }
5344    }
5345
5346    #[test]
5347    fn cast_scalar_bool_int_roundtrip_6w07b() {
5348        use super::cast_scalar;
5349        // Property (br-frankenpandas-6w07b): Bool<->Int64 cast. Seeded LCG, no mocks.
5350        assert_eq!(
5351            cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
5352            Scalar::Int64(1)
5353        );
5354        assert_eq!(
5355            cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
5356            Scalar::Int64(0)
5357        );
5358        assert_eq!(
5359            cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
5360            Scalar::Bool(false)
5361        );
5362        let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
5363        let mut next = || {
5364            st = st
5365                .wrapping_mul(6_364_136_223_846_793_005)
5366                .wrapping_add(1_442_695_040_888_963_407);
5367            (st >> 33) as u32
5368        };
5369        for _ in 0..2000u32 {
5370            let v = (next() % 21) as i64 - 10;
5371            assert_eq!(
5372                cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
5373                Scalar::Bool(v != 0),
5374                "int->bool v={v}"
5375            );
5376        }
5377    }
5378
5379    /// br-frankenpandas-6a83t: cast_scalar is the scalar dtype-coercion path
5380    #[test]
5381    fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
5382        use super::cast_scalar;
5383        // Property (br-frankenpandas-u9lec): Float64->Int64 truncates toward zero, not
5384        // floor (-3.7 -> -3). Seeded LCG, no mocks.
5385        let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
5386        let mut next = || {
5387            st = st
5388                .wrapping_mul(6_364_136_223_846_793_005)
5389                .wrapping_add(1_442_695_040_888_963_407);
5390            (st >> 33) as u32
5391        };
5392        // Explicit negative-direction checks (the gotcha).
5393        for (f, exp) in [
5394            (-3.7, -3i64),
5395            (3.7, 3),
5396            (-3.2, -3),
5397            (3.2, 3),
5398            (-0.9, 0),
5399            (0.9, 0),
5400            (-5.0, -5),
5401            (5.0, 5),
5402        ] {
5403            assert_eq!(
5404                cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
5405                Scalar::Int64(exp),
5406                "cast {f}"
5407            );
5408        }
5409        // Property over random signed fractional values.
5410        for _ in 0..3000u32 {
5411            let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; // [-1000, 1000]
5412            let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
5413            assert_eq!(
5414                got,
5415                Scalar::Int64(v.trunc() as i64),
5416                "trunc-toward-zero v={v}"
5417            );
5418        }
5419    }
5420
5421    #[test]
5422    fn nancount_nunique_prod_any_all_mx60x() {
5423        use super::{nanall, nanany, nancount, nannunique, nanprod};
5424        // br-frankenpandas-mx60x: nancount/nannunique/nanprod/nanany/nanall skip NaN
5425        // and match finite-only oracles. Seeded LCG, no mocks.
5426        let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
5427        let mut next = || {
5428            s = s
5429                .wrapping_mul(6_364_136_223_846_793_005)
5430                .wrapping_add(1_442_695_040_888_963_407);
5431            (s >> 33) as u32
5432        };
5433        let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
5434        let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
5435        for iter in 0..1000u32 {
5436            let n = (next() % 10) as usize + 1;
5437            let raw: Vec<f64> = (0..n)
5438                .map(|_| {
5439                    if next() % 4 == 0 {
5440                        f64::NAN
5441                    } else {
5442                        (next() % 5) as f64
5443                    }
5444                })
5445                .collect();
5446            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
5447            if finite.is_empty() {
5448                continue;
5449            }
5450            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
5451            let distinct: std::collections::HashSet<u64> =
5452                finite.iter().map(|x| x.to_bits()).collect();
5453            let prod: f64 = finite.iter().product();
5454            assert!(
5455                (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
5456                "nancount iter={iter}"
5457            );
5458            assert!(
5459                (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
5460                "nannunique iter={iter}"
5461            );
5462            assert!(
5463                (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
5464                "nanprod iter={iter}"
5465            );
5466            assert_eq!(
5467                asb(nanany(&scalars)),
5468                finite.iter().any(|&x| x != 0.0),
5469                "nanany iter={iter}"
5470            );
5471            assert_eq!(
5472                asb(nanall(&scalars)),
5473                finite.iter().all(|&x| x != 0.0),
5474                "nanall iter={iter}"
5475            );
5476        }
5477    }
5478
5479    #[test]
5480    fn nan_reduction_kernels_skip_correctness_1uagc() {
5481        use super::{nanmax, nanmedian, nanmin, nansum};
5482        // br-frankenpandas-1uagc: nansum/nanmin/nanmax/nanmedian skip NaN and match
5483        // finite-only oracles. Seeded LCG, no mocks.
5484        let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
5485        let mut next = || {
5486            s = s
5487                .wrapping_mul(6_364_136_223_846_793_005)
5488                .wrapping_add(1_442_695_040_888_963_407);
5489            (s >> 33) as u32
5490        };
5491        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
5492        for iter in 0..1000u32 {
5493            let n = (next() % 12) as usize + 1;
5494            let raw: Vec<f64> = (0..n)
5495                .map(|_| {
5496                    if next() % 4 == 0 {
5497                        f64::NAN
5498                    } else {
5499                        (next() % 200) as f64 - 100.0
5500                    }
5501                })
5502                .collect();
5503            let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
5504            if finite.is_empty() {
5505                continue;
5506            }
5507            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
5508            let sum: f64 = finite.iter().sum();
5509            let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
5510            let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
5511            finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
5512            let m = finite.len();
5513            let med = if m % 2 == 1 {
5514                finite[m / 2]
5515            } else {
5516                (finite[m / 2 - 1] + finite[m / 2]) / 2.0
5517            };
5518            assert!(
5519                (val(nansum(&scalars)) - sum).abs() < 1e-7,
5520                "nansum iter={iter}"
5521            );
5522            assert!(
5523                (val(nanmin(&scalars)) - mn).abs() < 1e-9,
5524                "nanmin iter={iter}"
5525            );
5526            assert!(
5527                (val(nanmax(&scalars)) - mx).abs() < 1e-9,
5528                "nanmax iter={iter}"
5529            );
5530            assert!(
5531                (val(nanmedian(&scalars)) - med).abs() < 1e-9,
5532                "nanmedian iter={iter}"
5533            );
5534        }
5535    }
5536
5537    #[test]
5538    fn nanvar_ddof_nanstd_nan_skip_p00ag() {
5539        use super::{nanmean, nanstd, nanvar};
5540        // br-frankenpandas-p00ag: nanmean/nanvar/nanstd skip NaN; ddof picks the
5541        // denominator; nanstd==sqrt(nanvar). Seeded LCG, no mocks.
5542        let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
5543        let mut next = || {
5544            s = s
5545                .wrapping_mul(6_364_136_223_846_793_005)
5546                .wrapping_add(1_442_695_040_888_963_407);
5547            (s >> 33) as u32
5548        };
5549        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
5550        for iter in 0..1000u32 {
5551            let n = (next() % 10) as usize + 2;
5552            let raw: Vec<f64> = (0..n)
5553                .map(|_| {
5554                    if next() % 4 == 0 {
5555                        f64::NAN
5556                    } else {
5557                        (next() % 200) as f64 / 7.0
5558                    }
5559                })
5560                .collect();
5561            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
5562            if finite.len() < 2 {
5563                continue;
5564            }
5565            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
5566            let nf = finite.len() as f64;
5567            let mean = finite.iter().sum::<f64>() / nf;
5568            let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
5569            assert!(
5570                (val(nanmean(&scalars)) - mean).abs() < 1e-7,
5571                "nanmean iter={iter}"
5572            );
5573            assert!(
5574                (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
5575                "nanvar ddof0 iter={iter}"
5576            );
5577            assert!(
5578                (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
5579                "nanvar ddof1 iter={iter}"
5580            );
5581            assert!(
5582                (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
5583                "nanstd ddof1 iter={iter}"
5584            );
5585        }
5586    }
5587
5588    #[test]
5589    fn nanskew_nankurt_min_sample_and_known_xybnq() {
5590        // br-frankenpandas-xybnq: guard nanskew/nankurt min-sample-size (NaN below
5591        // threshold) + known pandas G1/G2 values (the f4dc5540 inline-copy bug area).
5592        use super::{nankurt, nanskew};
5593        let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
5594        let val = |s: Scalar| -> Option<f64> {
5595            if s.is_missing() {
5596                None
5597            } else {
5598                s.to_f64().ok()
5599            }
5600        };
5601
5602        // skew needs >= 3 observations.
5603        assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
5604        let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
5605        assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
5606        let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
5607        assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
5608
5609        // kurt needs >= 4 observations.
5610        assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
5611        let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
5612        assert!(
5613            (k - (-1.2)).abs() < 1e-6,
5614            "pandas kurt([1..5]) == -1.2, got {k}"
5615        );
5616    }
5617
5618    #[test]
5619    #[ignore = "foreground release attribution harness"]
5620    fn nanskew_fused_moment_scan_ab_mavln() {
5621        const ROWS: usize = 100_000;
5622        const BATCH: usize = 8;
5623
5624        fn former(values: &[Scalar]) -> Scalar {
5625            let nums = super::collect_finite(values);
5626            let n = nums.len() as f64;
5627            if n < 3.0 {
5628                return Scalar::Null(NullKind::NaN);
5629            }
5630            let mean = nums.iter().sum::<f64>() / n;
5631            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
5632            let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
5633            let s2 = m2 / (n - 1.0);
5634            if s2 == 0.0 {
5635                return Scalar::Float64(0.0);
5636            }
5637            let s3 = s2.powf(1.5);
5638            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
5639        }
5640
5641        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
5642            match (former, candidate) {
5643                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
5644                (a, b) => assert_eq!(a, b),
5645            }
5646        }
5647
5648        fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
5649            std::hint::black_box(skew(std::hint::black_box(values)));
5650            let started = std::time::Instant::now();
5651            for _ in 0..BATCH {
5652                std::hint::black_box(skew(std::hint::black_box(values)));
5653            }
5654            started.elapsed().as_nanos()
5655        }
5656
5657        fn median(samples: &mut [u128]) -> u128 {
5658            samples.sort_unstable();
5659            samples[samples.len() / 2]
5660        }
5661
5662        for values in [
5663            vec![],
5664            vec![Scalar::Int64(1), Scalar::Int64(2)],
5665            vec![Scalar::Int64(7); 16],
5666            vec![
5667                Scalar::Int64(-3),
5668                Scalar::Null(NullKind::NaN),
5669                Scalar::Float64(2.5),
5670                Scalar::Utf8("skip".to_owned()),
5671                Scalar::Int64(11),
5672            ],
5673        ] {
5674            assert_bits_eq(former(&values), super::nanskew(&values));
5675        }
5676
5677        let values = (0..ROWS)
5678            .map(|i| {
5679                if i % 257 == 0 {
5680                    Scalar::Null(NullKind::NaN)
5681                } else {
5682                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
5683                }
5684            })
5685            .collect::<Vec<_>>();
5686        assert_bits_eq(former(&values), super::nanskew(&values));
5687
5688        for _ in 0..2 {
5689            std::hint::black_box(elapsed(&values, former));
5690            std::hint::black_box(elapsed(&values, super::nanskew));
5691        }
5692
5693        let mut former_samples = Vec::with_capacity(18);
5694        let mut candidate_samples = Vec::with_capacity(18);
5695        for block in 0_usize..9 {
5696            if block.is_multiple_of(2) {
5697                former_samples.push(elapsed(&values, former));
5698                candidate_samples.push(elapsed(&values, super::nanskew));
5699                candidate_samples.push(elapsed(&values, super::nanskew));
5700                former_samples.push(elapsed(&values, former));
5701            } else {
5702                candidate_samples.push(elapsed(&values, super::nanskew));
5703                former_samples.push(elapsed(&values, former));
5704                former_samples.push(elapsed(&values, former));
5705                candidate_samples.push(elapsed(&values, super::nanskew));
5706            }
5707        }
5708
5709        let former_p50 = median(&mut former_samples);
5710        let candidate_p50 = median(&mut candidate_samples);
5711        eprintln!(
5712            "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
5713            former_p50 as f64 / candidate_p50 as f64,
5714        );
5715        eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
5716        eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
5717    }
5718
5719    #[test]
5720    #[ignore = "foreground performance probe"]
5721    fn nankurt_fused_moment_scan_ab_idka7() {
5722        const ROWS: usize = 65_536;
5723        const BATCH: usize = 4;
5724
5725        fn former(values: &[Scalar]) -> Scalar {
5726            let nums = super::collect_finite(values);
5727            let n = nums.len() as f64;
5728            if n < 4.0 {
5729                return Scalar::Null(NullKind::NaN);
5730            }
5731            let mean = nums.iter().sum::<f64>() / n;
5732            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
5733            let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
5734            let s2 = m2 / (n - 1.0);
5735            if s2 == 0.0 {
5736                return Scalar::Float64(0.0);
5737            }
5738            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
5739            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
5740            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
5741        }
5742
5743        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
5744            match (former, candidate) {
5745                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
5746                (a, b) => assert_eq!(a, b),
5747            }
5748        }
5749
5750        fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
5751            let started = std::time::Instant::now();
5752            for _ in 0..BATCH {
5753                std::hint::black_box(kurt(std::hint::black_box(values)));
5754            }
5755            started.elapsed().as_nanos()
5756        }
5757
5758        fn median(samples: &mut [u128]) -> u128 {
5759            samples.sort_unstable();
5760            samples[samples.len() / 2]
5761        }
5762
5763        for values in [
5764            vec![],
5765            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
5766            vec![Scalar::Int64(7); 16],
5767            vec![
5768                Scalar::Int64(-3),
5769                Scalar::Null(NullKind::NaN),
5770                Scalar::Float64(2.5),
5771                Scalar::Utf8("skip".to_owned()),
5772                Scalar::Int64(11),
5773                Scalar::Float64(-7.25),
5774            ],
5775        ] {
5776            assert_bits_eq(former(&values), super::nankurt(&values));
5777        }
5778
5779        let values = (0..ROWS)
5780            .map(|i| {
5781                if i % 257 == 0 {
5782                    Scalar::Null(NullKind::NaN)
5783                } else {
5784                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
5785                }
5786            })
5787            .collect::<Vec<_>>();
5788        assert_bits_eq(former(&values), super::nankurt(&values));
5789
5790        for _ in 0..2 {
5791            std::hint::black_box(elapsed(&values, former));
5792            std::hint::black_box(elapsed(&values, super::nankurt));
5793        }
5794
5795        let mut former_samples = Vec::with_capacity(10);
5796        let mut candidate_samples = Vec::with_capacity(10);
5797        for block in 0_usize..5 {
5798            if block.is_multiple_of(2) {
5799                former_samples.push(elapsed(&values, former));
5800                candidate_samples.push(elapsed(&values, super::nankurt));
5801                candidate_samples.push(elapsed(&values, super::nankurt));
5802                former_samples.push(elapsed(&values, former));
5803            } else {
5804                candidate_samples.push(elapsed(&values, super::nankurt));
5805                former_samples.push(elapsed(&values, former));
5806                former_samples.push(elapsed(&values, former));
5807                candidate_samples.push(elapsed(&values, super::nankurt));
5808            }
5809        }
5810
5811        let former_p50 = median(&mut former_samples);
5812        let candidate_p50 = median(&mut candidate_samples);
5813        eprintln!(
5814            "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
5815            former_p50 as f64 / candidate_p50 as f64,
5816        );
5817        eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
5818        eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
5819    }
5820
5821    /// behind astype/promotion. Property test of its confirmed identity +
5822    /// numeric/bool coercion rules over random scalars. Deterministic seeded LCG.
5823    #[test]
5824    fn cast_scalar_to_utf8_formatting_yes7i() {
5825        // Property (br-frankenpandas-yes7i): cast to Utf8 formats per pandas
5826        // astype(str): Int64 -> decimal, Bool -> True/False. Seeded LCG, no mocks.
5827        let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
5828        let mut next = || {
5829            st = st
5830                .wrapping_mul(6_364_136_223_846_793_005)
5831                .wrapping_add(1_442_695_040_888_963_407);
5832            (st >> 33) as u32
5833        };
5834        for _ in 0..3000u32 {
5835            let n = (next() % 4_000_001) as i64 - 2_000_000;
5836            assert_eq!(
5837                cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
5838                Scalar::Utf8(n.to_string())
5839            );
5840        }
5841        assert_eq!(
5842            cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
5843            Scalar::Utf8("True".to_string())
5844        );
5845        assert_eq!(
5846            cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
5847            Scalar::Utf8("False".to_string())
5848        );
5849    }
5850
5851    #[test]
5852    fn cast_scalar_coercion_rules_6a83t() {
5853        let mut state: u64 = 0x5a17_c0de_1234_abcd;
5854        let mut next = || {
5855            state = state
5856                .wrapping_mul(6_364_136_223_846_793_005)
5857                .wrapping_add(1_442_695_040_888_963_407);
5858            (state >> 33) as u32
5859        };
5860
5861        for _ in 0..4000u32 {
5862            let n = (next() % 21) as i64 - 10; // -10..=10, incl 0
5863            let b = next() % 2 == 0;
5864            let f = f64::from((next() % 41) as i32 - 20) / 4.0; // finite, incl 0.0
5865
5866            let i = Scalar::Int64(n);
5867            let bo = Scalar::Bool(b);
5868            let fl = Scalar::Float64(f);
5869
5870            // Identity casts.
5871            assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
5872            assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
5873            assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
5874
5875            // Representation-preserving nullable identities.
5876            assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
5877            assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
5878
5879            // Int64 coercions.
5880            assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
5881            assert_eq!(
5882                cast_scalar(&i, DType::Float64),
5883                Ok(Scalar::Float64(n as f64))
5884            );
5885
5886            // Bool coercions.
5887            assert_eq!(
5888                cast_scalar(&bo, DType::Int64),
5889                Ok(Scalar::Int64(i64::from(b)))
5890            );
5891            assert_eq!(
5892                cast_scalar(&bo, DType::Float64),
5893                Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
5894            );
5895
5896            // Finite Float64 -> Int64 truncates toward zero (x as i64).
5897            assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
5898        }
5899    }
5900
5901    /// br-frankenpandas-esjjy / fd90.182: ergonomic From impls for Scalar.
5902    #[test]
5903    fn scalar_from_primitive_types() {
5904        // Each primitive maps to its canonical Scalar variant.
5905        assert_eq!(Scalar::from(true), Scalar::Bool(true));
5906        assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
5907        assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
5908        assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
5909        assert_eq!(
5910            Scalar::from(String::from("world")),
5911            Scalar::Utf8("world".to_owned())
5912        );
5913
5914        // .into() works in mixed-type Vec<Scalar> contexts (the README's
5915        // case_when example pattern, and what fd90.181 needed for apply_row
5916        // closures).
5917        let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
5918        assert_eq!(mixed.len(), 3);
5919        assert_eq!(mixed[0], Scalar::Int64(1));
5920        assert_eq!(mixed[1], Scalar::Float64(2.0));
5921        assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
5922    }
5923
5924    #[test]
5925    fn dtype_inference_coerces_numeric_values() {
5926        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
5927        assert_eq!(
5928            infer_dtype(&values).expect("dtype should infer"),
5929            DType::Float64
5930        );
5931    }
5932
5933    #[test]
5934    fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
5935        let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
5936        let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
5937        assert_eq!(left.dtype(), DType::Interval);
5938        assert!(!left.is_missing());
5939        assert_eq!(
5940            infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
5941            DType::Interval
5942        );
5943        assert_eq!(
5944            common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
5945            DType::Interval
5946        );
5947        assert_eq!(
5948            cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
5949            Scalar::Null(NullKind::Null)
5950        );
5951        assert_eq!(
5952            cast_scalar(&left, DType::Utf8).expect("interval string cast"),
5953            Scalar::Utf8("(0.0, 1.0]".to_owned())
5954        );
5955        assert_eq!(
5956            super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
5957            Scalar::Int64(2)
5958        );
5959    }
5960
5961    #[test]
5962    fn cast_scalar_parses_temporal_extension_strings_avm08() {
5963        let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
5964            .expect("timestamp parse")
5965            .nanos;
5966        assert_eq!(
5967            cast_scalar(
5968                &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
5969                DType::Datetime64
5970            )
5971            .expect("datetime cast"),
5972            Scalar::Datetime64(expected_nanos)
5973        );
5974        assert_eq!(
5975            cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
5976            Scalar::Period(Period::new(216, PeriodFreq::Quarterly))
5977        );
5978        assert_eq!(
5979            cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
5980                .expect("interval cast"),
5981            Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
5982        );
5983    }
5984
5985    #[test]
5986    fn missing_values_get_target_missing_marker() {
5987        let missing = Scalar::Null(NullKind::Null);
5988        let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
5989        assert_eq!(cast, Scalar::Null(NullKind::NaN));
5990    }
5991
5992    #[test]
5993    fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
5994        let cases = [
5995            (Scalar::Bool(true), "True"),
5996            (Scalar::Bool(false), "False"),
5997            (Scalar::Int64(-7), "-7"),
5998            (Scalar::Float64(1.0), "1.0"),
5999            (Scalar::Float64(1.5), "1.5"),
6000            (Scalar::Float64(f64::NAN), "nan"),
6001            (Scalar::Null(NullKind::Null), "None"),
6002            (Scalar::Null(NullKind::NaN), "nan"),
6003            (Scalar::Null(NullKind::NaT), "NaT"),
6004        ];
6005
6006        for (value, expected) in cases {
6007            assert_eq!(
6008                cast_scalar(&value, DType::Utf8).expect("cast"),
6009                Scalar::Utf8(expected.to_owned())
6010            );
6011        }
6012    }
6013
6014    #[test]
6015    fn semantic_eq_treats_nan_as_equal() {
6016        let left = Scalar::Float64(f64::NAN);
6017        let right = Scalar::Null(NullKind::NaN);
6018        assert!(left.semantic_eq(&right));
6019    }
6020
6021    #[test]
6022    fn semantic_eq_treats_nan_as_missing_null() {
6023        let left = Scalar::Float64(f64::NAN);
6024        let right = Scalar::Null(NullKind::Null);
6025        assert!(left.semantic_eq(&right));
6026    }
6027
6028    #[test]
6029    fn common_dtype_rejects_string_numeric_mix() {
6030        let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
6031        assert_eq!(
6032            err.to_string(),
6033            "dtype coercion from Utf8 to Int64 has no compatible common type"
6034        );
6035        let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
6036        assert_eq!(
6037            err.to_string(),
6038            "dtype coercion from Float64 to Utf8 has no compatible common type"
6039        );
6040    }
6041
6042    #[test]
6043    fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
6044        let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
6045
6046        assert_eq!(dtype.value_dtype, DType::Float64);
6047        assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
6048    }
6049
6050    #[test]
6051    fn sparse_dtype_rejects_sparse_value_dtype() {
6052        let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
6053
6054        assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
6055    }
6056
6057    #[test]
6058    fn common_dtype_rejects_sparse_dense_mix() {
6059        let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
6060
6061        assert_eq!(
6062            err.to_string(),
6063            "dtype coercion from Sparse to Int64 has no compatible common type"
6064        );
6065    }
6066
6067    // ── Nullable Int64/Bool dtype tests (br-frankenpandas-rg8ys.6.4) ────
6068
6069    #[test]
6070    fn nullable_int64_promotion_matrix() {
6071        // Int64 + Int64Nullable -> Int64Nullable (nullable absorbs)
6072        assert_eq!(
6073            common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
6074            DType::Int64Nullable
6075        );
6076        assert_eq!(
6077            common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
6078            DType::Int64Nullable
6079        );
6080
6081        // Int64Nullable + Float64 -> Float64 (float always wins)
6082        assert_eq!(
6083            common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
6084            DType::Float64
6085        );
6086        assert_eq!(
6087            common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
6088            DType::Float64
6089        );
6090
6091        // Int64Nullable + Int64Nullable -> Int64Nullable
6092        assert_eq!(
6093            common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
6094            DType::Int64Nullable
6095        );
6096
6097        // Bool + Int64Nullable -> Int64Nullable
6098        assert_eq!(
6099            common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
6100            DType::Int64Nullable
6101        );
6102
6103        // BoolNullable + Int64 -> Int64Nullable
6104        assert_eq!(
6105            common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
6106            DType::Int64Nullable
6107        );
6108    }
6109
6110    #[test]
6111    fn nullable_bool_promotion_matrix() {
6112        // Bool + BoolNullable -> BoolNullable
6113        assert_eq!(
6114            common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
6115            DType::BoolNullable
6116        );
6117        assert_eq!(
6118            common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
6119            DType::BoolNullable
6120        );
6121
6122        // BoolNullable + Float64 -> Float64
6123        assert_eq!(
6124            common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
6125            DType::Float64
6126        );
6127    }
6128
6129    #[test]
6130    fn dtype_is_nullable_helper() {
6131        assert!(DType::Int64Nullable.is_nullable());
6132        assert!(DType::BoolNullable.is_nullable());
6133        assert!(!DType::Int64.is_nullable());
6134        assert!(!DType::Bool.is_nullable());
6135        assert!(!DType::Float64.is_nullable());
6136        assert!(!DType::Utf8.is_nullable());
6137    }
6138
6139    #[test]
6140    fn dtype_to_nullable_conversions() {
6141        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
6142        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
6143        assert_eq!(DType::Float64.to_nullable(), DType::Float64); // unchanged
6144        assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
6145    }
6146
6147    #[test]
6148    fn dtype_to_non_nullable_conversions() {
6149        assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
6150        assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
6151        assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); // unchanged
6152        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
6153    }
6154
6155    #[test]
6156    fn nullable_dtype_name_reports_pandas_style() {
6157        assert_eq!(DType::Int64.name(), "int64");
6158        assert_eq!(DType::Int64Nullable.name(), "Int64"); // capital I
6159        assert_eq!(DType::Bool.name(), "bool");
6160        assert_eq!(DType::BoolNullable.name(), "boolean");
6161    }
6162
6163    #[test]
6164    fn cast_scalar_int64_nullable_identity() {
6165        let val = Scalar::Int64(42);
6166        // Int64 -> Int64Nullable is identity (no actual conversion)
6167        let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
6168        assert_eq!(result, Scalar::Int64(42));
6169
6170        // Int64Nullable -> Int64 is also identity
6171        let result2 = cast_scalar(&val, DType::Int64).unwrap();
6172        assert_eq!(result2, Scalar::Int64(42));
6173    }
6174
6175    #[test]
6176    fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
6177        // pandas astype(str) of floats == Python str(float): whole -> ".0",
6178        // shortest round-trip decimals, scientific (e+NN/e-NN) for large/small,
6179        // inf -> "inf", NaN -> "nan". Verified vs live pandas 2.2.3. (Previously
6180        // large/small lost scientific notation, e.g. 1e16 -> "10000000000000000.0".)
6181        let cases: &[(f64, &str)] = &[
6182            (1.0, "1.0"),
6183            (2.5, "2.5"),
6184            (100.0, "100.0"),
6185            (0.1, "0.1"),
6186            (0.0001, "0.0001"),
6187            (1e16, "1e+16"),
6188            (1e20, "1e+20"),
6189            (1e-5, "1e-05"),
6190            (1e-7, "1e-07"),
6191            (f64::INFINITY, "inf"),
6192            (f64::NEG_INFINITY, "-inf"),
6193        ];
6194        for (v, expected) in cases {
6195            assert_eq!(
6196                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
6197                Scalar::Utf8((*expected).to_owned()),
6198                "float {v} -> str"
6199            );
6200        }
6201    }
6202
6203    fn float_to_string_for_astype_former(value: f64) -> String {
6204        if value.is_nan() {
6205            return "nan".to_owned();
6206        }
6207        if value.is_infinite() {
6208            return value.to_string();
6209        }
6210        let rendered = format!("{value:?}");
6211        match rendered.split_once('e') {
6212            None => rendered,
6213            Some((mantissa, exponent)) => {
6214                let (sign, digits) = match exponent.strip_prefix('-') {
6215                    Some(digits) => ('-', digits),
6216                    None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
6217                };
6218                format!("{mantissa}e{sign}{digits:0>2}")
6219            }
6220        }
6221    }
6222
6223    fn scientific_astype_values(len: usize) -> Vec<f64> {
6224        const EXPONENTS: [i32; 16] = [
6225            -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
6226        ];
6227        (0..len)
6228            .map(|position| {
6229                let mantissa = 1.0 + (position % 997) as f64 / 997.0;
6230                let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
6231                if position.is_multiple_of(2) {
6232                    magnitude
6233                } else {
6234                    -magnitude
6235                }
6236            })
6237            .collect()
6238    }
6239
6240    #[test]
6241    fn float_to_string_for_astype_in_place_matches_former() {
6242        let fixed = [
6243            f64::NAN,
6244            f64::INFINITY,
6245            f64::NEG_INFINITY,
6246            0.0,
6247            -0.0,
6248            f64::MIN_POSITIVE,
6249            f64::MAX,
6250            f64::MIN,
6251            1e16,
6252            -1e16,
6253            1e-5,
6254            -1e-5,
6255            1.234_567_890_123_456_8e20,
6256            -9.876_543_210_987_654e-123,
6257        ];
6258        for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
6259            assert_eq!(
6260                super::float_to_string_for_astype(value),
6261                float_to_string_for_astype_former(value),
6262                "value={value:?}"
6263            );
6264        }
6265    }
6266
6267    #[test]
6268    #[ignore = "foreground performance probe"]
6269    fn float_to_string_for_astype_in_place_ab() {
6270        use std::time::Instant;
6271
6272        const VALUES: usize = 16_384;
6273        const SAMPLES: usize = 10;
6274        let values = scientific_astype_values(VALUES);
6275        for &value in &values {
6276            let former = float_to_string_for_astype_former(value);
6277            assert!(former.contains('e'), "benchmark value must be scientific");
6278            assert_eq!(super::float_to_string_for_astype(value), former);
6279        }
6280
6281        for _ in 0..2 {
6282            for &value in &values {
6283                std::hint::black_box(float_to_string_for_astype_former(value));
6284                std::hint::black_box(super::float_to_string_for_astype(value));
6285            }
6286        }
6287
6288        let mut former_ns = Vec::with_capacity(SAMPLES);
6289        let mut public_ns = Vec::with_capacity(SAMPLES);
6290        for sample in 0..SAMPLES {
6291            let run = |formatter: fn(f64) -> String| {
6292                let started = Instant::now();
6293                for &value in std::hint::black_box(&values) {
6294                    std::hint::black_box(formatter(std::hint::black_box(value)));
6295                }
6296                started.elapsed().as_nanos()
6297            };
6298            if sample.is_multiple_of(2) {
6299                former_ns.push(run(float_to_string_for_astype_former));
6300                public_ns.push(run(super::float_to_string_for_astype));
6301            } else {
6302                public_ns.push(run(super::float_to_string_for_astype));
6303                former_ns.push(run(float_to_string_for_astype_former));
6304            }
6305        }
6306
6307        former_ns.sort_unstable();
6308        public_ns.sort_unstable();
6309        let former_p50 = former_ns[SAMPLES / 2];
6310        let public_p50 = public_ns[SAMPLES / 2];
6311        println!(
6312            "float_to_string_for_astype_in_place_ab values={VALUES} former_p50_ns={former_p50} public_p50_ns={public_p50} speedup={:.6} former_samples={former_ns:?} public_samples={public_ns:?}",
6313            former_p50 as f64 / public_p50 as f64
6314        );
6315    }
6316
6317    #[test]
6318    fn cast_float_to_utf8_threshold_boundaries_match_python() {
6319        // Python str(float) switches to scientific notation only at |x| >= 1e16
6320        // or |x| < 1e-4. Values JUST INSIDE those bounds must stay decimal — a
6321        // formatter that switches to sci early (or late) diverges. All expected
6322        // values verified against Python 3 str()/repr (== pandas astype(str)).
6323        let cases: &[(f64, &str)] = &[
6324            (1e15, "1000000000000000.0"),
6325            (9_999_999_999_999_998.0, "9999999999999998.0"),
6326            (1_234_567_890_123_456.0, "1234567890123456.0"),
6327            (123_456_789_012_345.0, "123456789012345.0"),
6328            (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
6329            (1e16, "1e+16"),
6330            (1.5e16, "1.5e+16"),
6331            (1e17, "1e+17"),
6332            (1e-4, "0.0001"),
6333            (5e-5, "5e-05"),
6334            (-1e15, "-1000000000000000.0"),
6335            (-1e16, "-1e+16"),
6336            (-1e-5, "-1e-05"),
6337        ];
6338        for (v, expected) in cases {
6339            assert_eq!(
6340                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
6341                Scalar::Utf8((*expected).to_owned()),
6342                "float {v} -> str"
6343            );
6344        }
6345    }
6346
6347    #[test]
6348    fn cast_to_bool_uses_pandas_nonzero_truthiness() {
6349        // pandas astype(bool): zero -> False, any nonzero -> True (not just 0/1),
6350        // -0.0 -> False, and NaN -> True (numpy bool(nan), br-cyi4h). Verified vs
6351        // live pandas 2.2.3.
6352        let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
6353        for (v, expected) in cases_int {
6354            assert_eq!(
6355                cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
6356                Scalar::Bool(*expected),
6357                "int {v} -> bool"
6358            );
6359        }
6360        let cases_float: &[(f64, bool)] = &[
6361            (0.0, false),
6362            (-0.0, false),
6363            (0.1, true),
6364            (2.5, true),
6365            (1.0, true),
6366            // pandas astype(bool): NaN is truthy -> True (numpy bool). br-cyi4h.
6367            (f64::NAN, true),
6368        ];
6369        for (v, expected) in cases_float {
6370            assert_eq!(
6371                cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
6372                Scalar::Bool(*expected),
6373                "float {v} -> bool"
6374            );
6375        }
6376    }
6377
6378    #[test]
6379    fn nullable_dtype_is_extension() {
6380        assert!(DType::Int64Nullable.is_extension());
6381        assert!(DType::BoolNullable.is_extension());
6382        assert!(!DType::Int64.is_extension());
6383        assert!(!DType::Bool.is_extension());
6384    }
6385
6386    #[test]
6387    fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
6388        let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
6389        assert_eq!(
6390            infer_dtype(&values).expect("dtype should infer"),
6391            DType::Utf8
6392        );
6393    }
6394
6395    // ── Scalar missingness methods ─────────────────────────────────────
6396
6397    #[test]
6398    fn is_null_detects_explicit_nulls() {
6399        assert!(Scalar::Null(NullKind::Null).is_null());
6400        assert!(Scalar::Null(NullKind::NaN).is_null());
6401        assert!(!Scalar::Int64(42).is_null());
6402        assert!(!Scalar::Float64(f64::NAN).is_null());
6403    }
6404
6405    #[test]
6406    fn is_na_matches_is_missing() {
6407        let vals = vec![
6408            Scalar::Null(NullKind::Null),
6409            Scalar::Float64(f64::NAN),
6410            Scalar::Int64(0),
6411            Scalar::Bool(false),
6412        ];
6413        for v in &vals {
6414            assert_eq!(v.is_na(), v.is_missing());
6415        }
6416    }
6417
6418    #[test]
6419    fn coalesce_picks_first_non_missing() {
6420        let null = Scalar::Null(NullKind::Null);
6421        let fill = Scalar::Int64(99);
6422        assert_eq!(null.coalesce(&fill), fill);
6423        assert_eq!(fill.coalesce(&null), fill);
6424    }
6425
6426    // ── Missingness utilities ──────────────────────────────────────────
6427
6428    #[test]
6429    fn isna_notna_complement() {
6430        let vals = vec![
6431            Scalar::Int64(1),
6432            Scalar::Null(NullKind::Null),
6433            Scalar::Float64(f64::NAN),
6434            Scalar::Float64(3.0),
6435        ];
6436        let na = super::isna(&vals);
6437        let not = super::notna(&vals);
6438        assert_eq!(na, vec![false, true, true, false]);
6439        for (a, b) in na.iter().zip(not.iter()) {
6440            assert_ne!(a, b);
6441        }
6442    }
6443
6444    #[test]
6445    fn count_na_counts_missing() {
6446        let vals = vec![
6447            Scalar::Int64(1),
6448            Scalar::Null(NullKind::Null),
6449            Scalar::Float64(f64::NAN),
6450        ];
6451        assert_eq!(super::count_na(&vals), 2);
6452    }
6453
6454    #[test]
6455    fn fill_na_replaces_missing() {
6456        let vals = vec![
6457            Scalar::Int64(1),
6458            Scalar::Null(NullKind::Null),
6459            Scalar::Float64(f64::NAN),
6460            Scalar::Int64(4),
6461        ];
6462        let filled = super::fill_na(&vals, &Scalar::Int64(0));
6463        assert_eq!(filled[0], Scalar::Int64(1));
6464        assert_eq!(filled[1], Scalar::Int64(0));
6465        assert_eq!(filled[2], Scalar::Int64(0));
6466        assert_eq!(filled[3], Scalar::Int64(4));
6467    }
6468
6469    #[test]
6470    fn dropna_removes_missing() {
6471        let vals = vec![
6472            Scalar::Int64(1),
6473            Scalar::Null(NullKind::Null),
6474            Scalar::Int64(3),
6475            Scalar::Float64(f64::NAN),
6476        ];
6477        let kept = super::dropna(&vals);
6478        assert_eq!(kept.len(), 2);
6479        assert_eq!(kept[0], Scalar::Int64(1));
6480        assert_eq!(kept[1], Scalar::Int64(3));
6481    }
6482
6483    #[test]
6484    fn null_helpers_match_scalar_oracle_imt0c() {
6485        // Differential vs independent scalar null-helper oracle
6486        // (br-frankenpandas-imt0c). Seeded LCG, no mocks.
6487        fn next(seed: &mut u64) -> u64 {
6488            *seed = seed
6489                .wrapping_mul(3202034522624059733)
6490                .wrapping_add(4354685564936845319);
6491            *seed
6492        }
6493
6494        fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
6495            let expected_missing = values.iter().filter(|value| value.is_missing()).count();
6496            let expected_dropped = values
6497                .iter()
6498                .filter(|value| !value.is_missing())
6499                .cloned()
6500                .collect::<Vec<_>>();
6501            let expected_filled = values
6502                .iter()
6503                .map(|value| {
6504                    if value.is_missing() {
6505                        fill.clone()
6506                    } else {
6507                        value.clone()
6508                    }
6509                })
6510                .collect::<Vec<_>>();
6511
6512            assert_eq!(
6513                super::count_na(values),
6514                expected_missing,
6515                "case={case}: count_na mismatch for {values:?}"
6516            );
6517
6518            let dropped = super::dropna(values);
6519            assert_eq!(
6520                dropped.len(),
6521                expected_dropped.len(),
6522                "case={case}: dropna length mismatch for {values:?}"
6523            );
6524            for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
6525            {
6526                assert!(
6527                    actual.semantic_eq(expected),
6528                    "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
6529                );
6530            }
6531
6532            let filled = super::fill_na(values, fill);
6533            assert_eq!(
6534                filled.len(),
6535                expected_filled.len(),
6536                "case={case}: fill_na length mismatch for {values:?}"
6537            );
6538            for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
6539                assert!(
6540                    actual.semantic_eq(expected),
6541                    "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
6542                );
6543            }
6544        }
6545
6546        let all_missing = [
6547            Scalar::Null(NullKind::Null),
6548            Scalar::Null(NullKind::NaN),
6549            Scalar::Float64(f64::NAN),
6550            Scalar::Timedelta64(i64::MIN),
6551        ];
6552        assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
6553
6554        let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
6555        for case in 0..260 {
6556            let len = (next(&mut seed) % 83 + 1) as usize;
6557            let mut values = Vec::with_capacity(len);
6558            for pos in 0..len {
6559                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
6560                values.push(match next(&mut seed) % 11 {
6561                    0 => Scalar::Null(NullKind::Null),
6562                    1 => Scalar::Null(NullKind::NaN),
6563                    2 => Scalar::Float64(f64::NAN),
6564                    3 => Scalar::Timedelta64(i64::MIN),
6565                    4 => Scalar::Bool(raw & 1 == 0),
6566                    5 => Scalar::Int64(raw),
6567                    6 => Scalar::Float64(raw as f64 / 37.0),
6568                    7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
6569                    8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
6570                    9 => Scalar::Utf8(String::new()),
6571                    _ => Scalar::Timedelta64(raw),
6572                });
6573            }
6574
6575            let fill = match case % 5 {
6576                0 => Scalar::Bool(true),
6577                1 => Scalar::Int64(-777),
6578                2 => Scalar::Float64(12.5),
6579                3 => Scalar::Utf8("filled".into()),
6580                _ => Scalar::Timedelta64(123_456),
6581            };
6582            assert_null_helpers(case, &values, &fill);
6583        }
6584    }
6585
6586    // ── Nanops ─────────────────────────────────────────────────────────
6587
6588    #[test]
6589    fn nansum_skips_nulls() {
6590        let vals = vec![
6591            Scalar::Float64(1.0),
6592            Scalar::Null(NullKind::Null),
6593            Scalar::Float64(2.0),
6594            Scalar::Float64(f64::NAN),
6595            Scalar::Int64(7),
6596        ];
6597        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
6598    }
6599
6600    #[test]
6601    fn nansum_empty_returns_zero() {
6602        assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
6603    }
6604
6605    #[test]
6606    fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
6607        // Differential vs independent sum/mean oracles
6608        // (br-frankenpandas-1xmi7). Seeded LCG, no mocks.
6609        fn next(seed: &mut u64) -> u64 {
6610            *seed = seed
6611                .wrapping_mul(6364136223846793005)
6612                .wrapping_add(1442695040888963407);
6613            *seed
6614        }
6615
6616        fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
6617            let mut sum = 0.0;
6618            let mut count = 0usize;
6619            for value in values {
6620                if value.is_missing() {
6621                    continue;
6622                }
6623                if let Ok(value) = value.to_f64() {
6624                    sum += value;
6625                    count += 1;
6626                }
6627            }
6628            let mean = if count == 0 {
6629                Scalar::Null(NullKind::NaN)
6630            } else {
6631                Scalar::Float64(sum / count as f64)
6632            };
6633            (Scalar::Float64(sum), mean)
6634        }
6635
6636        fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
6637            let mut sum = 0_i128;
6638            let mut count = 0_i128;
6639            for value in values {
6640                if let Scalar::Timedelta64(ns) = value
6641                    && !value.is_missing()
6642                {
6643                    sum += i128::from(*ns);
6644                    count += 1;
6645                }
6646            }
6647            if count == 0 {
6648                return (Scalar::Float64(0.0), Scalar::Null(NullKind::NaN));
6649            }
6650            let sum = sum.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
6651            let mean = (sum / count).clamp(i128::from(i64::MIN), i128::from(i64::MAX));
6652            (
6653                Scalar::Timedelta64(sum as i64),
6654                Scalar::Timedelta64(mean as i64),
6655            )
6656        }
6657
6658        fn assert_sum_mean(
6659            case: usize,
6660            family: &str,
6661            values: &[Scalar],
6662            expected_sum: Scalar,
6663            expected_mean: Scalar,
6664        ) {
6665            let actual_sum = super::nansum(values);
6666            let actual_mean = super::nanmean(values);
6667            assert!(
6668                actual_sum.semantic_eq(&expected_sum),
6669                "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
6670            );
6671            assert!(
6672                actual_mean.semantic_eq(&expected_mean),
6673                "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
6674            );
6675        }
6676
6677        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
6678        let (sum, mean) = expected_numeric(&all_missing);
6679        assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
6680
6681        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
6682        let (sum, mean) = expected_timedelta(&td_all_missing);
6683        assert_sum_mean(
6684            usize::MAX - 1,
6685            "timedelta_all_missing",
6686            &td_all_missing,
6687            sum,
6688            mean,
6689        );
6690
6691        let mut seed = 0x511d_ed5a_7a11_1a55_u64;
6692        for case in 0..260 {
6693            let len = (next(&mut seed) % 89 + 1) as usize;
6694
6695            let mut numeric = Vec::with_capacity(len);
6696            numeric.push(Scalar::Int64(case as i64 - 130));
6697            for _ in 1..len {
6698                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
6699                numeric.push(match next(&mut seed) % 8 {
6700                    0 => Scalar::Null(NullKind::Null),
6701                    1 => Scalar::Null(NullKind::NaN),
6702                    2 => Scalar::Float64(f64::NAN),
6703                    3 => Scalar::Bool(raw & 1 == 0),
6704                    4 => Scalar::Int64(raw % 257),
6705                    5 => Scalar::Float64(raw as f64 / 67.0),
6706                    6 => Scalar::Float64(0.0),
6707                    _ => Scalar::Float64(-0.0),
6708                });
6709            }
6710            let (sum, mean) = expected_numeric(&numeric);
6711            assert_sum_mean(case, "numeric", &numeric, sum, mean);
6712
6713            let mut timedeltas = Vec::with_capacity(len);
6714            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
6715            for _ in 1..len {
6716                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
6717                timedeltas.push(match next(&mut seed) % 7 {
6718                    0 => Scalar::Null(NullKind::Null),
6719                    1 => Scalar::Timedelta64(i64::MIN),
6720                    _ => Scalar::Timedelta64(raw),
6721                });
6722            }
6723            let (sum, mean) = expected_timedelta(&timedeltas);
6724            assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
6725        }
6726    }
6727
6728    #[test]
6729    fn nannunique_merges_negative_zero_and_zero() {
6730        let vals = vec![
6731            Scalar::Float64(-0.0),
6732            Scalar::Float64(0.0),
6733            Scalar::Float64(1.0),
6734        ];
6735        assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
6736    }
6737
6738    #[test]
6739    fn nannunique_matches_scalar_bucket_oracle_elvbg() {
6740        // Differential vs independent scalar unique-bucket oracle
6741        // (br-frankenpandas-elvbg). Seeded LCG, no mocks.
6742        fn next(seed: &mut u64) -> u64 {
6743            *seed = seed
6744                .wrapping_mul(2862933555777941757)
6745                .wrapping_add(3037000493);
6746            *seed
6747        }
6748
6749        fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
6750            match (left, right) {
6751                (Scalar::Float64(left), Scalar::Float64(right)) => {
6752                    let left = if *left == 0.0 { 0.0 } else { *left };
6753                    let right = if *right == 0.0 { 0.0 } else { *right };
6754                    left.to_bits() == right.to_bits()
6755                }
6756                _ => left == right,
6757            }
6758        }
6759
6760        fn expected_nunique(values: &[Scalar]) -> i64 {
6761            let mut seen = Vec::<Scalar>::new();
6762            for value in values {
6763                if value.is_missing() {
6764                    continue;
6765                }
6766                if !seen.iter().any(|existing| same_bucket(existing, value)) {
6767                    seen.push(value.clone());
6768                }
6769            }
6770            seen.len() as i64
6771        }
6772
6773        fn assert_nannunique(case: usize, values: &[Scalar]) {
6774            assert_eq!(
6775                super::nannunique(values),
6776                Scalar::Int64(expected_nunique(values)),
6777                "case={case}: nannunique mismatch for {values:?}"
6778            );
6779        }
6780
6781        assert_nannunique(
6782            usize::MAX,
6783            &[
6784                Scalar::Float64(-0.0),
6785                Scalar::Float64(0.0),
6786                Scalar::Float64(f64::NAN),
6787                Scalar::Null(NullKind::Null),
6788                Scalar::Timedelta64(i64::MIN),
6789            ],
6790        );
6791
6792        let mut seed = 0x0e1b_60d0_b5e7_u64;
6793        for case in 0..320 {
6794            let len = (next(&mut seed) % 97 + 1) as usize;
6795            let mut values = Vec::with_capacity(len);
6796            for pos in 0..len {
6797                let raw = (next(&mut seed) % 1_001) as i64 - 500;
6798                values.push(match next(&mut seed) % 11 {
6799                    0 => Scalar::Null(NullKind::Null),
6800                    1 => Scalar::Null(NullKind::NaN),
6801                    2 => Scalar::Float64(f64::NAN),
6802                    3 => Scalar::Bool(raw & 1 == 0),
6803                    4 => Scalar::Int64(raw % 37),
6804                    5 => Scalar::Float64(raw as f64 / 19.0),
6805                    6 => Scalar::Float64(0.0),
6806                    7 => Scalar::Float64(-0.0),
6807                    8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
6808                    9 => Scalar::Utf8(String::new()),
6809                    _ => Scalar::Timedelta64(raw % 41),
6810                });
6811            }
6812            assert_nannunique(case, &values);
6813        }
6814    }
6815
6816    #[test]
6817    fn nanmean_basic() {
6818        let vals = vec![
6819            Scalar::Float64(2.0),
6820            Scalar::Null(NullKind::Null),
6821            Scalar::Float64(4.0),
6822        ];
6823        assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
6824    }
6825
6826    #[test]
6827    fn nanmean_all_null_returns_nan() {
6828        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
6829        assert!(super::nanmean(&vals).is_missing());
6830    }
6831
6832    #[test]
6833    fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
6834        // Per br-frankenpandas-620mj: pandas td_series.sum()/mean() return
6835        // Timedelta64, not Float64(0.0). Was silently zero before because
6836        // collect_finite drops Timedelta64 (to_f64 errors).
6837        let one_hour = 3_600 * 1_000_000_000_i64;
6838        let vals = vec![
6839            Scalar::Timedelta64(one_hour),
6840            Scalar::Timedelta64(2 * one_hour),
6841            Scalar::Timedelta64(3 * one_hour),
6842        ];
6843        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
6844        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
6845    }
6846
6847    #[test]
6848    fn nansum_nanmean_timedelta64_skips_nat_620mj() {
6849        let one_hour = 3_600 * 1_000_000_000_i64;
6850        let vals = vec![
6851            Scalar::Timedelta64(Timedelta::NAT),
6852            Scalar::Timedelta64(one_hour),
6853            Scalar::Timedelta64(3 * one_hour),
6854            Scalar::Timedelta64(Timedelta::NAT),
6855        ];
6856        // NAT is missing → skipped. Sum: 1h+3h=4h; mean: 2h.
6857        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
6858        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
6859    }
6860
6861    #[test]
6862    fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
6863        // Mixed Timedelta64 + other type bails out of the Timedelta path
6864        // and uses Float64 collect_finite (which drops Timedelta).
6865        // Preserves existing cross-type behavior (effectively ignores TD).
6866        let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
6867        // Int64(5) makes it through to_f64 → 5.0; Timedelta is dropped.
6868        assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
6869    }
6870
6871    #[test]
6872    fn nancount_counts_non_missing() {
6873        let vals = vec![
6874            Scalar::Int64(1),
6875            Scalar::Null(NullKind::Null),
6876            Scalar::Float64(3.0),
6877        ];
6878        assert_eq!(super::nancount(&vals), Scalar::Int64(2));
6879    }
6880
6881    #[test]
6882    fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
6883        // Differential vs scalar truthiness/count oracle
6884        // (br-frankenpandas-zr2qg). Seeded LCG, no mocks.
6885        fn next(seed: &mut u64) -> u64 {
6886            *seed = seed
6887                .wrapping_mul(6364136223846793005)
6888                .wrapping_add(1442695040888963407);
6889            *seed
6890        }
6891
6892        fn truthy(value: &Scalar) -> Option<bool> {
6893            if value.is_missing() {
6894                return None;
6895            }
6896            match value {
6897                Scalar::Bool(value) => Some(*value),
6898                Scalar::Int64(value) => Some(*value != 0),
6899                Scalar::Float64(value) => Some(*value != 0.0),
6900                Scalar::Utf8(value) => Some(!value.is_empty()),
6901                Scalar::Timedelta64(value) => Some(*value != 0),
6902                _ => None,
6903            }
6904        }
6905
6906        fn assert_nanops(case: usize, values: &[Scalar]) {
6907            let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
6908            let expected_any = truth_values.iter().any(|value| *value);
6909            let expected_all = !truth_values.iter().any(|value| !*value);
6910            let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
6911
6912            assert_eq!(
6913                super::nanany(values),
6914                Scalar::Bool(expected_any),
6915                "case={case}: nanany mismatch for {values:?}"
6916            );
6917            assert_eq!(
6918                super::nanall(values),
6919                Scalar::Bool(expected_all),
6920                "case={case}: nanall mismatch for {values:?}"
6921            );
6922            assert_eq!(
6923                super::nancount(values),
6924                Scalar::Int64(expected_count),
6925                "case={case}: nancount mismatch for {values:?}"
6926            );
6927        }
6928
6929        assert_nanops(
6930            usize::MAX,
6931            &[
6932                Scalar::Null(NullKind::Null),
6933                Scalar::Null(NullKind::NaN),
6934                Scalar::Float64(f64::NAN),
6935                Scalar::Timedelta64(i64::MIN),
6936            ],
6937        );
6938
6939        let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
6940        for case in 0..320 {
6941            let len = (next(&mut seed) % 89 + 1) as usize;
6942            let mut values = Vec::with_capacity(len);
6943            for pos in 0..len {
6944                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
6945                let value = match next(&mut seed) % 12 {
6946                    0 => Scalar::Null(NullKind::Null),
6947                    1 => Scalar::Null(NullKind::NaN),
6948                    2 => Scalar::Float64(f64::NAN),
6949                    3 => Scalar::Bool(raw & 1 == 0),
6950                    4 => Scalar::Bool(false),
6951                    5 => Scalar::Int64(raw % 17),
6952                    6 => Scalar::Int64(0),
6953                    7 => Scalar::Float64(raw as f64 / 23.0),
6954                    8 => Scalar::Float64(0.0),
6955                    9 => Scalar::Utf8(if raw & 1 == 0 {
6956                        String::new()
6957                    } else {
6958                        format!("nanops_{case}_{pos}")
6959                    }),
6960                    10 => Scalar::Timedelta64(raw),
6961                    _ => Scalar::Timedelta64(0),
6962                };
6963                values.push(value);
6964            }
6965            assert_nanops(case, &values);
6966        }
6967    }
6968
6969    #[test]
6970    fn nanmin_basic() {
6971        let vals = vec![
6972            Scalar::Float64(5.0),
6973            Scalar::Null(NullKind::Null),
6974            Scalar::Float64(2.0),
6975            Scalar::Float64(8.0),
6976        ];
6977        assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
6978    }
6979
6980    #[test]
6981    fn nanmax_basic() {
6982        let vals = vec![
6983            Scalar::Float64(5.0),
6984            Scalar::Float64(f64::NAN),
6985            Scalar::Float64(8.0),
6986        ];
6987        assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
6988    }
6989
6990    #[test]
6991    fn nanmin_nanmax_empty_returns_nan() {
6992        assert!(super::nanmin(&[]).is_missing());
6993        assert!(super::nanmax(&[]).is_missing());
6994    }
6995
6996    #[test]
6997    fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
6998        // Differential vs independent same-family comparator oracle
6999        // (br-frankenpandas-vj7ds). Seeded LCG, no mocks.
7000        fn next(seed: &mut u64) -> u64 {
7001            *seed = seed
7002                .wrapping_mul(6364136223846793005)
7003                .wrapping_add(1442695040888963407);
7004            *seed
7005        }
7006
7007        fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
7008            match (left, right) {
7009                (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
7010                (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
7011                (Scalar::Float64(left), Scalar::Float64(right)) => {
7012                    left.partial_cmp(right).expect("finite floats")
7013                }
7014                (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
7015                (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
7016                _ => panic!("mixed family in nanmin/nanmax oracle"),
7017            }
7018        }
7019
7020        fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
7021            let present = values
7022                .iter()
7023                .filter(|value| !value.is_missing())
7024                .cloned()
7025                .collect::<Vec<_>>();
7026            let actual_min = super::nanmin(values);
7027            let actual_max = super::nanmax(values);
7028            if present.is_empty() {
7029                assert!(
7030                    actual_min.is_missing(),
7031                    "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
7032                );
7033                assert!(
7034                    actual_max.is_missing(),
7035                    "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
7036                );
7037                return;
7038            }
7039
7040            let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
7041            let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
7042            assert!(
7043                actual_min.semantic_eq(expected_min.expect("min")),
7044                "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
7045                expected_min.expect("min")
7046            );
7047            assert!(
7048                actual_max.semantic_eq(expected_max.expect("max")),
7049                "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
7050                expected_max.expect("max")
7051            );
7052        }
7053
7054        let all_missing = [
7055            Scalar::Null(NullKind::Null),
7056            Scalar::Null(NullKind::NaN),
7057            Scalar::Float64(f64::NAN),
7058            Scalar::Timedelta64(i64::MIN),
7059        ];
7060        assert_minmax(usize::MAX, "all_missing", &all_missing);
7061
7062        let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
7063        for case in 0..240 {
7064            let len = (next(&mut seed) % 73 + 1) as usize;
7065
7066            let mut ints = Vec::with_capacity(len);
7067            ints.push(Scalar::Int64(case as i64 - 120));
7068            for _ in 1..len {
7069                let raw = (next(&mut seed) % 1_001) as i64 - 500;
7070                ints.push(match next(&mut seed) % 6 {
7071                    0 => Scalar::Null(NullKind::Null),
7072                    1 => Scalar::Null(NullKind::NaN),
7073                    _ => Scalar::Int64(raw),
7074                });
7075            }
7076            assert_minmax(case, "int", &ints);
7077
7078            let mut floats = Vec::with_capacity(len);
7079            floats.push(Scalar::Float64(case as f64 / 11.0));
7080            for _ in 1..len {
7081                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
7082                floats.push(match next(&mut seed) % 8 {
7083                    0 | 1 => Scalar::Float64(f64::NAN),
7084                    2 => Scalar::Float64(f64::INFINITY),
7085                    3 => Scalar::Float64(f64::NEG_INFINITY),
7086                    4 => Scalar::Float64(0.0),
7087                    5 => Scalar::Float64(-0.0),
7088                    _ => Scalar::Float64(raw as f64 / 41.0),
7089                });
7090            }
7091            assert_minmax(case, "float", &floats);
7092
7093            let mut bools = Vec::with_capacity(len);
7094            bools.push(Scalar::Bool(case & 1 == 0));
7095            for _ in 1..len {
7096                bools.push(match next(&mut seed) % 5 {
7097                    0 => Scalar::Null(NullKind::Null),
7098                    1 => Scalar::Null(NullKind::NaN),
7099                    raw => Scalar::Bool(raw & 1 == 0),
7100                });
7101            }
7102            assert_minmax(case, "bool", &bools);
7103
7104            let mut utf8 = Vec::with_capacity(len);
7105            utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
7106            for pos in 1..len {
7107                utf8.push(match next(&mut seed) % 7 {
7108                    0 => Scalar::Null(NullKind::Null),
7109                    1 => Scalar::Null(NullKind::NaN),
7110                    raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
7111                });
7112            }
7113            assert_minmax(case, "utf8", &utf8);
7114
7115            let mut timedeltas = Vec::with_capacity(len);
7116            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
7117            for _ in 1..len {
7118                let raw = (next(&mut seed) % 1_003) as i64 - 501;
7119                timedeltas.push(match next(&mut seed) % 7 {
7120                    0 => Scalar::Null(NullKind::Null),
7121                    1 => Scalar::Timedelta64(i64::MIN),
7122                    _ => Scalar::Timedelta64(raw),
7123                });
7124            }
7125            assert_minmax(case, "timedelta", &timedeltas);
7126        }
7127    }
7128
7129    #[test]
7130    fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
7131        let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
7132        assert!(super::nanmin(&vals).is_missing());
7133        assert!(super::nanmax(&vals).is_missing());
7134
7135        let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
7136        assert!(super::nanmin(&vals2).is_missing());
7137        assert!(super::nanmax(&vals2).is_missing());
7138    }
7139
7140    #[test]
7141    fn nanmin_nanmax_compatible_numeric_types_ok() {
7142        let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
7143        assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
7144        assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
7145    }
7146
7147    #[test]
7148    fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
7149        // Per br-frankenpandas-yic5m: nanmin/nanmax on Timedelta64 returns
7150        // the smallest/largest Timedelta64 — was silently NaN before
7151        // because Timedelta64.to_f64() errors and the catch-all swallowed it.
7152        let one_hour = 3_600 * 1_000_000_000_i64;
7153        let vals = vec![
7154            Scalar::Timedelta64(3 * one_hour),
7155            Scalar::Timedelta64(one_hour),
7156            Scalar::Timedelta64(2 * one_hour),
7157        ];
7158        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
7159        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
7160    }
7161
7162    #[test]
7163    fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
7164        let one_hour = 3_600 * 1_000_000_000_i64;
7165        let vals = vec![
7166            Scalar::Timedelta64(Timedelta::NAT),
7167            Scalar::Timedelta64(one_hour),
7168            Scalar::Timedelta64(2 * one_hour),
7169            Scalar::Timedelta64(Timedelta::NAT),
7170        ];
7171        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
7172        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
7173    }
7174
7175    #[test]
7176    fn nanmedian_odd_count() {
7177        let vals = vec![
7178            Scalar::Float64(3.0),
7179            Scalar::Null(NullKind::Null),
7180            Scalar::Float64(1.0),
7181            Scalar::Float64(2.0),
7182        ];
7183        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
7184    }
7185
7186    #[test]
7187    fn nanmedian_even_count() {
7188        let vals = vec![
7189            Scalar::Float64(1.0),
7190            Scalar::Float64(3.0),
7191            Scalar::Float64(2.0),
7192            Scalar::Float64(4.0),
7193        ];
7194        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
7195    }
7196
7197    #[test]
7198    fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
7199        // Differential vs independent sort-based median oracles
7200        // (br-frankenpandas-oabhi). Seeded LCG, no mocks.
7201        fn next(seed: &mut u64) -> u64 {
7202            *seed = seed
7203                .wrapping_mul(6364136223846793005)
7204                .wrapping_add(1442695040888963407);
7205            *seed
7206        }
7207
7208        fn expected_numeric(values: &[Scalar]) -> Scalar {
7209            let mut finite = values
7210                .iter()
7211                .filter(|value| !value.is_missing())
7212                .filter_map(|value| value.to_f64().ok())
7213                .filter(|value| !value.is_nan())
7214                .collect::<Vec<_>>();
7215            if finite.is_empty() {
7216                return Scalar::Null(NullKind::NaN);
7217            }
7218            finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
7219            let mid = finite.len() / 2;
7220            if finite.len().is_multiple_of(2) {
7221                Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
7222            } else {
7223                Scalar::Float64(finite[mid])
7224            }
7225        }
7226
7227        fn expected_timedelta(values: &[Scalar]) -> Scalar {
7228            let mut finite = values
7229                .iter()
7230                .filter_map(|value| match value {
7231                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
7232                    _ => None,
7233                })
7234                .collect::<Vec<_>>();
7235            if finite.is_empty() {
7236                return Scalar::Null(NullKind::NaN);
7237            }
7238            finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
7239            let mid = finite.len() / 2;
7240            let median = if finite.len().is_multiple_of(2) {
7241                (finite[mid - 1] + finite[mid]) / 2.0
7242            } else {
7243                finite[mid]
7244            };
7245            Scalar::Timedelta64(median as i64)
7246        }
7247
7248        fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
7249            let actual = super::nanmedian(values);
7250            assert!(
7251                actual.semantic_eq(&expected),
7252                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
7253            );
7254        }
7255
7256        assert_median(
7257            usize::MAX,
7258            "numeric_all_missing",
7259            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
7260            Scalar::Null(NullKind::NaN),
7261        );
7262        assert_median(
7263            usize::MAX - 1,
7264            "timedelta_all_missing",
7265            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
7266            Scalar::Null(NullKind::NaN),
7267        );
7268
7269        let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
7270        for case in 0..220 {
7271            let len = (next(&mut seed) % 79 + 1) as usize;
7272
7273            let mut numeric = Vec::with_capacity(len);
7274            numeric.push(Scalar::Int64(case as i64 - 110));
7275            for _ in 1..len {
7276                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
7277                numeric.push(match next(&mut seed) % 8 {
7278                    0 => Scalar::Null(NullKind::Null),
7279                    1 => Scalar::Null(NullKind::NaN),
7280                    2 => Scalar::Float64(f64::NAN),
7281                    3 => Scalar::Bool(raw & 1 == 0),
7282                    4 => Scalar::Int64(raw % 251),
7283                    5 => Scalar::Float64(raw as f64 / 61.0),
7284                    6 => Scalar::Float64(0.0),
7285                    _ => Scalar::Float64(-0.0),
7286                });
7287            }
7288            assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
7289
7290            let mut timedeltas = Vec::with_capacity(len);
7291            timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
7292            for _ in 1..len {
7293                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
7294                timedeltas.push(match next(&mut seed) % 7 {
7295                    0 => Scalar::Null(NullKind::Null),
7296                    1 => Scalar::Timedelta64(i64::MIN),
7297                    _ => Scalar::Timedelta64(raw),
7298                });
7299            }
7300            assert_median(
7301                case,
7302                "timedelta",
7303                &timedeltas,
7304                expected_timedelta(&timedeltas),
7305            );
7306        }
7307    }
7308
7309    #[test]
7310    fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
7311        // Differential vs independent variance/std/sem oracles
7312        // (br-frankenpandas-k7apg). Seeded LCG, no mocks.
7313        fn next(seed: &mut u64) -> u64 {
7314            *seed = seed
7315                .wrapping_mul(2862933555777941757)
7316                .wrapping_add(3037000493);
7317            *seed
7318        }
7319
7320        fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
7321            values
7322                .iter()
7323                .filter(|value| !value.is_missing())
7324                .filter_map(|value| value.to_f64().ok())
7325                .collect()
7326        }
7327
7328        fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
7329            values
7330                .iter()
7331                .filter_map(|value| match value {
7332                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
7333                    _ => None,
7334                })
7335                .collect()
7336        }
7337
7338        fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
7339            if samples.len() <= ddof {
7340                return None;
7341            }
7342            let mean = samples.iter().sum::<f64>() / samples.len() as f64;
7343            let sum_sq = samples
7344                .iter()
7345                .map(|value| (value - mean).powi(2))
7346                .sum::<f64>();
7347            let var = sum_sq / (samples.len() - ddof) as f64;
7348            let std = var.sqrt();
7349            let sem = std / (samples.len() as f64).sqrt();
7350            Some((var, std, sem))
7351        }
7352
7353        fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
7354            let samples = numeric_samples(values);
7355            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
7356                let missing = Scalar::Null(NullKind::NaN);
7357                return (missing.clone(), missing.clone(), missing);
7358            };
7359            (
7360                Scalar::Float64(var),
7361                Scalar::Float64(std),
7362                Scalar::Float64(sem),
7363            )
7364        }
7365
7366        fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
7367            let samples = timedelta_samples(values);
7368            if samples.is_empty() {
7369                let missing = Scalar::Null(NullKind::NaN);
7370                return (missing.clone(), missing.clone(), missing);
7371            }
7372            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
7373                let missing = Scalar::Timedelta64(i64::MIN);
7374                return (missing.clone(), missing.clone(), missing);
7375            };
7376            (
7377                Scalar::Timedelta64(var as i64),
7378                Scalar::Timedelta64(std as i64),
7379                Scalar::Timedelta64(sem as i64),
7380            )
7381        }
7382
7383        fn assert_reductions(
7384            case: usize,
7385            family: &str,
7386            values: &[Scalar],
7387            ddof: usize,
7388            expected: (Scalar, Scalar, Scalar),
7389        ) {
7390            let (expected_var, expected_std, expected_sem) = expected;
7391            let actual_var = super::nanvar(values, ddof);
7392            let actual_std = super::nanstd(values, ddof);
7393            let actual_sem = super::nansem(values, ddof);
7394            assert!(
7395                actual_var.semantic_eq(&expected_var),
7396                "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
7397            );
7398            assert!(
7399                actual_std.semantic_eq(&expected_std),
7400                "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
7401            );
7402            assert!(
7403                actual_sem.semantic_eq(&expected_sem),
7404                "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
7405            );
7406        }
7407
7408        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
7409        assert_reductions(
7410            usize::MAX,
7411            "numeric_all_missing",
7412            &numeric_all_missing,
7413            0,
7414            expected_numeric(&numeric_all_missing, 0),
7415        );
7416
7417        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
7418        assert_reductions(
7419            usize::MAX - 1,
7420            "timedelta_all_missing",
7421            &td_all_missing,
7422            0,
7423            expected_timedelta(&td_all_missing, 0),
7424        );
7425
7426        let mut seed = 0x7a11_c0de_5eed_0421_u64;
7427        for case in 0..240 {
7428            let len = (next(&mut seed) % 83 + 1) as usize;
7429            let ddof = (next(&mut seed) % 4) as usize;
7430
7431            let mut numeric = Vec::with_capacity(len);
7432            numeric.push(Scalar::Float64(case as f64 / 13.0));
7433            for _ in 1..len {
7434                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
7435                numeric.push(match next(&mut seed) % 8 {
7436                    0 => Scalar::Null(NullKind::Null),
7437                    1 => Scalar::Null(NullKind::NaN),
7438                    2 => Scalar::Float64(f64::NAN),
7439                    3 => Scalar::Bool(raw & 1 == 0),
7440                    4 => Scalar::Int64(raw % 251),
7441                    5 => Scalar::Float64(raw as f64 / 73.0),
7442                    6 => Scalar::Float64(0.0),
7443                    _ => Scalar::Float64(-0.0),
7444                });
7445            }
7446            assert_reductions(
7447                case,
7448                "numeric",
7449                &numeric,
7450                ddof,
7451                expected_numeric(&numeric, ddof),
7452            );
7453
7454            let mut timedeltas = Vec::with_capacity(len);
7455            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
7456            for _ in 1..len {
7457                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
7458                timedeltas.push(match next(&mut seed) % 7 {
7459                    0 => Scalar::Null(NullKind::Null),
7460                    1 => Scalar::Timedelta64(i64::MIN),
7461                    _ => Scalar::Timedelta64(raw),
7462                });
7463            }
7464            assert_reductions(
7465                case,
7466                "timedelta",
7467                &timedeltas,
7468                ddof,
7469                expected_timedelta(&timedeltas, ddof),
7470            );
7471        }
7472    }
7473
7474    #[test]
7475    fn nanvar_population() {
7476        let vals = vec![
7477            Scalar::Float64(2.0),
7478            Scalar::Float64(4.0),
7479            Scalar::Float64(4.0),
7480            Scalar::Float64(4.0),
7481            Scalar::Float64(5.0),
7482            Scalar::Float64(5.0),
7483            Scalar::Float64(7.0),
7484            Scalar::Float64(9.0),
7485        ];
7486        let var = super::nanvar(&vals, 0);
7487        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
7488        if let Scalar::Float64(v) = var {
7489            assert!((v - 4.0).abs() < 1e-10);
7490        }
7491    }
7492
7493    #[test]
7494    fn nanvar_sample_ddof1() {
7495        let vals = vec![
7496            Scalar::Float64(2.0),
7497            Scalar::Float64(4.0),
7498            Scalar::Float64(4.0),
7499            Scalar::Float64(4.0),
7500            Scalar::Float64(5.0),
7501            Scalar::Float64(5.0),
7502            Scalar::Float64(7.0),
7503            Scalar::Float64(9.0),
7504        ];
7505        let var = super::nanvar(&vals, 1);
7506        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
7507        if let Scalar::Float64(v) = var {
7508            assert!((v - 32.0 / 7.0).abs() < 1e-10);
7509        }
7510    }
7511
7512    #[test]
7513    fn nanvar_insufficient_values_returns_nan() {
7514        let vals = vec![Scalar::Float64(5.0)];
7515        assert!(super::nanvar(&vals, 1).is_missing());
7516    }
7517
7518    #[test]
7519    fn nanstd_is_sqrt_of_var() {
7520        let vals = vec![
7521            Scalar::Float64(2.0),
7522            Scalar::Float64(4.0),
7523            Scalar::Float64(4.0),
7524            Scalar::Float64(4.0),
7525            Scalar::Float64(5.0),
7526            Scalar::Float64(5.0),
7527            Scalar::Float64(7.0),
7528            Scalar::Float64(9.0),
7529        ];
7530        let std = super::nanstd(&vals, 0);
7531        assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
7532        if let Scalar::Float64(v) = std {
7533            assert!((v - 2.0).abs() < 1e-10);
7534        }
7535    }
7536
7537    #[test]
7538    fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
7539        // Per br-frankenpandas-j8ntk: pandas td_series.median() returns
7540        // Timedelta64; was silently NaN before via collect_finite.
7541        let one_hour = 3_600 * 1_000_000_000_i64;
7542        let vals = vec![
7543            Scalar::Timedelta64(one_hour),
7544            Scalar::Timedelta64(2 * one_hour),
7545            Scalar::Timedelta64(3 * one_hour),
7546        ];
7547        assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
7548    }
7549
7550    #[test]
7551    fn nanstd_timedelta64_preserves_dtype_j8ntk() {
7552        // Per br-frankenpandas-j8ntk: pandas td_series.std() returns
7553        // Timedelta64. Check Timedelta64 output and reasonable magnitude
7554        // for population std of [1h, 2h, 3h] = sqrt(2/3) * 1h.
7555        let one_hour: i64 = 3_600 * 1_000_000_000;
7556        let vals = vec![
7557            Scalar::Timedelta64(one_hour),
7558            Scalar::Timedelta64(2 * one_hour),
7559            Scalar::Timedelta64(3 * one_hour),
7560        ];
7561        let std = super::nanstd(&vals, 0);
7562        match std {
7563            Scalar::Timedelta64(ns) => {
7564                let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
7565                assert!(
7566                    (ns as f64 - expected).abs() < 1e6,
7567                    "expected ~{expected} ns, got {ns}"
7568                );
7569            }
7570            other => panic!("expected Timedelta64, got {other:?}"),
7571        }
7572    }
7573
7574    #[test]
7575    fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
7576        let one_hour = 3_600 * 1_000_000_000_i64;
7577        let vals = vec![Scalar::Timedelta64(one_hour)];
7578        // ddof=1 with n=1 → underflow, returns NaT
7579        match super::nanstd(&vals, 1) {
7580            Scalar::Timedelta64(v) => assert_eq!(v, Timedelta::NAT),
7581            other => panic!("expected Timedelta64 NAT, got {other:?}"),
7582        }
7583        match super::nansem(&vals, 1) {
7584            Scalar::Timedelta64(v) => assert_eq!(v, Timedelta::NAT),
7585            other => panic!("expected Timedelta64 NAT, got {other:?}"),
7586        }
7587    }
7588
7589    #[test]
7590    fn nanops_with_mixed_types() {
7591        let vals = vec![
7592            Scalar::Bool(true),
7593            Scalar::Int64(3),
7594            Scalar::Float64(6.0),
7595            Scalar::Null(NullKind::Null),
7596        ];
7597        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
7598        assert_eq!(super::nancount(&vals), Scalar::Int64(3));
7599    }
7600
7601    #[test]
7602    fn nanops_all_missing_returns_identity() {
7603        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
7604        assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
7605        assert!(super::nanmean(&vals).is_missing());
7606        assert!(super::nanmedian(&vals).is_missing());
7607        assert!(super::nanvar(&vals, 0).is_missing());
7608        assert!(super::nanstd(&vals, 0).is_missing());
7609    }
7610
7611    // ── Timedelta tests ────────────────────────────────────────────────
7612
7613    #[test]
7614    fn timedelta_parse_simple_units() {
7615        use super::Timedelta;
7616        assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
7617        assert_eq!(
7618            Timedelta::parse("2h").unwrap(),
7619            2 * Timedelta::NANOS_PER_HOUR
7620        );
7621        assert_eq!(
7622            Timedelta::parse("30m").unwrap(),
7623            30 * Timedelta::NANOS_PER_MIN
7624        );
7625        assert_eq!(
7626            Timedelta::parse("45s").unwrap(),
7627            45 * Timedelta::NANOS_PER_SEC
7628        );
7629        assert_eq!(
7630            Timedelta::parse("100ms").unwrap(),
7631            100 * Timedelta::NANOS_PER_MILLI
7632        );
7633        assert_eq!(
7634            Timedelta::parse("500us").unwrap(),
7635            500 * Timedelta::NANOS_PER_MICRO
7636        );
7637        assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
7638    }
7639
7640    #[test]
7641    fn timedelta_parse_compound() {
7642        use super::Timedelta;
7643        let expected = Timedelta::NANOS_PER_DAY
7644            + 2 * Timedelta::NANOS_PER_HOUR
7645            + 30 * Timedelta::NANOS_PER_MIN;
7646        assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
7647        assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
7648    }
7649
7650    #[test]
7651    fn timedelta_parse_iso8601_matches_pandas_tdiso() {
7652        use super::Timedelta;
7653        // Verified vs pandas 2.2.3 Timedelta(...).value.
7654        assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
7655        assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
7656        assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
7657        assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
7658        assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
7659        assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
7660        // pandas quirks: T ignored, M is minutes everywhere, units in any order.
7661        assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
7662        assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
7663        assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
7664        assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
7665        assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
7666        // Rejected like pandas: years, lowercase, bare P/PT.
7667        assert!(Timedelta::parse("P1Y").is_err());
7668        assert!(Timedelta::parse("p1d").is_err());
7669        assert!(Timedelta::parse("P").is_err());
7670        assert!(Timedelta::parse("PT").is_err());
7671    }
7672
7673    #[test]
7674    fn timedelta_parse_time_format() {
7675        use super::Timedelta;
7676        let expected = Timedelta::NANOS_PER_HOUR
7677            + 30 * Timedelta::NANOS_PER_MIN
7678            + 45 * Timedelta::NANOS_PER_SEC;
7679        assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
7680    }
7681
7682    #[test]
7683    fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
7684        use super::{Timedelta, TimedeltaError};
7685        let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
7686            .expect_err("non-ASCII fractional seconds must reject");
7687        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
7688    }
7689
7690    #[test]
7691    fn timedelta_parse_time_format_rejects_overflow_without_panic() {
7692        use super::{Timedelta, TimedeltaError};
7693        let err = Timedelta::parse("9223372036854775807:00")
7694            .expect_err("oversized hour component must reject");
7695        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
7696    }
7697
7698    #[test]
7699    fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
7700        // Per br-frankenpandas-zw3mg: the compound parser used a raw
7701        // `as i64` cast that silently saturated to i64::MAX when the
7702        // product of (decimal-digit f64) × unit multiplier overflows.
7703        // Use a large literal (no scientific notation — the lexer only
7704        // accepts digits, '.', '-'). 1e18 days × NANOS_PER_DAY (~8.64e13)
7705        // overflows i64.
7706        use super::{Timedelta, TimedeltaError};
7707        let huge = format!("{} days", "9".repeat(18));
7708        assert!(matches!(
7709            Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
7710            TimedeltaError::Overflow
7711        ));
7712    }
7713
7714    #[test]
7715    fn timedelta_parse_nat() {
7716        use super::Timedelta;
7717        assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
7718        assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
7719    }
7720
7721    #[test]
7722    fn timedelta_parse_negative() {
7723        use super::Timedelta;
7724        assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
7725    }
7726
7727    #[test]
7728    fn timedelta_components() {
7729        use super::Timedelta;
7730        let nanos = Timedelta::NANOS_PER_DAY
7731            + Timedelta::NANOS_PER_HOUR
7732            + Timedelta::NANOS_PER_MIN
7733            + Timedelta::NANOS_PER_SEC
7734            + Timedelta::NANOS_PER_MILLI
7735            + 2 * Timedelta::NANOS_PER_MICRO
7736            + 3;
7737        let comp = Timedelta::components(nanos);
7738        assert_eq!(comp.days, 1);
7739        assert_eq!(comp.hours, 1);
7740        assert_eq!(comp.minutes, 1);
7741        assert_eq!(comp.seconds, 1);
7742        assert_eq!(comp.milliseconds, 1);
7743        assert_eq!(comp.microseconds, 2);
7744        assert_eq!(comp.nanoseconds, 3);
7745    }
7746
7747    #[test]
7748    fn timedelta_negative_components_floor_div() {
7749        use super::Timedelta;
7750        // pandas floor-normalizes negative timedeltas: pd.Timedelta(-1,'s') has
7751        // days=-1, seconds=86399, components=(-1, 23, 59, 59, 0, 0, 0).
7752        let neg_1s = -Timedelta::NANOS_PER_SEC;
7753        assert_eq!(Timedelta::days(neg_1s), -1);
7754        assert_eq!(Timedelta::seconds(neg_1s), 86399);
7755        assert_eq!(Timedelta::microseconds(neg_1s), 0);
7756        assert_eq!(Timedelta::nanoseconds(neg_1s), 0);
7757        let comp = Timedelta::components(neg_1s);
7758        assert_eq!(
7759            (
7760                comp.days,
7761                comp.hours,
7762                comp.minutes,
7763                comp.seconds,
7764                comp.milliseconds,
7765                comp.microseconds,
7766                comp.nanoseconds
7767            ),
7768            (-1, 23, 59, 59, 0, 0, 0)
7769        );
7770
7771        // pd.Timedelta(-86401,'s'): days=-2, seconds=86399.
7772        let neg = -86_401 * Timedelta::NANOS_PER_SEC;
7773        assert_eq!(Timedelta::days(neg), -2);
7774        assert_eq!(Timedelta::seconds(neg), 86399);
7775    }
7776
7777    #[test]
7778    fn timedelta_total_seconds() {
7779        use super::Timedelta;
7780        let nanos = 90_000_000_000i64; // 90 seconds
7781        assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
7782        assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
7783    }
7784
7785    #[test]
7786    fn timedelta_format_basic() {
7787        use super::Timedelta;
7788        assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
7789        assert_eq!(
7790            Timedelta::format(Timedelta::NANOS_PER_DAY),
7791            "1 days 00:00:00"
7792        );
7793        assert_eq!(
7794            Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
7795            "1 days 02:00:00"
7796        );
7797    }
7798
7799    #[test]
7800    fn timedelta_format_subsecond_matches_pandas() {
7801        use super::Timedelta;
7802        // pandas str(Timedelta) uses 6 fractional digits (microseconds) unless a
7803        // sub-microsecond (nanosecond) component is present, then 9 digits.
7804        // Verified vs live pandas 2.2.3.
7805        assert_eq!(
7806            Timedelta::format(1_500_000_000), // 1.5s
7807            "0 days 00:00:01.500000"
7808        );
7809        assert_eq!(
7810            Timedelta::format(1_000_000), // 1ms
7811            "0 days 00:00:00.001000"
7812        );
7813        assert_eq!(
7814            Timedelta::format(123_456_000), // 123456us
7815            "0 days 00:00:00.123456"
7816        );
7817        // Nanosecond component -> 9 digits.
7818        assert_eq!(
7819            Timedelta::format(500), // 500ns
7820            "0 days 00:00:00.000000500"
7821        );
7822        assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
7823    }
7824
7825    #[test]
7826    fn timedelta_format_negative_uses_python_borrow_form() {
7827        use super::Timedelta;
7828        // pandas/Python normalize negatives via floor division: the days count
7829        // goes negative, the time remainder stays non-negative, and a '+' joins
7830        // them. Verified vs live pandas 2.2.3.
7831        assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
7832        assert_eq!(
7833            Timedelta::format(-Timedelta::NANOS_PER_DAY),
7834            "-1 days +00:00:00"
7835        );
7836        assert_eq!(
7837            Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
7838            "-2 days +23:00:00"
7839        );
7840        assert_eq!(
7841            Timedelta::format(-1_500_000_000),
7842            "-1 days +23:59:58.500000"
7843        );
7844        assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
7845        assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
7846    }
7847
7848    #[test]
7849    #[ignore = "foreground release attribution harness"]
7850    fn timedelta_format_single_buffer_ab_5ro9h() {
7851        use std::{hint::black_box, time::Instant};
7852
7853        use super::Timedelta;
7854
7855        fn former(nanos: i64) -> String {
7856            if nanos == Timedelta::NAT {
7857                return "NaT".to_string();
7858            }
7859
7860            let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7861            let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7862            let hours = rem / Timedelta::NANOS_PER_HOUR;
7863            let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
7864            let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
7865            let frac = rem % Timedelta::NANOS_PER_SEC;
7866
7867            let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
7868            let sep = if days < 0 { "+" } else { "" };
7869            if frac > 0 {
7870                if frac % 1_000 == 0 {
7871                    format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
7872                } else {
7873                    format!("{days} days {sep}{time_part}.{frac:09}")
7874                }
7875            } else {
7876                format!("{days} days {sep}{time_part}")
7877            }
7878        }
7879
7880        fn candidate(nanos: i64) -> String {
7881            Timedelta::format(nanos)
7882        }
7883
7884        fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
7885            let started = Instant::now();
7886            let mut digest = 0_usize;
7887            for &value in values {
7888                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
7889            }
7890            black_box(digest);
7891            started.elapsed().as_nanos()
7892        }
7893
7894        fn median(samples: &mut [u128]) -> u128 {
7895            samples.sort_unstable();
7896            samples[samples.len() / 2]
7897        }
7898
7899        let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
7900        let values: Vec<i64> = (0..16_384)
7901            .map(|i| {
7902                seed = seed
7903                    .wrapping_mul(6_364_136_223_846_793_005)
7904                    .wrapping_add(1_442_695_040_888_963_407);
7905                let magnitude = (seed & i64::MAX as u64) as i64;
7906                match i % 4 {
7907                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
7908                    1 => magnitude,
7909                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
7910                    _ => -magnitude,
7911                }
7912            })
7913            .collect();
7914
7915        for &value in &[
7916            Timedelta::NAT,
7917            0,
7918            1,
7919            -1,
7920            Timedelta::NANOS_PER_DAY,
7921            -Timedelta::NANOS_PER_DAY,
7922            i64::MAX,
7923            i64::MIN + 1,
7924        ] {
7925            assert_eq!(former(value), candidate(value));
7926        }
7927        for &value in &values {
7928            assert_eq!(former(value), candidate(value));
7929        }
7930
7931        for _ in 0..2 {
7932            black_box(elapsed(&values, former));
7933            black_box(elapsed(&values, candidate));
7934        }
7935
7936        let mut former_samples = Vec::with_capacity(18);
7937        let mut candidate_samples = Vec::with_capacity(18);
7938        for block in 0_usize..9 {
7939            if block.is_multiple_of(2) {
7940                former_samples.push(elapsed(&values, former));
7941                candidate_samples.push(elapsed(&values, candidate));
7942                candidate_samples.push(elapsed(&values, candidate));
7943                former_samples.push(elapsed(&values, former));
7944            } else {
7945                candidate_samples.push(elapsed(&values, candidate));
7946                former_samples.push(elapsed(&values, former));
7947                former_samples.push(elapsed(&values, former));
7948                candidate_samples.push(elapsed(&values, candidate));
7949            }
7950        }
7951
7952        let former_p50 = median(&mut former_samples);
7953        let candidate_p50 = median(&mut candidate_samples);
7954        eprintln!(
7955            "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
7956            values.len(),
7957            former_p50 as f64 / candidate_p50 as f64,
7958        );
7959        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
7960        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
7961    }
7962
7963    #[test]
7964    fn timedelta_isoformat_basic() {
7965        use super::Timedelta;
7966        assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
7967        assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
7968        assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
7969        assert_eq!(
7970            Timedelta::isoformat(
7971                Timedelta::NANOS_PER_DAY
7972                    + 2 * Timedelta::NANOS_PER_HOUR
7973                    + 30 * Timedelta::NANOS_PER_MIN
7974                    + 45 * Timedelta::NANOS_PER_SEC
7975            ),
7976            "P1DT2H30M45S"
7977        );
7978        assert_eq!(
7979            Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
7980            "P0DT0H0M1.5S"
7981        );
7982        assert_eq!(
7983            Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
7984            "-P1DT1H0M0S"
7985        );
7986    }
7987
7988    #[test]
7989    #[ignore = "foreground release attribution harness"]
7990    fn timedelta_isoformat_single_buffer_ab_7jra1() {
7991        use std::{hint::black_box, time::Instant};
7992
7993        use super::Timedelta;
7994
7995        fn former_impl(nanos: i64) -> String {
7996            if nanos == Timedelta::NAT {
7997                return "NaT".to_string();
7998            }
7999
8000            let negative = nanos < 0;
8001            let abs_nanos = nanos.saturating_abs();
8002            let days = abs_nanos / Timedelta::NANOS_PER_DAY;
8003            let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
8004            let hours = remaining / Timedelta::NANOS_PER_HOUR;
8005            let remaining = remaining % Timedelta::NANOS_PER_HOUR;
8006            let minutes = remaining / Timedelta::NANOS_PER_MIN;
8007            let remaining = remaining % Timedelta::NANOS_PER_MIN;
8008            let seconds = remaining / Timedelta::NANOS_PER_SEC;
8009            let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
8010
8011            let mut result = String::new();
8012            if negative {
8013                result.push('-');
8014            }
8015
8016            result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
8017
8018            if sub_sec_nanos == 0 {
8019                result.push_str(&format!("{seconds}S"));
8020            } else {
8021                let frac = format!("{sub_sec_nanos:09}");
8022                let trimmed = frac.trim_end_matches('0');
8023                result.push_str(&format!("{seconds}.{trimmed}S"));
8024            }
8025
8026            result
8027        }
8028
8029        fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
8030            let start = Instant::now();
8031            let mut digest = 0_usize;
8032            for &value in values {
8033                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
8034            }
8035            black_box(digest);
8036            start.elapsed().as_nanos()
8037        }
8038
8039        fn median(values: &mut [u128]) -> u128 {
8040            values.sort_unstable();
8041            values[values.len() / 2]
8042        }
8043
8044        let mut seed = 0x7d5a_4c31_91e2_b607_u64;
8045        let values: Vec<i64> = (0..16_384)
8046            .map(|i| {
8047                seed = seed
8048                    .wrapping_mul(6_364_136_223_846_793_005)
8049                    .wrapping_add(1_442_695_040_888_963_407);
8050                let magnitude =
8051                    (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
8052                match i % 4 {
8053                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
8054                    1 => magnitude,
8055                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
8056                    _ => -magnitude,
8057                }
8058            })
8059            .collect();
8060
8061        for &value in &[
8062            Timedelta::NAT,
8063            0,
8064            1,
8065            -1,
8066            Timedelta::NANOS_PER_DAY,
8067            i64::MAX,
8068            i64::MIN + 1,
8069        ] {
8070            assert_eq!(former_impl(value), Timedelta::isoformat(value));
8071        }
8072        for &value in &values {
8073            assert_eq!(former_impl(value), Timedelta::isoformat(value));
8074        }
8075
8076        for _ in 0..2 {
8077            black_box(elapsed(&values, former_impl));
8078            black_box(elapsed(&values, Timedelta::isoformat));
8079        }
8080
8081        let mut former = Vec::with_capacity(18);
8082        let mut candidate = Vec::with_capacity(18);
8083        for block in 0..9 {
8084            if block % 2 == 0 {
8085                former.push(elapsed(&values, former_impl));
8086                candidate.push(elapsed(&values, Timedelta::isoformat));
8087                candidate.push(elapsed(&values, Timedelta::isoformat));
8088                former.push(elapsed(&values, former_impl));
8089            } else {
8090                candidate.push(elapsed(&values, Timedelta::isoformat));
8091                former.push(elapsed(&values, former_impl));
8092                former.push(elapsed(&values, former_impl));
8093                candidate.push(elapsed(&values, Timedelta::isoformat));
8094            }
8095        }
8096
8097        let former_p50 = median(&mut former);
8098        let candidate_p50 = median(&mut candidate);
8099        eprintln!(
8100            "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
8101            values.len(),
8102            former_p50,
8103            candidate_p50,
8104            former_p50 as f64 / candidate_p50 as f64,
8105            former_p50 as f64 / values.len() as f64,
8106            candidate_p50 as f64 / values.len() as f64,
8107        );
8108        eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
8109        eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
8110    }
8111
8112    #[test]
8113    fn timedelta_floor_ceil_round() {
8114        use super::Timedelta;
8115        let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
8116
8117        // floor: rounds down
8118        assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
8119        assert_eq!(Timedelta::floor(nanos, "d"), 0);
8120
8121        // ceil: rounds up
8122        assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
8123        assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
8124
8125        // round: rounds to nearest (banker's rounding on tie)
8126        assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
8127
8128        // NaT preserved
8129        assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
8130        assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
8131        assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
8132
8133        // Invalid freq returns NAT
8134        assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
8135    }
8136
8137    #[test]
8138    fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
8139        use super::Timedelta;
8140
8141        assert_eq!(
8142            Timedelta::floor(-1, "s"),
8143            -Timedelta::NANOS_PER_SEC,
8144            "floor(-1ns, 1s)"
8145        );
8146        assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
8147        assert_eq!(
8148            Timedelta::floor(-1_500_000_000, "s"),
8149            -2 * Timedelta::NANOS_PER_SEC
8150        );
8151        assert_eq!(
8152            Timedelta::ceil(-1_500_000_000, "s"),
8153            -Timedelta::NANOS_PER_SEC
8154        );
8155        assert_eq!(
8156            Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
8157            -Timedelta::NANOS_PER_SEC
8158        );
8159        assert_eq!(
8160            Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
8161            -Timedelta::NANOS_PER_SEC
8162        );
8163        assert_eq!(
8164            Timedelta::floor(1_500_000_000, "s"),
8165            Timedelta::NANOS_PER_SEC
8166        );
8167        assert_eq!(
8168            Timedelta::ceil(1_500_000_000, "s"),
8169            2 * Timedelta::NANOS_PER_SEC
8170        );
8171    }
8172
8173    #[test]
8174    fn timedelta_scalar_dtype() {
8175        let td = Scalar::Timedelta64(86_400_000_000_000);
8176        assert_eq!(td.dtype(), DType::Timedelta64);
8177    }
8178
8179    #[test]
8180    fn timedelta_scalar_is_missing() {
8181        use super::Timedelta;
8182        let valid = Scalar::Timedelta64(1000);
8183        let nat = Scalar::Timedelta64(Timedelta::NAT);
8184        assert!(!valid.is_missing());
8185        assert!(nat.is_missing());
8186    }
8187
8188    #[test]
8189    fn dtype_utf8_deserializes_legacy_aliases() {
8190        let dtype: DType = serde_json::from_str("\"str\"").unwrap();
8191        assert_eq!(dtype, DType::Utf8);
8192
8193        let dtype: DType = serde_json::from_str("\"string\"").unwrap();
8194        assert_eq!(dtype, DType::Utf8);
8195    }
8196
8197    #[test]
8198    fn scalar_utf8_deserializes_legacy_aliases() {
8199        let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
8200        assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
8201
8202        let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
8203        assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
8204    }
8205
8206    #[test]
8207    fn nancumsum_skips_nulls_and_accumulates() {
8208        let values = vec![
8209            Scalar::Float64(1.0),
8210            Scalar::Null(NullKind::NaN),
8211            Scalar::Float64(2.0),
8212            Scalar::Float64(3.0),
8213        ];
8214        let out = super::nancumsum(&values);
8215        assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
8216        assert!(out[1].is_missing());
8217        assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
8218        assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
8219    }
8220
8221    #[test]
8222    fn nancumprod_skips_nulls_and_multiplies() {
8223        let values = vec![
8224            Scalar::Float64(2.0),
8225            Scalar::Null(NullKind::NaN),
8226            Scalar::Float64(3.0),
8227            Scalar::Float64(4.0),
8228        ];
8229        let out = super::nancumprod(&values);
8230        assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
8231        assert!(out[1].is_missing());
8232        assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
8233        assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
8234    }
8235
8236    #[test]
8237    fn nancummax_tracks_running_max() {
8238        let values = vec![
8239            Scalar::Float64(1.0),
8240            Scalar::Float64(3.0),
8241            Scalar::Null(NullKind::NaN),
8242            Scalar::Float64(2.0),
8243            Scalar::Float64(5.0),
8244        ];
8245        let out = super::nancummax(&values);
8246        assert_eq!(out[0], Scalar::Float64(1.0));
8247        assert_eq!(out[1], Scalar::Float64(3.0));
8248        assert!(out[2].is_missing());
8249        assert_eq!(out[3], Scalar::Float64(3.0));
8250        assert_eq!(out[4], Scalar::Float64(5.0));
8251    }
8252
8253    #[test]
8254    fn nancummin_tracks_running_min() {
8255        let values = vec![
8256            Scalar::Float64(5.0),
8257            Scalar::Float64(3.0),
8258            Scalar::Null(NullKind::NaN),
8259            Scalar::Float64(4.0),
8260            Scalar::Float64(1.0),
8261        ];
8262        let out = super::nancummin(&values);
8263        assert_eq!(out[0], Scalar::Float64(5.0));
8264        assert_eq!(out[1], Scalar::Float64(3.0));
8265        assert!(out[2].is_missing());
8266        assert_eq!(out[3], Scalar::Float64(3.0));
8267        assert_eq!(out[4], Scalar::Float64(1.0));
8268    }
8269
8270    #[test]
8271    fn nancumsum_timedelta64_preserves_dtype_x0x91() {
8272        // Per br-frankenpandas-x0x91: pandas td_series.cumsum() returns
8273        // Timedelta64 running sums. Was silently NaN before.
8274        let one_hour = 3_600 * 1_000_000_000_i64;
8275        let values = vec![
8276            Scalar::Timedelta64(one_hour),
8277            Scalar::Timedelta64(2 * one_hour),
8278            Scalar::Timedelta64(3 * one_hour),
8279        ];
8280        let out = super::nancumsum(&values);
8281        assert_eq!(out[0], Scalar::Timedelta64(one_hour));
8282        assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
8283        assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
8284    }
8285
8286    #[test]
8287    fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
8288        let one_hour = 3_600 * 1_000_000_000_i64;
8289        let values = vec![
8290            Scalar::Timedelta64(2 * one_hour),
8291            Scalar::Timedelta64(5 * one_hour),
8292            Scalar::Timedelta64(one_hour),
8293            Scalar::Timedelta64(3 * one_hour),
8294        ];
8295        let mx = super::nancummax(&values);
8296        assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
8297        assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
8298        assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
8299        assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
8300
8301        let mn = super::nancummin(&values);
8302        assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
8303        assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
8304        assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
8305        assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
8306    }
8307
8308    #[test]
8309    fn nancumulative_timedelta64_skips_nat_x0x91() {
8310        let one_hour = 3_600 * 1_000_000_000_i64;
8311        let values = vec![
8312            Scalar::Timedelta64(one_hour),
8313            Scalar::Timedelta64(Timedelta::NAT),
8314            Scalar::Timedelta64(2 * one_hour),
8315        ];
8316        let cs = super::nancumsum(&values);
8317        assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
8318        assert!(cs[1].is_missing());
8319        assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
8320    }
8321
8322    #[test]
8323    fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
8324        // Differential vs independent cumulative nanops oracles
8325        // (br-frankenpandas-k63oz). Seeded LCG, no mocks.
8326        fn next(seed: &mut u64) -> u64 {
8327            *seed = seed
8328                .wrapping_mul(3202034522624059733)
8329                .wrapping_add(4354685564936845319);
8330            *seed
8331        }
8332
8333        fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
8334            assert_eq!(
8335                actual.len(),
8336                expected.len(),
8337                "case={case} family={family} op={op}: length mismatch"
8338            );
8339            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
8340                assert!(
8341                    actual.semantic_eq(expected),
8342                    "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
8343                );
8344            }
8345        }
8346
8347        fn expected_numeric(
8348            values: &[Scalar],
8349        ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
8350            let mut sum = Vec::with_capacity(values.len());
8351            let mut prod = Vec::with_capacity(values.len());
8352            let mut max = Vec::with_capacity(values.len());
8353            let mut min = Vec::with_capacity(values.len());
8354            let mut running_sum = 0.0_f64;
8355            let mut running_prod = 1.0_f64;
8356            let mut running_max: Option<f64> = None;
8357            let mut running_min: Option<f64> = None;
8358
8359            for value in values {
8360                if value.is_missing() {
8361                    sum.push(Scalar::Null(NullKind::NaN));
8362                    prod.push(Scalar::Null(NullKind::NaN));
8363                    max.push(Scalar::Null(NullKind::NaN));
8364                    min.push(Scalar::Null(NullKind::NaN));
8365                    continue;
8366                }
8367                let Ok(value) = value.to_f64() else {
8368                    sum.push(Scalar::Null(NullKind::NaN));
8369                    prod.push(Scalar::Null(NullKind::NaN));
8370                    max.push(Scalar::Null(NullKind::NaN));
8371                    min.push(Scalar::Null(NullKind::NaN));
8372                    continue;
8373                };
8374                if value.is_nan() {
8375                    sum.push(Scalar::Null(NullKind::NaN));
8376                    prod.push(Scalar::Null(NullKind::NaN));
8377                    max.push(Scalar::Null(NullKind::NaN));
8378                    min.push(Scalar::Null(NullKind::NaN));
8379                    continue;
8380                }
8381                running_sum += value;
8382                running_prod *= value;
8383                running_max = Some(running_max.map_or(value, |current| current.max(value)));
8384                running_min = Some(running_min.map_or(value, |current| current.min(value)));
8385                sum.push(Scalar::Float64(running_sum));
8386                prod.push(Scalar::Float64(running_prod));
8387                max.push(Scalar::Float64(running_max.expect("initialized")));
8388                min.push(Scalar::Float64(running_min.expect("initialized")));
8389            }
8390
8391            (sum, prod, max, min)
8392        }
8393
8394        fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
8395            let mut sum = Vec::with_capacity(values.len());
8396            let mut max = Vec::with_capacity(values.len());
8397            let mut min = Vec::with_capacity(values.len());
8398            let mut running_sum = 0_i128;
8399            let mut running_max: Option<i64> = None;
8400            let mut running_min: Option<i64> = None;
8401
8402            for value in values {
8403                if value.is_missing() {
8404                    sum.push(Scalar::Null(NullKind::NaT));
8405                    max.push(Scalar::Null(NullKind::NaT));
8406                    min.push(Scalar::Null(NullKind::NaT));
8407                    continue;
8408                }
8409                let Scalar::Timedelta64(ns) = value else {
8410                    sum.push(Scalar::Null(NullKind::NaT));
8411                    max.push(Scalar::Null(NullKind::NaT));
8412                    min.push(Scalar::Null(NullKind::NaT));
8413                    continue;
8414                };
8415                running_sum = running_sum.saturating_add(i128::from(*ns));
8416                let clamped = running_sum.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
8417                running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
8418                running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
8419                sum.push(Scalar::Timedelta64(clamped as i64));
8420                max.push(Scalar::Timedelta64(running_max.expect("initialized")));
8421                min.push(Scalar::Timedelta64(running_min.expect("initialized")));
8422            }
8423
8424            (sum, max, min)
8425        }
8426
8427        let mut seed = 0xc0de_c63a_5eed_0421_u64;
8428        for case in 0..260 {
8429            let len = (next(&mut seed) % 89 + 1) as usize;
8430
8431            let mut numeric = Vec::with_capacity(len);
8432            numeric.push(Scalar::Int64(case as i64 - 130));
8433            for _ in 1..len {
8434                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
8435                numeric.push(match next(&mut seed) % 8 {
8436                    0 => Scalar::Null(NullKind::Null),
8437                    1 => Scalar::Null(NullKind::NaN),
8438                    2 => Scalar::Float64(f64::NAN),
8439                    3 => Scalar::Bool(raw & 1 == 0),
8440                    4 => Scalar::Int64(raw % 251),
8441                    5 => Scalar::Float64(raw as f64 / 79.0),
8442                    6 => Scalar::Float64(0.0),
8443                    _ => Scalar::Float64(-0.0),
8444                });
8445            }
8446            let (sum, prod, max, min) = expected_numeric(&numeric);
8447            assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
8448            assert_vec(
8449                case,
8450                "numeric",
8451                "cumprod",
8452                &super::nancumprod(&numeric),
8453                &prod,
8454            );
8455            assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
8456            assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
8457
8458            let mut timedeltas = Vec::with_capacity(len);
8459            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
8460            for _ in 1..len {
8461                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
8462                timedeltas.push(match next(&mut seed) % 7 {
8463                    0 => Scalar::Null(NullKind::Null),
8464                    1 => Scalar::Timedelta64(i64::MIN),
8465                    _ => Scalar::Timedelta64(raw),
8466                });
8467            }
8468            let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
8469            assert_vec(
8470                case,
8471                "timedelta",
8472                "cumsum",
8473                &super::nancumsum(&timedeltas),
8474                &td_sum,
8475            );
8476            assert_vec(
8477                case,
8478                "timedelta",
8479                "cummax",
8480                &super::nancummax(&timedeltas),
8481                &td_max,
8482            );
8483            assert_vec(
8484                case,
8485                "timedelta",
8486                "cummin",
8487                &super::nancummin(&timedeltas),
8488                &td_min,
8489            );
8490        }
8491    }
8492
8493    #[test]
8494    fn nanquantile_linear_interpolation_matches_numpy() {
8495        let values = vec![
8496            Scalar::Float64(1.0),
8497            Scalar::Float64(2.0),
8498            Scalar::Float64(3.0),
8499            Scalar::Float64(4.0),
8500            Scalar::Float64(5.0),
8501        ];
8502        // median
8503        let q = super::nanquantile(&values, 0.5);
8504        assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
8505        // 25th percentile: interpolate between 2.0 and 3.0 at pos 1.0 → 2.0
8506        let q25 = super::nanquantile(&values, 0.25);
8507        assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
8508    }
8509
8510    #[test]
8511    fn nanquantile_ignores_nulls() {
8512        let values = vec![
8513            Scalar::Float64(1.0),
8514            Scalar::Null(NullKind::NaN),
8515            Scalar::Float64(3.0),
8516        ];
8517        let q = super::nanquantile(&values, 0.5);
8518        assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
8519    }
8520
8521    #[test]
8522    fn nanquantile_empty_and_out_of_range_yield_null() {
8523        assert!(super::nanquantile(&[], 0.5).is_missing());
8524        assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
8525        assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
8526    }
8527
8528    #[test]
8529    fn nanquantile_timedelta64_preserves_dtype_5djk7() {
8530        // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
8531        // Timedelta64 — was silently NaN before via collect_finite.
8532        let one_hour: i64 = 3_600 * 1_000_000_000;
8533        let vals = vec![
8534            Scalar::Timedelta64(one_hour),
8535            Scalar::Timedelta64(2 * one_hour),
8536            Scalar::Timedelta64(3 * one_hour),
8537            Scalar::Timedelta64(4 * one_hour),
8538            Scalar::Timedelta64(5 * one_hour),
8539        ];
8540        assert_eq!(
8541            super::nanquantile(&vals, 0.5),
8542            Scalar::Timedelta64(3 * one_hour)
8543        );
8544        assert_eq!(
8545            super::nanquantile(&vals, 0.0),
8546            Scalar::Timedelta64(one_hour)
8547        );
8548        assert_eq!(
8549            super::nanquantile(&vals, 1.0),
8550            Scalar::Timedelta64(5 * one_hour)
8551        );
8552    }
8553
8554    #[test]
8555    fn nanquantile_timedelta64_linear_interpolation_5djk7() {
8556        let one_hour: i64 = 3_600 * 1_000_000_000;
8557        let vals = vec![
8558            Scalar::Timedelta64(one_hour),
8559            Scalar::Timedelta64(3 * one_hour),
8560        ];
8561        // Linear interpolation: at q=0.5, midpoint = 2h
8562        assert_eq!(
8563            super::nanquantile(&vals, 0.5),
8564            Scalar::Timedelta64(2 * one_hour)
8565        );
8566    }
8567
8568    #[test]
8569    fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
8570        // Differential vs independent sort-based quantile oracles
8571        // (br-frankenpandas-ecb7r). Seeded LCG, no mocks.
8572        fn next(seed: &mut u64) -> u64 {
8573            *seed = seed
8574                .wrapping_mul(3202034522624059733)
8575                .wrapping_add(4354685564936845319);
8576            *seed
8577        }
8578
8579        fn interpolated(sorted: &[f64], q: f64) -> f64 {
8580            if sorted.len() == 1 {
8581                return sorted[0];
8582            }
8583            let pos = q * (sorted.len() - 1) as f64;
8584            let lo = pos.floor() as usize;
8585            let hi = pos.ceil() as usize;
8586            if lo == hi {
8587                sorted[lo]
8588            } else {
8589                let weight = pos - lo as f64;
8590                sorted[lo] + (sorted[hi] - sorted[lo]) * weight
8591            }
8592        }
8593
8594        fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
8595            if !(0.0..=1.0).contains(&q) {
8596                return Scalar::Null(NullKind::NaN);
8597            }
8598            let mut samples = values
8599                .iter()
8600                .filter(|value| !value.is_missing())
8601                .filter_map(|value| value.to_f64().ok())
8602                .collect::<Vec<_>>();
8603            if samples.is_empty() {
8604                return Scalar::Null(NullKind::NaN);
8605            }
8606            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
8607            Scalar::Float64(interpolated(&samples, q))
8608        }
8609
8610        fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
8611            if !(0.0..=1.0).contains(&q) {
8612                return Scalar::Null(NullKind::NaN);
8613            }
8614            let mut samples = values
8615                .iter()
8616                .filter_map(|value| match value {
8617                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
8618                    _ => None,
8619                })
8620                .collect::<Vec<_>>();
8621            if samples.is_empty() {
8622                return Scalar::Null(NullKind::NaN);
8623            }
8624            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
8625            Scalar::Timedelta64(interpolated(&samples, q) as i64)
8626        }
8627
8628        fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
8629            let actual = super::nanquantile(values, q);
8630            assert!(
8631                actual.semantic_eq(&expected),
8632                "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
8633            );
8634        }
8635
8636        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
8637        assert_quantile(
8638            usize::MAX,
8639            "numeric_all_missing",
8640            &numeric_all_missing,
8641            0.5,
8642            expected_numeric(&numeric_all_missing, 0.5),
8643        );
8644        assert_quantile(
8645            usize::MAX - 1,
8646            "numeric_out_of_range",
8647            &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
8648            1.25,
8649            Scalar::Null(NullKind::NaN),
8650        );
8651
8652        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
8653        assert_quantile(
8654            usize::MAX - 2,
8655            "timedelta_all_missing",
8656            &td_all_missing,
8657            0.5,
8658            expected_timedelta(&td_all_missing, 0.5),
8659        );
8660        assert_quantile(
8661            usize::MAX - 3,
8662            "timedelta_out_of_range",
8663            &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
8664            -0.25,
8665            Scalar::Null(NullKind::NaN),
8666        );
8667
8668        let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
8669        for case in 0..260 {
8670            let len = (next(&mut seed) % 83 + 1) as usize;
8671            let q = match next(&mut seed) % 8 {
8672                0 => 0.0,
8673                1 => 0.25,
8674                2 => 0.5,
8675                3 => 0.75,
8676                4 => 1.0,
8677                _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
8678            };
8679
8680            let mut numeric = Vec::with_capacity(len);
8681            numeric.push(Scalar::Int64(case as i64 - 130));
8682            for _ in 1..len {
8683                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
8684                numeric.push(match next(&mut seed) % 8 {
8685                    0 => Scalar::Null(NullKind::Null),
8686                    1 => Scalar::Null(NullKind::NaN),
8687                    2 => Scalar::Float64(f64::NAN),
8688                    3 => Scalar::Bool(raw & 1 == 0),
8689                    4 => Scalar::Int64(raw % 251),
8690                    5 => Scalar::Float64(raw as f64 / 67.0),
8691                    6 => Scalar::Float64(0.0),
8692                    _ => Scalar::Float64(-0.0),
8693                });
8694            }
8695            assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
8696
8697            let mut timedeltas = Vec::with_capacity(len);
8698            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
8699            for _ in 1..len {
8700                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
8701                timedeltas.push(match next(&mut seed) % 7 {
8702                    0 => Scalar::Null(NullKind::Null),
8703                    1 => Scalar::Timedelta64(i64::MIN),
8704                    _ => Scalar::Timedelta64(raw),
8705                });
8706            }
8707            assert_quantile(
8708                case,
8709                "timedelta",
8710                &timedeltas,
8711                q,
8712                expected_timedelta(&timedeltas, q),
8713            );
8714        }
8715    }
8716
8717    #[test]
8718    fn nanargmax_returns_first_position() {
8719        let values = vec![
8720            Scalar::Float64(1.0),
8721            Scalar::Null(NullKind::NaN),
8722            Scalar::Float64(4.0),
8723            Scalar::Float64(4.0),
8724            Scalar::Float64(2.0),
8725        ];
8726        assert_eq!(super::nanargmax(&values), Some(2));
8727    }
8728
8729    #[test]
8730    fn nanargmin_returns_first_position() {
8731        let values = vec![
8732            Scalar::Float64(3.0),
8733            Scalar::Null(NullKind::NaN),
8734            Scalar::Float64(1.0),
8735            Scalar::Float64(1.0),
8736        ];
8737        assert_eq!(super::nanargmin(&values), Some(2));
8738    }
8739
8740    #[test]
8741    fn nanargmax_all_missing_returns_none() {
8742        let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
8743        assert_eq!(super::nanargmax(&values), None);
8744        assert_eq!(super::nanargmin(&values), None);
8745    }
8746
8747    #[test]
8748    fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
8749        // Differential vs independent first-tie arg oracles
8750        // (br-frankenpandas-unkj6). Seeded LCG, no mocks.
8751        fn next(seed: &mut u64) -> u64 {
8752            *seed = seed
8753                .wrapping_mul(2862933555777941757)
8754                .wrapping_add(3037000493);
8755            *seed
8756        }
8757
8758        fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
8759            let mut best: Option<(usize, f64)> = None;
8760            for (idx, value) in values.iter().enumerate() {
8761                if value.is_missing() {
8762                    continue;
8763                }
8764                let Ok(value) = value.to_f64() else {
8765                    continue;
8766                };
8767                if value.is_nan() {
8768                    continue;
8769                }
8770                match best {
8771                    None => best = Some((idx, value)),
8772                    Some((_, current))
8773                        if (find_max && value > current) || (!find_max && value < current) =>
8774                    {
8775                        best = Some((idx, value));
8776                    }
8777                    _ => {}
8778                }
8779            }
8780            best.map(|(idx, _)| idx)
8781        }
8782
8783        fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
8784            let mut best: Option<(usize, i64)> = None;
8785            for (idx, value) in values.iter().enumerate() {
8786                if value.is_missing() {
8787                    continue;
8788                }
8789                let Scalar::Timedelta64(ns) = value else {
8790                    continue;
8791                };
8792                match best {
8793                    None => best = Some((idx, *ns)),
8794                    Some((_, current))
8795                        if (find_max && *ns > current) || (!find_max && *ns < current) =>
8796                    {
8797                        best = Some((idx, *ns));
8798                    }
8799                    _ => {}
8800                }
8801            }
8802            best.map(|(idx, _)| idx)
8803        }
8804
8805        fn assert_args(
8806            case: usize,
8807            family: &str,
8808            values: &[Scalar],
8809            expected_min: Option<usize>,
8810            expected_max: Option<usize>,
8811        ) {
8812            assert_eq!(
8813                super::nanargmin(values),
8814                expected_min,
8815                "case={case} family={family}: nanargmin mismatch for {values:?}"
8816            );
8817            assert_eq!(
8818                super::nanargmax(values),
8819                expected_max,
8820                "case={case} family={family}: nanargmax mismatch for {values:?}"
8821            );
8822        }
8823
8824        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
8825        assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
8826        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
8827        assert_args(
8828            usize::MAX - 1,
8829            "timedelta_all_missing",
8830            &td_all_missing,
8831            None,
8832            None,
8833        );
8834
8835        let mut seed = 0xa126_5eed_ed9e_u64;
8836        for case in 0..260 {
8837            let len = (next(&mut seed) % 83 + 1) as usize;
8838
8839            let mut numeric = Vec::with_capacity(len);
8840            numeric.push(Scalar::Int64(case as i64 - 130));
8841            if len > 1 {
8842                numeric.push(Scalar::Int64(case as i64 - 130));
8843            }
8844            for _ in numeric.len()..len {
8845                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
8846                numeric.push(match next(&mut seed) % 9 {
8847                    0 => Scalar::Null(NullKind::Null),
8848                    1 => Scalar::Null(NullKind::NaN),
8849                    2 => Scalar::Float64(f64::NAN),
8850                    3 => Scalar::Bool(raw & 1 == 0),
8851                    4 => Scalar::Int64(raw % 211),
8852                    5 => Scalar::Float64(raw as f64 / 47.0),
8853                    6 => Scalar::Float64(0.0),
8854                    7 => Scalar::Float64(-0.0),
8855                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
8856                });
8857            }
8858            assert_args(
8859                case,
8860                "numeric",
8861                &numeric,
8862                expected_numeric(&numeric, false),
8863                expected_numeric(&numeric, true),
8864            );
8865
8866            let mut timedeltas = Vec::with_capacity(len);
8867            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
8868            if len > 1 {
8869                timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
8870            }
8871            for _ in timedeltas.len()..len {
8872                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
8873                timedeltas.push(match next(&mut seed) % 7 {
8874                    0 => Scalar::Null(NullKind::Null),
8875                    1 => Scalar::Timedelta64(i64::MIN),
8876                    _ => Scalar::Timedelta64(raw),
8877                });
8878            }
8879            assert_args(
8880                case,
8881                "timedelta",
8882                &timedeltas,
8883                expected_timedelta(&timedeltas, false),
8884                expected_timedelta(&timedeltas, true),
8885            );
8886        }
8887    }
8888
8889    #[test]
8890    fn nansem_matches_std_over_sqrt_n() {
8891        let values = vec![
8892            Scalar::Float64(2.0),
8893            Scalar::Float64(4.0),
8894            Scalar::Float64(4.0),
8895            Scalar::Float64(4.0),
8896            Scalar::Float64(5.0),
8897            Scalar::Float64(5.0),
8898            Scalar::Float64(7.0),
8899            Scalar::Float64(9.0),
8900        ];
8901        // numpy/scipy: std(ddof=1) = 2.138089935299395; sem = std/sqrt(8) = 0.7559
8902        let sem = super::nansem(&values, 1);
8903        assert!(matches!(sem, Scalar::Float64(_)));
8904        let Scalar::Float64(v) = sem else {
8905            return;
8906        };
8907        assert!((v - 0.7559289460184544).abs() < 1e-9);
8908    }
8909
8910    #[test]
8911    fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
8912        fn former(values: &[Scalar], ddof: usize) -> Scalar {
8913            let nums = super::collect_finite(values);
8914            if nums.len() <= ddof {
8915                return Scalar::Null(NullKind::NaN);
8916            }
8917            match super::nanstd(values, ddof) {
8918                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
8919                other => other,
8920            }
8921        }
8922
8923        fn assert_same_bits(values: &[Scalar], ddof: usize) {
8924            let expected = former(values, ddof);
8925            let actual = super::nansem(values, ddof);
8926            match (&expected, &actual) {
8927                (Scalar::Float64(expected), Scalar::Float64(actual)) => {
8928                    assert_eq!(
8929                        actual.to_bits(),
8930                        expected.to_bits(),
8931                        "values={values:?} ddof={ddof}"
8932                    );
8933                }
8934                _ => assert!(
8935                    actual.semantic_eq(&expected),
8936                    "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
8937                ),
8938            }
8939        }
8940
8941        let mut generated = Vec::with_capacity(4_096);
8942        for idx in 0..4_096_i64 {
8943            generated.push(match idx % 257 {
8944                0 => Scalar::Null(NullKind::NaN),
8945                1 => Scalar::Float64(-0.0),
8946                2 => Scalar::Float64(0.0),
8947                _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
8948                _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
8949            });
8950        }
8951
8952        let cases = [
8953            Vec::new(),
8954            vec![Scalar::Int64(1)],
8955            vec![
8956                Scalar::Null(NullKind::Null),
8957                Scalar::Float64(f64::NAN),
8958                Scalar::Int64(i64::MIN),
8959                Scalar::Int64(i64::MAX),
8960                Scalar::Float64(-0.0),
8961                Scalar::Float64(0.0),
8962            ],
8963            generated,
8964        ];
8965        for values in &cases {
8966            for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
8967                assert_same_bits(values, ddof);
8968            }
8969        }
8970    }
8971
8972    #[test]
8973    #[ignore = "foreground release A/B harness"]
8974    fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
8975        const ROWS: usize = 262_144;
8976        const BATCH: usize = 8;
8977        const BLOCKS: usize = 9;
8978        const PRECONDITION_CALLS: usize = 2;
8979
8980        fn former(values: &[Scalar], ddof: usize) -> Scalar {
8981            let nums = super::collect_finite(values);
8982            if nums.len() <= ddof {
8983                return Scalar::Null(NullKind::NaN);
8984            }
8985            match super::nanstd(values, ddof) {
8986                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
8987                other => other,
8988            }
8989        }
8990
8991        fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
8992            let values = std::hint::black_box(values);
8993            if candidate {
8994                super::nansem(values, 1)
8995            } else {
8996                former(values, 1)
8997            }
8998        }
8999
9000        fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
9001            for _ in 0..PRECONDITION_CALLS {
9002                std::hint::black_box(evaluate(values, candidate));
9003            }
9004            let started = std::time::Instant::now();
9005            for _ in 0..BATCH {
9006                std::hint::black_box(evaluate(values, candidate));
9007            }
9008            started.elapsed().as_nanos()
9009        }
9010
9011        fn median(mut samples: Vec<u128>) -> u128 {
9012            samples.sort_unstable();
9013            samples[samples.len() / 2]
9014        }
9015
9016        fn spread(a: u128, b: u128) -> f64 {
9017            a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
9018        }
9019
9020        let values = (0..ROWS)
9021            .map(|idx| {
9022                if idx % 257 == 0 {
9023                    Scalar::Null(NullKind::NaN)
9024                } else {
9025                    Scalar::Int64((idx % 8_191) as i64 - 4_095)
9026                }
9027            })
9028            .collect::<Vec<_>>();
9029
9030        let expected_bits = match former(&values, 1) {
9031            Scalar::Float64(value) => Some(value.to_bits()),
9032            _ => None,
9033        };
9034        let actual_bits = match super::nansem(&values, 1) {
9035            Scalar::Float64(value) => Some(value.to_bits()),
9036            _ => None,
9037        };
9038        assert!(
9039            expected_bits.is_some(),
9040            "numeric nansem must return Float64"
9041        );
9042        assert_eq!(actual_bits, expected_bits, "A/B output bits");
9043
9044        std::hint::black_box(evaluate(&values, false));
9045        std::hint::black_box(evaluate(&values, true));
9046
9047        let body_started = std::time::Instant::now();
9048        let mut former_a = Vec::with_capacity(BLOCKS);
9049        let mut former_b = Vec::with_capacity(BLOCKS);
9050        let mut candidate_a = Vec::with_capacity(BLOCKS);
9051        let mut candidate_b = Vec::with_capacity(BLOCKS);
9052        for block in 0..BLOCKS {
9053            let order = if block % 2 == 0 {
9054                [(false, 0), (true, 0), (true, 1), (false, 1)]
9055            } else {
9056                [(true, 1), (false, 1), (false, 0), (true, 0)]
9057            };
9058            for (candidate, duplicate) in order {
9059                let elapsed = elapsed_ns(&values, candidate);
9060                match (candidate, duplicate) {
9061                    (false, 0) => former_a.push(elapsed),
9062                    (false, _) => former_b.push(elapsed),
9063                    (true, 0) => candidate_a.push(elapsed),
9064                    (true, _) => candidate_b.push(elapsed),
9065                }
9066            }
9067        }
9068
9069        let former_a = median(former_a) / BATCH as u128;
9070        let former_b = median(former_b) / BATCH as u128;
9071        let candidate_a = median(candidate_a) / BATCH as u128;
9072        let candidate_b = median(candidate_b) / BATCH as u128;
9073        let former_mean = (former_a + former_b) as f64 / 2.0;
9074        let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
9075        println!(
9076            "NANSEM_SINGLE_BUFFER_AB rows={ROWS} former_a_ns={former_a} former_b_ns={former_b} candidate_a_ns={candidate_a} candidate_b_ns={candidate_b} former_spread={:.6} candidate_spread={:.6} speedup={:.6} body_seconds={:.6}",
9077            spread(former_a, former_b),
9078            spread(candidate_a, candidate_b),
9079            former_mean / candidate_mean,
9080            body_started.elapsed().as_secs_f64()
9081        );
9082    }
9083
9084    #[test]
9085    fn nansem_empty_returns_null() {
9086        assert!(super::nansem(&[], 1).is_missing());
9087        assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
9088    }
9089
9090    #[test]
9091    fn nanptp_returns_max_minus_min() {
9092        let values = vec![
9093            Scalar::Float64(3.0),
9094            Scalar::Null(NullKind::NaN),
9095            Scalar::Float64(7.0),
9096            Scalar::Float64(1.0),
9097        ];
9098        assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
9099    }
9100
9101    #[test]
9102    fn nanptp_empty_returns_null() {
9103        assert!(super::nanptp(&[]).is_missing());
9104        assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
9105    }
9106
9107    #[test]
9108    fn nanptp_timedelta64_preserves_dtype_u2g0r() {
9109        // Per br-frankenpandas-u2g0r: ptp on Timedelta64 returns Timedelta64.
9110        let one_hour: i64 = 3_600 * 1_000_000_000;
9111        let values = vec![
9112            Scalar::Timedelta64(one_hour),
9113            Scalar::Timedelta64(5 * one_hour),
9114            Scalar::Timedelta64(2 * one_hour),
9115        ];
9116        assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
9117    }
9118
9119    #[test]
9120    fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
9121        // Differential vs independent max-min oracles
9122        // (br-frankenpandas-affjt). Seeded LCG, no mocks.
9123        fn next(seed: &mut u64) -> u64 {
9124            *seed = seed
9125                .wrapping_mul(3202034522624059733)
9126                .wrapping_add(4354685564936845319);
9127            *seed
9128        }
9129
9130        fn expected_numeric(values: &[Scalar]) -> Scalar {
9131            let mut lo = f64::INFINITY;
9132            let mut hi = f64::NEG_INFINITY;
9133            let mut seen = false;
9134            for value in values {
9135                if value.is_missing() {
9136                    continue;
9137                }
9138                if let Ok(value) = value.to_f64() {
9139                    seen = true;
9140                    lo = lo.min(value);
9141                    hi = hi.max(value);
9142                }
9143            }
9144            if seen {
9145                Scalar::Float64(hi - lo)
9146            } else {
9147                Scalar::Null(NullKind::NaN)
9148            }
9149        }
9150
9151        fn expected_timedelta(values: &[Scalar]) -> Scalar {
9152            let mut lo = i64::MAX;
9153            let mut hi = i64::MIN;
9154            let mut seen = false;
9155            for value in values {
9156                if let Scalar::Timedelta64(ns) = value
9157                    && !value.is_missing()
9158                {
9159                    seen = true;
9160                    lo = lo.min(*ns);
9161                    hi = hi.max(*ns);
9162                }
9163            }
9164            if seen {
9165                Scalar::Timedelta64(hi - lo)
9166            } else {
9167                Scalar::Null(NullKind::NaN)
9168            }
9169        }
9170
9171        fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
9172            let actual = super::nanptp(values);
9173            assert!(
9174                actual.semantic_eq(&expected),
9175                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
9176            );
9177        }
9178
9179        assert_ptp(
9180            usize::MAX,
9181            "numeric_all_missing",
9182            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
9183            Scalar::Null(NullKind::NaN),
9184        );
9185        assert_ptp(
9186            usize::MAX - 1,
9187            "timedelta_all_missing",
9188            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
9189            Scalar::Null(NullKind::NaN),
9190        );
9191
9192        let mut seed = 0xa22f_17ed_57a7_15e5_u64;
9193        for case in 0..260 {
9194            let len = (next(&mut seed) % 83 + 1) as usize;
9195
9196            let mut numeric = Vec::with_capacity(len);
9197            numeric.push(Scalar::Int64(case as i64 - 130));
9198            for _ in 1..len {
9199                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
9200                numeric.push(match next(&mut seed) % 9 {
9201                    0 => Scalar::Null(NullKind::Null),
9202                    1 => Scalar::Null(NullKind::NaN),
9203                    2 => Scalar::Float64(f64::NAN),
9204                    3 => Scalar::Bool(raw & 1 == 0),
9205                    4 => Scalar::Int64(raw),
9206                    5 => Scalar::Float64(raw as f64 / 53.0),
9207                    6 => Scalar::Float64(0.0),
9208                    7 => Scalar::Float64(-0.0),
9209                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
9210                });
9211            }
9212            assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
9213
9214            let mut timedeltas = Vec::with_capacity(len);
9215            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
9216            for _ in 1..len {
9217                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
9218                timedeltas.push(match next(&mut seed) % 7 {
9219                    0 => Scalar::Null(NullKind::Null),
9220                    1 => Scalar::Timedelta64(i64::MIN),
9221                    _ => Scalar::Timedelta64(raw),
9222                });
9223            }
9224            assert_ptp(
9225                case,
9226                "timedelta",
9227                &timedeltas,
9228                expected_timedelta(&timedeltas),
9229            );
9230        }
9231    }
9232
9233    #[test]
9234    fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
9235        // Per br-frankenpandas-ql1t5: argmax/argmin on Timedelta64 compare
9236        // i64 ns directly instead of silently skipping via to_f64.
9237        let one_hour: i64 = 3_600 * 1_000_000_000;
9238        let values = vec![
9239            Scalar::Timedelta64(2 * one_hour),
9240            Scalar::Timedelta64(5 * one_hour),
9241            Scalar::Timedelta64(one_hour),
9242            Scalar::Timedelta64(3 * one_hour),
9243        ];
9244        assert_eq!(super::nanargmax(&values), Some(1));
9245        assert_eq!(super::nanargmin(&values), Some(2));
9246    }
9247
9248    #[test]
9249    fn nanprod_timedelta64_returns_null_szq6a() {
9250        // Per br-frankenpandas-szq6a: pandas raises on Timedelta prod
9251        // (dimensionally undefined). We surface Null instead of the
9252        // misleading Float64(1.0) the old empty-iterator default emitted.
9253        let one_hour: i64 = 3_600 * 1_000_000_000;
9254        let values = vec![
9255            Scalar::Timedelta64(2 * one_hour),
9256            Scalar::Timedelta64(3 * one_hour),
9257        ];
9258        assert!(super::nanprod(&values).is_missing());
9259    }
9260
9261    #[test]
9262    fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
9263        // Differential vs independent product oracles
9264        // (br-frankenpandas-9938h). Seeded LCG, no mocks.
9265        fn next(seed: &mut u64) -> u64 {
9266            *seed = seed
9267                .wrapping_mul(6364136223846793005)
9268                .wrapping_add(1442695040888963407);
9269            *seed
9270        }
9271
9272        fn expected_numeric(values: &[Scalar]) -> Scalar {
9273            let mut product = 1.0_f64;
9274            for value in values {
9275                if value.is_missing() {
9276                    continue;
9277                }
9278                if let Ok(value) = value.to_f64() {
9279                    product *= value;
9280                }
9281            }
9282            Scalar::Float64(product)
9283        }
9284
9285        fn expected_timedelta(values: &[Scalar]) -> Scalar {
9286            if values
9287                .iter()
9288                .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
9289            {
9290                Scalar::Null(NullKind::NaN)
9291            } else {
9292                Scalar::Float64(1.0)
9293            }
9294        }
9295
9296        fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
9297            let actual = super::nanprod(values);
9298            assert!(
9299                actual.semantic_eq(&expected),
9300                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
9301            );
9302        }
9303
9304        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
9305        assert_prod(
9306            usize::MAX,
9307            "numeric_all_missing",
9308            &all_missing,
9309            Scalar::Float64(1.0),
9310        );
9311
9312        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
9313        assert_prod(
9314            usize::MAX - 1,
9315            "timedelta_all_missing",
9316            &td_all_missing,
9317            expected_timedelta(&td_all_missing),
9318        );
9319
9320        let mut seed = 0x6e0d_9938_a11c_0de5_u64;
9321        for case in 0..280 {
9322            let len = (next(&mut seed) % 89 + 1) as usize;
9323
9324            let mut numeric = Vec::with_capacity(len);
9325            numeric.push(Scalar::Int64((case % 17) as i64 - 8));
9326            for _ in 1..len {
9327                let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
9328                numeric.push(match next(&mut seed) % 9 {
9329                    0 => Scalar::Null(NullKind::Null),
9330                    1 => Scalar::Null(NullKind::NaN),
9331                    2 => Scalar::Float64(f64::NAN),
9332                    3 => Scalar::Bool(raw & 1 == 0),
9333                    4 => Scalar::Int64(raw % 19),
9334                    5 => Scalar::Float64(raw as f64 / 97.0),
9335                    6 => Scalar::Float64(0.0),
9336                    7 => Scalar::Float64(-0.0),
9337                    _ => Scalar::Float64(1.0),
9338                });
9339            }
9340            assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
9341
9342            let mut timedeltas = Vec::with_capacity(len);
9343            timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
9344            for _ in 1..len {
9345                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
9346                timedeltas.push(match next(&mut seed) % 7 {
9347                    0 => Scalar::Null(NullKind::Null),
9348                    1 => Scalar::Timedelta64(i64::MIN),
9349                    _ => Scalar::Timedelta64(raw),
9350                });
9351            }
9352            assert_prod(
9353                case,
9354                "timedelta",
9355                &timedeltas,
9356                expected_timedelta(&timedeltas),
9357            );
9358        }
9359    }
9360
9361    #[test]
9362    fn nanskew_symmetric_distribution_near_zero() {
9363        let values = vec![
9364            Scalar::Float64(1.0),
9365            Scalar::Float64(2.0),
9366            Scalar::Float64(3.0),
9367            Scalar::Float64(4.0),
9368            Scalar::Float64(5.0),
9369        ];
9370        // Perfectly symmetric -> skew = 0
9371        let skew = super::nanskew(&values);
9372        assert!(matches!(skew, Scalar::Float64(_)));
9373        let Scalar::Float64(v) = skew else {
9374            return;
9375        };
9376        assert!(v.abs() < 1e-9);
9377    }
9378
9379    #[test]
9380    fn nanskew_too_few_values_returns_null() {
9381        assert!(super::nanskew(&[]).is_missing());
9382        assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
9383    }
9384
9385    #[test]
9386    fn nankurt_symmetric_uniform_distribution() {
9387        let values = vec![
9388            Scalar::Float64(1.0),
9389            Scalar::Float64(2.0),
9390            Scalar::Float64(3.0),
9391            Scalar::Float64(4.0),
9392            Scalar::Float64(5.0),
9393        ];
9394        // pandas kurt([1,2,3,4,5]) = -1.2
9395        let kurt = super::nankurt(&values);
9396        assert!(matches!(kurt, Scalar::Float64(_)));
9397        let Scalar::Float64(v) = kurt else {
9398            return;
9399        };
9400        assert!((v + 1.2).abs() < 1e-9);
9401    }
9402
9403    #[test]
9404    fn nankurt_too_few_values_returns_null() {
9405        let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
9406        assert!(super::nankurt(&vals).is_missing());
9407    }
9408
9409    #[test]
9410    fn nanskew_constant_series_returns_zero() {
9411        let values = vec![
9412            Scalar::Float64(5.0),
9413            Scalar::Float64(5.0),
9414            Scalar::Float64(5.0),
9415        ];
9416        assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
9417        assert_eq!(
9418            super::nankurt(&[
9419                Scalar::Float64(5.0),
9420                Scalar::Float64(5.0),
9421                Scalar::Float64(5.0),
9422                Scalar::Float64(5.0),
9423            ]),
9424            Scalar::Float64(0.0)
9425        );
9426    }
9427
9428    #[test]
9429    fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
9430        // Differential vs independent bias-corrected moment oracles
9431        // (br-frankenpandas-jr7zk). Seeded LCG, no mocks.
9432        fn next(seed: &mut u64) -> u64 {
9433            *seed = seed
9434                .wrapping_mul(2862933555777941757)
9435                .wrapping_add(3037000493);
9436            *seed
9437        }
9438
9439        fn samples(values: &[Scalar]) -> Vec<f64> {
9440            values
9441                .iter()
9442                .filter(|value| !value.is_missing())
9443                .filter_map(|value| value.to_f64().ok())
9444                .collect()
9445        }
9446
9447        fn expected_skew(values: &[Scalar]) -> Scalar {
9448            let samples = samples(values);
9449            let n = samples.len() as f64;
9450            if n < 3.0 {
9451                return Scalar::Null(NullKind::NaN);
9452            }
9453            let mean = samples.iter().sum::<f64>() / n;
9454            let m2 = samples
9455                .iter()
9456                .map(|value| (value - mean).powi(2))
9457                .sum::<f64>();
9458            let m3 = samples
9459                .iter()
9460                .map(|value| (value - mean).powi(3))
9461                .sum::<f64>();
9462            let s2 = m2 / (n - 1.0);
9463            if s2 == 0.0 {
9464                return Scalar::Float64(0.0);
9465            }
9466            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
9467        }
9468
9469        fn expected_kurt(values: &[Scalar]) -> Scalar {
9470            let samples = samples(values);
9471            let n = samples.len() as f64;
9472            if n < 4.0 {
9473                return Scalar::Null(NullKind::NaN);
9474            }
9475            let mean = samples.iter().sum::<f64>() / n;
9476            let m2 = samples
9477                .iter()
9478                .map(|value| (value - mean).powi(2))
9479                .sum::<f64>();
9480            let m4 = samples
9481                .iter()
9482                .map(|value| (value - mean).powi(4))
9483                .sum::<f64>();
9484            let s2 = m2 / (n - 1.0);
9485            if s2 == 0.0 {
9486                return Scalar::Float64(0.0);
9487            }
9488            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
9489            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
9490            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
9491        }
9492
9493        fn assert_moments(case: usize, values: &[Scalar]) {
9494            let expected_skew = expected_skew(values);
9495            let expected_kurt = expected_kurt(values);
9496            let actual_skew = super::nanskew(values);
9497            let actual_kurt = super::nankurt(values);
9498            assert!(
9499                actual_skew.semantic_eq(&expected_skew),
9500                "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
9501            );
9502            assert!(
9503                actual_kurt.semantic_eq(&expected_kurt),
9504                "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
9505            );
9506        }
9507
9508        assert_moments(
9509            usize::MAX,
9510            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
9511        );
9512        assert_moments(
9513            usize::MAX - 1,
9514            &[
9515                Scalar::Float64(7.0),
9516                Scalar::Float64(7.0),
9517                Scalar::Float64(7.0),
9518                Scalar::Float64(7.0),
9519            ],
9520        );
9521
9522        let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
9523        for case in 0..260 {
9524            let len = (next(&mut seed) % 89 + 1) as usize;
9525            let mut values = Vec::with_capacity(len);
9526            if case % 11 == 0 {
9527                values.extend((0..len).map(|_| Scalar::Float64(3.0)));
9528            } else {
9529                values.push(Scalar::Float64(case as f64 / 19.0));
9530                for _ in 1..len {
9531                    let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
9532                    values.push(match next(&mut seed) % 8 {
9533                        0 => Scalar::Null(NullKind::Null),
9534                        1 => Scalar::Null(NullKind::NaN),
9535                        2 => Scalar::Float64(f64::NAN),
9536                        3 => Scalar::Bool(raw & 1 == 0),
9537                        4 => Scalar::Int64(raw % 251),
9538                        5 => Scalar::Float64(raw as f64 / 83.0),
9539                        6 => Scalar::Float64(0.0),
9540                        _ => Scalar::Float64(-0.0),
9541                    });
9542                }
9543            }
9544            assert_moments(case, &values);
9545        }
9546    }
9547
9548    // ── Interval tests (br-frankenpandas-j8k4) ──────────────────────────
9549
9550    #[test]
9551    fn interval_default_closed_is_right() {
9552        assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
9553    }
9554
9555    #[test]
9556    fn interval_left_and_right_closed_helpers() {
9557        assert!(IntervalClosed::Left.left_closed());
9558        assert!(!IntervalClosed::Left.right_closed());
9559        assert!(!IntervalClosed::Right.left_closed());
9560        assert!(IntervalClosed::Right.right_closed());
9561        assert!(IntervalClosed::Both.left_closed());
9562        assert!(IntervalClosed::Both.right_closed());
9563        assert!(!IntervalClosed::Neither.left_closed());
9564        assert!(!IntervalClosed::Neither.right_closed());
9565    }
9566
9567    #[test]
9568    fn interval_display_matches_pandas_notation() {
9569        assert_eq!(
9570            Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
9571            "(0.0, 5.0]"
9572        );
9573        assert_eq!(
9574            Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
9575            "[0.0, 5.0)"
9576        );
9577        assert_eq!(
9578            Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
9579            "[0.0, 5.0]"
9580        );
9581        assert_eq!(
9582            Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
9583            "(0.0, 5.0)"
9584        );
9585        assert_eq!(
9586            Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
9587            "(2.5, 3.5]"
9588        );
9589        assert_eq!(
9590            Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
9591            "(-1.0, 0.0]"
9592        );
9593        assert_eq!(
9594            Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
9595            "(1e+20, 2e+20]"
9596        );
9597    }
9598
9599    #[test]
9600    fn interval_length_and_mid() {
9601        let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
9602        assert_eq!(i.length(), 8.0);
9603        assert_eq!(i.mid(), 6.0);
9604    }
9605
9606    #[test]
9607    fn interval_contains_matches_closed_policy() {
9608        let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
9609        assert!(!right.contains(0.0));
9610        assert!(right.contains(2.5));
9611        assert!(right.contains(5.0));
9612
9613        let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
9614        assert!(left.contains(0.0));
9615        assert!(left.contains(2.5));
9616        assert!(!left.contains(5.0));
9617
9618        let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
9619        assert!(both.contains(0.0));
9620        assert!(both.contains(5.0));
9621
9622        let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
9623        assert!(!neither.contains(0.0));
9624        assert!(!neither.contains(5.0));
9625        assert!(neither.contains(2.5));
9626    }
9627
9628    #[test]
9629    fn interval_contains_nan_returns_false() {
9630        let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
9631        assert!(!i.contains(f64::NAN));
9632    }
9633
9634    #[test]
9635    fn interval_is_empty_matches_pandas() {
9636        // pd.Interval(3, 3, 'right').is_empty → True
9637        assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
9638        assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
9639        assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
9640        // pd.Interval(3, 3, 'both').is_empty → False (single point)
9641        assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
9642        // Non-degenerate intervals are never empty.
9643        assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
9644    }
9645
9646    #[test]
9647    fn interval_overlaps_disjoint_returns_false() {
9648        let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
9649        let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
9650        assert!(!a.overlaps(&b));
9651        assert!(!b.overlaps(&a));
9652    }
9653
9654    #[test]
9655    fn interval_overlaps_nested_returns_true() {
9656        let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
9657        let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
9658        assert!(outer.overlaps(&inner));
9659        assert!(inner.overlaps(&outer));
9660    }
9661
9662    #[test]
9663    fn interval_overlaps_touching_respects_closed_policy() {
9664        // (0, 1] touching (1, 2] at point 1.
9665        let right_right = (
9666            Interval::new(0.0, 1.0, IntervalClosed::Right),
9667            Interval::new(1.0, 2.0, IntervalClosed::Right),
9668        );
9669        // right_right.0 is closed at 1; right_right.1 is open at 1 → no overlap.
9670        assert!(!right_right.0.overlaps(&right_right.1));
9671
9672        // [0, 1] touching [1, 2] — both closed at 1 → overlap.
9673        let both_both = (
9674            Interval::new(0.0, 1.0, IntervalClosed::Both),
9675            Interval::new(1.0, 2.0, IntervalClosed::Both),
9676        );
9677        assert!(both_both.0.overlaps(&both_both.1));
9678    }
9679
9680    #[test]
9681    fn interval_roundtrips_through_serde_json() {
9682        let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
9683        let json = serde_json::to_string(&i).expect("serialize");
9684        let back: Interval = serde_json::from_str(&json).expect("deserialize");
9685        assert_eq!(i, back);
9686    }
9687
9688    #[test]
9689    fn interval_serde_default_closed_is_right_when_missing() {
9690        // JSON payloads that omit `closed` deserialize with the pandas default.
9691        let back: Interval =
9692            serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
9693        assert_eq!(back.closed, IntervalClosed::Right);
9694    }
9695
9696    // ── Period tests (br-frankenpandas-epoj) ────────────────────────────
9697
9698    #[test]
9699    fn period_freq_parses_canonical_aliases() {
9700        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::Annual));
9701        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::Annual));
9702        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::Quarterly));
9703        assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
9704        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::Weekly));
9705        assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
9706        assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
9707        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
9708        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
9709        assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
9710        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
9711    }
9712
9713    #[test]
9714    fn period_freq_parse_is_case_insensitive() {
9715        assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::Quarterly));
9716        assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
9717    }
9718
9719    #[test]
9720    fn period_freq_rejects_unknown_aliases() {
9721        assert_eq!(PeriodFreq::parse("nanosec"), None);
9722        assert_eq!(PeriodFreq::parse(""), None);
9723        assert_eq!(PeriodFreq::parse("xyz"), None);
9724    }
9725
9726    #[test]
9727    fn period_freq_alias_roundtrip() {
9728        for freq in [
9729            PeriodFreq::Annual,
9730            PeriodFreq::Quarterly,
9731            PeriodFreq::Monthly,
9732            PeriodFreq::Weekly,
9733            PeriodFreq::Daily,
9734            PeriodFreq::Business,
9735            PeriodFreq::Hourly,
9736            PeriodFreq::Minutely,
9737            PeriodFreq::Secondly,
9738        ] {
9739            assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
9740        }
9741    }
9742
9743    #[test]
9744    fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
9745        assert_eq!(PeriodFreq::Annual.alias(), "Y-DEC");
9746        assert_eq!(PeriodFreq::Quarterly.alias(), "Q-DEC");
9747        assert_eq!(PeriodFreq::Weekly.alias(), "W-SUN");
9748
9749        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::Annual));
9750        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::Annual));
9751        assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::Annual));
9752        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::Quarterly));
9753        assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::Quarterly));
9754        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::Weekly));
9755        assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::Weekly));
9756    }
9757
9758    #[test]
9759    fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
9760        assert_eq!(PeriodFreq::Hourly.alias(), "h");
9761        assert_eq!(PeriodFreq::Minutely.alias(), "min");
9762        assert_eq!(PeriodFreq::Secondly.alias(), "s");
9763
9764        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
9765        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
9766        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
9767    }
9768
9769    #[test]
9770    fn period_scalar_accessors_match_pandas_star8() {
9771        let period = Period::new(600, PeriodFreq::Monthly);
9772
9773        assert_eq!(period.ordinal(), 600);
9774        assert_eq!(period.freq(), PeriodFreq::Monthly);
9775        assert_eq!(period.freqstr(), "M");
9776    }
9777
9778    #[test]
9779    fn period_parse_common_pandas_ordinals_avm08() {
9780        assert_eq!(
9781            Period::parse("2024").unwrap(),
9782            Period::new(54, PeriodFreq::Annual)
9783        );
9784        assert_eq!(
9785            Period::parse("2024Q1").unwrap(),
9786            Period::new(216, PeriodFreq::Quarterly)
9787        );
9788        assert_eq!(
9789            Period::parse("2024-01").unwrap(),
9790            Period::new(648, PeriodFreq::Monthly)
9791        );
9792        assert_eq!(
9793            Period::parse("2024-01-15").unwrap(),
9794            Period::new(19_737, PeriodFreq::Daily)
9795        );
9796        assert!(Period::parse("216").is_err());
9797    }
9798
9799    #[test]
9800    fn period_shift_advances_ordinal() {
9801        let q1 = Period::new(216, PeriodFreq::Quarterly);
9802        let q2 = q1.shift(1);
9803        assert_eq!(q2.ordinal, 217);
9804        assert_eq!(q2.freq, PeriodFreq::Quarterly);
9805        let q0 = q1.shift(-1);
9806        assert_eq!(q0.ordinal, 215);
9807    }
9808
9809    #[test]
9810    fn period_shift_saturates_on_overflow() {
9811        let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
9812        assert_eq!(p.shift(100).ordinal, i64::MAX);
9813        let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
9814        assert_eq!(p.shift(-100).ordinal, i64::MIN);
9815    }
9816
9817    #[test]
9818    fn period_diff_returns_period_count() {
9819        let a = Period::new(216, PeriodFreq::Quarterly);
9820        let b = Period::new(220, PeriodFreq::Quarterly);
9821        assert_eq!(b.diff(&a), Some(4));
9822        assert_eq!(a.diff(&b), Some(-4));
9823    }
9824
9825    #[test]
9826    fn period_diff_rejects_mismatched_freq() {
9827        let monthly = Period::new(100, PeriodFreq::Monthly);
9828        let quarterly = Period::new(100, PeriodFreq::Quarterly);
9829        assert_eq!(monthly.diff(&quarterly), None);
9830        assert_eq!(quarterly.diff(&monthly), None);
9831    }
9832
9833    #[test]
9834    fn period_cmp_same_freq_respects_ordinal_order() {
9835        use std::cmp::Ordering;
9836        let a = Period::new(10, PeriodFreq::Monthly);
9837        let b = Period::new(20, PeriodFreq::Monthly);
9838        assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
9839        assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
9840        assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
9841    }
9842
9843    #[test]
9844    fn period_cmp_cross_freq_returns_none() {
9845        let m = Period::new(1, PeriodFreq::Monthly);
9846        let q = Period::new(1, PeriodFreq::Quarterly);
9847        assert_eq!(m.cmp_same_freq(&q), None);
9848    }
9849
9850    #[test]
9851    fn period_arithmetic_matches_seeded_oracles_bac28() {
9852        use std::cmp::Ordering;
9853
9854        fn next(seed: &mut u64) -> u64 {
9855            *seed = seed
9856                .wrapping_mul(2862933555777941757)
9857                .wrapping_add(3037000493);
9858            *seed
9859        }
9860
9861        fn freq_for(raw: u64) -> PeriodFreq {
9862            match raw % 9 {
9863                0 => PeriodFreq::Annual,
9864                1 => PeriodFreq::Quarterly,
9865                2 => PeriodFreq::Monthly,
9866                3 => PeriodFreq::Weekly,
9867                4 => PeriodFreq::Daily,
9868                5 => PeriodFreq::Business,
9869                6 => PeriodFreq::Hourly,
9870                7 => PeriodFreq::Minutely,
9871                _ => PeriodFreq::Secondly,
9872            }
9873        }
9874
9875        fn different_freq(freq: PeriodFreq) -> PeriodFreq {
9876            match freq {
9877                PeriodFreq::Annual => PeriodFreq::Quarterly,
9878                PeriodFreq::Quarterly => PeriodFreq::Monthly,
9879                PeriodFreq::Monthly => PeriodFreq::Weekly,
9880                PeriodFreq::Weekly => PeriodFreq::Daily,
9881                PeriodFreq::Daily => PeriodFreq::Business,
9882                PeriodFreq::Business => PeriodFreq::Hourly,
9883                PeriodFreq::Hourly => PeriodFreq::Minutely,
9884                PeriodFreq::Minutely => PeriodFreq::Secondly,
9885                PeriodFreq::Secondly => PeriodFreq::Annual,
9886            }
9887        }
9888
9889        fn assert_period_case(
9890            case: usize,
9891            freq: PeriodFreq,
9892            ordinal: i64,
9893            shift_by: i64,
9894            other_ordinal: i64,
9895        ) {
9896            let period = Period::new(ordinal, freq);
9897            let shifted = period.shift(shift_by);
9898            assert_eq!(
9899                shifted.ordinal,
9900                ordinal.saturating_add(shift_by),
9901                "case {case}: shift ordinal"
9902            );
9903            assert_eq!(shifted.freq, freq, "case {case}: shift freq");
9904
9905            let same_freq_other = Period::new(other_ordinal, freq);
9906            assert_eq!(
9907                period.diff(&same_freq_other),
9908                Some(ordinal.saturating_sub(other_ordinal)),
9909                "case {case}: same-freq diff"
9910            );
9911            assert_eq!(
9912                period.cmp_same_freq(&same_freq_other),
9913                Some(ordinal.cmp(&other_ordinal)),
9914                "case {case}: same-freq cmp"
9915            );
9916
9917            let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
9918            assert_eq!(
9919                period.diff(&cross_freq_other),
9920                None,
9921                "case {case}: cross-freq diff"
9922            );
9923            assert_eq!(
9924                period.cmp_same_freq(&cross_freq_other),
9925                None,
9926                "case {case}: cross-freq cmp"
9927            );
9928        }
9929
9930        assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
9931        assert_period_case(
9932            usize::MAX - 1,
9933            PeriodFreq::Daily,
9934            i64::MIN + 2,
9935            -10,
9936            i64::MAX,
9937        );
9938        assert_eq!(
9939            Period::new(10, PeriodFreq::Monthly)
9940                .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
9941            Some(Ordering::Equal)
9942        );
9943
9944        let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
9945        for case in 0..260 {
9946            let freq = freq_for(next(&mut seed));
9947            let ordinal = match case % 53 {
9948                0 => i64::MAX - (next(&mut seed) % 8) as i64,
9949                1 => i64::MIN + (next(&mut seed) % 8) as i64,
9950                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
9951            };
9952            let shift_by = match case % 47 {
9953                0 => 512,
9954                1 => -512,
9955                _ => (next(&mut seed) % 4097) as i64 - 2048,
9956            };
9957            let other_ordinal = match case % 41 {
9958                0 => i64::MAX,
9959                1 => i64::MIN,
9960                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
9961            };
9962            assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
9963        }
9964    }
9965
9966    #[test]
9967    fn period_display_is_pandas_calendar_string() {
9968        // Ordinal 216 on the quarterly axis (1970Q1 == 0) is 1970 + 54y = 2024Q1.
9969        assert_eq!(
9970            Period::new(216, PeriodFreq::Quarterly).to_string(),
9971            "2024Q1"
9972        );
9973        // 1970 + 54 == 2024 on the annual axis.
9974        assert_eq!(Period::new(54, PeriodFreq::Annual).to_string(), "2024");
9975        // 1970-01 == 0 -> 2024-03 is 54*12 + 2 == 650 months.
9976        assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
9977        // Day 0 == 1970-01-01; 2024-01-15.
9978        assert_eq!(
9979            Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
9980            "2024-01-15"
9981        );
9982        assert_eq!(
9983            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
9984            "NaT"
9985        );
9986    }
9987
9988    fn period_display_former_profile(period: &Period) -> String {
9989        let calendar = period.calendar_string();
9990        let mut rendered = String::new();
9991        rendered.push_str(&calendar);
9992        rendered
9993    }
9994
9995    fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
9996        use std::{hint::black_box, time::Instant};
9997
9998        let started = Instant::now();
9999        let mut checksum = 0usize;
10000        for period in periods {
10001            let rendered = render(black_box(period));
10002            checksum = checksum.wrapping_add(rendered.len());
10003            drop(black_box(rendered));
10004        }
10005        black_box(checksum);
10006        started.elapsed().as_nanos()
10007    }
10008
10009    #[test]
10010    #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
10011    fn profile_period_display_direct_sink_ab_6pqra() {
10012        const FREQUENCIES: [PeriodFreq; 9] = [
10013            PeriodFreq::Annual,
10014            PeriodFreq::Quarterly,
10015            PeriodFreq::Monthly,
10016            PeriodFreq::Weekly,
10017            PeriodFreq::Daily,
10018            PeriodFreq::Business,
10019            PeriodFreq::Hourly,
10020            PeriodFreq::Minutely,
10021            PeriodFreq::Secondly,
10022        ];
10023        const SAMPLES: usize = 10;
10024
10025        let periods = (0..65_536)
10026            .map(|index| {
10027                let ordinal = if index % 4093 == 0 {
10028                    i64::MIN
10029                } else {
10030                    ((index as i64 * 7_919) % 4_000_001) - 2_000_000
10031                };
10032                Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
10033            })
10034            .collect::<Vec<_>>();
10035
10036        for period in &periods {
10037            assert_eq!(period_display_former_profile(period), period.to_string());
10038        }
10039
10040        for _ in 0..2 {
10041            measure_period_renderer(&periods, period_display_former_profile);
10042            measure_period_renderer(&periods, Period::to_string);
10043        }
10044
10045        let mut former_ns = Vec::with_capacity(SAMPLES);
10046        let mut public_ns = Vec::with_capacity(SAMPLES);
10047        for sample in 0..SAMPLES {
10048            if sample % 2 == 0 {
10049                former_ns.push(measure_period_renderer(
10050                    &periods,
10051                    period_display_former_profile,
10052                ));
10053                public_ns.push(measure_period_renderer(&periods, Period::to_string));
10054            } else {
10055                public_ns.push(measure_period_renderer(&periods, Period::to_string));
10056                former_ns.push(measure_period_renderer(
10057                    &periods,
10058                    period_display_former_profile,
10059                ));
10060            }
10061        }
10062        former_ns.sort_unstable();
10063        public_ns.sort_unstable();
10064        let former_p50 = former_ns[SAMPLES / 2];
10065        let public_p50 = public_ns[SAMPLES / 2];
10066        let former_p95 = former_ns[SAMPLES - 1];
10067        let public_p95 = public_ns[SAMPLES - 1];
10068        println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
10069        println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
10070        println!(
10071            "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
10072            former_p50 as f64 / public_p50 as f64
10073        );
10074        println!(
10075            "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
10076            former_p95 as f64 / public_p95 as f64
10077        );
10078    }
10079
10080    #[cfg(test)]
10081    fn fp_days(ymd: &str) -> i64 {
10082        Period::parse(ymd).expect("daily period").ordinal
10083    }
10084
10085    #[test]
10086    fn period_roundtrips_through_serde_json() {
10087        let p = Period::new(42, PeriodFreq::Weekly);
10088        let json = serde_json::to_string(&p).expect("serialize");
10089        let back: Period = serde_json::from_str(&json).expect("deserialize");
10090        assert_eq!(p, back);
10091    }
10092
10093    // ── period_range tests (br-frankenpandas-2jef — epoj Phase 2) ───────
10094
10095    use super::period_range;
10096
10097    #[test]
10098    fn period_range_zero_periods_is_empty() {
10099        let start = Period::new(216, PeriodFreq::Quarterly);
10100        assert!(period_range(start, 0).is_empty());
10101    }
10102
10103    #[test]
10104    fn period_range_single_period_returns_start_only() {
10105        let start = Period::new(216, PeriodFreq::Quarterly);
10106        let r = period_range(start, 1);
10107        assert_eq!(r.len(), 1);
10108        assert_eq!(r[0], start);
10109    }
10110
10111    #[test]
10112    fn period_range_increments_ordinal_by_one_per_step() {
10113        let start = Period::new(216, PeriodFreq::Quarterly);
10114        let r = period_range(start, 4);
10115        assert_eq!(r.len(), 4);
10116        assert_eq!(r[0].ordinal, 216);
10117        assert_eq!(r[1].ordinal, 217);
10118        assert_eq!(r[2].ordinal, 218);
10119        assert_eq!(r[3].ordinal, 219);
10120    }
10121
10122    #[test]
10123    fn period_range_preserves_frequency() {
10124        let start = Period::new(0, PeriodFreq::Monthly);
10125        let r = period_range(start, 12);
10126        assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
10127    }
10128
10129    #[test]
10130    fn period_range_negative_starting_ordinal_works() {
10131        // Ordinal axis is signed — pre-epoch periods are valid.
10132        let start = Period::new(-3, PeriodFreq::Annual);
10133        let r = period_range(start, 5);
10134        assert_eq!(
10135            r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
10136            vec![-3, -2, -1, 0, 1]
10137        );
10138    }
10139
10140    #[test]
10141    fn period_range_large_n_does_not_panic() {
10142        // 1024 monthly periods — large enough to catch any allocation bug.
10143        let start = Period::new(0, PeriodFreq::Monthly);
10144        let r = period_range(start, 1024);
10145        assert_eq!(r.len(), 1024);
10146        assert_eq!(r[1023].ordinal, 1023);
10147    }
10148
10149    #[test]
10150    fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
10151        fn next(seed: &mut u64) -> u64 {
10152            *seed = seed
10153                .wrapping_mul(6364136223846793005)
10154                .wrapping_add(1442695040888963407);
10155            *seed
10156        }
10157
10158        fn freq_for(raw: u64) -> PeriodFreq {
10159            match raw % 9 {
10160                0 => PeriodFreq::Annual,
10161                1 => PeriodFreq::Quarterly,
10162                2 => PeriodFreq::Monthly,
10163                3 => PeriodFreq::Weekly,
10164                4 => PeriodFreq::Daily,
10165                5 => PeriodFreq::Business,
10166                6 => PeriodFreq::Hourly,
10167                7 => PeriodFreq::Minutely,
10168                _ => PeriodFreq::Secondly,
10169            }
10170        }
10171
10172        fn assert_oracle_case(case: usize, start: Period, periods: usize) {
10173            let got = period_range(start, periods);
10174            assert_eq!(got.len(), periods, "case {case}: length");
10175
10176            for (position, period) in got.iter().enumerate() {
10177                let expected_ordinal = start.ordinal.saturating_add(position as i64);
10178                assert_eq!(
10179                    period.ordinal, expected_ordinal,
10180                    "case {case}: ordinal at {position}"
10181                );
10182                assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
10183            }
10184        }
10185
10186        assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
10187        assert_oracle_case(
10188            usize::MAX - 1,
10189            Period::new(i64::MAX - 3, PeriodFreq::Daily),
10190            8,
10191        );
10192
10193        let mut seed = 0x9e21_0d1c_5eed_0421_u64;
10194        for case in 0..260 {
10195            let freq = freq_for(next(&mut seed));
10196            let periods = (next(&mut seed) % 80) as usize;
10197            let start_ordinal = if case % 37 == 0 {
10198                i64::MAX - 7
10199            } else {
10200                (next(&mut seed) % 20_001) as i64 - 10_000
10201            };
10202            assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
10203        }
10204    }
10205
10206    // ── interval_range tests (br-frankenpandas-xaom) ────────────────────
10207
10208    use super::{TypeError, interval_range_by_periods, interval_range_by_step};
10209
10210    #[test]
10211    fn interval_range_by_periods_matches_pandas_default_case() {
10212        // pd.interval_range(0, 10, periods=5) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
10213        let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
10214        assert_eq!(bins.len(), 5);
10215        for (i, bin) in bins.iter().enumerate() {
10216            assert_eq!(bin.left, (i as f64) * 2.0);
10217            assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
10218            assert_eq!(bin.closed, IntervalClosed::Right);
10219        }
10220    }
10221
10222    #[test]
10223    fn interval_range_by_periods_final_edge_is_exact_end() {
10224        // Guards against accumulated float drift on the last right edge.
10225        let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
10226        assert_eq!(bins.last().unwrap().right, 1.0);
10227    }
10228
10229    #[test]
10230    fn interval_range_by_periods_zero_periods_is_empty() {
10231        assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
10232    }
10233
10234    #[test]
10235    fn interval_range_by_periods_reversed_range_is_empty() {
10236        // pandas: pd.interval_range(10, 0, periods=5) → IntervalIndex([]).
10237        assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
10238    }
10239
10240    #[test]
10241    fn interval_range_by_periods_preserves_closed_policy() {
10242        for closed in [
10243            IntervalClosed::Left,
10244            IntervalClosed::Right,
10245            IntervalClosed::Both,
10246            IntervalClosed::Neither,
10247        ] {
10248            let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
10249            assert!(bins.iter().all(|b| b.closed == closed));
10250        }
10251    }
10252
10253    #[test]
10254    fn interval_range_by_step_matches_pandas_default_case() {
10255        // pd.interval_range(0, 10, freq=2) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
10256        let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
10257        assert_eq!(bins.len(), 5);
10258        assert_eq!(bins[0].left, 0.0);
10259        assert_eq!(bins[4].right, 10.0);
10260    }
10261
10262    #[test]
10263    fn interval_range_by_step_rejects_non_positive_step() {
10264        assert!(matches!(
10265            interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
10266            Err(TypeError::InvalidIntervalStep { .. })
10267        ));
10268        assert!(matches!(
10269            interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
10270            Err(TypeError::InvalidIntervalStep { .. })
10271        ));
10272        assert!(matches!(
10273            interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
10274            Err(TypeError::InvalidIntervalStep { .. })
10275        ));
10276        assert!(matches!(
10277            interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
10278            Err(TypeError::InvalidIntervalStep { .. })
10279        ));
10280    }
10281
10282    #[test]
10283    fn interval_range_by_step_rejects_non_dividing_step() {
10284        // pandas: pd.interval_range(0, 10, freq=3) → ValueError
10285        // (span=10 not divisible by step=3). Reject with IntervalStepDoesNotDivide.
10286        assert!(matches!(
10287            interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
10288            Err(TypeError::IntervalStepDoesNotDivide { .. })
10289        ));
10290    }
10291
10292    #[test]
10293    fn interval_range_by_step_reversed_range_is_empty() {
10294        let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
10295        assert!(bins.is_empty());
10296    }
10297
10298    #[test]
10299    fn interval_range_by_step_degenerate_zero_span_is_empty() {
10300        let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
10301        assert!(bins.is_empty());
10302    }
10303
10304    #[test]
10305    fn interval_range_by_step_accepts_float_step_within_tolerance() {
10306        // step=0.1 ten times == 1.0 but float arithmetic produces 0.9999...
10307        let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
10308        assert_eq!(bins.len(), 10);
10309        assert_eq!(bins.last().unwrap().right, 1.0);
10310    }
10311
10312    #[test]
10313    fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
10314        // Differential vs independent interval edge oracles
10315        // (br-frankenpandas-t9ozf). Seeded LCG, no mocks.
10316        fn next(seed: &mut u64) -> u64 {
10317            *seed = seed
10318                .wrapping_mul(2862933555777941757)
10319                .wrapping_add(3037000493);
10320            *seed
10321        }
10322
10323        fn closed_for(raw: u64) -> IntervalClosed {
10324            match raw % 4 {
10325                0 => IntervalClosed::Left,
10326                1 => IntervalClosed::Right,
10327                2 => IntervalClosed::Both,
10328                _ => IntervalClosed::Neither,
10329            }
10330        }
10331
10332        fn assert_interval(
10333            case: usize,
10334            kind: &str,
10335            pos: usize,
10336            actual: &Interval,
10337            expected: &Interval,
10338        ) {
10339            assert!(
10340                (actual.left - expected.left).abs() < 1e-12,
10341                "case={case} kind={kind} pos={pos}: expected left {}, got {}",
10342                expected.left,
10343                actual.left
10344            );
10345            assert!(
10346                (actual.right - expected.right).abs() < 1e-12,
10347                "case={case} kind={kind} pos={pos}: expected right {}, got {}",
10348                expected.right,
10349                actual.right
10350            );
10351            assert_eq!(
10352                actual.closed, expected.closed,
10353                "case={case} kind={kind} pos={pos}: closed mismatch"
10354            );
10355        }
10356
10357        fn expected_by_periods(
10358            start: f64,
10359            end: f64,
10360            periods: usize,
10361            closed: IntervalClosed,
10362        ) -> Vec<Interval> {
10363            if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
10364                return Vec::new();
10365            }
10366            let step = (end - start) / periods as f64;
10367            (0..periods)
10368                .map(|pos| {
10369                    let left = start + step * pos as f64;
10370                    let right = if pos + 1 == periods {
10371                        end
10372                    } else {
10373                        start + step * (pos + 1) as f64
10374                    };
10375                    Interval::new(left, right, closed)
10376                })
10377                .collect()
10378        }
10379
10380        fn expected_by_step(
10381            start: f64,
10382            end: f64,
10383            step: f64,
10384            closed: IntervalClosed,
10385        ) -> Vec<Interval> {
10386            if start >= end {
10387                return Vec::new();
10388            }
10389            let count = ((end - start) / step).round() as usize;
10390            (0..count)
10391                .map(|pos| {
10392                    let left = start + step * pos as f64;
10393                    let right = if pos + 1 == count {
10394                        end
10395                    } else {
10396                        start + step * (pos + 1) as f64
10397                    };
10398                    Interval::new(left, right, closed)
10399                })
10400                .collect()
10401        }
10402
10403        assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
10404        assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
10405        assert!(
10406            interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
10407                .expect("zero span")
10408                .is_empty()
10409        );
10410
10411        let mut seed = 0x171e_7a11_c0de_5eed_u64;
10412        for case in 0..220 {
10413            let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
10414            let periods = (next(&mut seed) % 24 + 1) as usize;
10415            let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
10416            let end = start + width;
10417            let closed = closed_for(next(&mut seed));
10418
10419            let actual = interval_range_by_periods(start, end, periods, closed);
10420            let expected = expected_by_periods(start, end, periods, closed);
10421            assert_eq!(
10422                actual.len(),
10423                expected.len(),
10424                "case={case} periods: length mismatch"
10425            );
10426            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
10427                assert_interval(case, "periods", pos, actual, expected);
10428            }
10429
10430            let step_count = (next(&mut seed) % 20 + 1) as usize;
10431            let step = (next(&mut seed) % 25 + 1) as f64;
10432            let step_end = start + step * step_count as f64;
10433            let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
10434            let expected = expected_by_step(start, step_end, step, closed);
10435            assert_eq!(
10436                actual.len(),
10437                expected.len(),
10438                "case={case} step: length mismatch"
10439            );
10440            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
10441                assert_interval(case, "step", pos, actual, expected);
10442            }
10443        }
10444    }
10445
10446    // ── Timedelta arithmetic tests (br-frankenpandas-4r56 Phase 1) ──────
10447
10448    use super::Timedelta;
10449
10450    #[test]
10451    fn timedelta_add_sums_non_nat() {
10452        let one_hour = Timedelta::NANOS_PER_HOUR;
10453        let one_day = Timedelta::NANOS_PER_DAY;
10454        assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
10455    }
10456
10457    #[test]
10458    fn timedelta_add_propagates_nat() {
10459        assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
10460        assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
10461        assert_eq!(
10462            Timedelta::add(Timedelta::NAT, Timedelta::NAT),
10463            Timedelta::NAT
10464        );
10465    }
10466
10467    #[test]
10468    fn timedelta_add_saturates_on_overflow() {
10469        assert_eq!(Timedelta::add(i64::MAX - 10, 100), i64::MAX);
10470        // Note: i64::MIN is NaT; use MIN+1 to test saturation on the negative side.
10471        assert_eq!(Timedelta::add(i64::MIN + 10, -100), i64::MIN);
10472    }
10473
10474    #[test]
10475    fn timedelta_sub_subtracts_non_nat() {
10476        let one_hour = Timedelta::NANOS_PER_HOUR;
10477        assert_eq!(
10478            Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
10479            one_hour - Timedelta::NANOS_PER_MIN
10480        );
10481    }
10482
10483    #[test]
10484    fn timedelta_sub_propagates_nat() {
10485        assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
10486        assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
10487    }
10488
10489    #[test]
10490    fn timedelta_neg_flips_sign_non_nat() {
10491        assert_eq!(Timedelta::neg(5), -5);
10492        assert_eq!(Timedelta::neg(-5), 5);
10493        assert_eq!(Timedelta::neg(0), 0);
10494    }
10495
10496    #[test]
10497    fn timedelta_neg_preserves_nat() {
10498        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
10499    }
10500
10501    #[test]
10502    fn timedelta_abs_returns_magnitude() {
10503        assert_eq!(Timedelta::abs(-5), 5);
10504        assert_eq!(Timedelta::abs(5), 5);
10505        assert_eq!(Timedelta::abs(0), 0);
10506        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
10507    }
10508
10509    #[test]
10510    fn timedelta_mul_scalar_scales() {
10511        let three_hours = Timedelta::NANOS_PER_HOUR * 3;
10512        assert_eq!(
10513            Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
10514            three_hours
10515        );
10516        assert_eq!(Timedelta::mul_scalar(100, 0), 0);
10517        assert_eq!(Timedelta::mul_scalar(100, -2), -200);
10518    }
10519
10520    #[test]
10521    fn timedelta_mul_scalar_saturates() {
10522        assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), i64::MAX);
10523        // (i64::MIN + 1) * 2 saturates to i64::MIN (magnitude too large).
10524        assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), i64::MIN);
10525    }
10526
10527    #[test]
10528    fn timedelta_mul_scalar_propagates_nat() {
10529        assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
10530    }
10531
10532    #[test]
10533    fn timedelta_div_scalar_floor_divides() {
10534        // Floor division (matches Python / pandas): -100 // 3 == -34, not -33.
10535        assert_eq!(Timedelta::div_scalar(100, 3), 33);
10536        assert_eq!(Timedelta::div_scalar(-100, 3), -34);
10537        assert_eq!(Timedelta::div_scalar(100, -3), -34);
10538        assert_eq!(Timedelta::div_scalar(-100, -3), 33);
10539    }
10540
10541    #[test]
10542    fn timedelta_div_scalar_zero_divisor_returns_nat() {
10543        assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
10544    }
10545
10546    #[test]
10547    fn timedelta_div_scalar_min_neg_one_propagates_nat() {
10548        // i64::MIN aliases NaT, so `div_scalar(i64::MIN, _)` propagates NaT
10549        // — the `i64::MIN / -1` arithmetic-overflow case is subsumed.
10550        assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
10551        // (i64::MIN + 1) is a real timedelta; `/ -1` does not overflow.
10552        assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
10553    }
10554
10555    #[test]
10556    fn timedelta_div_scalar_propagates_nat() {
10557        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
10558    }
10559
10560    #[test]
10561    fn timedelta_div_timedelta_returns_float_ratio() {
10562        let two_hours = Timedelta::NANOS_PER_HOUR * 2;
10563        let one_hour = Timedelta::NANOS_PER_HOUR;
10564        assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
10565        assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
10566    }
10567
10568    #[test]
10569    fn timedelta_div_timedelta_nat_returns_nan() {
10570        assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
10571        assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
10572    }
10573
10574    // ── Timestamp tests (br-frankenpandas-9p0u — 4r56 Phase 2) ──────────
10575
10576    use super::Timestamp;
10577
10578    #[test]
10579    fn timestamp_from_nanos_is_naive_utc() {
10580        let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
10581        assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
10582        assert_eq!(ts.tz, None);
10583        assert!(!ts.is_nat());
10584    }
10585
10586    #[test]
10587    fn timestamp_from_nanos_tz_carries_tz_name() {
10588        let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
10589        assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
10590    }
10591
10592    #[test]
10593    fn timestamp_now_returns_current_time() {
10594        let before = std::time::SystemTime::now()
10595            .duration_since(std::time::UNIX_EPOCH)
10596            .unwrap()
10597            .as_nanos() as i64;
10598        let ts = Timestamp::now();
10599        let after = std::time::SystemTime::now()
10600            .duration_since(std::time::UNIX_EPOCH)
10601            .unwrap()
10602            .as_nanos() as i64;
10603        assert!(ts.nanos >= before);
10604        assert!(ts.nanos <= after);
10605        assert!(!ts.is_nat());
10606    }
10607
10608    #[test]
10609    fn timestamp_today_returns_midnight() {
10610        let ts = Timestamp::today();
10611        assert!(!ts.is_nat());
10612        // Today should be normalized (midnight), so hour/min/sec should be 0
10613        assert_eq!(ts.hour(), Some(0));
10614        assert_eq!(ts.minute(), Some(0));
10615        assert_eq!(ts.second(), Some(0));
10616    }
10617
10618    #[test]
10619    fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
10620        let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
10621        let one_day = Timedelta::NANOS_PER_DAY;
10622        let shifted = ts.add_timedelta(one_day);
10623        assert_eq!(shifted.nanos, one_day);
10624        assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
10625    }
10626
10627    #[test]
10628    fn timestamp_add_timedelta_saturates_on_overflow() {
10629        let ts = Timestamp::from_nanos(i64::MAX - 10);
10630        let shifted = ts.add_timedelta(100);
10631        assert_eq!(shifted.nanos, i64::MAX);
10632    }
10633
10634    #[test]
10635    fn timestamp_add_timedelta_propagates_nat() {
10636        // NaT Timestamp + anything = NaT.
10637        assert!(Timestamp::nat().add_timedelta(100).is_nat());
10638        // Timestamp + NaT Timedelta = NaT.
10639        assert!(
10640            Timestamp::from_nanos(0)
10641                .add_timedelta(Timedelta::NAT)
10642                .is_nat()
10643        );
10644    }
10645
10646    #[test]
10647    fn timestamp_sub_timedelta_shifts_backward() {
10648        let ts = Timestamp::from_nanos(1_000);
10649        let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
10650        assert_eq!(shifted.nanos, 0);
10651    }
10652
10653    #[test]
10654    fn timestamp_sub_timestamp_returns_timedelta_nanos() {
10655        let t0 = Timestamp::from_nanos(0);
10656        let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
10657        assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
10658        assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
10659    }
10660
10661    #[test]
10662    fn timestamp_sub_timestamp_nat_propagates() {
10663        let ts = Timestamp::from_nanos(1_000);
10664        assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
10665        assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
10666    }
10667
10668    #[test]
10669    fn timestamp_semantic_eq_treats_two_nat_as_equal() {
10670        assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
10671        assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
10672        assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
10673    }
10674
10675    #[test]
10676    fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
10677        use std::cmp::Ordering;
10678        let a = Timestamp::from_nanos(0);
10679        let b = Timestamp::from_nanos(100);
10680        assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
10681        assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
10682        assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
10683        assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
10684        assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
10685    }
10686
10687    #[test]
10688    fn timestamp_display_matches_phase2_debug_format() {
10689        assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
10690        assert_eq!(
10691            Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
10692            "Timestamp[42, US/Eastern]"
10693        );
10694        assert_eq!(Timestamp::nat().to_string(), "NaT");
10695    }
10696
10697    #[test]
10698    fn timestamp_value_and_unit_match_pandas_l0edr() {
10699        let ts = Timestamp::from_nanos(1_000_000_123);
10700        assert_eq!(ts.value(), 1_000_000_123);
10701        assert_eq!(ts.unit(), Some("ns"));
10702
10703        let nat = Timestamp::nat();
10704        assert_eq!(nat.value(), Timestamp::NAT);
10705        assert_eq!(nat.unit(), None);
10706    }
10707
10708    #[test]
10709    fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
10710        let ts = Timestamp::from_nanos(1_000_000_123);
10711        assert_eq!(ts.asm8(), ts.value());
10712        assert_eq!(ts.to_datetime64(), ts.value());
10713        assert_eq!(ts.to_numpy(), ts.value());
10714
10715        let nat = Timestamp::nat();
10716        assert_eq!(nat.asm8(), Timestamp::NAT);
10717        assert_eq!(nat.to_datetime64(), Timestamp::NAT);
10718        assert_eq!(nat.to_numpy(), Timestamp::NAT);
10719    }
10720
10721    #[test]
10722    fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
10723        assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
10724        assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
10725        assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
10726        assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
10727        assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
10728
10729        assert!(matches!(
10730            Timestamp::from_nanos(-500).timestamp(),
10731            Ok(value) if value == -0.0 && value.is_sign_negative()
10732        ));
10733        assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
10734        assert_eq!(
10735            Timestamp::nat().timestamp(),
10736            Err(TypeError::ValueIsMissing {
10737                kind: NullKind::NaT,
10738            })
10739        );
10740    }
10741
10742    #[test]
10743    fn timestamp_roundtrips_through_serde_json() {
10744        let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
10745        let json = serde_json::to_string(&naive).expect("serialize");
10746        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
10747        assert_eq!(naive, back);
10748
10749        let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
10750        let json = serde_json::to_string(&tz_aware).expect("serialize");
10751        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
10752        assert_eq!(tz_aware, back);
10753    }
10754
10755    #[test]
10756    fn timestamp_is_send_and_sync() {
10757        fn assert_send_sync<T: Send + Sync>() {}
10758        assert_send_sync::<Timestamp>();
10759    }
10760
10761    // ── Timestamp rounding tests (br-frankenpandas-5h6n) ────────────────
10762
10763    #[test]
10764    fn timestamp_pre_epoch_accessors_floor_not_truncate() {
10765        // br-frankenpandas-wkjtw: pre-1970 instants with a sub-day part used to
10766        // truncate toward zero, landing on the wrong calendar day. -1 ns is
10767        // 1969-12-31 23:59:59.999999999 UTC.
10768        let ts = Timestamp::from_nanos(-1);
10769        assert_eq!(ts.year(), Some(1969));
10770        assert_eq!(ts.month(), Some(12));
10771        assert_eq!(ts.day(), Some(31));
10772        assert_eq!(ts.hour(), Some(23));
10773        assert_eq!(ts.minute(), Some(59));
10774        assert_eq!(ts.second(), Some(59));
10775        assert_eq!(ts.microsecond(), Some(999_999));
10776        assert_eq!(ts.nanosecond(), Some(999));
10777        // 1969-12-31 is a Wednesday (pandas Monday=0 -> 2).
10778        assert_eq!(ts.dayofweek(), Some(2));
10779
10780        // 1969-12-31 12:00:00 — the classic truncation case (-43200 s).
10781        let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
10782        assert_eq!(noon.year(), Some(1969));
10783        assert_eq!(noon.month(), Some(12));
10784        assert_eq!(noon.day(), Some(31));
10785        assert_eq!(noon.hour(), Some(12));
10786
10787        // Exact midnight pre-epoch was already correct; keep it green.
10788        let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
10789        assert_eq!(midnight.year(), Some(1969));
10790        assert_eq!(midnight.day(), Some(31));
10791        assert_eq!(midnight.hour(), Some(0));
10792    }
10793
10794    #[test]
10795    fn timestamp_floor_to_rounds_down() {
10796        // 12:34:56 → floor by 1H → 12:00:00
10797        let h = Timedelta::NANOS_PER_HOUR;
10798        let twelve_h = h * 12;
10799        let twelve_thirty_four =
10800            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
10801        let ts = Timestamp::from_nanos(twelve_thirty_four);
10802        let floored = ts.floor_to(h);
10803        assert_eq!(floored.nanos, twelve_h);
10804    }
10805
10806    #[test]
10807    fn timestamp_floor_to_handles_already_aligned() {
10808        // 12:00:00 floored by 1H → 12:00:00 (no change).
10809        let h = Timedelta::NANOS_PER_HOUR;
10810        let twelve_h = h * 12;
10811        let ts = Timestamp::from_nanos(twelve_h);
10812        assert_eq!(ts.floor_to(h).nanos, twelve_h);
10813    }
10814
10815    #[test]
10816    fn timestamp_floor_to_handles_negative_nanos() {
10817        // -100 ns floored by 60 ns:
10818        //   div_euclid(-100, 60) = -2 (since -2*60=-120, rem=20 ≥ 0).
10819        //   result = -2 * 60 = -120.
10820        let ts = Timestamp::from_nanos(-100);
10821        assert_eq!(ts.floor_to(60).nanos, -120);
10822    }
10823
10824    #[test]
10825    fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
10826        let ts = Timestamp::from_nanos(i64::MIN + 1);
10827        assert!(ts.floor_to(10).is_nat());
10828
10829        let safe = Timestamp::from_nanos(i64::MIN + 10);
10830        assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
10831
10832        let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
10833        assert_eq!(tz.nanos, -120);
10834        assert_eq!(tz.tz.as_deref(), Some("UTC"));
10835    }
10836
10837    #[test]
10838    fn timestamp_ceil_to_rounds_up() {
10839        // 12:34:56 → ceil by 1H → 13:00:00.
10840        let h = Timedelta::NANOS_PER_HOUR;
10841        let twelve_h = h * 12;
10842        let thirteen_h = h * 13;
10843        let twelve_thirty_four =
10844            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
10845        let ts = Timestamp::from_nanos(twelve_thirty_four);
10846        assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
10847    }
10848
10849    #[test]
10850    fn timestamp_ceil_to_no_op_on_aligned() {
10851        let h = Timedelta::NANOS_PER_HOUR;
10852        let twelve_h = h * 12;
10853        let ts = Timestamp::from_nanos(twelve_h);
10854        assert_eq!(ts.ceil_to(h).nanos, twelve_h);
10855    }
10856
10857    #[test]
10858    fn timestamp_round_to_rounds_to_nearest() {
10859        // 12:30:01 (one second past the half-hour): round to 1H → 13:00:00.
10860        let h = Timedelta::NANOS_PER_HOUR;
10861        let twelve_h = h * 12;
10862        let twelve_thirty_one_sec =
10863            twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
10864        let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
10865        assert_eq!(ts.round_to(h).nanos, h * 13);
10866
10867        // 12:29:59 (one second before half): round to 1H → 12:00:00.
10868        let twelve_twenty_nine_sec =
10869            twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
10870        let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
10871        assert_eq!(ts.round_to(h).nanos, twelve_h);
10872    }
10873
10874    #[test]
10875    fn timestamp_round_to_bankers_tie_to_even() {
10876        // Tie cases: rem == unit/2 exactly. Pick even-multiple floor.
10877        // unit=10, so half=5. nanos=5: floor=0 (even), so → 0.
10878        // nanos=15: floor=1 (odd), so → 20.
10879        // nanos=25: floor=2 (even), so → 20.
10880        // nanos=35: floor=3 (odd), so → 40.
10881        assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
10882        assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
10883        assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
10884        assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
10885    }
10886
10887    #[test]
10888    fn timestamp_round_to_zero_unit_returns_nat() {
10889        let ts = Timestamp::from_nanos(100);
10890        assert!(ts.round_to(0).is_nat());
10891        assert!(ts.floor_to(0).is_nat());
10892        assert!(ts.ceil_to(0).is_nat());
10893    }
10894
10895    #[test]
10896    fn timestamp_round_to_negative_unit_returns_nat() {
10897        let ts = Timestamp::from_nanos(100);
10898        assert!(ts.round_to(-10).is_nat());
10899        assert!(ts.floor_to(-10).is_nat());
10900        assert!(ts.ceil_to(-10).is_nat());
10901    }
10902
10903    #[test]
10904    fn timestamp_rounding_propagates_nat() {
10905        let nat = Timestamp::nat();
10906        assert!(nat.floor_to(60).is_nat());
10907        assert!(nat.ceil_to(60).is_nat());
10908        assert!(nat.round_to(60).is_nat());
10909    }
10910
10911    #[test]
10912    fn timestamp_rounding_preserves_tz() {
10913        let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
10914        assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
10915        assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
10916        assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
10917    }
10918
10919    // ── Timestamp string-unit rounding tests (br-frankenpandas-lbsx) ────
10920
10921    #[test]
10922    fn timestamp_floor_to_unit_h_rounds_to_hour() {
10923        let h = Timedelta::NANOS_PER_HOUR;
10924        let twelve_h = h * 12;
10925        let twelve_thirty_four =
10926            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
10927        let ts = Timestamp::from_nanos(twelve_thirty_four);
10928        assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
10929        assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
10930        assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
10931        assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
10932        assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
10933    }
10934
10935    #[test]
10936    fn timestamp_ceil_to_unit_d_rounds_to_day() {
10937        // 12:34:56 → ceil to 1 day → 24:00:00 (next day).
10938        let h = Timedelta::NANOS_PER_HOUR;
10939        let d = Timedelta::NANOS_PER_DAY;
10940        let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
10941        let ts = Timestamp::from_nanos(twelve_thirty_four);
10942        assert_eq!(ts.ceil_to_unit("D").nanos, d);
10943        assert_eq!(ts.ceil_to_unit("day").nanos, d);
10944        assert_eq!(ts.ceil_to_unit("days").nanos, d);
10945    }
10946
10947    #[test]
10948    fn timestamp_round_to_unit_min_rounds_to_minute() {
10949        // 12:34:31 → round to 1 minute → 12:35:00.
10950        let m = Timedelta::NANOS_PER_MIN;
10951        let twelve_thirty_four_thirty_one =
10952            Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
10953        let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
10954        let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
10955        assert_eq!(ts.round_to_unit("min").nanos, expected);
10956        assert_eq!(ts.round_to_unit("T").nanos, expected); // pandas pre-2.2 alias
10957        assert_eq!(ts.round_to_unit("minute").nanos, expected);
10958    }
10959
10960    #[test]
10961    fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
10962        let ts = Timestamp::from_nanos(
10963            Timedelta::NANOS_PER_HOUR * 12
10964                + Timedelta::NANOS_PER_MIN * 34
10965                + Timedelta::NANOS_PER_SEC * 31,
10966        );
10967
10968        assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
10969        assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
10970        assert_eq!(ts.round("min"), ts.round_to_unit("min"));
10971    }
10972
10973    #[test]
10974    fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
10975        let ts = Timestamp::from_nanos_tz(
10976            Timedelta::NANOS_PER_DAY * 3
10977                + Timedelta::NANOS_PER_HOUR * 12
10978                + Timedelta::NANOS_PER_MIN * 34,
10979            "US/Eastern",
10980        );
10981        let normalized = ts.normalize();
10982
10983        assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
10984        assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
10985        assert!(Timestamp::nat().normalize().is_nat());
10986        for nanos in [
10987            i64::MIN + 1,
10988            -Timedelta::NANOS_PER_DAY - 1,
10989            -Timedelta::NANOS_PER_DAY,
10990            -1,
10991            0,
10992            Timedelta::NANOS_PER_DAY - 1,
10993            Timedelta::NANOS_PER_DAY,
10994            i64::MAX,
10995        ] {
10996            let timestamp = Timestamp::from_nanos(nanos);
10997            assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
10998        }
10999    }
11000
11001    #[test]
11002    #[ignore = "foreground profile-first A/B"]
11003    fn timestamp_normalize_direct_day_profile_dk721() {
11004        use std::{hint::black_box, time::Instant};
11005
11006        fn former(timestamp: &Timestamp) -> Timestamp {
11007            timestamp.floor_to_unit("D")
11008        }
11009
11010        fn candidate(timestamp: &Timestamp) -> Timestamp {
11011            timestamp.normalize()
11012        }
11013
11014        fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
11015            let started = Instant::now();
11016            let mut checksum = 0_u64;
11017            for timestamp in input {
11018                let normalized = normalize(black_box(timestamp));
11019                checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
11020            }
11021            black_box(checksum);
11022            started.elapsed().as_nanos()
11023        }
11024
11025        fn percentile(samples: &mut [u128], percent: usize) -> u128 {
11026            samples.sort_unstable();
11027            let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
11028            samples[rank]
11029        }
11030
11031        let parity_cases = [
11032            Timestamp::nat(),
11033            Timestamp::from_nanos(i64::MIN + 1),
11034            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
11035            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
11036            Timestamp::from_nanos(-1),
11037            Timestamp::from_nanos(0),
11038            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
11039            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
11040            Timestamp::from_nanos(i64::MAX),
11041            Timestamp::from_nanos_tz(-1, "US/Eastern"),
11042            Timestamp::from_nanos_tz(
11043                Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
11044                "Asia/Tokyo",
11045            ),
11046        ];
11047        for timestamp in &parity_cases {
11048            assert_eq!(former(timestamp), candidate(timestamp));
11049            assert_eq!(timestamp.normalize(), former(timestamp));
11050        }
11051
11052        const ROWS: usize = 16_384;
11053        const SAMPLES: usize = 20;
11054        let input = (0..ROWS)
11055            .map(|index| {
11056                let day = index as i64 % 4_096 - 2_048;
11057                let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
11058                    % Timedelta::NANOS_PER_DAY as u64) as i64;
11059                Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
11060            })
11061            .collect::<Vec<_>>();
11062        for timestamp in &input {
11063            assert_eq!(former(timestamp), candidate(timestamp));
11064        }
11065
11066        for _ in 0..3 {
11067            black_box(elapsed(&input, former));
11068            black_box(elapsed(&input, candidate));
11069        }
11070
11071        let mut former_ns = Vec::with_capacity(SAMPLES);
11072        let mut candidate_ns = Vec::with_capacity(SAMPLES);
11073        for sample in 0..SAMPLES {
11074            if sample % 2 == 0 {
11075                former_ns.push(elapsed(&input, former));
11076                candidate_ns.push(elapsed(&input, candidate));
11077            } else {
11078                candidate_ns.push(elapsed(&input, candidate));
11079                former_ns.push(elapsed(&input, former));
11080            }
11081        }
11082
11083        let mut former_sorted = former_ns.clone();
11084        let mut candidate_sorted = candidate_ns.clone();
11085        let former_p50 = percentile(&mut former_sorted, 50);
11086        let former_p95 = percentile(&mut former_sorted, 95);
11087        let former_p99 = percentile(&mut former_sorted, 99);
11088        let candidate_p50 = percentile(&mut candidate_sorted, 50);
11089        let candidate_p95 = percentile(&mut candidate_sorted, 95);
11090        let candidate_p99 = percentile(&mut candidate_sorted, 99);
11091        println!(
11092            "TIMESTAMP_NORMALIZE_DIRECT_DAY 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_p99_ns={former_p99} candidate_p99_ns={candidate_p99} speedup_p99={:.6} former_samples={former_ns:?} candidate_samples={candidate_ns:?}",
11093            former_p50 as f64 / candidate_p50 as f64,
11094            former_p95 as f64 / candidate_p95 as f64,
11095            former_p99 as f64 / candidate_p99 as f64,
11096        );
11097    }
11098
11099    #[test]
11100    fn timestamp_unit_rounding_unknown_unit_returns_nat() {
11101        let ts = Timestamp::from_nanos(100);
11102        assert!(ts.floor_to_unit("fortnight").is_nat());
11103        assert!(ts.ceil_to_unit("century").is_nat());
11104        assert!(ts.round_to_unit("xyz").is_nat());
11105    }
11106
11107    #[test]
11108    fn timestamp_unit_rounding_propagates_nat() {
11109        let nat = Timestamp::nat();
11110        assert!(nat.floor_to_unit("H").is_nat());
11111        assert!(nat.ceil_to_unit("H").is_nat());
11112        assert!(nat.round_to_unit("H").is_nat());
11113    }
11114
11115    #[test]
11116    fn timestamp_unit_rounding_preserves_tz() {
11117        let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
11118        assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
11119        assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
11120        assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
11121    }
11122
11123    #[test]
11124    fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
11125        // Public surface check: pandas alias core set.
11126        assert_eq!(
11127            Timedelta::unit_to_nanos("W"),
11128            Some(Timedelta::NANOS_PER_WEEK)
11129        );
11130        assert_eq!(
11131            Timedelta::unit_to_nanos("D"),
11132            Some(Timedelta::NANOS_PER_DAY)
11133        );
11134        assert_eq!(
11135            Timedelta::unit_to_nanos("H"),
11136            Some(Timedelta::NANOS_PER_HOUR)
11137        );
11138        assert_eq!(
11139            Timedelta::unit_to_nanos("min"),
11140            Some(Timedelta::NANOS_PER_MIN)
11141        );
11142        assert_eq!(
11143            Timedelta::unit_to_nanos("s"),
11144            Some(Timedelta::NANOS_PER_SEC)
11145        );
11146        assert_eq!(
11147            Timedelta::unit_to_nanos("ms"),
11148            Some(Timedelta::NANOS_PER_MILLI)
11149        );
11150        assert_eq!(
11151            Timedelta::unit_to_nanos("us"),
11152            Some(Timedelta::NANOS_PER_MICRO)
11153        );
11154        assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
11155        // Empty string → days (pandas default).
11156        assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
11157        // Unknown alias → None.
11158        assert_eq!(Timedelta::unit_to_nanos("century"), None);
11159    }
11160
11161    #[test]
11162    fn timestamp_isoformat_basic() {
11163        let ts = Timestamp::from_nanos(0);
11164        assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
11165
11166        let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
11167        assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
11168
11169        let ts_tz = Timestamp::from_nanos_tz(
11170            Timedelta::NANOS_PER_DAY
11171                + Timedelta::NANOS_PER_HOUR * 14
11172                + Timedelta::NANOS_PER_MIN * 30,
11173            "America/New_York",
11174        );
11175        assert!(ts_tz.isoformat().contains("1970-01-02T14:30:00"));
11176        assert!(ts_tz.isoformat().contains("[America/New_York]"));
11177
11178        assert_eq!(Timestamp::nat().isoformat(), "NaT");
11179    }
11180
11181    #[test]
11182    fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
11183        assert_eq!(
11184            Timestamp::from_nanos(-1).isoformat(),
11185            "1969-12-31T23:59:59.999999999"
11186        );
11187        assert_eq!(
11188            Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
11189            "1969-12-31T23:59:59"
11190        );
11191        assert_eq!(
11192            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
11193            "1969-12-31T00:00:00"
11194        );
11195        assert_eq!(
11196            Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
11197            "1969-12-31T23:59:59.999999999+00:00"
11198        );
11199    }
11200
11201    #[test]
11202    fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
11203        assert_eq!(
11204            Timestamp::from_nanos(123_456_789).isoformat(),
11205            "1970-01-01T00:00:00.123456789"
11206        );
11207        assert_eq!(
11208            Timestamp::from_nanos(123_456_000).isoformat(),
11209            "1970-01-01T00:00:00.123456"
11210        );
11211        assert_eq!(
11212            Timestamp::from_nanos(123_000_000).isoformat(),
11213            "1970-01-01T00:00:00.123000"
11214        );
11215        assert_eq!(
11216            Timestamp::from_nanos_tz(1, "UTC").isoformat(),
11217            "1970-01-01T00:00:00.000000001+00:00"
11218        );
11219    }
11220
11221    fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
11222        if timestamp.is_nat() {
11223            return "NaT".to_owned();
11224        }
11225        let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
11226        match &timestamp.tz {
11227            Some(tz) if tz == "UTC" => format!("{base}+00:00"),
11228            Some(tz) => format!("{base}[{tz}]"),
11229            None => base,
11230        }
11231    }
11232
11233    #[test]
11234    fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
11235        let nanos = [
11236            Timestamp::NAT,
11237            -Timedelta::NANOS_PER_DAY - 1,
11238            -Timedelta::NANOS_PER_SEC,
11239            -1,
11240            0,
11241            1,
11242            123_456_000,
11243            123_456_789,
11244            i64::MAX,
11245        ];
11246        let timezones = [
11247            None,
11248            Some("UTC"),
11249            Some("America/New_York"),
11250            Some(""),
11251            Some("Etc/Γ"),
11252        ];
11253        for value in nanos {
11254            for timezone in timezones {
11255                let timestamp = Timestamp {
11256                    nanos: value,
11257                    tz: timezone.map(str::to_owned),
11258                };
11259                assert_eq!(
11260                    timestamp.isoformat(),
11261                    timestamp_isoformat_former_q8g50(&timestamp),
11262                    "nanos={value} timezone={timezone:?}"
11263                );
11264            }
11265        }
11266    }
11267
11268    #[test]
11269    #[ignore = "foreground release A/B only"]
11270    fn timestamp_isoformat_one_buffer_ab_q8g50() {
11271        use std::{hint::black_box, time::Instant};
11272
11273        const ITEMS: usize = 8_192;
11274        const SAMPLES: usize = 10;
11275
11276        fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
11277            let started = Instant::now();
11278            let mut checksum = 0usize;
11279            for timestamp in black_box(values) {
11280                checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
11281            }
11282            black_box(checksum);
11283            started.elapsed().as_nanos()
11284        }
11285
11286        let values = (0..ITEMS)
11287            .map(|idx| {
11288                let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
11289                let timezone = if idx.is_multiple_of(2) {
11290                    "UTC"
11291                } else {
11292                    "America/New_York"
11293                };
11294                Timestamp::from_nanos_tz(nanos, timezone)
11295            })
11296            .collect::<Vec<_>>();
11297        for timestamp in &values {
11298            assert_eq!(
11299                timestamp.isoformat(),
11300                timestamp_isoformat_former_q8g50(timestamp)
11301            );
11302        }
11303
11304        black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
11305        black_box(elapsed(&values, Timestamp::isoformat));
11306
11307        let mut former_ns = Vec::with_capacity(SAMPLES);
11308        let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
11309        for sample in 0..SAMPLES {
11310            if sample.is_multiple_of(2) {
11311                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
11312                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
11313            } else {
11314                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
11315                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
11316            }
11317        }
11318        former_ns.sort_unstable();
11319        one_buffer_ns.sort_unstable();
11320        let former_p50 = former_ns[SAMPLES / 2];
11321        let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
11322        println!(
11323            "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
11324            former_p50 as f64 / one_buffer_p50 as f64
11325        );
11326        println!("former_samples_ns={former_ns:?}");
11327        println!("one_buffer_samples_ns={one_buffer_ns:?}");
11328    }
11329
11330    #[test]
11331    fn timestamp_strftime_basic() {
11332        let ts = Timestamp::from_nanos(
11333            Timedelta::NANOS_PER_DAY * 365
11334                + Timedelta::NANOS_PER_HOUR * 9
11335                + Timedelta::NANOS_PER_MIN * 15,
11336        );
11337        assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
11338        assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
11339        assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
11340        assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%1971|%%01|%Q|%|λ");
11341        assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
11342    }
11343
11344    #[test]
11345    #[ignore = "foreground normal-release attribution harness"]
11346    fn timestamp_strftime_one_buffer_profile_8qzbo() {
11347        use std::{hint::black_box, time::Instant};
11348
11349        const ITEMS: usize = 8_192;
11350        const SAMPLES: usize = 10;
11351        const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
11352
11353        fn former(timestamp: &Timestamp, format: &str) -> String {
11354            if timestamp.is_nat() {
11355                return "NaT".to_string();
11356            }
11357            let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
11358            let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
11359
11360            let days_since_epoch = total_secs / 86400;
11361            let secs_of_day = (total_secs % 86400 + 86400) % 86400;
11362            let days = days_since_epoch + 719_468;
11363            let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
11364            let doe = days - era * 146_097;
11365            let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
11366            let y = yoe + era * 400;
11367            let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
11368            let mp = (5 * doy + 2) / 153;
11369            let d = doy - (153 * mp + 2) / 5 + 1;
11370            let m = if mp < 10 { mp + 3 } else { mp - 9 };
11371            let year = if m <= 2 { y + 1 } else { y };
11372            let hour = secs_of_day / 3600;
11373            let minute = (secs_of_day % 3600) / 60;
11374            let second = secs_of_day % 60;
11375            let micros = sub_nanos / 1000;
11376
11377            format
11378                .replace("%Y", &format!("{year:04}"))
11379                .replace("%m", &format!("{m:02}"))
11380                .replace("%d", &format!("{d:02}"))
11381                .replace("%H", &format!("{hour:02}"))
11382                .replace("%M", &format!("{minute:02}"))
11383                .replace("%S", &format!("{second:02}"))
11384                .replace("%f", &format!("{micros:06}"))
11385        }
11386
11387        fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
11388            let started = Instant::now();
11389            let mut digest = 0_usize;
11390            for timestamp in timestamps {
11391                let value = formatter(black_box(timestamp), black_box(FORMAT));
11392                digest = digest.wrapping_add(value.len());
11393                digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
11394                black_box(value);
11395            }
11396            black_box(digest);
11397            started.elapsed().as_nanos()
11398        }
11399
11400        fn percentile(samples: &mut [u128], pct: usize) -> u128 {
11401            samples.sort_unstable();
11402            let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
11403            samples[rank]
11404        }
11405
11406        let edge_timestamps = [
11407            Timestamp::nat(),
11408            Timestamp::from_nanos(i64::MIN + 1),
11409            Timestamp::from_nanos(-1_234_567_890),
11410            Timestamp::from_nanos(0),
11411            Timestamp::from_nanos(1_735_732_800_123_456_789),
11412            Timestamp::from_nanos(i64::MAX),
11413        ];
11414        let edge_formats = [
11415            "",
11416            "%Y-%m-%d %H:%M:%S.%f",
11417            "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
11418            "%%Y|%%%m|%Q|%|λ",
11419            FORMAT,
11420        ];
11421        for timestamp in &edge_timestamps {
11422            for format in edge_formats {
11423                assert_eq!(former(timestamp, format), timestamp.strftime(format));
11424            }
11425        }
11426
11427        let timestamps = (0..ITEMS)
11428            .map(|index| {
11429                let centered = index as i64 - ITEMS as i64 / 2;
11430                Timestamp::from_nanos(centered * 987_654_321_123_456)
11431            })
11432            .collect::<Vec<_>>();
11433        for timestamp in &timestamps {
11434            assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
11435        }
11436
11437        black_box(elapsed(&timestamps, former));
11438        black_box(elapsed(&timestamps, Timestamp::strftime));
11439
11440        let mut former_samples = Vec::with_capacity(SAMPLES);
11441        let mut public_samples = Vec::with_capacity(SAMPLES);
11442        for sample in 0..SAMPLES {
11443            if sample.is_multiple_of(2) {
11444                former_samples.push(elapsed(&timestamps, former));
11445                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
11446            } else {
11447                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
11448                former_samples.push(elapsed(&timestamps, former));
11449            }
11450        }
11451        let former_p50 = percentile(&mut former_samples, 50);
11452        let former_p95 = percentile(&mut former_samples, 95);
11453        let public_p50 = percentile(&mut public_samples, 50);
11454        let public_p95 = percentile(&mut public_samples, 95);
11455        println!(
11456            "TIMESTAMP_STRFTIME_AB items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} former_p95_ns={former_p95} public_p50_ns={public_p50} public_p95_ns={public_p95} p50_speedup={:.6} p95_speedup={:.6}",
11457            former_p50 as f64 / public_p50 as f64,
11458            former_p95 as f64 / public_p95 as f64,
11459        );
11460        println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
11461        println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
11462    }
11463
11464    #[test]
11465    fn timestamp_day_name_and_month_name() {
11466        let ts = Timestamp::from_nanos(0);
11467        assert_eq!(ts.day_name(), "Thursday");
11468        assert_eq!(ts.month_name(), "January");
11469
11470        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
11471        assert_eq!(ts2.day_name(), "Friday");
11472        assert_eq!(ts2.month_name(), "January");
11473
11474        assert_eq!(Timestamp::nat().day_name(), "NaT");
11475        assert_eq!(Timestamp::nat().month_name(), "NaT");
11476    }
11477
11478    #[test]
11479    fn timestamp_replace_validates_components_zw0y2() {
11480        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
11481        let replaced = ts.replace(
11482            Some(2024),
11483            Some(2),
11484            Some(29),
11485            Some(23),
11486            Some(59),
11487            Some(58),
11488            Some(987_654),
11489            Some(321),
11490        );
11491        assert_eq!(replaced.year(), Some(2024));
11492        assert_eq!(replaced.month(), Some(2));
11493        assert_eq!(replaced.day(), Some(29));
11494        assert_eq!(replaced.hour(), Some(23));
11495        assert_eq!(replaced.minute(), Some(59));
11496        assert_eq!(replaced.second(), Some(58));
11497        assert_eq!(replaced.microsecond(), Some(987_654));
11498        assert_eq!(replaced.nanosecond(), Some(321));
11499
11500        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
11501        assert_eq!(
11502            tz.replace(None, Some(2), Some(29), None, None, None, None, None)
11503                .tz
11504                .as_deref(),
11505            Some("UTC")
11506        );
11507
11508        assert!(
11509            ts.replace(None, Some(13), None, None, None, None, None, None)
11510                .is_nat()
11511        );
11512        assert!(
11513            ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
11514                .is_nat()
11515        );
11516        assert!(
11517            ts.replace(None, None, None, Some(24), None, None, None, None)
11518                .is_nat()
11519        );
11520        assert!(
11521            ts.replace(None, None, None, None, Some(60), None, None, None)
11522                .is_nat()
11523        );
11524        assert!(
11525            ts.replace(None, None, None, None, None, Some(60), None, None)
11526                .is_nat()
11527        );
11528        assert!(
11529            ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
11530                .is_nat()
11531        );
11532        assert!(
11533            ts.replace(None, None, None, None, None, None, None, Some(1_000))
11534                .is_nat()
11535        );
11536        assert!(
11537            Timestamp::nat()
11538                .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
11539                .is_nat()
11540        );
11541    }
11542
11543    #[test]
11544    fn timestamp_component_accessors() {
11545        let ts = Timestamp::from_nanos(0);
11546        assert_eq!(ts.year(), Some(1970));
11547        assert_eq!(ts.month(), Some(1));
11548        assert_eq!(ts.day(), Some(1));
11549        assert_eq!(ts.hour(), Some(0));
11550        assert_eq!(ts.minute(), Some(0));
11551        assert_eq!(ts.second(), Some(0));
11552        assert_eq!(ts.microsecond(), Some(0));
11553        assert_eq!(ts.nanosecond(), Some(0));
11554
11555        let ts2 = Timestamp::from_nanos(
11556            Timedelta::NANOS_PER_DAY * 365
11557                + Timedelta::NANOS_PER_HOUR * 14
11558                + Timedelta::NANOS_PER_MIN * 30
11559                + Timedelta::NANOS_PER_SEC * 45
11560                + 123_456_789,
11561        );
11562        assert_eq!(ts2.year(), Some(1971));
11563        assert_eq!(ts2.month(), Some(1));
11564        assert_eq!(ts2.day(), Some(1));
11565        assert_eq!(ts2.hour(), Some(14));
11566        assert_eq!(ts2.minute(), Some(30));
11567        assert_eq!(ts2.second(), Some(45));
11568        assert_eq!(ts2.microsecond(), Some(123456));
11569        assert_eq!(ts2.nanosecond(), Some(789));
11570
11571        assert_eq!(Timestamp::nat().year(), None);
11572        assert_eq!(Timestamp::nat().month(), None);
11573        assert_eq!(Timestamp::nat().day(), None);
11574    }
11575
11576    #[test]
11577    fn timestamp_dayofweek_dayofyear_quarter() {
11578        let ts = Timestamp::from_nanos(0);
11579        assert_eq!(ts.dayofweek(), Some(3));
11580        assert_eq!(ts.weekday(), Some(3));
11581        assert_eq!(ts.dayofyear(), Some(1));
11582        assert_eq!(ts.quarter(), Some(1));
11583
11584        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
11585        assert_eq!(ts2.quarter(), Some(2));
11586
11587        let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
11588        assert_eq!(ts3.dayofyear(), Some(1));
11589        assert_eq!(ts3.dayofweek(), Some(4));
11590
11591        assert_eq!(Timestamp::nat().dayofweek(), None);
11592        assert_eq!(Timestamp::nat().dayofyear(), None);
11593        assert_eq!(Timestamp::nat().quarter(), None);
11594    }
11595
11596    #[test]
11597    fn timestamp_is_boundary_methods() {
11598        let jan1 = Timestamp::from_nanos(0);
11599        assert_eq!(jan1.is_leap_year(), Some(false));
11600        assert_eq!(jan1.is_month_start(), Some(true));
11601        assert_eq!(jan1.is_month_end(), Some(false));
11602        assert_eq!(jan1.is_quarter_start(), Some(true));
11603        assert_eq!(jan1.is_quarter_end(), Some(false));
11604        assert_eq!(jan1.is_year_start(), Some(true));
11605        assert_eq!(jan1.is_year_end(), Some(false));
11606
11607        let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
11608        assert_eq!(dec31.is_month_start(), Some(false));
11609        assert_eq!(dec31.is_month_end(), Some(true));
11610        assert_eq!(dec31.is_quarter_end(), Some(true));
11611        assert_eq!(dec31.is_year_end(), Some(true));
11612
11613        assert_eq!(Timestamp::nat().is_leap_year(), None);
11614        assert_eq!(Timestamp::nat().is_month_start(), None);
11615    }
11616
11617    #[test]
11618    fn timestamp_days_in_month() {
11619        let jan = Timestamp::from_nanos(0);
11620        assert_eq!(jan.days_in_month(), Some(31));
11621        assert_eq!(jan.daysinmonth(), Some(31));
11622
11623        let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
11624        assert_eq!(feb_non_leap.days_in_month(), Some(28));
11625
11626        assert_eq!(Timestamp::nat().days_in_month(), None);
11627    }
11628
11629    #[test]
11630    fn timestamp_weekofyear() {
11631        let jan1 = Timestamp::from_nanos(0);
11632        assert_eq!(jan1.weekofyear(), Some(1));
11633        assert_eq!(jan1.week(), Some(1));
11634
11635        let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
11636        assert_eq!(jan8.weekofyear(), Some(2));
11637
11638        assert_eq!(Timestamp::nat().weekofyear(), None);
11639        assert_eq!(Timestamp::nat().week(), None);
11640    }
11641
11642    #[test]
11643    fn timestamp_weekofyear_iso_53_week_boundaries() {
11644        // ISO-8601 53-week-year boundaries vs pandas 2.2.3 isocalendar().week.
11645        // (br-frankenpandas-xmfmd) Date -> nanos via days since 1970-01-01.
11646        fn week_of(date_days: i64) -> Option<i64> {
11647            Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
11648        }
11649        // Days from 1970-01-01 for each date (UTC, no tz).
11650        // 2021-01-01 -> week 53 (2020 is a 53-week year); FP used to give 52.
11651        assert_eq!(week_of(18_628), Some(53)); // 2021-01-01
11652        // 2016-01-01 -> week 53 (2015 is a 53-week year).
11653        assert_eq!(week_of(16_801), Some(53)); // 2016-01-01
11654        // 2026-12-31 -> week 53; FP used to give 1.
11655        assert_eq!(week_of(20_818), Some(53)); // 2026-12-31
11656        // 2020-12-31 -> week 53.
11657        assert_eq!(week_of(18_627), Some(53)); // 2020-12-31
11658        // Cases that must stay correct (non-53 boundaries):
11659        assert_eq!(week_of(19_358), Some(52)); // 2023-01-01 -> week 52
11660        assert_eq!(week_of(20_087), Some(1)); // 2024-12-30 -> week 1
11661        assert_eq!(week_of(18_260), Some(1)); // 2019-12-30 -> week 1
11662    }
11663
11664    #[test]
11665    fn iso_weeks_in_year_53_week_years() {
11666        use super::iso_weeks_in_year;
11667        // Known 53-week years; everything else is 52.
11668        for y in [2004, 2009, 2015, 2020, 2026] {
11669            assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
11670        }
11671        for y in [2018, 2019, 2021, 2022, 2023, 2024] {
11672            assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
11673        }
11674    }
11675
11676    #[test]
11677    fn timestamp_to_unit() {
11678        let ts = Timestamp::from_nanos(1_000_000_000);
11679        assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
11680        assert_eq!(ts.to_unit("us"), Some(1_000_000));
11681        assert_eq!(ts.to_unit("ms"), Some(1_000));
11682        assert_eq!(ts.to_unit("s"), Some(1));
11683        assert_eq!(ts.to_unit("invalid"), None);
11684
11685        assert_eq!(Timestamp::nat().to_unit("ns"), None);
11686    }
11687
11688    #[test]
11689    fn timestamp_toordinal() {
11690        // 2026-01-01 is ordinal 738886 (days since Jan 1, year 1)
11691        // Days from Unix epoch: 738886 - 719163 = 19723
11692        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
11693        let ts = Timestamp::from_nanos(nanos_2026_01_01);
11694        assert_eq!(ts.toordinal(), Some(738886));
11695
11696        // NaT returns None
11697        assert_eq!(Timestamp::nat().toordinal(), None);
11698    }
11699
11700    #[test]
11701    fn timestamp_fromordinal() {
11702        // Round-trip test: create a timestamp from ordinal derived from toordinal
11703        // First create a known timestamp
11704        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
11705        let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
11706        let ordinal = ts_orig.toordinal().unwrap();
11707
11708        // Now convert back using fromordinal
11709        let ts = Timestamp::fromordinal(ordinal);
11710        assert_eq!(ts.year(), ts_orig.year());
11711        assert_eq!(ts.month(), ts_orig.month());
11712        assert_eq!(ts.day(), ts_orig.day());
11713
11714        // Invalid ordinal returns NaT
11715        let nat = Timestamp::fromordinal(0);
11716        assert!(nat.is_nat());
11717    }
11718
11719    #[test]
11720    fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
11721        const EPOCH_ORDINAL: i64 = 719_163;
11722        let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
11723        let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
11724
11725        let max_valid = Timestamp::fromordinal(max_valid_ordinal);
11726        assert!(!max_valid.is_nat());
11727        assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
11728
11729        assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
11730        assert!(Timestamp::fromordinal(i64::MAX).is_nat());
11731    }
11732
11733    #[test]
11734    fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
11735        const EPOCH_ORDINAL: i64 = 719_163;
11736        const DAY: i64 = Timedelta::NANOS_PER_DAY;
11737
11738        fn next(seed: &mut u64) -> u64 {
11739            *seed = seed
11740                .wrapping_mul(3202034522624059733)
11741                .wrapping_add(4354685564936845319);
11742            *seed
11743        }
11744
11745        fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
11746            let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
11747            let ts = Timestamp::from_nanos(nanos);
11748            let expected_day_offset = nanos.div_euclid(DAY);
11749            let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
11750
11751            assert_eq!(
11752                ts.toordinal(),
11753                Some(expected_ordinal),
11754                "case {case}: toordinal"
11755            );
11756
11757            let midnight = Timestamp::fromordinal(expected_ordinal);
11758            assert_eq!(
11759                midnight.nanos,
11760                expected_day_offset * DAY,
11761                "case {case}: fromordinal nanos"
11762            );
11763            assert_eq!(
11764                midnight.toordinal(),
11765                Some(expected_ordinal),
11766                "case {case}: fromordinal roundtrip"
11767            );
11768        }
11769
11770        assert_eq!(Timestamp::nat().toordinal(), None);
11771        assert!(Timestamp::fromordinal(0).is_nat());
11772        assert!(Timestamp::fromordinal(-1).is_nat());
11773
11774        assert_ordinal_case(usize::MAX, -1, DAY - 1);
11775        assert_ordinal_case(usize::MAX - 1, 0, -1);
11776        assert_ordinal_case(usize::MAX - 2, 19_723, 0);
11777
11778        let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
11779        for case in 0..260 {
11780            let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
11781            let subday_nanos = match case % 7 {
11782                0 => 0,
11783                1 => DAY - 1,
11784                2 => -1,
11785                _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
11786            };
11787            assert_ordinal_case(case, day_offset, subday_nanos);
11788        }
11789    }
11790
11791    #[test]
11792    fn timestamp_parse_iso8601_date_only() {
11793        let ts = Timestamp::parse("2024-01-15").unwrap();
11794        assert_eq!(ts.year(), Some(2024));
11795        assert_eq!(ts.month(), Some(1));
11796        assert_eq!(ts.day(), Some(15));
11797        assert_eq!(ts.hour(), Some(0));
11798        assert_eq!(ts.minute(), Some(0));
11799        assert_eq!(ts.second(), Some(0));
11800    }
11801
11802    #[test]
11803    fn timestamp_parse_iso8601_datetime() {
11804        let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
11805        assert_eq!(ts.year(), Some(2024));
11806        assert_eq!(ts.month(), Some(1));
11807        assert_eq!(ts.day(), Some(15));
11808        assert_eq!(ts.hour(), Some(10));
11809        assert_eq!(ts.minute(), Some(30));
11810        assert_eq!(ts.second(), Some(45));
11811    }
11812
11813    #[test]
11814    fn timestamp_parse_space_separator() {
11815        let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
11816        assert_eq!(ts.year(), Some(2024));
11817        assert_eq!(ts.hour(), Some(10));
11818    }
11819
11820    #[test]
11821    fn timestamp_parse_with_fractional_seconds() {
11822        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
11823        assert_eq!(ts.second(), Some(45));
11824        assert_eq!(ts.microsecond(), Some(123456));
11825        assert_eq!(ts.nanosecond(), Some(789));
11826    }
11827
11828    #[test]
11829    fn timestamp_parse_utc_timezone() {
11830        let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
11831        assert_eq!(ts.tz, Some("UTC".to_string()));
11832    }
11833
11834    #[test]
11835    fn timestamp_parse_offset_timezone() {
11836        let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
11837        assert_eq!(ts.tz, Some("+05:30".to_string()));
11838
11839        let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
11840        assert_eq!(ts.tz, Some("-05:30".to_string()));
11841    }
11842
11843    #[test]
11844    fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
11845        assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
11846        assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
11847        assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
11848        assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
11849        assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
11850    }
11851
11852    #[test]
11853    fn timestamp_parse_nat() {
11854        let ts = Timestamp::parse("NaT").unwrap();
11855        assert!(ts.is_nat());
11856        let ts2 = Timestamp::parse("nat").unwrap();
11857        assert!(ts2.is_nat());
11858    }
11859
11860    #[test]
11861    fn timestamp_parse_invalid() {
11862        assert!(Timestamp::parse("not a date").is_err());
11863        assert!(Timestamp::parse("2024-13-01").is_err()); // invalid month
11864        assert!(Timestamp::parse("2024-01-32").is_err()); // invalid day
11865    }
11866
11867    #[test]
11868    fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
11869        assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
11870        assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
11871        assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
11872        assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
11873        assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
11874
11875        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
11876        assert_eq!(ts.second(), Some(45));
11877        assert_eq!(ts.microsecond(), Some(123456));
11878        assert_eq!(ts.nanosecond(), Some(789));
11879    }
11880
11881    #[test]
11882    #[ignore = "foreground profile-first A/B"]
11883    fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
11884        use std::{hint::black_box, time::Instant};
11885
11886        const CALLS: usize = 131_072;
11887        const SAMPLES: usize = 12;
11888        type ParsedTime = Option<(u32, u32, u32, u64)>;
11889        const VALID: [&str; 16] = [
11890            "00:00:00.0",
11891            "01:02:03.1",
11892            "02:03:04.01",
11893            "03:04:05.001",
11894            "04:05:06.0001",
11895            "05:06:07.00001",
11896            "06:07:08.000001",
11897            "07:08:09.0000001",
11898            "08:09:10.00000001",
11899            "09:10:11.000000001",
11900            "10:11:12.123456789",
11901            "11:12:13.999999999",
11902            "12:13:14.123456789987",
11903            "13:14:15.000000000001",
11904            "14:15:16.101010101010",
11905            "23:59:59.987654321234",
11906        ];
11907
11908        #[inline(never)]
11909        fn former(s: &str) -> ParsedTime {
11910            let (time_str, frac_str) = match s.split_once('.') {
11911                Some((time, frac)) => (time, Some(frac)),
11912                None => (s, None),
11913            };
11914            let parts: Vec<&str> = time_str.split(':').collect();
11915            if parts.is_empty() || parts.len() > 3 {
11916                return None;
11917            }
11918            let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
11919            let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
11920            let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
11921
11922            if hour > 23 || minute > 59 || second > 59 {
11923                return None;
11924            }
11925
11926            let nanos = match frac_str {
11927                None => 0,
11928                Some(frac) => {
11929                    if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
11930                        return None;
11931                    }
11932                    let truncated = &frac[..frac.len().min(9)];
11933                    let padded = format!("{truncated:0<9}");
11934                    padded.parse::<u64>().ok()?
11935                }
11936            };
11937
11938            Some((hour, minute, second, nanos))
11939        }
11940
11941        #[inline(never)]
11942        fn candidate(s: &str) -> ParsedTime {
11943            Timestamp::parse_time(s)
11944        }
11945
11946        fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
11947            let started = Instant::now();
11948            for input in black_box(inputs) {
11949                black_box(parser(black_box(*input)));
11950            }
11951            started.elapsed().as_nanos()
11952        }
11953
11954        fn percentile(samples: &[u128], percent: usize) -> u128 {
11955            let mut sorted = samples.to_vec();
11956            sorted.sort_unstable();
11957            let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
11958            sorted[rank]
11959        }
11960
11961        let invalid = [
11962            "",
11963            "24:00:00.1",
11964            "12:60:00.1",
11965            "12:00:60.1",
11966            "12:00:00.",
11967            "12:00:00.abc",
11968            "12:00:00.-1",
11969            "12:00:00.123",
11970            "12:00:00.123456789x",
11971            "12:00:00.1.2",
11972            "12:00:00:01.1",
11973        ];
11974        for input in VALID.iter().chain(invalid.iter()) {
11975            assert_eq!(candidate(input), former(input), "input={input:?}");
11976        }
11977
11978        let inputs = (0..CALLS)
11979            .map(|index| VALID[index % VALID.len()])
11980            .collect::<Vec<_>>();
11981        for _ in 0..2 {
11982            black_box(elapsed(&inputs, former));
11983            black_box(elapsed(&inputs, candidate));
11984        }
11985
11986        let mut former_ns = Vec::with_capacity(SAMPLES);
11987        let mut candidate_ns = Vec::with_capacity(SAMPLES);
11988        for sample in 0..SAMPLES {
11989            if sample.is_multiple_of(2) {
11990                former_ns.push(elapsed(&inputs, former));
11991                candidate_ns.push(elapsed(&inputs, candidate));
11992            } else {
11993                candidate_ns.push(elapsed(&inputs, candidate));
11994                former_ns.push(elapsed(&inputs, former));
11995            }
11996        }
11997
11998        let former_p50 = percentile(&former_ns, 50);
11999        let former_p95 = percentile(&former_ns, 95);
12000        let former_p99 = percentile(&former_ns, 99);
12001        let candidate_p50 = percentile(&candidate_ns, 50);
12002        let candidate_p95 = percentile(&candidate_ns, 95);
12003        let candidate_p99 = percentile(&candidate_ns, 99);
12004        println!(
12005            "TIMESTAMP_FRACTION_PARSE calls={CALLS} 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_p99_ns={former_p99} candidate_p99_ns={candidate_p99} speedup_p99={:.6} former_samples={former_ns:?} candidate_samples={candidate_ns:?}",
12006            former_p50 as f64 / candidate_p50 as f64,
12007            former_p95 as f64 / candidate_p95 as f64,
12008            former_p99 as f64 / candidate_p99 as f64,
12009        );
12010    }
12011
12012    #[test]
12013    fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
12014        fn next(seed: &mut u64) -> u64 {
12015            *seed = seed
12016                .wrapping_mul(3935559000370003845)
12017                .wrapping_add(2691343689449507681);
12018            *seed
12019        }
12020
12021        fn leap(year: i64) -> bool {
12022            (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
12023        }
12024
12025        fn month_len(year: i64, month: u32) -> u32 {
12026            match month {
12027                1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
12028                4 | 6 | 9 | 11 => 30,
12029                2 if leap(year) => 29,
12030                2 => 28,
12031                _ => 0,
12032            }
12033        }
12034
12035        struct Components {
12036            year: i64,
12037            month: u32,
12038            day: u32,
12039            hour: u32,
12040            minute: u32,
12041            second: u32,
12042            nanos: u64,
12043        }
12044
12045        fn assert_components(case: usize, text: &str, expected: Components) {
12046            let ts = Timestamp::parse(text).expect("seeded valid timestamp");
12047            let Components {
12048                year,
12049                month,
12050                day,
12051                hour,
12052                minute,
12053                second,
12054                nanos,
12055            } = expected;
12056            assert_eq!(ts.year(), Some(year), "case {case}: year");
12057            assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
12058            assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
12059            assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
12060            assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
12061            assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
12062            assert_eq!(
12063                ts.microsecond(),
12064                Some((nanos / 1000) as i64),
12065                "case {case}: microsecond"
12066            );
12067            assert_eq!(
12068                ts.nanosecond(),
12069                Some((nanos % 1000) as i64),
12070                "case {case}: nanosecond"
12071            );
12072        }
12073
12074        assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
12075        assert!(
12076            Timestamp::parse("nAt")
12077                .expect("mixed-case NaT parses")
12078                .is_nat()
12079        );
12080        assert!(Timestamp::parse("1900-02-29").is_err());
12081        assert!(Timestamp::parse("2001-04-31").is_err());
12082        assert!(Timestamp::parse("2024-00-15").is_err());
12083
12084        assert_components(
12085            usize::MAX,
12086            "2000-02-29",
12087            Components {
12088                year: 2000,
12089                month: 2,
12090                day: 29,
12091                hour: 0,
12092                minute: 0,
12093                second: 0,
12094                nanos: 0,
12095            },
12096        );
12097        assert_components(
12098            usize::MAX - 1,
12099            "2024-02-29T23:59:59.000000001",
12100            Components {
12101                year: 2024,
12102                month: 2,
12103                day: 29,
12104                hour: 23,
12105                minute: 59,
12106                second: 59,
12107                nanos: 1,
12108            },
12109        );
12110
12111        let mut seed = 0x15e0_1d50_1f0a_cade_u64;
12112        for case in 0..260 {
12113            let year = 1900 + (next(&mut seed) % 201) as i64;
12114            let month = 1 + (next(&mut seed) % 12) as u32;
12115            let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
12116            let hour = (next(&mut seed) % 24) as u32;
12117            let minute = (next(&mut seed) % 60) as u32;
12118            let second = (next(&mut seed) % 60) as u32;
12119            let nanos = next(&mut seed) % 1_000_000_000;
12120
12121            match case % 4 {
12122                0 => {
12123                    let text = format!("{year:04}-{month:02}-{day:02}");
12124                    assert_components(
12125                        case,
12126                        &text,
12127                        Components {
12128                            year,
12129                            month,
12130                            day,
12131                            hour: 0,
12132                            minute: 0,
12133                            second: 0,
12134                            nanos: 0,
12135                        },
12136                    );
12137                }
12138                1 => {
12139                    let text =
12140                        format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
12141                    assert_components(
12142                        case,
12143                        &text,
12144                        Components {
12145                            year,
12146                            month,
12147                            day,
12148                            hour,
12149                            minute,
12150                            second,
12151                            nanos: 0,
12152                        },
12153                    );
12154                }
12155                2 => {
12156                    let text =
12157                        format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
12158                    assert_components(
12159                        case,
12160                        &text,
12161                        Components {
12162                            year,
12163                            month,
12164                            day,
12165                            hour,
12166                            minute,
12167                            second,
12168                            nanos: 0,
12169                        },
12170                    );
12171                }
12172                _ => {
12173                    let text = format!(
12174                        "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
12175                    );
12176                    assert_components(
12177                        case,
12178                        &text,
12179                        Components {
12180                            year,
12181                            month,
12182                            day,
12183                            hour,
12184                            minute,
12185                            second,
12186                            nanos,
12187                        },
12188                    );
12189                }
12190            }
12191        }
12192    }
12193
12194    #[test]
12195    fn period_parse_annual() {
12196        let p = Period::parse("2024").unwrap();
12197        assert_eq!(p.freq(), PeriodFreq::Annual);
12198        assert_eq!(p.ordinal(), 2024 - 1970);
12199    }
12200
12201    #[test]
12202    fn period_parse_quarterly() {
12203        let p = Period::parse("2024Q1").unwrap();
12204        assert_eq!(p.freq(), PeriodFreq::Quarterly);
12205        assert_eq!(p.ordinal(), (2024 - 1970) * 4);
12206
12207        let p2 = Period::parse("2024q3").unwrap();
12208        assert_eq!(p2.freq(), PeriodFreq::Quarterly);
12209        assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
12210    }
12211
12212    #[test]
12213    fn period_parse_monthly() {
12214        let p = Period::parse("2024-01").unwrap();
12215        assert_eq!(p.freq(), PeriodFreq::Monthly);
12216        assert_eq!(p.ordinal(), (2024 - 1970) * 12);
12217
12218        let p2 = Period::parse("2024-12").unwrap();
12219        assert_eq!(p2.freq(), PeriodFreq::Monthly);
12220        assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
12221    }
12222
12223    #[test]
12224    fn period_parse_nat() {
12225        let p = Period::parse("NaT").unwrap();
12226        assert_eq!(p.ordinal(), i64::MIN);
12227    }
12228
12229    #[test]
12230    fn period_parse_invalid() {
12231        assert!(Period::parse("not a period").is_err());
12232        assert!(Period::parse("2024Q5").is_err()); // invalid quarter
12233        assert!(Period::parse("2024-13").is_err()); // invalid month
12234    }
12235
12236    #[test]
12237    fn interval_parse_basic() {
12238        let i = Interval::parse("[0, 1]").unwrap();
12239        assert_eq!(i.left, 0.0);
12240        assert_eq!(i.right, 1.0);
12241        assert_eq!(i.closed, IntervalClosed::Both);
12242
12243        let i2 = Interval::parse("(0, 1)").unwrap();
12244        assert_eq!(i2.left, 0.0);
12245        assert_eq!(i2.right, 1.0);
12246        assert_eq!(i2.closed, IntervalClosed::Neither);
12247
12248        let i3 = Interval::parse("[0, 1)").unwrap();
12249        assert_eq!(i3.closed, IntervalClosed::Left);
12250
12251        let i4 = Interval::parse("(0, 1]").unwrap();
12252        assert_eq!(i4.closed, IntervalClosed::Right);
12253    }
12254
12255    #[test]
12256    fn interval_parse_floats() {
12257        let i = Interval::parse("[-1.5, 2.5)").unwrap();
12258        assert_eq!(i.left, -1.5);
12259        assert_eq!(i.right, 2.5);
12260        assert_eq!(i.closed, IntervalClosed::Left);
12261    }
12262
12263    #[test]
12264    fn interval_parse_invalid() {
12265        assert!(Interval::parse("invalid").is_err());
12266        assert!(Interval::parse("[0]").is_err());
12267        assert!(Interval::parse("0, 1").is_err()); // missing brackets
12268    }
12269
12270    fn interval_parse_error_profile(s: &str) -> super::TypeError {
12271        super::TypeError::ValueNotParseable {
12272            value: s.to_string(),
12273            target: "Interval".to_string(),
12274        }
12275    }
12276
12277    #[inline(never)]
12278    fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
12279        let s = std::hint::black_box(s).trim();
12280        if s.len() < 5 {
12281            return Err(interval_parse_error_profile(s));
12282        }
12283
12284        let first_char = s.chars().next().unwrap();
12285        let last_char = s.chars().last().unwrap();
12286        let left_closed = match first_char {
12287            '[' => true,
12288            '(' => false,
12289            _ => return Err(interval_parse_error_profile(s)),
12290        };
12291        let right_closed = match last_char {
12292            ']' => true,
12293            ')' => false,
12294            _ => return Err(interval_parse_error_profile(s)),
12295        };
12296        let closed = match (left_closed, right_closed) {
12297            (true, true) => IntervalClosed::Both,
12298            (true, false) => IntervalClosed::Left,
12299            (false, true) => IntervalClosed::Right,
12300            (false, false) => IntervalClosed::Neither,
12301        };
12302
12303        let inner = &s[1..s.len() - 1];
12304        let parts: Vec<&str> = inner.split(',').collect();
12305        if parts.len() != 2 {
12306            return Err(interval_parse_error_profile(s));
12307        }
12308        let left = parts[0]
12309            .trim()
12310            .parse()
12311            .map_err(|_| interval_parse_error_profile(s))?;
12312        let right = parts[1]
12313            .trim()
12314            .parse()
12315            .map_err(|_| interval_parse_error_profile(s))?;
12316        Ok(Interval::new(left, right, closed))
12317    }
12318
12319    #[inline(never)]
12320    fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
12321        Interval::parse(std::hint::black_box(s))
12322    }
12323
12324    fn assert_interval_parse_profile_parity(s: &str) {
12325        match (
12326            interval_parse_former_profile(s),
12327            interval_parse_split_once_profile(s),
12328        ) {
12329            (Ok(former), Ok(candidate)) => {
12330                assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
12331                assert_eq!(
12332                    former.right.to_bits(),
12333                    candidate.right.to_bits(),
12334                    "right: {s}"
12335                );
12336                assert_eq!(former.closed, candidate.closed, "closed: {s}");
12337            }
12338            (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
12339            (former, candidate) => assert_eq!(
12340                former.is_ok(),
12341                candidate.is_ok(),
12342                "parse result mismatch for {s}: {former:?} != {candidate:?}"
12343            ),
12344        }
12345    }
12346
12347    #[inline(never)]
12348    fn measure_interval_parser_profile(
12349        parser: fn(&str) -> Result<Interval, super::TypeError>,
12350        inputs: &[&str],
12351        rounds: usize,
12352    ) -> u128 {
12353        use std::{hint::black_box, time::Instant};
12354
12355        let started = Instant::now();
12356        let mut checksum = 0_u64;
12357        for _ in 0..rounds {
12358            for input in inputs {
12359                let parsed = parser(black_box(input)).expect("profile input must parse");
12360                let closed = match parsed.closed {
12361                    IntervalClosed::Left => 1_u64,
12362                    IntervalClosed::Right => 2,
12363                    IntervalClosed::Both => 3,
12364                    IntervalClosed::Neither => 4,
12365                };
12366                checksum = checksum
12367                    .wrapping_add(parsed.left.to_bits().rotate_left(7))
12368                    .wrapping_add(parsed.right.to_bits().rotate_right(11))
12369                    .wrapping_add(closed);
12370                black_box(parsed);
12371            }
12372        }
12373        black_box(checksum);
12374        started.elapsed().as_nanos()
12375    }
12376
12377    #[test]
12378    #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
12379    fn profile_interval_parse_endpoint_split_ab_81jjv() {
12380        const VALID: [&str; 8] = [
12381            "[0, 1]",
12382            "(-0.0, 0.0]",
12383            " [ -1.5e3 , 2.75E-4 ) ",
12384            "(NaN, -0]",
12385            "[-inf, inf)",
12386            "[9.25, -7.5]",
12387            "(4.9406564584124654e-324, 1.7976931348623157e308)",
12388            "[-42, 17.125)",
12389        ];
12390        const INVALID: [&str; 12] = [
12391            "invalid",
12392            "[0]",
12393            "0, 1",
12394            "[0 1]",
12395            "[0, 1, 2]",
12396            "[0, 1,]",
12397            "[0,,1]",
12398            "[, 1]",
12399            "[0, ]",
12400            "{0, 1}",
12401            "[0, 1}",
12402            "  ⟦0, 1⟧  ",
12403        ];
12404        const ROUNDS: usize = 16_384;
12405        const SAMPLES: usize = 10;
12406
12407        for input in VALID.iter().chain(INVALID.iter()) {
12408            assert_interval_parse_profile_parity(input);
12409        }
12410        for _ in 0..2 {
12411            measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
12412            measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
12413        }
12414
12415        let mut former_ns = Vec::with_capacity(SAMPLES);
12416        let mut candidate_ns = Vec::with_capacity(SAMPLES);
12417        for sample in 0..SAMPLES {
12418            if sample % 2 == 0 {
12419                former_ns.push(measure_interval_parser_profile(
12420                    interval_parse_former_profile,
12421                    &VALID,
12422                    ROUNDS,
12423                ));
12424                candidate_ns.push(measure_interval_parser_profile(
12425                    interval_parse_split_once_profile,
12426                    &VALID,
12427                    ROUNDS,
12428                ));
12429            } else {
12430                candidate_ns.push(measure_interval_parser_profile(
12431                    interval_parse_split_once_profile,
12432                    &VALID,
12433                    ROUNDS,
12434                ));
12435                former_ns.push(measure_interval_parser_profile(
12436                    interval_parse_former_profile,
12437                    &VALID,
12438                    ROUNDS,
12439                ));
12440            }
12441        }
12442        former_ns.sort_unstable();
12443        candidate_ns.sort_unstable();
12444        let former_p50 = former_ns[SAMPLES / 2];
12445        let candidate_p50 = candidate_ns[SAMPLES / 2];
12446        let former_p95 = former_ns[SAMPLES - 1];
12447        let candidate_p95 = candidate_ns[SAMPLES - 1];
12448        println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
12449        println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
12450        println!(
12451            "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
12452            former_p50 as f64 / candidate_p50 as f64
12453        );
12454        println!(
12455            "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
12456            former_p95 as f64 / candidate_p95 as f64
12457        );
12458    }
12459}