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`, plus fill/drop helpers, plus
54//! the `nan*` aggregations ([`nansum`], [`nanmean`], [`nancount`],
55//! [`nanmin`], [`nanmax`], [`nanmedian`], [`nanvar`], [`nanstd`])
56//! that mirror pandas' missing-aware reductions.
57//!
58//! ⚠️ Only HALF that list is a module-level pandas surface. `pd.isna` and
59//! `pd.notna` are free functions; `pd.fillna` and `pd.dropna` do NOT exist
60//! (measured 2.2.3: `AttributeError` on the module) -- pandas exposes fill
61//! and drop only as METHODS, `Series.fillna` / `DataFrame.dropna`. The free
62//! fns here are an FP convenience, not a pandas mirror.
63//!
64//! ## Error reporting
65//!
66//! Errors are explicit enums via `thiserror`: [`TypeError`] for
67//! dtype-related failures (incompatible-cast, no-common-dtype) and
68//! [`TimedeltaError`] for parse failures.
69
70use serde::{Deserialize, Serialize};
71use thiserror::Error;
72
73#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
74#[serde(rename_all = "snake_case")]
75pub enum DType {
76    Null,
77    Bool,
78    /// Nullable boolean extension dtype. Matches pandas `BooleanDtype()`.
79    #[serde(rename = "boolean")]
80    BoolNullable,
81    Int64,
82    /// Nullable Int64 extension dtype. Matches pandas `Int64Dtype()` / `pd.NA`.
83    #[serde(rename = "Int64")]
84    Int64Nullable,
85    Float64,
86    /// Nullable Float64 extension dtype. Matches pandas `Float64Dtype()` / `pd.NA`.
87    ///
88    /// Distinct from [`DType::Float64`] the way `Int64Nullable` is distinct from
89    /// `Int64`: same 8-byte payload, different missing value. MEASURED, live
90    /// pandas 2.2.3 — a Float64 lane stores `pd.NA`, and it does so even when
91    /// the input was an explicit NaN:
92    ///
93    /// ```text
94    ///   pd.Series([1.5, None], dtype="Float64")[1]      -> <NA>   (is pd.NA)
95    ///   pd.Series([float("nan")], dtype="Float64")[0]   -> <NA>   COERCED
96    ///   pd.Series([1.5, None])[1]                       -> nan    (numpy)
97    /// ```
98    ///
99    /// which is why [`Scalar::missing_for_dtype`] gives this dtype
100    /// `NullKind::Null` and gives `Float64` `NullKind::NaN`.
101    ///
102    /// The serde spelling is pandas' spelling: `float64` is the numpy dtype and
103    /// `Float64` is the extension dtype, so this rename does NOT collide with
104    /// `Float64` — the enum is `rename_all = "snake_case"`, exactly as
105    /// `Int64Nullable`/`Int64` already are. (br-frankenpandas-qkqfb)
106    #[serde(rename = "Float64")]
107    Float64Nullable,
108    #[serde(alias = "string", alias = "str")]
109    Utf8,
110    Categorical,
111    Timedelta64,
112    /// Nanosecond-precision datetime since Unix epoch.
113    ///
114    /// A timezone is metadata shared by the whole column; values remain UTC
115    /// nanoseconds in the contiguous datetime buffer.
116    Datetime64 {
117        #[serde(default, skip_serializing_if = "Option::is_none")]
118        tz: Option<String>,
119    },
120    /// Period ordinal. Matches pandas `period[freq]`. Stores ordinal + frequency code.
121    Period,
122    /// Numeric interval value. Matches pandas `interval[float64]`.
123    Interval,
124    Sparse,
125}
126
127impl DType {
128    /// Returns true if the dtype is numeric (integer or floating point).
129    #[must_use]
130    pub const fn is_numeric(&self) -> bool {
131        matches!(
132            self,
133            Self::Int64 | Self::Int64Nullable | Self::Float64 | Self::Float64Nullable
134        )
135    }
136
137    /// Returns true if the dtype is an integer type.
138    #[must_use]
139    pub const fn is_integer(&self) -> bool {
140        matches!(self, Self::Int64 | Self::Int64Nullable)
141    }
142
143    /// Returns true if the dtype is a floating point type.
144    #[must_use]
145    pub const fn is_floating(&self) -> bool {
146        matches!(self, Self::Float64 | Self::Float64Nullable)
147    }
148
149    /// Returns true if the dtype is boolean.
150    #[must_use]
151    pub const fn is_bool(&self) -> bool {
152        matches!(self, Self::Bool | Self::BoolNullable)
153    }
154
155    /// Returns true if the dtype is object/string type.
156    #[must_use]
157    pub const fn is_object(&self) -> bool {
158        matches!(self, Self::Utf8)
159    }
160
161    /// Returns true if the dtype is datetime.
162    #[must_use]
163    pub const fn is_datetime(&self) -> bool {
164        matches!(self, Self::Datetime64 { .. })
165    }
166
167    /// Returns true if the dtype is timedelta.
168    #[must_use]
169    pub const fn is_timedelta(&self) -> bool {
170        matches!(self, Self::Timedelta64)
171    }
172
173    /// Returns true if the dtype is categorical.
174    #[must_use]
175    pub const fn is_categorical(&self) -> bool {
176        matches!(self, Self::Categorical)
177    }
178
179    /// Returns true if the dtype is sparse.
180    #[must_use]
181    pub const fn is_sparse(&self) -> bool {
182        matches!(self, Self::Sparse)
183    }
184
185    /// Returns true if the dtype is period.
186    #[must_use]
187    pub const fn is_period(&self) -> bool {
188        matches!(self, Self::Period)
189    }
190
191    /// Returns true if the dtype is interval.
192    #[must_use]
193    pub const fn is_interval(&self) -> bool {
194        matches!(self, Self::Interval)
195    }
196
197    /// Return the dtype name as a string.
198    ///
199    /// Matches numpy dtype.name property.
200    #[must_use]
201    pub const fn name(&self) -> &'static str {
202        match self {
203            Self::Bool => "bool",
204            Self::BoolNullable => "boolean",
205            Self::Int64 => "int64",
206            Self::Int64Nullable => "Int64",
207            Self::Float64 => "float64",
208            // MEASURED: str(pd.Float64Dtype()) == "Float64", the same
209            // capital-letter convention as Int64/boolean.
210            Self::Float64Nullable => "Float64",
211            Self::Utf8 => "object",
212            Self::Datetime64 { .. } => "datetime64[ns]",
213            Self::Timedelta64 => "timedelta64[ns]",
214            Self::Categorical => "category",
215            Self::Period => "period",
216            Self::Interval => "interval",
217            Self::Sparse => "Sparse",
218            Self::Null => "object",
219        }
220    }
221
222    /// Return the dtype kind character.
223    ///
224    /// Matches numpy dtype.kind property.
225    #[must_use]
226    pub const fn kind(&self) -> char {
227        match self {
228            Self::Bool | Self::BoolNullable => 'b',
229            Self::Int64 | Self::Int64Nullable => 'i',
230            // MEASURED: pd.Float64Dtype().kind == 'f', matching numpy float64 —
231            // the extension dtype reports its underlying kind, exactly as
232            // Int64Nullable reports 'i'.
233            Self::Float64 | Self::Float64Nullable => 'f',
234            Self::Utf8 => 'O',
235            Self::Datetime64 { .. } => 'M',
236            Self::Timedelta64 => 'm',
237            Self::Categorical => 'O',
238            Self::Period => 'O',
239            Self::Interval => 'O',
240            Self::Sparse => 'O',
241            Self::Null => 'O',
242        }
243    }
244
245    /// Return the dtype itemsize in bytes.
246    ///
247    /// Matches numpy dtype.itemsize property.
248    #[must_use]
249    pub const fn itemsize(&self) -> usize {
250        match self {
251            Self::Bool | Self::BoolNullable => 1,
252            Self::Int64
253            | Self::Int64Nullable
254            | Self::Float64
255            | Self::Float64Nullable
256            | Self::Datetime64 { .. }
257            | Self::Timedelta64
258            | Self::Period => 8,
259            Self::Utf8 | Self::Categorical | Self::Interval | Self::Sparse | Self::Null => 8,
260        }
261    }
262
263    /// Returns true if this is an extension dtype (categorical, sparse, period, interval, nullable).
264    ///
265    /// Matches `pd.api.types.is_extension_array_dtype()`.
266    #[must_use]
267    pub const fn is_extension(&self) -> bool {
268        matches!(
269            self,
270            Self::Categorical
271                | Self::Sparse
272                | Self::Period
273                | Self::Interval
274                | Self::Int64Nullable
275                | Self::Float64Nullable
276                | Self::BoolNullable
277        )
278    }
279
280    /// Returns true if this is a nullable extension dtype (Int64, boolean).
281    ///
282    /// Nullable extension dtypes preserve their dtype when nulls are introduced,
283    /// unlike numpy dtypes which promote to float64.
284    #[must_use]
285    pub const fn is_nullable(&self) -> bool {
286        matches!(
287            self,
288            Self::Int64Nullable | Self::Float64Nullable | Self::BoolNullable
289        )
290    }
291
292    /// Returns the non-nullable equivalent dtype.
293    ///
294    /// For nullable extension dtypes, returns the numpy equivalent.
295    /// For non-nullable dtypes, returns self.
296    #[must_use]
297    pub fn to_non_nullable(&self) -> Self {
298        match self {
299            Self::Int64Nullable => Self::Int64,
300            Self::Float64Nullable => Self::Float64,
301            Self::BoolNullable => Self::Bool,
302            other => other.clone(),
303        }
304    }
305
306    /// Returns the nullable equivalent dtype.
307    ///
308    /// For numpy int64/bool, returns the nullable extension dtype.
309    /// For already-nullable or other dtypes, returns self.
310    #[must_use]
311    pub fn to_nullable(&self) -> Self {
312        match self {
313            Self::Int64 => Self::Int64Nullable,
314            Self::Float64 => Self::Float64Nullable,
315            Self::Bool => Self::BoolNullable,
316            other => other.clone(),
317        }
318    }
319
320    /// Returns true if this is a signed integer type.
321    ///
322    /// Matches `pd.api.types.is_signed_integer_dtype()`.
323    #[must_use]
324    pub const fn is_signed_integer(&self) -> bool {
325        matches!(self, Self::Int64 | Self::Int64Nullable)
326    }
327
328    /// Returns true for the Utf8 dtype.
329    ///
330    /// ⚠️ NARROWER THAN `pd.api.types.is_string_dtype()`, which the old wording
331    /// ("string/object dtype") papered over. MEASURED, live pandas 2.2.3
332    /// (CrimsonPine 2026-08-19):
333    /// ```text
334    ///   Series(['a','b'])                        object    is_string_dtype TRUE
335    ///   Series([1,2], dtype=object)              object    is_string_dtype FALSE
336    ///   Series(Categorical(['a','b']))           category  is_string_dtype TRUE
337    ///   Series(['a','b'], dtype='string')        string    is_string_dtype TRUE
338    ///   Series([1,2])                            int64     is_string_dtype FALSE
339    /// ```
340    /// So pandas is NOT testing "object dtype": an object column holding ints is
341    /// FALSE, and a CATEGORICAL column is TRUE. This returns true only for `Utf8`,
342    /// which means it disagrees with pandas on a categorical-of-strings.
343    ///
344    /// Left as-is rather than widened: making this true for `Categorical`
345    /// unconditionally would be wrong for a categorical of non-strings, and this
346    /// enum carries no element type for its categories to test.
347    #[must_use]
348    pub const fn is_string_dtype(&self) -> bool {
349        matches!(self, Self::Utf8)
350    }
351
352    /// Returns true for any real numeric dtype (integer or float).
353    ///
354    /// Matches `pd.api.types.is_any_real_numeric_dtype()`.
355    #[must_use]
356    pub const fn is_any_real_numeric(&self) -> bool {
357        self.is_numeric()
358    }
359
360    /// Returns true for datetime-like dtypes (datetime, timedelta, period).
361    ///
362    /// Matches `pd.api.types.is_datetime64_any_dtype()` family.
363    #[must_use]
364    pub const fn is_datetime_like(&self) -> bool {
365        matches!(
366            self,
367            Self::Datetime64 { .. } | Self::Timedelta64 | Self::Period
368        )
369    }
370
371    /// Return the numpy dtype character code.
372    ///
373    /// Matches numpy dtype.char property.
374    #[must_use]
375    pub const fn char(&self) -> char {
376        match self {
377            Self::Bool | Self::BoolNullable => '?',
378            Self::Int64 | Self::Int64Nullable => 'l',
379            Self::Float64 | Self::Float64Nullable => 'd',
380            Self::Utf8 => 'O',
381            Self::Datetime64 { .. } => 'M',
382            Self::Timedelta64 => 'm',
383            Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => 'O',
384        }
385    }
386
387    /// Return the numpy type number.
388    ///
389    /// Matches numpy dtype.num property.
390    #[must_use]
391    pub const fn num(&self) -> i32 {
392        match self {
393            Self::Bool | Self::BoolNullable => 0,
394            Self::Int64 | Self::Int64Nullable => 7,
395            Self::Float64 | Self::Float64Nullable => 12,
396            Self::Utf8 => 17,
397            Self::Datetime64 { .. } => 21,
398            Self::Timedelta64 => 22,
399            Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => 17,
400        }
401    }
402
403    /// Return the byte order character.
404    ///
405    /// Matches numpy dtype.byteorder property. Returns '=' (native) for all types.
406    #[must_use]
407    pub const fn byteorder(&self) -> char {
408        '='
409    }
410
411    /// Return the numpy dtype string representation.
412    ///
413    /// Matches numpy dtype.str property.
414    #[must_use]
415    pub const fn str_repr(&self) -> &'static str {
416        match self {
417            Self::Bool | Self::BoolNullable => "|b1",
418            Self::Int64 | Self::Int64Nullable => "<i8",
419            Self::Float64 | Self::Float64Nullable => "<f8",
420            Self::Utf8 => "|O8",
421            Self::Datetime64 { .. } => "<M8[ns]",
422            Self::Timedelta64 => "<m8[ns]",
423            Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => "|O8",
424        }
425    }
426
427    /// Construct pandas' timezone-naive `datetime64[ns]` dtype.
428    #[must_use]
429    pub const fn datetime64_naive() -> Self {
430        Self::Datetime64 { tz: None }
431    }
432
433    /// Construct a timezone-aware `datetime64[ns, tz]` dtype.
434    #[must_use]
435    pub fn datetime64_tz(tz: impl Into<String>) -> Self {
436        Self::Datetime64 {
437            tz: Some(tz.into()),
438        }
439    }
440
441    /// Return the column-level timezone carried by a datetime dtype.
442    #[must_use]
443    pub fn timezone(&self) -> Option<&str> {
444        match self {
445            Self::Datetime64 { tz } => tz.as_deref(),
446            _ => None,
447        }
448    }
449
450    /// Render the pandas dtype spelling, including a timezone when present.
451    #[must_use]
452    pub fn display_name(&self) -> String {
453        match self {
454            Self::Datetime64 { tz: Some(tz) } => format!("datetime64[ns, {tz}]"),
455            _ => self.name().to_owned(),
456        }
457    }
458}
459
460impl std::str::FromStr for DType {
461    type Err = TypeError;
462
463    fn from_str(s: &str) -> Result<Self, Self::Err> {
464        let trimmed = s.trim();
465        match trimmed {
466            "int64" | "int" | "i8" | "integer" | "<i8" => Ok(Self::Int64),
467            "Int64" | "Int64Dtype" => Ok(Self::Int64Nullable),
468            "float64" | "float" | "f8" | "floating" | "<f8" => Ok(Self::Float64),
469            "Float64" | "Float64Dtype" => Ok(Self::Float64Nullable),
470            "bool" | "|b1" => Ok(Self::Bool),
471            "boolean" | "BooleanDtype" => Ok(Self::BoolNullable),
472            "string" | "str" | "object" | "utf8" | "Utf8" | "O" | "|O8" => Ok(Self::Utf8),
473            "category" | "categorical" | "CategoricalDtype" => Ok(Self::Categorical),
474            "timedelta64" | "timedelta64[ns]" | "timedelta" | "Timedelta" | "<m8[ns]" => {
475                Ok(Self::Timedelta64)
476            }
477            "period" | "Period" => Ok(Self::Period),
478            "interval" | "Interval" => Ok(Self::Interval),
479            "sparse" | "Sparse" => Ok(Self::Sparse),
480            "null" | "Null" => Ok(Self::Null),
481            _ if trimmed.starts_with("period[") || trimmed.starts_with("Period[") => {
482                Ok(Self::Period)
483            }
484            _ if trimmed.starts_with("interval[") || trimmed.starts_with("Interval[") => {
485                Ok(Self::Interval)
486            }
487            _ if trimmed.starts_with("sparse[") || trimmed.starts_with("Sparse[") => {
488                Ok(Self::Sparse)
489            }
490            _ if trimmed.starts_with("datetime64")
491                || trimmed.starts_with("datetime")
492                || trimmed.starts_with("<M8") =>
493            {
494                if let Some(idx) = trimmed.find(',') {
495                    let tz_part = if let Some(rest) = trimmed.get(idx + 1..) {
496                        rest.trim().trim_end_matches(']').trim().to_string()
497                    } else {
498                        String::new()
499                    };
500                    Ok(Self::Datetime64 { tz: Some(tz_part) })
501                } else {
502                    Ok(Self::Datetime64 { tz: None })
503                }
504            }
505            _ => Err(TypeError::ValueNotParseable {
506                value: s.to_string(),
507                target: "DType".to_string(),
508            }),
509        }
510    }
511}
512
513impl std::fmt::Display for DType {
514    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515        write!(f, "{}", self.display_name())
516    }
517}
518
519/// A numpy numeric dtype narrower than the 64-bit storage a column keeps its
520/// values in: pandas' int8 / int16 / int32, uint8 / uint16 / uint32 / uint64
521/// and float32, and over a nullable column the masked Int8 ... UInt64 /
522/// Float32 (fvsao.23).
523///
524/// The values stay in the Int64 / Float64 storage (or its nullable form);
525/// the width is the dtype pandas reports and confines the values: an integer
526/// width holds only values in its range (a cast or arithmetic wraps into it,
527/// as numpy does: `astype('int8')` of 300 is 44), float32 only values exactly
528/// representable as an `f32` (every result is rounded to the nearest `f32`,
529/// which for `+ - * /` and `sqrt` is what float32 arithmetic gives: binary64
530/// carries more than 2 * 24 + 2 significand bits, so rounding twice cannot
531/// land elsewhere).
532///
533/// uint64 holds only values below 2**63 in that storage: a larger one would
534/// be its negative two's-complement pattern, which every path that does not
535/// know the width reads as the negative number, so it is refused instead.
536#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
537pub enum NumericWidth {
538    #[serde(rename = "int8")]
539    Int8,
540    #[serde(rename = "int16")]
541    Int16,
542    #[serde(rename = "int32")]
543    Int32,
544    #[serde(rename = "uint8")]
545    UInt8,
546    #[serde(rename = "uint16")]
547    UInt16,
548    #[serde(rename = "uint32")]
549    UInt32,
550    #[serde(rename = "uint64")]
551    UInt64,
552    #[serde(rename = "float32")]
553    Float32,
554}
555
556impl NumericWidth {
557    /// Every width, integers first.
558    pub const ALL: [Self; 8] = [
559        Self::Int8,
560        Self::Int16,
561        Self::Int32,
562        Self::UInt8,
563        Self::UInt16,
564        Self::UInt32,
565        Self::UInt64,
566        Self::Float32,
567    ];
568
569    /// pandas' dtype name: numpy's (`int32`) over a numpy column, the masked
570    /// extension dtype's (`Int32`, `UInt8`, `Float32`) over a nullable one.
571    #[must_use]
572    pub const fn name(self, nullable: bool) -> &'static str {
573        match (self, nullable) {
574            (Self::Int8, false) => "int8",
575            (Self::Int16, false) => "int16",
576            (Self::Int32, false) => "int32",
577            (Self::UInt8, false) => "uint8",
578            (Self::UInt16, false) => "uint16",
579            (Self::UInt32, false) => "uint32",
580            (Self::UInt64, false) => "uint64",
581            (Self::Float32, false) => "float32",
582            (Self::Int8, true) => "Int8",
583            (Self::Int16, true) => "Int16",
584            (Self::Int32, true) => "Int32",
585            (Self::UInt8, true) => "UInt8",
586            (Self::UInt16, true) => "UInt16",
587            (Self::UInt32, true) => "UInt32",
588            (Self::UInt64, true) => "UInt64",
589            (Self::Float32, true) => "Float32",
590        }
591    }
592
593    /// The width and whether it is the masked (nullable) dtype, for a pandas
594    /// or numpy dtype name: `int32` / `i4` / `<i4`, `Int32` / `Int32Dtype`,
595    /// `float32` / `f4` / `single`, ... `None` for any other name, the 64-bit
596    /// ones included (those are [`DType`]'s).
597    #[must_use]
598    pub fn parse(name: &str) -> Option<(Self, bool)> {
599        let name = name.trim();
600        let name = name
601            .strip_prefix('<')
602            .or_else(|| name.strip_prefix('|'))
603            .or_else(|| name.strip_prefix('='))
604            .unwrap_or(name);
605        let found = match name {
606            "int8" | "i1" | "byte" => (Self::Int8, false),
607            "int16" | "i2" | "short" => (Self::Int16, false),
608            "int32" | "i4" | "intc" => (Self::Int32, false),
609            "uint8" | "u1" | "ubyte" => (Self::UInt8, false),
610            "uint16" | "u2" | "ushort" => (Self::UInt16, false),
611            "uint32" | "u4" | "uintc" => (Self::UInt32, false),
612            "uint64" | "u8" | "uint" | "ulonglong" | "uintp" => (Self::UInt64, false),
613            "float32" | "f4" | "single" => (Self::Float32, false),
614            "Int8" | "Int8Dtype" => (Self::Int8, true),
615            "Int16" | "Int16Dtype" => (Self::Int16, true),
616            "Int32" | "Int32Dtype" => (Self::Int32, true),
617            "UInt8" | "UInt8Dtype" => (Self::UInt8, true),
618            "UInt16" | "UInt16Dtype" => (Self::UInt16, true),
619            "UInt32" | "UInt32Dtype" => (Self::UInt32, true),
620            "UInt64" | "UInt64Dtype" => (Self::UInt64, true),
621            "Float32" | "Float32Dtype" => (Self::Float32, true),
622            _ => return None,
623        };
624        Some(found)
625    }
626
627    /// The storage dtype a column of this width keeps its values in.
628    #[must_use]
629    pub const fn storage(self, nullable: bool) -> DType {
630        match (self.is_float(), nullable) {
631            (true, false) => DType::Float64,
632            (true, true) => DType::Float64Nullable,
633            (false, false) => DType::Int64,
634            (false, true) => DType::Int64Nullable,
635        }
636    }
637
638    /// Whether a column of `dtype` can carry this width: an integer width
639    /// over Int64 / Int64Nullable, float32 over Float64 / Float64Nullable.
640    #[must_use]
641    pub const fn fits_storage(self, dtype: &DType) -> bool {
642        if self.is_float() {
643            matches!(dtype, DType::Float64 | DType::Float64Nullable)
644        } else {
645            matches!(dtype, DType::Int64 | DType::Int64Nullable)
646        }
647    }
648
649    /// numpy's `itemsize`: bytes per element.
650    #[must_use]
651    pub const fn itemsize(self) -> usize {
652        match self {
653            Self::Int8 | Self::UInt8 => 1,
654            Self::Int16 | Self::UInt16 => 2,
655            Self::Int32 | Self::UInt32 | Self::Float32 => 4,
656            Self::UInt64 => 8,
657        }
658    }
659
660    /// numpy's `kind`: `'i'`, `'u'` or `'f'`.
661    #[must_use]
662    pub const fn kind(self) -> char {
663        match self {
664            Self::Int8 | Self::Int16 | Self::Int32 => 'i',
665            Self::UInt8 | Self::UInt16 | Self::UInt32 | Self::UInt64 => 'u',
666            Self::Float32 => 'f',
667        }
668    }
669
670    #[must_use]
671    pub const fn is_float(self) -> bool {
672        matches!(self, Self::Float32)
673    }
674
675    #[must_use]
676    pub const fn is_unsigned(self) -> bool {
677        matches!(
678            self,
679            Self::UInt8 | Self::UInt16 | Self::UInt32 | Self::UInt64
680        )
681    }
682
683    /// The smallest and largest value an integer width holds in the Int64
684    /// storage (uint64's largest is `i64::MAX`, see the type's doc); `None`
685    /// for float32.
686    #[must_use]
687    pub const fn int_bounds(self) -> Option<(i64, i64)> {
688        match self {
689            Self::Int8 => Some((i8::MIN as i64, i8::MAX as i64)),
690            Self::Int16 => Some((i16::MIN as i64, i16::MAX as i64)),
691            Self::Int32 => Some((i32::MIN as i64, i32::MAX as i64)),
692            Self::UInt8 => Some((0, u8::MAX as i64)),
693            Self::UInt16 => Some((0, u16::MAX as i64)),
694            Self::UInt32 => Some((0, u32::MAX as i64)),
695            Self::UInt64 => Some((0, i64::MAX)),
696            Self::Float32 => None,
697        }
698    }
699
700    /// Whether an integer width holds `value` unchanged.
701    #[must_use]
702    pub const fn holds_int(self, value: i64) -> bool {
703        match self.int_bounds() {
704            Some((low, high)) => low <= value && value <= high,
705            None => false,
706        }
707    }
708
709    /// `value` wrapped into an integer width as numpy's casts and integer
710    /// arithmetic wrap it (modulo 2**bits, two's complement): int8 of 300 is
711    /// 44, uint8 of -5 is 251. Any wrapping i64 result reduces to the right
712    /// one, since 2**bits divides 2**64. `None` for float32, and for a uint64
713    /// result at or above 2**63 (not held; see the type's doc).
714    #[must_use]
715    pub const fn wrap_int(self, value: i64) -> Option<i64> {
716        match self {
717            Self::Int8 => Some(value as i8 as i64),
718            Self::Int16 => Some(value as i16 as i64),
719            Self::Int32 => Some(value as i32 as i64),
720            Self::UInt8 => Some(value as u8 as i64),
721            Self::UInt16 => Some(value as u16 as i64),
722            Self::UInt32 => Some(value as u32 as i64),
723            Self::UInt64 if value >= 0 => Some(value),
724            Self::UInt64 | Self::Float32 => None,
725        }
726    }
727
728    /// `value` rounded to the nearest `f32` (ties to even), as a float32
729    /// column holds it: 0.1 is 0.10000000149011612. NaN and infinities stay;
730    /// a finite value beyond `f32::MAX` becomes an infinity, as numpy's cast.
731    #[must_use]
732    #[allow(clippy::cast_possible_truncation)]
733    pub fn round_f32(value: f64) -> f64 {
734        f64::from(value as f32)
735    }
736
737    /// The smallest signed integer width holding every value in
738    /// `low..=high`, or `None` when only int64 does (`to_numeric(...,
739    /// downcast='integer')`).
740    #[must_use]
741    pub const fn smallest_signed(low: i64, high: i64) -> Option<Self> {
742        if low >= i8::MIN as i64 && high <= i8::MAX as i64 {
743            Some(Self::Int8)
744        } else if low >= i16::MIN as i64 && high <= i16::MAX as i64 {
745            Some(Self::Int16)
746        } else if low >= i32::MIN as i64 && high <= i32::MAX as i64 {
747            Some(Self::Int32)
748        } else {
749            None
750        }
751    }
752
753    /// The smallest unsigned integer width holding every value in
754    /// `low..=high`, or `None` when a value is negative
755    /// (`downcast='unsigned'`).
756    #[must_use]
757    pub const fn smallest_unsigned(low: i64, high: i64) -> Option<Self> {
758        if low < 0 {
759            None
760        } else if high <= u8::MAX as i64 {
761            Some(Self::UInt8)
762        } else if high <= u16::MAX as i64 {
763            Some(Self::UInt16)
764        } else if high <= u32::MAX as i64 {
765            Some(Self::UInt32)
766        } else {
767            Some(Self::UInt64)
768        }
769    }
770
771    /// pandas' dtype for the codes of a categorical with `categories`
772    /// categories: the smallest signed width whose maximum exceeds the
773    /// count (codes run -1 .. count - 1; `coerce_indexer_dtype`), so 126
774    /// categories are int8 and 127 are int16. `None` means int64.
775    #[must_use]
776    pub const fn for_category_codes(categories: usize) -> Option<Self> {
777        if categories < i8::MAX as usize {
778            Some(Self::Int8)
779        } else if categories < i16::MAX as usize {
780            Some(Self::Int16)
781        } else if categories < i32::MAX as usize {
782            Some(Self::Int32)
783        } else {
784            None
785        }
786    }
787}
788
789/// numpy's `pairwise_sum`, the kernel of its float `add.reduce` over a
790/// contiguous run, every addition in `T`: below 8 values a running sum from
791/// 0; up to 128, eight running sums seeded with the first eight values and
792/// stepped over the 8-value blocks, folded as
793/// `((r0 + r1) + (r2 + r3)) + ((r4 + r5) + (r6 + r7))`, then the remainder in
794/// order; beyond that the two halves (the first a multiple of 8 long) summed
795/// apart. pandas' float32 and float64 sums are it bit for bit, where a sum
796/// rounded once or added left to right differs in the last place (fvsao.23,
797/// br-frankenpandas-9iim6).
798#[must_use]
799pub fn numpy_pairwise_sum<T>(values: &[T]) -> T
800where
801    T: Copy + Default + std::ops::Add<Output = T>,
802{
803    // The same split as `pairwise_range`, over the slice itself (no copy).
804    if values.len() <= PAIRWISE_BLOCK {
805        return pairwise_block(values);
806    }
807    let mut half = values.len() / 2;
808    half -= half % 8;
809    numpy_pairwise_sum(&values[..half]) + numpy_pairwise_sum(&values[half..])
810}
811
812/// numpy's `PW_BLOCKSIZE`: runs this long or shorter are summed directly.
813const PAIRWISE_BLOCK: usize = 128;
814
815/// [`numpy_pairwise_sum`] over `len` values that numpy reads from one array
816/// but fp holds in another shape (a cast, chunks, missing slots as 0):
817/// `fill(start, block)` writes values `start..start + block.len()` into each
818/// block, at most 128 long, the blocks asked for left to right.
819pub fn numpy_pairwise_sum_by<T, F>(len: usize, fill: &F) -> T
820where
821    T: Copy + Default + std::ops::Add<Output = T>,
822    F: Fn(usize, &mut [T]),
823{
824    pairwise_range(0, len, fill)
825}
826
827/// Values `start..start + len` of [`numpy_pairwise_sum_by`].
828fn pairwise_range<T, F>(start: usize, len: usize, fill: &F) -> T
829where
830    T: Copy + Default + std::ops::Add<Output = T>,
831    F: Fn(usize, &mut [T]),
832{
833    if len <= PAIRWISE_BLOCK {
834        let mut buffer = [T::default(); PAIRWISE_BLOCK];
835        let block = &mut buffer[..len];
836        fill(start, block);
837        return pairwise_block(block);
838    }
839    let mut half = len / 2;
840    half -= half % 8;
841    pairwise_range(start, half, fill) + pairwise_range(start + half, len - half, fill)
842}
843
844/// [`numpy_pairwise_sum`] of `term(value)` over `values`, each term made
845/// where it is added.
846fn numpy_pairwise_sum_of<T, F>(values: &[f64], term: &F) -> T
847where
848    T: Copy + Default + std::ops::Add<Output = T>,
849    F: Fn(f64) -> T,
850{
851    if values.len() > PAIRWISE_BLOCK {
852        let mut half = values.len() / 2;
853        half -= half % 8;
854        return numpy_pairwise_sum_of(&values[..half], term)
855            + numpy_pairwise_sum_of(&values[half..], term);
856    }
857    let n = values.len();
858    if n < 8 {
859        return values
860            .iter()
861            .fold(T::default(), |acc, &value| acc + term(value));
862    }
863    let mut sums: [T; 8] = std::array::from_fn(|lane| term(values[lane]));
864    let whole = n - n % 8;
865    for block in values[8..whole].as_chunks::<8>().0 {
866        for (sum, &value) in sums.iter_mut().zip(block) {
867            *sum = *sum + term(value);
868        }
869    }
870    let folded =
871        ((sums[0] + sums[1]) + (sums[2] + sums[3])) + ((sums[4] + sums[5]) + (sums[6] + sums[7]));
872    values[whole..]
873        .iter()
874        .fold(folded, |acc, &value| acc + term(value))
875}
876
877/// numpy's pairwise sum of at most 128 contiguous values.
878fn pairwise_block<T>(values: &[T]) -> T
879where
880    T: Copy + Default + std::ops::Add<Output = T>,
881{
882    let n = values.len();
883    if n < 8 {
884        return values.iter().fold(T::default(), |acc, &value| acc + value);
885    }
886    let mut sums = [T::default(); 8];
887    sums.copy_from_slice(&values[..8]);
888    let whole = n - n % 8;
889    for block in values[8..whole].as_chunks::<8>().0 {
890        for (sum, &value) in sums.iter_mut().zip(block) {
891            *sum = *sum + value;
892        }
893    }
894    let folded =
895        ((sums[0] + sums[1]) + (sums[2] + sums[3])) + ((sums[4] + sums[5]) + (sums[6] + sums[7]));
896    values[whole..]
897        .iter()
898        .fold(folded, |acc, &value| acc + value)
899}
900
901/// A numeric column's values as pandas' float reductions read them: one
902/// buffer or the chunks of one (a `concat` result), float64 or a numpy int64
903/// array (read through numpy's int64 -> float64 cast; ints that pandas holds
904/// as float64 because one is missing are `Float`).
905#[derive(Debug, Clone, Copy)]
906pub enum ReductionValues<'a> {
907    Float(&'a [f64]),
908    Int(&'a [i64]),
909    FloatChunks(&'a [&'a [f64]]),
910    IntChunks(&'a [&'a [i64]]),
911}
912
913impl ReductionValues<'_> {
914    fn len(self) -> usize {
915        match self {
916            Self::Float(values) => values.len(),
917            Self::Int(values) => values.len(),
918            Self::FloatChunks(chunks) => chunks.iter().map(|chunk| chunk.len()).sum(),
919            Self::IntChunks(chunks) => chunks.iter().map(|chunk| chunk.len()).sum(),
920        }
921    }
922}
923
924/// Reads [`ReductionValues`] block by block, left to right (a chunked
925/// column's cursor only moves forward).
926struct ValueReader<'a> {
927    values: ReductionValues<'a>,
928    /// The chunk the last block started in and that chunk's first position.
929    cursor: std::cell::Cell<(usize, usize)>,
930}
931
932impl<'a> ValueReader<'a> {
933    fn new(values: ReductionValues<'a>) -> Self {
934        Self {
935            values,
936            cursor: std::cell::Cell::new((0, 0)),
937        }
938    }
939
940    /// Values `start..start + block.len()` as float64.
941    #[allow(clippy::cast_precision_loss)] // numpy's int64 -> float64 cast
942    fn read(&self, start: usize, block: &mut [f64]) {
943        match self.values {
944            ReductionValues::Float(values) => {
945                block.copy_from_slice(&values[start..start + block.len()]);
946            }
947            ReductionValues::Int(values) => {
948                for (slot, &value) in block.iter_mut().zip(&values[start..]) {
949                    *slot = value as f64;
950                }
951            }
952            ReductionValues::FloatChunks(chunks) => {
953                self.read_chunks(chunks, start, block, |slots, values| {
954                    slots.copy_from_slice(values);
955                });
956            }
957            ReductionValues::IntChunks(chunks) => {
958                self.read_chunks(chunks, start, block, |slots, values| {
959                    for (slot, &value) in slots.iter_mut().zip(values) {
960                        *slot = value as f64;
961                    }
962                });
963            }
964        }
965    }
966
967    fn read_chunks<T>(
968        &self,
969        chunks: &[&[T]],
970        start: usize,
971        block: &mut [f64],
972        copy: impl Fn(&mut [f64], &[T]),
973    ) {
974        let (mut chunk, mut chunk_start) = self.cursor.get();
975        if start < chunk_start {
976            (chunk, chunk_start) = (0, 0);
977        }
978        while start >= chunk_start + chunks[chunk].len() {
979            chunk_start += chunks[chunk].len();
980            chunk += 1;
981        }
982        self.cursor.set((chunk, chunk_start));
983        let mut filled = 0;
984        while filled < block.len() {
985            let offset = start + filled - chunk_start;
986            let take = (chunks[chunk].len() - offset).min(block.len() - filled);
987            copy(
988                &mut block[filled..filled + take],
989                &chunks[chunk][offset..offset + take],
990            );
991            filled += take;
992            if filled < block.len() {
993                chunk_start += chunks[chunk].len();
994                chunk += 1;
995            }
996        }
997    }
998}
999
1000/// How pandas holds a column's missing values, which decides the order its
1001/// float reductions add in (br-frankenpandas-9iim6).
1002#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1003pub enum MissingLayout {
1004    /// A numpy float64 / int64 array: pandas' nanops fill the missing (NaN,
1005    /// NaT) slots with 0 in place and sum the whole array, every pairwise
1006    /// block keeping its position.
1007    Numpy,
1008    /// A masked (nullable `Float64` / `Int64`) array: numpy adds each run of
1009    /// present values onto a running total (`add.reduce(where=)`).
1010    Masked,
1011}
1012
1013/// numpy's buffer for a casting reduction: an int64 array summed as float64
1014/// is cast, and summed, 8192 values at a time.
1015const NUMPY_CAST_BUFFER: usize = 8192;
1016
1017/// pandas' float reductions of one numeric column - `sum`, `mean`, `var`,
1018/// `std`, `sem`, `skew`, `kurt` - adding in numpy's exact order, so a long
1019/// column answers pandas' bits rather than a nearby value. Measured against
1020/// live pandas 2.2.3 / numpy 2.3.5; bead br-frankenpandas-9iim6 holds the
1021/// model and the alternatives it rejected.
1022#[derive(Debug, Clone, Copy)]
1023pub struct PandasReductions<'a> {
1024    values: ReductionValues<'a>,
1025    /// Packed presence bits, bit `i % 64` of word `i / 64` for slot `i`;
1026    /// `None` when every slot is present.
1027    present: Option<&'a [u64]>,
1028    /// The float values' NaNs are the missing slots (and some value is one).
1029    nan_missing: bool,
1030    layout: MissingLayout,
1031    len: usize,
1032    count: usize,
1033    /// The float total, when the count's sweep already added it.
1034    total: Option<f64>,
1035}
1036
1037impl<'a> PandasReductions<'a> {
1038    /// A numpy float64 array, its NaNs the missing values (nanops' mask is
1039    /// `isnan`); read without a presence bitmap.
1040    #[must_use]
1041    pub fn numpy_nan_missing(values: ReductionValues<'a>) -> Self {
1042        let len = values.len();
1043        let mut reductions = Self {
1044            values,
1045            present: None,
1046            nan_missing: true,
1047            layout: MissingLayout::Numpy,
1048            len,
1049            count: len,
1050            total: None,
1051        };
1052        if let ReductionValues::Float(_) | ReductionValues::FloatChunks(_) = values {
1053            // One sweep counts the values and adds them, NaN as 0 in place.
1054            let SumPair(total, count) = reductions.add_reduce(|value| SumPair(value, 1), false);
1055            reductions.count = count;
1056            reductions.total = Some(total);
1057        }
1058        reductions.nan_missing = reductions.count < len;
1059        reductions
1060    }
1061
1062    /// `present` is the packed presence bits (`None`: all present).
1063    #[must_use]
1064    pub fn new(
1065        values: ReductionValues<'a>,
1066        present: Option<&'a [u64]>,
1067        layout: MissingLayout,
1068    ) -> Self {
1069        let len = values.len();
1070        let count = present.map_or(len, |words| {
1071            let whole: usize = words[..len / 64]
1072                .iter()
1073                .map(|word| word.count_ones() as usize)
1074                .sum();
1075            let tail = len % 64;
1076            whole
1077                + if tail == 0 {
1078                    0
1079                } else {
1080                    (words[len / 64] & ((1_u64 << tail) - 1)).count_ones() as usize
1081                }
1082        });
1083        Self {
1084            values,
1085            present: present.filter(|_| count < len),
1086            nan_missing: false,
1087            layout,
1088            len,
1089            count,
1090            total: None,
1091        }
1092    }
1093
1094    /// The present values.
1095    #[must_use]
1096    pub fn count(&self) -> usize {
1097        self.count
1098    }
1099
1100    /// The first slot in `from..end` whose presence is `present`, else `end`.
1101    fn next_slot(&self, from: usize, end: usize, present: bool) -> usize {
1102        let Some(words) = self.present else {
1103            return if present { from } else { end };
1104        };
1105        let mut i = from;
1106        while i < end {
1107            let word = if present {
1108                words[i / 64]
1109            } else {
1110                !words[i / 64]
1111            };
1112            let ahead = word >> (i % 64);
1113            if ahead != 0 {
1114                return (i + ahead.trailing_zeros() as usize).min(end);
1115            }
1116            i += 64 - i % 64;
1117        }
1118        end
1119    }
1120
1121    /// numpy's `add.reduce` of `term(value)` over the present values, in this
1122    /// layout's order; `cast_buffered` adds 8192 values at a time onto the
1123    /// total, as numpy sums an int64 array as float64. A `T` of several sums
1124    /// adds each in that same order.
1125    fn add_reduce<T>(&self, term: impl Fn(f64) -> T, cast_buffered: bool) -> T
1126    where
1127        T: Copy + Default + std::ops::Add<Output = T>,
1128    {
1129        let reader = ValueReader::new(self.values);
1130        // The values of `first..first + block.len()`, each through `term`.
1131        let read_terms = |first: usize, block: &mut [T]| {
1132            let mut values = [0.0_f64; PAIRWISE_BLOCK];
1133            let values = &mut values[..block.len()];
1134            reader.read(first, values);
1135            let terms = block.iter_mut().zip(values.iter());
1136            if self.nan_missing {
1137                // The NaN slots are 0, in place.
1138                for (slot, &value) in terms {
1139                    *slot = if value.is_nan() {
1140                        T::default()
1141                    } else {
1142                        term(value)
1143                    };
1144                }
1145            } else {
1146                for (slot, &value) in terms {
1147                    *slot = term(value);
1148                }
1149            }
1150        };
1151        let buffer = if cast_buffered {
1152            NUMPY_CAST_BUFFER
1153        } else {
1154            self.len.max(1)
1155        };
1156        let mut total = T::default();
1157        let mut chunk_start = 0;
1158        while chunk_start < self.len {
1159            let chunk_end = (chunk_start + buffer).min(self.len);
1160            match self.layout {
1161                MissingLayout::Numpy => {
1162                    if let (ReductionValues::Float(values), None) = (self.values, self.present) {
1163                        let values = &values[chunk_start..chunk_end];
1164                        let part = if self.nan_missing {
1165                            // The NaN slots are 0, in place.
1166                            let term = |value: f64| {
1167                                if value.is_nan() {
1168                                    T::default()
1169                                } else {
1170                                    term(value)
1171                                }
1172                            };
1173                            numpy_pairwise_sum_of(values, &term)
1174                        } else {
1175                            numpy_pairwise_sum_of(values, &term)
1176                        };
1177                        total = total + part;
1178                        chunk_start = chunk_end;
1179                        continue;
1180                    }
1181                    let fill = |start: usize, block: &mut [T]| {
1182                        let first = chunk_start + start;
1183                        read_terms(first, block);
1184                        // The missing slots are 0, in place.
1185                        let end = first + block.len();
1186                        let mut slot = self.next_slot(first, end, false);
1187                        while slot < end {
1188                            let run_end = self.next_slot(slot, end, true);
1189                            block[slot - first..run_end - first].fill(T::default());
1190                            slot = self.next_slot(run_end, end, false);
1191                        }
1192                    };
1193                    total = total + numpy_pairwise_sum_by(chunk_end - chunk_start, &fill);
1194                }
1195                MissingLayout::Masked => {
1196                    let mut run_start = self.next_slot(chunk_start, chunk_end, true);
1197                    while run_start < chunk_end {
1198                        let run_end = self.next_slot(run_start, chunk_end, false);
1199                        let fill = |start: usize, block: &mut [T]| {
1200                            read_terms(run_start + start, block);
1201                        };
1202                        total = total + numpy_pairwise_sum_by(run_end - run_start, &fill);
1203                        run_start = self.next_slot(run_end, chunk_end, true);
1204                    }
1205                }
1206            }
1207            chunk_start = chunk_end;
1208        }
1209        total
1210    }
1211
1212    /// The values' total as [`Self::add_reduce`] adds them, a present float
1213    /// buffer summed in place.
1214    fn total(&self, cast_buffered: bool) -> f64 {
1215        if let Some(total) = self.total {
1216            return total;
1217        }
1218        if let (ReductionValues::Float(values), None, false) =
1219            (self.values, self.present, self.nan_missing)
1220        {
1221            return 0.0 + numpy_pairwise_sum(values);
1222        }
1223        self.add_reduce(|value| value, cast_buffered)
1224    }
1225
1226    /// The total `mean` divides: an int64 array's through numpy's cast
1227    /// buffer (a datetime64's NaT slots are 0 in it).
1228    fn mean_total(&self) -> f64 {
1229        let int = matches!(
1230            self.values,
1231            ReductionValues::Int(_) | ReductionValues::IntChunks(_)
1232        );
1233        self.total(int)
1234    }
1235
1236    /// `Series.sum()` of a float column, missing values skipped.
1237    #[must_use]
1238    pub fn sum(&self) -> f64 {
1239        self.total(false)
1240    }
1241
1242    /// `Series.mean()`; NaN with no present value.
1243    #[must_use]
1244    #[allow(clippy::cast_precision_loss)] // pandas' float count
1245    pub fn mean(&self) -> f64 {
1246        if self.count == 0 {
1247            return f64::NAN;
1248        }
1249        self.mean_total() / self.count as f64
1250    }
1251
1252    /// `Series.var(ddof=ddof)`; NaN with `ddof` or fewer present values.
1253    #[must_use]
1254    #[allow(clippy::cast_precision_loss)] // pandas' float count
1255    pub fn var(&self, ddof: usize) -> f64 {
1256        if self.count <= ddof {
1257            return f64::NAN;
1258        }
1259        // nanops casts an int64 array to float64 whole before its mean; the
1260        // masked var sums int64 values through the cast buffer.
1261        let total = if self.layout == MissingLayout::Masked {
1262            self.mean_total()
1263        } else {
1264            self.total(false)
1265        };
1266        let mean = total / self.count as f64;
1267        let squares = self.add_reduce(
1268            |value| {
1269                let deviation = mean - value;
1270                deviation * deviation
1271            },
1272            false,
1273        );
1274        squares / (self.count - ddof) as f64
1275    }
1276
1277    /// `Series.std(ddof=ddof)`.
1278    #[must_use]
1279    pub fn std(&self, ddof: usize) -> f64 {
1280        self.var(ddof).sqrt()
1281    }
1282
1283    /// This column as nanops reads it: pandas' `sem`, `skew` and `kurt` read
1284    /// even a masked column with its missing slots filled with 0.
1285    fn as_numpy(&self) -> Self {
1286        Self {
1287            layout: MissingLayout::Numpy,
1288            ..*self
1289        }
1290    }
1291
1292    /// `Series.sem(ddof=ddof)`: `sqrt(var) / sqrt(count)`.
1293    #[must_use]
1294    #[allow(clippy::cast_precision_loss)] // pandas' float count
1295    pub fn sem(&self, ddof: usize) -> f64 {
1296        self.as_numpy().var(ddof).sqrt() / (self.count as f64).sqrt()
1297    }
1298
1299    /// The central sums `(m2, m3 or m4)` of nanskew / nankurt.
1300    #[allow(clippy::cast_precision_loss)] // pandas' float count
1301    fn central_moments(&self, fourth: bool) -> (f64, f64) {
1302        let numpy = self.as_numpy();
1303        let mean = numpy.total(false) / self.count as f64;
1304        // Both sums in one sweep: each adds in numpy's order on its own.
1305        let SumPair(m2, higher) = numpy.add_reduce(
1306            |value| {
1307                let deviation = value - mean;
1308                let square = deviation * deviation;
1309                let higher = if fourth {
1310                    square * square
1311                } else {
1312                    square * deviation
1313                };
1314                SumPair(square, higher)
1315            },
1316            false,
1317        );
1318        (m2, higher)
1319    }
1320
1321    /// `Series.skew()`: pandas' nanskew; NaN below 3 values, 0 for constant
1322    /// data.
1323    #[must_use]
1324    #[allow(clippy::cast_precision_loss)] // pandas' float count
1325    pub fn skew(&self) -> f64 {
1326        if self.count < 3 {
1327            return f64::NAN;
1328        }
1329        let (m2, m3) = self.central_moments(false);
1330        let (m2, m3) = (zero_out_fperr(m2), zero_out_fperr(m3));
1331        if m2 == 0.0 {
1332            return 0.0;
1333        }
1334        let count = self.count as f64;
1335        // pandas raises with libm pow (n = 2922 tells it from sqrt); a
1336        // literal 0.5 exponent would let LLVM substitute sqrt.
1337        let half = std::hint::black_box(0.5);
1338        (count * (count - 1.0).powf(half) / (count - 2.0)) * (m3 / m2.powf(1.5))
1339    }
1340
1341    /// `Series.kurt()`: pandas' nankurt; NaN below 4 values, 0 when the
1342    /// denominator vanishes (constant data).
1343    #[must_use]
1344    #[allow(clippy::cast_precision_loss)] // pandas' float count
1345    pub fn kurt(&self) -> f64 {
1346        if self.count < 4 {
1347            return f64::NAN;
1348        }
1349        let (m2, m4) = self.central_moments(true);
1350        let count = self.count as f64;
1351        let numerator = zero_out_fperr(count * (count + 1.0) * (count - 1.0) * m4);
1352        let denominator = zero_out_fperr((count - 2.0) * (count - 3.0) * (m2 * m2));
1353        if denominator == 0.0 {
1354            return 0.0;
1355        }
1356        let adjustment = 3.0 * ((count - 1.0) * (count - 1.0)) / ((count - 2.0) * (count - 3.0));
1357        numerator / denominator - adjustment
1358    }
1359}
1360
1361/// Two sums carried side by side (two float sums, or a float sum and a
1362/// count), added lane by lane.
1363#[derive(Debug, Clone, Copy, Default)]
1364struct SumPair<A, B = A>(A, B);
1365
1366impl<A: std::ops::Add<Output = A>, B: std::ops::Add<Output = B>> std::ops::Add for SumPair<A, B> {
1367    type Output = Self;
1368
1369    fn add(self, other: Self) -> Self {
1370        Self(self.0 + other.0, self.1 + other.1)
1371    }
1372}
1373
1374/// pandas' `_zero_out_fperr`: a moment below 1e-14 in magnitude is 0.
1375fn zero_out_fperr(value: f64) -> f64 {
1376    if value.abs() < 1e-14 { 0.0 } else { value }
1377}
1378
1379/// What pandas' default text-to-float64 conversion - `read_csv` /
1380/// `read_table` with `float_precision=None` or `'high'`, and `to_numeric` of
1381/// strings - makes of a token (br-frankenpandas-py3c0).
1382#[derive(Debug, Clone, Copy, PartialEq)]
1383pub enum PandasDecimal {
1384    /// A decimal number, converted as pandas converts it.
1385    Value(f64),
1386    /// A token that starts as a number but that pandas does not read as a
1387    /// float: trailing text, an exponent without digits or with more than 17,
1388    /// a value past float64's range.
1389    Rejected,
1390    /// No digits before an exponent: not a decimal (the `inf` / `nan`
1391    /// spellings, `.`, `-`); the caller's own rules apply.
1392    NotDecimal,
1393}
1394
1395/// Significant digits pandas' converter keeps, leading zeros included;
1396/// also the most exponent digits it reads.
1397const PANDAS_DECIMAL_DIGITS: usize = 17;
1398
1399/// The significand as pandas accumulates it, `x * 10 + d` in float64. While
1400/// the digits stay within 2^53 every step is exact, so they add as an
1401/// integer.
1402#[derive(Default)]
1403struct PandasSignificand {
1404    exact: u64,
1405    float: f64,
1406    rounding: bool,
1407    digits: usize,
1408}
1409
1410impl PandasSignificand {
1411    fn push(&mut self, digit: u8) {
1412        self.digits += 1;
1413        if !self.rounding {
1414            let next = self.exact * 10 + u64::from(digit);
1415            if next <= 1 << 53 {
1416                self.exact = next;
1417                return;
1418            }
1419            self.rounding = true;
1420            #[allow(clippy::cast_precision_loss)] // at most 2^53: exact
1421            let exact = self.exact as f64;
1422            self.float = exact;
1423        }
1424        self.float = self.float * 10.0 + f64::from(digit);
1425    }
1426
1427    #[allow(clippy::cast_precision_loss)] // at most 2^53: exact
1428    fn value(&self) -> f64 {
1429        if self.rounding {
1430            self.float
1431        } else {
1432            self.exact as f64
1433        }
1434    }
1435}
1436
1437/// pandas' scaling table: the float64 nearest each `1e0 ..= 1e308`.
1438static PANDAS_POW10: std::sync::LazyLock<[f64; 309]> = std::sync::LazyLock::new(|| {
1439    std::array::from_fn(|power| format!("1e{power}").parse().unwrap_or(f64::INFINITY))
1440});
1441
1442/// pandas' default text-to-float64 conversion of `token` (no surrounding
1443/// space). It is not correctly rounded: the first 17 digits - leading zeros
1444/// count - accumulate as `x * 10 + d` in float64 (digits past them in the
1445/// integer part raise the exponent, in the fraction they are dropped), the
1446/// exponent is a wrapping 32-bit integer of at most 17 digits, and the value
1447/// is scaled ONCE by a float64 power of ten: `x * 1e{e}` for `e` up to 308,
1448/// `x / 1e{-e}` down to -308, `x / 1e{-308-e} / 1e308` down to -616, `+0.0`
1449/// below that; past 308, or overflowing to infinity, the token is not a
1450/// float. The sign applies last. Measured against live pandas 2.2.3 over
1451/// 180k tokens (repr / `%.20e` / `%.25f` / 1-30 digit fractions / leading
1452/// zeros / exponents to +-640 / wrapping exponents), 0 mismatches;
1453/// `float()` misses about a third of them.
1454#[must_use]
1455pub fn pandas_decimal_to_f64(token: &[u8]) -> PandasDecimal {
1456    let (negative, body) = match token.first() {
1457        Some(b'-') => (true, &token[1..]),
1458        Some(b'+') => (false, &token[1..]),
1459        _ => (false, token),
1460    };
1461    let mut significand = PandasSignificand::default();
1462    let mut exponent = 0_i32;
1463    let mut pos = 0;
1464    while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1465        if significand.digits < PANDAS_DECIMAL_DIGITS {
1466            significand.push(byte - b'0');
1467        } else {
1468            exponent = exponent.wrapping_add(1);
1469        }
1470        pos += 1;
1471    }
1472    let mut seen_digit = pos > 0;
1473    if body.get(pos) == Some(&b'.') {
1474        pos += 1;
1475        while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1476            if significand.digits < PANDAS_DECIMAL_DIGITS {
1477                significand.push(byte - b'0');
1478                exponent = exponent.wrapping_sub(1);
1479            }
1480            seen_digit = true;
1481            pos += 1;
1482        }
1483    }
1484    if !seen_digit {
1485        return PandasDecimal::NotDecimal;
1486    }
1487    if let Some(b'e' | b'E') = body.get(pos) {
1488        pos += 1;
1489        let negative_exponent = match body.get(pos) {
1490            Some(b'-') => {
1491                pos += 1;
1492                true
1493            }
1494            Some(b'+') => {
1495                pos += 1;
1496                false
1497            }
1498            _ => false,
1499        };
1500        let start = pos;
1501        let mut written = 0_i32;
1502        while pos - start < PANDAS_DECIMAL_DIGITS
1503            && let Some(&byte @ b'0'..=b'9') = body.get(pos)
1504        {
1505            written = written
1506                .wrapping_mul(10)
1507                .wrapping_add(i32::from(byte - b'0'));
1508            pos += 1;
1509        }
1510        if pos == start {
1511            return PandasDecimal::Rejected;
1512        }
1513        exponent = exponent.wrapping_add(if negative_exponent {
1514            written.wrapping_neg()
1515        } else {
1516            written
1517        });
1518    }
1519    if pos != body.len() {
1520        return PandasDecimal::Rejected;
1521    }
1522    let value = significand.value();
1523    let pow10 = |power: i32| PANDAS_POW10[power.unsigned_abs() as usize];
1524    let magnitude = match exponent {
1525        309.. => return PandasDecimal::Rejected,
1526        0.. => value * pow10(exponent),
1527        -308.. => value / pow10(exponent),
1528        -616.. => value / pow10(-308 - exponent) / pow10(308),
1529        _ => return PandasDecimal::Value(0.0),
1530    };
1531    if magnitude.is_infinite() {
1532        return PandasDecimal::Rejected;
1533    }
1534    PandasDecimal::Value(if negative { -magnitude } else { magnitude })
1535}
1536
1537/// An integer cell of a column pandas reads as float64 (one of its cells is
1538/// fractional): the integer's digits through [`pandas_decimal_to_f64`],
1539/// exact up to 2^53.
1540#[must_use]
1541#[allow(clippy::cast_precision_loss)] // at most 2^53, or 19 digits: a value
1542pub fn pandas_int_to_f64(value: i64) -> f64 {
1543    if value.unsigned_abs() <= 1 << 53 {
1544        return value as f64;
1545    }
1546    match pandas_decimal_to_f64(value.to_string().as_bytes()) {
1547        PandasDecimal::Value(parsed) => parsed,
1548        // 19 digits at most: always a value.
1549        PandasDecimal::Rejected | PandasDecimal::NotDecimal => value as f64,
1550    }
1551}
1552
1553/// A numeric column's numpy dtype as numpy's promotion sees it: kind and
1554/// bits. The 64-bit ones are a column without a [`NumericWidth`].
1555#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1556pub enum NumpyNumeric {
1557    Bool,
1558    Int(u8),
1559    UInt(u8),
1560    Float(u8),
1561}
1562
1563impl NumpyNumeric {
1564    /// The numpy dtype of a column of `dtype` carrying `width`; `None` for a
1565    /// column that is not bool, integer or float (or a width its storage
1566    /// cannot carry).
1567    #[must_use]
1568    pub const fn of(dtype: &DType, width: Option<NumericWidth>) -> Option<Self> {
1569        match (dtype, width) {
1570            (DType::Bool | DType::BoolNullable, None) => Some(Self::Bool),
1571            (DType::Int64 | DType::Int64Nullable, None) => Some(Self::Int(64)),
1572            (DType::Float64 | DType::Float64Nullable, None) => Some(Self::Float(64)),
1573            (DType::Int64 | DType::Int64Nullable, Some(width)) if !width.is_float() => {
1574                Some(Self::of_width(width))
1575            }
1576            (DType::Float64 | DType::Float64Nullable, Some(NumericWidth::Float32)) => {
1577                Some(Self::Float(32))
1578            }
1579            _ => None,
1580        }
1581    }
1582
1583    #[must_use]
1584    pub const fn of_width(width: NumericWidth) -> Self {
1585        match width {
1586            NumericWidth::Int8 => Self::Int(8),
1587            NumericWidth::Int16 => Self::Int(16),
1588            NumericWidth::Int32 => Self::Int(32),
1589            NumericWidth::UInt8 => Self::UInt(8),
1590            NumericWidth::UInt16 => Self::UInt(16),
1591            NumericWidth::UInt32 => Self::UInt(32),
1592            NumericWidth::UInt64 => Self::UInt(64),
1593            NumericWidth::Float32 => Self::Float(32),
1594        }
1595    }
1596
1597    /// The width a column of this numpy dtype carries: `None` for bool,
1598    /// int64 and float64.
1599    #[must_use]
1600    pub const fn width(self) -> Option<NumericWidth> {
1601        match self {
1602            Self::Int(8) => Some(NumericWidth::Int8),
1603            Self::Int(16) => Some(NumericWidth::Int16),
1604            Self::Int(32) => Some(NumericWidth::Int32),
1605            Self::UInt(8) => Some(NumericWidth::UInt8),
1606            Self::UInt(16) => Some(NumericWidth::UInt16),
1607            Self::UInt(32) => Some(NumericWidth::UInt32),
1608            Self::UInt(64) => Some(NumericWidth::UInt64),
1609            Self::Float(32) => Some(NumericWidth::Float32),
1610            _ => None,
1611        }
1612    }
1613
1614    #[must_use]
1615    pub const fn is_float(self) -> bool {
1616        matches!(self, Self::Float(_))
1617    }
1618
1619    /// numpy's `result_type` of two arrays: the smallest dtype holding both
1620    /// (bool yields to anything; int8 + uint8 is int16, int64 + uint64
1621    /// float64; float32 holds integers of up to 16 bits, a wider integer
1622    /// makes it float64).
1623    #[must_use]
1624    pub const fn result_type(self, other: Self) -> Self {
1625        const fn wider(a: u8, b: u8) -> u8 {
1626            if a > b { a } else { b }
1627        }
1628        match (self, other) {
1629            (Self::Bool, x) | (x, Self::Bool) => x,
1630            (Self::Int(a), Self::Int(b)) => Self::Int(wider(a, b)),
1631            (Self::UInt(a), Self::UInt(b)) => Self::UInt(wider(a, b)),
1632            (Self::Int(signed), Self::UInt(unsigned))
1633            | (Self::UInt(unsigned), Self::Int(signed)) => {
1634                if signed > unsigned {
1635                    Self::Int(signed)
1636                } else if unsigned < 64 {
1637                    Self::Int(wider(signed, unsigned * 2))
1638                } else {
1639                    Self::Float(64)
1640                }
1641            }
1642            (Self::Float(a), Self::Float(b)) => Self::Float(wider(a, b)),
1643            (Self::Float(bits), Self::Int(int_bits) | Self::UInt(int_bits))
1644            | (Self::Int(int_bits) | Self::UInt(int_bits), Self::Float(bits)) => {
1645                if int_bits <= 16 {
1646                    Self::Float(bits)
1647                } else {
1648                    Self::Float(64)
1649                }
1650            }
1651        }
1652    }
1653
1654    /// The dtype of this array combined with a Python `int` (NEP 50: the
1655    /// Python scalar is weak, the array's dtype wins; bool becomes int64).
1656    /// Whether the int fits that dtype is the caller's check.
1657    #[must_use]
1658    pub const fn with_python_int(self) -> Self {
1659        match self {
1660            Self::Bool => Self::Int(64),
1661            other => other,
1662        }
1663    }
1664
1665    /// The dtype of this array combined with a Python `float`: a float
1666    /// array keeps its dtype (float32 + 0.2 is float32), anything else is
1667    /// float64.
1668    #[must_use]
1669    pub const fn with_python_float(self) -> Self {
1670        match self {
1671            Self::Float(bits) => Self::Float(bits),
1672            _ => Self::Float(64),
1673        }
1674    }
1675}
1676
1677/// Trait for types that carry or represent a [`DType`].
1678pub trait AsDType {
1679    /// Return the corresponding [`DType`].
1680    fn as_dtype(&self) -> DType;
1681}
1682
1683impl AsDType for DType {
1684    fn as_dtype(&self) -> DType {
1685        self.clone()
1686    }
1687}
1688
1689impl AsDType for &DType {
1690    fn as_dtype(&self) -> DType {
1691        (*self).clone()
1692    }
1693}
1694
1695impl AsDType for &str {
1696    fn as_dtype(&self) -> DType {
1697        self.parse::<DType>().unwrap_or(DType::Utf8)
1698    }
1699}
1700
1701impl AsDType for String {
1702    fn as_dtype(&self) -> DType {
1703        self.as_str().as_dtype()
1704    }
1705}
1706
1707pub mod api {
1708    //! Public pandas API modules (`pandas.api.*`).
1709
1710    pub mod types {
1711        //! Dtype inspection and conversion functions (`pandas.api.types`).
1712
1713        use crate::{AsDType, DType, Scalar, TypeError};
1714
1715        /// Matches `pd.api.types.is_bool_dtype`.
1716        #[must_use]
1717        pub fn is_bool_dtype(dtype: &impl AsDType) -> bool {
1718            dtype.as_dtype().is_bool()
1719        }
1720
1721        /// Matches `pd.api.types.is_numeric_dtype`.
1722        #[must_use]
1723        pub fn is_numeric_dtype(dtype: &impl AsDType) -> bool {
1724            dtype.as_dtype().is_numeric()
1725        }
1726
1727        /// Matches `pd.api.types.is_integer_dtype`.
1728        #[must_use]
1729        pub fn is_integer_dtype(dtype: &impl AsDType) -> bool {
1730            dtype.as_dtype().is_integer()
1731        }
1732
1733        /// Matches `pd.api.types.is_signed_integer_dtype`.
1734        #[must_use]
1735        pub fn is_signed_integer_dtype(dtype: &impl AsDType) -> bool {
1736            dtype.as_dtype().is_signed_integer()
1737        }
1738
1739        /// Matches `pd.api.types.is_unsigned_integer_dtype`.
1740        #[must_use]
1741        pub fn is_unsigned_integer_dtype(_dtype: &impl AsDType) -> bool {
1742            false
1743        }
1744
1745        /// Matches `pd.api.types.is_float_dtype`.
1746        #[must_use]
1747        pub fn is_float_dtype(dtype: &impl AsDType) -> bool {
1748            dtype.as_dtype().is_floating()
1749        }
1750
1751        /// Matches `pd.api.types.is_string_dtype`.
1752        #[must_use]
1753        pub fn is_string_dtype(dtype: &impl AsDType) -> bool {
1754            dtype.as_dtype().is_string_dtype()
1755        }
1756
1757        /// Matches `pd.api.types.is_datetime64_any_dtype`.
1758        #[must_use]
1759        pub fn is_datetime64_any_dtype(dtype: &impl AsDType) -> bool {
1760            dtype.as_dtype().is_datetime()
1761        }
1762
1763        /// Matches `pd.api.types.is_datetime64_dtype`.
1764        #[must_use]
1765        pub fn is_datetime64_dtype(dtype: &impl AsDType) -> bool {
1766            dtype.as_dtype().is_datetime()
1767        }
1768
1769        /// Matches `pd.api.types.is_datetime64_ns_dtype`.
1770        #[must_use]
1771        pub fn is_datetime64_ns_dtype(dtype: &impl AsDType) -> bool {
1772            dtype.as_dtype().is_datetime()
1773        }
1774
1775        /// Matches `pd.api.types.is_timedelta64_dtype`.
1776        #[must_use]
1777        pub fn is_timedelta64_dtype(dtype: &impl AsDType) -> bool {
1778            dtype.as_dtype().is_timedelta()
1779        }
1780
1781        /// Matches `pd.api.types.is_timedelta64_ns_dtype`.
1782        #[must_use]
1783        pub fn is_timedelta64_ns_dtype(dtype: &impl AsDType) -> bool {
1784            dtype.as_dtype().is_timedelta()
1785        }
1786
1787        /// Matches `pd.api.types.is_period_dtype`.
1788        #[must_use]
1789        pub fn is_period_dtype(dtype: &impl AsDType) -> bool {
1790            dtype.as_dtype().is_period()
1791        }
1792
1793        /// Matches `pd.api.types.is_categorical_dtype`.
1794        #[must_use]
1795        pub fn is_categorical_dtype(dtype: &impl AsDType) -> bool {
1796            dtype.as_dtype().is_categorical()
1797        }
1798
1799        /// Matches `pd.api.types.is_interval_dtype`.
1800        #[must_use]
1801        pub fn is_interval_dtype(dtype: &impl AsDType) -> bool {
1802            dtype.as_dtype().is_interval()
1803        }
1804
1805        /// Matches `pd.api.types.is_sparse`.
1806        #[must_use]
1807        pub fn is_sparse(dtype: &impl AsDType) -> bool {
1808            dtype.as_dtype().is_sparse()
1809        }
1810
1811        /// Matches `pd.api.types.is_extension_array_dtype`.
1812        #[must_use]
1813        pub fn is_extension_array_dtype(dtype: &impl AsDType) -> bool {
1814            dtype.as_dtype().is_extension()
1815        }
1816
1817        /// Matches `pd.api.types.is_object_dtype`.
1818        #[must_use]
1819        pub fn is_object_dtype(dtype: &impl AsDType) -> bool {
1820            dtype.as_dtype().is_object()
1821        }
1822
1823        /// Matches `pd.api.types.is_int64_dtype`.
1824        #[must_use]
1825        pub fn is_int64_dtype(dtype: &impl AsDType) -> bool {
1826            matches!(dtype.as_dtype(), DType::Int64 | DType::Int64Nullable)
1827        }
1828
1829        /// Matches `pd.api.types.is_dtype_equal`.
1830        #[must_use]
1831        pub fn is_dtype_equal(source: &impl AsDType, target: &impl AsDType) -> bool {
1832            source.as_dtype() == target.as_dtype()
1833        }
1834
1835        /// Matches `pd.api.types.is_scalar`.
1836        #[must_use]
1837        pub const fn is_scalar(_scalar: &Scalar) -> bool {
1838            true
1839        }
1840
1841        /// Convert a string specification into a pandas DType. Matches `pd.api.types.pandas_dtype`.
1842        ///
1843        /// # Errors
1844        ///
1845        /// Returns [`TypeError::ValueNotParseable`] if the string cannot be parsed as a valid dtype.
1846        pub fn pandas_dtype(name: &str) -> Result<DType, TypeError> {
1847            name.parse::<DType>()
1848        }
1849
1850        /// Infer the dtype kind of a slice of scalars. Matches `pd.api.types.infer_dtype`.
1851        #[must_use]
1852        pub fn infer_dtype(scalars: &[Scalar], skipna: bool) -> &'static str {
1853            if scalars.is_empty() {
1854                return "empty";
1855            }
1856            let mut has_int = false;
1857            let mut has_float = false;
1858            let mut has_bool = false;
1859            let mut has_str = false;
1860            let mut has_ts = false;
1861            let mut has_td = false;
1862            let mut has_period = false;
1863            let mut count = 0;
1864
1865            for s in scalars {
1866                if s.is_null() {
1867                    if !skipna {
1868                        return "mixed";
1869                    }
1870                    continue;
1871                }
1872                count += 1;
1873                match s {
1874                    Scalar::Bool(_) => has_bool = true,
1875                    Scalar::Int64(_) => has_int = true,
1876                    Scalar::Float64(_) => has_float = true,
1877                    Scalar::Utf8(_) => has_str = true,
1878                    Scalar::Datetime64(_) => has_ts = true,
1879                    Scalar::Timedelta64(_) => has_td = true,
1880                    Scalar::Period(_) => has_period = true,
1881                    _ => {}
1882                }
1883            }
1884
1885            if count == 0 {
1886                return "empty";
1887            }
1888            if has_bool && !has_int && !has_float && !has_str && !has_ts && !has_td && !has_period {
1889                return "boolean";
1890            }
1891            if has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td && !has_period {
1892                return "integer";
1893            }
1894            if (has_float || (has_int && has_float))
1895                && !has_bool
1896                && !has_str
1897                && !has_ts
1898                && !has_td
1899                && !has_period
1900            {
1901                return "floating";
1902            }
1903            if has_str && !has_int && !has_float && !has_bool && !has_ts && !has_td && !has_period {
1904                return "string";
1905            }
1906            if has_ts && !has_int && !has_float && !has_bool && !has_str && !has_td && !has_period {
1907                return "datetime64";
1908            }
1909            if has_td && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_period {
1910                return "timedelta64";
1911            }
1912            if has_period && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td {
1913                return "period";
1914            }
1915            "mixed"
1916        }
1917
1918        /// Convenience helper for 64-bit float types (`pd.api.types.is_float64_dtype` does NOT exist in pandas; see [`is_float_dtype`]).
1919        #[must_use]
1920        pub fn is_float64_dtype(dtype: &impl AsDType) -> bool {
1921            matches!(dtype.as_dtype(), DType::Float64 | DType::Float64Nullable)
1922        }
1923
1924        /// Convenience helper for 32-bit integer types (`pd.api.types.is_int32_dtype` does NOT exist in pandas; see [`is_integer_dtype`]).
1925        #[must_use]
1926        pub fn is_int32_dtype(_dtype: &impl AsDType) -> bool {
1927            false
1928        }
1929
1930        /// Matches `pd.api.types.is_number`.
1931        #[must_use]
1932        pub fn is_number(scalar: &Scalar) -> bool {
1933            scalar.is_numeric() || matches!(scalar, Scalar::Bool(_))
1934        }
1935
1936        /// Matches `pd.api.types.is_bool`.
1937        #[must_use]
1938        pub fn is_bool(scalar: &Scalar) -> bool {
1939            matches!(scalar, Scalar::Bool(_))
1940        }
1941
1942        /// Matches `pd.api.types.is_integer`.
1943        #[must_use]
1944        pub fn is_integer(scalar: &Scalar) -> bool {
1945            matches!(scalar, Scalar::Int64(_))
1946        }
1947
1948        /// Matches `pd.api.types.is_float`.
1949        #[must_use]
1950        pub fn is_float(scalar: &Scalar) -> bool {
1951            matches!(scalar, Scalar::Float64(_))
1952        }
1953    }
1954
1955    pub mod extensions {
1956        //! Extension arrays and accessor registration hooks (`pandas.api.extensions`).
1957
1958        /// Compatibility registration hook for DataFrame accessors matching `pd.api.extensions.register_dataframe_accessor`.
1959        pub fn register_dataframe_accessor(_name: &str) {}
1960
1961        /// Compatibility registration hook for Series accessors matching `pd.api.extensions.register_series_accessor`.
1962        pub fn register_series_accessor(_name: &str) {}
1963
1964        /// Compatibility registration hook for Index accessors matching `pd.api.extensions.register_index_accessor`.
1965        pub fn register_index_accessor(_name: &str) {}
1966    }
1967
1968    pub mod indexers {
1969        //! Custom window and rolling indexers (`pandas.api.indexers`).
1970
1971        /// Base specification for window indexers, matching `pd.api.indexers.BaseIndexer`.
1972        #[derive(Debug, Clone, PartialEq, Eq, Default)]
1973        pub struct BaseIndexer {
1974            pub window_size: usize,
1975            pub step: usize,
1976        }
1977
1978        impl BaseIndexer {
1979            #[must_use]
1980            pub const fn new(window_size: usize, step: usize) -> Self {
1981                Self { window_size, step }
1982            }
1983        }
1984
1985        /// Fixed forward-looking window indexer, matching `pd.api.indexers.FixedForwardWindowIndexer`.
1986        #[derive(Debug, Clone, PartialEq, Eq, Default)]
1987        pub struct FixedForwardWindowIndexer {
1988            pub window_size: usize,
1989        }
1990
1991        impl FixedForwardWindowIndexer {
1992            #[must_use]
1993            pub const fn new(window_size: usize) -> Self {
1994                Self { window_size }
1995            }
1996        }
1997
1998        /// Variable offset window indexer, matching `pd.api.indexers.VariableOffsetWindowIndexer`.
1999        #[derive(Debug, Clone, PartialEq, Eq, Default)]
2000        pub struct VariableOffsetWindowIndexer {
2001            pub index_offset: i64,
2002        }
2003
2004        impl VariableOffsetWindowIndexer {
2005            #[must_use]
2006            pub const fn new(index_offset: i64) -> Self {
2007                Self { index_offset }
2008            }
2009        }
2010    }
2011}
2012
2013pub use api::types::pandas_dtype;
2014
2015#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2016pub struct SparseDType {
2017    pub value_dtype: DType,
2018    pub fill_value: Scalar,
2019}
2020
2021impl SparseDType {
2022    /// Construct a pandas-style sparse dtype descriptor.
2023    ///
2024    /// This records the logical dense value dtype plus the scalar value that is
2025    /// elided from storage. The concrete sparse column representation lives in
2026    /// fp-columnar; this descriptor is the shared public contract.
2027    pub fn new(value_dtype: DType, fill_value: Scalar) -> Result<Self, TypeError> {
2028        if matches!(value_dtype, DType::Null | DType::Sparse) {
2029            return Err(TypeError::InvalidSparseValueDType { dtype: value_dtype });
2030        }
2031
2032        let fill_value = if fill_value.is_missing() {
2033            Scalar::missing_for_dtype(value_dtype.clone())
2034        } else {
2035            cast_scalar_owned(fill_value, value_dtype.clone())?
2036        };
2037
2038        Ok(Self {
2039            value_dtype,
2040            fill_value,
2041        })
2042    }
2043
2044    /// Render the pandas dtype name, `Sparse[<subtype>, <fill>]`.
2045    ///
2046    /// br-frankenpandas-3gxc6. [`DType::name`] can only answer `"Sparse"`: it
2047    /// is a `const fn` returning `&'static str` and `DType::Sparse` carries no
2048    /// payload, so the subtype and fill value — which live here — are lost by
2049    /// the time a caller has a bare [`DType`]. pandas never spells the bare
2050    /// form; even `pd.Series([1.5, 0.0]).astype("Sparse")` resolves to
2051    /// `Sparse[float64, nan]`.
2052    ///
2053    /// MEASURED, live pandas 2.2.3, `str(dtype)` / `dtype.name`:
2054    ///
2055    /// ```text
2056    ///   SparseDtype("int64",   0)     -> Sparse[int64, 0]
2057    ///   SparseDtype("int64",   7)     -> Sparse[int64, 7]
2058    ///   SparseDtype("float64", nan)   -> Sparse[float64, nan]
2059    ///   SparseDtype("float64", 0.0)   -> Sparse[float64, 0.0]
2060    ///   SparseDtype("bool",    False) -> Sparse[bool, False]
2061    ///   SparseDtype(object,    nan)   -> Sparse[object, nan]
2062    /// ```
2063    ///
2064    /// The fill is rendered by `scalar_to_string_for_astype`, which already
2065    /// spells every one of those cases the way pandas does in this position:
2066    /// `True`/`False` capitalised, integers bare, lowercase `nan`, and the
2067    /// trailing `.0` preserved on whole floats. Deliberately reusing it rather
2068    /// than writing a second float formatter — a divergence between the two
2069    /// would surface as a dtype name that no longer round-trips.
2070    #[must_use]
2071    pub fn pandas_name(&self) -> String {
2072        format!(
2073            "Sparse[{}, {}]",
2074            self.value_dtype.name(),
2075            scalar_to_string_for_astype(self.fill_value.clone())
2076        )
2077    }
2078}
2079
2080impl AsDType for SparseDType {
2081    fn as_dtype(&self) -> DType {
2082        DType::Sparse
2083    }
2084}
2085
2086/// Pandas-equivalent categorical dtype descriptor (`pd.CategoricalDtype`).
2087///
2088/// Encapsulates the optional category vocabulary and ordering semantics.
2089#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
2090pub struct CategoricalDtype {
2091    pub categories: Option<Vec<String>>,
2092    pub ordered: bool,
2093}
2094
2095pub type CategoricalDType = CategoricalDtype;
2096
2097impl CategoricalDtype {
2098    /// Construct a new `CategoricalDtype`.
2099    #[must_use]
2100    pub const fn new(categories: Option<Vec<String>>, ordered: bool) -> Self {
2101        Self {
2102            categories,
2103            ordered,
2104        }
2105    }
2106
2107    /// Return categories if known.
2108    #[must_use]
2109    pub fn categories(&self) -> Option<&[String]> {
2110        self.categories.as_deref()
2111    }
2112
2113    /// Return whether this categorical is ordered.
2114    #[must_use]
2115    pub const fn ordered(&self) -> bool {
2116        self.ordered
2117    }
2118
2119    /// Return the pandas dtype string name (`"category"`).
2120    #[must_use]
2121    pub const fn name(&self) -> &'static str {
2122        "category"
2123    }
2124
2125    /// Return the pandas kind character (`"O"`).
2126    #[must_use]
2127    pub const fn kind(&self) -> &'static str {
2128        "O"
2129    }
2130}
2131
2132impl AsDType for CategoricalDtype {
2133    fn as_dtype(&self) -> DType {
2134        DType::Categorical
2135    }
2136}
2137
2138impl std::fmt::Display for CategoricalDtype {
2139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2140        let ord_str = if self.ordered { "True" } else { "False" };
2141        match &self.categories {
2142            Some(cats) => write!(
2143                f,
2144                "CategoricalDtype(categories={cats:?}, ordered={ord_str})"
2145            ),
2146            None => write!(f, "CategoricalDtype(categories=None, ordered={ord_str})"),
2147        }
2148    }
2149}
2150
2151/// Pandas-equivalent period dtype descriptor (`pd.PeriodDtype`).
2152///
2153/// Represents time period durations with a specific frequency (default `"D"`).
2154#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2155pub struct PeriodDtype {
2156    pub freq: String,
2157}
2158
2159pub type PeriodDType = PeriodDtype;
2160
2161impl PeriodDtype {
2162    /// Construct a new `PeriodDtype` with given frequency.
2163    #[must_use]
2164    pub fn new(freq: impl Into<String>) -> Self {
2165        Self { freq: freq.into() }
2166    }
2167
2168    /// Return the period frequency string.
2169    #[must_use]
2170    pub fn freq(&self) -> &str {
2171        &self.freq
2172    }
2173
2174    /// Return the pandas dtype string name (`period[<freq>]`).
2175    #[must_use]
2176    pub fn name(&self) -> String {
2177        format!("period[{}]", self.freq)
2178    }
2179
2180    /// Return the pandas kind character (`"O"`).
2181    #[must_use]
2182    pub const fn kind(&self) -> &'static str {
2183        "O"
2184    }
2185}
2186
2187impl Default for PeriodDtype {
2188    fn default() -> Self {
2189        Self {
2190            freq: "D".to_string(),
2191        }
2192    }
2193}
2194
2195impl AsDType for PeriodDtype {
2196    fn as_dtype(&self) -> DType {
2197        DType::Period
2198    }
2199}
2200
2201impl std::fmt::Display for PeriodDtype {
2202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2203        write!(f, "period[{}]", self.freq)
2204    }
2205}
2206
2207/// Pandas-equivalent interval dtype descriptor (`pd.IntervalDtype`).
2208///
2209/// Encapsulates the interval subtype and endpoint closure behavior.
2210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2211pub struct IntervalDtype {
2212    pub subtype: DType,
2213    pub closed: Option<IntervalClosed>,
2214}
2215
2216pub type IntervalDType = IntervalDtype;
2217
2218impl IntervalDtype {
2219    /// Construct a new `IntervalDtype`.
2220    #[must_use]
2221    pub const fn new(subtype: DType, closed: Option<IntervalClosed>) -> Self {
2222        Self { subtype, closed }
2223    }
2224
2225    /// Return the interval subtype.
2226    #[must_use]
2227    pub const fn subtype(&self) -> &DType {
2228        &self.subtype
2229    }
2230
2231    /// Return the endpoint closure convention.
2232    #[must_use]
2233    pub const fn closed(&self) -> Option<IntervalClosed> {
2234        self.closed
2235    }
2236
2237    /// Return the pandas dtype string name (`"interval"`).
2238    #[must_use]
2239    pub const fn name(&self) -> &'static str {
2240        "interval"
2241    }
2242
2243    /// Return the pandas kind character (`"O"`).
2244    #[must_use]
2245    pub const fn kind(&self) -> &'static str {
2246        "O"
2247    }
2248}
2249
2250impl Default for IntervalDtype {
2251    fn default() -> Self {
2252        Self {
2253            subtype: DType::Float64,
2254            closed: Some(IntervalClosed::Right),
2255        }
2256    }
2257}
2258
2259impl AsDType for IntervalDtype {
2260    fn as_dtype(&self) -> DType {
2261        DType::Interval
2262    }
2263}
2264
2265impl std::fmt::Display for IntervalDtype {
2266    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2267        match self.closed {
2268            Some(c) => write!(f, "interval[{}, {c}]", self.subtype.name()),
2269            None => write!(f, "interval[{}]", self.subtype.name()),
2270        }
2271    }
2272}
2273
2274#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
2275#[serde(rename_all = "snake_case")]
2276pub enum NullKind {
2277    Null,
2278    NaN,
2279    NaT,
2280}
2281
2282/// JSON spelling of a `Scalar::Float64` payload. JSON has no infinity:
2283/// serde_json writes a non-finite `f64` as `null` and cannot read that back,
2284/// so a division-by-zero answer could not travel through a fixture or the
2285/// oracle at all. ±inf is spelled `"inf"` / `"-inf"` (the pandas oracle emits
2286/// the same strings); finite values and NaN serialize exactly as before, and
2287/// the `null` serde_json writes for NaN now reads back as NaN.
2288/// (br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.3)
2289mod float64_json {
2290    use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
2291
2292    pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
2293        if value.is_infinite() {
2294            serializer.serialize_str(if value.is_sign_positive() {
2295                "inf"
2296            } else {
2297                "-inf"
2298            })
2299        } else {
2300            serializer.serialize_f64(*value)
2301        }
2302    }
2303
2304    #[derive(Deserialize)]
2305    #[serde(untagged)]
2306    enum Repr {
2307        Number(f64),
2308        Text(String),
2309        Null(()),
2310    }
2311
2312    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
2313        match Repr::deserialize(deserializer)? {
2314            Repr::Number(value) => Ok(value),
2315            Repr::Text(text) => match text.as_str() {
2316                "inf" => Ok(f64::INFINITY),
2317                "-inf" => Ok(f64::NEG_INFINITY),
2318                other => Err(D::Error::custom(format!(
2319                    "float64 value must be a number, \"inf\" or \"-inf\", got {other:?}"
2320                ))),
2321            },
2322            Repr::Null(()) => Ok(f64::NAN),
2323        }
2324    }
2325}
2326
2327#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2328#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
2329pub enum Scalar {
2330    Null(NullKind),
2331    Bool(bool),
2332    Int64(i64),
2333    Float64(#[serde(with = "float64_json")] f64),
2334    #[serde(alias = "string", alias = "str")]
2335    Utf8(String),
2336    Timedelta64(i64),
2337    /// Nanoseconds since Unix epoch. Matches pandas `datetime64[ns]`.
2338    /// Uses `Timestamp::NAT` (i64::MIN) for missing values.
2339    Datetime64(i64),
2340    /// Period value (ordinal + frequency). A `Period` whose `ordinal` is
2341    /// `i64::MIN` is NaT (missing). The frequency is carried so writers can
2342    /// render the pandas calendar string (`2024Q1`, `2024-03`, ...) — the
2343    /// calendar string is not recoverable from the ordinal alone, since
2344    /// different frequencies share overlapping ordinal axes.
2345    Period(Period),
2346    /// Numeric interval value. Missing values remain `Scalar::Null`.
2347    Interval(Interval),
2348    /// A pandas object cell none of the kinds above holds: a list
2349    /// (`str.split`'s cells, `Series([[1, 2], [3]])`) or a host-language
2350    /// value the core only carries (fvsao.33).
2351    Object(ObjectValue),
2352}
2353
2354/// A pandas object cell that is not one of [`Scalar`]'s value kinds: a list,
2355/// or a value of the host language (a Python `datetime.date`, dict, numpy
2356/// dtype) that the core carries without reading (fvsao.33).
2357#[derive(Clone)]
2358pub enum ObjectValue {
2359    /// A list of values, compared and printed as Python's list.
2360    List(std::sync::Arc<[Scalar]>),
2361    /// A bytes value, compared and printed as Python's bytes (`b'ab'`):
2362    /// `str.encode`'s cells. The core reads it, so a bytes column needs no
2363    /// host (4qg5w.8).
2364    Bytes(std::sync::Arc<[u8]>),
2365    /// A host-language value, opaque to the core.
2366    Host(HostValue),
2367}
2368
2369/// A host-language value an object cell carries - the Python binding's
2370/// objects: compared and printed by the host itself.
2371pub trait HostObject: Send + Sync {
2372    /// `self == other` in the host language.
2373    fn host_eq(&self, other: &dyn HostObject) -> bool;
2374    /// The host's `repr` (`datetime.date(2024, 1, 5)`).
2375    fn host_repr(&self) -> String;
2376    /// The host's `str` (`2024-01-05`), what `astype(str)` makes of it.
2377    fn host_str(&self) -> String;
2378    /// The cell as pandas displays it in a repr (`pprint_thing`), where that
2379    /// differs from its `str`: a tuple's or array's items unquoted (`(a, 1)`,
2380    /// `[1, 2]`); by default its `str`.
2381    fn host_pprint(&self) -> String {
2382        self.host_str()
2383    }
2384    /// The host's hash, None for an unhashable value (a dict).
2385    fn host_hash(&self) -> Option<u64>;
2386    /// `self` ordered against `other` in the host language (Python's `<` /
2387    /// `>` / `==`), None where the host cannot order them (a date against a
2388    /// time, two dicts).
2389    fn host_cmp(&self, other: &dyn HostObject) -> Option<std::cmp::Ordering>;
2390    /// `self == other` in the host language for a plain value (numpy's
2391    /// `dtype('float64') == 'float64'` is True); false unless the host says so.
2392    fn host_eq_scalar(&self, _other: &Scalar) -> bool {
2393        false
2394    }
2395    /// The value's type as the host's own errors name it (`datetime.date`,
2396    /// `dict`), for a refusal pandas lets the host raise.
2397    fn host_type_name(&self) -> String {
2398        "object".to_owned()
2399    }
2400    /// The value itself, for the host that made it to take back.
2401    fn as_any(&self) -> &dyn std::any::Any;
2402}
2403
2404/// How many host objects are alive (see [`host_values_block_workers`]).
2405static LIVE_HOST_VALUES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2406
2407/// Whether this process's callers may hold a host lock (see
2408/// [`declare_host_lock`]).
2409static HOST_LOCK_DECLARED: std::sync::atomic::AtomicBool =
2410    std::sync::atomic::AtomicBool::new(false);
2411
2412/// Declare that callers into the core may hold a host lock that host objects
2413/// need - the Python binding, whose every call holds the GIL, declares it
2414/// when its module loads. Without it no worker is ever blocked.
2415pub fn declare_host_lock() {
2416    HOST_LOCK_DECLARED.store(true, std::sync::atomic::Ordering::Relaxed);
2417}
2418
2419/// Whether a parallel kernel must run inline (one worker): a host value
2420/// compares, hashes and prints through its host (Python), which a worker
2421/// thread reaches only by taking the host's lock (the GIL); when the thread
2422/// that spawned the worker holds that lock while it waits for the worker,
2423/// both wait forever - `DataFrame.groupby(dates).rank()` hung that way
2424/// (4qg5w.13). So while any host object is alive in a process whose callers
2425/// may hold that lock, kernels size themselves to one worker.
2426#[must_use]
2427pub fn host_values_block_workers() -> bool {
2428    workers_blocked(
2429        HOST_LOCK_DECLARED.load(std::sync::atomic::Ordering::Relaxed),
2430        LIVE_HOST_VALUES.load(std::sync::atomic::Ordering::Relaxed),
2431    )
2432}
2433
2434/// The rule of [`host_values_block_workers`], free of process state.
2435const fn workers_blocked(host_lock_declared: bool, live_host_values: usize) -> bool {
2436    host_lock_declared && live_host_values > 0
2437}
2438
2439/// A host object, counted alive while any handle to it exists.
2440struct HostSlot(Box<dyn HostObject>);
2441
2442impl Drop for HostSlot {
2443    fn drop(&mut self) {
2444        LIVE_HOST_VALUES.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2445    }
2446}
2447
2448/// A shared handle on a [`HostObject`].
2449#[derive(Clone)]
2450pub struct HostValue(std::sync::Arc<HostSlot>);
2451
2452impl HostValue {
2453    #[must_use]
2454    pub fn new(object: impl HostObject + 'static) -> Self {
2455        LIVE_HOST_VALUES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2456        Self(std::sync::Arc::new(HostSlot(Box::new(object))))
2457    }
2458
2459    #[must_use]
2460    pub fn object(&self) -> &dyn HostObject {
2461        &*self.0.0
2462    }
2463}
2464
2465impl PartialEq for HostValue {
2466    fn eq(&self, other: &Self) -> bool {
2467        std::sync::Arc::ptr_eq(&self.0, &other.0) || self.object().host_eq(other.object())
2468    }
2469}
2470
2471impl std::fmt::Debug for HostValue {
2472    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2473        formatter.write_str(&self.object().host_repr())
2474    }
2475}
2476
2477impl ObjectValue {
2478    /// A list cell of `items`.
2479    #[must_use]
2480    pub fn list(items: Vec<Scalar>) -> Self {
2481        Self::List(items.into())
2482    }
2483
2484    /// The items of a list cell.
2485    #[must_use]
2486    pub fn as_list(&self) -> Option<&[Scalar]> {
2487        match self {
2488            Self::List(items) => Some(items),
2489            Self::Bytes(_) | Self::Host(_) => None,
2490        }
2491    }
2492
2493    /// A bytes cell of `data`.
2494    #[must_use]
2495    pub fn bytes(data: Vec<u8>) -> Self {
2496        Self::Bytes(data.into())
2497    }
2498
2499    /// The bytes of a bytes cell.
2500    #[must_use]
2501    pub fn as_bytes(&self) -> Option<&[u8]> {
2502        match self {
2503            Self::Bytes(data) => Some(data),
2504            Self::List(_) | Self::Host(_) => None,
2505        }
2506    }
2507
2508    /// The cell as Python's `repr` spells it (`[1, 'a', None]`, `b'ab'`).
2509    #[must_use]
2510    pub fn repr(&self) -> String {
2511        match self {
2512            Self::List(items) => {
2513                let parts: Vec<String> = items.iter().map(Scalar::python_repr).collect();
2514                format!("[{}]", parts.join(", "))
2515            }
2516            Self::Bytes(data) => python_bytes_repr(data),
2517            Self::Host(value) => value.object().host_repr(),
2518        }
2519    }
2520
2521    /// The cell as pandas displays it in a repr (pandas' `pprint_thing`): a
2522    /// list's items unquoted (`[1, a]`), a host value as the host pprints it.
2523    #[must_use]
2524    pub fn pprint(&self) -> String {
2525        match self {
2526            Self::List(items) => {
2527                let parts: Vec<String> = items
2528                    .iter()
2529                    .map(|item| match item {
2530                        Scalar::Utf8(text) => text.clone(),
2531                        Scalar::Object(object) => object.pprint(),
2532                        other => other.python_repr(),
2533                    })
2534                    .collect();
2535                format!("[{}]", parts.join(", "))
2536            }
2537            Self::Bytes(data) => python_bytes_repr(data),
2538            Self::Host(value) => value.object().host_pprint(),
2539        }
2540    }
2541
2542    /// The cell's Python type as Python's errors name it (`list`, `bytes`,
2543    /// `datetime.date`).
2544    #[must_use]
2545    pub fn type_name(&self) -> String {
2546        match self {
2547            Self::List(_) => "list".to_owned(),
2548            Self::Bytes(_) => "bytes".to_owned(),
2549            Self::Host(value) => value.object().host_type_name(),
2550        }
2551    }
2552
2553    /// Python's `==` between this cell and a plain value: a host value asks
2554    /// the host (a dtype equals its name), a list or bytes never equals one
2555    /// (`b'a' == 'a'` is False).
2556    #[must_use]
2557    pub fn python_eq_scalar(&self, other: &Scalar) -> bool {
2558        match self {
2559            Self::Host(value) => value.object().host_eq_scalar(other),
2560            Self::List(_) | Self::Bytes(_) => false,
2561        }
2562    }
2563
2564    /// Python's ordering of two cells, None where Python raises: host values
2565    /// by the host, lists item by item (a shorter prefix first), bytes by
2566    /// byte, and cells of different kinds unordered.
2567    #[must_use]
2568    pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2569        match (self, other) {
2570            (Self::Bytes(left), Self::Bytes(right)) => Some(left.cmp(right)),
2571            (Self::Host(left), Self::Host(right)) => {
2572                if left == right {
2573                    Some(std::cmp::Ordering::Equal)
2574                } else {
2575                    left.object().host_cmp(right.object())
2576                }
2577            }
2578            (Self::List(left), Self::List(right)) => {
2579                for (a, b) in left.iter().zip(right.iter()) {
2580                    if a != b {
2581                        let ordering = a.python_cmp(b)?;
2582                        if ordering.is_ne() {
2583                            return Some(ordering);
2584                        }
2585                    }
2586                }
2587                Some(left.len().cmp(&right.len()))
2588            }
2589            _ => None,
2590        }
2591    }
2592
2593    /// A total order over cells, for sorted labels and ordered maps: Python's
2594    /// ordering where it has one; otherwise a list before a host value, then
2595    /// the reprs, then identity - so two unequal cells are never Equal and
2596    /// equal cells always are.
2597    #[must_use]
2598    pub fn total_cmp(&self, other: &Self) -> std::cmp::Ordering {
2599        use std::cmp::Ordering;
2600        if self == other {
2601            return Ordering::Equal;
2602        }
2603        if let Some(ordering) = self.python_cmp(other).filter(|ordering| ordering.is_ne()) {
2604            return ordering;
2605        }
2606        let rank = |cell: &Self| match cell {
2607            Self::List(_) => 0_u8,
2608            Self::Bytes(_) => 1,
2609            Self::Host(_) => 2,
2610        };
2611        rank(self)
2612            .cmp(&rank(other))
2613            .then_with(|| self.repr().cmp(&other.repr()))
2614            .then_with(|| self.address().cmp(&other.address()))
2615    }
2616
2617    /// Where the cell's shared data lives: the last tie-break of
2618    /// [`Self::total_cmp`] between unequal cells that print alike.
2619    fn address(&self) -> usize {
2620        match self {
2621            Self::List(items) => items.as_ptr().addr(),
2622            Self::Bytes(data) => data.as_ptr().addr(),
2623            Self::Host(value) => std::sync::Arc::as_ptr(&value.0).cast::<()>().addr(),
2624        }
2625    }
2626}
2627
2628/// Python's `repr` of a bytes value: `b'...'` (double quotes when it holds a
2629/// `'` and no `"`), printable ASCII as itself, `\\`, `\t`, `\n`, `\r` and
2630/// the quote escaped, every other byte as `\xNN`.
2631#[must_use]
2632pub fn python_bytes_repr(data: &[u8]) -> String {
2633    let quote = if data.contains(&b'\'') && !data.contains(&b'"') {
2634        b'"'
2635    } else {
2636        b'\''
2637    };
2638    let mut out = String::with_capacity(data.len() + 3);
2639    out.push('b');
2640    out.push(char::from(quote));
2641    for &byte in data {
2642        match byte {
2643            b'\\' => out.push_str("\\\\"),
2644            b'\t' => out.push_str("\\t"),
2645            b'\n' => out.push_str("\\n"),
2646            b'\r' => out.push_str("\\r"),
2647            _ if byte == quote => {
2648                out.push('\\');
2649                out.push(char::from(byte));
2650            }
2651            0x20..=0x7e => out.push(char::from(byte)),
2652            _ => out.push_str(&format!("\\x{byte:02x}")),
2653        }
2654    }
2655    out.push(char::from(quote));
2656    out
2657}
2658
2659impl PartialOrd for ObjectValue {
2660    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2661        Some(self.cmp(other))
2662    }
2663}
2664
2665/// [`ObjectValue::total_cmp`], so a cell can be an ordered label.
2666impl Ord for ObjectValue {
2667    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2668        self.total_cmp(other)
2669    }
2670}
2671
2672impl PartialEq for ObjectValue {
2673    fn eq(&self, other: &Self) -> bool {
2674        match (self, other) {
2675            (Self::List(left), Self::List(right)) => left == right,
2676            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2677            (Self::Host(left), Self::Host(right)) => left == right,
2678            _ => false,
2679        }
2680    }
2681}
2682
2683/// So a cell can key a hash map (groupby, unique, isin): lists by their
2684/// items' reprs, host values by the host's hash (their repr when the host
2685/// has none).
2686impl Eq for ObjectValue {}
2687
2688impl std::hash::Hash for ObjectValue {
2689    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2690        match self {
2691            Self::List(items) => {
2692                0_u8.hash(state);
2693                for item in items.iter() {
2694                    item.python_repr().hash(state);
2695                }
2696            }
2697            Self::Bytes(data) => {
2698                2_u8.hash(state);
2699                data.hash(state);
2700            }
2701            Self::Host(value) => {
2702                1_u8.hash(state);
2703                match value.object().host_hash() {
2704                    Some(hash) => hash.hash(state),
2705                    None => value.object().host_repr().hash(state),
2706                }
2707            }
2708        }
2709    }
2710}
2711
2712impl std::fmt::Debug for ObjectValue {
2713    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2714        formatter.write_str(&self.repr())
2715    }
2716}
2717
2718/// Python's `str` of the cell - what `astype(str)` and the writers produce:
2719/// a list or bytes as its repr (`['a', 1]`, `b'ab'`), a host value as its
2720/// str.
2721impl std::fmt::Display for ObjectValue {
2722    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2723        match self {
2724            Self::List(_) | Self::Bytes(_) => formatter.write_str(&self.repr()),
2725            Self::Host(value) => formatter.write_str(&value.object().host_str()),
2726        }
2727    }
2728}
2729
2730/// A list cell serializes as the sequence of its items, a bytes cell as
2731/// `{"bytes": [..]}`; a host value has no serialized form.
2732impl Serialize for ObjectValue {
2733    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2734        match self {
2735            Self::List(items) => items.as_ref().serialize(serializer),
2736            Self::Bytes(data) => SerializedObject::Bytes {
2737                bytes: data.to_vec(),
2738            }
2739            .serialize(serializer),
2740            Self::Host(_) => Err(serde::ser::Error::custom(
2741                "a host-language object cell cannot be serialized",
2742            )),
2743        }
2744    }
2745}
2746
2747/// The serialized forms of an object cell: a list's items, or a bytes
2748/// value's bytes.
2749#[derive(Serialize, Deserialize)]
2750#[serde(untagged)]
2751enum SerializedObject {
2752    List(Vec<Scalar>),
2753    Bytes { bytes: Vec<u8> },
2754}
2755
2756impl<'de> Deserialize<'de> for ObjectValue {
2757    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2758        Ok(match SerializedObject::deserialize(deserializer)? {
2759            SerializedObject::List(items) => Self::list(items),
2760            SerializedObject::Bytes { bytes } => Self::bytes(bytes),
2761        })
2762    }
2763}
2764
2765impl std::fmt::Display for Scalar {
2766    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2767        match self {
2768            Self::Null(NullKind::NaN) => write!(f, "NaN"),
2769            Self::Null(NullKind::NaT) => write!(f, "NaT"),
2770            Self::Null(NullKind::Null) => write!(f, "None"),
2771            Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
2772            Self::Int64(v) => write!(f, "{v}"),
2773            Self::Float64(v) => write!(f, "{v}"),
2774            Self::Utf8(s) => write!(f, "{s}"),
2775            Self::Timedelta64(nanos) => write!(f, "{}", Timedelta::format(*nanos)),
2776            Self::Datetime64(nanos) => {
2777                if *nanos == Timestamp::NAT {
2778                    write!(f, "NaT")
2779                } else {
2780                    write!(f, "Timestamp[{nanos}]")
2781                }
2782            }
2783            Self::Period(p) => {
2784                if p.ordinal == i64::MIN {
2785                    write!(f, "NaT")
2786                } else {
2787                    write!(f, "{}", p.calendar_string())
2788                }
2789            }
2790            Self::Interval(interval) => write!(f, "{interval}"),
2791            Self::Object(object) => write!(f, "{object}"),
2792        }
2793    }
2794}
2795
2796impl Scalar {
2797    /// Python's ordering of two values: numbers by value, text by code
2798    /// point, instants, durations and same-frequency periods by their
2799    /// payload, intervals by (left, right), object cells by
2800    /// [`ObjectValue::python_cmp`]; None where
2801    /// Python raises (a number against text, a list against a tuple, two
2802    /// dicts).
2803    #[must_use]
2804    pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2805        let numeric =
2806            |value: &Self| matches!(value, Self::Bool(_) | Self::Int64(_) | Self::Float64(_));
2807        match (self, other) {
2808            (Self::Utf8(a), Self::Utf8(b)) => Some(a.cmp(b)),
2809            (Self::Datetime64(a), Self::Datetime64(b))
2810            | (Self::Timedelta64(a), Self::Timedelta64(b)) => Some(a.cmp(b)),
2811            (Self::Period(a), Self::Period(b)) if a.freq == b.freq => {
2812                Some(a.ordinal.cmp(&b.ordinal))
2813            }
2814            (Self::Interval(a), Self::Interval(b)) => Some(
2815                a.left
2816                    .partial_cmp(&b.left)?
2817                    .then(a.right.partial_cmp(&b.right)?),
2818            ),
2819            (Self::Object(a), Self::Object(b)) => a.python_cmp(b),
2820            _ if numeric(self) && numeric(other) => {
2821                self.to_f64().ok()?.partial_cmp(&other.to_f64().ok()?)
2822            }
2823            _ => None,
2824        }
2825    }
2826
2827    /// The two types Python's TypeError names when it cannot order `self`
2828    /// against `other` (see [`Self::python_cmp`]): two lists by the first
2829    /// unequal items they hold (`[1] < ['a']` names 'int' and 'str'), any
2830    /// other pair by their own types.
2831    #[must_use]
2832    pub fn python_cmp_type_names(&self, other: &Self) -> (String, String) {
2833        if let (Self::Object(ObjectValue::List(left)), Self::Object(ObjectValue::List(right))) =
2834            (self, other)
2835            && let Some((a, b)) = left.iter().zip(right.iter()).find(|(a, b)| a != b)
2836        {
2837            return a.python_cmp_type_names(b);
2838        }
2839        (self.python_type_name(), other.python_type_name())
2840    }
2841
2842    /// The value's Python type as Python's errors name it (`str`, `int`,
2843    /// `Timestamp`, `list`), for a TypeError pandas lets Python raise.
2844    #[must_use]
2845    pub fn python_type_name(&self) -> String {
2846        match self {
2847            Self::Null(NullKind::NaN) | Self::Float64(_) => "float",
2848            Self::Null(NullKind::NaT) => "NaTType",
2849            Self::Null(NullKind::Null) => "NoneType",
2850            Self::Bool(_) => "bool",
2851            Self::Int64(_) => "int",
2852            Self::Utf8(_) => "str",
2853            Self::Timedelta64(_) => "Timedelta",
2854            Self::Datetime64(_) => "Timestamp",
2855            Self::Period(_) => "Period",
2856            Self::Interval(_) => "Interval",
2857            Self::Object(object) => return object.type_name(),
2858        }
2859        .to_owned()
2860    }
2861
2862    /// The value as Python's `repr` spells it inside a container (`'a'`,
2863    /// `1`, `1.5`, `None`, `nan`, `[1, 2]`) - how a list cell prints its
2864    /// items.
2865    #[must_use]
2866    pub fn python_repr(&self) -> String {
2867        match self {
2868            Self::Null(NullKind::NaN) => "nan".to_owned(),
2869            Self::Null(NullKind::NaT) => "NaT".to_owned(),
2870            Self::Null(NullKind::Null) => "None".to_owned(),
2871            Self::Utf8(text) => {
2872                let quote = if text.contains('\'') && !text.contains('"') {
2873                    '"'
2874                } else {
2875                    '\''
2876                };
2877                let mut out = String::with_capacity(text.len() + 2);
2878                out.push(quote);
2879                for ch in text.chars() {
2880                    match ch {
2881                        '\\' => out.push_str("\\\\"),
2882                        '\n' => out.push_str("\\n"),
2883                        '\r' => out.push_str("\\r"),
2884                        '\t' => out.push_str("\\t"),
2885                        c if c == quote => {
2886                            out.push('\\');
2887                            out.push(c);
2888                        }
2889                        c => out.push(c),
2890                    }
2891                }
2892                out.push(quote);
2893                out
2894            }
2895            Self::Float64(value) => {
2896                if value.is_nan() {
2897                    "nan".to_owned()
2898                } else if value.is_infinite() {
2899                    if *value > 0.0 { "inf" } else { "-inf" }.to_owned()
2900                } else if value.fract() == 0.0 && value.abs() < 1e16 {
2901                    format!("{value:.1}")
2902                } else {
2903                    format!("{value}")
2904                }
2905            }
2906            Self::Object(object) => object.repr(),
2907            other => other.to_string(),
2908        }
2909    }
2910}
2911
2912/// Pandas `pd.NA` singleton representing missing data in nullable dtypes.
2913pub const NA: Scalar = Scalar::Null(NullKind::Null);
2914
2915/// Pandas `pd.NaT` singleton representing Not-a-Time in datetime/timedelta data.
2916pub const NAT: Scalar = Scalar::Null(NullKind::NaT);
2917
2918/// Alias for [`NAT`] matching pandas capitalization `pd.NaT`.
2919#[allow(non_upper_case_globals)]
2920pub const NaT: Scalar = NAT;
2921
2922// Ergonomic From impls (br-frankenpandas-esjjy / fd90.182). Mirrors
2923// IndexLabel's From<i64>/From<&str>/From<String> so users can write
2924//   let v: Vec<Scalar> = vec![1i64.into(), 2.0.into(), "three".into()];
2925// instead of the explicit Scalar::Int64(...)/Scalar::Float64(...) form.
2926//
2927// i64 maps to Int64 (more common than Timedelta64 in pandas-style code).
2928// Users wanting Timedelta64 should construct it explicitly with
2929// Scalar::Timedelta64(nanos) or via Timedelta::parse / to_timedelta.
2930
2931impl From<bool> for Scalar {
2932    fn from(value: bool) -> Self {
2933        Self::Bool(value)
2934    }
2935}
2936
2937impl From<i64> for Scalar {
2938    fn from(value: i64) -> Self {
2939        Self::Int64(value)
2940    }
2941}
2942
2943impl From<f64> for Scalar {
2944    fn from(value: f64) -> Self {
2945        Self::Float64(value)
2946    }
2947}
2948
2949impl From<&str> for Scalar {
2950    fn from(value: &str) -> Self {
2951        Self::Utf8(value.to_owned())
2952    }
2953}
2954
2955impl From<String> for Scalar {
2956    fn from(value: String) -> Self {
2957        Self::Utf8(value)
2958    }
2959}
2960
2961impl Scalar {
2962    #[inline]
2963    const fn debug_variant_name(&self) -> &'static str {
2964        match self {
2965            Self::Null(_) => "Null",
2966            Self::Bool(_) => "Bool",
2967            Self::Int64(_) => "Int64",
2968            Self::Float64(_) => "Float64",
2969            Self::Utf8(_) => "Utf8",
2970            Self::Timedelta64(_) => "Timedelta64",
2971            Self::Datetime64(_) => "Datetime64",
2972            Self::Period(_) => "Period",
2973            Self::Interval(_) => "Interval",
2974            Self::Object(_) => "Object",
2975        }
2976    }
2977
2978    #[must_use]
2979    pub fn dtype(&self) -> DType {
2980        match self {
2981            Self::Null(_) => DType::Null,
2982            Self::Bool(_) => DType::Bool,
2983            Self::Int64(_) => DType::Int64,
2984            Self::Float64(_) => DType::Float64,
2985            Self::Utf8(_) => DType::Utf8,
2986            Self::Timedelta64(_) => DType::Timedelta64,
2987            Self::Datetime64(_) => DType::datetime64_naive(),
2988            Self::Period(_) => DType::Period,
2989            Self::Interval(_) => DType::Interval,
2990            // pandas' object dtype, which this crate spells Utf8.
2991            Self::Object(_) => DType::Utf8,
2992        }
2993    }
2994
2995    #[must_use]
2996    pub fn is_missing(&self) -> bool {
2997        match self {
2998            Self::Null(_) => true,
2999            Self::Float64(v) => v.is_nan(),
3000            Self::Timedelta64(v) => *v == Timedelta::NAT,
3001            Self::Datetime64(v) => *v == Timestamp::NAT,
3002            Self::Period(p) => p.ordinal == i64::MIN,
3003            _ => false,
3004        }
3005    }
3006
3007    #[must_use]
3008    pub fn is_nan(&self) -> bool {
3009        matches!(self, Self::Null(NullKind::NaN)) || matches!(self, Self::Float64(v) if v.is_nan())
3010    }
3011
3012    /// Returns true if this is a Bool scalar.
3013    #[must_use]
3014    pub const fn is_bool(&self) -> bool {
3015        matches!(self, Self::Bool(_))
3016    }
3017
3018    /// Returns true if this is an Int64 scalar.
3019    #[must_use]
3020    pub const fn is_integer(&self) -> bool {
3021        matches!(self, Self::Int64(_))
3022    }
3023
3024    /// Returns true if this is a Float64 scalar.
3025    #[must_use]
3026    pub const fn is_float(&self) -> bool {
3027        matches!(self, Self::Float64(_))
3028    }
3029
3030    /// Returns true if this is a numeric scalar (Int64 or Float64).
3031    #[must_use]
3032    pub const fn is_numeric(&self) -> bool {
3033        matches!(self, Self::Int64(_) | Self::Float64(_))
3034    }
3035
3036    /// Returns true if this is a Utf8 (string) scalar.
3037    #[must_use]
3038    pub const fn is_string(&self) -> bool {
3039        matches!(self, Self::Utf8(_))
3040    }
3041
3042    /// Returns true if this is a Datetime64 scalar.
3043    #[must_use]
3044    pub const fn is_datetime(&self) -> bool {
3045        matches!(self, Self::Datetime64(_))
3046    }
3047
3048    /// Returns true if this is a Timedelta64 scalar.
3049    #[must_use]
3050    pub const fn is_timedelta(&self) -> bool {
3051        matches!(self, Self::Timedelta64(_))
3052    }
3053
3054    /// Returns true if this is a Period scalar.
3055    #[must_use]
3056    pub const fn is_period(&self) -> bool {
3057        matches!(self, Self::Period(_))
3058    }
3059
3060    /// Returns true if this is an Interval scalar.
3061    #[must_use]
3062    pub const fn is_interval(&self) -> bool {
3063        matches!(self, Self::Interval(_))
3064    }
3065
3066    /// Returns the wrapped i64 if this is an [`Scalar::Int64`] variant.
3067    #[must_use]
3068    pub const fn as_i64(&self) -> Option<i64> {
3069        match self {
3070            Self::Int64(v) => Some(*v),
3071            _ => None,
3072        }
3073    }
3074
3075    /// Alias for [`Scalar::as_i64`].
3076    #[must_use]
3077    pub const fn as_int(&self) -> Option<i64> {
3078        self.as_i64()
3079    }
3080
3081    /// Returns the wrapped f64 if this is a [`Scalar::Float64`] variant.
3082    #[must_use]
3083    pub const fn as_f64(&self) -> Option<f64> {
3084        match self {
3085            Self::Float64(v) => Some(*v),
3086            _ => None,
3087        }
3088    }
3089
3090    /// Alias for [`Scalar::as_f64`].
3091    #[must_use]
3092    pub const fn as_float(&self) -> Option<f64> {
3093        self.as_f64()
3094    }
3095
3096    /// Returns the wrapped bool if this is a [`Scalar::Bool`] variant.
3097    #[must_use]
3098    pub const fn as_bool(&self) -> Option<bool> {
3099        match self {
3100            Self::Bool(v) => Some(*v),
3101            _ => None,
3102        }
3103    }
3104
3105    /// Returns a string slice if this is a [`Scalar::Utf8`] variant.
3106    #[must_use]
3107    pub fn as_str(&self) -> Option<&str> {
3108        match self {
3109            Self::Utf8(s) => Some(s.as_str()),
3110            _ => None,
3111        }
3112    }
3113
3114    /// Returns the raw nanoseconds timestamp if this is a [`Scalar::Datetime64`] variant.
3115    #[must_use]
3116    pub const fn as_datetime_nanos(&self) -> Option<i64> {
3117        match self {
3118            Self::Datetime64(v) => Some(*v),
3119            _ => None,
3120        }
3121    }
3122
3123    /// Returns the raw nanoseconds duration if this is a [`Scalar::Timedelta64`] variant.
3124    #[must_use]
3125    pub const fn as_timedelta_nanos(&self) -> Option<i64> {
3126        match self {
3127            Self::Timedelta64(v) => Some(*v),
3128            _ => None,
3129        }
3130    }
3131
3132    /// Returns the period ordinal if this is a [`Scalar::Period`] variant.
3133    #[must_use]
3134    pub const fn as_period_ordinal(&self) -> Option<i64> {
3135        match self {
3136            Self::Period(p) => Some(p.ordinal),
3137            _ => None,
3138        }
3139    }
3140
3141    /// Returns the [`Interval`] if this is a [`Scalar::Interval`] variant.
3142    #[must_use]
3143    pub const fn as_interval(&self) -> Option<Interval> {
3144        match self {
3145            Self::Interval(i) => Some(*i),
3146            _ => None,
3147        }
3148    }
3149
3150    #[must_use]
3151    pub fn missing_for_dtype(dtype: DType) -> Self {
3152        match dtype {
3153            DType::Float64 => Self::Null(NullKind::NaN),
3154            // NOT NaN, and this is the whole reason the dtype exists. MEASURED,
3155            // live pandas 2.2.3: a Float64 lane stores pd.NA, and it coerces an
3156            // explicit NaN INPUT to pd.NA —
3157            //     pd.Series([float("nan")], dtype="Float64")[0]  ->  <NA>
3158            // whereas the numpy lane above keeps a real NaN. Giving this dtype
3159            // NullKind::NaN would make the two flavours indistinguishable, which
3160            // is exactly the gap br-frankenpandas-qkqfb was filed for.
3161            DType::Float64Nullable => Self::Null(NullKind::Null),
3162            DType::Timedelta64 => Self::Timedelta64(Timedelta::NAT),
3163            DType::Datetime64 { .. } => Self::Datetime64(Timestamp::NAT),
3164            DType::Period => Self::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
3165            DType::Null => Self::Null(NullKind::Null),
3166            DType::Bool
3167            | DType::BoolNullable
3168            | DType::Int64
3169            | DType::Int64Nullable
3170            | DType::Utf8
3171            | DType::Categorical
3172            | DType::Interval
3173            | DType::Sparse => Self::Null(NullKind::Null),
3174        }
3175    }
3176
3177    #[must_use]
3178    pub fn semantic_eq(&self, other: &Self) -> bool {
3179        match (self, other) {
3180            (Self::Float64(a), Self::Float64(b)) => {
3181                if a.is_nan() && b.is_nan() {
3182                    return true;
3183                }
3184                if *a == *b {
3185                    return true;
3186                }
3187                let diff = (*a - *b).abs();
3188                let max_abs = a.abs().max(b.abs());
3189                if max_abs == 0.0 {
3190                    diff < f64::EPSILON
3191                } else {
3192                    diff / max_abs < 1e-14
3193                }
3194            }
3195            (Self::Null(_), Self::Float64(v)) | (Self::Float64(v), Self::Null(_)) => v.is_nan(),
3196            // All Null kinds (Null / NaN / NaT) mark missingness; they are
3197            // semantically indistinguishable for oracle-parity checks even
3198            // though derived PartialEq would reject a cross-kind pair.
3199            // fp-frame normalizes Float64 column missing cells to
3200            // Null(NaN) at Column::new time, while fixture oracles encode
3201            // the canonical missing marker as Null(Null).
3202            (Self::Null(_), Self::Null(_)) => true,
3203            // The DTYPE-SENTINEL missings are missing too, and this function
3204            // already says so for every other flavour. `missing_for_dtype`
3205            // DEFINES the canonical missing for Timedelta64 as
3206            // `Timedelta64(Timedelta::NAT)`, for Datetime64 as
3207            // `Datetime64(Timestamp::NAT)` and for Period as ordinal
3208            // `i64::MIN`, and `is_missing()` returns true for all three — but
3209            // without this arm none of them could ever equal the `Null` marker
3210            // an oracle records for pandas' NaT, so a parity check compared a
3211            // raw i64::MIN bit pattern against a null and called it a value
3212            // mismatch.
3213            //
3214            // OBSERVED on fp_p2d_021_series_to_timedelta_negative_null_hardened:
3215            //   FP     timedelta64:-9223372036854775808
3216            //   pandas null           (the format has no `na_t` marker, so
3217            //                          `null` IS NaT there)
3218            //
3219            // `compare_join_expected` in fp-conformance already carried this as
3220            // a manual `|| (left.is_missing() && right.is_missing())`; putting
3221            // it here makes that clause redundant instead of special, and
3222            // covers the series and dataframe comparators that lacked it.
3223            //
3224            // This is a COMPARISON rule only. It deliberately does not touch
3225            // `missing_for_dtype`: fp-columnar's 2026-07-14 NullKind TRAP note
3226            // records that the sentinel and `Null(NaT)` representations coexist
3227            // inside one column and a uniform gather cannot reproduce the mix,
3228            // which is a storage-model question. (br-frankenpandas-xwxci)
3229            _ if self.is_missing() && other.is_missing() => true,
3230            // An Interval's `==` ignores its subtype (pandas' Interval(0, 3)
3231            // == Interval(0.0, 3.0)), but interval[int64] and
3232            // interval[float64] are different pandas dtypes - '(0, 3]' and
3233            // '(0.0, 3.0]' (fvsao.54).
3234            (Self::Interval(a), Self::Interval(b)) => a == b && a.subtype == b.subtype,
3235            _ => self == other,
3236        }
3237    }
3238
3239    #[must_use]
3240    pub fn semantic_le(&self, other: &Self) -> bool {
3241        match self.semantic_cmp(other) {
3242            std::cmp::Ordering::Less | std::cmp::Ordering::Equal => true,
3243            std::cmp::Ordering::Greater => false,
3244        }
3245    }
3246
3247    #[must_use]
3248    pub fn semantic_ge(&self, other: &Self) -> bool {
3249        match self.semantic_cmp(other) {
3250            std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => true,
3251            std::cmp::Ordering::Less => false,
3252        }
3253    }
3254
3255    #[must_use]
3256    pub fn is_null(&self) -> bool {
3257        matches!(self, Self::Null(_))
3258    }
3259
3260    #[must_use]
3261    pub fn is_na(&self) -> bool {
3262        self.is_missing()
3263    }
3264
3265    /// Return `true` if this scalar is NA/missing (alias for [`Self::is_na`]).
3266    #[must_use]
3267    pub fn isna(&self) -> bool {
3268        self.is_missing()
3269    }
3270
3271    /// Return `true` if this scalar is null (alias for [`Self::is_null`]).
3272    #[must_use]
3273    pub fn isnull(&self) -> bool {
3274        self.is_null()
3275    }
3276
3277    /// Return `true` if this scalar is not NA/missing (matches pandas `notna`).
3278    #[must_use]
3279    pub fn notna(&self) -> bool {
3280        !self.is_missing()
3281    }
3282
3283    /// Return `true` if this scalar is not null/missing (matches pandas `notnull`).
3284    #[must_use]
3285    pub fn notnull(&self) -> bool {
3286        !self.is_missing()
3287    }
3288
3289    /// Return `true` if this scalar is not NA/missing.
3290    #[must_use]
3291    pub fn is_not_na(&self) -> bool {
3292        !self.is_missing()
3293    }
3294
3295    /// Return `true` if this scalar is not NA/missing.
3296    #[must_use]
3297    pub fn not_na(&self) -> bool {
3298        !self.is_missing()
3299    }
3300
3301    #[must_use]
3302    pub fn coalesce(&self, other: &Self) -> Self {
3303        if self.is_missing() {
3304            other.clone()
3305        } else {
3306            self.clone()
3307        }
3308    }
3309
3310    #[must_use]
3311    pub fn semantic_cmp(&self, other: &Self) -> std::cmp::Ordering {
3312        match (self, other) {
3313            (Self::Int64(a), Self::Int64(b)) => a.cmp(b),
3314            (Self::Float64(a), Self::Float64(b)) => {
3315                a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
3316            }
3317            (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
3318            (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
3319            (Self::Null(a), Self::Null(b)) => a.cmp(b),
3320            (Self::Timedelta64(a), Self::Timedelta64(b)) => {
3321                if *a == Timedelta::NAT || *b == Timedelta::NAT {
3322                    std::cmp::Ordering::Equal
3323                } else {
3324                    a.cmp(b)
3325                }
3326            }
3327            (Self::Datetime64(a), Self::Datetime64(b)) => {
3328                if *a == Timestamp::NAT || *b == Timestamp::NAT {
3329                    std::cmp::Ordering::Equal
3330                } else {
3331                    a.cmp(b)
3332                }
3333            }
3334            (Self::Period(a), Self::Period(b)) => {
3335                if a.ordinal == i64::MIN || b.ordinal == i64::MIN {
3336                    std::cmp::Ordering::Equal
3337                } else {
3338                    a.ordinal.cmp(&b.ordinal)
3339                }
3340            }
3341            (Self::Interval(a), Self::Interval(b)) => a
3342                .left
3343                .partial_cmp(&b.left)
3344                .unwrap_or(std::cmp::Ordering::Equal)
3345                .then_with(|| {
3346                    a.right
3347                        .partial_cmp(&b.right)
3348                        .unwrap_or(std::cmp::Ordering::Equal)
3349                })
3350                .then_with(|| a.closed.cmp(&b.closed)),
3351            // Object cells (dates, lists) in Python's order (fvsao.66).
3352            (Self::Object(a), Self::Object(b)) => a.cmp(b),
3353            // Cross-numeric comparison
3354            (Self::Int64(a), Self::Float64(b)) => (*a as f64)
3355                .partial_cmp(b)
3356                .unwrap_or(std::cmp::Ordering::Equal),
3357            (Self::Float64(a), Self::Int64(b)) => a
3358                .partial_cmp(&(*b as f64))
3359                .unwrap_or(std::cmp::Ordering::Equal),
3360            // Derived Debug starts every variant with its static variant name.
3361            // Different variants therefore order by that name before either
3362            // payload is observed; compare those names without allocating.
3363            (a, b) => a.debug_variant_name().cmp(b.debug_variant_name()),
3364        }
3365    }
3366
3367    pub fn to_f64(&self) -> Result<f64, TypeError> {
3368        match self {
3369            Self::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
3370            Self::Int64(v) => Ok(*v as f64),
3371            Self::Float64(v) => Ok(*v),
3372            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3373            Self::Utf8(v) => Err(TypeError::NonNumericValue {
3374                value: v.clone(),
3375                dtype: DType::Utf8,
3376            }),
3377            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3378                kind: NullKind::NaT,
3379            }),
3380            Self::Timedelta64(v) => Err(TypeError::NonNumericValue {
3381                value: Timedelta::format(*v),
3382                dtype: DType::Timedelta64,
3383            }),
3384            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3385                kind: NullKind::NaT,
3386            }),
3387            Self::Datetime64(v) => Err(TypeError::NonNumericValue {
3388                value: format!("Timestamp[{v}]"),
3389                dtype: DType::datetime64_naive(),
3390            }),
3391            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3392                kind: NullKind::NaT,
3393            }),
3394            Self::Period(p) => Err(TypeError::NonNumericValue {
3395                value: p.calendar_string(),
3396                dtype: DType::Period,
3397            }),
3398            Self::Interval(v) => Err(TypeError::NonNumericValue {
3399                value: v.to_string(),
3400                dtype: DType::Interval,
3401            }),
3402            Self::Object(object) => Err(TypeError::NonNumericValue {
3403                value: object.repr(),
3404                dtype: DType::Utf8,
3405            }),
3406        }
3407    }
3408
3409    /// Try to convert to i64. Returns error for missing or non-numeric values.
3410    pub fn to_i64(&self) -> Result<i64, TypeError> {
3411        match self {
3412            Self::Bool(v) => Ok(if *v { 1 } else { 0 }),
3413            Self::Int64(v) => Ok(*v),
3414            Self::Float64(v) => Ok(*v as i64),
3415            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3416            Self::Utf8(v) => Err(TypeError::NonNumericValue {
3417                value: v.clone(),
3418                dtype: DType::Utf8,
3419            }),
3420            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3421                kind: NullKind::NaT,
3422            }),
3423            Self::Timedelta64(v) => Ok(*v),
3424            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3425                kind: NullKind::NaT,
3426            }),
3427            Self::Datetime64(v) => Ok(*v),
3428            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3429                kind: NullKind::NaT,
3430            }),
3431            Self::Period(p) => Ok(p.ordinal),
3432            Self::Interval(v) => Err(TypeError::NonNumericValue {
3433                value: v.to_string(),
3434                dtype: DType::Interval,
3435            }),
3436            Self::Object(object) => Err(TypeError::NonNumericValue {
3437                value: object.repr(),
3438                dtype: DType::Utf8,
3439            }),
3440        }
3441    }
3442
3443    /// Try to convert to bool. Returns error for missing values.
3444    pub fn to_bool(&self) -> Result<bool, TypeError> {
3445        match self {
3446            Self::Bool(v) => Ok(*v),
3447            Self::Int64(v) => Ok(*v != 0),
3448            Self::Float64(v) => Ok(*v != 0.0 && !v.is_nan()),
3449            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3450            Self::Utf8(v) => Ok(!v.is_empty()),
3451            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3452                kind: NullKind::NaT,
3453            }),
3454            Self::Timedelta64(v) => Ok(*v != 0),
3455            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3456                kind: NullKind::NaT,
3457            }),
3458            Self::Datetime64(v) => Ok(*v != 0),
3459            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3460                kind: NullKind::NaT,
3461            }),
3462            Self::Period(p) => Ok(p.ordinal != 0),
3463            Self::Interval(_) => Ok(true),
3464            // Python's truth: a list or bytes is true when it has items, any
3465            // other object true.
3466            Self::Object(ObjectValue::List(items)) => Ok(!items.is_empty()),
3467            Self::Object(ObjectValue::Bytes(data)) => Ok(!data.is_empty()),
3468            Self::Object(ObjectValue::Host(_)) => Ok(true),
3469        }
3470    }
3471
3472    /// Try to convert to string representation.
3473    pub fn to_str(&self) -> String {
3474        match self {
3475            Self::Bool(v) => if *v { "True" } else { "False" }.to_string(),
3476            Self::Int64(v) => v.to_string(),
3477            Self::Float64(v) => {
3478                if v.is_nan() {
3479                    "nan".to_string()
3480                } else if v.is_infinite() {
3481                    if *v > 0.0 { "inf" } else { "-inf" }.to_string()
3482                } else {
3483                    v.to_string()
3484                }
3485            }
3486            Self::Null(_) => "NaN".to_string(),
3487            Self::Utf8(v) => v.clone(),
3488            Self::Timedelta64(v) => Timedelta::format(*v),
3489            Self::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_string(),
3490            Self::Datetime64(v) => Timestamp::from_nanos(*v).isoformat(),
3491            Self::Period(p) if p.ordinal == i64::MIN => "NaT".to_string(),
3492            Self::Period(p) => p.calendar_string(),
3493            Self::Interval(v) => v.to_string(),
3494            Self::Object(object) => object.to_string(),
3495        }
3496    }
3497}
3498
3499#[derive(Debug, Error, Clone, PartialEq)]
3500pub enum TypeError {
3501    #[error("dtype coercion from {left:?} to {right:?} has no compatible common type")]
3502    IncompatibleDtypes { left: DType, right: DType },
3503    #[error("cannot cast scalar of dtype {from:?} to {to:?}")]
3504    InvalidCast { from: DType, to: DType },
3505    #[error("cannot cast float {value} to int64 without loss")]
3506    LossyFloatToInt { value: f64 },
3507    #[error("expected 0/1 for bool cast from int64 but found {value}")]
3508    InvalidBoolInt { value: i64 },
3509    #[error("expected 0.0/1.0 for bool cast from float64 but found {value}")]
3510    InvalidBoolFloat { value: f64 },
3511    #[error("value {value:?} has non-numeric dtype {dtype:?}")]
3512    NonNumericValue { value: String, dtype: DType },
3513    #[error("value is missing ({kind:?})")]
3514    ValueIsMissing { kind: NullKind },
3515    #[error("sparse value dtype cannot be {dtype:?}")]
3516    InvalidSparseValueDType { dtype: DType },
3517    #[error("interval_range step must be finite, positive, and not NaN (got {step})")]
3518    InvalidIntervalStep { step: f64 },
3519    #[error("interval_range step {step} does not evenly divide range end-start={span}")]
3520    IntervalStepDoesNotDivide { step: f64, span: f64 },
3521    #[error("interval_range requires exactly 3 of (start, end, periods, freq) to be specified")]
3522    IntervalRangeParameterCount,
3523    #[error("cannot parse '{value}' as {target}")]
3524    ValueNotParseable { value: String, target: String },
3525}
3526
3527pub fn common_dtype(left: DType, right: DType) -> Result<DType, TypeError> {
3528    use DType::{
3529        Bool, BoolNullable, Categorical, Float64, Float64Nullable, Int64, Int64Nullable, Null,
3530        Sparse, Timedelta64,
3531    };
3532
3533    let out = match (&left, &right) {
3534        (a, b) if a == b => a.clone(),
3535        (Null, other) | (other, Null) => other.clone(),
3536        (Categorical, Categorical) => Categorical,
3537
3538        // Bool promotions (nullable absorbs non-nullable)
3539        (Bool, Int64) | (Int64, Bool) => Int64,
3540        (Bool, Int64Nullable) | (Int64Nullable, Bool) => Int64Nullable,
3541        (BoolNullable, Int64) | (Int64, BoolNullable) => Int64Nullable,
3542        (BoolNullable, Int64Nullable) | (Int64Nullable, BoolNullable) => Int64Nullable,
3543        (Bool, BoolNullable) | (BoolNullable, Bool) => BoolNullable,
3544        (Bool, Float64) | (Float64, Bool) => Float64,
3545        // MEASURED, live pandas 2.2.3:
3546        //     pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
3547        //         -> Float64        (the EXTENSION dtype, not numpy float64)
3548        // Flipped together with the Int64Nullable arm below; see the
3549        // associativity note there for why they cannot move independently.
3550        (BoolNullable, Float64) | (Float64, BoolNullable) => Float64Nullable,
3551
3552        // Int64 promotions (nullable absorbs non-nullable)
3553        (Int64, Float64) | (Float64, Int64) => Float64,
3554        // MEASURED, live pandas 2.2.3, both spellings agree:
3555        //     find_common_type([Int64, float64])                        -> Float64
3556        //     pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5])  -> Float64
3557        // i.e. the NULLABLE flavour wins, so the answer is Float64Nullable.
3558        //
3559        // ⚠ THIS ARM AND THE BoolNullable ARM ABOVE ARE ONE ATOMIC CHANGE. The
3560        // lattice is checked for associativity over ALL dtypes by
3561        // `common_dtype_lattice_axioms_be314`, and flipping only this arm breaks
3562        // it on (BoolNullable, Int64, Float64):
3563        //     (BN ∨ I64) ∨ F64 = Int64Nullable ∨ Float64 = Float64Nullable
3564        //     BN ∨ (I64 ∨ F64) = BN ∨ Float64            = Float64      ✗
3565        // Both arms flip, or neither does. (br-frankenpandas-qkqfb, unblocks
3566        // br-frankenpandas-f0aaa)
3567        (Int64Nullable, Float64) | (Float64, Int64Nullable) => Float64Nullable,
3568        (Int64, Int64Nullable) | (Int64Nullable, Int64) => Int64Nullable,
3569
3570        // Float64Nullable promotions. These are now REACHABLE: the two arms
3571        // above produce Float64Nullable, so anything that folds a dtype list
3572        // (melt's try_fold, combine_first's target_dtype) can feed it back in
3573        // here. They are what makes that fold associative.
3574        //
3575        // MEASURED, live pandas 2.2.3 ARITHMETIC (which is what this function
3576        // models -- see the Bool arms above, which follow arithmetic rather than
3577        // find_common_type, since find_common_type answers `object` for every
3578        // bool+numeric pair and FrankenPandas has no object dtype yet, that
3579        // being br-frankenpandas-hlcgl):
3580        //     Float64(ext) + float64(numpy)          -> Float64
3581        //     Int64(ext)   + Float64(ext)            -> Float64
3582        //     boolean(ext) + Float64(ext)            -> Float64
3583        // The nullable float absorbs every other numeric flavour, which also
3584        // makes it the top of the numeric lattice and keeps promotion
3585        // associative.
3586        (Float64Nullable, Float64) | (Float64, Float64Nullable) => Float64Nullable,
3587        (Float64Nullable, Int64) | (Int64, Float64Nullable) => Float64Nullable,
3588        (Float64Nullable, Int64Nullable) | (Int64Nullable, Float64Nullable) => Float64Nullable,
3589        (Float64Nullable, Bool) | (Bool, Float64Nullable) => Float64Nullable,
3590        (Float64Nullable, BoolNullable) | (BoolNullable, Float64Nullable) => Float64Nullable,
3591
3592        // Datetime/Timedelta
3593        (Timedelta64, Timedelta64) => Timedelta64,
3594        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
3595            if left_tz == right_tz =>
3596        {
3597            DType::Datetime64 {
3598                tz: left_tz.clone(),
3599            }
3600        }
3601
3602        (Sparse, _) | (_, Sparse) => {
3603            return Err(TypeError::IncompatibleDtypes {
3604                left: left.clone(),
3605                right: right.clone(),
3606            });
3607        }
3608        _ => {
3609            return Err(TypeError::IncompatibleDtypes { left, right });
3610        }
3611    };
3612
3613    Ok(out)
3614}
3615
3616pub fn infer_dtype(values: &[Scalar]) -> Result<DType, TypeError> {
3617    let mut current = DType::Null;
3618    let mut saw_utf8 = false;
3619    let mut saw_timedelta = false;
3620    let mut saw_datetime = false;
3621    let mut saw_non_utf8_non_null = false;
3622    // br-frankenpandas-rh1od: pandas constructs OBJECT columns whenever a
3623    // Python bool mixes with any numeric scalar ([True, 2] -> object,
3624    // measured live 2.2.3); numpy's bool<int common-type never fires at the
3625    // constructor. FrankenPandas coerced to Int64 here, which no pandas
3626    // constructor path produces. Strings already take the object bucket
3627    // below (DISC-005); bool+numeric joins them.
3628    let mut saw_bool = false;
3629    let mut saw_numeric = false;
3630
3631    // NOTE (br-frankenpandas-nywa8): inferring Float64 from a NaN-KIND missing
3632    // looks like the right central fix for pandas' int64 -> float64 promotion,
3633    // and it is NOT. `NullKind::NaN` is used throughout FrankenPandas as the
3634    // GENERIC missing marker, not specifically as "a float NaN" — e.g. short-row
3635    // padding and `missing_for_dtype(Float64)` both produce it. Promoting on it
3636    // broke 19 pre-existing fp-columnar tests (ffill returning Float64(1.0)
3637    // where Int64(1) was pinned, isin flipping a bool) because those columns are
3638    // legitimately Int64 with a generic missing. Measured, then reverted.
3639    //
3640    // The promotion has to be applied where a gap is INTRODUCED and the
3641    // introducer knows it is inventing one — see `concat_dataframes_*`, which
3642    // promotes locally. Do not move it back here without first giving
3643    // "pandas-introduced gap" a marker distinct from generic missingness.
3644    for value in values {
3645        match value.dtype() {
3646            DType::Null => {}
3647            DType::Utf8 => saw_utf8 = true,
3648            DType::Bool => {
3649                saw_bool = true;
3650                saw_non_utf8_non_null = true;
3651                current = common_dtype(current, DType::Bool)?;
3652            }
3653            DType::Int64 | DType::Float64 => {
3654                saw_numeric = true;
3655                saw_non_utf8_non_null = true;
3656                current = common_dtype(current, value.dtype())?;
3657            }
3658            DType::Timedelta64 => {
3659                saw_timedelta = true;
3660                if current == DType::Null {
3661                    current = DType::Timedelta64;
3662                } else if current != DType::Timedelta64 {
3663                    return Err(TypeError::IncompatibleDtypes {
3664                        left: current,
3665                        right: DType::Timedelta64,
3666                    });
3667                }
3668            }
3669            DType::Datetime64 { .. } => {
3670                saw_datetime = true;
3671                if current == DType::Null {
3672                    current = DType::datetime64_naive();
3673                } else if !current.is_datetime() {
3674                    return Err(TypeError::IncompatibleDtypes {
3675                        left: current,
3676                        right: DType::datetime64_naive(),
3677                    });
3678                }
3679            }
3680            other => {
3681                saw_non_utf8_non_null = true;
3682                current = common_dtype(current, other)?;
3683            }
3684        }
3685
3686        if saw_bool && saw_numeric {
3687            // Constructor inference follows pandas object-dtype behavior for
3688            // heterogeneous string/scalar payloads while arithmetic coercion
3689            // remains governed by the stricter common_dtype lattice.
3690            return Ok(DType::Utf8);
3691        }
3692        if saw_utf8 && saw_non_utf8_non_null {
3693            // Constructor inference follows pandas object-dtype behavior for
3694            // heterogeneous string/scalar payloads while arithmetic coercion
3695            // remains governed by the stricter common_dtype lattice.
3696            return Ok(DType::Utf8);
3697        }
3698        if saw_timedelta && saw_non_utf8_non_null {
3699            return Err(TypeError::IncompatibleDtypes {
3700                left: DType::Timedelta64,
3701                right: current,
3702            });
3703        }
3704        if saw_datetime && saw_non_utf8_non_null {
3705            return Err(TypeError::IncompatibleDtypes {
3706                left: DType::datetime64_naive(),
3707                right: current,
3708            });
3709        }
3710    }
3711
3712    if saw_utf8 {
3713        Ok(DType::Utf8)
3714    } else {
3715        Ok(current)
3716    }
3717}
3718
3719/// Cast a scalar to a target dtype, taking ownership to avoid redundant clones
3720/// when the value already has the correct type (AG-03: identity-cast skip).
3721pub fn cast_scalar_owned(value: Scalar, target: DType) -> Result<Scalar, TypeError> {
3722    let from = value.dtype();
3723    if from == target {
3724        return Ok(value);
3725    }
3726    // Int64 <-> Int64Nullable: same representation, just different dtype tracking
3727    if (from == DType::Int64 && target == DType::Int64Nullable)
3728        || (from == DType::Int64Nullable && target == DType::Int64)
3729    {
3730        return Ok(value);
3731    }
3732    // Bool <-> BoolNullable: same representation
3733    if (from == DType::Bool && target == DType::BoolNullable)
3734        || (from == DType::BoolNullable && target == DType::Bool)
3735    {
3736        return Ok(value);
3737    }
3738    // Float64 <-> Float64Nullable: same 8-byte payload, and a PRESENT value
3739    // round-trips unchanged in both directions. MEASURED, live pandas 2.2.3:
3740    //     pd.Series([1.5, None], dtype="Float64").astype("float64") -> [1.5, nan]
3741    //     pd.Series([1.5, None]).astype("Float64")                  -> [1.5, <NA>]
3742    // Only the MISSING marker differs, and a missing input never reaches here --
3743    // `value.is_missing()` below routes it to `missing_for_dtype(target)`, which
3744    // is what converts NaN <-> pd.NA. (br-frankenpandas-qkqfb)
3745    if (from == DType::Float64 && target == DType::Float64Nullable)
3746        || (from == DType::Float64Nullable && target == DType::Float64)
3747    {
3748        return Ok(value);
3749    }
3750    // A datetime scalar is an instant and a zone is its column's metadata, so
3751    // it takes any datetime64 dtype as it is (a fill or set value on a
3752    // tz-aware column was refused as an invalid cast).
3753    if from.is_datetime() && target.is_datetime() {
3754        return Ok(value);
3755    }
3756    if target == DType::Utf8 {
3757        return Ok(Scalar::Utf8(scalar_to_string_for_astype(value)));
3758    }
3759    // Per br-frankenpandas-cyi4h: pandas astype(bool) (the numpy bool dtype)
3760    // treats a float NaN as truthy -> True (bool(nan) is True), unlike the
3761    // nullable 'boolean' dtype which keeps NA. FP's NaN=missing model would
3762    // otherwise fall through to the missing branch below and yield a null.
3763    // Verified vs live pandas 2.2.3.
3764    if target == DType::Bool
3765        && let Scalar::Float64(v) = &value
3766        && v.is_nan()
3767    {
3768        return Ok(Scalar::Bool(true));
3769    }
3770    // TEMPORAL -> NUMPY bool IS NONZERO-TRUTHY ON THE RAW NANOSECONDS, and it
3771    // sits here for exactly the reason the NaN check above does: FP's
3772    // missing-value model would otherwise swallow NaT below, and pandas does not
3773    // treat it as missing here.
3774    //
3775    // MEASURED, live pandas 2.2.3, `.astype('bool')` beside `.astype('int64')`
3776    // so the rule is visible as one rule rather than four cases:
3777    //
3778    //   value                                 nanos                  bool
3779    //   Timestamp(0)                              0                 False
3780    //   Timestamp('2024-03-15 10:30:45.123..')  1.71e18               True
3781    //   Timestamp('1969-12-31 23:59:59.999..')       -1               True
3782    //   NaT (either dtype)          -9223372036854775808              True
3783    //   Timedelta(0)                              0                 False
3784    //   Timedelta('1 days')          86400000000000                   True
3785    //   Timedelta('-1 ns')                       -1                   True
3786    //
3787    // So `nanos != 0` is the whole rule, and NaT needs no case of its own: it IS
3788    // i64::MIN, which is nonzero. Only the epoch and a zero duration are False.
3789    //
3790    // ⚠️ THE NULLABLE `boolean` REFUSES ALL OF THESE, including the ones whose
3791    // nanos are 0 or 1 — `.astype('boolean')` raises "Need to pass bool-like
3792    // values" for EVERY row above, so it is the dtype it rejects, not the value.
3793    // That is why this is guarded on `DType::Bool` alone and why the strict
3794    // `BoolNullable` arm below is left without a temporal case.
3795    if target == DType::Bool {
3796        match &value {
3797            Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3798                return Ok(Scalar::Bool(*nanos != 0));
3799            }
3800            _ => {}
3801        }
3802    }
3803    // TEMPORAL -> NUMPY int64 IS RAW NANOSECONDS, and this sits ABOVE the
3804    // missing-value branch on purpose.
3805    //
3806    // MEASURED, live pandas 2.2.3:
3807    //     pd.Series([Timestamp('2024-03-15 10:30:45.123456789')]).astype('int64')
3808    //       -> 1710498645123456789
3809    //     pd.Series([Timedelta('1 days 02:03:04.005006007')]).astype('int64')
3810    //       -> 93784005006007
3811    //     pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
3812    //       -> -9223372036854775808        <- THE SENTINEL, not a missing value
3813    //
3814    // ⚠️ NaT IS WHY THE ORDER MATTERS. Below this point `value.is_missing()`
3815    // would turn NaT into `Null(Null)`, and pandas emphatically does not: it
3816    // hands back i64::MIN, which is the same bit pattern NaT already IS. Doing
3817    // the cast here makes the sentinel round-trip by construction rather than by
3818    // a second special case.
3819    //
3820    // ⚠️ NUMPY `int64` ONLY — the NULLABLE `Int64` REFUSES this, and so must we:
3821    //     .astype('Int64')   -> TypeError: datetime64[ns] cannot be converted
3822    //                          to IntegerDtype
3823    //     .astype('float64') -> TypeError: Cannot cast DatetimeArray to dtype
3824    //                          float64
3825    // which is why this is guarded on the exact target rather than folded into
3826    // the `Int64 | Int64Nullable` arm below, and why no Float64 arm is added.
3827    if target == DType::Int64 {
3828        match &value {
3829            Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3830                return Ok(Scalar::Int64(*nanos));
3831            }
3832            _ => {}
3833        }
3834    }
3835    if value.is_missing() {
3836        return Ok(Scalar::missing_for_dtype(target));
3837    }
3838
3839    // Note: identity casts (from == target) are handled above, so same-type
3840    // arms are omitted from the match below.
3841    match target {
3842        DType::Null => Ok(Scalar::Null(NullKind::Null)),
3843        DType::Bool => match &value {
3844            // numpy bool: zero -> False, ANY nonzero -> True (it does not
3845            // restrict to 0/1). e.g. bool of -3 / 2.5 is True.
3846            Scalar::Int64(v) => Ok(Scalar::Bool(*v != 0)),
3847            // 0.0 and -0.0 -> False; every other value, INCLUDING NaN, -> True
3848            // (NaN != 0.0 is true), matching numpy/pandas truthiness.
3849            Scalar::Float64(v) => Ok(Scalar::Bool(*v != 0.0)),
3850            _ => Err(TypeError::InvalidCast { from, to: target }),
3851        },
3852        DType::BoolNullable => match &value {
3853            // pandas nullable Boolean ('boolean') is STRICT: only 0/1 (or
3854            // True/False) are accepted — any other value raises "Need to pass
3855            // bool-like values", UNLIKE numpy bool which is nonzero-truthy.
3856            // (br-frankenpandas-tjomg)
3857            Scalar::Bool(b) => Ok(Scalar::Bool(*b)),
3858            Scalar::Int64(0) => Ok(Scalar::Bool(false)),
3859            Scalar::Int64(1) => Ok(Scalar::Bool(true)),
3860            Scalar::Int64(v) => Err(TypeError::InvalidBoolInt { value: *v }),
3861            Scalar::Float64(v) if *v == 0.0 => Ok(Scalar::Bool(false)),
3862            Scalar::Float64(v) if *v == 1.0 => Ok(Scalar::Bool(true)),
3863            Scalar::Float64(v) => Err(TypeError::InvalidBoolFloat { value: *v }),
3864            _ => Err(TypeError::InvalidCast { from, to: target }),
3865        },
3866        DType::Int64 | DType::Int64Nullable => match &value {
3867            Scalar::Bool(v) => Ok(Scalar::Int64(i64::from(*v))),
3868            Scalar::Float64(v) => {
3869                // pandas astype(int64) truncates a finite float toward zero
3870                // (1.9 -> 1, -1.9 -> -1, 2.5 -> 2); only non-finite (NaN/±inf)
3871                // or out-of-i64-range values raise. Verified vs pandas 2.2.3
3872                // (br-frankenpandas-qcutc). NaN is handled as missing above, so
3873                // here non-finite means ±inf. `as i64` performs the toward-zero
3874                // truncation for in-range finite values.
3875                if !v.is_finite() {
3876                    return Err(TypeError::LossyFloatToInt { value: *v });
3877                }
3878                if *v < i64::MIN as f64 || *v >= 9223372036854775808.0 {
3879                    return Err(TypeError::LossyFloatToInt { value: *v });
3880                }
3881                Ok(Scalar::Int64(*v as i64))
3882            }
3883            Scalar::Utf8(s) => {
3884                // Try direct int parse first, then try float parse + truncate
3885                // (pandas accepts "1.0" as valid int via float intermediate)
3886                if let Ok(v) = s.parse::<i64>() {
3887                    return Ok(Scalar::Int64(v));
3888                }
3889                if let Ok(f) = s.parse::<f64>()
3890                    && f.is_finite()
3891                    && f.fract() == 0.0
3892                    && f >= i64::MIN as f64
3893                    && f < 9223372036854775808.0
3894                {
3895                    return Ok(Scalar::Int64(f as i64));
3896                }
3897                Err(TypeError::InvalidCast { from, to: target })
3898            }
3899            _ => Err(TypeError::InvalidCast { from, to: target }),
3900        },
3901        // Both float flavours accept the same source values; they differ only in
3902        // the missing marker, which is handled above. MEASURED:
3903        //     pd.Series([1,None],dtype="Int64").astype("Float64") -> [1.0, <NA>]
3904        DType::Float64 | DType::Float64Nullable => match &value {
3905            Scalar::Bool(v) => Ok(Scalar::Float64(if *v { 1.0 } else { 0.0 })),
3906            Scalar::Int64(v) => Ok(Scalar::Float64(*v as f64)),
3907            Scalar::Utf8(s) => s
3908                .parse::<f64>()
3909                .map(Scalar::Float64)
3910                .map_err(|_| TypeError::InvalidCast { from, to: target }),
3911            _ => Err(TypeError::InvalidCast { from, to: target }),
3912        },
3913        DType::Utf8 => Ok(Scalar::Utf8(scalar_to_string_for_astype(value))),
3914        DType::Categorical => Err(TypeError::InvalidCast { from, to: target }),
3915        DType::Timedelta64 => match &value {
3916            // A BOOL IS 0 OR 1 NANOSECONDS on the astype path. Measured:
3917            //     pd.Series([True]).astype('timedelta64[ns]') -> 1ns
3918            //     pd.Series([True]).astype('datetime64[ns]')  -> 1970-01-01 ...001
3919            // ⚠️ The CONSTRUCTOR refuses the same thing —
3920            //     pd.DataFrame([[True]], dtype='datetime64[ns]')
3921            //       -> TypeError: dtype bool cannot be converted to datetime64[ns]
3922            // -- the same astype/constructor split `float_to_temporal_nanos`
3923            // documents for non-finite input. This cast is shared, so it takes
3924            // astype's answer and the constructor's refusal belongs in
3925            // `DataFrame::with_constructor_dtype`.
3926            Scalar::Bool(v) => Ok(Scalar::Timedelta64(i64::from(*v))),
3927            Scalar::Int64(v) => Ok(Scalar::Timedelta64(*v)),
3928            Scalar::Float64(v) => Ok(Scalar::Timedelta64(float_to_temporal_nanos(*v))),
3929            Scalar::Utf8(s) => Timedelta::parse(s)
3930                .map(Scalar::Timedelta64)
3931                .map_err(|_| TypeError::InvalidCast { from, to: target }),
3932            _ => Err(TypeError::InvalidCast { from, to: target }),
3933        },
3934        DType::Datetime64 { .. } => match &value {
3935            // See the Timedelta64 arm above for the measurement and for why the
3936            // constructor's stricter refusal is not encoded here.
3937            Scalar::Bool(v) => Ok(Scalar::Datetime64(i64::from(*v))),
3938            Scalar::Int64(v) => Ok(Scalar::Datetime64(*v)),
3939            Scalar::Float64(v) => Ok(Scalar::Datetime64(float_to_temporal_nanos(*v))),
3940            Scalar::Utf8(s) => Timestamp::parse(s)
3941                .map(|timestamp| Scalar::Datetime64(timestamp.nanos))
3942                .map_err(|_| TypeError::InvalidCast { from, to: target }),
3943            _ => Err(TypeError::InvalidCast { from, to: target }),
3944        },
3945        DType::Period => match &value {
3946            // Int cast to a freq-less DType::Period: default to Daily (pandas
3947            // requires an explicit freq in the dtype; ours is freq-less).
3948            Scalar::Int64(v) => Ok(Scalar::Period(Period::new(*v, PeriodFreq::Daily))),
3949            Scalar::Utf8(s) => Period::parse(s)
3950                .map(Scalar::Period)
3951                .map_err(|_| TypeError::InvalidCast { from, to: target }),
3952            _ => Err(TypeError::InvalidCast { from, to: target }),
3953        },
3954        DType::Interval => match &value {
3955            Scalar::Utf8(s) => Interval::parse(s)
3956                .map(Scalar::Interval)
3957                .map_err(|_| TypeError::InvalidCast { from, to: target }),
3958            _ => Err(TypeError::InvalidCast { from, to: target }),
3959        },
3960        DType::Sparse => Err(TypeError::InvalidCast { from, to: target }),
3961    }
3962}
3963
3964/// A float reinterpreted as integer NANOSECONDS, the way pandas casts to
3965/// `datetime64[ns]` / `timedelta64[ns]`.
3966///
3967/// ⚠️ THIS IS NOT THE `int64` RULE, and the difference is the whole reason this
3968/// helper exists rather than a reuse. The explicit constructor REFUSES a lossy
3969/// float -> int64 (`TypeError::LossyFloatToInt`, mirroring pandas' "Trying to
3970/// coerce float values to integers"), but the temporal dtypes silently truncate.
3971/// MEASURED side by side, live pandas 2.2.3, on the single value `1.5`:
3972///
3973/// ```text
3974/// pd.DataFrame([[1.5]], dtype="int64")           -> ValueError
3975/// pd.DataFrame([[1.5]], dtype="datetime64[ns]")  -> 1ns
3976/// pd.DataFrame([[1.5]], dtype="timedelta64[ns]") -> 1ns
3977/// ```
3978///
3979/// TRUNCATION IS TOWARD ZERO, NOT FLOOR. Measured on both signs, where the two
3980/// disagree: 0.9 -> 0 and -0.9 -> 0; 1.5 -> 1 and -1.5 -> -1; -2.5 -> -2 (a
3981/// floor would give -1, -2 and -3). Rust's `as i64` is exactly this truncation.
3982///
3983/// ANYTHING NOT REPRESENTABLE AS `i64` BECOMES NaT, which is why this cannot be
3984/// a bare `as` — Rust's saturating cast would hand back `i64::MAX` where pandas
3985/// hands back NaT, and would map NaN to 0, i.e. the epoch. Measured, all NaT:
3986/// NaN, +inf, -inf, 1e30, -1e30, 9.3e18, and exactly 2^63 and -2^63; while
3987/// 2^63 - 1024 IS representable and converts (2262-04-11 23:47:16.854774784).
3988/// The bounds are therefore strict on both ends — `i64::MIN as f64` is exactly
3989/// -2^63, which pandas already reads as NaT because it IS the NaT sentinel.
3990///
3991/// ⚠️ ONE KNOWN DIVERGENCE, RECORDED RATHER THAN GUESSED. For `timedelta64[ns]`
3992/// pandas' two paths disagree on the non-finite input: `astype` yields NaT but
3993/// the constructor raises OverflowError. `datetime64[ns]` has no such split —
3994/// both give NaT. This cast is shared by both paths, so it takes the behaviour
3995/// they agree on for datetimes and `astype`'s for timedeltas; the constructor's
3996/// stricter refusal belongs in `DataFrame::with_constructor_dtype`, which is
3997/// already where the constructor-only `int64`-rejects-NA check lives, and for
3998/// the same reason.
3999fn float_to_temporal_nanos(value: f64) -> i64 {
4000    // Strict on both ends: `i64::MIN as f64` and `i64::MAX as f64` are -2^63 and
4001    // 2^63, and pandas reads both of those as NaT.
4002    if value.is_finite() && value > (i64::MIN as f64) && value < (i64::MAX as f64) {
4003        // Truncates toward zero, and the guard above means it cannot saturate.
4004        value as i64
4005    } else {
4006        // `Timestamp::NAT` and `Timedelta::NAT` are the same value (`i64::MIN`),
4007        // so this one sentinel is correct for both callers.
4008        Timestamp::NAT
4009    }
4010}
4011
4012fn scalar_to_string_for_astype(value: Scalar) -> String {
4013    match value {
4014        Scalar::Null(NullKind::Null) => "None".to_owned(),
4015        Scalar::Null(NullKind::NaN) => "nan".to_owned(),
4016        Scalar::Null(NullKind::NaT) => "NaT".to_owned(),
4017        Scalar::Bool(true) => "True".to_owned(),
4018        Scalar::Bool(false) => "False".to_owned(),
4019        Scalar::Int64(v) => v.to_string(),
4020        Scalar::Float64(v) => float_to_string_for_astype(v),
4021        Scalar::Utf8(s) => s,
4022        Scalar::Timedelta64(v) if v == Timedelta::NAT => "NaT".to_owned(),
4023        Scalar::Timedelta64(v) => Timedelta::format(v),
4024        Scalar::Datetime64(v) if v == Timestamp::NAT => "NaT".to_owned(),
4025        Scalar::Datetime64(v) => format!("Timestamp[{v}]"),
4026        Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
4027        Scalar::Period(p) => p.calendar_string(),
4028        Scalar::Interval(v) => v.to_string(),
4029        // astype(str) of a list cell is its repr, of a host value its str.
4030        Scalar::Object(object) => object.to_string(),
4031    }
4032}
4033
4034pub fn float_to_string_for_astype(value: f64) -> String {
4035    use std::fmt::Write as _;
4036
4037    if value.is_nan() {
4038        return "nan".to_owned();
4039    }
4040    if value.is_infinite() {
4041        return value.to_string(); // "inf" / "-inf"
4042    }
4043    // pandas astype(str) renders floats via Python str(float): whole numbers
4044    // keep ".0", decimals use the shortest round-trip, and extreme magnitudes use
4045    // scientific notation ("1e+16", "1e-05"). Rust's Debug formatter matches this
4046    // (shortest round-trip, ".0" on whole numbers, scientific at Python's
4047    // boundaries); only the exponent spelling differs (Rust "1e16"/"1e-5" vs
4048    // Python "1e+16"/"1e-05"), so normalize that. The old `{:.1}` whole / Display
4049    // decimal path lost scientific notation (1e16 -> "10000000000000000.0").
4050    // Leave enough spare capacity for the positive sign and one exponent pad
4051    // digit, then normalize the formatter output in place. The former branch
4052    // allocated a second String and copied the mantissa solely to change
4053    // `e16`/`e-5` into pandas' `e+16`/`e-05` spelling.
4054    let mut rendered = String::with_capacity(32);
4055    let _ = write!(rendered, "{value:?}");
4056    let Some(exponent_marker) = rendered.find('e') else {
4057        return rendered;
4058    };
4059
4060    let sign_position = exponent_marker + 1;
4061    let digits_position = match rendered.as_bytes().get(sign_position) {
4062        Some(b'+' | b'-') => sign_position + 1,
4063        _ => {
4064            rendered.insert(sign_position, '+');
4065            sign_position + 1
4066        }
4067    };
4068    if rendered.len() - digits_position == 1 {
4069        rendered.insert(digits_position, '0');
4070    }
4071    rendered
4072}
4073
4074static ENG_FLOAT_ACCURACY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(3);
4075static ENG_FLOAT_USE_PREFIX: std::sync::atomic::AtomicBool =
4076    std::sync::atomic::AtomicBool::new(false);
4077static ENG_FLOAT_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
4078
4079/// Format float values according to engineering format, matching pandas `EngFormatter`.
4080pub fn eng_float_format(num: f64, accuracy: Option<usize>, use_eng_prefix: bool) -> String {
4081    if num.is_nan() {
4082        return "NaN".to_string();
4083    }
4084    if num.is_infinite() {
4085        return if num < 0.0 {
4086            "-inf".to_string()
4087        } else {
4088            "inf".to_string()
4089        };
4090    }
4091
4092    let sign = if num < 0.0 { -1.0 } else { 1.0 };
4093    let abs_num = num.abs();
4094
4095    let pow10 = if abs_num != 0.0 {
4096        let p = (abs_num.log10() / 3.0).floor() as i32 * 3;
4097        p.clamp(-24, 24)
4098    } else {
4099        0
4100    };
4101
4102    let prefix = if use_eng_prefix {
4103        match pow10 {
4104            -24 => "y",
4105            -21 => "z",
4106            -18 => "a",
4107            -15 => "f",
4108            -12 => "p",
4109            -9 => "n",
4110            -6 => "u",
4111            -3 => "m",
4112            0 => "",
4113            3 => "k",
4114            6 => "M",
4115            9 => "G",
4116            12 => "T",
4117            15 => "P",
4118            18 => "E",
4119            21 => "Z",
4120            24 => "Y",
4121            _ => "",
4122        }
4123        .to_string()
4124    } else if pow10 < 0 {
4125        format!("E-{:02}", -pow10)
4126    } else {
4127        format!("E+{:02}", pow10)
4128    };
4129
4130    let mant = (sign * abs_num) / 10f64.powi(pow10);
4131
4132    if let Some(acc) = accuracy {
4133        format!("{mant:.acc$}{prefix}", acc = acc)
4134    } else {
4135        format!("{mant}{prefix}")
4136    }
4137}
4138
4139/// Set pandas-compatible engineering float formatting option.
4140/// Matches `pd.set_eng_float_format(accuracy=3, use_eng_prefix=False)`.
4141pub fn set_eng_float_format(accuracy: usize, use_eng_prefix: bool) {
4142    use std::sync::atomic::Ordering;
4143    ENG_FLOAT_ACCURACY.store(accuracy, Ordering::Relaxed);
4144    ENG_FLOAT_USE_PREFIX.store(use_eng_prefix, Ordering::Relaxed);
4145    ENG_FLOAT_ACTIVE.store(true, Ordering::Relaxed);
4146}
4147
4148/// Reset engineering float formatting back to default.
4149pub fn reset_eng_float_format() {
4150    use std::sync::atomic::Ordering;
4151    ENG_FLOAT_ACTIVE.store(false, Ordering::Relaxed);
4152}
4153
4154/// Get the current engineering float format configuration if active.
4155pub fn get_eng_float_format() -> Option<(usize, bool)> {
4156    use std::sync::atomic::Ordering;
4157    if ENG_FLOAT_ACTIVE.load(Ordering::Relaxed) {
4158        Some((
4159            ENG_FLOAT_ACCURACY.load(Ordering::Relaxed),
4160            ENG_FLOAT_USE_PREFIX.load(Ordering::Relaxed),
4161        ))
4162    } else {
4163        None
4164    }
4165}
4166
4167// ── Global Configuration Options (matching pd.options) ───────────────────
4168
4169/// Error encountered when inspecting or modifying configuration options.
4170#[derive(Debug, Error, Clone, PartialEq, Eq)]
4171pub enum OptionError {
4172    #[error("no such option: '{pat}'")]
4173    NotFound { pat: String },
4174    #[error("option pattern '{pat}' matches multiple options: {matches:?}")]
4175    Ambiguous { pat: String, matches: Vec<String> },
4176    #[error("invalid option value for '{pat}': {reason}")]
4177    InvalidValue { pat: String, reason: String },
4178}
4179
4180/// Represents a configuration option value, matching pandas `pd.options`.
4181#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4182pub enum OptionValue {
4183    None,
4184    Int(i64),
4185    Float(f64),
4186    Bool(bool),
4187    Str(String),
4188}
4189
4190impl OptionValue {
4191    #[must_use]
4192    pub const fn is_none(&self) -> bool {
4193        matches!(self, Self::None)
4194    }
4195
4196    #[must_use]
4197    pub const fn as_int(&self) -> Option<i64> {
4198        match self {
4199            Self::Int(i) => Some(*i),
4200            _ => None,
4201        }
4202    }
4203
4204    #[must_use]
4205    pub const fn as_float(&self) -> Option<f64> {
4206        match self {
4207            Self::Float(f) => Some(*f),
4208            _ => None,
4209        }
4210    }
4211
4212    #[must_use]
4213    pub const fn as_bool(&self) -> Option<bool> {
4214        match self {
4215            Self::Bool(b) => Some(*b),
4216            _ => None,
4217        }
4218    }
4219
4220    #[must_use]
4221    pub fn as_str(&self) -> Option<&str> {
4222        match self {
4223            Self::Str(s) => Some(s.as_str()),
4224            _ => None,
4225        }
4226    }
4227}
4228
4229impl std::fmt::Display for OptionValue {
4230    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4231        match self {
4232            Self::None => write!(f, "None"),
4233            Self::Int(i) => write!(f, "{i}"),
4234            Self::Float(fl) => write!(f, "{fl}"),
4235            Self::Bool(b) => write!(f, "{b}"),
4236            Self::Str(s) => write!(f, "{s}"),
4237        }
4238    }
4239}
4240
4241impl From<i64> for OptionValue {
4242    fn from(v: i64) -> Self {
4243        Self::Int(v)
4244    }
4245}
4246
4247impl From<i32> for OptionValue {
4248    fn from(v: i32) -> Self {
4249        Self::Int(i64::from(v))
4250    }
4251}
4252
4253impl From<usize> for OptionValue {
4254    fn from(v: usize) -> Self {
4255        Self::Int(i64::try_from(v).unwrap_or(i64::MAX))
4256    }
4257}
4258
4259impl From<f64> for OptionValue {
4260    fn from(v: f64) -> Self {
4261        Self::Float(v)
4262    }
4263}
4264
4265impl From<bool> for OptionValue {
4266    fn from(v: bool) -> Self {
4267        Self::Bool(v)
4268    }
4269}
4270
4271impl From<&str> for OptionValue {
4272    fn from(v: &str) -> Self {
4273        Self::Str(v.to_string())
4274    }
4275}
4276
4277impl From<String> for OptionValue {
4278    fn from(v: String) -> Self {
4279        Self::Str(v)
4280    }
4281}
4282
4283impl From<()> for OptionValue {
4284    fn from(_: ()) -> Self {
4285        Self::None
4286    }
4287}
4288
4289fn default_options_map() -> std::collections::BTreeMap<String, OptionValue> {
4290    let mut m = std::collections::BTreeMap::new();
4291    m.insert("display.max_rows".to_string(), OptionValue::Int(60));
4292    m.insert("display.min_rows".to_string(), OptionValue::Int(10));
4293    m.insert("display.max_columns".to_string(), OptionValue::Int(0));
4294    m.insert("display.width".to_string(), OptionValue::Int(80));
4295    m.insert("display.precision".to_string(), OptionValue::Int(6));
4296    m.insert("display.max_colwidth".to_string(), OptionValue::Int(50));
4297    m.insert(
4298        "display.show_dimensions".to_string(),
4299        OptionValue::Bool(true),
4300    );
4301    m.insert("display.float_format".to_string(), OptionValue::None);
4302    m.insert(
4303        "display.large_repr".to_string(),
4304        OptionValue::Str("truncate".to_string()),
4305    );
4306    m.insert(
4307        "display.max_info_columns".to_string(),
4308        OptionValue::Int(100),
4309    );
4310    m.insert(
4311        "display.max_info_rows".to_string(),
4312        OptionValue::Int(1690785),
4313    );
4314    m.insert("display.memory_usage".to_string(), OptionValue::Bool(true));
4315    m.insert(
4316        "display.colheader_justify".to_string(),
4317        OptionValue::Str("right".to_string()),
4318    );
4319    m.insert("display.chop_threshold".to_string(), OptionValue::None);
4320    m.insert(
4321        "display.date_dayfirst".to_string(),
4322        OptionValue::Bool(false),
4323    );
4324    m.insert(
4325        "display.date_yearfirst".to_string(),
4326        OptionValue::Bool(false),
4327    );
4328    m.insert(
4329        "display.encoding".to_string(),
4330        OptionValue::Str("utf-8".to_string()),
4331    );
4332    m.insert("mode.sim_interactive".to_string(), OptionValue::Bool(false));
4333    m.insert(
4334        "mode.chained_assignment".to_string(),
4335        OptionValue::Str("warn".to_string()),
4336    );
4337    m.insert("mode.use_inf_as_na".to_string(), OptionValue::Bool(false));
4338    m.insert("mode.copy_on_write".to_string(), OptionValue::Bool(false));
4339    m.insert(
4340        "mode.data_manager".to_string(),
4341        OptionValue::Str("block".to_string()),
4342    );
4343    m.insert(
4344        "compute.use_bottleneck".to_string(),
4345        OptionValue::Bool(true),
4346    );
4347    m.insert("compute.use_numba".to_string(), OptionValue::Bool(false));
4348    m.insert(
4349        "io.excel.zip.reader".to_string(),
4350        OptionValue::Str("zipfile".to_string()),
4351    );
4352    m.insert(
4353        "io.parquet.engine".to_string(),
4354        OptionValue::Str("auto".to_string()),
4355    );
4356    m.insert(
4357        "io.sql.engine".to_string(),
4358        OptionValue::Str("auto".to_string()),
4359    );
4360    m.insert(
4361        "plotting.backend".to_string(),
4362        OptionValue::Str("matplotlib".to_string()),
4363    );
4364    m.insert(
4365        "plotting.matplotlib.register_converters".to_string(),
4366        OptionValue::Bool(true),
4367    );
4368    m
4369}
4370
4371static GLOBAL_OPTIONS: std::sync::LazyLock<
4372    std::sync::Mutex<std::collections::BTreeMap<String, OptionValue>>,
4373> = std::sync::LazyLock::new(|| std::sync::Mutex::new(default_options_map()));
4374
4375fn resolve_option_key(
4376    pat: &str,
4377    map: &std::collections::BTreeMap<String, OptionValue>,
4378) -> Result<String, OptionError> {
4379    if map.contains_key(pat) {
4380        return Ok(pat.to_string());
4381    }
4382    let matches: Vec<String> = map
4383        .keys()
4384        .filter(|k| k.ends_with(pat) || k.contains(pat))
4385        .cloned()
4386        .collect();
4387    if matches.len() == 1 {
4388        Ok(matches[0].clone())
4389    } else if matches.is_empty() {
4390        Err(OptionError::NotFound {
4391            pat: pat.to_string(),
4392        })
4393    } else {
4394        Err(OptionError::Ambiguous {
4395            pat: pat.to_string(),
4396            matches,
4397        })
4398    }
4399}
4400
4401/// Retrieve the current value of a configuration option, matching `pd.get_option(pat)`.
4402///
4403/// # Errors
4404/// Returns [`OptionError::NotFound`] if `pat` does not match any known option,
4405/// or [`OptionError::Ambiguous`] if it matches multiple options.
4406pub fn get_option(pat: &str) -> Result<OptionValue, OptionError> {
4407    let map = GLOBAL_OPTIONS
4408        .lock()
4409        .unwrap_or_else(std::sync::PoisonError::into_inner);
4410    let key = resolve_option_key(pat, &map)?;
4411    Ok(map.get(&key).cloned().unwrap_or(OptionValue::None))
4412}
4413
4414/// Set the value of a configuration option, matching `pd.set_option(pat, value)`.
4415///
4416/// # Errors
4417/// Returns [`OptionError::NotFound`] if `pat` does not match any known option,
4418/// or [`OptionError::Ambiguous`] if it matches multiple options.
4419pub fn set_option(pat: &str, val: impl Into<OptionValue>) -> Result<(), OptionError> {
4420    let mut map = GLOBAL_OPTIONS
4421        .lock()
4422        .unwrap_or_else(std::sync::PoisonError::into_inner);
4423    let key = resolve_option_key(pat, &map)?;
4424    let v = val.into();
4425    map.insert(key, v);
4426    Ok(())
4427}
4428
4429/// Reset one or all configuration options to their defaults, matching `pd.reset_option(pat)`.
4430///
4431/// If `pat` is `None` or `"all"`, all options are reset to defaults.
4432///
4433/// # Errors
4434/// Returns [`OptionError::NotFound`] or [`OptionError::Ambiguous`] if `pat` does not uniquely match an option.
4435pub fn reset_option(pat: Option<&str>) -> Result<(), OptionError> {
4436    let mut map = GLOBAL_OPTIONS
4437        .lock()
4438        .unwrap_or_else(std::sync::PoisonError::into_inner);
4439    let defaults = default_options_map();
4440    let p = pat.unwrap_or("all");
4441    if p == "all" {
4442        *map = defaults;
4443        return Ok(());
4444    }
4445    let key = resolve_option_key(p, &defaults)?;
4446    if let Some(def_val) = defaults.get(&key) {
4447        map.insert(key, def_val.clone());
4448    }
4449    Ok(())
4450}
4451
4452/// Return formatted descriptions of one or all options, matching `pd.describe_option(pat)`.
4453///
4454/// # Errors
4455/// Returns [`OptionError::NotFound`] if `pat` is provided but matches no options.
4456pub fn describe_option(pat: Option<&str>) -> Result<String, OptionError> {
4457    use std::fmt::Write as _;
4458    let map = GLOBAL_OPTIONS
4459        .lock()
4460        .unwrap_or_else(std::sync::PoisonError::into_inner);
4461    let mut out = String::with_capacity(map.len() * 40);
4462    let mut matched = 0;
4463    for (k, v) in map.iter() {
4464        if let Some(p) = pat
4465            && !k.contains(p)
4466        {
4467            continue;
4468        }
4469        if matched > 0 {
4470            out.push('\n');
4471        }
4472        let _ = write!(out, "{k} : [currently: {v}]");
4473        matched += 1;
4474    }
4475    if matched == 0
4476        && let Some(p) = pat
4477    {
4478        return Err(OptionError::NotFound { pat: p.to_string() });
4479    }
4480    Ok(out)
4481}
4482
4483/// RAII scope guard that restores options to their prior values when dropped.
4484#[derive(Debug)]
4485pub struct OptionContextGuard {
4486    saved: Vec<(String, OptionValue)>,
4487}
4488
4489impl Drop for OptionContextGuard {
4490    fn drop(&mut self) {
4491        let mut map = GLOBAL_OPTIONS
4492            .lock()
4493            .unwrap_or_else(std::sync::PoisonError::into_inner);
4494        for (k, old) in self.saved.drain(..) {
4495            map.insert(k, old);
4496        }
4497    }
4498}
4499
4500/// Temporarily override options within a scoped context, matching `pd.option_context(...)`.
4501///
4502/// # Errors
4503/// Returns [`OptionError::NotFound`] or [`OptionError::Ambiguous`] if any pattern is invalid.
4504pub fn option_context(entries: &[(&str, OptionValue)]) -> Result<OptionContextGuard, OptionError> {
4505    let mut map = GLOBAL_OPTIONS
4506        .lock()
4507        .unwrap_or_else(std::sync::PoisonError::into_inner);
4508    let mut saved = Vec::with_capacity(entries.len());
4509    for (pat, new_val) in entries {
4510        let key = resolve_option_key(pat, &map)?;
4511        if let Some(old) = map.get(&key) {
4512            saved.push((key.clone(), old.clone()));
4513        }
4514        map.insert(key, new_val.clone());
4515    }
4516    Ok(OptionContextGuard { saved })
4517}
4518
4519/// Cast a scalar reference to a target dtype (clones only when conversion is needed).
4520pub fn cast_scalar(value: &Scalar, target: DType) -> Result<Scalar, TypeError> {
4521    cast_scalar_owned(value.clone(), target)
4522}
4523
4524// ── Timedelta support ──────────────────────────────────────────────────
4525
4526#[derive(Debug, Error, Clone, PartialEq)]
4527pub enum TimedeltaError {
4528    #[error("invalid timedelta string: {0}")]
4529    InvalidFormat(String),
4530    #[error("overflow in timedelta computation")]
4531    Overflow,
4532}
4533
4534impl TimedeltaError {
4535    /// The pandas exception class this corresponds to, per
4536    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2.
4537    ///
4538    /// Returns `None` for [`Self::InvalidFormat`], which is a parse failure
4539    /// rather than a member of the temporal-arithmetic taxonomy.
4540    #[must_use]
4541    pub const fn pandas_error(&self) -> Option<PandasTemporalError> {
4542        match self {
4543            // Probed: pd.Timedelta(float('inf'), 's') raises
4544            // OutOfBoundsTimedelta, NOT a bare OverflowError.
4545            Self::Overflow => Some(PandasTemporalError::OutOfBoundsTimedelta),
4546            Self::InvalidFormat(_) => None,
4547        }
4548    }
4549}
4550
4551#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4552pub struct CategoricalMetadata {
4553    /// The unique category values, in order.
4554    pub categories: Vec<Scalar>,
4555    /// Whether the categories have a meaningful total ordering.
4556    pub ordered: bool,
4557}
4558
4559impl CategoricalMetadata {
4560    #[must_use]
4561    pub fn new(categories: Vec<Scalar>, ordered: bool) -> Self {
4562        Self {
4563            categories,
4564            ordered,
4565        }
4566    }
4567}
4568
4569#[derive(Debug, Clone, Copy, Default)]
4570pub struct TimedeltaComponents {
4571    pub days: i64,
4572    pub hours: i64,
4573    pub minutes: i64,
4574    pub seconds: i64,
4575    pub milliseconds: i64,
4576    pub microseconds: i64,
4577    pub nanoseconds: i64,
4578}
4579
4580/// The pandas-side exception class a failed temporal operation corresponds to.
4581///
4582/// Introduced by br-frankenpandas-fyr1z-policy-carrier-f29nz and completed by
4583/// fyr1z.3, which established that pandas uses FIVE distinct classes here — so
4584/// a STRICT arm must raise the RIGHT one per op rather than a blanket type.
4585/// Every mapping below was probed against live pandas 2.2.3, not inferred.
4586///
4587/// Named `...TemporalError` rather than `...OverflowError` because
4588/// [`Self::ZeroDivision`] is not an overflow; a type whose name promised
4589/// "overflow" while carrying divide-by-zero would be exactly the kind of stale
4590/// label this codebase keeps having to correct.
4591#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4592pub enum PandasTemporalError {
4593    /// `OverflowError`. e.g. `pd.Timedelta.max + pd.Timedelta('1ns')`, and
4594    /// `Series + Timedelta` / `Series - Series` / `.diff()` which report
4595    /// "Overflow in int64 addition".
4596    Overflow,
4597    /// `OutOfBoundsDatetime`. e.g. `pd.Timestamp.max + pd.Timedelta('1ns')`
4598    /// and `pd.Timestamp.min - pd.Timestamp.max`.
4599    OutOfBoundsDatetime,
4600    /// `OutOfBoundsTimedelta`. Raised by the `pd.Timedelta(value, unit=...)`
4601    /// constructor path (see br-frankenpandas-8v92m), not by the six
4602    /// arithmetic helpers below. Probed: `pd.Timedelta(float('inf'), 's')` ->
4603    /// "Cannot cast inf from s to 'ns' without overflow."
4604    OutOfBoundsTimedelta,
4605    /// `ValueError("overflow in timedelta operation")`. Raised by the
4606    /// REDUCTIONS `Series.sum()` and `Series.std()` over timedelta64.
4607    OverflowInTimedeltaOperation,
4608    /// `ZeroDivisionError`. Raised by SCALAR `Timedelta // 0`, `Timedelta / 0`
4609    /// and `Timedelta // 0.0` ONLY.
4610    ///
4611    /// ⚠ The VECTORIZED division family does NOT raise: probed,
4612    /// `Series([Timedelta]) // 0` and `/ 0` both return NaT. A STRICT arm must
4613    /// not widen this class to the vectorized surface — doing so would create
4614    /// divergence where FrankenPandas is already bit-for-bit correct, which is
4615    /// the central finding of br-frankenpandas-fyr1z (see DISC-018).
4616    ZeroDivision,
4617}
4618
4619/// A temporal overflow, naming the operation that overflowed and the pandas
4620/// exception it corresponds to.
4621#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4622pub struct TemporalFailure {
4623    /// The FrankenPandas operation, e.g. `"Timedelta::add"`.
4624    pub op: &'static str,
4625    /// What pandas raises for this operation.
4626    pub pandas_error: PandasTemporalError,
4627    /// The operand pair whose exact result left the representable range, when
4628    /// the failing operation had one. Carried for the HARDENED audit trail
4629    /// (br-frankenpandas-fyr1z-hardened-audit-vllv6) so a recovery entry can
4630    /// name the range violation rather than merely that one occurred.
4631    pub operands: Option<(i64, i64)>,
4632}
4633
4634impl TemporalFailure {
4635    #[must_use]
4636    pub const fn new(op: &'static str, pandas_error: PandasTemporalError) -> Self {
4637        Self {
4638            op,
4639            pandas_error,
4640            operands: None,
4641        }
4642    }
4643
4644    /// Attach the operands that produced this failure.
4645    #[must_use]
4646    pub const fn with_operands(mut self, lhs: i64, rhs: i64) -> Self {
4647        self.operands = Some((lhs, rhs));
4648        self
4649    }
4650}
4651
4652/// A bounded defensive recovery that HARDENED mode performed, recorded so a run
4653/// can be audited after the fact.
4654///
4655/// br-frankenpandas-fyr1z-hardened-audit-vllv6. AGENTS.md's security doctrine
4656/// requires "deterministic audit logs for recoveries and policy overrides", and
4657/// overflow-to-NaT is exactly a bounded defensive recovery. Until now it was
4658/// SILENT: a caller could not distinguish a NaT produced by an overflow from a
4659/// NaT that was already in the input, which is the whole substance of the
4660/// DISC-018 impact statement.
4661#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4662pub struct TemporalRecovery {
4663    /// The operation that overflowed.
4664    pub op: &'static str,
4665    /// The pandas exception this would have been under STRICT.
4666    pub pandas_error: PandasTemporalError,
4667    /// The operands whose exact result was unrepresentable, when known.
4668    pub operands: Option<(i64, i64)>,
4669    /// The value actually returned. Always the family's NaT sentinel today.
4670    pub recovered_as: i64,
4671}
4672
4673/// Deterministic, opt-in audit trail for HARDENED-mode recoveries.
4674///
4675/// Disabled by default and costs one `Option` check when off, so the default
4676/// path is unchanged. The log is THREAD-LOCAL: FrankenPandas parallelises many
4677/// kernels, and a shared log would impose a lock on hot arithmetic and make the
4678/// entry ORDER nondeterministic — which would defeat the point. Each worker
4679/// therefore accumulates its own deterministic sequence; a caller auditing a
4680/// parallel op drains per thread.
4681pub mod overflow_audit {
4682    use std::cell::RefCell;
4683
4684    use super::TemporalRecovery;
4685
4686    thread_local! {
4687        static LOG: RefCell<Option<Vec<TemporalRecovery>>> = const { RefCell::new(None) };
4688    }
4689
4690    /// Begin recording on THIS thread, discarding anything already buffered.
4691    pub fn enable() {
4692        LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
4693    }
4694
4695    /// Stop recording on this thread and discard the buffer.
4696    pub fn disable() {
4697        LOG.with(|log| *log.borrow_mut() = None);
4698    }
4699
4700    /// Whether recording is active on this thread.
4701    #[must_use]
4702    pub fn is_enabled() -> bool {
4703        LOG.with(|log| log.borrow().is_some())
4704    }
4705
4706    /// Take the recorded recoveries, leaving recording enabled and empty.
4707    #[must_use]
4708    pub fn drain() -> Vec<TemporalRecovery> {
4709        LOG.with(|log| match log.borrow_mut().as_mut() {
4710            Some(entries) => std::mem::take(entries),
4711            None => Vec::new(),
4712        })
4713    }
4714
4715    /// Record a recovery. A no-op — and allocation-free — when disabled.
4716    pub(super) fn record(entry: TemporalRecovery) {
4717        LOG.with(|log| {
4718            if let Some(entries) = log.borrow_mut().as_mut() {
4719                entries.push(entry);
4720            }
4721        });
4722    }
4723}
4724
4725/// How a temporal overflow should be surfaced.
4726///
4727/// br-frankenpandas-fyr1z-policy-carrier-f29nz adds this carrier WITHOUT
4728/// changing any default behavior: every existing call site is on
4729/// [`OverflowPolicy::SurfaceNat`], which is exactly what the codebase did
4730/// before. `Strict` exists so fyr1z.3 can wire per-op raise arms in a separate,
4731/// reviewable step, and NOTHING routes to it yet.
4732///
4733/// Note DISC-018: a blanket "STRICT raises everywhere" is NOT pandas parity —
4734/// pandas silently wraps on `Series * int` and `.cumsum()`, and returns NaT for
4735/// `.mean()`. The strict arm therefore needs a per-op table, which is why the
4736/// policy is carried per operation rather than set globally.
4737#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
4738pub enum OverflowPolicy {
4739    /// Today's behavior, and the only arm currently wired up: overflow becomes
4740    /// the family's NaT sentinel.
4741    #[default]
4742    SurfaceNat,
4743    /// Reserved for fyr1z.3. Surfaces the [`TemporalFailure`] to the caller.
4744    Strict,
4745    /// HARDENED mode (br-frankenpandas-fyr1z-hardened-audit-vllv6): returns the
4746    /// SAME NaT as [`Self::SurfaceNat`], bit-for-bit, and additionally records a
4747    /// [`TemporalRecovery`] into [`overflow_audit`] when that log is enabled.
4748    ///
4749    /// This adds observability, never semantics. AGENTS.md defines hardened
4750    /// mode as "bounded defensive recovery" and requires a deterministic audit
4751    /// log for exactly that.
4752    HardenedNat,
4753}
4754
4755impl OverflowPolicy {
4756    /// Resolve a fallible temporal result under this policy.
4757    ///
4758    /// `SurfaceNat` discards the overflow and yields `nat`, reproducing the
4759    /// pre-f29nz behavior bit-for-bit. `Strict` propagates the overflow.
4760    ///
4761    /// # Errors
4762    /// Returns the [`TemporalFailure`] unchanged under [`Self::Strict`].
4763    pub fn resolve<T>(
4764        self,
4765        outcome: Result<T, TemporalFailure>,
4766        nat: T,
4767    ) -> Result<T, TemporalFailure> {
4768        self.resolve_recording(outcome, nat, i64::MIN)
4769    }
4770
4771    /// [`Self::resolve`] plus the sentinel value to record in the audit trail.
4772    ///
4773    /// Split out because the recovered value is generic (`T`) but the audit
4774    /// entry needs its i64 backing; `recovered_as` supplies that without
4775    /// constraining `T`.
4776    ///
4777    /// # Errors
4778    /// Returns the [`TemporalFailure`] unchanged under [`Self::Strict`].
4779    pub fn resolve_recording<T>(
4780        self,
4781        outcome: Result<T, TemporalFailure>,
4782        nat: T,
4783        recovered_as: i64,
4784    ) -> Result<T, TemporalFailure> {
4785        match (self, outcome) {
4786            (_, Ok(value)) => Ok(value),
4787            (Self::SurfaceNat, Err(_)) => Ok(nat),
4788            (Self::Strict, Err(failure)) => Err(failure),
4789            (Self::HardenedNat, Err(failure)) => {
4790                // Same value as SurfaceNat; the ONLY difference is the record.
4791                overflow_audit::record(TemporalRecovery {
4792                    op: failure.op,
4793                    pandas_error: failure.pandas_error,
4794                    operands: failure.operands,
4795                    recovered_as,
4796                });
4797                Ok(nat)
4798            }
4799        }
4800    }
4801}
4802
4803pub struct Timedelta;
4804
4805impl Timedelta {
4806    pub const NANOS_PER_MICRO: i64 = 1_000;
4807    pub const NANOS_PER_MILLI: i64 = 1_000_000;
4808    pub const NANOS_PER_SEC: i64 = 1_000_000_000;
4809    pub const NANOS_PER_MIN: i64 = 60 * Self::NANOS_PER_SEC;
4810    pub const NANOS_PER_HOUR: i64 = 60 * Self::NANOS_PER_MIN;
4811    pub const NANOS_PER_DAY: i64 = 24 * Self::NANOS_PER_HOUR;
4812    pub const NANOS_PER_WEEK: i64 = 7 * Self::NANOS_PER_DAY;
4813
4814    pub const NAT: i64 = i64::MIN;
4815
4816    pub fn parse(s: &str) -> Result<i64, TimedeltaError> {
4817        let s = s.trim();
4818
4819        if s.eq_ignore_ascii_case("nat") {
4820            return Ok(Self::NAT);
4821        }
4822
4823        let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
4824            (true, rest.trim())
4825        } else {
4826            (false, s)
4827        };
4828
4829        if let Some(nanos) = Self::try_parse_time_format(s) {
4830            return Ok(if negative { -nanos } else { nanos });
4831        }
4832
4833        if let Some(nanos) = Self::try_parse_iso8601_duration(s) {
4834            return Ok(if negative { -nanos } else { nanos });
4835        }
4836
4837        // pandas' leading '-' negates the unit values but not an HH:MM:SS
4838        // part that follows one: "-1 days +02:03:04" (how pandas prints a
4839        // negative Timedelta) is -1 day + 2:03:04. Negating the whole
4840        // compound read it as -(1 day 2:03:04), so a printed Timedelta did
4841        // not parse back to itself.
4842        let (units, clock) = Self::parse_compound(s)?;
4843        let units = if negative { -units } else { units };
4844        units.checked_add(clock).ok_or(TimedeltaError::Overflow)
4845    }
4846
4847    /// Parse an ISO-8601 duration the way pandas `Timedelta` accepts it:
4848    /// a leading uppercase `P`, an optional `T` separator that is otherwise
4849    /// ignored, and unit letters `W`/`D`/`H`/`M`/`S` in any position. `M` is
4850    /// always MINUTES (never months), and only seconds may be fractional —
4851    /// years/months and lowercase units are rejected, matching pandas.
4852    /// (pandas mis-handles fractional non-second components; those are rejected
4853    /// here rather than reproducing the buggy value.) (br-frankenpandas-c3p8b)
4854    fn try_parse_iso8601_duration(s: &str) -> Option<i64> {
4855        let mut rest = s.strip_prefix('P')?;
4856        if rest.is_empty() {
4857            return None;
4858        }
4859        let mut total: i64 = 0;
4860        let mut saw_component = false;
4861        while !rest.is_empty() {
4862            if let Some(after_t) = rest.strip_prefix('T') {
4863                rest = after_t;
4864                continue;
4865            }
4866            let num_end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')?;
4867            if num_end == 0 {
4868                return None;
4869            }
4870            let num_str = &rest[..num_end];
4871            let unit = rest.as_bytes()[num_end];
4872            let is_fractional = num_str.contains('.');
4873            rest = &rest[num_end + 1..];
4874
4875            let (multiplier, frac_ok) = match unit {
4876                b'W' => (Self::NANOS_PER_WEEK, false),
4877                b'D' => (Self::NANOS_PER_DAY, false),
4878                b'H' => (Self::NANOS_PER_HOUR, false),
4879                b'M' => (Self::NANOS_PER_MIN, false),
4880                b'S' => (Self::NANOS_PER_SEC, true),
4881                _ => return None,
4882            };
4883            if is_fractional {
4884                if !frac_ok {
4885                    return None;
4886                }
4887                let value: f64 = num_str.parse().ok()?;
4888                let product = value * multiplier as f64;
4889                if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
4890                    return None;
4891                }
4892                total = total.checked_add(product.round() as i64)?;
4893            } else {
4894                let value: i64 = num_str.parse().ok()?;
4895                total = total.checked_add(value.checked_mul(multiplier)?)?;
4896            }
4897            saw_component = true;
4898        }
4899        saw_component.then_some(total)
4900    }
4901
4902    fn try_parse_time_format(s: &str) -> Option<i64> {
4903        let parts: Vec<&str> = s.split(':').collect();
4904        if parts.len() < 2 || parts.len() > 3 {
4905            return None;
4906        }
4907
4908        let hours: i64 = parts[0].parse().ok()?;
4909        let minutes: i64 = parts[1].parse().ok()?;
4910
4911        let (seconds, frac_nanos) = if parts.len() == 3 {
4912            if let Some((sec_str, frac_str)) = parts[2].split_once('.') {
4913                let sec: i64 = sec_str.parse().ok()?;
4914                if !frac_str.bytes().all(|byte| byte.is_ascii_digit()) {
4915                    return None;
4916                }
4917                let mut frac = 0_i64;
4918                let taken = frac_str.len().min(9);
4919                for byte in frac_str.bytes().take(9) {
4920                    frac = frac * 10 + i64::from(byte - b'0');
4921                }
4922                for _ in taken..9 {
4923                    frac *= 10;
4924                }
4925                (sec, frac)
4926            } else {
4927                let sec: i64 = parts[2].parse().ok()?;
4928                (sec, 0)
4929            }
4930        } else {
4931            (0, 0)
4932        };
4933
4934        hours
4935            .checked_mul(Self::NANOS_PER_HOUR)?
4936            .checked_add(minutes.checked_mul(Self::NANOS_PER_MIN)?)?
4937            .checked_add(seconds.checked_mul(Self::NANOS_PER_SEC)?)?
4938            .checked_add(frac_nanos)
4939    }
4940
4941    /// The number-and-unit values of a compound Timedelta string, and the
4942    /// HH:MM:SS part that may end it (which the leading sign does not
4943    /// negate; see [`Self::parse`]). A sign inside the string is pandas'
4944    /// "only leading negative signs are allowed" error ("1 days -02:00:00"
4945    /// read as 22 hours).
4946    fn parse_compound(s: &str) -> Result<(i64, i64), TimedeltaError> {
4947        let mut total: i64 = 0;
4948        let mut clock: i64 = 0;
4949        let mut remaining = s;
4950
4951        while !remaining.is_empty() {
4952            remaining = remaining.trim_start();
4953            if remaining.is_empty() {
4954                break;
4955            }
4956            if remaining.starts_with('-') {
4957                return Err(TimedeltaError::InvalidFormat(format!(
4958                    "only leading negative signs are allowed: {s}"
4959                )));
4960            }
4961
4962            // Per br-frankenpandas-i9bah: check if remaining is a time format
4963            // (HH:MM:SS) which can appear after "N days " in pandas timedelta strings.
4964            if remaining.contains(':')
4965                && let Some(time_nanos) = Self::try_parse_time_format(remaining)
4966            {
4967                clock = time_nanos;
4968                break;
4969            }
4970
4971            let num_end = remaining
4972                .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
4973                .unwrap_or(remaining.len());
4974
4975            if num_end == 0 {
4976                return Err(TimedeltaError::InvalidFormat(s.to_string()));
4977            }
4978
4979            let num_str = &remaining[..num_end];
4980            let num: f64 = num_str
4981                .parse()
4982                .map_err(|_| TimedeltaError::InvalidFormat(s.to_string()))?;
4983
4984            remaining = remaining[num_end..].trim_start();
4985
4986            let unit_end = remaining
4987                .find(|c: char| c.is_ascii_digit() || c.is_whitespace())
4988                .unwrap_or(remaining.len());
4989
4990            let unit = &remaining[..unit_end];
4991            remaining = &remaining[unit_end..];
4992
4993            let multiplier = Self::unit_to_nanos(unit)
4994                .ok_or_else(|| TimedeltaError::InvalidFormat(s.to_string()))?;
4995
4996            // Per br-frankenpandas-zw3mg: pandas raises OverflowError on
4997            // huge scientific-notation Timedeltas like "1e100 days". The
4998            // raw `as i64` cast silently saturated to i64::MAX, masking
4999            // overflow before checked_add could catch it.
5000            let product = num * multiplier as f64;
5001            if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5002                return Err(TimedeltaError::Overflow);
5003            }
5004            let nanos = product.round() as i64;
5005            total = total.checked_add(nanos).ok_or(TimedeltaError::Overflow)?;
5006        }
5007
5008        // NOTE: there is deliberately no "total == 0 is suspicious" guard here.
5009        // One used to live at this spot and rejected every legitimately-zero
5010        // compound -- `to_timedelta("0 seconds")` raised while `"1 second"` and
5011        // `"10 seconds"` parsed, because the only exemption was the literal
5012        // string "0". pandas 2.2.3 accepts all of `0 seconds` / `0 days` / `0s`
5013        // / `0.0 hours` / `-0 seconds` as a zero Timedelta. The guard was also
5014        // unnecessary: the loop above returns `InvalidFormat` on an unparseable
5015        // number AND on an unknown unit, so the only way to reach here with
5016        // `total == 0` is an input whose components genuinely sum to zero.
5017        Ok((total, clock))
5018    }
5019
5020    /// Map a pandas-style frequency-alias string to a nanosecond-count.
5021    ///
5022    /// Recognizes pandas's offset alias core set plus common word forms:
5023    /// W/week(s), D/day(s), H/hr/hour(s), m/T/min/minute(s), s/sec/second(s),
5024    /// ms/milli/millisecond(s)/L, us/µs/micro/microsecond(s)/U, ns/nano/
5025    /// nanosecond(s)/N. Empty string maps to days (matches pandas default).
5026    /// Returns `None` for unrecognized aliases — callers can choose to map
5027    /// that to NaT (consistent with the rest of fp-types) or surface as a
5028    /// typed error.
5029    ///
5030    /// Per br-frankenpandas-lbsx (9p0u Phase 2.6): public surface so
5031    /// downstream crates can consume the same alias map fp-types uses for
5032    /// `Timedelta::from_unit` / `Timestamp::*_to_unit`.
5033    #[must_use]
5034    pub fn unit_to_nanos(unit: &str) -> Option<i64> {
5035        match unit.to_lowercase().as_str() {
5036            "w" | "week" | "weeks" => Some(Self::NANOS_PER_WEEK),
5037            "d" | "day" | "days" => Some(Self::NANOS_PER_DAY),
5038            "h" | "hr" | "hour" | "hours" => Some(Self::NANOS_PER_HOUR),
5039            "m" | "min" | "minute" | "minutes" | "t" => Some(Self::NANOS_PER_MIN),
5040            "s" | "sec" | "second" | "seconds" => Some(Self::NANOS_PER_SEC),
5041            "ms" | "milli" | "millis" | "millisecond" | "milliseconds" | "l" => {
5042                Some(Self::NANOS_PER_MILLI)
5043            }
5044            "us" | "µs" | "micro" | "micros" | "microsecond" | "microseconds" | "u" => {
5045                Some(Self::NANOS_PER_MICRO)
5046            }
5047            "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" | "n" => Some(1),
5048            "" => Some(Self::NANOS_PER_DAY),
5049            _ => None,
5050        }
5051    }
5052
5053    pub fn components(nanos: i64) -> TimedeltaComponents {
5054        if nanos == Self::NAT {
5055            return TimedeltaComponents::default();
5056        }
5057
5058        // pandas/Python normalize via FLOOR division (like format()): the days
5059        // component can be negative while the time-of-day remainder is always in
5060        // [0, 1 day). So pd.Timedelta(-1,'s').components == (-1, 23, 59, 59, 0, 0, 0),
5061        // NOT the abs-based (0, 0, 0, 1, 0, 0, 0).
5062        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5063        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5064
5065        let hours = rem / Self::NANOS_PER_HOUR;
5066        let rem = rem % Self::NANOS_PER_HOUR;
5067
5068        let minutes = rem / Self::NANOS_PER_MIN;
5069        let rem = rem % Self::NANOS_PER_MIN;
5070
5071        let seconds = rem / Self::NANOS_PER_SEC;
5072        let rem = rem % Self::NANOS_PER_SEC;
5073
5074        let milliseconds = rem / Self::NANOS_PER_MILLI;
5075        let rem = rem % Self::NANOS_PER_MILLI;
5076
5077        let microseconds = rem / Self::NANOS_PER_MICRO;
5078        let nanoseconds = rem % Self::NANOS_PER_MICRO;
5079
5080        TimedeltaComponents {
5081            days,
5082            hours,
5083            minutes,
5084            seconds,
5085            milliseconds,
5086            microseconds,
5087            nanoseconds,
5088        }
5089    }
5090
5091    pub fn total_seconds(nanos: i64) -> f64 {
5092        if nanos == Self::NAT {
5093            f64::NAN
5094        } else {
5095            nanos as f64 / Self::NANOS_PER_SEC as f64
5096        }
5097    }
5098
5099    /// Convert to specified time unit.
5100    ///
5101    /// Matches pd.Timedelta.as_unit(). Supported units: ns, us, ms, s, m, h, D.
5102    #[must_use]
5103    pub fn as_unit(nanos: i64, unit: &str) -> f64 {
5104        if nanos == Self::NAT {
5105            return f64::NAN;
5106        }
5107        let nanos_f = nanos as f64;
5108        match unit {
5109            "ns" | "nanoseconds" => nanos_f,
5110            "us" | "microseconds" => nanos_f / Self::NANOS_PER_MICRO as f64,
5111            "ms" | "milliseconds" => nanos_f / Self::NANOS_PER_MILLI as f64,
5112            "s" | "seconds" => nanos_f / Self::NANOS_PER_SEC as f64,
5113            "m" | "minutes" => nanos_f / Self::NANOS_PER_MIN as f64,
5114            "h" | "hours" => nanos_f / Self::NANOS_PER_HOUR as f64,
5115            "D" | "days" => nanos_f / Self::NANOS_PER_DAY as f64,
5116            _ => f64::NAN,
5117        }
5118    }
5119
5120    /// Return the days component, or `None` for `NaT`. Matches
5121    /// `pd.Timedelta.days`.
5122    ///
5123    /// ⚠️ `None`, NOT `0`, AND THE TYPE IS THE FIX
5124    /// (br-frankenpandas-timedelta-nat-days-returns-zero-406ni). All four
5125    /// component helpers used to return `0` for `NaT`, one of them behind a
5126    /// comment asserting "pandas returns 0 for NaT.days (no error)". MEASURED,
5127    /// live pandas 2.2.3: `pd.NaT.days` is **nan**, and
5128    /// `pd.to_timedelta([1, None, -1], unit='s').dt.days` is float64
5129    /// `[0.0, nan, -1.0]` — pandas promotes the whole column because NaN cannot
5130    /// live in int64.
5131    ///
5132    /// An `i64` return cannot express that, so correctness depended on every
5133    /// caller remembering to test `NAT` first. It did — `timedelta_component`
5134    /// checked in three separate arms — but that is a convention, and the bead
5135    /// filed it as a landmine for the next person to wire a `.dt` accessor: a
5136    /// function whose doc says "matches pandas" handing back a plausible integer
5137    /// where pandas has a missing value. `Option<i64>` moves the fact into the
5138    /// type, so a caller cannot forget and the duplicated `NAT` tests go away.
5139    #[must_use]
5140    pub fn days(nanos: i64) -> Option<i64> {
5141        if nanos == Self::NAT {
5142            return None;
5143        }
5144        // FLOOR division like pandas: pd.Timedelta(-1,'s').days == -1, not 0.
5145        Some(nanos.div_euclid(Self::NANOS_PER_DAY))
5146    }
5147
5148    /// Return the seconds component (0-86399), or `None` for `NaT`. Matches
5149    /// `pd.Timedelta.seconds`. See [`Self::days`] for why this is an `Option`.
5150    #[must_use]
5151    pub fn seconds(nanos: i64) -> Option<i64> {
5152        if nanos == Self::NAT {
5153            return None;
5154        }
5155        // Floor-normalized time-of-day remainder: pd.Timedelta(-1,'s').seconds == 86399.
5156        Some(nanos.rem_euclid(Self::NANOS_PER_DAY) / Self::NANOS_PER_SEC)
5157    }
5158
5159    /// Return the microseconds component (0-999999), or `None` for `NaT`.
5160    /// Matches `pd.Timedelta.microseconds`. See [`Self::days`].
5161    #[must_use]
5162    pub fn microseconds(nanos: i64) -> Option<i64> {
5163        if nanos == Self::NAT {
5164            return None;
5165        }
5166        Some(nanos.rem_euclid(Self::NANOS_PER_SEC) / Self::NANOS_PER_MICRO)
5167    }
5168
5169    /// Return the nanoseconds component (0-999), or `None` for `NaT`. Matches
5170    /// `pd.Timedelta.nanoseconds`. See [`Self::days`].
5171    #[must_use]
5172    pub fn nanoseconds(nanos: i64) -> Option<i64> {
5173        if nanos == Self::NAT {
5174            return None;
5175        }
5176        Some(nanos.rem_euclid(Self::NANOS_PER_MICRO))
5177    }
5178
5179    /// The coarsest [`TimedeltaStringResolution`] that renders `nanos`
5180    /// losslessly. Fold over a column with `max`.
5181    ///
5182    /// `NaT` reports `Days`, the identity of that fold, because pandas excludes
5183    /// it from the scan: `[1 days, NaT]` still renders `['1 days', 'NaT']`.
5184    #[must_use]
5185    pub const fn string_resolution(nanos: i64) -> TimedeltaStringResolution {
5186        if nanos == Self::NAT || nanos.rem_euclid(Self::NANOS_PER_DAY) == 0 {
5187            TimedeltaStringResolution::Days
5188        } else {
5189            TimedeltaStringResolution::Full
5190        }
5191    }
5192
5193    /// Render `nanos` the way `astype(str)` does, at a resolution chosen for the
5194    /// whole column by [`Self::string_resolution`].
5195    ///
5196    /// The `Full` arm is [`Self::format`] verbatim — the per-value sub-second
5197    /// width was already right. Only the `Days` arm is new, and it exists
5198    /// because a column of whole days drops its time part completely:
5199    /// `'1 days'`, not `'1 days 00:00:00'`.
5200    #[must_use]
5201    pub fn format_at_resolution(nanos: i64, resolution: TimedeltaStringResolution) -> String {
5202        if nanos == Self::NAT {
5203            return "NaT".to_string();
5204        }
5205        match resolution {
5206            TimedeltaStringResolution::Full => Self::format(nanos),
5207            // Euclidean division, so a negative whole-day value keeps pandas'
5208            // spelling: -2 days is "-2 days", never "-1 days -24:00:00".
5209            TimedeltaStringResolution::Days => {
5210                format!("{} days", nanos.div_euclid(Self::NANOS_PER_DAY))
5211            }
5212        }
5213    }
5214
5215    pub fn format(nanos: i64) -> String {
5216        use std::fmt::Write as _;
5217
5218        if nanos == Self::NAT {
5219            return "NaT".to_string();
5220        }
5221
5222        // pandas / Python timedelta normalize via FLOOR division: the days
5223        // component can be negative while the time-of-day remainder is always
5224        // non-negative, and a negative-days value prints a '+' before the time
5225        // (e.g. -1s -> "-1 days +23:59:59", not "-0 days 00:00:01"). Compute the
5226        // components with Euclidean div/rem so the remainder is in [0, 1 day).
5227        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5228        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5229        let hours = rem / Self::NANOS_PER_HOUR;
5230        let minutes = (rem % Self::NANOS_PER_HOUR) / Self::NANOS_PER_MIN;
5231        let seconds = (rem % Self::NANOS_PER_MIN) / Self::NANOS_PER_SEC;
5232        let frac = rem % Self::NANOS_PER_SEC;
5233
5234        // Build directly into the returned allocation. The former path first
5235        // allocated an `HH:MM:SS` string, then copied it into the result.
5236        let mut result = String::with_capacity(32);
5237        let _ = write!(result, "{days} days ");
5238        // '+' joins the negative day count to the positive time remainder.
5239        if days < 0 {
5240            result.push('+');
5241        }
5242        let _ = write!(result, "{hours:02}:{minutes:02}:{seconds:02}");
5243        if frac > 0 {
5244            // pandas renders the sub-second part with microsecond precision
5245            // (6 digits) unless a sub-microsecond (nanosecond) component is
5246            // present, in which case it widens to 9 digits.
5247            if frac % 1_000 == 0 {
5248                let _ = write!(result, ".{:06}", frac / 1_000);
5249            } else {
5250                let _ = write!(result, ".{frac:09}");
5251            }
5252        }
5253        result
5254    }
5255
5256    /// Build a nanosecond Timedelta from a float quantity of `unit`.
5257    ///
5258    /// Matches `pd.Timedelta(value, unit=...)`:
5259    /// - `NaN` → `NAT`. pandas returns `NaT`, and `NAT` is how NaT is spelled
5260    ///   in this i64 representation. Rust's float→int `as` maps `NaN` to
5261    ///   **0**, so the unguarded cast used to hand back a ZERO DURATION for a
5262    ///   missing value (br-frankenpandas-8v92m).
5263    /// - non-finite or out-of-range product → [`TimedeltaError::Overflow`].
5264    ///   pandas raises `OutOfBoundsTimedelta` ("Cannot cast inf from s to 'ns'
5265    ///   without overflow"); the `as` cast used to SATURATE to `i64::MAX`,
5266    ///   returning a finite, plausible ~106751-day duration instead.
5267    /// - unknown unit → [`TimedeltaError::InvalidFormat`], unchanged.
5268    ///
5269    /// The overflow guard is the same one `parse` and the component parser
5270    /// already use (added by br-frankenpandas-zw3mg, which fixed two of the
5271    /// three sites sharing this expression and missed this one).
5272    pub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError> {
5273        let multiplier = Self::unit_to_nanos(unit)
5274            .ok_or_else(|| TimedeltaError::InvalidFormat(unit.to_string()))?;
5275        if value.is_nan() {
5276            return Ok(Self::NAT);
5277        }
5278        let product = value * multiplier as f64;
5279        if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5280            return Err(TimedeltaError::Overflow);
5281        }
5282        Ok(product.round() as i64)
5283    }
5284
5285    // ── Arithmetic (br-frankenpandas-4r56 Phase 1) ──────────────────────
5286    //
5287    // NaT propagation: any arithmetic with `NAT` returns `NAT`. Matches
5288    // pandas `pd.NaT + anything == NaT`, `pd.NaT - anything == NaT`, etc.
5289    //
5290    // Overflow (br-frankenpandas-lgyy8): i64 overflow yields `NAT` in BOTH
5291    // directions. It never wraps and never fabricates a finite value.
5292    //
5293    // These previously used `saturating_*`, which was asymmetric and failed
5294    // OPEN on one side. Because `NAT == i64::MIN`, negative overflow clamped
5295    // onto the sentinel and already surfaced as missing — but POSITIVE
5296    // overflow clamped to `i64::MAX`, a perfectly valid, finite, plausible
5297    // duration (and, for `Timestamp`, a ~year-2262 instant) returned as if it
5298    // were real data. Live pandas 2.2.3 never does that, in either the scalar
5299    // or the vectorized path:
5300    //
5301    //   pd.Timedelta.min + Timedelta('-1ns')      -> NaT  (lands on the sentinel)
5302    //   pd.Series[datetime64] + Timedelta('-1ns') -> [NaT, ...]
5303    //   pd.Timedelta.max + Timedelta('1ns')       -> raises OverflowError
5304    //   pd.Timestamp.max + Timedelta('1ns')       -> raises OutOfBoundsDatetime
5305    //   pd.Series[datetime64] + Timedelta('1ns')  -> raises OverflowError
5306    //   pd.Timestamp.min - pd.Timestamp.max       -> raises OutOfBoundsDatetime
5307    //   pd.Timedelta.max * 2                      -> raises OverflowError
5308    //
5309    // We surface NaT where pandas raises, rather than making these infallible
5310    // `#[must_use]` helpers fallible: that is the SAME documented divergence
5311    // `div_scalar` already takes for divide-by-zero ("matches pandas, which
5312    // raises, but we surface as NaT to avoid panics at the type-system
5313    // boundary"). Every input whose exact result is representable is
5314    // unaffected bit-for-bit; only overflow moves.
5315
5316    /// Add two Timedelta nanosecond values, reporting overflow.
5317    ///
5318    /// br-frankenpandas-fyr1z-policy-carrier-f29nz. NaT propagation is NOT an
5319    /// overflow — a NaT operand yields `Ok(NAT)`, exactly as before. Only an
5320    /// unrepresentable result is an `Err`.
5321    ///
5322    /// # Errors
5323    /// [`PandasTemporalError::Overflow`] when the sum exceeds i64.
5324    pub fn try_add(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5325        if a == Self::NAT || b == Self::NAT {
5326            return Ok(Self::NAT);
5327        }
5328        a.checked_add(b).ok_or(
5329            TemporalFailure::new("Timedelta::add", PandasTemporalError::Overflow)
5330                .with_operands(a, b),
5331        )
5332    }
5333
5334    /// Add two Timedelta nanosecond values. NaT propagates; overflow → NaT.
5335    #[must_use]
5336    pub fn add(a: i64, b: i64) -> i64 {
5337        Self::try_add(a, b).unwrap_or(Self::NAT)
5338    }
5339
5340    /// Subtract two Timedelta nanosecond values, reporting overflow.
5341    ///
5342    /// # Errors
5343    /// [`PandasTemporalError::Overflow`] when the difference exceeds i64.
5344    pub fn try_sub(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5345        if a == Self::NAT || b == Self::NAT {
5346            return Ok(Self::NAT);
5347        }
5348        a.checked_sub(b).ok_or(
5349            TemporalFailure::new("Timedelta::sub", PandasTemporalError::Overflow)
5350                .with_operands(a, b),
5351        )
5352    }
5353
5354    /// Subtract two Timedelta nanosecond values. NaT propagates; overflow → NaT.
5355    #[must_use]
5356    pub fn sub(a: i64, b: i64) -> i64 {
5357        Self::try_sub(a, b).unwrap_or(Self::NAT)
5358    }
5359
5360    /// Negate a Timedelta value. NaT stays NaT.
5361    ///
5362    /// There is no overflow case to handle, and the `saturating_` call is a
5363    /// belt-and-braces no-op: the only `i64` whose negation overflows is
5364    /// `i64::MIN`, and `i64::MIN` IS the NaT sentinel, so it is consumed by
5365    /// the guard above. The representable range is `[i64::MIN + 1, i64::MAX]`,
5366    /// which is symmetric about zero.
5367    ///
5368    /// CORRECTED br-frankenpandas-fyr1z: this used to claim "pandas:
5369    /// `-pd.Timedelta.min` is NaT since min == -max - 1 cannot be negated".
5370    /// That is false in both halves. pandas' `Timedelta.min.value` is
5371    /// `-9223372036854775807` == `-Timedelta.max.value`, NOT `-max - 1`
5372    /// (`-max - 1` is `i64::MIN`, which pandas also reserves for NaT), and
5373    /// live pandas 2.2.3 returns `Timedelta('106751 days 23:47:16.854775807')`
5374    /// — i.e. `Timedelta.max` — for `-pd.Timedelta.min`, `abs(pd.Timedelta
5375    /// .min)`, and the vectorized `-Series[timedelta64]` / `.abs()` forms.
5376    /// Do not "fix" this to return NaT; that would be the parity regression.
5377    #[must_use]
5378    pub fn neg(a: i64) -> i64 {
5379        if a == Self::NAT {
5380            return Self::NAT;
5381        }
5382        a.saturating_neg()
5383    }
5384
5385    /// Absolute value of a Timedelta. NaT stays NaT.
5386    ///
5387    /// As with [`Timedelta::neg`], no overflow is reachable: `i64::MIN` is the
5388    /// NaT sentinel and is consumed by the guard, and `|i64::MIN + 1|` is
5389    /// exactly `i64::MAX`. pandas agrees — `abs(pd.Timedelta.min)` is
5390    /// `Timedelta.max`, not NaT.
5391    #[must_use]
5392    pub fn abs(a: i64) -> i64 {
5393        if a == Self::NAT {
5394            return Self::NAT;
5395        }
5396        a.saturating_abs()
5397    }
5398
5399    /// Multiply a Timedelta value by an integer factor. NaT propagates;
5400    /// overflow → NaT (see the overflow note above).
5401    ///
5402    /// Matches pandas `pd.Timedelta(...) * int`, which raises `OverflowError`
5403    /// rather than returning a saturated duration.
5404    #[must_use]
5405    pub fn mul_scalar(a: i64, factor: i64) -> i64 {
5406        Self::try_mul_scalar(a, factor).unwrap_or(Self::NAT)
5407    }
5408
5409    /// Multiply a Timedelta by an integer factor under an explicit policy.
5410    ///
5411    /// br-frankenpandas-fyr1z-wrap-signoff-s4lkx, DECIDED BY THE MAINTAINER:
5412    /// **STRICT REPRODUCES PANDAS' SILENT WRAP.** The rationale is that this is
5413    /// a PORT — STRICT means bit-for-bit observable parity with the incumbent
5414    /// *including its quirks*, so the wrap is a deliberately reproduced pandas
5415    /// behaviour, not a defect of ours.
5416    ///
5417    /// Verified against live pandas 2.2.3: `Series([Timedelta.max]) * 2` returns
5418    /// `-2` ns (displayed `-1 days +23:59:59.999999998`), which is exactly
5419    /// `i64::MAX.wrapping_mul(2)`. Rust's wrapping arithmetic reproduces numpy's
5420    /// int64 wraparound bit-for-bit, so no emulation is needed.
5421    ///
5422    /// The wrap is INTEGER-MULTIPLIER ONLY: `Series * 2.0` returns NaT in
5423    /// pandas, so a float multiplier must not route here.
5424    ///
5425    /// Every other policy keeps today's behaviour — NaT, with HARDENED also
5426    /// recording the recovery. So the fail-open shape br-frankenpandas-lgyy8
5427    /// removed is reachable ONLY when a caller explicitly asks for STRICT
5428    /// incumbent parity, never by default. See DISC-020.
5429    #[must_use]
5430    pub fn mul_scalar_with_policy(a: i64, factor: i64, policy: OverflowPolicy) -> i64 {
5431        if a == Self::NAT {
5432            return Self::NAT;
5433        }
5434        if matches!(policy, OverflowPolicy::Strict) {
5435            return a.wrapping_mul(factor);
5436        }
5437        policy
5438            .resolve_recording(Self::try_mul_scalar(a, factor), Self::NAT, Self::NAT)
5439            .unwrap_or(Self::NAT)
5440    }
5441
5442    /// Multiply a Timedelta value by an integer factor, reporting overflow.
5443    ///
5444    /// # Errors
5445    /// [`PandasTemporalError::Overflow`] when the product exceeds i64 — which
5446    /// is what the SCALAR `pd.Timedelta.max * 2` raises. Note DISC-018: the
5447    /// VECTORIZED `Series * int` wraps silently instead, so a strict arm for
5448    /// this op must decide per-surface rather than inherit this class blindly.
5449    pub fn try_mul_scalar(a: i64, factor: i64) -> Result<i64, TemporalFailure> {
5450        if a == Self::NAT {
5451            return Ok(Self::NAT);
5452        }
5453        a.checked_mul(factor).ok_or(
5454            TemporalFailure::new("Timedelta::mul_scalar", PandasTemporalError::Overflow)
5455                .with_operands(a, factor),
5456        )
5457    }
5458
5459    /// Floor-divide a Timedelta value by an integer divisor. NaT propagates.
5460    /// Returns NaT on divide-by-zero (matches pandas, which raises, but we
5461    /// surface as NaT to avoid panics at the type-system boundary).
5462    ///
5463    /// Matches pandas / Python `pd.Timedelta(...) // int`: floor division,
5464    /// not truncation toward zero. `-100 // 3 == -34`, and `100 // -3 ==
5465    /// -34`. Rust's `/` truncates toward zero and `div_euclid` keeps the
5466    /// remainder non-negative — neither matches pandas when the divisor is
5467    /// negative. This helper adjusts trunc-toward-zero into floor.
5468    #[must_use]
5469    pub fn div_scalar(a: i64, divisor: i64) -> i64 {
5470        Self::try_div_scalar(a, divisor).unwrap_or(Self::NAT)
5471    }
5472
5473    /// Floor-divide a Timedelta by an integer divisor, reporting divide-by-zero.
5474    ///
5475    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2. NaT propagation is not a
5476    /// failure and yields `Ok(NAT)`; only a zero divisor is an `Err`.
5477    ///
5478    /// ⚠ SCALAR SEMANTICS ONLY. pandas raises `ZeroDivisionError` for the
5479    /// scalar `pd.Timedelta('1s') // 0`, but the VECTORIZED
5480    /// `Series([Timedelta]) // 0` returns NaT (both probed on 2.2.3). The
5481    /// infallible [`Self::div_scalar`] above keeps the NaT behavior that the
5482    /// vectorized callers depend on, and a STRICT arm must route only the
5483    /// scalar surface here.
5484    ///
5485    /// # Errors
5486    /// [`PandasTemporalError::ZeroDivision`] when `divisor == 0`.
5487    pub fn try_div_scalar(a: i64, divisor: i64) -> Result<i64, TemporalFailure> {
5488        if divisor == 0 {
5489            return Err(TemporalFailure::new(
5490                "Timedelta::div_scalar",
5491                PandasTemporalError::ZeroDivision,
5492            )
5493            .with_operands(a, divisor));
5494        }
5495        if a == Self::NAT {
5496            return Ok(Self::NAT);
5497        }
5498        Ok(Self::div_scalar_inner(a, divisor))
5499    }
5500
5501    fn div_scalar_inner(a: i64, divisor: i64) -> i64 {
5502        // NAT == i64::MIN so the classic `i64::MIN / -1` overflow path is
5503        // already handled by the NAT check above. `(i64::MIN + 1) / -1`
5504        // equals `i64::MAX` with no overflow, so we never need a
5505        // saturation branch here.
5506        let q = a / divisor;
5507        let r = a % divisor;
5508        // If remainder is non-zero and has opposite sign from divisor,
5509        // Rust's trunc-toward-zero `/` is one step above the floor. Adjust
5510        // down by 1 to match Python/pandas floor division.
5511        if r != 0 && (r < 0) != (divisor < 0) {
5512            q - 1
5513        } else {
5514            q
5515        }
5516    }
5517
5518    /// Divide two Timedelta values, returning the ratio as f64.
5519    /// Matches pandas `pd.Timedelta(...) / pd.Timedelta(...)` → float.
5520    /// NaT in either operand → NaN. Zero divisor → ±Inf (per IEEE 754).
5521    #[must_use]
5522    pub fn div_timedelta(a: i64, b: i64) -> f64 {
5523        if a == Self::NAT || b == Self::NAT {
5524            return f64::NAN;
5525        }
5526        (a as f64) / (b as f64)
5527    }
5528
5529    /// Returns ISO 8601 duration format string.
5530    ///
5531    /// Matches pandas `pd.Timedelta.isoformat()`. Returns format like
5532    /// "P1DT2H3M4.567890123S" for 1 day, 2 hours, 3 minutes, 4.567890123 seconds.
5533    /// A negative duration is pandas' components form: whole days rounded
5534    /// down, then a non-negative clock (-1 day -1 hour is "P-2DT23H0M0S";
5535    /// it was "-P1DT1H0M0S"). NaT returns "NaT".
5536    #[must_use]
5537    pub fn isoformat(nanos: i64) -> String {
5538        use std::fmt::Write as _;
5539
5540        if nanos == Self::NAT {
5541            return "NaT".to_string();
5542        }
5543
5544        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5545        let remaining = nanos.rem_euclid(Self::NANOS_PER_DAY);
5546
5547        let hours = remaining / Self::NANOS_PER_HOUR;
5548        let remaining = remaining % Self::NANOS_PER_HOUR;
5549
5550        let minutes = remaining / Self::NANOS_PER_MIN;
5551        let remaining = remaining % Self::NANOS_PER_MIN;
5552
5553        let seconds = remaining / Self::NANOS_PER_SEC;
5554        let sub_sec_nanos = remaining % Self::NANOS_PER_SEC;
5555
5556        // Build directly into the returned allocation. The former sequence of
5557        // `format!` calls allocated two temporary strings for integral values
5558        // and three for fractional values before copying them into `result`.
5559        let mut result = String::with_capacity(40);
5560        // `fmt::Write for String` is infallible.
5561        let _ = write!(result, "P{days}DT{hours}H{minutes}M{seconds}");
5562        if sub_sec_nanos != 0 {
5563            result.push('.');
5564            let _ = write!(result, "{sub_sec_nanos:09}");
5565            while result.ends_with('0') {
5566                result.pop();
5567            }
5568        }
5569        result.push('S');
5570        result
5571    }
5572
5573    /// Rounds down to the nearest frequency unit.
5574    ///
5575    /// Matches pandas `pd.Timedelta.floor(freq)`. NaT is preserved.
5576    #[must_use]
5577    pub fn floor(nanos: i64, freq: &str) -> i64 {
5578        if nanos == Self::NAT {
5579            return Self::NAT;
5580        }
5581        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5582            return Self::NAT;
5583        };
5584        if unit_nanos == 0 {
5585            return Self::NAT;
5586        }
5587        nanos
5588            .div_euclid(unit_nanos)
5589            .checked_mul(unit_nanos)
5590            .unwrap_or(Self::NAT)
5591    }
5592
5593    /// Rounds up to the nearest frequency unit.
5594    ///
5595    /// Matches pandas `pd.Timedelta.ceil(freq)`. NaT is preserved; overflow
5596    /// → NaT (`pd.Timedelta.max.ceil('D')` raises `OutOfBoundsTimedelta:
5597    /// Cannot round ... without overflow`, so a clamped `i64::MAX` would be a
5598    /// fabricated finite duration — see br-frankenpandas-kyd16).
5599    #[must_use]
5600    pub fn ceil(nanos: i64, freq: &str) -> i64 {
5601        if nanos == Self::NAT {
5602            return Self::NAT;
5603        }
5604        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5605            return Self::NAT;
5606        };
5607        if unit_nanos == 0 {
5608            return Self::NAT;
5609        }
5610        let remainder = nanos.rem_euclid(unit_nanos);
5611        if remainder == 0 {
5612            nanos
5613        } else {
5614            nanos
5615                .checked_add(unit_nanos - remainder)
5616                .unwrap_or(Self::NAT)
5617        }
5618    }
5619
5620    /// Rounds to the nearest frequency unit.
5621    ///
5622    /// Matches pandas `pd.Timedelta.round(freq)`. Uses banker's rounding
5623    /// (round half to even). NaT is preserved.
5624    #[must_use]
5625    pub fn round(nanos: i64, freq: &str) -> i64 {
5626        if nanos == Self::NAT {
5627            return Self::NAT;
5628        }
5629        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5630            return Self::NAT;
5631        };
5632        if unit_nanos == 0 {
5633            return Self::NAT;
5634        }
5635        let negative = nanos < 0;
5636        let abs_nanos = nanos.saturating_abs();
5637
5638        let quotient = abs_nanos / unit_nanos;
5639        let remainder = abs_nanos % unit_nanos;
5640        let half = unit_nanos / 2;
5641
5642        // Round-UP must be checked (br-frankenpandas-kyd16). `quotient *
5643        // unit_nanos` is always <= abs_nanos and cannot overflow, but
5644        // `(quotient + 1) * unit_nanos` can exceed i64::MAX — and this used
5645        // UNCHECKED arithmetic, so it panicked in debug and WRAPPED to a
5646        // large-negative duration in release. pandas raises
5647        // OutOfBoundsTimedelta ("Cannot round ... without overflow"); we
5648        // surface NaT, consistent with the rest of this block.
5649        let round_up = || {
5650            quotient
5651                .checked_add(1)
5652                .and_then(|q| q.checked_mul(unit_nanos))
5653        };
5654        let rounded = if remainder > half {
5655            round_up()
5656        } else if remainder < half {
5657            Some(quotient * unit_nanos)
5658        } else {
5659            // Exactly half: round to even
5660            if quotient % 2 == 0 {
5661                Some(quotient * unit_nanos)
5662            } else {
5663                round_up()
5664            }
5665        };
5666
5667        match rounded {
5668            // Negating is safe: `rounded` is non-negative and at most i64::MAX,
5669            // so `-rounded` is at worst i64::MIN + 1 — never the NaT sentinel.
5670            Some(rounded) => {
5671                if negative {
5672                    -rounded
5673                } else {
5674                    rounded
5675                }
5676            }
5677            None => Self::NAT,
5678        }
5679    }
5680}
5681
5682// ── Time zones ──────────────────────────────────────────────────────────
5683//
5684// A tz-aware value is a UTC instant plus a zone name; what the zone adds is
5685// the wall clock the instant shows there. These are the conversions every
5686// crate shares (Timestamp, DatetimeIndex, datetime columns).
5687
5688/// Why a time-zone conversion failed, as pandas (pytz) classifies it.
5689#[derive(Debug, Clone, PartialEq, Eq, Error)]
5690pub enum TimeZoneError {
5691    /// Neither 'UTC', a fixed offset ('+05:30') nor an IANA name - pandas'
5692    /// `UnknownTimeZoneError`, a `KeyError` whose message is the quoted name.
5693    #[error("'{0}'")]
5694    Unknown(String),
5695    /// A wall-clock time a DST change skips - pandas' `NonExistentTimeError`,
5696    /// whose message is the wall time.
5697    #[error("{0}")]
5698    NonExistent(String),
5699    /// A wall-clock time a DST change repeats - pandas' `AmbiguousTimeError`.
5700    #[error("Cannot infer dst time from {0}, try using the 'ambiguous' argument")]
5701    Ambiguous(String),
5702}
5703
5704/// A parsed zone: UTC or a fixed offset, or an IANA zone with DST rules.
5705enum Zone {
5706    Fixed(chrono::FixedOffset),
5707    Named(chrono_tz::Tz),
5708}
5709
5710impl Zone {
5711    /// pandas' zone spellings: 'UTC' / 'Z', a `+HH:MM` / `-HH:MM` offset (also
5712    /// as `UTC+HH:MM`, how a fixed-offset dtype names its zone), or an IANA
5713    /// name ('US/Eastern', 'Asia/Tokyo', 'Etc/GMT+5').
5714    fn parse(tz: &str) -> Result<Self, TimeZoneError> {
5715        use chrono::Offset;
5716        let name = tz.trim();
5717        if name == "UTC" || name == "Z" {
5718            return Ok(Self::Fixed(chrono::Utc.fix()));
5719        }
5720        let offset = name
5721            .strip_prefix("UTC")
5722            .filter(|rest| rest.starts_with(['+', '-']))
5723            .unwrap_or(name);
5724        let bytes = offset.as_bytes();
5725        if bytes.len() == 6
5726            && matches!(bytes[0], b'+' | b'-')
5727            && bytes[3] == b':'
5728            && [1, 2, 4, 5].iter().all(|&i| bytes[i].is_ascii_digit())
5729        {
5730            let hours: i32 = offset[1..3].parse().unwrap_or(24);
5731            let minutes: i32 = offset[4..6].parse().unwrap_or(60);
5732            let sign = if bytes[0] == b'-' { -1 } else { 1 };
5733            return (hours <= 23 && minutes <= 59)
5734                .then(|| chrono::FixedOffset::east_opt(sign * (hours * 3_600 + minutes * 60)))
5735                .flatten()
5736                .map(Self::Fixed)
5737                .ok_or_else(|| TimeZoneError::Unknown(name.to_owned()));
5738        }
5739        name.parse::<chrono_tz::Tz>()
5740            .map(Self::Named)
5741            .map_err(|_| TimeZoneError::Unknown(name.to_owned()))
5742    }
5743
5744    /// Seconds east of UTC this zone is at the UTC instant `utc_nanos`.
5745    fn offset_seconds(&self, utc_nanos: i64) -> i32 {
5746        use chrono::{Offset, TimeZone};
5747        match self {
5748            Self::Fixed(offset) => offset.local_minus_utc(),
5749            Self::Named(zone) => {
5750                let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5751                zone.offset_from_utc_datetime(&utc).fix().local_minus_utc()
5752            }
5753        }
5754    }
5755}
5756
5757/// Whether `tz` names a zone pandas accepts ('UTC', `+HH:MM`, an IANA name).
5758pub fn tz_validate(tz: &str) -> Result<(), TimeZoneError> {
5759    Zone::parse(tz).map(|_| ())
5760}
5761
5762/// The name pandas gives the zone `tz`: a fixed offset is `UTC+HH:MM`
5763/// ('+05:30' and 'UTC+05:30' alike; a zero offset or 'Z' is 'UTC'), an
5764/// IANA name stays as given.
5765pub fn tz_canonical_name(tz: &str) -> Result<String, TimeZoneError> {
5766    Ok(match Zone::parse(tz)? {
5767        Zone::Fixed(offset) if offset.local_minus_utc() == 0 => "UTC".to_owned(),
5768        Zone::Fixed(offset) => format!("UTC{offset}"),
5769        Zone::Named(_) => tz.trim().to_owned(),
5770    })
5771}
5772
5773/// The zone's name at the UTC instant `utc_nanos` as `strftime('%Z')` prints
5774/// it: an IANA zone's abbreviation then ('EST' / 'EDT'), a fixed offset's
5775/// `UTC+HH:MM` ('UTC' for zero).
5776pub fn tz_abbreviation(tz: &str, utc_nanos: i64) -> Result<String, TimeZoneError> {
5777    use chrono::TimeZone;
5778    match Zone::parse(tz)? {
5779        Zone::Named(zone) => {
5780            let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5781            let offset = zone.offset_from_utc_datetime(&utc);
5782            Ok(chrono_tz::OffsetName::abbreviation(&offset)
5783                .map_or_else(|| tz.trim().to_owned(), str::to_owned))
5784        }
5785        Zone::Fixed(_) => tz_canonical_name(tz),
5786    }
5787}
5788
5789/// The UTC offset, in seconds east of UTC, that `tz` has at the UTC instant
5790/// `utc_nanos` - what a tz-aware timestamp adds to its instant to show its
5791/// wall clock.
5792pub fn tz_offset_seconds(tz: &str, utc_nanos: i64) -> Result<i32, TimeZoneError> {
5793    Ok(Zone::parse(tz)?.offset_seconds(utc_nanos))
5794}
5795
5796/// The wall clock the UTC instant `utc_nanos` shows in `tz`, as naive
5797/// nanoseconds (NaT, `i64::MIN`, stays NaT).
5798pub fn tz_utc_to_wall_nanos(tz: &str, utc_nanos: i64) -> Result<i64, TimeZoneError> {
5799    if utc_nanos == i64::MIN {
5800        return Ok(utc_nanos);
5801    }
5802    let offset = Zone::parse(tz)?.offset_seconds(utc_nanos);
5803    Ok(utc_nanos.saturating_add(i64::from(offset) * 1_000_000_000))
5804}
5805
5806/// The UTC instant of the wall-clock time `wall_nanos` in `tz`, as pandas'
5807/// `tz_localize` with ambiguous / nonexistent = 'raise': a wall time a DST
5808/// change skips is [`TimeZoneError::NonExistent`], one it repeats
5809/// [`TimeZoneError::Ambiguous`]. NaT (`i64::MIN`) stays NaT.
5810pub fn tz_wall_to_utc_nanos(tz: &str, wall_nanos: i64) -> Result<i64, TimeZoneError> {
5811    tz_wall_to_utc_nanos_with(tz, wall_nanos, AmbiguousTime::Raise, NonexistentTime::Raise)
5812}
5813
5814/// What `tz_localize` does with a wall time a DST change repeats (pandas'
5815/// `ambiguous=`, for one value): refuse it, take its first occurrence (DST,
5816/// pandas' `True`) or its second (standard time, `False`), or make it NaT.
5817#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5818pub enum AmbiguousTime {
5819    Raise,
5820    Earliest,
5821    Latest,
5822    NaT,
5823}
5824
5825/// What `tz_localize` does with a wall time a DST change skips (pandas'
5826/// `nonexistent=`): refuse it, move it to the first instant after the gap
5827/// (`shift_forward`) or the last nanosecond before it (`shift_backward`),
5828/// make it NaT, or move the wall time by a duration (nanoseconds) and
5829/// localize that.
5830#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5831pub enum NonexistentTime {
5832    Raise,
5833    ShiftForward,
5834    ShiftBackward,
5835    NaT,
5836    Shift(i64),
5837}
5838
5839/// [`tz_wall_to_utc_nanos`] under pandas' `ambiguous` / `nonexistent`
5840/// policies; NaT (`i64::MIN`) where a policy says NaT.
5841pub fn tz_wall_to_utc_nanos_with(
5842    tz: &str,
5843    wall_nanos: i64,
5844    ambiguous: AmbiguousTime,
5845    nonexistent: NonexistentTime,
5846) -> Result<i64, TimeZoneError> {
5847    use chrono::{LocalResult, TimeZone};
5848    if wall_nanos == i64::MIN {
5849        return Ok(wall_nanos);
5850    }
5851    let zone = Zone::parse(tz)?;
5852    let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
5853    let local = match &zone {
5854        Zone::Fixed(offset) => offset
5855            .from_local_datetime(&naive)
5856            .map(|at| at.fixed_offset()),
5857        Zone::Named(zone) => zone.from_local_datetime(&naive).map(|at| at.fixed_offset()),
5858    };
5859    let nanos_of = |at: chrono::DateTime<chrono::FixedOffset>| {
5860        at.timestamp_nanos_opt()
5861            .ok_or_else(|| TimeZoneError::NonExistent(naive.to_string()))
5862    };
5863    match local {
5864        LocalResult::Single(at) => nanos_of(at),
5865        LocalResult::Ambiguous(earliest, latest) => match ambiguous {
5866            AmbiguousTime::Raise => Err(TimeZoneError::Ambiguous(naive.to_string())),
5867            AmbiguousTime::Earliest => nanos_of(earliest),
5868            AmbiguousTime::Latest => nanos_of(latest),
5869            AmbiguousTime::NaT => Ok(i64::MIN),
5870        },
5871        LocalResult::None => match nonexistent {
5872            NonexistentTime::Raise => Err(TimeZoneError::NonExistent(naive.to_string())),
5873            NonexistentTime::NaT => Ok(i64::MIN),
5874            NonexistentTime::Shift(delta) => {
5875                let shifted = wall_nanos
5876                    .checked_add(delta)
5877                    .ok_or_else(|| TimeZoneError::NonExistent(naive.to_string()))?;
5878                tz_wall_to_utc_nanos_with(tz, shifted, ambiguous, NonexistentTime::Raise)
5879            }
5880            NonexistentTime::ShiftForward | NonexistentTime::ShiftBackward => {
5881                // The gap's UTC transition: the wall time read with the
5882                // offset in force before the change lands after it, read
5883                // with the offset after the change lands before it; the
5884                // first instant between them carrying the later offset is
5885                // the transition (exact to the nanosecond - pandas'
5886                // shift_backward is one nanosecond before it).
5887                const DAY: i64 = 86_400_000_000_000;
5888                let offset_at = |utc: i64| i64::from(zone.offset_seconds(utc)) * 1_000_000_000;
5889                let before = wall_nanos.saturating_sub(offset_at(wall_nanos.saturating_sub(DAY)));
5890                let after = wall_nanos.saturating_sub(offset_at(wall_nanos.saturating_add(DAY)));
5891                let (mut low, mut high) = (before.min(after), before.max(after));
5892                let later = offset_at(high);
5893                while high - low > 1 {
5894                    let middle = low + (high - low) / 2;
5895                    if offset_at(middle) == later {
5896                        high = middle;
5897                    } else {
5898                        low = middle;
5899                    }
5900                }
5901                Ok(if nonexistent == NonexistentTime::ShiftForward {
5902                    high
5903                } else {
5904                    high - 1
5905                })
5906            }
5907        },
5908    }
5909}
5910
5911/// `wall_nanos` formatted as Python's (glibc's) `strftime` does - what
5912/// pandas' `Timestamp.strftime` / `Series.dt.strftime` / `to_csv(date_format=)`
5913/// run per value: the C-locale directives (`%a %A %b %B %c %d %e %f %H %I
5914/// %j %m %M %p %S %U %w %W %x %X %y %Y %z %Z %%`), glibc's (`%C %D %F %g %G
5915/// %h %k %l %n %P %r %R %t %T %u %V`) and its `-` (no padding), `_` (space
5916/// padding), `0` and `^` (upper case) flags. An unknown directive is echoed
5917/// as written, as glibc does. `zone` is a tz-aware value's UTC offset (in
5918/// seconds) and abbreviation at that instant, which `%z` / `%Z` print (empty
5919/// for a naive value).
5920#[must_use]
5921pub fn strftime_python(wall_nanos: i64, format: &str, zone: Option<(i32, &str)>) -> String {
5922    const DAYS: [&str; 7] = [
5923        "Sunday",
5924        "Monday",
5925        "Tuesday",
5926        "Wednesday",
5927        "Thursday",
5928        "Friday",
5929        "Saturday",
5930    ];
5931    const MONTHS: [&str; 12] = [
5932        "January",
5933        "February",
5934        "March",
5935        "April",
5936        "May",
5937        "June",
5938        "July",
5939        "August",
5940        "September",
5941        "October",
5942        "November",
5943        "December",
5944    ];
5945    // Floor both boundaries so a pre-epoch instant keeps a consistent date
5946    // and time (1969-12-31 23:59:59.999999 for -1 ns).
5947    let total_secs = wall_nanos.div_euclid(1_000_000_000);
5948    let sub_nanos = wall_nanos.rem_euclid(1_000_000_000);
5949    let days = total_secs.div_euclid(86_400);
5950    let secs_of_day = total_secs.rem_euclid(86_400);
5951    let (year, month, day) = civil_from_days(days);
5952    let (hour, minute, second) = (
5953        secs_of_day / 3_600,
5954        (secs_of_day % 3_600) / 60,
5955        secs_of_day % 60,
5956    );
5957    let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
5958    let weekday = (days + 4).rem_euclid(7); // 0 = Sunday
5959    let yday = days - days_from_civil(year, 1, 1); // 0-based
5960    let iso_weekday = if weekday == 0 { 7 } else { weekday };
5961    let (iso_year, iso_week) = {
5962        let week = (yday + 1 - iso_weekday + 10).div_euclid(7);
5963        if week < 1 {
5964            (year - 1, iso_weeks_in_year(year - 1))
5965        } else if week > iso_weeks_in_year(year) {
5966            (year + 1, 1)
5967        } else {
5968            (year, week)
5969        }
5970    };
5971    let month_name = MONTHS[(month as usize).saturating_sub(1) % 12];
5972    let day_name = DAYS[weekday as usize];
5973
5974    let mut out = String::with_capacity(format.len().saturating_add(16));
5975    let mut chars = format.chars().peekable();
5976    while let Some(ch) = chars.next() {
5977        if ch != '%' {
5978            out.push(ch);
5979            continue;
5980        }
5981        let flag = chars.next_if(|c| matches!(c, '-' | '_' | '0' | '^'));
5982        let Some(conversion) = chars.next() else {
5983            out.push('%');
5984            if let Some(flag) = flag {
5985                out.push(flag);
5986            }
5987            break;
5988        };
5989        // A number `width` wide, padded with `pad` unless a flag says
5990        // otherwise.
5991        let number = |value: i64, width: usize, pad: char| -> String {
5992            match flag.unwrap_or(pad) {
5993                '-' => value.to_string(),
5994                '_' | ' ' => format!("{value:>width$}"),
5995                _ => format!("{value:0width$}"),
5996            }
5997        };
5998        let text = |value: &str| -> String {
5999            if flag == Some('^') {
6000                value.to_uppercase()
6001            } else {
6002                value.to_owned()
6003            }
6004        };
6005        let piece = match conversion {
6006            'a' => text(&day_name[..3]),
6007            'A' => text(day_name),
6008            'b' | 'h' => text(&month_name[..3]),
6009            'B' => text(month_name),
6010            'c' => text(&strftime_python(wall_nanos, "%a %b %e %H:%M:%S %Y", zone)),
6011            'C' => number(year.div_euclid(100), 2, '0'),
6012            'd' => number(i64::from(day), 2, '0'),
6013            'D' | 'x' => strftime_python(wall_nanos, "%m/%d/%y", zone),
6014            'e' => number(i64::from(day), 2, ' '),
6015            'f' => number(sub_nanos / 1_000, 6, '0'),
6016            'F' => strftime_python(wall_nanos, "%Y-%m-%d", zone),
6017            'g' => number(iso_year.rem_euclid(100), 2, '0'),
6018            'G' => number(iso_year, 1, '0'),
6019            'H' => number(hour, 2, '0'),
6020            'I' => number(hour12, 2, '0'),
6021            'j' => number(yday + 1, 3, '0'),
6022            'k' => number(hour, 2, ' '),
6023            'l' => number(hour12, 2, ' '),
6024            'm' => number(i64::from(month), 2, '0'),
6025            'M' => number(minute, 2, '0'),
6026            'n' => "\n".to_owned(),
6027            'p' => text(if hour < 12 { "AM" } else { "PM" }),
6028            'P' => (if hour < 12 { "am" } else { "pm" }).to_owned(),
6029            'r' => strftime_python(wall_nanos, "%I:%M:%S %p", zone),
6030            'R' => strftime_python(wall_nanos, "%H:%M", zone),
6031            'S' => number(second, 2, '0'),
6032            't' => "\t".to_owned(),
6033            'T' | 'X' => strftime_python(wall_nanos, "%H:%M:%S", zone),
6034            'u' => number(iso_weekday, 1, '0'),
6035            'U' => number((yday + 7 - weekday).div_euclid(7), 2, '0'),
6036            'V' => number(iso_week, 2, '0'),
6037            'w' => number(weekday, 1, '0'),
6038            'W' => number(
6039                (yday + 7 - (weekday + 6).rem_euclid(7)).div_euclid(7),
6040                2,
6041                '0',
6042            ),
6043            'y' => number(year.rem_euclid(100), 2, '0'),
6044            'Y' => number(year, 1, '0'),
6045            'z' => zone.map_or_else(String::new, |(offset, _)| {
6046                let sign = if offset < 0 { '-' } else { '+' };
6047                let offset = offset.unsigned_abs();
6048                let (h, m, s) = (offset / 3_600, (offset % 3_600) / 60, offset % 60);
6049                if s == 0 {
6050                    format!("{sign}{h:02}{m:02}")
6051                } else {
6052                    format!("{sign}{h:02}{m:02}{s:02}")
6053                }
6054            }),
6055            'Z' => zone.map_or_else(String::new, |(_, name)| text(name)),
6056            '%' => "%".to_owned(),
6057            other => {
6058                // glibc echoes a conversion it does not know.
6059                out.push('%');
6060                if let Some(flag) = flag {
6061                    out.push(flag);
6062                }
6063                out.push(other);
6064                continue;
6065            }
6066        };
6067        out.push_str(&piece);
6068    }
6069    out
6070}
6071
6072/// The instant `nanos` formatted by [`strftime_python`]: a naive value as
6073/// it is; in `tz` (a tz-aware value, `nanos` its UTC instant) on the zone's
6074/// wall clock with the offset and abbreviation of that instant.
6075#[must_use]
6076pub fn strftime_in_zone(nanos: i64, format: &str, tz: Option<&str>) -> String {
6077    let aware = tz.and_then(|zone| {
6078        let offset = tz_offset_seconds(zone, nanos).ok()?;
6079        let name = tz_abbreviation(zone, nanos).ok()?;
6080        Some((offset, name))
6081    });
6082    match aware {
6083        Some((offset, name)) => strftime_python(
6084            nanos.saturating_add(i64::from(offset) * 1_000_000_000),
6085            format,
6086            Some((offset, &name)),
6087        ),
6088        None => strftime_python(nanos, format, None),
6089    }
6090}
6091
6092/// `str(Timestamp)` of the instant `nanos` in `tz`, as pandas prints a
6093/// tz-aware value (repr cells, `astype(str)`): its wall clock
6094/// 'YYYY-MM-DD HH:MM:SS', its own fraction when it has one (six digits, nine
6095/// for nanoseconds), and the zone's `+HH:MM` offset then.
6096#[must_use]
6097pub fn timestamp_text_in_zone(nanos: i64, tz: &str) -> String {
6098    let offset = tz_offset_seconds(tz, nanos).unwrap_or(0);
6099    let wall = nanos.saturating_add(i64::from(offset) * 1_000_000_000);
6100    let mut text = strftime_python(wall, "%Y-%m-%d %H:%M:%S", None);
6101    let fraction = wall.rem_euclid(1_000_000_000);
6102    if fraction % 1_000 != 0 {
6103        text.push_str(&format!(".{fraction:09}"));
6104    } else if fraction != 0 {
6105        text.push_str(&format!(".{:06}", fraction / 1_000));
6106    }
6107    let sign = if offset < 0 { '-' } else { '+' };
6108    let minutes = offset.unsigned_abs() / 60;
6109    text.push_str(&format!("{sign}{:02}:{:02}", minutes / 60, minutes % 60));
6110    text
6111}
6112
6113/// Days since 1970-01-01 of the proleptic-Gregorian date `(year, month,
6114/// day)` (Howard Hinnant's days-from-civil; the inverse of
6115/// `civil_from_days`).
6116fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
6117    let (month, day) = (i64::from(month), i64::from(day));
6118    let year = if month <= 2 { year - 1 } else { year };
6119    let era = if year >= 0 { year } else { year - 399 } / 400;
6120    let yoe = year - era * 400;
6121    let doy = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
6122    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
6123    era * 146_097 + doe - 719_468
6124}
6125
6126// ── Timestamp types (br-frankenpandas-9p0u — 4r56 Phase 2) ─────────────
6127//
6128// Nanosecond-precision i64 since Unix epoch + optional IANA tz name. The
6129// zone's DST-aware conversions are the time-zone functions above
6130// (`tz_offset_seconds`, `tz_wall_to_utc_nanos`); arithmetic here stays on
6131// the absolute nanos axis.
6132
6133/// Number of days in a given month (1-12) of a given year.
6134fn days_in_month(year: i64, month: u32) -> Option<u32> {
6135    if !(1..=12).contains(&month) {
6136        return None;
6137    }
6138    let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
6139    let days: [u32; 12] = [
6140        31,
6141        if is_leap { 29 } else { 28 },
6142        31,
6143        30,
6144        31,
6145        30,
6146        31,
6147        31,
6148        30,
6149        31,
6150        30,
6151        31,
6152    ];
6153    Some(days[(month - 1) as usize])
6154}
6155
6156/// Number of ISO-8601 weeks in a year (52 or 53).
6157///
6158/// A year has 53 ISO weeks iff its first day falls on a Thursday, or it is a
6159/// leap year whose first day is a Wednesday — captured by the dominical
6160/// closed form `p(year) == 4 || p(year - 1) == 3`, where
6161/// `p(y) = (y + ⌊y/4⌋ − ⌊y/100⌋ + ⌊y/400⌋) mod 7` is the weekday of Dec 31.
6162fn iso_weeks_in_year(year: i64) -> i64 {
6163    fn p(y: i64) -> i64 {
6164        (y + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400)).rem_euclid(7)
6165    }
6166    if p(year) == 4 || p(year - 1) == 3 {
6167        53
6168    } else {
6169        52
6170    }
6171}
6172
6173/// A nanosecond-precision point in time, Unix-epoch anchored.
6174///
6175/// Phase 2 scope: construction, arithmetic, equality, ordering, serde.
6176/// TZ semantics (IANA tz lookup, DST-aware shift) are deferred to Phase
6177/// 3 — see br-frankenpandas-4r56.
6178#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
6179pub struct Timestamp {
6180    /// Nanoseconds since Unix epoch. `i64::MIN` is NaT.
6181    pub nanos: i64,
6182    /// Optional IANA time-zone name (e.g. `"US/Eastern"`). `None` means
6183    /// naive / UTC-anchored. Phase 2 treats this as opaque metadata;
6184    /// Phase 3 wires chrono_tz interpretation.
6185    #[serde(default, skip_serializing_if = "Option::is_none")]
6186    pub tz: Option<String>,
6187}
6188
6189/// How `astype(str)` renders a `timedelta64[ns]` COLUMN.
6190///
6191/// ⚠️ THE TIMEDELTA LADDER IS NOT THE DATETIME ONE, and copying the sibling
6192/// across is the mistake this type exists to prevent. It has exactly TWO rungs,
6193/// and — unlike [`DatetimeStringResolution`] — THE SUB-SECOND WIDTH IS PER
6194/// VALUE, not per column. MEASURED, live pandas 2.2.3:
6195///
6196/// ```text
6197/// [1 days, 2 days]              -> ['1 days', '2 days']
6198/// [1 days, 5 ms]                -> ['1 days 00:00:00', '0 days 00:00:00.005000']
6199/// [1 days 02:03:04.005, 1 ns]   -> ['1 days 02:03:04.005000',
6200///                                   '0 days 00:00:00.000000001']
6201/// ```
6202///
6203/// That last row is the whole distinction: a millisecond value keeps its SIX
6204/// digits while its neighbour prints NINE. On the datetime side the same pair
6205/// would have been widened to a common nine. So the only column-wide question
6206/// here is whether the time-of-day part can be dropped entirely, which is what
6207/// [`Timedelta::string_resolution`] answers; [`Timedelta::format`] already gets
6208/// the per-value part right and is reused unchanged.
6209#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6210pub enum TimedeltaStringResolution {
6211    /// `1 days` / `-2 days` / `0 days` — every value is a whole day.
6212    Days,
6213    /// `1 days 02:03:04.005000` — the full rendering, sub-second width per value.
6214    Full,
6215}
6216
6217/// How wide `astype(str)` renders a `datetime64[ns]` value.
6218///
6219/// ⚠️ THIS IS A PROPERTY OF THE COLUMN, NOT OF THE VALUE, which is the whole
6220/// reason it is a separate type rather than a branch inside a per-scalar
6221/// formatter. MEASURED, live pandas 2.2.3 — the SAME midnight timestamp renders
6222/// three different ways depending only on what it shares a column with:
6223///
6224/// ```text
6225/// Series([midnight, midnight]).astype(str)   -> '2024-03-15'
6226/// Series([midnight, one_nanosecond]).astype(str)
6227///                                            -> '2024-03-15 00:00:00.000000000'
6228/// str(Timestamp(midnight))                   -> '2024-03-15 00:00:00'
6229/// ```
6230///
6231/// pandas picks the coarsest rung that is lossless for EVERY element and
6232/// imposes it on all of them. The `Ord` derive is the fold: scan the column
6233/// with `max` over [`Timestamp::string_resolution`], then format every value at
6234/// the winner. Variants are declared coarsest-first so that `max` means
6235/// "finest needed".
6236#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6237pub enum DatetimeStringResolution {
6238    /// `2024-03-15` — every value in the column is midnight.
6239    Date,
6240    /// `2024-03-15 10:30:45` — every value is a whole second.
6241    Second,
6242    /// `2024-03-15 10:30:45.123`
6243    Milli,
6244    /// `2024-03-15 10:30:45.123456`
6245    Micro,
6246    /// `2024-03-15 10:30:45.123456789`
6247    Nano,
6248}
6249
6250impl Timestamp {
6251    /// NaT sentinel, parallel to `Timedelta::NAT`.
6252    pub const NAT: i64 = i64::MIN;
6253
6254    /// Construct a UTC-anchored (tz=None) Timestamp from nanoseconds
6255    /// since Unix epoch.
6256    #[must_use]
6257    pub const fn from_nanos(nanos: i64) -> Self {
6258        Self { nanos, tz: None }
6259    }
6260
6261    /// Construct a Timestamp tagged with an IANA tz name.
6262    ///
6263    /// Phase 2 doesn't interpret the tz — it only carries the name
6264    /// through arithmetic + serde. Phase 3 wires chrono_tz conversion.
6265    #[must_use]
6266    pub fn from_nanos_tz(nanos: i64, tz_name: impl Into<String>) -> Self {
6267        Self {
6268            nanos,
6269            tz: Some(tz_name.into()),
6270        }
6271    }
6272
6273    /// Returns the current UTC timestamp.
6274    ///
6275    /// ⚠️ THIS MATCHES `pd.Timestamp.utcnow()`, NOT `pd.Timestamp.now()`, and the
6276    /// old doc claimed both. They are different functions: pandas' `now()` returns
6277    /// LOCAL time with no timezone attached, while `utcnow()` returns UTC.
6278    /// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-19) on a UTC-4 host:
6279    /// ```text
6280    ///   pd.Timestamp.now()    2026-08-19 07:17:07.266940        tz None
6281    ///   pd.Timestamp.utcnow() 2026-08-19 11:17:07.267100+00:00  tz UTC
6282    ///   difference: 14400 s
6283    /// ```
6284    /// A caller who trusted the old claim and ran on a non-UTC host would be off by
6285    /// their whole UTC offset — four hours here — with no error and no NaT to notice.
6286    /// This crate has no local-timezone concept, so the UTC answer is the only one it
6287    /// can give; only the false half of the claim is removed.
6288    #[must_use]
6289    pub fn now() -> Self {
6290        use std::time::{SystemTime, UNIX_EPOCH};
6291        let duration = SystemTime::now()
6292            .duration_since(UNIX_EPOCH)
6293            .unwrap_or_default();
6294        let nanos = duration.as_nanos() as i64;
6295        Self { nanos, tz: None }
6296    }
6297
6298    /// Alias for `now()`. Matches `pd.Timestamp.utcnow()`.
6299    #[must_use]
6300    pub fn utcnow() -> Self {
6301        Self::now()
6302    }
6303
6304    /// Returns today's date at midnight UTC.
6305    ///
6306    /// Matches `pd.Timestamp.today()`.
6307    #[must_use]
6308    pub fn today() -> Self {
6309        let now = Self::now();
6310        now.normalize()
6311    }
6312
6313    /// The NaT sentinel value for a Timestamp.
6314    #[must_use]
6315    pub const fn nat() -> Self {
6316        Self {
6317            nanos: Self::NAT,
6318            tz: None,
6319        }
6320    }
6321
6322    /// True iff this Timestamp is NaT.
6323    #[must_use]
6324    pub const fn is_nat(&self) -> bool {
6325        self.nanos == Self::NAT
6326    }
6327
6328    /// Nanoseconds since Unix epoch, matching `pd.Timestamp.value`.
6329    #[must_use]
6330    pub const fn value(&self) -> i64 {
6331        self.nanos
6332    }
6333
6334    /// Stored resolution unit, matching `pd.Timestamp.unit`.
6335    ///
6336    /// FrankenPandas `Timestamp` stores nanoseconds internally, so non-NaT
6337    /// values report `ns`. `NaT` has no unit.
6338    #[must_use]
6339    pub const fn unit(&self) -> Option<&'static str> {
6340        if self.is_nat() { None } else { Some("ns") }
6341    }
6342
6343    /// Return the resolution of the timestamp (always "ns" for nanoseconds).
6344    ///
6345    /// Matches `pd.Timestamp.resolution`. Returns None for NaT.
6346    #[must_use]
6347    pub const fn resolution(&self) -> Option<&'static str> {
6348        if self.is_nat() { None } else { Some("ns") }
6349    }
6350
6351    /// Numpy datetime64 scalar payload, matching `pd.Timestamp.asm8`.
6352    #[must_use]
6353    pub const fn asm8(&self) -> i64 {
6354        self.value()
6355    }
6356
6357    /// Convert to a datetime64 payload, matching `pd.Timestamp.to_datetime64()`.
6358    #[must_use]
6359    pub const fn to_datetime64(&self) -> i64 {
6360        self.value()
6361    }
6362
6363    /// Convert to a numpy scalar payload, matching `pd.Timestamp.to_numpy()`.
6364    #[must_use]
6365    pub const fn to_numpy(&self) -> i64 {
6366        self.value()
6367    }
6368
6369    /// POSIX timestamp in seconds, matching `pd.Timestamp.timestamp()`.
6370    ///
6371    /// Pandas exposes this through Python's datetime surface, so sub-microsecond
6372    /// nanoseconds are rounded to six decimal places. `NaT` raises in pandas;
6373    /// fp-types surfaces the same condition as a missing-value error.
6374    pub fn timestamp(&self) -> Result<f64, TypeError> {
6375        if self.is_nat() {
6376            return Err(TypeError::ValueIsMissing {
6377                kind: NullKind::NaT,
6378            });
6379        }
6380        let seconds = self.nanos as f64 / 1_000_000_000.0;
6381        let rounded = format!("{seconds:.6}").parse().unwrap_or(seconds);
6382        Ok(rounded)
6383    }
6384
6385    /// Add a Timedelta. NaT in either operand → NaT; overflow → NaT.
6386    /// TZ is preserved from `self`.
6387    ///
6388    /// Overflow is NaT in both directions (br-frankenpandas-lgyy8) — see the
6389    /// overflow note on [`Timedelta::add`]. A saturated `i64::MAX` would be a
6390    /// finite, plausible ~year-2262 instant returned as if it were real data;
6391    /// `pd.Timestamp.max + pd.Timedelta('1ns')` raises `OutOfBoundsDatetime`.
6392    #[must_use]
6393    pub fn add_timedelta(&self, td_nanos: i64) -> Self {
6394        self.try_add_timedelta(td_nanos)
6395            .unwrap_or_else(|_| Self::nat())
6396    }
6397
6398    /// Shift by a Timedelta, reporting overflow.
6399    ///
6400    /// br-frankenpandas-fyr1z-policy-carrier-f29nz. A NaT operand is
6401    /// propagation, not overflow, so it yields `Ok(nat())`. On overflow the
6402    /// caller gets the error INSTEAD of the tz-dropped NaT; the infallible
6403    /// `add_timedelta` above still produces that NaT, unchanged.
6404    ///
6405    /// # Errors
6406    /// [`PandasTemporalError::OutOfBoundsDatetime`], matching
6407    /// `pd.Timestamp.max + pd.Timedelta('1ns')`.
6408    pub fn try_add_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6409        if self.is_nat() || td_nanos == Timedelta::NAT {
6410            return Ok(Self::nat());
6411        }
6412        match self.nanos.checked_add(td_nanos) {
6413            Some(nanos) => Ok(Self {
6414                nanos,
6415                tz: self.tz.clone(),
6416            }),
6417            // Overflow drops the tz with the value: an out-of-range instant has
6418            // no zone, and `Self::nat()` is the one canonical NaT (matching the
6419            // NaT-operand arms above, which also return an untagged NaT).
6420            None => Err(TemporalFailure::new(
6421                "Timestamp::add_timedelta",
6422                PandasTemporalError::OutOfBoundsDatetime,
6423            )
6424            .with_operands(self.nanos, td_nanos)),
6425        }
6426    }
6427
6428    /// Subtract a Timedelta. NaT propagation; overflow → NaT. TZ preserved.
6429    #[must_use]
6430    pub fn sub_timedelta(&self, td_nanos: i64) -> Self {
6431        self.try_sub_timedelta(td_nanos)
6432            .unwrap_or_else(|_| Self::nat())
6433    }
6434
6435    /// Shift back by a Timedelta, reporting overflow. See
6436    /// [`Self::try_add_timedelta`].
6437    ///
6438    /// # Errors
6439    /// [`PandasTemporalError::OutOfBoundsDatetime`].
6440    pub fn try_sub_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6441        if self.is_nat() || td_nanos == Timedelta::NAT {
6442            return Ok(Self::nat());
6443        }
6444        match self.nanos.checked_sub(td_nanos) {
6445            Some(nanos) => Ok(Self {
6446                nanos,
6447                tz: self.tz.clone(),
6448            }),
6449            None => Err(TemporalFailure::new(
6450                "Timestamp::sub_timedelta",
6451                PandasTemporalError::OutOfBoundsDatetime,
6452            )
6453            .with_operands(self.nanos, td_nanos)),
6454        }
6455    }
6456
6457    /// Subtract another Timestamp. Returns a Timedelta (i64 nanos).
6458    /// NaT in either → `Timedelta::NAT`; overflow → `Timedelta::NAT`
6459    /// (`pd.Timestamp.min - pd.Timestamp.max` raises `OutOfBoundsDatetime`).
6460    #[must_use]
6461    pub fn sub_timestamp(&self, other: &Self) -> i64 {
6462        self.try_sub_timestamp(other).unwrap_or(Timedelta::NAT)
6463    }
6464
6465    /// Elapsed nanoseconds between two Timestamps, reporting overflow.
6466    ///
6467    /// # Errors
6468    /// [`PandasTemporalError::OutOfBoundsDatetime`], matching
6469    /// `pd.Timestamp.min - pd.Timestamp.max`.
6470    pub fn try_sub_timestamp(&self, other: &Self) -> Result<i64, TemporalFailure> {
6471        if self.is_nat() || other.is_nat() {
6472            return Ok(Timedelta::NAT);
6473        }
6474        self.nanos.checked_sub(other.nanos).ok_or(
6475            TemporalFailure::new(
6476                "Timestamp::sub_timestamp",
6477                PandasTemporalError::OutOfBoundsDatetime,
6478            )
6479            .with_operands(self.nanos, other.nanos),
6480        )
6481    }
6482
6483    /// NaT-aware semantic equality: two NaT Timestamps are equal to each
6484    /// other (matches pandas `pd.NaT == pd.NaT` under `equals()`, though
6485    /// pandas's `==` operator returns False for NaT==NaT — we follow the
6486    /// `semantic_eq` convention used elsewhere in fp-types).
6487    #[must_use]
6488    pub fn semantic_eq(&self, other: &Self) -> bool {
6489        if self.is_nat() && other.is_nat() {
6490            return true;
6491        }
6492        if self.is_nat() || other.is_nat() {
6493            return false;
6494        }
6495        self.nanos == other.nanos && self.tz == other.tz
6496    }
6497
6498    // ── Rounding to a Timedelta unit (br-frankenpandas-5h6n) ────────────
6499    //
6500    // Pure i64 arithmetic on the nanos axis. tz is preserved. Phase 3
6501    // chrono_tz integration will add a tz-aware variant that handles DST
6502    // boundaries correctly; these methods operate on the absolute time
6503    // axis, matching pandas's tz-naive `.floor` / `.ceil` / `.round`
6504    // semantics for unit values smaller than a day.
6505
6506    /// Round down to the nearest multiple of `unit_nanos`.
6507    ///
6508    /// Matches `pd.Timestamp(...).floor(unit)`. NaT in `self` or a
6509    /// non-positive `unit_nanos` returns NaT.
6510    #[must_use]
6511    pub fn floor_to(&self, unit_nanos: i64) -> Self {
6512        if self.is_nat() || unit_nanos <= 0 {
6513            return Self::nat();
6514        }
6515        let Some(nanos) = self.nanos.div_euclid(unit_nanos).checked_mul(unit_nanos) else {
6516            return Self::nat();
6517        };
6518        Self {
6519            nanos,
6520            tz: self.tz.clone(),
6521        }
6522    }
6523
6524    /// Round up to the nearest multiple of `unit_nanos`.
6525    ///
6526    /// Matches `pd.Timestamp(...).ceil(unit)`. NaT or non-positive
6527    /// `unit_nanos` returns NaT. Already-multiple inputs return self.
6528    #[must_use]
6529    pub fn ceil_to(&self, unit_nanos: i64) -> Self {
6530        if self.is_nat() || unit_nanos <= 0 {
6531            return Self::nat();
6532        }
6533        let rem = self.nanos.rem_euclid(unit_nanos);
6534        let nanos = if rem == 0 {
6535            self.nanos
6536        } else {
6537            // Checked, matching the sibling `floor_to` directly above
6538            // (br-frankenpandas-kyd16). A clamped i64::MAX would be a finite,
6539            // plausible ~year-2262 instant; `pd.Timestamp.max.ceil('D')`
6540            // raises OutOfBoundsDatetime "Cannot round ... without overflow".
6541            let Some(nanos) = self.nanos.checked_add(unit_nanos - rem) else {
6542                return Self::nat();
6543            };
6544            nanos
6545        };
6546        Self {
6547            nanos,
6548            tz: self.tz.clone(),
6549        }
6550    }
6551
6552    /// Round to the nearest multiple of `unit_nanos`, banker's rounding
6553    /// (half-to-even) on ties.
6554    ///
6555    /// Matches `pd.Timestamp(...).round(unit)`. NaT or non-positive
6556    /// `unit_nanos` returns NaT.
6557    #[must_use]
6558    pub fn round_to(&self, unit_nanos: i64) -> Self {
6559        if self.is_nat() || unit_nanos <= 0 {
6560            return Self::nat();
6561        }
6562        let floor = self.nanos.div_euclid(unit_nanos);
6563        let rem = self.nanos.rem_euclid(unit_nanos);
6564        let half = unit_nanos / 2;
6565        let chosen_floor = if rem < half {
6566            floor
6567        } else if rem > half {
6568            floor + 1
6569        } else if unit_nanos % 2 != 0 {
6570            // Odd unit can't have a true half; treat as round-up.
6571            floor + 1
6572        } else {
6573            // Tie: pick the even multiple.
6574            if floor % 2 == 0 { floor } else { floor + 1 }
6575        };
6576        // Checked, matching the sibling `floor_to` (br-frankenpandas-kyd16):
6577        // `pd.Timestamp.max.round('D')` raises OutOfBoundsDatetime rather than
6578        // returning the clamped i64::MAX instant.
6579        let Some(nanos) = chosen_floor.checked_mul(unit_nanos) else {
6580            return Self::nat();
6581        };
6582        Self {
6583            nanos,
6584            tz: self.tz.clone(),
6585        }
6586    }
6587
6588    // ── String-unit rounding (br-frankenpandas-lbsx) ────────────────────
6589    //
6590    // Pandas convenience: `.floor('H')` / `.ceil('1D')` / `.round('15min')`.
6591    // These read the frequency with `fixed_freq_nanos`, then delegate to
6592    // the nanos-based `floor_to`/`ceil_to`/`round_to`. Unknown unit strings
6593    // return NaT, matching the rest of fp-types' "missing-input → missing-
6594    // output" convention.
6595
6596    /// A fixed frequency's length: a bare unit (`Timedelta::unit_to_nanos`)
6597    /// or a multiple of one ('15min', '1D', '30s' - they were unknown, so
6598    /// `round('15min')` was NaT); None for anything else.
6599    fn fixed_freq_nanos(freq: &str) -> Option<i64> {
6600        Timedelta::unit_to_nanos(freq).or_else(|| Timedelta::parse(freq).ok())
6601    }
6602
6603    /// Round down to the nearest multiple of the named unit.
6604    ///
6605    /// Matches `pd.Timestamp(...).floor(unit)`. Unknown unit → NaT.
6606    #[must_use]
6607    pub fn floor_to_unit(&self, unit: &str) -> Self {
6608        match Self::fixed_freq_nanos(unit) {
6609            Some(unit_nanos) => self.floor_to(unit_nanos),
6610            None => Self::nat(),
6611        }
6612    }
6613
6614    /// Round up to the nearest multiple of the named unit.
6615    ///
6616    /// Matches `pd.Timestamp(...).ceil(unit)`. Unknown unit → NaT.
6617    #[must_use]
6618    pub fn ceil_to_unit(&self, unit: &str) -> Self {
6619        match Self::fixed_freq_nanos(unit) {
6620            Some(unit_nanos) => self.ceil_to(unit_nanos),
6621            None => Self::nat(),
6622        }
6623    }
6624
6625    /// Round to the nearest multiple of the named unit, banker's rounding.
6626    ///
6627    /// Matches `pd.Timestamp(...).round(unit)`. Unknown unit → NaT.
6628    #[must_use]
6629    pub fn round_to_unit(&self, unit: &str) -> Self {
6630        match Self::fixed_freq_nanos(unit) {
6631            Some(unit_nanos) => self.round_to(unit_nanos),
6632            None => Self::nat(),
6633        }
6634    }
6635
6636    /// Pandas-named alias for [`floor_to_unit`](Self::floor_to_unit).
6637    #[must_use]
6638    pub fn floor(&self, freq: &str) -> Self {
6639        self.floor_to_unit(freq)
6640    }
6641
6642    /// Pandas-named alias for [`ceil_to_unit`](Self::ceil_to_unit).
6643    #[must_use]
6644    pub fn ceil(&self, freq: &str) -> Self {
6645        self.ceil_to_unit(freq)
6646    }
6647
6648    /// Pandas-named alias for [`round_to_unit`](Self::round_to_unit).
6649    #[must_use]
6650    pub fn round(&self, freq: &str) -> Self {
6651        self.round_to_unit(freq)
6652    }
6653
6654    /// Extract the year component from the timestamp.
6655    ///
6656    /// Matches `pd.Timestamp.year`. Returns None for NaT.
6657    #[must_use]
6658    pub fn year(&self) -> Option<i64> {
6659        if self.is_nat() {
6660            return None;
6661        }
6662        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
6663        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
6664        // for the post-1970 positive case.
6665        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6666        let days = days_since_epoch + 719_468;
6667        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6668        let doe = days - era * 146_097;
6669        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6670        let y = yoe + era * 400;
6671        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6672        let mp = (5 * doy + 2) / 153;
6673        let m = if mp < 10 { mp + 3 } else { mp - 9 };
6674        Some(if m <= 2 { y + 1 } else { y })
6675    }
6676
6677    /// Extract the month component (1-12) from the timestamp.
6678    ///
6679    /// Matches `pd.Timestamp.month`. Returns None for NaT.
6680    #[must_use]
6681    pub fn month(&self) -> Option<i64> {
6682        if self.is_nat() {
6683            return None;
6684        }
6685        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
6686        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
6687        // for the post-1970 positive case.
6688        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6689        let days = days_since_epoch + 719_468;
6690        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6691        let doe = days - era * 146_097;
6692        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6693        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6694        let mp = (5 * doy + 2) / 153;
6695        Some(if mp < 10 { mp + 3 } else { mp - 9 })
6696    }
6697
6698    /// Extract the day component (1-31) from the timestamp.
6699    ///
6700    /// Matches `pd.Timestamp.day`. Returns None for NaT.
6701    #[must_use]
6702    pub fn day(&self) -> Option<i64> {
6703        if self.is_nat() {
6704            return None;
6705        }
6706        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
6707        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
6708        // for the post-1970 positive case.
6709        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6710        let days = days_since_epoch + 719_468;
6711        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6712        let doe = days - era * 146_097;
6713        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6714        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6715        let mp = (5 * doy + 2) / 153;
6716        Some(doy - (153 * mp + 2) / 5 + 1)
6717    }
6718
6719    /// Extract the hour component (0-23) from the timestamp.
6720    ///
6721    /// Matches `pd.Timestamp.hour`. Returns None for NaT.
6722    #[must_use]
6723    pub fn hour(&self) -> Option<i64> {
6724        if self.is_nat() {
6725            return None;
6726        }
6727        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
6728        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
6729        // rem_euclid == `%` for the post-1970 positive case.
6730        let secs_of_day =
6731            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6732        Some(secs_of_day / 3600)
6733    }
6734
6735    /// Extract the minute component (0-59) from the timestamp.
6736    ///
6737    /// Matches `pd.Timestamp.minute`. Returns None for NaT.
6738    #[must_use]
6739    pub fn minute(&self) -> Option<i64> {
6740        if self.is_nat() {
6741            return None;
6742        }
6743        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
6744        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
6745        // rem_euclid == `%` for the post-1970 positive case.
6746        let secs_of_day =
6747            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6748        Some((secs_of_day % 3600) / 60)
6749    }
6750
6751    /// Extract the second component (0-59) from the timestamp.
6752    ///
6753    /// Matches `pd.Timestamp.second`. Returns None for NaT.
6754    #[must_use]
6755    pub fn second(&self) -> Option<i64> {
6756        if self.is_nat() {
6757            return None;
6758        }
6759        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
6760        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
6761        // rem_euclid == `%` for the post-1970 positive case.
6762        let secs_of_day =
6763            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6764        Some(secs_of_day % 60)
6765    }
6766
6767    /// Extract the microsecond component (0-999999) from the timestamp.
6768    ///
6769    /// Matches `pd.Timestamp.microsecond`. Returns None for NaT.
6770    #[must_use]
6771    pub fn microsecond(&self) -> Option<i64> {
6772        if self.is_nat() {
6773            return None;
6774        }
6775        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
6776        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
6777        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
6778        Some((sub_nanos / 1000) as i64)
6779    }
6780
6781    /// Extract the nanosecond component (0-999) from the timestamp.
6782    ///
6783    /// Matches `pd.Timestamp.nanosecond`. Returns None for NaT.
6784    #[must_use]
6785    pub fn nanosecond(&self) -> Option<i64> {
6786        if self.is_nat() {
6787            return None;
6788        }
6789        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
6790        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
6791        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
6792        Some((sub_nanos % 1000) as i64)
6793    }
6794
6795    /// Return the day of the week (Monday=0, Sunday=6).
6796    ///
6797    /// Matches `pd.Timestamp.dayofweek`. Returns None for NaT.
6798    #[must_use]
6799    pub fn dayofweek(&self) -> Option<i64> {
6800        if self.is_nat() {
6801            return None;
6802        }
6803        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
6804        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6805        let dow = ((days_since_epoch + 3) % 7 + 7) % 7;
6806        Some(dow)
6807    }
6808
6809    /// Alias for dayofweek(). Matches `pd.Timestamp.weekday`.
6810    #[must_use]
6811    pub fn weekday(&self) -> Option<i64> {
6812        self.dayofweek()
6813    }
6814
6815    /// Alias for dayofweek(). Matches `pd.Timestamp.day_of_week`.
6816    #[must_use]
6817    pub fn day_of_week(&self) -> Option<i64> {
6818        self.dayofweek()
6819    }
6820
6821    /// Return the day of the year (1-366).
6822    ///
6823    /// Matches `pd.Timestamp.dayofyear`. Returns None for NaT.
6824    #[must_use]
6825    pub fn dayofyear(&self) -> Option<i64> {
6826        if self.is_nat() {
6827            return None;
6828        }
6829        let m = self.month()?;
6830        let d = self.day()?;
6831        let y = self.year()?;
6832        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
6833        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
6834        let base = days_before[(m - 1) as usize] + d;
6835        if is_leap && m > 2 {
6836            Some(base + 1)
6837        } else {
6838            Some(base)
6839        }
6840    }
6841
6842    /// Alias for dayofyear(). Matches `pd.Timestamp.day_of_year`.
6843    #[must_use]
6844    pub fn day_of_year(&self) -> Option<i64> {
6845        self.dayofyear()
6846    }
6847
6848    /// Return the proleptic Gregorian ordinal (number of days since Jan 1, year 1).
6849    ///
6850    /// Matches `pd.Timestamp.toordinal()`. Returns None for NaT.
6851    #[must_use]
6852    pub fn toordinal(&self) -> Option<i64> {
6853        if self.is_nat() {
6854            return None;
6855        }
6856        let y = self.year()?;
6857        let m = self.month()?;
6858        let d = self.day()?;
6859        // Algorithm: count days from year 1 to the start of the given year,
6860        // add days in the months before the given month, add the day of month.
6861        // Account for leap years.
6862        let y_minus_1 = y - 1;
6863        let mut ordinal = y_minus_1 * 365 + y_minus_1 / 4 - y_minus_1 / 100 + y_minus_1 / 400;
6864        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
6865        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
6866        ordinal += days_before[(m - 1) as usize];
6867        if is_leap && m > 2 {
6868            ordinal += 1;
6869        }
6870        ordinal += d;
6871        Some(ordinal)
6872    }
6873
6874    /// Construct a Timestamp from a proleptic Gregorian ordinal.
6875    ///
6876    /// Matches `pd.Timestamp.fromordinal(ordinal)`. Returns NaT for invalid ordinals.
6877    #[must_use]
6878    pub fn fromordinal(ordinal: i64) -> Self {
6879        if ordinal <= 0 {
6880            return Self {
6881                nanos: Self::NAT,
6882                tz: None,
6883            };
6884        }
6885        // Convert y/m/d to days since Unix epoch, then to nanos
6886        // Unix epoch is 1970-01-01, which is ordinal 719163
6887        let days_since_epoch = ordinal - 719163;
6888        match days_since_epoch.checked_mul(Timedelta::NANOS_PER_DAY) {
6889            Some(nanos) => Self { nanos, tz: None },
6890            None => Self::nat(),
6891        }
6892    }
6893
6894    /// Return the Julian Date (astronomical day number).
6895    ///
6896    /// Matches `pd.Timestamp.to_julian_date()`. Returns NaN for NaT.
6897    /// The Julian Date is the continuous count of days since the beginning
6898    /// of the Julian Period (January 1, 4713 BC in the proleptic Julian calendar).
6899    #[must_use]
6900    pub fn to_julian_date(&self) -> f64 {
6901        if self.is_nat() {
6902            return f64::NAN;
6903        }
6904        // Gregorian ordinal 1 (Jan 1, year 1) corresponds to Julian Day 1721425.5
6905        // (at noon, since JD starts at noon)
6906        // For a timestamp at midnight, we subtract 0.5
6907        let ordinal = match self.toordinal() {
6908            Some(o) => o,
6909            None => return f64::NAN,
6910        };
6911        // Fractional day from time components
6912        let h = self.hour().unwrap_or(0) as f64;
6913        let m = self.minute().unwrap_or(0) as f64;
6914        let s = self.second().unwrap_or(0) as f64;
6915        let us = self.microsecond().unwrap_or(0) as f64;
6916        let ns = self.nanosecond().unwrap_or(0) as f64;
6917        let frac_day =
6918            (h + m / 60.0 + s / 3600.0 + us / 3_600_000_000.0 + ns / 3_600_000_000_000.0) / 24.0;
6919        // Julian day at midnight of ordinal 1 is 1721424.5
6920        1721424.5 + ordinal as f64 + frac_day
6921    }
6922
6923    /// Return the quarter (1-4) of the year.
6924    ///
6925    /// Matches `pd.Timestamp.quarter`. Returns None for NaT.
6926    #[must_use]
6927    pub fn quarter(&self) -> Option<i64> {
6928        self.month().map(|m| (m - 1) / 3 + 1)
6929    }
6930
6931    /// Return the ISO week number (1-53).
6932    ///
6933    /// Matches `pd.Timestamp.week`. Returns None for NaT.
6934    #[must_use]
6935    pub fn weekofyear(&self) -> Option<i64> {
6936        if self.is_nat() {
6937            return None;
6938        }
6939        let doy = self.dayofyear()?;
6940        let dow = self.dayofweek()?;
6941        let year = self.year()?;
6942        let iso_dow = if dow == 6 { 7 } else { dow + 1 };
6943        let week = (doy - iso_dow + 10) / 7;
6944        // ISO-8601 has 53-week years, so the clamps must consult the actual
6945        // week count, not hardcode 52/1: a week<1 belongs to the LAST week of
6946        // the previous year (52 OR 53), and a week beyond this year's count
6947        // wraps to week 1 of the next year. pandas isocalendar().week agrees:
6948        // 2021-01-01 -> 53 (2020 is a 53-week year), 2026-12-31 -> 53.
6949        if week < 1 {
6950            Some(iso_weeks_in_year(year - 1))
6951        } else if week > iso_weeks_in_year(year) {
6952            Some(1)
6953        } else {
6954            Some(week)
6955        }
6956    }
6957
6958    /// Alias for weekofyear(). Matches `pd.Timestamp.week`.
6959    #[must_use]
6960    pub fn week(&self) -> Option<i64> {
6961        self.weekofyear()
6962    }
6963
6964    /// Return the timestamp value in the specified unit.
6965    ///
6966    /// Matches `pd.Timestamp.value` when unit is nanoseconds.
6967    /// Supported units: "ns", "us", "ms", "s".
6968    #[must_use]
6969    pub fn to_unit(&self, unit: &str) -> Option<i64> {
6970        if self.is_nat() {
6971            return None;
6972        }
6973        match unit {
6974            "ns" | "nanosecond" | "nanoseconds" => Some(self.nanos),
6975            "us" | "microsecond" | "microseconds" => Some(self.nanos / 1_000),
6976            "ms" | "millisecond" | "milliseconds" => Some(self.nanos / 1_000_000),
6977            "s" | "second" | "seconds" => Some(self.nanos / 1_000_000_000),
6978            _ => None,
6979        }
6980    }
6981
6982    /// Whether the year is a leap year.
6983    ///
6984    /// Matches `pd.Timestamp.is_leap_year`. Returns None for NaT.
6985    #[must_use]
6986    pub fn is_leap_year(&self) -> Option<bool> {
6987        self.year()
6988            .map(|y| (y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
6989    }
6990
6991    /// Whether the day is the first day of the month.
6992    ///
6993    /// Matches `pd.Timestamp.is_month_start`. Returns None for NaT.
6994    #[must_use]
6995    pub fn is_month_start(&self) -> Option<bool> {
6996        self.day().map(|d| d == 1)
6997    }
6998
6999    /// Whether the day is the last day of the month.
7000    ///
7001    /// Matches `pd.Timestamp.is_month_end`. Returns None for NaT.
7002    #[must_use]
7003    pub fn is_month_end(&self) -> Option<bool> {
7004        let y = self.year()?;
7005        let m = self.month()?;
7006        let d = self.day()?;
7007        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7008        let days_in_month: [i64; 12] = [
7009            31,
7010            if is_leap { 29 } else { 28 },
7011            31,
7012            30,
7013            31,
7014            30,
7015            31,
7016            31,
7017            30,
7018            31,
7019            30,
7020            31,
7021        ];
7022        Some(d == days_in_month[(m - 1) as usize])
7023    }
7024
7025    /// Whether the day is the first day of a quarter.
7026    ///
7027    /// Matches `pd.Timestamp.is_quarter_start`. Returns None for NaT.
7028    #[must_use]
7029    pub fn is_quarter_start(&self) -> Option<bool> {
7030        let m = self.month()?;
7031        let d = self.day()?;
7032        Some(d == 1 && (m == 1 || m == 4 || m == 7 || m == 10))
7033    }
7034
7035    /// Whether the day is the last day of a quarter.
7036    ///
7037    /// Matches `pd.Timestamp.is_quarter_end`. Returns None for NaT.
7038    #[must_use]
7039    pub fn is_quarter_end(&self) -> Option<bool> {
7040        let m = self.month()?;
7041        let d = self.day()?;
7042        Some(
7043            (m == 3 && d == 31)
7044                || (m == 6 && d == 30)
7045                || (m == 9 && d == 30)
7046                || (m == 12 && d == 31),
7047        )
7048    }
7049
7050    /// Whether the day is the first day of the year (Jan 1).
7051    ///
7052    /// Matches `pd.Timestamp.is_year_start`. Returns None for NaT.
7053    #[must_use]
7054    pub fn is_year_start(&self) -> Option<bool> {
7055        let m = self.month()?;
7056        let d = self.day()?;
7057        Some(m == 1 && d == 1)
7058    }
7059
7060    /// Whether the day is the last day of the year (Dec 31).
7061    ///
7062    /// Matches `pd.Timestamp.is_year_end`. Returns None for NaT.
7063    #[must_use]
7064    pub fn is_year_end(&self) -> Option<bool> {
7065        let m = self.month()?;
7066        let d = self.day()?;
7067        Some(m == 12 && d == 31)
7068    }
7069
7070    /// Return the number of days in the month of this timestamp.
7071    ///
7072    /// Matches `pd.Timestamp.days_in_month`. Returns None for NaT.
7073    #[must_use]
7074    pub fn days_in_month(&self) -> Option<i64> {
7075        let y = self.year()?;
7076        let m = self.month()?;
7077        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7078        let days: [i64; 12] = [
7079            31,
7080            if is_leap { 29 } else { 28 },
7081            31,
7082            30,
7083            31,
7084            30,
7085            31,
7086            31,
7087            30,
7088            31,
7089            30,
7090            31,
7091        ];
7092        Some(days[(m - 1) as usize])
7093    }
7094
7095    /// Alias for days_in_month(). Matches `pd.Timestamp.daysinmonth`.
7096    #[must_use]
7097    pub fn daysinmonth(&self) -> Option<i64> {
7098        self.days_in_month()
7099    }
7100
7101    /// Normalize to midnight/day boundary, matching `pd.Timestamp.normalize()`.
7102    #[must_use]
7103    pub fn normalize(&self) -> Self {
7104        self.floor_to(Timedelta::NANOS_PER_DAY)
7105    }
7106
7107    /// Replace timestamp components with new values.
7108    ///
7109    /// Matches pd.Timestamp.replace(). None values keep the existing component.
7110    #[must_use]
7111    #[allow(clippy::too_many_arguments)]
7112    pub fn replace(
7113        &self,
7114        year: Option<i64>,
7115        month: Option<i64>,
7116        day: Option<i64>,
7117        hour: Option<i64>,
7118        minute: Option<i64>,
7119        second: Option<i64>,
7120        microsecond: Option<i64>,
7121        nanosecond: Option<i64>,
7122    ) -> Self {
7123        if self.is_nat() {
7124            return self.clone();
7125        }
7126        let cur_year = self.year().unwrap_or(1970);
7127        let cur_month = self.month().unwrap_or(1);
7128        let cur_day = self.day().unwrap_or(1);
7129        let cur_hour = self.hour().unwrap_or(0);
7130        let cur_minute = self.minute().unwrap_or(0);
7131        let cur_second = self.second().unwrap_or(0);
7132        let cur_micro = self.microsecond().unwrap_or(0);
7133        let cur_nano = self.nanosecond().unwrap_or(0);
7134
7135        let y = year.unwrap_or(cur_year);
7136        let mo = month.unwrap_or(cur_month);
7137        let d = day.unwrap_or(cur_day);
7138        let h = hour.unwrap_or(cur_hour);
7139        let mi = minute.unwrap_or(cur_minute);
7140        let s = second.unwrap_or(cur_second);
7141        let us = microsecond.unwrap_or(cur_micro);
7142        let ns = nanosecond.unwrap_or(cur_nano);
7143
7144        if !(1..=12).contains(&mo)
7145            || !(1..=days_in_month(y, mo as u32).unwrap_or(0) as i64).contains(&d)
7146            || !(0..=23).contains(&h)
7147            || !(0..=59).contains(&mi)
7148            || !(0..=59).contains(&s)
7149            || !(0..=999_999).contains(&us)
7150            || !(0..=999).contains(&ns)
7151        {
7152            return Self::nat();
7153        }
7154
7155        // Checked nanosecond arithmetic (br-frankenpandas-dzz6x). The component
7156        // validation above rejects an out-of-range month/day/hour/... but says
7157        // nothing about the YEAR, and i64 nanoseconds run out at
7158        // `i64::MAX / NANOS_PER_DAY` = 106_751 days from the epoch — about year
7159        // 2262, the same bound pandas documents for ns-resolution Timestamps.
7160        // Unchecked, `replace(year=3000)` wrapped in release mode and returned a
7161        // silently wrong, plausible-looking in-range instant. Overflow now folds
7162        // to NaT, matching both the validation arm above and the sibling
7163        // constructors `fromordinal` / `floor_to`, which already fail this way.
7164        // In-range results are unchanged: the checked ops return exactly the
7165        // value the plain operators produced whenever no overflow occurred.
7166        let days_from_epoch = Self::days_from_ymd(y, mo, d);
7167        let secs = h * 3600 + mi * 60 + s;
7168        let Some(total_nanos) = days_from_epoch
7169            .checked_mul(Timedelta::NANOS_PER_DAY)
7170            .and_then(|nanos| {
7171                secs.checked_mul(Timedelta::NANOS_PER_SEC)
7172                    .and_then(|s_nanos| nanos.checked_add(s_nanos))
7173            })
7174            .and_then(|nanos| {
7175                us.checked_mul(Timedelta::NANOS_PER_MICRO)
7176                    .and_then(|us_nanos| nanos.checked_add(us_nanos))
7177            })
7178            .and_then(|nanos| nanos.checked_add(ns))
7179        else {
7180            return Self::nat();
7181        };
7182
7183        Self {
7184            nanos: total_nanos,
7185            tz: self.tz.clone(),
7186        }
7187    }
7188
7189    fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
7190        let y = if month <= 2 { year - 1 } else { year };
7191        let era = if y >= 0 { y } else { y - 399 } / 400;
7192        let yoe = y - era * 400;
7193        let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
7194        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
7195        era * 146097 + doe - 719468
7196    }
7197
7198    /// Return an ISO 8601 string representation of the timestamp.
7199    ///
7200    /// Matches `pd.Timestamp.isoformat()`. NaT returns "NaT".
7201    #[must_use]
7202    pub fn isoformat(&self) -> String {
7203        use std::fmt::Write as _;
7204
7205        if self.is_nat() {
7206            return "NaT".to_string();
7207        }
7208        let display_nanos = self
7209            .tz
7210            .as_deref()
7211            .and_then(Self::fixed_utc_offset_seconds)
7212            .and_then(|offset| self.nanos.checked_add(offset * Timedelta::NANOS_PER_SEC))
7213            .unwrap_or(self.nanos);
7214        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
7215        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
7216        let days_since_epoch = display_nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7217        let nanos_of_day = display_nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7218        let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7219        let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7220
7221        let days = days_since_epoch + 719_468;
7222        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7223        let doe = days - era * 146_097;
7224        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7225        let y = yoe + era * 400;
7226        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7227        let mp = (5 * doy + 2) / 153;
7228        let d = doy - (153 * mp + 2) / 5 + 1;
7229        let m = if mp < 10 { mp + 3 } else { mp - 9 };
7230        let year = if m <= 2 { y + 1 } else { y };
7231
7232        let hour = secs_of_day / 3600;
7233        let minute = (secs_of_day % 3600) / 60;
7234        let second = secs_of_day % 60;
7235
7236        // Build the timestamp and its optional timezone suffix in the returned
7237        // allocation. The former timezone-aware path first allocated `base`,
7238        // then allocated again to copy `base` into the suffixed result.
7239        let suffix_capacity = self
7240            .tz
7241            .as_ref()
7242            .map_or(0, |tz| if tz == "UTC" { 6 } else { tz.len() + 2 });
7243        let mut result = String::with_capacity(29 + suffix_capacity);
7244        if sub_nanos == 0 {
7245            let _ = write!(
7246                result,
7247                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}"
7248            );
7249        } else if sub_nanos.is_multiple_of(1_000) {
7250            let _ = write!(
7251                result,
7252                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{:06}",
7253                sub_nanos / 1_000
7254            );
7255        } else {
7256            let _ = write!(
7257                result,
7258                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{sub_nanos:09}"
7259            );
7260        }
7261        match &self.tz {
7262            Some(tz) if tz == "UTC" => result.push_str("+00:00"),
7263            Some(tz) if Self::fixed_utc_offset_seconds(tz).is_some() => {
7264                result.push_str(tz.strip_prefix("UTC").unwrap_or(tz));
7265            }
7266            Some(tz) => {
7267                result.push('[');
7268                result.push_str(tz);
7269                result.push(']');
7270            }
7271            None => {}
7272        }
7273        result
7274    }
7275
7276    /// Alias for isoformat.
7277    #[must_use]
7278    pub fn to_iso8601(&self) -> String {
7279        self.isoformat()
7280    }
7281
7282    /// The coarsest [`DatetimeStringResolution`] that renders `nanos` losslessly.
7283    ///
7284    /// Fold this over a column with `max` to get the column's width — see
7285    /// [`DatetimeStringResolution`] for why the width is a property of the
7286    /// COLUMN and not of the value. `NaT` reports [`DatetimeStringResolution`]
7287    /// `::Date`, the identity for that fold, because pandas excludes it from the
7288    /// scan entirely: a column of one midnight plus one NaT still renders
7289    /// `['2024-03-15', 'NaT']`.
7290    #[must_use]
7291    pub const fn string_resolution(nanos: i64) -> DatetimeStringResolution {
7292        if nanos == Self::NAT {
7293            return DatetimeStringResolution::Date;
7294        }
7295        if nanos.rem_euclid(Timedelta::NANOS_PER_DAY) == 0 {
7296            DatetimeStringResolution::Date
7297        } else if nanos.rem_euclid(Timedelta::NANOS_PER_SEC) == 0 {
7298            DatetimeStringResolution::Second
7299        } else if nanos.rem_euclid(Timedelta::NANOS_PER_MILLI) == 0 {
7300            DatetimeStringResolution::Milli
7301        } else if nanos.rem_euclid(Timedelta::NANOS_PER_MICRO) == 0 {
7302            DatetimeStringResolution::Micro
7303        } else {
7304            DatetimeStringResolution::Nano
7305        }
7306    }
7307
7308    /// Render `nanos` the way `astype(str)` does, at a resolution chosen for the
7309    /// whole column by [`Self::string_resolution`].
7310    ///
7311    /// ⚠️ NOT [`Self::isoformat`]. That one is `pd.Timestamp.isoformat()` — a `T`
7312    /// separator, and a width chosen per VALUE. This is the array formatter:
7313    /// a SPACE separator, and a width imposed on every element alike. MEASURED,
7314    /// live pandas 2.2.3, one column per rung:
7315    ///
7316    /// ```text
7317    /// all midnight       -> '2024-03-15'
7318    /// all whole seconds  -> '2024-03-15 10:30:45'
7319    /// all whole millis   -> '2024-03-15 10:30:45.123'
7320    /// all whole micros   -> '2024-03-15 10:30:45.123456'
7321    /// anything finer     -> '2024-03-15 10:30:45.123456789'
7322    /// NaT                -> 'NaT'          (a STRING, not a missing value)
7323    /// ```
7324    ///
7325    /// There is NO minute rung: a column of whole minutes still renders its
7326    /// seconds (`'2024-01-01 00:05:00'`).
7327    #[must_use]
7328    pub fn format_at_resolution(nanos: i64, resolution: DatetimeStringResolution) -> String {
7329        use std::fmt::Write as _;
7330
7331        if nanos == Self::NAT {
7332            return "NaT".to_string();
7333        }
7334        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos,
7335        // the same correction isoformat makes (br-frankenpandas-wkjtw): a
7336        // pre-epoch value must render 1969-12-31 23:59:59.999999999, not a
7337        // negative fraction.
7338        let days_since_epoch = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7339        let nanos_of_day = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7340        let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7341        let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC);
7342        // The crate's existing Hinnant civil-from-days, NOT a second copy: two
7343        // implementations of a calendar algorithm are two chances to drift.
7344        let (year, month, day) = civil_from_days(days_since_epoch);
7345
7346        // pandas' datetime64[ns] range is 1677..=2262, so the year is always
7347        // four digits and `{:04}` never truncates.
7348        let mut result = String::with_capacity(30);
7349        // `fmt::Write for String` is infallible.
7350        let _ = write!(result, "{year:04}-{month:02}-{day:02}");
7351        if matches!(resolution, DatetimeStringResolution::Date) {
7352            return result;
7353        }
7354        let _ = write!(
7355            result,
7356            " {:02}:{:02}:{:02}",
7357            secs_of_day / 3600,
7358            (secs_of_day % 3600) / 60,
7359            secs_of_day % 60
7360        );
7361        let (fraction, width) = match resolution {
7362            DatetimeStringResolution::Date | DatetimeStringResolution::Second => return result,
7363            DatetimeStringResolution::Milli => (sub_nanos / Timedelta::NANOS_PER_MILLI, 3_usize),
7364            DatetimeStringResolution::Micro => (sub_nanos / Timedelta::NANOS_PER_MICRO, 6_usize),
7365            DatetimeStringResolution::Nano => (sub_nanos, 9_usize),
7366        };
7367        let _ = write!(result, ".{fraction:0width$}", width = width);
7368        result
7369    }
7370
7371    /// Parse a datetime string into a Timestamp.
7372    ///
7373    /// Supports ISO 8601 formats:
7374    /// - "2024-01-15" (date only, time defaults to 00:00:00)
7375    /// - "2024-01-15T10:30:00" (datetime)
7376    /// - "2024-01-15 10:30:00" (space separator)
7377    /// - "2024-01-15T10:30:00.123456" (with fractional seconds)
7378    /// - "2024-01-15T10:30:00Z" (UTC timezone)
7379    /// - "2024-01-15T10:30:00+05:30" (offset timezone)
7380    /// - "NaT" (Not a Timestamp)
7381    ///
7382    /// Matches `pd.Timestamp()` constructor behavior.
7383    pub fn parse(s: &str) -> Result<Self, TypeError> {
7384        let s = s.trim();
7385
7386        if s.eq_ignore_ascii_case("nat") {
7387            return Ok(Self::nat());
7388        }
7389
7390        let Some((datetime_part, tz)) = Self::split_timezone(s) else {
7391            return Err(TypeError::ValueNotParseable {
7392                value: s.to_string(),
7393                target: "Timestamp".to_string(),
7394            });
7395        };
7396
7397        let (date_part, time_part) = if datetime_part.contains('T') {
7398            datetime_part
7399                .split_once('T')
7400                .ok_or_else(|| TypeError::ValueNotParseable {
7401                    value: s.to_string(),
7402                    target: "Timestamp".to_string(),
7403                })?
7404        } else if datetime_part.contains(' ')
7405            && datetime_part.chars().filter(|&c| c == ' ').count() == 1
7406        {
7407            datetime_part
7408                .split_once(' ')
7409                .ok_or_else(|| TypeError::ValueNotParseable {
7410                    value: s.to_string(),
7411                    target: "Timestamp".to_string(),
7412                })?
7413        } else {
7414            (datetime_part, "00:00:00")
7415        };
7416
7417        let (year, month, day) =
7418            Self::parse_date(date_part).ok_or_else(|| TypeError::ValueNotParseable {
7419                value: s.to_string(),
7420                target: "Timestamp".to_string(),
7421            })?;
7422
7423        let (hour, minute, second, nanos) =
7424            Self::parse_time(time_part).ok_or_else(|| TypeError::ValueNotParseable {
7425                value: s.to_string(),
7426                target: "Timestamp".to_string(),
7427            })?;
7428
7429        // br-frankenpandas-94o1u: an unrepresentable instant is a parse
7430        // failure, not a wrapped value.
7431        let wall_nanos = Self::ymd_hms_to_nanos(year, month, day, hour, minute, second, nanos)
7432            .ok_or_else(|| TypeError::ValueNotParseable {
7433                value: s.to_string(),
7434                target: "Timestamp".to_string(),
7435            })?;
7436        // The digits are the wall clock at the offset; the instant is that
7437        // wall time less the offset ('10:00+09:00' is 01:00 UTC - it was
7438        // read as 10:00 UTC, so it showed as 19:00+09:00).
7439        let offset = tz
7440            .as_deref()
7441            .and_then(Self::fixed_utc_offset_seconds)
7442            .unwrap_or(0);
7443        let total_nanos = offset
7444            .checked_mul(1_000_000_000)
7445            .and_then(|offset| wall_nanos.checked_sub(offset))
7446            .ok_or_else(|| TypeError::ValueNotParseable {
7447                value: s.to_string(),
7448                target: "Timestamp".to_string(),
7449            })?;
7450
7451        Ok(if let Some(tz_name) = tz {
7452            Self::from_nanos_tz(total_nanos, tz_name)
7453        } else {
7454            Self::from_nanos(total_nanos)
7455        })
7456    }
7457
7458    fn split_timezone(s: &str) -> Option<(&str, Option<String>)> {
7459        if let Some(stripped) = s.strip_suffix('Z') {
7460            Some((stripped, Some("UTC".to_string())))
7461        } else if let Some(idx) = s.rfind('+') {
7462            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7463                Some((&s[..idx], Some(s[idx..].to_string())))
7464            } else if idx > 10 {
7465                None
7466            } else {
7467                Some((s, None))
7468            }
7469        } else if let Some(idx) = s.rfind('-') {
7470            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7471                Some((&s[..idx], Some(s[idx..].to_string())))
7472            } else if idx > 10 {
7473                None
7474            } else {
7475                Some((s, None))
7476            }
7477        } else {
7478            Some((s, None))
7479        }
7480    }
7481
7482    fn fixed_utc_offset_seconds(tz: &str) -> Option<i64> {
7483        if tz == "UTC" {
7484            return Some(0);
7485        }
7486        let offset = tz.strip_prefix("UTC").unwrap_or(tz);
7487        if !Self::is_timezone_offset(offset) {
7488            return None;
7489        }
7490        let sign = if offset.starts_with('+') { 1 } else { -1 };
7491        let hours = offset[1..3].parse::<i64>().ok()?;
7492        let minutes = offset[4..6].parse::<i64>().ok()?;
7493        Some(sign * (hours * 3_600 + minutes * 60))
7494    }
7495
7496    fn is_timezone_offset(s: &str) -> bool {
7497        let bytes = s.as_bytes();
7498        if bytes.len() != 6 || !matches!(bytes[0], b'+' | b'-') || bytes[3] != b':' {
7499            return false;
7500        }
7501        if !bytes[1..3].iter().all(u8::is_ascii_digit)
7502            || !bytes[4..6].iter().all(u8::is_ascii_digit)
7503        {
7504            return false;
7505        }
7506        let hour = u32::from(bytes[1] - b'0') * 10 + u32::from(bytes[2] - b'0');
7507        let minute = u32::from(bytes[4] - b'0') * 10 + u32::from(bytes[5] - b'0');
7508        hour <= 23 && minute <= 59
7509    }
7510
7511    fn parse_date(s: &str) -> Option<(i64, u32, u32)> {
7512        let parts: Vec<&str> = s.split('-').collect();
7513        if parts.len() != 3 {
7514            return None;
7515        }
7516        let year: i64 = parts[0].parse().ok()?;
7517        let month: u32 = parts[1].parse().ok()?;
7518        let day: u32 = parts[2].parse().ok()?;
7519        if !(1..=days_in_month(year, month)?).contains(&day) {
7520            return None;
7521        }
7522        Some((year, month, day))
7523    }
7524
7525    fn parse_time(s: &str) -> Option<(u32, u32, u32, u64)> {
7526        let (time_str, frac_str) = match s.split_once('.') {
7527            Some((time, frac)) => (time, Some(frac)),
7528            None => (s, None),
7529        };
7530        let parts: Vec<&str> = time_str.split(':').collect();
7531        if parts.is_empty() || parts.len() > 3 {
7532            return None;
7533        }
7534        let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
7535        let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
7536        let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
7537
7538        if hour > 23 || minute > 59 || second > 59 {
7539            return None;
7540        }
7541
7542        let nanos = match frac_str {
7543            None => 0,
7544            Some(frac) => {
7545                if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
7546                    return None;
7547                }
7548                let digits = frac.len().min(9);
7549                let mut nanos = 0_u64;
7550                for byte in frac.bytes().take(digits) {
7551                    nanos = nanos * 10 + u64::from(byte - b'0');
7552                }
7553                for _ in digits..9 {
7554                    nanos *= 10;
7555                }
7556                nanos
7557            }
7558        };
7559
7560        Some((hour, minute, second, nanos))
7561    }
7562
7563    /// Compose a civil date-time into i64 nanoseconds since the epoch, or
7564    /// `None` when the instant is not representable.
7565    ///
7566    /// Checked composition (br-frankenpandas-94o1u). `parse_date` validates the
7567    /// month and the day-of-month but parses the YEAR as an unbounded `i64`,
7568    /// and i64 nanoseconds top out around year 2262 — the bound pandas
7569    /// documents for ns-resolution Timestamps. Unchecked, the two multiplies
7570    /// below wrapped in release, so `Timestamp::parse("300000-01-01")` returned
7571    /// `Ok` holding a silently wrong, plausible-looking in-range instant.
7572    /// pandas raises `OutOfBoundsDatetime`.
7573    ///
7574    /// This is the ingestion path — CSV/JSON date columns and user strings —
7575    /// so failing OPEN with corrupt data is the failure mode the security
7576    /// doctrine specifically forbids. `None` here becomes the same
7577    /// `ValueNotParseable` the caller already returns for any other
7578    /// unparseable input, so no new error variant and no API change.
7579    ///
7580    /// The day-count arithmetic above the multiplies cannot overflow for any
7581    /// `year` that survives `str::parse::<i64>` minus the era arithmetic's own
7582    /// bounds, but it is routed through checked ops anyway so an extreme year
7583    /// is rejected rather than wrapped before it ever reaches the seconds step.
7584    fn ymd_hms_to_nanos(
7585        year: i64,
7586        month: u32,
7587        day: u32,
7588        hour: u32,
7589        minute: u32,
7590        second: u32,
7591        sub_nanos: u64,
7592    ) -> Option<i64> {
7593        let m = month as i64;
7594        let d = day as i64;
7595
7596        let y = if m <= 2 { year.checked_sub(1)? } else { year };
7597        let era = if y >= 0 { y } else { y.checked_sub(399)? } / 400;
7598        let yoe = y.checked_sub(era.checked_mul(400)?)?;
7599        let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
7600        let doe = yoe
7601            .checked_mul(365)?
7602            .checked_add(yoe / 4 - yoe / 100)?
7603            .checked_add(doy)?;
7604        let days_since_epoch = era
7605            .checked_mul(146_097)?
7606            .checked_add(doe)?
7607            .checked_sub(719_468)?;
7608
7609        let total_seconds = days_since_epoch
7610            .checked_mul(86400)?
7611            .checked_add(i64::from(hour) * 3600)?
7612            .checked_add(i64::from(minute) * 60)?
7613            .checked_add(i64::from(second))?;
7614        total_seconds
7615            .checked_mul(Timedelta::NANOS_PER_SEC)?
7616            .checked_add(sub_nanos as i64)
7617    }
7618
7619    /// Format timestamp using strftime directives.
7620    ///
7621    /// Matches `pd.Timestamp.strftime(format)`: Python's (glibc's) directive
7622    /// set, see [`strftime_python`] (it knew only %Y %m %d %H %M %S %f and
7623    /// printed `%%Y` as `%2024`). A tz-aware Timestamp formats its wall clock,
7624    /// `%z` / `%Z` its zone's offset and abbreviation then. NaT returns "NaT".
7625    #[must_use]
7626    pub fn strftime(&self, format: &str) -> String {
7627        if self.is_nat() {
7628            return "NaT".to_string();
7629        }
7630        strftime_in_zone(self.nanos, format, self.tz.as_deref())
7631    }
7632
7633    /// Return the day of the week as a string (e.g., "Monday").
7634    ///
7635    /// Matches `pd.Timestamp.day_name()`. NaT returns "NaT".
7636    #[must_use]
7637    pub fn day_name(&self) -> String {
7638        const NAMES: [&str; 7] = [
7639            "Thursday",
7640            "Friday",
7641            "Saturday",
7642            "Sunday",
7643            "Monday",
7644            "Tuesday",
7645            "Wednesday",
7646        ];
7647        if self.is_nat() {
7648            return "NaT".to_string();
7649        }
7650        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
7651        // Truncating `/` rounds a negative, non-midnight instant TOWARD zero, so
7652        // it lands on the following day and names the wrong weekday: pandas 2.2.3
7653        // gives 1969-07-20T20:17:40 -> "Sunday", truncation gave "Monday". The
7654        // wkjtw fix was applied to `dayofweek` but never here.
7655        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7656        let dow = ((days_since_epoch % 7) + 7) % 7;
7657        NAMES[dow as usize].to_string()
7658    }
7659
7660    /// Return the month name as a string (e.g., "January").
7661    ///
7662    /// Matches `pd.Timestamp.month_name()`. NaT returns "NaT".
7663    #[must_use]
7664    pub fn month_name(&self) -> String {
7665        const NAMES: [&str; 12] = [
7666            "January",
7667            "February",
7668            "March",
7669            "April",
7670            "May",
7671            "June",
7672            "July",
7673            "August",
7674            "September",
7675            "October",
7676            "November",
7677            "December",
7678        ];
7679        if self.is_nat() {
7680            return "NaT".to_string();
7681        }
7682        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
7683        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
7684        // for the post-1970 positive case.
7685        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7686        let days = days_since_epoch + 719_468;
7687        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7688        let doe = days - era * 146_097;
7689        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7690        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7691        let mp = (5 * doy + 2) / 153;
7692        let m = if mp < 10 { mp + 3 } else { mp - 9 };
7693        NAMES[(m - 1) as usize].to_string()
7694    }
7695
7696    /// Localize a naive timestamp to a timezone.
7697    ///
7698    /// Matches `pd.Timestamp.tz_localize(tz)`. If `tz` is None, removes the
7699    /// timezone (makes timestamp naive). NaT propagates.
7700    #[must_use]
7701    pub fn tz_localize(&self, tz: Option<&str>) -> Self {
7702        if self.is_nat() {
7703            return Self::nat();
7704        }
7705        Self {
7706            nanos: self.nanos,
7707            tz: tz.map(String::from),
7708        }
7709    }
7710
7711    /// Convert timezone-aware timestamp to another timezone.
7712    ///
7713    /// Matches `pd.Timestamp.tz_convert(tz)`. If timestamp is naive (no tz),
7714    /// the timezone is simply attached without conversion. NaT propagates.
7715    /// Note: actual UTC offset conversion requires chrono-tz (Phase 3).
7716    #[must_use]
7717    pub fn tz_convert(&self, tz: &str) -> Self {
7718        if self.is_nat() {
7719            return Self::nat();
7720        }
7721        Self {
7722            nanos: self.nanos,
7723            tz: Some(tz.to_string()),
7724        }
7725    }
7726
7727    /// Create a Timestamp from a Unix timestamp (seconds since epoch).
7728    ///
7729    /// Matches `pd.Timestamp.fromtimestamp(ts)`. The optional `tz` parameter
7730    /// specifies the timezone to localize to.
7731    #[must_use]
7732    pub fn fromtimestamp(ts: f64, tz: Option<&str>) -> Self {
7733        if ts.is_nan() || ts.is_infinite() {
7734            return Self::nat();
7735        }
7736        let nanos_f64 = ts * 1_000_000_000.0;
7737        // Check for overflow before casting - i64 range is roughly ±9.2e18
7738        const MAX_NANOS: f64 = i64::MAX as f64;
7739        const MIN_NANOS: f64 = i64::MIN as f64;
7740        if !(MIN_NANOS..=MAX_NANOS).contains(&nanos_f64) {
7741            return Self::nat();
7742        }
7743        Self {
7744            nanos: nanos_f64 as i64,
7745            tz: tz.map(String::from),
7746        }
7747    }
7748
7749    /// Create a Timestamp from milliseconds since epoch.
7750    ///
7751    /// Convenience constructor complementing fromtimestamp. An `ms` outside
7752    /// the representable nanosecond range → NaT, matching `fromtimestamp`
7753    /// directly above (br-frankenpandas-kyd16); the previous
7754    /// `saturating_mul` handed back a finite ~year-2262 instant instead.
7755    #[must_use]
7756    pub fn from_millis(ms: i64, tz: Option<&str>) -> Self {
7757        let Some(nanos) = ms.checked_mul(1_000_000) else {
7758            return Self::nat();
7759        };
7760        Self {
7761            nanos,
7762            tz: tz.map(String::from),
7763        }
7764    }
7765
7766    /// Create a Timestamp from microseconds since epoch.
7767    ///
7768    /// Convenience constructor complementing fromtimestamp.
7769    #[must_use]
7770    pub fn from_micros(us: i64, tz: Option<&str>) -> Self {
7771        let Some(nanos) = us.checked_mul(1_000) else {
7772            return Self::nat();
7773        };
7774        Self {
7775            nanos,
7776            tz: tz.map(String::from),
7777        }
7778    }
7779
7780    /// Return the timezone string, or None if naive.
7781    #[must_use]
7782    pub fn tzinfo(&self) -> Option<&str> {
7783        self.tz.as_deref()
7784    }
7785
7786    /// Return the timezone name, or None if naive.
7787    ///
7788    /// Alias for tzinfo() matching pandas Timestamp.tzname().
7789    #[must_use]
7790    pub fn tzname(&self) -> Option<&str> {
7791        self.tzinfo()
7792    }
7793}
7794
7795impl std::fmt::Display for Timestamp {
7796    /// Phase 2 debug-style format; Phase 3 replaces with pandas ISO-8601
7797    /// notation once chrono interpretation lands.
7798    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7799        if self.is_nat() {
7800            return f.write_str("NaT");
7801        }
7802        match &self.tz {
7803            Some(tz) => write!(f, "Timestamp[{}, {}]", self.nanos, tz),
7804            None => write!(f, "Timestamp[{}, UTC]", self.nanos),
7805        }
7806    }
7807}
7808
7809impl PartialOrd for Timestamp {
7810    /// Orders by nanos axis; NaT is incomparable (`None`). Tz difference
7811    /// does not affect ordering — two Timestamps at the same absolute
7812    /// nanos compare equal regardless of tz label (Phase 3 will revisit
7813    /// whether tz affects ordering semantics).
7814    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
7815        if self.is_nat() || other.is_nat() {
7816            return None;
7817        }
7818        Some(self.nanos.cmp(&other.nanos))
7819    }
7820}
7821
7822// ── Missingness utilities ──────────────────────────────────────────────
7823
7824pub fn isna(values: &[Scalar]) -> Vec<bool> {
7825    values.iter().map(Scalar::is_missing).collect()
7826}
7827
7828pub fn isnull(values: &[Scalar]) -> Vec<bool> {
7829    isna(values)
7830}
7831
7832pub fn notna(values: &[Scalar]) -> Vec<bool> {
7833    values.iter().map(|v| !v.is_missing()).collect()
7834}
7835
7836pub fn notnull(values: &[Scalar]) -> Vec<bool> {
7837    notna(values)
7838}
7839
7840pub fn count_na(values: &[Scalar]) -> usize {
7841    values.iter().filter(|v| v.is_missing()).count()
7842}
7843
7844pub fn fill_na(values: &[Scalar], fill: &Scalar) -> Vec<Scalar> {
7845    values
7846        .iter()
7847        .map(|v| {
7848            if v.is_missing() {
7849                fill.clone()
7850            } else {
7851                v.clone()
7852            }
7853        })
7854        .collect()
7855}
7856
7857pub fn dropna(values: &[Scalar]) -> Vec<Scalar> {
7858    values.iter().filter(|v| !v.is_missing()).cloned().collect()
7859}
7860
7861// ── Nanops: null-skipping numeric reductions ───────────────────────────
7862
7863fn collect_finite(values: &[Scalar]) -> Vec<f64> {
7864    values
7865        .iter()
7866        .filter(|v| !v.is_missing())
7867        .filter_map(|v| v.to_f64().ok())
7868        .collect()
7869}
7870
7871/// Per br-frankenpandas-620mj: if a column is uniformly Timedelta64
7872/// (with optional NAT/Null missing), sum/mean preserve Timedelta dtype
7873/// matching pandas — instead of silently coercing to Float64(0.0) via
7874/// the collect_finite path (which drops Timedelta64 because to_f64
7875/// errors). A NaT-only input remains a Timedelta family so sum returns
7876/// zero Timedelta and mean returns NaT. Returns Some(sum_in_ns,
7877/// observed_count) when applicable.
7878fn collect_timedelta_ns(values: &[Scalar]) -> Option<(i128, usize)> {
7879    let mut sum: i128 = 0;
7880    let mut count: usize = 0;
7881    let mut saw_timedelta = false;
7882    for v in values {
7883        match v {
7884            Scalar::Timedelta64(ns) => {
7885                saw_timedelta = true;
7886                if v.is_missing() {
7887                    continue;
7888                }
7889                sum += i128::from(*ns);
7890                count += 1;
7891            }
7892            _ if v.is_missing() => continue,
7893            // Any non-Timedelta non-missing value bails out to the
7894            // existing Float64 path, preserving cross-type behavior.
7895            _ => return None,
7896        }
7897    }
7898    if saw_timedelta {
7899        Some((sum, count))
7900    } else {
7901        None
7902    }
7903}
7904
7905/// Narrow an exact `i128` nanosecond quantity back to a `Timedelta64` scalar,
7906/// surfacing NaT when the value is not representable.
7907///
7908/// Per br-frankenpandas-opz27, this replaces the `clamp(i64::MIN, i64::MAX)`
7909/// the reduction paths used to do, which failed open twice over:
7910///
7911/// - a positive overflow became `i64::MAX`, a fabricated finite ~106751-day
7912///   Timedelta presented as real data (the br-frankenpandas-lgyy8 class);
7913/// - `Timedelta::NAT` *is* `i64::MIN`, so the clamp's lower bound landed
7914///   exactly on the missing sentinel — a negative overflow silently became
7915///   NaT by accident, and the bound was off by one against the true minimum.
7916///
7917/// The representable range is therefore `[i64::MIN + 1, i64::MAX]`, and both
7918/// overflow directions now yield NaT deliberately. Live pandas 2.2.3 raises
7919/// (`OverflowError` / `ValueError: overflow in timedelta operation`) where
7920/// these reductions overflow; FP surfaces NaT instead, matching the
7921/// infallible-helper convention established by `Timedelta::div_scalar` and
7922/// br-frankenpandas-lgyy8. Every exactly-representable result is unaffected.
7923fn timedelta_ns_to_scalar(ns: i128) -> Scalar {
7924    if ns > i128::from(i64::MAX) || ns <= i128::from(i64::MIN) {
7925        return Scalar::Timedelta64(Timedelta::NAT);
7926    }
7927    Scalar::Timedelta64(ns as i64)
7928}
7929
7930pub fn nansum(values: &[Scalar]) -> Scalar {
7931    if let Some((sum, _)) = collect_timedelta_ns(values) {
7932        return timedelta_ns_to_scalar(sum);
7933    }
7934    // Fused single-pass fold: filter missing / non-f64-coercible and accumulate
7935    // in one scan, avoiding the intermediate `collect_finite` Vec<f64> and its
7936    // second pass. Bit-identical to `collect_finite(..).iter().sum()`: same
7937    // finite values in the same order, same left-fold f64 `+` (empty -> 0.0).
7938    let mut sum = 0.0_f64;
7939    for v in values {
7940        if v.is_missing() {
7941            continue;
7942        }
7943        if let Ok(x) = v.to_f64() {
7944            sum += x;
7945        }
7946    }
7947    Scalar::Float64(sum)
7948}
7949
7950/// Sum of a STRING group: pandas concatenates, skipping missing entries.
7951///
7952/// br-frankenpandas-a7faz. `nansum` cannot serve this: it coerces through
7953/// `to_f64`, which fails for every `Utf8`, so a string column sums to
7954/// `Float64(0.0)` — a wrong value rather than a refusal. This is a separate
7955/// reducer rather than a branch inside `nansum` on purpose: the SUM SURFACES
7956/// DISAGREE in pandas and a shared change would silently move the others.
7957///
7958/// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18):
7959/// ```text
7960///   Series(['a','b','c']).sum()              -> 'abc'
7961///   Series(['a',None,'c']).sum()             -> TypeError: can only concatenate str
7962///   DataFrame({'v':['a',None]}).sum()        -> TypeError (same)
7963///   df.groupby(k)['v'].sum()  with a None    -> 'a'      SKIPS, does not raise
7964///   s.resample('ME').sum()    with a None    -> 'ps'     SKIPS, does not raise
7965/// ```
7966/// So the REDUCTION surfaces raise on a missing entry while the GROUPED surfaces
7967/// skip it. This function implements the grouped rule and must not be wired into
7968/// `Series::sum`/`DataFrame::sum` without implementing their raise.
7969///
7970/// ⚠️ AND AN EMPTY OR ALL-MISSING GROUP IS INTEGER `0`, NOT `""`. Measured:
7971/// ```text
7972///   Series(['p','q'], index=[Jan-01, Mar-01]).resample('ME').sum()
7973///     -> ['p', 0, 'q']        <- the empty February bucket is int 0
7974///   Series([None,None,'r','u'], ...).resample('ME').sum()
7975///     -> [0, 'ru']            <- an all-missing bucket is int 0 too
7976///   types: ['int', 'str']     <- the output column is genuinely MIXED
7977/// ```
7978/// That is pandas' `sum()` identity element leaking through unchanged, and it is
7979/// why this returns `Scalar::Int64(0)` rather than an empty string: matching the
7980/// incumbent here means reproducing a mixed-dtype column.
7981///
7982/// Concatenation is POSITIONAL, not sorted — `Series(['z','a','m']).sum()` is
7983/// `'zam'`. Callers that bucket by time therefore hand the values over in index
7984/// order, which is what produced `'psq'` for a Jan bucket holding Jan-01 'p',
7985/// Jan-05 's', Jan-15 'q'.
7986#[must_use]
7987pub fn nansum_utf8(values: &[Scalar]) -> Scalar {
7988    let mut out: Option<String> = None;
7989    for v in values {
7990        if v.is_missing() {
7991            continue;
7992        }
7993        if let Scalar::Utf8(part) = v {
7994            out.get_or_insert_with(String::new).push_str(part);
7995        }
7996    }
7997    match out {
7998        Some(joined) => Scalar::Utf8(joined),
7999        // Not `Utf8(String::new())`: pandas yields the integer identity here.
8000        None => Scalar::Int64(0),
8001    }
8002}
8003
8004pub fn nanmean(values: &[Scalar]) -> Scalar {
8005    if let Some((sum, count)) = collect_timedelta_ns(values) {
8006        if count == 0 {
8007            return Scalar::Timedelta64(Timedelta::NAT);
8008        }
8009        // |sum / count| <= max|ns| for count >= 1, so the mean of representable
8010        // inputs is always representable; the narrowing is defensive only.
8011        return timedelta_ns_to_scalar(sum / count as i128);
8012    }
8013    // br-frankenpandas-adv58: Datetime64 mean is the mean of the epoch-ns
8014    // backing, re-read as an instant. Accumulated in i128 and divided with
8015    // Rust's toward-zero integer division, which is exactly the rounding pandas
8016    // shows where it is exact ([0,1] -> 0, [0,3] -> 1, [-3,0] -> -1; floor and
8017    // ties-to-even are both refuted). Where pandas is NOT exact it snaps to its
8018    // f64 grid — even for a constant series — and FP stays exact. See DISC-019.
8019    if let Some((sum, count)) = collect_datetime_ns(values) {
8020        if count == 0 {
8021            return Scalar::Datetime64(Timestamp::NAT);
8022        }
8023        let mean = sum / count as i128;
8024        if mean > i128::from(i64::MAX) || mean <= i128::from(i64::MIN) {
8025            return Scalar::Datetime64(Timestamp::NAT);
8026        }
8027        return Scalar::Datetime64(mean as i64);
8028    }
8029    // Fused single-pass fold (see `nansum`): accumulate sum + count of finite
8030    // values in one scan. Bit-identical to the prior `collect_finite` two-pass:
8031    // count == nums.len(), sum folds the same values in the same order.
8032    let mut sum = 0.0_f64;
8033    let mut count = 0usize;
8034    for v in values {
8035        if v.is_missing() {
8036            continue;
8037        }
8038        if let Ok(x) = v.to_f64() {
8039            sum += x;
8040            count += 1;
8041        }
8042    }
8043    if count == 0 {
8044        return Scalar::Null(NullKind::NaN);
8045    }
8046    Scalar::Float64(sum / count as f64)
8047}
8048
8049pub fn nanany(values: &[Scalar]) -> Scalar {
8050    for v in values {
8051        if v.is_missing() {
8052            continue;
8053        }
8054        match v {
8055            Scalar::Bool(flag) if *flag => return Scalar::Bool(true),
8056            Scalar::Int64(val) if *val != 0 => return Scalar::Bool(true),
8057            Scalar::Float64(val) if !val.is_nan() && *val != 0.0 => return Scalar::Bool(true),
8058            Scalar::Utf8(val) if !val.is_empty() => return Scalar::Bool(true),
8059            // pandas Series([td]).any() returns True for any non-zero
8060            // Timedelta. NaT is already filtered by is_missing() above.
8061            Scalar::Timedelta64(ns) if *ns != 0 => return Scalar::Bool(true),
8062            _ => continue,
8063        }
8064    }
8065    Scalar::Bool(false)
8066}
8067
8068pub fn nanall(values: &[Scalar]) -> Scalar {
8069    for v in values {
8070        if v.is_missing() {
8071            continue;
8072        }
8073        match v {
8074            Scalar::Bool(flag) if !*flag => return Scalar::Bool(false),
8075            Scalar::Int64(val) if *val == 0 => return Scalar::Bool(false),
8076            Scalar::Float64(val) if val.is_nan() || *val == 0.0 => return Scalar::Bool(false),
8077            Scalar::Utf8(val) if val.is_empty() => return Scalar::Bool(false),
8078            // pandas Series([td(0)]).all() returns False; any non-zero
8079            // Timedelta is truthy. NaT is already filtered by is_missing.
8080            Scalar::Timedelta64(ns) if *ns == 0 => return Scalar::Bool(false),
8081            _ => continue,
8082        }
8083    }
8084    Scalar::Bool(true)
8085}
8086
8087pub fn nancount(values: &[Scalar]) -> Scalar {
8088    let n = values.iter().filter(|v| !v.is_missing()).count();
8089    Scalar::Int64(n as i64)
8090}
8091
8092pub fn nanmin(values: &[Scalar]) -> Scalar {
8093    let mut min: Option<&Scalar> = None;
8094    for v in values {
8095        if v.is_missing() {
8096            continue;
8097        }
8098        match (min, v) {
8099            (None, _) => min = Some(v),
8100            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8101                if b < a {
8102                    min = Some(v)
8103                }
8104            }
8105            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8106                if *b < *a {
8107                    min = Some(v)
8108                }
8109            }
8110            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8111                if b < a {
8112                    min = Some(v)
8113                }
8114            }
8115            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8116                if b < a {
8117                    min = Some(v)
8118                }
8119            }
8120            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
8121            // the catch-all below would silently return NaN. Compare ns
8122            // representations directly; NAT is already filtered by
8123            // is_missing() above.
8124            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8125                if b < a {
8126                    min = Some(v)
8127                }
8128            }
8129            // br-frankenpandas-axhhk: Datetime64 needs the same arm for the
8130            // same reason — its to_f64() errors too. Without it a 2+-element
8131            // datetime column returned Null(NaN), while a 1-element one
8132            // returned the right answer via the (None, _) seed above.
8133            (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8134                if b < a {
8135                    min = Some(v)
8136                }
8137            }
8138            // br-frankenpandas-qoabs: Period, third dtype with the same
8139            // to_f64() failure. Ordinals are ONLY comparable within one freq —
8140            // pandas refuses mixed freq outright (IncompatibleFrequency), so a
8141            // differing freq must NOT be ordered here. Comparing the raw
8142            // ordinals across freqs would invent an ordering pandas rejects
8143            // (monthly 2020-01 is ordinal 600, daily 2020-01-05 is 18267).
8144            // br-frankenpandas-qoabs: Period, third dtype with the same
8145            // to_f64() failure. Ordinals are ONLY comparable within one freq —
8146            // pandas refuses mixed freq outright (IncompatibleFrequency), so a
8147            // differing freq must NOT be ordered here. Comparing the raw
8148            // ordinals across freqs would invent an ordering pandas rejects
8149            // (monthly 2020-01 is ordinal 600, daily 2020-01-05 is 18267).
8150            (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8151                if a.freq != b.freq {
8152                    return Scalar::Null(NullKind::NaN);
8153                }
8154                if b.ordinal < a.ordinal {
8155                    min = Some(v)
8156                }
8157            }
8158            // br-frankenpandas-srqdo: Interval, fourth dtype whose to_f64()
8159            // errors. pandas orders Intervals by (left, right) — a tie on left
8160            // falls through to right. `closed` is NOT part of the comparison:
8161            // pandas does order scalar Intervals that tie on both bounds by an
8162            // internal `closed` ordering, but a real IntervalArray requires a
8163            // UNIFORM closed, so that case cannot arise from an Interval
8164            // column, and guessing an undocumented enum order would be worse
8165            // than keeping the first on an exact tie.
8166            //
8167            // A NaN bound is not orderable and has no pandas counterpart —
8168            // IntervalArray refuses to build one ("missing values must be
8169            // missing in the same location both left and right") — so bail to
8170            // missing rather than impose an arbitrary order. Note this avoids
8171            // `partial_cmp().unwrap()`, which would be a panic in library code.
8172            (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8173                if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8174                    return Scalar::Null(NullKind::NaN);
8175                }
8176                if (b.left, b.right) < (a.left, a.right) {
8177                    min = Some(v)
8178                }
8179            }
8180            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8181                (Ok(af), Ok(bf)) if bf < af => min = Some(v),
8182                (Ok(_), Ok(_)) => {}
8183                _ => return Scalar::Null(NullKind::NaN),
8184            },
8185        }
8186    }
8187    match min {
8188        Some(v) => v.clone(),
8189        None => Scalar::Null(NullKind::NaN),
8190    }
8191}
8192
8193pub fn nanmax(values: &[Scalar]) -> Scalar {
8194    let mut max: Option<&Scalar> = None;
8195    for v in values {
8196        if v.is_missing() {
8197            continue;
8198        }
8199        match (max, v) {
8200            (None, _) => max = Some(v),
8201            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8202                if b > a {
8203                    max = Some(v)
8204                }
8205            }
8206            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8207                if *b > *a {
8208                    max = Some(v)
8209                }
8210            }
8211            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8212                if b > a {
8213                    max = Some(v)
8214                }
8215            }
8216            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8217                if b > a {
8218                    max = Some(v)
8219                }
8220            }
8221            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
8222            // the catch-all below would silently return NaN. Compare ns
8223            // representations directly; NAT is already filtered above.
8224            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8225                if b > a {
8226                    max = Some(v)
8227                }
8228            }
8229            // br-frankenpandas-axhhk: Datetime64 sibling of the arm above.
8230            (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8231                if b > a {
8232                    max = Some(v)
8233                }
8234            }
8235            // br-frankenpandas-qoabs: Period, freq-guarded — see `nanmin`.
8236            (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8237                if a.freq != b.freq {
8238                    return Scalar::Null(NullKind::NaN);
8239                }
8240                if b.ordinal > a.ordinal {
8241                    max = Some(v)
8242                }
8243            }
8244            // br-frankenpandas-srqdo: Interval, ordered by (left, right) with
8245            // NaN bounds refused — see `nanmin` for the full reasoning.
8246            (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8247                if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8248                    return Scalar::Null(NullKind::NaN);
8249                }
8250                if (b.left, b.right) > (a.left, a.right) {
8251                    max = Some(v)
8252                }
8253            }
8254            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8255                (Ok(af), Ok(bf)) if bf > af => max = Some(v),
8256                (Ok(_), Ok(_)) => {}
8257                _ => return Scalar::Null(NullKind::NaN),
8258            },
8259        }
8260    }
8261    match max {
8262        Some(v) => v.clone(),
8263        None => Scalar::Null(NullKind::NaN),
8264    }
8265}
8266
8267/// Which temporal family a uniformly-temporal input belongs to, and everything
8268/// needed to rebuild a `Scalar` of it from a raw i64 backing.
8269///
8270/// br-frankenpandas-d7zjp replaced the previous `fn(i64) -> Scalar` constructor
8271/// with this enum for one reason: a plain fn pointer CANNOT CARRY A FREQ, and a
8272/// `Period` is `{ordinal, freq}`. That limitation is what blocked Period from
8273/// joining median/quantile/cummax/cummin when Datetime64 did.
8274///
8275/// The i64 payload is nanoseconds for Timedelta64/Datetime64 and an ORDINAL for
8276/// Period — different units, but every operation here is pure ordering or an
8277/// average over that backing, which is meaningful in both.
8278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8279enum TemporalFamily {
8280    Timedelta,
8281    Datetime,
8282    /// Periods only compare within ONE freq; see [`collect_temporal_backing`].
8283    Period(PeriodFreq),
8284}
8285
8286impl TemporalFamily {
8287    /// Rebuild a scalar of this family from its raw backing.
8288    fn make(self, raw: i64) -> Scalar {
8289        match self {
8290            Self::Timedelta => Scalar::Timedelta64(raw),
8291            Self::Datetime => Scalar::Datetime64(raw),
8292            Self::Period(freq) => Scalar::Period(Period::new(raw, freq)),
8293        }
8294    }
8295
8296    /// The family's missing sentinel, dtype preserved.
8297    fn nat(self) -> Scalar {
8298        self.make(i64::MIN)
8299    }
8300}
8301
8302/// Per br-frankenpandas-j8ntk: harvest the raw backing of a uniformly-temporal
8303/// input as f64 (53 bits of mantissa, exact for ns spans up to ~104 days;
8304/// beyond that pandas itself loses precision the same way), together with the
8305/// family to rebuild results in. A NaT-only input keeps its family.
8306///
8307/// Returns `None` unless every non-missing value belongs to ONE family — which
8308/// for Period means one FREQ as well, because pandas refuses to order Periods
8309/// of differing freq at all (`IncompatibleFrequency`) and their ordinals are
8310/// not comparable across freqs.
8311///
8312/// br-frankenpandas-adv58 widened this to Datetime64 and d7zjp to Period. The
8313/// f64 hop is inherited deliberately: quantile interpolates by a fractional
8314/// weight, so the newer families keep the SAME accuracy contract the Timedelta
8315/// arm already had rather than inventing a stricter one per dtype.
8316fn collect_temporal_backing(values: &[Scalar]) -> Option<(Vec<f64>, TemporalFamily)> {
8317    let mut out = Vec::with_capacity(values.len());
8318    let mut family: Option<TemporalFamily> = None;
8319    for v in values {
8320        let (raw, this) = match v {
8321            Scalar::Timedelta64(ns) => (*ns, TemporalFamily::Timedelta),
8322            Scalar::Datetime64(ns) => (*ns, TemporalFamily::Datetime),
8323            Scalar::Period(p) => (p.ordinal, TemporalFamily::Period(p.freq)),
8324            _ if v.is_missing() => continue,
8325            _ => return None,
8326        };
8327        // Mixing families — or, for Period, mixing freqs — is not one family.
8328        match family {
8329            Some(existing) if existing != this => return None,
8330            _ => family = Some(this),
8331        }
8332        if v.is_missing() {
8333            continue;
8334        }
8335        out.push(raw as f64);
8336    }
8337    family.map(|f| (out, f))
8338}
8339
8340/// Timedelta64-ONLY view of [`collect_temporal_backing`].
8341///
8342/// var/sem keep this narrower gate on purpose: live pandas 2.2.3 RAISES
8343/// `TypeError: 'DatetimeArray' ... does not support reduction 'var'` (and the
8344/// same for 'sem', and for every one of them on Period), so widening them would
8345/// invent a value pandas refuses to produce.
8346fn collect_timedelta_ns_f64(values: &[Scalar]) -> Option<Vec<f64>> {
8347    match collect_temporal_backing(values) {
8348        Some((out, TemporalFamily::Timedelta)) => Some(out),
8349        _ => None,
8350    }
8351}
8352
8353/// Clamp an f64 result into i64 range and wrap as Scalar::Timedelta64.
8354fn float_ns_to_timedelta(value: f64) -> Scalar {
8355    float_ns_to_temporal(value, TemporalFamily::Timedelta)
8356}
8357
8358/// Family-generic form of [`float_ns_to_timedelta`], per br-frankenpandas-adv58:
8359/// NaT for a non-finite input, otherwise the value in the caller's family.
8360fn float_ns_to_temporal(value: f64, make: TemporalFamily) -> Scalar {
8361    if !value.is_finite() {
8362        return make.nat();
8363    }
8364    let clamped = value.clamp(i64::MIN as f64, i64::MAX as f64);
8365    make.make(clamped as i64)
8366}
8367
8368pub fn nanmedian(values: &[Scalar]) -> Scalar {
8369    // Preserve exact nanosecond ordering for uniformly-temporal input.
8370    // Converting to f64 loses distinct ticks beyond the 53-bit boundary.
8371    //
8372    // br-frankenpandas-adv58: Datetime64 joins Timedelta64 here, and keeps the
8373    // SAME exact i128 treatment its Timedelta sibling already had. Note that
8374    // this makes FP strictly more precise than pandas 2.2.3, which routes
8375    // datetime median through f64 and therefore snaps to a 256 ns grid at
8376    // 2020-era timestamps — returning, for an odd-count input, a Timestamp that
8377    // is not even one of the supplied values. See DISC-019.
8378    // br-frankenpandas-d7zjp: Period joins via the family enum, which — unlike
8379    // the fn-pointer constructor this replaced — can carry its freq. A
8380    // mixed-freq input is not one family, so it falls through rather than
8381    // being ordered by raw ordinal, matching pandas refusing it outright.
8382    let Some((_, make)) = collect_temporal_backing(values) else {
8383        // Not uniformly temporal: fall through to the numeric arm below.
8384        return nanmedian_numeric(values);
8385    };
8386    let mut td: Vec<i64> = values
8387        .iter()
8388        .filter(|value| !value.is_missing())
8389        .filter_map(|value| match value {
8390            Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
8391            Scalar::Period(p) => Some(p.ordinal),
8392            _ => None,
8393        })
8394        .collect();
8395    if td.is_empty() {
8396        // All-missing temporal input falls through to the numeric arm, which
8397        // yields Null(NaN). Do NOT "improve" this to a family-typed NaT: the
8398        // Null(NaN) result is pinned by the oracle test
8399        // `nanmedian_matches_numeric_and_timedelta_oracle_oabhi`, and the old
8400        // `is_timedelta_input` gate produced it by returning false for an
8401        // all-missing input. `collect_temporal_backing` marks the family on
8402        // seeing the VARIANT instead, so the fall-through has to be explicit.
8403        return nanmedian_numeric(values);
8404    }
8405    // O(n) selection instead of a full sort: order statistics depend only
8406    // on values, so the unstable partition yields the same middle values.
8407    let n = td.len();
8408    let mid = n / 2;
8409    let (left, mid_ref, _right) = td.select_nth_unstable(mid);
8410    let mid_val = *mid_ref;
8411    let median_ns = if n.is_multiple_of(2) {
8412        let lower = left.iter().copied().fold(i64::MIN, i64::max);
8413        // Toward-zero division, matching pandas where pandas is exact.
8414        (i128::from(lower) + i128::from(mid_val)) / 2
8415    } else {
8416        i128::from(mid_val)
8417    };
8418    make.make(median_ns as i64)
8419}
8420
8421/// Numeric (f64) median arm, split out of [`nanmedian`] by
8422/// br-frankenpandas-adv58 so the temporal arm can return early. Also the
8423/// fall-through for non-uniform input, e.g. mixed Datetime64 + Int64.
8424fn nanmedian_numeric(values: &[Scalar]) -> Scalar {
8425    let mut nums = collect_finite(values);
8426    if nums.is_empty() {
8427        return Scalar::Null(NullKind::NaN);
8428    }
8429    // O(n) selection instead of an O(n log n) full sort: select_nth_unstable_by
8430    // places the `mid`-th smallest at index `mid` with all smaller elements
8431    // (unordered) in the left partition. For even n the (mid-1)-th smallest is
8432    // the MAX of that left partition. Bit-identical to the sort path: order
8433    // statistics depend only on VALUES, and ties share a value, so the
8434    // unstable partition yields the same nums[mid-1]/nums[mid] the sort did.
8435    let n = nums.len();
8436    let mid = n / 2;
8437    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
8438    let (left, mid_ref, _right) = nums.select_nth_unstable_by(mid, cmp);
8439    let mid_val = *mid_ref;
8440    if n.is_multiple_of(2) {
8441        let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
8442        Scalar::Float64((lower + mid_val) / 2.0)
8443    } else {
8444        Scalar::Float64(mid_val)
8445    }
8446}
8447
8448pub fn nanvar(values: &[Scalar], ddof: usize) -> Scalar {
8449    // Per br-frankenpandas-j8ntk: Timedelta64 var preserves dtype — pandas
8450    // returns Timedelta even though variance is ns² conceptually; matching.
8451    if let Some(td) = collect_timedelta_ns_f64(values) {
8452        if td.len() <= ddof {
8453            return Scalar::Timedelta64(Timedelta::NAT);
8454        }
8455        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8456        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8457        return float_ns_to_timedelta(sum_sq / (td.len() - ddof) as f64);
8458    }
8459    let nums = collect_finite(values);
8460    if nums.len() <= ddof {
8461        return Scalar::Null(NullKind::NaN);
8462    }
8463    let mean: f64 = nums.iter().sum::<f64>() / nums.len() as f64;
8464    let sum_sq: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
8465    Scalar::Float64(sum_sq / (nums.len() - ddof) as f64)
8466}
8467
8468pub fn nanstd(values: &[Scalar], ddof: usize) -> Scalar {
8469    // Per br-frankenpandas-j8ntk: Timedelta64 std preserves dtype.
8470    //
8471    // br-frankenpandas-40ujm: Datetime64 is accepted here too, and the family
8472    // constructor is deliberately DISCARDED — the dispersion of a set of
8473    // instants is a DURATION, so datetime std returns a Timedelta, exactly as
8474    // pandas does. Verified against the oracle: pandas gives the identical
8475    // value for a Datetime64 series and a Timedelta64 series built from the
8476    // same ns (both 2592479955563784 for [0, 60d, 31d]).
8477    //
8478    // This is the ONLY reduction in the std/var/sem group that widens. pandas
8479    // RAISES for datetime64 var and sem ("does not support reduction"), so
8480    // those keep the Timedelta-only `collect_timedelta_ns_f64` gate rather than
8481    // inventing a value pandas refuses to produce.
8482    //
8483    // br-frankenpandas-d7zjp: PERIOD IS EXCLUDED HERE. pandas raises
8484    // "'PeriodArray' with dtype period[M] does not support reduction 'std'",
8485    // so widening std to Period alongside Datetime64 would invent a value —
8486    // and the family enum makes that mistake one line away, hence the guard.
8487    if let Some((td, family)) = collect_temporal_backing(values)
8488        && !matches!(family, TemporalFamily::Period(_))
8489    {
8490        if td.len() <= ddof {
8491            return Scalar::Timedelta64(Timedelta::NAT);
8492        }
8493        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8494        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8495        let var = sum_sq / (td.len() - ddof) as f64;
8496        return float_ns_to_timedelta(var.sqrt());
8497    }
8498    match nanvar(values, ddof) {
8499        Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
8500        other => other,
8501    }
8502}
8503
8504/// Standard error of the mean over non-missing values.
8505///
8506/// Matches `pd.Series.sem(ddof=1)` / `scipy.stats.sem`. Computed as
8507/// `std(values, ddof) / sqrt(n)` where `n` is the non-missing count.
8508/// Returns `Null(NaN)` when `n <= ddof`.
8509pub fn nansem(values: &[Scalar], ddof: usize) -> Scalar {
8510    // Per br-frankenpandas-j8ntk: Timedelta64 sem preserves dtype.
8511    if let Some(td) = collect_timedelta_ns_f64(values) {
8512        if td.len() <= ddof {
8513            return Scalar::Timedelta64(Timedelta::NAT);
8514        }
8515        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8516        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8517        let var = sum_sq / (td.len() - ddof) as f64;
8518        let std = var.sqrt();
8519        return float_ns_to_timedelta(std / (td.len() as f64).sqrt());
8520    }
8521    let nums = collect_finite(values);
8522    if nums.len() <= ddof {
8523        return Scalar::Null(NullKind::NaN);
8524    }
8525    let n = nums.len();
8526    let mean = nums.iter().sum::<f64>() / n as f64;
8527    let sum_sq = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
8528    let var = sum_sq / (n - ddof) as f64;
8529    let std = var.sqrt();
8530    Scalar::Float64(std / (n as f64).sqrt())
8531}
8532
8533/// Standard error of the mean as pandas' groupby, resample and pivot_table
8534/// compute it: `sqrt(var / n)` (libgroupby's `group_var(name="sem")`), which
8535/// can differ in the last bit from [`nansem`]'s `std / sqrt(n)` (Series.sem):
8536/// for `[1.0, 4.0]` this is `1.5` and nansem `1.4999999999999998`
8537/// (br-frankenpandas-7hxqv). Timedelta input keeps [`nansem`].
8538pub fn nansem_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8539    if collect_timedelta_ns_f64(values).is_some() {
8540        return nansem(values, ddof);
8541    }
8542    grouped_moments(values)
8543        .sem(ddof)
8544        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8545}
8546
8547/// pandas' compensated running sum: its cython `group_sum`, `group_mean`
8548/// and `group_cumsum` add each float as `y = v - comp; t = sum + y;
8549/// comp = t - sum - y; sum = t` (Kahan), `comp` reset to 0 where it is NaN
8550/// (an inf added; GH#53606). A plain `+=` fold differs from it in the last
8551/// bits - groupby sum of ten 0.1 is 1.0 in pandas, 0.9999999999999999
8552/// naively (br-frankenpandas-xhogl).
8553#[derive(Clone, Copy, Debug, Default, PartialEq)]
8554pub struct KahanSum {
8555    sum: f64,
8556    compensation: f64,
8557}
8558
8559impl KahanSum {
8560    /// `value` added, as pandas' group kernels add it.
8561    #[inline]
8562    pub fn add(&mut self, value: f64) {
8563        let y = value - self.compensation;
8564        let t = self.sum + y;
8565        self.compensation = t - self.sum - y;
8566        if self.compensation.is_nan() {
8567            self.compensation = 0.0;
8568        }
8569        self.sum = t;
8570    }
8571
8572    /// The sum so far.
8573    #[inline]
8574    #[must_use]
8575    pub fn sum(self) -> f64 {
8576        self.sum
8577    }
8578}
8579
8580/// pandas' online variance: its cython `group_var` folds each float as
8581/// Welford (`mean += (v - old) / n; m2 += (v - mean) * (v - old)`) and
8582/// answers `m2 / (n - ddof)`, std its square root and sem
8583/// `sqrt(m2 / (n - ddof) / n)` - where the two-pass form differs in the
8584/// last bits (a constant group's var is 0.0, not 1e-34;
8585/// br-frankenpandas-xhogl).
8586#[derive(Clone, Copy, Debug, Default, PartialEq)]
8587pub struct WelfordVar {
8588    count: usize,
8589    mean: f64,
8590    m2: f64,
8591}
8592
8593impl WelfordVar {
8594    /// `value` folded in.
8595    #[inline]
8596    pub fn add(&mut self, value: f64) {
8597        self.count += 1;
8598        let old = self.mean;
8599        self.mean += (value - old) / self.count as f64;
8600        self.m2 += (value - self.mean) * (value - old);
8601    }
8602
8603    /// The values folded in.
8604    #[must_use]
8605    pub fn count(self) -> usize {
8606        self.count
8607    }
8608
8609    /// `m2 / (n - ddof)`; None while `n <= ddof`.
8610    #[must_use]
8611    pub fn var(self, ddof: usize) -> Option<f64> {
8612        (self.count > ddof).then(|| self.m2 / (self.count - ddof) as f64)
8613    }
8614
8615    /// The square root of [`Self::var`].
8616    #[must_use]
8617    pub fn std(self, ddof: usize) -> Option<f64> {
8618        self.var(ddof).map(f64::sqrt)
8619    }
8620
8621    /// `sqrt(var / n)`, pandas' grouped sem.
8622    #[must_use]
8623    pub fn sem(self, ddof: usize) -> Option<f64> {
8624        self.var(ddof).map(|var| (var / self.count as f64).sqrt())
8625    }
8626}
8627
8628/// pandas' online skewness: its cython `group_skew` folds each float into
8629/// running moments (`delta = v - m1; delta_n = delta / n; term1 = delta *
8630/// delta_n * (n - 1); m1 += delta_n; m3 += term1 * delta_n * (n - 2) -
8631/// 3 * delta_n * m2; m2 += term1`) and answers
8632/// `n * (n - 1) ** 0.5 / (n - 2) * (m3 / m2 ** 1.5)` - 0 when `m2` is 0,
8633/// missing below 3 values - where the two-pass [`nanskew`] (Series.skew)
8634/// differs in the last bits (br-frankenpandas-vjfq9).
8635#[derive(Clone, Copy, Debug, Default, PartialEq)]
8636pub struct SkewMoments {
8637    count: usize,
8638    m1: f64,
8639    m2: f64,
8640    m3: f64,
8641}
8642
8643impl SkewMoments {
8644    /// `value` folded in.
8645    #[inline]
8646    pub fn add(&mut self, value: f64) {
8647        let before = self.count as f64;
8648        self.count += 1;
8649        let n = self.count as f64;
8650        let delta = value - self.m1;
8651        let delta_n = delta / n;
8652        let term1 = delta * delta_n * before;
8653        self.m1 += delta_n;
8654        self.m3 += term1 * delta_n * (n - 2.0) - 3.0 * delta_n * self.m2;
8655        self.m2 += term1;
8656    }
8657
8658    /// The values folded in.
8659    #[must_use]
8660    pub fn count(self) -> usize {
8661        self.count
8662    }
8663
8664    /// The bias-corrected skewness; None below 3 values.
8665    #[must_use]
8666    pub fn skew(self) -> Option<f64> {
8667        if self.count < 3 {
8668            return None;
8669        }
8670        if self.m2 == 0.0 {
8671            return Some(0.0);
8672        }
8673        let n = self.count as f64;
8674        // pandas raises with libm pow: pow(n - 1, 0.5) is not always sqrt's
8675        // correctly rounded answer (n = 2922 differs), and a constant 0.5
8676        // exponent would let LLVM substitute sqrt.
8677        let half = std::hint::black_box(0.5);
8678        Some((n * (n - 1.0).powf(half) / (n - 2.0)) * (self.m3 / self.m2.powf(1.5)))
8679    }
8680}
8681
8682/// [`nanskew`] as pandas' grouped skew: [`SkewMoments`] over the present
8683/// values.
8684#[must_use]
8685pub fn nanskew_grouped(values: &[Scalar]) -> Scalar {
8686    let mut moments = SkewMoments::default();
8687    for value in values {
8688        if value.is_missing() {
8689            continue;
8690        }
8691        if let Ok(x) = value.to_f64() {
8692            moments.add(x);
8693        }
8694    }
8695    moments
8696        .skew()
8697        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8698}
8699
8700/// The present values' Welford moments, as [`nanvar_grouped`] reads them.
8701fn grouped_moments(values: &[Scalar]) -> WelfordVar {
8702    let mut moments = WelfordVar::default();
8703    for value in values {
8704        if value.is_missing() {
8705            continue;
8706        }
8707        if let Ok(x) = value.to_f64() {
8708            moments.add(x);
8709        }
8710    }
8711    moments
8712}
8713
8714/// [`nansum`] as pandas' groupby / resample / pivot_table add floats: the
8715/// compensated [`KahanSum`] (br-frankenpandas-xhogl). Timedelta input keeps
8716/// [`nansum`]'s exact integer sum.
8717#[must_use]
8718pub fn nansum_grouped(values: &[Scalar]) -> Scalar {
8719    if collect_timedelta_ns(values).is_some() {
8720        return nansum(values);
8721    }
8722    let mut sum = KahanSum::default();
8723    for value in values {
8724        if value.is_missing() {
8725            continue;
8726        }
8727        if let Ok(x) = value.to_f64() {
8728            sum.add(x);
8729        }
8730    }
8731    Scalar::Float64(sum.sum())
8732}
8733
8734/// [`nanmean`] as pandas' grouped mean: the [`KahanSum`] over the count.
8735/// Temporal input keeps [`nanmean`].
8736#[must_use]
8737pub fn nanmean_grouped(values: &[Scalar]) -> Scalar {
8738    if collect_timedelta_ns(values).is_some() || collect_datetime_ns(values).is_some() {
8739        return nanmean(values);
8740    }
8741    let mut sum = KahanSum::default();
8742    let mut count = 0_usize;
8743    for value in values {
8744        if value.is_missing() {
8745            continue;
8746        }
8747        if let Ok(x) = value.to_f64() {
8748            sum.add(x);
8749            count += 1;
8750        }
8751    }
8752    if count == 0 {
8753        return Scalar::Null(NullKind::NaN);
8754    }
8755    Scalar::Float64(sum.sum() / count as f64)
8756}
8757
8758/// [`nanvar`] as pandas' grouped var: [`WelfordVar`]. Timedelta input keeps
8759/// [`nanvar`].
8760#[must_use]
8761pub fn nanvar_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8762    if collect_timedelta_ns_f64(values).is_some() {
8763        return nanvar(values, ddof);
8764    }
8765    grouped_moments(values)
8766        .var(ddof)
8767        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8768}
8769
8770/// [`nanstd`] as pandas' grouped std: [`WelfordVar`]. Temporal input keeps
8771/// [`nanstd`].
8772#[must_use]
8773pub fn nanstd_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8774    if collect_temporal_backing(values).is_some() {
8775        return nanstd(values, ddof);
8776    }
8777    grouped_moments(values)
8778        .std(ddof)
8779        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8780}
8781
8782/// Peak-to-peak range of non-missing values (max − min).
8783///
8784/// Matches `np.ptp` behavior on nan-safe inputs. Returns `Null(NaN)`
8785/// for empty or all-missing inputs.
8786pub fn nanptp(values: &[Scalar]) -> Scalar {
8787    // br-frankenpandas-axhhk: Datetime64 ptp is NOT a dtype-preserving sibling
8788    // of the Timedelta64 arm below — the span between two instants is a
8789    // DURATION, so pandas returns a Timedelta here (`s.max() - s.min()` on a
8790    // datetime64 Series). Subtract in i128 and narrow through the shared
8791    // opz27 helper so an unrepresentable span becomes NaT rather than a
8792    // fabricated extreme. Previously to_f64() errored on every element, `seen`
8793    // stayed false, and this returned Null(NaN).
8794    if is_datetime_input(values) {
8795        let (mut lo, mut hi) = (i64::MAX, i64::MIN);
8796        for value in values {
8797            if value.is_missing() {
8798                continue;
8799            }
8800            if let Scalar::Datetime64(ns) = value {
8801                lo = lo.min(*ns);
8802                hi = hi.max(*ns);
8803            }
8804        }
8805        return timedelta_ns_to_scalar(i128::from(hi) - i128::from(lo));
8806    }
8807    // Preserve every nanosecond in the uniformly-Timedelta64 case. Converting
8808    // to f64 before subtracting loses ranges below one f64 ULP beyond 104 days.
8809    // The Scalar fallback below retains mixed-family behavior.
8810    let (mut td_lo, mut td_hi) = (i64::MAX, i64::MIN);
8811    let mut saw_timedelta = false;
8812    let mut all_timedelta = true;
8813    for value in values {
8814        if value.is_missing() {
8815            continue;
8816        }
8817        match value {
8818            Scalar::Timedelta64(ns) => {
8819                saw_timedelta = true;
8820                td_lo = td_lo.min(*ns);
8821                td_hi = td_hi.max(*ns);
8822            }
8823            _ => {
8824                all_timedelta = false;
8825                break;
8826            }
8827        }
8828    }
8829    if all_timedelta && saw_timedelta {
8830        // Subtract in i128: the true range of two representable Timedeltas can
8831        // exceed i64 (max - min overflows), where live pandas 2.2.3 raises
8832        // OverflowError. Saturating here fabricated a finite Timedelta.max.
8833        return timedelta_ns_to_scalar(i128::from(td_hi) - i128::from(td_lo));
8834    }
8835    // Fused single-pass min/max (see `nansum`): track lo/hi while filtering, no
8836    // intermediate Vec<f64>. Bit-identical to the prior collect_finite two-pass:
8837    // `seen` is true exactly when collect_finite would be non-empty, and the
8838    // lo/hi comparisons fold the same finite values in the same order.
8839    let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
8840    let mut seen = false;
8841    for v in values {
8842        if v.is_missing() {
8843            continue;
8844        }
8845        if let Ok(x) = v.to_f64() {
8846            seen = true;
8847            if x < lo {
8848                lo = x;
8849            }
8850            if x > hi {
8851                hi = x;
8852            }
8853        }
8854    }
8855    if !seen {
8856        return Scalar::Null(NullKind::NaN);
8857    }
8858    Scalar::Float64(hi - lo)
8859}
8860
8861/// Sample skewness (bias-corrected, Fisher-Pearson) over non-missing values.
8862///
8863/// Matches `pd.Series.skew()`. Requires at least 3 non-missing values;
8864/// returns `Null(NaN)` otherwise, and when the sample standard deviation
8865/// is zero.
8866pub fn nanskew(values: &[Scalar]) -> Scalar {
8867    let nums = collect_finite(values);
8868    let n = nums.len() as f64;
8869    if n < 3.0 {
8870        return Scalar::Null(NullKind::NaN);
8871    }
8872    let mean = nums.iter().sum::<f64>() / n;
8873    // Accumulate both central moments while the collected values are hot. Each
8874    // sum still observes the same terms in the same order as the former two
8875    // iterator passes, preserving floating-point results bit-for-bit.
8876    let (mut m2, mut m3) = (0.0_f64, 0.0_f64);
8877    for x in nums {
8878        let delta = x - mean;
8879        // d2 reuse: 2 multiplies per element instead of 3. powi(3) lowers to two
8880        // multiplies of {delta, delta*delta}, and float MULTIPLY is commutative
8881        // bit-for-bit, so both sums observe the identical terms — the comment above
8882        // about preserving results bit-for-bit still holds. No ADDITION order changed.
8883        // (br-frankenpandas-8s4mb)
8884        let d2 = delta * delta;
8885        m2 += d2;
8886        m3 += d2 * delta;
8887    }
8888    let s2 = m2 / (n - 1.0);
8889    if s2 == 0.0 {
8890        return Scalar::Float64(0.0);
8891    }
8892    let s3 = s2.powf(1.5);
8893    Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
8894}
8895
8896/// Excess sample kurtosis (Fisher's definition, bias-corrected) over
8897/// non-missing values.
8898///
8899/// Matches `pd.Series.kurt()`. Requires at least 4 non-missing values;
8900/// returns `Null(NaN)` otherwise, and when the sample standard deviation
8901/// is zero.
8902pub fn nankurt(values: &[Scalar]) -> Scalar {
8903    let nums = collect_finite(values);
8904    let n = nums.len() as f64;
8905    if n < 4.0 {
8906        return Scalar::Null(NullKind::NaN);
8907    }
8908    let mean = nums.iter().sum::<f64>() / n;
8909    // Accumulate both central moments while the collected values are hot. Each
8910    // sum still observes the same terms in the same order as the former two
8911    // iterator passes, preserving floating-point results bit-for-bit.
8912    let (mut m2, mut m4) = (0.0_f64, 0.0_f64);
8913    for x in nums {
8914        let delta = x - mean;
8915        // d2 reuse; see `nanskew`. powi(4) lowers to (d*d)*(d*d), which is exactly
8916        // d2 * d2, so this is bit-identical.
8917        let d2 = delta * delta;
8918        m2 += d2;
8919        m4 += d2 * d2;
8920    }
8921    let s2 = m2 / (n - 1.0);
8922    if s2 == 0.0 {
8923        return Scalar::Float64(0.0);
8924    }
8925    let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
8926    let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
8927    Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
8928}
8929
8930/// Product of non-missing values. Returns 1.0 for empty input (matching pandas).
8931pub fn nanprod(values: &[Scalar]) -> Scalar {
8932    // Per br-frankenpandas-szq6a: pandas raises TypeError on
8933    // td_series.prod() because Timedelta² has no dimension. Returning the
8934    // misleading Float64(1.0) (empty-iterator default after collect_finite
8935    // drops every Timedelta64) is worse than surfacing missing. NaT
8936    // propagates the "type-incompatible" signal in lieu of a Result-level
8937    // error.
8938    if is_timedelta_input(values) {
8939        return Scalar::Null(NullKind::NaN);
8940    }
8941    // Fused single-pass fold (see `nansum`): filter missing / non-coercible and
8942    // multiply in one scan, no intermediate Vec<f64>. Bit-identical to
8943    // `collect_finite(..).iter().product()`: same finite values, same order,
8944    // same f64 `*` (Product for f64 == fold(1.0, *)); empty -> 1.0.
8945    let mut prod = 1.0_f64;
8946    for v in values {
8947        if v.is_missing() {
8948            continue;
8949        }
8950        if let Ok(x) = v.to_f64() {
8951            prod *= x;
8952        }
8953    }
8954    Scalar::Float64(prod)
8955}
8956
8957/// Cumulative sum respecting null propagation.
8958///
8959/// Per br-frankenpandas-x0x91: detect uniformly-Timedelta64 input
8960/// (allowing Null/NAT missing markers). Returns true when at least one
8961/// non-missing value is Timedelta64 and no other dtype appears.
8962fn is_timedelta_input(values: &[Scalar]) -> bool {
8963    let mut saw_td = false;
8964    for v in values {
8965        if v.is_missing() {
8966            continue;
8967        }
8968        match v {
8969            Scalar::Timedelta64(_) => saw_td = true,
8970            _ => return false,
8971        }
8972    }
8973    saw_td
8974}
8975
8976/// Datetime64 mirror of [`collect_timedelta_ns`], per br-frankenpandas-adv58.
8977///
8978/// Note the deliberate difference from [`is_datetime_input`]: the family is
8979/// marked on seeing the *variant*, before the missing check, so an ALL-NaT
8980/// datetime input still reports as the Datetime family with `count == 0`. That
8981/// is what lets `nanmean` return `Datetime64(NaT)` — preserving dtype the way
8982/// pandas does — instead of degrading to a numeric NaN. `collect_timedelta_ns`
8983/// has used this convention all along; matching it keeps the two families
8984/// symmetric.
8985fn collect_datetime_ns(values: &[Scalar]) -> Option<(i128, usize)> {
8986    let mut sum: i128 = 0;
8987    let mut count: usize = 0;
8988    let mut saw_datetime = false;
8989    for v in values {
8990        match v {
8991            Scalar::Datetime64(ns) => {
8992                saw_datetime = true;
8993                if v.is_missing() {
8994                    continue;
8995                }
8996                sum += i128::from(*ns);
8997                count += 1;
8998            }
8999            _ if v.is_missing() => continue,
9000            _ => return None,
9001        }
9002    }
9003    if saw_datetime {
9004        Some((sum, count))
9005    } else {
9006        None
9007    }
9008}
9009
9010/// Sibling of [`is_timedelta_input`] for Datetime64, per br-frankenpandas-axhhk.
9011///
9012/// `Datetime64::to_f64()` errors exactly like `Timedelta64::to_f64()` does, so
9013/// every reduction that routed datetimes through the f64 catch-all silently
9014/// produced `Null(NaN)`. Datetime64 orders exactly like its i64 nanosecond
9015/// backing, and NaT (`Timestamp::NAT`) is already filtered by `is_missing`.
9016fn is_datetime_input(values: &[Scalar]) -> bool {
9017    let mut saw_dt = false;
9018    for v in values {
9019        if v.is_missing() {
9020            continue;
9021        }
9022        match v {
9023            Scalar::Datetime64(_) => saw_dt = true,
9024            _ => return false,
9025        }
9026    }
9027    saw_dt
9028}
9029
9030/// Returns true for uniformly-Int64 input with optional missing markers.
9031fn is_int64_input(values: &[Scalar]) -> bool {
9032    let mut saw_int = false;
9033    for value in values {
9034        if value.is_missing() {
9035            continue;
9036        }
9037        match value {
9038            Scalar::Int64(_) => saw_int = true,
9039            _ => return false,
9040        }
9041    }
9042    saw_int
9043}
9044
9045/// First-position arg-extremum over a uniformly i64-backed scalar family.
9046/// True when every non-missing value is an Interval, per br-frankenpandas-2h9dm.
9047fn is_interval_input(values: &[Scalar]) -> bool {
9048    let mut saw_interval = false;
9049    for v in values {
9050        if v.is_missing() {
9051            continue;
9052        }
9053        match v {
9054            Scalar::Interval(_) => saw_interval = true,
9055            _ => return false,
9056        }
9057    }
9058    saw_interval
9059}
9060
9061/// Positional extreme over a uniformly-Interval input, per br-frankenpandas-2h9dm.
9062///
9063/// Intervals cannot use [`nanarg_i64`] (they are two f64s, not an i64 newtype)
9064/// and cannot use the f64 fallback in the callers (`to_f64` errors on them), so
9065/// they get this dedicated lexicographic (left, right) walk. `closed` is not
9066/// part of the comparison, for the reasons documented on `nanmin`.
9067///
9068/// Returns `None` if any bound is NaN: such an interval is not orderable and
9069/// pandas will not even construct one, so an arbitrary index would be worse
9070/// than declining. This is also why the comparison is a plain `<`/`>` on a
9071/// tuple rather than `partial_cmp().unwrap()`, which would panic.
9072fn nanarg_interval(values: &[Scalar], find_max: bool) -> Option<usize> {
9073    let mut best: Option<(usize, (f64, f64))> = None;
9074    for (index, value) in values.iter().enumerate() {
9075        if value.is_missing() {
9076            continue;
9077        }
9078        let Scalar::Interval(iv) = value else {
9079            continue;
9080        };
9081        if iv.left.is_nan() || iv.right.is_nan() {
9082            return None;
9083        }
9084        let key = (iv.left, iv.right);
9085        match best {
9086            None => best = Some((index, key)),
9087            // Strict comparison keeps the FIRST occurrence of a duplicated
9088            // extreme, which is what pandas' idxmin/idxmax return.
9089            Some((_, current)) if (find_max && key > current) || (!find_max && key < current) => {
9090                best = Some((index, key));
9091            }
9092            _ => {}
9093        }
9094    }
9095    best.map(|(index, _)| index)
9096}
9097
9098fn nanarg_i64(values: &[Scalar], find_max: bool) -> Option<usize> {
9099    let mut best: Option<(usize, i64)> = None;
9100    for (index, value) in values.iter().enumerate() {
9101        if value.is_missing() {
9102            continue;
9103        }
9104        // br-frankenpandas-axhhk: Datetime64 joins the typed i64 families here.
9105        // Its ns backing orders identically, and routing it through the f64
9106        // path instead returned None for any 2+-element datetime input.
9107        //
9108        // br-frankenpandas-d7zjp: Period cannot join this or-pattern — it is a
9109        // STRUCT, not an i64 newtype — so it contributes its ordinal here. The
9110        // caller has already established a single freq via
9111        // `collect_temporal_backing`, so these ordinals are comparable.
9112        let candidate = match value {
9113            Scalar::Int64(raw) | Scalar::Timedelta64(raw) | Scalar::Datetime64(raw) => raw,
9114            Scalar::Period(p) => &p.ordinal,
9115            _ => continue,
9116        };
9117        match best {
9118            None => best = Some((index, *candidate)),
9119            Some((_, current))
9120                if (find_max && *candidate > current) || (!find_max && *candidate < current) =>
9121            {
9122                best = Some((index, *candidate));
9123            }
9124            _ => {}
9125        }
9126    }
9127    best.map(|(index, _)| index)
9128}
9129
9130/// Per br-frankenpandas-x0x91: cumulative running aggregation over a
9131/// uniformly-Timedelta64 input. NaT/Null positions emit NaT and skip
9132/// the accumulator. Saturating i128 keeps overflow contained at i64
9133/// bounds when emitting.
9134fn timedelta_cumulative<F>(values: &[Scalar], init: i128, mut step: F) -> Vec<Scalar>
9135where
9136    F: FnMut(i128, i128) -> i128,
9137{
9138    let mut out = Vec::with_capacity(values.len());
9139    let mut running: i128 = init;
9140    for v in values {
9141        if v.is_missing() {
9142            out.push(Scalar::Null(NullKind::NaT));
9143            continue;
9144        }
9145        if let Scalar::Timedelta64(ns) = v {
9146            // `running` is exact: i128 has enough headroom that folding i64
9147            // nanoseconds cannot overflow it for any constructible input. Only
9148            // the narrowing to the output element can fail, so a running sum
9149            // that overflows i64 and later returns to range emits its true
9150            // value again instead of poisoning the tail — nothing is
9151            // fabricated at any index.
9152            running = step(running, i128::from(*ns));
9153            out.push(timedelta_ns_to_scalar(running));
9154        } else {
9155            out.push(Scalar::Null(NullKind::NaT));
9156        }
9157    }
9158    out
9159}
9160
9161/// Per br-frankenpandas-x0x91: running extrema (min/max) over a
9162/// uniformly-Timedelta64 input. `sentinel` is the identity element
9163/// (i64::MAX for min, i64::MIN for max) used until the first
9164/// non-missing value initializes the accumulator.
9165/// `make` builds the output scalar from the running ns value, so the same
9166/// walk serves Timedelta64 and — per br-frankenpandas-axhhk — Datetime64,
9167/// whose running extrema are Timestamps rather than durations.
9168fn timedelta_cumulative_extrema<F>(
9169    values: &[Scalar],
9170    sentinel: i64,
9171    make: TemporalFamily,
9172    mut step: F,
9173) -> Vec<Scalar>
9174where
9175    F: FnMut(i64, i64) -> i64,
9176{
9177    let mut out = Vec::with_capacity(values.len());
9178    let mut running: Option<i64> = None;
9179    for v in values {
9180        if v.is_missing() {
9181            out.push(Scalar::Null(NullKind::NaT));
9182            continue;
9183        }
9184        // br-frankenpandas-d7zjp: a Period contributes its ordinal.
9185        let raw = match v {
9186            Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
9187            Scalar::Period(p) => Some(p.ordinal),
9188            _ => None,
9189        };
9190        if let Some(ns) = raw.as_ref() {
9191            let new_val = match running {
9192                Some(prev) => step(prev, *ns),
9193                None => *ns,
9194            };
9195            running = Some(new_val);
9196            out.push(make.make(new_val));
9197        } else {
9198            out.push(Scalar::Null(NullKind::NaT));
9199        }
9200    }
9201    let _ = sentinel; // silence unused warning if closure ignores it
9202    out
9203}
9204
9205/// Matches `np.nancumsum` / `pd.Series.cumsum()`. Missing input positions
9206/// pass through as `Null(NaN)` in the output; the running sum ignores
9207/// those positions when accumulating.
9208/// Cumulative sum under an explicit overflow policy.
9209///
9210/// br-frankenpandas-fyr1z-wrap-signoff-s4lkx, DECIDED BY THE MAINTAINER: under
9211/// [`OverflowPolicy::Strict`] this REPRODUCES pandas' silent int64 wraparound,
9212/// because STRICT means bit-for-bit observable parity with the incumbent
9213/// including its quirks.
9214///
9215/// Verified against live pandas 2.2.3:
9216/// `Series([Timedelta.max, Timedelta.max]).cumsum()` returns
9217/// `[9223372036854775807, -2]` and the three-element case
9218/// `[max, -2, 9223372036854775805]` — exactly `wrapping_add` accumulation in
9219/// i64. Note the third element proves the accumulator KEEPS WRAPPING rather
9220/// than sticking: it is `(-2).wrapping_add(max)`.
9221///
9222/// Under every other policy this delegates to [`nancumsum`], which keeps the
9223/// exact-i128 accumulation and NaT-on-unrepresentable behaviour from
9224/// br-frankenpandas-opz27. See DISC-020.
9225#[must_use]
9226pub fn nancumsum_with_policy(values: &[Scalar], policy: OverflowPolicy) -> Vec<Scalar> {
9227    if !matches!(policy, OverflowPolicy::Strict) || !is_timedelta_input(values) {
9228        return nancumsum(values);
9229    }
9230    let mut out = Vec::with_capacity(values.len());
9231    let mut running: i64 = 0;
9232    for value in values {
9233        if value.is_missing() {
9234            out.push(Scalar::Null(NullKind::NaT));
9235            continue;
9236        }
9237        if let Scalar::Timedelta64(ns) = value {
9238            // Deliberately WRAPPING, not checked: this is the incumbent's
9239            // observable behaviour and STRICT exists to reproduce it.
9240            running = running.wrapping_add(*ns);
9241            out.push(Scalar::Timedelta64(running));
9242        } else {
9243            out.push(Scalar::Null(NullKind::NaT));
9244        }
9245    }
9246    out
9247}
9248
9249pub fn nancumsum(values: &[Scalar]) -> Vec<Scalar> {
9250    // Per br-frankenpandas-x0x91: when input is uniformly Timedelta64 (with
9251    // optional NaT/Null missing markers), preserve Timedelta dtype to match
9252    // pandas td_series.cumsum() returning Timedelta64.
9253    if is_timedelta_input(values) {
9254        return timedelta_cumulative(values, 0_i128, |acc, x| acc.saturating_add(x));
9255    }
9256    let mut out = Vec::with_capacity(values.len());
9257    let mut running = 0.0_f64;
9258    for v in values {
9259        if v.is_missing() {
9260            out.push(Scalar::Null(NullKind::NaN));
9261            continue;
9262        }
9263        match v.to_f64() {
9264            Ok(x) if !x.is_nan() => {
9265                running += x;
9266                out.push(Scalar::Float64(running));
9267            }
9268            _ => out.push(Scalar::Null(NullKind::NaN)),
9269        }
9270    }
9271    out
9272}
9273
9274/// Cumulative product respecting null propagation.
9275///
9276/// Matches `np.nancumprod` / `pd.Series.cumprod()`. Missing positions
9277/// pass through as `Null(NaN)` without advancing the running product.
9278pub fn nancumprod(values: &[Scalar]) -> Vec<Scalar> {
9279    let mut out = Vec::with_capacity(values.len());
9280    let mut running = 1.0_f64;
9281    for v in values {
9282        if v.is_missing() {
9283            out.push(Scalar::Null(NullKind::NaN));
9284            continue;
9285        }
9286        match v.to_f64() {
9287            Ok(x) if !x.is_nan() => {
9288                running *= x;
9289                out.push(Scalar::Float64(running));
9290            }
9291            _ => out.push(Scalar::Null(NullKind::NaN)),
9292        }
9293    }
9294    out
9295}
9296
9297/// Cumulative maximum respecting null propagation.
9298///
9299/// Matches `pd.Series.cummax()`. Missing positions pass through as
9300/// `Null(NaN)` without updating the running maximum. The first
9301/// non-missing value initializes the running maximum.
9302pub fn nancummax(values: &[Scalar]) -> Vec<Scalar> {
9303    // Per br-frankenpandas-x0x91 (Timedelta64), -axhhk (Datetime64) and
9304    // -d7zjp (Period): every uniformly-temporal family preserves its dtype
9305    // here. Without this the f64 path below errors on every element and
9306    // produces an all-NaN column. A mixed-freq Period input is not one family,
9307    // so it correctly does not take this path.
9308    if let Some((_, family)) = collect_temporal_backing(values) {
9309        return timedelta_cumulative_extrema(values, i64::MAX, family, |acc, x| acc.max(x));
9310    }
9311    let mut out = Vec::with_capacity(values.len());
9312    let mut running: Option<f64> = None;
9313    for v in values {
9314        if v.is_missing() {
9315            out.push(Scalar::Null(NullKind::NaN));
9316            continue;
9317        }
9318        match v.to_f64() {
9319            Ok(x) if !x.is_nan() => {
9320                let new_val = match running {
9321                    Some(prev) => prev.max(x),
9322                    None => x,
9323                };
9324                running = Some(new_val);
9325                out.push(Scalar::Float64(new_val));
9326            }
9327            _ => out.push(Scalar::Null(NullKind::NaN)),
9328        }
9329    }
9330    out
9331}
9332
9333/// Cumulative minimum respecting null propagation.
9334///
9335/// Matches `pd.Series.cummin()`. Symmetric to `nancummax`.
9336pub fn nancummin(values: &[Scalar]) -> Vec<Scalar> {
9337    // Per br-frankenpandas-x0x91: Timedelta64 preserves dtype.
9338    if is_timedelta_input(values) {
9339        return timedelta_cumulative_extrema(
9340            values,
9341            i64::MIN,
9342            TemporalFamily::Timedelta,
9343            |acc, x| acc.min(x),
9344        );
9345    }
9346    // br-frankenpandas-axhhk / -d7zjp: Datetime64 and Period siblings.
9347    if let Some((_, family)) = collect_temporal_backing(values) {
9348        return timedelta_cumulative_extrema(values, i64::MIN, family, |acc, x| acc.min(x));
9349    }
9350    let mut out = Vec::with_capacity(values.len());
9351    let mut running: Option<f64> = None;
9352    for v in values {
9353        if v.is_missing() {
9354            out.push(Scalar::Null(NullKind::NaN));
9355            continue;
9356        }
9357        match v.to_f64() {
9358            Ok(x) if !x.is_nan() => {
9359                let new_val = match running {
9360                    Some(prev) => prev.min(x),
9361                    None => x,
9362                };
9363                running = Some(new_val);
9364                out.push(Scalar::Float64(new_val));
9365            }
9366            _ => out.push(Scalar::Null(NullKind::NaN)),
9367        }
9368    }
9369    out
9370}
9371
9372/// Linear-interpolation quantile over non-missing numeric values.
9373///
9374/// Matches `np.nanquantile(values, q)` with `interpolation='linear'`.
9375/// Returns `Null(NaN)` for empty inputs or when `q` is outside
9376/// `[0.0, 1.0]`.
9377pub fn nanquantile(values: &[Scalar], q: f64) -> Scalar {
9378    if !(0.0..=1.0).contains(&q) {
9379        return Scalar::Null(NullKind::NaN);
9380    }
9381    // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
9382    // Timedelta64 with linear-interpolated ns. Was silently NaN before.
9383    if let Some((mut td, make)) = collect_temporal_backing(values) {
9384        if td.is_empty() {
9385            return make.nat();
9386        }
9387        let n = td.len();
9388        if n == 1 {
9389            return float_ns_to_temporal(td[0], make);
9390        }
9391        let pos = q * (n - 1) as f64;
9392        let lo = pos.floor() as usize;
9393        let hi = pos.ceil() as usize;
9394        // O(n) selection instead of a full sort (see the numeric arm below):
9395        // select the lo-th order statistic; the (lo+1)-th is the MIN of the
9396        // right partition. Bit-identical (finite ns, values-only order stats).
9397        let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9398        let (_left, lo_ref, right) = td.select_nth_unstable_by(lo, cmp);
9399        let lo_val = *lo_ref;
9400        let ns = if lo == hi {
9401            lo_val
9402        } else {
9403            let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9404            let weight = pos - lo as f64;
9405            lo_val + (hi_val - lo_val) * weight
9406        };
9407        return float_ns_to_temporal(ns, make);
9408    }
9409    let mut nums = collect_finite(values);
9410    if nums.is_empty() {
9411        return Scalar::Null(NullKind::NaN);
9412    }
9413    let n = nums.len();
9414    if n == 1 {
9415        return Scalar::Float64(nums[0]);
9416    }
9417    let pos = q * (n - 1) as f64;
9418    let lo = pos.floor() as usize;
9419    let hi = pos.ceil() as usize;
9420    // O(n) selection instead of a full sort: select the `lo`-th order statistic;
9421    // when interpolation is needed (hi == lo+1) the (lo+1)-th smallest is the
9422    // MIN of the right partition. Bit-identical to the sort path (same
9423    // nums[lo]/nums[hi] values, since order statistics depend only on values).
9424    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9425    let (_left, lo_ref, right) = nums.select_nth_unstable_by(lo, cmp);
9426    let lo_val = *lo_ref;
9427    if lo == hi {
9428        return Scalar::Float64(lo_val);
9429    }
9430    let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9431    let weight = pos - lo as f64;
9432    Scalar::Float64(lo_val + (hi_val - lo_val) * weight)
9433}
9434
9435/// Position (in the original slice) of the non-missing maximum.
9436///
9437/// Matches `np.nanargmax`. Returns `None` if every value is missing.
9438/// Ties resolve to the first position seen (matching numpy).
9439pub fn nanargmax(values: &[Scalar]) -> Option<usize> {
9440    // Compare typed 64-bit families directly: f64 coercion loses ordering for
9441    // adjacent Int64 values beyond the 53-bit exactness boundary.
9442    // br-frankenpandas-axhhk: Datetime64 belongs here too — it not only loses
9443    // ordering under f64, its to_f64() errors outright, so it returned None.
9444    if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9445        return nanarg_i64(values, true);
9446    }
9447    // br-frankenpandas-2h9dm: Intervals order lexicographically by
9448    // (left, right) and fit neither the i64 walk above nor the f64 fallback
9449    // below, whose to_f64() errors on them — so they returned None.
9450    if is_interval_input(values) {
9451        return nanarg_interval(values, true);
9452    }
9453    let mut best: Option<(usize, f64)> = None;
9454    for (i, v) in values.iter().enumerate() {
9455        if v.is_missing() {
9456            continue;
9457        }
9458        if let Ok(x) = v.to_f64() {
9459            if x.is_nan() {
9460                continue;
9461            }
9462            match best {
9463                None => best = Some((i, x)),
9464                Some((_, cur)) if x > cur => best = Some((i, x)),
9465                _ => {}
9466            }
9467        }
9468    }
9469    best.map(|(i, _)| i)
9470}
9471
9472/// Position (in the original slice) of the non-missing minimum.
9473///
9474/// Matches `np.nanargmin`. Returns `None` if every value is missing.
9475pub fn nanargmin(values: &[Scalar]) -> Option<usize> {
9476    // See nanargmax: preserve exact ordering for typed 64-bit families
9477    // (Datetime64 included, per br-frankenpandas-axhhk).
9478    if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9479        return nanarg_i64(values, false);
9480    }
9481    // br-frankenpandas-2h9dm: Interval sibling of the branch in `nanargmax`.
9482    if is_interval_input(values) {
9483        return nanarg_interval(values, false);
9484    }
9485    let mut best: Option<(usize, f64)> = None;
9486    for (i, v) in values.iter().enumerate() {
9487        if v.is_missing() {
9488            continue;
9489        }
9490        if let Ok(x) = v.to_f64() {
9491            if x.is_nan() {
9492                continue;
9493            }
9494            match best {
9495                None => best = Some((i, x)),
9496                Some((_, cur)) if x < cur => best = Some((i, x)),
9497                _ => {}
9498            }
9499        }
9500    }
9501    best.map(|(i, _)| i)
9502}
9503
9504/// Count of unique non-missing values.
9505pub fn nannunique(values: &[Scalar]) -> Scalar {
9506    use rustc_hash::FxHashSet;
9507    #[derive(Hash, PartialEq, Eq)]
9508    enum ScalarKey<'a> {
9509        Bool(bool),
9510        Int64(i64),
9511        FloatBits(u64),
9512        Utf8(&'a str),
9513        Timedelta64(i64),
9514        Datetime64(i64),
9515        Period(i64, PeriodFreq),
9516        Interval(u64, u64, IntervalClosed),
9517        // An object cell counts by its repr (pandas hashes the object; a
9518        // list would be unhashable there).
9519        Object(String),
9520    }
9521
9522    let mut seen = FxHashSet::default();
9523    for val in values {
9524        if val.is_missing() {
9525            continue;
9526        }
9527        let key = match val {
9528            Scalar::Bool(v) => ScalarKey::Bool(*v),
9529            Scalar::Int64(v) => ScalarKey::Int64(*v),
9530            Scalar::Float64(v) => {
9531                let normalized = if *v == 0.0 { 0.0 } else { *v };
9532                ScalarKey::FloatBits(normalized.to_bits())
9533            }
9534            Scalar::Utf8(v) => ScalarKey::Utf8(v.as_str()),
9535            Scalar::Timedelta64(v) => ScalarKey::Timedelta64(*v),
9536            Scalar::Datetime64(v) => ScalarKey::Datetime64(*v),
9537            Scalar::Period(p) => ScalarKey::Period(p.ordinal, p.freq),
9538            Scalar::Interval(v) => ScalarKey::Interval(
9539                normalized_float_bits(v.left),
9540                normalized_float_bits(v.right),
9541                v.closed,
9542            ),
9543            Scalar::Object(object) => ScalarKey::Object(object.repr()),
9544            Scalar::Null(_) => continue,
9545        };
9546        seen.insert(key);
9547    }
9548    Scalar::Int64(seen.len() as i64)
9549}
9550
9551fn normalized_float_bits(value: f64) -> u64 {
9552    let normalized = if value == 0.0 { 0.0 } else { value };
9553    normalized.to_bits()
9554}
9555
9556// ── Interval types (br-frankenpandas-j8k4 Phase 1) ──────────────────────
9557//
9558// Scaffolding for pandas `pd.Interval` / `pd.IntervalIndex` / `pd.IntervalDtype`.
9559//
9560// Phase 1 ships float-valued intervals only (matches `cut`/`qcut` output on
9561// numeric bins — the dominant pandas use case). Generic-subtype intervals
9562// over Int64 / Timestamp are deferred to Phase 2 alongside the DType::Interval
9563// enum-variant wiring. See br-j8k4 for the phased roadmap.
9564//
9565// Semantics mirror pandas: closed tells which endpoints are included.
9566//   Left    → [left, right)
9567//   Right   → (left, right]       ← pandas default
9568//   Both    → [left, right]
9569//   Neither → (left, right)
9570
9571/// Endpoint-inclusion policy for an `Interval`.
9572///
9573/// Matches pandas `pd.Interval.closed` / `pd.IntervalDtype.closed` string
9574/// values ("left" / "right" / "both" / "neither").
9575#[derive(
9576    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
9577)]
9578#[serde(rename_all = "snake_case")]
9579#[non_exhaustive]
9580pub enum IntervalClosed {
9581    /// `[left, right)` — left-inclusive, right-exclusive.
9582    Left,
9583    /// `(left, right]` — left-exclusive, right-inclusive. Pandas default.
9584    #[default]
9585    Right,
9586    /// `[left, right]` — both endpoints included.
9587    Both,
9588    /// `(left, right)` — neither endpoint included.
9589    Neither,
9590}
9591
9592impl IntervalClosed {
9593    /// Left endpoint included?
9594    #[must_use]
9595    pub fn left_closed(self) -> bool {
9596        matches!(self, Self::Left | Self::Both)
9597    }
9598
9599    /// Right endpoint included?
9600    #[must_use]
9601    pub fn right_closed(self) -> bool {
9602        matches!(self, Self::Right | Self::Both)
9603    }
9604}
9605
9606impl std::fmt::Display for IntervalClosed {
9607    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9608        match self {
9609            Self::Left => write!(f, "left"),
9610            Self::Right => write!(f, "right"),
9611            Self::Both => write!(f, "both"),
9612            Self::Neither => write!(f, "neither"),
9613        }
9614    }
9615}
9616
9617/// The type of an interval's endpoints, pandas' `interval[int64]` or
9618/// `interval[float64]` subtype: integer endpoints print without '.0'
9619/// (`pd.cut(s, [0, 3, 6])` is `(0, 3]`, where float edges are `(0.0, 3.0]`).
9620/// The endpoints themselves are `f64` either way (fvsao.54).
9621#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
9622#[serde(rename_all = "snake_case")]
9623pub enum IntervalSubtype {
9624    #[default]
9625    Float64,
9626    Int64,
9627}
9628
9629impl IntervalSubtype {
9630    /// Whether this is the float subtype (serde skips it, the default).
9631    #[must_use]
9632    pub const fn is_float(&self) -> bool {
9633        matches!(self, Self::Float64)
9634    }
9635
9636    /// The subtype's dtype name ('int64' / 'float64').
9637    #[must_use]
9638    pub const fn name(&self) -> &'static str {
9639        match self {
9640            Self::Float64 => "float64",
9641            Self::Int64 => "int64",
9642        }
9643    }
9644}
9645
9646/// A bounded numeric interval between two `f64` endpoints.
9647///
9648/// Matches `pd.Interval(left, right, closed)` on the numeric-subtype path.
9649/// Accessors match pandas: `.left`, `.right`, `.closed`, `.length`, `.mid`,
9650/// `.contains`, `.is_empty`, `.overlaps`. Equality ignores the `subtype`, as
9651/// pandas' `Interval(0, 3) == Interval(0.0, 3.0)`.
9652#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
9653pub struct Interval {
9654    pub left: f64,
9655    pub right: f64,
9656    #[serde(default)]
9657    pub closed: IntervalClosed,
9658    /// The endpoints' type as pandas reports and prints it.
9659    #[serde(default, skip_serializing_if = "IntervalSubtype::is_float")]
9660    pub subtype: IntervalSubtype,
9661}
9662
9663impl PartialEq for Interval {
9664    fn eq(&self, other: &Self) -> bool {
9665        self.left == other.left && self.right == other.right && self.closed == other.closed
9666    }
9667}
9668
9669/// An interval as a label (an IntervalIndex's; br-frankenpandas-c27hq): its
9670/// endpoints compare as floats, so only an interval with a NaN endpoint,
9671/// which pandas never builds, is unequal to itself.
9672impl Eq for Interval {}
9673
9674impl Interval {
9675    /// An endpoint as it compares: -0.0 is 0.0, as `==` has it.
9676    fn endpoint_key(value: f64) -> f64 {
9677        if value == 0.0 { 0.0 } else { value }
9678    }
9679}
9680
9681/// Hashed as it compares: the endpoints (-0.0 as 0.0) and the closed side;
9682/// the subtype is not part of the value.
9683impl std::hash::Hash for Interval {
9684    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
9685        Self::endpoint_key(self.left).to_bits().hash(state);
9686        Self::endpoint_key(self.right).to_bits().hash(state);
9687        self.closed.hash(state);
9688    }
9689}
9690
9691/// pandas' IntervalIndex order: by the left endpoint, then the right, then
9692/// the closed side.
9693impl Ord for Interval {
9694    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
9695        Self::endpoint_key(self.left)
9696            .total_cmp(&Self::endpoint_key(other.left))
9697            .then_with(|| {
9698                Self::endpoint_key(self.right).total_cmp(&Self::endpoint_key(other.right))
9699            })
9700            .then_with(|| self.closed.cmp(&other.closed))
9701    }
9702}
9703
9704impl PartialOrd for Interval {
9705    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
9706        Some(self.cmp(other))
9707    }
9708}
9709
9710impl Interval {
9711    /// Construct an interval. No validation on `left <= right` — pandas also
9712    /// accepts reversed intervals (they're non-empty only if empty-by-design).
9713    #[must_use]
9714    pub const fn new(left: f64, right: f64, closed: IntervalClosed) -> Self {
9715        Self {
9716            left,
9717            right,
9718            closed,
9719            subtype: IntervalSubtype::Float64,
9720        }
9721    }
9722
9723    /// This interval with integer endpoints (pandas' `interval[int64]`)
9724    /// when both are whole numbers; unchanged otherwise.
9725    #[must_use]
9726    pub fn with_int_endpoints(self) -> Self {
9727        if self.left.fract() == 0.0 && self.right.fract() == 0.0 {
9728            Self {
9729                subtype: IntervalSubtype::Int64,
9730                ..self
9731            }
9732        } else {
9733            self
9734        }
9735    }
9736
9737    /// `right - left` (pandas `.length`). Negative for reversed intervals.
9738    #[must_use]
9739    pub fn length(&self) -> f64 {
9740        self.right - self.left
9741    }
9742
9743    /// Midpoint `(left + right) / 2` (pandas `.mid`).
9744    #[must_use]
9745    pub fn mid(&self) -> f64 {
9746        (self.left + self.right) / 2.0
9747    }
9748
9749    /// Empty iff endpoints coincide AND at least one side is open.
9750    /// Pandas semantics: `pd.Interval(3, 3, 'right').is_empty → True`.
9751    #[must_use]
9752    pub fn is_empty(&self) -> bool {
9753        self.left == self.right && !matches!(self.closed, IntervalClosed::Both)
9754    }
9755
9756    /// Does `value` fall inside this interval?
9757    ///
9758    /// NaN always returns false, matching pandas `pd.Interval.__contains__`
9759    /// behavior (NaN doesn't compare equal to anything).
9760    #[must_use]
9761    pub fn contains(&self, value: f64) -> bool {
9762        if value.is_nan() {
9763            return false;
9764        }
9765        let left_ok = if self.closed.left_closed() {
9766            value >= self.left
9767        } else {
9768            value > self.left
9769        };
9770        let right_ok = if self.closed.right_closed() {
9771            value <= self.right
9772        } else {
9773            value < self.right
9774        };
9775        left_ok && right_ok
9776    }
9777
9778    /// Do `self` and `other` share any point?
9779    ///
9780    /// Matches `pd.Interval.overlaps(other)`. Two intervals overlap iff the
9781    /// max of their lefts is less than the min of their rights, with
9782    /// endpoint-inclusion determining the strictness of the comparison when
9783    /// they touch exactly.
9784    #[must_use]
9785    pub fn overlaps(&self, other: &Self) -> bool {
9786        if self.left > other.right || other.left > self.right {
9787            return false;
9788        }
9789        // Touching-at-a-point: overlap iff both sides at that touchpoint are closed.
9790        if self.right == other.left {
9791            return self.closed.right_closed() && other.closed.left_closed();
9792        }
9793        if other.right == self.left {
9794            return other.closed.right_closed() && self.closed.left_closed();
9795        }
9796        true
9797    }
9798
9799    /// Parse an interval string. Supports bracket notation:
9800    /// - '[0, 1]' -> closed on both ends
9801    /// - '(0, 1)' -> open on both ends
9802    /// - '[0, 1)' -> closed left, open right (pandas default)
9803    /// - '(0, 1]' -> open left, closed right
9804    pub fn parse(s: &str) -> Result<Self, TypeError> {
9805        let s = s.trim();
9806        if s.len() < 5 {
9807            return Err(TypeError::ValueNotParseable {
9808                value: s.to_string(),
9809                target: "Interval".to_string(),
9810            });
9811        }
9812
9813        let first_char = s.chars().next().unwrap();
9814        let last_char = s.chars().last().unwrap();
9815
9816        let left_closed = match first_char {
9817            '[' => true,
9818            '(' => false,
9819            _ => {
9820                return Err(TypeError::ValueNotParseable {
9821                    value: s.to_string(),
9822                    target: "Interval".to_string(),
9823                });
9824            }
9825        };
9826
9827        let right_closed = match last_char {
9828            ']' => true,
9829            ')' => false,
9830            _ => {
9831                return Err(TypeError::ValueNotParseable {
9832                    value: s.to_string(),
9833                    target: "Interval".to_string(),
9834                });
9835            }
9836        };
9837
9838        let closed = match (left_closed, right_closed) {
9839            (true, true) => IntervalClosed::Both,
9840            (true, false) => IntervalClosed::Left,
9841            (false, true) => IntervalClosed::Right,
9842            (false, false) => IntervalClosed::Neither,
9843        };
9844
9845        let inner = &s[1..s.len() - 1];
9846        let Some((left_text, right_text)) = inner.split_once(',') else {
9847            return Err(TypeError::ValueNotParseable {
9848                value: s.to_string(),
9849                target: "Interval".to_string(),
9850            });
9851        };
9852        if right_text.contains(',') {
9853            return Err(TypeError::ValueNotParseable {
9854                value: s.to_string(),
9855                target: "Interval".to_string(),
9856            });
9857        }
9858
9859        let left: f64 = left_text
9860            .trim()
9861            .parse()
9862            .map_err(|_| TypeError::ValueNotParseable {
9863                value: s.to_string(),
9864                target: "Interval".to_string(),
9865            })?;
9866
9867        let right: f64 = right_text
9868            .trim()
9869            .parse()
9870            .map_err(|_| TypeError::ValueNotParseable {
9871                value: s.to_string(),
9872                target: "Interval".to_string(),
9873            })?;
9874
9875        Ok(Self::new(left, right, closed))
9876    }
9877}
9878
9879impl std::fmt::Display for Interval {
9880    /// Matches `str(pd.Interval(...))`: `interval[float64]` endpoints render
9881    /// with Python `str(float)` semantics, so whole numbers KEEP ".0"
9882    /// (`str(pd.Interval(0.0, 5.0, 'right'))` is `"(0.0, 5.0]"`, not `"(0, 5]"`).
9883    /// Verified vs pandas 2.2.3 across whole/fractional/negative/scientific
9884    /// endpoints. (br-frankenpandas-5xw1b) The `interval[int64]` subtype
9885    /// prints integers (`"(0, 5]"`).
9886    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9887        let left_bracket = if self.closed.left_closed() { '[' } else { '(' };
9888        let right_bracket = if self.closed.right_closed() { ']' } else { ')' };
9889        // The int64 subtype prints its endpoints as integers ('(0, 3]').
9890        #[allow(clippy::cast_possible_truncation)] // whole numbers, checked
9891        let endpoint = |value: f64| match self.subtype {
9892            IntervalSubtype::Int64 if value.fract() == 0.0 => format!("{}", value as i64),
9893            _ => float_to_string_for_astype(value),
9894        };
9895        write!(
9896            f,
9897            "{left_bracket}{}, {}{right_bracket}",
9898            endpoint(self.left),
9899            endpoint(self.right)
9900        )
9901    }
9902}
9903
9904// ── interval_range builders (br-frankenpandas-xaom — Phase 2 of j8k4) ────
9905
9906/// Build `periods` equal-width intervals spanning `[start, end]`.
9907///
9908/// Matches `pd.interval_range(start, end, periods=N, closed=...)` for the
9909/// numeric-subtype case. Returns exactly `periods` intervals; when
9910/// `periods == 0` or `start >= end`, returns an empty vector (matches
9911/// pandas's empty IntervalIndex).
9912///
9913/// ```
9914/// use fp_types::{interval_range_by_periods, IntervalClosed};
9915/// let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
9916/// assert_eq!(bins.len(), 5);
9917/// assert_eq!(bins[0].left, 0.0);
9918/// assert_eq!(bins[0].right, 2.0);
9919/// assert_eq!(bins[4].right, 10.0);
9920/// ```
9921#[must_use]
9922pub fn interval_range_by_periods(
9923    start: f64,
9924    end: f64,
9925    periods: usize,
9926    closed: IntervalClosed,
9927) -> Vec<Interval> {
9928    if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
9929        return Vec::new();
9930    }
9931    let step = (end - start) / (periods as f64);
9932    let mut out = Vec::with_capacity(periods);
9933    for i in 0..periods {
9934        let left = start + step * (i as f64);
9935        // Use end exactly for the final right edge to avoid float drift.
9936        let right = if i + 1 == periods {
9937            end
9938        } else {
9939            start + step * ((i + 1) as f64)
9940        };
9941        out.push(Interval::new(left, right, closed));
9942    }
9943    out
9944}
9945
9946/// Build equal-`step`-width intervals spanning `[start, end]`.
9947///
9948/// Matches `pd.interval_range(start, end, freq=step, closed=...)` for the
9949/// numeric-subtype case. `step` must be finite and positive; `(end - start)`
9950/// must be an integer multiple of `step` (within float tolerance) — pandas
9951/// raises `ValueError` otherwise; this fn returns `Err(TypeError::IntervalStepDoesNotDivide)`.
9952///
9953/// Returns an empty vector when `start == end` (matches pandas' zero-bin
9954/// IntervalIndex); returns an empty vector when `start > end` (pandas also
9955/// returns empty rather than erroring in this case).
9956pub fn interval_range_by_step(
9957    start: f64,
9958    end: f64,
9959    step: f64,
9960    closed: IntervalClosed,
9961) -> Result<Vec<Interval>, TypeError> {
9962    if !step.is_finite() || !step.is_sign_positive() || step == 0.0 {
9963        return Err(TypeError::InvalidIntervalStep { step });
9964    }
9965    if !start.is_finite() || !end.is_finite() || start >= end {
9966        return Ok(Vec::new());
9967    }
9968    let span = end - start;
9969    let periods_f = span / step;
9970    let periods = periods_f.round() as i64;
9971    if periods <= 0 {
9972        return Ok(Vec::new());
9973    }
9974    let reconstructed = step * (periods as f64);
9975    // Relative tolerance: allow float-rounding noise proportional to span.
9976    if (span - reconstructed).abs() > span.abs() * 1e-9 + 1e-12 {
9977        return Err(TypeError::IntervalStepDoesNotDivide { step, span });
9978    }
9979    let periods = periods as usize;
9980    let mut out = Vec::with_capacity(periods);
9981    for i in 0..periods {
9982        let left = start + step * (i as f64);
9983        let right = if i + 1 == periods {
9984            end
9985        } else {
9986            start + step * ((i + 1) as f64)
9987        };
9988        out.push(Interval::new(left, right, closed));
9989    }
9990    Ok(out)
9991}
9992
9993/// Build equal-width intervals spanning a range, matching `pd.interval_range`.
9994///
9995/// Of the four parameters `start`, `end`, `periods`, and `freq`, exactly three must
9996/// be specified (`Some`). `closed` defaults to `IntervalClosed::Right` when `None`.
9997///
9998/// # Errors
9999/// Returns `TypeError::IntervalRangeParameterCount` if not exactly 3 of the 4 parameters
10000/// are specified.
10001/// Returns `TypeError::InvalidIntervalStep` if `freq` is not finite, not positive, or zero.
10002/// Returns `TypeError::IntervalStepDoesNotDivide` if `start`, `end`, and `freq` are given
10003/// but `(end - start)` is not an integer multiple of `freq`.
10004pub fn interval_range(
10005    start: Option<f64>,
10006    end: Option<f64>,
10007    periods: Option<usize>,
10008    freq: Option<f64>,
10009    closed: Option<IntervalClosed>,
10010) -> Result<Vec<Interval>, TypeError> {
10011    let count = usize::from(start.is_some())
10012        + usize::from(end.is_some())
10013        + usize::from(periods.is_some())
10014        + usize::from(freq.is_some());
10015    if count != 3 {
10016        return Err(TypeError::IntervalRangeParameterCount);
10017    }
10018    let closed = closed.unwrap_or(IntervalClosed::Right);
10019
10020    match (start, end, periods, freq) {
10021        (Some(start), Some(end), Some(periods), None) => {
10022            Ok(interval_range_by_periods(start, end, periods, closed))
10023        }
10024        (Some(start), Some(end), None, Some(freq)) => {
10025            interval_range_by_step(start, end, freq, closed)
10026        }
10027        (Some(start), None, Some(periods), Some(freq)) => {
10028            if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10029                return Err(TypeError::InvalidIntervalStep { step: freq });
10030            }
10031            if !start.is_finite() || periods == 0 {
10032                return Ok(Vec::new());
10033            }
10034            let mut out = Vec::with_capacity(periods);
10035            for i in 0..periods {
10036                let left = start + freq * (i as f64);
10037                let right = start + freq * ((i + 1) as f64);
10038                out.push(Interval::new(left, right, closed));
10039            }
10040            Ok(out)
10041        }
10042        (None, Some(end), Some(periods), Some(freq)) => {
10043            if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10044                return Err(TypeError::InvalidIntervalStep { step: freq });
10045            }
10046            if !end.is_finite() || periods == 0 {
10047                return Ok(Vec::new());
10048            }
10049            let start = end - freq * (periods as f64);
10050            let mut out = Vec::with_capacity(periods);
10051            for i in 0..periods {
10052                let left = start + freq * (i as f64);
10053                let right = if i + 1 == periods {
10054                    end
10055                } else {
10056                    start + freq * ((i + 1) as f64)
10057                };
10058                out.push(Interval::new(left, right, closed));
10059            }
10060            Ok(out)
10061        }
10062        _ => Err(TypeError::IntervalRangeParameterCount),
10063    }
10064}
10065
10066// ── Period types (br-frankenpandas-epoj Phase 1) ────────────────────────
10067//
10068// Scaffolding for pandas `pd.Period` / `pd.PeriodIndex` / `pd.PeriodDtype`.
10069//
10070// A Period is a calendar *span* (Q1 2024, Jan 2024, 2024-03-15), distinct
10071// from a Timestamp (an instant). Phase 1 ships the PeriodFreq enum +
10072// Period struct with ordinal-based arithmetic (Period + n, Period - Period),
10073// Display in pandas notation, and parse from standard strings. Calendar-
10074// conversion (ordinal ↔ ymd) and DType::Period wiring land in Phase 2.
10075
10076/// Period frequency code. Matches pandas offset alias core set.
10077///
10078/// The ordinal axis is frequency-specific: for Monthly, ordinal 0 is a
10079/// fixed anchor (pandas uses months since 1970-01). Phase 1 doesn't
10080/// commit to a specific epoch yet — the ordinal scheme is opaque until
10081/// Phase 2 wires calendar arithmetic. What Phase 1 DOES nail down is:
10082/// same-freq Periods compare + subtract; Period + i64 shifts by `n`
10083/// periods of the declared frequency.
10084#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10085#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
10086#[non_exhaustive]
10087pub enum PeriodFreq {
10088    /// `Y-DEC` / `A` / `Y` — annual periods.
10089    Annual,
10090    /// `Q-DEC` / `Q` — quarterly periods.
10091    Quarterly,
10092    /// `M` — monthly periods.
10093    Monthly,
10094    /// `W-SUN` / `W` — weekly periods.
10095    Weekly,
10096    /// `D` — daily periods.
10097    Daily,
10098    /// `B` — business-day periods.
10099    Business,
10100    /// `h` / `H` — hourly periods.
10101    Hourly,
10102    /// `min` / `T` — minutely periods.
10103    Minutely,
10104    /// `s` / `S` — secondly periods.
10105    Secondly,
10106    /// `ms` — millisecond periods. NOT `MS`, which pandas reads as month start.
10107    Milliseconds,
10108    /// `us` / `US` — microsecond periods.
10109    Microseconds,
10110    /// `ns` / `NS` — nanosecond periods.
10111    Nanoseconds,
10112}
10113
10114impl PeriodFreq {
10115    /// Parse a pandas-style frequency alias. Recognizes the common subset
10116    /// (Y-DEC/A/Y, Q-DEC/Q, M, W-SUN/W, D, B, h/H, min/T, s/S) plus the
10117    /// sub-second units ms, us/US, ns/NS.
10118    ///
10119    /// Case-insensitive with ONE exception: bare `MS` is month start in pandas,
10120    /// not milliseconds, and is refused here the way pandas refuses it for
10121    /// `to_period`. See the check at the top of the body.
10122    pub fn parse(alias: &str) -> Option<Self> {
10123        // ⚠️ CASE MATTERS FOR EXACTLY ONE ALIAS, and this parser uppercases
10124        // everything. MEASURED, live pandas 2.2.3, Timestamp.to_period(f):
10125        //     'ms' -> millisecond      'Ms' -> millisecond
10126        //     'MS' -> ValueError       (it is month start, a date_range-only freq)
10127        //     'us' -> microsecond      'US' -> microsecond
10128        //     'ns' -> nanosecond       'NS' -> nanosecond
10129        // So only the fully-capitalised `MS` is excluded; every other casing of
10130        // "ms" is milliseconds, while us/ns are case-insensitive and belong in
10131        // the table below. Checked here, before the uppercase collapses it.
10132        if alias.eq_ignore_ascii_case("ms") && alias != "MS" {
10133            return Some(Self::Milliseconds);
10134        }
10135        match alias.to_ascii_uppercase().as_str() {
10136            "A" | "Y" | "A-DEC" | "Y-DEC" | "ANNUAL" | "YEARLY" => Some(Self::Annual),
10137            "Q" | "Q-DEC" | "QUARTERLY" => Some(Self::Quarterly),
10138            "M" | "MONTHLY" => Some(Self::Monthly),
10139            "W" | "W-SUN" | "WEEKLY" => Some(Self::Weekly),
10140            "D" | "DAILY" => Some(Self::Daily),
10141            "B" | "BUSINESS" => Some(Self::Business),
10142            "H" | "HOURLY" => Some(Self::Hourly),
10143            "T" | "MIN" | "MINUTELY" => Some(Self::Minutely),
10144            "S" | "SECONDLY" => Some(Self::Secondly),
10145            "US" | "MICROSECOND" | "MICROSECONDS" => Some(Self::Microseconds),
10146            "NS" | "NANOSECOND" | "NANOSECONDS" => Some(Self::Nanoseconds),
10147            // The spelled-out form only; bare "MS" is deliberately absent, and
10148            // every other casing of it was taken above.
10149            "MILLISECOND" | "MILLISECONDS" => Some(Self::Milliseconds),
10150            _ => None,
10151        }
10152    }
10153
10154    /// Canonical pandas alias string.
10155    #[must_use]
10156    pub const fn alias(self) -> &'static str {
10157        match self {
10158            Self::Annual => "Y-DEC",
10159            Self::Quarterly => "Q-DEC",
10160            Self::Monthly => "M",
10161            Self::Weekly => "W-SUN",
10162            Self::Daily => "D",
10163            Self::Business => "B",
10164            Self::Hourly => "h",
10165            Self::Minutely => "min",
10166            Self::Secondly => "s",
10167            Self::Milliseconds => "ms",
10168            Self::Microseconds => "us",
10169            Self::Nanoseconds => "ns",
10170        }
10171    }
10172
10173    /// Resolution word for `PeriodIndex.resolution`, or `None` where pandas has
10174    /// no answer.
10175    ///
10176    /// ⚠️ THIS IS NOT THE ALIAS TABLE. pandas' `.resolution` names the period's
10177    /// *component*, in the same vocabulary `DatetimeIndex::resolution` already
10178    /// uses here -- it is not the frequency string, which is what
10179    /// [`PeriodFreq::alias`] is for. MEASURED, live pandas 2.2.3, one-element
10180    /// `PeriodIndex` per freq:
10181    ///     Y   -> 'year'        Q   -> 'quarter'     M  -> 'month'
10182    ///     D   -> 'day'         h   -> 'hour'        min-> 'minute'
10183    ///     s   -> 'second'
10184    ///     W   -> raises AttributeError
10185    ///     B   -> raises AttributeError
10186    /// Every arm below previously returned the alias instead ("A-DEC", "M", "H",
10187    /// "T", "S", ...), so all nine disagreed with the incumbent; W and B answered
10188    /// where pandas refuses. The refusal is modelled as `None` rather than a
10189    /// wrong word, because the caller already returns `Option` for the empty
10190    /// index and pandas' own failure there is an absence, not a value.
10191    #[must_use]
10192    pub const fn resolution(self) -> Option<&'static str> {
10193        match self {
10194            Self::Annual => Some("year"),
10195            Self::Quarterly => Some("quarter"),
10196            Self::Monthly => Some("month"),
10197            Self::Daily => Some("day"),
10198            Self::Hourly => Some("hour"),
10199            Self::Minutely => Some("minute"),
10200            Self::Secondly => Some("second"),
10201            Self::Milliseconds => Some("millisecond"),
10202            Self::Microseconds => Some("microsecond"),
10203            Self::Nanoseconds => Some("nanosecond"),
10204            // pandas' Week and BusinessDay offsets carry no `_resolution_obj`,
10205            // so `.resolution` raises AttributeError rather than answering.
10206            Self::Weekly | Self::Business => None,
10207        }
10208    }
10209}
10210
10211impl std::fmt::Display for PeriodFreq {
10212    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10213        f.write_str(self.alias())
10214    }
10215}
10216
10217/// A single pandas-style Period value.
10218///
10219/// Stored as an integer ordinal on a frequency-specific axis plus the
10220/// frequency code. Two Periods with different `freq` are incompatible —
10221/// arithmetic and comparison require same-freq operands. The derived order
10222/// (ordinal, then freq) is a total one for index labels (45fzr): within one
10223/// freq it is the periods' own.
10224#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10225pub struct Period {
10226    pub ordinal: i64,
10227    pub freq: PeriodFreq,
10228}
10229
10230impl Period {
10231    #[must_use]
10232    pub const fn new(ordinal: i64, freq: PeriodFreq) -> Self {
10233        Self { ordinal, freq }
10234    }
10235
10236    /// Whether this is NaT: the missing period, ordinal `i64::MIN` (what a
10237    /// missing element of a PeriodIndex holds and what renders `NaT`).
10238    #[must_use]
10239    pub const fn is_nat(&self) -> bool {
10240        self.ordinal == i64::MIN
10241    }
10242
10243    /// Integer position on this period's frequency axis, matching
10244    /// `pd.Period.ordinal`.
10245    #[must_use]
10246    pub const fn ordinal(&self) -> i64 {
10247        self.ordinal
10248    }
10249
10250    /// Frequency code for this period, matching `pd.Period.freq`.
10251    #[must_use]
10252    pub const fn freq(&self) -> PeriodFreq {
10253        self.freq
10254    }
10255
10256    /// Canonical pandas frequency alias, matching `pd.Period.freqstr`.
10257    #[must_use]
10258    pub const fn freqstr(&self) -> &'static str {
10259        self.freq.alias()
10260    }
10261
10262    /// Same-freq ordinal comparison. Returns `None` if `freq` differs —
10263    /// caller decides whether that's an error or a panic site.
10264    #[must_use]
10265    pub fn cmp_same_freq(&self, other: &Self) -> Option<std::cmp::Ordering> {
10266        if self.freq != other.freq {
10267            return None;
10268        }
10269        Some(self.ordinal.cmp(&other.ordinal))
10270    }
10271
10272    /// Shift by `n` periods of the current frequency.
10273    /// Matches `pd.Period + n` and `pd.Period - n`.
10274    #[must_use]
10275    pub fn shift(&self, n: i64) -> Self {
10276        Self {
10277            ordinal: self.ordinal.saturating_add(n),
10278            freq: self.freq,
10279        }
10280    }
10281
10282    /// Period-difference in units of the shared frequency.
10283    /// Returns `None` if `freq` differs (pandas raises IncompatibleFrequency).
10284    #[must_use]
10285    pub fn diff(&self, other: &Self) -> Option<i64> {
10286        if self.freq != other.freq {
10287            return None;
10288        }
10289        Some(self.ordinal.saturating_sub(other.ordinal))
10290    }
10291
10292    /// Parse common pandas `Period(...)` strings and infer the frequency.
10293    ///
10294    /// Supported forms mirror pandas' unambiguous scalar constructor cases:
10295    /// annual (`"2024"`), quarterly (`"2024Q1"`), monthly (`"2024-01"`),
10296    /// and daily (`"2024-01-15"`). The ordinal axes match pandas:
10297    /// 1970, 1970Q1, 1970-01, and 1970-01-01 all have ordinal 0.
10298    pub fn parse(s: &str) -> Result<Self, TypeError> {
10299        let trimmed = s.trim();
10300        if trimmed.eq_ignore_ascii_case("nat") {
10301            return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
10302        }
10303
10304        if let Some((year, quarter)) = parse_quarter_period(trimmed) {
10305            let ordinal = year
10306                .checked_sub(1970)
10307                .and_then(|offset| offset.checked_mul(4))
10308                .and_then(|base| base.checked_add(i64::from(quarter) - 1))
10309                .ok_or_else(|| TypeError::ValueNotParseable {
10310                    value: s.to_owned(),
10311                    target: "Period".to_owned(),
10312                })?;
10313            return Ok(Self::new(ordinal, PeriodFreq::Quarterly));
10314        }
10315
10316        if let Some((year, month, day)) = parse_ymd_period(trimmed) {
10317            let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
10318            return Ok(Self::new(ordinal, PeriodFreq::Daily));
10319        }
10320
10321        if let Some((year, month)) = parse_year_month_period(trimmed) {
10322            let ordinal = year
10323                .checked_sub(1970)
10324                .and_then(|offset| offset.checked_mul(12))
10325                .and_then(|base| base.checked_add(i64::from(month) - 1))
10326                .ok_or_else(|| TypeError::ValueNotParseable {
10327                    value: s.to_owned(),
10328                    target: "Period".to_owned(),
10329                })?;
10330            return Ok(Self::new(ordinal, PeriodFreq::Monthly));
10331        }
10332
10333        if let Some(year) = parse_annual_period(trimmed) {
10334            let ordinal = year
10335                .checked_sub(1970)
10336                .ok_or_else(|| TypeError::ValueNotParseable {
10337                    value: s.to_owned(),
10338                    target: "Period".to_owned(),
10339                })?;
10340            return Ok(Self::new(ordinal, PeriodFreq::Annual));
10341        }
10342
10343        Err(TypeError::ValueNotParseable {
10344            value: s.to_owned(),
10345            target: "Period".to_owned(),
10346        })
10347    }
10348
10349    /// Pandas calendar string for this period, matching `str(pd.Period)`.
10350    ///
10351    /// Inverts the frequency-specific ordinal axes anchored at 1970:
10352    /// `1970`/`1970Q1`/`1970-01`/`1970-01-01`/`1970-01-01 00:00` all have
10353    /// ordinal 0. Returns `"NaT"` for the missing sentinel (`i64::MIN`).
10354    ///
10355    /// EVERY frequency is exact, Weekly and Business included.
10356    ///
10357    /// ⚠️ THOSE TWO ARE NOT INDEXED IN DAYS, which is what made them wrong until
10358    /// 08363d42f: a weekly ordinal counts WEEKS from the Monday 1969-12-22 and
10359    /// renders as the RANGE it spans (`2024-03-11/2024-03-17`), and a business
10360    /// ordinal counts BUSINESS DAYS at five per week. Both used to be handed to
10361    /// `civil_from_days`, which reads its argument as days since the epoch, so
10362    /// ordinal 2829 rendered `1977-09-30` instead of the week of 2024-03-15.
10363    ///
10364    /// The note that used to sit here called them "best-effort" and said neither
10365    /// was "reachable through the current parse/cast paths". The first half was
10366    /// a real limitation; the second was too narrow a survey. [`Self::parse`]
10367    /// indeed cannot produce them and neither can `cast_scalar` — but
10368    /// `DatetimeIndex::to_period("W")` builds them directly, and fp-index then
10369    /// renders those values through `Display` in `PeriodIndex::format`,
10370    /// `to_index`, `to_flat_index`, the `.str` accessor and the `get_loc` error
10371    /// message. The frequencies were unreachable only from the two paths the
10372    /// note happened to check.
10373    #[must_use]
10374    pub fn calendar_string(&self) -> String {
10375        let mut rendered = String::new();
10376        // `fmt::Write for String` is infallible.
10377        let _ = self.write_calendar(&mut rendered);
10378        rendered
10379    }
10380
10381    fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
10382        if self.ordinal == i64::MIN {
10383            return rendered.write_str("NaT");
10384        }
10385        let ord = self.ordinal;
10386        match self.freq {
10387            PeriodFreq::Annual => {
10388                let year = 1970 + ord;
10389                write!(rendered, "{year}")
10390            }
10391            PeriodFreq::Quarterly => {
10392                let year = 1970 + ord.div_euclid(4);
10393                let quarter = ord.rem_euclid(4) + 1;
10394                write!(rendered, "{year}Q{quarter}")
10395            }
10396            PeriodFreq::Monthly => {
10397                let year = 1970 + ord.div_euclid(12);
10398                let month = ord.rem_euclid(12) + 1;
10399                write!(rendered, "{year:04}-{month:02}")
10400            }
10401            PeriodFreq::Daily => {
10402                let (y, m, d) = civil_from_days(ord);
10403                write!(rendered, "{y:04}-{m:02}-{d:02}")
10404            }
10405            // ⚠️ NOT DAYS SINCE THE EPOCH. A business ordinal counts BUSINESS
10406            // DAYS — five per week — so handing it to `civil_from_days` (which
10407            // wants a day count) put the label decades out: ordinal 14141 is
10408            // 2024-03-15 and rendered as 2008-09-19.
10409            //
10410            // The forward map in fp-index is
10411            //     days.div_euclid(7) * 5 + {Thu:0, Fri:1, Mon:2, Tue:3, Wed:4}
10412            // measured against pandas at every sampled date, so this is its
10413            // inverse: five ordinals per seven days, with the remainder naming a
10414            // weekday offset from the Thursday the epoch falls on.
10415            PeriodFreq::Business => {
10416                const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
10417                // Euclidean, so a pre-epoch ordinal keeps a remainder in 0..5:
10418                // ordinal -1 is 1969-12-31, not a negative weekday index.
10419                let offset = WEEKDAY_OFFSET[ord.rem_euclid(5) as usize];
10420                let days = ord.div_euclid(5).saturating_mul(7).saturating_add(offset);
10421                let (y, m, d) = civil_from_days(days);
10422                write!(rendered, "{y:04}-{m:02}-{d:02}")
10423            }
10424            // ⚠️ TWO BUGS IN ONE ARM. A weekly ordinal counts WEEKS from the
10425            // Monday 1969-12-22 (ten days before the epoch), and pandas renders a
10426            // weekly period as the RANGE it spans, not as one date:
10427            //     Period('2024-03-15', 'W') -> '2024-03-11/2024-03-17'
10428            // ordinal 2829, which this arm rendered as '1977-09-30'.
10429            //
10430            // fp-frame's `format_period_label` already produced the range form
10431            // for the same freq, so the two renderers disagreed on every weekly
10432            // period; this makes them agree.
10433            PeriodFreq::Weekly => {
10434                // Days-since-epoch of the anchor Monday 1969-12-22.
10435                const WEEK_ANCHOR_DAY: i64 = -10;
10436                let start = ord.saturating_mul(7).saturating_add(WEEK_ANCHOR_DAY);
10437                let (sy, sm, sd) = civil_from_days(start);
10438                let (ey, em, ed) = civil_from_days(start.saturating_add(6));
10439                write!(rendered, "{sy:04}-{sm:02}-{sd:02}/{ey:04}-{em:02}-{ed:02}")
10440            }
10441            PeriodFreq::Hourly => {
10442                let (y, m, d) = civil_from_days(ord.div_euclid(24));
10443                let hour = ord.rem_euclid(24);
10444                write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
10445            }
10446            PeriodFreq::Minutely => {
10447                let day = ord.div_euclid(1440);
10448                let mins = ord.rem_euclid(1440);
10449                let (y, m, d) = civil_from_days(day);
10450                write!(
10451                    rendered,
10452                    "{y:04}-{m:02}-{d:02} {:02}:{:02}",
10453                    mins / 60,
10454                    mins % 60
10455                )
10456            }
10457            PeriodFreq::Secondly => {
10458                let day = ord.div_euclid(86_400);
10459                let secs = ord.rem_euclid(86_400);
10460                let (y, m, d) = civil_from_days(day);
10461                write!(
10462                    rendered,
10463                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
10464                    secs / 3600,
10465                    (secs % 3600) / 60,
10466                    secs % 60
10467                )
10468            }
10469            // The three sub-second frequencies differ only in the divisor and
10470            // the FIXED fraction width -- pandas pads to the full width and
10471            // never trims trailing zeros. MEASURED on 2024-03-15 10:30:45.123456789:
10472            //     ms -> "2024-03-15 10:30:45.123"
10473            //     us -> "2024-03-15 10:30:45.123456"
10474            //     ns -> "2024-03-15 10:30:45.123456789"
10475            PeriodFreq::Milliseconds | PeriodFreq::Microseconds | PeriodFreq::Nanoseconds => {
10476                let (per_sec, width) = match self.freq {
10477                    PeriodFreq::Milliseconds => (1_000_i64, 3_usize),
10478                    PeriodFreq::Microseconds => (1_000_000_i64, 6_usize),
10479                    _ => (1_000_000_000_i64, 9_usize),
10480                };
10481                // 86_400 * 1e9 = 8.64e13 -- the widest of these is well inside i64.
10482                let per_day = 86_400 * per_sec;
10483                let day = ord.div_euclid(per_day);
10484                let rest = ord.rem_euclid(per_day);
10485                let secs = rest / per_sec;
10486                let frac = rest % per_sec;
10487                let (y, m, d) = civil_from_days(day);
10488                write!(
10489                    rendered,
10490                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{:0width$}",
10491                    secs / 3600,
10492                    (secs % 3600) / 60,
10493                    secs % 60,
10494                    frac,
10495                    width = width
10496                )
10497            }
10498        }
10499    }
10500}
10501
10502/// Convert a day count (days since 1970-01-01) to a proleptic-Gregorian
10503/// `(year, month, day)`, using Howard Hinnant's civil-from-days algorithm
10504/// (same kernel as `Timestamp::isoformat`).
10505fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
10506    let days = days_since_epoch + 719_468;
10507    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
10508    let doe = days - era * 146_097;
10509    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
10510    let y = yoe + era * 400;
10511    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
10512    let mp = (5 * doy + 2) / 153;
10513    let d = doy - (153 * mp + 2) / 5 + 1;
10514    let m = if mp < 10 { mp + 3 } else { mp - 9 };
10515    let year = if m <= 2 { y + 1 } else { y };
10516    (year, m as u32, d as u32)
10517}
10518
10519fn parse_annual_period(value: &str) -> Option<i64> {
10520    (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
10521        .then(|| value.parse::<i64>().ok())
10522        .flatten()
10523}
10524
10525fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
10526    let (year, month) = value.split_once('-')?;
10527    if year.len() != 4 || month.len() != 2 {
10528        return None;
10529    }
10530    let year = year.parse::<i64>().ok()?;
10531    let month = month.parse::<u32>().ok()?;
10532    (1..=12).contains(&month).then_some((year, month))
10533}
10534
10535fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
10536    let mut parts = value.split('-');
10537    let year = parts.next()?;
10538    let month = parts.next()?;
10539    let day = parts.next()?;
10540    if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
10541        return None;
10542    }
10543    let year = year.parse::<i64>().ok()?;
10544    let month = month.parse::<u32>().ok()?;
10545    let day = day.parse::<u32>().ok()?;
10546    (1..=days_in_month(year, month)?)
10547        .contains(&day)
10548        .then_some((year, month, day))
10549}
10550
10551fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
10552    let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
10553    if year.len() != 4 || quarter.len() != 1 {
10554        return None;
10555    }
10556    let year = year.parse::<i64>().ok()?;
10557    let quarter = quarter.parse::<u32>().ok()?;
10558    (1..=4).contains(&quarter).then_some((year, quarter))
10559}
10560
10561impl std::fmt::Display for Period {
10562    /// Pandas `str(Period)` form: the calendar string (`2024`, `2024Q1`,
10563    /// `2024-03`, `2024-01-15`, ...). NaT (ordinal `i64::MIN`) renders `NaT`.
10564    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10565        self.write_calendar(f)
10566    }
10567}
10568
10569/// Build `periods` consecutive Periods starting at `start`.
10570///
10571/// Matches `pd.period_range(start, periods=N, freq=start.freq)` for the
10572/// count-based form. The frequency is taken from `start` — pandas requires
10573/// `freq` to match when both are passed; mismatches are an error in
10574/// pandas, but here we sidestep ambiguity by deriving from `start.freq`.
10575///
10576/// Per br-frankenpandas-2jef (epoj Phase 2). Pure ordinal arithmetic — no
10577/// calendar conversion (Phase 3 wires chrono). `periods=0` returns empty.
10578///
10579/// ```
10580/// use fp_types::{period_range, Period, PeriodFreq};
10581/// let q1 = Period::new(216, PeriodFreq::Quarterly);
10582/// let year = period_range(q1, 4);
10583/// assert_eq!(year.len(), 4);
10584/// assert_eq!(year[0].ordinal, 216);
10585/// assert_eq!(year[3].ordinal, 219);
10586/// ```
10587#[must_use]
10588pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
10589    (0..periods).map(|i| start.shift(i as i64)).collect()
10590}
10591
10592#[cfg(test)]
10593mod tests {
10594    use super::{
10595        DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
10596        cast_scalar, common_dtype, infer_dtype,
10597    };
10598
10599    /// A host value for the tests: a named thing, equal by name, unhashable
10600    /// when the name is empty.
10601    struct Named(&'static str);
10602
10603    impl super::HostObject for Named {
10604        fn host_eq(&self, other: &dyn super::HostObject) -> bool {
10605            other
10606                .as_any()
10607                .downcast_ref::<Named>()
10608                .is_some_and(|other| other.0 == self.0)
10609        }
10610        fn host_repr(&self) -> String {
10611            format!("Named({:?})", self.0)
10612        }
10613        fn host_str(&self) -> String {
10614            self.0.to_owned()
10615        }
10616        fn host_hash(&self) -> Option<u64> {
10617            (!self.0.is_empty()).then_some(self.0.len() as u64)
10618        }
10619        // Names starting with '!' cannot be ordered (as a date against a time).
10620        fn host_cmp(&self, other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
10621            let other = other.as_any().downcast_ref::<Named>()?;
10622            (!self.0.starts_with('!') && !other.0.starts_with('!')).then(|| self.0.cmp(other.0))
10623        }
10624        fn as_any(&self) -> &dyn std::any::Any {
10625            self
10626        }
10627    }
10628
10629    #[test]
10630    fn host_values_block_workers_only_under_a_declared_host_lock_4qg5w_13() {
10631        use std::sync::atomic::Ordering;
10632
10633        use super::{HostValue, LIVE_HOST_VALUES, workers_blocked};
10634        // The rule: inline only when a host lock may be held AND a host value
10635        // is alive. NEGATIVE: without a declared lock (pure Rust callers, this
10636        // test process) nothing is blocked however many host values live.
10637        assert!(workers_blocked(true, 1));
10638        assert!(!workers_blocked(true, 0));
10639        assert!(!workers_blocked(false, 3));
10640        // The count: non-zero while a handle is held, clones included (other
10641        // tests may hold host values concurrently, so only "alive while held"
10642        // is asserted, never "dead after drop"; the lock is never declared
10643        // here, so no concurrent test loses its workers).
10644        let first = HostValue::new(Named("held"));
10645        assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
10646        let clone = first.clone();
10647        drop(first);
10648        assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
10649        assert_eq!(clone.object().host_str(), "held");
10650    }
10651
10652    #[test]
10653    fn object_cells_order_like_python_then_totally_fvsao_66() {
10654        use std::cmp::Ordering;
10655
10656        use super::{HostValue, ObjectValue};
10657        let host = |name: &'static str| ObjectValue::Host(HostValue::new(Named(name)));
10658        let list = |items: Vec<Scalar>| ObjectValue::list(items);
10659        // Host values order as the host orders them (a date before a later
10660        // date), not by their reprs.
10661        assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
10662        assert!(host("b") > host("a"));
10663        assert_eq!(host("a").cmp(&host("a")), Ordering::Equal);
10664        // Lists item by item, numbers by value (1 < 10, where the reprs sort
10665        // "10" first), a shorter prefix first.
10666        let one_ten = list(vec![Scalar::Int64(1), Scalar::Int64(10)]);
10667        let one_two = list(vec![Scalar::Int64(1), Scalar::Int64(2)]);
10668        assert_eq!(one_two.python_cmp(&one_ten), Some(Ordering::Less));
10669        assert!(list(vec![Scalar::Int64(1)]) < one_two);
10670        // Python's 1 == 1.0: an equal item pair is skipped, not the answer.
10671        let mixed = list(vec![Scalar::Float64(1.0), Scalar::Int64(3)]);
10672        assert_eq!(one_two.python_cmp(&mixed), Some(Ordering::Less));
10673        // Where Python raises there is no python_cmp, but the total order
10674        // still separates the cells: a list before a host value, then reprs.
10675        assert_eq!(one_two.python_cmp(&host("a")), None);
10676        assert!(one_two < host("a"));
10677        assert_eq!(host("!z").python_cmp(&host("!a")), None);
10678        assert!(host("!a") < host("!z"));
10679        let text = list(vec![Scalar::Utf8("a".to_owned())]);
10680        assert_eq!(one_two.python_cmp(&text), None);
10681        assert_ne!(one_two.cmp(&text), Ordering::Equal);
10682        // NEGATIVE: unequal cells that print alike are never Equal (NaN is not
10683        // equal to itself), so an ordered map cannot merge them.
10684        let nan = || list(vec![Scalar::Float64(f64::NAN)]);
10685        let (first, second) = (nan(), nan());
10686        assert_ne!(first, second);
10687        assert_ne!(first.cmp(&second), Ordering::Equal);
10688        assert_eq!(first.cmp(&second), second.cmp(&first).reverse());
10689    }
10690
10691    #[test]
10692    fn bytes_cells_print_order_and_serialize_like_python_bytes_4qg5w_8() {
10693        use std::cmp::Ordering;
10694
10695        use super::ObjectValue;
10696        let bytes = |data: &[u8]| Scalar::Object(ObjectValue::bytes(data.to_vec()));
10697        // Python's repr: single quotes unless the bytes hold a ' and no ",
10698        // \xNN for the unprintable, \\ \t \n \r escaped.
10699        assert_eq!(bytes(b"ab").python_repr(), "b'ab'");
10700        assert_eq!(bytes(b"a'b").python_repr(), "b\"a'b\"");
10701        assert_eq!(bytes(b"a'\"").python_repr(), "b'a\\'\"'");
10702        assert_eq!(bytes(b"\x00\t\\\xff").python_repr(), "b'\\x00\\t\\\\\\xff'");
10703        assert_eq!(bytes(b"ab").python_type_name(), "bytes");
10704        // Ordered byte by byte, a prefix first; never equal to a str.
10705        assert_eq!(bytes(b"ab").python_cmp(&bytes(b"b")), Some(Ordering::Less));
10706        assert_eq!(bytes(b"a").python_cmp(&bytes(b"ab")), Some(Ordering::Less));
10707        assert_eq!(bytes(b"a").python_cmp(&Scalar::Utf8("a".to_owned())), None);
10708        assert_ne!(bytes(b"a"), Scalar::Utf8("a".to_owned()));
10709        assert!(!bytes(b"").to_bool().unwrap());
10710        // The serde form the conformance fixtures carry, both ways.
10711        let json = serde_json::to_string(&bytes(b"hi")).unwrap();
10712        assert_eq!(json, r#"{"kind":"object","value":{"bytes":[104,105]}}"#);
10713        let back: Scalar = serde_json::from_str(&json).unwrap();
10714        assert_eq!(back, bytes(b"hi"));
10715        // NEGATIVE: a list cell still (de)serializes as its items.
10716        let list: Scalar =
10717            serde_json::from_str(r#"{"kind":"object","value":[{"kind":"int64","value":1}]}"#)
10718                .unwrap();
10719        assert_eq!(
10720            list,
10721            Scalar::Object(ObjectValue::list(vec![Scalar::Int64(1)]))
10722        );
10723    }
10724
10725    #[test]
10726    fn values_order_and_name_their_types_as_python_does_fvsao_71() {
10727        use std::cmp::Ordering;
10728
10729        use super::{HostValue, ObjectValue};
10730        let text = |value: &str| Scalar::Utf8(value.to_owned());
10731        let host =
10732            |name: &'static str| Scalar::Object(ObjectValue::Host(HostValue::new(Named(name))));
10733        let list = |items: Vec<Scalar>| Scalar::Object(ObjectValue::list(items));
10734        // Numbers across kinds by value, text by code point, instants,
10735        // intervals by (left, right), cells as the host orders them.
10736        assert_eq!(
10737            Scalar::Bool(true).python_cmp(&Scalar::Float64(1.5)),
10738            Some(Ordering::Less)
10739        );
10740        assert_eq!(
10741            Scalar::Int64(2).python_cmp(&Scalar::Float64(2.0)),
10742            Some(Ordering::Equal)
10743        );
10744        assert_eq!(text("b").python_cmp(&text("a")), Some(Ordering::Greater));
10745        assert_eq!(
10746            Scalar::Datetime64(5).python_cmp(&Scalar::Datetime64(9)),
10747            Some(Ordering::Less)
10748        );
10749        let interval = |left: f64, right: f64| {
10750            Scalar::Interval(Interval::new(left, right, IntervalClosed::Right))
10751        };
10752        assert_eq!(
10753            interval(0.0, 5.0).python_cmp(&interval(0.0, 2.0)),
10754            Some(Ordering::Greater)
10755        );
10756        assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
10757        // NEGATIVES: what Python cannot order - a str and an int, an instant
10758        // and a duration, a cell and a number, unorderable host values.
10759        assert_eq!(text("a").python_cmp(&Scalar::Int64(1)), None);
10760        assert_eq!(
10761            Scalar::Datetime64(1).python_cmp(&Scalar::Timedelta64(1)),
10762            None
10763        );
10764        assert_eq!(host("a").python_cmp(&Scalar::Int64(1)), None);
10765        assert_eq!(host("!a").python_cmp(&host("b")), None);
10766        // Their types as Python's TypeError names them; a host value by its
10767        // host (the default for a host that cannot say is 'object'), a list
10768        // pair by the first unequal items it holds.
10769        assert_eq!(text("a").python_type_name(), "str");
10770        assert_eq!(Scalar::Bool(true).python_type_name(), "bool");
10771        assert_eq!(Scalar::Datetime64(1).python_type_name(), "Timestamp");
10772        assert_eq!(list(vec![]).python_type_name(), "list");
10773        assert_eq!(host("a").python_type_name(), "object");
10774        let (left, right) = list(vec![Scalar::Int64(1), Scalar::Int64(2)])
10775            .python_cmp_type_names(&list(vec![Scalar::Int64(1), text("x")]));
10776        assert_eq!((left.as_str(), right.as_str()), ("int", "str"));
10777        let (left, right) = text("a").python_cmp_type_names(&list(vec![]));
10778        assert_eq!((left.as_str(), right.as_str()), ("str", "list"));
10779    }
10780
10781    #[test]
10782    fn object_cells_print_compare_and_hash_like_python_fvsao_33() {
10783        use std::hash::{Hash, Hasher};
10784
10785        use super::{HostValue, ObjectValue};
10786        let hash = |value: &ObjectValue| {
10787            let mut hasher = std::collections::hash_map::DefaultHasher::new();
10788            value.hash(&mut hasher);
10789            hasher.finish()
10790        };
10791        let list = ObjectValue::list(vec![
10792            Scalar::Int64(1),
10793            Scalar::Utf8("a".to_owned()),
10794            Scalar::Null(NullKind::Null),
10795            Scalar::Float64(2.0),
10796            Scalar::Object(ObjectValue::list(vec![Scalar::Utf8("b".to_owned())])),
10797        ]);
10798        // repr / str (astype(str), writers) quote strings; pandas' display
10799        // (pprint) does not.
10800        assert_eq!(list.repr(), "[1, 'a', None, 2.0, ['b']]");
10801        assert_eq!(list.to_string(), "[1, 'a', None, 2.0, ['b']]");
10802        assert_eq!(list.pprint(), "[1, a, None, 2.0, [b]]");
10803        // An object cell is object data (pandas' object dtype, Utf8 here).
10804        assert_eq!(Scalar::Object(list.clone()).dtype(), DType::Utf8);
10805        assert!(!Scalar::Object(list.clone()).is_missing());
10806        // Equal lists are equal and hash alike; a different item is not
10807        // equal; a list never equals a host value.
10808        let same = ObjectValue::list(list.as_list().unwrap().to_vec());
10809        assert_eq!(list, same);
10810        assert_eq!(hash(&list), hash(&same));
10811        let other = ObjectValue::list(vec![Scalar::Int64(1)]);
10812        assert_ne!(list, other);
10813        let host = ObjectValue::Host(HostValue::new(Named("x")));
10814        assert_ne!(list, host);
10815        // Host values compare and print through the host.
10816        assert_eq!(host, ObjectValue::Host(HostValue::new(Named("x"))));
10817        assert_ne!(host, ObjectValue::Host(HostValue::new(Named("y"))));
10818        assert_eq!(host.repr(), "Named(\"x\")");
10819        assert_eq!(host.to_string(), "x");
10820        // Python truth: an empty list is false, a host value true.
10821        assert!(
10822            !Scalar::Object(ObjectValue::list(Vec::new()))
10823                .to_bool()
10824                .unwrap()
10825        );
10826        assert!(Scalar::Object(host.clone()).to_bool().unwrap());
10827        // A list is not a number.
10828        assert!(Scalar::Object(list.clone()).to_f64().is_err());
10829        // A list cell serializes as its items and reads back; a host value
10830        // refuses to serialize.
10831        let json = serde_json::to_string(&Scalar::Object(other.clone())).unwrap();
10832        assert_eq!(
10833            serde_json::from_str::<Scalar>(&json).unwrap(),
10834            Scalar::Object(other)
10835        );
10836        assert!(serde_json::to_string(&Scalar::Object(host)).is_err());
10837    }
10838
10839    #[test]
10840    fn a_host_cell_displays_by_its_pprint_and_stringifies_by_its_str() {
10841        use super::{HostValue, ObjectValue};
10842
10843        /// A host tuple: Python's str quotes its items, pandas' display not.
10844        struct Pair;
10845        impl super::HostObject for Pair {
10846            fn host_eq(&self, _other: &dyn super::HostObject) -> bool {
10847                false
10848            }
10849            fn host_repr(&self) -> String {
10850                "('a', 1)".to_owned()
10851            }
10852            fn host_str(&self) -> String {
10853                "('a', 1)".to_owned()
10854            }
10855            fn host_pprint(&self) -> String {
10856                "(a, 1)".to_owned()
10857            }
10858            fn host_hash(&self) -> Option<u64> {
10859                None
10860            }
10861            fn host_cmp(&self, _other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
10862                None
10863            }
10864            fn as_any(&self) -> &dyn std::any::Any {
10865                self
10866            }
10867        }
10868        let pair = ObjectValue::Host(HostValue::new(Pair));
10869        assert_eq!(pair.pprint(), "(a, 1)");
10870        // Inside a list cell too.
10871        let list = ObjectValue::list(vec![Scalar::Object(pair.clone())]);
10872        assert_eq!(list.pprint(), "[(a, 1)]");
10873        // NEGATIVE: str (astype(str), writers) stays the host's str.
10874        assert_eq!(pair.to_string(), "('a', 1)");
10875        // NEGATIVE: a host without its own pprint displays by its str.
10876        let named = ObjectValue::Host(HostValue::new(Named("x")));
10877        assert_eq!(named.pprint(), "x");
10878    }
10879
10880    #[test]
10881    fn float64_json_spells_infinity_and_round_trips() {
10882        // br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.3: serde_json
10883        // wrote +-inf as `null` and could not read it back, so pandas'
10884        // division-by-zero answers could not reach a fixture.
10885        let json = |s: &Scalar| serde_json::to_string(s).expect("serialize");
10886        let back = |text: &str| serde_json::from_str::<Scalar>(text);
10887        assert_eq!(
10888            json(&Scalar::Float64(f64::INFINITY)),
10889            r#"{"kind":"float64","value":"inf"}"#
10890        );
10891        assert_eq!(
10892            json(&Scalar::Float64(f64::NEG_INFINITY)),
10893            r#"{"kind":"float64","value":"-inf"}"#
10894        );
10895        // Unchanged spellings: finite numbers, -0.0, and NaN as null.
10896        assert_eq!(
10897            json(&Scalar::Float64(1.5)),
10898            r#"{"kind":"float64","value":1.5}"#
10899        );
10900        assert_eq!(
10901            json(&Scalar::Float64(-0.0)),
10902            r#"{"kind":"float64","value":-0.0}"#
10903        );
10904        assert_eq!(
10905            json(&Scalar::Float64(f64::NAN)),
10906            r#"{"kind":"float64","value":null}"#
10907        );
10908        for value in [f64::INFINITY, f64::NEG_INFINITY, 1.5, -2.25e300] {
10909            let scalar = Scalar::Float64(value);
10910            assert_eq!(back(&json(&scalar)).expect("round trip"), scalar);
10911        }
10912        let negative_zero = back(r#"{"kind":"float64","value":-0.0}"#).expect("-0.0");
10913        assert!(matches!(negative_zero, Scalar::Float64(v) if v == 0.0 && v.is_sign_negative()));
10914        assert!(matches!(
10915            back(r#"{"kind":"float64","value":null}"#).expect("null"),
10916            Scalar::Float64(v) if v.is_nan()
10917        ));
10918        // Anything else is an error, not a silent NaN.
10919        assert!(back(r#"{"kind":"float64","value":"Infinity"}"#).is_err());
10920        assert!(back(r#"{"kind":"float64","value":"1.5"}"#).is_err());
10921    }
10922
10923    /// br-frankenpandas-ay8o9: Scalar::semantic_cmp underpins ALL ordering in
10924    /// the library (sort, min/max, is_monotonic, searchsorted, groupby key
10925    /// order) and is the reference the differential harnesses rely on. Property
10926    /// test of its total-order axioms over finite/non-NaT same-dtype scalars,
10927    /// plus the intentional NaN degeneracy. Deterministic seeded LCG — no rand
10928    /// crate, no mocks.
10929    /// br-frankenpandas-767ak: extends ay8o9's NaN pinning to the temporal NAT
10930    /// sentinels (i64::MIN). semantic_cmp treats NAT as degenerate (Equal to all
10931    /// same-dtype), which is why temporal ordering ops must treat NAT as missing.
10932    #[test]
10933    fn semantic_cmp_cross_numeric_int_float_cdpai() {
10934        // Property (br-frankenpandas-cdpai): semantic_cmp compares Int64 vs Float64
10935        // as f64, antisymmetric across the operand order. Seeded LCG, no mocks.
10936        use std::cmp::Ordering;
10937        let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
10938        let mut next = || {
10939            st = st
10940                .wrapping_mul(6_364_136_223_846_793_005)
10941                .wrapping_add(1_442_695_040_888_963_407);
10942            (st >> 33) as u32
10943        };
10944        for _ in 0..3000u32 {
10945            let i = (next() % 21) as i64 - 10;
10946            let f = (next() % 400) as f64 / 20.0 - 10.0; // finite
10947            let exp = (i as f64).partial_cmp(&f).unwrap();
10948            assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
10949            assert_eq!(
10950                Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
10951                exp.reverse()
10952            );
10953        }
10954        // Exact int/float equality compares Equal in both directions.
10955        assert_eq!(
10956            Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
10957            Ordering::Equal
10958        );
10959        assert_eq!(
10960            Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
10961            Ordering::Equal
10962        );
10963        assert_eq!(
10964            Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
10965            Ordering::Less
10966        );
10967        assert_eq!(
10968            Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
10969            Ordering::Greater
10970        );
10971    }
10972
10973    #[test]
10974    fn semantic_cmp_nat_degeneracy_temporal_767ak() {
10975        use std::cmp::Ordering;
10976        const NAT: i64 = i64::MIN;
10977
10978        // Timedelta64 NAT is degenerate (Equal to finite and to itself).
10979        let td_nat = Scalar::Timedelta64(NAT);
10980        for v in [-3i64, 0, 5, 99] {
10981            let td = Scalar::Timedelta64(v);
10982            assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
10983            assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
10984        }
10985        assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
10986
10987        // Datetime64 NAT likewise.
10988        let dt_nat = Scalar::Datetime64(NAT);
10989        for v in [-3i64, 0, 5, 99] {
10990            let dt = Scalar::Datetime64(v);
10991            assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
10992            assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
10993        }
10994        assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
10995
10996        // Non-NAT temporal values order normally (reflexive, antisymmetric, lt).
10997        for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
10998            let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
10999            assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
11000            assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); // a.cmp(b)
11001            assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
11002            let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
11003            assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
11004        }
11005    }
11006
11007    fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
11008        [
11009            Scalar::Null(NullKind::Null),
11010            Scalar::Bool(true),
11011            Scalar::Int64(-7),
11012            Scalar::Float64(3.5),
11013            Scalar::Utf8("mixed".to_owned()),
11014            Scalar::Timedelta64(11),
11015            Scalar::Datetime64(1_735_732_800_123_456_789),
11016            Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
11017            Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
11018        ]
11019    }
11020
11021    fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
11022        !matches!(
11023            (left, right),
11024            (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
11025        )
11026    }
11027
11028    #[test]
11029    fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
11030        let values = semantic_cmp_cross_variant_values_d5ikg();
11031        for (left_index, left) in values.iter().enumerate() {
11032            for (right_index, right) in values.iter().enumerate() {
11033                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11034                {
11035                    assert_eq!(
11036                        left.semantic_cmp(right),
11037                        format!("{left:?}").cmp(&format!("{right:?}")),
11038                        "cross-variant order mismatch: {left:?} vs {right:?}"
11039                    );
11040                }
11041            }
11042        }
11043    }
11044
11045    #[test]
11046    #[ignore = "foreground release attribution harness"]
11047    fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
11048        use std::cmp::Ordering;
11049
11050        const BATCH: usize = 4_096;
11051        const BLOCKS: usize = 9;
11052
11053        fn former(left: &Scalar, right: &Scalar) -> Ordering {
11054            format!("{left:?}").cmp(&format!("{right:?}"))
11055        }
11056
11057        fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
11058            left.semantic_cmp(right)
11059        }
11060
11061        fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
11062            let mut less = 0usize;
11063            let started = std::time::Instant::now();
11064            for _ in 0..BATCH {
11065                for (left_index, left) in values.iter().enumerate() {
11066                    for (right_index, right) in values.iter().enumerate() {
11067                        if left_index != right_index
11068                            && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11069                            && compare(std::hint::black_box(left), std::hint::black_box(right))
11070                                == Ordering::Less
11071                        {
11072                            less += 1;
11073                        }
11074                    }
11075                }
11076            }
11077            std::hint::black_box(less);
11078            started.elapsed().as_nanos()
11079        }
11080
11081        fn median(samples: &mut [u128]) -> u128 {
11082            samples.sort_unstable();
11083            samples[samples.len() / 2]
11084        }
11085
11086        let values = semantic_cmp_cross_variant_values_d5ikg();
11087
11088        for (left_index, left) in values.iter().enumerate() {
11089            for (right_index, right) in values.iter().enumerate() {
11090                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11091                {
11092                    assert_eq!(
11093                        former(left, right),
11094                        candidate(left, right),
11095                        "cross-variant order mismatch: {left:?} vs {right:?}"
11096                    );
11097                }
11098            }
11099        }
11100
11101        std::hint::black_box(elapsed(&values, former));
11102        std::hint::black_box(elapsed(&values, candidate));
11103
11104        let mut former_samples = Vec::with_capacity(BLOCKS * 2);
11105        let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
11106        for block in 0..BLOCKS {
11107            if block.is_multiple_of(2) {
11108                former_samples.push(elapsed(&values, former));
11109                candidate_samples.push(elapsed(&values, candidate));
11110                candidate_samples.push(elapsed(&values, candidate));
11111                former_samples.push(elapsed(&values, former));
11112            } else {
11113                candidate_samples.push(elapsed(&values, candidate));
11114                former_samples.push(elapsed(&values, former));
11115                former_samples.push(elapsed(&values, former));
11116                candidate_samples.push(elapsed(&values, candidate));
11117            }
11118        }
11119
11120        let former_p50 = median(&mut former_samples);
11121        let candidate_p50 = median(&mut candidate_samples);
11122        eprintln!(
11123            "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
11124            former_p50 as f64 / candidate_p50 as f64
11125        );
11126    }
11127
11128    #[test]
11129    fn semantic_cmp_total_order_axioms_ay8o9() {
11130        use std::cmp::Ordering;
11131
11132        let mut state: u64 = 0xc0ff_eeba_df00_d123;
11133        let mut next = || {
11134            state = state
11135                .wrapping_mul(6_364_136_223_846_793_005)
11136                .wrapping_add(1_442_695_040_888_963_407);
11137            (state >> 33) as u32
11138        };
11139
11140        for iter in 0..6000u32 {
11141            let dt = next() % 4;
11142            // Build a same-dtype, finite, non-NaT scalar from a random u32.
11143            let mk = |r: u32| match dt {
11144                0 => Scalar::Int64((r % 11) as i64 - 5),
11145                // finite, in -5.0..=5.0 by 0.5 — no NaN/inf.
11146                1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
11147                2 => Scalar::Utf8(format!("s{}", r % 5)),
11148                _ => Scalar::Bool(r.is_multiple_of(2)),
11149            };
11150            let a = mk(next());
11151            let b = mk(next());
11152            let c = mk(next());
11153            let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
11154
11155            // Reflexivity.
11156            assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
11157            // Antisymmetry.
11158            assert_eq!(
11159                a.semantic_cmp(&b),
11160                b.semantic_cmp(&a).reverse(),
11161                "antisymmetric {ctx}"
11162            );
11163            // le / ge / eq consistency with the ordering.
11164            let ab = a.semantic_cmp(&b);
11165            assert_eq!(
11166                a.semantic_le(&b),
11167                ab != Ordering::Greater,
11168                "le-consistent {ctx}"
11169            );
11170            assert_eq!(
11171                a.semantic_ge(&b),
11172                ab != Ordering::Less,
11173                "ge-consistent {ctx}"
11174            );
11175            assert_eq!(
11176                a.semantic_le(&b) && a.semantic_ge(&b),
11177                ab == Ordering::Equal,
11178                "le&ge<=>eq {ctx}"
11179            );
11180            // Transitivity: a<=b && b<=c  =>  a<=c.
11181            if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
11182                assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
11183            }
11184        }
11185
11186        // Pin the intentional NaN degeneracy: a Float64 NaN compares Equal to
11187        // every finite Float64 (and to itself) — this is why ordering ops must
11188        // treat NaN as missing rather than relying on semantic_cmp to order it.
11189        let nan = Scalar::Float64(f64::NAN);
11190        for v in [
11191            Scalar::Float64(-3.5),
11192            Scalar::Float64(0.0),
11193            Scalar::Float64(7.25),
11194        ] {
11195            assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
11196            assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
11197        }
11198        assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
11199    }
11200
11201    /// br-frankenpandas-be314: common_dtype is the dtype-promotion lattice
11202    /// underpinning every binary op, alignment, and concat (dtype coercion is a
11203    /// crown-jewel correctness area). Exhaustively (all 14x14 DType pairs) assert
11204    /// its lattice axioms — an asymmetric arm would make df1+df2 and df2+df1
11205    /// disagree on dtype.
11206    #[test]
11207    fn common_dtype_lattice_axioms_be314() {
11208        let all: [DType; 14] = [
11209            DType::Null,
11210            DType::Bool,
11211            DType::BoolNullable,
11212            DType::Int64,
11213            DType::Int64Nullable,
11214            DType::Float64,
11215            // br-frankenpandas-qkqfb: a new variant is only safe once the
11216            // commutativity and associativity sweeps below cover it.
11217            DType::Float64Nullable,
11218            DType::Utf8,
11219            DType::Categorical,
11220            DType::Timedelta64,
11221            DType::datetime64_naive(),
11222            DType::Period,
11223            DType::Interval,
11224            DType::Sparse,
11225        ];
11226
11227        for a in &all {
11228            // Idempotence: a promoted with itself is itself.
11229            assert_eq!(
11230                common_dtype(a.clone(), a.clone()),
11231                Ok(a.clone()),
11232                "idempotent {a:?}"
11233            );
11234            // Null is the identity element of the promotion lattice.
11235            assert_eq!(
11236                common_dtype(DType::Null, a.clone()),
11237                Ok(a.clone()),
11238                "null-left identity {a:?}"
11239            );
11240            assert_eq!(
11241                common_dtype(a.clone(), DType::Null),
11242                Ok(a.clone()),
11243                "null-right identity {a:?}"
11244            );
11245
11246            for b in &all {
11247                // Commutativity: same Ok value AND same ok-ness. An asymmetric
11248                // match arm would make binary-op output dtype order-dependent.
11249                assert_eq!(
11250                    common_dtype(a.clone(), b.clone()).ok(),
11251                    common_dtype(b.clone(), a.clone()).ok(),
11252                    "commutative value {a:?},{b:?}"
11253                );
11254                assert_eq!(
11255                    common_dtype(a.clone(), b.clone()).is_ok(),
11256                    common_dtype(b.clone(), a.clone()).is_ok(),
11257                    "commutative ok-ness {a:?},{b:?}"
11258                );
11259            }
11260        }
11261
11262        // Associativity over the Ok-closed subset: when both nestings succeed,
11263        // promotion order must not change the result.
11264        for a in &all {
11265            for b in &all {
11266                for c in &all {
11267                    if let (Ok(ab), Ok(bc)) = (
11268                        common_dtype(a.clone(), b.clone()),
11269                        common_dtype(b.clone(), c.clone()),
11270                    ) && let (Ok(left), Ok(right)) =
11271                        (common_dtype(ab, c.clone()), common_dtype(a.clone(), bc))
11272                    {
11273                        assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
11274                    }
11275                }
11276            }
11277        }
11278    }
11279
11280    /// br-frankenpandas-e3sfq: infer_dtype drives Column/Series construction
11281    /// dtype inference. Assert its homogeneous + mixed-coercion rules.
11282    #[test]
11283    fn infer_dtype_coercion_rules_e3sfq() {
11284        use DType::{Bool, Float64, Int64, Null, Utf8};
11285
11286        // Empty and all-null infer to Null.
11287        assert_eq!(infer_dtype(&[]), Ok(Null));
11288        assert_eq!(
11289            infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
11290            Ok(Null)
11291        );
11292
11293        // Homogeneous slices infer to their own dtype (random, seeded LCG).
11294        let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
11295        let mut next = || {
11296            s = s
11297                .wrapping_mul(6_364_136_223_846_793_005)
11298                .wrapping_add(1_442_695_040_888_963_407);
11299            (s >> 33) as u32
11300        };
11301        for _ in 0..600u32 {
11302            let n = (next() % 6) as usize + 1;
11303            let ints: Vec<Scalar> = (0..n)
11304                .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
11305                .collect();
11306            assert_eq!(infer_dtype(&ints), Ok(Int64));
11307            let floats: Vec<Scalar> = (0..n)
11308                .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
11309                .collect();
11310            assert_eq!(infer_dtype(&floats), Ok(Float64));
11311            let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
11312            assert_eq!(infer_dtype(&bools), Ok(Bool));
11313            let strs: Vec<Scalar> = (0..n)
11314                .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
11315                .collect();
11316            assert_eq!(infer_dtype(&strs), Ok(Utf8));
11317        }
11318
11319        // Mixed-coercion rules.
11320        assert_eq!(
11321            infer_dtype(&[
11322                Scalar::Int64(1),
11323                Scalar::Null(NullKind::Null),
11324                Scalar::Int64(2)
11325            ]),
11326            Ok(Int64),
11327            "Int64 + nulls -> Int64"
11328        );
11329        assert_eq!(
11330            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
11331            Ok(Float64),
11332            "Int64 + Float64 -> Float64"
11333        );
11334        // br-frankenpandas-rh1od: MEASURED live pandas 2.2.3 — a bool mixed
11335        // with numerics constructs OBJECT; the old Int64 coercion here was
11336        // numpy common-type behavior no pandas constructor path produces.
11337        assert_eq!(
11338            infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
11339            Ok(Utf8),
11340            "Bool + Int64 -> object bucket (pandas constructs object)"
11341        );
11342        assert_eq!(
11343            infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
11344            Ok(Utf8),
11345            "Utf8 + Int64 -> Utf8 (object fallback)"
11346        );
11347    }
11348
11349    /// br-frankenpandas-1ews0: missing_for_dtype is the canonical per-dtype
11350    /// missing sentinel (used by null-fill / with_validity / cast). Exhaustively
11351    /// assert it is always missing, and that casting any missing to any dtype
11352    /// stays missing.
11353    #[test]
11354    fn missing_for_dtype_always_missing_1ews0() {
11355        let all: [DType; 14] = [
11356            DType::Null,
11357            DType::Bool,
11358            DType::BoolNullable,
11359            DType::Int64,
11360            DType::Int64Nullable,
11361            DType::Float64,
11362            DType::Float64Nullable,
11363            DType::Utf8,
11364            DType::Categorical,
11365            DType::Timedelta64,
11366            DType::datetime64_naive(),
11367            DType::Period,
11368            DType::Interval,
11369            DType::Sparse,
11370        ];
11371        for dt in &all {
11372            let m = Scalar::missing_for_dtype(dt.clone());
11373            assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
11374            for target in &all {
11375                let cast = cast_scalar(&m, target.clone()).expect("cast of missing");
11376                if target == &DType::Utf8 {
11377                    // Casting a missing value to string follows pandas astype(str):
11378                    // it yields a string ("None"/"NaN"/"NaT"), NOT a missing value.
11379                    assert!(
11380                        matches!(cast, Scalar::Utf8(_)),
11381                        "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
11382                    );
11383                } else if matches!(dt, DType::Timedelta64 | DType::Datetime64 { .. })
11384                    && matches!(target, DType::Bool | DType::Int64)
11385                {
11386                    // ⚠️ TWO MORE PLACES pandas BREAKS this invariant, and both
11387                    // are the same underlying fact: NaT is not a separate
11388                    // representation, it IS i64::MIN, and the numpy casts read
11389                    // the bits. MEASURED, live pandas 2.2.3:
11390                    //
11391                    //   pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
11392                    //     -> -9223372036854775808      the SENTINEL, not a missing
11393                    //   pd.Series([pd.NaT], dtype='timedelta64[ns]').astype('bool')
11394                    //     -> True                      nonzero, so truthy
11395                    //
11396                    // Same shape as the Utf8 carve-out above: the invariant is
11397                    // FrankenPandas' own, and pandas does not honour it wherever
11398                    // a cast is defined to reinterpret rather than to convert.
11399                    // Narrowly scoped on purpose — every other missing, and these
11400                    // two toward every other target, still stay missing.
11401                    match target {
11402                        DType::Bool => assert_eq!(
11403                            cast,
11404                            Scalar::Bool(true),
11405                            "cast(missing {dt:?} -> Bool) is pandas' nonzero-truthy \
11406                             read of the NaT bits"
11407                        ),
11408                        _ => assert_eq!(
11409                            cast,
11410                            Scalar::Int64(i64::MIN),
11411                            "cast(missing {dt:?} -> Int64) is the NaT sentinel itself"
11412                        ),
11413                    }
11414                } else {
11415                    // Every other target preserves missingness via cast_scalar's
11416                    // value.is_missing() -> missing_for_dtype(target) branch.
11417                    assert!(
11418                        cast.is_missing(),
11419                        "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
11420                    );
11421                }
11422            }
11423        }
11424    }
11425
11426    #[test]
11427    fn cast_scalar_bool_int_roundtrip_6w07b() {
11428        use super::cast_scalar;
11429        // Property (br-frankenpandas-6w07b): Bool<->Int64 cast. Seeded LCG, no mocks.
11430        assert_eq!(
11431            cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
11432            Scalar::Int64(1)
11433        );
11434        assert_eq!(
11435            cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
11436            Scalar::Int64(0)
11437        );
11438        assert_eq!(
11439            cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
11440            Scalar::Bool(false)
11441        );
11442        let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
11443        let mut next = || {
11444            st = st
11445                .wrapping_mul(6_364_136_223_846_793_005)
11446                .wrapping_add(1_442_695_040_888_963_407);
11447            (st >> 33) as u32
11448        };
11449        for _ in 0..2000u32 {
11450            let v = (next() % 21) as i64 - 10;
11451            assert_eq!(
11452                cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
11453                Scalar::Bool(v != 0),
11454                "int->bool v={v}"
11455            );
11456        }
11457    }
11458
11459    /// br-frankenpandas-6a83t: cast_scalar is the scalar dtype-coercion path
11460    #[test]
11461    fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
11462        use super::cast_scalar;
11463        // Property (br-frankenpandas-u9lec): Float64->Int64 truncates toward zero, not
11464        // floor (-3.7 -> -3). Seeded LCG, no mocks.
11465        let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
11466        let mut next = || {
11467            st = st
11468                .wrapping_mul(6_364_136_223_846_793_005)
11469                .wrapping_add(1_442_695_040_888_963_407);
11470            (st >> 33) as u32
11471        };
11472        // Explicit negative-direction checks (the gotcha).
11473        for (f, exp) in [
11474            (-3.7, -3i64),
11475            (3.7, 3),
11476            (-3.2, -3),
11477            (3.2, 3),
11478            (-0.9, 0),
11479            (0.9, 0),
11480            (-5.0, -5),
11481            (5.0, 5),
11482        ] {
11483            assert_eq!(
11484                cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
11485                Scalar::Int64(exp),
11486                "cast {f}"
11487            );
11488        }
11489        // Property over random signed fractional values.
11490        for _ in 0..3000u32 {
11491            let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; // [-1000, 1000]
11492            let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
11493            assert_eq!(
11494                got,
11495                Scalar::Int64(v.trunc() as i64),
11496                "trunc-toward-zero v={v}"
11497            );
11498        }
11499    }
11500
11501    /// Float -> `datetime64[ns]` / `timedelta64[ns]` reinterprets the float as
11502    /// integer NANOSECONDS. Every value here is transcribed from live pandas
11503    /// 2.2.3, measured on both the constructor and `astype` paths.
11504    ///
11505    /// ⚠️ THE CONTRAST WITH `int64` IS THE POINT: the explicit constructor
11506    /// REFUSES a lossy float -> int64, and silently truncates the same float
11507    /// into a temporal dtype. Assuming one rule covers both is how this gets
11508    /// re-broken, so both are asserted here on the same input.
11509    #[test]
11510    fn cast_scalar_float_to_temporal_truncates_to_nanoseconds() {
11511        use super::{Timedelta, Timestamp, cast_scalar};
11512
11513        // TRUNCATION TOWARD ZERO, on both signs, where a floor would disagree.
11514        // pandas: 0.9 -> 0, -0.9 -> 0, 1.5 -> 1, -1.5 -> -1, -2.5 -> -2.
11515        for (input, want) in [
11516            (1.5_f64, 1_i64),
11517            (-1.5, -1),
11518            (0.9, 0),
11519            (-0.9, 0),
11520            (2.5, 2),
11521            (-2.5, -2),
11522            (1.999_999, 1),
11523            (-1.999_999, -1),
11524            (2.0, 2),
11525            (1e18, 1_000_000_000_000_000_000),
11526        ] {
11527            assert_eq!(
11528                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11529                Scalar::Datetime64(want),
11530                "datetime64 cast of {input}"
11531            );
11532            assert_eq!(
11533                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11534                Scalar::Timedelta64(want),
11535                "timedelta64 cast of {input}"
11536            );
11537        }
11538
11539        // ANYTHING NOT REPRESENTABLE AS i64 IS NaT — not a saturated i64::MAX,
11540        // and not the epoch. A bare `as i64` would produce both of those wrong
11541        // answers (saturation for the large values, 0 for NaN).
11542        for input in [
11543            f64::NAN,
11544            f64::INFINITY,
11545            f64::NEG_INFINITY,
11546            1e30,
11547            -1e30,
11548            9.3e18,
11549            -9.3e18,
11550            9_223_372_036_854_775_808.0,  // exactly 2^63
11551            -9_223_372_036_854_775_808.0, // exactly -2^63, which IS the NaT sentinel
11552        ] {
11553            assert_eq!(
11554                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11555                Scalar::Datetime64(Timestamp::NAT),
11556                "datetime64 cast of {input} must be NaT"
11557            );
11558            assert_eq!(
11559                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11560                Scalar::Timedelta64(Timedelta::NAT),
11561                "timedelta64 cast of {input} must be NaT"
11562            );
11563        }
11564
11565        // ...but the largest float BELOW 2^63 is representable and converts.
11566        // pandas renders it 2262-04-11 23:47:16.854774784.
11567        let just_inside = 9_223_372_036_854_774_784.0_f64; // 2^63 - 1024
11568        assert_eq!(
11569            cast_scalar(&Scalar::Float64(just_inside), DType::datetime64_naive()).unwrap(),
11570            Scalar::Datetime64(9_223_372_036_854_774_784),
11571            "the largest representable float must NOT be treated as NaT"
11572        );
11573
11574        // THE CONTRAST. Same input, three dtypes, two different rules — the
11575        // temporal ones truncate where int64 refuses outright.
11576        assert_eq!(
11577            cast_scalar(&Scalar::Float64(1.5), DType::datetime64_naive()).unwrap(),
11578            Scalar::Datetime64(1)
11579        );
11580        assert_eq!(
11581            cast_scalar(&Scalar::Float64(1.5), DType::Int64).unwrap(),
11582            Scalar::Int64(1),
11583            "the SHARED cast truncates here too; it is the explicit constructor \
11584             that refuses, via Column::new's LossyFloatToInt pre-check"
11585        );
11586    }
11587
11588    /// The MIRROR direction: `datetime64[ns]` / `timedelta64[ns]` -> numpy
11589    /// `int64` is the raw nanosecond count, and a bool is 0 or 1 nanoseconds
11590    /// going the other way. Every value transcribed from live pandas 2.2.3
11591    /// `astype`.
11592    #[test]
11593    fn cast_scalar_temporal_to_int64_is_raw_nanoseconds() {
11594        use super::{Timedelta, Timestamp, cast_scalar};
11595
11596        // Timestamp('2024-03-15 10:30:45.123456789') and
11597        // Timedelta('1 days 02:03:04.005006007').
11598        for nanos in [1_710_498_645_123_456_789_i64, 93_784_005_006_007, 0, -1] {
11599            assert_eq!(
11600                cast_scalar(&Scalar::Datetime64(nanos), DType::Int64).unwrap(),
11601                Scalar::Int64(nanos),
11602                "datetime64 -> int64 must be the raw nanos ({nanos})"
11603            );
11604            assert_eq!(
11605                cast_scalar(&Scalar::Timedelta64(nanos), DType::Int64).unwrap(),
11606                Scalar::Int64(nanos)
11607            );
11608        }
11609
11610        // ⚠️ NaT BECOMES THE SENTINEL, NOT A MISSING VALUE. pandas:
11611        //     pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
11612        //       -> -9223372036854775808
11613        // This is the assertion that pins the cast ABOVE the is_missing()
11614        // branch; move it below and both of these become Null.
11615        assert_eq!(
11616            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Int64).unwrap(),
11617            Scalar::Int64(i64::MIN),
11618            "NaT -> int64 is the sentinel i64::MIN, not a missing value"
11619        );
11620        assert_eq!(
11621            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Int64).unwrap(),
11622            Scalar::Int64(i64::MIN)
11623        );
11624
11625        // ⚠️ THE NULLABLE Int64 REFUSES WHAT numpy int64 ACCEPTS:
11626        //     .astype('Int64')   -> TypeError: datetime64[ns] cannot be
11627        //                          converted to IntegerDtype
11628        //     .astype('float64') -> TypeError: Cannot cast DatetimeArray
11629        // Both must stay refused, which is what makes the guard on the exact
11630        // target load-bearing rather than cosmetic.
11631        // `DType` stopped being `Copy` when `Datetime64 { tz }` landed
11632        // (2f159e68f), so the loop variable is cloned into each call.
11633        for target in [DType::Int64Nullable, DType::Float64, DType::Float64Nullable] {
11634            assert!(
11635                cast_scalar(
11636                    &Scalar::Datetime64(1_710_498_645_123_456_789),
11637                    target.clone()
11638                )
11639                .is_err(),
11640                "datetime64 -> {target:?} must stay refused"
11641            );
11642            assert!(
11643                cast_scalar(&Scalar::Timedelta64(93_784_005_006_007), target.clone()).is_err(),
11644                "timedelta64 -> {target:?} must stay refused"
11645            );
11646        }
11647
11648        // A bool is 0 or 1 NANOSECONDS on the astype path.
11649        for (flag, want) in [(true, 1_i64), (false, 0)] {
11650            assert_eq!(
11651                cast_scalar(&Scalar::Bool(flag), DType::datetime64_naive()).unwrap(),
11652                Scalar::Datetime64(want)
11653            );
11654            assert_eq!(
11655                cast_scalar(&Scalar::Bool(flag), DType::Timedelta64).unwrap(),
11656                Scalar::Timedelta64(want)
11657            );
11658        }
11659    }
11660
11661    /// The two halves of the column-width datetime formatter, checked apart:
11662    /// which rung a value NEEDS, and how a value RENDERS at a given rung.
11663    /// Transcribed from live pandas 2.2.3 `.astype(str)`, one column per rung.
11664    #[test]
11665    fn timestamp_string_resolution_and_formatting_match_pandas() {
11666        use super::{DatetimeStringResolution as Res, Timestamp};
11667
11668        const MIDNIGHT: i64 = 1_710_460_800_000_000_000; // 2024-03-15 00:00:00
11669
11670        // Which rung each value needs, on its own.
11671        assert_eq!(Timestamp::string_resolution(MIDNIGHT), Res::Date);
11672        assert_eq!(
11673            Timestamp::string_resolution(MIDNIGHT + 37_845_000_000_000),
11674            Res::Second
11675        );
11676        assert_eq!(
11677            Timestamp::string_resolution(MIDNIGHT + 37_845_123_000_000),
11678            Res::Milli
11679        );
11680        assert_eq!(
11681            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_000),
11682            Res::Micro
11683        );
11684        assert_eq!(
11685            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_789),
11686            Res::Nano
11687        );
11688        // A whole MINUTE is not its own rung — it still needs Second.
11689        assert_eq!(
11690            Timestamp::string_resolution(MIDNIGHT + 300_000_000_000),
11691            Res::Second
11692        );
11693        // NaT reports the coarsest rung, the identity of the `max` fold, which
11694        // is what keeps it from dragging a column to nanoseconds.
11695        assert_eq!(Timestamp::string_resolution(Timestamp::NAT), Res::Date);
11696
11697        // Coarsest-first ordering is what makes `max` mean "finest needed".
11698        assert!(Res::Date < Res::Second);
11699        assert!(Res::Second < Res::Milli);
11700        assert!(Res::Milli < Res::Micro);
11701        assert!(Res::Micro < Res::Nano);
11702
11703        // ...and how ONE value renders at each rung it might be forced into.
11704        let value = MIDNIGHT + 37_845_123_456_789;
11705        assert_eq!(
11706            Timestamp::format_at_resolution(value, Res::Date),
11707            "2024-03-15"
11708        );
11709        assert_eq!(
11710            Timestamp::format_at_resolution(value, Res::Second),
11711            "2024-03-15 10:30:45"
11712        );
11713        assert_eq!(
11714            Timestamp::format_at_resolution(value, Res::Milli),
11715            "2024-03-15 10:30:45.123"
11716        );
11717        assert_eq!(
11718            Timestamp::format_at_resolution(value, Res::Micro),
11719            "2024-03-15 10:30:45.123456"
11720        );
11721        assert_eq!(
11722            Timestamp::format_at_resolution(value, Res::Nano),
11723            "2024-03-15 10:30:45.123456789"
11724        );
11725
11726        // A midnight forced to the nanosecond rung keeps its zero fraction --
11727        // pandas pads, it does not trim.
11728        assert_eq!(
11729            Timestamp::format_at_resolution(MIDNIGHT, Res::Nano),
11730            "2024-03-15 00:00:00.000000000"
11731        );
11732
11733        // ⚠️ NOT isoformat: a SPACE separator, not a `T`.
11734        assert_eq!(
11735            Timestamp::format_at_resolution(MIDNIGHT, Res::Second),
11736            "2024-03-15 00:00:00"
11737        );
11738
11739        // NaT is the STRING "NaT" at every rung.
11740        for resolution in [Res::Date, Res::Second, Res::Milli, Res::Micro, Res::Nano] {
11741            assert_eq!(
11742                Timestamp::format_at_resolution(Timestamp::NAT, resolution),
11743                "NaT"
11744            );
11745        }
11746
11747        // Pre-epoch: rem_euclid must keep the fraction on the right side of
11748        // midnight, or -1ns renders as 1970-01-01 with a negative fraction.
11749        assert_eq!(
11750            Timestamp::format_at_resolution(-1, Res::Nano),
11751            "1969-12-31 23:59:59.999999999"
11752        );
11753
11754        // Both ends of pandas' datetime64[ns] range.
11755        assert_eq!(
11756            Timestamp::format_at_resolution(-9_223_372_036_854_775_806, Res::Nano),
11757            "1677-09-21 00:12:43.145224194"
11758        );
11759        assert_eq!(
11760            Timestamp::format_at_resolution(9_223_372_036_854_775_807, Res::Nano),
11761            "2262-04-11 23:47:16.854775807"
11762        );
11763    }
11764
11765    /// Temporal -> numpy `bool` is nonzero-truthy on the RAW NANOSECONDS, which
11766    /// makes NaT `true`. Transcribed from live pandas 2.2.3 `.astype('bool')`,
11767    /// measured beside `.astype('int64')` so the one rule is visible as one rule.
11768    #[test]
11769    fn cast_scalar_temporal_to_bool_is_nonzero_on_the_nanos() {
11770        use super::{Timedelta, Timestamp, cast_scalar};
11771
11772        // Only the epoch and a zero duration are false.
11773        for (nanos, want) in [
11774            (0_i64, false),
11775            (1_710_498_645_123_456_789, true),
11776            (-1, true),
11777            (86_400_000_000_000, true),
11778            (1, true),
11779        ] {
11780            assert_eq!(
11781                cast_scalar(&Scalar::Datetime64(nanos), DType::Bool).unwrap(),
11782                Scalar::Bool(want),
11783                "datetime64 {nanos} -> bool"
11784            );
11785            assert_eq!(
11786                cast_scalar(&Scalar::Timedelta64(nanos), DType::Bool).unwrap(),
11787                Scalar::Bool(want),
11788                "timedelta64 {nanos} -> bool"
11789            );
11790        }
11791
11792        // ⚠️ NaT IS TRUE, not missing. It needs no case of its own — NaT IS
11793        // i64::MIN, which is nonzero — but it only reaches the rule because the
11794        // cast sits ABOVE is_missing(); below it, both of these become Null.
11795        assert_eq!(
11796            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Bool).unwrap(),
11797            Scalar::Bool(true),
11798            "NaT -> bool is true in pandas, not a missing value"
11799        );
11800        assert_eq!(
11801            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Bool).unwrap(),
11802            Scalar::Bool(true)
11803        );
11804
11805        // ⚠️ THE NULLABLE `boolean` REFUSES THE WHOLE DTYPE, not just the odd
11806        // value: pandas raises "Need to pass bool-like values" for every row
11807        // above, INCLUDING the ones whose nanos are 0 or 1. That exclusion is
11808        // what the `DType::Bool` guard buys, so it is asserted rather than
11809        // assumed.
11810        //
11811        // NaT is deliberately NOT in this loop, and the reason is a KNOWN
11812        // DIVERGENCE rather than an oversight: `is_missing()` catches NaT before
11813        // any BoolNullable arm can refuse it, so FP answers `Null` where pandas
11814        // raises. Asserting `is_err()` for it here would fail. Left visible.
11815        for nanos in [0_i64, 1, -1, 1_710_498_645_123_456_789] {
11816            assert!(
11817                cast_scalar(&Scalar::Datetime64(nanos), DType::BoolNullable).is_err(),
11818                "datetime64 {nanos} -> nullable boolean must stay refused"
11819            );
11820            assert!(
11821                cast_scalar(&Scalar::Timedelta64(nanos), DType::BoolNullable).is_err(),
11822                "timedelta64 {nanos} -> nullable boolean must stay refused"
11823            );
11824        }
11825    }
11826
11827    #[test]
11828    fn nancount_nunique_prod_any_all_mx60x() {
11829        use super::{nanall, nanany, nancount, nannunique, nanprod};
11830        // br-frankenpandas-mx60x: nancount/nannunique/nanprod/nanany/nanall skip NaN
11831        // and match finite-only oracles. Seeded LCG, no mocks.
11832        let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
11833        let mut next = || {
11834            s = s
11835                .wrapping_mul(6_364_136_223_846_793_005)
11836                .wrapping_add(1_442_695_040_888_963_407);
11837            (s >> 33) as u32
11838        };
11839        let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
11840        let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
11841        for iter in 0..1000u32 {
11842            let n = (next() % 10) as usize + 1;
11843            let raw: Vec<f64> = (0..n)
11844                .map(|_| {
11845                    if next() % 4 == 0 {
11846                        f64::NAN
11847                    } else {
11848                        (next() % 5) as f64
11849                    }
11850                })
11851                .collect();
11852            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
11853            if finite.is_empty() {
11854                continue;
11855            }
11856            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
11857            let distinct: std::collections::HashSet<u64> =
11858                finite.iter().map(|x| x.to_bits()).collect();
11859            let prod: f64 = finite.iter().product();
11860            assert!(
11861                (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
11862                "nancount iter={iter}"
11863            );
11864            assert!(
11865                (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
11866                "nannunique iter={iter}"
11867            );
11868            assert!(
11869                (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
11870                "nanprod iter={iter}"
11871            );
11872            assert_eq!(
11873                asb(nanany(&scalars)),
11874                finite.iter().any(|&x| x != 0.0),
11875                "nanany iter={iter}"
11876            );
11877            assert_eq!(
11878                asb(nanall(&scalars)),
11879                finite.iter().all(|&x| x != 0.0),
11880                "nanall iter={iter}"
11881            );
11882        }
11883    }
11884
11885    #[test]
11886    fn nan_reduction_kernels_skip_correctness_1uagc() {
11887        use super::{nanmax, nanmedian, nanmin, nansum};
11888        // br-frankenpandas-1uagc: nansum/nanmin/nanmax/nanmedian skip NaN and match
11889        // finite-only oracles. Seeded LCG, no mocks.
11890        let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
11891        let mut next = || {
11892            s = s
11893                .wrapping_mul(6_364_136_223_846_793_005)
11894                .wrapping_add(1_442_695_040_888_963_407);
11895            (s >> 33) as u32
11896        };
11897        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
11898        for iter in 0..1000u32 {
11899            let n = (next() % 12) as usize + 1;
11900            let raw: Vec<f64> = (0..n)
11901                .map(|_| {
11902                    if next() % 4 == 0 {
11903                        f64::NAN
11904                    } else {
11905                        (next() % 200) as f64 - 100.0
11906                    }
11907                })
11908                .collect();
11909            let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
11910            if finite.is_empty() {
11911                continue;
11912            }
11913            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
11914            let sum: f64 = finite.iter().sum();
11915            let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
11916            let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
11917            finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
11918            let m = finite.len();
11919            let med = if m % 2 == 1 {
11920                finite[m / 2]
11921            } else {
11922                (finite[m / 2 - 1] + finite[m / 2]) / 2.0
11923            };
11924            assert!(
11925                (val(nansum(&scalars)) - sum).abs() < 1e-7,
11926                "nansum iter={iter}"
11927            );
11928            assert!(
11929                (val(nanmin(&scalars)) - mn).abs() < 1e-9,
11930                "nanmin iter={iter}"
11931            );
11932            assert!(
11933                (val(nanmax(&scalars)) - mx).abs() < 1e-9,
11934                "nanmax iter={iter}"
11935            );
11936            assert!(
11937                (val(nanmedian(&scalars)) - med).abs() < 1e-9,
11938                "nanmedian iter={iter}"
11939            );
11940        }
11941    }
11942
11943    #[test]
11944    fn nanvar_ddof_nanstd_nan_skip_p00ag() {
11945        use super::{nanmean, nanstd, nanvar};
11946        // br-frankenpandas-p00ag: nanmean/nanvar/nanstd skip NaN; ddof picks the
11947        // denominator; nanstd==sqrt(nanvar). Seeded LCG, no mocks.
11948        let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
11949        let mut next = || {
11950            s = s
11951                .wrapping_mul(6_364_136_223_846_793_005)
11952                .wrapping_add(1_442_695_040_888_963_407);
11953            (s >> 33) as u32
11954        };
11955        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
11956        for iter in 0..1000u32 {
11957            let n = (next() % 10) as usize + 2;
11958            let raw: Vec<f64> = (0..n)
11959                .map(|_| {
11960                    if next() % 4 == 0 {
11961                        f64::NAN
11962                    } else {
11963                        (next() % 200) as f64 / 7.0
11964                    }
11965                })
11966                .collect();
11967            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
11968            if finite.len() < 2 {
11969                continue;
11970            }
11971            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
11972            let nf = finite.len() as f64;
11973            let mean = finite.iter().sum::<f64>() / nf;
11974            let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
11975            assert!(
11976                (val(nanmean(&scalars)) - mean).abs() < 1e-7,
11977                "nanmean iter={iter}"
11978            );
11979            assert!(
11980                (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
11981                "nanvar ddof0 iter={iter}"
11982            );
11983            assert!(
11984                (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
11985                "nanvar ddof1 iter={iter}"
11986            );
11987            assert!(
11988                (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
11989                "nanstd ddof1 iter={iter}"
11990            );
11991        }
11992    }
11993
11994    #[test]
11995    fn nanskew_nankurt_min_sample_and_known_xybnq() {
11996        // br-frankenpandas-xybnq: guard nanskew/nankurt min-sample-size (NaN below
11997        // threshold) + known pandas G1/G2 values (the f4dc5540 inline-copy bug area).
11998        use super::{nankurt, nanskew};
11999        let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
12000        let val = |s: Scalar| -> Option<f64> {
12001            if s.is_missing() {
12002                None
12003            } else {
12004                s.to_f64().ok()
12005            }
12006        };
12007
12008        // skew needs >= 3 observations.
12009        assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
12010        let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
12011        assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
12012        let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
12013        assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
12014
12015        // kurt needs >= 4 observations.
12016        assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
12017        let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
12018        assert!(
12019            (k - (-1.2)).abs() < 1e-6,
12020            "pandas kurt([1..5]) == -1.2, got {k}"
12021        );
12022    }
12023
12024    #[test]
12025    #[ignore = "foreground release attribution harness"]
12026    fn nanskew_fused_moment_scan_ab_mavln() {
12027        const ROWS: usize = 100_000;
12028        const BATCH: usize = 8;
12029
12030        fn former(values: &[Scalar]) -> Scalar {
12031            let nums = super::collect_finite(values);
12032            let n = nums.len() as f64;
12033            if n < 3.0 {
12034                return Scalar::Null(NullKind::NaN);
12035            }
12036            let mean = nums.iter().sum::<f64>() / n;
12037            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12038            let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
12039            let s2 = m2 / (n - 1.0);
12040            if s2 == 0.0 {
12041                return Scalar::Float64(0.0);
12042            }
12043            let s3 = s2.powf(1.5);
12044            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
12045        }
12046
12047        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12048            match (former, candidate) {
12049                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12050                (a, b) => assert_eq!(a, b),
12051            }
12052        }
12053
12054        fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
12055            std::hint::black_box(skew(std::hint::black_box(values)));
12056            let started = std::time::Instant::now();
12057            for _ in 0..BATCH {
12058                std::hint::black_box(skew(std::hint::black_box(values)));
12059            }
12060            started.elapsed().as_nanos()
12061        }
12062
12063        fn median(samples: &mut [u128]) -> u128 {
12064            samples.sort_unstable();
12065            samples[samples.len() / 2]
12066        }
12067
12068        for values in [
12069            vec![],
12070            vec![Scalar::Int64(1), Scalar::Int64(2)],
12071            vec![Scalar::Int64(7); 16],
12072            vec![
12073                Scalar::Int64(-3),
12074                Scalar::Null(NullKind::NaN),
12075                Scalar::Float64(2.5),
12076                Scalar::Utf8("skip".to_owned()),
12077                Scalar::Int64(11),
12078            ],
12079        ] {
12080            assert_bits_eq(former(&values), super::nanskew(&values));
12081        }
12082
12083        let values = (0..ROWS)
12084            .map(|i| {
12085                if i % 257 == 0 {
12086                    Scalar::Null(NullKind::NaN)
12087                } else {
12088                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12089                }
12090            })
12091            .collect::<Vec<_>>();
12092        assert_bits_eq(former(&values), super::nanskew(&values));
12093
12094        for _ in 0..2 {
12095            std::hint::black_box(elapsed(&values, former));
12096            std::hint::black_box(elapsed(&values, super::nanskew));
12097        }
12098
12099        let mut former_samples = Vec::with_capacity(18);
12100        let mut candidate_samples = Vec::with_capacity(18);
12101        for block in 0_usize..9 {
12102            if block.is_multiple_of(2) {
12103                former_samples.push(elapsed(&values, former));
12104                candidate_samples.push(elapsed(&values, super::nanskew));
12105                candidate_samples.push(elapsed(&values, super::nanskew));
12106                former_samples.push(elapsed(&values, former));
12107            } else {
12108                candidate_samples.push(elapsed(&values, super::nanskew));
12109                former_samples.push(elapsed(&values, former));
12110                former_samples.push(elapsed(&values, former));
12111                candidate_samples.push(elapsed(&values, super::nanskew));
12112            }
12113        }
12114
12115        let former_p50 = median(&mut former_samples);
12116        let candidate_p50 = median(&mut candidate_samples);
12117        eprintln!(
12118            "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12119            former_p50 as f64 / candidate_p50 as f64,
12120        );
12121        eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
12122        eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12123    }
12124
12125    #[test]
12126    #[ignore = "foreground performance probe"]
12127    fn nankurt_fused_moment_scan_ab_idka7() {
12128        const ROWS: usize = 65_536;
12129        const BATCH: usize = 4;
12130
12131        fn former(values: &[Scalar]) -> Scalar {
12132            let nums = super::collect_finite(values);
12133            let n = nums.len() as f64;
12134            if n < 4.0 {
12135                return Scalar::Null(NullKind::NaN);
12136            }
12137            let mean = nums.iter().sum::<f64>() / n;
12138            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12139            let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
12140            let s2 = m2 / (n - 1.0);
12141            if s2 == 0.0 {
12142                return Scalar::Float64(0.0);
12143            }
12144            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
12145            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
12146            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
12147        }
12148
12149        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12150            match (former, candidate) {
12151                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12152                (a, b) => assert_eq!(a, b),
12153            }
12154        }
12155
12156        fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
12157            let started = std::time::Instant::now();
12158            for _ in 0..BATCH {
12159                std::hint::black_box(kurt(std::hint::black_box(values)));
12160            }
12161            started.elapsed().as_nanos()
12162        }
12163
12164        fn median(samples: &mut [u128]) -> u128 {
12165            samples.sort_unstable();
12166            samples[samples.len() / 2]
12167        }
12168
12169        for values in [
12170            vec![],
12171            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12172            vec![Scalar::Int64(7); 16],
12173            vec![
12174                Scalar::Int64(-3),
12175                Scalar::Null(NullKind::NaN),
12176                Scalar::Float64(2.5),
12177                Scalar::Utf8("skip".to_owned()),
12178                Scalar::Int64(11),
12179                Scalar::Float64(-7.25),
12180            ],
12181        ] {
12182            assert_bits_eq(former(&values), super::nankurt(&values));
12183        }
12184
12185        let values = (0..ROWS)
12186            .map(|i| {
12187                if i % 257 == 0 {
12188                    Scalar::Null(NullKind::NaN)
12189                } else {
12190                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12191                }
12192            })
12193            .collect::<Vec<_>>();
12194        assert_bits_eq(former(&values), super::nankurt(&values));
12195
12196        for _ in 0..2 {
12197            std::hint::black_box(elapsed(&values, former));
12198            std::hint::black_box(elapsed(&values, super::nankurt));
12199        }
12200
12201        let mut former_samples = Vec::with_capacity(10);
12202        let mut candidate_samples = Vec::with_capacity(10);
12203        for block in 0_usize..5 {
12204            if block.is_multiple_of(2) {
12205                former_samples.push(elapsed(&values, former));
12206                candidate_samples.push(elapsed(&values, super::nankurt));
12207                candidate_samples.push(elapsed(&values, super::nankurt));
12208                former_samples.push(elapsed(&values, former));
12209            } else {
12210                candidate_samples.push(elapsed(&values, super::nankurt));
12211                former_samples.push(elapsed(&values, former));
12212                former_samples.push(elapsed(&values, former));
12213                candidate_samples.push(elapsed(&values, super::nankurt));
12214            }
12215        }
12216
12217        let former_p50 = median(&mut former_samples);
12218        let candidate_p50 = median(&mut candidate_samples);
12219        eprintln!(
12220            "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12221            former_p50 as f64 / candidate_p50 as f64,
12222        );
12223        eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
12224        eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12225    }
12226
12227    /// behind astype/promotion. Property test of its confirmed identity +
12228    /// numeric/bool coercion rules over random scalars. Deterministic seeded LCG.
12229    #[test]
12230    fn cast_scalar_to_utf8_formatting_yes7i() {
12231        // Property (br-frankenpandas-yes7i): cast to Utf8 formats per pandas
12232        // astype(str): Int64 -> decimal, Bool -> True/False. Seeded LCG, no mocks.
12233        let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
12234        let mut next = || {
12235            st = st
12236                .wrapping_mul(6_364_136_223_846_793_005)
12237                .wrapping_add(1_442_695_040_888_963_407);
12238            (st >> 33) as u32
12239        };
12240        for _ in 0..3000u32 {
12241            let n = (next() % 4_000_001) as i64 - 2_000_000;
12242            assert_eq!(
12243                cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
12244                Scalar::Utf8(n.to_string())
12245            );
12246        }
12247        assert_eq!(
12248            cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
12249            Scalar::Utf8("True".to_string())
12250        );
12251        assert_eq!(
12252            cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
12253            Scalar::Utf8("False".to_string())
12254        );
12255    }
12256
12257    #[test]
12258    fn cast_scalar_coercion_rules_6a83t() {
12259        let mut state: u64 = 0x5a17_c0de_1234_abcd;
12260        let mut next = || {
12261            state = state
12262                .wrapping_mul(6_364_136_223_846_793_005)
12263                .wrapping_add(1_442_695_040_888_963_407);
12264            (state >> 33) as u32
12265        };
12266
12267        for _ in 0..4000u32 {
12268            let n = (next() % 21) as i64 - 10; // -10..=10, incl 0
12269            let b = next() % 2 == 0;
12270            let f = f64::from((next() % 41) as i32 - 20) / 4.0; // finite, incl 0.0
12271
12272            let i = Scalar::Int64(n);
12273            let bo = Scalar::Bool(b);
12274            let fl = Scalar::Float64(f);
12275
12276            // Identity casts.
12277            assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
12278            assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
12279            assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
12280
12281            // Representation-preserving nullable identities.
12282            assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
12283            assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
12284
12285            // Int64 coercions.
12286            assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
12287            assert_eq!(
12288                cast_scalar(&i, DType::Float64),
12289                Ok(Scalar::Float64(n as f64))
12290            );
12291
12292            // Bool coercions.
12293            assert_eq!(
12294                cast_scalar(&bo, DType::Int64),
12295                Ok(Scalar::Int64(i64::from(b)))
12296            );
12297            assert_eq!(
12298                cast_scalar(&bo, DType::Float64),
12299                Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
12300            );
12301
12302            // Finite Float64 -> Int64 truncates toward zero (x as i64).
12303            assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
12304        }
12305    }
12306
12307    /// br-frankenpandas-esjjy / fd90.182: ergonomic From impls for Scalar.
12308    #[test]
12309    fn scalar_from_primitive_types() {
12310        // Each primitive maps to its canonical Scalar variant.
12311        assert_eq!(Scalar::from(true), Scalar::Bool(true));
12312        assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
12313        assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
12314        assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
12315        assert_eq!(
12316            Scalar::from(String::from("world")),
12317            Scalar::Utf8("world".to_owned())
12318        );
12319
12320        // .into() works in mixed-type Vec<Scalar> contexts (the README's
12321        // case_when example pattern, and what fd90.181 needed for apply_row
12322        // closures).
12323        let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
12324        assert_eq!(mixed[0], Scalar::Int64(1));
12325        assert_eq!(mixed[1], Scalar::Float64(2.0));
12326        assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
12327    }
12328
12329    #[test]
12330    fn dtype_inference_routes_bool_numeric_mix_to_object_bucket_rh1od() {
12331        // Was `dtype_inference_coerces_numeric_values` (Bool+Int64+Float64 ->
12332        // Float64). br-frankenpandas-rh1od, MEASURED live pandas 2.2.3:
12333        // pd.Series([True, 7, 3.5]) constructs OBJECT — no pandas constructor
12334        // path produces the numpy common-type Float64 here.
12335        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
12336        assert_eq!(
12337            infer_dtype(&values).expect("dtype should infer"),
12338            DType::Utf8
12339        );
12340    }
12341
12342    #[test]
12343    fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
12344        let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
12345        let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
12346        assert_eq!(left.dtype(), DType::Interval);
12347        assert!(!left.is_missing());
12348        assert_eq!(
12349            infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
12350            DType::Interval
12351        );
12352        assert_eq!(
12353            common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
12354            DType::Interval
12355        );
12356        assert_eq!(
12357            cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
12358            Scalar::Null(NullKind::Null)
12359        );
12360        assert_eq!(
12361            cast_scalar(&left, DType::Utf8).expect("interval string cast"),
12362            Scalar::Utf8("(0.0, 1.0]".to_owned())
12363        );
12364        assert_eq!(
12365            super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
12366            Scalar::Int64(2)
12367        );
12368    }
12369
12370    #[test]
12371    fn cast_scalar_parses_temporal_extension_strings_avm08() {
12372        let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
12373            .expect("timestamp parse")
12374            .nanos;
12375        assert_eq!(
12376            cast_scalar(
12377                &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
12378                DType::datetime64_naive()
12379            )
12380            .expect("datetime cast"),
12381            Scalar::Datetime64(expected_nanos)
12382        );
12383        assert_eq!(
12384            cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
12385            Scalar::Period(Period::new(216, PeriodFreq::Quarterly))
12386        );
12387        assert_eq!(
12388            cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
12389                .expect("interval cast"),
12390            Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
12391        );
12392    }
12393
12394    #[test]
12395    fn missing_values_get_target_missing_marker() {
12396        let missing = Scalar::Null(NullKind::Null);
12397        let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
12398        assert_eq!(cast, Scalar::Null(NullKind::NaN));
12399    }
12400
12401    #[test]
12402    fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
12403        let cases = [
12404            (Scalar::Bool(true), "True"),
12405            (Scalar::Bool(false), "False"),
12406            (Scalar::Int64(-7), "-7"),
12407            (Scalar::Float64(1.0), "1.0"),
12408            (Scalar::Float64(1.5), "1.5"),
12409            (Scalar::Float64(f64::NAN), "nan"),
12410            (Scalar::Null(NullKind::Null), "None"),
12411            (Scalar::Null(NullKind::NaN), "nan"),
12412            (Scalar::Null(NullKind::NaT), "NaT"),
12413        ];
12414
12415        for (value, expected) in cases {
12416            assert_eq!(
12417                cast_scalar(&value, DType::Utf8).expect("cast"),
12418                Scalar::Utf8(expected.to_owned())
12419            );
12420        }
12421    }
12422
12423    #[test]
12424    fn semantic_eq_treats_nan_as_equal() {
12425        let left = Scalar::Float64(f64::NAN);
12426        let right = Scalar::Null(NullKind::NaN);
12427        assert!(left.semantic_eq(&right));
12428    }
12429
12430    #[test]
12431    fn semantic_eq_treats_nan_as_missing_null() {
12432        let left = Scalar::Float64(f64::NAN);
12433        let right = Scalar::Null(NullKind::Null);
12434        assert!(left.semantic_eq(&right));
12435    }
12436
12437    /// A DTYPE-SENTINEL missing equals a `Null` marker, for every dtype that
12438    /// has one.
12439    ///
12440    /// `missing_for_dtype` DEFINES the canonical missing for Timedelta64 as
12441    /// `Timedelta64(NAT)`, for Datetime64 as `Datetime64(NAT)` and for Period as
12442    /// ordinal `i64::MIN`, and `is_missing()` agrees — but `semantic_eq` used to
12443    /// unify only the `Null`/NaN flavours, so an oracle's `null` for pandas' NaT
12444    /// could never match FP's sentinel. Observed on
12445    /// `fp_p2d_021_series_to_timedelta_negative_null_hardened`, where the
12446    /// fixture pinned the raw `-9223372036854775808` as though it were data.
12447    ///
12448    /// THE NEGATIVE CASES ARE THE POINT — "both missing" must not become "any
12449    /// sentinel matches anything":
12450    /// - a NaT sentinel must NOT equal a PRESENT timedelta;
12451    /// - two DIFFERENT present timedeltas must stay unequal;
12452    /// - Period and Datetime64 must unify too, or the fix is Timedelta-only.
12453    ///
12454    /// (br-frankenpandas-xwxci)
12455    #[test]
12456    fn semantic_eq_unifies_dtype_sentinel_missing_with_null_xwxci() {
12457        for sentinel in [
12458            Scalar::Timedelta64(Timedelta::NAT),
12459            Scalar::Datetime64(Timestamp::NAT),
12460            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
12461        ] {
12462            assert!(sentinel.is_missing(), "{sentinel:?} must report missing");
12463            for marker in [
12464                Scalar::Null(NullKind::Null),
12465                Scalar::Null(NullKind::NaN),
12466                Scalar::Null(NullKind::NaT),
12467            ] {
12468                assert!(
12469                    sentinel.semantic_eq(&marker),
12470                    "{sentinel:?} vs {marker:?} are both missing"
12471                );
12472                assert!(marker.semantic_eq(&sentinel), "and symmetrically");
12473            }
12474        }
12475
12476        // NOT a blanket match: a sentinel differs from a PRESENT value.
12477        let present = Scalar::Timedelta64(-60);
12478        assert!(!Scalar::Timedelta64(Timedelta::NAT).semantic_eq(&present));
12479        assert!(!present.semantic_eq(&Scalar::Null(NullKind::Null)));
12480        // And two distinct present values stay distinct.
12481        assert!(!present.semantic_eq(&Scalar::Timedelta64(-61)));
12482    }
12483
12484    #[test]
12485    fn common_dtype_rejects_string_numeric_mix() {
12486        let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
12487        assert_eq!(
12488            err.to_string(),
12489            "dtype coercion from Utf8 to Int64 has no compatible common type"
12490        );
12491        let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
12492        assert_eq!(
12493            err.to_string(),
12494            "dtype coercion from Float64 to Utf8 has no compatible common type"
12495        );
12496    }
12497
12498    #[test]
12499    fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
12500        let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
12501
12502        assert_eq!(dtype.value_dtype, DType::Float64);
12503        assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
12504    }
12505
12506    #[test]
12507    fn sparse_dtype_rejects_sparse_value_dtype() {
12508        let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
12509
12510        assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
12511    }
12512
12513    #[test]
12514    fn common_dtype_rejects_sparse_dense_mix() {
12515        let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
12516
12517        assert_eq!(
12518            err.to_string(),
12519            "dtype coercion from Sparse to Int64 has no compatible common type"
12520        );
12521    }
12522
12523    // ── Nullable Int64/Bool dtype tests (br-frankenpandas-rg8ys.6.4) ────
12524
12525    #[test]
12526    fn nullable_int64_promotion_matrix() {
12527        // Int64 + Int64Nullable -> Int64Nullable (nullable absorbs)
12528        assert_eq!(
12529            common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
12530            DType::Int64Nullable
12531        );
12532        assert_eq!(
12533            common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
12534            DType::Int64Nullable
12535        );
12536
12537        // Int64Nullable + Float64 -> Float64Nullable. The old comment here said
12538        // "float always wins"; that is half right. The float wins, but the
12539        // NULLABLE flavour of it does — MEASURED, live pandas 2.2.3:
12540        //   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5]) -> Float64
12541        // where that Float64 is the extension dtype (missing = pd.NA), not
12542        // numpy float64 (missing = NaN). (br-frankenpandas-qkqfb)
12543        assert_eq!(
12544            common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
12545            DType::Float64Nullable
12546        );
12547        assert_eq!(
12548            common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
12549            DType::Float64Nullable
12550        );
12551
12552        // Int64Nullable + Int64Nullable -> Int64Nullable
12553        assert_eq!(
12554            common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
12555            DType::Int64Nullable
12556        );
12557
12558        // Bool + Int64Nullable -> Int64Nullable
12559        assert_eq!(
12560            common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
12561            DType::Int64Nullable
12562        );
12563
12564        // BoolNullable + Int64 -> Int64Nullable
12565        assert_eq!(
12566            common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
12567            DType::Int64Nullable
12568        );
12569    }
12570
12571    #[test]
12572    fn nullable_bool_promotion_matrix() {
12573        // Bool + BoolNullable -> BoolNullable
12574        assert_eq!(
12575            common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
12576            DType::BoolNullable
12577        );
12578        assert_eq!(
12579            common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
12580            DType::BoolNullable
12581        );
12582
12583        // BoolNullable + Float64 -> Float64Nullable. MEASURED, live pandas 2.2.3:
12584        //   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
12585        //     -> Float64   (extension)
12586        // This arm moves together with the Int64Nullable one in
12587        // nullable_int64_promotion_matrix; flipping either alone breaks lattice
12588        // associativity. (br-frankenpandas-qkqfb)
12589        assert_eq!(
12590            common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
12591            DType::Float64Nullable
12592        );
12593
12594        // CONTROL: the all-numpy pair is untouched and stays on the numpy side.
12595        //   pd.Series([True,False],dtype="bool") + pd.Series([1.5,2.5]) -> float64
12596        assert_eq!(
12597            common_dtype(DType::Bool, DType::Float64).unwrap(),
12598            DType::Float64
12599        );
12600    }
12601
12602    #[test]
12603    fn dtype_is_nullable_helper() {
12604        assert!(DType::Int64Nullable.is_nullable());
12605        assert!(DType::BoolNullable.is_nullable());
12606        assert!(!DType::Int64.is_nullable());
12607        assert!(!DType::Bool.is_nullable());
12608        assert!(!DType::Float64.is_nullable());
12609        assert!(!DType::Utf8.is_nullable());
12610    }
12611
12612    #[test]
12613    fn dtype_to_nullable_conversions() {
12614        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
12615        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
12616        // ⚠ THIS LINE WAS RED ON main SINCE fa6caee91 AND NOBODY SAW IT.
12617        // It used to read `Float64.to_nullable() == Float64  // unchanged`,
12618        // which was true only while FP had no nullable float at all. fa6caee91
12619        // (br-frankenpandas-qkqfb slice 1) added DType::Float64Nullable and
12620        // pointed to_nullable at it, but that commit was gated with
12621        // `cargo check --all-targets` plus a NAME-FILTERED test run, so this
12622        // pre-existing test was never executed and the break went unnoticed.
12623        // Float64's nullable flavour IS Float64Nullable — that is the dtype's
12624        // entire reason to exist — so the assertion is what was stale.
12625        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
12626        assert_eq!(
12627            DType::Float64Nullable.to_nullable(),
12628            DType::Float64Nullable,
12629            "idempotent: already nullable"
12630        );
12631        assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
12632    }
12633
12634    #[test]
12635    fn dtype_to_non_nullable_conversions() {
12636        assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
12637        assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
12638        assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); // unchanged
12639        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
12640    }
12641
12642    #[test]
12643    fn nullable_dtype_name_reports_pandas_style() {
12644        assert_eq!(DType::Int64.name(), "int64");
12645        assert_eq!(DType::Int64Nullable.name(), "Int64"); // capital I
12646        assert_eq!(DType::Bool.name(), "bool");
12647        assert_eq!(DType::BoolNullable.name(), "boolean");
12648    }
12649
12650    #[test]
12651    fn cast_scalar_int64_nullable_identity() {
12652        let val = Scalar::Int64(42);
12653        // Int64 -> Int64Nullable is identity (no actual conversion)
12654        let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
12655        assert_eq!(result, Scalar::Int64(42));
12656
12657        // Int64Nullable -> Int64 is also identity
12658        let result2 = cast_scalar(&val, DType::Int64).unwrap();
12659        assert_eq!(result2, Scalar::Int64(42));
12660    }
12661
12662    #[test]
12663    fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
12664        // pandas astype(str) of floats == Python str(float): whole -> ".0",
12665        // shortest round-trip decimals, scientific (e+NN/e-NN) for large/small,
12666        // inf -> "inf", NaN -> "nan". Verified vs live pandas 2.2.3. (Previously
12667        // large/small lost scientific notation, e.g. 1e16 -> "10000000000000000.0".)
12668        let cases: &[(f64, &str)] = &[
12669            (1.0, "1.0"),
12670            (2.5, "2.5"),
12671            (100.0, "100.0"),
12672            (0.1, "0.1"),
12673            (0.0001, "0.0001"),
12674            (1e16, "1e+16"),
12675            (1e20, "1e+20"),
12676            (1e-5, "1e-05"),
12677            (1e-7, "1e-07"),
12678            (f64::INFINITY, "inf"),
12679            (f64::NEG_INFINITY, "-inf"),
12680        ];
12681        for (v, expected) in cases {
12682            assert_eq!(
12683                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
12684                Scalar::Utf8((*expected).to_owned()),
12685                "float {v} -> str"
12686            );
12687        }
12688    }
12689
12690    fn float_to_string_for_astype_former(value: f64) -> String {
12691        if value.is_nan() {
12692            return "nan".to_owned();
12693        }
12694        if value.is_infinite() {
12695            return value.to_string();
12696        }
12697        let rendered = format!("{value:?}");
12698        match rendered.split_once('e') {
12699            None => rendered,
12700            Some((mantissa, exponent)) => {
12701                let (sign, digits) = match exponent.strip_prefix('-') {
12702                    Some(digits) => ('-', digits),
12703                    None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
12704                };
12705                format!("{mantissa}e{sign}{digits:0>2}")
12706            }
12707        }
12708    }
12709
12710    fn scientific_astype_values(len: usize) -> Vec<f64> {
12711        const EXPONENTS: [i32; 16] = [
12712            -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
12713        ];
12714        (0..len)
12715            .map(|position| {
12716                let mantissa = 1.0 + (position % 997) as f64 / 997.0;
12717                let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
12718                if position.is_multiple_of(2) {
12719                    magnitude
12720                } else {
12721                    -magnitude
12722                }
12723            })
12724            .collect()
12725    }
12726
12727    #[test]
12728    fn float_to_string_for_astype_in_place_matches_former() {
12729        let fixed = [
12730            f64::NAN,
12731            f64::INFINITY,
12732            f64::NEG_INFINITY,
12733            0.0,
12734            -0.0,
12735            f64::MIN_POSITIVE,
12736            f64::MAX,
12737            f64::MIN,
12738            1e16,
12739            -1e16,
12740            1e-5,
12741            -1e-5,
12742            1.234_567_890_123_456_8e20,
12743            -9.876_543_210_987_654e-123,
12744        ];
12745        for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
12746            assert_eq!(
12747                super::float_to_string_for_astype(value),
12748                float_to_string_for_astype_former(value),
12749                "value={value:?}"
12750            );
12751        }
12752    }
12753
12754    #[test]
12755    #[ignore = "foreground performance probe"]
12756    fn float_to_string_for_astype_in_place_ab() {
12757        use std::time::Instant;
12758
12759        const VALUES: usize = 16_384;
12760        const SAMPLES: usize = 10;
12761        let values = scientific_astype_values(VALUES);
12762        for &value in &values {
12763            let former = float_to_string_for_astype_former(value);
12764            assert!(former.contains('e'), "benchmark value must be scientific");
12765            assert_eq!(super::float_to_string_for_astype(value), former);
12766        }
12767
12768        for _ in 0..2 {
12769            for &value in &values {
12770                std::hint::black_box(float_to_string_for_astype_former(value));
12771                std::hint::black_box(super::float_to_string_for_astype(value));
12772            }
12773        }
12774
12775        let mut former_ns = Vec::with_capacity(SAMPLES);
12776        let mut public_ns = Vec::with_capacity(SAMPLES);
12777        for sample in 0..SAMPLES {
12778            let run = |formatter: fn(f64) -> String| {
12779                let started = Instant::now();
12780                for &value in std::hint::black_box(&values) {
12781                    std::hint::black_box(formatter(std::hint::black_box(value)));
12782                }
12783                started.elapsed().as_nanos()
12784            };
12785            if sample.is_multiple_of(2) {
12786                former_ns.push(run(float_to_string_for_astype_former));
12787                public_ns.push(run(super::float_to_string_for_astype));
12788            } else {
12789                public_ns.push(run(super::float_to_string_for_astype));
12790                former_ns.push(run(float_to_string_for_astype_former));
12791            }
12792        }
12793
12794        former_ns.sort_unstable();
12795        public_ns.sort_unstable();
12796        let former_p50 = former_ns[SAMPLES / 2];
12797        let public_p50 = public_ns[SAMPLES / 2];
12798        println!(
12799            "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:?}",
12800            former_p50 as f64 / public_p50 as f64
12801        );
12802    }
12803
12804    #[test]
12805    fn cast_float_to_utf8_threshold_boundaries_match_python() {
12806        // Python str(float) switches to scientific notation only at |x| >= 1e16
12807        // or |x| < 1e-4. Values JUST INSIDE those bounds must stay decimal — a
12808        // formatter that switches to sci early (or late) diverges. All expected
12809        // values verified against Python 3 str()/repr (== pandas astype(str)).
12810        let cases: &[(f64, &str)] = &[
12811            (1e15, "1000000000000000.0"),
12812            (9_999_999_999_999_998.0, "9999999999999998.0"),
12813            (1_234_567_890_123_456.0, "1234567890123456.0"),
12814            (123_456_789_012_345.0, "123456789012345.0"),
12815            (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
12816            (1e16, "1e+16"),
12817            (1.5e16, "1.5e+16"),
12818            (1e17, "1e+17"),
12819            (1e-4, "0.0001"),
12820            (5e-5, "5e-05"),
12821            (-1e15, "-1000000000000000.0"),
12822            (-1e16, "-1e+16"),
12823            (-1e-5, "-1e-05"),
12824        ];
12825        for (v, expected) in cases {
12826            assert_eq!(
12827                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
12828                Scalar::Utf8((*expected).to_owned()),
12829                "float {v} -> str"
12830            );
12831        }
12832    }
12833
12834    #[test]
12835    fn cast_to_bool_uses_pandas_nonzero_truthiness() {
12836        // pandas astype(bool): zero -> False, any nonzero -> True (not just 0/1),
12837        // -0.0 -> False, and NaN -> True (numpy bool(nan), br-cyi4h). Verified vs
12838        // live pandas 2.2.3.
12839        let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
12840        for (v, expected) in cases_int {
12841            assert_eq!(
12842                cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
12843                Scalar::Bool(*expected),
12844                "int {v} -> bool"
12845            );
12846        }
12847        let cases_float: &[(f64, bool)] = &[
12848            (0.0, false),
12849            (-0.0, false),
12850            (0.1, true),
12851            (2.5, true),
12852            (1.0, true),
12853            // pandas astype(bool): NaN is truthy -> True (numpy bool). br-cyi4h.
12854            (f64::NAN, true),
12855        ];
12856        for (v, expected) in cases_float {
12857            assert_eq!(
12858                cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
12859                Scalar::Bool(*expected),
12860                "float {v} -> bool"
12861            );
12862        }
12863    }
12864
12865    #[test]
12866    fn nullable_dtype_is_extension() {
12867        assert!(DType::Int64Nullable.is_extension());
12868        assert!(DType::BoolNullable.is_extension());
12869        assert!(!DType::Int64.is_extension());
12870        assert!(!DType::Bool.is_extension());
12871    }
12872
12873    #[test]
12874    fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
12875        let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
12876        assert_eq!(
12877            infer_dtype(&values).expect("dtype should infer"),
12878            DType::Utf8
12879        );
12880    }
12881
12882    #[test]
12883    fn infer_dtype_routes_bool_numeric_mix_to_utf8_object_bucket_rh1od() {
12884        // br-frankenpandas-rh1od, MEASURED live pandas 2.2.3: a bool mixed
12885        // with any numeric scalar constructs OBJECT ([True, 2] -> object,
12886        // payloads preserved); numpy's bool<int common-type never fires at
12887        // the constructor. Discriminating: before the change this inferred
12888        // Int64 and coerced True -> 1.
12889        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Bool(false)];
12890        assert_eq!(
12891            infer_dtype(&values).expect("dtype should infer"),
12892            DType::Utf8
12893        );
12894        let with_float = vec![Scalar::Int64(1), Scalar::Float64(2.5), Scalar::Bool(true)];
12895        assert_eq!(
12896            infer_dtype(&with_float).expect("dtype should infer"),
12897            DType::Utf8
12898        );
12899        let with_null = vec![
12900            Scalar::Bool(true),
12901            Scalar::Null(NullKind::Null),
12902            Scalar::Int64(2),
12903        ];
12904        assert_eq!(
12905            infer_dtype(&with_null).expect("dtype should infer"),
12906            DType::Utf8
12907        );
12908    }
12909
12910    #[test]
12911    fn infer_dtype_keeps_nonmixed_bool_and_numeric_paths_rh1od() {
12912        // Pure bool stays bool; numeric-only mixes keep the common_dtype
12913        // lattice (int+float -> float64) — the object bucket is ONLY for the
12914        // cross-family mix.
12915        assert_eq!(
12916            infer_dtype(&[Scalar::Bool(true), Scalar::Bool(false)]).expect("dtype should infer"),
12917            DType::Bool
12918        );
12919        assert_eq!(
12920            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]).expect("dtype should infer"),
12921            DType::Float64
12922        );
12923    }
12924
12925    // ── Scalar missingness methods ─────────────────────────────────────
12926
12927    #[test]
12928    fn is_null_detects_explicit_nulls() {
12929        assert!(Scalar::Null(NullKind::Null).is_null());
12930        assert!(Scalar::Null(NullKind::NaN).is_null());
12931        assert!(!Scalar::Int64(42).is_null());
12932        assert!(!Scalar::Float64(f64::NAN).is_null());
12933    }
12934
12935    #[test]
12936    fn is_na_matches_is_missing() {
12937        let vals = vec![
12938            Scalar::Null(NullKind::Null),
12939            Scalar::Float64(f64::NAN),
12940            Scalar::Int64(0),
12941            Scalar::Bool(false),
12942        ];
12943        for v in &vals {
12944            assert_eq!(v.is_na(), v.is_missing());
12945        }
12946    }
12947
12948    #[test]
12949    fn coalesce_picks_first_non_missing() {
12950        let null = Scalar::Null(NullKind::Null);
12951        let fill = Scalar::Int64(99);
12952        assert_eq!(null.coalesce(&fill), fill);
12953        assert_eq!(fill.coalesce(&null), fill);
12954    }
12955
12956    // ── Missingness utilities ──────────────────────────────────────────
12957
12958    #[test]
12959    fn isna_notna_complement() {
12960        let vals = vec![
12961            Scalar::Int64(1),
12962            Scalar::Null(NullKind::Null),
12963            Scalar::Float64(f64::NAN),
12964            Scalar::Float64(3.0),
12965        ];
12966        let na = super::isna(&vals);
12967        let not = super::notna(&vals);
12968        assert_eq!(na, vec![false, true, true, false]);
12969        for (a, b) in na.iter().zip(not.iter()) {
12970            assert_ne!(a, b);
12971        }
12972    }
12973
12974    #[test]
12975    fn count_na_counts_missing() {
12976        let vals = vec![
12977            Scalar::Int64(1),
12978            Scalar::Null(NullKind::Null),
12979            Scalar::Float64(f64::NAN),
12980        ];
12981        assert_eq!(super::count_na(&vals), 2);
12982    }
12983
12984    #[test]
12985    fn fill_na_replaces_missing() {
12986        let vals = vec![
12987            Scalar::Int64(1),
12988            Scalar::Null(NullKind::Null),
12989            Scalar::Float64(f64::NAN),
12990            Scalar::Int64(4),
12991        ];
12992        let filled = super::fill_na(&vals, &Scalar::Int64(0));
12993        assert_eq!(filled[0], Scalar::Int64(1));
12994        assert_eq!(filled[1], Scalar::Int64(0));
12995        assert_eq!(filled[2], Scalar::Int64(0));
12996        assert_eq!(filled[3], Scalar::Int64(4));
12997    }
12998
12999    #[test]
13000    fn dropna_removes_missing() {
13001        let vals = vec![
13002            Scalar::Int64(1),
13003            Scalar::Null(NullKind::Null),
13004            Scalar::Int64(3),
13005            Scalar::Float64(f64::NAN),
13006        ];
13007        let kept = super::dropna(&vals);
13008        assert_eq!(kept.len(), 2);
13009        assert_eq!(kept[0], Scalar::Int64(1));
13010        assert_eq!(kept[1], Scalar::Int64(3));
13011    }
13012
13013    #[test]
13014    fn null_helpers_match_scalar_oracle_imt0c() {
13015        // Differential vs independent scalar null-helper oracle
13016        // (br-frankenpandas-imt0c). Seeded LCG, no mocks.
13017        fn next(seed: &mut u64) -> u64 {
13018            *seed = seed
13019                .wrapping_mul(3202034522624059733)
13020                .wrapping_add(4354685564936845319);
13021            *seed
13022        }
13023
13024        fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
13025            let expected_missing = values.iter().filter(|value| value.is_missing()).count();
13026            let expected_dropped = values
13027                .iter()
13028                .filter(|value| !value.is_missing())
13029                .cloned()
13030                .collect::<Vec<_>>();
13031            let expected_filled = values
13032                .iter()
13033                .map(|value| {
13034                    if value.is_missing() {
13035                        fill.clone()
13036                    } else {
13037                        value.clone()
13038                    }
13039                })
13040                .collect::<Vec<_>>();
13041
13042            assert_eq!(
13043                super::count_na(values),
13044                expected_missing,
13045                "case={case}: count_na mismatch for {values:?}"
13046            );
13047
13048            let dropped = super::dropna(values);
13049            assert_eq!(
13050                dropped.len(),
13051                expected_dropped.len(),
13052                "case={case}: dropna length mismatch for {values:?}"
13053            );
13054            for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
13055            {
13056                assert!(
13057                    actual.semantic_eq(expected),
13058                    "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
13059                );
13060            }
13061
13062            let filled = super::fill_na(values, fill);
13063            assert_eq!(
13064                filled.len(),
13065                expected_filled.len(),
13066                "case={case}: fill_na length mismatch for {values:?}"
13067            );
13068            for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
13069                assert!(
13070                    actual.semantic_eq(expected),
13071                    "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
13072                );
13073            }
13074        }
13075
13076        let all_missing = [
13077            Scalar::Null(NullKind::Null),
13078            Scalar::Null(NullKind::NaN),
13079            Scalar::Float64(f64::NAN),
13080            Scalar::Timedelta64(i64::MIN),
13081        ];
13082        assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
13083
13084        let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
13085        for case in 0..260 {
13086            let len = (next(&mut seed) % 83 + 1) as usize;
13087            let mut values = Vec::with_capacity(len);
13088            for pos in 0..len {
13089                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13090                values.push(match next(&mut seed) % 11 {
13091                    0 => Scalar::Null(NullKind::Null),
13092                    1 => Scalar::Null(NullKind::NaN),
13093                    2 => Scalar::Float64(f64::NAN),
13094                    3 => Scalar::Timedelta64(i64::MIN),
13095                    4 => Scalar::Bool(raw & 1 == 0),
13096                    5 => Scalar::Int64(raw),
13097                    6 => Scalar::Float64(raw as f64 / 37.0),
13098                    7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
13099                    8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
13100                    9 => Scalar::Utf8(String::new()),
13101                    _ => Scalar::Timedelta64(raw),
13102                });
13103            }
13104
13105            let fill = match case % 5 {
13106                0 => Scalar::Bool(true),
13107                1 => Scalar::Int64(-777),
13108                2 => Scalar::Float64(12.5),
13109                3 => Scalar::Utf8("filled".into()),
13110                _ => Scalar::Timedelta64(123_456),
13111            };
13112            assert_null_helpers(case, &values, &fill);
13113        }
13114    }
13115
13116    // ── Nanops ─────────────────────────────────────────────────────────
13117
13118    #[test]
13119    fn nansum_skips_nulls() {
13120        let vals = vec![
13121            Scalar::Float64(1.0),
13122            Scalar::Null(NullKind::Null),
13123            Scalar::Float64(2.0),
13124            Scalar::Float64(f64::NAN),
13125            Scalar::Int64(7),
13126        ];
13127        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
13128    }
13129
13130    #[test]
13131    fn nansum_empty_returns_zero() {
13132        assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
13133    }
13134
13135    #[test]
13136    fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
13137        // Differential vs independent sum/mean oracles
13138        // (br-frankenpandas-1xmi7). Seeded LCG, no mocks.
13139        fn next(seed: &mut u64) -> u64 {
13140            *seed = seed
13141                .wrapping_mul(6364136223846793005)
13142                .wrapping_add(1442695040888963407);
13143            *seed
13144        }
13145
13146        fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
13147            let mut sum = 0.0;
13148            let mut count = 0usize;
13149            for value in values {
13150                if value.is_missing() {
13151                    continue;
13152                }
13153                if let Ok(value) = value.to_f64() {
13154                    sum += value;
13155                    count += 1;
13156                }
13157            }
13158            let mean = if count == 0 {
13159                Scalar::Null(NullKind::NaN)
13160            } else {
13161                Scalar::Float64(sum / count as f64)
13162            };
13163            (Scalar::Float64(sum), mean)
13164        }
13165
13166        fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
13167            let mut sum = 0_i128;
13168            let mut count = 0_i128;
13169            for value in values {
13170                if let Scalar::Timedelta64(ns) = value
13171                    && !value.is_missing()
13172                {
13173                    sum += i128::from(*ns);
13174                    count += 1;
13175                }
13176            }
13177            if count == 0 {
13178                return (Scalar::Timedelta64(0), Scalar::Timedelta64(Timedelta::NAT));
13179            }
13180            // br-frankenpandas-opz27: this reference oracle used to clamp, which
13181            // is the exact behaviour the production path was just fixed away
13182            // from. Keeping the clamp here would leave the oracle blessing a
13183            // contradicted rule (it only ever agreed because these inputs do
13184            // not overflow). Mirror the representable-range contract instead.
13185            (
13186                super::timedelta_ns_to_scalar(sum),
13187                super::timedelta_ns_to_scalar(sum / count),
13188            )
13189        }
13190
13191        fn assert_sum_mean(
13192            case: usize,
13193            family: &str,
13194            values: &[Scalar],
13195            expected_sum: Scalar,
13196            expected_mean: Scalar,
13197        ) {
13198            let actual_sum = super::nansum(values);
13199            let actual_mean = super::nanmean(values);
13200            assert!(
13201                actual_sum.semantic_eq(&expected_sum),
13202                "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
13203            );
13204            assert!(
13205                actual_mean.semantic_eq(&expected_mean),
13206                "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
13207            );
13208        }
13209
13210        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13211        let (sum, mean) = expected_numeric(&all_missing);
13212        assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
13213
13214        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
13215        let (sum, mean) = expected_timedelta(&td_all_missing);
13216        assert_sum_mean(
13217            usize::MAX - 1,
13218            "timedelta_all_missing",
13219            &td_all_missing,
13220            sum,
13221            mean,
13222        );
13223
13224        let mut seed = 0x511d_ed5a_7a11_1a55_u64;
13225        for case in 0..260 {
13226            let len = (next(&mut seed) % 89 + 1) as usize;
13227
13228            let mut numeric = Vec::with_capacity(len);
13229            numeric.push(Scalar::Int64(case as i64 - 130));
13230            for _ in 1..len {
13231                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13232                numeric.push(match next(&mut seed) % 8 {
13233                    0 => Scalar::Null(NullKind::Null),
13234                    1 => Scalar::Null(NullKind::NaN),
13235                    2 => Scalar::Float64(f64::NAN),
13236                    3 => Scalar::Bool(raw & 1 == 0),
13237                    4 => Scalar::Int64(raw % 257),
13238                    5 => Scalar::Float64(raw as f64 / 67.0),
13239                    6 => Scalar::Float64(0.0),
13240                    _ => Scalar::Float64(-0.0),
13241                });
13242            }
13243            let (sum, mean) = expected_numeric(&numeric);
13244            assert_sum_mean(case, "numeric", &numeric, sum, mean);
13245
13246            let mut timedeltas = Vec::with_capacity(len);
13247            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
13248            for _ in 1..len {
13249                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13250                timedeltas.push(match next(&mut seed) % 7 {
13251                    0 => Scalar::Null(NullKind::Null),
13252                    1 => Scalar::Timedelta64(i64::MIN),
13253                    _ => Scalar::Timedelta64(raw),
13254                });
13255            }
13256            let (sum, mean) = expected_timedelta(&timedeltas);
13257            assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
13258        }
13259    }
13260
13261    #[test]
13262    fn nannunique_merges_negative_zero_and_zero() {
13263        let vals = vec![
13264            Scalar::Float64(-0.0),
13265            Scalar::Float64(0.0),
13266            Scalar::Float64(1.0),
13267        ];
13268        assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
13269    }
13270
13271    #[test]
13272    fn nannunique_matches_scalar_bucket_oracle_elvbg() {
13273        // Differential vs independent scalar unique-bucket oracle
13274        // (br-frankenpandas-elvbg). Seeded LCG, no mocks.
13275        fn next(seed: &mut u64) -> u64 {
13276            *seed = seed
13277                .wrapping_mul(2862933555777941757)
13278                .wrapping_add(3037000493);
13279            *seed
13280        }
13281
13282        fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
13283            match (left, right) {
13284                (Scalar::Float64(left), Scalar::Float64(right)) => {
13285                    let left = if *left == 0.0 { 0.0 } else { *left };
13286                    let right = if *right == 0.0 { 0.0 } else { *right };
13287                    left.to_bits() == right.to_bits()
13288                }
13289                _ => left == right,
13290            }
13291        }
13292
13293        fn expected_nunique(values: &[Scalar]) -> i64 {
13294            let mut seen = Vec::<Scalar>::new();
13295            for value in values {
13296                if value.is_missing() {
13297                    continue;
13298                }
13299                if !seen.iter().any(|existing| same_bucket(existing, value)) {
13300                    seen.push(value.clone());
13301                }
13302            }
13303            seen.len() as i64
13304        }
13305
13306        fn assert_nannunique(case: usize, values: &[Scalar]) {
13307            assert_eq!(
13308                super::nannunique(values),
13309                Scalar::Int64(expected_nunique(values)),
13310                "case={case}: nannunique mismatch for {values:?}"
13311            );
13312        }
13313
13314        assert_nannunique(
13315            usize::MAX,
13316            &[
13317                Scalar::Float64(-0.0),
13318                Scalar::Float64(0.0),
13319                Scalar::Float64(f64::NAN),
13320                Scalar::Null(NullKind::Null),
13321                Scalar::Timedelta64(i64::MIN),
13322            ],
13323        );
13324
13325        let mut seed = 0x0e1b_60d0_b5e7_u64;
13326        for case in 0..320 {
13327            let len = (next(&mut seed) % 97 + 1) as usize;
13328            let mut values = Vec::with_capacity(len);
13329            for pos in 0..len {
13330                let raw = (next(&mut seed) % 1_001) as i64 - 500;
13331                values.push(match next(&mut seed) % 11 {
13332                    0 => Scalar::Null(NullKind::Null),
13333                    1 => Scalar::Null(NullKind::NaN),
13334                    2 => Scalar::Float64(f64::NAN),
13335                    3 => Scalar::Bool(raw & 1 == 0),
13336                    4 => Scalar::Int64(raw % 37),
13337                    5 => Scalar::Float64(raw as f64 / 19.0),
13338                    6 => Scalar::Float64(0.0),
13339                    7 => Scalar::Float64(-0.0),
13340                    8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
13341                    9 => Scalar::Utf8(String::new()),
13342                    _ => Scalar::Timedelta64(raw % 41),
13343                });
13344            }
13345            assert_nannunique(case, &values);
13346        }
13347    }
13348
13349    #[test]
13350    fn nanmean_basic() {
13351        let vals = vec![
13352            Scalar::Float64(2.0),
13353            Scalar::Null(NullKind::Null),
13354            Scalar::Float64(4.0),
13355        ];
13356        assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
13357    }
13358
13359    #[test]
13360    fn nanmean_all_null_returns_nan() {
13361        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13362        assert!(super::nanmean(&vals).is_missing());
13363    }
13364
13365    #[test]
13366    fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
13367        // Per br-frankenpandas-620mj: pandas td_series.sum()/mean() return
13368        // Timedelta64, not Float64(0.0). Was silently zero before because
13369        // collect_finite drops Timedelta64 (to_f64 errors).
13370        let one_hour = 3_600 * 1_000_000_000_i64;
13371        let vals = vec![
13372            Scalar::Timedelta64(one_hour),
13373            Scalar::Timedelta64(2 * one_hour),
13374            Scalar::Timedelta64(3 * one_hour),
13375        ];
13376        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
13377        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13378    }
13379
13380    #[test]
13381    fn nansum_nanmean_timedelta64_skips_nat_620mj() {
13382        let one_hour = 3_600 * 1_000_000_000_i64;
13383        let vals = vec![
13384            Scalar::Timedelta64(Timedelta::NAT),
13385            Scalar::Timedelta64(one_hour),
13386            Scalar::Timedelta64(3 * one_hour),
13387            Scalar::Timedelta64(Timedelta::NAT),
13388        ];
13389        // NAT is missing → skipped. Sum: 1h+3h=4h; mean: 2h.
13390        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
13391        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13392    }
13393
13394    /// br-frankenpandas-opz27: the Timedelta reduction surface used to narrow
13395    /// its exact i128 accumulator with `clamp(i64::MIN, i64::MAX)`, which
13396    /// fabricated a finite Timedelta.max on positive overflow. Live pandas
13397    /// 2.2.3 raises `ValueError: overflow in timedelta operation` here; FP
13398    /// surfaces NaT per the lgyy8 convention. A clamping implementation
13399    /// returns `Timedelta64(i64::MAX)` and fails this.
13400    #[test]
13401    fn nansum_timedelta_overflow_is_nat_not_fabricated_max_opz27() {
13402        let vals = vec![Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MAX)];
13403        let got = super::nansum(&vals);
13404        assert!(
13405            got.is_missing(),
13406            "overflowing sum must be missing, got {got:?}"
13407        );
13408        assert_eq!(got, Scalar::Timedelta64(Timedelta::NAT));
13409        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13410    }
13411
13412    /// The negative direction used to reach NaT only *by accident*, because
13413    /// `Timedelta::NAT == i64::MIN` is exactly the clamp's lower bound — and
13414    /// that bound is off by one against the true minimum (`i64::MIN + 1`).
13415    /// Pin both the sentinel and the boundary so the accident becomes a rule.
13416    #[test]
13417    fn nansum_timedelta_negative_overflow_is_nat_opz27() {
13418        let min_repr = i64::MIN + 1; // Timedelta.min; i64::MIN is the NaT sentinel
13419        let vals = vec![Scalar::Timedelta64(min_repr), Scalar::Timedelta64(min_repr)];
13420        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(Timedelta::NAT));
13421
13422        // Exactly the most-negative representable total stays a real value and
13423        // must NOT collapse into the sentinel one nanosecond above it.
13424        let exact = vec![Scalar::Timedelta64(min_repr + 1), Scalar::Timedelta64(-1)];
13425        let got = super::nansum(&exact);
13426        assert_eq!(got, Scalar::Timedelta64(min_repr));
13427        assert!(!got.is_missing(), "Timedelta.min is representable, not NaT");
13428    }
13429
13430    /// pandas 2.2.3: `Series([Timedelta.min, Timedelta.max]).max() - .min()`
13431    /// raises OverflowError. FP used `saturating_sub`, fabricating
13432    /// Timedelta.max as a plausible range.
13433    #[test]
13434    fn nanptp_timedelta_overflow_is_nat_opz27() {
13435        let vals = vec![
13436            Scalar::Timedelta64(i64::MIN + 1),
13437            Scalar::Timedelta64(i64::MAX),
13438        ];
13439        let got = super::nanptp(&vals);
13440        assert!(
13441            got.is_missing(),
13442            "unrepresentable range must be NaT, got {got:?}"
13443        );
13444        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13445
13446        // A representable range is still exact to the nanosecond (the reason
13447        // this path avoids f64 at all).
13448        let hour = 3_600 * 1_000_000_000_i64;
13449        let ok = vec![Scalar::Timedelta64(hour), Scalar::Timedelta64(4 * hour)];
13450        assert_eq!(super::nanptp(&ok), Scalar::Timedelta64(3 * hour));
13451    }
13452
13453    /// The load-bearing cumsum case: accumulation stays exact in i128, so only
13454    /// the *unrepresentable* index goes NaT and a later index that returns to
13455    /// range emits its true value. A clamping implementation pins `running` at
13456    /// i64::MAX and can never produce the final value, so it fails this test.
13457    #[test]
13458    fn nancumsum_timedelta_overflow_recovers_exact_value_opz27() {
13459        let vals = vec![
13460            Scalar::Timedelta64(i64::MAX),
13461            Scalar::Timedelta64(i64::MAX), // true total 2*i64::MAX: unrepresentable
13462            Scalar::Timedelta64(i64::MIN + 1), // back in range: total == i64::MAX
13463        ];
13464        let out = super::nancumsum(&vals);
13465        assert_eq!(out.len(), 3);
13466        assert_eq!(out[0], Scalar::Timedelta64(i64::MAX));
13467        assert!(
13468            out[1].is_missing(),
13469            "overflowed index must be NaT, got {:?}",
13470            out[1]
13471        );
13472        assert_eq!(
13473            out[2],
13474            Scalar::Timedelta64(i64::MAX),
13475            "exact i128 accumulation must recover; a clamped running sum cannot"
13476        );
13477    }
13478
13479    /// Non-overflowing cumsum is unchanged bit-for-bit, and input NaT still
13480    /// passes through without advancing the running total.
13481    #[test]
13482    fn nancumsum_timedelta_exact_path_unchanged_opz27() {
13483        let sec = 1_000_000_000_i64;
13484        let vals = vec![
13485            Scalar::Timedelta64(sec),
13486            Scalar::Timedelta64(Timedelta::NAT),
13487            Scalar::Timedelta64(2 * sec),
13488        ];
13489        let out = super::nancumsum(&vals);
13490        assert_eq!(out[0], Scalar::Timedelta64(sec));
13491        assert!(out[1].is_missing());
13492        assert_eq!(out[2], Scalar::Timedelta64(3 * sec));
13493    }
13494
13495    const DAY_NS: i64 = 86_400 * 1_000_000_000;
13496    /// 2020-01-01T00:00:00Z in epoch nanoseconds.
13497    const DT_2020: i64 = 1_577_836_800_000_000_000;
13498
13499    /// br-frankenpandas-axhhk: every one of these returned `Null(NaN)` (or
13500    /// `None`) before the Datetime64 arms existed, because `Datetime64::to_f64()`
13501    /// errors and each reduction fell through to the f64 catch-all. Expectations
13502    /// are the live pandas 2.2.3 answers for
13503    /// `Series([2020-01-01, +60d, +31d])`:
13504    ///   min 2020-01-01 · max 2020-03-01 · ptp Timedelta 60 days
13505    ///   argmin 0 · argmax 1 · cummax/cummin Timestamps
13506    #[test]
13507    fn datetime64_ordering_reductions_match_pandas_axhhk() {
13508        let d = Scalar::Datetime64;
13509        let vals = vec![
13510            d(DT_2020),
13511            d(DT_2020 + 60 * DAY_NS),
13512            d(DT_2020 + 31 * DAY_NS),
13513        ];
13514
13515        assert_eq!(super::nanmin(&vals), d(DT_2020));
13516        assert_eq!(super::nanmax(&vals), d(DT_2020 + 60 * DAY_NS));
13517        assert_eq!(super::nanargmin(&vals), Some(0));
13518        assert_eq!(super::nanargmax(&vals), Some(1));
13519
13520        // ptp of two INSTANTS is a DURATION: Timedelta64, not Datetime64.
13521        let span = super::nanptp(&vals);
13522        assert_eq!(span, Scalar::Timedelta64(60 * DAY_NS));
13523        assert_eq!(span.dtype(), DType::Timedelta64);
13524
13525        assert_eq!(
13526            super::nancummax(&vals),
13527            vec![
13528                d(DT_2020),
13529                d(DT_2020 + 60 * DAY_NS),
13530                d(DT_2020 + 60 * DAY_NS)
13531            ]
13532        );
13533        assert_eq!(
13534            super::nancummin(&vals),
13535            vec![d(DT_2020), d(DT_2020), d(DT_2020)]
13536        );
13537    }
13538
13539    /// The size-dependence is the part that made this bug quiet, so pin it
13540    /// explicitly rather than only asserting the headline. A ONE-element
13541    /// datetime slice was always correct (the `(None, _)` arm seeds `min`
13542    /// before any comparison runs); TWO elements hit the catch-all and
13543    /// returned NaN. A regression that drops the Datetime64 arm would still
13544    /// pass a single-element test.
13545    #[test]
13546    fn datetime64_min_max_size_dependence_pinned_axhhk() {
13547        let d = Scalar::Datetime64;
13548        let one = vec![d(DT_2020)];
13549        assert_eq!(super::nanmin(&one), d(DT_2020));
13550        assert_eq!(super::nanmax(&one), d(DT_2020));
13551
13552        let two = vec![d(DT_2020 + DAY_NS), d(DT_2020)];
13553        let got_min = super::nanmin(&two);
13554        assert!(
13555            !got_min.is_missing(),
13556            "2-element datetime min must not be missing, got {got_min:?}"
13557        );
13558        assert_eq!(got_min, d(DT_2020));
13559        assert_eq!(super::nanmax(&two), d(DT_2020 + DAY_NS));
13560    }
13561
13562    /// NaT still skips, and a datetime span too large for i64 surfaces NaT via
13563    /// the shared opz27 narrowing rather than a fabricated extreme.
13564    #[test]
13565    fn datetime64_reductions_skip_nat_and_guard_span_overflow_axhhk() {
13566        let d = Scalar::Datetime64;
13567        let with_nat = vec![
13568            d(Timestamp::NAT),
13569            d(DT_2020 + 31 * DAY_NS),
13570            d(DT_2020),
13571            d(Timestamp::NAT),
13572        ];
13573        assert_eq!(super::nanmin(&with_nat), d(DT_2020));
13574        assert_eq!(super::nanmax(&with_nat), d(DT_2020 + 31 * DAY_NS));
13575        assert_eq!(super::nanptp(&with_nat), Scalar::Timedelta64(31 * DAY_NS));
13576        // argmin/argmax report positions in the ORIGINAL slice, NaT skipped.
13577        assert_eq!(super::nanargmin(&with_nat), Some(2));
13578        assert_eq!(super::nanargmax(&with_nat), Some(1));
13579
13580        // Span exceeding i64 ns: NaT, never a fabricated Timedelta.max.
13581        let huge = vec![d(i64::MIN + 1), d(i64::MAX)];
13582        let span = super::nanptp(&huge);
13583        assert!(span.is_missing(), "unrepresentable span must be NaT");
13584        assert_ne!(span, Scalar::Timedelta64(i64::MAX));
13585    }
13586
13587    /// br-frankenpandas-adv58: mean/median/quantile returned `Null(NaN)` for
13588    /// datetime input. Expectations are the live pandas 2.2.3 answers for
13589    /// `Series([2020-01-01, +60d, +31d])`, which at day granularity pandas
13590    /// computes exactly:
13591    ///   mean 2020-01-31T08:00 · median 2020-02-01 · q0.5 2020-02-01
13592    ///   q0.25 2020-01-16T12:00
13593    #[test]
13594    fn datetime64_averaging_reductions_match_pandas_adv58() {
13595        let d = Scalar::Datetime64;
13596        let vals = vec![
13597            d(DT_2020),
13598            d(DT_2020 + 60 * DAY_NS),
13599            d(DT_2020 + 31 * DAY_NS),
13600        ];
13601        // 1580457600e9 / 1580515200e9 / 1579176000e9, straight from the probe.
13602        assert_eq!(super::nanmean(&vals), d(1_580_457_600_000_000_000));
13603        assert_eq!(super::nanmedian(&vals), d(1_580_515_200_000_000_000));
13604        assert_eq!(super::nanquantile(&vals, 0.5), d(1_580_515_200_000_000_000));
13605        assert_eq!(
13606            super::nanquantile(&vals, 0.25),
13607            d(1_579_176_000_000_000_000)
13608        );
13609    }
13610
13611    /// The even-count rounding rule, probed at 1 ns granularity where pandas is
13612    /// exact. It is TRUNCATION TOWARD ZERO — plain Rust integer division.
13613    /// `floor` would give -1 for [-1,0]; ties-to-even would give 2 for [1,2].
13614    /// Both are refuted by these cases, so this test discriminates against the
13615    /// two rounding rules a reimplementation is most likely to pick.
13616    #[test]
13617    fn datetime64_mean_median_round_toward_zero_adv58() {
13618        let d = Scalar::Datetime64;
13619        for (a, b, want) in [
13620            (0_i64, 1_i64, 0_i64),
13621            (0, 3, 1),
13622            (1, 2, 1),
13623            (-1, 0, 0),
13624            (-3, 0, -1),
13625            (-2, -1, -1),
13626            (0, 2, 1),
13627            (-2, 0, -1),
13628        ] {
13629            let vals = vec![d(a), d(b)];
13630            assert_eq!(
13631                super::nanmean(&vals),
13632                d(want),
13633                "mean of [{a}, {b}] should be {want}"
13634            );
13635            assert_eq!(
13636                super::nanmedian(&vals),
13637                d(want),
13638                "median of [{a}, {b}] should be {want}"
13639            );
13640        }
13641    }
13642
13643    /// NaT is skipped, and an all-NaT datetime input stays in the Datetime
13644    /// family rather than degrading to a numeric NaN.
13645    #[test]
13646    fn datetime64_averaging_skips_nat_adv58() {
13647        let d = Scalar::Datetime64;
13648        let vals = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
13649        // pandas: mean == median == 2020-01-02, count 2.
13650        assert_eq!(super::nanmean(&vals), d(DT_2020 + DAY_NS));
13651        assert_eq!(super::nanmedian(&vals), d(DT_2020 + DAY_NS));
13652
13653        let all_nat = vec![d(Timestamp::NAT), d(Timestamp::NAT)];
13654        let got = super::nanmean(&all_nat);
13655        assert!(
13656            got.is_missing(),
13657            "all-NaT mean must be missing, got {got:?}"
13658        );
13659        assert_eq!(
13660            got.dtype(),
13661            DType::datetime64_naive(),
13662            "must stay Datetime64"
13663        );
13664    }
13665
13666    /// FP is EXACT here and pandas is not: pandas routes datetime
13667    /// mean/median/quantile through f64, so at 2020-era magnitudes (~1.58e18,
13668    /// f64 ULP 256 ns) it snaps to a 256 ns grid — it returns B+0 for the mean
13669    /// of the CONSTANT series [B+1, B+1], and for an odd-count median it can
13670    /// return a Timestamp that is not even one of the inputs. FP keeps the
13671    /// exact i128 treatment its Timedelta sibling already had. DISC-019.
13672    #[test]
13673    fn datetime64_averaging_is_exact_where_pandas_snaps_adv58() {
13674        let d = Scalar::Datetime64;
13675
13676        // Constant series: the answer is unambiguous; pandas still loses it.
13677        let constant = vec![d(DT_2020 + 1), d(DT_2020 + 1)];
13678        assert_eq!(super::nanmean(&constant), d(DT_2020 + 1));
13679        assert_eq!(super::nanmedian(&constant), d(DT_2020 + 1));
13680
13681        // Odd-count median is a SELECTION: the result must be an input value.
13682        let odd = vec![d(DT_2020), d(DT_2020 + 129), d(DT_2020 + 258)];
13683        let med = super::nanmedian(&odd);
13684        assert_eq!(med, d(DT_2020 + 129));
13685        assert!(
13686            odd.contains(&med),
13687            "odd-count median must be one of the inputs; pandas returns B+256, which is not"
13688        );
13689    }
13690
13691    /// br-frankenpandas-40ujm: datetime std returned `Null(NaN)`; pandas 2.2.3
13692    /// returns a Timedelta. Every value below is the probed oracle answer for
13693    /// `Series([2020-01-01, +60d, +31d])`, in raw ns:
13694    ///   ddof=1 (default) 2592479955563784   ddof=0 2116751019841492
13695    ///   ddof=2           3666320313338702   ddof=3 NaT (n - ddof <= 0)
13696    /// pandas truncates the sqrt toward zero (ddof=0 is 2116751019841492.8).
13697    #[test]
13698    fn datetime64_std_matches_pandas_ddof_variants_40ujm() {
13699        let d = Scalar::Datetime64;
13700        let vals = vec![
13701            d(DT_2020),
13702            d(DT_2020 + 60 * DAY_NS),
13703            d(DT_2020 + 31 * DAY_NS),
13704        ];
13705        // Dispersion of instants is a DURATION: Timedelta64, not Datetime64.
13706        let s1 = super::nanstd(&vals, 1);
13707        assert_eq!(s1, Scalar::Timedelta64(2_592_479_955_563_784));
13708        assert_eq!(s1.dtype(), DType::Timedelta64);
13709        assert_eq!(
13710            super::nanstd(&vals, 0),
13711            Scalar::Timedelta64(2_116_751_019_841_492)
13712        );
13713        assert_eq!(
13714            super::nanstd(&vals, 2),
13715            Scalar::Timedelta64(3_666_320_313_338_702)
13716        );
13717        // n - ddof <= 0 => NaT, matching pandas.
13718        assert!(super::nanstd(&vals, 3).is_missing());
13719    }
13720
13721    /// pandas returns the SAME std for a Datetime64 series and a Timedelta64
13722    /// series built from identical ns. That equivalence is the whole basis for
13723    /// routing both families through one computation, so pin it directly.
13724    #[test]
13725    fn datetime64_std_equals_timedelta64_std_on_same_ns_40ujm() {
13726        let offsets = [0_i64, 60 * DAY_NS, 31 * DAY_NS];
13727        let dt: Vec<Scalar> = offsets.iter().map(|o| Scalar::Datetime64(*o)).collect();
13728        let td: Vec<Scalar> = offsets.iter().map(|o| Scalar::Timedelta64(*o)).collect();
13729        assert_eq!(super::nanstd(&dt, 1), super::nanstd(&td, 1));
13730        assert_eq!(
13731            super::nanstd(&dt, 1),
13732            Scalar::Timedelta64(2_592_479_955_563_784)
13733        );
13734    }
13735
13736    /// NaT skips (a 3-element series with one NaT must equal the 2-element
13737    /// series without it), a single element gives NaT at the default ddof, and
13738    /// var/sem stay REFUSED for datetimes because pandas raises on them.
13739    #[test]
13740    fn datetime64_std_skips_nat_and_var_sem_stay_unsupported_40ujm() {
13741        let d = Scalar::Datetime64;
13742        let with_nat = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
13743        let without = vec![d(DT_2020), d(DT_2020 + 2 * DAY_NS)];
13744        // pandas: both are Timedelta 1 days 09:56:28.051789035.
13745        assert_eq!(super::nanstd(&with_nat, 1), super::nanstd(&without, 1));
13746        assert_eq!(
13747            super::nanstd(&with_nat, 1),
13748            Scalar::Timedelta64(122_188_051_789_035)
13749        );
13750
13751        // n=1 with ddof=1 -> NaT, as pandas returns.
13752        assert!(super::nanstd(&[d(DT_2020)], 1).is_missing());
13753        assert!(super::nanstd(&[d(Timestamp::NAT)], 1).is_missing());
13754
13755        // pandas RAISES TypeError for datetime64 var and sem. FP must not
13756        // invent a value: these stay on the Timedelta-only gate and report
13757        // missing. A regression that widened them would return a number here.
13758        let vals = vec![d(DT_2020), d(DT_2020 + 60 * DAY_NS)];
13759        assert!(super::nanvar(&vals, 1).is_missing());
13760        assert!(super::nansem(&vals, 1).is_missing());
13761    }
13762
13763    /// br-frankenpandas-qoabs: Period is the THIRD dtype whose `to_f64()`
13764    /// errors, so min/max fell into the f64 catch-all and returned
13765    /// `Null(NaN)`. pandas 2.2.3 on `Series([2020-01, 2020-03, 2020-02], M)`
13766    /// gives min 2020-01 and max 2020-03; ordinals are 600/601/602.
13767    #[test]
13768    fn period_min_max_match_pandas_qoabs() {
13769        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13770        let vals = vec![p(600), p(602), p(601)];
13771        assert_eq!(super::nanmin(&vals), p(600));
13772        assert_eq!(super::nanmax(&vals), p(602));
13773
13774        // Size-dependence, exactly as in axhhk: ONE element always worked via
13775        // the `(None, _)` seed, so a test with a single value would pass even
13776        // with no Period arm at all. Assert both sizes.
13777        assert_eq!(super::nanmin(&[p(600)]), p(600));
13778        let two = vec![p(602), p(600)];
13779        assert!(!super::nanmin(&two).is_missing());
13780        assert_eq!(super::nanmin(&two), p(600));
13781        assert_eq!(super::nanmax(&two), p(602));
13782    }
13783
13784    /// A Period whose ordinal is the NaT sentinel is missing and skipped, and
13785    /// an all-missing Period input reports missing rather than a value.
13786    #[test]
13787    fn period_min_max_skip_nat_qoabs() {
13788        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13789        let nat = Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly));
13790        let vals = vec![nat.clone(), p(602), p(600), nat.clone()];
13791        assert_eq!(super::nanmin(&vals), p(600));
13792        assert_eq!(super::nanmax(&vals), p(602));
13793        assert!(super::nanmin(&[nat.clone(), nat]).is_missing());
13794    }
13795
13796    /// MIXED FREQ must not be ordered. pandas refuses it outright
13797    /// (`IncompatibleFrequency: Input has different freq=D from Period(freq=M)`),
13798    /// so FP reports missing rather than inventing an order. This is the test
13799    /// that discriminates: an implementation comparing raw ordinals would
13800    /// happily return a value here, because monthly 2020-01 is ordinal 600
13801    /// while daily 2020-01-05 is 18267 — it would call the daily period later.
13802    #[test]
13803    fn period_mixed_freq_is_not_ordered_qoabs() {
13804        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
13805        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
13806        let vals = vec![month.clone(), day.clone()];
13807        let got_min = super::nanmin(&vals);
13808        assert!(
13809            got_min.is_missing(),
13810            "mixed-freq Period min must not be ordered, got {got_min:?}"
13811        );
13812        assert_ne!(
13813            got_min, day,
13814            "must not rank the daily period by raw ordinal"
13815        );
13816        assert!(super::nanmax(&vals).is_missing());
13817    }
13818
13819    /// br-frankenpandas-d7zjp: the rest of the Period reduction family, which
13820    /// qoabs deferred because a `fn(i64) -> Scalar` constructor cannot carry a
13821    /// freq. Expectations are the probed pandas 2.2.3 answers for
13822    /// `Series([2020-01, 2020-03, 2020-02], freq=M)` (ordinals 600/601/602):
13823    ///   median 2020-02 · quantile(0.5) 2020-02 · idxmin 0 · idxmax 1
13824    ///   cummax ends 2020-03 · cummin ends 2020-01
13825    #[test]
13826    fn period_full_reduction_family_matches_pandas_d7zjp() {
13827        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13828        let vals = vec![p(600), p(602), p(601)];
13829
13830        assert_eq!(super::nanmedian(&vals), p(601));
13831        assert_eq!(super::nanquantile(&vals, 0.5), p(601));
13832        assert_eq!(super::nanargmin(&vals), Some(0));
13833        assert_eq!(super::nanargmax(&vals), Some(1));
13834        assert_eq!(super::nancummax(&vals), vec![p(600), p(602), p(602)]);
13835        assert_eq!(super::nancummin(&vals), vec![p(600), p(600), p(600)]);
13836    }
13837
13838    /// Even-count Period median picks by TRUNCATION TOWARD ZERO on the ordinal,
13839    /// the same rule the datetime family uses. Probed: pandas gives 2020-02 for
13840    /// [2020-01, 2020-04] (ordinals 600/603, midpoint 601.5) and 2020-01 for
13841    /// [2020-01, 2020-02] (600/601, midpoint 600.5).
13842    #[test]
13843    fn period_even_count_median_truncates_toward_zero_d7zjp() {
13844        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13845        assert_eq!(super::nanmedian(&[p(600), p(603)]), p(601));
13846        assert_eq!(super::nanmedian(&[p(600), p(601)]), p(600));
13847    }
13848
13849    /// MIXED FREQ must not be ordered by ANY of these, for the same reason as
13850    /// in qoabs: pandas raises IncompatibleFrequency, and raw ordinals are not
13851    /// comparable across freqs (monthly 2020-01 is 600, daily 2020-01-05 is
13852    /// 18267). The family enum encodes the freq, so a mixed input is simply not
13853    /// one family and never reaches a typed arm.
13854    #[test]
13855    fn period_mixed_freq_not_ordered_by_any_reduction_d7zjp() {
13856        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
13857        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
13858        let vals = vec![month, day];
13859
13860        assert!(super::nanmedian(&vals).is_missing());
13861        assert!(super::nanquantile(&vals, 0.5).is_missing());
13862        assert_eq!(super::nanargmin(&vals), None);
13863        assert_eq!(super::nanargmax(&vals), None);
13864        // The cumulative ops must not emit an ordered Period column either.
13865        assert!(super::nancummax(&vals).iter().all(Scalar::is_missing));
13866        assert!(super::nancummin(&vals).iter().all(Scalar::is_missing));
13867    }
13868
13869    /// pandas RAISES for Period mean/sum/std/var ("does not support reduction",
13870    /// and for mean explicitly "the meaning is ambiguous"). FP must not invent
13871    /// values. `std` is the trap here: the family enum puts Period one line
13872    /// away from the Datetime64 arm that 40ujm deliberately widened, so this
13873    /// asserts the guard holds.
13874    #[test]
13875    fn period_unsupported_reductions_stay_missing_d7zjp() {
13876        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13877        let vals = vec![p(600), p(602), p(601)];
13878        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
13879        assert!(super::nanvar(&vals, 1).is_missing(), "pandas raises var");
13880        assert!(super::nansem(&vals, 1).is_missing(), "pandas raises sem");
13881        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
13882    }
13883
13884    /// br-frankenpandas-srqdo: Interval is the FOURTH dtype whose `to_f64()`
13885    /// errors, so min/max fell into the f64 catch-all and returned
13886    /// `Null(NaN)`. pandas 2.2.3 on `IntervalArray.from_tuples([(0,1),(4,5),(2,3)])`
13887    /// gives min `(0, 1]` and max `(4, 5]`.
13888    #[test]
13889    fn interval_min_max_match_pandas_srqdo() {
13890        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13891        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
13892        assert_eq!(super::nanmin(&vals), iv(0.0, 1.0));
13893        assert_eq!(super::nanmax(&vals), iv(4.0, 5.0));
13894
13895        // Size-dependence, per the axhhk lesson: ONE element always worked via
13896        // the `(None, _)` seed, so a single-value test passes even with no arm.
13897        assert_eq!(super::nanmin(&[iv(2.0, 3.0)]), iv(2.0, 3.0));
13898        let two = vec![iv(4.0, 5.0), iv(0.0, 1.0)];
13899        assert!(!super::nanmin(&two).is_missing());
13900        assert_eq!(super::nanmin(&two), iv(0.0, 1.0));
13901        assert_eq!(super::nanmax(&two), iv(4.0, 5.0));
13902    }
13903
13904    /// The tie-on-left case, which is what discriminates a correct (left, right)
13905    /// comparison from one that only looks at `left`. pandas: Interval(0,2) <
13906    /// Interval(0,5) is True. An implementation comparing left alone keeps
13907    /// whichever came first and returns the wrong element here.
13908    #[test]
13909    fn interval_ties_on_left_order_by_right_srqdo() {
13910        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13911        let vals = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
13912        assert_eq!(super::nanmin(&vals), iv(0.0, 2.0));
13913        assert_eq!(super::nanmax(&vals), iv(0.0, 9.0));
13914    }
13915
13916    /// A NaN bound has no pandas counterpart — `IntervalArray` refuses to build
13917    /// one ("missing values must be missing in the same location both left and
13918    /// right") — so it must report missing rather than impose an arbitrary
13919    /// order. Critically this must NOT panic: the obvious
13920    /// `partial_cmp().unwrap()` implementation would.
13921    #[test]
13922    fn interval_nan_bound_is_not_ordered_srqdo() {
13923        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13924        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
13925        assert!(super::nanmin(&vals).is_missing());
13926        assert!(super::nanmax(&vals).is_missing());
13927    }
13928
13929    /// pandas RAISES or NotImplementedErrors every other reduction for
13930    /// Interval (median/mean/sum/std/quantile/cummax). FP must not invent
13931    /// values, so they stay missing.
13932    #[test]
13933    fn interval_unsupported_reductions_stay_missing_srqdo() {
13934        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13935        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
13936        assert!(super::nanmedian(&vals).is_missing(), "pandas raises median");
13937        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
13938        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
13939        assert!(
13940            super::nanquantile(&vals, 0.5).is_missing(),
13941            "pandas raises quantile"
13942        );
13943        assert!(
13944            super::nancummax(&vals).iter().all(Scalar::is_missing),
13945            "pandas NotImplementedErrors cummax"
13946        );
13947    }
13948
13949    /// br-frankenpandas-2h9dm: Interval argmin/argmax returned None, because
13950    /// `Interval::to_f64()` errors and the f64 fallback skipped every element.
13951    /// All four expectations are probed pandas 2.2.3 `idxmin`/`idxmax`.
13952    #[test]
13953    fn interval_argmin_argmax_match_pandas_2h9dm() {
13954        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13955        // pandas: idxmin 1, idxmax 0
13956        let vals = vec![iv(4.0, 5.0), iv(0.0, 1.0), iv(2.0, 3.0)];
13957        assert_eq!(super::nanargmin(&vals), Some(1));
13958        assert_eq!(super::nanargmax(&vals), Some(0));
13959
13960        // Left-tie resolves by RIGHT. pandas: idxmin 1, idxmax 2. An
13961        // implementation comparing only `left` keeps index 0 for both.
13962        let tie = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
13963        assert_eq!(super::nanargmin(&tie), Some(1));
13964        assert_eq!(super::nanargmax(&tie), Some(2));
13965    }
13966
13967    /// Duplicated extreme returns the FIRST occurrence (pandas idxmin 0 on
13968    /// [(0,1),(0,1),(9,9)]), and missing entries are skipped while the returned
13969    /// index stays a position in the ORIGINAL slice (pandas idxmin 2 / idxmax 0
13970    /// on [(4,5), None, (0,1)]).
13971    #[test]
13972    fn interval_arg_first_occurrence_and_missing_2h9dm() {
13973        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13974        let dup = vec![iv(0.0, 1.0), iv(0.0, 1.0), iv(9.0, 9.0)];
13975        assert_eq!(
13976            super::nanargmin(&dup),
13977            Some(0),
13978            "first occurrence, not last"
13979        );
13980        assert_eq!(super::nanargmax(&dup), Some(2));
13981
13982        let with_missing = vec![iv(4.0, 5.0), Scalar::Null(NullKind::NaN), iv(0.0, 1.0)];
13983        assert_eq!(super::nanargmin(&with_missing), Some(2));
13984        assert_eq!(super::nanargmax(&with_missing), Some(0));
13985    }
13986
13987    /// A NaN bound is not orderable, so decline rather than return an arbitrary
13988    /// index — and critically, do not panic the way `partial_cmp().unwrap()`
13989    /// would.
13990    #[test]
13991    fn interval_arg_nan_bound_declines_2h9dm() {
13992        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13993        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
13994        assert_eq!(super::nanargmin(&vals), None);
13995        assert_eq!(super::nanargmax(&vals), None);
13996    }
13997
13998    /// br-frankenpandas-fyr1z-policy-carrier-f29nz: the load-bearing guarantee
13999    /// of this bead is NO DEFAULT BEHAVIOR CHANGE. Prove it rather than assert
14000    /// it: over a seeded corpus that deliberately straddles the i64 boundary
14001    /// and the NaT sentinel, every infallible helper must equal its fallible
14002    /// sibling resolved under the default `SurfaceNat` policy — which is also
14003    /// exactly what the pre-f29nz bodies computed.
14004    #[test]
14005    fn overflow_policy_carrier_preserves_default_behavior_f29nz() {
14006        // Seeded LCG, no rand dependency (see [[differential-test-coverage]]).
14007        let mut state: u64 = 0x5DEE_CE66_D125_1F00;
14008        let mut next = || {
14009            state = state
14010                .wrapping_mul(6_364_136_223_846_793_005)
14011                .wrapping_add(1_442_695_040_888_963_407);
14012            state
14013        };
14014        // Edge values first, then random ones. i64::MIN is the NaT sentinel.
14015        let mut corpus: Vec<i64> = vec![
14016            0,
14017            1,
14018            -1,
14019            2,
14020            -2,
14021            i64::MAX,
14022            i64::MIN,
14023            i64::MIN + 1,
14024            i64::MAX - 1,
14025            i64::MAX / 2,
14026            -(i64::MAX / 2),
14027        ];
14028        for _ in 0..400 {
14029            let raw = next() as i64;
14030            corpus.push(raw);
14031            corpus.push(raw / 3);
14032        }
14033
14034        let policy = super::OverflowPolicy::default();
14035        assert_eq!(
14036            policy,
14037            super::OverflowPolicy::SurfaceNat,
14038            "default must not move"
14039        );
14040
14041        for &a in &corpus {
14042            for &b in &corpus {
14043                // Timedelta::add / sub / mul_scalar
14044                assert_eq!(
14045                    Timedelta::add(a, b),
14046                    policy
14047                        .resolve(Timedelta::try_add(a, b), Timedelta::NAT)
14048                        .expect("SurfaceNat never errors"),
14049                    "add({a}, {b}) diverged"
14050                );
14051                assert_eq!(
14052                    Timedelta::sub(a, b),
14053                    policy
14054                        .resolve(Timedelta::try_sub(a, b), Timedelta::NAT)
14055                        .expect("SurfaceNat never errors"),
14056                    "sub({a}, {b}) diverged"
14057                );
14058                assert_eq!(
14059                    Timedelta::mul_scalar(a, b),
14060                    policy
14061                        .resolve(Timedelta::try_mul_scalar(a, b), Timedelta::NAT)
14062                        .expect("SurfaceNat never errors"),
14063                    "mul_scalar({a}, {b}) diverged"
14064                );
14065
14066                // Timestamp::{add,sub}_timedelta / sub_timestamp — including tz,
14067                // since overflow deliberately drops it.
14068                let ts = Timestamp::from_nanos(a);
14069                assert_eq!(
14070                    ts.add_timedelta(b),
14071                    ts.try_add_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14072                    "add_timedelta({a}, {b}) diverged"
14073                );
14074                assert_eq!(
14075                    ts.sub_timedelta(b),
14076                    ts.try_sub_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14077                    "sub_timedelta({a}, {b}) diverged"
14078                );
14079                let other = Timestamp::from_nanos(b);
14080                assert_eq!(
14081                    ts.sub_timestamp(&other),
14082                    ts.try_sub_timestamp(&other).unwrap_or(Timedelta::NAT),
14083                    "sub_timestamp({a}, {b}) diverged"
14084                );
14085            }
14086        }
14087    }
14088
14089    /// The carrier must actually CARRY something: `Strict` propagates the
14090    /// overflow with the right op name and the pandas error class probed from
14091    /// live 2.2.3. Without this, `resolve` could ignore its policy and the
14092    /// equivalence test above would still pass.
14093    #[test]
14094    fn overflow_policy_strict_reports_op_and_pandas_class_f29nz() {
14095        use super::{OverflowPolicy, PandasTemporalError};
14096
14097        let strict = OverflowPolicy::Strict;
14098
14099        // pd.Timedelta.max + pd.Timedelta('1ns') -> OverflowError
14100        let err = strict
14101            .resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT)
14102            .expect_err("must surface under Strict");
14103        assert_eq!(err.op, "Timedelta::add");
14104        assert_eq!(err.pandas_error, PandasTemporalError::Overflow);
14105
14106        // pd.Timestamp.max + pd.Timedelta('1ns') -> OutOfBoundsDatetime
14107        let ts = Timestamp::from_nanos(i64::MAX);
14108        let err = strict
14109            .resolve(ts.try_add_timedelta(1), Timestamp::nat())
14110            .expect_err("must surface under Strict");
14111        assert_eq!(err.op, "Timestamp::add_timedelta");
14112        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14113
14114        // pd.Timestamp.min - pd.Timestamp.max -> OutOfBoundsDatetime
14115        let err = strict
14116            .resolve(
14117                Timestamp::from_nanos(i64::MIN + 1)
14118                    .try_sub_timestamp(&Timestamp::from_nanos(i64::MAX)),
14119                Timedelta::NAT,
14120            )
14121            .expect_err("must surface under Strict");
14122        assert_eq!(err.op, "Timestamp::sub_timestamp");
14123        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14124
14125        // A NaT operand is PROPAGATION, not overflow: Strict must still be Ok.
14126        assert_eq!(
14127            strict
14128                .resolve(Timedelta::try_add(Timedelta::NAT, 1), Timedelta::NAT)
14129                .expect("NaT propagation is not an overflow"),
14130            Timedelta::NAT
14131        );
14132        // And a representable result is untouched under either policy.
14133        assert_eq!(
14134            strict
14135                .resolve(Timedelta::try_add(2, 3), Timedelta::NAT)
14136                .expect("no overflow"),
14137            5
14138        );
14139    }
14140
14141    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2: the scalar divide-by-zero
14142    /// row, and the boundary a STRICT arm must not cross. All four expectations
14143    /// probed on live pandas 2.2.3:
14144    ///   SCALAR  Timedelta('1s') // 0   -> ZeroDivisionError
14145    ///   SCALAR  Timedelta('1s') / 0    -> ZeroDivisionError
14146    ///   VECTOR  Series([Td]) // 0      -> NaT   (must NOT raise)
14147    ///   VECTOR  Series([Td]) / 0       -> NaT   (must NOT raise)
14148    #[test]
14149    fn timedelta_scalar_zero_division_taxonomy_t7ht2() {
14150        use super::{OverflowPolicy, PandasTemporalError};
14151
14152        // The fallible scalar sibling reports ZeroDivision with its op name.
14153        let err = Timedelta::try_div_scalar(1_000_000_000, 0)
14154            .expect_err("scalar divide-by-zero must be reportable");
14155        assert_eq!(err.op, "Timedelta::div_scalar");
14156        assert_eq!(err.pandas_error, PandasTemporalError::ZeroDivision);
14157
14158        // THE BOUNDARY: the infallible helper the vectorized callers use keeps
14159        // returning NaT. If this ever starts raising, FrankenPandas diverges
14160        // from pandas on a row where it is currently bit-for-bit correct.
14161        assert_eq!(Timedelta::div_scalar(1_000_000_000, 0), Timedelta::NAT);
14162        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 0), Timedelta::NAT);
14163
14164        // Under the default policy the failure resolves back to NaT, so
14165        // nothing changes for existing callers.
14166        assert_eq!(
14167            OverflowPolicy::default()
14168                .resolve(Timedelta::try_div_scalar(1_000_000_000, 0), Timedelta::NAT)
14169                .expect("SurfaceNat never errors"),
14170            Timedelta::NAT
14171        );
14172
14173        // Non-zero divisors are untouched, including the floor-division
14174        // adjustment for mixed signs (-7 // 2 == -4, not -3).
14175        assert_eq!(Timedelta::try_div_scalar(-7, 2), Ok(-4));
14176        assert_eq!(Timedelta::div_scalar(-7, 2), -4);
14177        assert_eq!(Timedelta::try_div_scalar(7, 2), Ok(3));
14178        // NaT propagates as Ok, not as a failure.
14179        assert_eq!(
14180            Timedelta::try_div_scalar(Timedelta::NAT, 2),
14181            Ok(Timedelta::NAT)
14182        );
14183    }
14184
14185    /// The constructor row of the taxonomy. Probed:
14186    /// `pd.Timedelta(float('inf'), 's')` raises OutOfBoundsTimedelta —
14187    /// specifically NOT a bare OverflowError, which is why the mapping is
14188    /// explicit rather than assumed.
14189    #[test]
14190    fn timedelta_constructor_error_maps_to_out_of_bounds_t7ht2() {
14191        use super::{PandasTemporalError, TimedeltaError};
14192
14193        assert_eq!(
14194            TimedeltaError::Overflow.pandas_error(),
14195            Some(PandasTemporalError::OutOfBoundsTimedelta)
14196        );
14197        // A parse failure is not part of the arithmetic taxonomy.
14198        assert_eq!(
14199            TimedeltaError::InvalidFormat("nonsense".into()).pandas_error(),
14200            None
14201        );
14202        // And the live path still errors on a non-finite input (8v92m).
14203        assert!(Timedelta::from_unit(f64::INFINITY, "s").is_err());
14204        assert_eq!(
14205            Timedelta::from_unit(f64::INFINITY, "s")
14206                .unwrap_err()
14207                .pandas_error(),
14208            Some(PandasTemporalError::OutOfBoundsTimedelta)
14209        );
14210    }
14211
14212    /// br-frankenpandas-fyr1z-hardened-audit-vllv6: HARDENED mode adds
14213    /// observability, NEVER semantics. Every value it returns must be
14214    /// bit-for-bit what SurfaceNat returns — proven over the same seeded corpus
14215    /// the f29nz equivalence test uses, with the audit log ENABLED throughout so
14216    /// recording cannot perturb results.
14217    #[test]
14218    fn hardened_audit_values_are_bit_identical_to_surface_nat_vllv6() {
14219        use super::{OverflowPolicy, overflow_audit};
14220
14221        overflow_audit::enable();
14222        let mut state: u64 = 0x1234_5678_9ABC_DEF0;
14223        let mut next = || {
14224            state = state
14225                .wrapping_mul(6_364_136_223_846_793_005)
14226                .wrapping_add(1_442_695_040_888_963_407);
14227            state
14228        };
14229        let mut corpus: Vec<i64> = vec![
14230            0,
14231            1,
14232            -1,
14233            2,
14234            -2,
14235            i64::MAX,
14236            i64::MIN,
14237            i64::MIN + 1,
14238            i64::MAX - 1,
14239        ];
14240        for _ in 0..120 {
14241            corpus.push(next() as i64);
14242        }
14243
14244        for &a in &corpus {
14245            for &b in &corpus {
14246                for op in [
14247                    Timedelta::try_add as fn(i64, i64) -> Result<i64, super::TemporalFailure>,
14248                    Timedelta::try_sub,
14249                    Timedelta::try_mul_scalar,
14250                    Timedelta::try_div_scalar,
14251                ] {
14252                    let soft = OverflowPolicy::SurfaceNat
14253                        .resolve(op(a, b), Timedelta::NAT)
14254                        .expect("SurfaceNat never errors");
14255                    let hard = OverflowPolicy::HardenedNat
14256                        .resolve(op(a, b), Timedelta::NAT)
14257                        .expect("HardenedNat never errors");
14258                    assert_eq!(hard, soft, "HARDENED changed a value for ({a}, {b})");
14259                }
14260            }
14261        }
14262        overflow_audit::disable();
14263    }
14264
14265    /// The audit trail itself: HARDENED records the op, the pandas class it
14266    /// would have raised, the OPERANDS whose exact result left the
14267    /// representable range, and the value actually returned — deterministically
14268    /// and in order. SurfaceNat and Strict record nothing.
14269    #[test]
14270    fn hardened_audit_records_deterministic_recovery_entries_vllv6() {
14271        use super::{OverflowPolicy, PandasTemporalError, overflow_audit};
14272
14273        overflow_audit::enable();
14274        assert!(overflow_audit::is_enabled());
14275        assert!(overflow_audit::drain().is_empty(), "starts empty");
14276
14277        // Two overflows and one representable result, in a fixed order.
14278        let _ =
14279            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14280        let _ = OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(2, 3), Timedelta::NAT);
14281        let _ =
14282            OverflowPolicy::HardenedNat.resolve(Timedelta::try_div_scalar(5, 0), Timedelta::NAT);
14283
14284        let entries = overflow_audit::drain();
14285        assert_eq!(entries.len(), 2, "only the two failures are recorded");
14286
14287        assert_eq!(entries[0].op, "Timedelta::add");
14288        assert_eq!(entries[0].pandas_error, PandasTemporalError::Overflow);
14289        assert_eq!(entries[0].operands, Some((i64::MAX, 1)));
14290        assert_eq!(entries[0].recovered_as, i64::MIN);
14291
14292        assert_eq!(entries[1].op, "Timedelta::div_scalar");
14293        assert_eq!(entries[1].pandas_error, PandasTemporalError::ZeroDivision);
14294        assert_eq!(entries[1].operands, Some((5, 0)));
14295
14296        // Draining leaves recording enabled and empty.
14297        assert!(overflow_audit::drain().is_empty());
14298
14299        // The OTHER policies must stay silent — the audit is HARDENED-only.
14300        let _ = OverflowPolicy::SurfaceNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14301        let _ = OverflowPolicy::Strict.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14302        assert!(
14303            overflow_audit::drain().is_empty(),
14304            "SurfaceNat/Strict must not write to the audit trail"
14305        );
14306
14307        overflow_audit::disable();
14308        assert!(!overflow_audit::is_enabled());
14309        // Disabled: recording is a no-op and drain yields nothing.
14310        let _ =
14311            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14312        assert!(
14313            overflow_audit::drain().is_empty(),
14314            "disabled must not record"
14315        );
14316    }
14317
14318    /// br-frankenpandas-fyr1z-wrap-signoff-s4lkx.
14319    ///
14320    /// THIS TEST PINS A PANDAS QUIRK THAT WE REPRODUCE ON PURPOSE. The values
14321    /// below are NOT what a careful implementation would choose: multiplying a
14322    /// positive duration by 2 yields a NEGATIVE one. They are what live pandas
14323    /// 2.2.3 returns, because numpy int64 wraps silently, and the maintainer
14324    /// decided that STRICT means bit-for-bit observable parity with the
14325    /// incumbent INCLUDING its quirks — this being a port.
14326    ///
14327    /// So: if this test fails, do NOT "fix" the wrap. Either pandas changed, or
14328    /// someone routed a non-STRICT caller into the STRICT path. Both need
14329    /// investigating rather than correcting the arithmetic.
14330    ///
14331    /// Oracle values, probed directly:
14332    ///   Series([Timedelta.max]) * 2            -> -2 ns
14333    ///   Series([max, max]).cumsum()            -> [max, -2]
14334    ///   Series([max, max, max]).cumsum()       -> [max, -2, max - 2]
14335    #[test]
14336    fn strict_reproduces_pandas_silent_timedelta_wrap_s4lkx() {
14337        use super::{OverflowPolicy, nancumsum_with_policy};
14338
14339        // Series * int -- pandas returns -2, i.e. i64::MAX.wrapping_mul(2).
14340        assert_eq!(
14341            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::Strict),
14342            -2,
14343            "STRICT must reproduce pandas' wrap, not repair it"
14344        );
14345
14346        // cumsum -- and the THIRD element is the important one: it proves the
14347        // accumulator keeps wrapping rather than sticking at a bound.
14348        let max = Scalar::Timedelta64(i64::MAX);
14349        let out = nancumsum_with_policy(
14350            &[max.clone(), max.clone(), max.clone()],
14351            OverflowPolicy::Strict,
14352        );
14353        assert_eq!(
14354            out,
14355            vec![
14356                Scalar::Timedelta64(i64::MAX),
14357                Scalar::Timedelta64(-2),
14358                Scalar::Timedelta64(i64::MAX - 2),
14359            ],
14360            "STRICT cumsum must reproduce pandas' int64 wraparound exactly"
14361        );
14362
14363        // NaT still propagates; the wrap is about overflow, not missingness.
14364        assert_eq!(
14365            Timedelta::mul_scalar_with_policy(Timedelta::NAT, 2, OverflowPolicy::Strict),
14366            Timedelta::NAT
14367        );
14368    }
14369
14370    /// The other half of the s4lkx decision, and the reason reproducing a
14371    /// fail-open quirk is acceptable at all: it is reachable ONLY when a caller
14372    /// explicitly asks for STRICT incumbent parity. Every other policy — and
14373    /// crucially the DEFAULT — still refuses to fabricate a plausible value,
14374    /// keeping the br-frankenpandas-lgyy8 guarantee intact.
14375    #[test]
14376    fn non_strict_policies_still_refuse_to_wrap_s4lkx() {
14377        use super::{OverflowPolicy, nancumsum_with_policy, overflow_audit};
14378
14379        for policy in [OverflowPolicy::SurfaceNat, OverflowPolicy::HardenedNat] {
14380            assert_eq!(
14381                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14382                Timedelta::NAT,
14383                "{policy:?} must NOT wrap"
14384            );
14385            assert_ne!(
14386                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14387                -2,
14388                "{policy:?} must not reproduce the pandas quirk"
14389            );
14390        }
14391        // The bare default is SurfaceNat, so an unconfigured caller is safe.
14392        assert_eq!(
14393            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::default()),
14394            Timedelta::NAT
14395        );
14396
14397        // cumsum likewise keeps the exact-i128 / NaT behaviour off STRICT.
14398        let max = Scalar::Timedelta64(i64::MAX);
14399        let soft = nancumsum_with_policy(&[max.clone(), max.clone()], OverflowPolicy::SurfaceNat);
14400        assert!(soft[1].is_missing(), "non-STRICT cumsum must NaT, not wrap");
14401        assert_eq!(soft, super::nancumsum(&[max.clone(), max]));
14402
14403        // HARDENED wrapping would be doubly wrong: it would fabricate a value
14404        // AND leave nothing in the audit trail to explain it.
14405        overflow_audit::enable();
14406        let _ = Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::HardenedNat);
14407        assert_eq!(
14408            overflow_audit::drain().len(),
14409            1,
14410            "HARDENED must record the recovery it performed"
14411        );
14412        overflow_audit::disable();
14413    }
14414
14415    /// Mixed Datetime64 + another dtype must NOT take the typed arm — it falls
14416    /// back exactly as before, so this fix cannot change cross-type behavior.
14417    #[test]
14418    fn datetime64_mixed_input_still_falls_back_axhhk() {
14419        let vals = vec![Scalar::Datetime64(DT_2020), Scalar::Int64(5)];
14420        // `is_datetime_input` is false here, so both keep their PRE-EXISTING
14421        // cross-type behavior, which differs between the two by construction:
14422        //   nanmin  — the catch-all compares via to_f64(); the Datetime64 side
14423        //             errors, so it bails to Null(NaN).
14424        //   nanptp  — its f64 loop SKIPS values whose to_f64() errors, so the
14425        //             datetime is dropped and the range is taken over the lone
14426        //             Int64 => Float64(0.0). Same shape as the documented
14427        //             mixed-timedelta fallback in ..._620mj (which yields 5.0).
14428        // Neither is changed by this bead; pinning both stops the new typed arm
14429        // from silently widening to mixed input later.
14430        assert!(super::nanmin(&vals).is_missing());
14431        assert_eq!(super::nanptp(&vals), Scalar::Float64(0.0));
14432    }
14433
14434    #[test]
14435    fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
14436        // Mixed Timedelta64 + other type bails out of the Timedelta path
14437        // and uses Float64 collect_finite (which drops Timedelta).
14438        // Preserves existing cross-type behavior (effectively ignores TD).
14439        let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
14440        // Int64(5) makes it through to_f64 → 5.0; Timedelta is dropped.
14441        assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
14442    }
14443
14444    #[test]
14445    fn nancount_counts_non_missing() {
14446        let vals = vec![
14447            Scalar::Int64(1),
14448            Scalar::Null(NullKind::Null),
14449            Scalar::Float64(3.0),
14450        ];
14451        assert_eq!(super::nancount(&vals), Scalar::Int64(2));
14452    }
14453
14454    #[test]
14455    fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
14456        // Differential vs scalar truthiness/count oracle
14457        // (br-frankenpandas-zr2qg). Seeded LCG, no mocks.
14458        fn next(seed: &mut u64) -> u64 {
14459            *seed = seed
14460                .wrapping_mul(6364136223846793005)
14461                .wrapping_add(1442695040888963407);
14462            *seed
14463        }
14464
14465        fn truthy(value: &Scalar) -> Option<bool> {
14466            if value.is_missing() {
14467                return None;
14468            }
14469            match value {
14470                Scalar::Bool(value) => Some(*value),
14471                Scalar::Int64(value) => Some(*value != 0),
14472                Scalar::Float64(value) => Some(*value != 0.0),
14473                Scalar::Utf8(value) => Some(!value.is_empty()),
14474                Scalar::Timedelta64(value) => Some(*value != 0),
14475                _ => None,
14476            }
14477        }
14478
14479        fn assert_nanops(case: usize, values: &[Scalar]) {
14480            let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
14481            let expected_any = truth_values.iter().any(|value| *value);
14482            let expected_all = !truth_values.iter().any(|value| !*value);
14483            let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
14484
14485            assert_eq!(
14486                super::nanany(values),
14487                Scalar::Bool(expected_any),
14488                "case={case}: nanany mismatch for {values:?}"
14489            );
14490            assert_eq!(
14491                super::nanall(values),
14492                Scalar::Bool(expected_all),
14493                "case={case}: nanall mismatch for {values:?}"
14494            );
14495            assert_eq!(
14496                super::nancount(values),
14497                Scalar::Int64(expected_count),
14498                "case={case}: nancount mismatch for {values:?}"
14499            );
14500        }
14501
14502        assert_nanops(
14503            usize::MAX,
14504            &[
14505                Scalar::Null(NullKind::Null),
14506                Scalar::Null(NullKind::NaN),
14507                Scalar::Float64(f64::NAN),
14508                Scalar::Timedelta64(i64::MIN),
14509            ],
14510        );
14511
14512        let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
14513        for case in 0..320 {
14514            let len = (next(&mut seed) % 89 + 1) as usize;
14515            let mut values = Vec::with_capacity(len);
14516            for pos in 0..len {
14517                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
14518                let value = match next(&mut seed) % 12 {
14519                    0 => Scalar::Null(NullKind::Null),
14520                    1 => Scalar::Null(NullKind::NaN),
14521                    2 => Scalar::Float64(f64::NAN),
14522                    3 => Scalar::Bool(raw & 1 == 0),
14523                    4 => Scalar::Bool(false),
14524                    5 => Scalar::Int64(raw % 17),
14525                    6 => Scalar::Int64(0),
14526                    7 => Scalar::Float64(raw as f64 / 23.0),
14527                    8 => Scalar::Float64(0.0),
14528                    9 => Scalar::Utf8(if raw & 1 == 0 {
14529                        String::new()
14530                    } else {
14531                        format!("nanops_{case}_{pos}")
14532                    }),
14533                    10 => Scalar::Timedelta64(raw),
14534                    _ => Scalar::Timedelta64(0),
14535                };
14536                values.push(value);
14537            }
14538            assert_nanops(case, &values);
14539        }
14540    }
14541
14542    #[test]
14543    fn nanmin_basic() {
14544        let vals = vec![
14545            Scalar::Float64(5.0),
14546            Scalar::Null(NullKind::Null),
14547            Scalar::Float64(2.0),
14548            Scalar::Float64(8.0),
14549        ];
14550        assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
14551    }
14552
14553    #[test]
14554    fn nanmax_basic() {
14555        let vals = vec![
14556            Scalar::Float64(5.0),
14557            Scalar::Float64(f64::NAN),
14558            Scalar::Float64(8.0),
14559        ];
14560        assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
14561    }
14562
14563    #[test]
14564    fn nanmin_nanmax_empty_returns_nan() {
14565        assert!(super::nanmin(&[]).is_missing());
14566        assert!(super::nanmax(&[]).is_missing());
14567    }
14568
14569    #[test]
14570    fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
14571        // Differential vs independent same-family comparator oracle
14572        // (br-frankenpandas-vj7ds). Seeded LCG, no mocks.
14573        fn next(seed: &mut u64) -> u64 {
14574            *seed = seed
14575                .wrapping_mul(6364136223846793005)
14576                .wrapping_add(1442695040888963407);
14577            *seed
14578        }
14579
14580        fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
14581            match (left, right) {
14582                (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
14583                (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
14584                (Scalar::Float64(left), Scalar::Float64(right)) => {
14585                    left.partial_cmp(right).expect("finite floats")
14586                }
14587                (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
14588                (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
14589                // `assert_minmax` verifies that every present value belongs
14590                // to one generated family before it invokes this comparator.
14591                _ => std::cmp::Ordering::Equal,
14592            }
14593        }
14594
14595        fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
14596            let present = values
14597                .iter()
14598                .filter(|value| !value.is_missing())
14599                .cloned()
14600                .collect::<Vec<_>>();
14601            let actual_min = super::nanmin(values);
14602            let actual_max = super::nanmax(values);
14603            if present.is_empty() {
14604                assert!(
14605                    actual_min.is_missing(),
14606                    "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
14607                );
14608                assert!(
14609                    actual_max.is_missing(),
14610                    "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
14611                );
14612                return;
14613            }
14614
14615            let is_expected_family = |value: &Scalar| match family {
14616                "int" => matches!(value, Scalar::Int64(_)),
14617                "float" => matches!(value, Scalar::Float64(_)),
14618                "bool" => matches!(value, Scalar::Bool(_)),
14619                "utf8" => matches!(value, Scalar::Utf8(_)),
14620                "timedelta" => matches!(value, Scalar::Timedelta64(_)),
14621                _ => false,
14622            };
14623            assert!(
14624                present.iter().all(is_expected_family),
14625                "case={case} family={family}: mixed family escaped generator: {values:?}"
14626            );
14627
14628            let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
14629            let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
14630            assert!(
14631                actual_min.semantic_eq(expected_min.expect("min")),
14632                "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
14633                expected_min.expect("min")
14634            );
14635            assert!(
14636                actual_max.semantic_eq(expected_max.expect("max")),
14637                "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
14638                expected_max.expect("max")
14639            );
14640        }
14641
14642        let all_missing = [
14643            Scalar::Null(NullKind::Null),
14644            Scalar::Null(NullKind::NaN),
14645            Scalar::Float64(f64::NAN),
14646            Scalar::Timedelta64(i64::MIN),
14647        ];
14648        assert_minmax(usize::MAX, "all_missing", &all_missing);
14649
14650        let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
14651        for case in 0..240 {
14652            let len = (next(&mut seed) % 73 + 1) as usize;
14653
14654            let mut ints = Vec::with_capacity(len);
14655            ints.push(Scalar::Int64(case as i64 - 120));
14656            for _ in 1..len {
14657                let raw = (next(&mut seed) % 1_001) as i64 - 500;
14658                ints.push(match next(&mut seed) % 6 {
14659                    0 => Scalar::Null(NullKind::Null),
14660                    1 => Scalar::Null(NullKind::NaN),
14661                    _ => Scalar::Int64(raw),
14662                });
14663            }
14664            assert_minmax(case, "int", &ints);
14665
14666            let mut floats = Vec::with_capacity(len);
14667            floats.push(Scalar::Float64(case as f64 / 11.0));
14668            for _ in 1..len {
14669                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14670                floats.push(match next(&mut seed) % 8 {
14671                    0 | 1 => Scalar::Float64(f64::NAN),
14672                    2 => Scalar::Float64(f64::INFINITY),
14673                    3 => Scalar::Float64(f64::NEG_INFINITY),
14674                    4 => Scalar::Float64(0.0),
14675                    5 => Scalar::Float64(-0.0),
14676                    _ => Scalar::Float64(raw as f64 / 41.0),
14677                });
14678            }
14679            assert_minmax(case, "float", &floats);
14680
14681            let mut bools = Vec::with_capacity(len);
14682            bools.push(Scalar::Bool(case & 1 == 0));
14683            for _ in 1..len {
14684                bools.push(match next(&mut seed) % 5 {
14685                    0 => Scalar::Null(NullKind::Null),
14686                    1 => Scalar::Null(NullKind::NaN),
14687                    raw => Scalar::Bool(raw & 1 == 0),
14688                });
14689            }
14690            assert_minmax(case, "bool", &bools);
14691
14692            let mut utf8 = Vec::with_capacity(len);
14693            utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
14694            for pos in 1..len {
14695                utf8.push(match next(&mut seed) % 7 {
14696                    0 => Scalar::Null(NullKind::Null),
14697                    1 => Scalar::Null(NullKind::NaN),
14698                    raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
14699                });
14700            }
14701            assert_minmax(case, "utf8", &utf8);
14702
14703            let mut timedeltas = Vec::with_capacity(len);
14704            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
14705            for _ in 1..len {
14706                let raw = (next(&mut seed) % 1_003) as i64 - 501;
14707                timedeltas.push(match next(&mut seed) % 7 {
14708                    0 => Scalar::Null(NullKind::Null),
14709                    1 => Scalar::Timedelta64(i64::MIN),
14710                    _ => Scalar::Timedelta64(raw),
14711                });
14712            }
14713            assert_minmax(case, "timedelta", &timedeltas);
14714        }
14715    }
14716
14717    #[test]
14718    fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
14719        let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
14720        assert!(super::nanmin(&vals).is_missing());
14721        assert!(super::nanmax(&vals).is_missing());
14722
14723        let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
14724        assert!(super::nanmin(&vals2).is_missing());
14725        assert!(super::nanmax(&vals2).is_missing());
14726    }
14727
14728    #[test]
14729    fn nanmin_nanmax_compatible_numeric_types_ok() {
14730        let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
14731        assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
14732        assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
14733    }
14734
14735    #[test]
14736    fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
14737        // Per br-frankenpandas-yic5m: nanmin/nanmax on Timedelta64 returns
14738        // the smallest/largest Timedelta64 — was silently NaN before
14739        // because Timedelta64.to_f64() errors and the catch-all swallowed it.
14740        let one_hour = 3_600 * 1_000_000_000_i64;
14741        let vals = vec![
14742            Scalar::Timedelta64(3 * one_hour),
14743            Scalar::Timedelta64(one_hour),
14744            Scalar::Timedelta64(2 * one_hour),
14745        ];
14746        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
14747        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
14748    }
14749
14750    #[test]
14751    fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
14752        let one_hour = 3_600 * 1_000_000_000_i64;
14753        let vals = vec![
14754            Scalar::Timedelta64(Timedelta::NAT),
14755            Scalar::Timedelta64(one_hour),
14756            Scalar::Timedelta64(2 * one_hour),
14757            Scalar::Timedelta64(Timedelta::NAT),
14758        ];
14759        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
14760        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
14761    }
14762
14763    #[test]
14764    fn nanmedian_odd_count() {
14765        let vals = vec![
14766            Scalar::Float64(3.0),
14767            Scalar::Null(NullKind::Null),
14768            Scalar::Float64(1.0),
14769            Scalar::Float64(2.0),
14770        ];
14771        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
14772    }
14773
14774    #[test]
14775    fn nanmedian_even_count() {
14776        let vals = vec![
14777            Scalar::Float64(1.0),
14778            Scalar::Float64(3.0),
14779            Scalar::Float64(2.0),
14780            Scalar::Float64(4.0),
14781        ];
14782        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
14783    }
14784
14785    #[test]
14786    fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
14787        // Differential vs independent sort-based median oracles
14788        // (br-frankenpandas-oabhi). Seeded LCG, no mocks.
14789        fn next(seed: &mut u64) -> u64 {
14790            *seed = seed
14791                .wrapping_mul(6364136223846793005)
14792                .wrapping_add(1442695040888963407);
14793            *seed
14794        }
14795
14796        fn expected_numeric(values: &[Scalar]) -> Scalar {
14797            let mut finite = values
14798                .iter()
14799                .filter(|value| !value.is_missing())
14800                .filter_map(|value| value.to_f64().ok())
14801                .filter(|value| !value.is_nan())
14802                .collect::<Vec<_>>();
14803            if finite.is_empty() {
14804                return Scalar::Null(NullKind::NaN);
14805            }
14806            finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
14807            let mid = finite.len() / 2;
14808            if finite.len().is_multiple_of(2) {
14809                Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
14810            } else {
14811                Scalar::Float64(finite[mid])
14812            }
14813        }
14814
14815        fn expected_timedelta(values: &[Scalar]) -> Scalar {
14816            let mut finite = values
14817                .iter()
14818                .filter_map(|value| match value {
14819                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns),
14820                    _ => None,
14821                })
14822                .collect::<Vec<_>>();
14823            if finite.is_empty() {
14824                return Scalar::Null(NullKind::NaN);
14825            }
14826            finite.sort_unstable();
14827            let mid = finite.len() / 2;
14828            let median = if finite.len().is_multiple_of(2) {
14829                (i128::from(finite[mid - 1]) + i128::from(finite[mid])) / 2
14830            } else {
14831                i128::from(finite[mid])
14832            };
14833            Scalar::Timedelta64(median as i64)
14834        }
14835
14836        fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
14837            let actual = super::nanmedian(values);
14838            assert!(
14839                actual.semantic_eq(&expected),
14840                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
14841            );
14842        }
14843
14844        assert_median(
14845            usize::MAX,
14846            "numeric_all_missing",
14847            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
14848            Scalar::Null(NullKind::NaN),
14849        );
14850        assert_median(
14851            usize::MAX - 1,
14852            "timedelta_all_missing",
14853            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
14854            Scalar::Null(NullKind::NaN),
14855        );
14856        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
14857        assert_median(
14858            usize::MAX - 2,
14859            "timedelta_odd_median_beyond_f64_exactness",
14860            &[
14861                Scalar::Timedelta64(beyond_f64_exact_ns),
14862                Scalar::Timedelta64(beyond_f64_exact_ns + 1),
14863                Scalar::Timedelta64(beyond_f64_exact_ns + 2),
14864                Scalar::Timedelta64(Timedelta::NAT),
14865            ],
14866            Scalar::Timedelta64(beyond_f64_exact_ns + 1),
14867        );
14868
14869        let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
14870        for case in 0..220 {
14871            let len = (next(&mut seed) % 79 + 1) as usize;
14872
14873            let mut numeric = Vec::with_capacity(len);
14874            numeric.push(Scalar::Int64(case as i64 - 110));
14875            for _ in 1..len {
14876                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14877                numeric.push(match next(&mut seed) % 8 {
14878                    0 => Scalar::Null(NullKind::Null),
14879                    1 => Scalar::Null(NullKind::NaN),
14880                    2 => Scalar::Float64(f64::NAN),
14881                    3 => Scalar::Bool(raw & 1 == 0),
14882                    4 => Scalar::Int64(raw % 251),
14883                    5 => Scalar::Float64(raw as f64 / 61.0),
14884                    6 => Scalar::Float64(0.0),
14885                    _ => Scalar::Float64(-0.0),
14886                });
14887            }
14888            assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
14889
14890            let mut timedeltas = Vec::with_capacity(len);
14891            timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
14892            for _ in 1..len {
14893                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14894                timedeltas.push(match next(&mut seed) % 7 {
14895                    0 => Scalar::Null(NullKind::Null),
14896                    1 => Scalar::Timedelta64(i64::MIN),
14897                    _ => Scalar::Timedelta64(raw),
14898                });
14899            }
14900            assert_median(
14901                case,
14902                "timedelta",
14903                &timedeltas,
14904                expected_timedelta(&timedeltas),
14905            );
14906        }
14907    }
14908
14909    #[test]
14910    fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
14911        // Differential vs independent variance/std/sem oracles
14912        // (br-frankenpandas-k7apg). Seeded LCG, no mocks.
14913        fn next(seed: &mut u64) -> u64 {
14914            *seed = seed
14915                .wrapping_mul(2862933555777941757)
14916                .wrapping_add(3037000493);
14917            *seed
14918        }
14919
14920        fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
14921            values
14922                .iter()
14923                .filter(|value| !value.is_missing())
14924                .filter_map(|value| value.to_f64().ok())
14925                .collect()
14926        }
14927
14928        fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
14929            values
14930                .iter()
14931                .filter_map(|value| match value {
14932                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
14933                    _ => None,
14934                })
14935                .collect()
14936        }
14937
14938        fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
14939            if samples.len() <= ddof {
14940                return None;
14941            }
14942            let mean = samples.iter().sum::<f64>() / samples.len() as f64;
14943            let sum_sq = samples
14944                .iter()
14945                .map(|value| (value - mean).powi(2))
14946                .sum::<f64>();
14947            let var = sum_sq / (samples.len() - ddof) as f64;
14948            let std = var.sqrt();
14949            let sem = std / (samples.len() as f64).sqrt();
14950            Some((var, std, sem))
14951        }
14952
14953        fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
14954            let samples = numeric_samples(values);
14955            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
14956                let missing = Scalar::Null(NullKind::NaN);
14957                return (missing.clone(), missing.clone(), missing);
14958            };
14959            (
14960                Scalar::Float64(var),
14961                Scalar::Float64(std),
14962                Scalar::Float64(sem),
14963            )
14964        }
14965
14966        fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
14967            let samples = timedelta_samples(values);
14968            if samples.is_empty() {
14969                let missing = Scalar::Timedelta64(Timedelta::NAT);
14970                return (missing.clone(), missing.clone(), missing);
14971            }
14972            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
14973                let missing = Scalar::Timedelta64(i64::MIN);
14974                return (missing.clone(), missing.clone(), missing);
14975            };
14976            (
14977                Scalar::Timedelta64(var as i64),
14978                Scalar::Timedelta64(std as i64),
14979                Scalar::Timedelta64(sem as i64),
14980            )
14981        }
14982
14983        fn assert_reductions(
14984            case: usize,
14985            family: &str,
14986            values: &[Scalar],
14987            ddof: usize,
14988            expected: (Scalar, Scalar, Scalar),
14989        ) {
14990            let (expected_var, expected_std, expected_sem) = expected;
14991            let actual_var = super::nanvar(values, ddof);
14992            let actual_std = super::nanstd(values, ddof);
14993            let actual_sem = super::nansem(values, ddof);
14994            assert!(
14995                actual_var.semantic_eq(&expected_var),
14996                "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
14997            );
14998            assert!(
14999                actual_std.semantic_eq(&expected_std),
15000                "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
15001            );
15002            assert!(
15003                actual_sem.semantic_eq(&expected_sem),
15004                "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
15005            );
15006        }
15007
15008        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15009        assert_reductions(
15010            usize::MAX,
15011            "numeric_all_missing",
15012            &numeric_all_missing,
15013            0,
15014            expected_numeric(&numeric_all_missing, 0),
15015        );
15016
15017        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
15018        assert_reductions(
15019            usize::MAX - 1,
15020            "timedelta_all_missing",
15021            &td_all_missing,
15022            0,
15023            expected_timedelta(&td_all_missing, 0),
15024        );
15025
15026        let mut seed = 0x7a11_c0de_5eed_0421_u64;
15027        for case in 0..240 {
15028            let len = (next(&mut seed) % 83 + 1) as usize;
15029            let ddof = (next(&mut seed) % 4) as usize;
15030
15031            let mut numeric = Vec::with_capacity(len);
15032            numeric.push(Scalar::Float64(case as f64 / 13.0));
15033            for _ in 1..len {
15034                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15035                numeric.push(match next(&mut seed) % 8 {
15036                    0 => Scalar::Null(NullKind::Null),
15037                    1 => Scalar::Null(NullKind::NaN),
15038                    2 => Scalar::Float64(f64::NAN),
15039                    3 => Scalar::Bool(raw & 1 == 0),
15040                    4 => Scalar::Int64(raw % 251),
15041                    5 => Scalar::Float64(raw as f64 / 73.0),
15042                    6 => Scalar::Float64(0.0),
15043                    _ => Scalar::Float64(-0.0),
15044                });
15045            }
15046            assert_reductions(
15047                case,
15048                "numeric",
15049                &numeric,
15050                ddof,
15051                expected_numeric(&numeric, ddof),
15052            );
15053
15054            let mut timedeltas = Vec::with_capacity(len);
15055            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15056            for _ in 1..len {
15057                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15058                timedeltas.push(match next(&mut seed) % 7 {
15059                    0 => Scalar::Null(NullKind::Null),
15060                    1 => Scalar::Timedelta64(i64::MIN),
15061                    _ => Scalar::Timedelta64(raw),
15062                });
15063            }
15064            assert_reductions(
15065                case,
15066                "timedelta",
15067                &timedeltas,
15068                ddof,
15069                expected_timedelta(&timedeltas, ddof),
15070            );
15071        }
15072    }
15073
15074    #[test]
15075    fn nanvar_population() {
15076        let vals = vec![
15077            Scalar::Float64(2.0),
15078            Scalar::Float64(4.0),
15079            Scalar::Float64(4.0),
15080            Scalar::Float64(4.0),
15081            Scalar::Float64(5.0),
15082            Scalar::Float64(5.0),
15083            Scalar::Float64(7.0),
15084            Scalar::Float64(9.0),
15085        ];
15086        let var = super::nanvar(&vals, 0);
15087        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15088        if let Scalar::Float64(v) = var {
15089            assert!((v - 4.0).abs() < 1e-10);
15090        }
15091    }
15092
15093    #[test]
15094    fn nanvar_sample_ddof1() {
15095        let vals = vec![
15096            Scalar::Float64(2.0),
15097            Scalar::Float64(4.0),
15098            Scalar::Float64(4.0),
15099            Scalar::Float64(4.0),
15100            Scalar::Float64(5.0),
15101            Scalar::Float64(5.0),
15102            Scalar::Float64(7.0),
15103            Scalar::Float64(9.0),
15104        ];
15105        let var = super::nanvar(&vals, 1);
15106        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15107        if let Scalar::Float64(v) = var {
15108            assert!((v - 32.0 / 7.0).abs() < 1e-10);
15109        }
15110    }
15111
15112    #[test]
15113    fn nanvar_insufficient_values_returns_nan() {
15114        let vals = vec![Scalar::Float64(5.0)];
15115        assert!(super::nanvar(&vals, 1).is_missing());
15116    }
15117
15118    #[test]
15119    fn nanstd_is_sqrt_of_var() {
15120        let vals = vec![
15121            Scalar::Float64(2.0),
15122            Scalar::Float64(4.0),
15123            Scalar::Float64(4.0),
15124            Scalar::Float64(4.0),
15125            Scalar::Float64(5.0),
15126            Scalar::Float64(5.0),
15127            Scalar::Float64(7.0),
15128            Scalar::Float64(9.0),
15129        ];
15130        let std = super::nanstd(&vals, 0);
15131        assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
15132        if let Scalar::Float64(v) = std {
15133            assert!((v - 2.0).abs() < 1e-10);
15134        }
15135    }
15136
15137    #[test]
15138    fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
15139        // Per br-frankenpandas-j8ntk: pandas td_series.median() returns
15140        // Timedelta64; was silently NaN before via collect_finite.
15141        let one_hour = 3_600 * 1_000_000_000_i64;
15142        let vals = vec![
15143            Scalar::Timedelta64(one_hour),
15144            Scalar::Timedelta64(2 * one_hour),
15145            Scalar::Timedelta64(3 * one_hour),
15146        ];
15147        assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
15148    }
15149
15150    #[test]
15151    fn nanstd_timedelta64_preserves_dtype_j8ntk() {
15152        // Per br-frankenpandas-j8ntk: pandas td_series.std() returns
15153        // Timedelta64. Check Timedelta64 output and reasonable magnitude
15154        // for population std of [1h, 2h, 3h] = sqrt(2/3) * 1h.
15155        let one_hour: i64 = 3_600 * 1_000_000_000;
15156        let vals = vec![
15157            Scalar::Timedelta64(one_hour),
15158            Scalar::Timedelta64(2 * one_hour),
15159            Scalar::Timedelta64(3 * one_hour),
15160        ];
15161        let std = super::nanstd(&vals, 0);
15162        assert!(matches!(std, Scalar::Timedelta64(_)));
15163        if let Scalar::Timedelta64(ns) = std {
15164            let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
15165            assert!(
15166                (ns as f64 - expected).abs() < 1e6,
15167                "expected ~{expected} ns, got {ns}"
15168            );
15169        }
15170    }
15171
15172    #[test]
15173    fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
15174        let one_hour = 3_600 * 1_000_000_000_i64;
15175        let vals = vec![Scalar::Timedelta64(one_hour)];
15176        // ddof=1 with n=1 → underflow, returns NaT
15177        assert_eq!(super::nanstd(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15178        assert_eq!(super::nansem(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15179    }
15180
15181    #[test]
15182    fn nanops_with_mixed_types() {
15183        let vals = vec![
15184            Scalar::Bool(true),
15185            Scalar::Int64(3),
15186            Scalar::Float64(6.0),
15187            Scalar::Null(NullKind::Null),
15188        ];
15189        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
15190        assert_eq!(super::nancount(&vals), Scalar::Int64(3));
15191    }
15192
15193    #[test]
15194    fn nanops_all_missing_returns_identity() {
15195        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15196        assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
15197        assert!(super::nanmean(&vals).is_missing());
15198        assert!(super::nanmedian(&vals).is_missing());
15199        assert!(super::nanvar(&vals, 0).is_missing());
15200        assert!(super::nanstd(&vals, 0).is_missing());
15201    }
15202
15203    // ── Timedelta tests ────────────────────────────────────────────────
15204
15205    #[test]
15206    fn timedelta_parse_simple_units() {
15207        use super::Timedelta;
15208        assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
15209        assert_eq!(
15210            Timedelta::parse("2h").unwrap(),
15211            2 * Timedelta::NANOS_PER_HOUR
15212        );
15213        assert_eq!(
15214            Timedelta::parse("30m").unwrap(),
15215            30 * Timedelta::NANOS_PER_MIN
15216        );
15217        assert_eq!(
15218            Timedelta::parse("45s").unwrap(),
15219            45 * Timedelta::NANOS_PER_SEC
15220        );
15221        assert_eq!(
15222            Timedelta::parse("100ms").unwrap(),
15223            100 * Timedelta::NANOS_PER_MILLI
15224        );
15225        assert_eq!(
15226            Timedelta::parse("500us").unwrap(),
15227            500 * Timedelta::NANOS_PER_MICRO
15228        );
15229        assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
15230    }
15231
15232    #[test]
15233    fn timedelta_parse_zero_valued_compound() {
15234        use super::Timedelta;
15235        // Each of these is a Timedelta of zero, not a parse failure. Verified
15236        // against live pandas 2.2.3: every form below yields
15237        // `Timedelta('0 days 00:00:00')`. A guard in `parse_compound` used to
15238        // reject them all except the bare "0", which made
15239        // `to_timedelta(["10 seconds", "1 second", "0 seconds"])` raise on the
15240        // third element only.
15241        for s in [
15242            "0 seconds",
15243            "0 second",
15244            "0 sec",
15245            "0s",
15246            "0 days",
15247            "0d",
15248            "0 hours",
15249            "0.0 hours",
15250            "0 minutes",
15251            "0ms",
15252            "0us",
15253            "0ns",
15254            "0",
15255            "0 days 0 seconds",
15256        ] {
15257            assert_eq!(Timedelta::parse(s).unwrap(), 0, "parse({s:?}) should be 0");
15258        }
15259        // The sign is carried by the caller, so a negative zero is still zero.
15260        assert_eq!(Timedelta::parse("-0 seconds").unwrap(), 0);
15261        // Removing the guard must NOT admit garbage: an unknown unit and a
15262        // missing number are still rejected inside the loop.
15263        assert!(Timedelta::parse("0 fortnights").is_err());
15264        assert!(Timedelta::parse("seconds").is_err());
15265    }
15266
15267    #[test]
15268    fn timedelta_parse_compound() {
15269        use super::Timedelta;
15270        let expected = Timedelta::NANOS_PER_DAY
15271            + 2 * Timedelta::NANOS_PER_HOUR
15272            + 30 * Timedelta::NANOS_PER_MIN;
15273        assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
15274        assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
15275    }
15276
15277    #[test]
15278    fn timedelta_parse_leading_sign_spares_the_clock_part() {
15279        use super::Timedelta;
15280        const S: i64 = Timedelta::NANOS_PER_SEC;
15281        // Verified vs pandas 2.2.3 Timedelta(...).total_seconds(); the second
15282        // is how pandas prints a negative Timedelta.
15283        assert_eq!(Timedelta::parse("-1 days 02:03:04").unwrap(), -79_016 * S);
15284        assert_eq!(Timedelta::parse("-1 days +02:03:04").unwrap(), -79_016 * S);
15285        assert_eq!(
15286            Timedelta::parse("-3 days +23:59:59.5").unwrap(),
15287            -172_800 * S - S / 2
15288        );
15289        assert_eq!(Timedelta::parse("-0 days 01:00:00").unwrap(), 3_600 * S);
15290        // Without a clock part after a unit, the whole value is negated.
15291        assert_eq!(Timedelta::parse("-1d2h").unwrap(), -93_600 * S);
15292        assert_eq!(Timedelta::parse("-02:03:04").unwrap(), -7_384 * S);
15293        // A sign inside the string is pandas' "only leading negative signs".
15294        assert!(Timedelta::parse("-1 days -02:03:04").is_err());
15295        assert!(Timedelta::parse("1 days -02:00:00").is_err());
15296    }
15297
15298    #[test]
15299    fn timedelta_parse_iso8601_matches_pandas_tdiso() {
15300        use super::Timedelta;
15301        // Verified vs pandas 2.2.3 Timedelta(...).value.
15302        assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
15303        assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
15304        assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
15305        assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
15306        assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
15307        assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
15308        // pandas quirks: T ignored, M is minutes everywhere, units in any order.
15309        assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
15310        assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
15311        assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
15312        assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
15313        assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
15314        // Rejected like pandas: years, lowercase, bare P/PT.
15315        assert!(Timedelta::parse("P1Y").is_err());
15316        assert!(Timedelta::parse("p1d").is_err());
15317        assert!(Timedelta::parse("P").is_err());
15318        assert!(Timedelta::parse("PT").is_err());
15319    }
15320
15321    #[test]
15322    fn timedelta_parse_time_format() {
15323        use super::Timedelta;
15324        let expected = Timedelta::NANOS_PER_HOUR
15325            + 30 * Timedelta::NANOS_PER_MIN
15326            + 45 * Timedelta::NANOS_PER_SEC;
15327        assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
15328    }
15329
15330    #[test]
15331    fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
15332        use super::{Timedelta, TimedeltaError};
15333        let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
15334            .expect_err("non-ASCII fractional seconds must reject");
15335        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15336    }
15337
15338    #[test]
15339    fn timedelta_parse_time_format_rejects_overflow_without_panic() {
15340        use super::{Timedelta, TimedeltaError};
15341        let err = Timedelta::parse("9223372036854775807:00")
15342            .expect_err("oversized hour component must reject");
15343        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15344    }
15345
15346    #[test]
15347    fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
15348        // Per br-frankenpandas-zw3mg: the compound parser used a raw
15349        // `as i64` cast that silently saturated to i64::MAX when the
15350        // product of (decimal-digit f64) × unit multiplier overflows.
15351        // Use a large literal (no scientific notation — the lexer only
15352        // accepts digits, '.', '-'). 1e18 days × NANOS_PER_DAY (~8.64e13)
15353        // overflows i64.
15354        use super::{Timedelta, TimedeltaError};
15355        let huge = format!("{} days", "9".repeat(18));
15356        assert!(matches!(
15357            Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
15358            TimedeltaError::Overflow
15359        ));
15360    }
15361
15362    #[test]
15363    fn timedelta_parse_nat() {
15364        use super::Timedelta;
15365        assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
15366        assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
15367    }
15368
15369    #[test]
15370    fn timedelta_parse_negative() {
15371        use super::Timedelta;
15372        assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
15373    }
15374
15375    #[test]
15376    fn timedelta_components() {
15377        use super::Timedelta;
15378        let nanos = Timedelta::NANOS_PER_DAY
15379            + Timedelta::NANOS_PER_HOUR
15380            + Timedelta::NANOS_PER_MIN
15381            + Timedelta::NANOS_PER_SEC
15382            + Timedelta::NANOS_PER_MILLI
15383            + 2 * Timedelta::NANOS_PER_MICRO
15384            + 3;
15385        let comp = Timedelta::components(nanos);
15386        assert_eq!(comp.days, 1);
15387        assert_eq!(comp.hours, 1);
15388        assert_eq!(comp.minutes, 1);
15389        assert_eq!(comp.seconds, 1);
15390        assert_eq!(comp.milliseconds, 1);
15391        assert_eq!(comp.microseconds, 2);
15392        assert_eq!(comp.nanoseconds, 3);
15393    }
15394
15395    #[test]
15396    fn timedelta_negative_components_floor_div() {
15397        use super::Timedelta;
15398        // pandas floor-normalizes negative timedeltas: pd.Timedelta(-1,'s') has
15399        // days=-1, seconds=86399, components=(-1, 23, 59, 59, 0, 0, 0).
15400        let neg_1s = -Timedelta::NANOS_PER_SEC;
15401        assert_eq!(Timedelta::days(neg_1s), Some(-1));
15402        assert_eq!(Timedelta::seconds(neg_1s), Some(86399));
15403        assert_eq!(Timedelta::microseconds(neg_1s), Some(0));
15404        assert_eq!(Timedelta::nanoseconds(neg_1s), Some(0));
15405        let comp = Timedelta::components(neg_1s);
15406        assert_eq!(
15407            (
15408                comp.days,
15409                comp.hours,
15410                comp.minutes,
15411                comp.seconds,
15412                comp.milliseconds,
15413                comp.microseconds,
15414                comp.nanoseconds
15415            ),
15416            (-1, 23, 59, 59, 0, 0, 0)
15417        );
15418
15419        // pd.Timedelta(-86401,'s'): days=-2, seconds=86399.
15420        let neg = -86_401 * Timedelta::NANOS_PER_SEC;
15421        assert_eq!(Timedelta::days(neg), Some(-2));
15422        assert_eq!(Timedelta::seconds(neg), Some(86399));
15423    }
15424
15425    /// br-frankenpandas-timedelta-nat-days-returns-zero-406ni.
15426    ///
15427    /// All four component helpers returned `0` for `NaT`, one of them behind a
15428    /// comment asserting "pandas returns 0 for NaT.days (no error)". MEASURED,
15429    /// live pandas 2.2.3: `pd.NaT.days` is **nan**, and
15430    /// `pd.to_timedelta([1, None, -1], unit='s').dt.days` is float64
15431    /// `[0.0, nan, -1.0]`.
15432    ///
15433    /// ⚠️ `0` IS THE ONE WRONG ANSWER THAT LOOKS RIGHT. It is a legal value for
15434    /// three of these four accessors — `seconds`, `microseconds` and
15435    /// `nanoseconds` all legitimately return 0 for a whole number of days — so a
15436    /// caller cannot distinguish "midnight" from "missing" by inspecting the
15437    /// result. That is the fail-open-as-plausible-data class, and it is why the
15438    /// fix is the return TYPE and not a corrected comment.
15439    #[test]
15440    fn timedelta_components_are_missing_for_nat_not_zero_406ni() {
15441        use super::Timedelta;
15442        assert_eq!(Timedelta::days(Timedelta::NAT), None);
15443        assert_eq!(Timedelta::seconds(Timedelta::NAT), None);
15444        assert_eq!(Timedelta::microseconds(Timedelta::NAT), None);
15445        assert_eq!(Timedelta::nanoseconds(Timedelta::NAT), None);
15446
15447        // NON-VACUITY: a whole number of days legitimately answers 0 for the
15448        // three sub-day components, so `Some(0)` and `None` must be reachable
15449        // from the same accessor. A test that only checked NaT could pass
15450        // against a helper that returned `None` unconditionally.
15451        let one_day = Timedelta::NANOS_PER_DAY;
15452        assert_eq!(Timedelta::days(one_day), Some(1));
15453        assert_eq!(Timedelta::seconds(one_day), Some(0));
15454        assert_eq!(Timedelta::microseconds(one_day), Some(0));
15455        assert_eq!(Timedelta::nanoseconds(one_day), Some(0));
15456    }
15457
15458    #[test]
15459    fn timedelta_total_seconds() {
15460        use super::Timedelta;
15461        let nanos = 90_000_000_000i64; // 90 seconds
15462        assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
15463        assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
15464    }
15465
15466    #[test]
15467    fn timedelta_format_basic() {
15468        use super::Timedelta;
15469        assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
15470        assert_eq!(
15471            Timedelta::format(Timedelta::NANOS_PER_DAY),
15472            "1 days 00:00:00"
15473        );
15474        assert_eq!(
15475            Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
15476            "1 days 02:00:00"
15477        );
15478    }
15479
15480    #[test]
15481    fn timedelta_format_subsecond_matches_pandas() {
15482        use super::Timedelta;
15483        // pandas str(Timedelta) uses 6 fractional digits (microseconds) unless a
15484        // sub-microsecond (nanosecond) component is present, then 9 digits.
15485        // Verified vs live pandas 2.2.3.
15486        assert_eq!(
15487            Timedelta::format(1_500_000_000), // 1.5s
15488            "0 days 00:00:01.500000"
15489        );
15490        assert_eq!(
15491            Timedelta::format(1_000_000), // 1ms
15492            "0 days 00:00:00.001000"
15493        );
15494        assert_eq!(
15495            Timedelta::format(123_456_000), // 123456us
15496            "0 days 00:00:00.123456"
15497        );
15498        // Nanosecond component -> 9 digits.
15499        assert_eq!(
15500            Timedelta::format(500), // 500ns
15501            "0 days 00:00:00.000000500"
15502        );
15503        assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
15504    }
15505
15506    #[test]
15507    fn timedelta_format_negative_uses_python_borrow_form() {
15508        use super::Timedelta;
15509        // pandas/Python normalize negatives via floor division: the days count
15510        // goes negative, the time remainder stays non-negative, and a '+' joins
15511        // them. Verified vs live pandas 2.2.3.
15512        assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
15513        assert_eq!(
15514            Timedelta::format(-Timedelta::NANOS_PER_DAY),
15515            "-1 days +00:00:00"
15516        );
15517        assert_eq!(
15518            Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
15519            "-2 days +23:00:00"
15520        );
15521        assert_eq!(
15522            Timedelta::format(-1_500_000_000),
15523            "-1 days +23:59:58.500000"
15524        );
15525        assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
15526        assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
15527    }
15528
15529    #[test]
15530    #[ignore = "foreground release attribution harness"]
15531    fn timedelta_format_single_buffer_ab_5ro9h() {
15532        use std::{hint::black_box, time::Instant};
15533
15534        use super::Timedelta;
15535
15536        fn former(nanos: i64) -> String {
15537            if nanos == Timedelta::NAT {
15538                return "NaT".to_string();
15539            }
15540
15541            let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
15542            let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
15543            let hours = rem / Timedelta::NANOS_PER_HOUR;
15544            let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
15545            let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
15546            let frac = rem % Timedelta::NANOS_PER_SEC;
15547
15548            let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
15549            let sep = if days < 0 { "+" } else { "" };
15550            if frac > 0 {
15551                if frac % 1_000 == 0 {
15552                    format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
15553                } else {
15554                    format!("{days} days {sep}{time_part}.{frac:09}")
15555                }
15556            } else {
15557                format!("{days} days {sep}{time_part}")
15558            }
15559        }
15560
15561        fn candidate(nanos: i64) -> String {
15562            Timedelta::format(nanos)
15563        }
15564
15565        fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
15566            let started = Instant::now();
15567            let mut digest = 0_usize;
15568            for &value in values {
15569                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
15570            }
15571            black_box(digest);
15572            started.elapsed().as_nanos()
15573        }
15574
15575        fn median(samples: &mut [u128]) -> u128 {
15576            samples.sort_unstable();
15577            samples[samples.len() / 2]
15578        }
15579
15580        let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
15581        let values: Vec<i64> = (0..16_384)
15582            .map(|i| {
15583                seed = seed
15584                    .wrapping_mul(6_364_136_223_846_793_005)
15585                    .wrapping_add(1_442_695_040_888_963_407);
15586                let magnitude = (seed & i64::MAX as u64) as i64;
15587                match i % 4 {
15588                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
15589                    1 => magnitude,
15590                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
15591                    _ => -magnitude,
15592                }
15593            })
15594            .collect();
15595
15596        for &value in &[
15597            Timedelta::NAT,
15598            0,
15599            1,
15600            -1,
15601            Timedelta::NANOS_PER_DAY,
15602            -Timedelta::NANOS_PER_DAY,
15603            i64::MAX,
15604            i64::MIN + 1,
15605        ] {
15606            assert_eq!(former(value), candidate(value));
15607        }
15608        for &value in &values {
15609            assert_eq!(former(value), candidate(value));
15610        }
15611
15612        for _ in 0..2 {
15613            black_box(elapsed(&values, former));
15614            black_box(elapsed(&values, candidate));
15615        }
15616
15617        let mut former_samples = Vec::with_capacity(18);
15618        let mut candidate_samples = Vec::with_capacity(18);
15619        for block in 0_usize..9 {
15620            if block.is_multiple_of(2) {
15621                former_samples.push(elapsed(&values, former));
15622                candidate_samples.push(elapsed(&values, candidate));
15623                candidate_samples.push(elapsed(&values, candidate));
15624                former_samples.push(elapsed(&values, former));
15625            } else {
15626                candidate_samples.push(elapsed(&values, candidate));
15627                former_samples.push(elapsed(&values, former));
15628                former_samples.push(elapsed(&values, former));
15629                candidate_samples.push(elapsed(&values, candidate));
15630            }
15631        }
15632
15633        let former_p50 = median(&mut former_samples);
15634        let candidate_p50 = median(&mut candidate_samples);
15635        eprintln!(
15636            "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
15637            values.len(),
15638            former_p50 as f64 / candidate_p50 as f64,
15639        );
15640        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
15641        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
15642    }
15643
15644    #[test]
15645    fn timedelta_isoformat_basic() {
15646        use super::Timedelta;
15647        assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
15648        assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
15649        assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
15650        assert_eq!(
15651            Timedelta::isoformat(
15652                Timedelta::NANOS_PER_DAY
15653                    + 2 * Timedelta::NANOS_PER_HOUR
15654                    + 30 * Timedelta::NANOS_PER_MIN
15655                    + 45 * Timedelta::NANOS_PER_SEC
15656            ),
15657            "P1DT2H30M45S"
15658        );
15659        assert_eq!(
15660            Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
15661            "P0DT0H0M1.5S"
15662        );
15663        // TEST-CHANGE (fvsao.68): this pinned "-P1DT1H0M0S"; pandas 2.2.3's
15664        // pd.Timedelta(-90000000000000).isoformat() is "P-2DT23H0M0S" (whole
15665        // days rounded down, then a non-negative clock), and -1ns is
15666        // "P-1DT23H59M59.999999999S" (both measured live).
15667        assert_eq!(
15668            Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
15669            "P-2DT23H0M0S"
15670        );
15671        assert_eq!(Timedelta::isoformat(-1), "P-1DT23H59M59.999999999S");
15672    }
15673
15674    #[test]
15675    #[ignore = "foreground release attribution harness"]
15676    fn timedelta_isoformat_single_buffer_ab_7jra1() {
15677        use std::{hint::black_box, time::Instant};
15678
15679        use super::Timedelta;
15680
15681        fn former_impl(nanos: i64) -> String {
15682            if nanos == Timedelta::NAT {
15683                return "NaT".to_string();
15684            }
15685
15686            let negative = nanos < 0;
15687            let abs_nanos = nanos.saturating_abs();
15688            let days = abs_nanos / Timedelta::NANOS_PER_DAY;
15689            let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
15690            let hours = remaining / Timedelta::NANOS_PER_HOUR;
15691            let remaining = remaining % Timedelta::NANOS_PER_HOUR;
15692            let minutes = remaining / Timedelta::NANOS_PER_MIN;
15693            let remaining = remaining % Timedelta::NANOS_PER_MIN;
15694            let seconds = remaining / Timedelta::NANOS_PER_SEC;
15695            let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
15696
15697            let mut result = String::new();
15698            if negative {
15699                result.push('-');
15700            }
15701
15702            result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
15703
15704            if sub_sec_nanos == 0 {
15705                result.push_str(&format!("{seconds}S"));
15706            } else {
15707                let frac = format!("{sub_sec_nanos:09}");
15708                let trimmed = frac.trim_end_matches('0');
15709                result.push_str(&format!("{seconds}.{trimmed}S"));
15710            }
15711
15712            result
15713        }
15714
15715        fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
15716            let start = Instant::now();
15717            let mut digest = 0_usize;
15718            for &value in values {
15719                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
15720            }
15721            black_box(digest);
15722            start.elapsed().as_nanos()
15723        }
15724
15725        fn median(values: &mut [u128]) -> u128 {
15726            values.sort_unstable();
15727            values[values.len() / 2]
15728        }
15729
15730        let mut seed = 0x7d5a_4c31_91e2_b607_u64;
15731        let values: Vec<i64> = (0..16_384)
15732            .map(|i| {
15733                seed = seed
15734                    .wrapping_mul(6_364_136_223_846_793_005)
15735                    .wrapping_add(1_442_695_040_888_963_407);
15736                let magnitude =
15737                    (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
15738                match i % 4 {
15739                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
15740                    1 => magnitude,
15741                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
15742                    _ => -magnitude,
15743                }
15744            })
15745            .collect();
15746
15747        // The former implementation wrote a negative duration "-P..."; since
15748        // fvsao.68 it is pandas' "P-..." form, so the two agree on
15749        // non-negative durations only (the timing still covers both signs).
15750        for &value in &[Timedelta::NAT, 0, 1, Timedelta::NANOS_PER_DAY, i64::MAX] {
15751            assert_eq!(former_impl(value), Timedelta::isoformat(value));
15752        }
15753        for &value in values.iter().filter(|value| **value >= 0) {
15754            assert_eq!(former_impl(value), Timedelta::isoformat(value));
15755        }
15756
15757        for _ in 0..2 {
15758            black_box(elapsed(&values, former_impl));
15759            black_box(elapsed(&values, Timedelta::isoformat));
15760        }
15761
15762        let mut former = Vec::with_capacity(18);
15763        let mut candidate = Vec::with_capacity(18);
15764        for block in 0..9 {
15765            if block % 2 == 0 {
15766                former.push(elapsed(&values, former_impl));
15767                candidate.push(elapsed(&values, Timedelta::isoformat));
15768                candidate.push(elapsed(&values, Timedelta::isoformat));
15769                former.push(elapsed(&values, former_impl));
15770            } else {
15771                candidate.push(elapsed(&values, Timedelta::isoformat));
15772                former.push(elapsed(&values, former_impl));
15773                former.push(elapsed(&values, former_impl));
15774                candidate.push(elapsed(&values, Timedelta::isoformat));
15775            }
15776        }
15777
15778        let former_p50 = median(&mut former);
15779        let candidate_p50 = median(&mut candidate);
15780        eprintln!(
15781            "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
15782            values.len(),
15783            former_p50,
15784            candidate_p50,
15785            former_p50 as f64 / candidate_p50 as f64,
15786            former_p50 as f64 / values.len() as f64,
15787            candidate_p50 as f64 / values.len() as f64,
15788        );
15789        eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
15790        eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
15791    }
15792
15793    #[test]
15794    fn timedelta_floor_ceil_round() {
15795        use super::Timedelta;
15796        let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
15797
15798        // floor: rounds down
15799        assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
15800        assert_eq!(Timedelta::floor(nanos, "d"), 0);
15801
15802        // ceil: rounds up
15803        assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
15804        assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
15805
15806        // round: rounds to nearest (banker's rounding on tie)
15807        assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
15808
15809        // NaT preserved
15810        assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
15811        assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
15812        assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
15813
15814        // Invalid freq returns NAT
15815        assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
15816    }
15817
15818    #[test]
15819    fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
15820        use super::Timedelta;
15821
15822        assert_eq!(
15823            Timedelta::floor(-1, "s"),
15824            -Timedelta::NANOS_PER_SEC,
15825            "floor(-1ns, 1s)"
15826        );
15827        assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
15828        assert_eq!(
15829            Timedelta::floor(-1_500_000_000, "s"),
15830            -2 * Timedelta::NANOS_PER_SEC
15831        );
15832        assert_eq!(
15833            Timedelta::ceil(-1_500_000_000, "s"),
15834            -Timedelta::NANOS_PER_SEC
15835        );
15836        assert_eq!(
15837            Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
15838            -Timedelta::NANOS_PER_SEC
15839        );
15840        assert_eq!(
15841            Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
15842            -Timedelta::NANOS_PER_SEC
15843        );
15844        assert_eq!(
15845            Timedelta::floor(1_500_000_000, "s"),
15846            Timedelta::NANOS_PER_SEC
15847        );
15848        assert_eq!(
15849            Timedelta::ceil(1_500_000_000, "s"),
15850            2 * Timedelta::NANOS_PER_SEC
15851        );
15852    }
15853
15854    #[test]
15855    fn timedelta_scalar_dtype() {
15856        let td = Scalar::Timedelta64(86_400_000_000_000);
15857        assert_eq!(td.dtype(), DType::Timedelta64);
15858    }
15859
15860    #[test]
15861    fn timedelta_scalar_is_missing() {
15862        use super::Timedelta;
15863        let valid = Scalar::Timedelta64(1000);
15864        let nat = Scalar::Timedelta64(Timedelta::NAT);
15865        assert!(!valid.is_missing());
15866        assert!(nat.is_missing());
15867    }
15868
15869    #[test]
15870    fn dtype_utf8_deserializes_legacy_aliases() {
15871        let dtype: DType = serde_json::from_str("\"str\"").unwrap();
15872        assert_eq!(dtype, DType::Utf8);
15873
15874        let dtype: DType = serde_json::from_str("\"string\"").unwrap();
15875        assert_eq!(dtype, DType::Utf8);
15876    }
15877
15878    #[test]
15879    fn datetime64_dtype_carries_timezone_00ze3() {
15880        let naive = DType::datetime64_naive();
15881        assert_eq!(naive.timezone(), None);
15882        assert_eq!(naive.display_name(), "datetime64[ns]");
15883
15884        let aware = DType::datetime64_tz("America/New_York");
15885        assert_eq!(aware.timezone(), Some("America/New_York"));
15886        assert_eq!(aware.display_name(), "datetime64[ns, America/New_York]");
15887        assert_ne!(aware, naive, "timezone must participate in dtype identity");
15888
15889        let json = serde_json::to_string(&aware).expect("serialize timezone dtype");
15890        assert_eq!(
15891            serde_json::from_str::<DType>(&json).expect("deserialize timezone dtype"),
15892            aware
15893        );
15894    }
15895
15896    #[test]
15897    fn scalar_utf8_deserializes_legacy_aliases() {
15898        let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
15899        assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
15900
15901        let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
15902        assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
15903    }
15904
15905    #[test]
15906    fn nancumsum_skips_nulls_and_accumulates() {
15907        let values = vec![
15908            Scalar::Float64(1.0),
15909            Scalar::Null(NullKind::NaN),
15910            Scalar::Float64(2.0),
15911            Scalar::Float64(3.0),
15912        ];
15913        let out = super::nancumsum(&values);
15914        assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
15915        assert!(out[1].is_missing());
15916        assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
15917        assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
15918    }
15919
15920    #[test]
15921    fn nancumprod_skips_nulls_and_multiplies() {
15922        let values = vec![
15923            Scalar::Float64(2.0),
15924            Scalar::Null(NullKind::NaN),
15925            Scalar::Float64(3.0),
15926            Scalar::Float64(4.0),
15927        ];
15928        let out = super::nancumprod(&values);
15929        assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
15930        assert!(out[1].is_missing());
15931        assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
15932        assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
15933    }
15934
15935    #[test]
15936    fn nancummax_tracks_running_max() {
15937        let values = vec![
15938            Scalar::Float64(1.0),
15939            Scalar::Float64(3.0),
15940            Scalar::Null(NullKind::NaN),
15941            Scalar::Float64(2.0),
15942            Scalar::Float64(5.0),
15943        ];
15944        let out = super::nancummax(&values);
15945        assert_eq!(out[0], Scalar::Float64(1.0));
15946        assert_eq!(out[1], Scalar::Float64(3.0));
15947        assert!(out[2].is_missing());
15948        assert_eq!(out[3], Scalar::Float64(3.0));
15949        assert_eq!(out[4], Scalar::Float64(5.0));
15950    }
15951
15952    #[test]
15953    fn nancummin_tracks_running_min() {
15954        let values = vec![
15955            Scalar::Float64(5.0),
15956            Scalar::Float64(3.0),
15957            Scalar::Null(NullKind::NaN),
15958            Scalar::Float64(4.0),
15959            Scalar::Float64(1.0),
15960        ];
15961        let out = super::nancummin(&values);
15962        assert_eq!(out[0], Scalar::Float64(5.0));
15963        assert_eq!(out[1], Scalar::Float64(3.0));
15964        assert!(out[2].is_missing());
15965        assert_eq!(out[3], Scalar::Float64(3.0));
15966        assert_eq!(out[4], Scalar::Float64(1.0));
15967    }
15968
15969    #[test]
15970    fn nancumsum_timedelta64_preserves_dtype_x0x91() {
15971        // Per br-frankenpandas-x0x91: pandas td_series.cumsum() returns
15972        // Timedelta64 running sums. Was silently NaN before.
15973        let one_hour = 3_600 * 1_000_000_000_i64;
15974        let values = vec![
15975            Scalar::Timedelta64(one_hour),
15976            Scalar::Timedelta64(2 * one_hour),
15977            Scalar::Timedelta64(3 * one_hour),
15978        ];
15979        let out = super::nancumsum(&values);
15980        assert_eq!(out[0], Scalar::Timedelta64(one_hour));
15981        assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
15982        assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
15983    }
15984
15985    #[test]
15986    fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
15987        let one_hour = 3_600 * 1_000_000_000_i64;
15988        let values = vec![
15989            Scalar::Timedelta64(2 * one_hour),
15990            Scalar::Timedelta64(5 * one_hour),
15991            Scalar::Timedelta64(one_hour),
15992            Scalar::Timedelta64(3 * one_hour),
15993        ];
15994        let mx = super::nancummax(&values);
15995        assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
15996        assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
15997        assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
15998        assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
15999
16000        let mn = super::nancummin(&values);
16001        assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
16002        assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
16003        assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
16004        assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
16005    }
16006
16007    #[test]
16008    fn nancumulative_timedelta64_skips_nat_x0x91() {
16009        let one_hour = 3_600 * 1_000_000_000_i64;
16010        let values = vec![
16011            Scalar::Timedelta64(one_hour),
16012            Scalar::Timedelta64(Timedelta::NAT),
16013            Scalar::Timedelta64(2 * one_hour),
16014        ];
16015        let cs = super::nancumsum(&values);
16016        assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
16017        assert!(cs[1].is_missing());
16018        assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
16019    }
16020
16021    #[test]
16022    fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
16023        // Differential vs independent cumulative nanops oracles
16024        // (br-frankenpandas-k63oz). Seeded LCG, no mocks.
16025        fn next(seed: &mut u64) -> u64 {
16026            *seed = seed
16027                .wrapping_mul(3202034522624059733)
16028                .wrapping_add(4354685564936845319);
16029            *seed
16030        }
16031
16032        fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
16033            assert_eq!(
16034                actual.len(),
16035                expected.len(),
16036                "case={case} family={family} op={op}: length mismatch"
16037            );
16038            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
16039                assert!(
16040                    actual.semantic_eq(expected),
16041                    "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
16042                );
16043            }
16044        }
16045
16046        fn expected_numeric(
16047            values: &[Scalar],
16048        ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16049            let mut sum = Vec::with_capacity(values.len());
16050            let mut prod = Vec::with_capacity(values.len());
16051            let mut max = Vec::with_capacity(values.len());
16052            let mut min = Vec::with_capacity(values.len());
16053            let mut running_sum = 0.0_f64;
16054            let mut running_prod = 1.0_f64;
16055            let mut running_max: Option<f64> = None;
16056            let mut running_min: Option<f64> = None;
16057
16058            for value in values {
16059                if value.is_missing() {
16060                    sum.push(Scalar::Null(NullKind::NaN));
16061                    prod.push(Scalar::Null(NullKind::NaN));
16062                    max.push(Scalar::Null(NullKind::NaN));
16063                    min.push(Scalar::Null(NullKind::NaN));
16064                    continue;
16065                }
16066                let Ok(value) = value.to_f64() else {
16067                    sum.push(Scalar::Null(NullKind::NaN));
16068                    prod.push(Scalar::Null(NullKind::NaN));
16069                    max.push(Scalar::Null(NullKind::NaN));
16070                    min.push(Scalar::Null(NullKind::NaN));
16071                    continue;
16072                };
16073                if value.is_nan() {
16074                    sum.push(Scalar::Null(NullKind::NaN));
16075                    prod.push(Scalar::Null(NullKind::NaN));
16076                    max.push(Scalar::Null(NullKind::NaN));
16077                    min.push(Scalar::Null(NullKind::NaN));
16078                    continue;
16079                }
16080                running_sum += value;
16081                running_prod *= value;
16082                running_max = Some(running_max.map_or(value, |current| current.max(value)));
16083                running_min = Some(running_min.map_or(value, |current| current.min(value)));
16084                sum.push(Scalar::Float64(running_sum));
16085                prod.push(Scalar::Float64(running_prod));
16086                max.push(Scalar::Float64(running_max.expect("initialized")));
16087                min.push(Scalar::Float64(running_min.expect("initialized")));
16088            }
16089
16090            (sum, prod, max, min)
16091        }
16092
16093        fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16094            let mut sum = Vec::with_capacity(values.len());
16095            let mut max = Vec::with_capacity(values.len());
16096            let mut min = Vec::with_capacity(values.len());
16097            let mut running_sum = 0_i128;
16098            let mut running_max: Option<i64> = None;
16099            let mut running_min: Option<i64> = None;
16100
16101            for value in values {
16102                if value.is_missing() {
16103                    sum.push(Scalar::Null(NullKind::NaT));
16104                    max.push(Scalar::Null(NullKind::NaT));
16105                    min.push(Scalar::Null(NullKind::NaT));
16106                    continue;
16107                }
16108                let Scalar::Timedelta64(ns) = value else {
16109                    sum.push(Scalar::Null(NullKind::NaT));
16110                    max.push(Scalar::Null(NullKind::NaT));
16111                    min.push(Scalar::Null(NullKind::NaT));
16112                    continue;
16113                };
16114                running_sum = running_sum.saturating_add(i128::from(*ns));
16115                running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
16116                running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
16117                // br-frankenpandas-opz27: mirror the production contract (NaT
16118                // outside the representable range), not the old clamp.
16119                sum.push(super::timedelta_ns_to_scalar(running_sum));
16120                max.push(Scalar::Timedelta64(running_max.expect("initialized")));
16121                min.push(Scalar::Timedelta64(running_min.expect("initialized")));
16122            }
16123
16124            (sum, max, min)
16125        }
16126
16127        let mut seed = 0xc0de_c63a_5eed_0421_u64;
16128        for case in 0..260 {
16129            let len = (next(&mut seed) % 89 + 1) as usize;
16130
16131            let mut numeric = Vec::with_capacity(len);
16132            numeric.push(Scalar::Int64(case as i64 - 130));
16133            for _ in 1..len {
16134                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16135                numeric.push(match next(&mut seed) % 8 {
16136                    0 => Scalar::Null(NullKind::Null),
16137                    1 => Scalar::Null(NullKind::NaN),
16138                    2 => Scalar::Float64(f64::NAN),
16139                    3 => Scalar::Bool(raw & 1 == 0),
16140                    4 => Scalar::Int64(raw % 251),
16141                    5 => Scalar::Float64(raw as f64 / 79.0),
16142                    6 => Scalar::Float64(0.0),
16143                    _ => Scalar::Float64(-0.0),
16144                });
16145            }
16146            let (sum, prod, max, min) = expected_numeric(&numeric);
16147            assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
16148            assert_vec(
16149                case,
16150                "numeric",
16151                "cumprod",
16152                &super::nancumprod(&numeric),
16153                &prod,
16154            );
16155            assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
16156            assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
16157
16158            let mut timedeltas = Vec::with_capacity(len);
16159            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16160            for _ in 1..len {
16161                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16162                timedeltas.push(match next(&mut seed) % 7 {
16163                    0 => Scalar::Null(NullKind::Null),
16164                    1 => Scalar::Timedelta64(i64::MIN),
16165                    _ => Scalar::Timedelta64(raw),
16166                });
16167            }
16168            let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
16169            assert_vec(
16170                case,
16171                "timedelta",
16172                "cumsum",
16173                &super::nancumsum(&timedeltas),
16174                &td_sum,
16175            );
16176            assert_vec(
16177                case,
16178                "timedelta",
16179                "cummax",
16180                &super::nancummax(&timedeltas),
16181                &td_max,
16182            );
16183            assert_vec(
16184                case,
16185                "timedelta",
16186                "cummin",
16187                &super::nancummin(&timedeltas),
16188                &td_min,
16189            );
16190        }
16191    }
16192
16193    #[test]
16194    fn nanquantile_linear_interpolation_matches_numpy() {
16195        let values = vec![
16196            Scalar::Float64(1.0),
16197            Scalar::Float64(2.0),
16198            Scalar::Float64(3.0),
16199            Scalar::Float64(4.0),
16200            Scalar::Float64(5.0),
16201        ];
16202        // median
16203        let q = super::nanquantile(&values, 0.5);
16204        assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
16205        // 25th percentile: interpolate between 2.0 and 3.0 at pos 1.0 → 2.0
16206        let q25 = super::nanquantile(&values, 0.25);
16207        assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16208    }
16209
16210    #[test]
16211    fn nanquantile_ignores_nulls() {
16212        let values = vec![
16213            Scalar::Float64(1.0),
16214            Scalar::Null(NullKind::NaN),
16215            Scalar::Float64(3.0),
16216        ];
16217        let q = super::nanquantile(&values, 0.5);
16218        assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16219    }
16220
16221    #[test]
16222    fn nanquantile_empty_and_out_of_range_yield_null() {
16223        assert!(super::nanquantile(&[], 0.5).is_missing());
16224        assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
16225        assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
16226    }
16227
16228    #[test]
16229    fn nanquantile_timedelta64_preserves_dtype_5djk7() {
16230        // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
16231        // Timedelta64 — was silently NaN before via collect_finite.
16232        let one_hour: i64 = 3_600 * 1_000_000_000;
16233        let vals = vec![
16234            Scalar::Timedelta64(one_hour),
16235            Scalar::Timedelta64(2 * one_hour),
16236            Scalar::Timedelta64(3 * one_hour),
16237            Scalar::Timedelta64(4 * one_hour),
16238            Scalar::Timedelta64(5 * one_hour),
16239        ];
16240        assert_eq!(
16241            super::nanquantile(&vals, 0.5),
16242            Scalar::Timedelta64(3 * one_hour)
16243        );
16244        assert_eq!(
16245            super::nanquantile(&vals, 0.0),
16246            Scalar::Timedelta64(one_hour)
16247        );
16248        assert_eq!(
16249            super::nanquantile(&vals, 1.0),
16250            Scalar::Timedelta64(5 * one_hour)
16251        );
16252    }
16253
16254    #[test]
16255    fn nanquantile_timedelta64_linear_interpolation_5djk7() {
16256        let one_hour: i64 = 3_600 * 1_000_000_000;
16257        let vals = vec![
16258            Scalar::Timedelta64(one_hour),
16259            Scalar::Timedelta64(3 * one_hour),
16260        ];
16261        // Linear interpolation: at q=0.5, midpoint = 2h
16262        assert_eq!(
16263            super::nanquantile(&vals, 0.5),
16264            Scalar::Timedelta64(2 * one_hour)
16265        );
16266    }
16267
16268    #[test]
16269    fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
16270        // Differential vs independent sort-based quantile oracles
16271        // (br-frankenpandas-ecb7r). Seeded LCG, no mocks.
16272        fn next(seed: &mut u64) -> u64 {
16273            *seed = seed
16274                .wrapping_mul(3202034522624059733)
16275                .wrapping_add(4354685564936845319);
16276            *seed
16277        }
16278
16279        fn interpolated(sorted: &[f64], q: f64) -> f64 {
16280            if sorted.len() == 1 {
16281                return sorted[0];
16282            }
16283            let pos = q * (sorted.len() - 1) as f64;
16284            let lo = pos.floor() as usize;
16285            let hi = pos.ceil() as usize;
16286            if lo == hi {
16287                sorted[lo]
16288            } else {
16289                let weight = pos - lo as f64;
16290                sorted[lo] + (sorted[hi] - sorted[lo]) * weight
16291            }
16292        }
16293
16294        fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
16295            if !(0.0..=1.0).contains(&q) {
16296                return Scalar::Null(NullKind::NaN);
16297            }
16298            let mut samples = values
16299                .iter()
16300                .filter(|value| !value.is_missing())
16301                .filter_map(|value| value.to_f64().ok())
16302                .collect::<Vec<_>>();
16303            if samples.is_empty() {
16304                return Scalar::Null(NullKind::NaN);
16305            }
16306            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16307            Scalar::Float64(interpolated(&samples, q))
16308        }
16309
16310        fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
16311            if !(0.0..=1.0).contains(&q) {
16312                return Scalar::Null(NullKind::NaN);
16313            }
16314            let mut samples = values
16315                .iter()
16316                .filter_map(|value| match value {
16317                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
16318                    _ => None,
16319                })
16320                .collect::<Vec<_>>();
16321            if samples.is_empty() {
16322                // Per br-frankenpandas-k7apg: a NaT-only Timedelta input stays in
16323                // the Timedelta family (pandas returns NaT, not float NaN).
16324                return Scalar::Timedelta64(Timedelta::NAT);
16325            }
16326            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16327            Scalar::Timedelta64(interpolated(&samples, q) as i64)
16328        }
16329
16330        fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
16331            let actual = super::nanquantile(values, q);
16332            assert!(
16333                actual.semantic_eq(&expected),
16334                "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
16335            );
16336        }
16337
16338        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16339        assert_quantile(
16340            usize::MAX,
16341            "numeric_all_missing",
16342            &numeric_all_missing,
16343            0.5,
16344            expected_numeric(&numeric_all_missing, 0.5),
16345        );
16346        assert_quantile(
16347            usize::MAX - 1,
16348            "numeric_out_of_range",
16349            &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
16350            1.25,
16351            Scalar::Null(NullKind::NaN),
16352        );
16353
16354        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16355        assert_quantile(
16356            usize::MAX - 2,
16357            "timedelta_all_missing",
16358            &td_all_missing,
16359            0.5,
16360            expected_timedelta(&td_all_missing, 0.5),
16361        );
16362        assert_quantile(
16363            usize::MAX - 3,
16364            "timedelta_out_of_range",
16365            &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
16366            -0.25,
16367            Scalar::Null(NullKind::NaN),
16368        );
16369
16370        let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
16371        for case in 0..260 {
16372            let len = (next(&mut seed) % 83 + 1) as usize;
16373            let q = match next(&mut seed) % 8 {
16374                0 => 0.0,
16375                1 => 0.25,
16376                2 => 0.5,
16377                3 => 0.75,
16378                4 => 1.0,
16379                _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
16380            };
16381
16382            let mut numeric = Vec::with_capacity(len);
16383            numeric.push(Scalar::Int64(case as i64 - 130));
16384            for _ in 1..len {
16385                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16386                numeric.push(match next(&mut seed) % 8 {
16387                    0 => Scalar::Null(NullKind::Null),
16388                    1 => Scalar::Null(NullKind::NaN),
16389                    2 => Scalar::Float64(f64::NAN),
16390                    3 => Scalar::Bool(raw & 1 == 0),
16391                    4 => Scalar::Int64(raw % 251),
16392                    5 => Scalar::Float64(raw as f64 / 67.0),
16393                    6 => Scalar::Float64(0.0),
16394                    _ => Scalar::Float64(-0.0),
16395                });
16396            }
16397            assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
16398
16399            let mut timedeltas = Vec::with_capacity(len);
16400            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16401            for _ in 1..len {
16402                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16403                timedeltas.push(match next(&mut seed) % 7 {
16404                    0 => Scalar::Null(NullKind::Null),
16405                    1 => Scalar::Timedelta64(i64::MIN),
16406                    _ => Scalar::Timedelta64(raw),
16407                });
16408            }
16409            assert_quantile(
16410                case,
16411                "timedelta",
16412                &timedeltas,
16413                q,
16414                expected_timedelta(&timedeltas, q),
16415            );
16416        }
16417    }
16418
16419    #[test]
16420    fn nanargmax_returns_first_position() {
16421        let values = vec![
16422            Scalar::Float64(1.0),
16423            Scalar::Null(NullKind::NaN),
16424            Scalar::Float64(4.0),
16425            Scalar::Float64(4.0),
16426            Scalar::Float64(2.0),
16427        ];
16428        assert_eq!(super::nanargmax(&values), Some(2));
16429    }
16430
16431    #[test]
16432    fn nanargmin_returns_first_position() {
16433        let values = vec![
16434            Scalar::Float64(3.0),
16435            Scalar::Null(NullKind::NaN),
16436            Scalar::Float64(1.0),
16437            Scalar::Float64(1.0),
16438        ];
16439        assert_eq!(super::nanargmin(&values), Some(2));
16440    }
16441
16442    #[test]
16443    fn nanargmax_all_missing_returns_none() {
16444        let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
16445        assert_eq!(super::nanargmax(&values), None);
16446        assert_eq!(super::nanargmin(&values), None);
16447    }
16448
16449    #[test]
16450    fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
16451        // Differential vs independent first-tie arg oracles
16452        // (br-frankenpandas-unkj6). Seeded LCG, no mocks.
16453        fn next(seed: &mut u64) -> u64 {
16454            *seed = seed
16455                .wrapping_mul(2862933555777941757)
16456                .wrapping_add(3037000493);
16457            *seed
16458        }
16459
16460        fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
16461            let mut best: Option<(usize, f64)> = None;
16462            for (idx, value) in values.iter().enumerate() {
16463                if value.is_missing() {
16464                    continue;
16465                }
16466                let Ok(value) = value.to_f64() else {
16467                    continue;
16468                };
16469                if value.is_nan() {
16470                    continue;
16471                }
16472                match best {
16473                    None => best = Some((idx, value)),
16474                    Some((_, current))
16475                        if (find_max && value > current) || (!find_max && value < current) =>
16476                    {
16477                        best = Some((idx, value));
16478                    }
16479                    _ => {}
16480                }
16481            }
16482            best.map(|(idx, _)| idx)
16483        }
16484
16485        fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
16486            let mut best: Option<(usize, i64)> = None;
16487            for (idx, value) in values.iter().enumerate() {
16488                if value.is_missing() {
16489                    continue;
16490                }
16491                let Scalar::Timedelta64(ns) = value else {
16492                    continue;
16493                };
16494                match best {
16495                    None => best = Some((idx, *ns)),
16496                    Some((_, current))
16497                        if (find_max && *ns > current) || (!find_max && *ns < current) =>
16498                    {
16499                        best = Some((idx, *ns));
16500                    }
16501                    _ => {}
16502                }
16503            }
16504            best.map(|(idx, _)| idx)
16505        }
16506
16507        fn assert_args(
16508            case: usize,
16509            family: &str,
16510            values: &[Scalar],
16511            expected_min: Option<usize>,
16512            expected_max: Option<usize>,
16513        ) {
16514            assert_eq!(
16515                super::nanargmin(values),
16516                expected_min,
16517                "case={case} family={family}: nanargmin mismatch for {values:?}"
16518            );
16519            assert_eq!(
16520                super::nanargmax(values),
16521                expected_max,
16522                "case={case} family={family}: nanargmax mismatch for {values:?}"
16523            );
16524        }
16525
16526        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16527        assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
16528        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16529        assert_args(
16530            usize::MAX - 1,
16531            "timedelta_all_missing",
16532            &td_all_missing,
16533            None,
16534            None,
16535        );
16536        let positive_int64_endpoint = [
16537            Scalar::Int64(i64::MAX - 1),
16538            Scalar::Null(NullKind::Null),
16539            Scalar::Int64(i64::MAX),
16540        ];
16541        assert_args(
16542            usize::MAX - 2,
16543            "int64_positive_endpoint_exact_order",
16544            &positive_int64_endpoint,
16545            Some(0),
16546            Some(2),
16547        );
16548        let negative_int64_endpoint = [
16549            Scalar::Int64(i64::MIN + 2),
16550            Scalar::Null(NullKind::NaN),
16551            Scalar::Int64(i64::MIN + 1),
16552        ];
16553        assert_args(
16554            usize::MAX - 3,
16555            "int64_negative_endpoint_exact_order",
16556            &negative_int64_endpoint,
16557            Some(2),
16558            Some(0),
16559        );
16560
16561        let mut seed = 0xa126_5eed_ed9e_u64;
16562        for case in 0..260 {
16563            let len = (next(&mut seed) % 83 + 1) as usize;
16564
16565            let mut numeric = Vec::with_capacity(len);
16566            numeric.push(Scalar::Int64(case as i64 - 130));
16567            if len > 1 {
16568                numeric.push(Scalar::Int64(case as i64 - 130));
16569            }
16570            for _ in numeric.len()..len {
16571                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16572                numeric.push(match next(&mut seed) % 9 {
16573                    0 => Scalar::Null(NullKind::Null),
16574                    1 => Scalar::Null(NullKind::NaN),
16575                    2 => Scalar::Float64(f64::NAN),
16576                    3 => Scalar::Bool(raw & 1 == 0),
16577                    4 => Scalar::Int64(raw % 211),
16578                    5 => Scalar::Float64(raw as f64 / 47.0),
16579                    6 => Scalar::Float64(0.0),
16580                    7 => Scalar::Float64(-0.0),
16581                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
16582                });
16583            }
16584            assert_args(
16585                case,
16586                "numeric",
16587                &numeric,
16588                expected_numeric(&numeric, false),
16589                expected_numeric(&numeric, true),
16590            );
16591
16592            let mut timedeltas = Vec::with_capacity(len);
16593            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16594            if len > 1 {
16595                timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16596            }
16597            for _ in timedeltas.len()..len {
16598                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16599                timedeltas.push(match next(&mut seed) % 7 {
16600                    0 => Scalar::Null(NullKind::Null),
16601                    1 => Scalar::Timedelta64(i64::MIN),
16602                    _ => Scalar::Timedelta64(raw),
16603                });
16604            }
16605            assert_args(
16606                case,
16607                "timedelta",
16608                &timedeltas,
16609                expected_timedelta(&timedeltas, false),
16610                expected_timedelta(&timedeltas, true),
16611            );
16612        }
16613    }
16614
16615    #[test]
16616    fn nansem_matches_std_over_sqrt_n() {
16617        let values = vec![
16618            Scalar::Float64(2.0),
16619            Scalar::Float64(4.0),
16620            Scalar::Float64(4.0),
16621            Scalar::Float64(4.0),
16622            Scalar::Float64(5.0),
16623            Scalar::Float64(5.0),
16624            Scalar::Float64(7.0),
16625            Scalar::Float64(9.0),
16626        ];
16627        // numpy/scipy: std(ddof=1) = 2.138089935299395; sem = std/sqrt(8) = 0.7559
16628        let sem = super::nansem(&values, 1);
16629        assert!(matches!(sem, Scalar::Float64(_)));
16630        let Scalar::Float64(v) = sem else {
16631            return;
16632        };
16633        assert!((v - 0.7559289460184544).abs() < 1e-9);
16634    }
16635
16636    #[test]
16637    fn nansem_grouped_is_sqrt_var_over_n_7hxqv() {
16638        // pandas 2.2.3: Series([1.0, 4.0]).groupby([0, 0]).sem() == 1.5 while
16639        // Series([1.0, 4.0]).sem() == 1.4999999999999998.
16640        let values = [
16641            Scalar::Float64(1.0),
16642            Scalar::Null(NullKind::NaN),
16643            Scalar::Float64(4.0),
16644        ];
16645        assert_eq!(super::nansem_grouped(&values, 1), Scalar::Float64(1.5));
16646        // NEGATIVE: Series.sem keeps std / sqrt(n).
16647        assert_eq!(
16648            super::nansem(&values, 1),
16649            Scalar::Float64(1.499_999_999_999_999_8)
16650        );
16651        assert!(super::nansem_grouped(&values[..1], 1).is_missing());
16652    }
16653
16654    #[test]
16655    fn grouped_reducers_add_as_pandas_group_kernels_xhogl() {
16656        // pandas 2.2.3 groupby of ten 0.1: sum 1.0, mean 0.1, var 0.0 - a
16657        // plain fold gives 0.9999999999999999, 0.09999999999999999 and
16658        // 2.1e-34 (br-frankenpandas-xhogl).
16659        let tenths: Vec<Scalar> = (0..10).map(|_| Scalar::Float64(0.1)).collect();
16660        assert_eq!(super::nansum_grouped(&tenths), Scalar::Float64(1.0));
16661        assert_eq!(super::nanmean_grouped(&tenths), Scalar::Float64(0.1));
16662        assert_eq!(super::nanvar_grouped(&tenths, 1), Scalar::Float64(0.0));
16663        assert_eq!(super::nanstd_grouped(&tenths, 1), Scalar::Float64(0.0));
16664        // NEGATIVE: the Series reductions keep their plain fold.
16665        assert_eq!(
16666            super::nansum(&tenths),
16667            Scalar::Float64(0.999_999_999_999_999_9)
16668        );
16669        // An inf keeps the sum inf (the compensation would go NaN).
16670        let mut sum = super::KahanSum::default();
16671        for value in [1.0, f64::INFINITY, 2.0] {
16672            sum.add(value);
16673        }
16674        assert_eq!(sum.sum(), f64::INFINITY);
16675        // Missing values are skipped; too few for ddof is missing.
16676        let gapped = [
16677            Scalar::Float64(1.0),
16678            Scalar::Null(NullKind::NaN),
16679            Scalar::Float64(4.0),
16680        ];
16681        assert_eq!(super::nanmean_grouped(&gapped), Scalar::Float64(2.5));
16682        assert_eq!(super::nanvar_grouped(&gapped, 1), Scalar::Float64(4.5));
16683        assert!(super::nanvar_grouped(&gapped[..1], 1).is_missing());
16684        // Timedelta input keeps the exact integer paths.
16685        let spans = [Scalar::Timedelta64(1), Scalar::Timedelta64(2)];
16686        assert_eq!(super::nansum_grouped(&spans), super::nansum(&spans));
16687    }
16688
16689    #[test]
16690    fn grouped_skew_is_pandas_online_group_skew_vjfq9() {
16691        // pandas 2.2.3 groupby skew of [1, 4, 8] is 0.42327316026800615 - a
16692        // two-pass form gives 0.4232731602680071 (br-frankenpandas-vjfq9).
16693        let group = [
16694            Scalar::Float64(1.0),
16695            Scalar::Null(NullKind::NaN),
16696            Scalar::Float64(4.0),
16697            Scalar::Float64(8.0),
16698        ];
16699        assert_eq!(
16700            super::nanskew_grouped(&group),
16701            Scalar::Float64(0.423_273_160_268_006_15)
16702        );
16703        // 2922 values: pandas raises (n - 1) ** 0.5 with libm pow, which is not
16704        // sqrt's answer for n - 1 = 2921 (sqrt gives -0.002284383734800802).
16705        let long: Vec<Scalar> = (0..2922_i32)
16706            .map(|i| Scalar::Float64(f64::from((i * 7919) % 1000) / 7.0))
16707            .collect();
16708        let glibc_pow = Scalar::Float64(-0.002_284_383_734_800_801_4);
16709        // That is pandas on glibc, the oracle's platform. pandas' Cython
16710        // `** 0.5` calls the platform's pow, as fp does, and Apple's libm
16711        // returns sqrt's answer for 2921 (CI 36847809394 macos-latest), so
16712        // another libm may give that one - never anything else
16713        // (br-frankenpandas-3bo1g).
16714        if cfg!(all(target_os = "linux", target_env = "gnu")) {
16715            assert_eq!(super::nanskew_grouped(&long), glibc_pow);
16716        } else {
16717            let sqrt = Scalar::Float64(-0.002_284_383_734_800_802);
16718            assert!([glibc_pow, sqrt].contains(&super::nanskew_grouped(&long)));
16719        }
16720        // A constant group is 0; below 3 values missing; an inf poisons its
16721        // group (pandas skips only NaN), where dropping it would leave [1, 2, 5].
16722        let constant = [7.0; 3].map(Scalar::Float64);
16723        assert_eq!(super::nanskew_grouped(&constant), Scalar::Float64(0.0));
16724        assert!(super::nanskew_grouped(&group[..2]).is_missing());
16725        let with_inf = [1.0, f64::INFINITY, 2.0, 5.0].map(Scalar::Float64);
16726        assert!(super::nanskew_grouped(&with_inf).is_missing());
16727    }
16728
16729    #[test]
16730    fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
16731        fn former(values: &[Scalar], ddof: usize) -> Scalar {
16732            let nums = super::collect_finite(values);
16733            if nums.len() <= ddof {
16734                return Scalar::Null(NullKind::NaN);
16735            }
16736            match super::nanstd(values, ddof) {
16737                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
16738                other => other,
16739            }
16740        }
16741
16742        fn assert_same_bits(values: &[Scalar], ddof: usize) {
16743            let expected = former(values, ddof);
16744            let actual = super::nansem(values, ddof);
16745            match (&expected, &actual) {
16746                (Scalar::Float64(expected), Scalar::Float64(actual)) => {
16747                    assert_eq!(
16748                        actual.to_bits(),
16749                        expected.to_bits(),
16750                        "values={values:?} ddof={ddof}"
16751                    );
16752                }
16753                _ => assert!(
16754                    actual.semantic_eq(&expected),
16755                    "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
16756                ),
16757            }
16758        }
16759
16760        let mut generated = Vec::with_capacity(4_096);
16761        for idx in 0..4_096_i64 {
16762            generated.push(match idx % 257 {
16763                0 => Scalar::Null(NullKind::NaN),
16764                1 => Scalar::Float64(-0.0),
16765                2 => Scalar::Float64(0.0),
16766                _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
16767                _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
16768            });
16769        }
16770
16771        let cases = [
16772            Vec::new(),
16773            vec![Scalar::Int64(1)],
16774            vec![
16775                Scalar::Null(NullKind::Null),
16776                Scalar::Float64(f64::NAN),
16777                Scalar::Int64(i64::MIN),
16778                Scalar::Int64(i64::MAX),
16779                Scalar::Float64(-0.0),
16780                Scalar::Float64(0.0),
16781            ],
16782            generated,
16783        ];
16784        for values in &cases {
16785            for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
16786                assert_same_bits(values, ddof);
16787            }
16788        }
16789    }
16790
16791    #[test]
16792    #[ignore = "foreground release A/B harness"]
16793    fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
16794        const ROWS: usize = 262_144;
16795        const BATCH: usize = 8;
16796        const BLOCKS: usize = 9;
16797        const PRECONDITION_CALLS: usize = 2;
16798
16799        fn former(values: &[Scalar], ddof: usize) -> Scalar {
16800            let nums = super::collect_finite(values);
16801            if nums.len() <= ddof {
16802                return Scalar::Null(NullKind::NaN);
16803            }
16804            match super::nanstd(values, ddof) {
16805                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
16806                other => other,
16807            }
16808        }
16809
16810        fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
16811            let values = std::hint::black_box(values);
16812            if candidate {
16813                super::nansem(values, 1)
16814            } else {
16815                former(values, 1)
16816            }
16817        }
16818
16819        fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
16820            for _ in 0..PRECONDITION_CALLS {
16821                std::hint::black_box(evaluate(values, candidate));
16822            }
16823            let started = std::time::Instant::now();
16824            for _ in 0..BATCH {
16825                std::hint::black_box(evaluate(values, candidate));
16826            }
16827            started.elapsed().as_nanos()
16828        }
16829
16830        fn median(mut samples: Vec<u128>) -> u128 {
16831            samples.sort_unstable();
16832            samples[samples.len() / 2]
16833        }
16834
16835        fn spread(a: u128, b: u128) -> f64 {
16836            a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
16837        }
16838
16839        let values = (0..ROWS)
16840            .map(|idx| {
16841                if idx % 257 == 0 {
16842                    Scalar::Null(NullKind::NaN)
16843                } else {
16844                    Scalar::Int64((idx % 8_191) as i64 - 4_095)
16845                }
16846            })
16847            .collect::<Vec<_>>();
16848
16849        let expected_bits = match former(&values, 1) {
16850            Scalar::Float64(value) => Some(value.to_bits()),
16851            _ => None,
16852        };
16853        let actual_bits = match super::nansem(&values, 1) {
16854            Scalar::Float64(value) => Some(value.to_bits()),
16855            _ => None,
16856        };
16857        assert!(
16858            expected_bits.is_some(),
16859            "numeric nansem must return Float64"
16860        );
16861        assert_eq!(actual_bits, expected_bits, "A/B output bits");
16862
16863        std::hint::black_box(evaluate(&values, false));
16864        std::hint::black_box(evaluate(&values, true));
16865
16866        let body_started = std::time::Instant::now();
16867        let mut former_a = Vec::with_capacity(BLOCKS);
16868        let mut former_b = Vec::with_capacity(BLOCKS);
16869        let mut candidate_a = Vec::with_capacity(BLOCKS);
16870        let mut candidate_b = Vec::with_capacity(BLOCKS);
16871        for block in 0..BLOCKS {
16872            let order = if block % 2 == 0 {
16873                [(false, 0), (true, 0), (true, 1), (false, 1)]
16874            } else {
16875                [(true, 1), (false, 1), (false, 0), (true, 0)]
16876            };
16877            for (candidate, duplicate) in order {
16878                let elapsed = elapsed_ns(&values, candidate);
16879                match (candidate, duplicate) {
16880                    (false, 0) => former_a.push(elapsed),
16881                    (false, _) => former_b.push(elapsed),
16882                    (true, 0) => candidate_a.push(elapsed),
16883                    (true, _) => candidate_b.push(elapsed),
16884                }
16885            }
16886        }
16887
16888        let former_a = median(former_a) / BATCH as u128;
16889        let former_b = median(former_b) / BATCH as u128;
16890        let candidate_a = median(candidate_a) / BATCH as u128;
16891        let candidate_b = median(candidate_b) / BATCH as u128;
16892        let former_mean = (former_a + former_b) as f64 / 2.0;
16893        let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
16894        println!(
16895            "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}",
16896            spread(former_a, former_b),
16897            spread(candidate_a, candidate_b),
16898            former_mean / candidate_mean,
16899            body_started.elapsed().as_secs_f64()
16900        );
16901    }
16902
16903    #[test]
16904    fn nansem_empty_returns_null() {
16905        assert!(super::nansem(&[], 1).is_missing());
16906        assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
16907    }
16908
16909    #[test]
16910    fn nanptp_returns_max_minus_min() {
16911        let values = vec![
16912            Scalar::Float64(3.0),
16913            Scalar::Null(NullKind::NaN),
16914            Scalar::Float64(7.0),
16915            Scalar::Float64(1.0),
16916        ];
16917        assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
16918    }
16919
16920    #[test]
16921    fn nanptp_empty_returns_null() {
16922        assert!(super::nanptp(&[]).is_missing());
16923        assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
16924    }
16925
16926    #[test]
16927    fn nanptp_timedelta64_preserves_dtype_u2g0r() {
16928        // Per br-frankenpandas-u2g0r: ptp on Timedelta64 returns Timedelta64.
16929        let one_hour: i64 = 3_600 * 1_000_000_000;
16930        let values = vec![
16931            Scalar::Timedelta64(one_hour),
16932            Scalar::Timedelta64(5 * one_hour),
16933            Scalar::Timedelta64(2 * one_hour),
16934        ];
16935        assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
16936    }
16937
16938    #[test]
16939    fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
16940        // Differential vs independent max-min oracles
16941        // (br-frankenpandas-affjt). Seeded LCG, no mocks.
16942        fn next(seed: &mut u64) -> u64 {
16943            *seed = seed
16944                .wrapping_mul(3202034522624059733)
16945                .wrapping_add(4354685564936845319);
16946            *seed
16947        }
16948
16949        fn expected_numeric(values: &[Scalar]) -> Scalar {
16950            let mut lo = f64::INFINITY;
16951            let mut hi = f64::NEG_INFINITY;
16952            let mut seen = false;
16953            for value in values {
16954                if value.is_missing() {
16955                    continue;
16956                }
16957                if let Ok(value) = value.to_f64() {
16958                    seen = true;
16959                    lo = lo.min(value);
16960                    hi = hi.max(value);
16961                }
16962            }
16963            if seen {
16964                Scalar::Float64(hi - lo)
16965            } else {
16966                Scalar::Null(NullKind::NaN)
16967            }
16968        }
16969
16970        fn expected_timedelta(values: &[Scalar]) -> Scalar {
16971            let mut lo = i64::MAX;
16972            let mut hi = i64::MIN;
16973            let mut seen = false;
16974            for value in values {
16975                if let Scalar::Timedelta64(ns) = value
16976                    && !value.is_missing()
16977                {
16978                    seen = true;
16979                    lo = lo.min(*ns);
16980                    hi = hi.max(*ns);
16981                }
16982            }
16983            if seen {
16984                Scalar::Timedelta64(hi - lo)
16985            } else {
16986                Scalar::Null(NullKind::NaN)
16987            }
16988        }
16989
16990        fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
16991            let actual = super::nanptp(values);
16992            assert!(
16993                actual.semantic_eq(&expected),
16994                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
16995            );
16996        }
16997
16998        assert_ptp(
16999            usize::MAX,
17000            "numeric_all_missing",
17001            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17002            Scalar::Null(NullKind::NaN),
17003        );
17004        assert_ptp(
17005            usize::MAX - 1,
17006            "timedelta_all_missing",
17007            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
17008            Scalar::Null(NullKind::NaN),
17009        );
17010        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
17011        assert_ptp(
17012            usize::MAX - 2,
17013            "timedelta_one_ns_range_beyond_f64_exactness",
17014            &[
17015                Scalar::Timedelta64(beyond_f64_exact_ns),
17016                Scalar::Timedelta64(beyond_f64_exact_ns - 1),
17017                Scalar::Timedelta64(Timedelta::NAT),
17018            ],
17019            Scalar::Timedelta64(1),
17020        );
17021
17022        let mut seed = 0xa22f_17ed_57a7_15e5_u64;
17023        for case in 0..260 {
17024            let len = (next(&mut seed) % 83 + 1) as usize;
17025
17026            let mut numeric = Vec::with_capacity(len);
17027            numeric.push(Scalar::Int64(case as i64 - 130));
17028            for _ in 1..len {
17029                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17030                numeric.push(match next(&mut seed) % 9 {
17031                    0 => Scalar::Null(NullKind::Null),
17032                    1 => Scalar::Null(NullKind::NaN),
17033                    2 => Scalar::Float64(f64::NAN),
17034                    3 => Scalar::Bool(raw & 1 == 0),
17035                    4 => Scalar::Int64(raw),
17036                    5 => Scalar::Float64(raw as f64 / 53.0),
17037                    6 => Scalar::Float64(0.0),
17038                    7 => Scalar::Float64(-0.0),
17039                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
17040                });
17041            }
17042            assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
17043
17044            let mut timedeltas = Vec::with_capacity(len);
17045            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17046            for _ in 1..len {
17047                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17048                timedeltas.push(match next(&mut seed) % 7 {
17049                    0 => Scalar::Null(NullKind::Null),
17050                    1 => Scalar::Timedelta64(i64::MIN),
17051                    _ => Scalar::Timedelta64(raw),
17052                });
17053            }
17054            assert_ptp(
17055                case,
17056                "timedelta",
17057                &timedeltas,
17058                expected_timedelta(&timedeltas),
17059            );
17060        }
17061    }
17062
17063    #[test]
17064    fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
17065        // Per br-frankenpandas-ql1t5: argmax/argmin on Timedelta64 compare
17066        // i64 ns directly instead of silently skipping via to_f64.
17067        let one_hour: i64 = 3_600 * 1_000_000_000;
17068        let values = vec![
17069            Scalar::Timedelta64(2 * one_hour),
17070            Scalar::Timedelta64(5 * one_hour),
17071            Scalar::Timedelta64(one_hour),
17072            Scalar::Timedelta64(3 * one_hour),
17073        ];
17074        assert_eq!(super::nanargmax(&values), Some(1));
17075        assert_eq!(super::nanargmin(&values), Some(2));
17076    }
17077
17078    #[test]
17079    fn nanprod_timedelta64_returns_null_szq6a() {
17080        // Per br-frankenpandas-szq6a: pandas raises on Timedelta prod
17081        // (dimensionally undefined). We surface Null instead of the
17082        // misleading Float64(1.0) the old empty-iterator default emitted.
17083        let one_hour: i64 = 3_600 * 1_000_000_000;
17084        let values = vec![
17085            Scalar::Timedelta64(2 * one_hour),
17086            Scalar::Timedelta64(3 * one_hour),
17087        ];
17088        assert!(super::nanprod(&values).is_missing());
17089    }
17090
17091    #[test]
17092    fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
17093        // Differential vs independent product oracles
17094        // (br-frankenpandas-9938h). Seeded LCG, no mocks.
17095        fn next(seed: &mut u64) -> u64 {
17096            *seed = seed
17097                .wrapping_mul(6364136223846793005)
17098                .wrapping_add(1442695040888963407);
17099            *seed
17100        }
17101
17102        fn expected_numeric(values: &[Scalar]) -> Scalar {
17103            let mut product = 1.0_f64;
17104            for value in values {
17105                if value.is_missing() {
17106                    continue;
17107                }
17108                if let Ok(value) = value.to_f64() {
17109                    product *= value;
17110                }
17111            }
17112            Scalar::Float64(product)
17113        }
17114
17115        fn expected_timedelta(values: &[Scalar]) -> Scalar {
17116            if values
17117                .iter()
17118                .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
17119            {
17120                Scalar::Null(NullKind::NaN)
17121            } else {
17122                Scalar::Float64(1.0)
17123            }
17124        }
17125
17126        fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
17127            let actual = super::nanprod(values);
17128            assert!(
17129                actual.semantic_eq(&expected),
17130                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
17131            );
17132        }
17133
17134        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17135        assert_prod(
17136            usize::MAX,
17137            "numeric_all_missing",
17138            &all_missing,
17139            Scalar::Float64(1.0),
17140        );
17141
17142        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17143        assert_prod(
17144            usize::MAX - 1,
17145            "timedelta_all_missing",
17146            &td_all_missing,
17147            expected_timedelta(&td_all_missing),
17148        );
17149
17150        let mut seed = 0x6e0d_9938_a11c_0de5_u64;
17151        for case in 0..280 {
17152            let len = (next(&mut seed) % 89 + 1) as usize;
17153
17154            let mut numeric = Vec::with_capacity(len);
17155            numeric.push(Scalar::Int64((case % 17) as i64 - 8));
17156            for _ in 1..len {
17157                let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
17158                numeric.push(match next(&mut seed) % 9 {
17159                    0 => Scalar::Null(NullKind::Null),
17160                    1 => Scalar::Null(NullKind::NaN),
17161                    2 => Scalar::Float64(f64::NAN),
17162                    3 => Scalar::Bool(raw & 1 == 0),
17163                    4 => Scalar::Int64(raw % 19),
17164                    5 => Scalar::Float64(raw as f64 / 97.0),
17165                    6 => Scalar::Float64(0.0),
17166                    7 => Scalar::Float64(-0.0),
17167                    _ => Scalar::Float64(1.0),
17168                });
17169            }
17170            assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
17171
17172            let mut timedeltas = Vec::with_capacity(len);
17173            timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
17174            for _ in 1..len {
17175                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17176                timedeltas.push(match next(&mut seed) % 7 {
17177                    0 => Scalar::Null(NullKind::Null),
17178                    1 => Scalar::Timedelta64(i64::MIN),
17179                    _ => Scalar::Timedelta64(raw),
17180                });
17181            }
17182            assert_prod(
17183                case,
17184                "timedelta",
17185                &timedeltas,
17186                expected_timedelta(&timedeltas),
17187            );
17188        }
17189    }
17190
17191    #[test]
17192    fn nanskew_symmetric_distribution_near_zero() {
17193        let values = vec![
17194            Scalar::Float64(1.0),
17195            Scalar::Float64(2.0),
17196            Scalar::Float64(3.0),
17197            Scalar::Float64(4.0),
17198            Scalar::Float64(5.0),
17199        ];
17200        // Perfectly symmetric -> skew = 0
17201        let skew = super::nanskew(&values);
17202        assert!(matches!(skew, Scalar::Float64(_)));
17203        let Scalar::Float64(v) = skew else {
17204            return;
17205        };
17206        assert!(v.abs() < 1e-9);
17207    }
17208
17209    #[test]
17210    fn nanskew_too_few_values_returns_null() {
17211        assert!(super::nanskew(&[]).is_missing());
17212        assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
17213    }
17214
17215    #[test]
17216    fn nankurt_symmetric_uniform_distribution() {
17217        let values = vec![
17218            Scalar::Float64(1.0),
17219            Scalar::Float64(2.0),
17220            Scalar::Float64(3.0),
17221            Scalar::Float64(4.0),
17222            Scalar::Float64(5.0),
17223        ];
17224        // pandas kurt([1,2,3,4,5]) = -1.2
17225        let kurt = super::nankurt(&values);
17226        assert!(matches!(kurt, Scalar::Float64(_)));
17227        let Scalar::Float64(v) = kurt else {
17228            return;
17229        };
17230        assert!((v + 1.2).abs() < 1e-9);
17231    }
17232
17233    #[test]
17234    fn nankurt_too_few_values_returns_null() {
17235        let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
17236        assert!(super::nankurt(&vals).is_missing());
17237    }
17238
17239    #[test]
17240    fn nanskew_constant_series_returns_zero() {
17241        let values = vec![
17242            Scalar::Float64(5.0),
17243            Scalar::Float64(5.0),
17244            Scalar::Float64(5.0),
17245        ];
17246        assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
17247        assert_eq!(
17248            super::nankurt(&[
17249                Scalar::Float64(5.0),
17250                Scalar::Float64(5.0),
17251                Scalar::Float64(5.0),
17252                Scalar::Float64(5.0),
17253            ]),
17254            Scalar::Float64(0.0)
17255        );
17256    }
17257
17258    #[test]
17259    fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
17260        // Differential vs independent bias-corrected moment oracles
17261        // (br-frankenpandas-jr7zk). Seeded LCG, no mocks.
17262        fn next(seed: &mut u64) -> u64 {
17263            *seed = seed
17264                .wrapping_mul(2862933555777941757)
17265                .wrapping_add(3037000493);
17266            *seed
17267        }
17268
17269        fn samples(values: &[Scalar]) -> Vec<f64> {
17270            values
17271                .iter()
17272                .filter(|value| !value.is_missing())
17273                .filter_map(|value| value.to_f64().ok())
17274                .collect()
17275        }
17276
17277        fn expected_skew(values: &[Scalar]) -> Scalar {
17278            let samples = samples(values);
17279            let n = samples.len() as f64;
17280            if n < 3.0 {
17281                return Scalar::Null(NullKind::NaN);
17282            }
17283            let mean = samples.iter().sum::<f64>() / n;
17284            let m2 = samples
17285                .iter()
17286                .map(|value| (value - mean).powi(2))
17287                .sum::<f64>();
17288            let m3 = samples
17289                .iter()
17290                .map(|value| (value - mean).powi(3))
17291                .sum::<f64>();
17292            let s2 = m2 / (n - 1.0);
17293            if s2 == 0.0 {
17294                return Scalar::Float64(0.0);
17295            }
17296            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
17297        }
17298
17299        fn expected_kurt(values: &[Scalar]) -> Scalar {
17300            let samples = samples(values);
17301            let n = samples.len() as f64;
17302            if n < 4.0 {
17303                return Scalar::Null(NullKind::NaN);
17304            }
17305            let mean = samples.iter().sum::<f64>() / n;
17306            let m2 = samples
17307                .iter()
17308                .map(|value| (value - mean).powi(2))
17309                .sum::<f64>();
17310            let m4 = samples
17311                .iter()
17312                .map(|value| (value - mean).powi(4))
17313                .sum::<f64>();
17314            let s2 = m2 / (n - 1.0);
17315            if s2 == 0.0 {
17316                return Scalar::Float64(0.0);
17317            }
17318            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
17319            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
17320            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
17321        }
17322
17323        fn assert_moments(case: usize, values: &[Scalar]) {
17324            let expected_skew = expected_skew(values);
17325            let expected_kurt = expected_kurt(values);
17326            let actual_skew = super::nanskew(values);
17327            let actual_kurt = super::nankurt(values);
17328            assert!(
17329                actual_skew.semantic_eq(&expected_skew),
17330                "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
17331            );
17332            assert!(
17333                actual_kurt.semantic_eq(&expected_kurt),
17334                "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
17335            );
17336        }
17337
17338        assert_moments(
17339            usize::MAX,
17340            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17341        );
17342        assert_moments(
17343            usize::MAX - 1,
17344            &[
17345                Scalar::Float64(7.0),
17346                Scalar::Float64(7.0),
17347                Scalar::Float64(7.0),
17348                Scalar::Float64(7.0),
17349            ],
17350        );
17351
17352        let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
17353        for case in 0..260 {
17354            let len = (next(&mut seed) % 89 + 1) as usize;
17355            let mut values = Vec::with_capacity(len);
17356            if case % 11 == 0 {
17357                values.extend((0..len).map(|_| Scalar::Float64(3.0)));
17358            } else {
17359                values.push(Scalar::Float64(case as f64 / 19.0));
17360                for _ in 1..len {
17361                    let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17362                    values.push(match next(&mut seed) % 8 {
17363                        0 => Scalar::Null(NullKind::Null),
17364                        1 => Scalar::Null(NullKind::NaN),
17365                        2 => Scalar::Float64(f64::NAN),
17366                        3 => Scalar::Bool(raw & 1 == 0),
17367                        4 => Scalar::Int64(raw % 251),
17368                        5 => Scalar::Float64(raw as f64 / 83.0),
17369                        6 => Scalar::Float64(0.0),
17370                        _ => Scalar::Float64(-0.0),
17371                    });
17372                }
17373            }
17374            assert_moments(case, &values);
17375        }
17376    }
17377
17378    // ── Interval tests (br-frankenpandas-j8k4) ──────────────────────────
17379
17380    #[test]
17381    fn interval_default_closed_is_right() {
17382        assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
17383    }
17384
17385    #[test]
17386    fn interval_left_and_right_closed_helpers() {
17387        assert!(IntervalClosed::Left.left_closed());
17388        assert!(!IntervalClosed::Left.right_closed());
17389        assert!(!IntervalClosed::Right.left_closed());
17390        assert!(IntervalClosed::Right.right_closed());
17391        assert!(IntervalClosed::Both.left_closed());
17392        assert!(IntervalClosed::Both.right_closed());
17393        assert!(!IntervalClosed::Neither.left_closed());
17394        assert!(!IntervalClosed::Neither.right_closed());
17395    }
17396
17397    #[test]
17398    fn interval_display_matches_pandas_notation() {
17399        assert_eq!(
17400            Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
17401            "(0.0, 5.0]"
17402        );
17403        assert_eq!(
17404            Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
17405            "[0.0, 5.0)"
17406        );
17407        assert_eq!(
17408            Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
17409            "[0.0, 5.0]"
17410        );
17411        assert_eq!(
17412            Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
17413            "(0.0, 5.0)"
17414        );
17415        assert_eq!(
17416            Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
17417            "(2.5, 3.5]"
17418        );
17419        assert_eq!(
17420            Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
17421            "(-1.0, 0.0]"
17422        );
17423        assert_eq!(
17424            Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
17425            "(1e+20, 2e+20]"
17426        );
17427    }
17428
17429    #[test]
17430    fn interval_length_and_mid() {
17431        let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
17432        assert_eq!(i.length(), 8.0);
17433        assert_eq!(i.mid(), 6.0);
17434    }
17435
17436    #[test]
17437    fn interval_contains_matches_closed_policy() {
17438        let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
17439        assert!(!right.contains(0.0));
17440        assert!(right.contains(2.5));
17441        assert!(right.contains(5.0));
17442
17443        let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
17444        assert!(left.contains(0.0));
17445        assert!(left.contains(2.5));
17446        assert!(!left.contains(5.0));
17447
17448        let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
17449        assert!(both.contains(0.0));
17450        assert!(both.contains(5.0));
17451
17452        let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
17453        assert!(!neither.contains(0.0));
17454        assert!(!neither.contains(5.0));
17455        assert!(neither.contains(2.5));
17456    }
17457
17458    #[test]
17459    fn interval_contains_nan_returns_false() {
17460        let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
17461        assert!(!i.contains(f64::NAN));
17462    }
17463
17464    #[test]
17465    fn interval_is_empty_matches_pandas() {
17466        // pd.Interval(3, 3, 'right').is_empty → True
17467        assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
17468        assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
17469        assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
17470        // pd.Interval(3, 3, 'both').is_empty → False (single point)
17471        assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
17472        // Non-degenerate intervals are never empty.
17473        assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
17474    }
17475
17476    #[test]
17477    fn interval_overlaps_disjoint_returns_false() {
17478        let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
17479        let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
17480        assert!(!a.overlaps(&b));
17481        assert!(!b.overlaps(&a));
17482    }
17483
17484    #[test]
17485    fn interval_overlaps_nested_returns_true() {
17486        let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
17487        let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
17488        assert!(outer.overlaps(&inner));
17489        assert!(inner.overlaps(&outer));
17490    }
17491
17492    #[test]
17493    fn interval_overlaps_touching_respects_closed_policy() {
17494        // (0, 1] touching (1, 2] at point 1.
17495        let right_right = (
17496            Interval::new(0.0, 1.0, IntervalClosed::Right),
17497            Interval::new(1.0, 2.0, IntervalClosed::Right),
17498        );
17499        // right_right.0 is closed at 1; right_right.1 is open at 1 → no overlap.
17500        assert!(!right_right.0.overlaps(&right_right.1));
17501
17502        // [0, 1] touching [1, 2] — both closed at 1 → overlap.
17503        let both_both = (
17504            Interval::new(0.0, 1.0, IntervalClosed::Both),
17505            Interval::new(1.0, 2.0, IntervalClosed::Both),
17506        );
17507        assert!(both_both.0.overlaps(&both_both.1));
17508    }
17509
17510    #[test]
17511    fn interval_roundtrips_through_serde_json() {
17512        let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
17513        let json = serde_json::to_string(&i).expect("serialize");
17514        let back: Interval = serde_json::from_str(&json).expect("deserialize");
17515        assert_eq!(i, back);
17516    }
17517
17518    #[test]
17519    fn interval_serde_default_closed_is_right_when_missing() {
17520        // JSON payloads that omit `closed` deserialize with the pandas default.
17521        let back: Interval =
17522            serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
17523        assert_eq!(back.closed, IntervalClosed::Right);
17524    }
17525
17526    // ── Period tests (br-frankenpandas-epoj) ────────────────────────────
17527
17528    #[test]
17529    fn period_freq_parses_canonical_aliases() {
17530        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::Annual));
17531        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::Annual));
17532        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::Quarterly));
17533        assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
17534        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::Weekly));
17535        assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
17536        assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
17537        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
17538        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
17539        assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
17540        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
17541    }
17542
17543    #[test]
17544    fn period_freq_parse_is_case_insensitive() {
17545        assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::Quarterly));
17546        assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
17547    }
17548
17549    #[test]
17550    fn period_freq_rejects_unknown_aliases() {
17551        assert_eq!(PeriodFreq::parse("nanosec"), None);
17552        assert_eq!(PeriodFreq::parse(""), None);
17553        assert_eq!(PeriodFreq::parse("xyz"), None);
17554    }
17555
17556    #[test]
17557    fn period_freq_alias_roundtrip() {
17558        for freq in [
17559            PeriodFreq::Annual,
17560            PeriodFreq::Quarterly,
17561            PeriodFreq::Monthly,
17562            PeriodFreq::Weekly,
17563            PeriodFreq::Daily,
17564            PeriodFreq::Business,
17565            PeriodFreq::Hourly,
17566            PeriodFreq::Minutely,
17567            PeriodFreq::Secondly,
17568            PeriodFreq::Milliseconds,
17569            PeriodFreq::Microseconds,
17570            PeriodFreq::Nanoseconds,
17571        ] {
17572            assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
17573        }
17574    }
17575
17576    /// The three sub-second frequencies pandas' `to_period` accepts and this
17577    /// crate used to reject. Transcribed from live pandas 2.2.3 on
17578    /// `Timestamp('2024-03-15 10:30:45.123456789')`.
17579    #[test]
17580    fn period_freq_subsecond_units_match_pandas() {
17581        // Aliases and resolution words.
17582        assert_eq!(PeriodFreq::Milliseconds.alias(), "ms");
17583        assert_eq!(PeriodFreq::Microseconds.alias(), "us");
17584        assert_eq!(PeriodFreq::Nanoseconds.alias(), "ns");
17585        assert_eq!(PeriodFreq::Milliseconds.resolution(), Some("millisecond"));
17586        assert_eq!(PeriodFreq::Microseconds.resolution(), Some("microsecond"));
17587        assert_eq!(PeriodFreq::Nanoseconds.resolution(), Some("nanosecond"));
17588
17589        // ⚠️ THE ONE CASE-SENSITIVE ALIAS. pandas reads bare "MS" as month start
17590        // and refuses it here, while every other casing of "ms" is milliseconds.
17591        assert_eq!(PeriodFreq::parse("ms"), Some(PeriodFreq::Milliseconds));
17592        assert_eq!(PeriodFreq::parse("Ms"), Some(PeriodFreq::Milliseconds));
17593        assert_eq!(PeriodFreq::parse("mS"), Some(PeriodFreq::Milliseconds));
17594        assert_eq!(PeriodFreq::parse("MS"), None);
17595        // us/ns are case-insensitive in pandas, so both casings resolve.
17596        assert_eq!(PeriodFreq::parse("us"), Some(PeriodFreq::Microseconds));
17597        assert_eq!(PeriodFreq::parse("US"), Some(PeriodFreq::Microseconds));
17598        assert_eq!(PeriodFreq::parse("ns"), Some(PeriodFreq::Nanoseconds));
17599        assert_eq!(PeriodFreq::parse("NS"), Some(PeriodFreq::Nanoseconds));
17600
17601        // Ordinals are unit counts since the epoch; labels pad the fraction to
17602        // the full width of the frequency and never trim trailing zeros.
17603        assert_eq!(
17604            Period::new(1_710_498_645_123, PeriodFreq::Milliseconds).calendar_string(),
17605            "2024-03-15 10:30:45.123"
17606        );
17607        assert_eq!(
17608            Period::new(1_710_498_645_123_456, PeriodFreq::Microseconds).calendar_string(),
17609            "2024-03-15 10:30:45.123456"
17610        );
17611        assert_eq!(
17612            Period::new(1_710_498_645_123_456_789, PeriodFreq::Nanoseconds).calendar_string(),
17613            "2024-03-15 10:30:45.123456789"
17614        );
17615
17616        // A whole-second instant still shows its zero fraction, and the
17617        // pre-epoch ordinals are the FLOOR, not a truncation toward zero:
17618        // Timestamp('1969-12-31 23:59:59.999') at 'ms' has ordinal -1.
17619        assert_eq!(
17620            Period::new(0, PeriodFreq::Milliseconds).calendar_string(),
17621            "1970-01-01 00:00:00.000"
17622        );
17623        assert_eq!(
17624            Period::new(-1, PeriodFreq::Milliseconds).calendar_string(),
17625            "1969-12-31 23:59:59.999"
17626        );
17627        assert_eq!(
17628            Period::new(-1_000, PeriodFreq::Microseconds).calendar_string(),
17629            "1969-12-31 23:59:59.999000"
17630        );
17631        assert_eq!(
17632            Period::new(-999_999, PeriodFreq::Nanoseconds).calendar_string(),
17633            "1969-12-31 23:59:59.999000001"
17634        );
17635    }
17636
17637    #[test]
17638    fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
17639        assert_eq!(PeriodFreq::Annual.alias(), "Y-DEC");
17640        assert_eq!(PeriodFreq::Quarterly.alias(), "Q-DEC");
17641        assert_eq!(PeriodFreq::Weekly.alias(), "W-SUN");
17642
17643        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::Annual));
17644        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::Annual));
17645        assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::Annual));
17646        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::Quarterly));
17647        assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::Quarterly));
17648        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::Weekly));
17649        assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::Weekly));
17650    }
17651
17652    #[test]
17653    fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
17654        assert_eq!(PeriodFreq::Hourly.alias(), "h");
17655        assert_eq!(PeriodFreq::Minutely.alias(), "min");
17656        assert_eq!(PeriodFreq::Secondly.alias(), "s");
17657
17658        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
17659        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
17660        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
17661    }
17662
17663    /// The resolution table is the COMPONENT WORD, never the frequency alias.
17664    /// Transcribed from live pandas 2.2.3: `pd.PeriodIndex([ts], freq=f).resolution`
17665    /// for each f, with W and B raising AttributeError.
17666    #[test]
17667    fn period_freq_resolution_is_the_component_word_not_the_alias() {
17668        assert_eq!(PeriodFreq::Annual.resolution(), Some("year"));
17669        assert_eq!(PeriodFreq::Quarterly.resolution(), Some("quarter"));
17670        assert_eq!(PeriodFreq::Monthly.resolution(), Some("month"));
17671        assert_eq!(PeriodFreq::Daily.resolution(), Some("day"));
17672        assert_eq!(PeriodFreq::Hourly.resolution(), Some("hour"));
17673        assert_eq!(PeriodFreq::Minutely.resolution(), Some("minute"));
17674        assert_eq!(PeriodFreq::Secondly.resolution(), Some("second"));
17675
17676        // pandas raises AttributeError for these two rather than answering.
17677        assert_eq!(PeriodFreq::Weekly.resolution(), None);
17678        assert_eq!(PeriodFreq::Business.resolution(), None);
17679
17680        // The bug this replaces was the alias table copied into the resolution
17681        // slot, so pin the two apart: no frequency may report the same string
17682        // for both. (Every pandas alias is short and lowercase-ish; every
17683        // resolution word is a full English noun -- they never coincide.)
17684        for freq in [
17685            PeriodFreq::Annual,
17686            PeriodFreq::Quarterly,
17687            PeriodFreq::Monthly,
17688            PeriodFreq::Weekly,
17689            PeriodFreq::Daily,
17690            PeriodFreq::Business,
17691            PeriodFreq::Hourly,
17692            PeriodFreq::Minutely,
17693            PeriodFreq::Secondly,
17694        ] {
17695            assert_ne!(
17696                Some(freq.alias()),
17697                freq.resolution(),
17698                "{freq:?} reports its alias as its resolution again"
17699            );
17700        }
17701    }
17702
17703    #[test]
17704    fn period_scalar_accessors_match_pandas_star8() {
17705        let period = Period::new(600, PeriodFreq::Monthly);
17706
17707        assert_eq!(period.ordinal(), 600);
17708        assert_eq!(period.freq(), PeriodFreq::Monthly);
17709        assert_eq!(period.freqstr(), "M");
17710    }
17711
17712    #[test]
17713    fn period_parse_common_pandas_ordinals_avm08() {
17714        assert_eq!(
17715            Period::parse("2024").unwrap(),
17716            Period::new(54, PeriodFreq::Annual)
17717        );
17718        assert_eq!(
17719            Period::parse("2024Q1").unwrap(),
17720            Period::new(216, PeriodFreq::Quarterly)
17721        );
17722        assert_eq!(
17723            Period::parse("2024-01").unwrap(),
17724            Period::new(648, PeriodFreq::Monthly)
17725        );
17726        assert_eq!(
17727            Period::parse("2024-01-15").unwrap(),
17728            Period::new(19_737, PeriodFreq::Daily)
17729        );
17730        assert!(Period::parse("216").is_err());
17731    }
17732
17733    #[test]
17734    fn period_shift_advances_ordinal() {
17735        let q1 = Period::new(216, PeriodFreq::Quarterly);
17736        let q2 = q1.shift(1);
17737        assert_eq!(q2.ordinal, 217);
17738        assert_eq!(q2.freq, PeriodFreq::Quarterly);
17739        let q0 = q1.shift(-1);
17740        assert_eq!(q0.ordinal, 215);
17741    }
17742
17743    #[test]
17744    fn period_shift_saturates_on_overflow() {
17745        let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
17746        assert_eq!(p.shift(100).ordinal, i64::MAX);
17747        let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
17748        assert_eq!(p.shift(-100).ordinal, i64::MIN);
17749    }
17750
17751    #[test]
17752    fn period_diff_returns_period_count() {
17753        let a = Period::new(216, PeriodFreq::Quarterly);
17754        let b = Period::new(220, PeriodFreq::Quarterly);
17755        assert_eq!(b.diff(&a), Some(4));
17756        assert_eq!(a.diff(&b), Some(-4));
17757    }
17758
17759    #[test]
17760    fn period_diff_rejects_mismatched_freq() {
17761        let monthly = Period::new(100, PeriodFreq::Monthly);
17762        let quarterly = Period::new(100, PeriodFreq::Quarterly);
17763        assert_eq!(monthly.diff(&quarterly), None);
17764        assert_eq!(quarterly.diff(&monthly), None);
17765    }
17766
17767    #[test]
17768    fn period_cmp_same_freq_respects_ordinal_order() {
17769        use std::cmp::Ordering;
17770        let a = Period::new(10, PeriodFreq::Monthly);
17771        let b = Period::new(20, PeriodFreq::Monthly);
17772        assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
17773        assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
17774        assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
17775    }
17776
17777    #[test]
17778    fn period_cmp_cross_freq_returns_none() {
17779        let m = Period::new(1, PeriodFreq::Monthly);
17780        let q = Period::new(1, PeriodFreq::Quarterly);
17781        assert_eq!(m.cmp_same_freq(&q), None);
17782    }
17783
17784    #[test]
17785    fn period_arithmetic_matches_seeded_oracles_bac28() {
17786        use std::cmp::Ordering;
17787
17788        fn next(seed: &mut u64) -> u64 {
17789            *seed = seed
17790                .wrapping_mul(2862933555777941757)
17791                .wrapping_add(3037000493);
17792            *seed
17793        }
17794
17795        fn freq_for(raw: u64) -> PeriodFreq {
17796            // All TWELVE frequencies. This stopped at nine, so no property
17797            // test here ever generated a sub-second period.
17798            match raw % 12 {
17799                0 => PeriodFreq::Annual,
17800                1 => PeriodFreq::Quarterly,
17801                2 => PeriodFreq::Monthly,
17802                3 => PeriodFreq::Weekly,
17803                4 => PeriodFreq::Daily,
17804                5 => PeriodFreq::Business,
17805                6 => PeriodFreq::Hourly,
17806                7 => PeriodFreq::Minutely,
17807                8 => PeriodFreq::Secondly,
17808                9 => PeriodFreq::Milliseconds,
17809                10 => PeriodFreq::Microseconds,
17810                _ => PeriodFreq::Nanoseconds,
17811            }
17812        }
17813
17814        fn different_freq(freq: PeriodFreq) -> PeriodFreq {
17815            match freq {
17816                PeriodFreq::Annual => PeriodFreq::Quarterly,
17817                PeriodFreq::Quarterly => PeriodFreq::Monthly,
17818                PeriodFreq::Monthly => PeriodFreq::Weekly,
17819                PeriodFreq::Weekly => PeriodFreq::Daily,
17820                PeriodFreq::Daily => PeriodFreq::Business,
17821                PeriodFreq::Business => PeriodFreq::Hourly,
17822                PeriodFreq::Hourly => PeriodFreq::Minutely,
17823                PeriodFreq::Minutely => PeriodFreq::Secondly,
17824                // The cycle closes through the sub-second units, so every
17825                // frequency still maps to a DIFFERENT one — the only property
17826                // this helper owes its callers.
17827                PeriodFreq::Secondly => PeriodFreq::Milliseconds,
17828                PeriodFreq::Milliseconds => PeriodFreq::Microseconds,
17829                PeriodFreq::Microseconds => PeriodFreq::Nanoseconds,
17830                PeriodFreq::Nanoseconds => PeriodFreq::Annual,
17831            }
17832        }
17833
17834        fn assert_period_case(
17835            case: usize,
17836            freq: PeriodFreq,
17837            ordinal: i64,
17838            shift_by: i64,
17839            other_ordinal: i64,
17840        ) {
17841            let period = Period::new(ordinal, freq);
17842            let shifted = period.shift(shift_by);
17843            assert_eq!(
17844                shifted.ordinal,
17845                ordinal.saturating_add(shift_by),
17846                "case {case}: shift ordinal"
17847            );
17848            assert_eq!(shifted.freq, freq, "case {case}: shift freq");
17849
17850            let same_freq_other = Period::new(other_ordinal, freq);
17851            assert_eq!(
17852                period.diff(&same_freq_other),
17853                Some(ordinal.saturating_sub(other_ordinal)),
17854                "case {case}: same-freq diff"
17855            );
17856            assert_eq!(
17857                period.cmp_same_freq(&same_freq_other),
17858                Some(ordinal.cmp(&other_ordinal)),
17859                "case {case}: same-freq cmp"
17860            );
17861
17862            let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
17863            assert_eq!(
17864                period.diff(&cross_freq_other),
17865                None,
17866                "case {case}: cross-freq diff"
17867            );
17868            assert_eq!(
17869                period.cmp_same_freq(&cross_freq_other),
17870                None,
17871                "case {case}: cross-freq cmp"
17872            );
17873        }
17874
17875        assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
17876        assert_period_case(
17877            usize::MAX - 1,
17878            PeriodFreq::Daily,
17879            i64::MIN + 2,
17880            -10,
17881            i64::MAX,
17882        );
17883        assert_eq!(
17884            Period::new(10, PeriodFreq::Monthly)
17885                .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
17886            Some(Ordering::Equal)
17887        );
17888
17889        let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
17890        for case in 0..260 {
17891            let freq = freq_for(next(&mut seed));
17892            let ordinal = match case % 53 {
17893                0 => i64::MAX - (next(&mut seed) % 8) as i64,
17894                1 => i64::MIN + (next(&mut seed) % 8) as i64,
17895                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
17896            };
17897            let shift_by = match case % 47 {
17898                0 => 512,
17899                1 => -512,
17900                _ => (next(&mut seed) % 4097) as i64 - 2048,
17901            };
17902            let other_ordinal = match case % 41 {
17903                0 => i64::MAX,
17904                1 => i64::MIN,
17905                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
17906            };
17907            assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
17908        }
17909    }
17910
17911    #[test]
17912    fn period_display_is_pandas_calendar_string() {
17913        // Ordinal 216 on the quarterly axis (1970Q1 == 0) is 1970 + 54y = 2024Q1.
17914        assert_eq!(
17915            Period::new(216, PeriodFreq::Quarterly).to_string(),
17916            "2024Q1"
17917        );
17918        // 1970 + 54 == 2024 on the annual axis.
17919        assert_eq!(Period::new(54, PeriodFreq::Annual).to_string(), "2024");
17920        // 1970-01 == 0 -> 2024-03 is 54*12 + 2 == 650 months.
17921        assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
17922        // Day 0 == 1970-01-01; 2024-01-15.
17923        assert_eq!(
17924            Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
17925            "2024-01-15"
17926        );
17927        assert_eq!(
17928            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
17929            "NaT"
17930        );
17931    }
17932
17933    /// The two frequencies whose ordinal is NOT a day count. Both rendered
17934    /// through `civil_from_days` and came out decades wrong; the test above
17935    /// covered Y/Q/M/D and never touched either, which is how it survived.
17936    ///
17937    /// Every string is `str(pd.Period(ordinal=..., freq=...))` on live pandas
17938    /// 2.2.3, and FrankenPandas' own ordinals were confirmed to agree with
17939    /// pandas' at each sampled date before these were taken.
17940    #[test]
17941    fn weekly_and_business_periods_do_not_index_days() {
17942        // ⚠️ WEEKLY IS A RANGE, not a date: the ordinal counts WEEKS from the
17943        // Monday 1969-12-22, and pandas prints the seven days it spans.
17944        // Ordinal 2829 is the week of 2024-03-15 and used to render
17945        // "1977-09-30" — the result of reading a week count as a day count.
17946        for (ordinal, want) in [
17947            (0_i64, "1969-12-22/1969-12-28"),
17948            (1, "1969-12-29/1970-01-04"),
17949            (2829, "2024-03-11/2024-03-17"),
17950            (1540, "1999-06-28/1999-07-04"),
17951            (15237, "2261-12-30/2262-01-05"),
17952            // Pre-epoch, where Euclidean division matters.
17953            (-1, "1969-12-15/1969-12-21"),
17954            (-2829, "1915-10-04/1915-10-10"),
17955        ] {
17956            assert_eq!(
17957                Period::new(ordinal, PeriodFreq::Weekly).to_string(),
17958                want,
17959                "weekly ordinal {ordinal}"
17960            );
17961        }
17962
17963        // ⚠️ BUSINESS COUNTS BUSINESS DAYS — five per week — so consecutive
17964        // ordinals skip the weekend. Ordinal 14141 is 2024-03-15 and used to
17965        // render "2008-09-19".
17966        for (ordinal, want) in [
17967            (0_i64, "1970-01-01"), // a Thursday: the epoch anchors the cycle
17968            (1, "1970-01-02"),     // Friday
17969            (2, "1970-01-05"),     // Monday — the weekend is SKIPPED
17970            (3, "1970-01-06"),
17971            (4, "1970-01-07"),
17972            (5, "1970-01-08"),
17973            (14141, "2024-03-15"),
17974            (76179, "2262-01-01"),
17975            // A Sunday input rolls FORWARD when the ordinal is taken, so 7697
17976            // is the Monday 1999-07-05 rather than 1999-07-04.
17977            (7697, "1999-07-05"),
17978            (-1, "1969-12-31"),
17979            (-5, "1969-12-25"),
17980            (-6, "1969-12-24"),
17981        ] {
17982            assert_eq!(
17983                Period::new(ordinal, PeriodFreq::Business).to_string(),
17984                want,
17985                "business ordinal {ordinal}"
17986            );
17987        }
17988
17989        // Five business ordinals per seven calendar days, checked as a property
17990        // rather than as a table: the same arithmetic the forward map in
17991        // fp-index uses, read backwards.
17992        for ordinal in -400_i64..400 {
17993            let rendered = Period::new(ordinal, PeriodFreq::Business).to_string();
17994            let later = Period::new(ordinal + 5, PeriodFreq::Business).to_string();
17995            assert_ne!(rendered, later, "business ordinals must not repeat");
17996        }
17997
17998        assert_eq!(Period::new(i64::MIN, PeriodFreq::Weekly).to_string(), "NaT");
17999        assert_eq!(
18000            Period::new(i64::MIN, PeriodFreq::Business).to_string(),
18001            "NaT"
18002        );
18003    }
18004
18005    fn period_display_former_profile(period: &Period) -> String {
18006        let calendar = period.calendar_string();
18007        let mut rendered = String::new();
18008        rendered.push_str(&calendar);
18009        rendered
18010    }
18011
18012    fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
18013        use std::{hint::black_box, time::Instant};
18014
18015        let started = Instant::now();
18016        let mut checksum = 0usize;
18017        for period in periods {
18018            let rendered = render(black_box(period));
18019            checksum = checksum.wrapping_add(rendered.len());
18020            drop(black_box(rendered));
18021        }
18022        black_box(checksum);
18023        started.elapsed().as_nanos()
18024    }
18025
18026    #[test]
18027    #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
18028    fn profile_period_display_direct_sink_ab_6pqra() {
18029        const FREQUENCIES: [PeriodFreq; 9] = [
18030            PeriodFreq::Annual,
18031            PeriodFreq::Quarterly,
18032            PeriodFreq::Monthly,
18033            PeriodFreq::Weekly,
18034            PeriodFreq::Daily,
18035            PeriodFreq::Business,
18036            PeriodFreq::Hourly,
18037            PeriodFreq::Minutely,
18038            PeriodFreq::Secondly,
18039        ];
18040        const SAMPLES: usize = 10;
18041
18042        let periods = (0..65_536)
18043            .map(|index| {
18044                let ordinal = if index % 4093 == 0 {
18045                    i64::MIN
18046                } else {
18047                    ((index as i64 * 7_919) % 4_000_001) - 2_000_000
18048                };
18049                Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
18050            })
18051            .collect::<Vec<_>>();
18052
18053        for period in &periods {
18054            assert_eq!(period_display_former_profile(period), period.to_string());
18055        }
18056
18057        for _ in 0..2 {
18058            measure_period_renderer(&periods, period_display_former_profile);
18059            measure_period_renderer(&periods, Period::to_string);
18060        }
18061
18062        let mut former_ns = Vec::with_capacity(SAMPLES);
18063        let mut public_ns = Vec::with_capacity(SAMPLES);
18064        for sample in 0..SAMPLES {
18065            if sample % 2 == 0 {
18066                former_ns.push(measure_period_renderer(
18067                    &periods,
18068                    period_display_former_profile,
18069                ));
18070                public_ns.push(measure_period_renderer(&periods, Period::to_string));
18071            } else {
18072                public_ns.push(measure_period_renderer(&periods, Period::to_string));
18073                former_ns.push(measure_period_renderer(
18074                    &periods,
18075                    period_display_former_profile,
18076                ));
18077            }
18078        }
18079        former_ns.sort_unstable();
18080        public_ns.sort_unstable();
18081        let former_p50 = former_ns[SAMPLES / 2];
18082        let public_p50 = public_ns[SAMPLES / 2];
18083        let former_p95 = former_ns[SAMPLES - 1];
18084        let public_p95 = public_ns[SAMPLES - 1];
18085        println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
18086        println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
18087        println!(
18088            "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
18089            former_p50 as f64 / public_p50 as f64
18090        );
18091        println!(
18092            "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
18093            former_p95 as f64 / public_p95 as f64
18094        );
18095    }
18096
18097    #[cfg(test)]
18098    fn fp_days(ymd: &str) -> i64 {
18099        Period::parse(ymd).expect("daily period").ordinal
18100    }
18101
18102    #[test]
18103    fn period_roundtrips_through_serde_json() {
18104        let p = Period::new(42, PeriodFreq::Weekly);
18105        let json = serde_json::to_string(&p).expect("serialize");
18106        let back: Period = serde_json::from_str(&json).expect("deserialize");
18107        assert_eq!(p, back);
18108    }
18109
18110    // ── period_range tests (br-frankenpandas-2jef — epoj Phase 2) ───────
18111
18112    use super::period_range;
18113
18114    #[test]
18115    fn period_range_zero_periods_is_empty() {
18116        let start = Period::new(216, PeriodFreq::Quarterly);
18117        assert!(period_range(start, 0).is_empty());
18118    }
18119
18120    #[test]
18121    fn period_range_single_period_returns_start_only() {
18122        let start = Period::new(216, PeriodFreq::Quarterly);
18123        let r = period_range(start, 1);
18124        assert_eq!(r.len(), 1);
18125        assert_eq!(r[0], start);
18126    }
18127
18128    #[test]
18129    fn period_range_increments_ordinal_by_one_per_step() {
18130        let start = Period::new(216, PeriodFreq::Quarterly);
18131        let r = period_range(start, 4);
18132        assert_eq!(r.len(), 4);
18133        assert_eq!(r[0].ordinal, 216);
18134        assert_eq!(r[1].ordinal, 217);
18135        assert_eq!(r[2].ordinal, 218);
18136        assert_eq!(r[3].ordinal, 219);
18137    }
18138
18139    #[test]
18140    fn period_range_preserves_frequency() {
18141        let start = Period::new(0, PeriodFreq::Monthly);
18142        let r = period_range(start, 12);
18143        assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
18144    }
18145
18146    #[test]
18147    fn period_range_negative_starting_ordinal_works() {
18148        // Ordinal axis is signed — pre-epoch periods are valid.
18149        let start = Period::new(-3, PeriodFreq::Annual);
18150        let r = period_range(start, 5);
18151        assert_eq!(
18152            r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
18153            vec![-3, -2, -1, 0, 1]
18154        );
18155    }
18156
18157    #[test]
18158    fn period_range_large_n_does_not_panic() {
18159        // 1024 monthly periods — large enough to catch any allocation bug.
18160        let start = Period::new(0, PeriodFreq::Monthly);
18161        let r = period_range(start, 1024);
18162        assert_eq!(r.len(), 1024);
18163        assert_eq!(r[1023].ordinal, 1023);
18164    }
18165
18166    #[test]
18167    fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
18168        fn next(seed: &mut u64) -> u64 {
18169            *seed = seed
18170                .wrapping_mul(6364136223846793005)
18171                .wrapping_add(1442695040888963407);
18172            *seed
18173        }
18174
18175        fn freq_for(raw: u64) -> PeriodFreq {
18176            // All TWELVE frequencies. This stopped at nine, so no property
18177            // test here ever generated a sub-second period.
18178            match raw % 12 {
18179                0 => PeriodFreq::Annual,
18180                1 => PeriodFreq::Quarterly,
18181                2 => PeriodFreq::Monthly,
18182                3 => PeriodFreq::Weekly,
18183                4 => PeriodFreq::Daily,
18184                5 => PeriodFreq::Business,
18185                6 => PeriodFreq::Hourly,
18186                7 => PeriodFreq::Minutely,
18187                8 => PeriodFreq::Secondly,
18188                9 => PeriodFreq::Milliseconds,
18189                10 => PeriodFreq::Microseconds,
18190                _ => PeriodFreq::Nanoseconds,
18191            }
18192        }
18193
18194        fn assert_oracle_case(case: usize, start: Period, periods: usize) {
18195            let got = period_range(start, periods);
18196            assert_eq!(got.len(), periods, "case {case}: length");
18197
18198            for (position, period) in got.iter().enumerate() {
18199                let expected_ordinal = start.ordinal.saturating_add(position as i64);
18200                assert_eq!(
18201                    period.ordinal, expected_ordinal,
18202                    "case {case}: ordinal at {position}"
18203                );
18204                assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
18205            }
18206        }
18207
18208        assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
18209        assert_oracle_case(
18210            usize::MAX - 1,
18211            Period::new(i64::MAX - 3, PeriodFreq::Daily),
18212            8,
18213        );
18214
18215        let mut seed = 0x9e21_0d1c_5eed_0421_u64;
18216        for case in 0..260 {
18217            let freq = freq_for(next(&mut seed));
18218            let periods = (next(&mut seed) % 80) as usize;
18219            let start_ordinal = if case % 37 == 0 {
18220                i64::MAX - 7
18221            } else {
18222                (next(&mut seed) % 20_001) as i64 - 10_000
18223            };
18224            assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
18225        }
18226    }
18227
18228    // ── interval_range tests (br-frankenpandas-xaom) ────────────────────
18229
18230    use super::{TypeError, interval_range, interval_range_by_periods, interval_range_by_step};
18231
18232    #[test]
18233    fn interval_range_by_periods_matches_pandas_default_case() {
18234        // pd.interval_range(0, 10, periods=5) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
18235        let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
18236        assert_eq!(bins.len(), 5);
18237        for (i, bin) in bins.iter().enumerate() {
18238            assert_eq!(bin.left, (i as f64) * 2.0);
18239            assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
18240            assert_eq!(bin.closed, IntervalClosed::Right);
18241        }
18242    }
18243
18244    #[test]
18245    fn interval_range_by_periods_final_edge_is_exact_end() {
18246        // Guards against accumulated float drift on the last right edge.
18247        let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
18248        assert_eq!(bins.last().unwrap().right, 1.0);
18249    }
18250
18251    #[test]
18252    fn interval_range_by_periods_zero_periods_is_empty() {
18253        assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
18254    }
18255
18256    #[test]
18257    fn interval_range_by_periods_reversed_range_is_empty() {
18258        // pandas: pd.interval_range(10, 0, periods=5) → IntervalIndex([]).
18259        assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
18260    }
18261
18262    #[test]
18263    fn interval_range_by_periods_preserves_closed_policy() {
18264        for closed in [
18265            IntervalClosed::Left,
18266            IntervalClosed::Right,
18267            IntervalClosed::Both,
18268            IntervalClosed::Neither,
18269        ] {
18270            let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
18271            assert!(bins.iter().all(|b| b.closed == closed));
18272        }
18273    }
18274
18275    #[test]
18276    fn interval_range_by_step_matches_pandas_default_case() {
18277        // pd.interval_range(0, 10, freq=2) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
18278        let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
18279        assert_eq!(bins.len(), 5);
18280        assert_eq!(bins[0].left, 0.0);
18281        assert_eq!(bins[4].right, 10.0);
18282    }
18283
18284    #[test]
18285    fn interval_range_by_step_rejects_non_positive_step() {
18286        assert!(matches!(
18287            interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
18288            Err(TypeError::InvalidIntervalStep { .. })
18289        ));
18290        assert!(matches!(
18291            interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
18292            Err(TypeError::InvalidIntervalStep { .. })
18293        ));
18294        assert!(matches!(
18295            interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
18296            Err(TypeError::InvalidIntervalStep { .. })
18297        ));
18298        assert!(matches!(
18299            interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
18300            Err(TypeError::InvalidIntervalStep { .. })
18301        ));
18302    }
18303
18304    #[test]
18305    fn interval_range_by_step_rejects_non_dividing_step() {
18306        // pandas: pd.interval_range(0, 10, freq=3) → ValueError
18307        // (span=10 not divisible by step=3). Reject with IntervalStepDoesNotDivide.
18308        assert!(matches!(
18309            interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
18310            Err(TypeError::IntervalStepDoesNotDivide { .. })
18311        ));
18312    }
18313
18314    #[test]
18315    fn interval_range_by_step_reversed_range_is_empty() {
18316        let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
18317        assert!(bins.is_empty());
18318    }
18319
18320    #[test]
18321    fn interval_range_by_step_degenerate_zero_span_is_empty() {
18322        let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
18323        assert!(bins.is_empty());
18324    }
18325
18326    #[test]
18327    fn interval_range_by_step_accepts_float_step_within_tolerance() {
18328        // step=0.1 ten times == 1.0 but float arithmetic produces 0.9999...
18329        let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
18330        assert_eq!(bins.len(), 10);
18331        assert_eq!(bins.last().unwrap().right, 1.0);
18332    }
18333
18334    #[test]
18335    fn interval_range_unified_api_tests() {
18336        // Case 1: start, end, periods
18337        let r1 = interval_range(Some(0.0), Some(10.0), Some(5), None, None).expect("ok");
18338        assert_eq!(r1.len(), 5);
18339        assert_eq!(r1[0].left, 0.0);
18340        assert_eq!(r1[0].right, 2.0);
18341        assert_eq!(r1[4].right, 10.0);
18342        assert_eq!(r1[0].closed, IntervalClosed::Right);
18343
18344        // Case 2: start, end, freq
18345        let r2 = interval_range(Some(0.0), Some(10.0), None, Some(2.0), None).expect("ok");
18346        assert_eq!(r2.len(), 5);
18347        assert_eq!(r2[0].left, 0.0);
18348        assert_eq!(r2[4].right, 10.0);
18349
18350        // Case 3: start, periods, freq
18351        let r3 = interval_range(
18352            Some(0.0),
18353            None,
18354            Some(5),
18355            Some(2.0),
18356            Some(IntervalClosed::Both),
18357        )
18358        .expect("ok");
18359        assert_eq!(r3.len(), 5);
18360        assert_eq!(r3[0].left, 0.0);
18361        assert_eq!(r3[4].right, 10.0);
18362        assert_eq!(r3[0].closed, IntervalClosed::Both);
18363
18364        // Case 4: end, periods, freq
18365        let r4 = interval_range(
18366            None,
18367            Some(10.0),
18368            Some(5),
18369            Some(2.0),
18370            Some(IntervalClosed::Left),
18371        )
18372        .expect("ok");
18373        assert_eq!(r4.len(), 5);
18374        assert_eq!(r4[0].left, 0.0);
18375        assert_eq!(r4[4].right, 10.0);
18376        assert_eq!(r4[0].closed, IntervalClosed::Left);
18377
18378        // Errors: not exactly 3 arguments
18379        assert!(matches!(
18380            interval_range(None, None, None, None, None),
18381            Err(TypeError::IntervalRangeParameterCount)
18382        ));
18383        assert!(matches!(
18384            interval_range(Some(0.0), Some(10.0), None, None, None),
18385            Err(TypeError::IntervalRangeParameterCount)
18386        ));
18387        assert!(matches!(
18388            interval_range(Some(0.0), Some(10.0), Some(5), Some(2.0), None),
18389            Err(TypeError::IntervalRangeParameterCount)
18390        ));
18391
18392        // Errors: non-positive freq
18393        assert!(matches!(
18394            interval_range(Some(0.0), None, Some(5), Some(-1.0), None),
18395            Err(TypeError::InvalidIntervalStep { .. })
18396        ));
18397        assert!(matches!(
18398            interval_range(Some(0.0), None, Some(5), Some(0.0), None),
18399            Err(TypeError::InvalidIntervalStep { .. })
18400        ));
18401    }
18402
18403    #[test]
18404    fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
18405        // Differential vs independent interval edge oracles
18406        // (br-frankenpandas-t9ozf). Seeded LCG, no mocks.
18407        fn next(seed: &mut u64) -> u64 {
18408            *seed = seed
18409                .wrapping_mul(2862933555777941757)
18410                .wrapping_add(3037000493);
18411            *seed
18412        }
18413
18414        fn closed_for(raw: u64) -> IntervalClosed {
18415            match raw % 4 {
18416                0 => IntervalClosed::Left,
18417                1 => IntervalClosed::Right,
18418                2 => IntervalClosed::Both,
18419                _ => IntervalClosed::Neither,
18420            }
18421        }
18422
18423        fn assert_interval(
18424            case: usize,
18425            kind: &str,
18426            pos: usize,
18427            actual: &Interval,
18428            expected: &Interval,
18429        ) {
18430            assert!(
18431                (actual.left - expected.left).abs() < 1e-12,
18432                "case={case} kind={kind} pos={pos}: expected left {}, got {}",
18433                expected.left,
18434                actual.left
18435            );
18436            assert!(
18437                (actual.right - expected.right).abs() < 1e-12,
18438                "case={case} kind={kind} pos={pos}: expected right {}, got {}",
18439                expected.right,
18440                actual.right
18441            );
18442            assert_eq!(
18443                actual.closed, expected.closed,
18444                "case={case} kind={kind} pos={pos}: closed mismatch"
18445            );
18446        }
18447
18448        fn expected_by_periods(
18449            start: f64,
18450            end: f64,
18451            periods: usize,
18452            closed: IntervalClosed,
18453        ) -> Vec<Interval> {
18454            if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
18455                return Vec::new();
18456            }
18457            let step = (end - start) / periods as f64;
18458            (0..periods)
18459                .map(|pos| {
18460                    let left = start + step * pos as f64;
18461                    let right = if pos + 1 == periods {
18462                        end
18463                    } else {
18464                        start + step * (pos + 1) as f64
18465                    };
18466                    Interval::new(left, right, closed)
18467                })
18468                .collect()
18469        }
18470
18471        fn expected_by_step(
18472            start: f64,
18473            end: f64,
18474            step: f64,
18475            closed: IntervalClosed,
18476        ) -> Vec<Interval> {
18477            if start >= end {
18478                return Vec::new();
18479            }
18480            let count = ((end - start) / step).round() as usize;
18481            (0..count)
18482                .map(|pos| {
18483                    let left = start + step * pos as f64;
18484                    let right = if pos + 1 == count {
18485                        end
18486                    } else {
18487                        start + step * (pos + 1) as f64
18488                    };
18489                    Interval::new(left, right, closed)
18490                })
18491                .collect()
18492        }
18493
18494        assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
18495        assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
18496        assert!(
18497            interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
18498                .expect("zero span")
18499                .is_empty()
18500        );
18501
18502        let mut seed = 0x171e_7a11_c0de_5eed_u64;
18503        for case in 0..220 {
18504            let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
18505            let periods = (next(&mut seed) % 24 + 1) as usize;
18506            let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
18507            let end = start + width;
18508            let closed = closed_for(next(&mut seed));
18509
18510            let actual = interval_range_by_periods(start, end, periods, closed);
18511            let expected = expected_by_periods(start, end, periods, closed);
18512            assert_eq!(
18513                actual.len(),
18514                expected.len(),
18515                "case={case} periods: length mismatch"
18516            );
18517            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18518                assert_interval(case, "periods", pos, actual, expected);
18519            }
18520
18521            let step_count = (next(&mut seed) % 20 + 1) as usize;
18522            let step = (next(&mut seed) % 25 + 1) as f64;
18523            let step_end = start + step * step_count as f64;
18524            let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
18525            let expected = expected_by_step(start, step_end, step, closed);
18526            assert_eq!(
18527                actual.len(),
18528                expected.len(),
18529                "case={case} step: length mismatch"
18530            );
18531            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18532                assert_interval(case, "step", pos, actual, expected);
18533            }
18534        }
18535    }
18536
18537    // ── Timedelta arithmetic tests (br-frankenpandas-4r56 Phase 1) ──────
18538
18539    use super::Timedelta;
18540
18541    #[test]
18542    fn timedelta_add_sums_non_nat() {
18543        let one_hour = Timedelta::NANOS_PER_HOUR;
18544        let one_day = Timedelta::NANOS_PER_DAY;
18545        assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
18546    }
18547
18548    #[test]
18549    fn timedelta_add_propagates_nat() {
18550        assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
18551        assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
18552        assert_eq!(
18553            Timedelta::add(Timedelta::NAT, Timedelta::NAT),
18554            Timedelta::NAT
18555        );
18556    }
18557
18558    #[test]
18559    fn timedelta_add_returns_nat_on_overflow() {
18560        // CORRECTED br-frankenpandas-lgyy8. This test previously asserted
18561        // `add(i64::MAX - 10, 100) == i64::MAX`, i.e. that positive overflow
18562        // yields a finite, plausible duration. Live pandas 2.2.3 raises
18563        // OverflowError for `pd.Timedelta.max + pd.Timedelta('1ns')` and never
18564        // returns a fabricated finite value, so the old expectation encoded a
18565        // fail-open bug. Overflow is now NaT in BOTH directions.
18566        assert_eq!(Timedelta::add(i64::MAX - 10, 100), Timedelta::NAT);
18567        // Negative side is unchanged: i64::MIN IS the NaT sentinel, so this
18568        // already surfaced as missing (pandas: Timedelta.min + -1ns -> NaT).
18569        assert_eq!(Timedelta::add(i64::MIN + 10, -100), Timedelta::NAT);
18570    }
18571
18572    #[test]
18573    fn timedelta_sub_subtracts_non_nat() {
18574        let one_hour = Timedelta::NANOS_PER_HOUR;
18575        assert_eq!(
18576            Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
18577            one_hour - Timedelta::NANOS_PER_MIN
18578        );
18579    }
18580
18581    #[test]
18582    fn timedelta_sub_propagates_nat() {
18583        assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
18584        assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
18585    }
18586
18587    #[test]
18588    fn timedelta_neg_flips_sign_non_nat() {
18589        assert_eq!(Timedelta::neg(5), -5);
18590        assert_eq!(Timedelta::neg(-5), 5);
18591        assert_eq!(Timedelta::neg(0), 0);
18592    }
18593
18594    #[test]
18595    fn timedelta_neg_preserves_nat() {
18596        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
18597    }
18598
18599    #[test]
18600    fn timedelta_abs_returns_magnitude() {
18601        assert_eq!(Timedelta::abs(-5), 5);
18602        assert_eq!(Timedelta::abs(5), 5);
18603        assert_eq!(Timedelta::abs(0), 0);
18604        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
18605    }
18606
18607    #[test]
18608    fn neg_and_abs_at_the_representable_floor_are_not_overflow_fyr1z() {
18609        // br-frankenpandas-fyr1z. Until this test existed, `neg`/`abs` were
18610        // only exercised at ±5 and 0, and the doc comment on `neg` asserted
18611        // the OPPOSITE of pandas: "pandas: `-pd.Timedelta.min` is NaT since
18612        // min == -max - 1 cannot be negated". Both halves are false, so an
18613        // implementer trusting the comment could have replaced
18614        // `saturating_neg()` with a NaT arm and broken parity without failing
18615        // a single existing assertion. Measured against the installed oracle,
18616        // pandas 2.2.3:
18617        //   pd.Timedelta.min.value                 == -9223372036854775807
18618        //   -pd.Timedelta.min                      -> Timedelta.max (NOT NaT)
18619        //   abs(pd.Timedelta.min)                  -> Timedelta.max (NOT NaT)
18620        //   -Series([Timedelta.min])               -> [Timedelta.max]
18621        //   Series([Timedelta.min]).abs()          -> [Timedelta.max]
18622        //
18623        // The reason there is no overflow to handle: pandas' representable
18624        // range is symmetric about zero because i64::MIN is spent on the NaT
18625        // sentinel, exactly as it is here.
18626        const MAX: i64 = i64::MAX;
18627        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
18628
18629        // The range really is symmetric — this is the premise the old comment
18630        // denied, and everything below follows from it.
18631        assert_eq!(MIN_OK, -MAX);
18632        assert_eq!(Timedelta::NAT, i64::MIN);
18633
18634        // The cases the false comment would have turned into NaT.
18635        assert_eq!(Timedelta::neg(MIN_OK), MAX);
18636        assert_eq!(Timedelta::neg(MAX), MIN_OK);
18637        assert_eq!(Timedelta::abs(MIN_OK), MAX);
18638        assert_eq!(Timedelta::abs(MAX), MAX);
18639
18640        // Round-tripping the floor must be exact, not sticky at a saturation
18641        // clamp: a `saturating_*` impl that ever clamped would land on
18642        // i64::MIN here and read as NaT.
18643        assert_eq!(Timedelta::neg(Timedelta::neg(MIN_OK)), MIN_OK);
18644        assert_ne!(Timedelta::neg(MIN_OK), Timedelta::NAT);
18645        assert_ne!(Timedelta::abs(MIN_OK), Timedelta::NAT);
18646
18647        // NaT itself is still the one input that stays NaT — the guard, not a
18648        // saturation branch, is what handles it.
18649        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
18650        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
18651    }
18652
18653    #[test]
18654    fn overflow_divergence_surface_is_only_where_pandas_refuses_fyr1z() {
18655        // br-frankenpandas-fyr1z, the decision bead for DISC-018. The bead was
18656        // filed on the premise "pandas raises; FP returns NaT", which would
18657        // make EVERY overflow a divergence. Probing live pandas 2.2.3 refutes
18658        // that: on the vectorized surface — the one users actually meet —
18659        // pandas returns NaT itself in several of these cases, so FP already
18660        // agrees there and a blanket "STRICT raises" mode would INTRODUCE
18661        // divergence rather than remove it.
18662        //
18663        // This test pins the agreement half. It is the negative control for
18664        // the divergence half already pinned by
18665        // `arithmetic_overflow_never_fabricates_a_finite_value_lgyy8`.
18666        const MAX: i64 = i64::MAX;
18667        const MIN_OK: i64 = i64::MIN + 1;
18668
18669        // ── AGREEMENT: pandas returns NaT here too, measured ───────────────
18670        // Series([Timedelta.max]) / 0    -> [NaT]
18671        // Series([Timedelta.max]) // 0   -> [NaT]
18672        // Series([Timedelta.max]) / 0.0  -> [NaT]
18673        assert_eq!(Timedelta::div_scalar(MAX, 0), Timedelta::NAT);
18674        assert_eq!(Timedelta::div_scalar(MIN_OK, 0), Timedelta::NAT);
18675        assert_eq!(Timedelta::div_scalar(0, 0), Timedelta::NAT);
18676
18677        // Series([Timedelta.min]) - Timedelta('1ns') -> [NaT], because the
18678        // result lands exactly on the i64::MIN sentinel. FP and pandas agree
18679        // — but only by SENTINEL COLLISION, not by policy. One further step
18680        // (`min - 2ns`) is `OverflowError: Overflow in int64 addition` in
18681        // pandas while FP still says NaT, which is the real divergence. A
18682        // test that only checked the 1ns case would therefore prove nothing;
18683        // both depths are asserted so the pair stays honest.
18684        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT); // pandas: NaT
18685        assert_eq!(Timedelta::sub(MIN_OK, 2), Timedelta::NAT); // pandas: RAISES
18686        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
18687        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(2).is_nat());
18688
18689        // ── DIVERGENCE: pandas refuses, FP surfaces NaT ────────────────────
18690        // Kept adjacent to the agreement cases so the boundary between the
18691        // two halves is visible in one place; DISC-018 is the prose record.
18692        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
18693        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
18694        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
18695
18696        // ── CONTROL: representable results are untouched by any of this ────
18697        assert_eq!(Timedelta::div_scalar(MAX, 1), MAX);
18698        assert_eq!(Timedelta::div_scalar(-100, 3), -34); // floor, not trunc
18699        assert_eq!(Timedelta::div_scalar(100, -3), -34);
18700        assert_eq!(Timedelta::sub(MIN_OK + 2, 1), MIN_OK + 1);
18701    }
18702
18703    #[test]
18704    fn timedelta_mul_scalar_scales() {
18705        let three_hours = Timedelta::NANOS_PER_HOUR * 3;
18706        assert_eq!(
18707            Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
18708            three_hours
18709        );
18710        assert_eq!(Timedelta::mul_scalar(100, 0), 0);
18711        assert_eq!(Timedelta::mul_scalar(100, -2), -200);
18712    }
18713
18714    #[test]
18715    fn timedelta_mul_scalar_returns_nat_on_overflow() {
18716        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX.
18717        // pandas `pd.Timedelta.max * 2` raises OverflowError.
18718        assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), Timedelta::NAT);
18719        assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), Timedelta::NAT);
18720    }
18721
18722    #[test]
18723    fn from_unit_nan_is_nat_and_overflow_is_err_8v92m() {
18724        use super::TimedeltaError;
18725
18726        // br-frankenpandas-8v92m. Rust's float->int `as` maps NaN to 0 and
18727        // saturates infinities, so the unguarded
18728        //     Ok((value * multiplier as f64).round() as i64)
18729        // failed OPEN twice: NaN became a ZERO DURATION, and inf/1e30 became a
18730        // finite plausible ~106751-day duration. Live pandas 2.2.3:
18731        //   pd.Timedelta(nan, unit='s')   -> NaT
18732        //   pd.Timedelta(inf, unit='s')   -> OutOfBoundsTimedelta
18733        //                                    "Cannot cast inf from s to 'ns' without overflow."
18734        //   pd.Timedelta(1e30, unit='s')  -> OutOfBoundsTimedelta
18735        //   pd.Timedelta(1.5, unit='s')   -> Timedelta('0 days 00:00:01.5')  <- must NOT change
18736        // The guard is copied from the two siblings that already had it
18737        // (br-frankenpandas-zw3mg), which is why `parse` behaviour is pinned
18738        // below too: all three copies must now agree.
18739
18740        // ── NaN -> NaT, NOT zero. This is the load-bearing case: an impl that
18741        // returns Ok(0) fails, and so does one that returns Err, because
18742        // pandas gives NaT rather than raising.
18743        assert_eq!(Timedelta::from_unit(f64::NAN, "s"), Ok(Timedelta::NAT));
18744        assert_ne!(Timedelta::from_unit(f64::NAN, "s"), Ok(0));
18745        assert_eq!(Timedelta::from_unit(f64::NAN, "D"), Ok(Timedelta::NAT));
18746
18747        // ── non-finite / out-of-range -> Overflow, not a saturated duration.
18748        assert_eq!(
18749            Timedelta::from_unit(f64::INFINITY, "s"),
18750            Err(TimedeltaError::Overflow)
18751        );
18752        assert_eq!(
18753            Timedelta::from_unit(f64::NEG_INFINITY, "s"),
18754            Err(TimedeltaError::Overflow)
18755        );
18756        assert_eq!(
18757            Timedelta::from_unit(1e30, "s"),
18758            Err(TimedeltaError::Overflow)
18759        );
18760        assert_eq!(
18761            Timedelta::from_unit(1e30, "D"),
18762            Err(TimedeltaError::Overflow)
18763        );
18764
18765        // ── CONTROL: ordinary values must be untouched, bit-for-bit. An
18766        // over-eager guard that rejected anything large would fail here.
18767        assert_eq!(Timedelta::from_unit(1.5, "s"), Ok(1_500_000_000));
18768        assert_eq!(Timedelta::from_unit(0.0, "s"), Ok(0));
18769        assert_eq!(Timedelta::from_unit(-2.5, "s"), Ok(-2_500_000_000));
18770        assert_eq!(Timedelta::from_unit(1.0, "D"), Ok(Timedelta::NANOS_PER_DAY));
18771        assert_eq!(
18772            Timedelta::from_unit(3.0, "h"),
18773            Ok(3 * Timedelta::NANOS_PER_HOUR)
18774        );
18775        // Just inside the representable range still returns its exact product,
18776        // so the boundary is pinned from the accepting side as well.
18777        let big_days = 100_000.0_f64;
18778        let expected = (big_days * Timedelta::NANOS_PER_DAY as f64).round() as i64;
18779        assert_eq!(Timedelta::from_unit(big_days, "D"), Ok(expected));
18780        assert!(expected > 0, "fixture must stay in range to be a control");
18781
18782        // ── an unknown unit is still InvalidFormat, NOT Overflow — the unit
18783        // check must keep running before the range check.
18784        assert!(matches!(
18785            Timedelta::from_unit(1.0, "nonsense-unit"),
18786            Err(TimedeltaError::InvalidFormat(_))
18787        ));
18788        assert!(matches!(
18789            Timedelta::from_unit(f64::NAN, "nonsense-unit"),
18790            Err(TimedeltaError::InvalidFormat(_)),
18791        ));
18792
18793        // ── the already-guarded sibling is unchanged. NOTE the input shape:
18794        // the compound lexer accepts only digits, '.' and '-', so scientific
18795        // notation is an InvalidFormat, not an Overflow — the overflow case
18796        // needs a long decimal literal (this is zw3mg's own fixture).
18797        let huge = format!("{} days", "9".repeat(18));
18798        assert!(matches!(
18799            Timedelta::parse(&huge),
18800            Err(TimedeltaError::Overflow)
18801        ));
18802        assert!(matches!(
18803            Timedelta::parse("1e100 days"),
18804            Err(TimedeltaError::InvalidFormat(_))
18805        ));
18806    }
18807
18808    #[test]
18809    fn rounding_and_ms_us_overflow_never_fabricates_a_finite_value_kyd16() {
18810        // br-frankenpandas-kyd16, the sibling sweep of lgyy8. Three defects:
18811        //   (1) Timedelta::round used UNCHECKED `(quotient + 1) * unit_nanos`
18812        //       on the round-up branch — debug PANIC, release WRAP to a
18813        //       large-negative duration.
18814        //   (2) Timedelta::floor/ceil and Timestamp::ceil_to/round_to
18815        //       saturated to i64::MAX, a finite plausible duration / ~year-2262
18816        //       instant handed back as real data — while their own sibling
18817        //       Timestamp::floor_to was ALREADY checked.
18818        //   (3) Timestamp::from_millis/from_micros saturated likewise, while
18819        //       their neighbour `fromtimestamp` already returned NaT.
18820        // Live pandas 2.2.3 raises on every one of these and names the cause:
18821        //   Timestamp.max.ceil('D')/round('D') -> OutOfBoundsDatetime
18822        //       "Cannot round 2262-04-11 23:47:16.854775807 to freq=<Day> without overflow"
18823        //   Timestamp.min.floor('D')           -> OutOfBoundsDatetime (same)
18824        //   Timedelta.max.ceil('D')/round('D') -> OutOfBoundsTimedelta (same shape)
18825        //   Timedelta.min.floor('D')           -> OutOfBoundsTimedelta (same)
18826        // ...but Timestamp.max.floor('D') is an ordinary in-range answer and
18827        // must NOT change. Both halves are asserted below.
18828        const MAX: i64 = i64::MAX;
18829        const MIN_OK: i64 = i64::MIN + 1;
18830        const DAY: i64 = Timedelta::NANOS_PER_DAY;
18831
18832        // ── (1) round(): must not panic, must not wrap negative ────────────
18833        let rounded = Timedelta::round(MAX, "D");
18834        assert_eq!(
18835            rounded,
18836            Timedelta::NAT,
18837            "rounding i64::MAX up to a whole day overflows; the old unchecked \
18838             multiply panicked in debug and wrapped in release"
18839        );
18840        // The wrap signature specifically: a positive input must never round
18841        // to a negative duration. This fails for a wrapping impl even if the
18842        // debug panic is somehow avoided.
18843        assert!(
18844            rounded == Timedelta::NAT || rounded > 0,
18845            "a positive duration must never round to a negative one"
18846        );
18847        assert_eq!(Timedelta::round(MIN_OK, "D"), Timedelta::NAT);
18848
18849        // ── (2) floor/ceil overflow -> NaT, not a fabricated finite value ──
18850        assert_eq!(Timedelta::ceil(MAX, "D"), Timedelta::NAT);
18851        assert_eq!(Timedelta::floor(MIN_OK, "D"), Timedelta::NAT);
18852        assert!(Timestamp::from_nanos(MAX).ceil_to(DAY).is_nat());
18853        assert!(Timestamp::from_nanos(MAX).round_to(DAY).is_nat());
18854        assert!(Timestamp::from_nanos(MIN_OK).floor_to(DAY).is_nat());
18855        assert!(Timestamp::from_nanos(MIN_OK).round_to(DAY).is_nat());
18856
18857        // ── (3) ms/us constructors out of range -> NaT ─────────────────────
18858        assert!(Timestamp::from_millis(MAX, None).is_nat());
18859        assert!(Timestamp::from_millis(MIN_OK, None).is_nat());
18860        assert!(Timestamp::from_micros(MAX, None).is_nat());
18861        assert!(Timestamp::from_micros(MIN_OK, Some("US/Eastern")).is_nat());
18862
18863        // ── CONTROL: in-range rounding is untouched. An implementation that
18864        // NaT'd too eagerly — or that treated "near the limit" as overflow —
18865        // fails every assertion below.
18866        //
18867        // Timestamp.max.floor('D') is the exact case pandas ANSWERS rather
18868        // than raising, so it pins the boundary from the other side.
18869        let max_floor = Timestamp::from_nanos(MAX).floor_to(DAY);
18870        assert!(!max_floor.is_nat(), "Timestamp.max.floor(D) must succeed");
18871        assert_eq!(max_floor.nanos, (MAX / DAY) * DAY);
18872        assert_eq!(Timedelta::floor(MAX, "D"), (MAX / DAY) * DAY);
18873        assert_eq!(
18874            Timedelta::ceil(MIN_OK, "D"),
18875            (MIN_OK.div_euclid(DAY) + 1) * DAY
18876        );
18877
18878        // Ordinary values, bit-for-bit.
18879        let hour = Timedelta::NANOS_PER_HOUR;
18880        assert_eq!(Timedelta::floor(90 * 60 * 1_000_000_000, "h"), hour);
18881        assert_eq!(Timedelta::ceil(90 * 60 * 1_000_000_000, "h"), 2 * hour);
18882        assert_eq!(Timedelta::round(90 * 60 * 1_000_000_000, "h"), 2 * hour);
18883        assert_eq!(Timedelta::round(-90 * 60 * 1_000_000_000, "h"), -2 * hour);
18884        assert_eq!(Timedelta::round(29 * 60 * 1_000_000_000, "h"), 0);
18885        assert_eq!(Timestamp::from_millis(1_500, None).nanos, 1_500_000_000);
18886        assert_eq!(Timestamp::from_micros(-2_000, None).nanos, -2_000_000);
18887        assert_eq!(
18888            Timestamp::from_nanos(hour + 1).floor_to(hour).nanos,
18889            hour,
18890            "in-range floor unchanged"
18891        );
18892        assert_eq!(
18893            Timestamp::from_nanos(hour + 1).ceil_to(hour).nanos,
18894            2 * hour,
18895            "in-range ceil unchanged"
18896        );
18897
18898        // NaT / degenerate-unit inputs unchanged.
18899        assert_eq!(Timedelta::round(Timedelta::NAT, "D"), Timedelta::NAT);
18900        assert_eq!(Timedelta::floor(Timedelta::NAT, "D"), Timedelta::NAT);
18901        assert_eq!(Timedelta::ceil(1_000, "nonsense-unit"), Timedelta::NAT);
18902        assert!(Timestamp::nat().ceil_to(DAY).is_nat());
18903        assert!(Timestamp::from_nanos(0).round_to(0).is_nat());
18904        // A non-overflowing round still carries its zone.
18905        assert_eq!(
18906            Timestamp::from_nanos_tz(hour + 1, "US/Eastern")
18907                .ceil_to(hour)
18908                .tz
18909                .as_deref(),
18910            Some("US/Eastern")
18911        );
18912    }
18913
18914    #[test]
18915    fn timedelta_mul_scalar_propagates_nat() {
18916        assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
18917    }
18918
18919    #[test]
18920    fn arithmetic_overflow_never_fabricates_a_finite_value_lgyy8() {
18921        // br-frankenpandas-lgyy8. The bug: these six helpers used
18922        // `saturating_*`, so POSITIVE overflow returned i64::MAX — a valid,
18923        // finite, plausible duration / ~year-2262 instant — as if it were real
18924        // data. (Negative overflow landed on i64::MIN, which IS the NaT
18925        // sentinel, so that direction already surfaced as missing.) Live
18926        // pandas 2.2.3 never returns a fabricated finite value on overflow in
18927        // either direction, scalar or vectorized:
18928        //   pd.Timedelta.max + Timedelta('1ns')  -> OverflowError
18929        //   pd.Timestamp.max + Timedelta('1ns')  -> OutOfBoundsDatetime
18930        //   pd.Timestamp.min - pd.Timestamp.max  -> OutOfBoundsDatetime
18931        //   pd.Timedelta.max * 2                 -> OverflowError
18932        //   pd.Timedelta.min + Timedelta('-1ns') -> NaT
18933        //
18934        // Every assertion below is a case a saturating implementation FAILS.
18935        const MAX: i64 = i64::MAX;
18936        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
18937
18938        // ── positive overflow: the actual bug ──────────────────────────────
18939        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
18940        assert_eq!(Timedelta::add(MAX - 10, 100), Timedelta::NAT);
18941        assert_eq!(Timedelta::sub(MAX, -1), Timedelta::NAT);
18942        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
18943        assert_eq!(Timedelta::mul_scalar(MAX / 2 + 2, 2), Timedelta::NAT);
18944        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
18945        assert!(Timestamp::from_nanos(MAX).sub_timedelta(-1).is_nat());
18946        // Timestamp.max - Timestamp.min: the true difference is ~2^64, far
18947        // outside i64. Saturation returned MAX (a ~292-year duration presented
18948        // as the real answer); pandas raises OutOfBoundsDatetime.
18949        assert_eq!(
18950            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(MIN_OK)),
18951            Timedelta::NAT
18952        );
18953
18954        // ── negative overflow: unchanged, still NaT ────────────────────────
18955        assert_eq!(Timedelta::add(MIN_OK, -1), Timedelta::NAT);
18956        assert_eq!(Timedelta::add(MIN_OK, -2), Timedelta::NAT);
18957        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
18958        assert_eq!(Timedelta::mul_scalar(MIN_OK, 2), Timedelta::NAT);
18959        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
18960        assert!(Timestamp::from_nanos(MIN_OK).add_timedelta(-1).is_nat());
18961        assert_eq!(
18962            Timestamp::from_nanos(MIN_OK).sub_timestamp(&Timestamp::from_nanos(MAX)),
18963            Timedelta::NAT
18964        );
18965
18966        // ── the boundary: the largest REPRESENTABLE results must still be
18967        // returned exactly. This is what stops the fix from being bought with
18968        // an over-eager NaT that swallows valid arithmetic — an implementation
18969        // that NaT'd one step early fails here, as does one that NaT'd on any
18970        // operand near the limits.
18971        assert_eq!(Timedelta::add(MAX - 1, 1), MAX);
18972        assert_eq!(Timedelta::add(MAX, 0), MAX);
18973        assert_eq!(Timedelta::sub(MAX, 1), MAX - 1);
18974        assert_eq!(Timedelta::add(MIN_OK + 1, -1), MIN_OK);
18975        assert_eq!(Timedelta::mul_scalar(MAX / 2, 2), (MAX / 2) * 2);
18976        assert_eq!(Timedelta::mul_scalar(MIN_OK, 1), MIN_OK);
18977        assert_eq!(Timestamp::from_nanos(MAX - 1).add_timedelta(1).nanos, MAX);
18978        assert_eq!(
18979            Timestamp::from_nanos(MIN_OK + 1).sub_timedelta(1).nanos,
18980            MIN_OK
18981        );
18982        assert_eq!(
18983            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(0)),
18984            MAX
18985        );
18986        // Ordinary values are untouched bit-for-bit.
18987        assert_eq!(Timedelta::add(1_000, 2_345), 3_345);
18988        assert_eq!(Timedelta::sub(1_000, 2_345), -1_345);
18989        assert_eq!(Timedelta::mul_scalar(-7, 6), -42);
18990
18991        // ── a result landing EXACTLY on i64::MIN is representable, but i64::MIN
18992        // IS the NaT sentinel, so it must read as NaT rather than as the most
18993        // negative duration. pandas agrees: Timedelta.min + -1ns -> NaT. Note
18994        // `MIN_OK - 1 == i64::MIN` does not overflow, so this case survives the
18995        // switch from saturating_* to checked_* only because the sentinel and
18996        // the clamp coincide — assert it explicitly rather than by accident.
18997        assert_eq!(MIN_OK - 1, i64::MIN);
18998        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
18999        assert_eq!(Timedelta::add(MIN_OK, 0), MIN_OK);
19000
19001        // ── NaT operands still propagate, and tz no longer rides along with a
19002        // fabricated instant: an overflowed Timestamp is the canonical NaT.
19003        assert!(Timestamp::nat().add_timedelta(1).is_nat());
19004        assert!(
19005            Timestamp::from_nanos(0)
19006                .add_timedelta(Timedelta::NAT)
19007                .is_nat()
19008        );
19009        let tzed = Timestamp::from_nanos_tz(MAX, "US/Eastern");
19010        let overflowed = tzed.add_timedelta(1);
19011        assert!(overflowed.is_nat());
19012        assert_eq!(overflowed.tz, None, "an overflow NaT carries no zone");
19013        // ...while a NON-overflowing shift still preserves the zone.
19014        assert_eq!(
19015            Timestamp::from_nanos_tz(0, "US/Eastern")
19016                .add_timedelta(Timedelta::NANOS_PER_DAY)
19017                .tz
19018                .as_deref(),
19019            Some("US/Eastern")
19020        );
19021    }
19022
19023    #[test]
19024    fn timedelta_div_scalar_floor_divides() {
19025        // Floor division (matches Python / pandas): -100 // 3 == -34, not -33.
19026        assert_eq!(Timedelta::div_scalar(100, 3), 33);
19027        assert_eq!(Timedelta::div_scalar(-100, 3), -34);
19028        assert_eq!(Timedelta::div_scalar(100, -3), -34);
19029        assert_eq!(Timedelta::div_scalar(-100, -3), 33);
19030    }
19031
19032    #[test]
19033    fn timedelta_div_scalar_zero_divisor_returns_nat() {
19034        assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
19035    }
19036
19037    #[test]
19038    fn timedelta_div_scalar_min_neg_one_propagates_nat() {
19039        // i64::MIN aliases NaT, so `div_scalar(i64::MIN, _)` propagates NaT
19040        // — the `i64::MIN / -1` arithmetic-overflow case is subsumed.
19041        assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
19042        // (i64::MIN + 1) is a real timedelta; `/ -1` does not overflow.
19043        assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
19044    }
19045
19046    #[test]
19047    fn timedelta_div_scalar_propagates_nat() {
19048        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
19049    }
19050
19051    #[test]
19052    fn timedelta_div_timedelta_returns_float_ratio() {
19053        let two_hours = Timedelta::NANOS_PER_HOUR * 2;
19054        let one_hour = Timedelta::NANOS_PER_HOUR;
19055        assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
19056        assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
19057    }
19058
19059    #[test]
19060    fn timedelta_div_timedelta_nat_returns_nan() {
19061        assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
19062        assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
19063    }
19064
19065    // ── Timestamp tests (br-frankenpandas-9p0u — 4r56 Phase 2) ──────────
19066
19067    use super::Timestamp;
19068
19069    #[test]
19070    fn timestamp_from_nanos_is_naive_utc() {
19071        let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
19072        assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
19073        assert_eq!(ts.tz, None);
19074        assert!(!ts.is_nat());
19075    }
19076
19077    #[test]
19078    fn timestamp_from_nanos_tz_carries_tz_name() {
19079        let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19080        assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
19081    }
19082
19083    #[test]
19084    fn timestamp_now_returns_current_time() {
19085        let before = std::time::SystemTime::now()
19086            .duration_since(std::time::UNIX_EPOCH)
19087            .unwrap()
19088            .as_nanos() as i64;
19089        let ts = Timestamp::now();
19090        let after = std::time::SystemTime::now()
19091            .duration_since(std::time::UNIX_EPOCH)
19092            .unwrap()
19093            .as_nanos() as i64;
19094        assert!(ts.nanos >= before);
19095        assert!(ts.nanos <= after);
19096        assert!(!ts.is_nat());
19097    }
19098
19099    #[test]
19100    fn timestamp_today_returns_midnight() {
19101        let ts = Timestamp::today();
19102        assert!(!ts.is_nat());
19103        // Today should be normalized (midnight), so hour/min/sec should be 0
19104        assert_eq!(ts.hour(), Some(0));
19105        assert_eq!(ts.minute(), Some(0));
19106        assert_eq!(ts.second(), Some(0));
19107    }
19108
19109    #[test]
19110    fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
19111        let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
19112        let one_day = Timedelta::NANOS_PER_DAY;
19113        let shifted = ts.add_timedelta(one_day);
19114        assert_eq!(shifted.nanos, one_day);
19115        assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
19116    }
19117
19118    #[test]
19119    fn timestamp_add_timedelta_returns_nat_on_overflow() {
19120        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX, i.e.
19121        // a finite ~year-2262 instant handed back as real data. pandas
19122        // `pd.Timestamp.max + pd.Timedelta('1ns')` raises OutOfBoundsDatetime.
19123        let ts = Timestamp::from_nanos(i64::MAX - 10);
19124        assert!(ts.add_timedelta(100).is_nat());
19125    }
19126
19127    #[test]
19128    fn timestamp_add_timedelta_propagates_nat() {
19129        // NaT Timestamp + anything = NaT.
19130        assert!(Timestamp::nat().add_timedelta(100).is_nat());
19131        // Timestamp + NaT Timedelta = NaT.
19132        assert!(
19133            Timestamp::from_nanos(0)
19134                .add_timedelta(Timedelta::NAT)
19135                .is_nat()
19136        );
19137    }
19138
19139    #[test]
19140    fn timestamp_sub_timedelta_shifts_backward() {
19141        let ts = Timestamp::from_nanos(1_000);
19142        let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
19143        assert_eq!(shifted.nanos, 0);
19144    }
19145
19146    #[test]
19147    fn timestamp_sub_timestamp_returns_timedelta_nanos() {
19148        let t0 = Timestamp::from_nanos(0);
19149        let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
19150        assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
19151        assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
19152    }
19153
19154    #[test]
19155    fn timestamp_sub_timestamp_nat_propagates() {
19156        let ts = Timestamp::from_nanos(1_000);
19157        assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
19158        assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
19159    }
19160
19161    #[test]
19162    fn timestamp_semantic_eq_treats_two_nat_as_equal() {
19163        assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
19164        assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
19165        assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
19166    }
19167
19168    #[test]
19169    fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
19170        use std::cmp::Ordering;
19171        let a = Timestamp::from_nanos(0);
19172        let b = Timestamp::from_nanos(100);
19173        assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
19174        assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
19175        assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
19176        assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
19177        assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
19178    }
19179
19180    #[test]
19181    fn time_zone_offsets_and_wall_clock_conversions_follow_pandas() {
19182        use crate::{
19183            TimeZoneError, tz_abbreviation, tz_canonical_name, tz_offset_seconds,
19184            tz_utc_to_wall_nanos, tz_validate, tz_wall_to_utc_nanos,
19185        };
19186        let hour = 3_600_000_000_000_i64;
19187        // 2024-03-10 14:30 UTC: Tokyo is +9h; New York is on EDT (-4h) after
19188        // 07:00 UTC that day and on EST (-5h) the day before.
19189        let instant = 1_710_081_000_000_000_000_i64;
19190        assert_eq!(tz_offset_seconds("Asia/Tokyo", instant), Ok(9 * 3_600));
19191        assert_eq!(tz_offset_seconds("US/Eastern", instant), Ok(-4 * 3_600));
19192        assert_eq!(
19193            tz_offset_seconds("US/Eastern", instant - 24 * hour),
19194            Ok(-5 * 3_600)
19195        );
19196        assert_eq!(tz_offset_seconds("+05:30", 0), Ok(19_800));
19197        assert_eq!(tz_offset_seconds("UTC+05:30", 0), Ok(19_800));
19198        assert_eq!(tz_offset_seconds("-03:00", 0), Ok(-10_800));
19199        assert_eq!(tz_offset_seconds("UTC", instant), Ok(0));
19200        assert_eq!(
19201            tz_utc_to_wall_nanos("Asia/Tokyo", instant),
19202            Ok(instant + 9 * hour)
19203        );
19204        // Wall 12:00 in New York on 2024-01-01 is 17:00 UTC, and back.
19205        let wall_noon = 19_723 * 24 * hour + 12 * hour;
19206        assert_eq!(
19207            tz_wall_to_utc_nanos("US/Eastern", wall_noon),
19208            Ok(wall_noon + 5 * hour)
19209        );
19210        assert_eq!(
19211            tz_utc_to_wall_nanos("US/Eastern", wall_noon + 5 * hour),
19212            Ok(wall_noon)
19213        );
19214        // NaT passes through both ways.
19215        assert_eq!(tz_wall_to_utc_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19216        assert_eq!(tz_utc_to_wall_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19217        // NEGATIVES: 02:30 on 2024-03-10 does not exist in New York; 01:30
19218        // on 2024-11-03 happens twice; unknown zones and malformed offsets
19219        // are pandas' UnknownTimeZoneError.
19220        let skipped = 19_792 * 24 * hour + 2 * hour + 30 * 60_000_000_000;
19221        assert_eq!(
19222            tz_wall_to_utc_nanos("US/Eastern", skipped),
19223            Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19224        );
19225        let repeated = 20_030 * 24 * hour + hour + 30 * 60_000_000_000;
19226        assert_eq!(
19227            tz_wall_to_utc_nanos("US/Eastern", repeated),
19228            Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19229        );
19230        assert_eq!(
19231            tz_offset_seconds("Mars/Olympus", 0),
19232            Err(TimeZoneError::Unknown("Mars/Olympus".to_owned()))
19233        );
19234        assert!(tz_validate("+24:00").is_err());
19235        assert!(tz_validate("+5:30").is_err());
19236        assert!(tz_validate("Europe/Paris").is_ok());
19237        // pandas' names: a fixed offset is UTC+HH:MM, a zero one UTC.
19238        assert_eq!(tz_canonical_name("+05:30").as_deref(), Ok("UTC+05:30"));
19239        assert_eq!(tz_canonical_name("UTC-03:00").as_deref(), Ok("UTC-03:00"));
19240        assert_eq!(tz_canonical_name("+00:00").as_deref(), Ok("UTC"));
19241        assert_eq!(tz_canonical_name("Z").as_deref(), Ok("UTC"));
19242        assert_eq!(tz_canonical_name("US/Eastern").as_deref(), Ok("US/Eastern"));
19243        // strftime('%Z'): the abbreviation in force at the instant.
19244        assert_eq!(tz_abbreviation("US/Eastern", instant).as_deref(), Ok("EDT"));
19245        assert_eq!(
19246            tz_abbreviation("US/Eastern", instant - 24 * hour).as_deref(),
19247            Ok("EST")
19248        );
19249        assert_eq!(tz_abbreviation("+05:30", 0).as_deref(), Ok("UTC+05:30"));
19250    }
19251
19252    /// pandas' `tz_localize(ambiguous=, nonexistent=)` for one wall time
19253    /// (br-frankenpandas-84w06), live pandas 2.2.3 in America/New_York:
19254    /// 02:30 on 2024-03-10 does not exist - shift_forward 03:00-04:00 (07:00
19255    /// UTC), shift_backward 01:59:59.999999999-05:00, NaT, or +1h 03:30-04:00;
19256    /// 01:30 on 2024-11-03 happens twice - True (DST) 05:30 UTC, False
19257    /// (standard) 06:30 UTC, NaT.
19258    #[test]
19259    fn tz_localize_policies_follow_pandas_84w06() {
19260        use super::{
19261            AmbiguousTime as A, NonexistentTime as N, TimeZoneError,
19262            tz_wall_to_utc_nanos_with as at,
19263        };
19264        let hour = 3_600_000_000_000_i64;
19265        let minute = 60_000_000_000_i64;
19266        let skipped = 19_792 * 24 * hour + 2 * hour + 30 * minute;
19267        let transition = 19_792 * 24 * hour + 7 * hour;
19268        let zone = "America/New_York";
19269        assert_eq!(at(zone, skipped, A::Raise, N::ShiftForward), Ok(transition));
19270        assert_eq!(
19271            at(zone, skipped, A::Raise, N::ShiftBackward),
19272            Ok(transition - 1)
19273        );
19274        assert_eq!(at(zone, skipped, A::Raise, N::NaT), Ok(i64::MIN));
19275        assert_eq!(
19276            at(zone, skipped, A::Raise, N::Shift(hour)),
19277            Ok(transition + 30 * minute)
19278        );
19279        let repeated = 20_030 * 24 * hour + hour + 30 * minute;
19280        assert_eq!(
19281            at(zone, repeated, A::Earliest, N::Raise),
19282            Ok(repeated + 4 * hour)
19283        );
19284        assert_eq!(
19285            at(zone, repeated, A::Latest, N::Raise),
19286            Ok(repeated + 5 * hour)
19287        );
19288        assert_eq!(at(zone, repeated, A::NaT, N::Raise), Ok(i64::MIN));
19289        // NEGATIVES: the policies leave a wall time that exists once alone,
19290        // and 'raise' still refuses as before.
19291        let noon = 19_723 * 24 * hour + 12 * hour;
19292        assert_eq!(at(zone, noon, A::NaT, N::NaT), Ok(noon + 5 * hour));
19293        assert_eq!(
19294            at(zone, skipped, A::NaT, N::Raise),
19295            Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19296        );
19297        assert_eq!(
19298            at(zone, repeated, A::Raise, N::NaT),
19299            Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19300        );
19301    }
19302
19303    #[test]
19304    fn timestamp_display_matches_phase2_debug_format() {
19305        assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
19306        assert_eq!(
19307            Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
19308            "Timestamp[42, US/Eastern]"
19309        );
19310        assert_eq!(Timestamp::nat().to_string(), "NaT");
19311    }
19312
19313    #[test]
19314    fn timestamp_value_and_unit_match_pandas_l0edr() {
19315        let ts = Timestamp::from_nanos(1_000_000_123);
19316        assert_eq!(ts.value(), 1_000_000_123);
19317        assert_eq!(ts.unit(), Some("ns"));
19318
19319        let nat = Timestamp::nat();
19320        assert_eq!(nat.value(), Timestamp::NAT);
19321        assert_eq!(nat.unit(), None);
19322    }
19323
19324    #[test]
19325    fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
19326        let ts = Timestamp::from_nanos(1_000_000_123);
19327        assert_eq!(ts.asm8(), ts.value());
19328        assert_eq!(ts.to_datetime64(), ts.value());
19329        assert_eq!(ts.to_numpy(), ts.value());
19330
19331        let nat = Timestamp::nat();
19332        assert_eq!(nat.asm8(), Timestamp::NAT);
19333        assert_eq!(nat.to_datetime64(), Timestamp::NAT);
19334        assert_eq!(nat.to_numpy(), Timestamp::NAT);
19335    }
19336
19337    #[test]
19338    fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
19339        assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
19340        assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
19341        assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
19342        assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
19343        assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
19344
19345        assert!(matches!(
19346            Timestamp::from_nanos(-500).timestamp(),
19347            Ok(value) if value == -0.0 && value.is_sign_negative()
19348        ));
19349        assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
19350        assert_eq!(
19351            Timestamp::nat().timestamp(),
19352            Err(TypeError::ValueIsMissing {
19353                kind: NullKind::NaT,
19354            })
19355        );
19356    }
19357
19358    #[test]
19359    fn timestamp_roundtrips_through_serde_json() {
19360        let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
19361        let json = serde_json::to_string(&naive).expect("serialize");
19362        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19363        assert_eq!(naive, back);
19364
19365        let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19366        let json = serde_json::to_string(&tz_aware).expect("serialize");
19367        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19368        assert_eq!(tz_aware, back);
19369    }
19370
19371    #[test]
19372    fn timestamp_is_send_and_sync() {
19373        fn assert_send_sync<T: Send + Sync>() {}
19374        assert_send_sync::<Timestamp>();
19375    }
19376
19377    // ── Timestamp rounding tests (br-frankenpandas-5h6n) ────────────────
19378
19379    #[test]
19380    fn timestamp_pre_epoch_accessors_floor_not_truncate() {
19381        // br-frankenpandas-wkjtw: pre-1970 instants with a sub-day part used to
19382        // truncate toward zero, landing on the wrong calendar day. -1 ns is
19383        // 1969-12-31 23:59:59.999999999 UTC.
19384        let ts = Timestamp::from_nanos(-1);
19385        assert_eq!(ts.year(), Some(1969));
19386        assert_eq!(ts.month(), Some(12));
19387        assert_eq!(ts.day(), Some(31));
19388        assert_eq!(ts.hour(), Some(23));
19389        assert_eq!(ts.minute(), Some(59));
19390        assert_eq!(ts.second(), Some(59));
19391        assert_eq!(ts.microsecond(), Some(999_999));
19392        assert_eq!(ts.nanosecond(), Some(999));
19393        // 1969-12-31 is a Wednesday (pandas Monday=0 -> 2).
19394        assert_eq!(ts.dayofweek(), Some(2));
19395
19396        // 1969-12-31 12:00:00 — the classic truncation case (-43200 s).
19397        let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
19398        assert_eq!(noon.year(), Some(1969));
19399        assert_eq!(noon.month(), Some(12));
19400        assert_eq!(noon.day(), Some(31));
19401        assert_eq!(noon.hour(), Some(12));
19402
19403        // Exact midnight pre-epoch was already correct; keep it green.
19404        let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
19405        assert_eq!(midnight.year(), Some(1969));
19406        assert_eq!(midnight.day(), Some(31));
19407        assert_eq!(midnight.hour(), Some(0));
19408    }
19409
19410    #[test]
19411    fn timestamp_floor_to_rounds_down() {
19412        // 12:34:56 → floor by 1H → 12:00:00
19413        let h = Timedelta::NANOS_PER_HOUR;
19414        let twelve_h = h * 12;
19415        let twelve_thirty_four =
19416            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19417        let ts = Timestamp::from_nanos(twelve_thirty_four);
19418        let floored = ts.floor_to(h);
19419        assert_eq!(floored.nanos, twelve_h);
19420    }
19421
19422    #[test]
19423    fn timestamp_floor_to_handles_already_aligned() {
19424        // 12:00:00 floored by 1H → 12:00:00 (no change).
19425        let h = Timedelta::NANOS_PER_HOUR;
19426        let twelve_h = h * 12;
19427        let ts = Timestamp::from_nanos(twelve_h);
19428        assert_eq!(ts.floor_to(h).nanos, twelve_h);
19429    }
19430
19431    #[test]
19432    fn timestamp_floor_to_handles_negative_nanos() {
19433        // -100 ns floored by 60 ns:
19434        //   div_euclid(-100, 60) = -2 (since -2*60=-120, rem=20 ≥ 0).
19435        //   result = -2 * 60 = -120.
19436        let ts = Timestamp::from_nanos(-100);
19437        assert_eq!(ts.floor_to(60).nanos, -120);
19438    }
19439
19440    #[test]
19441    fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
19442        let ts = Timestamp::from_nanos(i64::MIN + 1);
19443        assert!(ts.floor_to(10).is_nat());
19444
19445        let safe = Timestamp::from_nanos(i64::MIN + 10);
19446        assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
19447
19448        let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
19449        assert_eq!(tz.nanos, -120);
19450        assert_eq!(tz.tz.as_deref(), Some("UTC"));
19451    }
19452
19453    #[test]
19454    fn timestamp_ceil_to_rounds_up() {
19455        // 12:34:56 → ceil by 1H → 13:00:00.
19456        let h = Timedelta::NANOS_PER_HOUR;
19457        let twelve_h = h * 12;
19458        let thirteen_h = h * 13;
19459        let twelve_thirty_four =
19460            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19461        let ts = Timestamp::from_nanos(twelve_thirty_four);
19462        assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
19463    }
19464
19465    #[test]
19466    fn timestamp_ceil_to_no_op_on_aligned() {
19467        let h = Timedelta::NANOS_PER_HOUR;
19468        let twelve_h = h * 12;
19469        let ts = Timestamp::from_nanos(twelve_h);
19470        assert_eq!(ts.ceil_to(h).nanos, twelve_h);
19471    }
19472
19473    #[test]
19474    fn timestamp_round_to_rounds_to_nearest() {
19475        // 12:30:01 (one second past the half-hour): round to 1H → 13:00:00.
19476        let h = Timedelta::NANOS_PER_HOUR;
19477        let twelve_h = h * 12;
19478        let twelve_thirty_one_sec =
19479            twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
19480        let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
19481        assert_eq!(ts.round_to(h).nanos, h * 13);
19482
19483        // 12:29:59 (one second before half): round to 1H → 12:00:00.
19484        let twelve_twenty_nine_sec =
19485            twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
19486        let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
19487        assert_eq!(ts.round_to(h).nanos, twelve_h);
19488    }
19489
19490    #[test]
19491    fn timestamp_round_to_bankers_tie_to_even() {
19492        // Tie cases: rem == unit/2 exactly. Pick even-multiple floor.
19493        // unit=10, so half=5. nanos=5: floor=0 (even), so → 0.
19494        // nanos=15: floor=1 (odd), so → 20.
19495        // nanos=25: floor=2 (even), so → 20.
19496        // nanos=35: floor=3 (odd), so → 40.
19497        assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
19498        assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
19499        assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
19500        assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
19501    }
19502
19503    #[test]
19504    fn timestamp_round_to_zero_unit_returns_nat() {
19505        let ts = Timestamp::from_nanos(100);
19506        assert!(ts.round_to(0).is_nat());
19507        assert!(ts.floor_to(0).is_nat());
19508        assert!(ts.ceil_to(0).is_nat());
19509    }
19510
19511    #[test]
19512    fn timestamp_round_to_negative_unit_returns_nat() {
19513        let ts = Timestamp::from_nanos(100);
19514        assert!(ts.round_to(-10).is_nat());
19515        assert!(ts.floor_to(-10).is_nat());
19516        assert!(ts.ceil_to(-10).is_nat());
19517    }
19518
19519    #[test]
19520    fn timestamp_rounding_propagates_nat() {
19521        let nat = Timestamp::nat();
19522        assert!(nat.floor_to(60).is_nat());
19523        assert!(nat.ceil_to(60).is_nat());
19524        assert!(nat.round_to(60).is_nat());
19525    }
19526
19527    #[test]
19528    fn timestamp_rounding_preserves_tz() {
19529        let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
19530        assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
19531        assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
19532        assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
19533    }
19534
19535    // ── Timestamp string-unit rounding tests (br-frankenpandas-lbsx) ────
19536
19537    #[test]
19538    fn timestamp_floor_to_unit_h_rounds_to_hour() {
19539        let h = Timedelta::NANOS_PER_HOUR;
19540        let twelve_h = h * 12;
19541        let twelve_thirty_four =
19542            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19543        let ts = Timestamp::from_nanos(twelve_thirty_four);
19544        assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
19545        assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
19546        assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
19547        assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
19548        assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
19549    }
19550
19551    #[test]
19552    fn timestamp_ceil_to_unit_d_rounds_to_day() {
19553        // 12:34:56 → ceil to 1 day → 24:00:00 (next day).
19554        let h = Timedelta::NANOS_PER_HOUR;
19555        let d = Timedelta::NANOS_PER_DAY;
19556        let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
19557        let ts = Timestamp::from_nanos(twelve_thirty_four);
19558        assert_eq!(ts.ceil_to_unit("D").nanos, d);
19559        assert_eq!(ts.ceil_to_unit("day").nanos, d);
19560        assert_eq!(ts.ceil_to_unit("days").nanos, d);
19561    }
19562
19563    #[test]
19564    fn timestamp_round_to_unit_min_rounds_to_minute() {
19565        // 12:34:31 → round to 1 minute → 12:35:00.
19566        let m = Timedelta::NANOS_PER_MIN;
19567        let twelve_thirty_four_thirty_one =
19568            Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
19569        let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
19570        let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
19571        assert_eq!(ts.round_to_unit("min").nanos, expected);
19572        assert_eq!(ts.round_to_unit("T").nanos, expected); // pandas pre-2.2 alias
19573        assert_eq!(ts.round_to_unit("minute").nanos, expected);
19574    }
19575
19576    #[test]
19577    fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
19578        let ts = Timestamp::from_nanos(
19579            Timedelta::NANOS_PER_HOUR * 12
19580                + Timedelta::NANOS_PER_MIN * 34
19581                + Timedelta::NANOS_PER_SEC * 31,
19582        );
19583
19584        assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
19585        assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
19586        assert_eq!(ts.round("min"), ts.round_to_unit("min"));
19587    }
19588
19589    #[test]
19590    fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
19591        let ts = Timestamp::from_nanos_tz(
19592            Timedelta::NANOS_PER_DAY * 3
19593                + Timedelta::NANOS_PER_HOUR * 12
19594                + Timedelta::NANOS_PER_MIN * 34,
19595            "US/Eastern",
19596        );
19597        let normalized = ts.normalize();
19598
19599        assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
19600        assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
19601        assert!(Timestamp::nat().normalize().is_nat());
19602        for nanos in [
19603            i64::MIN + 1,
19604            -Timedelta::NANOS_PER_DAY - 1,
19605            -Timedelta::NANOS_PER_DAY,
19606            -1,
19607            0,
19608            Timedelta::NANOS_PER_DAY - 1,
19609            Timedelta::NANOS_PER_DAY,
19610            i64::MAX,
19611        ] {
19612            let timestamp = Timestamp::from_nanos(nanos);
19613            assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
19614        }
19615    }
19616
19617    #[test]
19618    #[ignore = "foreground profile-first A/B"]
19619    fn timestamp_normalize_direct_day_profile_dk721() {
19620        use std::{hint::black_box, time::Instant};
19621
19622        fn former(timestamp: &Timestamp) -> Timestamp {
19623            timestamp.floor_to_unit("D")
19624        }
19625
19626        fn candidate(timestamp: &Timestamp) -> Timestamp {
19627            timestamp.normalize()
19628        }
19629
19630        fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
19631            let started = Instant::now();
19632            let mut checksum = 0_u64;
19633            for timestamp in input {
19634                let normalized = normalize(black_box(timestamp));
19635                checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
19636            }
19637            black_box(checksum);
19638            started.elapsed().as_nanos()
19639        }
19640
19641        fn percentile(samples: &mut [u128], percent: usize) -> u128 {
19642            samples.sort_unstable();
19643            let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
19644            samples[rank]
19645        }
19646
19647        let parity_cases = [
19648            Timestamp::nat(),
19649            Timestamp::from_nanos(i64::MIN + 1),
19650            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
19651            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
19652            Timestamp::from_nanos(-1),
19653            Timestamp::from_nanos(0),
19654            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
19655            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
19656            Timestamp::from_nanos(i64::MAX),
19657            Timestamp::from_nanos_tz(-1, "US/Eastern"),
19658            Timestamp::from_nanos_tz(
19659                Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
19660                "Asia/Tokyo",
19661            ),
19662        ];
19663        for timestamp in &parity_cases {
19664            assert_eq!(former(timestamp), candidate(timestamp));
19665            assert_eq!(timestamp.normalize(), former(timestamp));
19666        }
19667
19668        const ROWS: usize = 16_384;
19669        const SAMPLES: usize = 20;
19670        let input = (0..ROWS)
19671            .map(|index| {
19672                let day = index as i64 % 4_096 - 2_048;
19673                let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
19674                    % Timedelta::NANOS_PER_DAY as u64) as i64;
19675                Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
19676            })
19677            .collect::<Vec<_>>();
19678        for timestamp in &input {
19679            assert_eq!(former(timestamp), candidate(timestamp));
19680        }
19681
19682        for _ in 0..3 {
19683            black_box(elapsed(&input, former));
19684            black_box(elapsed(&input, candidate));
19685        }
19686
19687        let mut former_ns = Vec::with_capacity(SAMPLES);
19688        let mut candidate_ns = Vec::with_capacity(SAMPLES);
19689        for sample in 0..SAMPLES {
19690            if sample % 2 == 0 {
19691                former_ns.push(elapsed(&input, former));
19692                candidate_ns.push(elapsed(&input, candidate));
19693            } else {
19694                candidate_ns.push(elapsed(&input, candidate));
19695                former_ns.push(elapsed(&input, former));
19696            }
19697        }
19698
19699        let mut former_sorted = former_ns.clone();
19700        let mut candidate_sorted = candidate_ns.clone();
19701        let former_p50 = percentile(&mut former_sorted, 50);
19702        let former_p95 = percentile(&mut former_sorted, 95);
19703        let former_p99 = percentile(&mut former_sorted, 99);
19704        let candidate_p50 = percentile(&mut candidate_sorted, 50);
19705        let candidate_p95 = percentile(&mut candidate_sorted, 95);
19706        let candidate_p99 = percentile(&mut candidate_sorted, 99);
19707        println!(
19708            "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:?}",
19709            former_p50 as f64 / candidate_p50 as f64,
19710            former_p95 as f64 / candidate_p95 as f64,
19711            former_p99 as f64 / candidate_p99 as f64,
19712        );
19713    }
19714
19715    #[test]
19716    fn timestamp_unit_rounding_unknown_unit_returns_nat() {
19717        let ts = Timestamp::from_nanos(100);
19718        assert!(ts.floor_to_unit("fortnight").is_nat());
19719        assert!(ts.ceil_to_unit("century").is_nat());
19720        assert!(ts.round_to_unit("xyz").is_nat());
19721    }
19722
19723    /// pd.Timestamp('2024-03-15 13:47:21').round('15min') is 13:45 (a
19724    /// multiple of a unit was unknown here: NaT).
19725    #[test]
19726    fn timestamp_rounding_reads_a_multiple_of_a_unit_3agof() {
19727        let (min, sec) = (Timedelta::NANOS_PER_MIN, Timedelta::NANOS_PER_SEC);
19728        let base = 1_710_460_800 * sec; // 2024-03-15 00:00:00
19729        let ts = Timestamp::from_nanos(base + 13 * Timedelta::NANOS_PER_HOUR + 47 * min + 21 * sec);
19730        let at = |minutes: i64, seconds: i64| base + minutes * min + seconds * sec;
19731        assert_eq!(ts.round("15min").nanos, at(13 * 60 + 45, 0));
19732        assert_eq!(ts.floor("15min").nanos, at(13 * 60 + 45, 0));
19733        assert_eq!(ts.ceil("15min").nanos, at(14 * 60, 0));
19734        assert_eq!(ts.round("30s").nanos, at(13 * 60 + 47, 30));
19735        assert_eq!(ts.ceil("1D").nanos, base + Timedelta::NANOS_PER_DAY);
19736        // 2024-03-15 is 19797 days after the epoch: the 7-day floor is day
19737        // 19796 (2024-03-14), as pandas'.
19738        assert_eq!(ts.floor("7D").nanos, 19_796 * Timedelta::NANOS_PER_DAY);
19739        // NEGATIVE: a calendar frequency is no fixed length.
19740        assert!(ts.round("ME").is_nat());
19741    }
19742
19743    #[test]
19744    fn timestamp_unit_rounding_propagates_nat() {
19745        let nat = Timestamp::nat();
19746        assert!(nat.floor_to_unit("H").is_nat());
19747        assert!(nat.ceil_to_unit("H").is_nat());
19748        assert!(nat.round_to_unit("H").is_nat());
19749    }
19750
19751    #[test]
19752    fn timestamp_unit_rounding_preserves_tz() {
19753        let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
19754        assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19755        assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19756        assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19757    }
19758
19759    #[test]
19760    fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
19761        // Public surface check: pandas alias core set.
19762        assert_eq!(
19763            Timedelta::unit_to_nanos("W"),
19764            Some(Timedelta::NANOS_PER_WEEK)
19765        );
19766        assert_eq!(
19767            Timedelta::unit_to_nanos("D"),
19768            Some(Timedelta::NANOS_PER_DAY)
19769        );
19770        assert_eq!(
19771            Timedelta::unit_to_nanos("H"),
19772            Some(Timedelta::NANOS_PER_HOUR)
19773        );
19774        assert_eq!(
19775            Timedelta::unit_to_nanos("min"),
19776            Some(Timedelta::NANOS_PER_MIN)
19777        );
19778        assert_eq!(
19779            Timedelta::unit_to_nanos("s"),
19780            Some(Timedelta::NANOS_PER_SEC)
19781        );
19782        assert_eq!(
19783            Timedelta::unit_to_nanos("ms"),
19784            Some(Timedelta::NANOS_PER_MILLI)
19785        );
19786        assert_eq!(
19787            Timedelta::unit_to_nanos("us"),
19788            Some(Timedelta::NANOS_PER_MICRO)
19789        );
19790        assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
19791        // Empty string → days (pandas default).
19792        assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
19793        // Unknown alias → None.
19794        assert_eq!(Timedelta::unit_to_nanos("century"), None);
19795    }
19796
19797    #[test]
19798    fn timestamp_isoformat_basic() {
19799        let ts = Timestamp::from_nanos(0);
19800        assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
19801
19802        let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
19803        assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
19804
19805        let ts_fixed_offset = Timestamp::from_nanos_tz(0, "UTC+05:30");
19806        assert_eq!(
19807            ts_fixed_offset.isoformat(),
19808            "1970-01-01T05:30:00+05:30",
19809            "a fixed-offset timestamp must render local wall time rather than a UTC instant with an annotation"
19810        );
19811
19812        let ts_tz = Timestamp::from_nanos_tz(
19813            Timedelta::NANOS_PER_DAY
19814                + Timedelta::NANOS_PER_HOUR * 14
19815                + Timedelta::NANOS_PER_MIN * 30,
19816            "America/New_York",
19817        );
19818        assert!(ts_tz.isoformat().contains("1970-01-02T14:30:00"));
19819        assert!(ts_tz.isoformat().contains("[America/New_York]"));
19820
19821        assert_eq!(Timestamp::nat().isoformat(), "NaT");
19822    }
19823
19824    #[test]
19825    fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
19826        assert_eq!(
19827            Timestamp::from_nanos(-1).isoformat(),
19828            "1969-12-31T23:59:59.999999999"
19829        );
19830        assert_eq!(
19831            Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
19832            "1969-12-31T23:59:59"
19833        );
19834        assert_eq!(
19835            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
19836            "1969-12-31T00:00:00"
19837        );
19838        assert_eq!(
19839            Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
19840            "1969-12-31T23:59:59.999999999+00:00"
19841        );
19842    }
19843
19844    #[test]
19845    fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
19846        assert_eq!(
19847            Timestamp::from_nanos(123_456_789).isoformat(),
19848            "1970-01-01T00:00:00.123456789"
19849        );
19850        assert_eq!(
19851            Timestamp::from_nanos(123_456_000).isoformat(),
19852            "1970-01-01T00:00:00.123456"
19853        );
19854        assert_eq!(
19855            Timestamp::from_nanos(123_000_000).isoformat(),
19856            "1970-01-01T00:00:00.123000"
19857        );
19858        assert_eq!(
19859            Timestamp::from_nanos_tz(1, "UTC").isoformat(),
19860            "1970-01-01T00:00:00.000000001+00:00"
19861        );
19862    }
19863
19864    fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
19865        if timestamp.is_nat() {
19866            return "NaT".to_owned();
19867        }
19868        let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
19869        match &timestamp.tz {
19870            Some(tz) if tz == "UTC" => format!("{base}+00:00"),
19871            Some(tz) => format!("{base}[{tz}]"),
19872            None => base,
19873        }
19874    }
19875
19876    #[test]
19877    fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
19878        let nanos = [
19879            Timestamp::NAT,
19880            -Timedelta::NANOS_PER_DAY - 1,
19881            -Timedelta::NANOS_PER_SEC,
19882            -1,
19883            0,
19884            1,
19885            123_456_000,
19886            123_456_789,
19887            i64::MAX,
19888        ];
19889        let timezones = [
19890            None,
19891            Some("UTC"),
19892            Some("America/New_York"),
19893            Some(""),
19894            Some("Etc/Γ"),
19895        ];
19896        for value in nanos {
19897            for timezone in timezones {
19898                let timestamp = Timestamp {
19899                    nanos: value,
19900                    tz: timezone.map(str::to_owned),
19901                };
19902                assert_eq!(
19903                    timestamp.isoformat(),
19904                    timestamp_isoformat_former_q8g50(&timestamp),
19905                    "nanos={value} timezone={timezone:?}"
19906                );
19907            }
19908        }
19909    }
19910
19911    #[test]
19912    #[ignore = "foreground release A/B only"]
19913    fn timestamp_isoformat_one_buffer_ab_q8g50() {
19914        use std::{hint::black_box, time::Instant};
19915
19916        const ITEMS: usize = 8_192;
19917        const SAMPLES: usize = 10;
19918
19919        fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
19920            let started = Instant::now();
19921            let mut checksum = 0usize;
19922            for timestamp in black_box(values) {
19923                checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
19924            }
19925            black_box(checksum);
19926            started.elapsed().as_nanos()
19927        }
19928
19929        let values = (0..ITEMS)
19930            .map(|idx| {
19931                let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
19932                let timezone = if idx.is_multiple_of(2) {
19933                    "UTC"
19934                } else {
19935                    "America/New_York"
19936                };
19937                Timestamp::from_nanos_tz(nanos, timezone)
19938            })
19939            .collect::<Vec<_>>();
19940        for timestamp in &values {
19941            assert_eq!(
19942                timestamp.isoformat(),
19943                timestamp_isoformat_former_q8g50(timestamp)
19944            );
19945        }
19946
19947        black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
19948        black_box(elapsed(&values, Timestamp::isoformat));
19949
19950        let mut former_ns = Vec::with_capacity(SAMPLES);
19951        let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
19952        for sample in 0..SAMPLES {
19953            if sample.is_multiple_of(2) {
19954                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
19955                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
19956            } else {
19957                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
19958                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
19959            }
19960        }
19961        former_ns.sort_unstable();
19962        one_buffer_ns.sort_unstable();
19963        let former_p50 = former_ns[SAMPLES / 2];
19964        let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
19965        println!(
19966            "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
19967            former_p50 as f64 / one_buffer_p50 as f64
19968        );
19969        println!("former_samples_ns={former_ns:?}");
19970        println!("one_buffer_samples_ns={one_buffer_ns:?}");
19971    }
19972
19973    #[test]
19974    fn timestamp_strftime_basic() {
19975        let ts = Timestamp::from_nanos(
19976            Timedelta::NANOS_PER_DAY * 365
19977                + Timedelta::NANOS_PER_HOUR * 9
19978                + Timedelta::NANOS_PER_MIN * 15,
19979        );
19980        assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
19981        assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
19982        assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
19983        // TEST-CHANGE: this pinned `%%Y` -> `%1971`; Python (CPython 3.13,
19984        // measured) prints `%%` as a literal `%` and echoes unknown `%Q`.
19985        assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%Y|%01|%Q|%|λ");
19986        assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
19987    }
19988
19989    #[test]
19990    fn strftime_follows_python_directives_and_zones() {
19991        // 1971-01-01 09:15 (a Friday; ISO week 53 of 1970). Expected texts
19992        // are CPython 3.13's datetime.strftime on Linux.
19993        let ts = Timestamp::from_nanos(
19994            Timedelta::NANOS_PER_DAY * 365
19995                + Timedelta::NANOS_PER_HOUR * 9
19996                + Timedelta::NANOS_PER_MIN * 15,
19997        );
19998        assert_eq!(
19999            ts.strftime("%-d %_m %^a %e %k %l %P %C %g %D %F %T %R %r %h %n %t|"),
20000            "1  1 FRI  1  9  9 am 19 70 01/01/71 1971-01-01 09:15:00 09:15 09:15:00 AM Jan \n \t|"
20001        );
20002        assert_eq!(
20003            ts.strftime("%a %A %b %B %c|%x %X|%I %p %j %U %W %w %y"),
20004            "Fri Friday Jan January Fri Jan  1 09:15:00 1971|01/01/71 09:15:00|09 AM 001 00 00 5 71"
20005        );
20006        // 2021-01-03: a Sunday, ISO 2020-W53-7.
20007        let sunday = Timestamp::parse("2021-01-03").expect("date");
20008        assert_eq!(sunday.strftime("%G-%V-%u %U %W %j"), "2020-53-7 01 00 003");
20009        // Microseconds only; a trailing lone percent stays; naive %z / %Z empty.
20010        let fraction = Timestamp::parse("2024-03-05 14:07:09.123456789").expect("ts");
20011        assert_eq!(fraction.strftime("%f|%z|%Z|abc%"), "123456|||abc%");
20012        // A tz-aware Timestamp prints its wall clock and zone.
20013        let eastern = Timestamp::from_nanos_tz(fraction.nanos, "US/Eastern");
20014        assert_eq!(
20015            eastern.strftime("%Y-%m-%d %H:%M %z %Z"),
20016            "2024-03-05 09:07 -0500 EST"
20017        );
20018        assert_eq!(
20019            crate::strftime_in_zone(fraction.nanos, "%H:%M %z", Some("+05:30")),
20020            "19:37 +0530"
20021        );
20022    }
20023
20024    #[test]
20025    fn timestamp_strftime_floors_pre_epoch_instants_1pmlp() {
20026        let apollo = Timestamp::parse("1969-07-20T20:17:40").unwrap();
20027        assert_eq!(
20028            apollo.strftime("%Y-%m-%d %H:%M:%S.%f"),
20029            "1969-07-20 20:17:40.000000"
20030        );
20031
20032        // The smallest negative instant catches both truncation defects:
20033        // second flooring and day flooring.
20034        let one_ns_before_epoch = Timestamp::from_nanos(-1);
20035        assert_eq!(
20036            one_ns_before_epoch.strftime("%Y-%m-%d %H:%M:%S.%f"),
20037            "1969-12-31 23:59:59.999999"
20038        );
20039    }
20040
20041    #[test]
20042    #[ignore = "foreground normal-release attribution harness"]
20043    fn timestamp_strftime_one_buffer_profile_8qzbo() {
20044        use std::{hint::black_box, time::Instant};
20045
20046        const ITEMS: usize = 8_192;
20047        const SAMPLES: usize = 10;
20048        const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
20049
20050        fn former(timestamp: &Timestamp, format: &str) -> String {
20051            if timestamp.is_nat() {
20052                return "NaT".to_string();
20053            }
20054            let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
20055            let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
20056
20057            let days_since_epoch = total_secs / 86400;
20058            let secs_of_day = (total_secs % 86400 + 86400) % 86400;
20059            let days = days_since_epoch + 719_468;
20060            let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
20061            let doe = days - era * 146_097;
20062            let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
20063            let y = yoe + era * 400;
20064            let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
20065            let mp = (5 * doy + 2) / 153;
20066            let d = doy - (153 * mp + 2) / 5 + 1;
20067            let m = if mp < 10 { mp + 3 } else { mp - 9 };
20068            let year = if m <= 2 { y + 1 } else { y };
20069            let hour = secs_of_day / 3600;
20070            let minute = (secs_of_day % 3600) / 60;
20071            let second = secs_of_day % 60;
20072            let micros = sub_nanos / 1000;
20073
20074            format
20075                .replace("%Y", &format!("{year:04}"))
20076                .replace("%m", &format!("{m:02}"))
20077                .replace("%d", &format!("{d:02}"))
20078                .replace("%H", &format!("{hour:02}"))
20079                .replace("%M", &format!("{minute:02}"))
20080                .replace("%S", &format!("{second:02}"))
20081                .replace("%f", &format!("{micros:06}"))
20082        }
20083
20084        fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
20085            let started = Instant::now();
20086            let mut digest = 0_usize;
20087            for timestamp in timestamps {
20088                let value = formatter(black_box(timestamp), black_box(FORMAT));
20089                digest = digest.wrapping_add(value.len());
20090                digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
20091                black_box(value);
20092            }
20093            black_box(digest);
20094            started.elapsed().as_nanos()
20095        }
20096
20097        fn percentile(samples: &mut [u128], pct: usize) -> u128 {
20098            samples.sort_unstable();
20099            let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
20100            samples[rank]
20101        }
20102
20103        let edge_timestamps = [
20104            Timestamp::nat(),
20105            Timestamp::from_nanos(i64::MIN + 1),
20106            Timestamp::from_nanos(-1_234_567_890),
20107            Timestamp::from_nanos(0),
20108            Timestamp::from_nanos(1_735_732_800_123_456_789),
20109            Timestamp::from_nanos(i64::MAX),
20110        ];
20111        let edge_formats = [
20112            "",
20113            "%Y-%m-%d %H:%M:%S.%f",
20114            "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
20115            "%%Y|%%%m|%Q|%|λ",
20116            FORMAT,
20117        ];
20118        for timestamp in &edge_timestamps {
20119            for format in edge_formats {
20120                assert_eq!(former(timestamp, format), timestamp.strftime(format));
20121            }
20122        }
20123
20124        let timestamps = (0..ITEMS)
20125            .map(|index| {
20126                let centered = index as i64 - ITEMS as i64 / 2;
20127                Timestamp::from_nanos(centered * 987_654_321_123_456)
20128            })
20129            .collect::<Vec<_>>();
20130        for timestamp in &timestamps {
20131            assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
20132        }
20133
20134        black_box(elapsed(&timestamps, former));
20135        black_box(elapsed(&timestamps, Timestamp::strftime));
20136
20137        let mut former_samples = Vec::with_capacity(SAMPLES);
20138        let mut public_samples = Vec::with_capacity(SAMPLES);
20139        for sample in 0..SAMPLES {
20140            if sample.is_multiple_of(2) {
20141                former_samples.push(elapsed(&timestamps, former));
20142                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
20143            } else {
20144                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
20145                former_samples.push(elapsed(&timestamps, former));
20146            }
20147        }
20148        let former_p50 = percentile(&mut former_samples, 50);
20149        let former_p95 = percentile(&mut former_samples, 95);
20150        let public_p50 = percentile(&mut public_samples, 50);
20151        let public_p95 = percentile(&mut public_samples, 95);
20152        println!(
20153            "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}",
20154            former_p50 as f64 / public_p50 as f64,
20155            former_p95 as f64 / public_p95 as f64,
20156        );
20157        println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
20158        println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
20159    }
20160
20161    #[test]
20162    fn timestamp_day_name_and_month_name() {
20163        let ts = Timestamp::from_nanos(0);
20164        assert_eq!(ts.day_name(), "Thursday");
20165        assert_eq!(ts.month_name(), "January");
20166
20167        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20168        assert_eq!(ts2.day_name(), "Friday");
20169        assert_eq!(ts2.month_name(), "January");
20170
20171        assert_eq!(Timestamp::nat().day_name(), "NaT");
20172        assert_eq!(Timestamp::nat().month_name(), "NaT");
20173    }
20174
20175    #[test]
20176    fn timestamp_replace_validates_components_zw0y2() {
20177        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20178        let replaced = ts.replace(
20179            Some(2024),
20180            Some(2),
20181            Some(29),
20182            Some(23),
20183            Some(59),
20184            Some(58),
20185            Some(987_654),
20186            Some(321),
20187        );
20188        assert_eq!(replaced.year(), Some(2024));
20189        assert_eq!(replaced.month(), Some(2));
20190        assert_eq!(replaced.day(), Some(29));
20191        assert_eq!(replaced.hour(), Some(23));
20192        assert_eq!(replaced.minute(), Some(59));
20193        assert_eq!(replaced.second(), Some(58));
20194        assert_eq!(replaced.microsecond(), Some(987_654));
20195        assert_eq!(replaced.nanosecond(), Some(321));
20196
20197        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20198        assert_eq!(
20199            tz.replace(None, Some(2), Some(29), None, None, None, None, None)
20200                .tz
20201                .as_deref(),
20202            Some("UTC")
20203        );
20204
20205        assert!(
20206            ts.replace(None, Some(13), None, None, None, None, None, None)
20207                .is_nat()
20208        );
20209        assert!(
20210            ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
20211                .is_nat()
20212        );
20213        assert!(
20214            ts.replace(None, None, None, Some(24), None, None, None, None)
20215                .is_nat()
20216        );
20217        assert!(
20218            ts.replace(None, None, None, None, Some(60), None, None, None)
20219                .is_nat()
20220        );
20221        assert!(
20222            ts.replace(None, None, None, None, None, Some(60), None, None)
20223                .is_nat()
20224        );
20225        assert!(
20226            ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
20227                .is_nat()
20228        );
20229        assert!(
20230            ts.replace(None, None, None, None, None, None, None, Some(1_000))
20231                .is_nat()
20232        );
20233        assert!(
20234            Timestamp::nat()
20235                .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
20236                .is_nat()
20237        );
20238    }
20239
20240    /// br-frankenpandas-dzz6x: `replace` validates every component EXCEPT the
20241    /// year, and i64 nanoseconds run out around year 2262. The old unchecked
20242    /// multiply wrapped in release mode and handed back a plausible-looking
20243    /// in-range instant for an unrepresentable year — the exact failure a naive
20244    /// implementation still produces, so each far-out year below is a real
20245    /// negative case, not a restatement of the code.
20246    #[test]
20247    fn timestamp_replace_returns_nat_on_nanosecond_overflow_dzz6x() {
20248        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20249
20250        for year in [3000, 10_000, 300_000, i64::MAX / 400] {
20251            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20252            assert!(
20253                out.is_nat(),
20254                "replace(year={year}) is unrepresentable in i64 ns and must be \
20255                 NaT, got nanos={:?} (year {:?}) — this is the silent wrap",
20256                out.nanos,
20257                out.year()
20258            );
20259        }
20260        for year in [-3000, -100_000, i64::MIN / 400] {
20261            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20262            assert!(out.is_nat(), "replace(year={year}) must be NaT");
20263        }
20264
20265        // Boundary: i64 ns tops out at 106_751 days from the epoch, so 2262 is
20266        // representable at the start of the year and 2263 is not. This pins the
20267        // fix to the real limit — a guard that merely rejected "big" years by
20268        // some rounder cutoff would fail one side of this pair.
20269        let in_range = ts.replace(
20270            Some(2262),
20271            Some(1),
20272            Some(1),
20273            Some(0),
20274            Some(0),
20275            Some(0),
20276            Some(0),
20277            Some(0),
20278        );
20279        assert!(
20280            !in_range.is_nat(),
20281            "2262-01-01 is representable and must survive"
20282        );
20283        assert_eq!(in_range.year(), Some(2262));
20284        assert!(
20285            ts.replace(
20286                Some(2263),
20287                Some(12),
20288                Some(31),
20289                Some(23),
20290                Some(59),
20291                Some(59),
20292                Some(999_999),
20293                Some(999)
20294            )
20295            .is_nat(),
20296            "end of 2263 exceeds the i64 ns axis and must be NaT"
20297        );
20298
20299        // In-range results are untouched by the checked arithmetic, including
20300        // the timezone, so the guard cannot have been bought with a behavior
20301        // change on the normal path.
20302        let unchanged = ts.replace(
20303            Some(1999),
20304            Some(6),
20305            Some(30),
20306            Some(12),
20307            Some(1),
20308            Some(2),
20309            Some(3),
20310            Some(4),
20311        );
20312        assert_eq!(unchanged.year(), Some(1999));
20313        assert_eq!(unchanged.month(), Some(6));
20314        assert_eq!(unchanged.day(), Some(30));
20315        assert_eq!(unchanged.hour(), Some(12));
20316        assert_eq!(unchanged.minute(), Some(1));
20317        assert_eq!(unchanged.second(), Some(2));
20318        assert_eq!(unchanged.microsecond(), Some(3));
20319        assert_eq!(unchanged.nanosecond(), Some(4));
20320        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20321        assert_eq!(
20322            tz.replace(Some(1999), None, None, None, None, None, None, None)
20323                .tz
20324                .as_deref(),
20325            Some("UTC")
20326        );
20327    }
20328
20329    #[test]
20330    fn timestamp_component_accessors() {
20331        let ts = Timestamp::from_nanos(0);
20332        assert_eq!(ts.year(), Some(1970));
20333        assert_eq!(ts.month(), Some(1));
20334        assert_eq!(ts.day(), Some(1));
20335        assert_eq!(ts.hour(), Some(0));
20336        assert_eq!(ts.minute(), Some(0));
20337        assert_eq!(ts.second(), Some(0));
20338        assert_eq!(ts.microsecond(), Some(0));
20339        assert_eq!(ts.nanosecond(), Some(0));
20340
20341        let ts2 = Timestamp::from_nanos(
20342            Timedelta::NANOS_PER_DAY * 365
20343                + Timedelta::NANOS_PER_HOUR * 14
20344                + Timedelta::NANOS_PER_MIN * 30
20345                + Timedelta::NANOS_PER_SEC * 45
20346                + 123_456_789,
20347        );
20348        assert_eq!(ts2.year(), Some(1971));
20349        assert_eq!(ts2.month(), Some(1));
20350        assert_eq!(ts2.day(), Some(1));
20351        assert_eq!(ts2.hour(), Some(14));
20352        assert_eq!(ts2.minute(), Some(30));
20353        assert_eq!(ts2.second(), Some(45));
20354        assert_eq!(ts2.microsecond(), Some(123456));
20355        assert_eq!(ts2.nanosecond(), Some(789));
20356
20357        assert_eq!(Timestamp::nat().year(), None);
20358        assert_eq!(Timestamp::nat().month(), None);
20359        assert_eq!(Timestamp::nat().day(), None);
20360    }
20361
20362    #[test]
20363    fn timestamp_dayofweek_dayofyear_quarter() {
20364        let ts = Timestamp::from_nanos(0);
20365        assert_eq!(ts.dayofweek(), Some(3));
20366        assert_eq!(ts.weekday(), Some(3));
20367        assert_eq!(ts.dayofyear(), Some(1));
20368        assert_eq!(ts.quarter(), Some(1));
20369
20370        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
20371        assert_eq!(ts2.quarter(), Some(2));
20372
20373        let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20374        assert_eq!(ts3.dayofyear(), Some(1));
20375        assert_eq!(ts3.dayofweek(), Some(4));
20376
20377        assert_eq!(Timestamp::nat().dayofweek(), None);
20378        assert_eq!(Timestamp::nat().dayofyear(), None);
20379        assert_eq!(Timestamp::nat().quarter(), None);
20380    }
20381
20382    #[test]
20383    fn timestamp_is_boundary_methods() {
20384        let jan1 = Timestamp::from_nanos(0);
20385        assert_eq!(jan1.is_leap_year(), Some(false));
20386        assert_eq!(jan1.is_month_start(), Some(true));
20387        assert_eq!(jan1.is_month_end(), Some(false));
20388        assert_eq!(jan1.is_quarter_start(), Some(true));
20389        assert_eq!(jan1.is_quarter_end(), Some(false));
20390        assert_eq!(jan1.is_year_start(), Some(true));
20391        assert_eq!(jan1.is_year_end(), Some(false));
20392
20393        let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
20394        assert_eq!(dec31.is_month_start(), Some(false));
20395        assert_eq!(dec31.is_month_end(), Some(true));
20396        assert_eq!(dec31.is_quarter_end(), Some(true));
20397        assert_eq!(dec31.is_year_end(), Some(true));
20398
20399        assert_eq!(Timestamp::nat().is_leap_year(), None);
20400        assert_eq!(Timestamp::nat().is_month_start(), None);
20401    }
20402
20403    #[test]
20404    fn timestamp_days_in_month() {
20405        let jan = Timestamp::from_nanos(0);
20406        assert_eq!(jan.days_in_month(), Some(31));
20407        assert_eq!(jan.daysinmonth(), Some(31));
20408
20409        let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
20410        assert_eq!(feb_non_leap.days_in_month(), Some(28));
20411
20412        assert_eq!(Timestamp::nat().days_in_month(), None);
20413    }
20414
20415    #[test]
20416    fn timestamp_weekofyear() {
20417        let jan1 = Timestamp::from_nanos(0);
20418        assert_eq!(jan1.weekofyear(), Some(1));
20419        assert_eq!(jan1.week(), Some(1));
20420
20421        let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
20422        assert_eq!(jan8.weekofyear(), Some(2));
20423
20424        assert_eq!(Timestamp::nat().weekofyear(), None);
20425        assert_eq!(Timestamp::nat().week(), None);
20426    }
20427
20428    #[test]
20429    fn timestamp_weekofyear_iso_53_week_boundaries() {
20430        // ISO-8601 53-week-year boundaries vs pandas 2.2.3 isocalendar().week.
20431        // (br-frankenpandas-xmfmd) Date -> nanos via days since 1970-01-01.
20432        fn week_of(date_days: i64) -> Option<i64> {
20433            Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
20434        }
20435        // Days from 1970-01-01 for each date (UTC, no tz).
20436        // 2021-01-01 -> week 53 (2020 is a 53-week year); FP used to give 52.
20437        assert_eq!(week_of(18_628), Some(53)); // 2021-01-01
20438        // 2016-01-01 -> week 53 (2015 is a 53-week year).
20439        assert_eq!(week_of(16_801), Some(53)); // 2016-01-01
20440        // 2026-12-31 -> week 53; FP used to give 1.
20441        assert_eq!(week_of(20_818), Some(53)); // 2026-12-31
20442        // 2020-12-31 -> week 53.
20443        assert_eq!(week_of(18_627), Some(53)); // 2020-12-31
20444        // Cases that must stay correct (non-53 boundaries):
20445        assert_eq!(week_of(19_358), Some(52)); // 2023-01-01 -> week 52
20446        assert_eq!(week_of(20_087), Some(1)); // 2024-12-30 -> week 1
20447        assert_eq!(week_of(18_260), Some(1)); // 2019-12-30 -> week 1
20448    }
20449
20450    #[test]
20451    fn iso_weeks_in_year_53_week_years() {
20452        use super::iso_weeks_in_year;
20453        // Known 53-week years; everything else is 52.
20454        for y in [2004, 2009, 2015, 2020, 2026] {
20455            assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
20456        }
20457        for y in [2018, 2019, 2021, 2022, 2023, 2024] {
20458            assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
20459        }
20460    }
20461
20462    #[test]
20463    fn timestamp_to_unit() {
20464        let ts = Timestamp::from_nanos(1_000_000_000);
20465        assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
20466        assert_eq!(ts.to_unit("us"), Some(1_000_000));
20467        assert_eq!(ts.to_unit("ms"), Some(1_000));
20468        assert_eq!(ts.to_unit("s"), Some(1));
20469        assert_eq!(ts.to_unit("invalid"), None);
20470
20471        assert_eq!(Timestamp::nat().to_unit("ns"), None);
20472    }
20473
20474    #[test]
20475    fn timestamp_toordinal() {
20476        // 2026-01-01 is ordinal 738886 (days since Jan 1, year 1)
20477        // Days from Unix epoch: 738886 - 719163 = 19723
20478        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
20479        let ts = Timestamp::from_nanos(nanos_2026_01_01);
20480        assert_eq!(ts.toordinal(), Some(738886));
20481
20482        // NaT returns None
20483        assert_eq!(Timestamp::nat().toordinal(), None);
20484    }
20485
20486    #[test]
20487    fn timestamp_fromordinal() {
20488        // Round-trip test: create a timestamp from ordinal derived from toordinal
20489        // First create a known timestamp
20490        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
20491        let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
20492        let ordinal = ts_orig.toordinal().unwrap();
20493
20494        // Now convert back using fromordinal
20495        let ts = Timestamp::fromordinal(ordinal);
20496        assert_eq!(ts.year(), ts_orig.year());
20497        assert_eq!(ts.month(), ts_orig.month());
20498        assert_eq!(ts.day(), ts_orig.day());
20499
20500        // Invalid ordinal returns NaT
20501        let nat = Timestamp::fromordinal(0);
20502        assert!(nat.is_nat());
20503    }
20504
20505    #[test]
20506    fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
20507        const EPOCH_ORDINAL: i64 = 719_163;
20508        let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
20509        let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
20510
20511        let max_valid = Timestamp::fromordinal(max_valid_ordinal);
20512        assert!(!max_valid.is_nat());
20513        assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
20514
20515        assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
20516        assert!(Timestamp::fromordinal(i64::MAX).is_nat());
20517    }
20518
20519    #[test]
20520    fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
20521        const EPOCH_ORDINAL: i64 = 719_163;
20522        const DAY: i64 = Timedelta::NANOS_PER_DAY;
20523
20524        fn next(seed: &mut u64) -> u64 {
20525            *seed = seed
20526                .wrapping_mul(3202034522624059733)
20527                .wrapping_add(4354685564936845319);
20528            *seed
20529        }
20530
20531        fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
20532            let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
20533            let ts = Timestamp::from_nanos(nanos);
20534            let expected_day_offset = nanos.div_euclid(DAY);
20535            let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
20536
20537            assert_eq!(
20538                ts.toordinal(),
20539                Some(expected_ordinal),
20540                "case {case}: toordinal"
20541            );
20542
20543            let midnight = Timestamp::fromordinal(expected_ordinal);
20544            assert_eq!(
20545                midnight.nanos,
20546                expected_day_offset * DAY,
20547                "case {case}: fromordinal nanos"
20548            );
20549            assert_eq!(
20550                midnight.toordinal(),
20551                Some(expected_ordinal),
20552                "case {case}: fromordinal roundtrip"
20553            );
20554        }
20555
20556        assert_eq!(Timestamp::nat().toordinal(), None);
20557        assert!(Timestamp::fromordinal(0).is_nat());
20558        assert!(Timestamp::fromordinal(-1).is_nat());
20559
20560        assert_ordinal_case(usize::MAX, -1, DAY - 1);
20561        assert_ordinal_case(usize::MAX - 1, 0, -1);
20562        assert_ordinal_case(usize::MAX - 2, 19_723, 0);
20563
20564        let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
20565        for case in 0..260 {
20566            let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
20567            let subday_nanos = match case % 7 {
20568                0 => 0,
20569                1 => DAY - 1,
20570                2 => -1,
20571                _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
20572            };
20573            assert_ordinal_case(case, day_offset, subday_nanos);
20574        }
20575    }
20576
20577    /// br-frankenpandas-94o1u: `parse_date` bounds the month and the day but
20578    /// parses the YEAR as an unbounded i64, and i64 nanoseconds top out around
20579    /// 2262. The old unchecked composition wrapped in release, so these inputs
20580    /// returned `Ok` holding a plausible in-range instant instead of failing —
20581    /// on the INGESTION path, where the input is untrusted. Each case below is
20582    /// a real negative case: a naive implementation still returns Ok here.
20583    #[test]
20584    fn timestamp_parse_rejects_unrepresentable_years_94o1u() {
20585        for s in [
20586            "300000-01-01",
20587            "10000000-06-15T12:30:45",
20588            "999999999-01-01",
20589            "-300000-01-01",
20590            "-99999999-12-31T23:59:59",
20591        ] {
20592            let got = Timestamp::parse(s);
20593            assert!(
20594                got.is_err(),
20595                "parse({s:?}) is unrepresentable in i64 ns and must be Err, got {:?} \
20596                 — this is the silent wrap",
20597                got.map(|ts| (ts.nanos, ts.year()))
20598            );
20599        }
20600
20601        // Boundary: the i64 ns axis reaches into 2262 but not 2263. Pins the
20602        // guard to the real limit — a cutoff at some rounder year fails a side.
20603        let ok = Timestamp::parse("2262-01-01").expect("2262-01-01 is representable");
20604        assert_eq!(ok.year(), Some(2262));
20605        assert!(
20606            Timestamp::parse("2263-12-31T23:59:59").is_err(),
20607            "end of 2263 exceeds the i64 ns axis and must be Err"
20608        );
20609
20610        // A rejected year must not poison the normal path: ordinary parses,
20611        // including every accepted shape (date-only, T- and space-separated,
20612        // fractional seconds, tz suffix), still succeed and are unchanged.
20613        assert_eq!(Timestamp::parse("2024-01-15").unwrap().year(), Some(2024));
20614        assert_eq!(
20615            Timestamp::parse("2024-01-15T10:30:45").unwrap().hour(),
20616            Some(10)
20617        );
20618        assert_eq!(
20619            Timestamp::parse("2024-01-15 10:30:45").unwrap().minute(),
20620            Some(30)
20621        );
20622        assert_eq!(
20623            Timestamp::parse("2024-01-15T10:30:45.123456789")
20624                .unwrap()
20625                .nanosecond(),
20626            Some(789)
20627        );
20628        assert_eq!(
20629            Timestamp::parse("2024-01-15T00:00:00Z").unwrap().year(),
20630            Some(2024)
20631        );
20632        // Pre-epoch (negative nanos) is representable and must keep working.
20633        assert_eq!(Timestamp::parse("1900-01-01").unwrap().year(), Some(1900));
20634    }
20635
20636    #[test]
20637    fn timestamp_parse_iso8601_date_only() {
20638        let ts = Timestamp::parse("2024-01-15").unwrap();
20639        assert_eq!(ts.year(), Some(2024));
20640        assert_eq!(ts.month(), Some(1));
20641        assert_eq!(ts.day(), Some(15));
20642        assert_eq!(ts.hour(), Some(0));
20643        assert_eq!(ts.minute(), Some(0));
20644        assert_eq!(ts.second(), Some(0));
20645    }
20646
20647    #[test]
20648    fn timestamp_parse_iso8601_datetime() {
20649        let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
20650        assert_eq!(ts.year(), Some(2024));
20651        assert_eq!(ts.month(), Some(1));
20652        assert_eq!(ts.day(), Some(15));
20653        assert_eq!(ts.hour(), Some(10));
20654        assert_eq!(ts.minute(), Some(30));
20655        assert_eq!(ts.second(), Some(45));
20656    }
20657
20658    #[test]
20659    fn timestamp_parse_space_separator() {
20660        let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
20661        assert_eq!(ts.year(), Some(2024));
20662        assert_eq!(ts.hour(), Some(10));
20663    }
20664
20665    #[test]
20666    fn timestamp_parse_with_fractional_seconds() {
20667        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20668        assert_eq!(ts.second(), Some(45));
20669        assert_eq!(ts.microsecond(), Some(123456));
20670        assert_eq!(ts.nanosecond(), Some(789));
20671    }
20672
20673    #[test]
20674    fn timestamp_parse_utc_timezone() {
20675        let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
20676        assert_eq!(ts.tz, Some("UTC".to_string()));
20677    }
20678
20679    #[test]
20680    fn timestamp_parse_offset_timezone() {
20681        let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
20682        assert_eq!(ts.tz, Some("+05:30".to_string()));
20683        // The instant is the wall time less the offset (it was the wall
20684        // time read as UTC).
20685        let utc = |text: &str| Timestamp::parse(text).unwrap().nanos;
20686        assert_eq!(ts.nanos, utc("2024-01-15T05:00:45"));
20687
20688        let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
20689        assert_eq!(ts.tz, Some("-05:30".to_string()));
20690        assert_eq!(ts.nanos, utc("2024-01-15T16:00:45"));
20691        // 'Z' is UTC itself.
20692        assert_eq!(
20693            Timestamp::parse("2024-01-15T10:30:45Z").unwrap().nanos,
20694            utc("2024-01-15T10:30:45")
20695        );
20696    }
20697
20698    #[test]
20699    fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
20700        assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
20701        assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
20702        assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
20703        assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
20704        assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
20705    }
20706
20707    #[test]
20708    fn timestamp_parse_nat() {
20709        let ts = Timestamp::parse("NaT").unwrap();
20710        assert!(ts.is_nat());
20711        let ts2 = Timestamp::parse("nat").unwrap();
20712        assert!(ts2.is_nat());
20713    }
20714
20715    #[test]
20716    fn timestamp_parse_invalid() {
20717        assert!(Timestamp::parse("not a date").is_err());
20718        assert!(Timestamp::parse("2024-13-01").is_err()); // invalid month
20719        assert!(Timestamp::parse("2024-01-32").is_err()); // invalid day
20720    }
20721
20722    #[test]
20723    fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
20724        assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
20725        assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
20726        assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
20727        assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
20728        assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
20729
20730        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
20731        assert_eq!(ts.second(), Some(45));
20732        assert_eq!(ts.microsecond(), Some(123456));
20733        assert_eq!(ts.nanosecond(), Some(789));
20734    }
20735
20736    #[test]
20737    #[ignore = "foreground profile-first A/B"]
20738    fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
20739        use std::{hint::black_box, time::Instant};
20740
20741        const CALLS: usize = 131_072;
20742        const SAMPLES: usize = 12;
20743        type ParsedTime = Option<(u32, u32, u32, u64)>;
20744        const VALID: [&str; 16] = [
20745            "00:00:00.0",
20746            "01:02:03.1",
20747            "02:03:04.01",
20748            "03:04:05.001",
20749            "04:05:06.0001",
20750            "05:06:07.00001",
20751            "06:07:08.000001",
20752            "07:08:09.0000001",
20753            "08:09:10.00000001",
20754            "09:10:11.000000001",
20755            "10:11:12.123456789",
20756            "11:12:13.999999999",
20757            "12:13:14.123456789987",
20758            "13:14:15.000000000001",
20759            "14:15:16.101010101010",
20760            "23:59:59.987654321234",
20761        ];
20762
20763        #[inline(never)]
20764        fn former(s: &str) -> ParsedTime {
20765            let (time_str, frac_str) = match s.split_once('.') {
20766                Some((time, frac)) => (time, Some(frac)),
20767                None => (s, None),
20768            };
20769            let parts: Vec<&str> = time_str.split(':').collect();
20770            if parts.is_empty() || parts.len() > 3 {
20771                return None;
20772            }
20773            let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
20774            let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
20775            let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
20776
20777            if hour > 23 || minute > 59 || second > 59 {
20778                return None;
20779            }
20780
20781            let nanos = match frac_str {
20782                None => 0,
20783                Some(frac) => {
20784                    if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
20785                        return None;
20786                    }
20787                    let truncated = &frac[..frac.len().min(9)];
20788                    let padded = format!("{truncated:0<9}");
20789                    padded.parse::<u64>().ok()?
20790                }
20791            };
20792
20793            Some((hour, minute, second, nanos))
20794        }
20795
20796        #[inline(never)]
20797        fn candidate(s: &str) -> ParsedTime {
20798            Timestamp::parse_time(s)
20799        }
20800
20801        fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
20802            let started = Instant::now();
20803            for input in black_box(inputs) {
20804                black_box(parser(black_box(*input)));
20805            }
20806            started.elapsed().as_nanos()
20807        }
20808
20809        fn percentile(samples: &[u128], percent: usize) -> u128 {
20810            let mut sorted = samples.to_vec();
20811            sorted.sort_unstable();
20812            let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
20813            sorted[rank]
20814        }
20815
20816        let invalid = [
20817            "",
20818            "24:00:00.1",
20819            "12:60:00.1",
20820            "12:00:60.1",
20821            "12:00:00.",
20822            "12:00:00.abc",
20823            "12:00:00.-1",
20824            "12:00:00.123",
20825            "12:00:00.123456789x",
20826            "12:00:00.1.2",
20827            "12:00:00:01.1",
20828        ];
20829        for input in VALID.iter().chain(invalid.iter()) {
20830            assert_eq!(candidate(input), former(input), "input={input:?}");
20831        }
20832
20833        let inputs = (0..CALLS)
20834            .map(|index| VALID[index % VALID.len()])
20835            .collect::<Vec<_>>();
20836        for _ in 0..2 {
20837            black_box(elapsed(&inputs, former));
20838            black_box(elapsed(&inputs, candidate));
20839        }
20840
20841        let mut former_ns = Vec::with_capacity(SAMPLES);
20842        let mut candidate_ns = Vec::with_capacity(SAMPLES);
20843        for sample in 0..SAMPLES {
20844            if sample.is_multiple_of(2) {
20845                former_ns.push(elapsed(&inputs, former));
20846                candidate_ns.push(elapsed(&inputs, candidate));
20847            } else {
20848                candidate_ns.push(elapsed(&inputs, candidate));
20849                former_ns.push(elapsed(&inputs, former));
20850            }
20851        }
20852
20853        let former_p50 = percentile(&former_ns, 50);
20854        let former_p95 = percentile(&former_ns, 95);
20855        let former_p99 = percentile(&former_ns, 99);
20856        let candidate_p50 = percentile(&candidate_ns, 50);
20857        let candidate_p95 = percentile(&candidate_ns, 95);
20858        let candidate_p99 = percentile(&candidate_ns, 99);
20859        println!(
20860            "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:?}",
20861            former_p50 as f64 / candidate_p50 as f64,
20862            former_p95 as f64 / candidate_p95 as f64,
20863            former_p99 as f64 / candidate_p99 as f64,
20864        );
20865    }
20866
20867    #[test]
20868    fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
20869        fn next(seed: &mut u64) -> u64 {
20870            *seed = seed
20871                .wrapping_mul(3935559000370003845)
20872                .wrapping_add(2691343689449507681);
20873            *seed
20874        }
20875
20876        fn leap(year: i64) -> bool {
20877            (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
20878        }
20879
20880        fn month_len(year: i64, month: u32) -> u32 {
20881            match month {
20882                1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
20883                4 | 6 | 9 | 11 => 30,
20884                2 if leap(year) => 29,
20885                2 => 28,
20886                _ => 0,
20887            }
20888        }
20889
20890        struct Components {
20891            year: i64,
20892            month: u32,
20893            day: u32,
20894            hour: u32,
20895            minute: u32,
20896            second: u32,
20897            nanos: u64,
20898        }
20899
20900        fn assert_components(case: usize, text: &str, expected: Components) {
20901            let ts = Timestamp::parse(text).expect("seeded valid timestamp");
20902            let Components {
20903                year,
20904                month,
20905                day,
20906                hour,
20907                minute,
20908                second,
20909                nanos,
20910            } = expected;
20911            assert_eq!(ts.year(), Some(year), "case {case}: year");
20912            assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
20913            assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
20914            assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
20915            assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
20916            assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
20917            assert_eq!(
20918                ts.microsecond(),
20919                Some((nanos / 1000) as i64),
20920                "case {case}: microsecond"
20921            );
20922            assert_eq!(
20923                ts.nanosecond(),
20924                Some((nanos % 1000) as i64),
20925                "case {case}: nanosecond"
20926            );
20927        }
20928
20929        assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
20930        assert!(
20931            Timestamp::parse("nAt")
20932                .expect("mixed-case NaT parses")
20933                .is_nat()
20934        );
20935        assert!(Timestamp::parse("1900-02-29").is_err());
20936        assert!(Timestamp::parse("2001-04-31").is_err());
20937        assert!(Timestamp::parse("2024-00-15").is_err());
20938
20939        assert_components(
20940            usize::MAX,
20941            "2000-02-29",
20942            Components {
20943                year: 2000,
20944                month: 2,
20945                day: 29,
20946                hour: 0,
20947                minute: 0,
20948                second: 0,
20949                nanos: 0,
20950            },
20951        );
20952        assert_components(
20953            usize::MAX - 1,
20954            "2024-02-29T23:59:59.000000001",
20955            Components {
20956                year: 2024,
20957                month: 2,
20958                day: 29,
20959                hour: 23,
20960                minute: 59,
20961                second: 59,
20962                nanos: 1,
20963            },
20964        );
20965
20966        let mut seed = 0x15e0_1d50_1f0a_cade_u64;
20967        for case in 0..260 {
20968            let year = 1900 + (next(&mut seed) % 201) as i64;
20969            let month = 1 + (next(&mut seed) % 12) as u32;
20970            let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
20971            let hour = (next(&mut seed) % 24) as u32;
20972            let minute = (next(&mut seed) % 60) as u32;
20973            let second = (next(&mut seed) % 60) as u32;
20974            let nanos = next(&mut seed) % 1_000_000_000;
20975
20976            match case % 4 {
20977                0 => {
20978                    let text = format!("{year:04}-{month:02}-{day:02}");
20979                    assert_components(
20980                        case,
20981                        &text,
20982                        Components {
20983                            year,
20984                            month,
20985                            day,
20986                            hour: 0,
20987                            minute: 0,
20988                            second: 0,
20989                            nanos: 0,
20990                        },
20991                    );
20992                }
20993                1 => {
20994                    let text =
20995                        format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
20996                    assert_components(
20997                        case,
20998                        &text,
20999                        Components {
21000                            year,
21001                            month,
21002                            day,
21003                            hour,
21004                            minute,
21005                            second,
21006                            nanos: 0,
21007                        },
21008                    );
21009                }
21010                2 => {
21011                    let text =
21012                        format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
21013                    assert_components(
21014                        case,
21015                        &text,
21016                        Components {
21017                            year,
21018                            month,
21019                            day,
21020                            hour,
21021                            minute,
21022                            second,
21023                            nanos: 0,
21024                        },
21025                    );
21026                }
21027                _ => {
21028                    let text = format!(
21029                        "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
21030                    );
21031                    assert_components(
21032                        case,
21033                        &text,
21034                        Components {
21035                            year,
21036                            month,
21037                            day,
21038                            hour,
21039                            minute,
21040                            second,
21041                            nanos,
21042                        },
21043                    );
21044                }
21045            }
21046        }
21047    }
21048
21049    #[test]
21050    fn period_parse_annual() {
21051        let p = Period::parse("2024").unwrap();
21052        assert_eq!(p.freq(), PeriodFreq::Annual);
21053        assert_eq!(p.ordinal(), 2024 - 1970);
21054    }
21055
21056    #[test]
21057    fn period_parse_quarterly() {
21058        let p = Period::parse("2024Q1").unwrap();
21059        assert_eq!(p.freq(), PeriodFreq::Quarterly);
21060        assert_eq!(p.ordinal(), (2024 - 1970) * 4);
21061
21062        let p2 = Period::parse("2024q3").unwrap();
21063        assert_eq!(p2.freq(), PeriodFreq::Quarterly);
21064        assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
21065    }
21066
21067    #[test]
21068    fn period_parse_monthly() {
21069        let p = Period::parse("2024-01").unwrap();
21070        assert_eq!(p.freq(), PeriodFreq::Monthly);
21071        assert_eq!(p.ordinal(), (2024 - 1970) * 12);
21072
21073        let p2 = Period::parse("2024-12").unwrap();
21074        assert_eq!(p2.freq(), PeriodFreq::Monthly);
21075        assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
21076    }
21077
21078    #[test]
21079    fn period_parse_nat() {
21080        let p = Period::parse("NaT").unwrap();
21081        assert_eq!(p.ordinal(), i64::MIN);
21082    }
21083
21084    #[test]
21085    fn period_parse_invalid() {
21086        assert!(Period::parse("not a period").is_err());
21087        assert!(Period::parse("2024Q5").is_err()); // invalid quarter
21088        assert!(Period::parse("2024-13").is_err()); // invalid month
21089    }
21090
21091    #[test]
21092    fn interval_parse_basic() {
21093        let i = Interval::parse("[0, 1]").unwrap();
21094        assert_eq!(i.left, 0.0);
21095        assert_eq!(i.right, 1.0);
21096        assert_eq!(i.closed, IntervalClosed::Both);
21097
21098        let i2 = Interval::parse("(0, 1)").unwrap();
21099        assert_eq!(i2.left, 0.0);
21100        assert_eq!(i2.right, 1.0);
21101        assert_eq!(i2.closed, IntervalClosed::Neither);
21102
21103        let i3 = Interval::parse("[0, 1)").unwrap();
21104        assert_eq!(i3.closed, IntervalClosed::Left);
21105
21106        let i4 = Interval::parse("(0, 1]").unwrap();
21107        assert_eq!(i4.closed, IntervalClosed::Right);
21108    }
21109
21110    #[test]
21111    fn interval_parse_floats() {
21112        let i = Interval::parse("[-1.5, 2.5)").unwrap();
21113        assert_eq!(i.left, -1.5);
21114        assert_eq!(i.right, 2.5);
21115        assert_eq!(i.closed, IntervalClosed::Left);
21116    }
21117
21118    #[test]
21119    fn interval_parse_invalid() {
21120        assert!(Interval::parse("invalid").is_err());
21121        assert!(Interval::parse("[0]").is_err());
21122        assert!(Interval::parse("0, 1").is_err()); // missing brackets
21123    }
21124
21125    fn interval_parse_error_profile(s: &str) -> super::TypeError {
21126        super::TypeError::ValueNotParseable {
21127            value: s.to_string(),
21128            target: "Interval".to_string(),
21129        }
21130    }
21131
21132    #[inline(never)]
21133    fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
21134        let s = std::hint::black_box(s).trim();
21135        if s.len() < 5 {
21136            return Err(interval_parse_error_profile(s));
21137        }
21138
21139        let first_char = s.chars().next().unwrap();
21140        let last_char = s.chars().last().unwrap();
21141        let left_closed = match first_char {
21142            '[' => true,
21143            '(' => false,
21144            _ => return Err(interval_parse_error_profile(s)),
21145        };
21146        let right_closed = match last_char {
21147            ']' => true,
21148            ')' => false,
21149            _ => return Err(interval_parse_error_profile(s)),
21150        };
21151        let closed = match (left_closed, right_closed) {
21152            (true, true) => IntervalClosed::Both,
21153            (true, false) => IntervalClosed::Left,
21154            (false, true) => IntervalClosed::Right,
21155            (false, false) => IntervalClosed::Neither,
21156        };
21157
21158        let inner = &s[1..s.len() - 1];
21159        let parts: Vec<&str> = inner.split(',').collect();
21160        if parts.len() != 2 {
21161            return Err(interval_parse_error_profile(s));
21162        }
21163        let left = parts[0]
21164            .trim()
21165            .parse()
21166            .map_err(|_| interval_parse_error_profile(s))?;
21167        let right = parts[1]
21168            .trim()
21169            .parse()
21170            .map_err(|_| interval_parse_error_profile(s))?;
21171        Ok(Interval::new(left, right, closed))
21172    }
21173
21174    #[inline(never)]
21175    fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
21176        Interval::parse(std::hint::black_box(s))
21177    }
21178
21179    fn assert_interval_parse_profile_parity(s: &str) {
21180        match (
21181            interval_parse_former_profile(s),
21182            interval_parse_split_once_profile(s),
21183        ) {
21184            (Ok(former), Ok(candidate)) => {
21185                assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
21186                assert_eq!(
21187                    former.right.to_bits(),
21188                    candidate.right.to_bits(),
21189                    "right: {s}"
21190                );
21191                assert_eq!(former.closed, candidate.closed, "closed: {s}");
21192            }
21193            (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
21194            (former, candidate) => assert_eq!(
21195                former.is_ok(),
21196                candidate.is_ok(),
21197                "parse result mismatch for {s}: {former:?} != {candidate:?}"
21198            ),
21199        }
21200    }
21201
21202    #[inline(never)]
21203    fn measure_interval_parser_profile(
21204        parser: fn(&str) -> Result<Interval, super::TypeError>,
21205        inputs: &[&str],
21206        rounds: usize,
21207    ) -> u128 {
21208        use std::{hint::black_box, time::Instant};
21209
21210        let started = Instant::now();
21211        let mut checksum = 0_u64;
21212        for _ in 0..rounds {
21213            for input in inputs {
21214                let parsed = parser(black_box(input)).expect("profile input must parse");
21215                let closed = match parsed.closed {
21216                    IntervalClosed::Left => 1_u64,
21217                    IntervalClosed::Right => 2,
21218                    IntervalClosed::Both => 3,
21219                    IntervalClosed::Neither => 4,
21220                };
21221                checksum = checksum
21222                    .wrapping_add(parsed.left.to_bits().rotate_left(7))
21223                    .wrapping_add(parsed.right.to_bits().rotate_right(11))
21224                    .wrapping_add(closed);
21225                black_box(parsed);
21226            }
21227        }
21228        black_box(checksum);
21229        started.elapsed().as_nanos()
21230    }
21231
21232    #[test]
21233    #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
21234    fn profile_interval_parse_endpoint_split_ab_81jjv() {
21235        const VALID: [&str; 8] = [
21236            "[0, 1]",
21237            "(-0.0, 0.0]",
21238            " [ -1.5e3 , 2.75E-4 ) ",
21239            "(NaN, -0]",
21240            "[-inf, inf)",
21241            "[9.25, -7.5]",
21242            "(4.9406564584124654e-324, 1.7976931348623157e308)",
21243            "[-42, 17.125)",
21244        ];
21245        const INVALID: [&str; 12] = [
21246            "invalid",
21247            "[0]",
21248            "0, 1",
21249            "[0 1]",
21250            "[0, 1, 2]",
21251            "[0, 1,]",
21252            "[0,,1]",
21253            "[, 1]",
21254            "[0, ]",
21255            "{0, 1}",
21256            "[0, 1}",
21257            "  ⟦0, 1⟧  ",
21258        ];
21259        const ROUNDS: usize = 16_384;
21260        const SAMPLES: usize = 10;
21261
21262        for input in VALID.iter().chain(INVALID.iter()) {
21263            assert_interval_parse_profile_parity(input);
21264        }
21265        for _ in 0..2 {
21266            measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
21267            measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
21268        }
21269
21270        let mut former_ns = Vec::with_capacity(SAMPLES);
21271        let mut candidate_ns = Vec::with_capacity(SAMPLES);
21272        for sample in 0..SAMPLES {
21273            if sample % 2 == 0 {
21274                former_ns.push(measure_interval_parser_profile(
21275                    interval_parse_former_profile,
21276                    &VALID,
21277                    ROUNDS,
21278                ));
21279                candidate_ns.push(measure_interval_parser_profile(
21280                    interval_parse_split_once_profile,
21281                    &VALID,
21282                    ROUNDS,
21283                ));
21284            } else {
21285                candidate_ns.push(measure_interval_parser_profile(
21286                    interval_parse_split_once_profile,
21287                    &VALID,
21288                    ROUNDS,
21289                ));
21290                former_ns.push(measure_interval_parser_profile(
21291                    interval_parse_former_profile,
21292                    &VALID,
21293                    ROUNDS,
21294                ));
21295            }
21296        }
21297        former_ns.sort_unstable();
21298        candidate_ns.sort_unstable();
21299        let former_p50 = former_ns[SAMPLES / 2];
21300        let candidate_p50 = candidate_ns[SAMPLES / 2];
21301        let former_p95 = former_ns[SAMPLES - 1];
21302        let candidate_p95 = candidate_ns[SAMPLES - 1];
21303        println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
21304        println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
21305        println!(
21306            "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
21307            former_p50 as f64 / candidate_p50 as f64
21308        );
21309        println!(
21310            "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
21311            former_p95 as f64 / candidate_p95 as f64
21312        );
21313    }
21314}
21315
21316/// `DType::Float64Nullable` — pandas' `Float64Dtype()`, the dtype a nullable
21317/// Int64 lane widens INTO (br-frankenpandas-qkqfb).
21318///
21319/// Every rule asserted here was measured against live pandas 2.2.3 before it was
21320/// written; the measurement is quoted next to the assertion it justifies.
21321#[cfg(test)]
21322mod float64_nullable_qkqfb {
21323    use super::{DType, NullKind, Scalar, cast_scalar, common_dtype};
21324
21325    /// THE POINT OF THE DTYPE. A numpy float lane's missing value is a real NaN;
21326    /// the extension lane's is pd.NA. If both mapped to the same marker the two
21327    /// flavours would be indistinguishable and the dtype would buy nothing.
21328    ///
21329    /// MEASURED, live pandas 2.2.3:
21330    /// ```text
21331    ///   pd.Series([1.5, None], dtype="Float64")[1]     -> <NA>   (is pd.NA)
21332    ///   pd.Series([1.5, None])[1]                      -> nan
21333    ///   pd.Series([float("nan")], dtype="Float64")[0]  -> <NA>   COERCED
21334    /// ```
21335    #[test]
21336    fn the_two_float_flavours_have_different_missing_markers_qkqfb() {
21337        assert_eq!(
21338            Scalar::missing_for_dtype(DType::Float64Nullable),
21339            Scalar::Null(NullKind::Null),
21340            "the extension lane stores pd.NA"
21341        );
21342        assert_eq!(
21343            Scalar::missing_for_dtype(DType::Float64),
21344            Scalar::Null(NullKind::NaN),
21345            "the numpy lane stores a real NaN"
21346        );
21347        // The negative case: collapsing these two is precisely the defect, so
21348        // assert they are NOT equal rather than only asserting each value.
21349        assert_ne!(
21350            Scalar::missing_for_dtype(DType::Float64Nullable),
21351            Scalar::missing_for_dtype(DType::Float64),
21352        );
21353    }
21354
21355    /// MEASURED: `str(pd.Float64Dtype())` is `"Float64"`, and the numpy dtype is
21356    /// `"float64"`. dtype-check fixtures assert pandas' SPELLING
21357    /// (br-frankenpandas-62d1s), so the capital F is load-bearing, not cosmetic.
21358    #[test]
21359    fn spelling_is_pandas_spelling_qkqfb() {
21360        assert_eq!(DType::Float64Nullable.name(), "Float64");
21361        assert_eq!(DType::Float64.name(), "float64");
21362        assert_ne!(DType::Float64Nullable.name(), DType::Float64.name());
21363    }
21364
21365    /// The serde spelling has to survive a round trip AND stay distinct from the
21366    /// numpy flavour. `rename_all = "snake_case"` turns `Float64` into
21367    /// `"float64"`, which is what leaves `"Float64"` free for the extension —
21368    /// the same trick `Int64Nullable` already relies on. A naive
21369    /// `#[serde(rename = "Float64")]` on the WRONG variant would collide, and
21370    /// this test is what would catch it.
21371    #[test]
21372    fn serde_round_trips_and_does_not_collide_with_numpy_float64_qkqfb() {
21373        let ext = serde_json::to_string(&DType::Float64Nullable).expect("serialize");
21374        let numpy = serde_json::to_string(&DType::Float64).expect("serialize");
21375        assert_eq!(ext, "\"Float64\"");
21376        assert_eq!(numpy, "\"float64\"");
21377        assert_ne!(ext, numpy);
21378
21379        assert_eq!(
21380            serde_json::from_str::<DType>(&ext).expect("deserialize"),
21381            DType::Float64Nullable
21382        );
21383        assert_eq!(
21384            serde_json::from_str::<DType>(&numpy).expect("deserialize"),
21385            DType::Float64
21386        );
21387    }
21388
21389    /// It is a float, it is numeric, and it is a nullable extension — all three,
21390    /// or downstream dtype dispatch silently skips it.
21391    #[test]
21392    fn predicates_place_it_in_the_right_families_qkqfb() {
21393        assert!(DType::Float64Nullable.is_floating());
21394        assert!(DType::Float64Nullable.is_numeric());
21395        assert!(DType::Float64Nullable.is_any_real_numeric());
21396        assert!(DType::Float64Nullable.is_nullable());
21397        assert!(DType::Float64Nullable.is_extension());
21398        // And NOT these: an integer predicate that accepted it would let a
21399        // float value through an int-only fast path.
21400        assert!(!DType::Float64Nullable.is_integer());
21401        assert!(!DType::Float64Nullable.is_signed_integer());
21402        assert!(!DType::Float64Nullable.is_bool());
21403        // MEASURED: pd.Float64Dtype().kind == 'f', matching numpy float64 --
21404        // the extension reports its UNDERLYING kind, as Int64Nullable does.
21405        assert_eq!(DType::Float64Nullable.kind(), 'f');
21406        assert_eq!(DType::Float64Nullable.kind(), DType::Float64.kind());
21407        assert_eq!(DType::Float64Nullable.itemsize(), 8);
21408    }
21409
21410    /// The nullable/non-nullable pairing must be a genuine involution, or a
21411    /// round trip through either accessor silently changes flavour.
21412    #[test]
21413    fn nullable_pairing_is_an_involution_qkqfb() {
21414        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
21415        assert_eq!(DType::Float64Nullable.to_non_nullable(), DType::Float64);
21416        // Idempotent at both ends.
21417        assert_eq!(DType::Float64Nullable.to_nullable(), DType::Float64Nullable);
21418        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
21419        // The other families are untouched by the new variant.
21420        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
21421        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
21422    }
21423
21424    /// MEASURED ARITHMETIC, live pandas 2.2.3 -- this function models arithmetic
21425    /// promotion, not `find_common_type` (see the Bool arms in `common_dtype`):
21426    /// ```text
21427    ///   Float64(ext) + float64(numpy)  -> Float64
21428    ///   Int64(ext)   + Float64(ext)    -> Float64
21429    ///   boolean(ext) + Float64(ext)    -> Float64
21430    ///   Float64(ext) - Float64(ext)    -> Float64
21431    /// ```
21432    /// The nullable float absorbs every other numeric flavour.
21433    #[test]
21434    fn the_nullable_float_absorbs_every_numeric_flavour_qkqfb() {
21435        for other in [
21436            DType::Float64,
21437            DType::Int64,
21438            DType::Int64Nullable,
21439            DType::Bool,
21440            DType::BoolNullable,
21441            DType::Float64Nullable,
21442        ] {
21443            assert_eq!(
21444                common_dtype(DType::Float64Nullable, other.clone()),
21445                Ok(DType::Float64Nullable),
21446                "Float64Nullable + {other:?}"
21447            );
21448            // Commutativity is asserted wholesale by
21449            // common_dtype_lattice_axioms_be314; repeated here because an
21450            // asymmetric arm makes df1+df2 disagree with df2+df1.
21451            assert_eq!(
21452                common_dtype(other.clone(), DType::Float64Nullable),
21453                Ok(DType::Float64Nullable),
21454                "{other:?} + Float64Nullable"
21455            );
21456        }
21457        // Null is the lattice identity and must not absorb it.
21458        assert_eq!(
21459            common_dtype(DType::Null, DType::Float64Nullable),
21460            Ok(DType::Float64Nullable)
21461        );
21462    }
21463
21464    /// A PRESENT value crosses between the two float flavours unchanged; only the
21465    /// MISSING marker is converted.
21466    ///
21467    /// MEASURED:
21468    /// ```text
21469    ///   pd.Series([1.5,None],dtype="Float64").astype("float64") -> [1.5, nan]
21470    ///   pd.Series([1,None],  dtype="Int64").astype("Float64")   -> [1.0, <NA>]
21471    /// ```
21472    #[test]
21473    fn casts_preserve_values_and_convert_only_the_marker_qkqfb() {
21474        let present = Scalar::Float64(1.5);
21475        assert_eq!(
21476            cast_scalar(&present, DType::Float64Nullable),
21477            Ok(Scalar::Float64(1.5))
21478        );
21479        assert_eq!(
21480            cast_scalar(&Scalar::Float64(1.5), DType::Float64),
21481            Ok(Scalar::Float64(1.5))
21482        );
21483        // Int -> nullable float widens the value, as pandas does.
21484        assert_eq!(
21485            cast_scalar(&Scalar::Int64(1), DType::Float64Nullable),
21486            Ok(Scalar::Float64(1.0))
21487        );
21488        assert_eq!(
21489            cast_scalar(&Scalar::Bool(true), DType::Float64Nullable),
21490            Ok(Scalar::Float64(1.0))
21491        );
21492
21493        // THE MARKER CONVERSION, in both directions. This is the assertion a
21494        // "just alias Float64Nullable to Float64" implementation fails.
21495        assert_eq!(
21496            cast_scalar(&Scalar::Null(NullKind::NaN), DType::Float64Nullable),
21497            Ok(Scalar::Null(NullKind::Null)),
21498            "numpy NaN entering an extension lane becomes pd.NA"
21499        );
21500        assert_eq!(
21501            cast_scalar(&Scalar::Null(NullKind::Null), DType::Float64),
21502            Ok(Scalar::Null(NullKind::NaN)),
21503            "pd.NA entering a numpy lane becomes NaN"
21504        );
21505    }
21506
21507    /// The slice boundary this test used to pin has now been crossed: a
21508    /// nullable lane widening against a numpy float answers the NULLABLE float.
21509    /// MEASURED, live pandas 2.2.3, both spellings:
21510    /// ```text
21511    ///   find_common_type([Int64, float64])                        ->  Float64
21512    ///   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5])  ->  Float64
21513    /// ```
21514    /// (`Float64` there is the EXTENSION dtype — `Float64Dtype()` — not numpy
21515    /// `float64`.) br-frankenpandas-qkqfb; unblocks br-frankenpandas-f0aaa.
21516    #[test]
21517    fn int64nullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
21518        assert_eq!(
21519            common_dtype(DType::Int64Nullable, DType::Float64),
21520            Ok(DType::Float64Nullable)
21521        );
21522        assert_eq!(
21523            common_dtype(DType::Float64, DType::Int64Nullable),
21524            Ok(DType::Float64Nullable)
21525        );
21526    }
21527
21528    /// The BoolNullable sibling, MEASURED on the same pandas:
21529    /// ```text
21530    ///   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
21531    ///       -> Float64   (extension)
21532    /// ```
21533    /// The numpy-bool lane is NOT affected and stays on numpy float64, which is
21534    /// the control that keeps this from being a blanket "nullable everywhere".
21535    #[test]
21536    fn boolnullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
21537        assert_eq!(
21538            common_dtype(DType::BoolNullable, DType::Float64),
21539            Ok(DType::Float64Nullable)
21540        );
21541        assert_eq!(
21542            common_dtype(DType::Bool, DType::Float64),
21543            Ok(DType::Float64),
21544            "numpy bool + numpy float stays entirely on the numpy side"
21545        );
21546    }
21547
21548    /// ⚠ WHY THOSE TWO ARMS CANNOT MOVE INDEPENDENTLY. This is the exact triple
21549    /// that fails if only the Int64Nullable arm is flipped, spelled out so the
21550    /// coupling survives someone later "simplifying" one arm back:
21551    /// ```text
21552    ///   (BoolNullable ∨ Int64) ∨ Float64 = Int64Nullable ∨ Float64 = Float64Nullable
21553    ///   BoolNullable ∨ (Int64 ∨ Float64) = BoolNullable  ∨ Float64 = ???
21554    /// ```
21555    /// `common_dtype_lattice_axioms_be314` sweeps this for all 14 dtypes; this
21556    /// test names the single witness so a failure is diagnosable without
21557    /// re-deriving it from a 14³ sweep. (br-frankenpandas-qkqfb)
21558    #[test]
21559    fn the_nullable_float_flip_is_associative_on_its_witness_triple_qkqfb() {
21560        let (bn, i64n, f64d) = (DType::BoolNullable, DType::Int64, DType::Float64);
21561
21562        let left = common_dtype(
21563            common_dtype(bn.clone(), i64n.clone()).unwrap(),
21564            f64d.clone(),
21565        )
21566        .unwrap();
21567        let right = common_dtype(bn, common_dtype(i64n, f64d).unwrap()).unwrap();
21568
21569        assert_eq!(left, right, "promotion order must not change the result");
21570        assert_eq!(left, DType::Float64Nullable);
21571    }
21572}
21573
21574/// br-frankenpandas-3gxc6: the Sparse dtype NAME is parameterized in pandas.
21575///
21576/// Every expectation below was read off live pandas 2.2.3 before the code was
21577/// written, via `str(dtype)` / `dtype.name` on a `pd.SparseDtype`.
21578#[cfg(test)]
21579mod sparse_dtype_pandas_name_3gxc6 {
21580    use super::{DType, Scalar, SparseDType};
21581
21582    fn name(value_dtype: DType, fill: Scalar) -> String {
21583        SparseDType::new(value_dtype, fill)
21584            .expect("sparse descriptor")
21585            .pandas_name()
21586    }
21587
21588    /// The row the corpus fixture `fp_p2d_017_series_dtype_sparse_strict`
21589    /// exercises. FrankenPandas used to answer the bare `"Sparse"`.
21590    #[test]
21591    fn int64_fill_zero_is_the_fixture_row() {
21592        assert_eq!(name(DType::Int64, Scalar::Int64(0)), "Sparse[int64, 0]");
21593    }
21594
21595    /// A non-default fill must appear, or the name would be a constant wearing
21596    /// a parameterized shape.
21597    #[test]
21598    fn the_fill_value_is_actually_rendered() {
21599        assert_eq!(name(DType::Int64, Scalar::Int64(7)), "Sparse[int64, 7]");
21600        assert_ne!(
21601            name(DType::Int64, Scalar::Int64(0)),
21602            name(DType::Int64, Scalar::Int64(7)),
21603            "two different fills must not collapse to one name"
21604        );
21605    }
21606
21607    /// pandas spells this `nan`, lowercase, not `NaN` and not `None`.
21608    #[test]
21609    fn float64_nan_fill_is_lowercase_nan() {
21610        assert_eq!(
21611            name(DType::Float64, Scalar::Float64(f64::NAN)),
21612            "Sparse[float64, nan]"
21613        );
21614    }
21615
21616    /// pandas keeps the trailing `.0` here. A `{}`-style float format would
21617    /// render `0` and silently make this name collide with the int64 one.
21618    #[test]
21619    fn float64_zero_fill_keeps_its_trailing_point_zero() {
21620        assert_eq!(
21621            name(DType::Float64, Scalar::Float64(0.0)),
21622            "Sparse[float64, 0.0]"
21623        );
21624        assert_ne!(
21625            name(DType::Float64, Scalar::Float64(0.0)),
21626            name(DType::Int64, Scalar::Int64(0)),
21627            "float64 and int64 zero fills are different dtypes"
21628        );
21629    }
21630
21631    /// Python capitalisation, not Rust's `false`.
21632    #[test]
21633    fn bool_fill_uses_python_capitalisation() {
21634        assert_eq!(
21635            name(DType::Bool, Scalar::Bool(false)),
21636            "Sparse[bool, False]"
21637        );
21638        assert_eq!(name(DType::Bool, Scalar::Bool(true)), "Sparse[bool, True]");
21639    }
21640
21641    /// FP spells its object dtype `object`, which is what pandas prints for a
21642    /// `SparseDtype(object, nan)`.
21643    #[test]
21644    fn utf8_subtype_renders_as_object() {
21645        let rendered = name(DType::Utf8, Scalar::Null(crate::NullKind::NaN));
21646        assert!(
21647            rendered.starts_with("Sparse[object, "),
21648            "expected an object subtype, got {rendered}"
21649        );
21650    }
21651
21652    /// The bare name is what this bead removed; guard against a regression
21653    /// that reintroduces it for any constructible descriptor.
21654    #[test]
21655    fn no_constructible_descriptor_renders_the_bare_name() {
21656        for (dtype, fill) in [
21657            (DType::Int64, Scalar::Int64(0)),
21658            (DType::Float64, Scalar::Float64(1.5)),
21659            (DType::Bool, Scalar::Bool(true)),
21660            (DType::Utf8, Scalar::Utf8("x".to_owned())),
21661        ] {
21662            let rendered = name(dtype.clone(), fill);
21663            assert_ne!(rendered, "Sparse", "bare name regressed for {dtype:?}");
21664            assert!(
21665                rendered.starts_with("Sparse[") && rendered.ends_with(']'),
21666                "malformed sparse name {rendered}"
21667            );
21668        }
21669    }
21670
21671    #[test]
21672    fn test_dtype_from_str_and_display() {
21673        use std::str::FromStr;
21674
21675        use crate::DType;
21676
21677        assert_eq!(DType::from_str("int64").unwrap(), DType::Int64);
21678        assert_eq!(DType::from_str("Int64").unwrap(), DType::Int64Nullable);
21679        assert_eq!(DType::from_str("float64").unwrap(), DType::Float64);
21680        assert_eq!(DType::from_str("Float64").unwrap(), DType::Float64Nullable);
21681        assert_eq!(DType::from_str("bool").unwrap(), DType::Bool);
21682        assert_eq!(DType::from_str("boolean").unwrap(), DType::BoolNullable);
21683        assert_eq!(DType::from_str("string").unwrap(), DType::Utf8);
21684        assert_eq!(DType::from_str("category").unwrap(), DType::Categorical);
21685        assert_eq!(
21686            DType::from_str("timedelta64[ns]").unwrap(),
21687            DType::Timedelta64
21688        );
21689        assert_eq!(
21690            DType::from_str("datetime64[ns]").unwrap(),
21691            DType::Datetime64 { tz: None }
21692        );
21693        assert_eq!(
21694            DType::from_str("datetime64[ns, UTC]").unwrap(),
21695            DType::Datetime64 {
21696                tz: Some("UTC".to_string())
21697            }
21698        );
21699        assert_eq!(DType::from_str("period").unwrap(), DType::Period);
21700        assert_eq!(DType::from_str("interval").unwrap(), DType::Interval);
21701        assert_eq!(DType::from_str("sparse").unwrap(), DType::Sparse);
21702
21703        assert_eq!(format!("{}", DType::Int64), "int64");
21704        assert_eq!(
21705            format!(
21706                "{}",
21707                DType::Datetime64 {
21708                    tz: Some("UTC".to_string())
21709                }
21710            ),
21711            "datetime64[ns, UTC]"
21712        );
21713    }
21714
21715    #[test]
21716    fn test_api_types_inspection_and_infer_dtype() {
21717        use crate::{
21718            DType, Scalar,
21719            api::types::{
21720                infer_dtype, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype,
21721                is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_int64_dtype,
21722                is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_object_dtype,
21723                is_period_dtype, is_scalar, is_signed_integer_dtype, is_sparse, is_string_dtype,
21724                is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype,
21725            },
21726        };
21727
21728        assert!(is_numeric_dtype(&DType::Int64));
21729        assert!(is_numeric_dtype(&DType::Float64));
21730        assert!(!is_numeric_dtype(&DType::Utf8));
21731        assert!(!is_numeric_dtype(&DType::Bool));
21732
21733        assert!(is_integer_dtype(&DType::Int64));
21734        assert!(is_integer_dtype(&DType::Int64Nullable));
21735        assert!(!is_integer_dtype(&DType::Float64));
21736
21737        assert!(is_int64_dtype(&DType::Int64));
21738        assert!(is_int64_dtype(&DType::Int64Nullable));
21739        assert!(!is_int64_dtype(&DType::Float64));
21740
21741        assert!(is_object_dtype(&DType::Utf8));
21742        assert!(!is_object_dtype(&DType::Int64));
21743
21744        assert!(is_dtype_equal(&DType::Int64, &DType::Int64));
21745        assert!(is_dtype_equal(&"int64", &DType::Int64));
21746        assert!(!is_dtype_equal(&DType::Int64, &DType::Float64));
21747
21748        assert!(is_signed_integer_dtype(&DType::Int64));
21749        assert!(!is_unsigned_integer_dtype(&DType::Int64));
21750
21751        assert!(is_float_dtype(&DType::Float64));
21752        assert!(is_bool_dtype(&DType::Bool));
21753        assert!(is_string_dtype(&DType::Utf8));
21754        assert!(is_datetime64_any_dtype(&DType::Datetime64 { tz: None }));
21755        assert!(is_timedelta64_dtype(&DType::Timedelta64));
21756        assert!(is_categorical_dtype(&DType::Categorical));
21757        assert!(is_period_dtype(&DType::Period));
21758        assert!(is_interval_dtype(&DType::Interval));
21759        assert!(is_sparse(&DType::Sparse));
21760        assert!(is_extension_array_dtype(&DType::Categorical));
21761        assert!(is_scalar(&Scalar::Int64(42)));
21762
21763        assert_eq!(pandas_dtype("float64").unwrap(), DType::Float64);
21764        assert!(pandas_dtype("invalid_dtype_xyz").is_err());
21765
21766        let ints = vec![Scalar::Int64(1), Scalar::Int64(2)];
21767        assert_eq!(infer_dtype(&ints, true), "integer");
21768
21769        let floats = vec![Scalar::Float64(1.0), Scalar::Float64(2.5)];
21770        assert_eq!(infer_dtype(&floats, true), "floating");
21771
21772        let bools = vec![Scalar::Bool(true), Scalar::Bool(false)];
21773        assert_eq!(infer_dtype(&bools, true), "boolean");
21774
21775        let strings = vec![Scalar::Utf8("a".to_string()), Scalar::Utf8("b".to_string())];
21776        assert_eq!(infer_dtype(&strings, true), "string");
21777
21778        let mixed = vec![Scalar::Int64(1), Scalar::Utf8("a".to_string())];
21779        assert_eq!(infer_dtype(&mixed, true), "mixed");
21780
21781        assert_eq!(infer_dtype(&[], true), "empty");
21782    }
21783
21784    #[test]
21785    fn test_na_nat_sentinels_and_eng_float_format() {
21786        use super::{
21787            NA, NAT, NaT, eng_float_format, get_eng_float_format, reset_eng_float_format,
21788            set_eng_float_format,
21789        };
21790
21791        // NA and NAT sentinels
21792        assert!(NA.is_null());
21793        assert!(NAT.is_null());
21794        assert_eq!(NAT, NaT);
21795        assert_eq!(format!("{NA}"), "None");
21796        assert_eq!(format!("{NAT}"), "NaT");
21797
21798        // Engineering float format tests
21799        assert_eq!(eng_float_format(1000.0, Some(3), false), "1.000E+03");
21800        assert_eq!(eng_float_format(0.005, Some(3), false), "5.000E-03");
21801        assert_eq!(eng_float_format(1234567.0, Some(3), false), "1.235E+06");
21802        assert_eq!(eng_float_format(-9876.54, Some(3), false), "-9.877E+03");
21803        assert_eq!(eng_float_format(0.0, Some(3), false), "0.000E+00");
21804
21805        // With prefixes
21806        assert_eq!(eng_float_format(1000.0, Some(3), true), "1.000k");
21807        assert_eq!(eng_float_format(0.005, Some(3), true), "5.000m");
21808        assert_eq!(eng_float_format(1234567.0, Some(3), true), "1.235M");
21809        assert_eq!(eng_float_format(-9876.54, Some(3), true), "-9.877k");
21810        assert_eq!(eng_float_format(0.0, Some(3), true), "0.000");
21811        assert_eq!(eng_float_format(1.5, Some(3), true), "1.500");
21812
21813        // Special numbers
21814        assert_eq!(eng_float_format(f64::NAN, Some(3), true), "NaN");
21815        assert_eq!(eng_float_format(f64::INFINITY, Some(3), true), "inf");
21816        assert_eq!(eng_float_format(f64::NEG_INFINITY, Some(3), true), "-inf");
21817
21818        // Configuration helpers
21819        reset_eng_float_format();
21820        assert_eq!(get_eng_float_format(), None);
21821        set_eng_float_format(4, true);
21822        assert_eq!(get_eng_float_format(), Some((4, true)));
21823        reset_eng_float_format();
21824        assert_eq!(get_eng_float_format(), None);
21825    }
21826
21827    #[test]
21828    fn test_options_system() {
21829        use super::{
21830            OptionError, OptionValue, describe_option, get_option, option_context, reset_option,
21831            set_option,
21832        };
21833
21834        // Reset to clean state
21835        reset_option(None).unwrap();
21836
21837        // 1. Default option checks
21838        let max_rows = get_option("display.max_rows").unwrap();
21839        assert_eq!(max_rows.as_int(), Some(60));
21840        assert_eq!(max_rows, OptionValue::Int(60));
21841        assert!(!max_rows.is_none());
21842
21843        // Partial key matching (suffix)
21844        let min_rows = get_option("min_rows").unwrap();
21845        assert_eq!(min_rows.as_int(), Some(10));
21846
21847        // 2. Setting options
21848        set_option("display.max_rows", 100).unwrap();
21849        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
21850
21851        set_option("mode.sim_interactive", true).unwrap();
21852        assert_eq!(
21853            get_option("mode.sim_interactive").unwrap().as_bool(),
21854            Some(true)
21855        );
21856
21857        set_option("mode.chained_assignment", "raise").unwrap();
21858        assert_eq!(
21859            get_option("mode.chained_assignment").unwrap().as_str(),
21860            Some("raise")
21861        );
21862
21863        // 3. OptionError handling
21864        assert!(matches!(
21865            get_option("nonexistent.option"),
21866            Err(OptionError::NotFound { .. })
21867        ));
21868        assert!(matches!(
21869            get_option("display"),
21870            Err(OptionError::Ambiguous { .. })
21871        ));
21872
21873        // 4. describe_option
21874        let desc = describe_option(Some("max_rows")).unwrap();
21875        assert!(desc.contains("display.max_rows : [currently: 100]"));
21876
21877        let desc_all = describe_option(None).unwrap();
21878        assert!(desc_all.contains("display.width"));
21879        assert!(desc_all.contains("compute.use_bottleneck"));
21880
21881        // 5. Scoped option_context
21882        {
21883            let _guard = option_context(&[
21884                ("display.max_rows", OptionValue::Int(999)),
21885                ("display.precision", OptionValue::Int(2)),
21886            ])
21887            .unwrap();
21888
21889            assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(999));
21890            assert_eq!(get_option("display.precision").unwrap().as_int(), Some(2));
21891        }
21892        // Restored after guard drop
21893        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
21894        assert_eq!(get_option("display.precision").unwrap().as_int(), Some(6));
21895
21896        // 6. Reset single option and all options
21897        reset_option(Some("display.max_rows")).unwrap();
21898        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(60));
21899
21900        reset_option(Some("all")).unwrap();
21901        assert_eq!(
21902            get_option("mode.chained_assignment").unwrap().as_str(),
21903            Some("warn")
21904        );
21905
21906        // 7. Expanded standard options
21907        assert_eq!(
21908            get_option("mode.copy_on_write").unwrap().as_bool(),
21909            Some(false)
21910        );
21911        assert_eq!(
21912            get_option("mode.data_manager").unwrap().as_str(),
21913            Some("block")
21914        );
21915        assert_eq!(
21916            get_option("display.large_repr").unwrap().as_str(),
21917            Some("truncate")
21918        );
21919        assert_eq!(
21920            get_option("display.max_info_columns").unwrap().as_int(),
21921            Some(100)
21922        );
21923        assert_eq!(
21924            get_option("display.memory_usage").unwrap().as_bool(),
21925            Some(true)
21926        );
21927        assert_eq!(
21928            get_option("display.colheader_justify").unwrap().as_str(),
21929            Some("right")
21930        );
21931        assert!(get_option("display.chop_threshold").unwrap().is_none());
21932        assert_eq!(
21933            get_option("io.parquet.engine").unwrap().as_str(),
21934            Some("auto")
21935        );
21936        assert_eq!(
21937            get_option("plotting.backend").unwrap().as_str(),
21938            Some("matplotlib")
21939        );
21940        assert_eq!(
21941            get_option("plotting.matplotlib.register_converters")
21942                .unwrap()
21943                .as_bool(),
21944            Some(true)
21945        );
21946
21947        // From<()> for OptionValue
21948        set_option("display.chop_threshold", ()).unwrap();
21949        assert!(get_option("display.chop_threshold").unwrap().is_none());
21950    }
21951
21952    #[test]
21953    fn test_scalar_typed_accessors() {
21954        use super::{Interval, IntervalClosed, Period, PeriodFreq, Scalar};
21955
21956        let s_i64 = Scalar::Int64(42);
21957        assert_eq!(s_i64.as_i64(), Some(42));
21958        assert_eq!(s_i64.as_int(), Some(42));
21959        assert_eq!(s_i64.as_f64(), None);
21960        assert_eq!(s_i64.as_float(), None);
21961        assert_eq!(s_i64.as_bool(), None);
21962        assert_eq!(s_i64.as_str(), None);
21963
21964        let s_f64 = Scalar::Float64(2.75);
21965        assert_eq!(s_f64.as_f64(), Some(2.75));
21966        assert_eq!(s_f64.as_float(), Some(2.75));
21967        assert_eq!(s_f64.as_i64(), None);
21968        assert_eq!(s_f64.as_int(), None);
21969
21970        let s_bool = Scalar::Bool(true);
21971        assert_eq!(s_bool.as_bool(), Some(true));
21972        assert_eq!(s_bool.as_int(), None);
21973
21974        let s_str = Scalar::Utf8("pandas".to_string());
21975        assert_eq!(s_str.as_str(), Some("pandas"));
21976        assert_eq!(s_str.as_bool(), None);
21977
21978        let s_dt = Scalar::Datetime64(1_000_000_000);
21979        assert_eq!(s_dt.as_datetime_nanos(), Some(1_000_000_000));
21980        assert_eq!(s_dt.as_str(), None);
21981
21982        let s_td = Scalar::Timedelta64(500_000);
21983        assert_eq!(s_td.as_timedelta_nanos(), Some(500_000));
21984        assert_eq!(s_td.as_int(), None);
21985
21986        let s_per = Scalar::Period(Period::new(2024, PeriodFreq::Daily));
21987        assert_eq!(s_per.as_period_ordinal(), Some(2024));
21988
21989        let s_iv = Scalar::Interval(Interval::new(0.0, 10.0, IntervalClosed::Both));
21990        assert_eq!(
21991            s_iv.as_interval(),
21992            Some(Interval::new(0.0, 10.0, IntervalClosed::Both))
21993        );
21994    }
21995
21996    #[test]
21997    fn test_api_submodules_and_types_inspectors() {
21998        use super::{
21999            DType, Scalar,
22000            api::{extensions, indexers, types},
22001        };
22002
22003        // api::types scalar inspectors
22004        assert!(types::is_number(&Scalar::Int64(42)));
22005        assert!(types::is_number(&Scalar::Float64(42.5)));
22006        assert!(types::is_number(&Scalar::Bool(true)));
22007        assert!(!types::is_number(&Scalar::Utf8("pandas".into())));
22008
22009        assert!(types::is_bool(&Scalar::Bool(false)));
22010        assert!(!types::is_bool(&Scalar::Int64(0)));
22011
22012        assert!(types::is_integer(&Scalar::Int64(10)));
22013        assert!(!types::is_integer(&Scalar::Float64(10.0)));
22014
22015        assert!(types::is_float(&Scalar::Float64(10.0)));
22016        assert!(!types::is_float(&Scalar::Int64(10)));
22017
22018        // api::types dtype inspectors
22019        assert!(types::is_float64_dtype(&DType::Float64));
22020        assert!(types::is_float64_dtype(&DType::Float64Nullable));
22021        assert!(!types::is_float64_dtype(&DType::Int64));
22022        assert!(!types::is_int32_dtype(&DType::Int64));
22023
22024        // api::extensions compatibility hooks
22025        extensions::register_dataframe_accessor("geo");
22026        extensions::register_series_accessor("geo");
22027        extensions::register_index_accessor("geo");
22028
22029        // api::indexers
22030        let base = indexers::BaseIndexer::new(5, 1);
22031        assert_eq!(base.window_size, 5);
22032        assert_eq!(base.step, 1);
22033
22034        let fwd = indexers::FixedForwardWindowIndexer::new(3);
22035        assert_eq!(fwd.window_size, 3);
22036
22037        let var = indexers::VariableOffsetWindowIndexer::new(100);
22038        assert_eq!(var.index_offset, 100);
22039    }
22040
22041    #[test]
22042    fn test_extension_dtypes_and_parameterized_parsing() {
22043        use super::{
22044            AsDType, CategoricalDtype, DType, IntervalClosed, IntervalDtype, PeriodDtype, Scalar,
22045            SparseDType, api::types, pandas_dtype,
22046        };
22047
22048        // CategoricalDtype
22049        let cat_default = CategoricalDtype::default();
22050        assert_eq!(cat_default.name(), "category");
22051        assert_eq!(cat_default.kind(), "O");
22052        assert!(!cat_default.ordered());
22053        assert_eq!(cat_default.categories(), None);
22054        assert_eq!(cat_default.as_dtype(), DType::Categorical);
22055        assert!(types::is_categorical_dtype(&cat_default));
22056        assert_eq!(
22057            cat_default.to_string(),
22058            "CategoricalDtype(categories=None, ordered=False)"
22059        );
22060
22061        let cat_custom =
22062            CategoricalDtype::new(Some(vec!["low".to_string(), "high".to_string()]), true);
22063        assert!(cat_custom.ordered());
22064        assert_eq!(
22065            cat_custom.categories(),
22066            Some(&["low".to_string(), "high".to_string()][..])
22067        );
22068        assert!(cat_custom.to_string().contains("ordered=True"));
22069
22070        // PeriodDtype
22071        let per_default = PeriodDtype::default();
22072        assert_eq!(per_default.freq(), "D");
22073        assert_eq!(per_default.name(), "period[D]");
22074        assert_eq!(per_default.kind(), "O");
22075        assert_eq!(per_default.as_dtype(), DType::Period);
22076        assert!(types::is_period_dtype(&per_default));
22077        assert_eq!(per_default.to_string(), "period[D]");
22078
22079        let per_custom = PeriodDtype::new("M");
22080        assert_eq!(per_custom.freq(), "M");
22081        assert_eq!(per_custom.to_string(), "period[M]");
22082
22083        // IntervalDtype
22084        let int_default = IntervalDtype::default();
22085        assert_eq!(*int_default.subtype(), DType::Float64);
22086        assert_eq!(int_default.closed(), Some(IntervalClosed::Right));
22087        assert_eq!(int_default.name(), "interval");
22088        assert_eq!(int_default.kind(), "O");
22089        assert_eq!(int_default.as_dtype(), DType::Interval);
22090        assert!(types::is_interval_dtype(&int_default));
22091        assert_eq!(int_default.to_string(), "interval[float64, right]");
22092
22093        let int_custom = IntervalDtype::new(DType::Int64, Some(IntervalClosed::Both));
22094        assert_eq!(*int_custom.subtype(), DType::Int64);
22095        assert_eq!(int_custom.closed(), Some(IntervalClosed::Both));
22096        assert_eq!(int_custom.to_string(), "interval[int64, both]");
22097
22098        // SparseDType AsDType
22099        let sp = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).unwrap();
22100        assert_eq!(sp.as_dtype(), DType::Sparse);
22101        assert!(types::is_sparse(&sp));
22102
22103        // Parameterized pandas_dtype parsing
22104        assert_eq!(pandas_dtype("period[D]").unwrap(), DType::Period);
22105        assert_eq!(pandas_dtype("Period[M]").unwrap(), DType::Period);
22106        assert_eq!(pandas_dtype("interval[float64]").unwrap(), DType::Interval);
22107        assert_eq!(pandas_dtype("Interval[int64]").unwrap(), DType::Interval);
22108        assert_eq!(pandas_dtype("sparse[float64]").unwrap(), DType::Sparse);
22109        assert_eq!(pandas_dtype("Sparse[int64, 0]").unwrap(), DType::Sparse);
22110    }
22111}
22112
22113/// `NumericWidth` / `NumpyNumeric` — numpy's narrow numeric dtypes and their
22114/// promotion (fvsao.23). Expected values are live pandas 2.2.3 / numpy 2.4.6.
22115#[cfg(test)]
22116mod numeric_width_fvsao23 {
22117    use super::{DType, NumericWidth, NumpyNumeric, numpy_pairwise_sum};
22118
22119    #[test]
22120    fn float32_sum_is_numpys_pairwise_sum_bit_for_bit() {
22121        // numpy 2.4.6: a = ((arange(n) * 37) % 1000).astype(float32) *
22122        // float32(0.013); a.sum().view(uint32). Lengths 5 and 64 are ones
22123        // where a float64 sum rounded once gives another float32 (NEGATIVE).
22124        let cases: [(usize, u32); 5] = [
22125            (5, 1_083_829_126),
22126            (64, 1_136_679_190),
22127            (129, 1_145_981_108),
22128            (1000, 1_170_926_592),
22129            (4097, 1_188_011_795),
22130        ];
22131        for (n, bits) in cases {
22132            #[allow(clippy::cast_precision_loss)] // below 1000
22133            let values: Vec<f32> = (0..n)
22134                .map(|k| ((k * 37) % 1000) as f32 * 0.013_f32)
22135                .collect();
22136            assert_eq!(numpy_pairwise_sum(&values).to_bits(), bits, "n={n}");
22137            if n < 100 {
22138                #[allow(clippy::cast_possible_truncation)]
22139                let rounded_once = values.iter().map(|&v| f64::from(v)).sum::<f64>() as f32;
22140                assert_ne!(rounded_once.to_bits(), bits, "n={n}");
22141            }
22142        }
22143        assert_eq!(numpy_pairwise_sum::<f32>(&[]), 0.0);
22144    }
22145
22146    #[test]
22147    fn names_parse_and_round_trip() {
22148        for width in NumericWidth::ALL {
22149            for nullable in [false, true] {
22150                assert_eq!(
22151                    NumericWidth::parse(width.name(nullable)),
22152                    Some((width, nullable))
22153                );
22154            }
22155        }
22156        for (name, expected) in [
22157            ("<i4", (NumericWidth::Int32, false)),
22158            ("f4", (NumericWidth::Float32, false)),
22159            ("UInt8Dtype", (NumericWidth::UInt8, true)),
22160        ] {
22161            assert_eq!(NumericWidth::parse(name), Some(expected), "{name}");
22162        }
22163        // The 64-bit names are DType's, not a width: 'i8' is numpy's int64.
22164        for name in ["int64", "Int64", "float64", "i8", "f8", "int", "float"] {
22165            assert_eq!(NumericWidth::parse(name), None, "{name}");
22166        }
22167    }
22168
22169    #[test]
22170    fn wrapping_is_numpys_modular_cast_not_saturation() {
22171        // pd.Series([1, 2, 300, -5]).astype('int8') -> [1, 2, 44, -5]
22172        assert_eq!(NumericWidth::Int8.wrap_int(300), Some(44));
22173        // .astype('uint8') -> [1, 2, 44, 251]; uint16 -5 -> 65531
22174        assert_eq!(NumericWidth::UInt8.wrap_int(-5), Some(251));
22175        assert_eq!(NumericWidth::UInt16.wrap_int(-5), Some(65531));
22176        assert_eq!(NumericWidth::UInt32.wrap_int(-5), Some(4_294_967_291));
22177        // int8 100 + 100 -> -56; 100 * 2 -> -56
22178        assert_eq!(NumericWidth::Int8.wrap_int(200), Some(-56));
22179        assert_eq!(
22180            NumericWidth::Int32.wrap_int(i64::from(i32::MAX) + 1),
22181            Some(i64::from(i32::MIN))
22182        );
22183        // A wrapped i64 product reduces to the width's product.
22184        let product = 50_000_i64.wrapping_pow(5);
22185        assert_eq!(
22186            NumericWidth::Int32.wrap_int(product),
22187            Some(i64::from(50_000_i32.wrapping_pow(5)))
22188        );
22189        // uint64 at or above 2**63 is refused, never stored negative.
22190        assert_eq!(NumericWidth::UInt64.wrap_int(-1), None);
22191        assert_eq!(NumericWidth::UInt64.wrap_int(7), Some(7));
22192        assert_eq!(NumericWidth::Float32.wrap_int(1), None);
22193        assert!(NumericWidth::Int8.holds_int(-128) && !NumericWidth::Int8.holds_int(128));
22194    }
22195
22196    #[test]
22197    fn float32_rounding_is_to_nearest_not_truncation() {
22198        // np.float32(0.1) as float64 -> 0.10000000149011612
22199        assert_eq!(NumericWidth::round_f32(0.1), 0.100_000_001_490_116_12);
22200        // float32 0.1 + 0.2 -> 0.30000001192092896 (not float64's
22201        // 0.30000000000000004)
22202        let sum =
22203            NumericWidth::round_f32(NumericWidth::round_f32(0.1) + NumericWidth::round_f32(0.2));
22204        assert_eq!(sum, 0.300_000_011_920_928_96);
22205        // 1 + 2**-24 is a tie between 1 and 1 + 2**-23: ties to even -> 1.
22206        // 1 + 3 * 2**-25 is above the tie: rounds up, where truncation stays 1.
22207        assert_eq!(NumericWidth::round_f32(1.0 + 2f64.powi(-24)), 1.0);
22208        let above_tie = 1.0 + 3.0 * 2f64.powi(-25);
22209        assert_eq!(NumericWidth::round_f32(above_tie), 1.0 + 2f64.powi(-23));
22210        assert!(NumericWidth::round_f32(f64::NAN).is_nan());
22211        assert_eq!(NumericWidth::round_f32(1e300), f64::INFINITY);
22212    }
22213
22214    #[test]
22215    fn result_type_matches_numpy_promotion() {
22216        use NumpyNumeric::{Bool, Float, Int, UInt};
22217        let cases = [
22218            (Int(32), Int(64), Int(64)), // int32 + int64 -> int64
22219            (Int(8), UInt(8), Int(16)),  // int8 + uint8 -> int16
22220            (Int(16), UInt(8), Int(16)),
22221            (Int(8), UInt(16), Int(32)),
22222            (Int(32), UInt(32), Int(64)),
22223            (Int(64), UInt(64), Float(64)), // no integer holds both
22224            (UInt(8), UInt(32), UInt(32)),
22225            (Float(32), Int(8), Float(32)), // float32 * int8 -> float32
22226            (Float(32), UInt(16), Float(32)),
22227            (Float(32), Int(32), Float(64)), // float32 * int32 -> float64
22228            (Float(32), Float(64), Float(64)),
22229            (Bool, Int(8), Int(8)),
22230            (Bool, Float(32), Float(32)),
22231        ];
22232        for (a, b, expected) in cases {
22233            assert_eq!(a.result_type(b), expected, "{a:?} {b:?}");
22234            assert_eq!(b.result_type(a), expected, "{b:?} {a:?}");
22235        }
22236        // NEP 50: int32 + 1 -> int32; int32 + 0.5 -> float64;
22237        // float32 + 0.2 -> float32
22238        assert_eq!(Int(32).with_python_int(), Int(32));
22239        assert_eq!(Int(32).with_python_float(), Float(64));
22240        assert_eq!(Float(32).with_python_float(), Float(32));
22241        assert_eq!(Bool.with_python_int(), Int(64));
22242    }
22243
22244    #[test]
22245    fn columns_map_to_numpy_dtypes() {
22246        let cases = [
22247            (DType::Int64, None, Some(NumpyNumeric::Int(64))),
22248            (
22249                DType::Int64Nullable,
22250                Some(NumericWidth::UInt8),
22251                Some(NumpyNumeric::UInt(8)),
22252            ),
22253            (
22254                DType::Float64,
22255                Some(NumericWidth::Float32),
22256                Some(NumpyNumeric::Float(32)),
22257            ),
22258            // A width its storage cannot carry is not a numpy dtype.
22259            (DType::Float64, Some(NumericWidth::Int8), None),
22260            (DType::Utf8, None, None),
22261        ];
22262        for (dtype, width, expected) in cases {
22263            assert_eq!(NumpyNumeric::of(&dtype, width), expected, "{dtype:?}");
22264        }
22265        for width in NumericWidth::ALL {
22266            assert_eq!(NumpyNumeric::of_width(width).width(), Some(width));
22267            assert!(width.fits_storage(&width.storage(false)));
22268            assert!(width.fits_storage(&width.storage(true)));
22269        }
22270        assert_eq!(NumpyNumeric::Int(64).width(), None);
22271    }
22272
22273    #[test]
22274    fn downcast_and_category_code_widths() {
22275        // to_numeric([1, 2], downcast='integer') -> int8; [1, 300] signed ->
22276        // int16, unsigned -> uint16
22277        let int32_max_plus_one = i64::from(i32::MAX) + 1;
22278        let signed = [
22279            ((1, 2), Some(NumericWidth::Int8)),
22280            ((1, 300), Some(NumericWidth::Int16)),
22281            ((0, int32_max_plus_one), None),
22282        ];
22283        for ((low, high), expected) in signed {
22284            assert_eq!(NumericWidth::smallest_signed(low, high), expected);
22285        }
22286        let unsigned = [((1, 300), Some(NumericWidth::UInt16)), ((-1, 3), None)];
22287        for ((low, high), expected) in unsigned {
22288            assert_eq!(NumericWidth::smallest_unsigned(low, high), expected);
22289        }
22290        // cat.codes: 2 categories int8, 200 int16; 126 int8, 127 int16
22291        for (categories, expected) in [
22292            (2, NumericWidth::Int8),
22293            (126, NumericWidth::Int8),
22294            (127, NumericWidth::Int16),
22295            (200, NumericWidth::Int16),
22296        ] {
22297            assert_eq!(NumericWidth::for_category_codes(categories), Some(expected));
22298        }
22299        assert_eq!(NumericWidth::itemsize(NumericWidth::Int8), 1);
22300        assert_eq!(NumericWidth::Float32.itemsize(), 4);
22301    }
22302}
22303
22304/// `PandasReductions` against live pandas 2.2.3 / numpy 2.3.5: the bits of
22305/// `Series(...).sum() / mean() / var() / std() / sem() / skew() / kurt()`
22306/// over data both sides build with the same integer arithmetic and one
22307/// division (br-frankenpandas-9iim6).
22308#[cfg(test)]
22309mod pandas_reductions_9iim6 {
22310    use super::{MissingLayout, PandasReductions, ReductionValues};
22311
22312    /// `((k * 7919 + 13) % 100003) / 7.0 - 7000.0`, times 1e6 where
22313    /// `k % 5 == 0`; missing where `k % 11 == 3`.
22314    #[allow(clippy::cast_precision_loss)] // below 100003
22315    fn floats(n: usize) -> (Vec<f64>, Vec<u64>) {
22316        let mut present = vec![0_u64; n.div_ceil(64)];
22317        let values = (0..n)
22318            .map(|k| {
22319                if k % 11 != 3 {
22320                    present[k / 64] |= 1 << (k % 64);
22321                }
22322                let base = ((k * 7919 + 13) % 100_003) as f64 / 7.0 - 7000.0;
22323                if k % 5 == 0 { base * 1e6 } else { base }
22324            })
22325            .collect();
22326        (values, present)
22327    }
22328
22329    /// `(k * 7919 + 13) % 100003 * 3_000_000_007`.
22330    fn ints(n: usize) -> Vec<i64> {
22331        (0..n)
22332            .map(|k| i64::try_from((k * 7919 + 13) % 100_003).unwrap() * 3_000_000_007)
22333            .collect()
22334    }
22335
22336    fn assert_bits(got: &[f64], expected: &[u64], case: &str) {
22337        let got: Vec<u64> = got.iter().map(|value| value.to_bits()).collect();
22338        assert_eq!(got, expected, "{case}");
22339    }
22340
22341    #[test]
22342    fn numpy_float64_with_nan_matches_pandas_bits() {
22343        // pandas: s = Series(floats(n)) with NaN at the missing slots.
22344        let cases: [(usize, [u64; 7]); 7] = [
22345            (
22346                7,
22347                [
22348                    0xc1ff_1185_2dcb_6db6,
22349                    0xc1d4_b658_c932_4924,
22350                    0x43db_301d_4a8d_87a3,
22351                    0x41e4_db58_e2f1_458e,
22352                    0x41d1_078f_09d3_9c5c,
22353                    0xc002_1f47_ceae_1b43,
22354                    0x4014_c8bc_93df_56e6,
22355                ],
22356            ),
22357            (
22358                8,
22359                [
22360                    0xc1ff_1184_f43d_b6da,
22361                    0xc1d1_c0de_426c_687d,
22362                    0x43d7_9d3c_ecd2_da2b,
22363                    0x41e3_7012_7d6c_71a5,
22364                    0x41cd_631d_3379_9929,
22365                    0xc003_b196_82f9_28dc,
22366                    0x4018_9de2_eba9_5ecc,
22367                ],
22368            ),
22369            (
22370                127,
22371                [
22372                    0x4200_324e_3389_2490,
22373                    0x4192_0704_ad1e_360d,
22374                    0x43c9_4a6b_3390_577d,
22375                    0x41dc_72bf_d6fa_9808,
22376                    0x41a5_38f5_8417_ae1e,
22377                    0x3fd0_b6bf_045c_e4d5,
22378                    0x4017_1585_bf13_21c4,
22379                ],
22380            ),
22381            (
22382                128,
22383                [
22384                    0x4200_324d_7236_db6e,
22385                    0x4191_df3a_f99d_a2ae,
22386                    0x43c9_1234_ffb7_4a93,
22387                    0x41dc_5310_c97c_292c,
22388                    0x41a5_09f4_cfcf_9206,
22389                    0x3fd0_d9df_0d68_00b0,
22390                    0x4017_61b6_5653_ae82,
22391                ],
22392            ),
22393            (
22394                129,
22395                [
22396                    0x4200_324c_d43e_db71,
22397                    0x4191_b81f_8a1d_61da,
22398                    0x43c8_daf6_85d3_386f,
22399                    0x41dc_33ca_af49_8c24,
22400                    0x41a4_dbc2_8609_a567,
22401                    0x3fd0_fcc5_39d9_6901,
22402                    0x4017_ade4_7855_7c25,
22403                ],
22404            ),
22405            (
22406                1000,
22407                [
22408                    0x421a_d4f6_8061_248e,
22409                    0x417e_39f9_3e1a_a248,
22410                    0x43c7_9481_cba1_263b,
22411                    0x41db_7825_28c0_37cc,
22412                    0x418d_27ba_a0ea_2f9a,
22413                    0x3fc8_e53a_e277_3d7f,
22414                    0x4018_3c97_3603_dfd0,
22415                ],
22416            ),
22417            (
22418                100_000,
22419                [
22420                    0x4283_088c_316e_46dc,
22421                    0x417b_7135_0c27_1185,
22422                    0x43c7_a0de_3b8e_ea34,
22423                    0x41db_7f57_6673_8d6b,
22424                    0x4157_58cc_33fd_4ae6,
22425                    0x3fc7_f1cf_b14a_14c8,
22426                    0x4018_06b5_f26a_c384,
22427                ],
22428            ),
22429        ];
22430        let all = |r: &PandasReductions<'_>| {
22431            [
22432                r.sum(),
22433                r.mean(),
22434                r.var(1),
22435                r.std(1),
22436                r.sem(1),
22437                r.skew(),
22438                r.kurt(),
22439            ]
22440        };
22441        for (n, expected) in cases {
22442            let (values, present) = floats(n);
22443            let r = PandasReductions::new(
22444                ReductionValues::Float(&values),
22445                Some(&present),
22446                MissingLayout::Numpy,
22447            );
22448            assert_bits(&all(&r), &expected, &format!("float64 n={n}"));
22449            // The same column holding NaN in its missing slots, whole and as
22450            // a concat's chunks.
22451            let with_nan: Vec<f64> = values
22452                .iter()
22453                .enumerate()
22454                .map(|(k, &value)| if k % 11 == 3 { f64::NAN } else { value })
22455                .collect();
22456            let r = PandasReductions::numpy_nan_missing(ReductionValues::Float(&with_nan));
22457            assert_bits(&all(&r), &expected, &format!("float64 NaN n={n}"));
22458            let (head, tail) = with_nan.split_at(n / 3);
22459            let chunks = [head, tail];
22460            let r = PandasReductions::numpy_nan_missing(ReductionValues::FloatChunks(&chunks));
22461            assert_bits(&all(&r), &expected, &format!("float64 NaN chunks n={n}"));
22462        }
22463        // NEGATIVE: the present values added left to right are not pandas'.
22464        let (values, present) = floats(100_000);
22465        let left_fold: f64 = values
22466            .iter()
22467            .enumerate()
22468            .filter(|&(k, _)| present[k / 64] >> (k % 64) & 1 == 1)
22469            .map(|(_, value)| value)
22470            .sum();
22471        assert_ne!(left_fold.to_bits(), 0x4283_088c_316e_46dc);
22472    }
22473
22474    #[test]
22475    fn numpy_int64_mean_sums_through_the_cast_buffer() {
22476        // pandas: Series(ints(n)) (int64): mean, var, sem, skew, kurt.
22477        let cases: [(usize, [u64; 5]); 3] = [
22478            (
22479                129,
22480                [
22481                    0x42e0_dda2_9987_3f9e,
22482                    0x45b9_0e2a_887d_aeda,
22483                    0x429c_34a1_c273_372f,
22484                    0x3f95_9e9d_c69e_ec88,
22485                    0xbff3_844b_ba13_eac1,
22486                ],
22487            ),
22488            (
22489                8193,
22490                [
22491                    0x42e1_0d5b_e407_5aa7,
22492                    0x45b8_3bf5_04f5_f2fc,
22493                    0x426b_d893_c5c9_85b1,
22494                    0x3f42_7452_ff15_86c7,
22495                    0xbff3_318c_611b_b59c,
22496                ],
22497            ),
22498            (
22499                20_000,
22500                [
22501                    0x42e1_0d17_ebf8_272d,
22502                    0x45b8_3c24_c921_82b6,
22503                    0x4261_d2a2_f139_68e2,
22504                    0x3f31_a21c_d4bb_ff52,
22505                    0xbff3_328c_4edc_26ee,
22506                ],
22507            ),
22508        ];
22509        for (n, expected) in cases {
22510            let values = ints(n);
22511            let r =
22512                PandasReductions::new(ReductionValues::Int(&values), None, MissingLayout::Numpy);
22513            let got = [r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()];
22514            assert_bits(&got, &expected, &format!("int64 n={n}"));
22515            // The same values read as chunks give the same bits.
22516            let (head, tail) = values.split_at(n / 3);
22517            let (middle, rest) = tail.split_at(1);
22518            let chunks = [head, middle, &[][..], rest];
22519            let chunked = PandasReductions::new(
22520                ReductionValues::IntChunks(&chunks),
22521                None,
22522                MissingLayout::Numpy,
22523            );
22524            let got = [
22525                chunked.mean(),
22526                chunked.var(1),
22527                chunked.sem(1),
22528                chunked.skew(),
22529                chunked.kurt(),
22530            ];
22531            assert_bits(&got, &expected, &format!("int64 chunks n={n}"));
22532        }
22533    }
22534
22535    #[test]
22536    fn masked_columns_add_runs_of_present_values() {
22537        // pandas: Series(pd.array(floats(n), dtype="Float64")) with NA at the
22538        // missing slots: sum, mean, var, sem. sum / mean differ from the
22539        // float64 column's above (n = 129: ...6e against ...71) - the runs.
22540        let cases: [(usize, [u64; 4]); 3] = [
22541            (
22542                129,
22543                [
22544                    0x4200_324c_d43e_db6e,
22545                    0x4191_b81f_8a1d_61d6,
22546                    0x43c8_daf6_85d3_3872,
22547                    0x41a4_dbc2_8609_a567,
22548                ],
22549            ),
22550            (
22551                1000,
22552                [
22553                    0x421a_d4f6_8061_2492,
22554                    0x417e_39f9_3e1a_a24c,
22555                    0x43c7_9481_cba1_263a,
22556                    0x418d_27ba_a0ea_2f9a,
22557                ],
22558            ),
22559            (
22560                100_000,
22561                [
22562                    0x4283_088c_316e_46de,
22563                    0x417b_7135_0c27_1188,
22564                    0x43c7_a0de_3b8e_ea37,
22565                    0x4157_58cc_33fd_4ae6,
22566                ],
22567            ),
22568        ];
22569        for (n, expected) in cases {
22570            let (values, present) = floats(n);
22571            let r = PandasReductions::new(
22572                ReductionValues::Float(&values),
22573                Some(&present),
22574                MissingLayout::Masked,
22575            );
22576            assert_bits(
22577                &[r.sum(), r.mean(), r.var(1), r.sem(1)],
22578                &expected,
22579                &format!("Float64 n={n}"),
22580            );
22581            let (head, tail) = values.split_at(n / 2 + 1);
22582            let chunks = [head, tail];
22583            let chunked = PandasReductions::new(
22584                ReductionValues::FloatChunks(&chunks),
22585                Some(&present),
22586                MissingLayout::Masked,
22587            );
22588            let got = [
22589                chunked.sum(),
22590                chunked.mean(),
22591                chunked.var(1),
22592                chunked.sem(1),
22593            ];
22594            assert_bits(&got, &expected, &format!("Float64 chunks n={n}"));
22595        }
22596        // pandas: pd.array(ints(n), dtype="Int64") with NA where k % 997 == 5:
22597        // mean and var, the runs summed within numpy's 8192-value buffers.
22598        for (n, expected) in [
22599            (8193, [0x42e1_0f35_29c2_807b_u64, 0x45b8_39ed_8746_bdcc]),
22600            (20_000, [0x42e1_0cf2_cc56_752a, 0x45b8_3c63_72fc_fad5]),
22601        ] {
22602            let values = ints(n);
22603            let mut present = vec![0_u64; n.div_ceil(64)];
22604            for k in (0..n).filter(|k| k % 997 != 5) {
22605                present[k / 64] |= 1 << (k % 64);
22606            }
22607            let r = PandasReductions::new(
22608                ReductionValues::Int(&values),
22609                Some(&present),
22610                MissingLayout::Masked,
22611            );
22612            assert_bits(&[r.mean(), r.var(1)], &expected, &format!("Int64 n={n}"));
22613        }
22614    }
22615
22616    #[test]
22617    fn edge_cases_match_pandas() {
22618        let reductions = |values: &[f64], present: Option<&[u64]>| {
22619            let r = PandasReductions::new(
22620                ReductionValues::Float(values),
22621                present,
22622                MissingLayout::Numpy,
22623            );
22624            [r.sum(), r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()]
22625        };
22626        // pandas: [1.5] * 10 -> 15.0 1.5 0.0 0.0 0.0 0.0 (a constant's kurt
22627        // is 0, not 0 minus the bias term); [2.0] * 3 kurt NaN.
22628        let constant = reductions(&[1.5; 10], None);
22629        assert_eq!(constant, [15.0, 1.5, 0.0, 0.0, 0.0, 0.0]);
22630        assert!(reductions(&[2.0; 3], None)[5].is_nan());
22631        // [1, 2] skew NaN; [1, 2, 4] skew 0.9352195295828237.
22632        assert!(reductions(&[1.0, 2.0], None)[4].is_nan());
22633        assert_eq!(
22634            reductions(&[1.0, 2.0, 4.0], None)[4],
22635            0.935_219_529_582_823_7
22636        );
22637        // Empty / all missing: sum 0.0, the rest NaN.
22638        let empty = reductions(&[], None);
22639        assert_eq!(empty[0], 0.0);
22640        assert!(empty[1..].iter().all(|value| value.is_nan()));
22641        let all_missing = reductions(&[3.0; 5], Some(&[0]));
22642        assert_eq!(all_missing[0], 0.0);
22643        assert!(all_missing[1].is_nan());
22644        // -0.0 * 10 sums to 0.0 (numpy adds onto the identity 0.0).
22645        assert_eq!(
22646            reductions(&[-0.0; 10], None)[0].to_bits(),
22647            0.0_f64.to_bits()
22648        );
22649        // An inf: sum / mean inf, the spread NaN.
22650        let inf = reductions(&[1.0, f64::INFINITY, 2.0, 5.0], None);
22651        assert_eq!(inf[0], f64::INFINITY);
22652        assert!(inf[2..].iter().all(|value| value.is_nan()));
22653    }
22654}
22655
22656/// pandas' default text-to-float64 conversion against live pandas 2.2.3
22657/// bits: `read_csv(StringIO('x\n' + token), dtype={'x': 'float64'})`
22658/// (br-frankenpandas-py3c0).
22659#[cfg(test)]
22660mod pandas_decimal_py3c0 {
22661    use super::{PandasDecimal, pandas_decimal_to_f64, pandas_int_to_f64};
22662
22663    fn bits(token: &str) -> u64 {
22664        match pandas_decimal_to_f64(token.as_bytes()) {
22665            PandasDecimal::Value(value) => value.to_bits(),
22666            other => panic!("{token:?}: {other:?}"),
22667        }
22668    }
22669
22670    #[test]
22671    fn tokens_convert_to_pandas_bits() {
22672        let cases = [
22673            ("9.890295358649789", 0x4023_c7d4_cb12_5ce4),
22674            ("0.8690736625851781286570704999", 0x3feb_cf73_91d3_c8f1),
22675            ("0.000000068288360759838675650889", 0x3e72_54bd_8bcd_610b),
22676            ("-0.0080749473608410608782560", 0xbf80_8999_16a7_63f3),
22677            ("99999999999999999", 0x4376_3457_85d8_a001),
22678            ("1234567890123456789012345", 0x44f0_56e0_f36a_6444),
22679            // 17 leading zeros are the 17 digits kept.
22680            ("00000000000000000.5", 0x0000_0000_0000_0000),
22681            ("-00000000000000000.5", 0x8000_0000_0000_0000),
22682            ("1.5E+10", 0x420b_f08e_b000_0000),
22683            ("-.5e-3", 0xbf40_624d_d2f1_a9fc),
22684            ("5.", 0x4014_0000_0000_0000),
22685            ("1e-320", 0x0000_0000_0000_07e8),
22686            ("2.5e-310", 0x0000_2e05_5c9a_3f6c),
22687            ("-1e-400", 0x8000_0000_0000_0000),
22688            // Below 1e-616: +0.0, the sign dropped.
22689            ("-1e-700", 0x0000_0000_0000_0000),
22690            // The exponent wraps as a 32-bit integer.
22691            ("1e-4294967296", 0x3ff0_0000_0000_0000),
22692            ("1.7976931348623157e308", 0x7fef_ffff_ffff_ffff),
22693            ("0.001e310", 0x7fac_7b1f_3cac_7433),
22694        ];
22695        for (token, expected) in cases {
22696            assert_eq!(bits(token), expected, "{token:?}");
22697        }
22698        // NEGATIVE: the correctly rounded value is not pandas'.
22699        let correctly_rounded: f64 = "9.890295358649789".parse().unwrap();
22700        assert_ne!(correctly_rounded.to_bits(), 0x4023_c7d4_cb12_5ce4);
22701    }
22702
22703    #[test]
22704    fn what_pandas_does_not_read_as_a_float() {
22705        for token in [
22706            "1e309",
22707            "0e400",
22708            "1.8e308",
22709            "1e+0000000000000000001",
22710            "1e-2147483649",
22711            "1e",
22712            "1e+",
22713            "1.5d3",
22714            "0x10",
22715            "1_000.5",
22716            "1..5",
22717        ] {
22718            assert_eq!(
22719                pandas_decimal_to_f64(token.as_bytes()),
22720                PandasDecimal::Rejected,
22721                "{token:?}"
22722            );
22723        }
22724        for token in ["inf", "-Infinity", "nan", ".", "-", "e5", "+.e1", "--1", ""] {
22725            assert_eq!(
22726                pandas_decimal_to_f64(token.as_bytes()),
22727                PandasDecimal::NotDecimal,
22728                "{token:?}"
22729            );
22730        }
22731    }
22732
22733    #[test]
22734    fn an_integer_in_a_float_column_takes_the_same_conversion() {
22735        assert_eq!(pandas_int_to_f64(-42).to_bits(), (-42.0_f64).to_bits());
22736        assert_eq!(
22737            pandas_int_to_f64(99_999_999_999_999_999).to_bits(),
22738            0x4376_3457_85d8_a001
22739        );
22740        assert_eq!(
22741            pandas_int_to_f64(-99_999_999_999_999_999).to_bits(),
22742            0xc376_3457_85d8_a001
22743        );
22744    }
22745}