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    /// nanops' mean of int64 values whose slots holding `missing` (a
1253    /// datetime64 column's NaT) it fills with 0: the total added as float64
1254    /// through numpy's cast buffer, 8192 at a time - as [`Self::mean`] adds
1255    /// an int column - read straight off `values`, over the count of the
1256    /// others. A filled copy and a presence bitmap the sum only re-zeroed
1257    /// made a datetime mean 0.37x pandas (br-frankenpandas-vk7y9). NaN when
1258    /// every slot is missing.
1259    #[must_use]
1260    #[allow(clippy::cast_precision_loss)] // pandas' float values and count
1261    pub fn int64_mean_skipping(values: &[i64], missing: i64) -> f64 {
1262        let count = values.iter().filter(|&&value| value != missing).count();
1263        if count == 0 {
1264            return f64::NAN;
1265        }
1266        let mut total = 0.0;
1267        for chunk in values.chunks(NUMPY_CAST_BUFFER) {
1268            let fill = |start: usize, block: &mut [f64]| {
1269                for (slot, &value) in block.iter_mut().zip(&chunk[start..]) {
1270                    *slot = if value == missing { 0.0 } else { value as f64 };
1271                }
1272            };
1273            total += numpy_pairwise_sum_by(chunk.len(), &fill);
1274        }
1275        total / count as f64
1276    }
1277
1278    /// `Series.var(ddof=ddof)`; NaN with `ddof` or fewer present values.
1279    #[must_use]
1280    #[allow(clippy::cast_precision_loss)] // pandas' float count
1281    pub fn var(&self, ddof: usize) -> f64 {
1282        if self.count <= ddof {
1283            return f64::NAN;
1284        }
1285        // nanops casts an int64 array to float64 whole before its mean; the
1286        // masked var sums int64 values through the cast buffer.
1287        let total = if self.layout == MissingLayout::Masked {
1288            self.mean_total()
1289        } else {
1290            self.total(false)
1291        };
1292        let mean = total / self.count as f64;
1293        let squares = self.add_reduce(
1294            |value| {
1295                let deviation = mean - value;
1296                deviation * deviation
1297            },
1298            false,
1299        );
1300        squares / (self.count - ddof) as f64
1301    }
1302
1303    /// `Series.std(ddof=ddof)`.
1304    #[must_use]
1305    pub fn std(&self, ddof: usize) -> f64 {
1306        self.var(ddof).sqrt()
1307    }
1308
1309    /// This column as nanops reads it: pandas' `sem`, `skew` and `kurt` read
1310    /// even a masked column with its missing slots filled with 0.
1311    fn as_numpy(&self) -> Self {
1312        Self {
1313            layout: MissingLayout::Numpy,
1314            ..*self
1315        }
1316    }
1317
1318    /// `Series.sem(ddof=ddof)`: `sqrt(var) / sqrt(count)`.
1319    #[must_use]
1320    #[allow(clippy::cast_precision_loss)] // pandas' float count
1321    pub fn sem(&self, ddof: usize) -> f64 {
1322        self.as_numpy().var(ddof).sqrt() / (self.count as f64).sqrt()
1323    }
1324
1325    /// The central sums `(m2, m3 or m4)` of nanskew / nankurt.
1326    #[allow(clippy::cast_precision_loss)] // pandas' float count
1327    fn central_moments(&self, fourth: bool) -> (f64, f64) {
1328        let numpy = self.as_numpy();
1329        let mean = numpy.total(false) / self.count as f64;
1330        // Both sums in one sweep: each adds in numpy's order on its own.
1331        let SumPair(m2, higher) = numpy.add_reduce(
1332            |value| {
1333                let deviation = value - mean;
1334                let square = deviation * deviation;
1335                let higher = if fourth {
1336                    square * square
1337                } else {
1338                    square * deviation
1339                };
1340                SumPair(square, higher)
1341            },
1342            false,
1343        );
1344        (m2, higher)
1345    }
1346
1347    /// `Series.skew()`: pandas' nanskew; NaN below 3 values, 0 for constant
1348    /// data.
1349    #[must_use]
1350    #[allow(clippy::cast_precision_loss)] // pandas' float count
1351    pub fn skew(&self) -> f64 {
1352        if self.count < 3 {
1353            return f64::NAN;
1354        }
1355        let (m2, m3) = self.central_moments(false);
1356        let (m2, m3) = (zero_out_fperr(m2), zero_out_fperr(m3));
1357        if m2 == 0.0 {
1358            return 0.0;
1359        }
1360        let count = self.count as f64;
1361        // pandas raises with libm pow (n = 2922 tells it from sqrt); a
1362        // literal 0.5 exponent would let LLVM substitute sqrt.
1363        let half = std::hint::black_box(0.5);
1364        (count * (count - 1.0).powf(half) / (count - 2.0)) * (m3 / m2.powf(1.5))
1365    }
1366
1367    /// `Series.kurt()`: pandas' nankurt; NaN below 4 values, 0 when the
1368    /// denominator vanishes (constant data).
1369    #[must_use]
1370    #[allow(clippy::cast_precision_loss)] // pandas' float count
1371    pub fn kurt(&self) -> f64 {
1372        if self.count < 4 {
1373            return f64::NAN;
1374        }
1375        let (m2, m4) = self.central_moments(true);
1376        let count = self.count as f64;
1377        let numerator = zero_out_fperr(count * (count + 1.0) * (count - 1.0) * m4);
1378        let denominator = zero_out_fperr((count - 2.0) * (count - 3.0) * (m2 * m2));
1379        if denominator == 0.0 {
1380            return 0.0;
1381        }
1382        let adjustment = 3.0 * ((count - 1.0) * (count - 1.0)) / ((count - 2.0) * (count - 3.0));
1383        numerator / denominator - adjustment
1384    }
1385}
1386
1387/// Two sums carried side by side (two float sums, or a float sum and a
1388/// count), added lane by lane.
1389#[derive(Debug, Clone, Copy, Default)]
1390struct SumPair<A, B = A>(A, B);
1391
1392impl<A: std::ops::Add<Output = A>, B: std::ops::Add<Output = B>> std::ops::Add for SumPair<A, B> {
1393    type Output = Self;
1394
1395    fn add(self, other: Self) -> Self {
1396        Self(self.0 + other.0, self.1 + other.1)
1397    }
1398}
1399
1400/// A float key's bits spread for an FxHash table: the high half folded
1401/// into the low (bijective, so equal bits stay equal and distinct stay
1402/// distinct). An integer-valued float's bits end in up to 52 zeros, which
1403/// FxHash's multiply keeps where the table takes its bucket from: 100 round
1404/// keys shared about two buckets, and drop_duplicates / duplicated / groupby
1405/// of round floats ran 4-6x slower than of fractional ones. The splitmix64
1406/// finalizer spread them too but cost fractional keys a sixth
1407/// (br-frankenpandas-mixf64, br-frankenpandas-bss5q.3).
1408#[must_use]
1409pub const fn spread_float_bits(bits: u64) -> u64 {
1410    bits ^ (bits >> 32)
1411}
1412
1413/// pandas' `_zero_out_fperr`: a moment below 1e-14 in magnitude is 0.
1414fn zero_out_fperr(value: f64) -> f64 {
1415    if value.abs() < 1e-14 { 0.0 } else { value }
1416}
1417
1418/// What pandas' default text-to-float64 conversion - `read_csv` /
1419/// `read_table` with `float_precision=None` or `'high'`, and `to_numeric` of
1420/// strings - makes of a token (br-frankenpandas-py3c0).
1421#[derive(Debug, Clone, Copy, PartialEq)]
1422pub enum PandasDecimal {
1423    /// A decimal number, converted as pandas converts it.
1424    Value(f64),
1425    /// A token that starts as a number but that pandas does not read as a
1426    /// float: trailing text, an exponent without digits or with more than 17,
1427    /// a value past float64's range.
1428    Rejected,
1429    /// No digits before an exponent: not a decimal (the `inf` / `nan`
1430    /// spellings, `.`, `-`); the caller's own rules apply.
1431    NotDecimal,
1432}
1433
1434/// Significant digits pandas' converter keeps, leading zeros included;
1435/// also the most exponent digits it reads.
1436const PANDAS_DECIMAL_DIGITS: usize = 17;
1437
1438/// The significand as pandas accumulates it, `x * 10 + d` in float64. While
1439/// the digits stay within 2^53 every step is exact, so they add as an
1440/// integer.
1441#[derive(Default)]
1442struct PandasSignificand {
1443    exact: u64,
1444    float: f64,
1445    rounding: bool,
1446    digits: usize,
1447}
1448
1449impl PandasSignificand {
1450    fn push(&mut self, digit: u8) {
1451        self.digits += 1;
1452        if !self.rounding {
1453            let next = self.exact * 10 + u64::from(digit);
1454            if next <= 1 << 53 {
1455                self.exact = next;
1456                return;
1457            }
1458            self.rounding = true;
1459            #[allow(clippy::cast_precision_loss)] // at most 2^53: exact
1460            let exact = self.exact as f64;
1461            self.float = exact;
1462        }
1463        self.float = self.float * 10.0 + f64::from(digit);
1464    }
1465
1466    #[allow(clippy::cast_precision_loss)] // at most 2^53: exact
1467    fn value(&self) -> f64 {
1468        if self.rounding {
1469            self.float
1470        } else {
1471            self.exact as f64
1472        }
1473    }
1474}
1475
1476/// pandas' scaling table: the float64 nearest each `1e0 ..= 1e308`.
1477static PANDAS_POW10: std::sync::LazyLock<[f64; 309]> = std::sync::LazyLock::new(|| {
1478    std::array::from_fn(|power| format!("1e{power}").parse().unwrap_or(f64::INFINITY))
1479});
1480
1481/// pandas' default text-to-float64 conversion of `token` (no surrounding
1482/// space). It is not correctly rounded: the first 17 digits - leading zeros
1483/// count - accumulate as `x * 10 + d` in float64 (digits past them in the
1484/// integer part raise the exponent, in the fraction they are dropped), the
1485/// exponent is a wrapping 32-bit integer of at most 17 digits, and the value
1486/// is scaled ONCE by a float64 power of ten: `x * 1e{e}` for `e` up to 308,
1487/// `x / 1e{-e}` down to -308, `x / 1e{-308-e} / 1e308` down to -616, `+0.0`
1488/// below that; past 308, or overflowing to infinity, the token is not a
1489/// float. The sign applies last. Measured against live pandas 2.2.3 over
1490/// 180k tokens (repr / `%.20e` / `%.25f` / 1-30 digit fractions / leading
1491/// zeros / exponents to +-640 / wrapping exponents), 0 mismatches;
1492/// `float()` misses about a third of them.
1493#[must_use]
1494pub fn pandas_decimal_to_f64(token: &[u8]) -> PandasDecimal {
1495    let (negative, body) = match token.first() {
1496        Some(b'-') => (true, &token[1..]),
1497        Some(b'+') => (false, &token[1..]),
1498        _ => (false, token),
1499    };
1500    let mut significand = PandasSignificand::default();
1501    let mut exponent = 0_i32;
1502    let mut pos = 0;
1503    while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1504        if significand.digits < PANDAS_DECIMAL_DIGITS {
1505            significand.push(byte - b'0');
1506        } else {
1507            exponent = exponent.wrapping_add(1);
1508        }
1509        pos += 1;
1510    }
1511    let mut seen_digit = pos > 0;
1512    if body.get(pos) == Some(&b'.') {
1513        pos += 1;
1514        while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1515            if significand.digits < PANDAS_DECIMAL_DIGITS {
1516                significand.push(byte - b'0');
1517                exponent = exponent.wrapping_sub(1);
1518            }
1519            seen_digit = true;
1520            pos += 1;
1521        }
1522    }
1523    if !seen_digit {
1524        return PandasDecimal::NotDecimal;
1525    }
1526    if let Some(b'e' | b'E') = body.get(pos) {
1527        pos += 1;
1528        let negative_exponent = match body.get(pos) {
1529            Some(b'-') => {
1530                pos += 1;
1531                true
1532            }
1533            Some(b'+') => {
1534                pos += 1;
1535                false
1536            }
1537            _ => false,
1538        };
1539        let start = pos;
1540        let mut written = 0_i32;
1541        while pos - start < PANDAS_DECIMAL_DIGITS
1542            && let Some(&byte @ b'0'..=b'9') = body.get(pos)
1543        {
1544            written = written
1545                .wrapping_mul(10)
1546                .wrapping_add(i32::from(byte - b'0'));
1547            pos += 1;
1548        }
1549        if pos == start {
1550            return PandasDecimal::Rejected;
1551        }
1552        exponent = exponent.wrapping_add(if negative_exponent {
1553            written.wrapping_neg()
1554        } else {
1555            written
1556        });
1557    }
1558    if pos != body.len() {
1559        return PandasDecimal::Rejected;
1560    }
1561    let value = significand.value();
1562    let pow10 = |power: i32| PANDAS_POW10[power.unsigned_abs() as usize];
1563    let magnitude = match exponent {
1564        309.. => return PandasDecimal::Rejected,
1565        0.. => value * pow10(exponent),
1566        -308.. => value / pow10(exponent),
1567        -616.. => value / pow10(-308 - exponent) / pow10(308),
1568        _ => return PandasDecimal::Value(0.0),
1569    };
1570    if magnitude.is_infinite() {
1571        return PandasDecimal::Rejected;
1572    }
1573    PandasDecimal::Value(if negative { -magnitude } else { magnitude })
1574}
1575
1576/// An integer cell of a column pandas reads as float64 (one of its cells is
1577/// fractional): the integer's digits through [`pandas_decimal_to_f64`],
1578/// exact up to 2^53.
1579#[must_use]
1580#[allow(clippy::cast_precision_loss)] // at most 2^53, or 19 digits: a value
1581pub fn pandas_int_to_f64(value: i64) -> f64 {
1582    if value.unsigned_abs() <= 1 << 53 {
1583        return value as f64;
1584    }
1585    match pandas_decimal_to_f64(value.to_string().as_bytes()) {
1586        PandasDecimal::Value(parsed) => parsed,
1587        // 19 digits at most: always a value.
1588        PandasDecimal::Rejected | PandasDecimal::NotDecimal => value as f64,
1589    }
1590}
1591
1592/// A numeric column's numpy dtype as numpy's promotion sees it: kind and
1593/// bits. The 64-bit ones are a column without a [`NumericWidth`].
1594#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1595pub enum NumpyNumeric {
1596    Bool,
1597    Int(u8),
1598    UInt(u8),
1599    Float(u8),
1600}
1601
1602impl NumpyNumeric {
1603    /// The numpy dtype of a column of `dtype` carrying `width`; `None` for a
1604    /// column that is not bool, integer or float (or a width its storage
1605    /// cannot carry).
1606    #[must_use]
1607    pub const fn of(dtype: &DType, width: Option<NumericWidth>) -> Option<Self> {
1608        match (dtype, width) {
1609            (DType::Bool | DType::BoolNullable, None) => Some(Self::Bool),
1610            (DType::Int64 | DType::Int64Nullable, None) => Some(Self::Int(64)),
1611            (DType::Float64 | DType::Float64Nullable, None) => Some(Self::Float(64)),
1612            (DType::Int64 | DType::Int64Nullable, Some(width)) if !width.is_float() => {
1613                Some(Self::of_width(width))
1614            }
1615            (DType::Float64 | DType::Float64Nullable, Some(NumericWidth::Float32)) => {
1616                Some(Self::Float(32))
1617            }
1618            _ => None,
1619        }
1620    }
1621
1622    #[must_use]
1623    pub const fn of_width(width: NumericWidth) -> Self {
1624        match width {
1625            NumericWidth::Int8 => Self::Int(8),
1626            NumericWidth::Int16 => Self::Int(16),
1627            NumericWidth::Int32 => Self::Int(32),
1628            NumericWidth::UInt8 => Self::UInt(8),
1629            NumericWidth::UInt16 => Self::UInt(16),
1630            NumericWidth::UInt32 => Self::UInt(32),
1631            NumericWidth::UInt64 => Self::UInt(64),
1632            NumericWidth::Float32 => Self::Float(32),
1633        }
1634    }
1635
1636    /// The width a column of this numpy dtype carries: `None` for bool,
1637    /// int64 and float64.
1638    #[must_use]
1639    pub const fn width(self) -> Option<NumericWidth> {
1640        match self {
1641            Self::Int(8) => Some(NumericWidth::Int8),
1642            Self::Int(16) => Some(NumericWidth::Int16),
1643            Self::Int(32) => Some(NumericWidth::Int32),
1644            Self::UInt(8) => Some(NumericWidth::UInt8),
1645            Self::UInt(16) => Some(NumericWidth::UInt16),
1646            Self::UInt(32) => Some(NumericWidth::UInt32),
1647            Self::UInt(64) => Some(NumericWidth::UInt64),
1648            Self::Float(32) => Some(NumericWidth::Float32),
1649            _ => None,
1650        }
1651    }
1652
1653    #[must_use]
1654    pub const fn is_float(self) -> bool {
1655        matches!(self, Self::Float(_))
1656    }
1657
1658    /// numpy's `result_type` of two arrays: the smallest dtype holding both
1659    /// (bool yields to anything; int8 + uint8 is int16, int64 + uint64
1660    /// float64; float32 holds integers of up to 16 bits, a wider integer
1661    /// makes it float64).
1662    #[must_use]
1663    pub const fn result_type(self, other: Self) -> Self {
1664        const fn wider(a: u8, b: u8) -> u8 {
1665            if a > b { a } else { b }
1666        }
1667        match (self, other) {
1668            (Self::Bool, x) | (x, Self::Bool) => x,
1669            (Self::Int(a), Self::Int(b)) => Self::Int(wider(a, b)),
1670            (Self::UInt(a), Self::UInt(b)) => Self::UInt(wider(a, b)),
1671            (Self::Int(signed), Self::UInt(unsigned))
1672            | (Self::UInt(unsigned), Self::Int(signed)) => {
1673                if signed > unsigned {
1674                    Self::Int(signed)
1675                } else if unsigned < 64 {
1676                    Self::Int(wider(signed, unsigned * 2))
1677                } else {
1678                    Self::Float(64)
1679                }
1680            }
1681            (Self::Float(a), Self::Float(b)) => Self::Float(wider(a, b)),
1682            (Self::Float(bits), Self::Int(int_bits) | Self::UInt(int_bits))
1683            | (Self::Int(int_bits) | Self::UInt(int_bits), Self::Float(bits)) => {
1684                if int_bits <= 16 {
1685                    Self::Float(bits)
1686                } else {
1687                    Self::Float(64)
1688                }
1689            }
1690        }
1691    }
1692
1693    /// The dtype of this array combined with a Python `int` (NEP 50: the
1694    /// Python scalar is weak, the array's dtype wins; bool becomes int64).
1695    /// Whether the int fits that dtype is the caller's check.
1696    #[must_use]
1697    pub const fn with_python_int(self) -> Self {
1698        match self {
1699            Self::Bool => Self::Int(64),
1700            other => other,
1701        }
1702    }
1703
1704    /// The dtype of this array combined with a Python `float`: a float
1705    /// array keeps its dtype (float32 + 0.2 is float32), anything else is
1706    /// float64.
1707    #[must_use]
1708    pub const fn with_python_float(self) -> Self {
1709        match self {
1710            Self::Float(bits) => Self::Float(bits),
1711            _ => Self::Float(64),
1712        }
1713    }
1714}
1715
1716/// Trait for types that carry or represent a [`DType`].
1717pub trait AsDType {
1718    /// Return the corresponding [`DType`].
1719    fn as_dtype(&self) -> DType;
1720}
1721
1722impl AsDType for DType {
1723    fn as_dtype(&self) -> DType {
1724        self.clone()
1725    }
1726}
1727
1728impl AsDType for &DType {
1729    fn as_dtype(&self) -> DType {
1730        (*self).clone()
1731    }
1732}
1733
1734impl AsDType for &str {
1735    fn as_dtype(&self) -> DType {
1736        self.parse::<DType>().unwrap_or(DType::Utf8)
1737    }
1738}
1739
1740impl AsDType for String {
1741    fn as_dtype(&self) -> DType {
1742        self.as_str().as_dtype()
1743    }
1744}
1745
1746pub mod api {
1747    //! Public pandas API modules (`pandas.api.*`).
1748
1749    pub mod types {
1750        //! Dtype inspection and conversion functions (`pandas.api.types`).
1751
1752        use crate::{AsDType, DType, Scalar, TypeError};
1753
1754        /// Matches `pd.api.types.is_bool_dtype`.
1755        #[must_use]
1756        pub fn is_bool_dtype(dtype: &impl AsDType) -> bool {
1757            dtype.as_dtype().is_bool()
1758        }
1759
1760        /// Matches `pd.api.types.is_numeric_dtype`.
1761        #[must_use]
1762        pub fn is_numeric_dtype(dtype: &impl AsDType) -> bool {
1763            dtype.as_dtype().is_numeric()
1764        }
1765
1766        /// Matches `pd.api.types.is_integer_dtype`.
1767        #[must_use]
1768        pub fn is_integer_dtype(dtype: &impl AsDType) -> bool {
1769            dtype.as_dtype().is_integer()
1770        }
1771
1772        /// Matches `pd.api.types.is_signed_integer_dtype`.
1773        #[must_use]
1774        pub fn is_signed_integer_dtype(dtype: &impl AsDType) -> bool {
1775            dtype.as_dtype().is_signed_integer()
1776        }
1777
1778        /// Matches `pd.api.types.is_unsigned_integer_dtype`.
1779        #[must_use]
1780        pub fn is_unsigned_integer_dtype(_dtype: &impl AsDType) -> bool {
1781            false
1782        }
1783
1784        /// Matches `pd.api.types.is_float_dtype`.
1785        #[must_use]
1786        pub fn is_float_dtype(dtype: &impl AsDType) -> bool {
1787            dtype.as_dtype().is_floating()
1788        }
1789
1790        /// Matches `pd.api.types.is_string_dtype`.
1791        #[must_use]
1792        pub fn is_string_dtype(dtype: &impl AsDType) -> bool {
1793            dtype.as_dtype().is_string_dtype()
1794        }
1795
1796        /// Matches `pd.api.types.is_datetime64_any_dtype`.
1797        #[must_use]
1798        pub fn is_datetime64_any_dtype(dtype: &impl AsDType) -> bool {
1799            dtype.as_dtype().is_datetime()
1800        }
1801
1802        /// Matches `pd.api.types.is_datetime64_dtype`.
1803        #[must_use]
1804        pub fn is_datetime64_dtype(dtype: &impl AsDType) -> bool {
1805            dtype.as_dtype().is_datetime()
1806        }
1807
1808        /// Matches `pd.api.types.is_datetime64_ns_dtype`.
1809        #[must_use]
1810        pub fn is_datetime64_ns_dtype(dtype: &impl AsDType) -> bool {
1811            dtype.as_dtype().is_datetime()
1812        }
1813
1814        /// Matches `pd.api.types.is_timedelta64_dtype`.
1815        #[must_use]
1816        pub fn is_timedelta64_dtype(dtype: &impl AsDType) -> bool {
1817            dtype.as_dtype().is_timedelta()
1818        }
1819
1820        /// Matches `pd.api.types.is_timedelta64_ns_dtype`.
1821        #[must_use]
1822        pub fn is_timedelta64_ns_dtype(dtype: &impl AsDType) -> bool {
1823            dtype.as_dtype().is_timedelta()
1824        }
1825
1826        /// Matches `pd.api.types.is_period_dtype`.
1827        #[must_use]
1828        pub fn is_period_dtype(dtype: &impl AsDType) -> bool {
1829            dtype.as_dtype().is_period()
1830        }
1831
1832        /// Matches `pd.api.types.is_categorical_dtype`.
1833        #[must_use]
1834        pub fn is_categorical_dtype(dtype: &impl AsDType) -> bool {
1835            dtype.as_dtype().is_categorical()
1836        }
1837
1838        /// Matches `pd.api.types.is_interval_dtype`.
1839        #[must_use]
1840        pub fn is_interval_dtype(dtype: &impl AsDType) -> bool {
1841            dtype.as_dtype().is_interval()
1842        }
1843
1844        /// Matches `pd.api.types.is_sparse`.
1845        #[must_use]
1846        pub fn is_sparse(dtype: &impl AsDType) -> bool {
1847            dtype.as_dtype().is_sparse()
1848        }
1849
1850        /// Matches `pd.api.types.is_extension_array_dtype`.
1851        #[must_use]
1852        pub fn is_extension_array_dtype(dtype: &impl AsDType) -> bool {
1853            dtype.as_dtype().is_extension()
1854        }
1855
1856        /// Matches `pd.api.types.is_object_dtype`.
1857        #[must_use]
1858        pub fn is_object_dtype(dtype: &impl AsDType) -> bool {
1859            dtype.as_dtype().is_object()
1860        }
1861
1862        /// Matches `pd.api.types.is_int64_dtype`.
1863        #[must_use]
1864        pub fn is_int64_dtype(dtype: &impl AsDType) -> bool {
1865            matches!(dtype.as_dtype(), DType::Int64 | DType::Int64Nullable)
1866        }
1867
1868        /// Matches `pd.api.types.is_dtype_equal`.
1869        #[must_use]
1870        pub fn is_dtype_equal(source: &impl AsDType, target: &impl AsDType) -> bool {
1871            source.as_dtype() == target.as_dtype()
1872        }
1873
1874        /// Matches `pd.api.types.is_scalar`.
1875        #[must_use]
1876        pub const fn is_scalar(_scalar: &Scalar) -> bool {
1877            true
1878        }
1879
1880        /// Convert a string specification into a pandas DType. Matches `pd.api.types.pandas_dtype`.
1881        ///
1882        /// # Errors
1883        ///
1884        /// Returns [`TypeError::ValueNotParseable`] if the string cannot be parsed as a valid dtype.
1885        pub fn pandas_dtype(name: &str) -> Result<DType, TypeError> {
1886            name.parse::<DType>()
1887        }
1888
1889        /// Infer the dtype kind of a slice of scalars. Matches `pd.api.types.infer_dtype`.
1890        #[must_use]
1891        pub fn infer_dtype(scalars: &[Scalar], skipna: bool) -> &'static str {
1892            if scalars.is_empty() {
1893                return "empty";
1894            }
1895            let mut has_int = false;
1896            let mut has_float = false;
1897            let mut has_bool = false;
1898            let mut has_str = false;
1899            let mut has_ts = false;
1900            let mut has_td = false;
1901            let mut has_period = false;
1902            let mut count = 0;
1903
1904            for s in scalars {
1905                if s.is_null() {
1906                    if !skipna {
1907                        return "mixed";
1908                    }
1909                    continue;
1910                }
1911                count += 1;
1912                match s {
1913                    Scalar::Bool(_) => has_bool = true,
1914                    Scalar::Int64(_) => has_int = true,
1915                    Scalar::Float64(_) => has_float = true,
1916                    Scalar::Utf8(_) => has_str = true,
1917                    Scalar::Datetime64(_) => has_ts = true,
1918                    Scalar::Timedelta64(_) => has_td = true,
1919                    Scalar::Period(_) => has_period = true,
1920                    _ => {}
1921                }
1922            }
1923
1924            if count == 0 {
1925                return "empty";
1926            }
1927            if has_bool && !has_int && !has_float && !has_str && !has_ts && !has_td && !has_period {
1928                return "boolean";
1929            }
1930            if has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td && !has_period {
1931                return "integer";
1932            }
1933            if (has_float || (has_int && has_float))
1934                && !has_bool
1935                && !has_str
1936                && !has_ts
1937                && !has_td
1938                && !has_period
1939            {
1940                return "floating";
1941            }
1942            if has_str && !has_int && !has_float && !has_bool && !has_ts && !has_td && !has_period {
1943                return "string";
1944            }
1945            if has_ts && !has_int && !has_float && !has_bool && !has_str && !has_td && !has_period {
1946                return "datetime64";
1947            }
1948            if has_td && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_period {
1949                return "timedelta64";
1950            }
1951            if has_period && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td {
1952                return "period";
1953            }
1954            "mixed"
1955        }
1956
1957        /// Convenience helper for 64-bit float types (`pd.api.types.is_float64_dtype` does NOT exist in pandas; see [`is_float_dtype`]).
1958        #[must_use]
1959        pub fn is_float64_dtype(dtype: &impl AsDType) -> bool {
1960            matches!(dtype.as_dtype(), DType::Float64 | DType::Float64Nullable)
1961        }
1962
1963        /// Convenience helper for 32-bit integer types (`pd.api.types.is_int32_dtype` does NOT exist in pandas; see [`is_integer_dtype`]).
1964        #[must_use]
1965        pub fn is_int32_dtype(_dtype: &impl AsDType) -> bool {
1966            false
1967        }
1968
1969        /// Matches `pd.api.types.is_number`.
1970        #[must_use]
1971        pub fn is_number(scalar: &Scalar) -> bool {
1972            scalar.is_numeric() || matches!(scalar, Scalar::Bool(_))
1973        }
1974
1975        /// Matches `pd.api.types.is_bool`.
1976        #[must_use]
1977        pub fn is_bool(scalar: &Scalar) -> bool {
1978            matches!(scalar, Scalar::Bool(_))
1979        }
1980
1981        /// Matches `pd.api.types.is_integer`.
1982        #[must_use]
1983        pub fn is_integer(scalar: &Scalar) -> bool {
1984            matches!(scalar, Scalar::Int64(_))
1985        }
1986
1987        /// Matches `pd.api.types.is_float`.
1988        #[must_use]
1989        pub fn is_float(scalar: &Scalar) -> bool {
1990            matches!(scalar, Scalar::Float64(_))
1991        }
1992    }
1993
1994    pub mod extensions {
1995        //! Extension arrays and accessor registration hooks (`pandas.api.extensions`).
1996
1997        /// Compatibility registration hook for DataFrame accessors matching `pd.api.extensions.register_dataframe_accessor`.
1998        pub fn register_dataframe_accessor(_name: &str) {}
1999
2000        /// Compatibility registration hook for Series accessors matching `pd.api.extensions.register_series_accessor`.
2001        pub fn register_series_accessor(_name: &str) {}
2002
2003        /// Compatibility registration hook for Index accessors matching `pd.api.extensions.register_index_accessor`.
2004        pub fn register_index_accessor(_name: &str) {}
2005    }
2006
2007    pub mod indexers {
2008        //! Custom window and rolling indexers (`pandas.api.indexers`).
2009
2010        /// Base specification for window indexers, matching `pd.api.indexers.BaseIndexer`.
2011        #[derive(Debug, Clone, PartialEq, Eq, Default)]
2012        pub struct BaseIndexer {
2013            pub window_size: usize,
2014            pub step: usize,
2015        }
2016
2017        impl BaseIndexer {
2018            #[must_use]
2019            pub const fn new(window_size: usize, step: usize) -> Self {
2020                Self { window_size, step }
2021            }
2022        }
2023
2024        /// Fixed forward-looking window indexer, matching `pd.api.indexers.FixedForwardWindowIndexer`.
2025        #[derive(Debug, Clone, PartialEq, Eq, Default)]
2026        pub struct FixedForwardWindowIndexer {
2027            pub window_size: usize,
2028        }
2029
2030        impl FixedForwardWindowIndexer {
2031            #[must_use]
2032            pub const fn new(window_size: usize) -> Self {
2033                Self { window_size }
2034            }
2035        }
2036
2037        /// Variable offset window indexer, matching `pd.api.indexers.VariableOffsetWindowIndexer`.
2038        #[derive(Debug, Clone, PartialEq, Eq, Default)]
2039        pub struct VariableOffsetWindowIndexer {
2040            pub index_offset: i64,
2041        }
2042
2043        impl VariableOffsetWindowIndexer {
2044            #[must_use]
2045            pub const fn new(index_offset: i64) -> Self {
2046                Self { index_offset }
2047            }
2048        }
2049    }
2050}
2051
2052pub use api::types::pandas_dtype;
2053
2054#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2055pub struct SparseDType {
2056    pub value_dtype: DType,
2057    pub fill_value: Scalar,
2058}
2059
2060impl SparseDType {
2061    /// Construct a pandas-style sparse dtype descriptor.
2062    ///
2063    /// This records the logical dense value dtype plus the scalar value that is
2064    /// elided from storage. The concrete sparse column representation lives in
2065    /// fp-columnar; this descriptor is the shared public contract.
2066    pub fn new(value_dtype: DType, fill_value: Scalar) -> Result<Self, TypeError> {
2067        if matches!(value_dtype, DType::Null | DType::Sparse) {
2068            return Err(TypeError::InvalidSparseValueDType { dtype: value_dtype });
2069        }
2070
2071        let fill_value = if fill_value.is_missing() {
2072            Scalar::missing_for_dtype(value_dtype.clone())
2073        } else {
2074            cast_scalar_owned(fill_value, value_dtype.clone())?
2075        };
2076
2077        Ok(Self {
2078            value_dtype,
2079            fill_value,
2080        })
2081    }
2082
2083    /// Render the pandas dtype name, `Sparse[<subtype>, <fill>]`.
2084    ///
2085    /// br-frankenpandas-3gxc6. [`DType::name`] can only answer `"Sparse"`: it
2086    /// is a `const fn` returning `&'static str` and `DType::Sparse` carries no
2087    /// payload, so the subtype and fill value — which live here — are lost by
2088    /// the time a caller has a bare [`DType`]. pandas never spells the bare
2089    /// form; even `pd.Series([1.5, 0.0]).astype("Sparse")` resolves to
2090    /// `Sparse[float64, nan]`.
2091    ///
2092    /// MEASURED, live pandas 2.2.3, `str(dtype)` / `dtype.name`:
2093    ///
2094    /// ```text
2095    ///   SparseDtype("int64",   0)     -> Sparse[int64, 0]
2096    ///   SparseDtype("int64",   7)     -> Sparse[int64, 7]
2097    ///   SparseDtype("float64", nan)   -> Sparse[float64, nan]
2098    ///   SparseDtype("float64", 0.0)   -> Sparse[float64, 0.0]
2099    ///   SparseDtype("bool",    False) -> Sparse[bool, False]
2100    ///   SparseDtype(object,    nan)   -> Sparse[object, nan]
2101    /// ```
2102    ///
2103    /// The fill is rendered by `scalar_to_string_for_astype`, which already
2104    /// spells every one of those cases the way pandas does in this position:
2105    /// `True`/`False` capitalised, integers bare, lowercase `nan`, and the
2106    /// trailing `.0` preserved on whole floats. Deliberately reusing it rather
2107    /// than writing a second float formatter — a divergence between the two
2108    /// would surface as a dtype name that no longer round-trips.
2109    #[must_use]
2110    pub fn pandas_name(&self) -> String {
2111        format!(
2112            "Sparse[{}, {}]",
2113            self.value_dtype.name(),
2114            scalar_to_string_for_astype(self.fill_value.clone())
2115        )
2116    }
2117}
2118
2119impl AsDType for SparseDType {
2120    fn as_dtype(&self) -> DType {
2121        DType::Sparse
2122    }
2123}
2124
2125/// Pandas-equivalent categorical dtype descriptor (`pd.CategoricalDtype`).
2126///
2127/// Encapsulates the optional category vocabulary and ordering semantics.
2128#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
2129pub struct CategoricalDtype {
2130    pub categories: Option<Vec<String>>,
2131    pub ordered: bool,
2132}
2133
2134pub type CategoricalDType = CategoricalDtype;
2135
2136impl CategoricalDtype {
2137    /// Construct a new `CategoricalDtype`.
2138    #[must_use]
2139    pub const fn new(categories: Option<Vec<String>>, ordered: bool) -> Self {
2140        Self {
2141            categories,
2142            ordered,
2143        }
2144    }
2145
2146    /// Return categories if known.
2147    #[must_use]
2148    pub fn categories(&self) -> Option<&[String]> {
2149        self.categories.as_deref()
2150    }
2151
2152    /// Return whether this categorical is ordered.
2153    #[must_use]
2154    pub const fn ordered(&self) -> bool {
2155        self.ordered
2156    }
2157
2158    /// Return the pandas dtype string name (`"category"`).
2159    #[must_use]
2160    pub const fn name(&self) -> &'static str {
2161        "category"
2162    }
2163
2164    /// Return the pandas kind character (`"O"`).
2165    #[must_use]
2166    pub const fn kind(&self) -> &'static str {
2167        "O"
2168    }
2169}
2170
2171impl AsDType for CategoricalDtype {
2172    fn as_dtype(&self) -> DType {
2173        DType::Categorical
2174    }
2175}
2176
2177impl std::fmt::Display for CategoricalDtype {
2178    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2179        let ord_str = if self.ordered { "True" } else { "False" };
2180        match &self.categories {
2181            Some(cats) => write!(
2182                f,
2183                "CategoricalDtype(categories={cats:?}, ordered={ord_str})"
2184            ),
2185            None => write!(f, "CategoricalDtype(categories=None, ordered={ord_str})"),
2186        }
2187    }
2188}
2189
2190/// Pandas-equivalent period dtype descriptor (`pd.PeriodDtype`).
2191///
2192/// Represents time period durations with a specific frequency (default `"D"`).
2193#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2194pub struct PeriodDtype {
2195    pub freq: String,
2196}
2197
2198pub type PeriodDType = PeriodDtype;
2199
2200impl PeriodDtype {
2201    /// Construct a new `PeriodDtype` with given frequency.
2202    #[must_use]
2203    pub fn new(freq: impl Into<String>) -> Self {
2204        Self { freq: freq.into() }
2205    }
2206
2207    /// Return the period frequency string.
2208    #[must_use]
2209    pub fn freq(&self) -> &str {
2210        &self.freq
2211    }
2212
2213    /// Return the pandas dtype string name (`period[<freq>]`).
2214    #[must_use]
2215    pub fn name(&self) -> String {
2216        format!("period[{}]", self.freq)
2217    }
2218
2219    /// Return the pandas kind character (`"O"`).
2220    #[must_use]
2221    pub const fn kind(&self) -> &'static str {
2222        "O"
2223    }
2224}
2225
2226impl Default for PeriodDtype {
2227    fn default() -> Self {
2228        Self {
2229            freq: "D".to_string(),
2230        }
2231    }
2232}
2233
2234impl AsDType for PeriodDtype {
2235    fn as_dtype(&self) -> DType {
2236        DType::Period
2237    }
2238}
2239
2240impl std::fmt::Display for PeriodDtype {
2241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2242        write!(f, "period[{}]", self.freq)
2243    }
2244}
2245
2246/// Pandas-equivalent interval dtype descriptor (`pd.IntervalDtype`).
2247///
2248/// Encapsulates the interval subtype and endpoint closure behavior.
2249#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2250pub struct IntervalDtype {
2251    pub subtype: DType,
2252    pub closed: Option<IntervalClosed>,
2253}
2254
2255pub type IntervalDType = IntervalDtype;
2256
2257impl IntervalDtype {
2258    /// Construct a new `IntervalDtype`.
2259    #[must_use]
2260    pub const fn new(subtype: DType, closed: Option<IntervalClosed>) -> Self {
2261        Self { subtype, closed }
2262    }
2263
2264    /// Return the interval subtype.
2265    #[must_use]
2266    pub const fn subtype(&self) -> &DType {
2267        &self.subtype
2268    }
2269
2270    /// Return the endpoint closure convention.
2271    #[must_use]
2272    pub const fn closed(&self) -> Option<IntervalClosed> {
2273        self.closed
2274    }
2275
2276    /// Return the pandas dtype string name (`"interval"`).
2277    #[must_use]
2278    pub const fn name(&self) -> &'static str {
2279        "interval"
2280    }
2281
2282    /// Return the pandas kind character (`"O"`).
2283    #[must_use]
2284    pub const fn kind(&self) -> &'static str {
2285        "O"
2286    }
2287}
2288
2289impl Default for IntervalDtype {
2290    fn default() -> Self {
2291        Self {
2292            subtype: DType::Float64,
2293            closed: Some(IntervalClosed::Right),
2294        }
2295    }
2296}
2297
2298impl AsDType for IntervalDtype {
2299    fn as_dtype(&self) -> DType {
2300        DType::Interval
2301    }
2302}
2303
2304impl std::fmt::Display for IntervalDtype {
2305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2306        match self.closed {
2307            Some(c) => write!(f, "interval[{}, {c}]", self.subtype.name()),
2308            None => write!(f, "interval[{}]", self.subtype.name()),
2309        }
2310    }
2311}
2312
2313#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
2314#[serde(rename_all = "snake_case")]
2315pub enum NullKind {
2316    Null,
2317    NaN,
2318    NaT,
2319}
2320
2321/// JSON spelling of a `Scalar::Float64` payload. JSON has no infinity:
2322/// serde_json writes a non-finite `f64` as `null` and cannot read that back,
2323/// so a division-by-zero answer could not travel through a fixture or the
2324/// oracle at all. ±inf is spelled `"inf"` / `"-inf"` (the pandas oracle emits
2325/// the same strings); finite values and NaN serialize exactly as before, and
2326/// the `null` serde_json writes for NaN now reads back as NaN.
2327/// (br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.3)
2328mod float64_json {
2329    use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
2330
2331    pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
2332        if value.is_infinite() {
2333            serializer.serialize_str(if value.is_sign_positive() {
2334                "inf"
2335            } else {
2336                "-inf"
2337            })
2338        } else {
2339            serializer.serialize_f64(*value)
2340        }
2341    }
2342
2343    #[derive(Deserialize)]
2344    #[serde(untagged)]
2345    enum Repr {
2346        Number(f64),
2347        Text(String),
2348        Null(()),
2349    }
2350
2351    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
2352        match Repr::deserialize(deserializer)? {
2353            Repr::Number(value) => Ok(value),
2354            Repr::Text(text) => match text.as_str() {
2355                "inf" => Ok(f64::INFINITY),
2356                "-inf" => Ok(f64::NEG_INFINITY),
2357                other => Err(D::Error::custom(format!(
2358                    "float64 value must be a number, \"inf\" or \"-inf\", got {other:?}"
2359                ))),
2360            },
2361            Repr::Null(()) => Ok(f64::NAN),
2362        }
2363    }
2364}
2365
2366#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2367#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
2368pub enum Scalar {
2369    Null(NullKind),
2370    Bool(bool),
2371    Int64(i64),
2372    Float64(#[serde(with = "float64_json")] f64),
2373    #[serde(alias = "string", alias = "str")]
2374    Utf8(String),
2375    Timedelta64(i64),
2376    /// Nanoseconds since Unix epoch. Matches pandas `datetime64[ns]`.
2377    /// Uses `Timestamp::NAT` (i64::MIN) for missing values.
2378    Datetime64(i64),
2379    /// Period value (ordinal + frequency). A `Period` whose `ordinal` is
2380    /// `i64::MIN` is NaT (missing). The frequency is carried so writers can
2381    /// render the pandas calendar string (`2024Q1`, `2024-03`, ...) — the
2382    /// calendar string is not recoverable from the ordinal alone, since
2383    /// different frequencies share overlapping ordinal axes.
2384    Period(Period),
2385    /// Numeric interval value. Missing values remain `Scalar::Null`.
2386    Interval(Interval),
2387    /// A pandas object cell none of the kinds above holds: a list
2388    /// (`str.split`'s cells, `Series([[1, 2], [3]])`) or a host-language
2389    /// value the core only carries (fvsao.33).
2390    Object(ObjectValue),
2391}
2392
2393/// A pandas object cell that is not one of [`Scalar`]'s value kinds: a list,
2394/// or a value of the host language (a Python `datetime.date`, dict, numpy
2395/// dtype) that the core carries without reading (fvsao.33).
2396#[derive(Clone)]
2397pub enum ObjectValue {
2398    /// A list of values, compared and printed as Python's list.
2399    List(std::sync::Arc<[Scalar]>),
2400    /// A bytes value, compared and printed as Python's bytes (`b'ab'`):
2401    /// `str.encode`'s cells. The core reads it, so a bytes column needs no
2402    /// host (4qg5w.8).
2403    Bytes(std::sync::Arc<[u8]>),
2404    /// A host-language value, opaque to the core.
2405    Host(HostValue),
2406}
2407
2408/// A host-language value an object cell carries - the Python binding's
2409/// objects: compared and printed by the host itself.
2410pub trait HostObject: Send + Sync {
2411    /// `self == other` in the host language.
2412    fn host_eq(&self, other: &dyn HostObject) -> bool;
2413    /// The host's `repr` (`datetime.date(2024, 1, 5)`).
2414    fn host_repr(&self) -> String;
2415    /// The host's `str` (`2024-01-05`), what `astype(str)` makes of it.
2416    fn host_str(&self) -> String;
2417    /// The cell as pandas displays it in a repr (`pprint_thing`), where that
2418    /// differs from its `str`: a tuple's or array's items unquoted (`(a, 1)`,
2419    /// `[1, 2]`); by default its `str`.
2420    fn host_pprint(&self) -> String {
2421        self.host_str()
2422    }
2423    /// The host's hash, None for an unhashable value (a dict).
2424    fn host_hash(&self) -> Option<u64>;
2425    /// `self` ordered against `other` in the host language (Python's `<` /
2426    /// `>` / `==`), None where the host cannot order them (a date against a
2427    /// time, two dicts).
2428    fn host_cmp(&self, other: &dyn HostObject) -> Option<std::cmp::Ordering>;
2429    /// `self == other` in the host language for a plain value (numpy's
2430    /// `dtype('float64') == 'float64'` is True); false unless the host says so.
2431    fn host_eq_scalar(&self, _other: &Scalar) -> bool {
2432        false
2433    }
2434    /// The value's type as the host's own errors name it (`datetime.date`,
2435    /// `dict`), for a refusal pandas lets the host raise.
2436    fn host_type_name(&self) -> String {
2437        "object".to_owned()
2438    }
2439    /// The value itself, for the host that made it to take back.
2440    fn as_any(&self) -> &dyn std::any::Any;
2441    /// A number standing for the value where the host's values of its kind
2442    /// are equal exactly when their numbers are, and equal to no value
2443    /// without one (a date's day): [`HostValue`] keeps it, and equal cells
2444    /// with one are found and hashed without the host (br-frankenpandas-jq8qb). None by
2445    /// default.
2446    fn host_number(&self) -> Option<i64> {
2447        None
2448    }
2449}
2450
2451/// How many host objects are alive (see [`host_values_block_workers`]).
2452static LIVE_HOST_VALUES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2453
2454/// Whether this process's callers may hold a host lock (see
2455/// [`declare_host_lock`]).
2456static HOST_LOCK_DECLARED: std::sync::atomic::AtomicBool =
2457    std::sync::atomic::AtomicBool::new(false);
2458
2459/// Declare that callers into the core may hold a host lock that host objects
2460/// need - the Python binding, whose every call holds the GIL, declares it
2461/// when its module loads. Without it no worker is ever blocked.
2462pub fn declare_host_lock() {
2463    HOST_LOCK_DECLARED.store(true, std::sync::atomic::Ordering::Relaxed);
2464}
2465
2466/// Whether a parallel kernel must run inline (one worker): a host value
2467/// compares, hashes and prints through its host (Python), which a worker
2468/// thread reaches only by taking the host's lock (the GIL); when the thread
2469/// that spawned the worker holds that lock while it waits for the worker,
2470/// both wait forever - `DataFrame.groupby(dates).rank()` hung that way
2471/// (4qg5w.13). So while any host object is alive in a process whose callers
2472/// may hold that lock, kernels size themselves to one worker.
2473#[must_use]
2474pub fn host_values_block_workers() -> bool {
2475    workers_blocked(
2476        HOST_LOCK_DECLARED.load(std::sync::atomic::Ordering::Relaxed),
2477        LIVE_HOST_VALUES.load(std::sync::atomic::Ordering::Relaxed),
2478    )
2479}
2480
2481/// The rule of [`host_values_block_workers`], free of process state.
2482const fn workers_blocked(host_lock_declared: bool, live_host_values: usize) -> bool {
2483    host_lock_declared && live_host_values > 0
2484}
2485
2486/// A host object, counted alive while any handle to it exists. The object
2487/// lives in the slot itself (one allocation a host value, where a boxed
2488/// object in a slot made two; br-frankenpandas-jq8qb).
2489struct HostSlot<T: ?Sized> {
2490    /// The object's [`HostObject::host_number`], read once.
2491    number: Option<i64>,
2492    object: T,
2493}
2494
2495impl<T: ?Sized> Drop for HostSlot<T> {
2496    fn drop(&mut self) {
2497        LIVE_HOST_VALUES.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2498    }
2499}
2500
2501/// A shared handle on a [`HostObject`].
2502#[derive(Clone)]
2503pub struct HostValue(std::sync::Arc<HostSlot<dyn HostObject>>);
2504
2505impl HostValue {
2506    #[must_use]
2507    pub fn new(object: impl HostObject + 'static) -> Self {
2508        LIVE_HOST_VALUES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2509        Self(std::sync::Arc::new(HostSlot {
2510            number: object.host_number(),
2511            object,
2512        }))
2513    }
2514
2515    #[must_use]
2516    pub fn object(&self) -> &dyn HostObject {
2517        &self.0.object
2518    }
2519
2520    /// The object's [`HostObject::host_number`].
2521    #[must_use]
2522    pub fn number(&self) -> Option<i64> {
2523        self.0.number
2524    }
2525}
2526
2527impl PartialEq for HostValue {
2528    fn eq(&self, other: &Self) -> bool {
2529        std::sync::Arc::ptr_eq(&self.0, &other.0)
2530            || match (self.number(), other.number()) {
2531                // Two numbered values: equal as their numbers, the host not
2532                // asked (a call into it and a downcast a compare; br-frankenpandas-jq8qb).
2533                (Some(left), Some(right)) => left == right,
2534                _ => self.object().host_eq(other.object()),
2535            }
2536    }
2537}
2538
2539impl std::fmt::Debug for HostValue {
2540    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2541        formatter.write_str(&self.object().host_repr())
2542    }
2543}
2544
2545impl ObjectValue {
2546    /// A list cell of `items`.
2547    #[must_use]
2548    pub fn list(items: Vec<Scalar>) -> Self {
2549        Self::List(items.into())
2550    }
2551
2552    /// The items of a list cell.
2553    #[must_use]
2554    pub fn as_list(&self) -> Option<&[Scalar]> {
2555        match self {
2556            Self::List(items) => Some(items),
2557            Self::Bytes(_) | Self::Host(_) => None,
2558        }
2559    }
2560
2561    /// A bytes cell of `data`.
2562    #[must_use]
2563    pub fn bytes(data: Vec<u8>) -> Self {
2564        Self::Bytes(data.into())
2565    }
2566
2567    /// The bytes of a bytes cell.
2568    #[must_use]
2569    pub fn as_bytes(&self) -> Option<&[u8]> {
2570        match self {
2571            Self::Bytes(data) => Some(data),
2572            Self::List(_) | Self::Host(_) => None,
2573        }
2574    }
2575
2576    /// The cell as Python's `repr` spells it (`[1, 'a', None]`, `b'ab'`).
2577    #[must_use]
2578    pub fn repr(&self) -> String {
2579        match self {
2580            Self::List(items) => {
2581                let parts: Vec<String> = items.iter().map(Scalar::python_repr).collect();
2582                format!("[{}]", parts.join(", "))
2583            }
2584            Self::Bytes(data) => python_bytes_repr(data),
2585            Self::Host(value) => value.object().host_repr(),
2586        }
2587    }
2588
2589    /// The cell as pandas displays it in a repr (pandas' `pprint_thing`): a
2590    /// list's items unquoted (`[1, a]`), a host value as the host pprints it.
2591    #[must_use]
2592    pub fn pprint(&self) -> String {
2593        match self {
2594            Self::List(items) => {
2595                let parts: Vec<String> = items
2596                    .iter()
2597                    .map(|item| match item {
2598                        Scalar::Utf8(text) => text.clone(),
2599                        Scalar::Object(object) => object.pprint(),
2600                        other => other.python_repr(),
2601                    })
2602                    .collect();
2603                format!("[{}]", parts.join(", "))
2604            }
2605            Self::Bytes(data) => python_bytes_repr(data),
2606            Self::Host(value) => value.object().host_pprint(),
2607        }
2608    }
2609
2610    /// The cell's Python type as Python's errors name it (`list`, `bytes`,
2611    /// `datetime.date`).
2612    #[must_use]
2613    pub fn type_name(&self) -> String {
2614        match self {
2615            Self::List(_) => "list".to_owned(),
2616            Self::Bytes(_) => "bytes".to_owned(),
2617            Self::Host(value) => value.object().host_type_name(),
2618        }
2619    }
2620
2621    /// Python's `==` between this cell and a plain value: a host value asks
2622    /// the host (a dtype equals its name), a list or bytes never equals one
2623    /// (`b'a' == 'a'` is False).
2624    #[must_use]
2625    pub fn python_eq_scalar(&self, other: &Scalar) -> bool {
2626        match self {
2627            Self::Host(value) => value.object().host_eq_scalar(other),
2628            Self::List(_) | Self::Bytes(_) => false,
2629        }
2630    }
2631
2632    /// Python's ordering of two cells, None where Python raises: host values
2633    /// by the host, lists item by item (a shorter prefix first), bytes by
2634    /// byte, and cells of different kinds unordered.
2635    #[must_use]
2636    pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2637        match (self, other) {
2638            (Self::Bytes(left), Self::Bytes(right)) => Some(left.cmp(right)),
2639            (Self::Host(left), Self::Host(right)) => {
2640                if left == right {
2641                    Some(std::cmp::Ordering::Equal)
2642                } else {
2643                    left.object().host_cmp(right.object())
2644                }
2645            }
2646            (Self::List(left), Self::List(right)) => {
2647                for (a, b) in left.iter().zip(right.iter()) {
2648                    if a != b {
2649                        let ordering = a.python_cmp(b)?;
2650                        if ordering.is_ne() {
2651                            return Some(ordering);
2652                        }
2653                    }
2654                }
2655                Some(left.len().cmp(&right.len()))
2656            }
2657            _ => None,
2658        }
2659    }
2660
2661    /// A total order over cells, for sorted labels and ordered maps: Python's
2662    /// ordering where it has one; otherwise a list before a host value, then
2663    /// the reprs, then identity - so two unequal cells are never Equal and
2664    /// equal cells always are.
2665    #[must_use]
2666    pub fn total_cmp(&self, other: &Self) -> std::cmp::Ordering {
2667        use std::cmp::Ordering;
2668        if self == other {
2669            return Ordering::Equal;
2670        }
2671        if let Some(ordering) = self.python_cmp(other).filter(|ordering| ordering.is_ne()) {
2672            return ordering;
2673        }
2674        let rank = |cell: &Self| match cell {
2675            Self::List(_) => 0_u8,
2676            Self::Bytes(_) => 1,
2677            Self::Host(_) => 2,
2678        };
2679        rank(self)
2680            .cmp(&rank(other))
2681            .then_with(|| self.repr().cmp(&other.repr()))
2682            .then_with(|| self.address().cmp(&other.address()))
2683    }
2684
2685    /// Where the cell's shared data lives: the last tie-break of
2686    /// [`Self::total_cmp`] between unequal cells that print alike.
2687    fn address(&self) -> usize {
2688        match self {
2689            Self::List(items) => items.as_ptr().addr(),
2690            Self::Bytes(data) => data.as_ptr().addr(),
2691            Self::Host(value) => std::sync::Arc::as_ptr(&value.0).cast::<()>().addr(),
2692        }
2693    }
2694}
2695
2696/// Python's `repr` of a bytes value: `b'...'` (double quotes when it holds a
2697/// `'` and no `"`), printable ASCII as itself, `\\`, `\t`, `\n`, `\r` and
2698/// the quote escaped, every other byte as `\xNN`.
2699#[must_use]
2700pub fn python_bytes_repr(data: &[u8]) -> String {
2701    let quote = if data.contains(&b'\'') && !data.contains(&b'"') {
2702        b'"'
2703    } else {
2704        b'\''
2705    };
2706    let mut out = String::with_capacity(data.len() + 3);
2707    out.push('b');
2708    out.push(char::from(quote));
2709    for &byte in data {
2710        match byte {
2711            b'\\' => out.push_str("\\\\"),
2712            b'\t' => out.push_str("\\t"),
2713            b'\n' => out.push_str("\\n"),
2714            b'\r' => out.push_str("\\r"),
2715            _ if byte == quote => {
2716                out.push('\\');
2717                out.push(char::from(byte));
2718            }
2719            0x20..=0x7e => out.push(char::from(byte)),
2720            _ => out.push_str(&format!("\\x{byte:02x}")),
2721        }
2722    }
2723    out.push(char::from(quote));
2724    out
2725}
2726
2727impl PartialOrd for ObjectValue {
2728    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2729        Some(self.cmp(other))
2730    }
2731}
2732
2733/// [`ObjectValue::total_cmp`], so a cell can be an ordered label.
2734impl Ord for ObjectValue {
2735    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2736        self.total_cmp(other)
2737    }
2738}
2739
2740impl PartialEq for ObjectValue {
2741    fn eq(&self, other: &Self) -> bool {
2742        match (self, other) {
2743            (Self::List(left), Self::List(right)) => left == right,
2744            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2745            (Self::Host(left), Self::Host(right)) => left == right,
2746            _ => false,
2747        }
2748    }
2749}
2750
2751/// So a cell can key a hash map (groupby, unique, isin): lists by their
2752/// items' reprs, host values by the host's hash (their repr when the host
2753/// has none).
2754impl Eq for ObjectValue {}
2755
2756impl std::hash::Hash for ObjectValue {
2757    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2758        match self {
2759            Self::List(items) => {
2760                0_u8.hash(state);
2761                for item in items.iter() {
2762                    item.python_repr().hash(state);
2763                }
2764            }
2765            Self::Bytes(data) => {
2766                2_u8.hash(state);
2767                data.hash(state);
2768            }
2769            Self::Host(value) => {
2770                1_u8.hash(state);
2771                // A numbered value hashes as its number, as it compares
2772                // (br-frankenpandas-jq8qb).
2773                if let Some(number) = value.number() {
2774                    number.hash(state);
2775                    return;
2776                }
2777                match value.object().host_hash() {
2778                    Some(hash) => hash.hash(state),
2779                    None => value.object().host_repr().hash(state),
2780                }
2781            }
2782        }
2783    }
2784}
2785
2786impl std::fmt::Debug for ObjectValue {
2787    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2788        formatter.write_str(&self.repr())
2789    }
2790}
2791
2792/// Python's `str` of the cell - what `astype(str)` and the writers produce:
2793/// a list or bytes as its repr (`['a', 1]`, `b'ab'`), a host value as its
2794/// str.
2795impl std::fmt::Display for ObjectValue {
2796    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2797        match self {
2798            Self::List(_) | Self::Bytes(_) => formatter.write_str(&self.repr()),
2799            Self::Host(value) => formatter.write_str(&value.object().host_str()),
2800        }
2801    }
2802}
2803
2804/// A list cell serializes as the sequence of its items, a bytes cell as
2805/// `{"bytes": [..]}`; a host value has no serialized form.
2806impl Serialize for ObjectValue {
2807    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2808        match self {
2809            Self::List(items) => items.as_ref().serialize(serializer),
2810            Self::Bytes(data) => SerializedObject::Bytes {
2811                bytes: data.to_vec(),
2812            }
2813            .serialize(serializer),
2814            Self::Host(_) => Err(serde::ser::Error::custom(
2815                "a host-language object cell cannot be serialized",
2816            )),
2817        }
2818    }
2819}
2820
2821/// The serialized forms of an object cell: a list's items, or a bytes
2822/// value's bytes.
2823#[derive(Serialize, Deserialize)]
2824#[serde(untagged)]
2825enum SerializedObject {
2826    List(Vec<Scalar>),
2827    Bytes { bytes: Vec<u8> },
2828}
2829
2830impl<'de> Deserialize<'de> for ObjectValue {
2831    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2832        Ok(match SerializedObject::deserialize(deserializer)? {
2833            SerializedObject::List(items) => Self::list(items),
2834            SerializedObject::Bytes { bytes } => Self::bytes(bytes),
2835        })
2836    }
2837}
2838
2839impl std::fmt::Display for Scalar {
2840    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2841        match self {
2842            Self::Null(NullKind::NaN) => write!(f, "NaN"),
2843            Self::Null(NullKind::NaT) => write!(f, "NaT"),
2844            Self::Null(NullKind::Null) => write!(f, "None"),
2845            Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
2846            Self::Int64(v) => write!(f, "{v}"),
2847            Self::Float64(v) => write!(f, "{v}"),
2848            Self::Utf8(s) => write!(f, "{s}"),
2849            Self::Timedelta64(nanos) => write!(f, "{}", Timedelta::format(*nanos)),
2850            Self::Datetime64(nanos) => {
2851                if *nanos == Timestamp::NAT {
2852                    write!(f, "NaT")
2853                } else {
2854                    write!(f, "Timestamp[{nanos}]")
2855                }
2856            }
2857            Self::Period(p) => {
2858                if p.ordinal == i64::MIN {
2859                    write!(f, "NaT")
2860                } else {
2861                    write!(f, "{}", p.calendar_string())
2862                }
2863            }
2864            Self::Interval(interval) => write!(f, "{interval}"),
2865            Self::Object(object) => write!(f, "{object}"),
2866        }
2867    }
2868}
2869
2870impl Scalar {
2871    /// Python's ordering of two values: numbers by value, text by code
2872    /// point, instants, durations and same-frequency periods by their
2873    /// payload, intervals by (left, right), object cells by
2874    /// [`ObjectValue::python_cmp`]; None where
2875    /// Python raises (a number against text, a list against a tuple, two
2876    /// dicts).
2877    #[must_use]
2878    pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2879        let numeric =
2880            |value: &Self| matches!(value, Self::Bool(_) | Self::Int64(_) | Self::Float64(_));
2881        match (self, other) {
2882            (Self::Utf8(a), Self::Utf8(b)) => Some(a.cmp(b)),
2883            (Self::Datetime64(a), Self::Datetime64(b))
2884            | (Self::Timedelta64(a), Self::Timedelta64(b)) => Some(a.cmp(b)),
2885            (Self::Period(a), Self::Period(b)) if a.freq == b.freq => {
2886                Some(a.ordinal.cmp(&b.ordinal))
2887            }
2888            (Self::Interval(a), Self::Interval(b)) => Some(
2889                a.left
2890                    .partial_cmp(&b.left)?
2891                    .then(a.right.partial_cmp(&b.right)?),
2892            ),
2893            (Self::Object(a), Self::Object(b)) => a.python_cmp(b),
2894            _ if numeric(self) && numeric(other) => {
2895                self.to_f64().ok()?.partial_cmp(&other.to_f64().ok()?)
2896            }
2897            _ => None,
2898        }
2899    }
2900
2901    /// The two types Python's TypeError names when it cannot order `self`
2902    /// against `other` (see [`Self::python_cmp`]): two lists by the first
2903    /// unequal items they hold (`[1] < ['a']` names 'int' and 'str'), any
2904    /// other pair by their own types.
2905    #[must_use]
2906    pub fn python_cmp_type_names(&self, other: &Self) -> (String, String) {
2907        if let (Self::Object(ObjectValue::List(left)), Self::Object(ObjectValue::List(right))) =
2908            (self, other)
2909            && let Some((a, b)) = left.iter().zip(right.iter()).find(|(a, b)| a != b)
2910        {
2911            return a.python_cmp_type_names(b);
2912        }
2913        (self.python_type_name(), other.python_type_name())
2914    }
2915
2916    /// The value's Python type as Python's errors name it (`str`, `int`,
2917    /// `Timestamp`, `list`), for a TypeError pandas lets Python raise.
2918    #[must_use]
2919    pub fn python_type_name(&self) -> String {
2920        match self {
2921            Self::Null(NullKind::NaN) | Self::Float64(_) => "float",
2922            Self::Null(NullKind::NaT) => "NaTType",
2923            Self::Null(NullKind::Null) => "NoneType",
2924            Self::Bool(_) => "bool",
2925            Self::Int64(_) => "int",
2926            Self::Utf8(_) => "str",
2927            Self::Timedelta64(_) => "Timedelta",
2928            Self::Datetime64(_) => "Timestamp",
2929            Self::Period(_) => "Period",
2930            Self::Interval(_) => "Interval",
2931            Self::Object(object) => return object.type_name(),
2932        }
2933        .to_owned()
2934    }
2935
2936    /// The value as Python's `repr` spells it inside a container (`'a'`,
2937    /// `1`, `1.5`, `None`, `nan`, `[1, 2]`) - how a list cell prints its
2938    /// items.
2939    #[must_use]
2940    pub fn python_repr(&self) -> String {
2941        match self {
2942            Self::Null(NullKind::NaN) => "nan".to_owned(),
2943            Self::Null(NullKind::NaT) => "NaT".to_owned(),
2944            Self::Null(NullKind::Null) => "None".to_owned(),
2945            Self::Utf8(text) => {
2946                let quote = if text.contains('\'') && !text.contains('"') {
2947                    '"'
2948                } else {
2949                    '\''
2950                };
2951                let mut out = String::with_capacity(text.len() + 2);
2952                out.push(quote);
2953                for ch in text.chars() {
2954                    match ch {
2955                        '\\' => out.push_str("\\\\"),
2956                        '\n' => out.push_str("\\n"),
2957                        '\r' => out.push_str("\\r"),
2958                        '\t' => out.push_str("\\t"),
2959                        c if c == quote => {
2960                            out.push('\\');
2961                            out.push(c);
2962                        }
2963                        c => out.push(c),
2964                    }
2965                }
2966                out.push(quote);
2967                out
2968            }
2969            Self::Float64(value) => {
2970                if value.is_nan() {
2971                    "nan".to_owned()
2972                } else if value.is_infinite() {
2973                    if *value > 0.0 { "inf" } else { "-inf" }.to_owned()
2974                } else if value.fract() == 0.0 && value.abs() < 1e16 {
2975                    format!("{value:.1}")
2976                } else {
2977                    format!("{value}")
2978                }
2979            }
2980            Self::Object(object) => object.repr(),
2981            other => other.to_string(),
2982        }
2983    }
2984}
2985
2986/// Pandas `pd.NA` singleton representing missing data in nullable dtypes.
2987pub const NA: Scalar = Scalar::Null(NullKind::Null);
2988
2989/// Pandas `pd.NaT` singleton representing Not-a-Time in datetime/timedelta data.
2990pub const NAT: Scalar = Scalar::Null(NullKind::NaT);
2991
2992/// Alias for [`NAT`] matching pandas capitalization `pd.NaT`.
2993#[allow(non_upper_case_globals)]
2994pub const NaT: Scalar = NAT;
2995
2996// Ergonomic From impls (br-frankenpandas-esjjy / fd90.182). Mirrors
2997// IndexLabel's From<i64>/From<&str>/From<String> so users can write
2998//   let v: Vec<Scalar> = vec![1i64.into(), 2.0.into(), "three".into()];
2999// instead of the explicit Scalar::Int64(...)/Scalar::Float64(...) form.
3000//
3001// i64 maps to Int64 (more common than Timedelta64 in pandas-style code).
3002// Users wanting Timedelta64 should construct it explicitly with
3003// Scalar::Timedelta64(nanos) or via Timedelta::parse / to_timedelta.
3004
3005impl From<bool> for Scalar {
3006    fn from(value: bool) -> Self {
3007        Self::Bool(value)
3008    }
3009}
3010
3011impl From<i64> for Scalar {
3012    fn from(value: i64) -> Self {
3013        Self::Int64(value)
3014    }
3015}
3016
3017impl From<f64> for Scalar {
3018    fn from(value: f64) -> Self {
3019        Self::Float64(value)
3020    }
3021}
3022
3023impl From<&str> for Scalar {
3024    fn from(value: &str) -> Self {
3025        Self::Utf8(value.to_owned())
3026    }
3027}
3028
3029impl From<String> for Scalar {
3030    fn from(value: String) -> Self {
3031        Self::Utf8(value)
3032    }
3033}
3034
3035impl Scalar {
3036    #[inline]
3037    const fn debug_variant_name(&self) -> &'static str {
3038        match self {
3039            Self::Null(_) => "Null",
3040            Self::Bool(_) => "Bool",
3041            Self::Int64(_) => "Int64",
3042            Self::Float64(_) => "Float64",
3043            Self::Utf8(_) => "Utf8",
3044            Self::Timedelta64(_) => "Timedelta64",
3045            Self::Datetime64(_) => "Datetime64",
3046            Self::Period(_) => "Period",
3047            Self::Interval(_) => "Interval",
3048            Self::Object(_) => "Object",
3049        }
3050    }
3051
3052    #[must_use]
3053    pub fn dtype(&self) -> DType {
3054        match self {
3055            Self::Null(_) => DType::Null,
3056            Self::Bool(_) => DType::Bool,
3057            Self::Int64(_) => DType::Int64,
3058            Self::Float64(_) => DType::Float64,
3059            Self::Utf8(_) => DType::Utf8,
3060            Self::Timedelta64(_) => DType::Timedelta64,
3061            Self::Datetime64(_) => DType::datetime64_naive(),
3062            Self::Period(_) => DType::Period,
3063            Self::Interval(_) => DType::Interval,
3064            // pandas' object dtype, which this crate spells Utf8.
3065            Self::Object(_) => DType::Utf8,
3066        }
3067    }
3068
3069    #[must_use]
3070    pub fn is_missing(&self) -> bool {
3071        match self {
3072            Self::Null(_) => true,
3073            Self::Float64(v) => v.is_nan(),
3074            Self::Timedelta64(v) => *v == Timedelta::NAT,
3075            Self::Datetime64(v) => *v == Timestamp::NAT,
3076            Self::Period(p) => p.ordinal == i64::MIN,
3077            _ => false,
3078        }
3079    }
3080
3081    #[must_use]
3082    pub fn is_nan(&self) -> bool {
3083        matches!(self, Self::Null(NullKind::NaN)) || matches!(self, Self::Float64(v) if v.is_nan())
3084    }
3085
3086    /// Returns true if this is a Bool scalar.
3087    #[must_use]
3088    pub const fn is_bool(&self) -> bool {
3089        matches!(self, Self::Bool(_))
3090    }
3091
3092    /// Returns true if this is an Int64 scalar.
3093    #[must_use]
3094    pub const fn is_integer(&self) -> bool {
3095        matches!(self, Self::Int64(_))
3096    }
3097
3098    /// Returns true if this is a Float64 scalar.
3099    #[must_use]
3100    pub const fn is_float(&self) -> bool {
3101        matches!(self, Self::Float64(_))
3102    }
3103
3104    /// Returns true if this is a numeric scalar (Int64 or Float64).
3105    #[must_use]
3106    pub const fn is_numeric(&self) -> bool {
3107        matches!(self, Self::Int64(_) | Self::Float64(_))
3108    }
3109
3110    /// Returns true if this is a Utf8 (string) scalar.
3111    #[must_use]
3112    pub const fn is_string(&self) -> bool {
3113        matches!(self, Self::Utf8(_))
3114    }
3115
3116    /// Returns true if this is a Datetime64 scalar.
3117    #[must_use]
3118    pub const fn is_datetime(&self) -> bool {
3119        matches!(self, Self::Datetime64(_))
3120    }
3121
3122    /// Returns true if this is a Timedelta64 scalar.
3123    #[must_use]
3124    pub const fn is_timedelta(&self) -> bool {
3125        matches!(self, Self::Timedelta64(_))
3126    }
3127
3128    /// Returns true if this is a Period scalar.
3129    #[must_use]
3130    pub const fn is_period(&self) -> bool {
3131        matches!(self, Self::Period(_))
3132    }
3133
3134    /// Returns true if this is an Interval scalar.
3135    #[must_use]
3136    pub const fn is_interval(&self) -> bool {
3137        matches!(self, Self::Interval(_))
3138    }
3139
3140    /// Returns the wrapped i64 if this is an [`Scalar::Int64`] variant.
3141    #[must_use]
3142    pub const fn as_i64(&self) -> Option<i64> {
3143        match self {
3144            Self::Int64(v) => Some(*v),
3145            _ => None,
3146        }
3147    }
3148
3149    /// Alias for [`Scalar::as_i64`].
3150    #[must_use]
3151    pub const fn as_int(&self) -> Option<i64> {
3152        self.as_i64()
3153    }
3154
3155    /// Returns the wrapped f64 if this is a [`Scalar::Float64`] variant.
3156    #[must_use]
3157    pub const fn as_f64(&self) -> Option<f64> {
3158        match self {
3159            Self::Float64(v) => Some(*v),
3160            _ => None,
3161        }
3162    }
3163
3164    /// Alias for [`Scalar::as_f64`].
3165    #[must_use]
3166    pub const fn as_float(&self) -> Option<f64> {
3167        self.as_f64()
3168    }
3169
3170    /// Returns the wrapped bool if this is a [`Scalar::Bool`] variant.
3171    #[must_use]
3172    pub const fn as_bool(&self) -> Option<bool> {
3173        match self {
3174            Self::Bool(v) => Some(*v),
3175            _ => None,
3176        }
3177    }
3178
3179    /// Returns a string slice if this is a [`Scalar::Utf8`] variant.
3180    #[must_use]
3181    pub fn as_str(&self) -> Option<&str> {
3182        match self {
3183            Self::Utf8(s) => Some(s.as_str()),
3184            _ => None,
3185        }
3186    }
3187
3188    /// Returns the raw nanoseconds timestamp if this is a [`Scalar::Datetime64`] variant.
3189    #[must_use]
3190    pub const fn as_datetime_nanos(&self) -> Option<i64> {
3191        match self {
3192            Self::Datetime64(v) => Some(*v),
3193            _ => None,
3194        }
3195    }
3196
3197    /// Returns the raw nanoseconds duration if this is a [`Scalar::Timedelta64`] variant.
3198    #[must_use]
3199    pub const fn as_timedelta_nanos(&self) -> Option<i64> {
3200        match self {
3201            Self::Timedelta64(v) => Some(*v),
3202            _ => None,
3203        }
3204    }
3205
3206    /// Returns the period ordinal if this is a [`Scalar::Period`] variant.
3207    #[must_use]
3208    pub const fn as_period_ordinal(&self) -> Option<i64> {
3209        match self {
3210            Self::Period(p) => Some(p.ordinal),
3211            _ => None,
3212        }
3213    }
3214
3215    /// Returns the [`Interval`] if this is a [`Scalar::Interval`] variant.
3216    #[must_use]
3217    pub const fn as_interval(&self) -> Option<Interval> {
3218        match self {
3219            Self::Interval(i) => Some(*i),
3220            _ => None,
3221        }
3222    }
3223
3224    #[must_use]
3225    pub fn missing_for_dtype(dtype: DType) -> Self {
3226        match dtype {
3227            DType::Float64 => Self::Null(NullKind::NaN),
3228            // NOT NaN, and this is the whole reason the dtype exists. MEASURED,
3229            // live pandas 2.2.3: a Float64 lane stores pd.NA, and it coerces an
3230            // explicit NaN INPUT to pd.NA —
3231            //     pd.Series([float("nan")], dtype="Float64")[0]  ->  <NA>
3232            // whereas the numpy lane above keeps a real NaN. Giving this dtype
3233            // NullKind::NaN would make the two flavours indistinguishable, which
3234            // is exactly the gap br-frankenpandas-qkqfb was filed for.
3235            DType::Float64Nullable => Self::Null(NullKind::Null),
3236            DType::Timedelta64 => Self::Timedelta64(Timedelta::NAT),
3237            DType::Datetime64 { .. } => Self::Datetime64(Timestamp::NAT),
3238            DType::Period => Self::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
3239            DType::Null => Self::Null(NullKind::Null),
3240            DType::Bool
3241            | DType::BoolNullable
3242            | DType::Int64
3243            | DType::Int64Nullable
3244            | DType::Utf8
3245            | DType::Categorical
3246            | DType::Interval
3247            | DType::Sparse => Self::Null(NullKind::Null),
3248        }
3249    }
3250
3251    #[must_use]
3252    pub fn semantic_eq(&self, other: &Self) -> bool {
3253        match (self, other) {
3254            (Self::Float64(a), Self::Float64(b)) => {
3255                if a.is_nan() && b.is_nan() {
3256                    return true;
3257                }
3258                if *a == *b {
3259                    return true;
3260                }
3261                let diff = (*a - *b).abs();
3262                let max_abs = a.abs().max(b.abs());
3263                if max_abs == 0.0 {
3264                    diff < f64::EPSILON
3265                } else {
3266                    diff / max_abs < 1e-14
3267                }
3268            }
3269            (Self::Null(_), Self::Float64(v)) | (Self::Float64(v), Self::Null(_)) => v.is_nan(),
3270            // All Null kinds (Null / NaN / NaT) mark missingness; they are
3271            // semantically indistinguishable for oracle-parity checks even
3272            // though derived PartialEq would reject a cross-kind pair.
3273            // fp-frame normalizes Float64 column missing cells to
3274            // Null(NaN) at Column::new time, while fixture oracles encode
3275            // the canonical missing marker as Null(Null).
3276            (Self::Null(_), Self::Null(_)) => true,
3277            // The DTYPE-SENTINEL missings are missing too, and this function
3278            // already says so for every other flavour. `missing_for_dtype`
3279            // DEFINES the canonical missing for Timedelta64 as
3280            // `Timedelta64(Timedelta::NAT)`, for Datetime64 as
3281            // `Datetime64(Timestamp::NAT)` and for Period as ordinal
3282            // `i64::MIN`, and `is_missing()` returns true for all three — but
3283            // without this arm none of them could ever equal the `Null` marker
3284            // an oracle records for pandas' NaT, so a parity check compared a
3285            // raw i64::MIN bit pattern against a null and called it a value
3286            // mismatch.
3287            //
3288            // OBSERVED on fp_p2d_021_series_to_timedelta_negative_null_hardened:
3289            //   FP     timedelta64:-9223372036854775808
3290            //   pandas null           (the format has no `na_t` marker, so
3291            //                          `null` IS NaT there)
3292            //
3293            // `compare_join_expected` in fp-conformance already carried this as
3294            // a manual `|| (left.is_missing() && right.is_missing())`; putting
3295            // it here makes that clause redundant instead of special, and
3296            // covers the series and dataframe comparators that lacked it.
3297            //
3298            // This is a COMPARISON rule only. It deliberately does not touch
3299            // `missing_for_dtype`: fp-columnar's 2026-07-14 NullKind TRAP note
3300            // records that the sentinel and `Null(NaT)` representations coexist
3301            // inside one column and a uniform gather cannot reproduce the mix,
3302            // which is a storage-model question. (br-frankenpandas-xwxci)
3303            _ if self.is_missing() && other.is_missing() => true,
3304            // An Interval's `==` ignores its subtype (pandas' Interval(0, 3)
3305            // == Interval(0.0, 3.0)), but interval[int64] and
3306            // interval[float64] are different pandas dtypes - '(0, 3]' and
3307            // '(0.0, 3.0]' (fvsao.54).
3308            (Self::Interval(a), Self::Interval(b)) => a == b && a.subtype == b.subtype,
3309            _ => self == other,
3310        }
3311    }
3312
3313    #[must_use]
3314    pub fn semantic_le(&self, other: &Self) -> bool {
3315        match self.semantic_cmp(other) {
3316            std::cmp::Ordering::Less | std::cmp::Ordering::Equal => true,
3317            std::cmp::Ordering::Greater => false,
3318        }
3319    }
3320
3321    #[must_use]
3322    pub fn semantic_ge(&self, other: &Self) -> bool {
3323        match self.semantic_cmp(other) {
3324            std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => true,
3325            std::cmp::Ordering::Less => false,
3326        }
3327    }
3328
3329    #[must_use]
3330    pub fn is_null(&self) -> bool {
3331        matches!(self, Self::Null(_))
3332    }
3333
3334    #[must_use]
3335    pub fn is_na(&self) -> bool {
3336        self.is_missing()
3337    }
3338
3339    /// Return `true` if this scalar is NA/missing (alias for [`Self::is_na`]).
3340    #[must_use]
3341    pub fn isna(&self) -> bool {
3342        self.is_missing()
3343    }
3344
3345    /// Return `true` if this scalar is null (alias for [`Self::is_null`]).
3346    #[must_use]
3347    pub fn isnull(&self) -> bool {
3348        self.is_null()
3349    }
3350
3351    /// Return `true` if this scalar is not NA/missing (matches pandas `notna`).
3352    #[must_use]
3353    pub fn notna(&self) -> bool {
3354        !self.is_missing()
3355    }
3356
3357    /// Return `true` if this scalar is not null/missing (matches pandas `notnull`).
3358    #[must_use]
3359    pub fn notnull(&self) -> bool {
3360        !self.is_missing()
3361    }
3362
3363    /// Return `true` if this scalar is not NA/missing.
3364    #[must_use]
3365    pub fn is_not_na(&self) -> bool {
3366        !self.is_missing()
3367    }
3368
3369    /// Return `true` if this scalar is not NA/missing.
3370    #[must_use]
3371    pub fn not_na(&self) -> bool {
3372        !self.is_missing()
3373    }
3374
3375    #[must_use]
3376    pub fn coalesce(&self, other: &Self) -> Self {
3377        if self.is_missing() {
3378            other.clone()
3379        } else {
3380            self.clone()
3381        }
3382    }
3383
3384    #[must_use]
3385    pub fn semantic_cmp(&self, other: &Self) -> std::cmp::Ordering {
3386        match (self, other) {
3387            (Self::Int64(a), Self::Int64(b)) => a.cmp(b),
3388            (Self::Float64(a), Self::Float64(b)) => {
3389                a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
3390            }
3391            (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
3392            (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
3393            (Self::Null(a), Self::Null(b)) => a.cmp(b),
3394            (Self::Timedelta64(a), Self::Timedelta64(b)) => {
3395                if *a == Timedelta::NAT || *b == Timedelta::NAT {
3396                    std::cmp::Ordering::Equal
3397                } else {
3398                    a.cmp(b)
3399                }
3400            }
3401            (Self::Datetime64(a), Self::Datetime64(b)) => {
3402                if *a == Timestamp::NAT || *b == Timestamp::NAT {
3403                    std::cmp::Ordering::Equal
3404                } else {
3405                    a.cmp(b)
3406                }
3407            }
3408            (Self::Period(a), Self::Period(b)) => {
3409                if a.ordinal == i64::MIN || b.ordinal == i64::MIN {
3410                    std::cmp::Ordering::Equal
3411                } else {
3412                    a.ordinal.cmp(&b.ordinal)
3413                }
3414            }
3415            (Self::Interval(a), Self::Interval(b)) => a
3416                .left
3417                .partial_cmp(&b.left)
3418                .unwrap_or(std::cmp::Ordering::Equal)
3419                .then_with(|| {
3420                    a.right
3421                        .partial_cmp(&b.right)
3422                        .unwrap_or(std::cmp::Ordering::Equal)
3423                })
3424                .then_with(|| a.closed.cmp(&b.closed)),
3425            // Object cells (dates, lists) in Python's order (fvsao.66).
3426            (Self::Object(a), Self::Object(b)) => a.cmp(b),
3427            // Cross-numeric comparison
3428            (Self::Int64(a), Self::Float64(b)) => (*a as f64)
3429                .partial_cmp(b)
3430                .unwrap_or(std::cmp::Ordering::Equal),
3431            (Self::Float64(a), Self::Int64(b)) => a
3432                .partial_cmp(&(*b as f64))
3433                .unwrap_or(std::cmp::Ordering::Equal),
3434            // Derived Debug starts every variant with its static variant name.
3435            // Different variants therefore order by that name before either
3436            // payload is observed; compare those names without allocating.
3437            (a, b) => a.debug_variant_name().cmp(b.debug_variant_name()),
3438        }
3439    }
3440
3441    pub fn to_f64(&self) -> Result<f64, TypeError> {
3442        match self {
3443            Self::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
3444            Self::Int64(v) => Ok(*v as f64),
3445            Self::Float64(v) => Ok(*v),
3446            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3447            Self::Utf8(v) => Err(TypeError::NonNumericValue {
3448                value: v.clone(),
3449                dtype: DType::Utf8,
3450            }),
3451            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3452                kind: NullKind::NaT,
3453            }),
3454            Self::Timedelta64(v) => Err(TypeError::NonNumericValue {
3455                value: Timedelta::format(*v),
3456                dtype: DType::Timedelta64,
3457            }),
3458            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3459                kind: NullKind::NaT,
3460            }),
3461            Self::Datetime64(v) => Err(TypeError::NonNumericValue {
3462                value: format!("Timestamp[{v}]"),
3463                dtype: DType::datetime64_naive(),
3464            }),
3465            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3466                kind: NullKind::NaT,
3467            }),
3468            Self::Period(p) => Err(TypeError::NonNumericValue {
3469                value: p.calendar_string(),
3470                dtype: DType::Period,
3471            }),
3472            Self::Interval(v) => Err(TypeError::NonNumericValue {
3473                value: v.to_string(),
3474                dtype: DType::Interval,
3475            }),
3476            Self::Object(object) => Err(TypeError::NonNumericValue {
3477                value: object.repr(),
3478                dtype: DType::Utf8,
3479            }),
3480        }
3481    }
3482
3483    /// Try to convert to i64. Returns error for missing or non-numeric values.
3484    pub fn to_i64(&self) -> Result<i64, TypeError> {
3485        match self {
3486            Self::Bool(v) => Ok(if *v { 1 } else { 0 }),
3487            Self::Int64(v) => Ok(*v),
3488            Self::Float64(v) => Ok(*v as i64),
3489            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3490            Self::Utf8(v) => Err(TypeError::NonNumericValue {
3491                value: v.clone(),
3492                dtype: DType::Utf8,
3493            }),
3494            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3495                kind: NullKind::NaT,
3496            }),
3497            Self::Timedelta64(v) => Ok(*v),
3498            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3499                kind: NullKind::NaT,
3500            }),
3501            Self::Datetime64(v) => Ok(*v),
3502            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3503                kind: NullKind::NaT,
3504            }),
3505            Self::Period(p) => Ok(p.ordinal),
3506            Self::Interval(v) => Err(TypeError::NonNumericValue {
3507                value: v.to_string(),
3508                dtype: DType::Interval,
3509            }),
3510            Self::Object(object) => Err(TypeError::NonNumericValue {
3511                value: object.repr(),
3512                dtype: DType::Utf8,
3513            }),
3514        }
3515    }
3516
3517    /// Try to convert to bool. Returns error for missing values.
3518    pub fn to_bool(&self) -> Result<bool, TypeError> {
3519        match self {
3520            Self::Bool(v) => Ok(*v),
3521            Self::Int64(v) => Ok(*v != 0),
3522            Self::Float64(v) => Ok(*v != 0.0 && !v.is_nan()),
3523            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3524            Self::Utf8(v) => Ok(!v.is_empty()),
3525            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3526                kind: NullKind::NaT,
3527            }),
3528            Self::Timedelta64(v) => Ok(*v != 0),
3529            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3530                kind: NullKind::NaT,
3531            }),
3532            Self::Datetime64(v) => Ok(*v != 0),
3533            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3534                kind: NullKind::NaT,
3535            }),
3536            Self::Period(p) => Ok(p.ordinal != 0),
3537            Self::Interval(_) => Ok(true),
3538            // Python's truth: a list or bytes is true when it has items, any
3539            // other object true.
3540            Self::Object(ObjectValue::List(items)) => Ok(!items.is_empty()),
3541            Self::Object(ObjectValue::Bytes(data)) => Ok(!data.is_empty()),
3542            Self::Object(ObjectValue::Host(_)) => Ok(true),
3543        }
3544    }
3545
3546    /// Try to convert to string representation.
3547    pub fn to_str(&self) -> String {
3548        match self {
3549            Self::Bool(v) => if *v { "True" } else { "False" }.to_string(),
3550            Self::Int64(v) => v.to_string(),
3551            Self::Float64(v) => {
3552                if v.is_nan() {
3553                    "nan".to_string()
3554                } else if v.is_infinite() {
3555                    if *v > 0.0 { "inf" } else { "-inf" }.to_string()
3556                } else {
3557                    v.to_string()
3558                }
3559            }
3560            Self::Null(_) => "NaN".to_string(),
3561            Self::Utf8(v) => v.clone(),
3562            Self::Timedelta64(v) => Timedelta::format(*v),
3563            Self::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_string(),
3564            Self::Datetime64(v) => Timestamp::from_nanos(*v).isoformat(),
3565            Self::Period(p) if p.ordinal == i64::MIN => "NaT".to_string(),
3566            Self::Period(p) => p.calendar_string(),
3567            Self::Interval(v) => v.to_string(),
3568            Self::Object(object) => object.to_string(),
3569        }
3570    }
3571}
3572
3573#[derive(Debug, Error, Clone, PartialEq)]
3574pub enum TypeError {
3575    #[error("dtype coercion from {left:?} to {right:?} has no compatible common type")]
3576    IncompatibleDtypes { left: DType, right: DType },
3577    #[error("cannot cast scalar of dtype {from:?} to {to:?}")]
3578    InvalidCast { from: DType, to: DType },
3579    #[error("cannot cast float {value} to int64 without loss")]
3580    LossyFloatToInt { value: f64 },
3581    #[error("expected 0/1 for bool cast from int64 but found {value}")]
3582    InvalidBoolInt { value: i64 },
3583    #[error("expected 0.0/1.0 for bool cast from float64 but found {value}")]
3584    InvalidBoolFloat { value: f64 },
3585    #[error("value {value:?} has non-numeric dtype {dtype:?}")]
3586    NonNumericValue { value: String, dtype: DType },
3587    #[error("value is missing ({kind:?})")]
3588    ValueIsMissing { kind: NullKind },
3589    #[error("sparse value dtype cannot be {dtype:?}")]
3590    InvalidSparseValueDType { dtype: DType },
3591    #[error("interval_range step must be finite, positive, and not NaN (got {step})")]
3592    InvalidIntervalStep { step: f64 },
3593    #[error("interval_range step {step} does not evenly divide range end-start={span}")]
3594    IntervalStepDoesNotDivide { step: f64, span: f64 },
3595    #[error("interval_range requires exactly 3 of (start, end, periods, freq) to be specified")]
3596    IntervalRangeParameterCount,
3597    #[error("cannot parse '{value}' as {target}")]
3598    ValueNotParseable { value: String, target: String },
3599}
3600
3601pub fn common_dtype(left: DType, right: DType) -> Result<DType, TypeError> {
3602    use DType::{
3603        Bool, BoolNullable, Categorical, Float64, Float64Nullable, Int64, Int64Nullable, Null,
3604        Sparse, Timedelta64,
3605    };
3606
3607    let out = match (&left, &right) {
3608        (a, b) if a == b => a.clone(),
3609        (Null, other) | (other, Null) => other.clone(),
3610        (Categorical, Categorical) => Categorical,
3611
3612        // Bool promotions (nullable absorbs non-nullable)
3613        (Bool, Int64) | (Int64, Bool) => Int64,
3614        (Bool, Int64Nullable) | (Int64Nullable, Bool) => Int64Nullable,
3615        (BoolNullable, Int64) | (Int64, BoolNullable) => Int64Nullable,
3616        (BoolNullable, Int64Nullable) | (Int64Nullable, BoolNullable) => Int64Nullable,
3617        (Bool, BoolNullable) | (BoolNullable, Bool) => BoolNullable,
3618        (Bool, Float64) | (Float64, Bool) => Float64,
3619        // MEASURED, live pandas 2.2.3:
3620        //     pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
3621        //         -> Float64        (the EXTENSION dtype, not numpy float64)
3622        // Flipped together with the Int64Nullable arm below; see the
3623        // associativity note there for why they cannot move independently.
3624        (BoolNullable, Float64) | (Float64, BoolNullable) => Float64Nullable,
3625
3626        // Int64 promotions (nullable absorbs non-nullable)
3627        (Int64, Float64) | (Float64, Int64) => Float64,
3628        // MEASURED, live pandas 2.2.3, both spellings agree:
3629        //     find_common_type([Int64, float64])                        -> Float64
3630        //     pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5])  -> Float64
3631        // i.e. the NULLABLE flavour wins, so the answer is Float64Nullable.
3632        //
3633        // ⚠ THIS ARM AND THE BoolNullable ARM ABOVE ARE ONE ATOMIC CHANGE. The
3634        // lattice is checked for associativity over ALL dtypes by
3635        // `common_dtype_lattice_axioms_be314`, and flipping only this arm breaks
3636        // it on (BoolNullable, Int64, Float64):
3637        //     (BN ∨ I64) ∨ F64 = Int64Nullable ∨ Float64 = Float64Nullable
3638        //     BN ∨ (I64 ∨ F64) = BN ∨ Float64            = Float64      ✗
3639        // Both arms flip, or neither does. (br-frankenpandas-qkqfb, unblocks
3640        // br-frankenpandas-f0aaa)
3641        (Int64Nullable, Float64) | (Float64, Int64Nullable) => Float64Nullable,
3642        (Int64, Int64Nullable) | (Int64Nullable, Int64) => Int64Nullable,
3643
3644        // Float64Nullable promotions. These are now REACHABLE: the two arms
3645        // above produce Float64Nullable, so anything that folds a dtype list
3646        // (melt's try_fold, combine_first's target_dtype) can feed it back in
3647        // here. They are what makes that fold associative.
3648        //
3649        // MEASURED, live pandas 2.2.3 ARITHMETIC (which is what this function
3650        // models -- see the Bool arms above, which follow arithmetic rather than
3651        // find_common_type, since find_common_type answers `object` for every
3652        // bool+numeric pair and FrankenPandas has no object dtype yet, that
3653        // being br-frankenpandas-hlcgl):
3654        //     Float64(ext) + float64(numpy)          -> Float64
3655        //     Int64(ext)   + Float64(ext)            -> Float64
3656        //     boolean(ext) + Float64(ext)            -> Float64
3657        // The nullable float absorbs every other numeric flavour, which also
3658        // makes it the top of the numeric lattice and keeps promotion
3659        // associative.
3660        (Float64Nullable, Float64) | (Float64, Float64Nullable) => Float64Nullable,
3661        (Float64Nullable, Int64) | (Int64, Float64Nullable) => Float64Nullable,
3662        (Float64Nullable, Int64Nullable) | (Int64Nullable, Float64Nullable) => Float64Nullable,
3663        (Float64Nullable, Bool) | (Bool, Float64Nullable) => Float64Nullable,
3664        (Float64Nullable, BoolNullable) | (BoolNullable, Float64Nullable) => Float64Nullable,
3665
3666        // Datetime/Timedelta
3667        (Timedelta64, Timedelta64) => Timedelta64,
3668        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
3669            if left_tz == right_tz =>
3670        {
3671            DType::Datetime64 {
3672                tz: left_tz.clone(),
3673            }
3674        }
3675
3676        (Sparse, _) | (_, Sparse) => {
3677            return Err(TypeError::IncompatibleDtypes {
3678                left: left.clone(),
3679                right: right.clone(),
3680            });
3681        }
3682        _ => {
3683            return Err(TypeError::IncompatibleDtypes { left, right });
3684        }
3685    };
3686
3687    Ok(out)
3688}
3689
3690pub fn infer_dtype(values: &[Scalar]) -> Result<DType, TypeError> {
3691    let mut current = DType::Null;
3692    let mut saw_utf8 = false;
3693    let mut saw_timedelta = false;
3694    let mut saw_datetime = false;
3695    let mut saw_non_utf8_non_null = false;
3696    // br-frankenpandas-rh1od: pandas constructs OBJECT columns whenever a
3697    // Python bool mixes with any numeric scalar ([True, 2] -> object,
3698    // measured live 2.2.3); numpy's bool<int common-type never fires at the
3699    // constructor. FrankenPandas coerced to Int64 here, which no pandas
3700    // constructor path produces. Strings already take the object bucket
3701    // below (DISC-005); bool+numeric joins them.
3702    let mut saw_bool = false;
3703    let mut saw_numeric = false;
3704    // A PeriodArray holds one freq: periods of two are incompatible, pandas'
3705    // object column of the periods as they are (their column held the first
3706    // freq, and a copy read the others in it - 2024-01 came back 2132Q1;
3707    // br-frankenpandas-h4bak).
3708    let mut period_freq: Option<PeriodFreq> = None;
3709
3710    // NOTE (br-frankenpandas-nywa8): inferring Float64 from a NaN-KIND missing
3711    // looks like the right central fix for pandas' int64 -> float64 promotion,
3712    // and it is NOT. `NullKind::NaN` is used throughout FrankenPandas as the
3713    // GENERIC missing marker, not specifically as "a float NaN" — e.g. short-row
3714    // padding and `missing_for_dtype(Float64)` both produce it. Promoting on it
3715    // broke 19 pre-existing fp-columnar tests (ffill returning Float64(1.0)
3716    // where Int64(1) was pinned, isin flipping a bool) because those columns are
3717    // legitimately Int64 with a generic missing. Measured, then reverted.
3718    //
3719    // The promotion has to be applied where a gap is INTRODUCED and the
3720    // introducer knows it is inventing one — see `concat_dataframes_*`, which
3721    // promotes locally. Do not move it back here without first giving
3722    // "pandas-introduced gap" a marker distinct from generic missingness.
3723    for value in values {
3724        if let Scalar::Period(period) = value
3725            && period.ordinal != i64::MIN
3726        {
3727            match period_freq {
3728                None => period_freq = Some(period.freq),
3729                Some(freq) if freq != period.freq => {
3730                    return Err(TypeError::IncompatibleDtypes {
3731                        left: DType::Period,
3732                        right: DType::Period,
3733                    });
3734                }
3735                Some(_) => {}
3736            }
3737        }
3738        match value.dtype() {
3739            DType::Null => {}
3740            DType::Utf8 => saw_utf8 = true,
3741            DType::Bool => {
3742                saw_bool = true;
3743                saw_non_utf8_non_null = true;
3744                current = common_dtype(current, DType::Bool)?;
3745            }
3746            DType::Int64 | DType::Float64 => {
3747                saw_numeric = true;
3748                saw_non_utf8_non_null = true;
3749                current = common_dtype(current, value.dtype())?;
3750            }
3751            DType::Timedelta64 => {
3752                saw_timedelta = true;
3753                if current == DType::Null {
3754                    current = DType::Timedelta64;
3755                } else if current != DType::Timedelta64 {
3756                    return Err(TypeError::IncompatibleDtypes {
3757                        left: current,
3758                        right: DType::Timedelta64,
3759                    });
3760                }
3761            }
3762            DType::Datetime64 { .. } => {
3763                saw_datetime = true;
3764                if current == DType::Null {
3765                    current = DType::datetime64_naive();
3766                } else if !current.is_datetime() {
3767                    return Err(TypeError::IncompatibleDtypes {
3768                        left: current,
3769                        right: DType::datetime64_naive(),
3770                    });
3771                }
3772            }
3773            other => {
3774                saw_non_utf8_non_null = true;
3775                current = common_dtype(current, other)?;
3776            }
3777        }
3778
3779        if saw_bool && saw_numeric {
3780            // Constructor inference follows pandas object-dtype behavior for
3781            // heterogeneous string/scalar payloads while arithmetic coercion
3782            // remains governed by the stricter common_dtype lattice.
3783            return Ok(DType::Utf8);
3784        }
3785        if saw_utf8 && saw_non_utf8_non_null {
3786            // Constructor inference follows pandas object-dtype behavior for
3787            // heterogeneous string/scalar payloads while arithmetic coercion
3788            // remains governed by the stricter common_dtype lattice.
3789            return Ok(DType::Utf8);
3790        }
3791        if saw_timedelta && saw_non_utf8_non_null {
3792            return Err(TypeError::IncompatibleDtypes {
3793                left: DType::Timedelta64,
3794                right: current,
3795            });
3796        }
3797        if saw_datetime && saw_non_utf8_non_null {
3798            return Err(TypeError::IncompatibleDtypes {
3799                left: DType::datetime64_naive(),
3800                right: current,
3801            });
3802        }
3803    }
3804
3805    if saw_utf8 {
3806        Ok(DType::Utf8)
3807    } else {
3808        Ok(current)
3809    }
3810}
3811
3812/// Cast a scalar to a target dtype, taking ownership to avoid redundant clones
3813/// when the value already has the correct type (AG-03: identity-cast skip).
3814pub fn cast_scalar_owned(value: Scalar, target: DType) -> Result<Scalar, TypeError> {
3815    let from = value.dtype();
3816    if from == target {
3817        return Ok(value);
3818    }
3819    // Int64 <-> Int64Nullable: same representation, just different dtype tracking
3820    if (from == DType::Int64 && target == DType::Int64Nullable)
3821        || (from == DType::Int64Nullable && target == DType::Int64)
3822    {
3823        return Ok(value);
3824    }
3825    // Bool <-> BoolNullable: same representation
3826    if (from == DType::Bool && target == DType::BoolNullable)
3827        || (from == DType::BoolNullable && target == DType::Bool)
3828    {
3829        return Ok(value);
3830    }
3831    // Float64 <-> Float64Nullable: same 8-byte payload, and a PRESENT value
3832    // round-trips unchanged in both directions. MEASURED, live pandas 2.2.3:
3833    //     pd.Series([1.5, None], dtype="Float64").astype("float64") -> [1.5, nan]
3834    //     pd.Series([1.5, None]).astype("Float64")                  -> [1.5, <NA>]
3835    // Only the MISSING marker differs, and a missing input never reaches here --
3836    // `value.is_missing()` below routes it to `missing_for_dtype(target)`, which
3837    // is what converts NaN <-> pd.NA. (br-frankenpandas-qkqfb)
3838    if (from == DType::Float64 && target == DType::Float64Nullable)
3839        || (from == DType::Float64Nullable && target == DType::Float64)
3840    {
3841        return Ok(value);
3842    }
3843    // A datetime scalar is an instant and a zone is its column's metadata, so
3844    // it takes any datetime64 dtype as it is (a fill or set value on a
3845    // tz-aware column was refused as an invalid cast).
3846    if from.is_datetime() && target.is_datetime() {
3847        return Ok(value);
3848    }
3849    if target == DType::Utf8 {
3850        return Ok(Scalar::Utf8(scalar_to_string_for_astype(value)));
3851    }
3852    // Per br-frankenpandas-cyi4h: pandas astype(bool) (the numpy bool dtype)
3853    // treats a float NaN as truthy -> True (bool(nan) is True), unlike the
3854    // nullable 'boolean' dtype which keeps NA. FP's NaN=missing model would
3855    // otherwise fall through to the missing branch below and yield a null.
3856    // Verified vs live pandas 2.2.3.
3857    if target == DType::Bool
3858        && let Scalar::Float64(v) = &value
3859        && v.is_nan()
3860    {
3861        return Ok(Scalar::Bool(true));
3862    }
3863    // TEMPORAL -> NUMPY bool IS NONZERO-TRUTHY ON THE RAW NANOSECONDS, and it
3864    // sits here for exactly the reason the NaN check above does: FP's
3865    // missing-value model would otherwise swallow NaT below, and pandas does not
3866    // treat it as missing here.
3867    //
3868    // MEASURED, live pandas 2.2.3, `.astype('bool')` beside `.astype('int64')`
3869    // so the rule is visible as one rule rather than four cases:
3870    //
3871    //   value                                 nanos                  bool
3872    //   Timestamp(0)                              0                 False
3873    //   Timestamp('2024-03-15 10:30:45.123..')  1.71e18               True
3874    //   Timestamp('1969-12-31 23:59:59.999..')       -1               True
3875    //   NaT (either dtype)          -9223372036854775808              True
3876    //   Timedelta(0)                              0                 False
3877    //   Timedelta('1 days')          86400000000000                   True
3878    //   Timedelta('-1 ns')                       -1                   True
3879    //
3880    // So `nanos != 0` is the whole rule, and NaT needs no case of its own: it IS
3881    // i64::MIN, which is nonzero. Only the epoch and a zero duration are False.
3882    //
3883    // ⚠️ THE NULLABLE `boolean` REFUSES ALL OF THESE, including the ones whose
3884    // nanos are 0 or 1 — `.astype('boolean')` raises "Need to pass bool-like
3885    // values" for EVERY row above, so it is the dtype it rejects, not the value.
3886    // That is why this is guarded on `DType::Bool` alone and why the strict
3887    // `BoolNullable` arm below is left without a temporal case.
3888    if target == DType::Bool {
3889        match &value {
3890            Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3891                return Ok(Scalar::Bool(*nanos != 0));
3892            }
3893            _ => {}
3894        }
3895    }
3896    // TEMPORAL -> NUMPY int64 IS RAW NANOSECONDS, and this sits ABOVE the
3897    // missing-value branch on purpose.
3898    //
3899    // MEASURED, live pandas 2.2.3:
3900    //     pd.Series([Timestamp('2024-03-15 10:30:45.123456789')]).astype('int64')
3901    //       -> 1710498645123456789
3902    //     pd.Series([Timedelta('1 days 02:03:04.005006007')]).astype('int64')
3903    //       -> 93784005006007
3904    //     pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
3905    //       -> -9223372036854775808        <- THE SENTINEL, not a missing value
3906    //
3907    // ⚠️ NaT IS WHY THE ORDER MATTERS. Below this point `value.is_missing()`
3908    // would turn NaT into `Null(Null)`, and pandas emphatically does not: it
3909    // hands back i64::MIN, which is the same bit pattern NaT already IS. Doing
3910    // the cast here makes the sentinel round-trip by construction rather than by
3911    // a second special case.
3912    //
3913    // ⚠️ NUMPY `int64` ONLY — the NULLABLE `Int64` REFUSES this, and so must we:
3914    //     .astype('Int64')   -> TypeError: datetime64[ns] cannot be converted
3915    //                          to IntegerDtype
3916    //     .astype('float64') -> TypeError: Cannot cast DatetimeArray to dtype
3917    //                          float64
3918    // which is why this is guarded on the exact target rather than folded into
3919    // the `Int64 | Int64Nullable` arm below, and why no Float64 arm is added.
3920    if target == DType::Int64 {
3921        match &value {
3922            Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3923                return Ok(Scalar::Int64(*nanos));
3924            }
3925            _ => {}
3926        }
3927    }
3928    if value.is_missing() {
3929        return Ok(Scalar::missing_for_dtype(target));
3930    }
3931
3932    // Note: identity casts (from == target) are handled above, so same-type
3933    // arms are omitted from the match below.
3934    match target {
3935        DType::Null => Ok(Scalar::Null(NullKind::Null)),
3936        DType::Bool => match &value {
3937            // numpy bool: zero -> False, ANY nonzero -> True (it does not
3938            // restrict to 0/1). e.g. bool of -3 / 2.5 is True.
3939            Scalar::Int64(v) => Ok(Scalar::Bool(*v != 0)),
3940            // 0.0 and -0.0 -> False; every other value, INCLUDING NaN, -> True
3941            // (NaN != 0.0 is true), matching numpy/pandas truthiness.
3942            Scalar::Float64(v) => Ok(Scalar::Bool(*v != 0.0)),
3943            _ => Err(TypeError::InvalidCast { from, to: target }),
3944        },
3945        DType::BoolNullable => match &value {
3946            // pandas nullable Boolean ('boolean') is STRICT: only 0/1 (or
3947            // True/False) are accepted — any other value raises "Need to pass
3948            // bool-like values", UNLIKE numpy bool which is nonzero-truthy.
3949            // (br-frankenpandas-tjomg)
3950            Scalar::Bool(b) => Ok(Scalar::Bool(*b)),
3951            Scalar::Int64(0) => Ok(Scalar::Bool(false)),
3952            Scalar::Int64(1) => Ok(Scalar::Bool(true)),
3953            Scalar::Int64(v) => Err(TypeError::InvalidBoolInt { value: *v }),
3954            Scalar::Float64(v) if *v == 0.0 => Ok(Scalar::Bool(false)),
3955            Scalar::Float64(v) if *v == 1.0 => Ok(Scalar::Bool(true)),
3956            Scalar::Float64(v) => Err(TypeError::InvalidBoolFloat { value: *v }),
3957            _ => Err(TypeError::InvalidCast { from, to: target }),
3958        },
3959        DType::Int64 | DType::Int64Nullable => match &value {
3960            Scalar::Bool(v) => Ok(Scalar::Int64(i64::from(*v))),
3961            Scalar::Float64(v) => {
3962                // pandas astype(int64) truncates a finite float toward zero
3963                // (1.9 -> 1, -1.9 -> -1, 2.5 -> 2); only non-finite (NaN/±inf)
3964                // or out-of-i64-range values raise. Verified vs pandas 2.2.3
3965                // (br-frankenpandas-qcutc). NaN is handled as missing above, so
3966                // here non-finite means ±inf. `as i64` performs the toward-zero
3967                // truncation for in-range finite values.
3968                if !v.is_finite() {
3969                    return Err(TypeError::LossyFloatToInt { value: *v });
3970                }
3971                if *v < i64::MIN as f64 || *v >= 9223372036854775808.0 {
3972                    return Err(TypeError::LossyFloatToInt { value: *v });
3973                }
3974                Ok(Scalar::Int64(*v as i64))
3975            }
3976            Scalar::Utf8(s) => {
3977                // Try direct int parse first, then try float parse + truncate
3978                // (pandas accepts "1.0" as valid int via float intermediate)
3979                if let Ok(v) = s.parse::<i64>() {
3980                    return Ok(Scalar::Int64(v));
3981                }
3982                if let Ok(f) = s.parse::<f64>()
3983                    && f.is_finite()
3984                    && f.fract() == 0.0
3985                    && f >= i64::MIN as f64
3986                    && f < 9223372036854775808.0
3987                {
3988                    return Ok(Scalar::Int64(f as i64));
3989                }
3990                Err(TypeError::InvalidCast { from, to: target })
3991            }
3992            _ => Err(TypeError::InvalidCast { from, to: target }),
3993        },
3994        // Both float flavours accept the same source values; they differ only in
3995        // the missing marker, which is handled above. MEASURED:
3996        //     pd.Series([1,None],dtype="Int64").astype("Float64") -> [1.0, <NA>]
3997        DType::Float64 | DType::Float64Nullable => match &value {
3998            Scalar::Bool(v) => Ok(Scalar::Float64(if *v { 1.0 } else { 0.0 })),
3999            Scalar::Int64(v) => Ok(Scalar::Float64(*v as f64)),
4000            Scalar::Utf8(s) => s
4001                .parse::<f64>()
4002                .map(Scalar::Float64)
4003                .map_err(|_| TypeError::InvalidCast { from, to: target }),
4004            _ => Err(TypeError::InvalidCast { from, to: target }),
4005        },
4006        DType::Utf8 => Ok(Scalar::Utf8(scalar_to_string_for_astype(value))),
4007        DType::Categorical => Err(TypeError::InvalidCast { from, to: target }),
4008        DType::Timedelta64 => match &value {
4009            // A BOOL IS 0 OR 1 NANOSECONDS on the astype path. Measured:
4010            //     pd.Series([True]).astype('timedelta64[ns]') -> 1ns
4011            //     pd.Series([True]).astype('datetime64[ns]')  -> 1970-01-01 ...001
4012            // ⚠️ The CONSTRUCTOR refuses the same thing —
4013            //     pd.DataFrame([[True]], dtype='datetime64[ns]')
4014            //       -> TypeError: dtype bool cannot be converted to datetime64[ns]
4015            // -- the same astype/constructor split `float_to_temporal_nanos`
4016            // documents for non-finite input. This cast is shared, so it takes
4017            // astype's answer and the constructor's refusal belongs in
4018            // `DataFrame::with_constructor_dtype`.
4019            Scalar::Bool(v) => Ok(Scalar::Timedelta64(i64::from(*v))),
4020            Scalar::Int64(v) => Ok(Scalar::Timedelta64(*v)),
4021            Scalar::Float64(v) => Ok(Scalar::Timedelta64(float_to_temporal_nanos(*v))),
4022            Scalar::Utf8(s) => Timedelta::parse(s)
4023                .map(Scalar::Timedelta64)
4024                .map_err(|_| TypeError::InvalidCast { from, to: target }),
4025            _ => Err(TypeError::InvalidCast { from, to: target }),
4026        },
4027        DType::Datetime64 { .. } => match &value {
4028            // See the Timedelta64 arm above for the measurement and for why the
4029            // constructor's stricter refusal is not encoded here.
4030            Scalar::Bool(v) => Ok(Scalar::Datetime64(i64::from(*v))),
4031            Scalar::Int64(v) => Ok(Scalar::Datetime64(*v)),
4032            Scalar::Float64(v) => Ok(Scalar::Datetime64(float_to_temporal_nanos(*v))),
4033            Scalar::Utf8(s) => Timestamp::parse(s)
4034                .map(|timestamp| Scalar::Datetime64(timestamp.nanos))
4035                .map_err(|_| TypeError::InvalidCast { from, to: target }),
4036            _ => Err(TypeError::InvalidCast { from, to: target }),
4037        },
4038        DType::Period => match &value {
4039            // Int cast to a freq-less DType::Period: default to Daily (pandas
4040            // requires an explicit freq in the dtype; ours is freq-less).
4041            Scalar::Int64(v) => Ok(Scalar::Period(Period::new(*v, PeriodFreq::Daily))),
4042            Scalar::Utf8(s) => Period::parse(s)
4043                .map(Scalar::Period)
4044                .map_err(|_| TypeError::InvalidCast { from, to: target }),
4045            _ => Err(TypeError::InvalidCast { from, to: target }),
4046        },
4047        DType::Interval => match &value {
4048            Scalar::Utf8(s) => Interval::parse(s)
4049                .map(Scalar::Interval)
4050                .map_err(|_| TypeError::InvalidCast { from, to: target }),
4051            _ => Err(TypeError::InvalidCast { from, to: target }),
4052        },
4053        DType::Sparse => Err(TypeError::InvalidCast { from, to: target }),
4054    }
4055}
4056
4057/// A float reinterpreted as integer NANOSECONDS, the way pandas casts to
4058/// `datetime64[ns]` / `timedelta64[ns]`.
4059///
4060/// ⚠️ THIS IS NOT THE `int64` RULE, and the difference is the whole reason this
4061/// helper exists rather than a reuse. The explicit constructor REFUSES a lossy
4062/// float -> int64 (`TypeError::LossyFloatToInt`, mirroring pandas' "Trying to
4063/// coerce float values to integers"), but the temporal dtypes silently truncate.
4064/// MEASURED side by side, live pandas 2.2.3, on the single value `1.5`:
4065///
4066/// ```text
4067/// pd.DataFrame([[1.5]], dtype="int64")           -> ValueError
4068/// pd.DataFrame([[1.5]], dtype="datetime64[ns]")  -> 1ns
4069/// pd.DataFrame([[1.5]], dtype="timedelta64[ns]") -> 1ns
4070/// ```
4071///
4072/// TRUNCATION IS TOWARD ZERO, NOT FLOOR. Measured on both signs, where the two
4073/// disagree: 0.9 -> 0 and -0.9 -> 0; 1.5 -> 1 and -1.5 -> -1; -2.5 -> -2 (a
4074/// floor would give -1, -2 and -3). Rust's `as i64` is exactly this truncation.
4075///
4076/// ANYTHING NOT REPRESENTABLE AS `i64` BECOMES NaT, which is why this cannot be
4077/// a bare `as` — Rust's saturating cast would hand back `i64::MAX` where pandas
4078/// hands back NaT, and would map NaN to 0, i.e. the epoch. Measured, all NaT:
4079/// NaN, +inf, -inf, 1e30, -1e30, 9.3e18, and exactly 2^63 and -2^63; while
4080/// 2^63 - 1024 IS representable and converts (2262-04-11 23:47:16.854774784).
4081/// The bounds are therefore strict on both ends — `i64::MIN as f64` is exactly
4082/// -2^63, which pandas already reads as NaT because it IS the NaT sentinel.
4083///
4084/// ⚠️ ONE KNOWN DIVERGENCE, RECORDED RATHER THAN GUESSED. For `timedelta64[ns]`
4085/// pandas' two paths disagree on the non-finite input: `astype` yields NaT but
4086/// the constructor raises OverflowError. `datetime64[ns]` has no such split —
4087/// both give NaT. This cast is shared by both paths, so it takes the behaviour
4088/// they agree on for datetimes and `astype`'s for timedeltas; the constructor's
4089/// stricter refusal belongs in `DataFrame::with_constructor_dtype`, which is
4090/// already where the constructor-only `int64`-rejects-NA check lives, and for
4091/// the same reason.
4092fn float_to_temporal_nanos(value: f64) -> i64 {
4093    // Strict on both ends: `i64::MIN as f64` and `i64::MAX as f64` are -2^63 and
4094    // 2^63, and pandas reads both of those as NaT.
4095    if value.is_finite() && value > (i64::MIN as f64) && value < (i64::MAX as f64) {
4096        // Truncates toward zero, and the guard above means it cannot saturate.
4097        value as i64
4098    } else {
4099        // `Timestamp::NAT` and `Timedelta::NAT` are the same value (`i64::MIN`),
4100        // so this one sentinel is correct for both callers.
4101        Timestamp::NAT
4102    }
4103}
4104
4105fn scalar_to_string_for_astype(value: Scalar) -> String {
4106    match value {
4107        Scalar::Null(NullKind::Null) => "None".to_owned(),
4108        Scalar::Null(NullKind::NaN) => "nan".to_owned(),
4109        Scalar::Null(NullKind::NaT) => "NaT".to_owned(),
4110        Scalar::Bool(true) => "True".to_owned(),
4111        Scalar::Bool(false) => "False".to_owned(),
4112        Scalar::Int64(v) => v.to_string(),
4113        Scalar::Float64(v) => float_to_string_for_astype(v),
4114        Scalar::Utf8(s) => s,
4115        Scalar::Timedelta64(v) if v == Timedelta::NAT => "NaT".to_owned(),
4116        Scalar::Timedelta64(v) => Timedelta::format(v),
4117        Scalar::Datetime64(v) if v == Timestamp::NAT => "NaT".to_owned(),
4118        Scalar::Datetime64(v) => timestamp_text(v),
4119        Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
4120        Scalar::Period(p) => p.calendar_string(),
4121        Scalar::Interval(v) => v.to_string(),
4122        // astype(str) of a list cell is its repr, of a host value its str.
4123        Scalar::Object(object) => object.to_string(),
4124    }
4125}
4126
4127pub fn float_to_string_for_astype(value: f64) -> String {
4128    use std::fmt::Write as _;
4129
4130    if value.is_nan() {
4131        return "nan".to_owned();
4132    }
4133    if value.is_infinite() {
4134        return value.to_string(); // "inf" / "-inf"
4135    }
4136    // pandas astype(str) renders floats via Python str(float): whole numbers
4137    // keep ".0", decimals use the shortest round-trip, and extreme magnitudes use
4138    // scientific notation ("1e+16", "1e-05"). Rust's Debug formatter matches this
4139    // (shortest round-trip, ".0" on whole numbers, scientific at Python's
4140    // boundaries); only the exponent spelling differs (Rust "1e16"/"1e-5" vs
4141    // Python "1e+16"/"1e-05"), so normalize that. The old `{:.1}` whole / Display
4142    // decimal path lost scientific notation (1e16 -> "10000000000000000.0").
4143    // Leave enough spare capacity for the positive sign and one exponent pad
4144    // digit, then normalize the formatter output in place. The former branch
4145    // allocated a second String and copied the mantissa solely to change
4146    // `e16`/`e-5` into pandas' `e+16`/`e-05` spelling.
4147    let mut rendered = String::with_capacity(32);
4148    let _ = write!(rendered, "{value:?}");
4149    let Some(exponent_marker) = rendered.find('e') else {
4150        return rendered;
4151    };
4152
4153    let sign_position = exponent_marker + 1;
4154    let digits_position = match rendered.as_bytes().get(sign_position) {
4155        Some(b'+' | b'-') => sign_position + 1,
4156        _ => {
4157            rendered.insert(sign_position, '+');
4158            sign_position + 1
4159        }
4160    };
4161    if rendered.len() - digits_position == 1 {
4162        rendered.insert(digits_position, '0');
4163    }
4164    rendered
4165}
4166
4167static ENG_FLOAT_ACCURACY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(3);
4168static ENG_FLOAT_USE_PREFIX: std::sync::atomic::AtomicBool =
4169    std::sync::atomic::AtomicBool::new(false);
4170static ENG_FLOAT_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
4171
4172/// Format float values according to engineering format, matching pandas `EngFormatter`.
4173pub fn eng_float_format(num: f64, accuracy: Option<usize>, use_eng_prefix: bool) -> String {
4174    if num.is_nan() {
4175        return "NaN".to_string();
4176    }
4177    if num.is_infinite() {
4178        return if num < 0.0 {
4179            "-inf".to_string()
4180        } else {
4181            "inf".to_string()
4182        };
4183    }
4184
4185    let sign = if num < 0.0 { -1.0 } else { 1.0 };
4186    let abs_num = num.abs();
4187
4188    let pow10 = if abs_num != 0.0 {
4189        let p = (abs_num.log10() / 3.0).floor() as i32 * 3;
4190        p.clamp(-24, 24)
4191    } else {
4192        0
4193    };
4194
4195    let prefix = if use_eng_prefix {
4196        match pow10 {
4197            -24 => "y",
4198            -21 => "z",
4199            -18 => "a",
4200            -15 => "f",
4201            -12 => "p",
4202            -9 => "n",
4203            -6 => "u",
4204            -3 => "m",
4205            0 => "",
4206            3 => "k",
4207            6 => "M",
4208            9 => "G",
4209            12 => "T",
4210            15 => "P",
4211            18 => "E",
4212            21 => "Z",
4213            24 => "Y",
4214            _ => "",
4215        }
4216        .to_string()
4217    } else if pow10 < 0 {
4218        format!("E-{:02}", -pow10)
4219    } else {
4220        format!("E+{:02}", pow10)
4221    };
4222
4223    let mant = (sign * abs_num) / 10f64.powi(pow10);
4224
4225    if let Some(acc) = accuracy {
4226        format!("{mant:.acc$}{prefix}", acc = acc)
4227    } else {
4228        format!("{mant}{prefix}")
4229    }
4230}
4231
4232/// Set pandas-compatible engineering float formatting option.
4233/// Matches `pd.set_eng_float_format(accuracy=3, use_eng_prefix=False)`.
4234pub fn set_eng_float_format(accuracy: usize, use_eng_prefix: bool) {
4235    use std::sync::atomic::Ordering;
4236    ENG_FLOAT_ACCURACY.store(accuracy, Ordering::Relaxed);
4237    ENG_FLOAT_USE_PREFIX.store(use_eng_prefix, Ordering::Relaxed);
4238    ENG_FLOAT_ACTIVE.store(true, Ordering::Relaxed);
4239}
4240
4241/// Reset engineering float formatting back to default.
4242pub fn reset_eng_float_format() {
4243    use std::sync::atomic::Ordering;
4244    ENG_FLOAT_ACTIVE.store(false, Ordering::Relaxed);
4245}
4246
4247/// Get the current engineering float format configuration if active.
4248pub fn get_eng_float_format() -> Option<(usize, bool)> {
4249    use std::sync::atomic::Ordering;
4250    if ENG_FLOAT_ACTIVE.load(Ordering::Relaxed) {
4251        Some((
4252            ENG_FLOAT_ACCURACY.load(Ordering::Relaxed),
4253            ENG_FLOAT_USE_PREFIX.load(Ordering::Relaxed),
4254        ))
4255    } else {
4256        None
4257    }
4258}
4259
4260// ── Global Configuration Options (matching pd.options) ───────────────────
4261
4262/// Error encountered when inspecting or modifying configuration options.
4263#[derive(Debug, Error, Clone, PartialEq, Eq)]
4264pub enum OptionError {
4265    #[error("no such option: '{pat}'")]
4266    NotFound { pat: String },
4267    #[error("option pattern '{pat}' matches multiple options: {matches:?}")]
4268    Ambiguous { pat: String, matches: Vec<String> },
4269    #[error("invalid option value for '{pat}': {reason}")]
4270    InvalidValue { pat: String, reason: String },
4271}
4272
4273/// Represents a configuration option value, matching pandas `pd.options`.
4274#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4275pub enum OptionValue {
4276    None,
4277    Int(i64),
4278    Float(f64),
4279    Bool(bool),
4280    Str(String),
4281}
4282
4283impl OptionValue {
4284    #[must_use]
4285    pub const fn is_none(&self) -> bool {
4286        matches!(self, Self::None)
4287    }
4288
4289    #[must_use]
4290    pub const fn as_int(&self) -> Option<i64> {
4291        match self {
4292            Self::Int(i) => Some(*i),
4293            _ => None,
4294        }
4295    }
4296
4297    #[must_use]
4298    pub const fn as_float(&self) -> Option<f64> {
4299        match self {
4300            Self::Float(f) => Some(*f),
4301            _ => None,
4302        }
4303    }
4304
4305    #[must_use]
4306    pub const fn as_bool(&self) -> Option<bool> {
4307        match self {
4308            Self::Bool(b) => Some(*b),
4309            _ => None,
4310        }
4311    }
4312
4313    #[must_use]
4314    pub fn as_str(&self) -> Option<&str> {
4315        match self {
4316            Self::Str(s) => Some(s.as_str()),
4317            _ => None,
4318        }
4319    }
4320}
4321
4322impl std::fmt::Display for OptionValue {
4323    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4324        match self {
4325            Self::None => write!(f, "None"),
4326            Self::Int(i) => write!(f, "{i}"),
4327            Self::Float(fl) => write!(f, "{fl}"),
4328            Self::Bool(b) => write!(f, "{b}"),
4329            Self::Str(s) => write!(f, "{s}"),
4330        }
4331    }
4332}
4333
4334impl From<i64> for OptionValue {
4335    fn from(v: i64) -> Self {
4336        Self::Int(v)
4337    }
4338}
4339
4340impl From<i32> for OptionValue {
4341    fn from(v: i32) -> Self {
4342        Self::Int(i64::from(v))
4343    }
4344}
4345
4346impl From<usize> for OptionValue {
4347    fn from(v: usize) -> Self {
4348        Self::Int(i64::try_from(v).unwrap_or(i64::MAX))
4349    }
4350}
4351
4352impl From<f64> for OptionValue {
4353    fn from(v: f64) -> Self {
4354        Self::Float(v)
4355    }
4356}
4357
4358impl From<bool> for OptionValue {
4359    fn from(v: bool) -> Self {
4360        Self::Bool(v)
4361    }
4362}
4363
4364impl From<&str> for OptionValue {
4365    fn from(v: &str) -> Self {
4366        Self::Str(v.to_string())
4367    }
4368}
4369
4370impl From<String> for OptionValue {
4371    fn from(v: String) -> Self {
4372        Self::Str(v)
4373    }
4374}
4375
4376impl From<()> for OptionValue {
4377    fn from(_: ()) -> Self {
4378        Self::None
4379    }
4380}
4381
4382fn default_options_map() -> std::collections::BTreeMap<String, OptionValue> {
4383    let mut m = std::collections::BTreeMap::new();
4384    m.insert("display.max_rows".to_string(), OptionValue::Int(60));
4385    m.insert("display.min_rows".to_string(), OptionValue::Int(10));
4386    m.insert("display.max_columns".to_string(), OptionValue::Int(0));
4387    m.insert("display.width".to_string(), OptionValue::Int(80));
4388    m.insert("display.precision".to_string(), OptionValue::Int(6));
4389    m.insert("display.max_colwidth".to_string(), OptionValue::Int(50));
4390    m.insert(
4391        "display.show_dimensions".to_string(),
4392        OptionValue::Bool(true),
4393    );
4394    m.insert("display.float_format".to_string(), OptionValue::None);
4395    m.insert(
4396        "display.large_repr".to_string(),
4397        OptionValue::Str("truncate".to_string()),
4398    );
4399    m.insert(
4400        "display.max_info_columns".to_string(),
4401        OptionValue::Int(100),
4402    );
4403    m.insert(
4404        "display.max_info_rows".to_string(),
4405        OptionValue::Int(1690785),
4406    );
4407    m.insert("display.memory_usage".to_string(), OptionValue::Bool(true));
4408    m.insert(
4409        "display.colheader_justify".to_string(),
4410        OptionValue::Str("right".to_string()),
4411    );
4412    m.insert("display.chop_threshold".to_string(), OptionValue::None);
4413    m.insert(
4414        "display.date_dayfirst".to_string(),
4415        OptionValue::Bool(false),
4416    );
4417    m.insert(
4418        "display.date_yearfirst".to_string(),
4419        OptionValue::Bool(false),
4420    );
4421    m.insert(
4422        "display.encoding".to_string(),
4423        OptionValue::Str("utf-8".to_string()),
4424    );
4425    m.insert("mode.sim_interactive".to_string(), OptionValue::Bool(false));
4426    m.insert(
4427        "mode.chained_assignment".to_string(),
4428        OptionValue::Str("warn".to_string()),
4429    );
4430    m.insert("mode.use_inf_as_na".to_string(), OptionValue::Bool(false));
4431    m.insert("mode.copy_on_write".to_string(), OptionValue::Bool(false));
4432    m.insert(
4433        "mode.data_manager".to_string(),
4434        OptionValue::Str("block".to_string()),
4435    );
4436    m.insert(
4437        "compute.use_bottleneck".to_string(),
4438        OptionValue::Bool(true),
4439    );
4440    m.insert("compute.use_numba".to_string(), OptionValue::Bool(false));
4441    m.insert(
4442        "io.excel.zip.reader".to_string(),
4443        OptionValue::Str("zipfile".to_string()),
4444    );
4445    m.insert(
4446        "io.parquet.engine".to_string(),
4447        OptionValue::Str("auto".to_string()),
4448    );
4449    m.insert(
4450        "io.sql.engine".to_string(),
4451        OptionValue::Str("auto".to_string()),
4452    );
4453    m.insert(
4454        "plotting.backend".to_string(),
4455        OptionValue::Str("matplotlib".to_string()),
4456    );
4457    m.insert(
4458        "plotting.matplotlib.register_converters".to_string(),
4459        OptionValue::Bool(true),
4460    );
4461    m
4462}
4463
4464static GLOBAL_OPTIONS: std::sync::LazyLock<
4465    std::sync::Mutex<std::collections::BTreeMap<String, OptionValue>>,
4466> = std::sync::LazyLock::new(|| std::sync::Mutex::new(default_options_map()));
4467
4468fn resolve_option_key(
4469    pat: &str,
4470    map: &std::collections::BTreeMap<String, OptionValue>,
4471) -> Result<String, OptionError> {
4472    if map.contains_key(pat) {
4473        return Ok(pat.to_string());
4474    }
4475    let matches: Vec<String> = map
4476        .keys()
4477        .filter(|k| k.ends_with(pat) || k.contains(pat))
4478        .cloned()
4479        .collect();
4480    if matches.len() == 1 {
4481        Ok(matches[0].clone())
4482    } else if matches.is_empty() {
4483        Err(OptionError::NotFound {
4484            pat: pat.to_string(),
4485        })
4486    } else {
4487        Err(OptionError::Ambiguous {
4488            pat: pat.to_string(),
4489            matches,
4490        })
4491    }
4492}
4493
4494/// Retrieve the current value of a configuration option, matching `pd.get_option(pat)`.
4495///
4496/// # Errors
4497/// Returns [`OptionError::NotFound`] if `pat` does not match any known option,
4498/// or [`OptionError::Ambiguous`] if it matches multiple options.
4499pub fn get_option(pat: &str) -> Result<OptionValue, OptionError> {
4500    let map = GLOBAL_OPTIONS
4501        .lock()
4502        .unwrap_or_else(std::sync::PoisonError::into_inner);
4503    let key = resolve_option_key(pat, &map)?;
4504    Ok(map.get(&key).cloned().unwrap_or(OptionValue::None))
4505}
4506
4507/// Set the value of a configuration option, matching `pd.set_option(pat, value)`.
4508///
4509/// # Errors
4510/// Returns [`OptionError::NotFound`] if `pat` does not match any known option,
4511/// or [`OptionError::Ambiguous`] if it matches multiple options.
4512pub fn set_option(pat: &str, val: impl Into<OptionValue>) -> Result<(), OptionError> {
4513    let mut map = GLOBAL_OPTIONS
4514        .lock()
4515        .unwrap_or_else(std::sync::PoisonError::into_inner);
4516    let key = resolve_option_key(pat, &map)?;
4517    let v = val.into();
4518    map.insert(key, v);
4519    Ok(())
4520}
4521
4522/// Reset one or all configuration options to their defaults, matching `pd.reset_option(pat)`.
4523///
4524/// If `pat` is `None` or `"all"`, all options are reset to defaults.
4525///
4526/// # Errors
4527/// Returns [`OptionError::NotFound`] or [`OptionError::Ambiguous`] if `pat` does not uniquely match an option.
4528pub fn reset_option(pat: Option<&str>) -> Result<(), OptionError> {
4529    let mut map = GLOBAL_OPTIONS
4530        .lock()
4531        .unwrap_or_else(std::sync::PoisonError::into_inner);
4532    let defaults = default_options_map();
4533    let p = pat.unwrap_or("all");
4534    if p == "all" {
4535        *map = defaults;
4536        return Ok(());
4537    }
4538    let key = resolve_option_key(p, &defaults)?;
4539    if let Some(def_val) = defaults.get(&key) {
4540        map.insert(key, def_val.clone());
4541    }
4542    Ok(())
4543}
4544
4545/// Return formatted descriptions of one or all options, matching `pd.describe_option(pat)`.
4546///
4547/// # Errors
4548/// Returns [`OptionError::NotFound`] if `pat` is provided but matches no options.
4549pub fn describe_option(pat: Option<&str>) -> Result<String, OptionError> {
4550    use std::fmt::Write as _;
4551    let map = GLOBAL_OPTIONS
4552        .lock()
4553        .unwrap_or_else(std::sync::PoisonError::into_inner);
4554    let mut out = String::with_capacity(map.len() * 40);
4555    let mut matched = 0;
4556    for (k, v) in map.iter() {
4557        if let Some(p) = pat
4558            && !k.contains(p)
4559        {
4560            continue;
4561        }
4562        if matched > 0 {
4563            out.push('\n');
4564        }
4565        let _ = write!(out, "{k} : [currently: {v}]");
4566        matched += 1;
4567    }
4568    if matched == 0
4569        && let Some(p) = pat
4570    {
4571        return Err(OptionError::NotFound { pat: p.to_string() });
4572    }
4573    Ok(out)
4574}
4575
4576/// RAII scope guard that restores options to their prior values when dropped.
4577#[derive(Debug)]
4578pub struct OptionContextGuard {
4579    saved: Vec<(String, OptionValue)>,
4580}
4581
4582impl Drop for OptionContextGuard {
4583    fn drop(&mut self) {
4584        let mut map = GLOBAL_OPTIONS
4585            .lock()
4586            .unwrap_or_else(std::sync::PoisonError::into_inner);
4587        for (k, old) in self.saved.drain(..) {
4588            map.insert(k, old);
4589        }
4590    }
4591}
4592
4593/// Temporarily override options within a scoped context, matching `pd.option_context(...)`.
4594///
4595/// # Errors
4596/// Returns [`OptionError::NotFound`] or [`OptionError::Ambiguous`] if any pattern is invalid.
4597pub fn option_context(entries: &[(&str, OptionValue)]) -> Result<OptionContextGuard, OptionError> {
4598    let mut map = GLOBAL_OPTIONS
4599        .lock()
4600        .unwrap_or_else(std::sync::PoisonError::into_inner);
4601    let mut saved = Vec::with_capacity(entries.len());
4602    for (pat, new_val) in entries {
4603        let key = resolve_option_key(pat, &map)?;
4604        if let Some(old) = map.get(&key) {
4605            saved.push((key.clone(), old.clone()));
4606        }
4607        map.insert(key, new_val.clone());
4608    }
4609    Ok(OptionContextGuard { saved })
4610}
4611
4612/// Cast a scalar reference to a target dtype (clones only when conversion is needed).
4613pub fn cast_scalar(value: &Scalar, target: DType) -> Result<Scalar, TypeError> {
4614    cast_scalar_owned(value.clone(), target)
4615}
4616
4617// ── Timedelta support ──────────────────────────────────────────────────
4618
4619#[derive(Debug, Error, Clone, PartialEq)]
4620pub enum TimedeltaError {
4621    #[error("invalid timedelta string: {0}")]
4622    InvalidFormat(String),
4623    #[error("overflow in timedelta computation")]
4624    Overflow,
4625}
4626
4627impl TimedeltaError {
4628    /// The pandas exception class this corresponds to, per
4629    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2.
4630    ///
4631    /// Returns `None` for [`Self::InvalidFormat`], which is a parse failure
4632    /// rather than a member of the temporal-arithmetic taxonomy.
4633    #[must_use]
4634    pub const fn pandas_error(&self) -> Option<PandasTemporalError> {
4635        match self {
4636            // Probed: pd.Timedelta(float('inf'), 's') raises
4637            // OutOfBoundsTimedelta, NOT a bare OverflowError.
4638            Self::Overflow => Some(PandasTemporalError::OutOfBoundsTimedelta),
4639            Self::InvalidFormat(_) => None,
4640        }
4641    }
4642}
4643
4644#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4645pub struct CategoricalMetadata {
4646    /// The unique category values, in order.
4647    pub categories: Vec<Scalar>,
4648    /// Whether the categories have a meaningful total ordering.
4649    pub ordered: bool,
4650}
4651
4652impl CategoricalMetadata {
4653    #[must_use]
4654    pub fn new(categories: Vec<Scalar>, ordered: bool) -> Self {
4655        Self {
4656            categories,
4657            ordered,
4658        }
4659    }
4660}
4661
4662#[derive(Debug, Clone, Copy, Default)]
4663pub struct TimedeltaComponents {
4664    pub days: i64,
4665    pub hours: i64,
4666    pub minutes: i64,
4667    pub seconds: i64,
4668    pub milliseconds: i64,
4669    pub microseconds: i64,
4670    pub nanoseconds: i64,
4671}
4672
4673/// The pandas-side exception class a failed temporal operation corresponds to.
4674///
4675/// Introduced by br-frankenpandas-fyr1z-policy-carrier-f29nz and completed by
4676/// fyr1z.3, which established that pandas uses FIVE distinct classes here — so
4677/// a STRICT arm must raise the RIGHT one per op rather than a blanket type.
4678/// Every mapping below was probed against live pandas 2.2.3, not inferred.
4679///
4680/// Named `...TemporalError` rather than `...OverflowError` because
4681/// [`Self::ZeroDivision`] is not an overflow; a type whose name promised
4682/// "overflow" while carrying divide-by-zero would be exactly the kind of stale
4683/// label this codebase keeps having to correct.
4684#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4685pub enum PandasTemporalError {
4686    /// `OverflowError`. e.g. `pd.Timedelta.max + pd.Timedelta('1ns')`, and
4687    /// `Series + Timedelta` / `Series - Series` / `.diff()` which report
4688    /// "Overflow in int64 addition".
4689    Overflow,
4690    /// `OutOfBoundsDatetime`. e.g. `pd.Timestamp.max + pd.Timedelta('1ns')`
4691    /// and `pd.Timestamp.min - pd.Timestamp.max`.
4692    OutOfBoundsDatetime,
4693    /// `OutOfBoundsTimedelta`. Raised by the `pd.Timedelta(value, unit=...)`
4694    /// constructor path (see br-frankenpandas-8v92m), not by the six
4695    /// arithmetic helpers below. Probed: `pd.Timedelta(float('inf'), 's')` ->
4696    /// "Cannot cast inf from s to 'ns' without overflow."
4697    OutOfBoundsTimedelta,
4698    /// `ValueError("overflow in timedelta operation")`. Raised by the
4699    /// REDUCTIONS `Series.sum()` and `Series.std()` over timedelta64.
4700    OverflowInTimedeltaOperation,
4701    /// `ZeroDivisionError`. Raised by SCALAR `Timedelta // 0`, `Timedelta / 0`
4702    /// and `Timedelta // 0.0` ONLY.
4703    ///
4704    /// ⚠ The VECTORIZED division family does NOT raise: probed,
4705    /// `Series([Timedelta]) // 0` and `/ 0` both return NaT. A STRICT arm must
4706    /// not widen this class to the vectorized surface — doing so would create
4707    /// divergence where FrankenPandas is already bit-for-bit correct, which is
4708    /// the central finding of br-frankenpandas-fyr1z (see DISC-018).
4709    ZeroDivision,
4710}
4711
4712/// A temporal overflow, naming the operation that overflowed and the pandas
4713/// exception it corresponds to.
4714#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4715pub struct TemporalFailure {
4716    /// The FrankenPandas operation, e.g. `"Timedelta::add"`.
4717    pub op: &'static str,
4718    /// What pandas raises for this operation.
4719    pub pandas_error: PandasTemporalError,
4720    /// The operand pair whose exact result left the representable range, when
4721    /// the failing operation had one. Carried for the HARDENED audit trail
4722    /// (br-frankenpandas-fyr1z-hardened-audit-vllv6) so a recovery entry can
4723    /// name the range violation rather than merely that one occurred.
4724    pub operands: Option<(i64, i64)>,
4725}
4726
4727impl TemporalFailure {
4728    #[must_use]
4729    pub const fn new(op: &'static str, pandas_error: PandasTemporalError) -> Self {
4730        Self {
4731            op,
4732            pandas_error,
4733            operands: None,
4734        }
4735    }
4736
4737    /// Attach the operands that produced this failure.
4738    #[must_use]
4739    pub const fn with_operands(mut self, lhs: i64, rhs: i64) -> Self {
4740        self.operands = Some((lhs, rhs));
4741        self
4742    }
4743}
4744
4745/// A bounded defensive recovery that HARDENED mode performed, recorded so a run
4746/// can be audited after the fact.
4747///
4748/// br-frankenpandas-fyr1z-hardened-audit-vllv6. AGENTS.md's security doctrine
4749/// requires "deterministic audit logs for recoveries and policy overrides", and
4750/// overflow-to-NaT is exactly a bounded defensive recovery. Until now it was
4751/// SILENT: a caller could not distinguish a NaT produced by an overflow from a
4752/// NaT that was already in the input, which is the whole substance of the
4753/// DISC-018 impact statement.
4754#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4755pub struct TemporalRecovery {
4756    /// The operation that overflowed.
4757    pub op: &'static str,
4758    /// The pandas exception this would have been under STRICT.
4759    pub pandas_error: PandasTemporalError,
4760    /// The operands whose exact result was unrepresentable, when known.
4761    pub operands: Option<(i64, i64)>,
4762    /// The value actually returned. Always the family's NaT sentinel today.
4763    pub recovered_as: i64,
4764}
4765
4766/// Deterministic, opt-in audit trail for HARDENED-mode recoveries.
4767///
4768/// Disabled by default and costs one `Option` check when off, so the default
4769/// path is unchanged. The log is THREAD-LOCAL: FrankenPandas parallelises many
4770/// kernels, and a shared log would impose a lock on hot arithmetic and make the
4771/// entry ORDER nondeterministic — which would defeat the point. Each worker
4772/// therefore accumulates its own deterministic sequence; a caller auditing a
4773/// parallel op drains per thread.
4774pub mod overflow_audit {
4775    use std::cell::RefCell;
4776
4777    use super::TemporalRecovery;
4778
4779    thread_local! {
4780        static LOG: RefCell<Option<Vec<TemporalRecovery>>> = const { RefCell::new(None) };
4781    }
4782
4783    /// Begin recording on THIS thread, discarding anything already buffered.
4784    pub fn enable() {
4785        LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
4786    }
4787
4788    /// Stop recording on this thread and discard the buffer.
4789    pub fn disable() {
4790        LOG.with(|log| *log.borrow_mut() = None);
4791    }
4792
4793    /// Whether recording is active on this thread.
4794    #[must_use]
4795    pub fn is_enabled() -> bool {
4796        LOG.with(|log| log.borrow().is_some())
4797    }
4798
4799    /// Take the recorded recoveries, leaving recording enabled and empty.
4800    #[must_use]
4801    pub fn drain() -> Vec<TemporalRecovery> {
4802        LOG.with(|log| match log.borrow_mut().as_mut() {
4803            Some(entries) => std::mem::take(entries),
4804            None => Vec::new(),
4805        })
4806    }
4807
4808    /// Record a recovery. A no-op — and allocation-free — when disabled.
4809    pub(super) fn record(entry: TemporalRecovery) {
4810        LOG.with(|log| {
4811            if let Some(entries) = log.borrow_mut().as_mut() {
4812                entries.push(entry);
4813            }
4814        });
4815    }
4816}
4817
4818/// How a temporal overflow should be surfaced.
4819///
4820/// br-frankenpandas-fyr1z-policy-carrier-f29nz adds this carrier WITHOUT
4821/// changing any default behavior: every existing call site is on
4822/// [`OverflowPolicy::SurfaceNat`], which is exactly what the codebase did
4823/// before. `Strict` exists so fyr1z.3 can wire per-op raise arms in a separate,
4824/// reviewable step, and NOTHING routes to it yet.
4825///
4826/// Note DISC-018: a blanket "STRICT raises everywhere" is NOT pandas parity —
4827/// pandas silently wraps on `Series * int` and `.cumsum()`, and returns NaT for
4828/// `.mean()`. The strict arm therefore needs a per-op table, which is why the
4829/// policy is carried per operation rather than set globally.
4830#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
4831pub enum OverflowPolicy {
4832    /// Today's behavior, and the only arm currently wired up: overflow becomes
4833    /// the family's NaT sentinel.
4834    #[default]
4835    SurfaceNat,
4836    /// Reserved for fyr1z.3. Surfaces the [`TemporalFailure`] to the caller.
4837    Strict,
4838    /// HARDENED mode (br-frankenpandas-fyr1z-hardened-audit-vllv6): returns the
4839    /// SAME NaT as [`Self::SurfaceNat`], bit-for-bit, and additionally records a
4840    /// [`TemporalRecovery`] into [`overflow_audit`] when that log is enabled.
4841    ///
4842    /// This adds observability, never semantics. AGENTS.md defines hardened
4843    /// mode as "bounded defensive recovery" and requires a deterministic audit
4844    /// log for exactly that.
4845    HardenedNat,
4846}
4847
4848impl OverflowPolicy {
4849    /// Resolve a fallible temporal result under this policy.
4850    ///
4851    /// `SurfaceNat` discards the overflow and yields `nat`, reproducing the
4852    /// pre-f29nz behavior bit-for-bit. `Strict` propagates the overflow.
4853    ///
4854    /// # Errors
4855    /// Returns the [`TemporalFailure`] unchanged under [`Self::Strict`].
4856    pub fn resolve<T>(
4857        self,
4858        outcome: Result<T, TemporalFailure>,
4859        nat: T,
4860    ) -> Result<T, TemporalFailure> {
4861        self.resolve_recording(outcome, nat, i64::MIN)
4862    }
4863
4864    /// [`Self::resolve`] plus the sentinel value to record in the audit trail.
4865    ///
4866    /// Split out because the recovered value is generic (`T`) but the audit
4867    /// entry needs its i64 backing; `recovered_as` supplies that without
4868    /// constraining `T`.
4869    ///
4870    /// # Errors
4871    /// Returns the [`TemporalFailure`] unchanged under [`Self::Strict`].
4872    pub fn resolve_recording<T>(
4873        self,
4874        outcome: Result<T, TemporalFailure>,
4875        nat: T,
4876        recovered_as: i64,
4877    ) -> Result<T, TemporalFailure> {
4878        match (self, outcome) {
4879            (_, Ok(value)) => Ok(value),
4880            (Self::SurfaceNat, Err(_)) => Ok(nat),
4881            (Self::Strict, Err(failure)) => Err(failure),
4882            (Self::HardenedNat, Err(failure)) => {
4883                // Same value as SurfaceNat; the ONLY difference is the record.
4884                overflow_audit::record(TemporalRecovery {
4885                    op: failure.op,
4886                    pandas_error: failure.pandas_error,
4887                    operands: failure.operands,
4888                    recovered_as,
4889                });
4890                Ok(nat)
4891            }
4892        }
4893    }
4894}
4895
4896pub struct Timedelta;
4897
4898impl Timedelta {
4899    pub const NANOS_PER_MICRO: i64 = 1_000;
4900    pub const NANOS_PER_MILLI: i64 = 1_000_000;
4901    pub const NANOS_PER_SEC: i64 = 1_000_000_000;
4902    pub const NANOS_PER_MIN: i64 = 60 * Self::NANOS_PER_SEC;
4903    pub const NANOS_PER_HOUR: i64 = 60 * Self::NANOS_PER_MIN;
4904    pub const NANOS_PER_DAY: i64 = 24 * Self::NANOS_PER_HOUR;
4905    pub const NANOS_PER_WEEK: i64 = 7 * Self::NANOS_PER_DAY;
4906
4907    pub const NAT: i64 = i64::MIN;
4908
4909    pub fn parse(s: &str) -> Result<i64, TimedeltaError> {
4910        let s = s.trim();
4911
4912        if s.eq_ignore_ascii_case("nat") {
4913            return Ok(Self::NAT);
4914        }
4915
4916        let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
4917            (true, rest.trim())
4918        } else {
4919            (false, s)
4920        };
4921
4922        if let Some(nanos) = Self::try_parse_time_format(s) {
4923            return Ok(if negative { -nanos } else { nanos });
4924        }
4925
4926        if let Some(nanos) = Self::try_parse_iso8601_duration(s) {
4927            return Ok(if negative { -nanos } else { nanos });
4928        }
4929
4930        // pandas' leading '-' negates the unit values but not an HH:MM:SS
4931        // part that follows one: "-1 days +02:03:04" (how pandas prints a
4932        // negative Timedelta) is -1 day + 2:03:04. Negating the whole
4933        // compound read it as -(1 day 2:03:04), so a printed Timedelta did
4934        // not parse back to itself.
4935        let (units, clock) = Self::parse_compound(s)?;
4936        let units = if negative { -units } else { units };
4937        units.checked_add(clock).ok_or(TimedeltaError::Overflow)
4938    }
4939
4940    /// Parse an ISO-8601 duration the way pandas `Timedelta` accepts it:
4941    /// a leading uppercase `P`, an optional `T` separator that is otherwise
4942    /// ignored, and unit letters `W`/`D`/`H`/`M`/`S` in any position. `M` is
4943    /// always MINUTES (never months), and only seconds may be fractional —
4944    /// years/months and lowercase units are rejected, matching pandas.
4945    /// (pandas mis-handles fractional non-second components; those are rejected
4946    /// here rather than reproducing the buggy value.) (br-frankenpandas-c3p8b)
4947    fn try_parse_iso8601_duration(s: &str) -> Option<i64> {
4948        let mut rest = s.strip_prefix('P')?;
4949        if rest.is_empty() {
4950            return None;
4951        }
4952        let mut total: i64 = 0;
4953        let mut saw_component = false;
4954        while !rest.is_empty() {
4955            if let Some(after_t) = rest.strip_prefix('T') {
4956                rest = after_t;
4957                continue;
4958            }
4959            let num_end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')?;
4960            if num_end == 0 {
4961                return None;
4962            }
4963            let num_str = &rest[..num_end];
4964            let unit = rest.as_bytes()[num_end];
4965            let is_fractional = num_str.contains('.');
4966            rest = &rest[num_end + 1..];
4967
4968            let (multiplier, frac_ok) = match unit {
4969                b'W' => (Self::NANOS_PER_WEEK, false),
4970                b'D' => (Self::NANOS_PER_DAY, false),
4971                b'H' => (Self::NANOS_PER_HOUR, false),
4972                b'M' => (Self::NANOS_PER_MIN, false),
4973                b'S' => (Self::NANOS_PER_SEC, true),
4974                _ => return None,
4975            };
4976            if is_fractional {
4977                if !frac_ok {
4978                    return None;
4979                }
4980                let value: f64 = num_str.parse().ok()?;
4981                let product = value * multiplier as f64;
4982                if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
4983                    return None;
4984                }
4985                total = total.checked_add(product.round() as i64)?;
4986            } else {
4987                let value: i64 = num_str.parse().ok()?;
4988                total = total.checked_add(value.checked_mul(multiplier)?)?;
4989            }
4990            saw_component = true;
4991        }
4992        saw_component.then_some(total)
4993    }
4994
4995    fn try_parse_time_format(s: &str) -> Option<i64> {
4996        let parts: Vec<&str> = s.split(':').collect();
4997        if parts.len() < 2 || parts.len() > 3 {
4998            return None;
4999        }
5000
5001        let hours: i64 = parts[0].parse().ok()?;
5002        let minutes: i64 = parts[1].parse().ok()?;
5003
5004        let (seconds, frac_nanos) = if parts.len() == 3 {
5005            if let Some((sec_str, frac_str)) = parts[2].split_once('.') {
5006                let sec: i64 = sec_str.parse().ok()?;
5007                if !frac_str.bytes().all(|byte| byte.is_ascii_digit()) {
5008                    return None;
5009                }
5010                let mut frac = 0_i64;
5011                let taken = frac_str.len().min(9);
5012                for byte in frac_str.bytes().take(9) {
5013                    frac = frac * 10 + i64::from(byte - b'0');
5014                }
5015                for _ in taken..9 {
5016                    frac *= 10;
5017                }
5018                (sec, frac)
5019            } else {
5020                let sec: i64 = parts[2].parse().ok()?;
5021                (sec, 0)
5022            }
5023        } else {
5024            (0, 0)
5025        };
5026
5027        hours
5028            .checked_mul(Self::NANOS_PER_HOUR)?
5029            .checked_add(minutes.checked_mul(Self::NANOS_PER_MIN)?)?
5030            .checked_add(seconds.checked_mul(Self::NANOS_PER_SEC)?)?
5031            .checked_add(frac_nanos)
5032    }
5033
5034    /// The number-and-unit values of a compound Timedelta string, and the
5035    /// HH:MM:SS part that may end it (which the leading sign does not
5036    /// negate; see [`Self::parse`]). A sign inside the string is pandas'
5037    /// "only leading negative signs are allowed" error ("1 days -02:00:00"
5038    /// read as 22 hours).
5039    fn parse_compound(s: &str) -> Result<(i64, i64), TimedeltaError> {
5040        let mut total: i64 = 0;
5041        let mut clock: i64 = 0;
5042        let mut remaining = s;
5043
5044        while !remaining.is_empty() {
5045            remaining = remaining.trim_start();
5046            if remaining.is_empty() {
5047                break;
5048            }
5049            if remaining.starts_with('-') {
5050                return Err(TimedeltaError::InvalidFormat(format!(
5051                    "only leading negative signs are allowed: {s}"
5052                )));
5053            }
5054
5055            // Per br-frankenpandas-i9bah: check if remaining is a time format
5056            // (HH:MM:SS) which can appear after "N days " in pandas timedelta strings.
5057            if remaining.contains(':')
5058                && let Some(time_nanos) = Self::try_parse_time_format(remaining)
5059            {
5060                clock = time_nanos;
5061                break;
5062            }
5063
5064            let num_end = remaining
5065                .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
5066                .unwrap_or(remaining.len());
5067
5068            if num_end == 0 {
5069                return Err(TimedeltaError::InvalidFormat(s.to_string()));
5070            }
5071
5072            let num_str = &remaining[..num_end];
5073            let num: f64 = num_str
5074                .parse()
5075                .map_err(|_| TimedeltaError::InvalidFormat(s.to_string()))?;
5076
5077            remaining = remaining[num_end..].trim_start();
5078
5079            let unit_end = remaining
5080                .find(|c: char| c.is_ascii_digit() || c.is_whitespace())
5081                .unwrap_or(remaining.len());
5082
5083            let unit = &remaining[..unit_end];
5084            remaining = &remaining[unit_end..];
5085
5086            let multiplier = Self::unit_to_nanos(unit)
5087                .ok_or_else(|| TimedeltaError::InvalidFormat(s.to_string()))?;
5088
5089            // Per br-frankenpandas-zw3mg: pandas raises OverflowError on
5090            // huge scientific-notation Timedeltas like "1e100 days". The
5091            // raw `as i64` cast silently saturated to i64::MAX, masking
5092            // overflow before checked_add could catch it.
5093            let product = num * multiplier as f64;
5094            if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5095                return Err(TimedeltaError::Overflow);
5096            }
5097            let nanos = product.round() as i64;
5098            total = total.checked_add(nanos).ok_or(TimedeltaError::Overflow)?;
5099        }
5100
5101        // NOTE: there is deliberately no "total == 0 is suspicious" guard here.
5102        // One used to live at this spot and rejected every legitimately-zero
5103        // compound -- `to_timedelta("0 seconds")` raised while `"1 second"` and
5104        // `"10 seconds"` parsed, because the only exemption was the literal
5105        // string "0". pandas 2.2.3 accepts all of `0 seconds` / `0 days` / `0s`
5106        // / `0.0 hours` / `-0 seconds` as a zero Timedelta. The guard was also
5107        // unnecessary: the loop above returns `InvalidFormat` on an unparseable
5108        // number AND on an unknown unit, so the only way to reach here with
5109        // `total == 0` is an input whose components genuinely sum to zero.
5110        Ok((total, clock))
5111    }
5112
5113    /// Map a pandas-style frequency-alias string to a nanosecond-count.
5114    ///
5115    /// Recognizes pandas's offset alias core set plus common word forms:
5116    /// W/week(s), D/day(s), H/hr/hour(s), m/T/min/minute(s), s/sec/second(s),
5117    /// ms/milli/millisecond(s)/L, us/µs/micro/microsecond(s)/U, ns/nano/
5118    /// nanosecond(s)/N. Empty string maps to days (matches pandas default).
5119    /// Returns `None` for unrecognized aliases — callers can choose to map
5120    /// that to NaT (consistent with the rest of fp-types) or surface as a
5121    /// typed error.
5122    ///
5123    /// Per br-frankenpandas-lbsx (9p0u Phase 2.6): public surface so
5124    /// downstream crates can consume the same alias map fp-types uses for
5125    /// `Timedelta::from_unit` / `Timestamp::*_to_unit`.
5126    #[must_use]
5127    pub fn unit_to_nanos(unit: &str) -> Option<i64> {
5128        match unit.to_lowercase().as_str() {
5129            "w" | "week" | "weeks" => Some(Self::NANOS_PER_WEEK),
5130            "d" | "day" | "days" => Some(Self::NANOS_PER_DAY),
5131            "h" | "hr" | "hour" | "hours" => Some(Self::NANOS_PER_HOUR),
5132            "m" | "min" | "minute" | "minutes" | "t" => Some(Self::NANOS_PER_MIN),
5133            "s" | "sec" | "second" | "seconds" => Some(Self::NANOS_PER_SEC),
5134            "ms" | "milli" | "millis" | "millisecond" | "milliseconds" | "l" => {
5135                Some(Self::NANOS_PER_MILLI)
5136            }
5137            "us" | "µs" | "micro" | "micros" | "microsecond" | "microseconds" | "u" => {
5138                Some(Self::NANOS_PER_MICRO)
5139            }
5140            "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" | "n" => Some(1),
5141            "" => Some(Self::NANOS_PER_DAY),
5142            _ => None,
5143        }
5144    }
5145
5146    pub fn components(nanos: i64) -> TimedeltaComponents {
5147        if nanos == Self::NAT {
5148            return TimedeltaComponents::default();
5149        }
5150
5151        // pandas/Python normalize via FLOOR division (like format()): the days
5152        // component can be negative while the time-of-day remainder is always in
5153        // [0, 1 day). So pd.Timedelta(-1,'s').components == (-1, 23, 59, 59, 0, 0, 0),
5154        // NOT the abs-based (0, 0, 0, 1, 0, 0, 0).
5155        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5156        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5157
5158        let hours = rem / Self::NANOS_PER_HOUR;
5159        let rem = rem % Self::NANOS_PER_HOUR;
5160
5161        let minutes = rem / Self::NANOS_PER_MIN;
5162        let rem = rem % Self::NANOS_PER_MIN;
5163
5164        let seconds = rem / Self::NANOS_PER_SEC;
5165        let rem = rem % Self::NANOS_PER_SEC;
5166
5167        let milliseconds = rem / Self::NANOS_PER_MILLI;
5168        let rem = rem % Self::NANOS_PER_MILLI;
5169
5170        let microseconds = rem / Self::NANOS_PER_MICRO;
5171        let nanoseconds = rem % Self::NANOS_PER_MICRO;
5172
5173        TimedeltaComponents {
5174            days,
5175            hours,
5176            minutes,
5177            seconds,
5178            milliseconds,
5179            microseconds,
5180            nanoseconds,
5181        }
5182    }
5183
5184    pub fn total_seconds(nanos: i64) -> f64 {
5185        if nanos == Self::NAT {
5186            f64::NAN
5187        } else {
5188            nanos as f64 / Self::NANOS_PER_SEC as f64
5189        }
5190    }
5191
5192    /// Convert to specified time unit.
5193    ///
5194    /// Matches pd.Timedelta.as_unit(). Supported units: ns, us, ms, s, m, h, D.
5195    #[must_use]
5196    pub fn as_unit(nanos: i64, unit: &str) -> f64 {
5197        if nanos == Self::NAT {
5198            return f64::NAN;
5199        }
5200        let nanos_f = nanos as f64;
5201        match unit {
5202            "ns" | "nanoseconds" => nanos_f,
5203            "us" | "microseconds" => nanos_f / Self::NANOS_PER_MICRO as f64,
5204            "ms" | "milliseconds" => nanos_f / Self::NANOS_PER_MILLI as f64,
5205            "s" | "seconds" => nanos_f / Self::NANOS_PER_SEC as f64,
5206            "m" | "minutes" => nanos_f / Self::NANOS_PER_MIN as f64,
5207            "h" | "hours" => nanos_f / Self::NANOS_PER_HOUR as f64,
5208            "D" | "days" => nanos_f / Self::NANOS_PER_DAY as f64,
5209            _ => f64::NAN,
5210        }
5211    }
5212
5213    /// Return the days component, or `None` for `NaT`. Matches
5214    /// `pd.Timedelta.days`.
5215    ///
5216    /// ⚠️ `None`, NOT `0`, AND THE TYPE IS THE FIX
5217    /// (br-frankenpandas-timedelta-nat-days-returns-zero-406ni). All four
5218    /// component helpers used to return `0` for `NaT`, one of them behind a
5219    /// comment asserting "pandas returns 0 for NaT.days (no error)". MEASURED,
5220    /// live pandas 2.2.3: `pd.NaT.days` is **nan**, and
5221    /// `pd.to_timedelta([1, None, -1], unit='s').dt.days` is float64
5222    /// `[0.0, nan, -1.0]` — pandas promotes the whole column because NaN cannot
5223    /// live in int64.
5224    ///
5225    /// An `i64` return cannot express that, so correctness depended on every
5226    /// caller remembering to test `NAT` first. It did — `timedelta_component`
5227    /// checked in three separate arms — but that is a convention, and the bead
5228    /// filed it as a landmine for the next person to wire a `.dt` accessor: a
5229    /// function whose doc says "matches pandas" handing back a plausible integer
5230    /// where pandas has a missing value. `Option<i64>` moves the fact into the
5231    /// type, so a caller cannot forget and the duplicated `NAT` tests go away.
5232    #[must_use]
5233    pub fn days(nanos: i64) -> Option<i64> {
5234        if nanos == Self::NAT {
5235            return None;
5236        }
5237        // FLOOR division like pandas: pd.Timedelta(-1,'s').days == -1, not 0.
5238        Some(nanos.div_euclid(Self::NANOS_PER_DAY))
5239    }
5240
5241    /// Return the seconds component (0-86399), or `None` for `NaT`. Matches
5242    /// `pd.Timedelta.seconds`. See [`Self::days`] for why this is an `Option`.
5243    #[must_use]
5244    pub fn seconds(nanos: i64) -> Option<i64> {
5245        if nanos == Self::NAT {
5246            return None;
5247        }
5248        // Floor-normalized time-of-day remainder: pd.Timedelta(-1,'s').seconds == 86399.
5249        Some(nanos.rem_euclid(Self::NANOS_PER_DAY) / Self::NANOS_PER_SEC)
5250    }
5251
5252    /// Return the microseconds component (0-999999), or `None` for `NaT`.
5253    /// Matches `pd.Timedelta.microseconds`. See [`Self::days`].
5254    #[must_use]
5255    pub fn microseconds(nanos: i64) -> Option<i64> {
5256        if nanos == Self::NAT {
5257            return None;
5258        }
5259        Some(nanos.rem_euclid(Self::NANOS_PER_SEC) / Self::NANOS_PER_MICRO)
5260    }
5261
5262    /// Return the nanoseconds component (0-999), or `None` for `NaT`. Matches
5263    /// `pd.Timedelta.nanoseconds`. See [`Self::days`].
5264    #[must_use]
5265    pub fn nanoseconds(nanos: i64) -> Option<i64> {
5266        if nanos == Self::NAT {
5267            return None;
5268        }
5269        Some(nanos.rem_euclid(Self::NANOS_PER_MICRO))
5270    }
5271
5272    /// The coarsest [`TimedeltaStringResolution`] that renders `nanos`
5273    /// losslessly. Fold over a column with `max`.
5274    ///
5275    /// `NaT` reports `Days`, the identity of that fold, because pandas excludes
5276    /// it from the scan: `[1 days, NaT]` still renders `['1 days', 'NaT']`.
5277    #[must_use]
5278    pub const fn string_resolution(nanos: i64) -> TimedeltaStringResolution {
5279        if nanos == Self::NAT || nanos.rem_euclid(Self::NANOS_PER_DAY) == 0 {
5280            TimedeltaStringResolution::Days
5281        } else {
5282            TimedeltaStringResolution::Full
5283        }
5284    }
5285
5286    /// Render `nanos` the way `astype(str)` does, at a resolution chosen for the
5287    /// whole column by [`Self::string_resolution`].
5288    ///
5289    /// The `Full` arm is [`Self::format`] verbatim — the per-value sub-second
5290    /// width was already right. Only the `Days` arm is new, and it exists
5291    /// because a column of whole days drops its time part completely:
5292    /// `'1 days'`, not `'1 days 00:00:00'`.
5293    #[must_use]
5294    pub fn format_at_resolution(nanos: i64, resolution: TimedeltaStringResolution) -> String {
5295        if nanos == Self::NAT {
5296            return "NaT".to_string();
5297        }
5298        match resolution {
5299            TimedeltaStringResolution::Full => Self::format(nanos),
5300            // Euclidean division, so a negative whole-day value keeps pandas'
5301            // spelling: -2 days is "-2 days", never "-1 days -24:00:00".
5302            TimedeltaStringResolution::Days => {
5303                format!("{} days", nanos.div_euclid(Self::NANOS_PER_DAY))
5304            }
5305        }
5306    }
5307
5308    pub fn format(nanos: i64) -> String {
5309        use std::fmt::Write as _;
5310
5311        if nanos == Self::NAT {
5312            return "NaT".to_string();
5313        }
5314
5315        // pandas / Python timedelta normalize via FLOOR division: the days
5316        // component can be negative while the time-of-day remainder is always
5317        // non-negative, and a negative-days value prints a '+' before the time
5318        // (e.g. -1s -> "-1 days +23:59:59", not "-0 days 00:00:01"). Compute the
5319        // components with Euclidean div/rem so the remainder is in [0, 1 day).
5320        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5321        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5322        let hours = rem / Self::NANOS_PER_HOUR;
5323        let minutes = (rem % Self::NANOS_PER_HOUR) / Self::NANOS_PER_MIN;
5324        let seconds = (rem % Self::NANOS_PER_MIN) / Self::NANOS_PER_SEC;
5325        let frac = rem % Self::NANOS_PER_SEC;
5326
5327        // Build directly into the returned allocation. The former path first
5328        // allocated an `HH:MM:SS` string, then copied it into the result.
5329        let mut result = String::with_capacity(32);
5330        let _ = write!(result, "{days} days ");
5331        // '+' joins the negative day count to the positive time remainder.
5332        if days < 0 {
5333            result.push('+');
5334        }
5335        let _ = write!(result, "{hours:02}:{minutes:02}:{seconds:02}");
5336        if frac > 0 {
5337            // pandas renders the sub-second part with microsecond precision
5338            // (6 digits) unless a sub-microsecond (nanosecond) component is
5339            // present, in which case it widens to 9 digits.
5340            if frac % 1_000 == 0 {
5341                let _ = write!(result, ".{:06}", frac / 1_000);
5342            } else {
5343                let _ = write!(result, ".{frac:09}");
5344            }
5345        }
5346        result
5347    }
5348
5349    /// Build a nanosecond Timedelta from a float quantity of `unit`.
5350    ///
5351    /// Matches `pd.Timedelta(value, unit=...)`:
5352    /// - `NaN` → `NAT`. pandas returns `NaT`, and `NAT` is how NaT is spelled
5353    ///   in this i64 representation. Rust's float→int `as` maps `NaN` to
5354    ///   **0**, so the unguarded cast used to hand back a ZERO DURATION for a
5355    ///   missing value (br-frankenpandas-8v92m).
5356    /// - non-finite or out-of-range product → [`TimedeltaError::Overflow`].
5357    ///   pandas raises `OutOfBoundsTimedelta` ("Cannot cast inf from s to 'ns'
5358    ///   without overflow"); the `as` cast used to SATURATE to `i64::MAX`,
5359    ///   returning a finite, plausible ~106751-day duration instead.
5360    /// - unknown unit → [`TimedeltaError::InvalidFormat`], unchanged.
5361    ///
5362    /// The overflow guard is the same one `parse` and the component parser
5363    /// already use (added by br-frankenpandas-zw3mg, which fixed two of the
5364    /// three sites sharing this expression and missed this one).
5365    pub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError> {
5366        let multiplier = Self::unit_to_nanos(unit)
5367            .ok_or_else(|| TimedeltaError::InvalidFormat(unit.to_string()))?;
5368        if value.is_nan() {
5369            return Ok(Self::NAT);
5370        }
5371        let product = value * multiplier as f64;
5372        if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5373            return Err(TimedeltaError::Overflow);
5374        }
5375        Ok(product.round() as i64)
5376    }
5377
5378    // ── Arithmetic (br-frankenpandas-4r56 Phase 1) ──────────────────────
5379    //
5380    // NaT propagation: any arithmetic with `NAT` returns `NAT`. Matches
5381    // pandas `pd.NaT + anything == NaT`, `pd.NaT - anything == NaT`, etc.
5382    //
5383    // Overflow (br-frankenpandas-lgyy8): i64 overflow yields `NAT` in BOTH
5384    // directions. It never wraps and never fabricates a finite value.
5385    //
5386    // These previously used `saturating_*`, which was asymmetric and failed
5387    // OPEN on one side. Because `NAT == i64::MIN`, negative overflow clamped
5388    // onto the sentinel and already surfaced as missing — but POSITIVE
5389    // overflow clamped to `i64::MAX`, a perfectly valid, finite, plausible
5390    // duration (and, for `Timestamp`, a ~year-2262 instant) returned as if it
5391    // were real data. Live pandas 2.2.3 never does that, in either the scalar
5392    // or the vectorized path:
5393    //
5394    //   pd.Timedelta.min + Timedelta('-1ns')      -> NaT  (lands on the sentinel)
5395    //   pd.Series[datetime64] + Timedelta('-1ns') -> [NaT, ...]
5396    //   pd.Timedelta.max + Timedelta('1ns')       -> raises OverflowError
5397    //   pd.Timestamp.max + Timedelta('1ns')       -> raises OutOfBoundsDatetime
5398    //   pd.Series[datetime64] + Timedelta('1ns')  -> raises OverflowError
5399    //   pd.Timestamp.min - pd.Timestamp.max       -> raises OutOfBoundsDatetime
5400    //   pd.Timedelta.max * 2                      -> raises OverflowError
5401    //
5402    // We surface NaT where pandas raises, rather than making these infallible
5403    // `#[must_use]` helpers fallible: that is the SAME documented divergence
5404    // `div_scalar` already takes for divide-by-zero ("matches pandas, which
5405    // raises, but we surface as NaT to avoid panics at the type-system
5406    // boundary"). Every input whose exact result is representable is
5407    // unaffected bit-for-bit; only overflow moves.
5408
5409    /// Add two Timedelta nanosecond values, reporting overflow.
5410    ///
5411    /// br-frankenpandas-fyr1z-policy-carrier-f29nz. NaT propagation is NOT an
5412    /// overflow — a NaT operand yields `Ok(NAT)`, exactly as before. Only an
5413    /// unrepresentable result is an `Err`.
5414    ///
5415    /// # Errors
5416    /// [`PandasTemporalError::Overflow`] when the sum exceeds i64.
5417    pub fn try_add(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5418        if a == Self::NAT || b == Self::NAT {
5419            return Ok(Self::NAT);
5420        }
5421        a.checked_add(b).ok_or(
5422            TemporalFailure::new("Timedelta::add", PandasTemporalError::Overflow)
5423                .with_operands(a, b),
5424        )
5425    }
5426
5427    /// Add two Timedelta nanosecond values. NaT propagates; overflow → NaT.
5428    #[must_use]
5429    pub fn add(a: i64, b: i64) -> i64 {
5430        Self::try_add(a, b).unwrap_or(Self::NAT)
5431    }
5432
5433    /// Subtract two Timedelta nanosecond values, reporting overflow.
5434    ///
5435    /// # Errors
5436    /// [`PandasTemporalError::Overflow`] when the difference exceeds i64.
5437    pub fn try_sub(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5438        if a == Self::NAT || b == Self::NAT {
5439            return Ok(Self::NAT);
5440        }
5441        a.checked_sub(b).ok_or(
5442            TemporalFailure::new("Timedelta::sub", PandasTemporalError::Overflow)
5443                .with_operands(a, b),
5444        )
5445    }
5446
5447    /// Subtract two Timedelta nanosecond values. NaT propagates; overflow → NaT.
5448    #[must_use]
5449    pub fn sub(a: i64, b: i64) -> i64 {
5450        Self::try_sub(a, b).unwrap_or(Self::NAT)
5451    }
5452
5453    /// Negate a Timedelta value. NaT stays NaT.
5454    ///
5455    /// There is no overflow case to handle, and the `saturating_` call is a
5456    /// belt-and-braces no-op: the only `i64` whose negation overflows is
5457    /// `i64::MIN`, and `i64::MIN` IS the NaT sentinel, so it is consumed by
5458    /// the guard above. The representable range is `[i64::MIN + 1, i64::MAX]`,
5459    /// which is symmetric about zero.
5460    ///
5461    /// CORRECTED br-frankenpandas-fyr1z: this used to claim "pandas:
5462    /// `-pd.Timedelta.min` is NaT since min == -max - 1 cannot be negated".
5463    /// That is false in both halves. pandas' `Timedelta.min.value` is
5464    /// `-9223372036854775807` == `-Timedelta.max.value`, NOT `-max - 1`
5465    /// (`-max - 1` is `i64::MIN`, which pandas also reserves for NaT), and
5466    /// live pandas 2.2.3 returns `Timedelta('106751 days 23:47:16.854775807')`
5467    /// — i.e. `Timedelta.max` — for `-pd.Timedelta.min`, `abs(pd.Timedelta
5468    /// .min)`, and the vectorized `-Series[timedelta64]` / `.abs()` forms.
5469    /// Do not "fix" this to return NaT; that would be the parity regression.
5470    #[must_use]
5471    pub fn neg(a: i64) -> i64 {
5472        if a == Self::NAT {
5473            return Self::NAT;
5474        }
5475        a.saturating_neg()
5476    }
5477
5478    /// Absolute value of a Timedelta. NaT stays NaT.
5479    ///
5480    /// As with [`Timedelta::neg`], no overflow is reachable: `i64::MIN` is the
5481    /// NaT sentinel and is consumed by the guard, and `|i64::MIN + 1|` is
5482    /// exactly `i64::MAX`. pandas agrees — `abs(pd.Timedelta.min)` is
5483    /// `Timedelta.max`, not NaT.
5484    #[must_use]
5485    pub fn abs(a: i64) -> i64 {
5486        if a == Self::NAT {
5487            return Self::NAT;
5488        }
5489        a.saturating_abs()
5490    }
5491
5492    /// Multiply a Timedelta value by an integer factor. NaT propagates;
5493    /// overflow → NaT (see the overflow note above).
5494    ///
5495    /// Matches pandas `pd.Timedelta(...) * int`, which raises `OverflowError`
5496    /// rather than returning a saturated duration.
5497    #[must_use]
5498    pub fn mul_scalar(a: i64, factor: i64) -> i64 {
5499        Self::try_mul_scalar(a, factor).unwrap_or(Self::NAT)
5500    }
5501
5502    /// Multiply a Timedelta by an integer factor under an explicit policy.
5503    ///
5504    /// br-frankenpandas-fyr1z-wrap-signoff-s4lkx, DECIDED BY THE MAINTAINER:
5505    /// **STRICT REPRODUCES PANDAS' SILENT WRAP.** The rationale is that this is
5506    /// a PORT — STRICT means bit-for-bit observable parity with the incumbent
5507    /// *including its quirks*, so the wrap is a deliberately reproduced pandas
5508    /// behaviour, not a defect of ours.
5509    ///
5510    /// Verified against live pandas 2.2.3: `Series([Timedelta.max]) * 2` returns
5511    /// `-2` ns (displayed `-1 days +23:59:59.999999998`), which is exactly
5512    /// `i64::MAX.wrapping_mul(2)`. Rust's wrapping arithmetic reproduces numpy's
5513    /// int64 wraparound bit-for-bit, so no emulation is needed.
5514    ///
5515    /// The wrap is INTEGER-MULTIPLIER ONLY: `Series * 2.0` returns NaT in
5516    /// pandas, so a float multiplier must not route here.
5517    ///
5518    /// Every other policy keeps today's behaviour — NaT, with HARDENED also
5519    /// recording the recovery. So the fail-open shape br-frankenpandas-lgyy8
5520    /// removed is reachable ONLY when a caller explicitly asks for STRICT
5521    /// incumbent parity, never by default. See DISC-020.
5522    #[must_use]
5523    pub fn mul_scalar_with_policy(a: i64, factor: i64, policy: OverflowPolicy) -> i64 {
5524        if a == Self::NAT {
5525            return Self::NAT;
5526        }
5527        if matches!(policy, OverflowPolicy::Strict) {
5528            return a.wrapping_mul(factor);
5529        }
5530        policy
5531            .resolve_recording(Self::try_mul_scalar(a, factor), Self::NAT, Self::NAT)
5532            .unwrap_or(Self::NAT)
5533    }
5534
5535    /// Multiply a Timedelta value by an integer factor, reporting overflow.
5536    ///
5537    /// # Errors
5538    /// [`PandasTemporalError::Overflow`] when the product exceeds i64 — which
5539    /// is what the SCALAR `pd.Timedelta.max * 2` raises. Note DISC-018: the
5540    /// VECTORIZED `Series * int` wraps silently instead, so a strict arm for
5541    /// this op must decide per-surface rather than inherit this class blindly.
5542    pub fn try_mul_scalar(a: i64, factor: i64) -> Result<i64, TemporalFailure> {
5543        if a == Self::NAT {
5544            return Ok(Self::NAT);
5545        }
5546        a.checked_mul(factor).ok_or(
5547            TemporalFailure::new("Timedelta::mul_scalar", PandasTemporalError::Overflow)
5548                .with_operands(a, factor),
5549        )
5550    }
5551
5552    /// Floor-divide a Timedelta value by an integer divisor. NaT propagates.
5553    /// Returns NaT on divide-by-zero (matches pandas, which raises, but we
5554    /// surface as NaT to avoid panics at the type-system boundary).
5555    ///
5556    /// Matches pandas / Python `pd.Timedelta(...) // int`: floor division,
5557    /// not truncation toward zero. `-100 // 3 == -34`, and `100 // -3 ==
5558    /// -34`. Rust's `/` truncates toward zero and `div_euclid` keeps the
5559    /// remainder non-negative — neither matches pandas when the divisor is
5560    /// negative. This helper adjusts trunc-toward-zero into floor.
5561    #[must_use]
5562    pub fn div_scalar(a: i64, divisor: i64) -> i64 {
5563        Self::try_div_scalar(a, divisor).unwrap_or(Self::NAT)
5564    }
5565
5566    /// Floor-divide a Timedelta by an integer divisor, reporting divide-by-zero.
5567    ///
5568    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2. NaT propagation is not a
5569    /// failure and yields `Ok(NAT)`; only a zero divisor is an `Err`.
5570    ///
5571    /// ⚠ SCALAR SEMANTICS ONLY. pandas raises `ZeroDivisionError` for the
5572    /// scalar `pd.Timedelta('1s') // 0`, but the VECTORIZED
5573    /// `Series([Timedelta]) // 0` returns NaT (both probed on 2.2.3). The
5574    /// infallible [`Self::div_scalar`] above keeps the NaT behavior that the
5575    /// vectorized callers depend on, and a STRICT arm must route only the
5576    /// scalar surface here.
5577    ///
5578    /// # Errors
5579    /// [`PandasTemporalError::ZeroDivision`] when `divisor == 0`.
5580    pub fn try_div_scalar(a: i64, divisor: i64) -> Result<i64, TemporalFailure> {
5581        if divisor == 0 {
5582            return Err(TemporalFailure::new(
5583                "Timedelta::div_scalar",
5584                PandasTemporalError::ZeroDivision,
5585            )
5586            .with_operands(a, divisor));
5587        }
5588        if a == Self::NAT {
5589            return Ok(Self::NAT);
5590        }
5591        Ok(Self::div_scalar_inner(a, divisor))
5592    }
5593
5594    fn div_scalar_inner(a: i64, divisor: i64) -> i64 {
5595        // NAT == i64::MIN so the classic `i64::MIN / -1` overflow path is
5596        // already handled by the NAT check above. `(i64::MIN + 1) / -1`
5597        // equals `i64::MAX` with no overflow, so we never need a
5598        // saturation branch here.
5599        let q = a / divisor;
5600        let r = a % divisor;
5601        // If remainder is non-zero and has opposite sign from divisor,
5602        // Rust's trunc-toward-zero `/` is one step above the floor. Adjust
5603        // down by 1 to match Python/pandas floor division.
5604        if r != 0 && (r < 0) != (divisor < 0) {
5605            q - 1
5606        } else {
5607            q
5608        }
5609    }
5610
5611    /// Divide two Timedelta values, returning the ratio as f64.
5612    /// Matches pandas `pd.Timedelta(...) / pd.Timedelta(...)` → float.
5613    /// NaT in either operand → NaN. Zero divisor → ±Inf (per IEEE 754).
5614    #[must_use]
5615    pub fn div_timedelta(a: i64, b: i64) -> f64 {
5616        if a == Self::NAT || b == Self::NAT {
5617            return f64::NAN;
5618        }
5619        (a as f64) / (b as f64)
5620    }
5621
5622    /// Returns ISO 8601 duration format string.
5623    ///
5624    /// Matches pandas `pd.Timedelta.isoformat()`. Returns format like
5625    /// "P1DT2H3M4.567890123S" for 1 day, 2 hours, 3 minutes, 4.567890123 seconds.
5626    /// A negative duration is pandas' components form: whole days rounded
5627    /// down, then a non-negative clock (-1 day -1 hour is "P-2DT23H0M0S";
5628    /// it was "-P1DT1H0M0S"). NaT returns "NaT".
5629    #[must_use]
5630    pub fn isoformat(nanos: i64) -> String {
5631        use std::fmt::Write as _;
5632
5633        if nanos == Self::NAT {
5634            return "NaT".to_string();
5635        }
5636
5637        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5638        let remaining = nanos.rem_euclid(Self::NANOS_PER_DAY);
5639
5640        let hours = remaining / Self::NANOS_PER_HOUR;
5641        let remaining = remaining % Self::NANOS_PER_HOUR;
5642
5643        let minutes = remaining / Self::NANOS_PER_MIN;
5644        let remaining = remaining % Self::NANOS_PER_MIN;
5645
5646        let seconds = remaining / Self::NANOS_PER_SEC;
5647        let sub_sec_nanos = remaining % Self::NANOS_PER_SEC;
5648
5649        // Build directly into the returned allocation. The former sequence of
5650        // `format!` calls allocated two temporary strings for integral values
5651        // and three for fractional values before copying them into `result`.
5652        let mut result = String::with_capacity(40);
5653        // `fmt::Write for String` is infallible.
5654        let _ = write!(result, "P{days}DT{hours}H{minutes}M{seconds}");
5655        if sub_sec_nanos != 0 {
5656            result.push('.');
5657            let _ = write!(result, "{sub_sec_nanos:09}");
5658            while result.ends_with('0') {
5659                result.pop();
5660            }
5661        }
5662        result.push('S');
5663        result
5664    }
5665
5666    /// Rounds down to the nearest frequency unit.
5667    ///
5668    /// Matches pandas `pd.Timedelta.floor(freq)`. NaT is preserved.
5669    #[must_use]
5670    pub fn floor(nanos: i64, freq: &str) -> i64 {
5671        if nanos == Self::NAT {
5672            return Self::NAT;
5673        }
5674        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5675            return Self::NAT;
5676        };
5677        if unit_nanos == 0 {
5678            return Self::NAT;
5679        }
5680        nanos
5681            .div_euclid(unit_nanos)
5682            .checked_mul(unit_nanos)
5683            .unwrap_or(Self::NAT)
5684    }
5685
5686    /// Rounds up to the nearest frequency unit.
5687    ///
5688    /// Matches pandas `pd.Timedelta.ceil(freq)`. NaT is preserved; overflow
5689    /// → NaT (`pd.Timedelta.max.ceil('D')` raises `OutOfBoundsTimedelta:
5690    /// Cannot round ... without overflow`, so a clamped `i64::MAX` would be a
5691    /// fabricated finite duration — see br-frankenpandas-kyd16).
5692    #[must_use]
5693    pub fn ceil(nanos: i64, freq: &str) -> i64 {
5694        if nanos == Self::NAT {
5695            return Self::NAT;
5696        }
5697        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5698            return Self::NAT;
5699        };
5700        if unit_nanos == 0 {
5701            return Self::NAT;
5702        }
5703        let remainder = nanos.rem_euclid(unit_nanos);
5704        if remainder == 0 {
5705            nanos
5706        } else {
5707            nanos
5708                .checked_add(unit_nanos - remainder)
5709                .unwrap_or(Self::NAT)
5710        }
5711    }
5712
5713    /// Rounds to the nearest frequency unit.
5714    ///
5715    /// Matches pandas `pd.Timedelta.round(freq)`. Uses banker's rounding
5716    /// (round half to even). NaT is preserved.
5717    #[must_use]
5718    pub fn round(nanos: i64, freq: &str) -> i64 {
5719        if nanos == Self::NAT {
5720            return Self::NAT;
5721        }
5722        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5723            return Self::NAT;
5724        };
5725        if unit_nanos == 0 {
5726            return Self::NAT;
5727        }
5728        let negative = nanos < 0;
5729        let abs_nanos = nanos.saturating_abs();
5730
5731        let quotient = abs_nanos / unit_nanos;
5732        let remainder = abs_nanos % unit_nanos;
5733        let half = unit_nanos / 2;
5734
5735        // Round-UP must be checked (br-frankenpandas-kyd16). `quotient *
5736        // unit_nanos` is always <= abs_nanos and cannot overflow, but
5737        // `(quotient + 1) * unit_nanos` can exceed i64::MAX — and this used
5738        // UNCHECKED arithmetic, so it panicked in debug and WRAPPED to a
5739        // large-negative duration in release. pandas raises
5740        // OutOfBoundsTimedelta ("Cannot round ... without overflow"); we
5741        // surface NaT, consistent with the rest of this block.
5742        let round_up = || {
5743            quotient
5744                .checked_add(1)
5745                .and_then(|q| q.checked_mul(unit_nanos))
5746        };
5747        let rounded = if remainder > half {
5748            round_up()
5749        } else if remainder < half {
5750            Some(quotient * unit_nanos)
5751        } else {
5752            // Exactly half: round to even
5753            if quotient % 2 == 0 {
5754                Some(quotient * unit_nanos)
5755            } else {
5756                round_up()
5757            }
5758        };
5759
5760        match rounded {
5761            // Negating is safe: `rounded` is non-negative and at most i64::MAX,
5762            // so `-rounded` is at worst i64::MIN + 1 — never the NaT sentinel.
5763            Some(rounded) => {
5764                if negative {
5765                    -rounded
5766                } else {
5767                    rounded
5768                }
5769            }
5770            None => Self::NAT,
5771        }
5772    }
5773}
5774
5775// ── Time zones ──────────────────────────────────────────────────────────
5776//
5777// A tz-aware value is a UTC instant plus a zone name; what the zone adds is
5778// the wall clock the instant shows there. These are the conversions every
5779// crate shares (Timestamp, DatetimeIndex, datetime columns).
5780
5781/// Why a time-zone conversion failed, as pandas (pytz) classifies it.
5782#[derive(Debug, Clone, PartialEq, Eq, Error)]
5783pub enum TimeZoneError {
5784    /// Neither 'UTC', a fixed offset ('+05:30') nor an IANA name - pandas'
5785    /// `UnknownTimeZoneError`, a `KeyError` whose message is the quoted name.
5786    #[error("'{0}'")]
5787    Unknown(String),
5788    /// A wall-clock time a DST change skips - pandas' `NonExistentTimeError`,
5789    /// whose message is the wall time.
5790    #[error("{0}")]
5791    NonExistent(String),
5792    /// A wall-clock time a DST change repeats - pandas' `AmbiguousTimeError`.
5793    #[error("Cannot infer dst time from {0}, try using the 'ambiguous' argument")]
5794    Ambiguous(String),
5795}
5796
5797/// A parsed zone: UTC or a fixed offset, or an IANA zone with DST rules.
5798enum Zone {
5799    Fixed(chrono::FixedOffset),
5800    Named(chrono_tz::Tz),
5801}
5802
5803impl Zone {
5804    /// pandas' zone spellings: 'UTC' / 'Z', a `+HH:MM` / `-HH:MM` offset (also
5805    /// as `UTC+HH:MM`, how a fixed-offset dtype names its zone), or an IANA
5806    /// name ('US/Eastern', 'Asia/Tokyo', 'Etc/GMT+5').
5807    fn parse(tz: &str) -> Result<Self, TimeZoneError> {
5808        use chrono::Offset;
5809        let name = tz.trim();
5810        if name == "UTC" || name == "Z" {
5811            return Ok(Self::Fixed(chrono::Utc.fix()));
5812        }
5813        let offset = name
5814            .strip_prefix("UTC")
5815            .filter(|rest| rest.starts_with(['+', '-']))
5816            .unwrap_or(name);
5817        let bytes = offset.as_bytes();
5818        if bytes.len() == 6
5819            && matches!(bytes[0], b'+' | b'-')
5820            && bytes[3] == b':'
5821            && [1, 2, 4, 5].iter().all(|&i| bytes[i].is_ascii_digit())
5822        {
5823            let hours: i32 = offset[1..3].parse().unwrap_or(24);
5824            let minutes: i32 = offset[4..6].parse().unwrap_or(60);
5825            let sign = if bytes[0] == b'-' { -1 } else { 1 };
5826            return (hours <= 23 && minutes <= 59)
5827                .then(|| chrono::FixedOffset::east_opt(sign * (hours * 3_600 + minutes * 60)))
5828                .flatten()
5829                .map(Self::Fixed)
5830                .ok_or_else(|| TimeZoneError::Unknown(name.to_owned()));
5831        }
5832        name.parse::<chrono_tz::Tz>()
5833            .map(Self::Named)
5834            .map_err(|_| TimeZoneError::Unknown(name.to_owned()))
5835    }
5836
5837    /// Seconds east of UTC this zone is at the UTC instant `utc_nanos`.
5838    fn offset_seconds(&self, utc_nanos: i64) -> i32 {
5839        use chrono::{Offset, TimeZone};
5840        match self {
5841            Self::Fixed(offset) => offset.local_minus_utc(),
5842            Self::Named(zone) => {
5843                let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5844                zone.offset_from_utc_datetime(&utc).fix().local_minus_utc()
5845            }
5846        }
5847    }
5848}
5849
5850/// Whether `tz` names a zone pandas accepts ('UTC', `+HH:MM`, an IANA name).
5851pub fn tz_validate(tz: &str) -> Result<(), TimeZoneError> {
5852    Zone::parse(tz).map(|_| ())
5853}
5854
5855/// The name pandas gives the zone `tz`: a fixed offset is `UTC+HH:MM`
5856/// ('+05:30' and 'UTC+05:30' alike; a zero offset or 'Z' is 'UTC'), an
5857/// IANA name stays as given.
5858pub fn tz_canonical_name(tz: &str) -> Result<String, TimeZoneError> {
5859    Ok(match Zone::parse(tz)? {
5860        Zone::Fixed(offset) if offset.local_minus_utc() == 0 => "UTC".to_owned(),
5861        Zone::Fixed(offset) => format!("UTC{offset}"),
5862        Zone::Named(_) => tz.trim().to_owned(),
5863    })
5864}
5865
5866/// The zone's name at the UTC instant `utc_nanos` as `strftime('%Z')` prints
5867/// it: an IANA zone's abbreviation then ('EST' / 'EDT'), a fixed offset's
5868/// `UTC+HH:MM` ('UTC' for zero).
5869pub fn tz_abbreviation(tz: &str, utc_nanos: i64) -> Result<String, TimeZoneError> {
5870    use chrono::TimeZone;
5871    match Zone::parse(tz)? {
5872        Zone::Named(zone) => {
5873            let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5874            let offset = zone.offset_from_utc_datetime(&utc);
5875            Ok(chrono_tz::OffsetName::abbreviation(&offset)
5876                .map_or_else(|| tz.trim().to_owned(), str::to_owned))
5877        }
5878        Zone::Fixed(_) => tz_canonical_name(tz),
5879    }
5880}
5881
5882/// The UTC offset, in seconds east of UTC, that `tz` has at the UTC instant
5883/// `utc_nanos` - what a tz-aware timestamp adds to its instant to show its
5884/// wall clock.
5885pub fn tz_offset_seconds(tz: &str, utc_nanos: i64) -> Result<i32, TimeZoneError> {
5886    Ok(Zone::parse(tz)?.offset_seconds(utc_nanos))
5887}
5888
5889/// The wall clock the UTC instant `utc_nanos` shows in `tz`, as naive
5890/// nanoseconds (NaT, `i64::MIN`, stays NaT).
5891pub fn tz_utc_to_wall_nanos(tz: &str, utc_nanos: i64) -> Result<i64, TimeZoneError> {
5892    if utc_nanos == i64::MIN {
5893        return Ok(utc_nanos);
5894    }
5895    let offset = Zone::parse(tz)?.offset_seconds(utc_nanos);
5896    Ok(utc_nanos.saturating_add(i64::from(offset) * 1_000_000_000))
5897}
5898
5899/// The UTC instant of the wall-clock time `wall_nanos` in `tz`, as pandas'
5900/// `tz_localize` with ambiguous / nonexistent = 'raise': a wall time a DST
5901/// change skips is [`TimeZoneError::NonExistent`], one it repeats
5902/// [`TimeZoneError::Ambiguous`]. NaT (`i64::MIN`) stays NaT.
5903pub fn tz_wall_to_utc_nanos(tz: &str, wall_nanos: i64) -> Result<i64, TimeZoneError> {
5904    tz_wall_to_utc_nanos_with(tz, wall_nanos, AmbiguousTime::Raise, NonexistentTime::Raise)
5905}
5906
5907/// What `tz_localize` does with a wall time a DST change repeats (pandas'
5908/// `ambiguous=`, for one value): refuse it, take its first occurrence (DST,
5909/// pandas' `True`) or its second (standard time, `False`), or make it NaT.
5910#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5911pub enum AmbiguousTime {
5912    Raise,
5913    Earliest,
5914    Latest,
5915    NaT,
5916}
5917
5918/// What `tz_localize` does with a wall time a DST change skips (pandas'
5919/// `nonexistent=`): refuse it, move it to the first instant after the gap
5920/// (`shift_forward`) or the last nanosecond before it (`shift_backward`),
5921/// make it NaT, or move the wall time by a duration (nanoseconds) and
5922/// localize that.
5923#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5924pub enum NonexistentTime {
5925    Raise,
5926    ShiftForward,
5927    ShiftBackward,
5928    NaT,
5929    Shift(i64),
5930}
5931
5932/// [`tz_wall_to_utc_nanos`] under pandas' `ambiguous` / `nonexistent`
5933/// policies; NaT (`i64::MIN`) where a policy says NaT.
5934pub fn tz_wall_to_utc_nanos_with(
5935    tz: &str,
5936    wall_nanos: i64,
5937    ambiguous: AmbiguousTime,
5938    nonexistent: NonexistentTime,
5939) -> Result<i64, TimeZoneError> {
5940    if wall_nanos == i64::MIN {
5941        return Ok(wall_nanos);
5942    }
5943    wall_to_utc_in(&Zone::parse(tz)?, wall_nanos, ambiguous, nonexistent)
5944}
5945
5946const NANOS_PER_HOUR: i64 = 3_600_000_000_000;
5947const NANOS_PER_SECOND: i64 = 1_000_000_000;
5948
5949/// Each of `utc`'s instants' wall clock in `tz` (NaT stays NaT), as
5950/// [`tz_utc_to_wall_nanos`] makes one: the zone parsed once, and an hour's
5951/// offset reused while the instants stay in an hour holding one offset -
5952/// the per-instant call parsed the zone's name and looked its offset up for
5953/// every instant (a zoned index's tz_localize(None) of a million 44 ms,
5954/// pandas 11; br-frankenpandas-6pqf3).
5955///
5956/// # Errors
5957/// An unknown zone.
5958pub fn tz_utc_to_wall_nanos_all(tz: &str, utc: &[i64]) -> Result<Vec<i64>, TimeZoneError> {
5959    let zone = Zone::parse(tz)?;
5960    let mut offsets = HourOffsets::new(&zone);
5961    Ok(utc
5962        .iter()
5963        .map(|&nanos| {
5964            if nanos == i64::MIN {
5965                nanos
5966            } else {
5967                nanos.saturating_add(i64::from(offsets.at(nanos)) * NANOS_PER_SECOND)
5968            }
5969        })
5970        .collect())
5971}
5972
5973/// Each of `walls`' wall-clock times placed in `tz` as
5974/// [`tz_wall_to_utc_nanos_with`] places one (the same `ambiguous` /
5975/// `nonexistent` rules; NaT stays NaT): the zone parsed once, and a local
5976/// hour holding no DST change mapped with its one offset while the times
5977/// stay in it (br-frankenpandas-6pqf3).
5978///
5979/// # Errors
5980/// An unknown zone, or a wall time the rules refuse.
5981pub fn tz_wall_to_utc_nanos_all(
5982    tz: &str,
5983    walls: &[i64],
5984    ambiguous: AmbiguousTime,
5985    nonexistent: NonexistentTime,
5986) -> Result<Vec<i64>, TimeZoneError> {
5987    let zone = Zone::parse(tz)?;
5988    let mut hour = i64::MIN;
5989    let mut checked = false;
5990    let mut simple: Option<i32> = None;
5991    walls
5992        .iter()
5993        .map(|&wall| {
5994            if wall == i64::MIN {
5995                return Ok(wall);
5996            }
5997            let at = wall.div_euclid(NANOS_PER_HOUR);
5998            if at == hour {
5999                if !checked {
6000                    checked = true;
6001                    simple = simple_local_hour(&zone, at);
6002                }
6003                if let Some(offset) = simple
6004                    && let Some(utc) = wall.checked_sub(i64::from(offset) * NANOS_PER_SECOND)
6005                {
6006                    return Ok(utc);
6007                }
6008            } else {
6009                hour = at;
6010                checked = false;
6011                simple = None;
6012            }
6013            wall_to_utc_in(&zone, wall, ambiguous, nonexistent)
6014        })
6015        .collect()
6016}
6017
6018/// The UTC offsets of a run of instants in one zone: the offset of the hour
6019/// the last instant fell in, kept while the next ones fall in it too and
6020/// the hour holds that one offset (checked once, at its first and last
6021/// nanosecond - a DST change inside makes them differ); any other instant's
6022/// looked up (br-frankenpandas-6pqf3). An instant run with no locality pays one lookup each,
6023/// as before.
6024struct HourOffsets<'a> {
6025    zone: &'a Zone,
6026    hour: i64,
6027    offset: i32,
6028    /// Whether `hour` holds `offset` throughout, once known.
6029    uniform: Option<bool>,
6030}
6031
6032impl<'a> HourOffsets<'a> {
6033    fn new(zone: &'a Zone) -> Self {
6034        Self {
6035            zone,
6036            hour: i64::MIN,
6037            offset: 0,
6038            uniform: None,
6039        }
6040    }
6041
6042    fn at(&mut self, utc: i64) -> i32 {
6043        if let Zone::Fixed(fixed) = self.zone {
6044            return fixed.local_minus_utc();
6045        }
6046        let hour = utc.div_euclid(NANOS_PER_HOUR);
6047        if hour != self.hour {
6048            self.hour = hour;
6049            self.uniform = None;
6050            self.offset = self.zone.offset_seconds(utc);
6051            return self.offset;
6052        }
6053        let uniform = *self.uniform.get_or_insert_with(|| {
6054            hour.checked_mul(NANOS_PER_HOUR).is_some_and(|start| {
6055                self.zone.offset_seconds(start) == self.offset
6056                    && start
6057                        .checked_add(NANOS_PER_HOUR - 1)
6058                        .is_some_and(|end| self.zone.offset_seconds(end) == self.offset)
6059            })
6060        });
6061        if uniform {
6062            self.offset
6063        } else {
6064            self.zone.offset_seconds(utc)
6065        }
6066    }
6067}
6068
6069/// The offset every wall time of local hour `hour` maps to UTC with, when
6070/// the hour holds no DST change: its first and last nanosecond each map to
6071/// one instant, at one offset (a gap or an overlap inside makes one of them
6072/// map otherwise or the offsets differ); None otherwise (br-frankenpandas-6pqf3).
6073fn simple_local_hour(zone: &Zone, hour: i64) -> Option<i32> {
6074    let start = hour.checked_mul(NANOS_PER_HOUR)?;
6075    let end = start.checked_add(NANOS_PER_HOUR - 1)?;
6076    let first = single_local_offset(zone, start)?;
6077    (single_local_offset(zone, end)? == first).then_some(first)
6078}
6079
6080/// The offset the wall time `wall_nanos` maps to UTC with when it maps to
6081/// exactly one instant.
6082fn single_local_offset(zone: &Zone, wall_nanos: i64) -> Option<i32> {
6083    use chrono::{LocalResult, Offset, TimeZone};
6084    let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6085    match zone {
6086        Zone::Fixed(offset) => Some(offset.local_minus_utc()),
6087        Zone::Named(zone) => match zone.from_local_datetime(&naive) {
6088            LocalResult::Single(at) => Some(at.offset().fix().local_minus_utc()),
6089            _ => None,
6090        },
6091    }
6092}
6093
6094/// A wall time as pandas names one it refuses to place: seconds, then the
6095/// microseconds as six digits when it has any and the nanoseconds as nine
6096/// when finer (chrono's text trimmed '.500000' to '.500'; br-frankenpandas-6pqf3).
6097fn wall_text(wall_nanos: i64) -> String {
6098    let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6099    let seconds = naive.format("%Y-%m-%d %H:%M:%S");
6100    let nanos = wall_nanos.rem_euclid(NANOS_PER_SECOND);
6101    if nanos == 0 {
6102        format!("{seconds}")
6103    } else if nanos % 1_000 == 0 {
6104        format!("{seconds}.{:06}", nanos / 1_000)
6105    } else {
6106        format!("{seconds}.{nanos:09}")
6107    }
6108}
6109
6110/// The offset pandas places a moved skipped wall time with: pytz's table
6111/// bisected at `moved` read as a UTC instant - the offset in force there
6112/// when moving forward onto an offset at or east of UTC, or when the zone's
6113/// first (local mean time) offset lies east and the move is forward or west
6114/// and it is backward; else the one after the next change (br-frankenpandas-6pqf3).
6115fn pandas_shift_offset(zone: &Zone, moved: i64, forward: bool) -> i32 {
6116    const DAY: i64 = 86_400 * NANOS_PER_SECOND;
6117    let here = zone.offset_seconds(moved);
6118    let first = zone.offset_seconds(i64::MIN + 1);
6119    let in_force = if forward {
6120        here >= 0 || first > 0
6121    } else {
6122        first < 0
6123    };
6124    if in_force {
6125        return here;
6126    }
6127    // The next change: the first day on whose offset differs (changes are
6128    // months apart), within three years.
6129    (1..=1_100_i64)
6130        .filter_map(|day| moved.checked_add(day * DAY))
6131        .map(|at| zone.offset_seconds(at))
6132        .find(|&offset| offset != here)
6133        .unwrap_or(here)
6134}
6135
6136/// [`tz_wall_to_utc_nanos_with`] in a zone already parsed.
6137fn wall_to_utc_in(
6138    zone: &Zone,
6139    wall_nanos: i64,
6140    ambiguous: AmbiguousTime,
6141    nonexistent: NonexistentTime,
6142) -> Result<i64, TimeZoneError> {
6143    use chrono::{LocalResult, TimeZone};
6144    let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6145    let local = match zone {
6146        Zone::Fixed(offset) => offset
6147            .from_local_datetime(&naive)
6148            .map(|at| at.fixed_offset()),
6149        Zone::Named(zone) => zone.from_local_datetime(&naive).map(|at| at.fixed_offset()),
6150    };
6151    let nanos_of = |at: chrono::DateTime<chrono::FixedOffset>| {
6152        at.timestamp_nanos_opt()
6153            .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))
6154    };
6155    match local {
6156        LocalResult::Single(at) => nanos_of(at),
6157        LocalResult::Ambiguous(earliest, latest) => match ambiguous {
6158            AmbiguousTime::Raise => Err(TimeZoneError::Ambiguous(wall_text(wall_nanos))),
6159            AmbiguousTime::Earliest => nanos_of(earliest),
6160            AmbiguousTime::Latest => nanos_of(latest),
6161            AmbiguousTime::NaT => Ok(i64::MIN),
6162        },
6163        LocalResult::None => match nonexistent {
6164            NonexistentTime::Raise => Err(TimeZoneError::NonExistent(wall_text(wall_nanos))),
6165            NonexistentTime::NaT => Ok(i64::MIN),
6166            NonexistentTime::Shift(delta) => {
6167                let shifted = wall_nanos
6168                    .checked_add(delta)
6169                    .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))?;
6170                if shifted == i64::MIN {
6171                    return Ok(shifted);
6172                }
6173                wall_to_utc_in(zone, shifted, ambiguous, NonexistentTime::Raise)
6174            }
6175            NonexistentTime::ShiftForward | NonexistentTime::ShiftBackward => {
6176                // pandas (pytz's tz_localize_to_utc) moves a skipped wall
6177                // time up to the next whole hour (shift_forward) or to a
6178                // nanosecond before its own hour (shift_backward), then
6179                // places that with the offset its table answers (see
6180                // [`pandas_shift_offset`]): the change's own instant for a
6181                // change on the hour, 03:00 (+11:00) where Lord Howe's
6182                // half-hour gap ends at 02:30 - this placed the gap's end
6183                // (br-frankenpandas-6pqf3).
6184                let forward = nonexistent == NonexistentTime::ShiftForward;
6185                let into_hour = wall_nanos.rem_euclid(NANOS_PER_HOUR);
6186                let moved = if forward {
6187                    wall_nanos.checked_add(NANOS_PER_HOUR - into_hour)
6188                } else {
6189                    wall_nanos.checked_sub(into_hour + 1)
6190                };
6191                moved
6192                    .and_then(|moved| {
6193                        let offset = pandas_shift_offset(zone, moved, forward);
6194                        moved.checked_sub(i64::from(offset) * NANOS_PER_SECOND)
6195                    })
6196                    .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))
6197            }
6198        },
6199    }
6200}
6201
6202/// `wall_nanos` formatted as Python's (glibc's) `strftime` does - what
6203/// pandas' `Timestamp.strftime` / `Series.dt.strftime` / `to_csv(date_format=)`
6204/// run per value: the C-locale directives (`%a %A %b %B %c %d %e %f %H %I
6205/// %j %m %M %p %S %U %w %W %x %X %y %Y %z %Z %%`), glibc's (`%C %D %F %g %G
6206/// %h %k %l %n %P %r %R %t %T %u %V`) and its `-` (no padding), `_` (space
6207/// padding), `0` and `^` (upper case) flags. An unknown directive is echoed
6208/// as written, as glibc does. `zone` is a tz-aware value's UTC offset (in
6209/// seconds) and abbreviation at that instant, which `%z` / `%Z` print (empty
6210/// for a naive value).
6211#[must_use]
6212pub fn strftime_python(wall_nanos: i64, format: &str, zone: Option<(i32, &str)>) -> String {
6213    const DAYS: [&str; 7] = [
6214        "Sunday",
6215        "Monday",
6216        "Tuesday",
6217        "Wednesday",
6218        "Thursday",
6219        "Friday",
6220        "Saturday",
6221    ];
6222    const MONTHS: [&str; 12] = [
6223        "January",
6224        "February",
6225        "March",
6226        "April",
6227        "May",
6228        "June",
6229        "July",
6230        "August",
6231        "September",
6232        "October",
6233        "November",
6234        "December",
6235    ];
6236    // Floor both boundaries so a pre-epoch instant keeps a consistent date
6237    // and time (1969-12-31 23:59:59.999999 for -1 ns).
6238    let total_secs = wall_nanos.div_euclid(1_000_000_000);
6239    let sub_nanos = wall_nanos.rem_euclid(1_000_000_000);
6240    let days = total_secs.div_euclid(86_400);
6241    let secs_of_day = total_secs.rem_euclid(86_400);
6242    let (year, month, day) = civil_from_days(days);
6243    let (hour, minute, second) = (
6244        secs_of_day / 3_600,
6245        (secs_of_day % 3_600) / 60,
6246        secs_of_day % 60,
6247    );
6248    let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
6249    let weekday = (days + 4).rem_euclid(7); // 0 = Sunday
6250    let yday = days - days_from_civil(year, 1, 1); // 0-based
6251    let iso_weekday = if weekday == 0 { 7 } else { weekday };
6252    let (iso_year, iso_week) = {
6253        let week = (yday + 1 - iso_weekday + 10).div_euclid(7);
6254        if week < 1 {
6255            (year - 1, iso_weeks_in_year(year - 1))
6256        } else if week > iso_weeks_in_year(year) {
6257            (year + 1, 1)
6258        } else {
6259            (year, week)
6260        }
6261    };
6262    let month_name = MONTHS[(month as usize).saturating_sub(1) % 12];
6263    let day_name = DAYS[weekday as usize];
6264
6265    let mut out = String::with_capacity(format.len().saturating_add(16));
6266    let mut chars = format.chars().peekable();
6267    while let Some(ch) = chars.next() {
6268        if ch != '%' {
6269            out.push(ch);
6270            continue;
6271        }
6272        let flag = chars.next_if(|c| matches!(c, '-' | '_' | '0' | '^'));
6273        let Some(conversion) = chars.next() else {
6274            out.push('%');
6275            if let Some(flag) = flag {
6276                out.push(flag);
6277            }
6278            break;
6279        };
6280        // A number `width` wide, padded with `pad` unless a flag says
6281        // otherwise.
6282        let number = |value: i64, width: usize, pad: char| -> String {
6283            match flag.unwrap_or(pad) {
6284                '-' => value.to_string(),
6285                '_' | ' ' => format!("{value:>width$}"),
6286                _ => format!("{value:0width$}"),
6287            }
6288        };
6289        let text = |value: &str| -> String {
6290            if flag == Some('^') {
6291                value.to_uppercase()
6292            } else {
6293                value.to_owned()
6294            }
6295        };
6296        let piece = match conversion {
6297            'a' => text(&day_name[..3]),
6298            'A' => text(day_name),
6299            'b' | 'h' => text(&month_name[..3]),
6300            'B' => text(month_name),
6301            'c' => text(&strftime_python(wall_nanos, "%a %b %e %H:%M:%S %Y", zone)),
6302            'C' => number(year.div_euclid(100), 2, '0'),
6303            'd' => number(i64::from(day), 2, '0'),
6304            'D' | 'x' => strftime_python(wall_nanos, "%m/%d/%y", zone),
6305            'e' => number(i64::from(day), 2, ' '),
6306            'f' => number(sub_nanos / 1_000, 6, '0'),
6307            'F' => strftime_python(wall_nanos, "%Y-%m-%d", zone),
6308            'g' => number(iso_year.rem_euclid(100), 2, '0'),
6309            'G' => number(iso_year, 1, '0'),
6310            'H' => number(hour, 2, '0'),
6311            'I' => number(hour12, 2, '0'),
6312            'j' => number(yday + 1, 3, '0'),
6313            'k' => number(hour, 2, ' '),
6314            'l' => number(hour12, 2, ' '),
6315            'm' => number(i64::from(month), 2, '0'),
6316            'M' => number(minute, 2, '0'),
6317            'n' => "\n".to_owned(),
6318            'p' => text(if hour < 12 { "AM" } else { "PM" }),
6319            'P' => (if hour < 12 { "am" } else { "pm" }).to_owned(),
6320            'r' => strftime_python(wall_nanos, "%I:%M:%S %p", zone),
6321            'R' => strftime_python(wall_nanos, "%H:%M", zone),
6322            'S' => number(second, 2, '0'),
6323            't' => "\t".to_owned(),
6324            'T' | 'X' => strftime_python(wall_nanos, "%H:%M:%S", zone),
6325            'u' => number(iso_weekday, 1, '0'),
6326            'U' => number((yday + 7 - weekday).div_euclid(7), 2, '0'),
6327            'V' => number(iso_week, 2, '0'),
6328            'w' => number(weekday, 1, '0'),
6329            'W' => number(
6330                (yday + 7 - (weekday + 6).rem_euclid(7)).div_euclid(7),
6331                2,
6332                '0',
6333            ),
6334            'y' => number(year.rem_euclid(100), 2, '0'),
6335            'Y' => number(year, 1, '0'),
6336            'z' => zone.map_or_else(String::new, |(offset, _)| {
6337                let sign = if offset < 0 { '-' } else { '+' };
6338                let offset = offset.unsigned_abs();
6339                let (h, m, s) = (offset / 3_600, (offset % 3_600) / 60, offset % 60);
6340                if s == 0 {
6341                    format!("{sign}{h:02}{m:02}")
6342                } else {
6343                    format!("{sign}{h:02}{m:02}{s:02}")
6344                }
6345            }),
6346            'Z' => zone.map_or_else(String::new, |(_, name)| text(name)),
6347            '%' => "%".to_owned(),
6348            other => {
6349                // glibc echoes a conversion it does not know.
6350                out.push('%');
6351                if let Some(flag) = flag {
6352                    out.push(flag);
6353                }
6354                out.push(other);
6355                continue;
6356            }
6357        };
6358        out.push_str(&piece);
6359    }
6360    out
6361}
6362
6363/// The instant `nanos` formatted by [`strftime_python`]: a naive value as
6364/// it is; in `tz` (a tz-aware value, `nanos` its UTC instant) on the zone's
6365/// wall clock with the offset and abbreviation of that instant.
6366#[must_use]
6367pub fn strftime_in_zone(nanos: i64, format: &str, tz: Option<&str>) -> String {
6368    let aware = tz.and_then(|zone| {
6369        let offset = tz_offset_seconds(zone, nanos).ok()?;
6370        let name = tz_abbreviation(zone, nanos).ok()?;
6371        Some((offset, name))
6372    });
6373    match aware {
6374        Some((offset, name)) => strftime_python(
6375            nanos.saturating_add(i64::from(offset) * 1_000_000_000),
6376            format,
6377            Some((offset, &name)),
6378        ),
6379        None => strftime_python(nanos, format, None),
6380    }
6381}
6382
6383/// `str(Timestamp)` of the naive instant `nanos`: its wall clock
6384/// 'YYYY-MM-DD HH:MM:SS' and its own fraction when it has one (six digits,
6385/// nine for nanoseconds) - how pandas prints a naive Timestamp an object
6386/// column holds (`astype(str)` spelled it 'Timestamp[<nanos>]';
6387/// br-frankenpandas-srzqw).
6388#[must_use]
6389pub fn timestamp_text(nanos: i64) -> String {
6390    let mut text = strftime_python(nanos, "%Y-%m-%d %H:%M:%S", None);
6391    let fraction = nanos.rem_euclid(1_000_000_000);
6392    if fraction % 1_000 != 0 {
6393        text.push_str(&format!(".{fraction:09}"));
6394    } else if fraction != 0 {
6395        text.push_str(&format!(".{:06}", fraction / 1_000));
6396    }
6397    text
6398}
6399
6400/// `str(Timestamp)` of the instant `nanos` in `tz`, as pandas prints a
6401/// tz-aware value (repr cells, `astype(str)`): its [`timestamp_text`] wall
6402/// clock and the zone's `+HH:MM` offset then.
6403#[must_use]
6404pub fn timestamp_text_in_zone(nanos: i64, tz: &str) -> String {
6405    let offset = tz_offset_seconds(tz, nanos).unwrap_or(0);
6406    let mut text = timestamp_text(nanos.saturating_add(i64::from(offset) * 1_000_000_000));
6407    let sign = if offset < 0 { '-' } else { '+' };
6408    let minutes = offset.unsigned_abs() / 60;
6409    text.push_str(&format!("{sign}{:02}:{:02}", minutes / 60, minutes % 60));
6410    text
6411}
6412
6413/// `nanos` (datetime64[ns]) plus `months` calendar months, the day clipped
6414/// to the target month's last day and the time of day kept - dateutil's
6415/// relativedelta, which pandas' `DateOffset(years=, months=)` applies (Jan
6416/// 31 + 1 month is Feb 29 in 2024). Civil-date arithmetic on the day count:
6417/// a chrono date made and read back a row was most of
6418/// s + DateOffset(months=1) (300k 12.9 ms, pandas 7.9; br-frankenpandas-4g57c).
6419/// None when the result leaves datetime64[ns].
6420#[must_use]
6421pub fn add_calendar_months_nanos(nanos: i64, months: i64) -> Option<i64> {
6422    const DAY: i64 = 86_400_000_000_000;
6423    let moved = add_calendar_months_days(nanos.div_euclid(DAY), months)?;
6424    i64::try_from(i128::from(moved) * i128::from(DAY) + i128::from(nanos.rem_euclid(DAY))).ok()
6425}
6426
6427/// The day (days since 1970-01-01) `months` calendar months after `day`,
6428/// the day of the month clipped to the target month's last day - the date
6429/// part of [`add_calendar_months_nanos`], which a column moving instants
6430/// that share a day computes once. None a million years out.
6431#[must_use]
6432pub fn add_calendar_months_days(day: i64, months: i64) -> Option<i64> {
6433    // No date is a million years out (and the day counts below would
6434    // overflow there).
6435    if day.unsigned_abs() > 365_000_000 {
6436        return None;
6437    }
6438    let (year, month, day) = civil_from_days(day);
6439    let total = year
6440        .checked_mul(12)?
6441        .checked_add(i64::from(month) - 1)?
6442        .checked_add(months)?;
6443    let year = total.div_euclid(12);
6444    if year.unsigned_abs() > 1_000_000 {
6445        return None;
6446    }
6447    let month = u32::try_from(total.rem_euclid(12)).ok()? + 1;
6448    let day = day.min(days_in_month(year, month)?);
6449    Some(days_from_civil(year, month, day))
6450}
6451
6452/// Days since 1970-01-01 of the proleptic-Gregorian date `(year, month,
6453/// day)` (Howard Hinnant's days-from-civil; the inverse of
6454/// `civil_from_days`).
6455fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
6456    let (month, day) = (i64::from(month), i64::from(day));
6457    let year = if month <= 2 { year - 1 } else { year };
6458    let era = if year >= 0 { year } else { year - 399 } / 400;
6459    let yoe = year - era * 400;
6460    let doy = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
6461    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
6462    era * 146_097 + doe - 719_468
6463}
6464
6465// ── Timestamp types (br-frankenpandas-9p0u — 4r56 Phase 2) ─────────────
6466//
6467// Nanosecond-precision i64 since Unix epoch + optional IANA tz name. The
6468// zone's DST-aware conversions are the time-zone functions above
6469// (`tz_offset_seconds`, `tz_wall_to_utc_nanos`); arithmetic here stays on
6470// the absolute nanos axis.
6471
6472/// Number of days in a given month (1-12) of a given year.
6473fn days_in_month(year: i64, month: u32) -> Option<u32> {
6474    if !(1..=12).contains(&month) {
6475        return None;
6476    }
6477    let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
6478    let days: [u32; 12] = [
6479        31,
6480        if is_leap { 29 } else { 28 },
6481        31,
6482        30,
6483        31,
6484        30,
6485        31,
6486        31,
6487        30,
6488        31,
6489        30,
6490        31,
6491    ];
6492    Some(days[(month - 1) as usize])
6493}
6494
6495/// Number of ISO-8601 weeks in a year (52 or 53).
6496///
6497/// A year has 53 ISO weeks iff its first day falls on a Thursday, or it is a
6498/// leap year whose first day is a Wednesday — captured by the dominical
6499/// closed form `p(year) == 4 || p(year - 1) == 3`, where
6500/// `p(y) = (y + ⌊y/4⌋ − ⌊y/100⌋ + ⌊y/400⌋) mod 7` is the weekday of Dec 31.
6501fn iso_weeks_in_year(year: i64) -> i64 {
6502    fn p(y: i64) -> i64 {
6503        (y + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400)).rem_euclid(7)
6504    }
6505    if p(year) == 4 || p(year - 1) == 3 {
6506        53
6507    } else {
6508        52
6509    }
6510}
6511
6512/// A nanosecond-precision point in time, Unix-epoch anchored.
6513///
6514/// Phase 2 scope: construction, arithmetic, equality, ordering, serde.
6515/// TZ semantics (IANA tz lookup, DST-aware shift) are deferred to Phase
6516/// 3 — see br-frankenpandas-4r56.
6517#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
6518pub struct Timestamp {
6519    /// Nanoseconds since Unix epoch. `i64::MIN` is NaT.
6520    pub nanos: i64,
6521    /// Optional IANA time-zone name (e.g. `"US/Eastern"`). `None` means
6522    /// naive / UTC-anchored. Phase 2 treats this as opaque metadata;
6523    /// Phase 3 wires chrono_tz interpretation.
6524    #[serde(default, skip_serializing_if = "Option::is_none")]
6525    pub tz: Option<String>,
6526}
6527
6528/// How `astype(str)` renders a `timedelta64[ns]` COLUMN.
6529///
6530/// ⚠️ THE TIMEDELTA LADDER IS NOT THE DATETIME ONE, and copying the sibling
6531/// across is the mistake this type exists to prevent. It has exactly TWO rungs,
6532/// and — unlike [`DatetimeStringResolution`] — THE SUB-SECOND WIDTH IS PER
6533/// VALUE, not per column. MEASURED, live pandas 2.2.3:
6534///
6535/// ```text
6536/// [1 days, 2 days]              -> ['1 days', '2 days']
6537/// [1 days, 5 ms]                -> ['1 days 00:00:00', '0 days 00:00:00.005000']
6538/// [1 days 02:03:04.005, 1 ns]   -> ['1 days 02:03:04.005000',
6539///                                   '0 days 00:00:00.000000001']
6540/// ```
6541///
6542/// That last row is the whole distinction: a millisecond value keeps its SIX
6543/// digits while its neighbour prints NINE. On the datetime side the same pair
6544/// would have been widened to a common nine. So the only column-wide question
6545/// here is whether the time-of-day part can be dropped entirely, which is what
6546/// [`Timedelta::string_resolution`] answers; [`Timedelta::format`] already gets
6547/// the per-value part right and is reused unchanged.
6548#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6549pub enum TimedeltaStringResolution {
6550    /// `1 days` / `-2 days` / `0 days` — every value is a whole day.
6551    Days,
6552    /// `1 days 02:03:04.005000` — the full rendering, sub-second width per value.
6553    Full,
6554}
6555
6556/// How wide `astype(str)` renders a `datetime64[ns]` value.
6557///
6558/// ⚠️ THIS IS A PROPERTY OF THE COLUMN, NOT OF THE VALUE, which is the whole
6559/// reason it is a separate type rather than a branch inside a per-scalar
6560/// formatter. MEASURED, live pandas 2.2.3 — the SAME midnight timestamp renders
6561/// three different ways depending only on what it shares a column with:
6562///
6563/// ```text
6564/// Series([midnight, midnight]).astype(str)   -> '2024-03-15'
6565/// Series([midnight, one_nanosecond]).astype(str)
6566///                                            -> '2024-03-15 00:00:00.000000000'
6567/// str(Timestamp(midnight))                   -> '2024-03-15 00:00:00'
6568/// ```
6569///
6570/// pandas picks the coarsest rung that is lossless for EVERY element and
6571/// imposes it on all of them. The `Ord` derive is the fold: scan the column
6572/// with `max` over [`Timestamp::string_resolution`], then format every value at
6573/// the winner. Variants are declared coarsest-first so that `max` means
6574/// "finest needed".
6575#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6576pub enum DatetimeStringResolution {
6577    /// `2024-03-15` — every value in the column is midnight.
6578    Date,
6579    /// `2024-03-15 10:30:45` — every value is a whole second.
6580    Second,
6581    /// `2024-03-15 10:30:45.123`
6582    Milli,
6583    /// `2024-03-15 10:30:45.123456`
6584    Micro,
6585    /// `2024-03-15 10:30:45.123456789`
6586    Nano,
6587}
6588
6589impl Timestamp {
6590    /// NaT sentinel, parallel to `Timedelta::NAT`.
6591    pub const NAT: i64 = i64::MIN;
6592
6593    /// Construct a UTC-anchored (tz=None) Timestamp from nanoseconds
6594    /// since Unix epoch.
6595    #[must_use]
6596    pub const fn from_nanos(nanos: i64) -> Self {
6597        Self { nanos, tz: None }
6598    }
6599
6600    /// Construct a Timestamp tagged with an IANA tz name.
6601    ///
6602    /// Phase 2 doesn't interpret the tz — it only carries the name
6603    /// through arithmetic + serde. Phase 3 wires chrono_tz conversion.
6604    #[must_use]
6605    pub fn from_nanos_tz(nanos: i64, tz_name: impl Into<String>) -> Self {
6606        Self {
6607            nanos,
6608            tz: Some(tz_name.into()),
6609        }
6610    }
6611
6612    /// Returns the current UTC timestamp.
6613    ///
6614    /// ⚠️ THIS MATCHES `pd.Timestamp.utcnow()`, NOT `pd.Timestamp.now()`, and the
6615    /// old doc claimed both. They are different functions: pandas' `now()` returns
6616    /// LOCAL time with no timezone attached, while `utcnow()` returns UTC.
6617    /// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-19) on a UTC-4 host:
6618    /// ```text
6619    ///   pd.Timestamp.now()    2026-08-19 07:17:07.266940        tz None
6620    ///   pd.Timestamp.utcnow() 2026-08-19 11:17:07.267100+00:00  tz UTC
6621    ///   difference: 14400 s
6622    /// ```
6623    /// A caller who trusted the old claim and ran on a non-UTC host would be off by
6624    /// their whole UTC offset — four hours here — with no error and no NaT to notice.
6625    /// This crate has no local-timezone concept, so the UTC answer is the only one it
6626    /// can give; only the false half of the claim is removed.
6627    #[must_use]
6628    pub fn now() -> Self {
6629        use std::time::{SystemTime, UNIX_EPOCH};
6630        let duration = SystemTime::now()
6631            .duration_since(UNIX_EPOCH)
6632            .unwrap_or_default();
6633        let nanos = duration.as_nanos() as i64;
6634        Self { nanos, tz: None }
6635    }
6636
6637    /// Alias for `now()`. Matches `pd.Timestamp.utcnow()`.
6638    #[must_use]
6639    pub fn utcnow() -> Self {
6640        Self::now()
6641    }
6642
6643    /// Returns today's date at midnight UTC.
6644    ///
6645    /// Matches `pd.Timestamp.today()`.
6646    #[must_use]
6647    pub fn today() -> Self {
6648        let now = Self::now();
6649        now.normalize()
6650    }
6651
6652    /// The NaT sentinel value for a Timestamp.
6653    #[must_use]
6654    pub const fn nat() -> Self {
6655        Self {
6656            nanos: Self::NAT,
6657            tz: None,
6658        }
6659    }
6660
6661    /// True iff this Timestamp is NaT.
6662    #[must_use]
6663    pub const fn is_nat(&self) -> bool {
6664        self.nanos == Self::NAT
6665    }
6666
6667    /// Nanoseconds since Unix epoch, matching `pd.Timestamp.value`.
6668    #[must_use]
6669    pub const fn value(&self) -> i64 {
6670        self.nanos
6671    }
6672
6673    /// Stored resolution unit, matching `pd.Timestamp.unit`.
6674    ///
6675    /// FrankenPandas `Timestamp` stores nanoseconds internally, so non-NaT
6676    /// values report `ns`. `NaT` has no unit.
6677    #[must_use]
6678    pub const fn unit(&self) -> Option<&'static str> {
6679        if self.is_nat() { None } else { Some("ns") }
6680    }
6681
6682    /// Return the resolution of the timestamp (always "ns" for nanoseconds).
6683    ///
6684    /// Matches `pd.Timestamp.resolution`. Returns None for NaT.
6685    #[must_use]
6686    pub const fn resolution(&self) -> Option<&'static str> {
6687        if self.is_nat() { None } else { Some("ns") }
6688    }
6689
6690    /// Numpy datetime64 scalar payload, matching `pd.Timestamp.asm8`.
6691    #[must_use]
6692    pub const fn asm8(&self) -> i64 {
6693        self.value()
6694    }
6695
6696    /// Convert to a datetime64 payload, matching `pd.Timestamp.to_datetime64()`.
6697    #[must_use]
6698    pub const fn to_datetime64(&self) -> i64 {
6699        self.value()
6700    }
6701
6702    /// Convert to a numpy scalar payload, matching `pd.Timestamp.to_numpy()`.
6703    #[must_use]
6704    pub const fn to_numpy(&self) -> i64 {
6705        self.value()
6706    }
6707
6708    /// POSIX timestamp in seconds, matching `pd.Timestamp.timestamp()`.
6709    ///
6710    /// Pandas exposes this through Python's datetime surface, so sub-microsecond
6711    /// nanoseconds are rounded to six decimal places. `NaT` raises in pandas;
6712    /// fp-types surfaces the same condition as a missing-value error.
6713    pub fn timestamp(&self) -> Result<f64, TypeError> {
6714        if self.is_nat() {
6715            return Err(TypeError::ValueIsMissing {
6716                kind: NullKind::NaT,
6717            });
6718        }
6719        let seconds = self.nanos as f64 / 1_000_000_000.0;
6720        let rounded = format!("{seconds:.6}").parse().unwrap_or(seconds);
6721        Ok(rounded)
6722    }
6723
6724    /// Add a Timedelta. NaT in either operand → NaT; overflow → NaT.
6725    /// TZ is preserved from `self`.
6726    ///
6727    /// Overflow is NaT in both directions (br-frankenpandas-lgyy8) — see the
6728    /// overflow note on [`Timedelta::add`]. A saturated `i64::MAX` would be a
6729    /// finite, plausible ~year-2262 instant returned as if it were real data;
6730    /// `pd.Timestamp.max + pd.Timedelta('1ns')` raises `OutOfBoundsDatetime`.
6731    #[must_use]
6732    pub fn add_timedelta(&self, td_nanos: i64) -> Self {
6733        self.try_add_timedelta(td_nanos)
6734            .unwrap_or_else(|_| Self::nat())
6735    }
6736
6737    /// Shift by a Timedelta, reporting overflow.
6738    ///
6739    /// br-frankenpandas-fyr1z-policy-carrier-f29nz. A NaT operand is
6740    /// propagation, not overflow, so it yields `Ok(nat())`. On overflow the
6741    /// caller gets the error INSTEAD of the tz-dropped NaT; the infallible
6742    /// `add_timedelta` above still produces that NaT, unchanged.
6743    ///
6744    /// # Errors
6745    /// [`PandasTemporalError::OutOfBoundsDatetime`], matching
6746    /// `pd.Timestamp.max + pd.Timedelta('1ns')`.
6747    pub fn try_add_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6748        if self.is_nat() || td_nanos == Timedelta::NAT {
6749            return Ok(Self::nat());
6750        }
6751        match self.nanos.checked_add(td_nanos) {
6752            Some(nanos) => Ok(Self {
6753                nanos,
6754                tz: self.tz.clone(),
6755            }),
6756            // Overflow drops the tz with the value: an out-of-range instant has
6757            // no zone, and `Self::nat()` is the one canonical NaT (matching the
6758            // NaT-operand arms above, which also return an untagged NaT).
6759            None => Err(TemporalFailure::new(
6760                "Timestamp::add_timedelta",
6761                PandasTemporalError::OutOfBoundsDatetime,
6762            )
6763            .with_operands(self.nanos, td_nanos)),
6764        }
6765    }
6766
6767    /// Subtract a Timedelta. NaT propagation; overflow → NaT. TZ preserved.
6768    #[must_use]
6769    pub fn sub_timedelta(&self, td_nanos: i64) -> Self {
6770        self.try_sub_timedelta(td_nanos)
6771            .unwrap_or_else(|_| Self::nat())
6772    }
6773
6774    /// Shift back by a Timedelta, reporting overflow. See
6775    /// [`Self::try_add_timedelta`].
6776    ///
6777    /// # Errors
6778    /// [`PandasTemporalError::OutOfBoundsDatetime`].
6779    pub fn try_sub_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6780        if self.is_nat() || td_nanos == Timedelta::NAT {
6781            return Ok(Self::nat());
6782        }
6783        match self.nanos.checked_sub(td_nanos) {
6784            Some(nanos) => Ok(Self {
6785                nanos,
6786                tz: self.tz.clone(),
6787            }),
6788            None => Err(TemporalFailure::new(
6789                "Timestamp::sub_timedelta",
6790                PandasTemporalError::OutOfBoundsDatetime,
6791            )
6792            .with_operands(self.nanos, td_nanos)),
6793        }
6794    }
6795
6796    /// Subtract another Timestamp. Returns a Timedelta (i64 nanos).
6797    /// NaT in either → `Timedelta::NAT`; overflow → `Timedelta::NAT`
6798    /// (`pd.Timestamp.min - pd.Timestamp.max` raises `OutOfBoundsDatetime`).
6799    #[must_use]
6800    pub fn sub_timestamp(&self, other: &Self) -> i64 {
6801        self.try_sub_timestamp(other).unwrap_or(Timedelta::NAT)
6802    }
6803
6804    /// Elapsed nanoseconds between two Timestamps, reporting overflow.
6805    ///
6806    /// # Errors
6807    /// [`PandasTemporalError::OutOfBoundsDatetime`], matching
6808    /// `pd.Timestamp.min - pd.Timestamp.max`.
6809    pub fn try_sub_timestamp(&self, other: &Self) -> Result<i64, TemporalFailure> {
6810        if self.is_nat() || other.is_nat() {
6811            return Ok(Timedelta::NAT);
6812        }
6813        self.nanos.checked_sub(other.nanos).ok_or(
6814            TemporalFailure::new(
6815                "Timestamp::sub_timestamp",
6816                PandasTemporalError::OutOfBoundsDatetime,
6817            )
6818            .with_operands(self.nanos, other.nanos),
6819        )
6820    }
6821
6822    /// NaT-aware semantic equality: two NaT Timestamps are equal to each
6823    /// other (matches pandas `pd.NaT == pd.NaT` under `equals()`, though
6824    /// pandas's `==` operator returns False for NaT==NaT — we follow the
6825    /// `semantic_eq` convention used elsewhere in fp-types).
6826    #[must_use]
6827    pub fn semantic_eq(&self, other: &Self) -> bool {
6828        if self.is_nat() && other.is_nat() {
6829            return true;
6830        }
6831        if self.is_nat() || other.is_nat() {
6832            return false;
6833        }
6834        self.nanos == other.nanos && self.tz == other.tz
6835    }
6836
6837    // ── Rounding to a Timedelta unit (br-frankenpandas-5h6n) ────────────
6838    //
6839    // Pure i64 arithmetic on the nanos axis. tz is preserved. Phase 3
6840    // chrono_tz integration will add a tz-aware variant that handles DST
6841    // boundaries correctly; these methods operate on the absolute time
6842    // axis, matching pandas's tz-naive `.floor` / `.ceil` / `.round`
6843    // semantics for unit values smaller than a day.
6844
6845    /// Round down to the nearest multiple of `unit_nanos`.
6846    ///
6847    /// Matches `pd.Timestamp(...).floor(unit)`. NaT in `self` or a
6848    /// non-positive `unit_nanos` returns NaT.
6849    #[must_use]
6850    pub fn floor_to(&self, unit_nanos: i64) -> Self {
6851        if self.is_nat() || unit_nanos <= 0 {
6852            return Self::nat();
6853        }
6854        let Some(nanos) = self.nanos.div_euclid(unit_nanos).checked_mul(unit_nanos) else {
6855            return Self::nat();
6856        };
6857        Self {
6858            nanos,
6859            tz: self.tz.clone(),
6860        }
6861    }
6862
6863    /// Round up to the nearest multiple of `unit_nanos`.
6864    ///
6865    /// Matches `pd.Timestamp(...).ceil(unit)`. NaT or non-positive
6866    /// `unit_nanos` returns NaT. Already-multiple inputs return self.
6867    #[must_use]
6868    pub fn ceil_to(&self, unit_nanos: i64) -> Self {
6869        if self.is_nat() || unit_nanos <= 0 {
6870            return Self::nat();
6871        }
6872        let rem = self.nanos.rem_euclid(unit_nanos);
6873        let nanos = if rem == 0 {
6874            self.nanos
6875        } else {
6876            // Checked, matching the sibling `floor_to` directly above
6877            // (br-frankenpandas-kyd16). A clamped i64::MAX would be a finite,
6878            // plausible ~year-2262 instant; `pd.Timestamp.max.ceil('D')`
6879            // raises OutOfBoundsDatetime "Cannot round ... without overflow".
6880            let Some(nanos) = self.nanos.checked_add(unit_nanos - rem) else {
6881                return Self::nat();
6882            };
6883            nanos
6884        };
6885        Self {
6886            nanos,
6887            tz: self.tz.clone(),
6888        }
6889    }
6890
6891    /// Round to the nearest multiple of `unit_nanos`, banker's rounding
6892    /// (half-to-even) on ties.
6893    ///
6894    /// Matches `pd.Timestamp(...).round(unit)`. NaT or non-positive
6895    /// `unit_nanos` returns NaT.
6896    #[must_use]
6897    pub fn round_to(&self, unit_nanos: i64) -> Self {
6898        if self.is_nat() || unit_nanos <= 0 {
6899            return Self::nat();
6900        }
6901        let floor = self.nanos.div_euclid(unit_nanos);
6902        let rem = self.nanos.rem_euclid(unit_nanos);
6903        let half = unit_nanos / 2;
6904        let chosen_floor = if rem < half {
6905            floor
6906        } else if rem > half {
6907            floor + 1
6908        } else if unit_nanos % 2 != 0 {
6909            // Odd unit can't have a true half; treat as round-up.
6910            floor + 1
6911        } else {
6912            // Tie: pick the even multiple.
6913            if floor % 2 == 0 { floor } else { floor + 1 }
6914        };
6915        // Checked, matching the sibling `floor_to` (br-frankenpandas-kyd16):
6916        // `pd.Timestamp.max.round('D')` raises OutOfBoundsDatetime rather than
6917        // returning the clamped i64::MAX instant.
6918        let Some(nanos) = chosen_floor.checked_mul(unit_nanos) else {
6919            return Self::nat();
6920        };
6921        Self {
6922            nanos,
6923            tz: self.tz.clone(),
6924        }
6925    }
6926
6927    // ── String-unit rounding (br-frankenpandas-lbsx) ────────────────────
6928    //
6929    // Pandas convenience: `.floor('H')` / `.ceil('1D')` / `.round('15min')`.
6930    // These read the frequency with `fixed_freq_nanos`, then delegate to
6931    // the nanos-based `floor_to`/`ceil_to`/`round_to`. Unknown unit strings
6932    // return NaT, matching the rest of fp-types' "missing-input → missing-
6933    // output" convention.
6934
6935    /// A fixed frequency's length: a bare unit (`Timedelta::unit_to_nanos`)
6936    /// or a multiple of one ('15min', '1D', '30s' - they were unknown, so
6937    /// `round('15min')` was NaT); None for anything else.
6938    fn fixed_freq_nanos(freq: &str) -> Option<i64> {
6939        Timedelta::unit_to_nanos(freq).or_else(|| Timedelta::parse(freq).ok())
6940    }
6941
6942    /// Round down to the nearest multiple of the named unit.
6943    ///
6944    /// Matches `pd.Timestamp(...).floor(unit)`. Unknown unit → NaT.
6945    #[must_use]
6946    pub fn floor_to_unit(&self, unit: &str) -> Self {
6947        match Self::fixed_freq_nanos(unit) {
6948            Some(unit_nanos) => self.floor_to(unit_nanos),
6949            None => Self::nat(),
6950        }
6951    }
6952
6953    /// Round up to the nearest multiple of the named unit.
6954    ///
6955    /// Matches `pd.Timestamp(...).ceil(unit)`. Unknown unit → NaT.
6956    #[must_use]
6957    pub fn ceil_to_unit(&self, unit: &str) -> Self {
6958        match Self::fixed_freq_nanos(unit) {
6959            Some(unit_nanos) => self.ceil_to(unit_nanos),
6960            None => Self::nat(),
6961        }
6962    }
6963
6964    /// Round to the nearest multiple of the named unit, banker's rounding.
6965    ///
6966    /// Matches `pd.Timestamp(...).round(unit)`. Unknown unit → NaT.
6967    #[must_use]
6968    pub fn round_to_unit(&self, unit: &str) -> Self {
6969        match Self::fixed_freq_nanos(unit) {
6970            Some(unit_nanos) => self.round_to(unit_nanos),
6971            None => Self::nat(),
6972        }
6973    }
6974
6975    /// Pandas-named alias for [`floor_to_unit`](Self::floor_to_unit).
6976    #[must_use]
6977    pub fn floor(&self, freq: &str) -> Self {
6978        self.floor_to_unit(freq)
6979    }
6980
6981    /// Pandas-named alias for [`ceil_to_unit`](Self::ceil_to_unit).
6982    #[must_use]
6983    pub fn ceil(&self, freq: &str) -> Self {
6984        self.ceil_to_unit(freq)
6985    }
6986
6987    /// Pandas-named alias for [`round_to_unit`](Self::round_to_unit).
6988    #[must_use]
6989    pub fn round(&self, freq: &str) -> Self {
6990        self.round_to_unit(freq)
6991    }
6992
6993    /// Extract the year component from the timestamp.
6994    ///
6995    /// Matches `pd.Timestamp.year`. Returns None for NaT.
6996    #[must_use]
6997    pub fn year(&self) -> Option<i64> {
6998        if self.is_nat() {
6999            return None;
7000        }
7001        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
7002        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
7003        // for the post-1970 positive case.
7004        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7005        let days = days_since_epoch + 719_468;
7006        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7007        let doe = days - era * 146_097;
7008        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7009        let y = yoe + era * 400;
7010        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7011        let mp = (5 * doy + 2) / 153;
7012        let m = if mp < 10 { mp + 3 } else { mp - 9 };
7013        Some(if m <= 2 { y + 1 } else { y })
7014    }
7015
7016    /// Extract the month component (1-12) from the timestamp.
7017    ///
7018    /// Matches `pd.Timestamp.month`. Returns None for NaT.
7019    #[must_use]
7020    pub fn month(&self) -> Option<i64> {
7021        if self.is_nat() {
7022            return None;
7023        }
7024        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
7025        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
7026        // for the post-1970 positive case.
7027        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7028        let days = days_since_epoch + 719_468;
7029        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7030        let doe = days - era * 146_097;
7031        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7032        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7033        let mp = (5 * doy + 2) / 153;
7034        Some(if mp < 10 { mp + 3 } else { mp - 9 })
7035    }
7036
7037    /// Extract the day component (1-31) from the timestamp.
7038    ///
7039    /// Matches `pd.Timestamp.day`. Returns None for NaT.
7040    #[must_use]
7041    pub fn day(&self) -> Option<i64> {
7042        if self.is_nat() {
7043            return None;
7044        }
7045        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
7046        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
7047        // for the post-1970 positive case.
7048        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7049        let days = days_since_epoch + 719_468;
7050        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7051        let doe = days - era * 146_097;
7052        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7053        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7054        let mp = (5 * doy + 2) / 153;
7055        Some(doy - (153 * mp + 2) / 5 + 1)
7056    }
7057
7058    /// Extract the hour component (0-23) from the timestamp.
7059    ///
7060    /// Matches `pd.Timestamp.hour`. Returns None for NaT.
7061    #[must_use]
7062    pub fn hour(&self) -> Option<i64> {
7063        if self.is_nat() {
7064            return None;
7065        }
7066        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
7067        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
7068        // rem_euclid == `%` for the post-1970 positive case.
7069        let secs_of_day =
7070            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7071        Some(secs_of_day / 3600)
7072    }
7073
7074    /// Extract the minute component (0-59) from the timestamp.
7075    ///
7076    /// Matches `pd.Timestamp.minute`. Returns None for NaT.
7077    #[must_use]
7078    pub fn minute(&self) -> Option<i64> {
7079        if self.is_nat() {
7080            return None;
7081        }
7082        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
7083        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
7084        // rem_euclid == `%` for the post-1970 positive case.
7085        let secs_of_day =
7086            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7087        Some((secs_of_day % 3600) / 60)
7088    }
7089
7090    /// Extract the second component (0-59) from the timestamp.
7091    ///
7092    /// Matches `pd.Timestamp.second`. Returns None for NaT.
7093    #[must_use]
7094    pub fn second(&self) -> Option<i64> {
7095        if self.is_nat() {
7096            return None;
7097        }
7098        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
7099        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
7100        // rem_euclid == `%` for the post-1970 positive case.
7101        let secs_of_day =
7102            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7103        Some(secs_of_day % 60)
7104    }
7105
7106    /// Extract the microsecond component (0-999999) from the timestamp.
7107    ///
7108    /// Matches `pd.Timestamp.microsecond`. Returns None for NaT.
7109    #[must_use]
7110    pub fn microsecond(&self) -> Option<i64> {
7111        if self.is_nat() {
7112            return None;
7113        }
7114        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
7115        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
7116        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7117        Some((sub_nanos / 1000) as i64)
7118    }
7119
7120    /// Extract the nanosecond component (0-999) from the timestamp.
7121    ///
7122    /// Matches `pd.Timestamp.nanosecond`. Returns None for NaT.
7123    #[must_use]
7124    pub fn nanosecond(&self) -> Option<i64> {
7125        if self.is_nat() {
7126            return None;
7127        }
7128        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
7129        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
7130        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7131        Some((sub_nanos % 1000) as i64)
7132    }
7133
7134    /// Return the day of the week (Monday=0, Sunday=6).
7135    ///
7136    /// Matches `pd.Timestamp.dayofweek`. Returns None for NaT.
7137    #[must_use]
7138    pub fn dayofweek(&self) -> Option<i64> {
7139        if self.is_nat() {
7140            return None;
7141        }
7142        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
7143        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7144        let dow = ((days_since_epoch + 3) % 7 + 7) % 7;
7145        Some(dow)
7146    }
7147
7148    /// Alias for dayofweek(). Matches `pd.Timestamp.weekday`.
7149    #[must_use]
7150    pub fn weekday(&self) -> Option<i64> {
7151        self.dayofweek()
7152    }
7153
7154    /// Alias for dayofweek(). Matches `pd.Timestamp.day_of_week`.
7155    #[must_use]
7156    pub fn day_of_week(&self) -> Option<i64> {
7157        self.dayofweek()
7158    }
7159
7160    /// Return the day of the year (1-366).
7161    ///
7162    /// Matches `pd.Timestamp.dayofyear`. Returns None for NaT.
7163    #[must_use]
7164    pub fn dayofyear(&self) -> Option<i64> {
7165        if self.is_nat() {
7166            return None;
7167        }
7168        let m = self.month()?;
7169        let d = self.day()?;
7170        let y = self.year()?;
7171        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7172        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
7173        let base = days_before[(m - 1) as usize] + d;
7174        if is_leap && m > 2 {
7175            Some(base + 1)
7176        } else {
7177            Some(base)
7178        }
7179    }
7180
7181    /// Alias for dayofyear(). Matches `pd.Timestamp.day_of_year`.
7182    #[must_use]
7183    pub fn day_of_year(&self) -> Option<i64> {
7184        self.dayofyear()
7185    }
7186
7187    /// Return the proleptic Gregorian ordinal (number of days since Jan 1, year 1).
7188    ///
7189    /// Matches `pd.Timestamp.toordinal()`. Returns None for NaT.
7190    #[must_use]
7191    pub fn toordinal(&self) -> Option<i64> {
7192        if self.is_nat() {
7193            return None;
7194        }
7195        let y = self.year()?;
7196        let m = self.month()?;
7197        let d = self.day()?;
7198        // Algorithm: count days from year 1 to the start of the given year,
7199        // add days in the months before the given month, add the day of month.
7200        // Account for leap years.
7201        let y_minus_1 = y - 1;
7202        let mut ordinal = y_minus_1 * 365 + y_minus_1 / 4 - y_minus_1 / 100 + y_minus_1 / 400;
7203        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7204        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
7205        ordinal += days_before[(m - 1) as usize];
7206        if is_leap && m > 2 {
7207            ordinal += 1;
7208        }
7209        ordinal += d;
7210        Some(ordinal)
7211    }
7212
7213    /// Construct a Timestamp from a proleptic Gregorian ordinal.
7214    ///
7215    /// Matches `pd.Timestamp.fromordinal(ordinal)`. Returns NaT for invalid ordinals.
7216    #[must_use]
7217    pub fn fromordinal(ordinal: i64) -> Self {
7218        if ordinal <= 0 {
7219            return Self {
7220                nanos: Self::NAT,
7221                tz: None,
7222            };
7223        }
7224        // Convert y/m/d to days since Unix epoch, then to nanos
7225        // Unix epoch is 1970-01-01, which is ordinal 719163
7226        let days_since_epoch = ordinal - 719163;
7227        match days_since_epoch.checked_mul(Timedelta::NANOS_PER_DAY) {
7228            Some(nanos) => Self { nanos, tz: None },
7229            None => Self::nat(),
7230        }
7231    }
7232
7233    /// Return the Julian Date (astronomical day number).
7234    ///
7235    /// Matches `pd.Timestamp.to_julian_date()`. Returns NaN for NaT.
7236    /// The Julian Date is the continuous count of days since the beginning
7237    /// of the Julian Period (January 1, 4713 BC in the proleptic Julian calendar).
7238    #[must_use]
7239    pub fn to_julian_date(&self) -> f64 {
7240        if self.is_nat() {
7241            return f64::NAN;
7242        }
7243        // Gregorian ordinal 1 (Jan 1, year 1) corresponds to Julian Day 1721425.5
7244        // (at noon, since JD starts at noon)
7245        // For a timestamp at midnight, we subtract 0.5
7246        let ordinal = match self.toordinal() {
7247            Some(o) => o,
7248            None => return f64::NAN,
7249        };
7250        // Fractional day from time components
7251        let h = self.hour().unwrap_or(0) as f64;
7252        let m = self.minute().unwrap_or(0) as f64;
7253        let s = self.second().unwrap_or(0) as f64;
7254        let us = self.microsecond().unwrap_or(0) as f64;
7255        let ns = self.nanosecond().unwrap_or(0) as f64;
7256        let frac_day =
7257            (h + m / 60.0 + s / 3600.0 + us / 3_600_000_000.0 + ns / 3_600_000_000_000.0) / 24.0;
7258        // Julian day at midnight of ordinal 1 is 1721424.5
7259        1721424.5 + ordinal as f64 + frac_day
7260    }
7261
7262    /// Return the quarter (1-4) of the year.
7263    ///
7264    /// Matches `pd.Timestamp.quarter`. Returns None for NaT.
7265    #[must_use]
7266    pub fn quarter(&self) -> Option<i64> {
7267        self.month().map(|m| (m - 1) / 3 + 1)
7268    }
7269
7270    /// Return the ISO week number (1-53).
7271    ///
7272    /// Matches `pd.Timestamp.week`. Returns None for NaT.
7273    #[must_use]
7274    pub fn weekofyear(&self) -> Option<i64> {
7275        if self.is_nat() {
7276            return None;
7277        }
7278        let doy = self.dayofyear()?;
7279        let dow = self.dayofweek()?;
7280        let year = self.year()?;
7281        let iso_dow = if dow == 6 { 7 } else { dow + 1 };
7282        let week = (doy - iso_dow + 10) / 7;
7283        // ISO-8601 has 53-week years, so the clamps must consult the actual
7284        // week count, not hardcode 52/1: a week<1 belongs to the LAST week of
7285        // the previous year (52 OR 53), and a week beyond this year's count
7286        // wraps to week 1 of the next year. pandas isocalendar().week agrees:
7287        // 2021-01-01 -> 53 (2020 is a 53-week year), 2026-12-31 -> 53.
7288        if week < 1 {
7289            Some(iso_weeks_in_year(year - 1))
7290        } else if week > iso_weeks_in_year(year) {
7291            Some(1)
7292        } else {
7293            Some(week)
7294        }
7295    }
7296
7297    /// Alias for weekofyear(). Matches `pd.Timestamp.week`.
7298    #[must_use]
7299    pub fn week(&self) -> Option<i64> {
7300        self.weekofyear()
7301    }
7302
7303    /// Return the timestamp value in the specified unit.
7304    ///
7305    /// Matches `pd.Timestamp.value` when unit is nanoseconds.
7306    /// Supported units: "ns", "us", "ms", "s".
7307    #[must_use]
7308    pub fn to_unit(&self, unit: &str) -> Option<i64> {
7309        if self.is_nat() {
7310            return None;
7311        }
7312        match unit {
7313            "ns" | "nanosecond" | "nanoseconds" => Some(self.nanos),
7314            "us" | "microsecond" | "microseconds" => Some(self.nanos / 1_000),
7315            "ms" | "millisecond" | "milliseconds" => Some(self.nanos / 1_000_000),
7316            "s" | "second" | "seconds" => Some(self.nanos / 1_000_000_000),
7317            _ => None,
7318        }
7319    }
7320
7321    /// Whether the year is a leap year.
7322    ///
7323    /// Matches `pd.Timestamp.is_leap_year`. Returns None for NaT.
7324    #[must_use]
7325    pub fn is_leap_year(&self) -> Option<bool> {
7326        self.year()
7327            .map(|y| (y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
7328    }
7329
7330    /// Whether the day is the first day of the month.
7331    ///
7332    /// Matches `pd.Timestamp.is_month_start`. Returns None for NaT.
7333    #[must_use]
7334    pub fn is_month_start(&self) -> Option<bool> {
7335        self.day().map(|d| d == 1)
7336    }
7337
7338    /// Whether the day is the last day of the month.
7339    ///
7340    /// Matches `pd.Timestamp.is_month_end`. Returns None for NaT.
7341    #[must_use]
7342    pub fn is_month_end(&self) -> Option<bool> {
7343        let y = self.year()?;
7344        let m = self.month()?;
7345        let d = self.day()?;
7346        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7347        let days_in_month: [i64; 12] = [
7348            31,
7349            if is_leap { 29 } else { 28 },
7350            31,
7351            30,
7352            31,
7353            30,
7354            31,
7355            31,
7356            30,
7357            31,
7358            30,
7359            31,
7360        ];
7361        Some(d == days_in_month[(m - 1) as usize])
7362    }
7363
7364    /// Whether the day is the first day of a quarter.
7365    ///
7366    /// Matches `pd.Timestamp.is_quarter_start`. Returns None for NaT.
7367    #[must_use]
7368    pub fn is_quarter_start(&self) -> Option<bool> {
7369        let m = self.month()?;
7370        let d = self.day()?;
7371        Some(d == 1 && (m == 1 || m == 4 || m == 7 || m == 10))
7372    }
7373
7374    /// Whether the day is the last day of a quarter.
7375    ///
7376    /// Matches `pd.Timestamp.is_quarter_end`. Returns None for NaT.
7377    #[must_use]
7378    pub fn is_quarter_end(&self) -> Option<bool> {
7379        let m = self.month()?;
7380        let d = self.day()?;
7381        Some(
7382            (m == 3 && d == 31)
7383                || (m == 6 && d == 30)
7384                || (m == 9 && d == 30)
7385                || (m == 12 && d == 31),
7386        )
7387    }
7388
7389    /// Whether the day is the first day of the year (Jan 1).
7390    ///
7391    /// Matches `pd.Timestamp.is_year_start`. Returns None for NaT.
7392    #[must_use]
7393    pub fn is_year_start(&self) -> Option<bool> {
7394        let m = self.month()?;
7395        let d = self.day()?;
7396        Some(m == 1 && d == 1)
7397    }
7398
7399    /// Whether the day is the last day of the year (Dec 31).
7400    ///
7401    /// Matches `pd.Timestamp.is_year_end`. Returns None for NaT.
7402    #[must_use]
7403    pub fn is_year_end(&self) -> Option<bool> {
7404        let m = self.month()?;
7405        let d = self.day()?;
7406        Some(m == 12 && d == 31)
7407    }
7408
7409    /// Return the number of days in the month of this timestamp.
7410    ///
7411    /// Matches `pd.Timestamp.days_in_month`. Returns None for NaT.
7412    #[must_use]
7413    pub fn days_in_month(&self) -> Option<i64> {
7414        let y = self.year()?;
7415        let m = self.month()?;
7416        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7417        let days: [i64; 12] = [
7418            31,
7419            if is_leap { 29 } else { 28 },
7420            31,
7421            30,
7422            31,
7423            30,
7424            31,
7425            31,
7426            30,
7427            31,
7428            30,
7429            31,
7430        ];
7431        Some(days[(m - 1) as usize])
7432    }
7433
7434    /// Alias for days_in_month(). Matches `pd.Timestamp.daysinmonth`.
7435    #[must_use]
7436    pub fn daysinmonth(&self) -> Option<i64> {
7437        self.days_in_month()
7438    }
7439
7440    /// Normalize to midnight/day boundary, matching `pd.Timestamp.normalize()`.
7441    #[must_use]
7442    pub fn normalize(&self) -> Self {
7443        self.floor_to(Timedelta::NANOS_PER_DAY)
7444    }
7445
7446    /// Replace timestamp components with new values.
7447    ///
7448    /// Matches pd.Timestamp.replace(). None values keep the existing component.
7449    #[must_use]
7450    #[allow(clippy::too_many_arguments)]
7451    pub fn replace(
7452        &self,
7453        year: Option<i64>,
7454        month: Option<i64>,
7455        day: Option<i64>,
7456        hour: Option<i64>,
7457        minute: Option<i64>,
7458        second: Option<i64>,
7459        microsecond: Option<i64>,
7460        nanosecond: Option<i64>,
7461    ) -> Self {
7462        if self.is_nat() {
7463            return self.clone();
7464        }
7465        let cur_year = self.year().unwrap_or(1970);
7466        let cur_month = self.month().unwrap_or(1);
7467        let cur_day = self.day().unwrap_or(1);
7468        let cur_hour = self.hour().unwrap_or(0);
7469        let cur_minute = self.minute().unwrap_or(0);
7470        let cur_second = self.second().unwrap_or(0);
7471        let cur_micro = self.microsecond().unwrap_or(0);
7472        let cur_nano = self.nanosecond().unwrap_or(0);
7473
7474        let y = year.unwrap_or(cur_year);
7475        let mo = month.unwrap_or(cur_month);
7476        let d = day.unwrap_or(cur_day);
7477        let h = hour.unwrap_or(cur_hour);
7478        let mi = minute.unwrap_or(cur_minute);
7479        let s = second.unwrap_or(cur_second);
7480        let us = microsecond.unwrap_or(cur_micro);
7481        let ns = nanosecond.unwrap_or(cur_nano);
7482
7483        if !(1..=12).contains(&mo)
7484            || !(1..=days_in_month(y, mo as u32).unwrap_or(0) as i64).contains(&d)
7485            || !(0..=23).contains(&h)
7486            || !(0..=59).contains(&mi)
7487            || !(0..=59).contains(&s)
7488            || !(0..=999_999).contains(&us)
7489            || !(0..=999).contains(&ns)
7490        {
7491            return Self::nat();
7492        }
7493
7494        // Checked nanosecond arithmetic (br-frankenpandas-dzz6x). The component
7495        // validation above rejects an out-of-range month/day/hour/... but says
7496        // nothing about the YEAR, and i64 nanoseconds run out at
7497        // `i64::MAX / NANOS_PER_DAY` = 106_751 days from the epoch — about year
7498        // 2262, the same bound pandas documents for ns-resolution Timestamps.
7499        // Unchecked, `replace(year=3000)` wrapped in release mode and returned a
7500        // silently wrong, plausible-looking in-range instant. Overflow now folds
7501        // to NaT, matching both the validation arm above and the sibling
7502        // constructors `fromordinal` / `floor_to`, which already fail this way.
7503        // In-range results are unchanged: the checked ops return exactly the
7504        // value the plain operators produced whenever no overflow occurred.
7505        let days_from_epoch = Self::days_from_ymd(y, mo, d);
7506        let secs = h * 3600 + mi * 60 + s;
7507        let Some(total_nanos) = days_from_epoch
7508            .checked_mul(Timedelta::NANOS_PER_DAY)
7509            .and_then(|nanos| {
7510                secs.checked_mul(Timedelta::NANOS_PER_SEC)
7511                    .and_then(|s_nanos| nanos.checked_add(s_nanos))
7512            })
7513            .and_then(|nanos| {
7514                us.checked_mul(Timedelta::NANOS_PER_MICRO)
7515                    .and_then(|us_nanos| nanos.checked_add(us_nanos))
7516            })
7517            .and_then(|nanos| nanos.checked_add(ns))
7518        else {
7519            return Self::nat();
7520        };
7521
7522        Self {
7523            nanos: total_nanos,
7524            tz: self.tz.clone(),
7525        }
7526    }
7527
7528    fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
7529        let y = if month <= 2 { year - 1 } else { year };
7530        let era = if y >= 0 { y } else { y - 399 } / 400;
7531        let yoe = y - era * 400;
7532        let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
7533        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
7534        era * 146097 + doe - 719468
7535    }
7536
7537    /// Return an ISO 8601 string representation of the timestamp.
7538    ///
7539    /// Matches `pd.Timestamp.isoformat()`. NaT returns "NaT".
7540    #[must_use]
7541    pub fn isoformat(&self) -> String {
7542        use std::fmt::Write as _;
7543
7544        if self.is_nat() {
7545            return "NaT".to_string();
7546        }
7547        let display_nanos = self
7548            .tz
7549            .as_deref()
7550            .and_then(Self::fixed_utc_offset_seconds)
7551            .and_then(|offset| self.nanos.checked_add(offset * Timedelta::NANOS_PER_SEC))
7552            .unwrap_or(self.nanos);
7553        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
7554        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
7555        let days_since_epoch = display_nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7556        let nanos_of_day = display_nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7557        let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7558        let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7559
7560        let days = days_since_epoch + 719_468;
7561        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7562        let doe = days - era * 146_097;
7563        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7564        let y = yoe + era * 400;
7565        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7566        let mp = (5 * doy + 2) / 153;
7567        let d = doy - (153 * mp + 2) / 5 + 1;
7568        let m = if mp < 10 { mp + 3 } else { mp - 9 };
7569        let year = if m <= 2 { y + 1 } else { y };
7570
7571        let hour = secs_of_day / 3600;
7572        let minute = (secs_of_day % 3600) / 60;
7573        let second = secs_of_day % 60;
7574
7575        // Build the timestamp and its optional timezone suffix in the returned
7576        // allocation. The former timezone-aware path first allocated `base`,
7577        // then allocated again to copy `base` into the suffixed result.
7578        let suffix_capacity = self
7579            .tz
7580            .as_ref()
7581            .map_or(0, |tz| if tz == "UTC" { 6 } else { tz.len() + 2 });
7582        let mut result = String::with_capacity(29 + suffix_capacity);
7583        if sub_nanos == 0 {
7584            let _ = write!(
7585                result,
7586                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}"
7587            );
7588        } else if sub_nanos.is_multiple_of(1_000) {
7589            let _ = write!(
7590                result,
7591                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{:06}",
7592                sub_nanos / 1_000
7593            );
7594        } else {
7595            let _ = write!(
7596                result,
7597                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{sub_nanos:09}"
7598            );
7599        }
7600        match &self.tz {
7601            Some(tz) if tz == "UTC" => result.push_str("+00:00"),
7602            Some(tz) if Self::fixed_utc_offset_seconds(tz).is_some() => {
7603                result.push_str(tz.strip_prefix("UTC").unwrap_or(tz));
7604            }
7605            Some(tz) => {
7606                result.push('[');
7607                result.push_str(tz);
7608                result.push(']');
7609            }
7610            None => {}
7611        }
7612        result
7613    }
7614
7615    /// Alias for isoformat.
7616    #[must_use]
7617    pub fn to_iso8601(&self) -> String {
7618        self.isoformat()
7619    }
7620
7621    /// The coarsest [`DatetimeStringResolution`] that renders `nanos` losslessly.
7622    ///
7623    /// Fold this over a column with `max` to get the column's width — see
7624    /// [`DatetimeStringResolution`] for why the width is a property of the
7625    /// COLUMN and not of the value. `NaT` reports [`DatetimeStringResolution`]
7626    /// `::Date`, the identity for that fold, because pandas excludes it from the
7627    /// scan entirely: a column of one midnight plus one NaT still renders
7628    /// `['2024-03-15', 'NaT']`.
7629    #[must_use]
7630    pub const fn string_resolution(nanos: i64) -> DatetimeStringResolution {
7631        if nanos == Self::NAT {
7632            return DatetimeStringResolution::Date;
7633        }
7634        if nanos.rem_euclid(Timedelta::NANOS_PER_DAY) == 0 {
7635            DatetimeStringResolution::Date
7636        } else if nanos.rem_euclid(Timedelta::NANOS_PER_SEC) == 0 {
7637            DatetimeStringResolution::Second
7638        } else if nanos.rem_euclid(Timedelta::NANOS_PER_MILLI) == 0 {
7639            DatetimeStringResolution::Milli
7640        } else if nanos.rem_euclid(Timedelta::NANOS_PER_MICRO) == 0 {
7641            DatetimeStringResolution::Micro
7642        } else {
7643            DatetimeStringResolution::Nano
7644        }
7645    }
7646
7647    /// Render `nanos` the way `astype(str)` does, at a resolution chosen for the
7648    /// whole column by [`Self::string_resolution`].
7649    ///
7650    /// ⚠️ NOT [`Self::isoformat`]. That one is `pd.Timestamp.isoformat()` — a `T`
7651    /// separator, and a width chosen per VALUE. This is the array formatter:
7652    /// a SPACE separator, and a width imposed on every element alike. MEASURED,
7653    /// live pandas 2.2.3, one column per rung:
7654    ///
7655    /// ```text
7656    /// all midnight       -> '2024-03-15'
7657    /// all whole seconds  -> '2024-03-15 10:30:45'
7658    /// all whole millis   -> '2024-03-15 10:30:45.123'
7659    /// all whole micros   -> '2024-03-15 10:30:45.123456'
7660    /// anything finer     -> '2024-03-15 10:30:45.123456789'
7661    /// NaT                -> 'NaT'          (a STRING, not a missing value)
7662    /// ```
7663    ///
7664    /// There is NO minute rung: a column of whole minutes still renders its
7665    /// seconds (`'2024-01-01 00:05:00'`).
7666    #[must_use]
7667    pub fn format_at_resolution(nanos: i64, resolution: DatetimeStringResolution) -> String {
7668        use std::fmt::Write as _;
7669
7670        if nanos == Self::NAT {
7671            return "NaT".to_string();
7672        }
7673        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos,
7674        // the same correction isoformat makes (br-frankenpandas-wkjtw): a
7675        // pre-epoch value must render 1969-12-31 23:59:59.999999999, not a
7676        // negative fraction.
7677        let days_since_epoch = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7678        let nanos_of_day = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7679        let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7680        let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC);
7681        // The crate's existing Hinnant civil-from-days, NOT a second copy: two
7682        // implementations of a calendar algorithm are two chances to drift.
7683        let (year, month, day) = civil_from_days(days_since_epoch);
7684
7685        // pandas' datetime64[ns] range is 1677..=2262, so the year is always
7686        // four digits and `{:04}` never truncates.
7687        let mut result = String::with_capacity(30);
7688        // `fmt::Write for String` is infallible.
7689        let _ = write!(result, "{year:04}-{month:02}-{day:02}");
7690        if matches!(resolution, DatetimeStringResolution::Date) {
7691            return result;
7692        }
7693        let _ = write!(
7694            result,
7695            " {:02}:{:02}:{:02}",
7696            secs_of_day / 3600,
7697            (secs_of_day % 3600) / 60,
7698            secs_of_day % 60
7699        );
7700        let (fraction, width) = match resolution {
7701            DatetimeStringResolution::Date | DatetimeStringResolution::Second => return result,
7702            DatetimeStringResolution::Milli => (sub_nanos / Timedelta::NANOS_PER_MILLI, 3_usize),
7703            DatetimeStringResolution::Micro => (sub_nanos / Timedelta::NANOS_PER_MICRO, 6_usize),
7704            DatetimeStringResolution::Nano => (sub_nanos, 9_usize),
7705        };
7706        let _ = write!(result, ".{fraction:0width$}", width = width);
7707        result
7708    }
7709
7710    /// Parse a datetime string into a Timestamp.
7711    ///
7712    /// Supports ISO 8601 formats:
7713    /// - "2024-01-15" (date only, time defaults to 00:00:00)
7714    /// - "2024-01-15T10:30:00" (datetime)
7715    /// - "2024-01-15 10:30:00" (space separator)
7716    /// - "2024-01-15T10:30:00.123456" (with fractional seconds)
7717    /// - "2024-01-15T10:30:00Z" (UTC timezone)
7718    /// - "2024-01-15T10:30:00+05:30" (offset timezone)
7719    /// - "NaT" (Not a Timestamp)
7720    ///
7721    /// Matches `pd.Timestamp()` constructor behavior.
7722    pub fn parse(s: &str) -> Result<Self, TypeError> {
7723        let s = s.trim();
7724
7725        if s.eq_ignore_ascii_case("nat") {
7726            return Ok(Self::nat());
7727        }
7728
7729        let Some((datetime_part, tz)) = Self::split_timezone(s) else {
7730            return Err(TypeError::ValueNotParseable {
7731                value: s.to_string(),
7732                target: "Timestamp".to_string(),
7733            });
7734        };
7735
7736        let (date_part, time_part) = if datetime_part.contains('T') {
7737            datetime_part
7738                .split_once('T')
7739                .ok_or_else(|| TypeError::ValueNotParseable {
7740                    value: s.to_string(),
7741                    target: "Timestamp".to_string(),
7742                })?
7743        } else if datetime_part.contains(' ')
7744            && datetime_part.chars().filter(|&c| c == ' ').count() == 1
7745        {
7746            datetime_part
7747                .split_once(' ')
7748                .ok_or_else(|| TypeError::ValueNotParseable {
7749                    value: s.to_string(),
7750                    target: "Timestamp".to_string(),
7751                })?
7752        } else {
7753            (datetime_part, "00:00:00")
7754        };
7755
7756        let (year, month, day) =
7757            Self::parse_date(date_part).ok_or_else(|| TypeError::ValueNotParseable {
7758                value: s.to_string(),
7759                target: "Timestamp".to_string(),
7760            })?;
7761
7762        let (hour, minute, second, nanos) =
7763            Self::parse_time(time_part).ok_or_else(|| TypeError::ValueNotParseable {
7764                value: s.to_string(),
7765                target: "Timestamp".to_string(),
7766            })?;
7767
7768        // br-frankenpandas-94o1u: an unrepresentable instant is a parse
7769        // failure, not a wrapped value.
7770        let wall_nanos = Self::ymd_hms_to_nanos(year, month, day, hour, minute, second, nanos)
7771            .ok_or_else(|| TypeError::ValueNotParseable {
7772                value: s.to_string(),
7773                target: "Timestamp".to_string(),
7774            })?;
7775        // The digits are the wall clock at the offset; the instant is that
7776        // wall time less the offset ('10:00+09:00' is 01:00 UTC - it was
7777        // read as 10:00 UTC, so it showed as 19:00+09:00).
7778        let offset = tz
7779            .as_deref()
7780            .and_then(Self::fixed_utc_offset_seconds)
7781            .unwrap_or(0);
7782        let total_nanos = offset
7783            .checked_mul(1_000_000_000)
7784            .and_then(|offset| wall_nanos.checked_sub(offset))
7785            .ok_or_else(|| TypeError::ValueNotParseable {
7786                value: s.to_string(),
7787                target: "Timestamp".to_string(),
7788            })?;
7789
7790        Ok(if let Some(tz_name) = tz {
7791            Self::from_nanos_tz(total_nanos, tz_name)
7792        } else {
7793            Self::from_nanos(total_nanos)
7794        })
7795    }
7796
7797    fn split_timezone(s: &str) -> Option<(&str, Option<String>)> {
7798        if let Some(stripped) = s.strip_suffix('Z') {
7799            Some((stripped, Some("UTC".to_string())))
7800        } else if let Some(idx) = s.rfind('+') {
7801            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7802                Some((&s[..idx], Some(s[idx..].to_string())))
7803            } else if idx > 10 {
7804                None
7805            } else {
7806                Some((s, None))
7807            }
7808        } else if let Some(idx) = s.rfind('-') {
7809            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7810                Some((&s[..idx], Some(s[idx..].to_string())))
7811            } else if idx > 10 {
7812                None
7813            } else {
7814                Some((s, None))
7815            }
7816        } else {
7817            Some((s, None))
7818        }
7819    }
7820
7821    fn fixed_utc_offset_seconds(tz: &str) -> Option<i64> {
7822        if tz == "UTC" {
7823            return Some(0);
7824        }
7825        let offset = tz.strip_prefix("UTC").unwrap_or(tz);
7826        if !Self::is_timezone_offset(offset) {
7827            return None;
7828        }
7829        let sign = if offset.starts_with('+') { 1 } else { -1 };
7830        let hours = offset[1..3].parse::<i64>().ok()?;
7831        let minutes = offset[4..6].parse::<i64>().ok()?;
7832        Some(sign * (hours * 3_600 + minutes * 60))
7833    }
7834
7835    fn is_timezone_offset(s: &str) -> bool {
7836        let bytes = s.as_bytes();
7837        if bytes.len() != 6 || !matches!(bytes[0], b'+' | b'-') || bytes[3] != b':' {
7838            return false;
7839        }
7840        if !bytes[1..3].iter().all(u8::is_ascii_digit)
7841            || !bytes[4..6].iter().all(u8::is_ascii_digit)
7842        {
7843            return false;
7844        }
7845        let hour = u32::from(bytes[1] - b'0') * 10 + u32::from(bytes[2] - b'0');
7846        let minute = u32::from(bytes[4] - b'0') * 10 + u32::from(bytes[5] - b'0');
7847        hour <= 23 && minute <= 59
7848    }
7849
7850    fn parse_date(s: &str) -> Option<(i64, u32, u32)> {
7851        let parts: Vec<&str> = s.split('-').collect();
7852        if parts.len() != 3 {
7853            return None;
7854        }
7855        let year: i64 = parts[0].parse().ok()?;
7856        let month: u32 = parts[1].parse().ok()?;
7857        let day: u32 = parts[2].parse().ok()?;
7858        if !(1..=days_in_month(year, month)?).contains(&day) {
7859            return None;
7860        }
7861        Some((year, month, day))
7862    }
7863
7864    fn parse_time(s: &str) -> Option<(u32, u32, u32, u64)> {
7865        let (time_str, frac_str) = match s.split_once('.') {
7866            Some((time, frac)) => (time, Some(frac)),
7867            None => (s, None),
7868        };
7869        let parts: Vec<&str> = time_str.split(':').collect();
7870        if parts.is_empty() || parts.len() > 3 {
7871            return None;
7872        }
7873        let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
7874        let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
7875        let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
7876
7877        if hour > 23 || minute > 59 || second > 59 {
7878            return None;
7879        }
7880
7881        let nanos = match frac_str {
7882            None => 0,
7883            Some(frac) => {
7884                if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
7885                    return None;
7886                }
7887                let digits = frac.len().min(9);
7888                let mut nanos = 0_u64;
7889                for byte in frac.bytes().take(digits) {
7890                    nanos = nanos * 10 + u64::from(byte - b'0');
7891                }
7892                for _ in digits..9 {
7893                    nanos *= 10;
7894                }
7895                nanos
7896            }
7897        };
7898
7899        Some((hour, minute, second, nanos))
7900    }
7901
7902    /// Compose a civil date-time into i64 nanoseconds since the epoch, or
7903    /// `None` when the instant is not representable.
7904    ///
7905    /// Checked composition (br-frankenpandas-94o1u). `parse_date` validates the
7906    /// month and the day-of-month but parses the YEAR as an unbounded `i64`,
7907    /// and i64 nanoseconds top out around year 2262 — the bound pandas
7908    /// documents for ns-resolution Timestamps. Unchecked, the two multiplies
7909    /// below wrapped in release, so `Timestamp::parse("300000-01-01")` returned
7910    /// `Ok` holding a silently wrong, plausible-looking in-range instant.
7911    /// pandas raises `OutOfBoundsDatetime`.
7912    ///
7913    /// This is the ingestion path — CSV/JSON date columns and user strings —
7914    /// so failing OPEN with corrupt data is the failure mode the security
7915    /// doctrine specifically forbids. `None` here becomes the same
7916    /// `ValueNotParseable` the caller already returns for any other
7917    /// unparseable input, so no new error variant and no API change.
7918    ///
7919    /// The day-count arithmetic above the multiplies cannot overflow for any
7920    /// `year` that survives `str::parse::<i64>` minus the era arithmetic's own
7921    /// bounds, but it is routed through checked ops anyway so an extreme year
7922    /// is rejected rather than wrapped before it ever reaches the seconds step.
7923    fn ymd_hms_to_nanos(
7924        year: i64,
7925        month: u32,
7926        day: u32,
7927        hour: u32,
7928        minute: u32,
7929        second: u32,
7930        sub_nanos: u64,
7931    ) -> Option<i64> {
7932        let m = month as i64;
7933        let d = day as i64;
7934
7935        let y = if m <= 2 { year.checked_sub(1)? } else { year };
7936        let era = if y >= 0 { y } else { y.checked_sub(399)? } / 400;
7937        let yoe = y.checked_sub(era.checked_mul(400)?)?;
7938        let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
7939        let doe = yoe
7940            .checked_mul(365)?
7941            .checked_add(yoe / 4 - yoe / 100)?
7942            .checked_add(doy)?;
7943        let days_since_epoch = era
7944            .checked_mul(146_097)?
7945            .checked_add(doe)?
7946            .checked_sub(719_468)?;
7947
7948        let total_seconds = days_since_epoch
7949            .checked_mul(86400)?
7950            .checked_add(i64::from(hour) * 3600)?
7951            .checked_add(i64::from(minute) * 60)?
7952            .checked_add(i64::from(second))?;
7953        total_seconds
7954            .checked_mul(Timedelta::NANOS_PER_SEC)?
7955            .checked_add(sub_nanos as i64)
7956    }
7957
7958    /// Format timestamp using strftime directives.
7959    ///
7960    /// Matches `pd.Timestamp.strftime(format)`: Python's (glibc's) directive
7961    /// set, see [`strftime_python`] (it knew only %Y %m %d %H %M %S %f and
7962    /// printed `%%Y` as `%2024`). A tz-aware Timestamp formats its wall clock,
7963    /// `%z` / `%Z` its zone's offset and abbreviation then. NaT returns "NaT".
7964    #[must_use]
7965    pub fn strftime(&self, format: &str) -> String {
7966        if self.is_nat() {
7967            return "NaT".to_string();
7968        }
7969        strftime_in_zone(self.nanos, format, self.tz.as_deref())
7970    }
7971
7972    /// Return the day of the week as a string (e.g., "Monday").
7973    ///
7974    /// Matches `pd.Timestamp.day_name()`. NaT returns "NaT".
7975    #[must_use]
7976    pub fn day_name(&self) -> String {
7977        const NAMES: [&str; 7] = [
7978            "Thursday",
7979            "Friday",
7980            "Saturday",
7981            "Sunday",
7982            "Monday",
7983            "Tuesday",
7984            "Wednesday",
7985        ];
7986        if self.is_nat() {
7987            return "NaT".to_string();
7988        }
7989        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
7990        // Truncating `/` rounds a negative, non-midnight instant TOWARD zero, so
7991        // it lands on the following day and names the wrong weekday: pandas 2.2.3
7992        // gives 1969-07-20T20:17:40 -> "Sunday", truncation gave "Monday". The
7993        // wkjtw fix was applied to `dayofweek` but never here.
7994        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7995        let dow = ((days_since_epoch % 7) + 7) % 7;
7996        NAMES[dow as usize].to_string()
7997    }
7998
7999    /// Return the month name as a string (e.g., "January").
8000    ///
8001    /// Matches `pd.Timestamp.month_name()`. NaT returns "NaT".
8002    #[must_use]
8003    pub fn month_name(&self) -> String {
8004        const NAMES: [&str; 12] = [
8005            "January",
8006            "February",
8007            "March",
8008            "April",
8009            "May",
8010            "June",
8011            "July",
8012            "August",
8013            "September",
8014            "October",
8015            "November",
8016            "December",
8017        ];
8018        if self.is_nat() {
8019            return "NaT".to_string();
8020        }
8021        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
8022        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
8023        // for the post-1970 positive case.
8024        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
8025        let days = days_since_epoch + 719_468;
8026        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
8027        let doe = days - era * 146_097;
8028        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
8029        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
8030        let mp = (5 * doy + 2) / 153;
8031        let m = if mp < 10 { mp + 3 } else { mp - 9 };
8032        NAMES[(m - 1) as usize].to_string()
8033    }
8034
8035    /// Localize a naive timestamp to a timezone.
8036    ///
8037    /// Matches `pd.Timestamp.tz_localize(tz)`. If `tz` is None, removes the
8038    /// timezone (makes timestamp naive). NaT propagates.
8039    #[must_use]
8040    pub fn tz_localize(&self, tz: Option<&str>) -> Self {
8041        if self.is_nat() {
8042            return Self::nat();
8043        }
8044        Self {
8045            nanos: self.nanos,
8046            tz: tz.map(String::from),
8047        }
8048    }
8049
8050    /// Convert timezone-aware timestamp to another timezone.
8051    ///
8052    /// Matches `pd.Timestamp.tz_convert(tz)`. If timestamp is naive (no tz),
8053    /// the timezone is simply attached without conversion. NaT propagates.
8054    /// Note: actual UTC offset conversion requires chrono-tz (Phase 3).
8055    #[must_use]
8056    pub fn tz_convert(&self, tz: &str) -> Self {
8057        if self.is_nat() {
8058            return Self::nat();
8059        }
8060        Self {
8061            nanos: self.nanos,
8062            tz: Some(tz.to_string()),
8063        }
8064    }
8065
8066    /// Create a Timestamp from a Unix timestamp (seconds since epoch).
8067    ///
8068    /// Matches `pd.Timestamp.fromtimestamp(ts)`. The optional `tz` parameter
8069    /// specifies the timezone to localize to.
8070    #[must_use]
8071    pub fn fromtimestamp(ts: f64, tz: Option<&str>) -> Self {
8072        if ts.is_nan() || ts.is_infinite() {
8073            return Self::nat();
8074        }
8075        let nanos_f64 = ts * 1_000_000_000.0;
8076        // Check for overflow before casting - i64 range is roughly ±9.2e18
8077        const MAX_NANOS: f64 = i64::MAX as f64;
8078        const MIN_NANOS: f64 = i64::MIN as f64;
8079        if !(MIN_NANOS..=MAX_NANOS).contains(&nanos_f64) {
8080            return Self::nat();
8081        }
8082        Self {
8083            nanos: nanos_f64 as i64,
8084            tz: tz.map(String::from),
8085        }
8086    }
8087
8088    /// Create a Timestamp from milliseconds since epoch.
8089    ///
8090    /// Convenience constructor complementing fromtimestamp. An `ms` outside
8091    /// the representable nanosecond range → NaT, matching `fromtimestamp`
8092    /// directly above (br-frankenpandas-kyd16); the previous
8093    /// `saturating_mul` handed back a finite ~year-2262 instant instead.
8094    #[must_use]
8095    pub fn from_millis(ms: i64, tz: Option<&str>) -> Self {
8096        let Some(nanos) = ms.checked_mul(1_000_000) else {
8097            return Self::nat();
8098        };
8099        Self {
8100            nanos,
8101            tz: tz.map(String::from),
8102        }
8103    }
8104
8105    /// Create a Timestamp from microseconds since epoch.
8106    ///
8107    /// Convenience constructor complementing fromtimestamp.
8108    #[must_use]
8109    pub fn from_micros(us: i64, tz: Option<&str>) -> Self {
8110        let Some(nanos) = us.checked_mul(1_000) else {
8111            return Self::nat();
8112        };
8113        Self {
8114            nanos,
8115            tz: tz.map(String::from),
8116        }
8117    }
8118
8119    /// Return the timezone string, or None if naive.
8120    #[must_use]
8121    pub fn tzinfo(&self) -> Option<&str> {
8122        self.tz.as_deref()
8123    }
8124
8125    /// Return the timezone name, or None if naive.
8126    ///
8127    /// Alias for tzinfo() matching pandas Timestamp.tzname().
8128    #[must_use]
8129    pub fn tzname(&self) -> Option<&str> {
8130        self.tzinfo()
8131    }
8132}
8133
8134impl std::fmt::Display for Timestamp {
8135    /// Phase 2 debug-style format; Phase 3 replaces with pandas ISO-8601
8136    /// notation once chrono interpretation lands.
8137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8138        if self.is_nat() {
8139            return f.write_str("NaT");
8140        }
8141        match &self.tz {
8142            Some(tz) => write!(f, "Timestamp[{}, {}]", self.nanos, tz),
8143            None => write!(f, "Timestamp[{}, UTC]", self.nanos),
8144        }
8145    }
8146}
8147
8148impl PartialOrd for Timestamp {
8149    /// Orders by nanos axis; NaT is incomparable (`None`). Tz difference
8150    /// does not affect ordering — two Timestamps at the same absolute
8151    /// nanos compare equal regardless of tz label (Phase 3 will revisit
8152    /// whether tz affects ordering semantics).
8153    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
8154        if self.is_nat() || other.is_nat() {
8155            return None;
8156        }
8157        Some(self.nanos.cmp(&other.nanos))
8158    }
8159}
8160
8161// ── Missingness utilities ──────────────────────────────────────────────
8162
8163pub fn isna(values: &[Scalar]) -> Vec<bool> {
8164    values.iter().map(Scalar::is_missing).collect()
8165}
8166
8167pub fn isnull(values: &[Scalar]) -> Vec<bool> {
8168    isna(values)
8169}
8170
8171pub fn notna(values: &[Scalar]) -> Vec<bool> {
8172    values.iter().map(|v| !v.is_missing()).collect()
8173}
8174
8175pub fn notnull(values: &[Scalar]) -> Vec<bool> {
8176    notna(values)
8177}
8178
8179pub fn count_na(values: &[Scalar]) -> usize {
8180    values.iter().filter(|v| v.is_missing()).count()
8181}
8182
8183pub fn fill_na(values: &[Scalar], fill: &Scalar) -> Vec<Scalar> {
8184    values
8185        .iter()
8186        .map(|v| {
8187            if v.is_missing() {
8188                fill.clone()
8189            } else {
8190                v.clone()
8191            }
8192        })
8193        .collect()
8194}
8195
8196pub fn dropna(values: &[Scalar]) -> Vec<Scalar> {
8197    values.iter().filter(|v| !v.is_missing()).cloned().collect()
8198}
8199
8200// ── Nanops: null-skipping numeric reductions ───────────────────────────
8201
8202fn collect_finite(values: &[Scalar]) -> Vec<f64> {
8203    values
8204        .iter()
8205        .filter(|v| !v.is_missing())
8206        .filter_map(|v| v.to_f64().ok())
8207        .collect()
8208}
8209
8210/// Per br-frankenpandas-620mj: if a column is uniformly Timedelta64
8211/// (with optional NAT/Null missing), sum/mean preserve Timedelta dtype
8212/// matching pandas — instead of silently coercing to Float64(0.0) via
8213/// the collect_finite path (which drops Timedelta64 because to_f64
8214/// errors). A NaT-only input remains a Timedelta family so sum returns
8215/// zero Timedelta and mean returns NaT. Returns Some(sum_in_ns,
8216/// observed_count) when applicable.
8217fn collect_timedelta_ns(values: &[Scalar]) -> Option<(i128, usize)> {
8218    let mut sum: i128 = 0;
8219    let mut count: usize = 0;
8220    let mut saw_timedelta = false;
8221    for v in values {
8222        match v {
8223            Scalar::Timedelta64(ns) => {
8224                saw_timedelta = true;
8225                if v.is_missing() {
8226                    continue;
8227                }
8228                sum += i128::from(*ns);
8229                count += 1;
8230            }
8231            _ if v.is_missing() => continue,
8232            // Any non-Timedelta non-missing value bails out to the
8233            // existing Float64 path, preserving cross-type behavior.
8234            _ => return None,
8235        }
8236    }
8237    if saw_timedelta {
8238        Some((sum, count))
8239    } else {
8240        None
8241    }
8242}
8243
8244/// Narrow an exact `i128` nanosecond quantity back to a `Timedelta64` scalar,
8245/// surfacing NaT when the value is not representable.
8246///
8247/// Per br-frankenpandas-opz27, this replaces the `clamp(i64::MIN, i64::MAX)`
8248/// the reduction paths used to do, which failed open twice over:
8249///
8250/// - a positive overflow became `i64::MAX`, a fabricated finite ~106751-day
8251///   Timedelta presented as real data (the br-frankenpandas-lgyy8 class);
8252/// - `Timedelta::NAT` *is* `i64::MIN`, so the clamp's lower bound landed
8253///   exactly on the missing sentinel — a negative overflow silently became
8254///   NaT by accident, and the bound was off by one against the true minimum.
8255///
8256/// The representable range is therefore `[i64::MIN + 1, i64::MAX]`, and both
8257/// overflow directions now yield NaT deliberately. Live pandas 2.2.3 raises
8258/// (`OverflowError` / `ValueError: overflow in timedelta operation`) where
8259/// these reductions overflow; FP surfaces NaT instead, matching the
8260/// infallible-helper convention established by `Timedelta::div_scalar` and
8261/// br-frankenpandas-lgyy8. Every exactly-representable result is unaffected.
8262fn timedelta_ns_to_scalar(ns: i128) -> Scalar {
8263    if ns > i128::from(i64::MAX) || ns <= i128::from(i64::MIN) {
8264        return Scalar::Timedelta64(Timedelta::NAT);
8265    }
8266    Scalar::Timedelta64(ns as i64)
8267}
8268
8269pub fn nansum(values: &[Scalar]) -> Scalar {
8270    if let Some((sum, _)) = collect_timedelta_ns(values) {
8271        return timedelta_ns_to_scalar(sum);
8272    }
8273    // Fused single-pass fold: filter missing / non-f64-coercible and accumulate
8274    // in one scan, avoiding the intermediate `collect_finite` Vec<f64> and its
8275    // second pass. Bit-identical to `collect_finite(..).iter().sum()`: same
8276    // finite values in the same order, same left-fold f64 `+` (empty -> 0.0).
8277    let mut sum = 0.0_f64;
8278    for v in values {
8279        if v.is_missing() {
8280            continue;
8281        }
8282        if let Ok(x) = v.to_f64() {
8283            sum += x;
8284        }
8285    }
8286    Scalar::Float64(sum)
8287}
8288
8289/// Sum of a STRING group: pandas concatenates, skipping missing entries.
8290///
8291/// br-frankenpandas-a7faz. `nansum` cannot serve this: it coerces through
8292/// `to_f64`, which fails for every `Utf8`, so a string column sums to
8293/// `Float64(0.0)` — a wrong value rather than a refusal. This is a separate
8294/// reducer rather than a branch inside `nansum` on purpose: the SUM SURFACES
8295/// DISAGREE in pandas and a shared change would silently move the others.
8296///
8297/// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18):
8298/// ```text
8299///   Series(['a','b','c']).sum()              -> 'abc'
8300///   Series(['a',None,'c']).sum()             -> TypeError: can only concatenate str
8301///   DataFrame({'v':['a',None]}).sum()        -> TypeError (same)
8302///   df.groupby(k)['v'].sum()  with a None    -> 'a'      SKIPS, does not raise
8303///   s.resample('ME').sum()    with a None    -> 'ps'     SKIPS, does not raise
8304/// ```
8305/// So the REDUCTION surfaces raise on a missing entry while the GROUPED surfaces
8306/// skip it. This function implements the grouped rule and must not be wired into
8307/// `Series::sum`/`DataFrame::sum` without implementing their raise.
8308///
8309/// ⚠️ AND AN EMPTY OR ALL-MISSING GROUP IS INTEGER `0`, NOT `""`. Measured:
8310/// ```text
8311///   Series(['p','q'], index=[Jan-01, Mar-01]).resample('ME').sum()
8312///     -> ['p', 0, 'q']        <- the empty February bucket is int 0
8313///   Series([None,None,'r','u'], ...).resample('ME').sum()
8314///     -> [0, 'ru']            <- an all-missing bucket is int 0 too
8315///   types: ['int', 'str']     <- the output column is genuinely MIXED
8316/// ```
8317/// That is pandas' `sum()` identity element leaking through unchanged, and it is
8318/// why this returns `Scalar::Int64(0)` rather than an empty string: matching the
8319/// incumbent here means reproducing a mixed-dtype column.
8320///
8321/// Concatenation is POSITIONAL, not sorted — `Series(['z','a','m']).sum()` is
8322/// `'zam'`. Callers that bucket by time therefore hand the values over in index
8323/// order, which is what produced `'psq'` for a Jan bucket holding Jan-01 'p',
8324/// Jan-05 's', Jan-15 'q'.
8325#[must_use]
8326pub fn nansum_utf8(values: &[Scalar]) -> Scalar {
8327    let mut out: Option<String> = None;
8328    for v in values {
8329        if v.is_missing() {
8330            continue;
8331        }
8332        if let Scalar::Utf8(part) = v {
8333            out.get_or_insert_with(String::new).push_str(part);
8334        }
8335    }
8336    match out {
8337        Some(joined) => Scalar::Utf8(joined),
8338        // Not `Utf8(String::new())`: pandas yields the integer identity here.
8339        None => Scalar::Int64(0),
8340    }
8341}
8342
8343pub fn nanmean(values: &[Scalar]) -> Scalar {
8344    if let Some((sum, count)) = collect_timedelta_ns(values) {
8345        if count == 0 {
8346            return Scalar::Timedelta64(Timedelta::NAT);
8347        }
8348        // |sum / count| <= max|ns| for count >= 1, so the mean of representable
8349        // inputs is always representable; the narrowing is defensive only.
8350        return timedelta_ns_to_scalar(sum / count as i128);
8351    }
8352    // br-frankenpandas-adv58: Datetime64 mean is the mean of the epoch-ns
8353    // backing, re-read as an instant. Accumulated in i128 and divided with
8354    // Rust's toward-zero integer division, which is exactly the rounding pandas
8355    // shows where it is exact ([0,1] -> 0, [0,3] -> 1, [-3,0] -> -1; floor and
8356    // ties-to-even are both refuted). Where pandas is NOT exact it snaps to its
8357    // f64 grid — even for a constant series — and FP stays exact. See DISC-019.
8358    if let Some((sum, count)) = collect_datetime_ns(values) {
8359        if count == 0 {
8360            return Scalar::Datetime64(Timestamp::NAT);
8361        }
8362        let mean = sum / count as i128;
8363        if mean > i128::from(i64::MAX) || mean <= i128::from(i64::MIN) {
8364            return Scalar::Datetime64(Timestamp::NAT);
8365        }
8366        return Scalar::Datetime64(mean as i64);
8367    }
8368    // Fused single-pass fold (see `nansum`): accumulate sum + count of finite
8369    // values in one scan. Bit-identical to the prior `collect_finite` two-pass:
8370    // count == nums.len(), sum folds the same values in the same order.
8371    let mut sum = 0.0_f64;
8372    let mut count = 0usize;
8373    for v in values {
8374        if v.is_missing() {
8375            continue;
8376        }
8377        if let Ok(x) = v.to_f64() {
8378            sum += x;
8379            count += 1;
8380        }
8381    }
8382    if count == 0 {
8383        return Scalar::Null(NullKind::NaN);
8384    }
8385    Scalar::Float64(sum / count as f64)
8386}
8387
8388pub fn nanany(values: &[Scalar]) -> Scalar {
8389    for v in values {
8390        if v.is_missing() {
8391            continue;
8392        }
8393        match v {
8394            Scalar::Bool(flag) if *flag => return Scalar::Bool(true),
8395            Scalar::Int64(val) if *val != 0 => return Scalar::Bool(true),
8396            Scalar::Float64(val) if !val.is_nan() && *val != 0.0 => return Scalar::Bool(true),
8397            Scalar::Utf8(val) if !val.is_empty() => return Scalar::Bool(true),
8398            // pandas Series([td]).any() returns True for any non-zero
8399            // Timedelta. NaT is already filtered by is_missing() above.
8400            Scalar::Timedelta64(ns) if *ns != 0 => return Scalar::Bool(true),
8401            _ => continue,
8402        }
8403    }
8404    Scalar::Bool(false)
8405}
8406
8407pub fn nanall(values: &[Scalar]) -> Scalar {
8408    for v in values {
8409        if v.is_missing() {
8410            continue;
8411        }
8412        match v {
8413            Scalar::Bool(flag) if !*flag => return Scalar::Bool(false),
8414            Scalar::Int64(val) if *val == 0 => return Scalar::Bool(false),
8415            Scalar::Float64(val) if val.is_nan() || *val == 0.0 => return Scalar::Bool(false),
8416            Scalar::Utf8(val) if val.is_empty() => return Scalar::Bool(false),
8417            // pandas Series([td(0)]).all() returns False; any non-zero
8418            // Timedelta is truthy. NaT is already filtered by is_missing.
8419            Scalar::Timedelta64(ns) if *ns == 0 => return Scalar::Bool(false),
8420            _ => continue,
8421        }
8422    }
8423    Scalar::Bool(true)
8424}
8425
8426pub fn nancount(values: &[Scalar]) -> Scalar {
8427    let n = values.iter().filter(|v| !v.is_missing()).count();
8428    Scalar::Int64(n as i64)
8429}
8430
8431pub fn nanmin(values: &[Scalar]) -> Scalar {
8432    let mut min: Option<&Scalar> = None;
8433    for v in values {
8434        if v.is_missing() {
8435            continue;
8436        }
8437        match (min, v) {
8438            (None, _) => min = Some(v),
8439            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8440                if b < a {
8441                    min = Some(v)
8442                }
8443            }
8444            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8445                if *b < *a {
8446                    min = Some(v)
8447                }
8448            }
8449            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8450                if b < a {
8451                    min = Some(v)
8452                }
8453            }
8454            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8455                if b < a {
8456                    min = Some(v)
8457                }
8458            }
8459            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
8460            // the catch-all below would silently return NaN. Compare ns
8461            // representations directly; NAT is already filtered by
8462            // is_missing() above.
8463            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8464                if b < a {
8465                    min = Some(v)
8466                }
8467            }
8468            // br-frankenpandas-axhhk: Datetime64 needs the same arm for the
8469            // same reason — its to_f64() errors too. Without it a 2+-element
8470            // datetime column returned Null(NaN), while a 1-element one
8471            // returned the right answer via the (None, _) seed above.
8472            (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8473                if b < a {
8474                    min = Some(v)
8475                }
8476            }
8477            // br-frankenpandas-qoabs: Period, third dtype with the same
8478            // to_f64() failure. Ordinals are ONLY comparable within one freq —
8479            // pandas refuses mixed freq outright (IncompatibleFrequency), so a
8480            // differing freq must NOT be ordered here. Comparing the raw
8481            // ordinals across freqs would invent an ordering pandas rejects
8482            // (monthly 2020-01 is ordinal 600, daily 2020-01-05 is 18267).
8483            // br-frankenpandas-qoabs: Period, third dtype with the same
8484            // to_f64() failure. Ordinals are ONLY comparable within one freq —
8485            // pandas refuses mixed freq outright (IncompatibleFrequency), so a
8486            // differing freq must NOT be ordered here. Comparing the raw
8487            // ordinals across freqs would invent an ordering pandas rejects
8488            // (monthly 2020-01 is ordinal 600, daily 2020-01-05 is 18267).
8489            (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8490                if a.freq != b.freq {
8491                    return Scalar::Null(NullKind::NaN);
8492                }
8493                if b.ordinal < a.ordinal {
8494                    min = Some(v)
8495                }
8496            }
8497            // br-frankenpandas-srqdo: Interval, fourth dtype whose to_f64()
8498            // errors. pandas orders Intervals by (left, right) — a tie on left
8499            // falls through to right. `closed` is NOT part of the comparison:
8500            // pandas does order scalar Intervals that tie on both bounds by an
8501            // internal `closed` ordering, but a real IntervalArray requires a
8502            // UNIFORM closed, so that case cannot arise from an Interval
8503            // column, and guessing an undocumented enum order would be worse
8504            // than keeping the first on an exact tie.
8505            //
8506            // A NaN bound is not orderable and has no pandas counterpart —
8507            // IntervalArray refuses to build one ("missing values must be
8508            // missing in the same location both left and right") — so bail to
8509            // missing rather than impose an arbitrary order. Note this avoids
8510            // `partial_cmp().unwrap()`, which would be a panic in library code.
8511            (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8512                if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8513                    return Scalar::Null(NullKind::NaN);
8514                }
8515                if (b.left, b.right) < (a.left, a.right) {
8516                    min = Some(v)
8517                }
8518            }
8519            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8520                (Ok(af), Ok(bf)) if bf < af => min = Some(v),
8521                (Ok(_), Ok(_)) => {}
8522                _ => return Scalar::Null(NullKind::NaN),
8523            },
8524        }
8525    }
8526    match min {
8527        Some(v) => v.clone(),
8528        None => Scalar::Null(NullKind::NaN),
8529    }
8530}
8531
8532pub fn nanmax(values: &[Scalar]) -> Scalar {
8533    let mut max: Option<&Scalar> = None;
8534    for v in values {
8535        if v.is_missing() {
8536            continue;
8537        }
8538        match (max, v) {
8539            (None, _) => max = Some(v),
8540            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8541                if b > a {
8542                    max = Some(v)
8543                }
8544            }
8545            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8546                if *b > *a {
8547                    max = Some(v)
8548                }
8549            }
8550            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8551                if b > a {
8552                    max = Some(v)
8553                }
8554            }
8555            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8556                if b > a {
8557                    max = Some(v)
8558                }
8559            }
8560            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
8561            // the catch-all below would silently return NaN. Compare ns
8562            // representations directly; NAT is already filtered above.
8563            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8564                if b > a {
8565                    max = Some(v)
8566                }
8567            }
8568            // br-frankenpandas-axhhk: Datetime64 sibling of the arm above.
8569            (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8570                if b > a {
8571                    max = Some(v)
8572                }
8573            }
8574            // br-frankenpandas-qoabs: Period, freq-guarded — see `nanmin`.
8575            (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8576                if a.freq != b.freq {
8577                    return Scalar::Null(NullKind::NaN);
8578                }
8579                if b.ordinal > a.ordinal {
8580                    max = Some(v)
8581                }
8582            }
8583            // br-frankenpandas-srqdo: Interval, ordered by (left, right) with
8584            // NaN bounds refused — see `nanmin` for the full reasoning.
8585            (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8586                if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8587                    return Scalar::Null(NullKind::NaN);
8588                }
8589                if (b.left, b.right) > (a.left, a.right) {
8590                    max = Some(v)
8591                }
8592            }
8593            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8594                (Ok(af), Ok(bf)) if bf > af => max = Some(v),
8595                (Ok(_), Ok(_)) => {}
8596                _ => return Scalar::Null(NullKind::NaN),
8597            },
8598        }
8599    }
8600    match max {
8601        Some(v) => v.clone(),
8602        None => Scalar::Null(NullKind::NaN),
8603    }
8604}
8605
8606/// Which temporal family a uniformly-temporal input belongs to, and everything
8607/// needed to rebuild a `Scalar` of it from a raw i64 backing.
8608///
8609/// br-frankenpandas-d7zjp replaced the previous `fn(i64) -> Scalar` constructor
8610/// with this enum for one reason: a plain fn pointer CANNOT CARRY A FREQ, and a
8611/// `Period` is `{ordinal, freq}`. That limitation is what blocked Period from
8612/// joining median/quantile/cummax/cummin when Datetime64 did.
8613///
8614/// The i64 payload is nanoseconds for Timedelta64/Datetime64 and an ORDINAL for
8615/// Period — different units, but every operation here is pure ordering or an
8616/// average over that backing, which is meaningful in both.
8617#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8618enum TemporalFamily {
8619    Timedelta,
8620    Datetime,
8621    /// Periods only compare within ONE freq; see [`collect_temporal_backing`].
8622    Period(PeriodFreq),
8623}
8624
8625impl TemporalFamily {
8626    /// Rebuild a scalar of this family from its raw backing.
8627    fn make(self, raw: i64) -> Scalar {
8628        match self {
8629            Self::Timedelta => Scalar::Timedelta64(raw),
8630            Self::Datetime => Scalar::Datetime64(raw),
8631            Self::Period(freq) => Scalar::Period(Period::new(raw, freq)),
8632        }
8633    }
8634
8635    /// The family's missing sentinel, dtype preserved.
8636    fn nat(self) -> Scalar {
8637        self.make(i64::MIN)
8638    }
8639}
8640
8641/// Per br-frankenpandas-j8ntk: harvest the raw backing of a uniformly-temporal
8642/// input as f64 (53 bits of mantissa, exact for ns spans up to ~104 days;
8643/// beyond that pandas itself loses precision the same way), together with the
8644/// family to rebuild results in. A NaT-only input keeps its family.
8645///
8646/// Returns `None` unless every non-missing value belongs to ONE family — which
8647/// for Period means one FREQ as well, because pandas refuses to order Periods
8648/// of differing freq at all (`IncompatibleFrequency`) and their ordinals are
8649/// not comparable across freqs.
8650///
8651/// br-frankenpandas-adv58 widened this to Datetime64 and d7zjp to Period. The
8652/// f64 hop is inherited deliberately: quantile interpolates by a fractional
8653/// weight, so the newer families keep the SAME accuracy contract the Timedelta
8654/// arm already had rather than inventing a stricter one per dtype.
8655fn collect_temporal_backing(values: &[Scalar]) -> Option<(Vec<f64>, TemporalFamily)> {
8656    let mut out = Vec::with_capacity(values.len());
8657    let mut family: Option<TemporalFamily> = None;
8658    for v in values {
8659        let (raw, this) = match v {
8660            Scalar::Timedelta64(ns) => (*ns, TemporalFamily::Timedelta),
8661            Scalar::Datetime64(ns) => (*ns, TemporalFamily::Datetime),
8662            Scalar::Period(p) => (p.ordinal, TemporalFamily::Period(p.freq)),
8663            _ if v.is_missing() => continue,
8664            _ => return None,
8665        };
8666        // Mixing families — or, for Period, mixing freqs — is not one family.
8667        match family {
8668            Some(existing) if existing != this => return None,
8669            _ => family = Some(this),
8670        }
8671        if v.is_missing() {
8672            continue;
8673        }
8674        out.push(raw as f64);
8675    }
8676    family.map(|f| (out, f))
8677}
8678
8679/// Timedelta64-ONLY view of [`collect_temporal_backing`].
8680///
8681/// var/sem keep this narrower gate on purpose: live pandas 2.2.3 RAISES
8682/// `TypeError: 'DatetimeArray' ... does not support reduction 'var'` (and the
8683/// same for 'sem', and for every one of them on Period), so widening them would
8684/// invent a value pandas refuses to produce.
8685fn collect_timedelta_ns_f64(values: &[Scalar]) -> Option<Vec<f64>> {
8686    match collect_temporal_backing(values) {
8687        Some((out, TemporalFamily::Timedelta)) => Some(out),
8688        _ => None,
8689    }
8690}
8691
8692/// Clamp an f64 result into i64 range and wrap as Scalar::Timedelta64.
8693fn float_ns_to_timedelta(value: f64) -> Scalar {
8694    float_ns_to_temporal(value, TemporalFamily::Timedelta)
8695}
8696
8697/// Family-generic form of [`float_ns_to_timedelta`], per br-frankenpandas-adv58:
8698/// NaT for a non-finite input, otherwise the value in the caller's family.
8699fn float_ns_to_temporal(value: f64, make: TemporalFamily) -> Scalar {
8700    if !value.is_finite() {
8701        return make.nat();
8702    }
8703    let clamped = value.clamp(i64::MIN as f64, i64::MAX as f64);
8704    make.make(clamped as i64)
8705}
8706
8707pub fn nanmedian(values: &[Scalar]) -> Scalar {
8708    // Preserve exact nanosecond ordering for uniformly-temporal input.
8709    // Converting to f64 loses distinct ticks beyond the 53-bit boundary.
8710    //
8711    // br-frankenpandas-adv58: Datetime64 joins Timedelta64 here, and keeps the
8712    // SAME exact i128 treatment its Timedelta sibling already had. Note that
8713    // this makes FP strictly more precise than pandas 2.2.3, which routes
8714    // datetime median through f64 and therefore snaps to a 256 ns grid at
8715    // 2020-era timestamps — returning, for an odd-count input, a Timestamp that
8716    // is not even one of the supplied values. See DISC-019.
8717    // br-frankenpandas-d7zjp: Period joins via the family enum, which — unlike
8718    // the fn-pointer constructor this replaced — can carry its freq. A
8719    // mixed-freq input is not one family, so it falls through rather than
8720    // being ordered by raw ordinal, matching pandas refusing it outright.
8721    let Some((_, make)) = collect_temporal_backing(values) else {
8722        // Not uniformly temporal: fall through to the numeric arm below.
8723        return nanmedian_numeric(values);
8724    };
8725    let mut td: Vec<i64> = values
8726        .iter()
8727        .filter(|value| !value.is_missing())
8728        .filter_map(|value| match value {
8729            Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
8730            Scalar::Period(p) => Some(p.ordinal),
8731            _ => None,
8732        })
8733        .collect();
8734    if td.is_empty() {
8735        // All-missing temporal input falls through to the numeric arm, which
8736        // yields Null(NaN). Do NOT "improve" this to a family-typed NaT: the
8737        // Null(NaN) result is pinned by the oracle test
8738        // `nanmedian_matches_numeric_and_timedelta_oracle_oabhi`, and the old
8739        // `is_timedelta_input` gate produced it by returning false for an
8740        // all-missing input. `collect_temporal_backing` marks the family on
8741        // seeing the VARIANT instead, so the fall-through has to be explicit.
8742        return nanmedian_numeric(values);
8743    }
8744    // O(n) selection instead of a full sort: order statistics depend only
8745    // on values, so the unstable partition yields the same middle values.
8746    let n = td.len();
8747    let mid = n / 2;
8748    let (left, mid_ref, _right) = td.select_nth_unstable(mid);
8749    let mid_val = *mid_ref;
8750    let median_ns = if n.is_multiple_of(2) {
8751        let lower = left.iter().copied().fold(i64::MIN, i64::max);
8752        // Toward-zero division, matching pandas where pandas is exact.
8753        (i128::from(lower) + i128::from(mid_val)) / 2
8754    } else {
8755        i128::from(mid_val)
8756    };
8757    make.make(median_ns as i64)
8758}
8759
8760/// Numeric (f64) median arm, split out of [`nanmedian`] by
8761/// br-frankenpandas-adv58 so the temporal arm can return early. Also the
8762/// fall-through for non-uniform input, e.g. mixed Datetime64 + Int64.
8763fn nanmedian_numeric(values: &[Scalar]) -> Scalar {
8764    let mut nums = collect_finite(values);
8765    if nums.is_empty() {
8766        return Scalar::Null(NullKind::NaN);
8767    }
8768    // O(n) selection instead of an O(n log n) full sort: select_nth_unstable_by
8769    // places the `mid`-th smallest at index `mid` with all smaller elements
8770    // (unordered) in the left partition. For even n the (mid-1)-th smallest is
8771    // the MAX of that left partition. Bit-identical to the sort path: order
8772    // statistics depend only on VALUES, and ties share a value, so the
8773    // unstable partition yields the same nums[mid-1]/nums[mid] the sort did.
8774    let n = nums.len();
8775    let mid = n / 2;
8776    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
8777    let (left, mid_ref, _right) = nums.select_nth_unstable_by(mid, cmp);
8778    let mid_val = *mid_ref;
8779    if n.is_multiple_of(2) {
8780        let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
8781        Scalar::Float64((lower + mid_val) / 2.0)
8782    } else {
8783        Scalar::Float64(mid_val)
8784    }
8785}
8786
8787pub fn nanvar(values: &[Scalar], ddof: usize) -> Scalar {
8788    // Per br-frankenpandas-j8ntk: Timedelta64 var preserves dtype — pandas
8789    // returns Timedelta even though variance is ns² conceptually; matching.
8790    if let Some(td) = collect_timedelta_ns_f64(values) {
8791        if td.len() <= ddof {
8792            return Scalar::Timedelta64(Timedelta::NAT);
8793        }
8794        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8795        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8796        return float_ns_to_timedelta(sum_sq / (td.len() - ddof) as f64);
8797    }
8798    let nums = collect_finite(values);
8799    if nums.len() <= ddof {
8800        return Scalar::Null(NullKind::NaN);
8801    }
8802    let mean: f64 = nums.iter().sum::<f64>() / nums.len() as f64;
8803    let sum_sq: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
8804    Scalar::Float64(sum_sq / (nums.len() - ddof) as f64)
8805}
8806
8807pub fn nanstd(values: &[Scalar], ddof: usize) -> Scalar {
8808    // Per br-frankenpandas-j8ntk: Timedelta64 std preserves dtype.
8809    //
8810    // br-frankenpandas-40ujm: Datetime64 is accepted here too, and the family
8811    // constructor is deliberately DISCARDED — the dispersion of a set of
8812    // instants is a DURATION, so datetime std returns a Timedelta, exactly as
8813    // pandas does. Verified against the oracle: pandas gives the identical
8814    // value for a Datetime64 series and a Timedelta64 series built from the
8815    // same ns (both 2592479955563784 for [0, 60d, 31d]).
8816    //
8817    // This is the ONLY reduction in the std/var/sem group that widens. pandas
8818    // RAISES for datetime64 var and sem ("does not support reduction"), so
8819    // those keep the Timedelta-only `collect_timedelta_ns_f64` gate rather than
8820    // inventing a value pandas refuses to produce.
8821    //
8822    // br-frankenpandas-d7zjp: PERIOD IS EXCLUDED HERE. pandas raises
8823    // "'PeriodArray' with dtype period[M] does not support reduction 'std'",
8824    // so widening std to Period alongside Datetime64 would invent a value —
8825    // and the family enum makes that mistake one line away, hence the guard.
8826    if let Some((td, family)) = collect_temporal_backing(values)
8827        && !matches!(family, TemporalFamily::Period(_))
8828    {
8829        if td.len() <= ddof {
8830            return Scalar::Timedelta64(Timedelta::NAT);
8831        }
8832        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8833        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8834        let var = sum_sq / (td.len() - ddof) as f64;
8835        return float_ns_to_timedelta(var.sqrt());
8836    }
8837    match nanvar(values, ddof) {
8838        Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
8839        other => other,
8840    }
8841}
8842
8843/// Standard error of the mean over non-missing values.
8844///
8845/// Matches `pd.Series.sem(ddof=1)` / `scipy.stats.sem`. Computed as
8846/// `std(values, ddof) / sqrt(n)` where `n` is the non-missing count.
8847/// Returns `Null(NaN)` when `n <= ddof`.
8848pub fn nansem(values: &[Scalar], ddof: usize) -> Scalar {
8849    // Per br-frankenpandas-j8ntk: Timedelta64 sem preserves dtype.
8850    if let Some(td) = collect_timedelta_ns_f64(values) {
8851        if td.len() <= ddof {
8852            return Scalar::Timedelta64(Timedelta::NAT);
8853        }
8854        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8855        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8856        let var = sum_sq / (td.len() - ddof) as f64;
8857        let std = var.sqrt();
8858        return float_ns_to_timedelta(std / (td.len() as f64).sqrt());
8859    }
8860    let nums = collect_finite(values);
8861    if nums.len() <= ddof {
8862        return Scalar::Null(NullKind::NaN);
8863    }
8864    let n = nums.len();
8865    let mean = nums.iter().sum::<f64>() / n as f64;
8866    let sum_sq = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
8867    let var = sum_sq / (n - ddof) as f64;
8868    let std = var.sqrt();
8869    Scalar::Float64(std / (n as f64).sqrt())
8870}
8871
8872/// Standard error of the mean as pandas' groupby, resample and pivot_table
8873/// compute it: `sqrt(var / n)` (libgroupby's `group_var(name="sem")`), which
8874/// can differ in the last bit from [`nansem`]'s `std / sqrt(n)` (Series.sem):
8875/// for `[1.0, 4.0]` this is `1.5` and nansem `1.4999999999999998`
8876/// (br-frankenpandas-7hxqv). Timedelta input keeps [`nansem`].
8877pub fn nansem_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8878    if collect_timedelta_ns_f64(values).is_some() {
8879        return nansem(values, ddof);
8880    }
8881    grouped_moments(values)
8882        .sem(ddof)
8883        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8884}
8885
8886/// pandas' compensated running sum: its cython `group_sum`, `group_mean`
8887/// and `group_cumsum` add each float as `y = v - comp; t = sum + y;
8888/// comp = t - sum - y; sum = t` (Kahan), `comp` reset to 0 where it is NaN
8889/// (an inf added; GH#53606). A plain `+=` fold differs from it in the last
8890/// bits - groupby sum of ten 0.1 is 1.0 in pandas, 0.9999999999999999
8891/// naively (br-frankenpandas-xhogl).
8892#[derive(Clone, Copy, Debug, Default, PartialEq)]
8893pub struct KahanSum {
8894    sum: f64,
8895    compensation: f64,
8896}
8897
8898impl KahanSum {
8899    /// `value` added, as pandas' group kernels add it.
8900    #[inline]
8901    pub fn add(&mut self, value: f64) {
8902        let y = value - self.compensation;
8903        let t = self.sum + y;
8904        self.compensation = t - self.sum - y;
8905        if self.compensation.is_nan() {
8906            self.compensation = 0.0;
8907        }
8908        self.sum = t;
8909    }
8910
8911    /// The sum so far.
8912    #[inline]
8913    #[must_use]
8914    pub fn sum(self) -> f64 {
8915        self.sum
8916    }
8917}
8918
8919/// pandas' online variance: its cython `group_var` folds each float as
8920/// Welford (`mean += (v - old) / n; m2 += (v - mean) * (v - old)`) and
8921/// answers `m2 / (n - ddof)`, std its square root and sem
8922/// `sqrt(m2 / (n - ddof) / n)` - where the two-pass form differs in the
8923/// last bits (a constant group's var is 0.0, not 1e-34;
8924/// br-frankenpandas-xhogl).
8925#[derive(Clone, Copy, Debug, Default, PartialEq)]
8926pub struct WelfordVar {
8927    count: usize,
8928    mean: f64,
8929    m2: f64,
8930}
8931
8932impl WelfordVar {
8933    /// `value` folded in.
8934    #[inline]
8935    pub fn add(&mut self, value: f64) {
8936        self.count += 1;
8937        let old = self.mean;
8938        self.mean += (value - old) / self.count as f64;
8939        self.m2 += (value - self.mean) * (value - old);
8940    }
8941
8942    /// The values folded in.
8943    #[must_use]
8944    pub fn count(self) -> usize {
8945        self.count
8946    }
8947
8948    /// `m2 / (n - ddof)`; None while `n <= ddof`.
8949    #[must_use]
8950    pub fn var(self, ddof: usize) -> Option<f64> {
8951        (self.count > ddof).then(|| self.m2 / (self.count - ddof) as f64)
8952    }
8953
8954    /// The square root of [`Self::var`].
8955    #[must_use]
8956    pub fn std(self, ddof: usize) -> Option<f64> {
8957        self.var(ddof).map(f64::sqrt)
8958    }
8959
8960    /// `sqrt(var / n)`, pandas' grouped sem.
8961    #[must_use]
8962    pub fn sem(self, ddof: usize) -> Option<f64> {
8963        self.var(ddof).map(|var| (var / self.count as f64).sqrt())
8964    }
8965}
8966
8967/// pandas' online skewness: its cython `group_skew` folds each float into
8968/// running moments (`delta = v - m1; delta_n = delta / n; term1 = delta *
8969/// delta_n * (n - 1); m1 += delta_n; m3 += term1 * delta_n * (n - 2) -
8970/// 3 * delta_n * m2; m2 += term1`) and answers
8971/// `n * (n - 1) ** 0.5 / (n - 2) * (m3 / m2 ** 1.5)` - 0 when `m2` is 0,
8972/// missing below 3 values - where the two-pass [`nanskew`] (Series.skew)
8973/// differs in the last bits (br-frankenpandas-vjfq9).
8974#[derive(Clone, Copy, Debug, Default, PartialEq)]
8975pub struct SkewMoments {
8976    count: usize,
8977    m1: f64,
8978    m2: f64,
8979    m3: f64,
8980}
8981
8982impl SkewMoments {
8983    /// `value` folded in.
8984    #[inline]
8985    pub fn add(&mut self, value: f64) {
8986        let before = self.count as f64;
8987        self.count += 1;
8988        let n = self.count as f64;
8989        let delta = value - self.m1;
8990        let delta_n = delta / n;
8991        let term1 = delta * delta_n * before;
8992        self.m1 += delta_n;
8993        self.m3 += term1 * delta_n * (n - 2.0) - 3.0 * delta_n * self.m2;
8994        self.m2 += term1;
8995    }
8996
8997    /// The values folded in.
8998    #[must_use]
8999    pub fn count(self) -> usize {
9000        self.count
9001    }
9002
9003    /// The bias-corrected skewness; None below 3 values.
9004    #[must_use]
9005    pub fn skew(self) -> Option<f64> {
9006        if self.count < 3 {
9007            return None;
9008        }
9009        if self.m2 == 0.0 {
9010            return Some(0.0);
9011        }
9012        let n = self.count as f64;
9013        // pandas raises with libm pow: pow(n - 1, 0.5) is not always sqrt's
9014        // correctly rounded answer (n = 2922 differs), and a constant 0.5
9015        // exponent would let LLVM substitute sqrt.
9016        let half = std::hint::black_box(0.5);
9017        Some((n * (n - 1.0).powf(half) / (n - 2.0)) * (self.m3 / self.m2.powf(1.5)))
9018    }
9019}
9020
9021/// [`nanskew`] as pandas' grouped skew: [`SkewMoments`] over the present
9022/// values.
9023#[must_use]
9024pub fn nanskew_grouped(values: &[Scalar]) -> Scalar {
9025    let mut moments = SkewMoments::default();
9026    for value in values {
9027        if value.is_missing() {
9028            continue;
9029        }
9030        if let Ok(x) = value.to_f64() {
9031            moments.add(x);
9032        }
9033    }
9034    moments
9035        .skew()
9036        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9037}
9038
9039/// The present values' Welford moments, as [`nanvar_grouped`] reads them.
9040fn grouped_moments(values: &[Scalar]) -> WelfordVar {
9041    let mut moments = WelfordVar::default();
9042    for value in values {
9043        if value.is_missing() {
9044            continue;
9045        }
9046        if let Ok(x) = value.to_f64() {
9047            moments.add(x);
9048        }
9049    }
9050    moments
9051}
9052
9053/// [`nansum`] as pandas' groupby / resample / pivot_table add floats: the
9054/// compensated [`KahanSum`] (br-frankenpandas-xhogl). Timedelta input keeps
9055/// [`nansum`]'s exact integer sum.
9056#[must_use]
9057pub fn nansum_grouped(values: &[Scalar]) -> Scalar {
9058    if collect_timedelta_ns(values).is_some() {
9059        return nansum(values);
9060    }
9061    let mut sum = KahanSum::default();
9062    for value in values {
9063        if value.is_missing() {
9064            continue;
9065        }
9066        if let Ok(x) = value.to_f64() {
9067            sum.add(x);
9068        }
9069    }
9070    Scalar::Float64(sum.sum())
9071}
9072
9073/// [`nanmean`] as pandas' grouped mean: the [`KahanSum`] over the count.
9074/// Temporal input keeps [`nanmean`].
9075#[must_use]
9076pub fn nanmean_grouped(values: &[Scalar]) -> Scalar {
9077    if collect_timedelta_ns(values).is_some() || collect_datetime_ns(values).is_some() {
9078        return nanmean(values);
9079    }
9080    let mut sum = KahanSum::default();
9081    let mut count = 0_usize;
9082    for value in values {
9083        if value.is_missing() {
9084            continue;
9085        }
9086        if let Ok(x) = value.to_f64() {
9087            sum.add(x);
9088            count += 1;
9089        }
9090    }
9091    if count == 0 {
9092        return Scalar::Null(NullKind::NaN);
9093    }
9094    Scalar::Float64(sum.sum() / count as f64)
9095}
9096
9097/// [`nanvar`] as pandas' grouped var: [`WelfordVar`]. Timedelta input keeps
9098/// [`nanvar`].
9099#[must_use]
9100pub fn nanvar_grouped(values: &[Scalar], ddof: usize) -> Scalar {
9101    if collect_timedelta_ns_f64(values).is_some() {
9102        return nanvar(values, ddof);
9103    }
9104    grouped_moments(values)
9105        .var(ddof)
9106        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9107}
9108
9109/// [`nanstd`] as pandas' grouped std: [`WelfordVar`]. Temporal input keeps
9110/// [`nanstd`].
9111#[must_use]
9112pub fn nanstd_grouped(values: &[Scalar], ddof: usize) -> Scalar {
9113    if collect_temporal_backing(values).is_some() {
9114        return nanstd(values, ddof);
9115    }
9116    grouped_moments(values)
9117        .std(ddof)
9118        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9119}
9120
9121/// Peak-to-peak range of non-missing values (max − min).
9122///
9123/// Matches `np.ptp` behavior on nan-safe inputs. Returns `Null(NaN)`
9124/// for empty or all-missing inputs.
9125pub fn nanptp(values: &[Scalar]) -> Scalar {
9126    // br-frankenpandas-axhhk: Datetime64 ptp is NOT a dtype-preserving sibling
9127    // of the Timedelta64 arm below — the span between two instants is a
9128    // DURATION, so pandas returns a Timedelta here (`s.max() - s.min()` on a
9129    // datetime64 Series). Subtract in i128 and narrow through the shared
9130    // opz27 helper so an unrepresentable span becomes NaT rather than a
9131    // fabricated extreme. Previously to_f64() errored on every element, `seen`
9132    // stayed false, and this returned Null(NaN).
9133    if is_datetime_input(values) {
9134        let (mut lo, mut hi) = (i64::MAX, i64::MIN);
9135        for value in values {
9136            if value.is_missing() {
9137                continue;
9138            }
9139            if let Scalar::Datetime64(ns) = value {
9140                lo = lo.min(*ns);
9141                hi = hi.max(*ns);
9142            }
9143        }
9144        return timedelta_ns_to_scalar(i128::from(hi) - i128::from(lo));
9145    }
9146    // Preserve every nanosecond in the uniformly-Timedelta64 case. Converting
9147    // to f64 before subtracting loses ranges below one f64 ULP beyond 104 days.
9148    // The Scalar fallback below retains mixed-family behavior.
9149    let (mut td_lo, mut td_hi) = (i64::MAX, i64::MIN);
9150    let mut saw_timedelta = false;
9151    let mut all_timedelta = true;
9152    for value in values {
9153        if value.is_missing() {
9154            continue;
9155        }
9156        match value {
9157            Scalar::Timedelta64(ns) => {
9158                saw_timedelta = true;
9159                td_lo = td_lo.min(*ns);
9160                td_hi = td_hi.max(*ns);
9161            }
9162            _ => {
9163                all_timedelta = false;
9164                break;
9165            }
9166        }
9167    }
9168    if all_timedelta && saw_timedelta {
9169        // Subtract in i128: the true range of two representable Timedeltas can
9170        // exceed i64 (max - min overflows), where live pandas 2.2.3 raises
9171        // OverflowError. Saturating here fabricated a finite Timedelta.max.
9172        return timedelta_ns_to_scalar(i128::from(td_hi) - i128::from(td_lo));
9173    }
9174    // Fused single-pass min/max (see `nansum`): track lo/hi while filtering, no
9175    // intermediate Vec<f64>. Bit-identical to the prior collect_finite two-pass:
9176    // `seen` is true exactly when collect_finite would be non-empty, and the
9177    // lo/hi comparisons fold the same finite values in the same order.
9178    let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
9179    let mut seen = false;
9180    for v in values {
9181        if v.is_missing() {
9182            continue;
9183        }
9184        if let Ok(x) = v.to_f64() {
9185            seen = true;
9186            if x < lo {
9187                lo = x;
9188            }
9189            if x > hi {
9190                hi = x;
9191            }
9192        }
9193    }
9194    if !seen {
9195        return Scalar::Null(NullKind::NaN);
9196    }
9197    Scalar::Float64(hi - lo)
9198}
9199
9200/// Sample skewness (bias-corrected, Fisher-Pearson) over non-missing values.
9201///
9202/// Matches `pd.Series.skew()`. Requires at least 3 non-missing values;
9203/// returns `Null(NaN)` otherwise, and when the sample standard deviation
9204/// is zero.
9205pub fn nanskew(values: &[Scalar]) -> Scalar {
9206    let nums = collect_finite(values);
9207    let n = nums.len() as f64;
9208    if n < 3.0 {
9209        return Scalar::Null(NullKind::NaN);
9210    }
9211    let mean = nums.iter().sum::<f64>() / n;
9212    // Accumulate both central moments while the collected values are hot. Each
9213    // sum still observes the same terms in the same order as the former two
9214    // iterator passes, preserving floating-point results bit-for-bit.
9215    let (mut m2, mut m3) = (0.0_f64, 0.0_f64);
9216    for x in nums {
9217        let delta = x - mean;
9218        // d2 reuse: 2 multiplies per element instead of 3. powi(3) lowers to two
9219        // multiplies of {delta, delta*delta}, and float MULTIPLY is commutative
9220        // bit-for-bit, so both sums observe the identical terms — the comment above
9221        // about preserving results bit-for-bit still holds. No ADDITION order changed.
9222        // (br-frankenpandas-8s4mb)
9223        let d2 = delta * delta;
9224        m2 += d2;
9225        m3 += d2 * delta;
9226    }
9227    let s2 = m2 / (n - 1.0);
9228    if s2 == 0.0 {
9229        return Scalar::Float64(0.0);
9230    }
9231    let s3 = s2.powf(1.5);
9232    Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
9233}
9234
9235/// Excess sample kurtosis (Fisher's definition, bias-corrected) over
9236/// non-missing values.
9237///
9238/// Matches `pd.Series.kurt()`. Requires at least 4 non-missing values;
9239/// returns `Null(NaN)` otherwise, and when the sample standard deviation
9240/// is zero.
9241pub fn nankurt(values: &[Scalar]) -> Scalar {
9242    let nums = collect_finite(values);
9243    let n = nums.len() as f64;
9244    if n < 4.0 {
9245        return Scalar::Null(NullKind::NaN);
9246    }
9247    let mean = nums.iter().sum::<f64>() / n;
9248    // Accumulate both central moments while the collected values are hot. Each
9249    // sum still observes the same terms in the same order as the former two
9250    // iterator passes, preserving floating-point results bit-for-bit.
9251    let (mut m2, mut m4) = (0.0_f64, 0.0_f64);
9252    for x in nums {
9253        let delta = x - mean;
9254        // d2 reuse; see `nanskew`. powi(4) lowers to (d*d)*(d*d), which is exactly
9255        // d2 * d2, so this is bit-identical.
9256        let d2 = delta * delta;
9257        m2 += d2;
9258        m4 += d2 * d2;
9259    }
9260    let s2 = m2 / (n - 1.0);
9261    if s2 == 0.0 {
9262        return Scalar::Float64(0.0);
9263    }
9264    let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
9265    let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
9266    Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
9267}
9268
9269/// Product of non-missing values. Returns 1.0 for empty input (matching pandas).
9270pub fn nanprod(values: &[Scalar]) -> Scalar {
9271    // Per br-frankenpandas-szq6a: pandas raises TypeError on
9272    // td_series.prod() because Timedelta² has no dimension. Returning the
9273    // misleading Float64(1.0) (empty-iterator default after collect_finite
9274    // drops every Timedelta64) is worse than surfacing missing. NaT
9275    // propagates the "type-incompatible" signal in lieu of a Result-level
9276    // error.
9277    if is_timedelta_input(values) {
9278        return Scalar::Null(NullKind::NaN);
9279    }
9280    // Fused single-pass fold (see `nansum`): filter missing / non-coercible and
9281    // multiply in one scan, no intermediate Vec<f64>. Bit-identical to
9282    // `collect_finite(..).iter().product()`: same finite values, same order,
9283    // same f64 `*` (Product for f64 == fold(1.0, *)); empty -> 1.0.
9284    let mut prod = 1.0_f64;
9285    for v in values {
9286        if v.is_missing() {
9287            continue;
9288        }
9289        if let Ok(x) = v.to_f64() {
9290            prod *= x;
9291        }
9292    }
9293    Scalar::Float64(prod)
9294}
9295
9296/// Cumulative sum respecting null propagation.
9297///
9298/// Per br-frankenpandas-x0x91: detect uniformly-Timedelta64 input
9299/// (allowing Null/NAT missing markers). Returns true when at least one
9300/// non-missing value is Timedelta64 and no other dtype appears.
9301fn is_timedelta_input(values: &[Scalar]) -> bool {
9302    let mut saw_td = false;
9303    for v in values {
9304        if v.is_missing() {
9305            continue;
9306        }
9307        match v {
9308            Scalar::Timedelta64(_) => saw_td = true,
9309            _ => return false,
9310        }
9311    }
9312    saw_td
9313}
9314
9315/// Datetime64 mirror of [`collect_timedelta_ns`], per br-frankenpandas-adv58.
9316///
9317/// Note the deliberate difference from [`is_datetime_input`]: the family is
9318/// marked on seeing the *variant*, before the missing check, so an ALL-NaT
9319/// datetime input still reports as the Datetime family with `count == 0`. That
9320/// is what lets `nanmean` return `Datetime64(NaT)` — preserving dtype the way
9321/// pandas does — instead of degrading to a numeric NaN. `collect_timedelta_ns`
9322/// has used this convention all along; matching it keeps the two families
9323/// symmetric.
9324fn collect_datetime_ns(values: &[Scalar]) -> Option<(i128, usize)> {
9325    let mut sum: i128 = 0;
9326    let mut count: usize = 0;
9327    let mut saw_datetime = false;
9328    for v in values {
9329        match v {
9330            Scalar::Datetime64(ns) => {
9331                saw_datetime = true;
9332                if v.is_missing() {
9333                    continue;
9334                }
9335                sum += i128::from(*ns);
9336                count += 1;
9337            }
9338            _ if v.is_missing() => continue,
9339            _ => return None,
9340        }
9341    }
9342    if saw_datetime {
9343        Some((sum, count))
9344    } else {
9345        None
9346    }
9347}
9348
9349/// Sibling of [`is_timedelta_input`] for Datetime64, per br-frankenpandas-axhhk.
9350///
9351/// `Datetime64::to_f64()` errors exactly like `Timedelta64::to_f64()` does, so
9352/// every reduction that routed datetimes through the f64 catch-all silently
9353/// produced `Null(NaN)`. Datetime64 orders exactly like its i64 nanosecond
9354/// backing, and NaT (`Timestamp::NAT`) is already filtered by `is_missing`.
9355fn is_datetime_input(values: &[Scalar]) -> bool {
9356    let mut saw_dt = false;
9357    for v in values {
9358        if v.is_missing() {
9359            continue;
9360        }
9361        match v {
9362            Scalar::Datetime64(_) => saw_dt = true,
9363            _ => return false,
9364        }
9365    }
9366    saw_dt
9367}
9368
9369/// Returns true for uniformly-Int64 input with optional missing markers.
9370fn is_int64_input(values: &[Scalar]) -> bool {
9371    let mut saw_int = false;
9372    for value in values {
9373        if value.is_missing() {
9374            continue;
9375        }
9376        match value {
9377            Scalar::Int64(_) => saw_int = true,
9378            _ => return false,
9379        }
9380    }
9381    saw_int
9382}
9383
9384/// First-position arg-extremum over a uniformly i64-backed scalar family.
9385/// True when every non-missing value is an Interval, per br-frankenpandas-2h9dm.
9386fn is_interval_input(values: &[Scalar]) -> bool {
9387    let mut saw_interval = false;
9388    for v in values {
9389        if v.is_missing() {
9390            continue;
9391        }
9392        match v {
9393            Scalar::Interval(_) => saw_interval = true,
9394            _ => return false,
9395        }
9396    }
9397    saw_interval
9398}
9399
9400/// Positional extreme over a uniformly-Interval input, per br-frankenpandas-2h9dm.
9401///
9402/// Intervals cannot use [`nanarg_i64`] (they are two f64s, not an i64 newtype)
9403/// and cannot use the f64 fallback in the callers (`to_f64` errors on them), so
9404/// they get this dedicated lexicographic (left, right) walk. `closed` is not
9405/// part of the comparison, for the reasons documented on `nanmin`.
9406///
9407/// Returns `None` if any bound is NaN: such an interval is not orderable and
9408/// pandas will not even construct one, so an arbitrary index would be worse
9409/// than declining. This is also why the comparison is a plain `<`/`>` on a
9410/// tuple rather than `partial_cmp().unwrap()`, which would panic.
9411fn nanarg_interval(values: &[Scalar], find_max: bool) -> Option<usize> {
9412    let mut best: Option<(usize, (f64, f64))> = None;
9413    for (index, value) in values.iter().enumerate() {
9414        if value.is_missing() {
9415            continue;
9416        }
9417        let Scalar::Interval(iv) = value else {
9418            continue;
9419        };
9420        if iv.left.is_nan() || iv.right.is_nan() {
9421            return None;
9422        }
9423        let key = (iv.left, iv.right);
9424        match best {
9425            None => best = Some((index, key)),
9426            // Strict comparison keeps the FIRST occurrence of a duplicated
9427            // extreme, which is what pandas' idxmin/idxmax return.
9428            Some((_, current)) if (find_max && key > current) || (!find_max && key < current) => {
9429                best = Some((index, key));
9430            }
9431            _ => {}
9432        }
9433    }
9434    best.map(|(index, _)| index)
9435}
9436
9437fn nanarg_i64(values: &[Scalar], find_max: bool) -> Option<usize> {
9438    let mut best: Option<(usize, i64)> = None;
9439    for (index, value) in values.iter().enumerate() {
9440        if value.is_missing() {
9441            continue;
9442        }
9443        // br-frankenpandas-axhhk: Datetime64 joins the typed i64 families here.
9444        // Its ns backing orders identically, and routing it through the f64
9445        // path instead returned None for any 2+-element datetime input.
9446        //
9447        // br-frankenpandas-d7zjp: Period cannot join this or-pattern — it is a
9448        // STRUCT, not an i64 newtype — so it contributes its ordinal here. The
9449        // caller has already established a single freq via
9450        // `collect_temporal_backing`, so these ordinals are comparable.
9451        let candidate = match value {
9452            Scalar::Int64(raw) | Scalar::Timedelta64(raw) | Scalar::Datetime64(raw) => raw,
9453            Scalar::Period(p) => &p.ordinal,
9454            _ => continue,
9455        };
9456        match best {
9457            None => best = Some((index, *candidate)),
9458            Some((_, current))
9459                if (find_max && *candidate > current) || (!find_max && *candidate < current) =>
9460            {
9461                best = Some((index, *candidate));
9462            }
9463            _ => {}
9464        }
9465    }
9466    best.map(|(index, _)| index)
9467}
9468
9469/// Per br-frankenpandas-x0x91: cumulative running aggregation over a
9470/// uniformly-Timedelta64 input. NaT/Null positions emit NaT and skip
9471/// the accumulator. Saturating i128 keeps overflow contained at i64
9472/// bounds when emitting.
9473fn timedelta_cumulative<F>(values: &[Scalar], init: i128, mut step: F) -> Vec<Scalar>
9474where
9475    F: FnMut(i128, i128) -> i128,
9476{
9477    let mut out = Vec::with_capacity(values.len());
9478    let mut running: i128 = init;
9479    for v in values {
9480        if v.is_missing() {
9481            out.push(Scalar::Null(NullKind::NaT));
9482            continue;
9483        }
9484        if let Scalar::Timedelta64(ns) = v {
9485            // `running` is exact: i128 has enough headroom that folding i64
9486            // nanoseconds cannot overflow it for any constructible input. Only
9487            // the narrowing to the output element can fail, so a running sum
9488            // that overflows i64 and later returns to range emits its true
9489            // value again instead of poisoning the tail — nothing is
9490            // fabricated at any index.
9491            running = step(running, i128::from(*ns));
9492            out.push(timedelta_ns_to_scalar(running));
9493        } else {
9494            out.push(Scalar::Null(NullKind::NaT));
9495        }
9496    }
9497    out
9498}
9499
9500/// Per br-frankenpandas-x0x91: running extrema (min/max) over a
9501/// uniformly-Timedelta64 input. `sentinel` is the identity element
9502/// (i64::MAX for min, i64::MIN for max) used until the first
9503/// non-missing value initializes the accumulator.
9504/// `make` builds the output scalar from the running ns value, so the same
9505/// walk serves Timedelta64 and — per br-frankenpandas-axhhk — Datetime64,
9506/// whose running extrema are Timestamps rather than durations.
9507fn timedelta_cumulative_extrema<F>(
9508    values: &[Scalar],
9509    sentinel: i64,
9510    make: TemporalFamily,
9511    mut step: F,
9512) -> Vec<Scalar>
9513where
9514    F: FnMut(i64, i64) -> i64,
9515{
9516    let mut out = Vec::with_capacity(values.len());
9517    let mut running: Option<i64> = None;
9518    for v in values {
9519        if v.is_missing() {
9520            out.push(Scalar::Null(NullKind::NaT));
9521            continue;
9522        }
9523        // br-frankenpandas-d7zjp: a Period contributes its ordinal.
9524        let raw = match v {
9525            Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
9526            Scalar::Period(p) => Some(p.ordinal),
9527            _ => None,
9528        };
9529        if let Some(ns) = raw.as_ref() {
9530            let new_val = match running {
9531                Some(prev) => step(prev, *ns),
9532                None => *ns,
9533            };
9534            running = Some(new_val);
9535            out.push(make.make(new_val));
9536        } else {
9537            out.push(Scalar::Null(NullKind::NaT));
9538        }
9539    }
9540    let _ = sentinel; // silence unused warning if closure ignores it
9541    out
9542}
9543
9544/// Matches `np.nancumsum` / `pd.Series.cumsum()`. Missing input positions
9545/// pass through as `Null(NaN)` in the output; the running sum ignores
9546/// those positions when accumulating.
9547/// Cumulative sum under an explicit overflow policy.
9548///
9549/// br-frankenpandas-fyr1z-wrap-signoff-s4lkx, DECIDED BY THE MAINTAINER: under
9550/// [`OverflowPolicy::Strict`] this REPRODUCES pandas' silent int64 wraparound,
9551/// because STRICT means bit-for-bit observable parity with the incumbent
9552/// including its quirks.
9553///
9554/// Verified against live pandas 2.2.3:
9555/// `Series([Timedelta.max, Timedelta.max]).cumsum()` returns
9556/// `[9223372036854775807, -2]` and the three-element case
9557/// `[max, -2, 9223372036854775805]` — exactly `wrapping_add` accumulation in
9558/// i64. Note the third element proves the accumulator KEEPS WRAPPING rather
9559/// than sticking: it is `(-2).wrapping_add(max)`.
9560///
9561/// Under every other policy this delegates to [`nancumsum`], which keeps the
9562/// exact-i128 accumulation and NaT-on-unrepresentable behaviour from
9563/// br-frankenpandas-opz27. See DISC-020.
9564#[must_use]
9565pub fn nancumsum_with_policy(values: &[Scalar], policy: OverflowPolicy) -> Vec<Scalar> {
9566    if !matches!(policy, OverflowPolicy::Strict) || !is_timedelta_input(values) {
9567        return nancumsum(values);
9568    }
9569    let mut out = Vec::with_capacity(values.len());
9570    let mut running: i64 = 0;
9571    for value in values {
9572        if value.is_missing() {
9573            out.push(Scalar::Null(NullKind::NaT));
9574            continue;
9575        }
9576        if let Scalar::Timedelta64(ns) = value {
9577            // Deliberately WRAPPING, not checked: this is the incumbent's
9578            // observable behaviour and STRICT exists to reproduce it.
9579            running = running.wrapping_add(*ns);
9580            out.push(Scalar::Timedelta64(running));
9581        } else {
9582            out.push(Scalar::Null(NullKind::NaT));
9583        }
9584    }
9585    out
9586}
9587
9588pub fn nancumsum(values: &[Scalar]) -> Vec<Scalar> {
9589    // Per br-frankenpandas-x0x91: when input is uniformly Timedelta64 (with
9590    // optional NaT/Null missing markers), preserve Timedelta dtype to match
9591    // pandas td_series.cumsum() returning Timedelta64.
9592    if is_timedelta_input(values) {
9593        return timedelta_cumulative(values, 0_i128, |acc, x| acc.saturating_add(x));
9594    }
9595    let mut out = Vec::with_capacity(values.len());
9596    let mut running = 0.0_f64;
9597    for v in values {
9598        if v.is_missing() {
9599            out.push(Scalar::Null(NullKind::NaN));
9600            continue;
9601        }
9602        match v.to_f64() {
9603            Ok(x) if !x.is_nan() => {
9604                running += x;
9605                out.push(Scalar::Float64(running));
9606            }
9607            _ => out.push(Scalar::Null(NullKind::NaN)),
9608        }
9609    }
9610    out
9611}
9612
9613/// Cumulative product respecting null propagation.
9614///
9615/// Matches `np.nancumprod` / `pd.Series.cumprod()`. Missing positions
9616/// pass through as `Null(NaN)` without advancing the running product.
9617pub fn nancumprod(values: &[Scalar]) -> Vec<Scalar> {
9618    let mut out = Vec::with_capacity(values.len());
9619    let mut running = 1.0_f64;
9620    for v in values {
9621        if v.is_missing() {
9622            out.push(Scalar::Null(NullKind::NaN));
9623            continue;
9624        }
9625        match v.to_f64() {
9626            Ok(x) if !x.is_nan() => {
9627                running *= x;
9628                out.push(Scalar::Float64(running));
9629            }
9630            _ => out.push(Scalar::Null(NullKind::NaN)),
9631        }
9632    }
9633    out
9634}
9635
9636/// Cumulative maximum respecting null propagation.
9637///
9638/// Matches `pd.Series.cummax()`. Missing positions pass through as
9639/// `Null(NaN)` without updating the running maximum. The first
9640/// non-missing value initializes the running maximum.
9641pub fn nancummax(values: &[Scalar]) -> Vec<Scalar> {
9642    // Per br-frankenpandas-x0x91 (Timedelta64), -axhhk (Datetime64) and
9643    // -d7zjp (Period): every uniformly-temporal family preserves its dtype
9644    // here. Without this the f64 path below errors on every element and
9645    // produces an all-NaN column. A mixed-freq Period input is not one family,
9646    // so it correctly does not take this path.
9647    if let Some((_, family)) = collect_temporal_backing(values) {
9648        return timedelta_cumulative_extrema(values, i64::MAX, family, |acc, x| acc.max(x));
9649    }
9650    let mut out = Vec::with_capacity(values.len());
9651    let mut running: Option<f64> = None;
9652    for v in values {
9653        if v.is_missing() {
9654            out.push(Scalar::Null(NullKind::NaN));
9655            continue;
9656        }
9657        match v.to_f64() {
9658            Ok(x) if !x.is_nan() => {
9659                let new_val = match running {
9660                    Some(prev) => prev.max(x),
9661                    None => x,
9662                };
9663                running = Some(new_val);
9664                out.push(Scalar::Float64(new_val));
9665            }
9666            _ => out.push(Scalar::Null(NullKind::NaN)),
9667        }
9668    }
9669    out
9670}
9671
9672/// Cumulative minimum respecting null propagation.
9673///
9674/// Matches `pd.Series.cummin()`. Symmetric to `nancummax`.
9675pub fn nancummin(values: &[Scalar]) -> Vec<Scalar> {
9676    // Per br-frankenpandas-x0x91: Timedelta64 preserves dtype.
9677    if is_timedelta_input(values) {
9678        return timedelta_cumulative_extrema(
9679            values,
9680            i64::MIN,
9681            TemporalFamily::Timedelta,
9682            |acc, x| acc.min(x),
9683        );
9684    }
9685    // br-frankenpandas-axhhk / -d7zjp: Datetime64 and Period siblings.
9686    if let Some((_, family)) = collect_temporal_backing(values) {
9687        return timedelta_cumulative_extrema(values, i64::MIN, family, |acc, x| acc.min(x));
9688    }
9689    let mut out = Vec::with_capacity(values.len());
9690    let mut running: Option<f64> = None;
9691    for v in values {
9692        if v.is_missing() {
9693            out.push(Scalar::Null(NullKind::NaN));
9694            continue;
9695        }
9696        match v.to_f64() {
9697            Ok(x) if !x.is_nan() => {
9698                let new_val = match running {
9699                    Some(prev) => prev.min(x),
9700                    None => x,
9701                };
9702                running = Some(new_val);
9703                out.push(Scalar::Float64(new_val));
9704            }
9705            _ => out.push(Scalar::Null(NullKind::NaN)),
9706        }
9707    }
9708    out
9709}
9710
9711/// Linear-interpolation quantile over non-missing numeric values.
9712///
9713/// Matches `np.nanquantile(values, q)` with `interpolation='linear'`.
9714/// Returns `Null(NaN)` for empty inputs or when `q` is outside
9715/// `[0.0, 1.0]`.
9716pub fn nanquantile(values: &[Scalar], q: f64) -> Scalar {
9717    if !(0.0..=1.0).contains(&q) {
9718        return Scalar::Null(NullKind::NaN);
9719    }
9720    // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
9721    // Timedelta64 with linear-interpolated ns. Was silently NaN before.
9722    if let Some((mut td, make)) = collect_temporal_backing(values) {
9723        if td.is_empty() {
9724            return make.nat();
9725        }
9726        let n = td.len();
9727        if n == 1 {
9728            return float_ns_to_temporal(td[0], make);
9729        }
9730        let pos = q * (n - 1) as f64;
9731        let lo = pos.floor() as usize;
9732        let hi = pos.ceil() as usize;
9733        // O(n) selection instead of a full sort (see the numeric arm below):
9734        // select the lo-th order statistic; the (lo+1)-th is the MIN of the
9735        // right partition. Bit-identical (finite ns, values-only order stats).
9736        let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9737        let (_left, lo_ref, right) = td.select_nth_unstable_by(lo, cmp);
9738        let lo_val = *lo_ref;
9739        let ns = if lo == hi {
9740            lo_val
9741        } else {
9742            let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9743            let weight = pos - lo as f64;
9744            lo_val + (hi_val - lo_val) * weight
9745        };
9746        return float_ns_to_temporal(ns, make);
9747    }
9748    let mut nums = collect_finite(values);
9749    if nums.is_empty() {
9750        return Scalar::Null(NullKind::NaN);
9751    }
9752    let n = nums.len();
9753    if n == 1 {
9754        return Scalar::Float64(nums[0]);
9755    }
9756    let pos = q * (n - 1) as f64;
9757    let lo = pos.floor() as usize;
9758    let hi = pos.ceil() as usize;
9759    // O(n) selection instead of a full sort: select the `lo`-th order statistic;
9760    // when interpolation is needed (hi == lo+1) the (lo+1)-th smallest is the
9761    // MIN of the right partition. Bit-identical to the sort path (same
9762    // nums[lo]/nums[hi] values, since order statistics depend only on values).
9763    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9764    let (_left, lo_ref, right) = nums.select_nth_unstable_by(lo, cmp);
9765    let lo_val = *lo_ref;
9766    if lo == hi {
9767        return Scalar::Float64(lo_val);
9768    }
9769    let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9770    let weight = pos - lo as f64;
9771    Scalar::Float64(lo_val + (hi_val - lo_val) * weight)
9772}
9773
9774/// Position (in the original slice) of the non-missing maximum.
9775///
9776/// Matches `np.nanargmax`. Returns `None` if every value is missing.
9777/// Ties resolve to the first position seen (matching numpy).
9778pub fn nanargmax(values: &[Scalar]) -> Option<usize> {
9779    // Compare typed 64-bit families directly: f64 coercion loses ordering for
9780    // adjacent Int64 values beyond the 53-bit exactness boundary.
9781    // br-frankenpandas-axhhk: Datetime64 belongs here too — it not only loses
9782    // ordering under f64, its to_f64() errors outright, so it returned None.
9783    if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9784        return nanarg_i64(values, true);
9785    }
9786    // br-frankenpandas-2h9dm: Intervals order lexicographically by
9787    // (left, right) and fit neither the i64 walk above nor the f64 fallback
9788    // below, whose to_f64() errors on them — so they returned None.
9789    if is_interval_input(values) {
9790        return nanarg_interval(values, true);
9791    }
9792    let mut best: Option<(usize, f64)> = None;
9793    for (i, v) in values.iter().enumerate() {
9794        if v.is_missing() {
9795            continue;
9796        }
9797        if let Ok(x) = v.to_f64() {
9798            if x.is_nan() {
9799                continue;
9800            }
9801            match best {
9802                None => best = Some((i, x)),
9803                Some((_, cur)) if x > cur => best = Some((i, x)),
9804                _ => {}
9805            }
9806        }
9807    }
9808    best.map(|(i, _)| i)
9809}
9810
9811/// Position (in the original slice) of the non-missing minimum.
9812///
9813/// Matches `np.nanargmin`. Returns `None` if every value is missing.
9814pub fn nanargmin(values: &[Scalar]) -> Option<usize> {
9815    // See nanargmax: preserve exact ordering for typed 64-bit families
9816    // (Datetime64 included, per br-frankenpandas-axhhk).
9817    if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9818        return nanarg_i64(values, false);
9819    }
9820    // br-frankenpandas-2h9dm: Interval sibling of the branch in `nanargmax`.
9821    if is_interval_input(values) {
9822        return nanarg_interval(values, false);
9823    }
9824    let mut best: Option<(usize, f64)> = None;
9825    for (i, v) in values.iter().enumerate() {
9826        if v.is_missing() {
9827            continue;
9828        }
9829        if let Ok(x) = v.to_f64() {
9830            if x.is_nan() {
9831                continue;
9832            }
9833            match best {
9834                None => best = Some((i, x)),
9835                Some((_, cur)) if x < cur => best = Some((i, x)),
9836                _ => {}
9837            }
9838        }
9839    }
9840    best.map(|(i, _)| i)
9841}
9842
9843/// Count of unique non-missing values.
9844pub fn nannunique(values: &[Scalar]) -> Scalar {
9845    use rustc_hash::FxHashSet;
9846    #[derive(Hash, PartialEq, Eq)]
9847    enum ScalarKey<'a> {
9848        Bool(bool),
9849        Int64(i64),
9850        FloatBits(u64),
9851        Utf8(&'a str),
9852        Timedelta64(i64),
9853        Datetime64(i64),
9854        Period(i64, PeriodFreq),
9855        Interval(u64, u64, IntervalClosed),
9856        // An object cell counts by its repr (pandas hashes the object; a
9857        // list would be unhashable there).
9858        Object(String),
9859    }
9860
9861    let mut seen = FxHashSet::default();
9862    for val in values {
9863        if val.is_missing() {
9864            continue;
9865        }
9866        let key = match val {
9867            Scalar::Bool(v) => ScalarKey::Bool(*v),
9868            Scalar::Int64(v) => ScalarKey::Int64(*v),
9869            Scalar::Float64(v) => {
9870                let normalized = if *v == 0.0 { 0.0 } else { *v };
9871                ScalarKey::FloatBits(normalized.to_bits())
9872            }
9873            Scalar::Utf8(v) => ScalarKey::Utf8(v.as_str()),
9874            Scalar::Timedelta64(v) => ScalarKey::Timedelta64(*v),
9875            Scalar::Datetime64(v) => ScalarKey::Datetime64(*v),
9876            Scalar::Period(p) => ScalarKey::Period(p.ordinal, p.freq),
9877            Scalar::Interval(v) => ScalarKey::Interval(
9878                normalized_float_bits(v.left),
9879                normalized_float_bits(v.right),
9880                v.closed,
9881            ),
9882            Scalar::Object(object) => ScalarKey::Object(object.repr()),
9883            Scalar::Null(_) => continue,
9884        };
9885        seen.insert(key);
9886    }
9887    Scalar::Int64(seen.len() as i64)
9888}
9889
9890fn normalized_float_bits(value: f64) -> u64 {
9891    let normalized = if value == 0.0 { 0.0 } else { value };
9892    normalized.to_bits()
9893}
9894
9895// ── Interval types (br-frankenpandas-j8k4 Phase 1) ──────────────────────
9896//
9897// Scaffolding for pandas `pd.Interval` / `pd.IntervalIndex` / `pd.IntervalDtype`.
9898//
9899// Phase 1 ships float-valued intervals only (matches `cut`/`qcut` output on
9900// numeric bins — the dominant pandas use case). Generic-subtype intervals
9901// over Int64 / Timestamp are deferred to Phase 2 alongside the DType::Interval
9902// enum-variant wiring. See br-j8k4 for the phased roadmap.
9903//
9904// Semantics mirror pandas: closed tells which endpoints are included.
9905//   Left    → [left, right)
9906//   Right   → (left, right]       ← pandas default
9907//   Both    → [left, right]
9908//   Neither → (left, right)
9909
9910/// Endpoint-inclusion policy for an `Interval`.
9911///
9912/// Matches pandas `pd.Interval.closed` / `pd.IntervalDtype.closed` string
9913/// values ("left" / "right" / "both" / "neither").
9914#[derive(
9915    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
9916)]
9917#[serde(rename_all = "snake_case")]
9918#[non_exhaustive]
9919pub enum IntervalClosed {
9920    /// `[left, right)` — left-inclusive, right-exclusive.
9921    Left,
9922    /// `(left, right]` — left-exclusive, right-inclusive. Pandas default.
9923    #[default]
9924    Right,
9925    /// `[left, right]` — both endpoints included.
9926    Both,
9927    /// `(left, right)` — neither endpoint included.
9928    Neither,
9929}
9930
9931impl IntervalClosed {
9932    /// Left endpoint included?
9933    #[must_use]
9934    pub fn left_closed(self) -> bool {
9935        matches!(self, Self::Left | Self::Both)
9936    }
9937
9938    /// Right endpoint included?
9939    #[must_use]
9940    pub fn right_closed(self) -> bool {
9941        matches!(self, Self::Right | Self::Both)
9942    }
9943}
9944
9945impl std::fmt::Display for IntervalClosed {
9946    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9947        match self {
9948            Self::Left => write!(f, "left"),
9949            Self::Right => write!(f, "right"),
9950            Self::Both => write!(f, "both"),
9951            Self::Neither => write!(f, "neither"),
9952        }
9953    }
9954}
9955
9956/// The type of an interval's endpoints, pandas' `interval[int64]` or
9957/// `interval[float64]` subtype: integer endpoints print without '.0'
9958/// (`pd.cut(s, [0, 3, 6])` is `(0, 3]`, where float edges are `(0.0, 3.0]`).
9959/// The endpoints themselves are `f64` either way (fvsao.54).
9960#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
9961#[serde(rename_all = "snake_case")]
9962pub enum IntervalSubtype {
9963    #[default]
9964    Float64,
9965    Int64,
9966}
9967
9968impl IntervalSubtype {
9969    /// Whether this is the float subtype (serde skips it, the default).
9970    #[must_use]
9971    pub const fn is_float(&self) -> bool {
9972        matches!(self, Self::Float64)
9973    }
9974
9975    /// The subtype's dtype name ('int64' / 'float64').
9976    #[must_use]
9977    pub const fn name(&self) -> &'static str {
9978        match self {
9979            Self::Float64 => "float64",
9980            Self::Int64 => "int64",
9981        }
9982    }
9983}
9984
9985/// A bounded numeric interval between two `f64` endpoints.
9986///
9987/// Matches `pd.Interval(left, right, closed)` on the numeric-subtype path.
9988/// Accessors match pandas: `.left`, `.right`, `.closed`, `.length`, `.mid`,
9989/// `.contains`, `.is_empty`, `.overlaps`. Equality ignores the `subtype`, as
9990/// pandas' `Interval(0, 3) == Interval(0.0, 3.0)`.
9991#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
9992pub struct Interval {
9993    pub left: f64,
9994    pub right: f64,
9995    #[serde(default)]
9996    pub closed: IntervalClosed,
9997    /// The endpoints' type as pandas reports and prints it.
9998    #[serde(default, skip_serializing_if = "IntervalSubtype::is_float")]
9999    pub subtype: IntervalSubtype,
10000}
10001
10002impl PartialEq for Interval {
10003    fn eq(&self, other: &Self) -> bool {
10004        self.left == other.left && self.right == other.right && self.closed == other.closed
10005    }
10006}
10007
10008/// An interval as a label (an IntervalIndex's; br-frankenpandas-c27hq): its
10009/// endpoints compare as floats, so only an interval with a NaN endpoint,
10010/// which pandas never builds, is unequal to itself.
10011impl Eq for Interval {}
10012
10013impl Interval {
10014    /// An endpoint as it compares: -0.0 is 0.0, as `==` has it.
10015    fn endpoint_key(value: f64) -> f64 {
10016        if value == 0.0 { 0.0 } else { value }
10017    }
10018}
10019
10020/// Hashed as it compares: the endpoints (-0.0 as 0.0) and the closed side;
10021/// the subtype is not part of the value.
10022impl std::hash::Hash for Interval {
10023    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
10024        Self::endpoint_key(self.left).to_bits().hash(state);
10025        Self::endpoint_key(self.right).to_bits().hash(state);
10026        self.closed.hash(state);
10027    }
10028}
10029
10030/// pandas' IntervalIndex order: by the left endpoint, then the right, then
10031/// the closed side.
10032impl Ord for Interval {
10033    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
10034        Self::endpoint_key(self.left)
10035            .total_cmp(&Self::endpoint_key(other.left))
10036            .then_with(|| {
10037                Self::endpoint_key(self.right).total_cmp(&Self::endpoint_key(other.right))
10038            })
10039            .then_with(|| self.closed.cmp(&other.closed))
10040    }
10041}
10042
10043impl PartialOrd for Interval {
10044    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
10045        Some(self.cmp(other))
10046    }
10047}
10048
10049impl Interval {
10050    /// Construct an interval. No validation on `left <= right` — pandas also
10051    /// accepts reversed intervals (they're non-empty only if empty-by-design).
10052    #[must_use]
10053    pub const fn new(left: f64, right: f64, closed: IntervalClosed) -> Self {
10054        Self {
10055            left,
10056            right,
10057            closed,
10058            subtype: IntervalSubtype::Float64,
10059        }
10060    }
10061
10062    /// This interval with integer endpoints (pandas' `interval[int64]`)
10063    /// when both are whole numbers; unchanged otherwise.
10064    #[must_use]
10065    pub fn with_int_endpoints(self) -> Self {
10066        if self.left.fract() == 0.0 && self.right.fract() == 0.0 {
10067            Self {
10068                subtype: IntervalSubtype::Int64,
10069                ..self
10070            }
10071        } else {
10072            self
10073        }
10074    }
10075
10076    /// `right - left` (pandas `.length`). Negative for reversed intervals.
10077    #[must_use]
10078    pub fn length(&self) -> f64 {
10079        self.right - self.left
10080    }
10081
10082    /// Midpoint `(left + right) / 2` (pandas `.mid`).
10083    #[must_use]
10084    pub fn mid(&self) -> f64 {
10085        (self.left + self.right) / 2.0
10086    }
10087
10088    /// Empty iff endpoints coincide AND at least one side is open.
10089    /// Pandas semantics: `pd.Interval(3, 3, 'right').is_empty → True`.
10090    #[must_use]
10091    pub fn is_empty(&self) -> bool {
10092        self.left == self.right && !matches!(self.closed, IntervalClosed::Both)
10093    }
10094
10095    /// Does `value` fall inside this interval?
10096    ///
10097    /// NaN always returns false, matching pandas `pd.Interval.__contains__`
10098    /// behavior (NaN doesn't compare equal to anything).
10099    #[must_use]
10100    pub fn contains(&self, value: f64) -> bool {
10101        if value.is_nan() {
10102            return false;
10103        }
10104        let left_ok = if self.closed.left_closed() {
10105            value >= self.left
10106        } else {
10107            value > self.left
10108        };
10109        let right_ok = if self.closed.right_closed() {
10110            value <= self.right
10111        } else {
10112            value < self.right
10113        };
10114        left_ok && right_ok
10115    }
10116
10117    /// Do `self` and `other` share any point?
10118    ///
10119    /// Matches `pd.Interval.overlaps(other)`. Two intervals overlap iff the
10120    /// max of their lefts is less than the min of their rights, with
10121    /// endpoint-inclusion determining the strictness of the comparison when
10122    /// they touch exactly.
10123    #[must_use]
10124    pub fn overlaps(&self, other: &Self) -> bool {
10125        if self.left > other.right || other.left > self.right {
10126            return false;
10127        }
10128        // Touching-at-a-point: overlap iff both sides at that touchpoint are closed.
10129        if self.right == other.left {
10130            return self.closed.right_closed() && other.closed.left_closed();
10131        }
10132        if other.right == self.left {
10133            return other.closed.right_closed() && self.closed.left_closed();
10134        }
10135        true
10136    }
10137
10138    /// Parse an interval string. Supports bracket notation:
10139    /// - '[0, 1]' -> closed on both ends
10140    /// - '(0, 1)' -> open on both ends
10141    /// - '[0, 1)' -> closed left, open right (pandas default)
10142    /// - '(0, 1]' -> open left, closed right
10143    pub fn parse(s: &str) -> Result<Self, TypeError> {
10144        let s = s.trim();
10145        if s.len() < 5 {
10146            return Err(TypeError::ValueNotParseable {
10147                value: s.to_string(),
10148                target: "Interval".to_string(),
10149            });
10150        }
10151
10152        let first_char = s.chars().next().unwrap();
10153        let last_char = s.chars().last().unwrap();
10154
10155        let left_closed = match first_char {
10156            '[' => true,
10157            '(' => false,
10158            _ => {
10159                return Err(TypeError::ValueNotParseable {
10160                    value: s.to_string(),
10161                    target: "Interval".to_string(),
10162                });
10163            }
10164        };
10165
10166        let right_closed = match last_char {
10167            ']' => true,
10168            ')' => false,
10169            _ => {
10170                return Err(TypeError::ValueNotParseable {
10171                    value: s.to_string(),
10172                    target: "Interval".to_string(),
10173                });
10174            }
10175        };
10176
10177        let closed = match (left_closed, right_closed) {
10178            (true, true) => IntervalClosed::Both,
10179            (true, false) => IntervalClosed::Left,
10180            (false, true) => IntervalClosed::Right,
10181            (false, false) => IntervalClosed::Neither,
10182        };
10183
10184        let inner = &s[1..s.len() - 1];
10185        let Some((left_text, right_text)) = inner.split_once(',') else {
10186            return Err(TypeError::ValueNotParseable {
10187                value: s.to_string(),
10188                target: "Interval".to_string(),
10189            });
10190        };
10191        if right_text.contains(',') {
10192            return Err(TypeError::ValueNotParseable {
10193                value: s.to_string(),
10194                target: "Interval".to_string(),
10195            });
10196        }
10197
10198        let left: f64 = left_text
10199            .trim()
10200            .parse()
10201            .map_err(|_| TypeError::ValueNotParseable {
10202                value: s.to_string(),
10203                target: "Interval".to_string(),
10204            })?;
10205
10206        let right: f64 = right_text
10207            .trim()
10208            .parse()
10209            .map_err(|_| TypeError::ValueNotParseable {
10210                value: s.to_string(),
10211                target: "Interval".to_string(),
10212            })?;
10213
10214        Ok(Self::new(left, right, closed))
10215    }
10216}
10217
10218impl std::fmt::Display for Interval {
10219    /// Matches `str(pd.Interval(...))`: `interval[float64]` endpoints render
10220    /// with Python `str(float)` semantics, so whole numbers KEEP ".0"
10221    /// (`str(pd.Interval(0.0, 5.0, 'right'))` is `"(0.0, 5.0]"`, not `"(0, 5]"`).
10222    /// Verified vs pandas 2.2.3 across whole/fractional/negative/scientific
10223    /// endpoints. (br-frankenpandas-5xw1b) The `interval[int64]` subtype
10224    /// prints integers (`"(0, 5]"`).
10225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10226        let left_bracket = if self.closed.left_closed() { '[' } else { '(' };
10227        let right_bracket = if self.closed.right_closed() { ']' } else { ')' };
10228        // The int64 subtype prints its endpoints as integers ('(0, 3]').
10229        #[allow(clippy::cast_possible_truncation)] // whole numbers, checked
10230        let endpoint = |value: f64| match self.subtype {
10231            IntervalSubtype::Int64 if value.fract() == 0.0 => format!("{}", value as i64),
10232            _ => float_to_string_for_astype(value),
10233        };
10234        write!(
10235            f,
10236            "{left_bracket}{}, {}{right_bracket}",
10237            endpoint(self.left),
10238            endpoint(self.right)
10239        )
10240    }
10241}
10242
10243// ── interval_range builders (br-frankenpandas-xaom — Phase 2 of j8k4) ────
10244
10245/// Build `periods` equal-width intervals spanning `[start, end]`.
10246///
10247/// Matches `pd.interval_range(start, end, periods=N, closed=...)` for the
10248/// numeric-subtype case. Returns exactly `periods` intervals; when
10249/// `periods == 0` or `start >= end`, returns an empty vector (matches
10250/// pandas's empty IntervalIndex).
10251///
10252/// ```
10253/// use fp_types::{interval_range_by_periods, IntervalClosed};
10254/// let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
10255/// assert_eq!(bins.len(), 5);
10256/// assert_eq!(bins[0].left, 0.0);
10257/// assert_eq!(bins[0].right, 2.0);
10258/// assert_eq!(bins[4].right, 10.0);
10259/// ```
10260#[must_use]
10261pub fn interval_range_by_periods(
10262    start: f64,
10263    end: f64,
10264    periods: usize,
10265    closed: IntervalClosed,
10266) -> Vec<Interval> {
10267    if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
10268        return Vec::new();
10269    }
10270    let step = (end - start) / (periods as f64);
10271    let mut out = Vec::with_capacity(periods);
10272    for i in 0..periods {
10273        let left = start + step * (i as f64);
10274        // Use end exactly for the final right edge to avoid float drift.
10275        let right = if i + 1 == periods {
10276            end
10277        } else {
10278            start + step * ((i + 1) as f64)
10279        };
10280        out.push(Interval::new(left, right, closed));
10281    }
10282    out
10283}
10284
10285/// Build equal-`step`-width intervals spanning `[start, end]`.
10286///
10287/// Matches `pd.interval_range(start, end, freq=step, closed=...)` for the
10288/// numeric-subtype case. `step` must be finite and positive; `(end - start)`
10289/// must be an integer multiple of `step` (within float tolerance) — pandas
10290/// raises `ValueError` otherwise; this fn returns `Err(TypeError::IntervalStepDoesNotDivide)`.
10291///
10292/// Returns an empty vector when `start == end` (matches pandas' zero-bin
10293/// IntervalIndex); returns an empty vector when `start > end` (pandas also
10294/// returns empty rather than erroring in this case).
10295pub fn interval_range_by_step(
10296    start: f64,
10297    end: f64,
10298    step: f64,
10299    closed: IntervalClosed,
10300) -> Result<Vec<Interval>, TypeError> {
10301    if !step.is_finite() || !step.is_sign_positive() || step == 0.0 {
10302        return Err(TypeError::InvalidIntervalStep { step });
10303    }
10304    if !start.is_finite() || !end.is_finite() || start >= end {
10305        return Ok(Vec::new());
10306    }
10307    let span = end - start;
10308    let periods_f = span / step;
10309    let periods = periods_f.round() as i64;
10310    if periods <= 0 {
10311        return Ok(Vec::new());
10312    }
10313    let reconstructed = step * (periods as f64);
10314    // Relative tolerance: allow float-rounding noise proportional to span.
10315    if (span - reconstructed).abs() > span.abs() * 1e-9 + 1e-12 {
10316        return Err(TypeError::IntervalStepDoesNotDivide { step, span });
10317    }
10318    let periods = periods as usize;
10319    let mut out = Vec::with_capacity(periods);
10320    for i in 0..periods {
10321        let left = start + step * (i as f64);
10322        let right = if i + 1 == periods {
10323            end
10324        } else {
10325            start + step * ((i + 1) as f64)
10326        };
10327        out.push(Interval::new(left, right, closed));
10328    }
10329    Ok(out)
10330}
10331
10332/// Build equal-width intervals spanning a range, matching `pd.interval_range`.
10333///
10334/// Of the four parameters `start`, `end`, `periods`, and `freq`, exactly three must
10335/// be specified (`Some`). `closed` defaults to `IntervalClosed::Right` when `None`.
10336///
10337/// # Errors
10338/// Returns `TypeError::IntervalRangeParameterCount` if not exactly 3 of the 4 parameters
10339/// are specified.
10340/// Returns `TypeError::InvalidIntervalStep` if `freq` is not finite, not positive, or zero.
10341/// Returns `TypeError::IntervalStepDoesNotDivide` if `start`, `end`, and `freq` are given
10342/// but `(end - start)` is not an integer multiple of `freq`.
10343pub fn interval_range(
10344    start: Option<f64>,
10345    end: Option<f64>,
10346    periods: Option<usize>,
10347    freq: Option<f64>,
10348    closed: Option<IntervalClosed>,
10349) -> Result<Vec<Interval>, TypeError> {
10350    let count = usize::from(start.is_some())
10351        + usize::from(end.is_some())
10352        + usize::from(periods.is_some())
10353        + usize::from(freq.is_some());
10354    if count != 3 {
10355        return Err(TypeError::IntervalRangeParameterCount);
10356    }
10357    let closed = closed.unwrap_or(IntervalClosed::Right);
10358
10359    match (start, end, periods, freq) {
10360        (Some(start), Some(end), Some(periods), None) => {
10361            Ok(interval_range_by_periods(start, end, periods, closed))
10362        }
10363        (Some(start), Some(end), None, Some(freq)) => {
10364            interval_range_by_step(start, end, freq, closed)
10365        }
10366        (Some(start), None, Some(periods), Some(freq)) => {
10367            if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10368                return Err(TypeError::InvalidIntervalStep { step: freq });
10369            }
10370            if !start.is_finite() || periods == 0 {
10371                return Ok(Vec::new());
10372            }
10373            let mut out = Vec::with_capacity(periods);
10374            for i in 0..periods {
10375                let left = start + freq * (i as f64);
10376                let right = start + freq * ((i + 1) as f64);
10377                out.push(Interval::new(left, right, closed));
10378            }
10379            Ok(out)
10380        }
10381        (None, Some(end), Some(periods), Some(freq)) => {
10382            if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10383                return Err(TypeError::InvalidIntervalStep { step: freq });
10384            }
10385            if !end.is_finite() || periods == 0 {
10386                return Ok(Vec::new());
10387            }
10388            let start = end - freq * (periods as f64);
10389            let mut out = Vec::with_capacity(periods);
10390            for i in 0..periods {
10391                let left = start + freq * (i as f64);
10392                let right = if i + 1 == periods {
10393                    end
10394                } else {
10395                    start + freq * ((i + 1) as f64)
10396                };
10397                out.push(Interval::new(left, right, closed));
10398            }
10399            Ok(out)
10400        }
10401        _ => Err(TypeError::IntervalRangeParameterCount),
10402    }
10403}
10404
10405// ── Period types (br-frankenpandas-epoj Phase 1) ────────────────────────
10406//
10407// Scaffolding for pandas `pd.Period` / `pd.PeriodIndex` / `pd.PeriodDtype`.
10408//
10409// A Period is a calendar *span* (Q1 2024, Jan 2024, 2024-03-15), distinct
10410// from a Timestamp (an instant). Phase 1 ships the PeriodFreq enum +
10411// Period struct with ordinal-based arithmetic (Period + n, Period - Period),
10412// Display in pandas notation, and parse from standard strings. Calendar-
10413// conversion (ordinal ↔ ymd) and DType::Period wiring land in Phase 2.
10414
10415/// Period frequency code. Matches pandas offset alias core set.
10416///
10417/// The ordinal axis is frequency-specific: for Monthly, ordinal 0 is a
10418/// fixed anchor (pandas uses months since 1970-01). Phase 1 doesn't
10419/// commit to a specific epoch yet — the ordinal scheme is opaque until
10420/// Phase 2 wires calendar arithmetic. What Phase 1 DOES nail down is:
10421/// same-freq Periods compare + subtract; Period + i64 shifts by `n`
10422/// periods of the declared frequency.
10423#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10424#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
10425#[non_exhaustive]
10426pub enum PeriodFreq {
10427    /// `Y-<MON>` / `A` / `Y` — annual periods of a fiscal year ending in the
10428    /// month carried (1-12; `Y` is `Y-DEC`). The ordinal counts fiscal years
10429    /// from 1970: `Period('2024', 'Y-JUN')` spans 2023-07-01..2024-06-30.
10430    Annual(u8),
10431    /// `Q-<MON>` / `Q` — quarters of a fiscal year ending in the month
10432    /// carried (1-12; `Q` is `Q-DEC`): `Period('2025Q1', 'Q-JAN')` spans
10433    /// 2024-02-01..2024-04-30.
10434    Quarterly(u8),
10435    /// `M` — monthly periods.
10436    Monthly,
10437    /// `W-<DAY>` / `W` — weeks ending on the weekday carried (0 = Monday ..
10438    /// 6 = Sunday; `W` is `W-SUN`).
10439    Weekly(u8),
10440    /// `D` — daily periods.
10441    Daily,
10442    /// `B` — business-day periods.
10443    Business,
10444    /// `h` / `H` — hourly periods.
10445    Hourly,
10446    /// `min` / `T` — minutely periods.
10447    Minutely,
10448    /// `s` / `S` — secondly periods.
10449    Secondly,
10450    /// `ms` — millisecond periods. NOT `MS`, which pandas reads as month start.
10451    Milliseconds,
10452    /// `us` / `US` — microsecond periods.
10453    Microseconds,
10454    /// `ns` / `NS` — nanosecond periods.
10455    Nanoseconds,
10456}
10457
10458/// The month abbreviations pandas anchors annual / quarterly frequencies on.
10459const PERIOD_MONTHS: [&str; 12] = [
10460    "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
10461];
10462/// The weekday abbreviations pandas anchors weekly frequencies on, Monday 0.
10463const PERIOD_WEEKDAYS: [&str; 7] = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];
10464
10465impl PeriodFreq {
10466    /// `Y` / `Y-DEC`: calendar years.
10467    pub const ANNUAL: Self = Self::Annual(12);
10468    /// `Q` / `Q-DEC`: calendar quarters.
10469    pub const QUARTERLY: Self = Self::Quarterly(12);
10470    /// `W` / `W-SUN`: weeks Monday to Sunday.
10471    pub const WEEKLY: Self = Self::Weekly(6);
10472
10473    /// Months a date's month count moves forward to land on its fiscal
10474    /// calendar: a fiscal year ending in month `m` starts in month `m + 1`,
10475    /// so `(months since 1970-01 + shift)` divided by 12 (3) is the annual
10476    /// (quarterly) ordinal. 0 for a year ending in December and for every
10477    /// unanchored frequency.
10478    #[must_use]
10479    pub const fn fiscal_month_shift(self) -> i64 {
10480        match self {
10481            Self::Annual(month) | Self::Quarterly(month) => (12 - (month as i64 % 12)) % 12,
10482            _ => 0,
10483        }
10484    }
10485
10486    /// Days a week starts after the Monday of `W-SUN`'s week: a week ending
10487    /// on weekday `d` (Monday 0) starts on `d + 1`, so `W-MON` weeks start a
10488    /// day later and `W-SAT` ones six days later (a Sunday). 0 for `W-SUN`
10489    /// and every other frequency.
10490    #[must_use]
10491    pub const fn week_start_shift(self) -> i64 {
10492        match self {
10493            Self::Weekly(day) => (day as i64 % 7 + 1) % 7,
10494            _ => 0,
10495        }
10496    }
10497
10498    /// The anchored form `prefix-ANCHOR` of a frequency alias (`Y-JUN`,
10499    /// `Q-JAN`, `W-MON`), with pandas' deprecated `A-` annual spelling.
10500    fn parse_anchored(alias: &str) -> Option<Self> {
10501        let (prefix, anchor) = alias.split_once('-')?;
10502        let month = PERIOD_MONTHS.iter().position(|name| *name == anchor);
10503        let day = PERIOD_WEEKDAYS.iter().position(|name| *name == anchor);
10504        match (prefix, month, day) {
10505            ("A" | "Y", Some(month), _) => Some(Self::Annual(month as u8 + 1)),
10506            ("Q", Some(month), _) => Some(Self::Quarterly(month as u8 + 1)),
10507            ("W", _, Some(day)) => Some(Self::Weekly(day as u8)),
10508            _ => None,
10509        }
10510    }
10511
10512    /// Parse a pandas-style frequency alias. Recognizes the common subset
10513    /// (Y-<MON>/A/Y, Q-<MON>/Q, M, W-<DAY>/W, D, B, h/H, min/T, s/S) plus the
10514    /// sub-second units ms, us/US, ns/NS.
10515    ///
10516    /// Case-insensitive with ONE exception: bare `MS` is month start in pandas,
10517    /// not milliseconds, and is refused here the way pandas refuses it for
10518    /// `to_period`. See the check at the top of the body.
10519    pub fn parse(alias: &str) -> Option<Self> {
10520        // ⚠️ CASE MATTERS FOR EXACTLY ONE ALIAS, and this parser uppercases
10521        // everything. MEASURED, live pandas 2.2.3, Timestamp.to_period(f):
10522        //     'ms' -> millisecond      'Ms' -> millisecond
10523        //     'MS' -> ValueError       (it is month start, a date_range-only freq)
10524        //     'us' -> microsecond      'US' -> microsecond
10525        //     'ns' -> nanosecond       'NS' -> nanosecond
10526        // So only the fully-capitalised `MS` is excluded; every other casing of
10527        // "ms" is milliseconds, while us/ns are case-insensitive and belong in
10528        // the table below. Checked here, before the uppercase collapses it.
10529        if alias.eq_ignore_ascii_case("ms") && alias != "MS" {
10530            return Some(Self::Milliseconds);
10531        }
10532        match alias.to_ascii_uppercase().as_str() {
10533            "A" | "Y" | "ANNUAL" | "YEARLY" => Some(Self::ANNUAL),
10534            "Q" | "QUARTERLY" => Some(Self::QUARTERLY),
10535            "M" | "MONTHLY" => Some(Self::Monthly),
10536            "W" | "WEEKLY" => Some(Self::WEEKLY),
10537            "D" | "DAILY" => Some(Self::Daily),
10538            "B" | "BUSINESS" => Some(Self::Business),
10539            "H" | "HOURLY" => Some(Self::Hourly),
10540            "T" | "MIN" | "MINUTELY" => Some(Self::Minutely),
10541            "S" | "SECONDLY" => Some(Self::Secondly),
10542            "US" | "MICROSECOND" | "MICROSECONDS" => Some(Self::Microseconds),
10543            "NS" | "NANOSECOND" | "NANOSECONDS" => Some(Self::Nanoseconds),
10544            // The spelled-out form only; bare "MS" is deliberately absent, and
10545            // every other casing of it was taken above.
10546            "MILLISECOND" | "MILLISECONDS" => Some(Self::Milliseconds),
10547            anchored => Self::parse_anchored(anchored),
10548        }
10549    }
10550
10551    /// Canonical pandas alias string.
10552    #[must_use]
10553    pub const fn alias(self) -> &'static str {
10554        const ANNUAL: [&str; 12] = [
10555            "Y-JAN", "Y-FEB", "Y-MAR", "Y-APR", "Y-MAY", "Y-JUN", "Y-JUL", "Y-AUG", "Y-SEP",
10556            "Y-OCT", "Y-NOV", "Y-DEC",
10557        ];
10558        const QUARTERLY: [&str; 12] = [
10559            "Q-JAN", "Q-FEB", "Q-MAR", "Q-APR", "Q-MAY", "Q-JUN", "Q-JUL", "Q-AUG", "Q-SEP",
10560            "Q-OCT", "Q-NOV", "Q-DEC",
10561        ];
10562        const WEEKLY: [&str; 7] = [
10563            "W-MON", "W-TUE", "W-WED", "W-THU", "W-FRI", "W-SAT", "W-SUN",
10564        ];
10565        match self {
10566            Self::Annual(month) => ANNUAL[(month as usize + 11) % 12],
10567            Self::Quarterly(month) => QUARTERLY[(month as usize + 11) % 12],
10568            Self::Monthly => "M",
10569            Self::Weekly(day) => WEEKLY[day as usize % 7],
10570            Self::Daily => "D",
10571            Self::Business => "B",
10572            Self::Hourly => "h",
10573            Self::Minutely => "min",
10574            Self::Secondly => "s",
10575            Self::Milliseconds => "ms",
10576            Self::Microseconds => "us",
10577            Self::Nanoseconds => "ns",
10578        }
10579    }
10580
10581    /// Resolution word for `PeriodIndex.resolution`, or `None` where pandas has
10582    /// no answer.
10583    ///
10584    /// ⚠️ THIS IS NOT THE ALIAS TABLE. pandas' `.resolution` names the period's
10585    /// *component*, in the same vocabulary `DatetimeIndex::resolution` already
10586    /// uses here -- it is not the frequency string, which is what
10587    /// [`PeriodFreq::alias`] is for. MEASURED, live pandas 2.2.3, one-element
10588    /// `PeriodIndex` per freq:
10589    ///     Y   -> 'year'        Q   -> 'quarter'     M  -> 'month'
10590    ///     D   -> 'day'         h   -> 'hour'        min-> 'minute'
10591    ///     s   -> 'second'
10592    ///     W   -> raises AttributeError
10593    ///     B   -> raises AttributeError
10594    /// Every arm below previously returned the alias instead ("A-DEC", "M", "H",
10595    /// "T", "S", ...), so all nine disagreed with the incumbent; W and B answered
10596    /// where pandas refuses. The refusal is modelled as `None` rather than a
10597    /// wrong word, because the caller already returns `Option` for the empty
10598    /// index and pandas' own failure there is an absence, not a value.
10599    #[must_use]
10600    pub const fn resolution(self) -> Option<&'static str> {
10601        match self {
10602            Self::Annual(_) => Some("year"),
10603            Self::Quarterly(_) => Some("quarter"),
10604            Self::Monthly => Some("month"),
10605            Self::Daily => Some("day"),
10606            Self::Hourly => Some("hour"),
10607            Self::Minutely => Some("minute"),
10608            Self::Secondly => Some("second"),
10609            Self::Milliseconds => Some("millisecond"),
10610            Self::Microseconds => Some("microsecond"),
10611            Self::Nanoseconds => Some("nanosecond"),
10612            // pandas' Week and BusinessDay offsets carry no `_resolution_obj`,
10613            // so `.resolution` raises AttributeError rather than answering.
10614            Self::Weekly(_) | Self::Business => None,
10615        }
10616    }
10617}
10618
10619impl std::fmt::Display for PeriodFreq {
10620    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10621        f.write_str(self.alias())
10622    }
10623}
10624
10625/// A single pandas-style Period value.
10626///
10627/// Stored as an integer ordinal on a frequency-specific axis plus the
10628/// frequency code. Two Periods with different `freq` are incompatible —
10629/// arithmetic and comparison require same-freq operands. The derived order
10630/// (ordinal, then freq) is a total one for index labels (45fzr): within one
10631/// freq it is the periods' own.
10632#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10633pub struct Period {
10634    pub ordinal: i64,
10635    pub freq: PeriodFreq,
10636}
10637
10638impl Period {
10639    #[must_use]
10640    pub const fn new(ordinal: i64, freq: PeriodFreq) -> Self {
10641        Self { ordinal, freq }
10642    }
10643
10644    /// Whether this is NaT: the missing period, ordinal `i64::MIN` (what a
10645    /// missing element of a PeriodIndex holds and what renders `NaT`).
10646    #[must_use]
10647    pub const fn is_nat(&self) -> bool {
10648        self.ordinal == i64::MIN
10649    }
10650
10651    /// Integer position on this period's frequency axis, matching
10652    /// `pd.Period.ordinal`.
10653    #[must_use]
10654    pub const fn ordinal(&self) -> i64 {
10655        self.ordinal
10656    }
10657
10658    /// Frequency code for this period, matching `pd.Period.freq`.
10659    #[must_use]
10660    pub const fn freq(&self) -> PeriodFreq {
10661        self.freq
10662    }
10663
10664    /// Canonical pandas frequency alias, matching `pd.Period.freqstr`.
10665    #[must_use]
10666    pub const fn freqstr(&self) -> &'static str {
10667        self.freq.alias()
10668    }
10669
10670    /// Same-freq ordinal comparison. Returns `None` if `freq` differs —
10671    /// caller decides whether that's an error or a panic site.
10672    #[must_use]
10673    pub fn cmp_same_freq(&self, other: &Self) -> Option<std::cmp::Ordering> {
10674        if self.freq != other.freq {
10675            return None;
10676        }
10677        Some(self.ordinal.cmp(&other.ordinal))
10678    }
10679
10680    /// Shift by `n` periods of the current frequency.
10681    /// Matches `pd.Period + n` and `pd.Period - n`.
10682    #[must_use]
10683    pub fn shift(&self, n: i64) -> Self {
10684        Self {
10685            ordinal: self.ordinal.saturating_add(n),
10686            freq: self.freq,
10687        }
10688    }
10689
10690    /// Period-difference in units of the shared frequency.
10691    /// Returns `None` if `freq` differs (pandas raises IncompatibleFrequency).
10692    #[must_use]
10693    pub fn diff(&self, other: &Self) -> Option<i64> {
10694        if self.freq != other.freq {
10695            return None;
10696        }
10697        Some(self.ordinal.saturating_sub(other.ordinal))
10698    }
10699
10700    /// Parse common pandas `Period(...)` strings and infer the frequency.
10701    ///
10702    /// Supported forms mirror pandas' unambiguous scalar constructor cases:
10703    /// annual (`"2024"`), quarterly (`"2024Q1"`), monthly (`"2024-01"`),
10704    /// and daily (`"2024-01-15"`). The ordinal axes match pandas:
10705    /// 1970, 1970Q1, 1970-01, and 1970-01-01 all have ordinal 0.
10706    pub fn parse(s: &str) -> Result<Self, TypeError> {
10707        let trimmed = s.trim();
10708        if trimmed.eq_ignore_ascii_case("nat") {
10709            return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
10710        }
10711
10712        if let Some((year, quarter)) = parse_quarter_period(trimmed) {
10713            let ordinal = year
10714                .checked_sub(1970)
10715                .and_then(|offset| offset.checked_mul(4))
10716                .and_then(|base| base.checked_add(i64::from(quarter) - 1))
10717                .ok_or_else(|| TypeError::ValueNotParseable {
10718                    value: s.to_owned(),
10719                    target: "Period".to_owned(),
10720                })?;
10721            return Ok(Self::new(ordinal, PeriodFreq::QUARTERLY));
10722        }
10723
10724        if let Some((year, month, day)) = parse_ymd_period(trimmed) {
10725            let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
10726            return Ok(Self::new(ordinal, PeriodFreq::Daily));
10727        }
10728
10729        if let Some((year, month)) = parse_year_month_period(trimmed) {
10730            let ordinal = year
10731                .checked_sub(1970)
10732                .and_then(|offset| offset.checked_mul(12))
10733                .and_then(|base| base.checked_add(i64::from(month) - 1))
10734                .ok_or_else(|| TypeError::ValueNotParseable {
10735                    value: s.to_owned(),
10736                    target: "Period".to_owned(),
10737                })?;
10738            return Ok(Self::new(ordinal, PeriodFreq::Monthly));
10739        }
10740
10741        if let Some(year) = parse_annual_period(trimmed) {
10742            let ordinal = year
10743                .checked_sub(1970)
10744                .ok_or_else(|| TypeError::ValueNotParseable {
10745                    value: s.to_owned(),
10746                    target: "Period".to_owned(),
10747                })?;
10748            return Ok(Self::new(ordinal, PeriodFreq::ANNUAL));
10749        }
10750
10751        Err(TypeError::ValueNotParseable {
10752            value: s.to_owned(),
10753            target: "Period".to_owned(),
10754        })
10755    }
10756
10757    /// Pandas calendar string for this period, matching `str(pd.Period)`.
10758    ///
10759    /// Inverts the frequency-specific ordinal axes anchored at 1970:
10760    /// `1970`/`1970Q1`/`1970-01`/`1970-01-01`/`1970-01-01 00:00` all have
10761    /// ordinal 0. Returns `"NaT"` for the missing sentinel (`i64::MIN`).
10762    ///
10763    /// EVERY frequency is exact, Weekly and Business included.
10764    ///
10765    /// ⚠️ THOSE TWO ARE NOT INDEXED IN DAYS, which is what made them wrong until
10766    /// 08363d42f: a weekly ordinal counts WEEKS from the Monday 1969-12-22 and
10767    /// renders as the RANGE it spans (`2024-03-11/2024-03-17`), and a business
10768    /// ordinal counts BUSINESS DAYS at five per week. Both used to be handed to
10769    /// `civil_from_days`, which reads its argument as days since the epoch, so
10770    /// ordinal 2829 rendered `1977-09-30` instead of the week of 2024-03-15.
10771    ///
10772    /// The note that used to sit here called them "best-effort" and said neither
10773    /// was "reachable through the current parse/cast paths". The first half was
10774    /// a real limitation; the second was too narrow a survey. [`Self::parse`]
10775    /// indeed cannot produce them and neither can `cast_scalar` — but
10776    /// `DatetimeIndex::to_period("W")` builds them directly, and fp-index then
10777    /// renders those values through `Display` in `PeriodIndex::format`,
10778    /// `to_index`, `to_flat_index`, the `.str` accessor and the `get_loc` error
10779    /// message. The frequencies were unreachable only from the two paths the
10780    /// note happened to check.
10781    #[must_use]
10782    pub fn calendar_string(&self) -> String {
10783        let mut rendered = String::new();
10784        // `fmt::Write for String` is infallible.
10785        let _ = self.write_calendar(&mut rendered);
10786        rendered
10787    }
10788
10789    fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
10790        if self.ordinal == i64::MIN {
10791            return rendered.write_str("NaT");
10792        }
10793        let ord = self.ordinal;
10794        match self.freq {
10795            // An anchored year or quarter is labelled by the fiscal year its
10796            // ordinal counts (Period('2024', 'Y-JUN') ends 2024-06-30), so
10797            // the label does not depend on the anchor.
10798            PeriodFreq::Annual(_) => {
10799                let year = 1970 + ord;
10800                write!(rendered, "{year}")
10801            }
10802            PeriodFreq::Quarterly(_) => {
10803                let year = 1970 + ord.div_euclid(4);
10804                let quarter = ord.rem_euclid(4) + 1;
10805                write!(rendered, "{year}Q{quarter}")
10806            }
10807            PeriodFreq::Monthly => {
10808                let year = 1970 + ord.div_euclid(12);
10809                let month = ord.rem_euclid(12) + 1;
10810                write!(rendered, "{year:04}-{month:02}")
10811            }
10812            PeriodFreq::Daily => {
10813                let (y, m, d) = civil_from_days(ord);
10814                write!(rendered, "{y:04}-{m:02}-{d:02}")
10815            }
10816            // ⚠️ NOT DAYS SINCE THE EPOCH. A business ordinal counts BUSINESS
10817            // DAYS — five per week — so handing it to `civil_from_days` (which
10818            // wants a day count) put the label decades out: ordinal 14141 is
10819            // 2024-03-15 and rendered as 2008-09-19.
10820            //
10821            // The forward map in fp-index is
10822            //     days.div_euclid(7) * 5 + {Thu:0, Fri:1, Mon:2, Tue:3, Wed:4}
10823            // measured against pandas at every sampled date, so this is its
10824            // inverse: five ordinals per seven days, with the remainder naming a
10825            // weekday offset from the Thursday the epoch falls on.
10826            PeriodFreq::Business => {
10827                const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
10828                // Euclidean, so a pre-epoch ordinal keeps a remainder in 0..5:
10829                // ordinal -1 is 1969-12-31, not a negative weekday index.
10830                let offset = WEEKDAY_OFFSET[ord.rem_euclid(5) as usize];
10831                let days = ord.div_euclid(5).saturating_mul(7).saturating_add(offset);
10832                let (y, m, d) = civil_from_days(days);
10833                write!(rendered, "{y:04}-{m:02}-{d:02}")
10834            }
10835            // ⚠️ TWO BUGS IN ONE ARM. A weekly ordinal counts WEEKS from the
10836            // Monday 1969-12-22 (ten days before the epoch), and pandas renders a
10837            // weekly period as the RANGE it spans, not as one date:
10838            //     Period('2024-03-15', 'W') -> '2024-03-11/2024-03-17'
10839            // ordinal 2829, which this arm rendered as '1977-09-30'.
10840            //
10841            // fp-frame's `format_period_label` already produced the range form
10842            // for the same freq, so the two renderers disagreed on every weekly
10843            // period; this makes them agree.
10844            PeriodFreq::Weekly(_) => {
10845                // Days-since-epoch of the anchor Monday 1969-12-22; a week
10846                // ending on another weekday starts that many days later
10847                // (W-MON weeks run Tuesday..Monday).
10848                const WEEK_ANCHOR_DAY: i64 = -10;
10849                let start = ord
10850                    .saturating_mul(7)
10851                    .saturating_add(WEEK_ANCHOR_DAY + self.freq.week_start_shift());
10852                let (sy, sm, sd) = civil_from_days(start);
10853                let (ey, em, ed) = civil_from_days(start.saturating_add(6));
10854                write!(rendered, "{sy:04}-{sm:02}-{sd:02}/{ey:04}-{em:02}-{ed:02}")
10855            }
10856            PeriodFreq::Hourly => {
10857                let (y, m, d) = civil_from_days(ord.div_euclid(24));
10858                let hour = ord.rem_euclid(24);
10859                write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
10860            }
10861            PeriodFreq::Minutely => {
10862                let day = ord.div_euclid(1440);
10863                let mins = ord.rem_euclid(1440);
10864                let (y, m, d) = civil_from_days(day);
10865                write!(
10866                    rendered,
10867                    "{y:04}-{m:02}-{d:02} {:02}:{:02}",
10868                    mins / 60,
10869                    mins % 60
10870                )
10871            }
10872            PeriodFreq::Secondly => {
10873                let day = ord.div_euclid(86_400);
10874                let secs = ord.rem_euclid(86_400);
10875                let (y, m, d) = civil_from_days(day);
10876                write!(
10877                    rendered,
10878                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
10879                    secs / 3600,
10880                    (secs % 3600) / 60,
10881                    secs % 60
10882                )
10883            }
10884            // The three sub-second frequencies differ only in the divisor and
10885            // the FIXED fraction width -- pandas pads to the full width and
10886            // never trims trailing zeros. MEASURED on 2024-03-15 10:30:45.123456789:
10887            //     ms -> "2024-03-15 10:30:45.123"
10888            //     us -> "2024-03-15 10:30:45.123456"
10889            //     ns -> "2024-03-15 10:30:45.123456789"
10890            PeriodFreq::Milliseconds | PeriodFreq::Microseconds | PeriodFreq::Nanoseconds => {
10891                let (per_sec, width) = match self.freq {
10892                    PeriodFreq::Milliseconds => (1_000_i64, 3_usize),
10893                    PeriodFreq::Microseconds => (1_000_000_i64, 6_usize),
10894                    _ => (1_000_000_000_i64, 9_usize),
10895                };
10896                // 86_400 * 1e9 = 8.64e13 -- the widest of these is well inside i64.
10897                let per_day = 86_400 * per_sec;
10898                let day = ord.div_euclid(per_day);
10899                let rest = ord.rem_euclid(per_day);
10900                let secs = rest / per_sec;
10901                let frac = rest % per_sec;
10902                let (y, m, d) = civil_from_days(day);
10903                write!(
10904                    rendered,
10905                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{:0width$}",
10906                    secs / 3600,
10907                    (secs % 3600) / 60,
10908                    secs % 60,
10909                    frac,
10910                    width = width
10911                )
10912            }
10913        }
10914    }
10915}
10916
10917/// Convert a day count (days since 1970-01-01) to a proleptic-Gregorian
10918/// `(year, month, day)`, using Howard Hinnant's civil-from-days algorithm
10919/// (same kernel as `Timestamp::isoformat`); the year astronomical (0 is 1
10920/// BC).
10921#[must_use]
10922pub fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
10923    let days = days_since_epoch + 719_468;
10924    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
10925    let doe = days - era * 146_097;
10926    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
10927    let y = yoe + era * 400;
10928    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
10929    let mp = (5 * doy + 2) / 153;
10930    let d = doy - (153 * mp + 2) / 5 + 1;
10931    let m = if mp < 10 { mp + 3 } else { mp - 9 };
10932    let year = if m <= 2 { y + 1 } else { y };
10933    (year, m as u32, d as u32)
10934}
10935
10936fn parse_annual_period(value: &str) -> Option<i64> {
10937    (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
10938        .then(|| value.parse::<i64>().ok())
10939        .flatten()
10940}
10941
10942fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
10943    let (year, month) = value.split_once('-')?;
10944    if year.len() != 4 || month.len() != 2 {
10945        return None;
10946    }
10947    let year = year.parse::<i64>().ok()?;
10948    let month = month.parse::<u32>().ok()?;
10949    (1..=12).contains(&month).then_some((year, month))
10950}
10951
10952fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
10953    let mut parts = value.split('-');
10954    let year = parts.next()?;
10955    let month = parts.next()?;
10956    let day = parts.next()?;
10957    if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
10958        return None;
10959    }
10960    let year = year.parse::<i64>().ok()?;
10961    let month = month.parse::<u32>().ok()?;
10962    let day = day.parse::<u32>().ok()?;
10963    (1..=days_in_month(year, month)?)
10964        .contains(&day)
10965        .then_some((year, month, day))
10966}
10967
10968fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
10969    let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
10970    if year.len() != 4 || quarter.len() != 1 {
10971        return None;
10972    }
10973    let year = year.parse::<i64>().ok()?;
10974    let quarter = quarter.parse::<u32>().ok()?;
10975    (1..=4).contains(&quarter).then_some((year, quarter))
10976}
10977
10978impl std::fmt::Display for Period {
10979    /// Pandas `str(Period)` form: the calendar string (`2024`, `2024Q1`,
10980    /// `2024-03`, `2024-01-15`, ...). NaT (ordinal `i64::MIN`) renders `NaT`.
10981    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10982        self.write_calendar(f)
10983    }
10984}
10985
10986/// Build `periods` consecutive Periods starting at `start`.
10987///
10988/// Matches `pd.period_range(start, periods=N, freq=start.freq)` for the
10989/// count-based form. The frequency is taken from `start` — pandas requires
10990/// `freq` to match when both are passed; mismatches are an error in
10991/// pandas, but here we sidestep ambiguity by deriving from `start.freq`.
10992///
10993/// Per br-frankenpandas-2jef (epoj Phase 2). Pure ordinal arithmetic — no
10994/// calendar conversion (Phase 3 wires chrono). `periods=0` returns empty.
10995///
10996/// ```
10997/// use fp_types::{period_range, Period, PeriodFreq};
10998/// let q1 = Period::new(216, PeriodFreq::QUARTERLY);
10999/// let year = period_range(q1, 4);
11000/// assert_eq!(year.len(), 4);
11001/// assert_eq!(year[0].ordinal, 216);
11002/// assert_eq!(year[3].ordinal, 219);
11003/// ```
11004#[must_use]
11005pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
11006    (0..periods).map(|i| start.shift(i as i64)).collect()
11007}
11008
11009#[cfg(test)]
11010mod tests {
11011    use super::{
11012        DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
11013        cast_scalar, common_dtype, infer_dtype,
11014    };
11015
11016    /// A host value for the tests: a named thing, equal by name, unhashable
11017    /// when the name is empty.
11018    struct Named(&'static str);
11019
11020    impl super::HostObject for Named {
11021        fn host_eq(&self, other: &dyn super::HostObject) -> bool {
11022            other
11023                .as_any()
11024                .downcast_ref::<Named>()
11025                .is_some_and(|other| other.0 == self.0)
11026        }
11027        fn host_repr(&self) -> String {
11028            format!("Named({:?})", self.0)
11029        }
11030        fn host_str(&self) -> String {
11031            self.0.to_owned()
11032        }
11033        fn host_hash(&self) -> Option<u64> {
11034            (!self.0.is_empty()).then_some(self.0.len() as u64)
11035        }
11036        // Names starting with '!' cannot be ordered (as a date against a time).
11037        fn host_cmp(&self, other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
11038            let other = other.as_any().downcast_ref::<Named>()?;
11039            (!self.0.starts_with('!') && !other.0.starts_with('!')).then(|| self.0.cmp(other.0))
11040        }
11041        fn as_any(&self) -> &dyn std::any::Any {
11042            self
11043        }
11044    }
11045
11046    #[test]
11047    fn host_values_block_workers_only_under_a_declared_host_lock_4qg5w_13() {
11048        use std::sync::atomic::Ordering;
11049
11050        use super::{HostValue, LIVE_HOST_VALUES, workers_blocked};
11051        // The rule: inline only when a host lock may be held AND a host value
11052        // is alive. NEGATIVE: without a declared lock (pure Rust callers, this
11053        // test process) nothing is blocked however many host values live.
11054        assert!(workers_blocked(true, 1));
11055        assert!(!workers_blocked(true, 0));
11056        assert!(!workers_blocked(false, 3));
11057        // The count: non-zero while a handle is held, clones included (other
11058        // tests may hold host values concurrently, so only "alive while held"
11059        // is asserted, never "dead after drop"; the lock is never declared
11060        // here, so no concurrent test loses its workers).
11061        let first = HostValue::new(Named("held"));
11062        assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11063        let clone = first.clone();
11064        drop(first);
11065        assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11066        assert_eq!(clone.object().host_str(), "held");
11067    }
11068
11069    #[test]
11070    fn object_cells_order_like_python_then_totally_fvsao_66() {
11071        use std::cmp::Ordering;
11072
11073        use super::{HostValue, ObjectValue};
11074        let host = |name: &'static str| ObjectValue::Host(HostValue::new(Named(name)));
11075        let list = |items: Vec<Scalar>| ObjectValue::list(items);
11076        // Host values order as the host orders them (a date before a later
11077        // date), not by their reprs.
11078        assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11079        assert!(host("b") > host("a"));
11080        assert_eq!(host("a").cmp(&host("a")), Ordering::Equal);
11081        // Lists item by item, numbers by value (1 < 10, where the reprs sort
11082        // "10" first), a shorter prefix first.
11083        let one_ten = list(vec![Scalar::Int64(1), Scalar::Int64(10)]);
11084        let one_two = list(vec![Scalar::Int64(1), Scalar::Int64(2)]);
11085        assert_eq!(one_two.python_cmp(&one_ten), Some(Ordering::Less));
11086        assert!(list(vec![Scalar::Int64(1)]) < one_two);
11087        // Python's 1 == 1.0: an equal item pair is skipped, not the answer.
11088        let mixed = list(vec![Scalar::Float64(1.0), Scalar::Int64(3)]);
11089        assert_eq!(one_two.python_cmp(&mixed), Some(Ordering::Less));
11090        // Where Python raises there is no python_cmp, but the total order
11091        // still separates the cells: a list before a host value, then reprs.
11092        assert_eq!(one_two.python_cmp(&host("a")), None);
11093        assert!(one_two < host("a"));
11094        assert_eq!(host("!z").python_cmp(&host("!a")), None);
11095        assert!(host("!a") < host("!z"));
11096        let text = list(vec![Scalar::Utf8("a".to_owned())]);
11097        assert_eq!(one_two.python_cmp(&text), None);
11098        assert_ne!(one_two.cmp(&text), Ordering::Equal);
11099        // NEGATIVE: unequal cells that print alike are never Equal (NaN is not
11100        // equal to itself), so an ordered map cannot merge them.
11101        let nan = || list(vec![Scalar::Float64(f64::NAN)]);
11102        let (first, second) = (nan(), nan());
11103        assert_ne!(first, second);
11104        assert_ne!(first.cmp(&second), Ordering::Equal);
11105        assert_eq!(first.cmp(&second), second.cmp(&first).reverse());
11106    }
11107
11108    #[test]
11109    fn bytes_cells_print_order_and_serialize_like_python_bytes_4qg5w_8() {
11110        use std::cmp::Ordering;
11111
11112        use super::ObjectValue;
11113        let bytes = |data: &[u8]| Scalar::Object(ObjectValue::bytes(data.to_vec()));
11114        // Python's repr: single quotes unless the bytes hold a ' and no ",
11115        // \xNN for the unprintable, \\ \t \n \r escaped.
11116        assert_eq!(bytes(b"ab").python_repr(), "b'ab'");
11117        assert_eq!(bytes(b"a'b").python_repr(), "b\"a'b\"");
11118        assert_eq!(bytes(b"a'\"").python_repr(), "b'a\\'\"'");
11119        assert_eq!(bytes(b"\x00\t\\\xff").python_repr(), "b'\\x00\\t\\\\\\xff'");
11120        assert_eq!(bytes(b"ab").python_type_name(), "bytes");
11121        // Ordered byte by byte, a prefix first; never equal to a str.
11122        assert_eq!(bytes(b"ab").python_cmp(&bytes(b"b")), Some(Ordering::Less));
11123        assert_eq!(bytes(b"a").python_cmp(&bytes(b"ab")), Some(Ordering::Less));
11124        assert_eq!(bytes(b"a").python_cmp(&Scalar::Utf8("a".to_owned())), None);
11125        assert_ne!(bytes(b"a"), Scalar::Utf8("a".to_owned()));
11126        assert!(!bytes(b"").to_bool().unwrap());
11127        // The serde form the conformance fixtures carry, both ways.
11128        let json = serde_json::to_string(&bytes(b"hi")).unwrap();
11129        assert_eq!(json, r#"{"kind":"object","value":{"bytes":[104,105]}}"#);
11130        let back: Scalar = serde_json::from_str(&json).unwrap();
11131        assert_eq!(back, bytes(b"hi"));
11132        // NEGATIVE: a list cell still (de)serializes as its items.
11133        let list: Scalar =
11134            serde_json::from_str(r#"{"kind":"object","value":[{"kind":"int64","value":1}]}"#)
11135                .unwrap();
11136        assert_eq!(
11137            list,
11138            Scalar::Object(ObjectValue::list(vec![Scalar::Int64(1)]))
11139        );
11140    }
11141
11142    #[test]
11143    fn values_order_and_name_their_types_as_python_does_fvsao_71() {
11144        use std::cmp::Ordering;
11145
11146        use super::{HostValue, ObjectValue};
11147        let text = |value: &str| Scalar::Utf8(value.to_owned());
11148        let host =
11149            |name: &'static str| Scalar::Object(ObjectValue::Host(HostValue::new(Named(name))));
11150        let list = |items: Vec<Scalar>| Scalar::Object(ObjectValue::list(items));
11151        // Numbers across kinds by value, text by code point, instants,
11152        // intervals by (left, right), cells as the host orders them.
11153        assert_eq!(
11154            Scalar::Bool(true).python_cmp(&Scalar::Float64(1.5)),
11155            Some(Ordering::Less)
11156        );
11157        assert_eq!(
11158            Scalar::Int64(2).python_cmp(&Scalar::Float64(2.0)),
11159            Some(Ordering::Equal)
11160        );
11161        assert_eq!(text("b").python_cmp(&text("a")), Some(Ordering::Greater));
11162        assert_eq!(
11163            Scalar::Datetime64(5).python_cmp(&Scalar::Datetime64(9)),
11164            Some(Ordering::Less)
11165        );
11166        let interval = |left: f64, right: f64| {
11167            Scalar::Interval(Interval::new(left, right, IntervalClosed::Right))
11168        };
11169        assert_eq!(
11170            interval(0.0, 5.0).python_cmp(&interval(0.0, 2.0)),
11171            Some(Ordering::Greater)
11172        );
11173        assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11174        // NEGATIVES: what Python cannot order - a str and an int, an instant
11175        // and a duration, a cell and a number, unorderable host values.
11176        assert_eq!(text("a").python_cmp(&Scalar::Int64(1)), None);
11177        assert_eq!(
11178            Scalar::Datetime64(1).python_cmp(&Scalar::Timedelta64(1)),
11179            None
11180        );
11181        assert_eq!(host("a").python_cmp(&Scalar::Int64(1)), None);
11182        assert_eq!(host("!a").python_cmp(&host("b")), None);
11183        // Their types as Python's TypeError names them; a host value by its
11184        // host (the default for a host that cannot say is 'object'), a list
11185        // pair by the first unequal items it holds.
11186        assert_eq!(text("a").python_type_name(), "str");
11187        assert_eq!(Scalar::Bool(true).python_type_name(), "bool");
11188        assert_eq!(Scalar::Datetime64(1).python_type_name(), "Timestamp");
11189        assert_eq!(list(vec![]).python_type_name(), "list");
11190        assert_eq!(host("a").python_type_name(), "object");
11191        let (left, right) = list(vec![Scalar::Int64(1), Scalar::Int64(2)])
11192            .python_cmp_type_names(&list(vec![Scalar::Int64(1), text("x")]));
11193        assert_eq!((left.as_str(), right.as_str()), ("int", "str"));
11194        let (left, right) = text("a").python_cmp_type_names(&list(vec![]));
11195        assert_eq!((left.as_str(), right.as_str()), ("str", "list"));
11196    }
11197
11198    #[test]
11199    fn object_cells_print_compare_and_hash_like_python_fvsao_33() {
11200        use std::hash::{Hash, Hasher};
11201
11202        use super::{HostValue, ObjectValue};
11203        let hash = |value: &ObjectValue| {
11204            let mut hasher = std::collections::hash_map::DefaultHasher::new();
11205            value.hash(&mut hasher);
11206            hasher.finish()
11207        };
11208        let list = ObjectValue::list(vec![
11209            Scalar::Int64(1),
11210            Scalar::Utf8("a".to_owned()),
11211            Scalar::Null(NullKind::Null),
11212            Scalar::Float64(2.0),
11213            Scalar::Object(ObjectValue::list(vec![Scalar::Utf8("b".to_owned())])),
11214        ]);
11215        // repr / str (astype(str), writers) quote strings; pandas' display
11216        // (pprint) does not.
11217        assert_eq!(list.repr(), "[1, 'a', None, 2.0, ['b']]");
11218        assert_eq!(list.to_string(), "[1, 'a', None, 2.0, ['b']]");
11219        assert_eq!(list.pprint(), "[1, a, None, 2.0, [b]]");
11220        // An object cell is object data (pandas' object dtype, Utf8 here).
11221        assert_eq!(Scalar::Object(list.clone()).dtype(), DType::Utf8);
11222        assert!(!Scalar::Object(list.clone()).is_missing());
11223        // Equal lists are equal and hash alike; a different item is not
11224        // equal; a list never equals a host value.
11225        let same = ObjectValue::list(list.as_list().unwrap().to_vec());
11226        assert_eq!(list, same);
11227        assert_eq!(hash(&list), hash(&same));
11228        let other = ObjectValue::list(vec![Scalar::Int64(1)]);
11229        assert_ne!(list, other);
11230        let host = ObjectValue::Host(HostValue::new(Named("x")));
11231        assert_ne!(list, host);
11232        // Host values compare and print through the host.
11233        assert_eq!(host, ObjectValue::Host(HostValue::new(Named("x"))));
11234        assert_ne!(host, ObjectValue::Host(HostValue::new(Named("y"))));
11235        assert_eq!(host.repr(), "Named(\"x\")");
11236        assert_eq!(host.to_string(), "x");
11237        // Python truth: an empty list is false, a host value true.
11238        assert!(
11239            !Scalar::Object(ObjectValue::list(Vec::new()))
11240                .to_bool()
11241                .unwrap()
11242        );
11243        assert!(Scalar::Object(host.clone()).to_bool().unwrap());
11244        // A list is not a number.
11245        assert!(Scalar::Object(list.clone()).to_f64().is_err());
11246        // A list cell serializes as its items and reads back; a host value
11247        // refuses to serialize.
11248        let json = serde_json::to_string(&Scalar::Object(other.clone())).unwrap();
11249        assert_eq!(
11250            serde_json::from_str::<Scalar>(&json).unwrap(),
11251            Scalar::Object(other)
11252        );
11253        assert!(serde_json::to_string(&Scalar::Object(host)).is_err());
11254    }
11255
11256    #[test]
11257    fn a_host_cell_displays_by_its_pprint_and_stringifies_by_its_str() {
11258        use super::{HostValue, ObjectValue};
11259
11260        /// A host tuple: Python's str quotes its items, pandas' display not.
11261        struct Pair;
11262        impl super::HostObject for Pair {
11263            fn host_eq(&self, _other: &dyn super::HostObject) -> bool {
11264                false
11265            }
11266            fn host_repr(&self) -> String {
11267                "('a', 1)".to_owned()
11268            }
11269            fn host_str(&self) -> String {
11270                "('a', 1)".to_owned()
11271            }
11272            fn host_pprint(&self) -> String {
11273                "(a, 1)".to_owned()
11274            }
11275            fn host_hash(&self) -> Option<u64> {
11276                None
11277            }
11278            fn host_cmp(&self, _other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
11279                None
11280            }
11281            fn as_any(&self) -> &dyn std::any::Any {
11282                self
11283            }
11284        }
11285        let pair = ObjectValue::Host(HostValue::new(Pair));
11286        assert_eq!(pair.pprint(), "(a, 1)");
11287        // Inside a list cell too.
11288        let list = ObjectValue::list(vec![Scalar::Object(pair.clone())]);
11289        assert_eq!(list.pprint(), "[(a, 1)]");
11290        // NEGATIVE: str (astype(str), writers) stays the host's str.
11291        assert_eq!(pair.to_string(), "('a', 1)");
11292        // NEGATIVE: a host without its own pprint displays by its str.
11293        let named = ObjectValue::Host(HostValue::new(Named("x")));
11294        assert_eq!(named.pprint(), "x");
11295    }
11296
11297    #[test]
11298    fn float64_json_spells_infinity_and_round_trips() {
11299        // br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.3: serde_json
11300        // wrote +-inf as `null` and could not read it back, so pandas'
11301        // division-by-zero answers could not reach a fixture.
11302        let json = |s: &Scalar| serde_json::to_string(s).expect("serialize");
11303        let back = |text: &str| serde_json::from_str::<Scalar>(text);
11304        assert_eq!(
11305            json(&Scalar::Float64(f64::INFINITY)),
11306            r#"{"kind":"float64","value":"inf"}"#
11307        );
11308        assert_eq!(
11309            json(&Scalar::Float64(f64::NEG_INFINITY)),
11310            r#"{"kind":"float64","value":"-inf"}"#
11311        );
11312        // Unchanged spellings: finite numbers, -0.0, and NaN as null.
11313        assert_eq!(
11314            json(&Scalar::Float64(1.5)),
11315            r#"{"kind":"float64","value":1.5}"#
11316        );
11317        assert_eq!(
11318            json(&Scalar::Float64(-0.0)),
11319            r#"{"kind":"float64","value":-0.0}"#
11320        );
11321        assert_eq!(
11322            json(&Scalar::Float64(f64::NAN)),
11323            r#"{"kind":"float64","value":null}"#
11324        );
11325        for value in [f64::INFINITY, f64::NEG_INFINITY, 1.5, -2.25e300] {
11326            let scalar = Scalar::Float64(value);
11327            assert_eq!(back(&json(&scalar)).expect("round trip"), scalar);
11328        }
11329        let negative_zero = back(r#"{"kind":"float64","value":-0.0}"#).expect("-0.0");
11330        assert!(matches!(negative_zero, Scalar::Float64(v) if v == 0.0 && v.is_sign_negative()));
11331        assert!(matches!(
11332            back(r#"{"kind":"float64","value":null}"#).expect("null"),
11333            Scalar::Float64(v) if v.is_nan()
11334        ));
11335        // Anything else is an error, not a silent NaN.
11336        assert!(back(r#"{"kind":"float64","value":"Infinity"}"#).is_err());
11337        assert!(back(r#"{"kind":"float64","value":"1.5"}"#).is_err());
11338    }
11339
11340    /// br-frankenpandas-ay8o9: Scalar::semantic_cmp underpins ALL ordering in
11341    /// the library (sort, min/max, is_monotonic, searchsorted, groupby key
11342    /// order) and is the reference the differential harnesses rely on. Property
11343    /// test of its total-order axioms over finite/non-NaT same-dtype scalars,
11344    /// plus the intentional NaN degeneracy. Deterministic seeded LCG — no rand
11345    /// crate, no mocks.
11346    /// br-frankenpandas-767ak: extends ay8o9's NaN pinning to the temporal NAT
11347    /// sentinels (i64::MIN). semantic_cmp treats NAT as degenerate (Equal to all
11348    /// same-dtype), which is why temporal ordering ops must treat NAT as missing.
11349    #[test]
11350    fn semantic_cmp_cross_numeric_int_float_cdpai() {
11351        // Property (br-frankenpandas-cdpai): semantic_cmp compares Int64 vs Float64
11352        // as f64, antisymmetric across the operand order. Seeded LCG, no mocks.
11353        use std::cmp::Ordering;
11354        let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
11355        let mut next = || {
11356            st = st
11357                .wrapping_mul(6_364_136_223_846_793_005)
11358                .wrapping_add(1_442_695_040_888_963_407);
11359            (st >> 33) as u32
11360        };
11361        for _ in 0..3000u32 {
11362            let i = (next() % 21) as i64 - 10;
11363            let f = (next() % 400) as f64 / 20.0 - 10.0; // finite
11364            let exp = (i as f64).partial_cmp(&f).unwrap();
11365            assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
11366            assert_eq!(
11367                Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
11368                exp.reverse()
11369            );
11370        }
11371        // Exact int/float equality compares Equal in both directions.
11372        assert_eq!(
11373            Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
11374            Ordering::Equal
11375        );
11376        assert_eq!(
11377            Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
11378            Ordering::Equal
11379        );
11380        assert_eq!(
11381            Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
11382            Ordering::Less
11383        );
11384        assert_eq!(
11385            Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
11386            Ordering::Greater
11387        );
11388    }
11389
11390    #[test]
11391    fn semantic_cmp_nat_degeneracy_temporal_767ak() {
11392        use std::cmp::Ordering;
11393        const NAT: i64 = i64::MIN;
11394
11395        // Timedelta64 NAT is degenerate (Equal to finite and to itself).
11396        let td_nat = Scalar::Timedelta64(NAT);
11397        for v in [-3i64, 0, 5, 99] {
11398            let td = Scalar::Timedelta64(v);
11399            assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
11400            assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
11401        }
11402        assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
11403
11404        // Datetime64 NAT likewise.
11405        let dt_nat = Scalar::Datetime64(NAT);
11406        for v in [-3i64, 0, 5, 99] {
11407            let dt = Scalar::Datetime64(v);
11408            assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
11409            assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
11410        }
11411        assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
11412
11413        // Non-NAT temporal values order normally (reflexive, antisymmetric, lt).
11414        for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
11415            let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
11416            assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
11417            assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); // a.cmp(b)
11418            assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
11419            let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
11420            assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
11421        }
11422    }
11423
11424    fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
11425        [
11426            Scalar::Null(NullKind::Null),
11427            Scalar::Bool(true),
11428            Scalar::Int64(-7),
11429            Scalar::Float64(3.5),
11430            Scalar::Utf8("mixed".to_owned()),
11431            Scalar::Timedelta64(11),
11432            Scalar::Datetime64(1_735_732_800_123_456_789),
11433            Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
11434            Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
11435        ]
11436    }
11437
11438    fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
11439        !matches!(
11440            (left, right),
11441            (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
11442        )
11443    }
11444
11445    #[test]
11446    fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
11447        let values = semantic_cmp_cross_variant_values_d5ikg();
11448        for (left_index, left) in values.iter().enumerate() {
11449            for (right_index, right) in values.iter().enumerate() {
11450                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11451                {
11452                    assert_eq!(
11453                        left.semantic_cmp(right),
11454                        format!("{left:?}").cmp(&format!("{right:?}")),
11455                        "cross-variant order mismatch: {left:?} vs {right:?}"
11456                    );
11457                }
11458            }
11459        }
11460    }
11461
11462    #[test]
11463    #[ignore = "foreground release attribution harness"]
11464    fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
11465        use std::cmp::Ordering;
11466
11467        const BATCH: usize = 4_096;
11468        const BLOCKS: usize = 9;
11469
11470        fn former(left: &Scalar, right: &Scalar) -> Ordering {
11471            format!("{left:?}").cmp(&format!("{right:?}"))
11472        }
11473
11474        fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
11475            left.semantic_cmp(right)
11476        }
11477
11478        fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
11479            let mut less = 0usize;
11480            let started = std::time::Instant::now();
11481            for _ in 0..BATCH {
11482                for (left_index, left) in values.iter().enumerate() {
11483                    for (right_index, right) in values.iter().enumerate() {
11484                        if left_index != right_index
11485                            && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11486                            && compare(std::hint::black_box(left), std::hint::black_box(right))
11487                                == Ordering::Less
11488                        {
11489                            less += 1;
11490                        }
11491                    }
11492                }
11493            }
11494            std::hint::black_box(less);
11495            started.elapsed().as_nanos()
11496        }
11497
11498        fn median(samples: &mut [u128]) -> u128 {
11499            samples.sort_unstable();
11500            samples[samples.len() / 2]
11501        }
11502
11503        let values = semantic_cmp_cross_variant_values_d5ikg();
11504
11505        for (left_index, left) in values.iter().enumerate() {
11506            for (right_index, right) in values.iter().enumerate() {
11507                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11508                {
11509                    assert_eq!(
11510                        former(left, right),
11511                        candidate(left, right),
11512                        "cross-variant order mismatch: {left:?} vs {right:?}"
11513                    );
11514                }
11515            }
11516        }
11517
11518        std::hint::black_box(elapsed(&values, former));
11519        std::hint::black_box(elapsed(&values, candidate));
11520
11521        let mut former_samples = Vec::with_capacity(BLOCKS * 2);
11522        let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
11523        for block in 0..BLOCKS {
11524            if block.is_multiple_of(2) {
11525                former_samples.push(elapsed(&values, former));
11526                candidate_samples.push(elapsed(&values, candidate));
11527                candidate_samples.push(elapsed(&values, candidate));
11528                former_samples.push(elapsed(&values, former));
11529            } else {
11530                candidate_samples.push(elapsed(&values, candidate));
11531                former_samples.push(elapsed(&values, former));
11532                former_samples.push(elapsed(&values, former));
11533                candidate_samples.push(elapsed(&values, candidate));
11534            }
11535        }
11536
11537        let former_p50 = median(&mut former_samples);
11538        let candidate_p50 = median(&mut candidate_samples);
11539        eprintln!(
11540            "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
11541            former_p50 as f64 / candidate_p50 as f64
11542        );
11543    }
11544
11545    #[test]
11546    fn semantic_cmp_total_order_axioms_ay8o9() {
11547        use std::cmp::Ordering;
11548
11549        let mut state: u64 = 0xc0ff_eeba_df00_d123;
11550        let mut next = || {
11551            state = state
11552                .wrapping_mul(6_364_136_223_846_793_005)
11553                .wrapping_add(1_442_695_040_888_963_407);
11554            (state >> 33) as u32
11555        };
11556
11557        for iter in 0..6000u32 {
11558            let dt = next() % 4;
11559            // Build a same-dtype, finite, non-NaT scalar from a random u32.
11560            let mk = |r: u32| match dt {
11561                0 => Scalar::Int64((r % 11) as i64 - 5),
11562                // finite, in -5.0..=5.0 by 0.5 — no NaN/inf.
11563                1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
11564                2 => Scalar::Utf8(format!("s{}", r % 5)),
11565                _ => Scalar::Bool(r.is_multiple_of(2)),
11566            };
11567            let a = mk(next());
11568            let b = mk(next());
11569            let c = mk(next());
11570            let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
11571
11572            // Reflexivity.
11573            assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
11574            // Antisymmetry.
11575            assert_eq!(
11576                a.semantic_cmp(&b),
11577                b.semantic_cmp(&a).reverse(),
11578                "antisymmetric {ctx}"
11579            );
11580            // le / ge / eq consistency with the ordering.
11581            let ab = a.semantic_cmp(&b);
11582            assert_eq!(
11583                a.semantic_le(&b),
11584                ab != Ordering::Greater,
11585                "le-consistent {ctx}"
11586            );
11587            assert_eq!(
11588                a.semantic_ge(&b),
11589                ab != Ordering::Less,
11590                "ge-consistent {ctx}"
11591            );
11592            assert_eq!(
11593                a.semantic_le(&b) && a.semantic_ge(&b),
11594                ab == Ordering::Equal,
11595                "le&ge<=>eq {ctx}"
11596            );
11597            // Transitivity: a<=b && b<=c  =>  a<=c.
11598            if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
11599                assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
11600            }
11601        }
11602
11603        // Pin the intentional NaN degeneracy: a Float64 NaN compares Equal to
11604        // every finite Float64 (and to itself) — this is why ordering ops must
11605        // treat NaN as missing rather than relying on semantic_cmp to order it.
11606        let nan = Scalar::Float64(f64::NAN);
11607        for v in [
11608            Scalar::Float64(-3.5),
11609            Scalar::Float64(0.0),
11610            Scalar::Float64(7.25),
11611        ] {
11612            assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
11613            assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
11614        }
11615        assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
11616    }
11617
11618    /// br-frankenpandas-be314: common_dtype is the dtype-promotion lattice
11619    /// underpinning every binary op, alignment, and concat (dtype coercion is a
11620    /// crown-jewel correctness area). Exhaustively (all 14x14 DType pairs) assert
11621    /// its lattice axioms — an asymmetric arm would make df1+df2 and df2+df1
11622    /// disagree on dtype.
11623    #[test]
11624    fn common_dtype_lattice_axioms_be314() {
11625        let all: [DType; 14] = [
11626            DType::Null,
11627            DType::Bool,
11628            DType::BoolNullable,
11629            DType::Int64,
11630            DType::Int64Nullable,
11631            DType::Float64,
11632            // br-frankenpandas-qkqfb: a new variant is only safe once the
11633            // commutativity and associativity sweeps below cover it.
11634            DType::Float64Nullable,
11635            DType::Utf8,
11636            DType::Categorical,
11637            DType::Timedelta64,
11638            DType::datetime64_naive(),
11639            DType::Period,
11640            DType::Interval,
11641            DType::Sparse,
11642        ];
11643
11644        for a in &all {
11645            // Idempotence: a promoted with itself is itself.
11646            assert_eq!(
11647                common_dtype(a.clone(), a.clone()),
11648                Ok(a.clone()),
11649                "idempotent {a:?}"
11650            );
11651            // Null is the identity element of the promotion lattice.
11652            assert_eq!(
11653                common_dtype(DType::Null, a.clone()),
11654                Ok(a.clone()),
11655                "null-left identity {a:?}"
11656            );
11657            assert_eq!(
11658                common_dtype(a.clone(), DType::Null),
11659                Ok(a.clone()),
11660                "null-right identity {a:?}"
11661            );
11662
11663            for b in &all {
11664                // Commutativity: same Ok value AND same ok-ness. An asymmetric
11665                // match arm would make binary-op output dtype order-dependent.
11666                assert_eq!(
11667                    common_dtype(a.clone(), b.clone()).ok(),
11668                    common_dtype(b.clone(), a.clone()).ok(),
11669                    "commutative value {a:?},{b:?}"
11670                );
11671                assert_eq!(
11672                    common_dtype(a.clone(), b.clone()).is_ok(),
11673                    common_dtype(b.clone(), a.clone()).is_ok(),
11674                    "commutative ok-ness {a:?},{b:?}"
11675                );
11676            }
11677        }
11678
11679        // Associativity over the Ok-closed subset: when both nestings succeed,
11680        // promotion order must not change the result.
11681        for a in &all {
11682            for b in &all {
11683                for c in &all {
11684                    if let (Ok(ab), Ok(bc)) = (
11685                        common_dtype(a.clone(), b.clone()),
11686                        common_dtype(b.clone(), c.clone()),
11687                    ) && let (Ok(left), Ok(right)) =
11688                        (common_dtype(ab, c.clone()), common_dtype(a.clone(), bc))
11689                    {
11690                        assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
11691                    }
11692                }
11693            }
11694        }
11695    }
11696
11697    /// br-frankenpandas-e3sfq: infer_dtype drives Column/Series construction
11698    /// dtype inference. Assert its homogeneous + mixed-coercion rules.
11699    #[test]
11700    fn infer_dtype_coercion_rules_e3sfq() {
11701        use DType::{Bool, Float64, Int64, Null, Utf8};
11702
11703        // Empty and all-null infer to Null.
11704        assert_eq!(infer_dtype(&[]), Ok(Null));
11705        assert_eq!(
11706            infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
11707            Ok(Null)
11708        );
11709
11710        // Homogeneous slices infer to their own dtype (random, seeded LCG).
11711        let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
11712        let mut next = || {
11713            s = s
11714                .wrapping_mul(6_364_136_223_846_793_005)
11715                .wrapping_add(1_442_695_040_888_963_407);
11716            (s >> 33) as u32
11717        };
11718        for _ in 0..600u32 {
11719            let n = (next() % 6) as usize + 1;
11720            let ints: Vec<Scalar> = (0..n)
11721                .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
11722                .collect();
11723            assert_eq!(infer_dtype(&ints), Ok(Int64));
11724            let floats: Vec<Scalar> = (0..n)
11725                .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
11726                .collect();
11727            assert_eq!(infer_dtype(&floats), Ok(Float64));
11728            let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
11729            assert_eq!(infer_dtype(&bools), Ok(Bool));
11730            let strs: Vec<Scalar> = (0..n)
11731                .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
11732                .collect();
11733            assert_eq!(infer_dtype(&strs), Ok(Utf8));
11734        }
11735
11736        // Mixed-coercion rules.
11737        assert_eq!(
11738            infer_dtype(&[
11739                Scalar::Int64(1),
11740                Scalar::Null(NullKind::Null),
11741                Scalar::Int64(2)
11742            ]),
11743            Ok(Int64),
11744            "Int64 + nulls -> Int64"
11745        );
11746        assert_eq!(
11747            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
11748            Ok(Float64),
11749            "Int64 + Float64 -> Float64"
11750        );
11751        // br-frankenpandas-rh1od: MEASURED live pandas 2.2.3 — a bool mixed
11752        // with numerics constructs OBJECT; the old Int64 coercion here was
11753        // numpy common-type behavior no pandas constructor path produces.
11754        assert_eq!(
11755            infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
11756            Ok(Utf8),
11757            "Bool + Int64 -> object bucket (pandas constructs object)"
11758        );
11759        assert_eq!(
11760            infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
11761            Ok(Utf8),
11762            "Utf8 + Int64 -> Utf8 (object fallback)"
11763        );
11764    }
11765
11766    /// br-frankenpandas-1ews0: missing_for_dtype is the canonical per-dtype
11767    /// missing sentinel (used by null-fill / with_validity / cast). Exhaustively
11768    /// assert it is always missing, and that casting any missing to any dtype
11769    /// stays missing.
11770    #[test]
11771    fn missing_for_dtype_always_missing_1ews0() {
11772        let all: [DType; 14] = [
11773            DType::Null,
11774            DType::Bool,
11775            DType::BoolNullable,
11776            DType::Int64,
11777            DType::Int64Nullable,
11778            DType::Float64,
11779            DType::Float64Nullable,
11780            DType::Utf8,
11781            DType::Categorical,
11782            DType::Timedelta64,
11783            DType::datetime64_naive(),
11784            DType::Period,
11785            DType::Interval,
11786            DType::Sparse,
11787        ];
11788        for dt in &all {
11789            let m = Scalar::missing_for_dtype(dt.clone());
11790            assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
11791            for target in &all {
11792                let cast = cast_scalar(&m, target.clone()).expect("cast of missing");
11793                if target == &DType::Utf8 {
11794                    // Casting a missing value to string follows pandas astype(str):
11795                    // it yields a string ("None"/"NaN"/"NaT"), NOT a missing value.
11796                    assert!(
11797                        matches!(cast, Scalar::Utf8(_)),
11798                        "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
11799                    );
11800                } else if matches!(dt, DType::Timedelta64 | DType::Datetime64 { .. })
11801                    && matches!(target, DType::Bool | DType::Int64)
11802                {
11803                    // ⚠️ TWO MORE PLACES pandas BREAKS this invariant, and both
11804                    // are the same underlying fact: NaT is not a separate
11805                    // representation, it IS i64::MIN, and the numpy casts read
11806                    // the bits. MEASURED, live pandas 2.2.3:
11807                    //
11808                    //   pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
11809                    //     -> -9223372036854775808      the SENTINEL, not a missing
11810                    //   pd.Series([pd.NaT], dtype='timedelta64[ns]').astype('bool')
11811                    //     -> True                      nonzero, so truthy
11812                    //
11813                    // Same shape as the Utf8 carve-out above: the invariant is
11814                    // FrankenPandas' own, and pandas does not honour it wherever
11815                    // a cast is defined to reinterpret rather than to convert.
11816                    // Narrowly scoped on purpose — every other missing, and these
11817                    // two toward every other target, still stay missing.
11818                    match target {
11819                        DType::Bool => assert_eq!(
11820                            cast,
11821                            Scalar::Bool(true),
11822                            "cast(missing {dt:?} -> Bool) is pandas' nonzero-truthy \
11823                             read of the NaT bits"
11824                        ),
11825                        _ => assert_eq!(
11826                            cast,
11827                            Scalar::Int64(i64::MIN),
11828                            "cast(missing {dt:?} -> Int64) is the NaT sentinel itself"
11829                        ),
11830                    }
11831                } else {
11832                    // Every other target preserves missingness via cast_scalar's
11833                    // value.is_missing() -> missing_for_dtype(target) branch.
11834                    assert!(
11835                        cast.is_missing(),
11836                        "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
11837                    );
11838                }
11839            }
11840        }
11841    }
11842
11843    #[test]
11844    fn cast_scalar_bool_int_roundtrip_6w07b() {
11845        use super::cast_scalar;
11846        // Property (br-frankenpandas-6w07b): Bool<->Int64 cast. Seeded LCG, no mocks.
11847        assert_eq!(
11848            cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
11849            Scalar::Int64(1)
11850        );
11851        assert_eq!(
11852            cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
11853            Scalar::Int64(0)
11854        );
11855        assert_eq!(
11856            cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
11857            Scalar::Bool(false)
11858        );
11859        let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
11860        let mut next = || {
11861            st = st
11862                .wrapping_mul(6_364_136_223_846_793_005)
11863                .wrapping_add(1_442_695_040_888_963_407);
11864            (st >> 33) as u32
11865        };
11866        for _ in 0..2000u32 {
11867            let v = (next() % 21) as i64 - 10;
11868            assert_eq!(
11869                cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
11870                Scalar::Bool(v != 0),
11871                "int->bool v={v}"
11872            );
11873        }
11874    }
11875
11876    /// br-frankenpandas-6a83t: cast_scalar is the scalar dtype-coercion path
11877    #[test]
11878    fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
11879        use super::cast_scalar;
11880        // Property (br-frankenpandas-u9lec): Float64->Int64 truncates toward zero, not
11881        // floor (-3.7 -> -3). Seeded LCG, no mocks.
11882        let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
11883        let mut next = || {
11884            st = st
11885                .wrapping_mul(6_364_136_223_846_793_005)
11886                .wrapping_add(1_442_695_040_888_963_407);
11887            (st >> 33) as u32
11888        };
11889        // Explicit negative-direction checks (the gotcha).
11890        for (f, exp) in [
11891            (-3.7, -3i64),
11892            (3.7, 3),
11893            (-3.2, -3),
11894            (3.2, 3),
11895            (-0.9, 0),
11896            (0.9, 0),
11897            (-5.0, -5),
11898            (5.0, 5),
11899        ] {
11900            assert_eq!(
11901                cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
11902                Scalar::Int64(exp),
11903                "cast {f}"
11904            );
11905        }
11906        // Property over random signed fractional values.
11907        for _ in 0..3000u32 {
11908            let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; // [-1000, 1000]
11909            let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
11910            assert_eq!(
11911                got,
11912                Scalar::Int64(v.trunc() as i64),
11913                "trunc-toward-zero v={v}"
11914            );
11915        }
11916    }
11917
11918    /// Float -> `datetime64[ns]` / `timedelta64[ns]` reinterprets the float as
11919    /// integer NANOSECONDS. Every value here is transcribed from live pandas
11920    /// 2.2.3, measured on both the constructor and `astype` paths.
11921    ///
11922    /// ⚠️ THE CONTRAST WITH `int64` IS THE POINT: the explicit constructor
11923    /// REFUSES a lossy float -> int64, and silently truncates the same float
11924    /// into a temporal dtype. Assuming one rule covers both is how this gets
11925    /// re-broken, so both are asserted here on the same input.
11926    #[test]
11927    fn cast_scalar_float_to_temporal_truncates_to_nanoseconds() {
11928        use super::{Timedelta, Timestamp, cast_scalar};
11929
11930        // TRUNCATION TOWARD ZERO, on both signs, where a floor would disagree.
11931        // pandas: 0.9 -> 0, -0.9 -> 0, 1.5 -> 1, -1.5 -> -1, -2.5 -> -2.
11932        for (input, want) in [
11933            (1.5_f64, 1_i64),
11934            (-1.5, -1),
11935            (0.9, 0),
11936            (-0.9, 0),
11937            (2.5, 2),
11938            (-2.5, -2),
11939            (1.999_999, 1),
11940            (-1.999_999, -1),
11941            (2.0, 2),
11942            (1e18, 1_000_000_000_000_000_000),
11943        ] {
11944            assert_eq!(
11945                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11946                Scalar::Datetime64(want),
11947                "datetime64 cast of {input}"
11948            );
11949            assert_eq!(
11950                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11951                Scalar::Timedelta64(want),
11952                "timedelta64 cast of {input}"
11953            );
11954        }
11955
11956        // ANYTHING NOT REPRESENTABLE AS i64 IS NaT — not a saturated i64::MAX,
11957        // and not the epoch. A bare `as i64` would produce both of those wrong
11958        // answers (saturation for the large values, 0 for NaN).
11959        for input in [
11960            f64::NAN,
11961            f64::INFINITY,
11962            f64::NEG_INFINITY,
11963            1e30,
11964            -1e30,
11965            9.3e18,
11966            -9.3e18,
11967            9_223_372_036_854_775_808.0,  // exactly 2^63
11968            -9_223_372_036_854_775_808.0, // exactly -2^63, which IS the NaT sentinel
11969        ] {
11970            assert_eq!(
11971                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11972                Scalar::Datetime64(Timestamp::NAT),
11973                "datetime64 cast of {input} must be NaT"
11974            );
11975            assert_eq!(
11976                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11977                Scalar::Timedelta64(Timedelta::NAT),
11978                "timedelta64 cast of {input} must be NaT"
11979            );
11980        }
11981
11982        // ...but the largest float BELOW 2^63 is representable and converts.
11983        // pandas renders it 2262-04-11 23:47:16.854774784.
11984        let just_inside = 9_223_372_036_854_774_784.0_f64; // 2^63 - 1024
11985        assert_eq!(
11986            cast_scalar(&Scalar::Float64(just_inside), DType::datetime64_naive()).unwrap(),
11987            Scalar::Datetime64(9_223_372_036_854_774_784),
11988            "the largest representable float must NOT be treated as NaT"
11989        );
11990
11991        // THE CONTRAST. Same input, three dtypes, two different rules — the
11992        // temporal ones truncate where int64 refuses outright.
11993        assert_eq!(
11994            cast_scalar(&Scalar::Float64(1.5), DType::datetime64_naive()).unwrap(),
11995            Scalar::Datetime64(1)
11996        );
11997        assert_eq!(
11998            cast_scalar(&Scalar::Float64(1.5), DType::Int64).unwrap(),
11999            Scalar::Int64(1),
12000            "the SHARED cast truncates here too; it is the explicit constructor \
12001             that refuses, via Column::new's LossyFloatToInt pre-check"
12002        );
12003    }
12004
12005    /// The MIRROR direction: `datetime64[ns]` / `timedelta64[ns]` -> numpy
12006    /// `int64` is the raw nanosecond count, and a bool is 0 or 1 nanoseconds
12007    /// going the other way. Every value transcribed from live pandas 2.2.3
12008    /// `astype`.
12009    #[test]
12010    fn cast_scalar_temporal_to_int64_is_raw_nanoseconds() {
12011        use super::{Timedelta, Timestamp, cast_scalar};
12012
12013        // Timestamp('2024-03-15 10:30:45.123456789') and
12014        // Timedelta('1 days 02:03:04.005006007').
12015        for nanos in [1_710_498_645_123_456_789_i64, 93_784_005_006_007, 0, -1] {
12016            assert_eq!(
12017                cast_scalar(&Scalar::Datetime64(nanos), DType::Int64).unwrap(),
12018                Scalar::Int64(nanos),
12019                "datetime64 -> int64 must be the raw nanos ({nanos})"
12020            );
12021            assert_eq!(
12022                cast_scalar(&Scalar::Timedelta64(nanos), DType::Int64).unwrap(),
12023                Scalar::Int64(nanos)
12024            );
12025        }
12026
12027        // ⚠️ NaT BECOMES THE SENTINEL, NOT A MISSING VALUE. pandas:
12028        //     pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
12029        //       -> -9223372036854775808
12030        // This is the assertion that pins the cast ABOVE the is_missing()
12031        // branch; move it below and both of these become Null.
12032        assert_eq!(
12033            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Int64).unwrap(),
12034            Scalar::Int64(i64::MIN),
12035            "NaT -> int64 is the sentinel i64::MIN, not a missing value"
12036        );
12037        assert_eq!(
12038            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Int64).unwrap(),
12039            Scalar::Int64(i64::MIN)
12040        );
12041
12042        // ⚠️ THE NULLABLE Int64 REFUSES WHAT numpy int64 ACCEPTS:
12043        //     .astype('Int64')   -> TypeError: datetime64[ns] cannot be
12044        //                          converted to IntegerDtype
12045        //     .astype('float64') -> TypeError: Cannot cast DatetimeArray
12046        // Both must stay refused, which is what makes the guard on the exact
12047        // target load-bearing rather than cosmetic.
12048        // `DType` stopped being `Copy` when `Datetime64 { tz }` landed
12049        // (2f159e68f), so the loop variable is cloned into each call.
12050        for target in [DType::Int64Nullable, DType::Float64, DType::Float64Nullable] {
12051            assert!(
12052                cast_scalar(
12053                    &Scalar::Datetime64(1_710_498_645_123_456_789),
12054                    target.clone()
12055                )
12056                .is_err(),
12057                "datetime64 -> {target:?} must stay refused"
12058            );
12059            assert!(
12060                cast_scalar(&Scalar::Timedelta64(93_784_005_006_007), target.clone()).is_err(),
12061                "timedelta64 -> {target:?} must stay refused"
12062            );
12063        }
12064
12065        // A bool is 0 or 1 NANOSECONDS on the astype path.
12066        for (flag, want) in [(true, 1_i64), (false, 0)] {
12067            assert_eq!(
12068                cast_scalar(&Scalar::Bool(flag), DType::datetime64_naive()).unwrap(),
12069                Scalar::Datetime64(want)
12070            );
12071            assert_eq!(
12072                cast_scalar(&Scalar::Bool(flag), DType::Timedelta64).unwrap(),
12073                Scalar::Timedelta64(want)
12074            );
12075        }
12076    }
12077
12078    /// The two halves of the column-width datetime formatter, checked apart:
12079    /// which rung a value NEEDS, and how a value RENDERS at a given rung.
12080    /// Transcribed from live pandas 2.2.3 `.astype(str)`, one column per rung.
12081    #[test]
12082    fn timestamp_string_resolution_and_formatting_match_pandas() {
12083        use super::{DatetimeStringResolution as Res, Timestamp};
12084
12085        const MIDNIGHT: i64 = 1_710_460_800_000_000_000; // 2024-03-15 00:00:00
12086
12087        // Which rung each value needs, on its own.
12088        assert_eq!(Timestamp::string_resolution(MIDNIGHT), Res::Date);
12089        assert_eq!(
12090            Timestamp::string_resolution(MIDNIGHT + 37_845_000_000_000),
12091            Res::Second
12092        );
12093        assert_eq!(
12094            Timestamp::string_resolution(MIDNIGHT + 37_845_123_000_000),
12095            Res::Milli
12096        );
12097        assert_eq!(
12098            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_000),
12099            Res::Micro
12100        );
12101        assert_eq!(
12102            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_789),
12103            Res::Nano
12104        );
12105        // A whole MINUTE is not its own rung — it still needs Second.
12106        assert_eq!(
12107            Timestamp::string_resolution(MIDNIGHT + 300_000_000_000),
12108            Res::Second
12109        );
12110        // NaT reports the coarsest rung, the identity of the `max` fold, which
12111        // is what keeps it from dragging a column to nanoseconds.
12112        assert_eq!(Timestamp::string_resolution(Timestamp::NAT), Res::Date);
12113
12114        // Coarsest-first ordering is what makes `max` mean "finest needed".
12115        assert!(Res::Date < Res::Second);
12116        assert!(Res::Second < Res::Milli);
12117        assert!(Res::Milli < Res::Micro);
12118        assert!(Res::Micro < Res::Nano);
12119
12120        // ...and how ONE value renders at each rung it might be forced into.
12121        let value = MIDNIGHT + 37_845_123_456_789;
12122        assert_eq!(
12123            Timestamp::format_at_resolution(value, Res::Date),
12124            "2024-03-15"
12125        );
12126        assert_eq!(
12127            Timestamp::format_at_resolution(value, Res::Second),
12128            "2024-03-15 10:30:45"
12129        );
12130        assert_eq!(
12131            Timestamp::format_at_resolution(value, Res::Milli),
12132            "2024-03-15 10:30:45.123"
12133        );
12134        assert_eq!(
12135            Timestamp::format_at_resolution(value, Res::Micro),
12136            "2024-03-15 10:30:45.123456"
12137        );
12138        assert_eq!(
12139            Timestamp::format_at_resolution(value, Res::Nano),
12140            "2024-03-15 10:30:45.123456789"
12141        );
12142
12143        // A midnight forced to the nanosecond rung keeps its zero fraction --
12144        // pandas pads, it does not trim.
12145        assert_eq!(
12146            Timestamp::format_at_resolution(MIDNIGHT, Res::Nano),
12147            "2024-03-15 00:00:00.000000000"
12148        );
12149
12150        // ⚠️ NOT isoformat: a SPACE separator, not a `T`.
12151        assert_eq!(
12152            Timestamp::format_at_resolution(MIDNIGHT, Res::Second),
12153            "2024-03-15 00:00:00"
12154        );
12155
12156        // NaT is the STRING "NaT" at every rung.
12157        for resolution in [Res::Date, Res::Second, Res::Milli, Res::Micro, Res::Nano] {
12158            assert_eq!(
12159                Timestamp::format_at_resolution(Timestamp::NAT, resolution),
12160                "NaT"
12161            );
12162        }
12163
12164        // Pre-epoch: rem_euclid must keep the fraction on the right side of
12165        // midnight, or -1ns renders as 1970-01-01 with a negative fraction.
12166        assert_eq!(
12167            Timestamp::format_at_resolution(-1, Res::Nano),
12168            "1969-12-31 23:59:59.999999999"
12169        );
12170
12171        // Both ends of pandas' datetime64[ns] range.
12172        assert_eq!(
12173            Timestamp::format_at_resolution(-9_223_372_036_854_775_806, Res::Nano),
12174            "1677-09-21 00:12:43.145224194"
12175        );
12176        assert_eq!(
12177            Timestamp::format_at_resolution(9_223_372_036_854_775_807, Res::Nano),
12178            "2262-04-11 23:47:16.854775807"
12179        );
12180    }
12181
12182    /// Temporal -> numpy `bool` is nonzero-truthy on the RAW NANOSECONDS, which
12183    /// makes NaT `true`. Transcribed from live pandas 2.2.3 `.astype('bool')`,
12184    /// measured beside `.astype('int64')` so the one rule is visible as one rule.
12185    #[test]
12186    fn cast_scalar_temporal_to_bool_is_nonzero_on_the_nanos() {
12187        use super::{Timedelta, Timestamp, cast_scalar};
12188
12189        // Only the epoch and a zero duration are false.
12190        for (nanos, want) in [
12191            (0_i64, false),
12192            (1_710_498_645_123_456_789, true),
12193            (-1, true),
12194            (86_400_000_000_000, true),
12195            (1, true),
12196        ] {
12197            assert_eq!(
12198                cast_scalar(&Scalar::Datetime64(nanos), DType::Bool).unwrap(),
12199                Scalar::Bool(want),
12200                "datetime64 {nanos} -> bool"
12201            );
12202            assert_eq!(
12203                cast_scalar(&Scalar::Timedelta64(nanos), DType::Bool).unwrap(),
12204                Scalar::Bool(want),
12205                "timedelta64 {nanos} -> bool"
12206            );
12207        }
12208
12209        // ⚠️ NaT IS TRUE, not missing. It needs no case of its own — NaT IS
12210        // i64::MIN, which is nonzero — but it only reaches the rule because the
12211        // cast sits ABOVE is_missing(); below it, both of these become Null.
12212        assert_eq!(
12213            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Bool).unwrap(),
12214            Scalar::Bool(true),
12215            "NaT -> bool is true in pandas, not a missing value"
12216        );
12217        assert_eq!(
12218            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Bool).unwrap(),
12219            Scalar::Bool(true)
12220        );
12221
12222        // ⚠️ THE NULLABLE `boolean` REFUSES THE WHOLE DTYPE, not just the odd
12223        // value: pandas raises "Need to pass bool-like values" for every row
12224        // above, INCLUDING the ones whose nanos are 0 or 1. That exclusion is
12225        // what the `DType::Bool` guard buys, so it is asserted rather than
12226        // assumed.
12227        //
12228        // NaT is deliberately NOT in this loop, and the reason is a KNOWN
12229        // DIVERGENCE rather than an oversight: `is_missing()` catches NaT before
12230        // any BoolNullable arm can refuse it, so FP answers `Null` where pandas
12231        // raises. Asserting `is_err()` for it here would fail. Left visible.
12232        for nanos in [0_i64, 1, -1, 1_710_498_645_123_456_789] {
12233            assert!(
12234                cast_scalar(&Scalar::Datetime64(nanos), DType::BoolNullable).is_err(),
12235                "datetime64 {nanos} -> nullable boolean must stay refused"
12236            );
12237            assert!(
12238                cast_scalar(&Scalar::Timedelta64(nanos), DType::BoolNullable).is_err(),
12239                "timedelta64 {nanos} -> nullable boolean must stay refused"
12240            );
12241        }
12242    }
12243
12244    #[test]
12245    fn nancount_nunique_prod_any_all_mx60x() {
12246        use super::{nanall, nanany, nancount, nannunique, nanprod};
12247        // br-frankenpandas-mx60x: nancount/nannunique/nanprod/nanany/nanall skip NaN
12248        // and match finite-only oracles. Seeded LCG, no mocks.
12249        let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
12250        let mut next = || {
12251            s = s
12252                .wrapping_mul(6_364_136_223_846_793_005)
12253                .wrapping_add(1_442_695_040_888_963_407);
12254            (s >> 33) as u32
12255        };
12256        let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
12257        let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
12258        for iter in 0..1000u32 {
12259            let n = (next() % 10) as usize + 1;
12260            let raw: Vec<f64> = (0..n)
12261                .map(|_| {
12262                    if next() % 4 == 0 {
12263                        f64::NAN
12264                    } else {
12265                        (next() % 5) as f64
12266                    }
12267                })
12268                .collect();
12269            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
12270            if finite.is_empty() {
12271                continue;
12272            }
12273            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
12274            let distinct: std::collections::HashSet<u64> =
12275                finite.iter().map(|x| x.to_bits()).collect();
12276            let prod: f64 = finite.iter().product();
12277            assert!(
12278                (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
12279                "nancount iter={iter}"
12280            );
12281            assert!(
12282                (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
12283                "nannunique iter={iter}"
12284            );
12285            assert!(
12286                (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
12287                "nanprod iter={iter}"
12288            );
12289            assert_eq!(
12290                asb(nanany(&scalars)),
12291                finite.iter().any(|&x| x != 0.0),
12292                "nanany iter={iter}"
12293            );
12294            assert_eq!(
12295                asb(nanall(&scalars)),
12296                finite.iter().all(|&x| x != 0.0),
12297                "nanall iter={iter}"
12298            );
12299        }
12300    }
12301
12302    #[test]
12303    fn nan_reduction_kernels_skip_correctness_1uagc() {
12304        use super::{nanmax, nanmedian, nanmin, nansum};
12305        // br-frankenpandas-1uagc: nansum/nanmin/nanmax/nanmedian skip NaN and match
12306        // finite-only oracles. Seeded LCG, no mocks.
12307        let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
12308        let mut next = || {
12309            s = s
12310                .wrapping_mul(6_364_136_223_846_793_005)
12311                .wrapping_add(1_442_695_040_888_963_407);
12312            (s >> 33) as u32
12313        };
12314        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
12315        for iter in 0..1000u32 {
12316            let n = (next() % 12) as usize + 1;
12317            let raw: Vec<f64> = (0..n)
12318                .map(|_| {
12319                    if next() % 4 == 0 {
12320                        f64::NAN
12321                    } else {
12322                        (next() % 200) as f64 - 100.0
12323                    }
12324                })
12325                .collect();
12326            let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
12327            if finite.is_empty() {
12328                continue;
12329            }
12330            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
12331            let sum: f64 = finite.iter().sum();
12332            let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
12333            let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
12334            finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
12335            let m = finite.len();
12336            let med = if m % 2 == 1 {
12337                finite[m / 2]
12338            } else {
12339                (finite[m / 2 - 1] + finite[m / 2]) / 2.0
12340            };
12341            assert!(
12342                (val(nansum(&scalars)) - sum).abs() < 1e-7,
12343                "nansum iter={iter}"
12344            );
12345            assert!(
12346                (val(nanmin(&scalars)) - mn).abs() < 1e-9,
12347                "nanmin iter={iter}"
12348            );
12349            assert!(
12350                (val(nanmax(&scalars)) - mx).abs() < 1e-9,
12351                "nanmax iter={iter}"
12352            );
12353            assert!(
12354                (val(nanmedian(&scalars)) - med).abs() < 1e-9,
12355                "nanmedian iter={iter}"
12356            );
12357        }
12358    }
12359
12360    #[test]
12361    fn nanvar_ddof_nanstd_nan_skip_p00ag() {
12362        use super::{nanmean, nanstd, nanvar};
12363        // br-frankenpandas-p00ag: nanmean/nanvar/nanstd skip NaN; ddof picks the
12364        // denominator; nanstd==sqrt(nanvar). Seeded LCG, no mocks.
12365        let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
12366        let mut next = || {
12367            s = s
12368                .wrapping_mul(6_364_136_223_846_793_005)
12369                .wrapping_add(1_442_695_040_888_963_407);
12370            (s >> 33) as u32
12371        };
12372        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
12373        for iter in 0..1000u32 {
12374            let n = (next() % 10) as usize + 2;
12375            let raw: Vec<f64> = (0..n)
12376                .map(|_| {
12377                    if next() % 4 == 0 {
12378                        f64::NAN
12379                    } else {
12380                        (next() % 200) as f64 / 7.0
12381                    }
12382                })
12383                .collect();
12384            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
12385            if finite.len() < 2 {
12386                continue;
12387            }
12388            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
12389            let nf = finite.len() as f64;
12390            let mean = finite.iter().sum::<f64>() / nf;
12391            let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
12392            assert!(
12393                (val(nanmean(&scalars)) - mean).abs() < 1e-7,
12394                "nanmean iter={iter}"
12395            );
12396            assert!(
12397                (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
12398                "nanvar ddof0 iter={iter}"
12399            );
12400            assert!(
12401                (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
12402                "nanvar ddof1 iter={iter}"
12403            );
12404            assert!(
12405                (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
12406                "nanstd ddof1 iter={iter}"
12407            );
12408        }
12409    }
12410
12411    #[test]
12412    fn nanskew_nankurt_min_sample_and_known_xybnq() {
12413        // br-frankenpandas-xybnq: guard nanskew/nankurt min-sample-size (NaN below
12414        // threshold) + known pandas G1/G2 values (the f4dc5540 inline-copy bug area).
12415        use super::{nankurt, nanskew};
12416        let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
12417        let val = |s: Scalar| -> Option<f64> {
12418            if s.is_missing() {
12419                None
12420            } else {
12421                s.to_f64().ok()
12422            }
12423        };
12424
12425        // skew needs >= 3 observations.
12426        assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
12427        let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
12428        assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
12429        let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
12430        assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
12431
12432        // kurt needs >= 4 observations.
12433        assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
12434        let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
12435        assert!(
12436            (k - (-1.2)).abs() < 1e-6,
12437            "pandas kurt([1..5]) == -1.2, got {k}"
12438        );
12439    }
12440
12441    #[test]
12442    #[ignore = "foreground release attribution harness"]
12443    fn nanskew_fused_moment_scan_ab_mavln() {
12444        const ROWS: usize = 100_000;
12445        const BATCH: usize = 8;
12446
12447        fn former(values: &[Scalar]) -> Scalar {
12448            let nums = super::collect_finite(values);
12449            let n = nums.len() as f64;
12450            if n < 3.0 {
12451                return Scalar::Null(NullKind::NaN);
12452            }
12453            let mean = nums.iter().sum::<f64>() / n;
12454            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12455            let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
12456            let s2 = m2 / (n - 1.0);
12457            if s2 == 0.0 {
12458                return Scalar::Float64(0.0);
12459            }
12460            let s3 = s2.powf(1.5);
12461            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
12462        }
12463
12464        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12465            match (former, candidate) {
12466                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12467                (a, b) => assert_eq!(a, b),
12468            }
12469        }
12470
12471        fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
12472            std::hint::black_box(skew(std::hint::black_box(values)));
12473            let started = std::time::Instant::now();
12474            for _ in 0..BATCH {
12475                std::hint::black_box(skew(std::hint::black_box(values)));
12476            }
12477            started.elapsed().as_nanos()
12478        }
12479
12480        fn median(samples: &mut [u128]) -> u128 {
12481            samples.sort_unstable();
12482            samples[samples.len() / 2]
12483        }
12484
12485        for values in [
12486            vec![],
12487            vec![Scalar::Int64(1), Scalar::Int64(2)],
12488            vec![Scalar::Int64(7); 16],
12489            vec![
12490                Scalar::Int64(-3),
12491                Scalar::Null(NullKind::NaN),
12492                Scalar::Float64(2.5),
12493                Scalar::Utf8("skip".to_owned()),
12494                Scalar::Int64(11),
12495            ],
12496        ] {
12497            assert_bits_eq(former(&values), super::nanskew(&values));
12498        }
12499
12500        let values = (0..ROWS)
12501            .map(|i| {
12502                if i % 257 == 0 {
12503                    Scalar::Null(NullKind::NaN)
12504                } else {
12505                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12506                }
12507            })
12508            .collect::<Vec<_>>();
12509        assert_bits_eq(former(&values), super::nanskew(&values));
12510
12511        for _ in 0..2 {
12512            std::hint::black_box(elapsed(&values, former));
12513            std::hint::black_box(elapsed(&values, super::nanskew));
12514        }
12515
12516        let mut former_samples = Vec::with_capacity(18);
12517        let mut candidate_samples = Vec::with_capacity(18);
12518        for block in 0_usize..9 {
12519            if block.is_multiple_of(2) {
12520                former_samples.push(elapsed(&values, former));
12521                candidate_samples.push(elapsed(&values, super::nanskew));
12522                candidate_samples.push(elapsed(&values, super::nanskew));
12523                former_samples.push(elapsed(&values, former));
12524            } else {
12525                candidate_samples.push(elapsed(&values, super::nanskew));
12526                former_samples.push(elapsed(&values, former));
12527                former_samples.push(elapsed(&values, former));
12528                candidate_samples.push(elapsed(&values, super::nanskew));
12529            }
12530        }
12531
12532        let former_p50 = median(&mut former_samples);
12533        let candidate_p50 = median(&mut candidate_samples);
12534        eprintln!(
12535            "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12536            former_p50 as f64 / candidate_p50 as f64,
12537        );
12538        eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
12539        eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12540    }
12541
12542    #[test]
12543    #[ignore = "foreground performance probe"]
12544    fn nankurt_fused_moment_scan_ab_idka7() {
12545        const ROWS: usize = 65_536;
12546        const BATCH: usize = 4;
12547
12548        fn former(values: &[Scalar]) -> Scalar {
12549            let nums = super::collect_finite(values);
12550            let n = nums.len() as f64;
12551            if n < 4.0 {
12552                return Scalar::Null(NullKind::NaN);
12553            }
12554            let mean = nums.iter().sum::<f64>() / n;
12555            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12556            let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
12557            let s2 = m2 / (n - 1.0);
12558            if s2 == 0.0 {
12559                return Scalar::Float64(0.0);
12560            }
12561            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
12562            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
12563            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
12564        }
12565
12566        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12567            match (former, candidate) {
12568                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12569                (a, b) => assert_eq!(a, b),
12570            }
12571        }
12572
12573        fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
12574            let started = std::time::Instant::now();
12575            for _ in 0..BATCH {
12576                std::hint::black_box(kurt(std::hint::black_box(values)));
12577            }
12578            started.elapsed().as_nanos()
12579        }
12580
12581        fn median(samples: &mut [u128]) -> u128 {
12582            samples.sort_unstable();
12583            samples[samples.len() / 2]
12584        }
12585
12586        for values in [
12587            vec![],
12588            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12589            vec![Scalar::Int64(7); 16],
12590            vec![
12591                Scalar::Int64(-3),
12592                Scalar::Null(NullKind::NaN),
12593                Scalar::Float64(2.5),
12594                Scalar::Utf8("skip".to_owned()),
12595                Scalar::Int64(11),
12596                Scalar::Float64(-7.25),
12597            ],
12598        ] {
12599            assert_bits_eq(former(&values), super::nankurt(&values));
12600        }
12601
12602        let values = (0..ROWS)
12603            .map(|i| {
12604                if i % 257 == 0 {
12605                    Scalar::Null(NullKind::NaN)
12606                } else {
12607                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12608                }
12609            })
12610            .collect::<Vec<_>>();
12611        assert_bits_eq(former(&values), super::nankurt(&values));
12612
12613        for _ in 0..2 {
12614            std::hint::black_box(elapsed(&values, former));
12615            std::hint::black_box(elapsed(&values, super::nankurt));
12616        }
12617
12618        let mut former_samples = Vec::with_capacity(10);
12619        let mut candidate_samples = Vec::with_capacity(10);
12620        for block in 0_usize..5 {
12621            if block.is_multiple_of(2) {
12622                former_samples.push(elapsed(&values, former));
12623                candidate_samples.push(elapsed(&values, super::nankurt));
12624                candidate_samples.push(elapsed(&values, super::nankurt));
12625                former_samples.push(elapsed(&values, former));
12626            } else {
12627                candidate_samples.push(elapsed(&values, super::nankurt));
12628                former_samples.push(elapsed(&values, former));
12629                former_samples.push(elapsed(&values, former));
12630                candidate_samples.push(elapsed(&values, super::nankurt));
12631            }
12632        }
12633
12634        let former_p50 = median(&mut former_samples);
12635        let candidate_p50 = median(&mut candidate_samples);
12636        eprintln!(
12637            "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12638            former_p50 as f64 / candidate_p50 as f64,
12639        );
12640        eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
12641        eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12642    }
12643
12644    /// behind astype/promotion. Property test of its confirmed identity +
12645    /// numeric/bool coercion rules over random scalars. Deterministic seeded LCG.
12646    #[test]
12647    fn cast_scalar_to_utf8_formatting_yes7i() {
12648        // Property (br-frankenpandas-yes7i): cast to Utf8 formats per pandas
12649        // astype(str): Int64 -> decimal, Bool -> True/False. Seeded LCG, no mocks.
12650        let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
12651        let mut next = || {
12652            st = st
12653                .wrapping_mul(6_364_136_223_846_793_005)
12654                .wrapping_add(1_442_695_040_888_963_407);
12655            (st >> 33) as u32
12656        };
12657        for _ in 0..3000u32 {
12658            let n = (next() % 4_000_001) as i64 - 2_000_000;
12659            assert_eq!(
12660                cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
12661                Scalar::Utf8(n.to_string())
12662            );
12663        }
12664        assert_eq!(
12665            cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
12666            Scalar::Utf8("True".to_string())
12667        );
12668        assert_eq!(
12669            cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
12670            Scalar::Utf8("False".to_string())
12671        );
12672    }
12673
12674    #[test]
12675    fn cast_scalar_coercion_rules_6a83t() {
12676        let mut state: u64 = 0x5a17_c0de_1234_abcd;
12677        let mut next = || {
12678            state = state
12679                .wrapping_mul(6_364_136_223_846_793_005)
12680                .wrapping_add(1_442_695_040_888_963_407);
12681            (state >> 33) as u32
12682        };
12683
12684        for _ in 0..4000u32 {
12685            let n = (next() % 21) as i64 - 10; // -10..=10, incl 0
12686            let b = next() % 2 == 0;
12687            let f = f64::from((next() % 41) as i32 - 20) / 4.0; // finite, incl 0.0
12688
12689            let i = Scalar::Int64(n);
12690            let bo = Scalar::Bool(b);
12691            let fl = Scalar::Float64(f);
12692
12693            // Identity casts.
12694            assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
12695            assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
12696            assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
12697
12698            // Representation-preserving nullable identities.
12699            assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
12700            assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
12701
12702            // Int64 coercions.
12703            assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
12704            assert_eq!(
12705                cast_scalar(&i, DType::Float64),
12706                Ok(Scalar::Float64(n as f64))
12707            );
12708
12709            // Bool coercions.
12710            assert_eq!(
12711                cast_scalar(&bo, DType::Int64),
12712                Ok(Scalar::Int64(i64::from(b)))
12713            );
12714            assert_eq!(
12715                cast_scalar(&bo, DType::Float64),
12716                Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
12717            );
12718
12719            // Finite Float64 -> Int64 truncates toward zero (x as i64).
12720            assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
12721        }
12722    }
12723
12724    /// br-frankenpandas-esjjy / fd90.182: ergonomic From impls for Scalar.
12725    #[test]
12726    fn scalar_from_primitive_types() {
12727        // Each primitive maps to its canonical Scalar variant.
12728        assert_eq!(Scalar::from(true), Scalar::Bool(true));
12729        assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
12730        assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
12731        assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
12732        assert_eq!(
12733            Scalar::from(String::from("world")),
12734            Scalar::Utf8("world".to_owned())
12735        );
12736
12737        // .into() works in mixed-type Vec<Scalar> contexts (the README's
12738        // case_when example pattern, and what fd90.181 needed for apply_row
12739        // closures).
12740        let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
12741        assert_eq!(mixed[0], Scalar::Int64(1));
12742        assert_eq!(mixed[1], Scalar::Float64(2.0));
12743        assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
12744    }
12745
12746    #[test]
12747    fn dtype_inference_routes_bool_numeric_mix_to_object_bucket_rh1od() {
12748        // Was `dtype_inference_coerces_numeric_values` (Bool+Int64+Float64 ->
12749        // Float64). br-frankenpandas-rh1od, MEASURED live pandas 2.2.3:
12750        // pd.Series([True, 7, 3.5]) constructs OBJECT — no pandas constructor
12751        // path produces the numpy common-type Float64 here.
12752        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
12753        assert_eq!(
12754            infer_dtype(&values).expect("dtype should infer"),
12755            DType::Utf8
12756        );
12757    }
12758
12759    #[test]
12760    fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
12761        let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
12762        let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
12763        assert_eq!(left.dtype(), DType::Interval);
12764        assert!(!left.is_missing());
12765        assert_eq!(
12766            infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
12767            DType::Interval
12768        );
12769        assert_eq!(
12770            common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
12771            DType::Interval
12772        );
12773        assert_eq!(
12774            cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
12775            Scalar::Null(NullKind::Null)
12776        );
12777        assert_eq!(
12778            cast_scalar(&left, DType::Utf8).expect("interval string cast"),
12779            Scalar::Utf8("(0.0, 1.0]".to_owned())
12780        );
12781        assert_eq!(
12782            super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
12783            Scalar::Int64(2)
12784        );
12785    }
12786
12787    #[test]
12788    fn cast_scalar_parses_temporal_extension_strings_avm08() {
12789        let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
12790            .expect("timestamp parse")
12791            .nanos;
12792        assert_eq!(
12793            cast_scalar(
12794                &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
12795                DType::datetime64_naive()
12796            )
12797            .expect("datetime cast"),
12798            Scalar::Datetime64(expected_nanos)
12799        );
12800        assert_eq!(
12801            cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
12802            Scalar::Period(Period::new(216, PeriodFreq::QUARTERLY))
12803        );
12804        assert_eq!(
12805            cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
12806                .expect("interval cast"),
12807            Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
12808        );
12809    }
12810
12811    #[test]
12812    fn missing_values_get_target_missing_marker() {
12813        let missing = Scalar::Null(NullKind::Null);
12814        let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
12815        assert_eq!(cast, Scalar::Null(NullKind::NaN));
12816    }
12817
12818    #[test]
12819    fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
12820        let cases = [
12821            (Scalar::Bool(true), "True"),
12822            (Scalar::Bool(false), "False"),
12823            (Scalar::Int64(-7), "-7"),
12824            (Scalar::Float64(1.0), "1.0"),
12825            (Scalar::Float64(1.5), "1.5"),
12826            (Scalar::Float64(f64::NAN), "nan"),
12827            (Scalar::Null(NullKind::Null), "None"),
12828            (Scalar::Null(NullKind::NaN), "nan"),
12829            (Scalar::Null(NullKind::NaT), "NaT"),
12830        ];
12831
12832        for (value, expected) in cases {
12833            assert_eq!(
12834                cast_scalar(&value, DType::Utf8).expect("cast"),
12835                Scalar::Utf8(expected.to_owned())
12836            );
12837        }
12838    }
12839
12840    #[test]
12841    fn semantic_eq_treats_nan_as_equal() {
12842        let left = Scalar::Float64(f64::NAN);
12843        let right = Scalar::Null(NullKind::NaN);
12844        assert!(left.semantic_eq(&right));
12845    }
12846
12847    #[test]
12848    fn semantic_eq_treats_nan_as_missing_null() {
12849        let left = Scalar::Float64(f64::NAN);
12850        let right = Scalar::Null(NullKind::Null);
12851        assert!(left.semantic_eq(&right));
12852    }
12853
12854    /// A DTYPE-SENTINEL missing equals a `Null` marker, for every dtype that
12855    /// has one.
12856    ///
12857    /// `missing_for_dtype` DEFINES the canonical missing for Timedelta64 as
12858    /// `Timedelta64(NAT)`, for Datetime64 as `Datetime64(NAT)` and for Period as
12859    /// ordinal `i64::MIN`, and `is_missing()` agrees — but `semantic_eq` used to
12860    /// unify only the `Null`/NaN flavours, so an oracle's `null` for pandas' NaT
12861    /// could never match FP's sentinel. Observed on
12862    /// `fp_p2d_021_series_to_timedelta_negative_null_hardened`, where the
12863    /// fixture pinned the raw `-9223372036854775808` as though it were data.
12864    ///
12865    /// THE NEGATIVE CASES ARE THE POINT — "both missing" must not become "any
12866    /// sentinel matches anything":
12867    /// - a NaT sentinel must NOT equal a PRESENT timedelta;
12868    /// - two DIFFERENT present timedeltas must stay unequal;
12869    /// - Period and Datetime64 must unify too, or the fix is Timedelta-only.
12870    ///
12871    /// (br-frankenpandas-xwxci)
12872    #[test]
12873    fn semantic_eq_unifies_dtype_sentinel_missing_with_null_xwxci() {
12874        for sentinel in [
12875            Scalar::Timedelta64(Timedelta::NAT),
12876            Scalar::Datetime64(Timestamp::NAT),
12877            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
12878        ] {
12879            assert!(sentinel.is_missing(), "{sentinel:?} must report missing");
12880            for marker in [
12881                Scalar::Null(NullKind::Null),
12882                Scalar::Null(NullKind::NaN),
12883                Scalar::Null(NullKind::NaT),
12884            ] {
12885                assert!(
12886                    sentinel.semantic_eq(&marker),
12887                    "{sentinel:?} vs {marker:?} are both missing"
12888                );
12889                assert!(marker.semantic_eq(&sentinel), "and symmetrically");
12890            }
12891        }
12892
12893        // NOT a blanket match: a sentinel differs from a PRESENT value.
12894        let present = Scalar::Timedelta64(-60);
12895        assert!(!Scalar::Timedelta64(Timedelta::NAT).semantic_eq(&present));
12896        assert!(!present.semantic_eq(&Scalar::Null(NullKind::Null)));
12897        // And two distinct present values stay distinct.
12898        assert!(!present.semantic_eq(&Scalar::Timedelta64(-61)));
12899    }
12900
12901    #[test]
12902    fn common_dtype_rejects_string_numeric_mix() {
12903        let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
12904        assert_eq!(
12905            err.to_string(),
12906            "dtype coercion from Utf8 to Int64 has no compatible common type"
12907        );
12908        let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
12909        assert_eq!(
12910            err.to_string(),
12911            "dtype coercion from Float64 to Utf8 has no compatible common type"
12912        );
12913    }
12914
12915    #[test]
12916    fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
12917        let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
12918
12919        assert_eq!(dtype.value_dtype, DType::Float64);
12920        assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
12921    }
12922
12923    #[test]
12924    fn sparse_dtype_rejects_sparse_value_dtype() {
12925        let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
12926
12927        assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
12928    }
12929
12930    #[test]
12931    fn common_dtype_rejects_sparse_dense_mix() {
12932        let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
12933
12934        assert_eq!(
12935            err.to_string(),
12936            "dtype coercion from Sparse to Int64 has no compatible common type"
12937        );
12938    }
12939
12940    // ── Nullable Int64/Bool dtype tests (br-frankenpandas-rg8ys.6.4) ────
12941
12942    #[test]
12943    fn nullable_int64_promotion_matrix() {
12944        // Int64 + Int64Nullable -> Int64Nullable (nullable absorbs)
12945        assert_eq!(
12946            common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
12947            DType::Int64Nullable
12948        );
12949        assert_eq!(
12950            common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
12951            DType::Int64Nullable
12952        );
12953
12954        // Int64Nullable + Float64 -> Float64Nullable. The old comment here said
12955        // "float always wins"; that is half right. The float wins, but the
12956        // NULLABLE flavour of it does — MEASURED, live pandas 2.2.3:
12957        //   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5]) -> Float64
12958        // where that Float64 is the extension dtype (missing = pd.NA), not
12959        // numpy float64 (missing = NaN). (br-frankenpandas-qkqfb)
12960        assert_eq!(
12961            common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
12962            DType::Float64Nullable
12963        );
12964        assert_eq!(
12965            common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
12966            DType::Float64Nullable
12967        );
12968
12969        // Int64Nullable + Int64Nullable -> Int64Nullable
12970        assert_eq!(
12971            common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
12972            DType::Int64Nullable
12973        );
12974
12975        // Bool + Int64Nullable -> Int64Nullable
12976        assert_eq!(
12977            common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
12978            DType::Int64Nullable
12979        );
12980
12981        // BoolNullable + Int64 -> Int64Nullable
12982        assert_eq!(
12983            common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
12984            DType::Int64Nullable
12985        );
12986    }
12987
12988    #[test]
12989    fn nullable_bool_promotion_matrix() {
12990        // Bool + BoolNullable -> BoolNullable
12991        assert_eq!(
12992            common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
12993            DType::BoolNullable
12994        );
12995        assert_eq!(
12996            common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
12997            DType::BoolNullable
12998        );
12999
13000        // BoolNullable + Float64 -> Float64Nullable. MEASURED, live pandas 2.2.3:
13001        //   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
13002        //     -> Float64   (extension)
13003        // This arm moves together with the Int64Nullable one in
13004        // nullable_int64_promotion_matrix; flipping either alone breaks lattice
13005        // associativity. (br-frankenpandas-qkqfb)
13006        assert_eq!(
13007            common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
13008            DType::Float64Nullable
13009        );
13010
13011        // CONTROL: the all-numpy pair is untouched and stays on the numpy side.
13012        //   pd.Series([True,False],dtype="bool") + pd.Series([1.5,2.5]) -> float64
13013        assert_eq!(
13014            common_dtype(DType::Bool, DType::Float64).unwrap(),
13015            DType::Float64
13016        );
13017    }
13018
13019    #[test]
13020    fn dtype_is_nullable_helper() {
13021        assert!(DType::Int64Nullable.is_nullable());
13022        assert!(DType::BoolNullable.is_nullable());
13023        assert!(!DType::Int64.is_nullable());
13024        assert!(!DType::Bool.is_nullable());
13025        assert!(!DType::Float64.is_nullable());
13026        assert!(!DType::Utf8.is_nullable());
13027    }
13028
13029    #[test]
13030    fn dtype_to_nullable_conversions() {
13031        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
13032        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
13033        // ⚠ THIS LINE WAS RED ON main SINCE fa6caee91 AND NOBODY SAW IT.
13034        // It used to read `Float64.to_nullable() == Float64  // unchanged`,
13035        // which was true only while FP had no nullable float at all. fa6caee91
13036        // (br-frankenpandas-qkqfb slice 1) added DType::Float64Nullable and
13037        // pointed to_nullable at it, but that commit was gated with
13038        // `cargo check --all-targets` plus a NAME-FILTERED test run, so this
13039        // pre-existing test was never executed and the break went unnoticed.
13040        // Float64's nullable flavour IS Float64Nullable — that is the dtype's
13041        // entire reason to exist — so the assertion is what was stale.
13042        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
13043        assert_eq!(
13044            DType::Float64Nullable.to_nullable(),
13045            DType::Float64Nullable,
13046            "idempotent: already nullable"
13047        );
13048        assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
13049    }
13050
13051    #[test]
13052    fn dtype_to_non_nullable_conversions() {
13053        assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
13054        assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
13055        assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); // unchanged
13056        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
13057    }
13058
13059    #[test]
13060    fn nullable_dtype_name_reports_pandas_style() {
13061        assert_eq!(DType::Int64.name(), "int64");
13062        assert_eq!(DType::Int64Nullable.name(), "Int64"); // capital I
13063        assert_eq!(DType::Bool.name(), "bool");
13064        assert_eq!(DType::BoolNullable.name(), "boolean");
13065    }
13066
13067    #[test]
13068    fn cast_scalar_int64_nullable_identity() {
13069        let val = Scalar::Int64(42);
13070        // Int64 -> Int64Nullable is identity (no actual conversion)
13071        let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
13072        assert_eq!(result, Scalar::Int64(42));
13073
13074        // Int64Nullable -> Int64 is also identity
13075        let result2 = cast_scalar(&val, DType::Int64).unwrap();
13076        assert_eq!(result2, Scalar::Int64(42));
13077    }
13078
13079    #[test]
13080    fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
13081        // pandas astype(str) of floats == Python str(float): whole -> ".0",
13082        // shortest round-trip decimals, scientific (e+NN/e-NN) for large/small,
13083        // inf -> "inf", NaN -> "nan". Verified vs live pandas 2.2.3. (Previously
13084        // large/small lost scientific notation, e.g. 1e16 -> "10000000000000000.0".)
13085        let cases: &[(f64, &str)] = &[
13086            (1.0, "1.0"),
13087            (2.5, "2.5"),
13088            (100.0, "100.0"),
13089            (0.1, "0.1"),
13090            (0.0001, "0.0001"),
13091            (1e16, "1e+16"),
13092            (1e20, "1e+20"),
13093            (1e-5, "1e-05"),
13094            (1e-7, "1e-07"),
13095            (f64::INFINITY, "inf"),
13096            (f64::NEG_INFINITY, "-inf"),
13097        ];
13098        for (v, expected) in cases {
13099            assert_eq!(
13100                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13101                Scalar::Utf8((*expected).to_owned()),
13102                "float {v} -> str"
13103            );
13104        }
13105    }
13106
13107    fn float_to_string_for_astype_former(value: f64) -> String {
13108        if value.is_nan() {
13109            return "nan".to_owned();
13110        }
13111        if value.is_infinite() {
13112            return value.to_string();
13113        }
13114        let rendered = format!("{value:?}");
13115        match rendered.split_once('e') {
13116            None => rendered,
13117            Some((mantissa, exponent)) => {
13118                let (sign, digits) = match exponent.strip_prefix('-') {
13119                    Some(digits) => ('-', digits),
13120                    None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
13121                };
13122                format!("{mantissa}e{sign}{digits:0>2}")
13123            }
13124        }
13125    }
13126
13127    fn scientific_astype_values(len: usize) -> Vec<f64> {
13128        const EXPONENTS: [i32; 16] = [
13129            -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
13130        ];
13131        (0..len)
13132            .map(|position| {
13133                let mantissa = 1.0 + (position % 997) as f64 / 997.0;
13134                let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
13135                if position.is_multiple_of(2) {
13136                    magnitude
13137                } else {
13138                    -magnitude
13139                }
13140            })
13141            .collect()
13142    }
13143
13144    #[test]
13145    fn float_to_string_for_astype_in_place_matches_former() {
13146        let fixed = [
13147            f64::NAN,
13148            f64::INFINITY,
13149            f64::NEG_INFINITY,
13150            0.0,
13151            -0.0,
13152            f64::MIN_POSITIVE,
13153            f64::MAX,
13154            f64::MIN,
13155            1e16,
13156            -1e16,
13157            1e-5,
13158            -1e-5,
13159            1.234_567_890_123_456_8e20,
13160            -9.876_543_210_987_654e-123,
13161        ];
13162        for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
13163            assert_eq!(
13164                super::float_to_string_for_astype(value),
13165                float_to_string_for_astype_former(value),
13166                "value={value:?}"
13167            );
13168        }
13169    }
13170
13171    #[test]
13172    #[ignore = "foreground performance probe"]
13173    fn float_to_string_for_astype_in_place_ab() {
13174        use std::time::Instant;
13175
13176        const VALUES: usize = 16_384;
13177        const SAMPLES: usize = 10;
13178        let values = scientific_astype_values(VALUES);
13179        for &value in &values {
13180            let former = float_to_string_for_astype_former(value);
13181            assert!(former.contains('e'), "benchmark value must be scientific");
13182            assert_eq!(super::float_to_string_for_astype(value), former);
13183        }
13184
13185        for _ in 0..2 {
13186            for &value in &values {
13187                std::hint::black_box(float_to_string_for_astype_former(value));
13188                std::hint::black_box(super::float_to_string_for_astype(value));
13189            }
13190        }
13191
13192        let mut former_ns = Vec::with_capacity(SAMPLES);
13193        let mut public_ns = Vec::with_capacity(SAMPLES);
13194        for sample in 0..SAMPLES {
13195            let run = |formatter: fn(f64) -> String| {
13196                let started = Instant::now();
13197                for &value in std::hint::black_box(&values) {
13198                    std::hint::black_box(formatter(std::hint::black_box(value)));
13199                }
13200                started.elapsed().as_nanos()
13201            };
13202            if sample.is_multiple_of(2) {
13203                former_ns.push(run(float_to_string_for_astype_former));
13204                public_ns.push(run(super::float_to_string_for_astype));
13205            } else {
13206                public_ns.push(run(super::float_to_string_for_astype));
13207                former_ns.push(run(float_to_string_for_astype_former));
13208            }
13209        }
13210
13211        former_ns.sort_unstable();
13212        public_ns.sort_unstable();
13213        let former_p50 = former_ns[SAMPLES / 2];
13214        let public_p50 = public_ns[SAMPLES / 2];
13215        println!(
13216            "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:?}",
13217            former_p50 as f64 / public_p50 as f64
13218        );
13219    }
13220
13221    #[test]
13222    fn cast_float_to_utf8_threshold_boundaries_match_python() {
13223        // Python str(float) switches to scientific notation only at |x| >= 1e16
13224        // or |x| < 1e-4. Values JUST INSIDE those bounds must stay decimal — a
13225        // formatter that switches to sci early (or late) diverges. All expected
13226        // values verified against Python 3 str()/repr (== pandas astype(str)).
13227        let cases: &[(f64, &str)] = &[
13228            (1e15, "1000000000000000.0"),
13229            (9_999_999_999_999_998.0, "9999999999999998.0"),
13230            (1_234_567_890_123_456.0, "1234567890123456.0"),
13231            (123_456_789_012_345.0, "123456789012345.0"),
13232            (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
13233            (1e16, "1e+16"),
13234            (1.5e16, "1.5e+16"),
13235            (1e17, "1e+17"),
13236            (1e-4, "0.0001"),
13237            (5e-5, "5e-05"),
13238            (-1e15, "-1000000000000000.0"),
13239            (-1e16, "-1e+16"),
13240            (-1e-5, "-1e-05"),
13241        ];
13242        for (v, expected) in cases {
13243            assert_eq!(
13244                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13245                Scalar::Utf8((*expected).to_owned()),
13246                "float {v} -> str"
13247            );
13248        }
13249    }
13250
13251    #[test]
13252    fn cast_to_bool_uses_pandas_nonzero_truthiness() {
13253        // pandas astype(bool): zero -> False, any nonzero -> True (not just 0/1),
13254        // -0.0 -> False, and NaN -> True (numpy bool(nan), br-cyi4h). Verified vs
13255        // live pandas 2.2.3.
13256        let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
13257        for (v, expected) in cases_int {
13258            assert_eq!(
13259                cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
13260                Scalar::Bool(*expected),
13261                "int {v} -> bool"
13262            );
13263        }
13264        let cases_float: &[(f64, bool)] = &[
13265            (0.0, false),
13266            (-0.0, false),
13267            (0.1, true),
13268            (2.5, true),
13269            (1.0, true),
13270            // pandas astype(bool): NaN is truthy -> True (numpy bool). br-cyi4h.
13271            (f64::NAN, true),
13272        ];
13273        for (v, expected) in cases_float {
13274            assert_eq!(
13275                cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
13276                Scalar::Bool(*expected),
13277                "float {v} -> bool"
13278            );
13279        }
13280    }
13281
13282    #[test]
13283    fn nullable_dtype_is_extension() {
13284        assert!(DType::Int64Nullable.is_extension());
13285        assert!(DType::BoolNullable.is_extension());
13286        assert!(!DType::Int64.is_extension());
13287        assert!(!DType::Bool.is_extension());
13288    }
13289
13290    #[test]
13291    fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
13292        let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
13293        assert_eq!(
13294            infer_dtype(&values).expect("dtype should infer"),
13295            DType::Utf8
13296        );
13297    }
13298
13299    #[test]
13300    fn infer_dtype_routes_bool_numeric_mix_to_utf8_object_bucket_rh1od() {
13301        // br-frankenpandas-rh1od, MEASURED live pandas 2.2.3: a bool mixed
13302        // with any numeric scalar constructs OBJECT ([True, 2] -> object,
13303        // payloads preserved); numpy's bool<int common-type never fires at
13304        // the constructor. Discriminating: before the change this inferred
13305        // Int64 and coerced True -> 1.
13306        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Bool(false)];
13307        assert_eq!(
13308            infer_dtype(&values).expect("dtype should infer"),
13309            DType::Utf8
13310        );
13311        let with_float = vec![Scalar::Int64(1), Scalar::Float64(2.5), Scalar::Bool(true)];
13312        assert_eq!(
13313            infer_dtype(&with_float).expect("dtype should infer"),
13314            DType::Utf8
13315        );
13316        let with_null = vec![
13317            Scalar::Bool(true),
13318            Scalar::Null(NullKind::Null),
13319            Scalar::Int64(2),
13320        ];
13321        assert_eq!(
13322            infer_dtype(&with_null).expect("dtype should infer"),
13323            DType::Utf8
13324        );
13325    }
13326
13327    #[test]
13328    fn infer_dtype_keeps_nonmixed_bool_and_numeric_paths_rh1od() {
13329        // Pure bool stays bool; numeric-only mixes keep the common_dtype
13330        // lattice (int+float -> float64) — the object bucket is ONLY for the
13331        // cross-family mix.
13332        assert_eq!(
13333            infer_dtype(&[Scalar::Bool(true), Scalar::Bool(false)]).expect("dtype should infer"),
13334            DType::Bool
13335        );
13336        assert_eq!(
13337            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]).expect("dtype should infer"),
13338            DType::Float64
13339        );
13340    }
13341
13342    // ── Scalar missingness methods ─────────────────────────────────────
13343
13344    #[test]
13345    fn is_null_detects_explicit_nulls() {
13346        assert!(Scalar::Null(NullKind::Null).is_null());
13347        assert!(Scalar::Null(NullKind::NaN).is_null());
13348        assert!(!Scalar::Int64(42).is_null());
13349        assert!(!Scalar::Float64(f64::NAN).is_null());
13350    }
13351
13352    #[test]
13353    fn is_na_matches_is_missing() {
13354        let vals = vec![
13355            Scalar::Null(NullKind::Null),
13356            Scalar::Float64(f64::NAN),
13357            Scalar::Int64(0),
13358            Scalar::Bool(false),
13359        ];
13360        for v in &vals {
13361            assert_eq!(v.is_na(), v.is_missing());
13362        }
13363    }
13364
13365    #[test]
13366    fn coalesce_picks_first_non_missing() {
13367        let null = Scalar::Null(NullKind::Null);
13368        let fill = Scalar::Int64(99);
13369        assert_eq!(null.coalesce(&fill), fill);
13370        assert_eq!(fill.coalesce(&null), fill);
13371    }
13372
13373    // ── Missingness utilities ──────────────────────────────────────────
13374
13375    #[test]
13376    fn isna_notna_complement() {
13377        let vals = vec![
13378            Scalar::Int64(1),
13379            Scalar::Null(NullKind::Null),
13380            Scalar::Float64(f64::NAN),
13381            Scalar::Float64(3.0),
13382        ];
13383        let na = super::isna(&vals);
13384        let not = super::notna(&vals);
13385        assert_eq!(na, vec![false, true, true, false]);
13386        for (a, b) in na.iter().zip(not.iter()) {
13387            assert_ne!(a, b);
13388        }
13389    }
13390
13391    #[test]
13392    fn count_na_counts_missing() {
13393        let vals = vec![
13394            Scalar::Int64(1),
13395            Scalar::Null(NullKind::Null),
13396            Scalar::Float64(f64::NAN),
13397        ];
13398        assert_eq!(super::count_na(&vals), 2);
13399    }
13400
13401    #[test]
13402    fn fill_na_replaces_missing() {
13403        let vals = vec![
13404            Scalar::Int64(1),
13405            Scalar::Null(NullKind::Null),
13406            Scalar::Float64(f64::NAN),
13407            Scalar::Int64(4),
13408        ];
13409        let filled = super::fill_na(&vals, &Scalar::Int64(0));
13410        assert_eq!(filled[0], Scalar::Int64(1));
13411        assert_eq!(filled[1], Scalar::Int64(0));
13412        assert_eq!(filled[2], Scalar::Int64(0));
13413        assert_eq!(filled[3], Scalar::Int64(4));
13414    }
13415
13416    #[test]
13417    fn dropna_removes_missing() {
13418        let vals = vec![
13419            Scalar::Int64(1),
13420            Scalar::Null(NullKind::Null),
13421            Scalar::Int64(3),
13422            Scalar::Float64(f64::NAN),
13423        ];
13424        let kept = super::dropna(&vals);
13425        assert_eq!(kept.len(), 2);
13426        assert_eq!(kept[0], Scalar::Int64(1));
13427        assert_eq!(kept[1], Scalar::Int64(3));
13428    }
13429
13430    #[test]
13431    fn null_helpers_match_scalar_oracle_imt0c() {
13432        // Differential vs independent scalar null-helper oracle
13433        // (br-frankenpandas-imt0c). Seeded LCG, no mocks.
13434        fn next(seed: &mut u64) -> u64 {
13435            *seed = seed
13436                .wrapping_mul(3202034522624059733)
13437                .wrapping_add(4354685564936845319);
13438            *seed
13439        }
13440
13441        fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
13442            let expected_missing = values.iter().filter(|value| value.is_missing()).count();
13443            let expected_dropped = values
13444                .iter()
13445                .filter(|value| !value.is_missing())
13446                .cloned()
13447                .collect::<Vec<_>>();
13448            let expected_filled = values
13449                .iter()
13450                .map(|value| {
13451                    if value.is_missing() {
13452                        fill.clone()
13453                    } else {
13454                        value.clone()
13455                    }
13456                })
13457                .collect::<Vec<_>>();
13458
13459            assert_eq!(
13460                super::count_na(values),
13461                expected_missing,
13462                "case={case}: count_na mismatch for {values:?}"
13463            );
13464
13465            let dropped = super::dropna(values);
13466            assert_eq!(
13467                dropped.len(),
13468                expected_dropped.len(),
13469                "case={case}: dropna length mismatch for {values:?}"
13470            );
13471            for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
13472            {
13473                assert!(
13474                    actual.semantic_eq(expected),
13475                    "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
13476                );
13477            }
13478
13479            let filled = super::fill_na(values, fill);
13480            assert_eq!(
13481                filled.len(),
13482                expected_filled.len(),
13483                "case={case}: fill_na length mismatch for {values:?}"
13484            );
13485            for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
13486                assert!(
13487                    actual.semantic_eq(expected),
13488                    "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
13489                );
13490            }
13491        }
13492
13493        let all_missing = [
13494            Scalar::Null(NullKind::Null),
13495            Scalar::Null(NullKind::NaN),
13496            Scalar::Float64(f64::NAN),
13497            Scalar::Timedelta64(i64::MIN),
13498        ];
13499        assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
13500
13501        let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
13502        for case in 0..260 {
13503            let len = (next(&mut seed) % 83 + 1) as usize;
13504            let mut values = Vec::with_capacity(len);
13505            for pos in 0..len {
13506                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13507                values.push(match next(&mut seed) % 11 {
13508                    0 => Scalar::Null(NullKind::Null),
13509                    1 => Scalar::Null(NullKind::NaN),
13510                    2 => Scalar::Float64(f64::NAN),
13511                    3 => Scalar::Timedelta64(i64::MIN),
13512                    4 => Scalar::Bool(raw & 1 == 0),
13513                    5 => Scalar::Int64(raw),
13514                    6 => Scalar::Float64(raw as f64 / 37.0),
13515                    7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
13516                    8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
13517                    9 => Scalar::Utf8(String::new()),
13518                    _ => Scalar::Timedelta64(raw),
13519                });
13520            }
13521
13522            let fill = match case % 5 {
13523                0 => Scalar::Bool(true),
13524                1 => Scalar::Int64(-777),
13525                2 => Scalar::Float64(12.5),
13526                3 => Scalar::Utf8("filled".into()),
13527                _ => Scalar::Timedelta64(123_456),
13528            };
13529            assert_null_helpers(case, &values, &fill);
13530        }
13531    }
13532
13533    // ── Nanops ─────────────────────────────────────────────────────────
13534
13535    #[test]
13536    fn nansum_skips_nulls() {
13537        let vals = vec![
13538            Scalar::Float64(1.0),
13539            Scalar::Null(NullKind::Null),
13540            Scalar::Float64(2.0),
13541            Scalar::Float64(f64::NAN),
13542            Scalar::Int64(7),
13543        ];
13544        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
13545    }
13546
13547    #[test]
13548    fn nansum_empty_returns_zero() {
13549        assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
13550    }
13551
13552    #[test]
13553    fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
13554        // Differential vs independent sum/mean oracles
13555        // (br-frankenpandas-1xmi7). Seeded LCG, no mocks.
13556        fn next(seed: &mut u64) -> u64 {
13557            *seed = seed
13558                .wrapping_mul(6364136223846793005)
13559                .wrapping_add(1442695040888963407);
13560            *seed
13561        }
13562
13563        fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
13564            let mut sum = 0.0;
13565            let mut count = 0usize;
13566            for value in values {
13567                if value.is_missing() {
13568                    continue;
13569                }
13570                if let Ok(value) = value.to_f64() {
13571                    sum += value;
13572                    count += 1;
13573                }
13574            }
13575            let mean = if count == 0 {
13576                Scalar::Null(NullKind::NaN)
13577            } else {
13578                Scalar::Float64(sum / count as f64)
13579            };
13580            (Scalar::Float64(sum), mean)
13581        }
13582
13583        fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
13584            let mut sum = 0_i128;
13585            let mut count = 0_i128;
13586            for value in values {
13587                if let Scalar::Timedelta64(ns) = value
13588                    && !value.is_missing()
13589                {
13590                    sum += i128::from(*ns);
13591                    count += 1;
13592                }
13593            }
13594            if count == 0 {
13595                return (Scalar::Timedelta64(0), Scalar::Timedelta64(Timedelta::NAT));
13596            }
13597            // br-frankenpandas-opz27: this reference oracle used to clamp, which
13598            // is the exact behaviour the production path was just fixed away
13599            // from. Keeping the clamp here would leave the oracle blessing a
13600            // contradicted rule (it only ever agreed because these inputs do
13601            // not overflow). Mirror the representable-range contract instead.
13602            (
13603                super::timedelta_ns_to_scalar(sum),
13604                super::timedelta_ns_to_scalar(sum / count),
13605            )
13606        }
13607
13608        fn assert_sum_mean(
13609            case: usize,
13610            family: &str,
13611            values: &[Scalar],
13612            expected_sum: Scalar,
13613            expected_mean: Scalar,
13614        ) {
13615            let actual_sum = super::nansum(values);
13616            let actual_mean = super::nanmean(values);
13617            assert!(
13618                actual_sum.semantic_eq(&expected_sum),
13619                "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
13620            );
13621            assert!(
13622                actual_mean.semantic_eq(&expected_mean),
13623                "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
13624            );
13625        }
13626
13627        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13628        let (sum, mean) = expected_numeric(&all_missing);
13629        assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
13630
13631        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
13632        let (sum, mean) = expected_timedelta(&td_all_missing);
13633        assert_sum_mean(
13634            usize::MAX - 1,
13635            "timedelta_all_missing",
13636            &td_all_missing,
13637            sum,
13638            mean,
13639        );
13640
13641        let mut seed = 0x511d_ed5a_7a11_1a55_u64;
13642        for case in 0..260 {
13643            let len = (next(&mut seed) % 89 + 1) as usize;
13644
13645            let mut numeric = Vec::with_capacity(len);
13646            numeric.push(Scalar::Int64(case as i64 - 130));
13647            for _ in 1..len {
13648                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13649                numeric.push(match next(&mut seed) % 8 {
13650                    0 => Scalar::Null(NullKind::Null),
13651                    1 => Scalar::Null(NullKind::NaN),
13652                    2 => Scalar::Float64(f64::NAN),
13653                    3 => Scalar::Bool(raw & 1 == 0),
13654                    4 => Scalar::Int64(raw % 257),
13655                    5 => Scalar::Float64(raw as f64 / 67.0),
13656                    6 => Scalar::Float64(0.0),
13657                    _ => Scalar::Float64(-0.0),
13658                });
13659            }
13660            let (sum, mean) = expected_numeric(&numeric);
13661            assert_sum_mean(case, "numeric", &numeric, sum, mean);
13662
13663            let mut timedeltas = Vec::with_capacity(len);
13664            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
13665            for _ in 1..len {
13666                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13667                timedeltas.push(match next(&mut seed) % 7 {
13668                    0 => Scalar::Null(NullKind::Null),
13669                    1 => Scalar::Timedelta64(i64::MIN),
13670                    _ => Scalar::Timedelta64(raw),
13671                });
13672            }
13673            let (sum, mean) = expected_timedelta(&timedeltas);
13674            assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
13675        }
13676    }
13677
13678    #[test]
13679    fn nannunique_merges_negative_zero_and_zero() {
13680        let vals = vec![
13681            Scalar::Float64(-0.0),
13682            Scalar::Float64(0.0),
13683            Scalar::Float64(1.0),
13684        ];
13685        assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
13686    }
13687
13688    #[test]
13689    fn nannunique_matches_scalar_bucket_oracle_elvbg() {
13690        // Differential vs independent scalar unique-bucket oracle
13691        // (br-frankenpandas-elvbg). Seeded LCG, no mocks.
13692        fn next(seed: &mut u64) -> u64 {
13693            *seed = seed
13694                .wrapping_mul(2862933555777941757)
13695                .wrapping_add(3037000493);
13696            *seed
13697        }
13698
13699        fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
13700            match (left, right) {
13701                (Scalar::Float64(left), Scalar::Float64(right)) => {
13702                    let left = if *left == 0.0 { 0.0 } else { *left };
13703                    let right = if *right == 0.0 { 0.0 } else { *right };
13704                    left.to_bits() == right.to_bits()
13705                }
13706                _ => left == right,
13707            }
13708        }
13709
13710        fn expected_nunique(values: &[Scalar]) -> i64 {
13711            let mut seen = Vec::<Scalar>::new();
13712            for value in values {
13713                if value.is_missing() {
13714                    continue;
13715                }
13716                if !seen.iter().any(|existing| same_bucket(existing, value)) {
13717                    seen.push(value.clone());
13718                }
13719            }
13720            seen.len() as i64
13721        }
13722
13723        fn assert_nannunique(case: usize, values: &[Scalar]) {
13724            assert_eq!(
13725                super::nannunique(values),
13726                Scalar::Int64(expected_nunique(values)),
13727                "case={case}: nannunique mismatch for {values:?}"
13728            );
13729        }
13730
13731        assert_nannunique(
13732            usize::MAX,
13733            &[
13734                Scalar::Float64(-0.0),
13735                Scalar::Float64(0.0),
13736                Scalar::Float64(f64::NAN),
13737                Scalar::Null(NullKind::Null),
13738                Scalar::Timedelta64(i64::MIN),
13739            ],
13740        );
13741
13742        let mut seed = 0x0e1b_60d0_b5e7_u64;
13743        for case in 0..320 {
13744            let len = (next(&mut seed) % 97 + 1) as usize;
13745            let mut values = Vec::with_capacity(len);
13746            for pos in 0..len {
13747                let raw = (next(&mut seed) % 1_001) as i64 - 500;
13748                values.push(match next(&mut seed) % 11 {
13749                    0 => Scalar::Null(NullKind::Null),
13750                    1 => Scalar::Null(NullKind::NaN),
13751                    2 => Scalar::Float64(f64::NAN),
13752                    3 => Scalar::Bool(raw & 1 == 0),
13753                    4 => Scalar::Int64(raw % 37),
13754                    5 => Scalar::Float64(raw as f64 / 19.0),
13755                    6 => Scalar::Float64(0.0),
13756                    7 => Scalar::Float64(-0.0),
13757                    8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
13758                    9 => Scalar::Utf8(String::new()),
13759                    _ => Scalar::Timedelta64(raw % 41),
13760                });
13761            }
13762            assert_nannunique(case, &values);
13763        }
13764    }
13765
13766    #[test]
13767    fn nanmean_basic() {
13768        let vals = vec![
13769            Scalar::Float64(2.0),
13770            Scalar::Null(NullKind::Null),
13771            Scalar::Float64(4.0),
13772        ];
13773        assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
13774    }
13775
13776    #[test]
13777    fn nanmean_all_null_returns_nan() {
13778        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13779        assert!(super::nanmean(&vals).is_missing());
13780    }
13781
13782    #[test]
13783    fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
13784        // Per br-frankenpandas-620mj: pandas td_series.sum()/mean() return
13785        // Timedelta64, not Float64(0.0). Was silently zero before because
13786        // collect_finite drops Timedelta64 (to_f64 errors).
13787        let one_hour = 3_600 * 1_000_000_000_i64;
13788        let vals = vec![
13789            Scalar::Timedelta64(one_hour),
13790            Scalar::Timedelta64(2 * one_hour),
13791            Scalar::Timedelta64(3 * one_hour),
13792        ];
13793        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
13794        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13795    }
13796
13797    #[test]
13798    fn nansum_nanmean_timedelta64_skips_nat_620mj() {
13799        let one_hour = 3_600 * 1_000_000_000_i64;
13800        let vals = vec![
13801            Scalar::Timedelta64(Timedelta::NAT),
13802            Scalar::Timedelta64(one_hour),
13803            Scalar::Timedelta64(3 * one_hour),
13804            Scalar::Timedelta64(Timedelta::NAT),
13805        ];
13806        // NAT is missing → skipped. Sum: 1h+3h=4h; mean: 2h.
13807        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
13808        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13809    }
13810
13811    /// br-frankenpandas-opz27: the Timedelta reduction surface used to narrow
13812    /// its exact i128 accumulator with `clamp(i64::MIN, i64::MAX)`, which
13813    /// fabricated a finite Timedelta.max on positive overflow. Live pandas
13814    /// 2.2.3 raises `ValueError: overflow in timedelta operation` here; FP
13815    /// surfaces NaT per the lgyy8 convention. A clamping implementation
13816    /// returns `Timedelta64(i64::MAX)` and fails this.
13817    #[test]
13818    fn nansum_timedelta_overflow_is_nat_not_fabricated_max_opz27() {
13819        let vals = vec![Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MAX)];
13820        let got = super::nansum(&vals);
13821        assert!(
13822            got.is_missing(),
13823            "overflowing sum must be missing, got {got:?}"
13824        );
13825        assert_eq!(got, Scalar::Timedelta64(Timedelta::NAT));
13826        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13827    }
13828
13829    /// The negative direction used to reach NaT only *by accident*, because
13830    /// `Timedelta::NAT == i64::MIN` is exactly the clamp's lower bound — and
13831    /// that bound is off by one against the true minimum (`i64::MIN + 1`).
13832    /// Pin both the sentinel and the boundary so the accident becomes a rule.
13833    #[test]
13834    fn nansum_timedelta_negative_overflow_is_nat_opz27() {
13835        let min_repr = i64::MIN + 1; // Timedelta.min; i64::MIN is the NaT sentinel
13836        let vals = vec![Scalar::Timedelta64(min_repr), Scalar::Timedelta64(min_repr)];
13837        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(Timedelta::NAT));
13838
13839        // Exactly the most-negative representable total stays a real value and
13840        // must NOT collapse into the sentinel one nanosecond above it.
13841        let exact = vec![Scalar::Timedelta64(min_repr + 1), Scalar::Timedelta64(-1)];
13842        let got = super::nansum(&exact);
13843        assert_eq!(got, Scalar::Timedelta64(min_repr));
13844        assert!(!got.is_missing(), "Timedelta.min is representable, not NaT");
13845    }
13846
13847    /// pandas 2.2.3: `Series([Timedelta.min, Timedelta.max]).max() - .min()`
13848    /// raises OverflowError. FP used `saturating_sub`, fabricating
13849    /// Timedelta.max as a plausible range.
13850    #[test]
13851    fn nanptp_timedelta_overflow_is_nat_opz27() {
13852        let vals = vec![
13853            Scalar::Timedelta64(i64::MIN + 1),
13854            Scalar::Timedelta64(i64::MAX),
13855        ];
13856        let got = super::nanptp(&vals);
13857        assert!(
13858            got.is_missing(),
13859            "unrepresentable range must be NaT, got {got:?}"
13860        );
13861        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13862
13863        // A representable range is still exact to the nanosecond (the reason
13864        // this path avoids f64 at all).
13865        let hour = 3_600 * 1_000_000_000_i64;
13866        let ok = vec![Scalar::Timedelta64(hour), Scalar::Timedelta64(4 * hour)];
13867        assert_eq!(super::nanptp(&ok), Scalar::Timedelta64(3 * hour));
13868    }
13869
13870    /// The load-bearing cumsum case: accumulation stays exact in i128, so only
13871    /// the *unrepresentable* index goes NaT and a later index that returns to
13872    /// range emits its true value. A clamping implementation pins `running` at
13873    /// i64::MAX and can never produce the final value, so it fails this test.
13874    #[test]
13875    fn nancumsum_timedelta_overflow_recovers_exact_value_opz27() {
13876        let vals = vec![
13877            Scalar::Timedelta64(i64::MAX),
13878            Scalar::Timedelta64(i64::MAX), // true total 2*i64::MAX: unrepresentable
13879            Scalar::Timedelta64(i64::MIN + 1), // back in range: total == i64::MAX
13880        ];
13881        let out = super::nancumsum(&vals);
13882        assert_eq!(out.len(), 3);
13883        assert_eq!(out[0], Scalar::Timedelta64(i64::MAX));
13884        assert!(
13885            out[1].is_missing(),
13886            "overflowed index must be NaT, got {:?}",
13887            out[1]
13888        );
13889        assert_eq!(
13890            out[2],
13891            Scalar::Timedelta64(i64::MAX),
13892            "exact i128 accumulation must recover; a clamped running sum cannot"
13893        );
13894    }
13895
13896    /// Non-overflowing cumsum is unchanged bit-for-bit, and input NaT still
13897    /// passes through without advancing the running total.
13898    #[test]
13899    fn nancumsum_timedelta_exact_path_unchanged_opz27() {
13900        let sec = 1_000_000_000_i64;
13901        let vals = vec![
13902            Scalar::Timedelta64(sec),
13903            Scalar::Timedelta64(Timedelta::NAT),
13904            Scalar::Timedelta64(2 * sec),
13905        ];
13906        let out = super::nancumsum(&vals);
13907        assert_eq!(out[0], Scalar::Timedelta64(sec));
13908        assert!(out[1].is_missing());
13909        assert_eq!(out[2], Scalar::Timedelta64(3 * sec));
13910    }
13911
13912    const DAY_NS: i64 = 86_400 * 1_000_000_000;
13913    /// 2020-01-01T00:00:00Z in epoch nanoseconds.
13914    const DT_2020: i64 = 1_577_836_800_000_000_000;
13915
13916    /// br-frankenpandas-axhhk: every one of these returned `Null(NaN)` (or
13917    /// `None`) before the Datetime64 arms existed, because `Datetime64::to_f64()`
13918    /// errors and each reduction fell through to the f64 catch-all. Expectations
13919    /// are the live pandas 2.2.3 answers for
13920    /// `Series([2020-01-01, +60d, +31d])`:
13921    ///   min 2020-01-01 · max 2020-03-01 · ptp Timedelta 60 days
13922    ///   argmin 0 · argmax 1 · cummax/cummin Timestamps
13923    #[test]
13924    fn datetime64_ordering_reductions_match_pandas_axhhk() {
13925        let d = Scalar::Datetime64;
13926        let vals = vec![
13927            d(DT_2020),
13928            d(DT_2020 + 60 * DAY_NS),
13929            d(DT_2020 + 31 * DAY_NS),
13930        ];
13931
13932        assert_eq!(super::nanmin(&vals), d(DT_2020));
13933        assert_eq!(super::nanmax(&vals), d(DT_2020 + 60 * DAY_NS));
13934        assert_eq!(super::nanargmin(&vals), Some(0));
13935        assert_eq!(super::nanargmax(&vals), Some(1));
13936
13937        // ptp of two INSTANTS is a DURATION: Timedelta64, not Datetime64.
13938        let span = super::nanptp(&vals);
13939        assert_eq!(span, Scalar::Timedelta64(60 * DAY_NS));
13940        assert_eq!(span.dtype(), DType::Timedelta64);
13941
13942        assert_eq!(
13943            super::nancummax(&vals),
13944            vec![
13945                d(DT_2020),
13946                d(DT_2020 + 60 * DAY_NS),
13947                d(DT_2020 + 60 * DAY_NS)
13948            ]
13949        );
13950        assert_eq!(
13951            super::nancummin(&vals),
13952            vec![d(DT_2020), d(DT_2020), d(DT_2020)]
13953        );
13954    }
13955
13956    /// The size-dependence is the part that made this bug quiet, so pin it
13957    /// explicitly rather than only asserting the headline. A ONE-element
13958    /// datetime slice was always correct (the `(None, _)` arm seeds `min`
13959    /// before any comparison runs); TWO elements hit the catch-all and
13960    /// returned NaN. A regression that drops the Datetime64 arm would still
13961    /// pass a single-element test.
13962    #[test]
13963    fn datetime64_min_max_size_dependence_pinned_axhhk() {
13964        let d = Scalar::Datetime64;
13965        let one = vec![d(DT_2020)];
13966        assert_eq!(super::nanmin(&one), d(DT_2020));
13967        assert_eq!(super::nanmax(&one), d(DT_2020));
13968
13969        let two = vec![d(DT_2020 + DAY_NS), d(DT_2020)];
13970        let got_min = super::nanmin(&two);
13971        assert!(
13972            !got_min.is_missing(),
13973            "2-element datetime min must not be missing, got {got_min:?}"
13974        );
13975        assert_eq!(got_min, d(DT_2020));
13976        assert_eq!(super::nanmax(&two), d(DT_2020 + DAY_NS));
13977    }
13978
13979    /// NaT still skips, and a datetime span too large for i64 surfaces NaT via
13980    /// the shared opz27 narrowing rather than a fabricated extreme.
13981    #[test]
13982    fn datetime64_reductions_skip_nat_and_guard_span_overflow_axhhk() {
13983        let d = Scalar::Datetime64;
13984        let with_nat = vec![
13985            d(Timestamp::NAT),
13986            d(DT_2020 + 31 * DAY_NS),
13987            d(DT_2020),
13988            d(Timestamp::NAT),
13989        ];
13990        assert_eq!(super::nanmin(&with_nat), d(DT_2020));
13991        assert_eq!(super::nanmax(&with_nat), d(DT_2020 + 31 * DAY_NS));
13992        assert_eq!(super::nanptp(&with_nat), Scalar::Timedelta64(31 * DAY_NS));
13993        // argmin/argmax report positions in the ORIGINAL slice, NaT skipped.
13994        assert_eq!(super::nanargmin(&with_nat), Some(2));
13995        assert_eq!(super::nanargmax(&with_nat), Some(1));
13996
13997        // Span exceeding i64 ns: NaT, never a fabricated Timedelta.max.
13998        let huge = vec![d(i64::MIN + 1), d(i64::MAX)];
13999        let span = super::nanptp(&huge);
14000        assert!(span.is_missing(), "unrepresentable span must be NaT");
14001        assert_ne!(span, Scalar::Timedelta64(i64::MAX));
14002    }
14003
14004    /// br-frankenpandas-adv58: mean/median/quantile returned `Null(NaN)` for
14005    /// datetime input. Expectations are the live pandas 2.2.3 answers for
14006    /// `Series([2020-01-01, +60d, +31d])`, which at day granularity pandas
14007    /// computes exactly:
14008    ///   mean 2020-01-31T08:00 · median 2020-02-01 · q0.5 2020-02-01
14009    ///   q0.25 2020-01-16T12:00
14010    #[test]
14011    fn datetime64_averaging_reductions_match_pandas_adv58() {
14012        let d = Scalar::Datetime64;
14013        let vals = vec![
14014            d(DT_2020),
14015            d(DT_2020 + 60 * DAY_NS),
14016            d(DT_2020 + 31 * DAY_NS),
14017        ];
14018        // 1580457600e9 / 1580515200e9 / 1579176000e9, straight from the probe.
14019        assert_eq!(super::nanmean(&vals), d(1_580_457_600_000_000_000));
14020        assert_eq!(super::nanmedian(&vals), d(1_580_515_200_000_000_000));
14021        assert_eq!(super::nanquantile(&vals, 0.5), d(1_580_515_200_000_000_000));
14022        assert_eq!(
14023            super::nanquantile(&vals, 0.25),
14024            d(1_579_176_000_000_000_000)
14025        );
14026    }
14027
14028    /// The even-count rounding rule, probed at 1 ns granularity where pandas is
14029    /// exact. It is TRUNCATION TOWARD ZERO — plain Rust integer division.
14030    /// `floor` would give -1 for [-1,0]; ties-to-even would give 2 for [1,2].
14031    /// Both are refuted by these cases, so this test discriminates against the
14032    /// two rounding rules a reimplementation is most likely to pick.
14033    #[test]
14034    fn datetime64_mean_median_round_toward_zero_adv58() {
14035        let d = Scalar::Datetime64;
14036        for (a, b, want) in [
14037            (0_i64, 1_i64, 0_i64),
14038            (0, 3, 1),
14039            (1, 2, 1),
14040            (-1, 0, 0),
14041            (-3, 0, -1),
14042            (-2, -1, -1),
14043            (0, 2, 1),
14044            (-2, 0, -1),
14045        ] {
14046            let vals = vec![d(a), d(b)];
14047            assert_eq!(
14048                super::nanmean(&vals),
14049                d(want),
14050                "mean of [{a}, {b}] should be {want}"
14051            );
14052            assert_eq!(
14053                super::nanmedian(&vals),
14054                d(want),
14055                "median of [{a}, {b}] should be {want}"
14056            );
14057        }
14058    }
14059
14060    /// NaT is skipped, and an all-NaT datetime input stays in the Datetime
14061    /// family rather than degrading to a numeric NaN.
14062    #[test]
14063    fn datetime64_averaging_skips_nat_adv58() {
14064        let d = Scalar::Datetime64;
14065        let vals = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14066        // pandas: mean == median == 2020-01-02, count 2.
14067        assert_eq!(super::nanmean(&vals), d(DT_2020 + DAY_NS));
14068        assert_eq!(super::nanmedian(&vals), d(DT_2020 + DAY_NS));
14069
14070        let all_nat = vec![d(Timestamp::NAT), d(Timestamp::NAT)];
14071        let got = super::nanmean(&all_nat);
14072        assert!(
14073            got.is_missing(),
14074            "all-NaT mean must be missing, got {got:?}"
14075        );
14076        assert_eq!(
14077            got.dtype(),
14078            DType::datetime64_naive(),
14079            "must stay Datetime64"
14080        );
14081    }
14082
14083    /// FP is EXACT here and pandas is not: pandas routes datetime
14084    /// mean/median/quantile through f64, so at 2020-era magnitudes (~1.58e18,
14085    /// f64 ULP 256 ns) it snaps to a 256 ns grid — it returns B+0 for the mean
14086    /// of the CONSTANT series [B+1, B+1], and for an odd-count median it can
14087    /// return a Timestamp that is not even one of the inputs. FP keeps the
14088    /// exact i128 treatment its Timedelta sibling already had. DISC-019.
14089    #[test]
14090    fn datetime64_averaging_is_exact_where_pandas_snaps_adv58() {
14091        let d = Scalar::Datetime64;
14092
14093        // Constant series: the answer is unambiguous; pandas still loses it.
14094        let constant = vec![d(DT_2020 + 1), d(DT_2020 + 1)];
14095        assert_eq!(super::nanmean(&constant), d(DT_2020 + 1));
14096        assert_eq!(super::nanmedian(&constant), d(DT_2020 + 1));
14097
14098        // Odd-count median is a SELECTION: the result must be an input value.
14099        let odd = vec![d(DT_2020), d(DT_2020 + 129), d(DT_2020 + 258)];
14100        let med = super::nanmedian(&odd);
14101        assert_eq!(med, d(DT_2020 + 129));
14102        assert!(
14103            odd.contains(&med),
14104            "odd-count median must be one of the inputs; pandas returns B+256, which is not"
14105        );
14106    }
14107
14108    /// br-frankenpandas-40ujm: datetime std returned `Null(NaN)`; pandas 2.2.3
14109    /// returns a Timedelta. Every value below is the probed oracle answer for
14110    /// `Series([2020-01-01, +60d, +31d])`, in raw ns:
14111    ///   ddof=1 (default) 2592479955563784   ddof=0 2116751019841492
14112    ///   ddof=2           3666320313338702   ddof=3 NaT (n - ddof <= 0)
14113    /// pandas truncates the sqrt toward zero (ddof=0 is 2116751019841492.8).
14114    #[test]
14115    fn datetime64_std_matches_pandas_ddof_variants_40ujm() {
14116        let d = Scalar::Datetime64;
14117        let vals = vec![
14118            d(DT_2020),
14119            d(DT_2020 + 60 * DAY_NS),
14120            d(DT_2020 + 31 * DAY_NS),
14121        ];
14122        // Dispersion of instants is a DURATION: Timedelta64, not Datetime64.
14123        let s1 = super::nanstd(&vals, 1);
14124        assert_eq!(s1, Scalar::Timedelta64(2_592_479_955_563_784));
14125        assert_eq!(s1.dtype(), DType::Timedelta64);
14126        assert_eq!(
14127            super::nanstd(&vals, 0),
14128            Scalar::Timedelta64(2_116_751_019_841_492)
14129        );
14130        assert_eq!(
14131            super::nanstd(&vals, 2),
14132            Scalar::Timedelta64(3_666_320_313_338_702)
14133        );
14134        // n - ddof <= 0 => NaT, matching pandas.
14135        assert!(super::nanstd(&vals, 3).is_missing());
14136    }
14137
14138    /// pandas returns the SAME std for a Datetime64 series and a Timedelta64
14139    /// series built from identical ns. That equivalence is the whole basis for
14140    /// routing both families through one computation, so pin it directly.
14141    #[test]
14142    fn datetime64_std_equals_timedelta64_std_on_same_ns_40ujm() {
14143        let offsets = [0_i64, 60 * DAY_NS, 31 * DAY_NS];
14144        let dt: Vec<Scalar> = offsets.iter().map(|o| Scalar::Datetime64(*o)).collect();
14145        let td: Vec<Scalar> = offsets.iter().map(|o| Scalar::Timedelta64(*o)).collect();
14146        assert_eq!(super::nanstd(&dt, 1), super::nanstd(&td, 1));
14147        assert_eq!(
14148            super::nanstd(&dt, 1),
14149            Scalar::Timedelta64(2_592_479_955_563_784)
14150        );
14151    }
14152
14153    /// NaT skips (a 3-element series with one NaT must equal the 2-element
14154    /// series without it), a single element gives NaT at the default ddof, and
14155    /// var/sem stay REFUSED for datetimes because pandas raises on them.
14156    #[test]
14157    fn datetime64_std_skips_nat_and_var_sem_stay_unsupported_40ujm() {
14158        let d = Scalar::Datetime64;
14159        let with_nat = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14160        let without = vec![d(DT_2020), d(DT_2020 + 2 * DAY_NS)];
14161        // pandas: both are Timedelta 1 days 09:56:28.051789035.
14162        assert_eq!(super::nanstd(&with_nat, 1), super::nanstd(&without, 1));
14163        assert_eq!(
14164            super::nanstd(&with_nat, 1),
14165            Scalar::Timedelta64(122_188_051_789_035)
14166        );
14167
14168        // n=1 with ddof=1 -> NaT, as pandas returns.
14169        assert!(super::nanstd(&[d(DT_2020)], 1).is_missing());
14170        assert!(super::nanstd(&[d(Timestamp::NAT)], 1).is_missing());
14171
14172        // pandas RAISES TypeError for datetime64 var and sem. FP must not
14173        // invent a value: these stay on the Timedelta-only gate and report
14174        // missing. A regression that widened them would return a number here.
14175        let vals = vec![d(DT_2020), d(DT_2020 + 60 * DAY_NS)];
14176        assert!(super::nanvar(&vals, 1).is_missing());
14177        assert!(super::nansem(&vals, 1).is_missing());
14178    }
14179
14180    /// br-frankenpandas-qoabs: Period is the THIRD dtype whose `to_f64()`
14181    /// errors, so min/max fell into the f64 catch-all and returned
14182    /// `Null(NaN)`. pandas 2.2.3 on `Series([2020-01, 2020-03, 2020-02], M)`
14183    /// gives min 2020-01 and max 2020-03; ordinals are 600/601/602.
14184    #[test]
14185    fn period_min_max_match_pandas_qoabs() {
14186        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14187        let vals = vec![p(600), p(602), p(601)];
14188        assert_eq!(super::nanmin(&vals), p(600));
14189        assert_eq!(super::nanmax(&vals), p(602));
14190
14191        // Size-dependence, exactly as in axhhk: ONE element always worked via
14192        // the `(None, _)` seed, so a test with a single value would pass even
14193        // with no Period arm at all. Assert both sizes.
14194        assert_eq!(super::nanmin(&[p(600)]), p(600));
14195        let two = vec![p(602), p(600)];
14196        assert!(!super::nanmin(&two).is_missing());
14197        assert_eq!(super::nanmin(&two), p(600));
14198        assert_eq!(super::nanmax(&two), p(602));
14199    }
14200
14201    /// A Period whose ordinal is the NaT sentinel is missing and skipped, and
14202    /// an all-missing Period input reports missing rather than a value.
14203    #[test]
14204    fn period_min_max_skip_nat_qoabs() {
14205        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14206        let nat = Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly));
14207        let vals = vec![nat.clone(), p(602), p(600), nat.clone()];
14208        assert_eq!(super::nanmin(&vals), p(600));
14209        assert_eq!(super::nanmax(&vals), p(602));
14210        assert!(super::nanmin(&[nat.clone(), nat]).is_missing());
14211    }
14212
14213    /// MIXED FREQ must not be ordered. pandas refuses it outright
14214    /// (`IncompatibleFrequency: Input has different freq=D from Period(freq=M)`),
14215    /// so FP reports missing rather than inventing an order. This is the test
14216    /// that discriminates: an implementation comparing raw ordinals would
14217    /// happily return a value here, because monthly 2020-01 is ordinal 600
14218    /// while daily 2020-01-05 is 18267 — it would call the daily period later.
14219    #[test]
14220    fn period_mixed_freq_is_not_ordered_qoabs() {
14221        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
14222        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
14223        let vals = vec![month.clone(), day.clone()];
14224        let got_min = super::nanmin(&vals);
14225        assert!(
14226            got_min.is_missing(),
14227            "mixed-freq Period min must not be ordered, got {got_min:?}"
14228        );
14229        assert_ne!(
14230            got_min, day,
14231            "must not rank the daily period by raw ordinal"
14232        );
14233        assert!(super::nanmax(&vals).is_missing());
14234    }
14235
14236    /// br-frankenpandas-d7zjp: the rest of the Period reduction family, which
14237    /// qoabs deferred because a `fn(i64) -> Scalar` constructor cannot carry a
14238    /// freq. Expectations are the probed pandas 2.2.3 answers for
14239    /// `Series([2020-01, 2020-03, 2020-02], freq=M)` (ordinals 600/601/602):
14240    ///   median 2020-02 · quantile(0.5) 2020-02 · idxmin 0 · idxmax 1
14241    ///   cummax ends 2020-03 · cummin ends 2020-01
14242    #[test]
14243    fn period_full_reduction_family_matches_pandas_d7zjp() {
14244        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14245        let vals = vec![p(600), p(602), p(601)];
14246
14247        assert_eq!(super::nanmedian(&vals), p(601));
14248        assert_eq!(super::nanquantile(&vals, 0.5), p(601));
14249        assert_eq!(super::nanargmin(&vals), Some(0));
14250        assert_eq!(super::nanargmax(&vals), Some(1));
14251        assert_eq!(super::nancummax(&vals), vec![p(600), p(602), p(602)]);
14252        assert_eq!(super::nancummin(&vals), vec![p(600), p(600), p(600)]);
14253    }
14254
14255    /// Even-count Period median picks by TRUNCATION TOWARD ZERO on the ordinal,
14256    /// the same rule the datetime family uses. Probed: pandas gives 2020-02 for
14257    /// [2020-01, 2020-04] (ordinals 600/603, midpoint 601.5) and 2020-01 for
14258    /// [2020-01, 2020-02] (600/601, midpoint 600.5).
14259    #[test]
14260    fn period_even_count_median_truncates_toward_zero_d7zjp() {
14261        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14262        assert_eq!(super::nanmedian(&[p(600), p(603)]), p(601));
14263        assert_eq!(super::nanmedian(&[p(600), p(601)]), p(600));
14264    }
14265
14266    /// MIXED FREQ must not be ordered by ANY of these, for the same reason as
14267    /// in qoabs: pandas raises IncompatibleFrequency, and raw ordinals are not
14268    /// comparable across freqs (monthly 2020-01 is 600, daily 2020-01-05 is
14269    /// 18267). The family enum encodes the freq, so a mixed input is simply not
14270    /// one family and never reaches a typed arm.
14271    #[test]
14272    fn period_mixed_freq_not_ordered_by_any_reduction_d7zjp() {
14273        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
14274        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
14275        let vals = vec![month, day];
14276
14277        assert!(super::nanmedian(&vals).is_missing());
14278        assert!(super::nanquantile(&vals, 0.5).is_missing());
14279        assert_eq!(super::nanargmin(&vals), None);
14280        assert_eq!(super::nanargmax(&vals), None);
14281        // The cumulative ops must not emit an ordered Period column either.
14282        assert!(super::nancummax(&vals).iter().all(Scalar::is_missing));
14283        assert!(super::nancummin(&vals).iter().all(Scalar::is_missing));
14284    }
14285
14286    /// pandas RAISES for Period mean/sum/std/var ("does not support reduction",
14287    /// and for mean explicitly "the meaning is ambiguous"). FP must not invent
14288    /// values. `std` is the trap here: the family enum puts Period one line
14289    /// away from the Datetime64 arm that 40ujm deliberately widened, so this
14290    /// asserts the guard holds.
14291    #[test]
14292    fn period_unsupported_reductions_stay_missing_d7zjp() {
14293        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14294        let vals = vec![p(600), p(602), p(601)];
14295        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
14296        assert!(super::nanvar(&vals, 1).is_missing(), "pandas raises var");
14297        assert!(super::nansem(&vals, 1).is_missing(), "pandas raises sem");
14298        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
14299    }
14300
14301    /// br-frankenpandas-srqdo: Interval is the FOURTH dtype whose `to_f64()`
14302    /// errors, so min/max fell into the f64 catch-all and returned
14303    /// `Null(NaN)`. pandas 2.2.3 on `IntervalArray.from_tuples([(0,1),(4,5),(2,3)])`
14304    /// gives min `(0, 1]` and max `(4, 5]`.
14305    #[test]
14306    fn interval_min_max_match_pandas_srqdo() {
14307        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14308        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
14309        assert_eq!(super::nanmin(&vals), iv(0.0, 1.0));
14310        assert_eq!(super::nanmax(&vals), iv(4.0, 5.0));
14311
14312        // Size-dependence, per the axhhk lesson: ONE element always worked via
14313        // the `(None, _)` seed, so a single-value test passes even with no arm.
14314        assert_eq!(super::nanmin(&[iv(2.0, 3.0)]), iv(2.0, 3.0));
14315        let two = vec![iv(4.0, 5.0), iv(0.0, 1.0)];
14316        assert!(!super::nanmin(&two).is_missing());
14317        assert_eq!(super::nanmin(&two), iv(0.0, 1.0));
14318        assert_eq!(super::nanmax(&two), iv(4.0, 5.0));
14319    }
14320
14321    /// The tie-on-left case, which is what discriminates a correct (left, right)
14322    /// comparison from one that only looks at `left`. pandas: Interval(0,2) <
14323    /// Interval(0,5) is True. An implementation comparing left alone keeps
14324    /// whichever came first and returns the wrong element here.
14325    #[test]
14326    fn interval_ties_on_left_order_by_right_srqdo() {
14327        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14328        let vals = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
14329        assert_eq!(super::nanmin(&vals), iv(0.0, 2.0));
14330        assert_eq!(super::nanmax(&vals), iv(0.0, 9.0));
14331    }
14332
14333    /// A NaN bound has no pandas counterpart — `IntervalArray` refuses to build
14334    /// one ("missing values must be missing in the same location both left and
14335    /// right") — so it must report missing rather than impose an arbitrary
14336    /// order. Critically this must NOT panic: the obvious
14337    /// `partial_cmp().unwrap()` implementation would.
14338    #[test]
14339    fn interval_nan_bound_is_not_ordered_srqdo() {
14340        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14341        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
14342        assert!(super::nanmin(&vals).is_missing());
14343        assert!(super::nanmax(&vals).is_missing());
14344    }
14345
14346    /// pandas RAISES or NotImplementedErrors every other reduction for
14347    /// Interval (median/mean/sum/std/quantile/cummax). FP must not invent
14348    /// values, so they stay missing.
14349    #[test]
14350    fn interval_unsupported_reductions_stay_missing_srqdo() {
14351        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14352        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
14353        assert!(super::nanmedian(&vals).is_missing(), "pandas raises median");
14354        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
14355        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
14356        assert!(
14357            super::nanquantile(&vals, 0.5).is_missing(),
14358            "pandas raises quantile"
14359        );
14360        assert!(
14361            super::nancummax(&vals).iter().all(Scalar::is_missing),
14362            "pandas NotImplementedErrors cummax"
14363        );
14364    }
14365
14366    /// br-frankenpandas-2h9dm: Interval argmin/argmax returned None, because
14367    /// `Interval::to_f64()` errors and the f64 fallback skipped every element.
14368    /// All four expectations are probed pandas 2.2.3 `idxmin`/`idxmax`.
14369    #[test]
14370    fn interval_argmin_argmax_match_pandas_2h9dm() {
14371        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14372        // pandas: idxmin 1, idxmax 0
14373        let vals = vec![iv(4.0, 5.0), iv(0.0, 1.0), iv(2.0, 3.0)];
14374        assert_eq!(super::nanargmin(&vals), Some(1));
14375        assert_eq!(super::nanargmax(&vals), Some(0));
14376
14377        // Left-tie resolves by RIGHT. pandas: idxmin 1, idxmax 2. An
14378        // implementation comparing only `left` keeps index 0 for both.
14379        let tie = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
14380        assert_eq!(super::nanargmin(&tie), Some(1));
14381        assert_eq!(super::nanargmax(&tie), Some(2));
14382    }
14383
14384    /// Duplicated extreme returns the FIRST occurrence (pandas idxmin 0 on
14385    /// [(0,1),(0,1),(9,9)]), and missing entries are skipped while the returned
14386    /// index stays a position in the ORIGINAL slice (pandas idxmin 2 / idxmax 0
14387    /// on [(4,5), None, (0,1)]).
14388    #[test]
14389    fn interval_arg_first_occurrence_and_missing_2h9dm() {
14390        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14391        let dup = vec![iv(0.0, 1.0), iv(0.0, 1.0), iv(9.0, 9.0)];
14392        assert_eq!(
14393            super::nanargmin(&dup),
14394            Some(0),
14395            "first occurrence, not last"
14396        );
14397        assert_eq!(super::nanargmax(&dup), Some(2));
14398
14399        let with_missing = vec![iv(4.0, 5.0), Scalar::Null(NullKind::NaN), iv(0.0, 1.0)];
14400        assert_eq!(super::nanargmin(&with_missing), Some(2));
14401        assert_eq!(super::nanargmax(&with_missing), Some(0));
14402    }
14403
14404    /// A NaN bound is not orderable, so decline rather than return an arbitrary
14405    /// index — and critically, do not panic the way `partial_cmp().unwrap()`
14406    /// would.
14407    #[test]
14408    fn interval_arg_nan_bound_declines_2h9dm() {
14409        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14410        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
14411        assert_eq!(super::nanargmin(&vals), None);
14412        assert_eq!(super::nanargmax(&vals), None);
14413    }
14414
14415    /// br-frankenpandas-fyr1z-policy-carrier-f29nz: the load-bearing guarantee
14416    /// of this bead is NO DEFAULT BEHAVIOR CHANGE. Prove it rather than assert
14417    /// it: over a seeded corpus that deliberately straddles the i64 boundary
14418    /// and the NaT sentinel, every infallible helper must equal its fallible
14419    /// sibling resolved under the default `SurfaceNat` policy — which is also
14420    /// exactly what the pre-f29nz bodies computed.
14421    #[test]
14422    fn overflow_policy_carrier_preserves_default_behavior_f29nz() {
14423        // Seeded LCG, no rand dependency (see [[differential-test-coverage]]).
14424        let mut state: u64 = 0x5DEE_CE66_D125_1F00;
14425        let mut next = || {
14426            state = state
14427                .wrapping_mul(6_364_136_223_846_793_005)
14428                .wrapping_add(1_442_695_040_888_963_407);
14429            state
14430        };
14431        // Edge values first, then random ones. i64::MIN is the NaT sentinel.
14432        let mut corpus: Vec<i64> = vec![
14433            0,
14434            1,
14435            -1,
14436            2,
14437            -2,
14438            i64::MAX,
14439            i64::MIN,
14440            i64::MIN + 1,
14441            i64::MAX - 1,
14442            i64::MAX / 2,
14443            -(i64::MAX / 2),
14444        ];
14445        for _ in 0..400 {
14446            let raw = next() as i64;
14447            corpus.push(raw);
14448            corpus.push(raw / 3);
14449        }
14450
14451        let policy = super::OverflowPolicy::default();
14452        assert_eq!(
14453            policy,
14454            super::OverflowPolicy::SurfaceNat,
14455            "default must not move"
14456        );
14457
14458        for &a in &corpus {
14459            for &b in &corpus {
14460                // Timedelta::add / sub / mul_scalar
14461                assert_eq!(
14462                    Timedelta::add(a, b),
14463                    policy
14464                        .resolve(Timedelta::try_add(a, b), Timedelta::NAT)
14465                        .expect("SurfaceNat never errors"),
14466                    "add({a}, {b}) diverged"
14467                );
14468                assert_eq!(
14469                    Timedelta::sub(a, b),
14470                    policy
14471                        .resolve(Timedelta::try_sub(a, b), Timedelta::NAT)
14472                        .expect("SurfaceNat never errors"),
14473                    "sub({a}, {b}) diverged"
14474                );
14475                assert_eq!(
14476                    Timedelta::mul_scalar(a, b),
14477                    policy
14478                        .resolve(Timedelta::try_mul_scalar(a, b), Timedelta::NAT)
14479                        .expect("SurfaceNat never errors"),
14480                    "mul_scalar({a}, {b}) diverged"
14481                );
14482
14483                // Timestamp::{add,sub}_timedelta / sub_timestamp — including tz,
14484                // since overflow deliberately drops it.
14485                let ts = Timestamp::from_nanos(a);
14486                assert_eq!(
14487                    ts.add_timedelta(b),
14488                    ts.try_add_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14489                    "add_timedelta({a}, {b}) diverged"
14490                );
14491                assert_eq!(
14492                    ts.sub_timedelta(b),
14493                    ts.try_sub_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14494                    "sub_timedelta({a}, {b}) diverged"
14495                );
14496                let other = Timestamp::from_nanos(b);
14497                assert_eq!(
14498                    ts.sub_timestamp(&other),
14499                    ts.try_sub_timestamp(&other).unwrap_or(Timedelta::NAT),
14500                    "sub_timestamp({a}, {b}) diverged"
14501                );
14502            }
14503        }
14504    }
14505
14506    /// The carrier must actually CARRY something: `Strict` propagates the
14507    /// overflow with the right op name and the pandas error class probed from
14508    /// live 2.2.3. Without this, `resolve` could ignore its policy and the
14509    /// equivalence test above would still pass.
14510    #[test]
14511    fn overflow_policy_strict_reports_op_and_pandas_class_f29nz() {
14512        use super::{OverflowPolicy, PandasTemporalError};
14513
14514        let strict = OverflowPolicy::Strict;
14515
14516        // pd.Timedelta.max + pd.Timedelta('1ns') -> OverflowError
14517        let err = strict
14518            .resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT)
14519            .expect_err("must surface under Strict");
14520        assert_eq!(err.op, "Timedelta::add");
14521        assert_eq!(err.pandas_error, PandasTemporalError::Overflow);
14522
14523        // pd.Timestamp.max + pd.Timedelta('1ns') -> OutOfBoundsDatetime
14524        let ts = Timestamp::from_nanos(i64::MAX);
14525        let err = strict
14526            .resolve(ts.try_add_timedelta(1), Timestamp::nat())
14527            .expect_err("must surface under Strict");
14528        assert_eq!(err.op, "Timestamp::add_timedelta");
14529        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14530
14531        // pd.Timestamp.min - pd.Timestamp.max -> OutOfBoundsDatetime
14532        let err = strict
14533            .resolve(
14534                Timestamp::from_nanos(i64::MIN + 1)
14535                    .try_sub_timestamp(&Timestamp::from_nanos(i64::MAX)),
14536                Timedelta::NAT,
14537            )
14538            .expect_err("must surface under Strict");
14539        assert_eq!(err.op, "Timestamp::sub_timestamp");
14540        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14541
14542        // A NaT operand is PROPAGATION, not overflow: Strict must still be Ok.
14543        assert_eq!(
14544            strict
14545                .resolve(Timedelta::try_add(Timedelta::NAT, 1), Timedelta::NAT)
14546                .expect("NaT propagation is not an overflow"),
14547            Timedelta::NAT
14548        );
14549        // And a representable result is untouched under either policy.
14550        assert_eq!(
14551            strict
14552                .resolve(Timedelta::try_add(2, 3), Timedelta::NAT)
14553                .expect("no overflow"),
14554            5
14555        );
14556    }
14557
14558    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2: the scalar divide-by-zero
14559    /// row, and the boundary a STRICT arm must not cross. All four expectations
14560    /// probed on live pandas 2.2.3:
14561    ///   SCALAR  Timedelta('1s') // 0   -> ZeroDivisionError
14562    ///   SCALAR  Timedelta('1s') / 0    -> ZeroDivisionError
14563    ///   VECTOR  Series([Td]) // 0      -> NaT   (must NOT raise)
14564    ///   VECTOR  Series([Td]) / 0       -> NaT   (must NOT raise)
14565    #[test]
14566    fn timedelta_scalar_zero_division_taxonomy_t7ht2() {
14567        use super::{OverflowPolicy, PandasTemporalError};
14568
14569        // The fallible scalar sibling reports ZeroDivision with its op name.
14570        let err = Timedelta::try_div_scalar(1_000_000_000, 0)
14571            .expect_err("scalar divide-by-zero must be reportable");
14572        assert_eq!(err.op, "Timedelta::div_scalar");
14573        assert_eq!(err.pandas_error, PandasTemporalError::ZeroDivision);
14574
14575        // THE BOUNDARY: the infallible helper the vectorized callers use keeps
14576        // returning NaT. If this ever starts raising, FrankenPandas diverges
14577        // from pandas on a row where it is currently bit-for-bit correct.
14578        assert_eq!(Timedelta::div_scalar(1_000_000_000, 0), Timedelta::NAT);
14579        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 0), Timedelta::NAT);
14580
14581        // Under the default policy the failure resolves back to NaT, so
14582        // nothing changes for existing callers.
14583        assert_eq!(
14584            OverflowPolicy::default()
14585                .resolve(Timedelta::try_div_scalar(1_000_000_000, 0), Timedelta::NAT)
14586                .expect("SurfaceNat never errors"),
14587            Timedelta::NAT
14588        );
14589
14590        // Non-zero divisors are untouched, including the floor-division
14591        // adjustment for mixed signs (-7 // 2 == -4, not -3).
14592        assert_eq!(Timedelta::try_div_scalar(-7, 2), Ok(-4));
14593        assert_eq!(Timedelta::div_scalar(-7, 2), -4);
14594        assert_eq!(Timedelta::try_div_scalar(7, 2), Ok(3));
14595        // NaT propagates as Ok, not as a failure.
14596        assert_eq!(
14597            Timedelta::try_div_scalar(Timedelta::NAT, 2),
14598            Ok(Timedelta::NAT)
14599        );
14600    }
14601
14602    /// The constructor row of the taxonomy. Probed:
14603    /// `pd.Timedelta(float('inf'), 's')` raises OutOfBoundsTimedelta —
14604    /// specifically NOT a bare OverflowError, which is why the mapping is
14605    /// explicit rather than assumed.
14606    #[test]
14607    fn timedelta_constructor_error_maps_to_out_of_bounds_t7ht2() {
14608        use super::{PandasTemporalError, TimedeltaError};
14609
14610        assert_eq!(
14611            TimedeltaError::Overflow.pandas_error(),
14612            Some(PandasTemporalError::OutOfBoundsTimedelta)
14613        );
14614        // A parse failure is not part of the arithmetic taxonomy.
14615        assert_eq!(
14616            TimedeltaError::InvalidFormat("nonsense".into()).pandas_error(),
14617            None
14618        );
14619        // And the live path still errors on a non-finite input (8v92m).
14620        assert!(Timedelta::from_unit(f64::INFINITY, "s").is_err());
14621        assert_eq!(
14622            Timedelta::from_unit(f64::INFINITY, "s")
14623                .unwrap_err()
14624                .pandas_error(),
14625            Some(PandasTemporalError::OutOfBoundsTimedelta)
14626        );
14627    }
14628
14629    /// br-frankenpandas-fyr1z-hardened-audit-vllv6: HARDENED mode adds
14630    /// observability, NEVER semantics. Every value it returns must be
14631    /// bit-for-bit what SurfaceNat returns — proven over the same seeded corpus
14632    /// the f29nz equivalence test uses, with the audit log ENABLED throughout so
14633    /// recording cannot perturb results.
14634    #[test]
14635    fn hardened_audit_values_are_bit_identical_to_surface_nat_vllv6() {
14636        use super::{OverflowPolicy, overflow_audit};
14637
14638        overflow_audit::enable();
14639        let mut state: u64 = 0x1234_5678_9ABC_DEF0;
14640        let mut next = || {
14641            state = state
14642                .wrapping_mul(6_364_136_223_846_793_005)
14643                .wrapping_add(1_442_695_040_888_963_407);
14644            state
14645        };
14646        let mut corpus: Vec<i64> = vec![
14647            0,
14648            1,
14649            -1,
14650            2,
14651            -2,
14652            i64::MAX,
14653            i64::MIN,
14654            i64::MIN + 1,
14655            i64::MAX - 1,
14656        ];
14657        for _ in 0..120 {
14658            corpus.push(next() as i64);
14659        }
14660
14661        for &a in &corpus {
14662            for &b in &corpus {
14663                for op in [
14664                    Timedelta::try_add as fn(i64, i64) -> Result<i64, super::TemporalFailure>,
14665                    Timedelta::try_sub,
14666                    Timedelta::try_mul_scalar,
14667                    Timedelta::try_div_scalar,
14668                ] {
14669                    let soft = OverflowPolicy::SurfaceNat
14670                        .resolve(op(a, b), Timedelta::NAT)
14671                        .expect("SurfaceNat never errors");
14672                    let hard = OverflowPolicy::HardenedNat
14673                        .resolve(op(a, b), Timedelta::NAT)
14674                        .expect("HardenedNat never errors");
14675                    assert_eq!(hard, soft, "HARDENED changed a value for ({a}, {b})");
14676                }
14677            }
14678        }
14679        overflow_audit::disable();
14680    }
14681
14682    /// The audit trail itself: HARDENED records the op, the pandas class it
14683    /// would have raised, the OPERANDS whose exact result left the
14684    /// representable range, and the value actually returned — deterministically
14685    /// and in order. SurfaceNat and Strict record nothing.
14686    #[test]
14687    fn hardened_audit_records_deterministic_recovery_entries_vllv6() {
14688        use super::{OverflowPolicy, PandasTemporalError, overflow_audit};
14689
14690        overflow_audit::enable();
14691        assert!(overflow_audit::is_enabled());
14692        assert!(overflow_audit::drain().is_empty(), "starts empty");
14693
14694        // Two overflows and one representable result, in a fixed order.
14695        let _ =
14696            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14697        let _ = OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(2, 3), Timedelta::NAT);
14698        let _ =
14699            OverflowPolicy::HardenedNat.resolve(Timedelta::try_div_scalar(5, 0), Timedelta::NAT);
14700
14701        let entries = overflow_audit::drain();
14702        assert_eq!(entries.len(), 2, "only the two failures are recorded");
14703
14704        assert_eq!(entries[0].op, "Timedelta::add");
14705        assert_eq!(entries[0].pandas_error, PandasTemporalError::Overflow);
14706        assert_eq!(entries[0].operands, Some((i64::MAX, 1)));
14707        assert_eq!(entries[0].recovered_as, i64::MIN);
14708
14709        assert_eq!(entries[1].op, "Timedelta::div_scalar");
14710        assert_eq!(entries[1].pandas_error, PandasTemporalError::ZeroDivision);
14711        assert_eq!(entries[1].operands, Some((5, 0)));
14712
14713        // Draining leaves recording enabled and empty.
14714        assert!(overflow_audit::drain().is_empty());
14715
14716        // The OTHER policies must stay silent — the audit is HARDENED-only.
14717        let _ = OverflowPolicy::SurfaceNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14718        let _ = OverflowPolicy::Strict.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14719        assert!(
14720            overflow_audit::drain().is_empty(),
14721            "SurfaceNat/Strict must not write to the audit trail"
14722        );
14723
14724        overflow_audit::disable();
14725        assert!(!overflow_audit::is_enabled());
14726        // Disabled: recording is a no-op and drain yields nothing.
14727        let _ =
14728            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14729        assert!(
14730            overflow_audit::drain().is_empty(),
14731            "disabled must not record"
14732        );
14733    }
14734
14735    /// br-frankenpandas-fyr1z-wrap-signoff-s4lkx.
14736    ///
14737    /// THIS TEST PINS A PANDAS QUIRK THAT WE REPRODUCE ON PURPOSE. The values
14738    /// below are NOT what a careful implementation would choose: multiplying a
14739    /// positive duration by 2 yields a NEGATIVE one. They are what live pandas
14740    /// 2.2.3 returns, because numpy int64 wraps silently, and the maintainer
14741    /// decided that STRICT means bit-for-bit observable parity with the
14742    /// incumbent INCLUDING its quirks — this being a port.
14743    ///
14744    /// So: if this test fails, do NOT "fix" the wrap. Either pandas changed, or
14745    /// someone routed a non-STRICT caller into the STRICT path. Both need
14746    /// investigating rather than correcting the arithmetic.
14747    ///
14748    /// Oracle values, probed directly:
14749    ///   Series([Timedelta.max]) * 2            -> -2 ns
14750    ///   Series([max, max]).cumsum()            -> [max, -2]
14751    ///   Series([max, max, max]).cumsum()       -> [max, -2, max - 2]
14752    #[test]
14753    fn strict_reproduces_pandas_silent_timedelta_wrap_s4lkx() {
14754        use super::{OverflowPolicy, nancumsum_with_policy};
14755
14756        // Series * int -- pandas returns -2, i.e. i64::MAX.wrapping_mul(2).
14757        assert_eq!(
14758            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::Strict),
14759            -2,
14760            "STRICT must reproduce pandas' wrap, not repair it"
14761        );
14762
14763        // cumsum -- and the THIRD element is the important one: it proves the
14764        // accumulator keeps wrapping rather than sticking at a bound.
14765        let max = Scalar::Timedelta64(i64::MAX);
14766        let out = nancumsum_with_policy(
14767            &[max.clone(), max.clone(), max.clone()],
14768            OverflowPolicy::Strict,
14769        );
14770        assert_eq!(
14771            out,
14772            vec![
14773                Scalar::Timedelta64(i64::MAX),
14774                Scalar::Timedelta64(-2),
14775                Scalar::Timedelta64(i64::MAX - 2),
14776            ],
14777            "STRICT cumsum must reproduce pandas' int64 wraparound exactly"
14778        );
14779
14780        // NaT still propagates; the wrap is about overflow, not missingness.
14781        assert_eq!(
14782            Timedelta::mul_scalar_with_policy(Timedelta::NAT, 2, OverflowPolicy::Strict),
14783            Timedelta::NAT
14784        );
14785    }
14786
14787    /// The other half of the s4lkx decision, and the reason reproducing a
14788    /// fail-open quirk is acceptable at all: it is reachable ONLY when a caller
14789    /// explicitly asks for STRICT incumbent parity. Every other policy — and
14790    /// crucially the DEFAULT — still refuses to fabricate a plausible value,
14791    /// keeping the br-frankenpandas-lgyy8 guarantee intact.
14792    #[test]
14793    fn non_strict_policies_still_refuse_to_wrap_s4lkx() {
14794        use super::{OverflowPolicy, nancumsum_with_policy, overflow_audit};
14795
14796        for policy in [OverflowPolicy::SurfaceNat, OverflowPolicy::HardenedNat] {
14797            assert_eq!(
14798                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14799                Timedelta::NAT,
14800                "{policy:?} must NOT wrap"
14801            );
14802            assert_ne!(
14803                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14804                -2,
14805                "{policy:?} must not reproduce the pandas quirk"
14806            );
14807        }
14808        // The bare default is SurfaceNat, so an unconfigured caller is safe.
14809        assert_eq!(
14810            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::default()),
14811            Timedelta::NAT
14812        );
14813
14814        // cumsum likewise keeps the exact-i128 / NaT behaviour off STRICT.
14815        let max = Scalar::Timedelta64(i64::MAX);
14816        let soft = nancumsum_with_policy(&[max.clone(), max.clone()], OverflowPolicy::SurfaceNat);
14817        assert!(soft[1].is_missing(), "non-STRICT cumsum must NaT, not wrap");
14818        assert_eq!(soft, super::nancumsum(&[max.clone(), max]));
14819
14820        // HARDENED wrapping would be doubly wrong: it would fabricate a value
14821        // AND leave nothing in the audit trail to explain it.
14822        overflow_audit::enable();
14823        let _ = Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::HardenedNat);
14824        assert_eq!(
14825            overflow_audit::drain().len(),
14826            1,
14827            "HARDENED must record the recovery it performed"
14828        );
14829        overflow_audit::disable();
14830    }
14831
14832    /// Mixed Datetime64 + another dtype must NOT take the typed arm — it falls
14833    /// back exactly as before, so this fix cannot change cross-type behavior.
14834    #[test]
14835    fn datetime64_mixed_input_still_falls_back_axhhk() {
14836        let vals = vec![Scalar::Datetime64(DT_2020), Scalar::Int64(5)];
14837        // `is_datetime_input` is false here, so both keep their PRE-EXISTING
14838        // cross-type behavior, which differs between the two by construction:
14839        //   nanmin  — the catch-all compares via to_f64(); the Datetime64 side
14840        //             errors, so it bails to Null(NaN).
14841        //   nanptp  — its f64 loop SKIPS values whose to_f64() errors, so the
14842        //             datetime is dropped and the range is taken over the lone
14843        //             Int64 => Float64(0.0). Same shape as the documented
14844        //             mixed-timedelta fallback in ..._620mj (which yields 5.0).
14845        // Neither is changed by this bead; pinning both stops the new typed arm
14846        // from silently widening to mixed input later.
14847        assert!(super::nanmin(&vals).is_missing());
14848        assert_eq!(super::nanptp(&vals), Scalar::Float64(0.0));
14849    }
14850
14851    #[test]
14852    fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
14853        // Mixed Timedelta64 + other type bails out of the Timedelta path
14854        // and uses Float64 collect_finite (which drops Timedelta).
14855        // Preserves existing cross-type behavior (effectively ignores TD).
14856        let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
14857        // Int64(5) makes it through to_f64 → 5.0; Timedelta is dropped.
14858        assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
14859    }
14860
14861    #[test]
14862    fn nancount_counts_non_missing() {
14863        let vals = vec![
14864            Scalar::Int64(1),
14865            Scalar::Null(NullKind::Null),
14866            Scalar::Float64(3.0),
14867        ];
14868        assert_eq!(super::nancount(&vals), Scalar::Int64(2));
14869    }
14870
14871    #[test]
14872    fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
14873        // Differential vs scalar truthiness/count oracle
14874        // (br-frankenpandas-zr2qg). Seeded LCG, no mocks.
14875        fn next(seed: &mut u64) -> u64 {
14876            *seed = seed
14877                .wrapping_mul(6364136223846793005)
14878                .wrapping_add(1442695040888963407);
14879            *seed
14880        }
14881
14882        fn truthy(value: &Scalar) -> Option<bool> {
14883            if value.is_missing() {
14884                return None;
14885            }
14886            match value {
14887                Scalar::Bool(value) => Some(*value),
14888                Scalar::Int64(value) => Some(*value != 0),
14889                Scalar::Float64(value) => Some(*value != 0.0),
14890                Scalar::Utf8(value) => Some(!value.is_empty()),
14891                Scalar::Timedelta64(value) => Some(*value != 0),
14892                _ => None,
14893            }
14894        }
14895
14896        fn assert_nanops(case: usize, values: &[Scalar]) {
14897            let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
14898            let expected_any = truth_values.iter().any(|value| *value);
14899            let expected_all = !truth_values.iter().any(|value| !*value);
14900            let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
14901
14902            assert_eq!(
14903                super::nanany(values),
14904                Scalar::Bool(expected_any),
14905                "case={case}: nanany mismatch for {values:?}"
14906            );
14907            assert_eq!(
14908                super::nanall(values),
14909                Scalar::Bool(expected_all),
14910                "case={case}: nanall mismatch for {values:?}"
14911            );
14912            assert_eq!(
14913                super::nancount(values),
14914                Scalar::Int64(expected_count),
14915                "case={case}: nancount mismatch for {values:?}"
14916            );
14917        }
14918
14919        assert_nanops(
14920            usize::MAX,
14921            &[
14922                Scalar::Null(NullKind::Null),
14923                Scalar::Null(NullKind::NaN),
14924                Scalar::Float64(f64::NAN),
14925                Scalar::Timedelta64(i64::MIN),
14926            ],
14927        );
14928
14929        let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
14930        for case in 0..320 {
14931            let len = (next(&mut seed) % 89 + 1) as usize;
14932            let mut values = Vec::with_capacity(len);
14933            for pos in 0..len {
14934                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
14935                let value = match next(&mut seed) % 12 {
14936                    0 => Scalar::Null(NullKind::Null),
14937                    1 => Scalar::Null(NullKind::NaN),
14938                    2 => Scalar::Float64(f64::NAN),
14939                    3 => Scalar::Bool(raw & 1 == 0),
14940                    4 => Scalar::Bool(false),
14941                    5 => Scalar::Int64(raw % 17),
14942                    6 => Scalar::Int64(0),
14943                    7 => Scalar::Float64(raw as f64 / 23.0),
14944                    8 => Scalar::Float64(0.0),
14945                    9 => Scalar::Utf8(if raw & 1 == 0 {
14946                        String::new()
14947                    } else {
14948                        format!("nanops_{case}_{pos}")
14949                    }),
14950                    10 => Scalar::Timedelta64(raw),
14951                    _ => Scalar::Timedelta64(0),
14952                };
14953                values.push(value);
14954            }
14955            assert_nanops(case, &values);
14956        }
14957    }
14958
14959    #[test]
14960    fn nanmin_basic() {
14961        let vals = vec![
14962            Scalar::Float64(5.0),
14963            Scalar::Null(NullKind::Null),
14964            Scalar::Float64(2.0),
14965            Scalar::Float64(8.0),
14966        ];
14967        assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
14968    }
14969
14970    #[test]
14971    fn nanmax_basic() {
14972        let vals = vec![
14973            Scalar::Float64(5.0),
14974            Scalar::Float64(f64::NAN),
14975            Scalar::Float64(8.0),
14976        ];
14977        assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
14978    }
14979
14980    #[test]
14981    fn nanmin_nanmax_empty_returns_nan() {
14982        assert!(super::nanmin(&[]).is_missing());
14983        assert!(super::nanmax(&[]).is_missing());
14984    }
14985
14986    #[test]
14987    fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
14988        // Differential vs independent same-family comparator oracle
14989        // (br-frankenpandas-vj7ds). Seeded LCG, no mocks.
14990        fn next(seed: &mut u64) -> u64 {
14991            *seed = seed
14992                .wrapping_mul(6364136223846793005)
14993                .wrapping_add(1442695040888963407);
14994            *seed
14995        }
14996
14997        fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
14998            match (left, right) {
14999                (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
15000                (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
15001                (Scalar::Float64(left), Scalar::Float64(right)) => {
15002                    left.partial_cmp(right).expect("finite floats")
15003                }
15004                (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
15005                (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
15006                // `assert_minmax` verifies that every present value belongs
15007                // to one generated family before it invokes this comparator.
15008                _ => std::cmp::Ordering::Equal,
15009            }
15010        }
15011
15012        fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
15013            let present = values
15014                .iter()
15015                .filter(|value| !value.is_missing())
15016                .cloned()
15017                .collect::<Vec<_>>();
15018            let actual_min = super::nanmin(values);
15019            let actual_max = super::nanmax(values);
15020            if present.is_empty() {
15021                assert!(
15022                    actual_min.is_missing(),
15023                    "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
15024                );
15025                assert!(
15026                    actual_max.is_missing(),
15027                    "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
15028                );
15029                return;
15030            }
15031
15032            let is_expected_family = |value: &Scalar| match family {
15033                "int" => matches!(value, Scalar::Int64(_)),
15034                "float" => matches!(value, Scalar::Float64(_)),
15035                "bool" => matches!(value, Scalar::Bool(_)),
15036                "utf8" => matches!(value, Scalar::Utf8(_)),
15037                "timedelta" => matches!(value, Scalar::Timedelta64(_)),
15038                _ => false,
15039            };
15040            assert!(
15041                present.iter().all(is_expected_family),
15042                "case={case} family={family}: mixed family escaped generator: {values:?}"
15043            );
15044
15045            let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
15046            let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
15047            assert!(
15048                actual_min.semantic_eq(expected_min.expect("min")),
15049                "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
15050                expected_min.expect("min")
15051            );
15052            assert!(
15053                actual_max.semantic_eq(expected_max.expect("max")),
15054                "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
15055                expected_max.expect("max")
15056            );
15057        }
15058
15059        let all_missing = [
15060            Scalar::Null(NullKind::Null),
15061            Scalar::Null(NullKind::NaN),
15062            Scalar::Float64(f64::NAN),
15063            Scalar::Timedelta64(i64::MIN),
15064        ];
15065        assert_minmax(usize::MAX, "all_missing", &all_missing);
15066
15067        let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
15068        for case in 0..240 {
15069            let len = (next(&mut seed) % 73 + 1) as usize;
15070
15071            let mut ints = Vec::with_capacity(len);
15072            ints.push(Scalar::Int64(case as i64 - 120));
15073            for _ in 1..len {
15074                let raw = (next(&mut seed) % 1_001) as i64 - 500;
15075                ints.push(match next(&mut seed) % 6 {
15076                    0 => Scalar::Null(NullKind::Null),
15077                    1 => Scalar::Null(NullKind::NaN),
15078                    _ => Scalar::Int64(raw),
15079                });
15080            }
15081            assert_minmax(case, "int", &ints);
15082
15083            let mut floats = Vec::with_capacity(len);
15084            floats.push(Scalar::Float64(case as f64 / 11.0));
15085            for _ in 1..len {
15086                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15087                floats.push(match next(&mut seed) % 8 {
15088                    0 | 1 => Scalar::Float64(f64::NAN),
15089                    2 => Scalar::Float64(f64::INFINITY),
15090                    3 => Scalar::Float64(f64::NEG_INFINITY),
15091                    4 => Scalar::Float64(0.0),
15092                    5 => Scalar::Float64(-0.0),
15093                    _ => Scalar::Float64(raw as f64 / 41.0),
15094                });
15095            }
15096            assert_minmax(case, "float", &floats);
15097
15098            let mut bools = Vec::with_capacity(len);
15099            bools.push(Scalar::Bool(case & 1 == 0));
15100            for _ in 1..len {
15101                bools.push(match next(&mut seed) % 5 {
15102                    0 => Scalar::Null(NullKind::Null),
15103                    1 => Scalar::Null(NullKind::NaN),
15104                    raw => Scalar::Bool(raw & 1 == 0),
15105                });
15106            }
15107            assert_minmax(case, "bool", &bools);
15108
15109            let mut utf8 = Vec::with_capacity(len);
15110            utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
15111            for pos in 1..len {
15112                utf8.push(match next(&mut seed) % 7 {
15113                    0 => Scalar::Null(NullKind::Null),
15114                    1 => Scalar::Null(NullKind::NaN),
15115                    raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
15116                });
15117            }
15118            assert_minmax(case, "utf8", &utf8);
15119
15120            let mut timedeltas = Vec::with_capacity(len);
15121            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15122            for _ in 1..len {
15123                let raw = (next(&mut seed) % 1_003) as i64 - 501;
15124                timedeltas.push(match next(&mut seed) % 7 {
15125                    0 => Scalar::Null(NullKind::Null),
15126                    1 => Scalar::Timedelta64(i64::MIN),
15127                    _ => Scalar::Timedelta64(raw),
15128                });
15129            }
15130            assert_minmax(case, "timedelta", &timedeltas);
15131        }
15132    }
15133
15134    #[test]
15135    fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
15136        let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
15137        assert!(super::nanmin(&vals).is_missing());
15138        assert!(super::nanmax(&vals).is_missing());
15139
15140        let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
15141        assert!(super::nanmin(&vals2).is_missing());
15142        assert!(super::nanmax(&vals2).is_missing());
15143    }
15144
15145    #[test]
15146    fn nanmin_nanmax_compatible_numeric_types_ok() {
15147        let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
15148        assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
15149        assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
15150    }
15151
15152    #[test]
15153    fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
15154        // Per br-frankenpandas-yic5m: nanmin/nanmax on Timedelta64 returns
15155        // the smallest/largest Timedelta64 — was silently NaN before
15156        // because Timedelta64.to_f64() errors and the catch-all swallowed it.
15157        let one_hour = 3_600 * 1_000_000_000_i64;
15158        let vals = vec![
15159            Scalar::Timedelta64(3 * one_hour),
15160            Scalar::Timedelta64(one_hour),
15161            Scalar::Timedelta64(2 * one_hour),
15162        ];
15163        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15164        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
15165    }
15166
15167    #[test]
15168    fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
15169        let one_hour = 3_600 * 1_000_000_000_i64;
15170        let vals = vec![
15171            Scalar::Timedelta64(Timedelta::NAT),
15172            Scalar::Timedelta64(one_hour),
15173            Scalar::Timedelta64(2 * one_hour),
15174            Scalar::Timedelta64(Timedelta::NAT),
15175        ];
15176        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15177        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
15178    }
15179
15180    #[test]
15181    fn nanmedian_odd_count() {
15182        let vals = vec![
15183            Scalar::Float64(3.0),
15184            Scalar::Null(NullKind::Null),
15185            Scalar::Float64(1.0),
15186            Scalar::Float64(2.0),
15187        ];
15188        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
15189    }
15190
15191    #[test]
15192    fn nanmedian_even_count() {
15193        let vals = vec![
15194            Scalar::Float64(1.0),
15195            Scalar::Float64(3.0),
15196            Scalar::Float64(2.0),
15197            Scalar::Float64(4.0),
15198        ];
15199        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
15200    }
15201
15202    #[test]
15203    fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
15204        // Differential vs independent sort-based median oracles
15205        // (br-frankenpandas-oabhi). Seeded LCG, no mocks.
15206        fn next(seed: &mut u64) -> u64 {
15207            *seed = seed
15208                .wrapping_mul(6364136223846793005)
15209                .wrapping_add(1442695040888963407);
15210            *seed
15211        }
15212
15213        fn expected_numeric(values: &[Scalar]) -> Scalar {
15214            let mut finite = values
15215                .iter()
15216                .filter(|value| !value.is_missing())
15217                .filter_map(|value| value.to_f64().ok())
15218                .filter(|value| !value.is_nan())
15219                .collect::<Vec<_>>();
15220            if finite.is_empty() {
15221                return Scalar::Null(NullKind::NaN);
15222            }
15223            finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
15224            let mid = finite.len() / 2;
15225            if finite.len().is_multiple_of(2) {
15226                Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
15227            } else {
15228                Scalar::Float64(finite[mid])
15229            }
15230        }
15231
15232        fn expected_timedelta(values: &[Scalar]) -> Scalar {
15233            let mut finite = values
15234                .iter()
15235                .filter_map(|value| match value {
15236                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns),
15237                    _ => None,
15238                })
15239                .collect::<Vec<_>>();
15240            if finite.is_empty() {
15241                return Scalar::Null(NullKind::NaN);
15242            }
15243            finite.sort_unstable();
15244            let mid = finite.len() / 2;
15245            let median = if finite.len().is_multiple_of(2) {
15246                (i128::from(finite[mid - 1]) + i128::from(finite[mid])) / 2
15247            } else {
15248                i128::from(finite[mid])
15249            };
15250            Scalar::Timedelta64(median as i64)
15251        }
15252
15253        fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
15254            let actual = super::nanmedian(values);
15255            assert!(
15256                actual.semantic_eq(&expected),
15257                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
15258            );
15259        }
15260
15261        assert_median(
15262            usize::MAX,
15263            "numeric_all_missing",
15264            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
15265            Scalar::Null(NullKind::NaN),
15266        );
15267        assert_median(
15268            usize::MAX - 1,
15269            "timedelta_all_missing",
15270            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
15271            Scalar::Null(NullKind::NaN),
15272        );
15273        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
15274        assert_median(
15275            usize::MAX - 2,
15276            "timedelta_odd_median_beyond_f64_exactness",
15277            &[
15278                Scalar::Timedelta64(beyond_f64_exact_ns),
15279                Scalar::Timedelta64(beyond_f64_exact_ns + 1),
15280                Scalar::Timedelta64(beyond_f64_exact_ns + 2),
15281                Scalar::Timedelta64(Timedelta::NAT),
15282            ],
15283            Scalar::Timedelta64(beyond_f64_exact_ns + 1),
15284        );
15285
15286        let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
15287        for case in 0..220 {
15288            let len = (next(&mut seed) % 79 + 1) as usize;
15289
15290            let mut numeric = Vec::with_capacity(len);
15291            numeric.push(Scalar::Int64(case as i64 - 110));
15292            for _ in 1..len {
15293                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15294                numeric.push(match next(&mut seed) % 8 {
15295                    0 => Scalar::Null(NullKind::Null),
15296                    1 => Scalar::Null(NullKind::NaN),
15297                    2 => Scalar::Float64(f64::NAN),
15298                    3 => Scalar::Bool(raw & 1 == 0),
15299                    4 => Scalar::Int64(raw % 251),
15300                    5 => Scalar::Float64(raw as f64 / 61.0),
15301                    6 => Scalar::Float64(0.0),
15302                    _ => Scalar::Float64(-0.0),
15303                });
15304            }
15305            assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
15306
15307            let mut timedeltas = Vec::with_capacity(len);
15308            timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
15309            for _ in 1..len {
15310                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15311                timedeltas.push(match next(&mut seed) % 7 {
15312                    0 => Scalar::Null(NullKind::Null),
15313                    1 => Scalar::Timedelta64(i64::MIN),
15314                    _ => Scalar::Timedelta64(raw),
15315                });
15316            }
15317            assert_median(
15318                case,
15319                "timedelta",
15320                &timedeltas,
15321                expected_timedelta(&timedeltas),
15322            );
15323        }
15324    }
15325
15326    #[test]
15327    fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
15328        // Differential vs independent variance/std/sem oracles
15329        // (br-frankenpandas-k7apg). Seeded LCG, no mocks.
15330        fn next(seed: &mut u64) -> u64 {
15331            *seed = seed
15332                .wrapping_mul(2862933555777941757)
15333                .wrapping_add(3037000493);
15334            *seed
15335        }
15336
15337        fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
15338            values
15339                .iter()
15340                .filter(|value| !value.is_missing())
15341                .filter_map(|value| value.to_f64().ok())
15342                .collect()
15343        }
15344
15345        fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
15346            values
15347                .iter()
15348                .filter_map(|value| match value {
15349                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
15350                    _ => None,
15351                })
15352                .collect()
15353        }
15354
15355        fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
15356            if samples.len() <= ddof {
15357                return None;
15358            }
15359            let mean = samples.iter().sum::<f64>() / samples.len() as f64;
15360            let sum_sq = samples
15361                .iter()
15362                .map(|value| (value - mean).powi(2))
15363                .sum::<f64>();
15364            let var = sum_sq / (samples.len() - ddof) as f64;
15365            let std = var.sqrt();
15366            let sem = std / (samples.len() as f64).sqrt();
15367            Some((var, std, sem))
15368        }
15369
15370        fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
15371            let samples = numeric_samples(values);
15372            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
15373                let missing = Scalar::Null(NullKind::NaN);
15374                return (missing.clone(), missing.clone(), missing);
15375            };
15376            (
15377                Scalar::Float64(var),
15378                Scalar::Float64(std),
15379                Scalar::Float64(sem),
15380            )
15381        }
15382
15383        fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
15384            let samples = timedelta_samples(values);
15385            if samples.is_empty() {
15386                let missing = Scalar::Timedelta64(Timedelta::NAT);
15387                return (missing.clone(), missing.clone(), missing);
15388            }
15389            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
15390                let missing = Scalar::Timedelta64(i64::MIN);
15391                return (missing.clone(), missing.clone(), missing);
15392            };
15393            (
15394                Scalar::Timedelta64(var as i64),
15395                Scalar::Timedelta64(std as i64),
15396                Scalar::Timedelta64(sem as i64),
15397            )
15398        }
15399
15400        fn assert_reductions(
15401            case: usize,
15402            family: &str,
15403            values: &[Scalar],
15404            ddof: usize,
15405            expected: (Scalar, Scalar, Scalar),
15406        ) {
15407            let (expected_var, expected_std, expected_sem) = expected;
15408            let actual_var = super::nanvar(values, ddof);
15409            let actual_std = super::nanstd(values, ddof);
15410            let actual_sem = super::nansem(values, ddof);
15411            assert!(
15412                actual_var.semantic_eq(&expected_var),
15413                "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
15414            );
15415            assert!(
15416                actual_std.semantic_eq(&expected_std),
15417                "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
15418            );
15419            assert!(
15420                actual_sem.semantic_eq(&expected_sem),
15421                "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
15422            );
15423        }
15424
15425        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15426        assert_reductions(
15427            usize::MAX,
15428            "numeric_all_missing",
15429            &numeric_all_missing,
15430            0,
15431            expected_numeric(&numeric_all_missing, 0),
15432        );
15433
15434        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
15435        assert_reductions(
15436            usize::MAX - 1,
15437            "timedelta_all_missing",
15438            &td_all_missing,
15439            0,
15440            expected_timedelta(&td_all_missing, 0),
15441        );
15442
15443        let mut seed = 0x7a11_c0de_5eed_0421_u64;
15444        for case in 0..240 {
15445            let len = (next(&mut seed) % 83 + 1) as usize;
15446            let ddof = (next(&mut seed) % 4) as usize;
15447
15448            let mut numeric = Vec::with_capacity(len);
15449            numeric.push(Scalar::Float64(case as f64 / 13.0));
15450            for _ in 1..len {
15451                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15452                numeric.push(match next(&mut seed) % 8 {
15453                    0 => Scalar::Null(NullKind::Null),
15454                    1 => Scalar::Null(NullKind::NaN),
15455                    2 => Scalar::Float64(f64::NAN),
15456                    3 => Scalar::Bool(raw & 1 == 0),
15457                    4 => Scalar::Int64(raw % 251),
15458                    5 => Scalar::Float64(raw as f64 / 73.0),
15459                    6 => Scalar::Float64(0.0),
15460                    _ => Scalar::Float64(-0.0),
15461                });
15462            }
15463            assert_reductions(
15464                case,
15465                "numeric",
15466                &numeric,
15467                ddof,
15468                expected_numeric(&numeric, ddof),
15469            );
15470
15471            let mut timedeltas = Vec::with_capacity(len);
15472            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15473            for _ in 1..len {
15474                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15475                timedeltas.push(match next(&mut seed) % 7 {
15476                    0 => Scalar::Null(NullKind::Null),
15477                    1 => Scalar::Timedelta64(i64::MIN),
15478                    _ => Scalar::Timedelta64(raw),
15479                });
15480            }
15481            assert_reductions(
15482                case,
15483                "timedelta",
15484                &timedeltas,
15485                ddof,
15486                expected_timedelta(&timedeltas, ddof),
15487            );
15488        }
15489    }
15490
15491    #[test]
15492    fn nanvar_population() {
15493        let vals = vec![
15494            Scalar::Float64(2.0),
15495            Scalar::Float64(4.0),
15496            Scalar::Float64(4.0),
15497            Scalar::Float64(4.0),
15498            Scalar::Float64(5.0),
15499            Scalar::Float64(5.0),
15500            Scalar::Float64(7.0),
15501            Scalar::Float64(9.0),
15502        ];
15503        let var = super::nanvar(&vals, 0);
15504        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15505        if let Scalar::Float64(v) = var {
15506            assert!((v - 4.0).abs() < 1e-10);
15507        }
15508    }
15509
15510    #[test]
15511    fn nanvar_sample_ddof1() {
15512        let vals = vec![
15513            Scalar::Float64(2.0),
15514            Scalar::Float64(4.0),
15515            Scalar::Float64(4.0),
15516            Scalar::Float64(4.0),
15517            Scalar::Float64(5.0),
15518            Scalar::Float64(5.0),
15519            Scalar::Float64(7.0),
15520            Scalar::Float64(9.0),
15521        ];
15522        let var = super::nanvar(&vals, 1);
15523        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15524        if let Scalar::Float64(v) = var {
15525            assert!((v - 32.0 / 7.0).abs() < 1e-10);
15526        }
15527    }
15528
15529    #[test]
15530    fn nanvar_insufficient_values_returns_nan() {
15531        let vals = vec![Scalar::Float64(5.0)];
15532        assert!(super::nanvar(&vals, 1).is_missing());
15533    }
15534
15535    #[test]
15536    fn nanstd_is_sqrt_of_var() {
15537        let vals = vec![
15538            Scalar::Float64(2.0),
15539            Scalar::Float64(4.0),
15540            Scalar::Float64(4.0),
15541            Scalar::Float64(4.0),
15542            Scalar::Float64(5.0),
15543            Scalar::Float64(5.0),
15544            Scalar::Float64(7.0),
15545            Scalar::Float64(9.0),
15546        ];
15547        let std = super::nanstd(&vals, 0);
15548        assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
15549        if let Scalar::Float64(v) = std {
15550            assert!((v - 2.0).abs() < 1e-10);
15551        }
15552    }
15553
15554    #[test]
15555    fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
15556        // Per br-frankenpandas-j8ntk: pandas td_series.median() returns
15557        // Timedelta64; was silently NaN before via collect_finite.
15558        let one_hour = 3_600 * 1_000_000_000_i64;
15559        let vals = vec![
15560            Scalar::Timedelta64(one_hour),
15561            Scalar::Timedelta64(2 * one_hour),
15562            Scalar::Timedelta64(3 * one_hour),
15563        ];
15564        assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
15565    }
15566
15567    #[test]
15568    fn nanstd_timedelta64_preserves_dtype_j8ntk() {
15569        // Per br-frankenpandas-j8ntk: pandas td_series.std() returns
15570        // Timedelta64. Check Timedelta64 output and reasonable magnitude
15571        // for population std of [1h, 2h, 3h] = sqrt(2/3) * 1h.
15572        let one_hour: i64 = 3_600 * 1_000_000_000;
15573        let vals = vec![
15574            Scalar::Timedelta64(one_hour),
15575            Scalar::Timedelta64(2 * one_hour),
15576            Scalar::Timedelta64(3 * one_hour),
15577        ];
15578        let std = super::nanstd(&vals, 0);
15579        assert!(matches!(std, Scalar::Timedelta64(_)));
15580        if let Scalar::Timedelta64(ns) = std {
15581            let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
15582            assert!(
15583                (ns as f64 - expected).abs() < 1e6,
15584                "expected ~{expected} ns, got {ns}"
15585            );
15586        }
15587    }
15588
15589    #[test]
15590    fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
15591        let one_hour = 3_600 * 1_000_000_000_i64;
15592        let vals = vec![Scalar::Timedelta64(one_hour)];
15593        // ddof=1 with n=1 → underflow, returns NaT
15594        assert_eq!(super::nanstd(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15595        assert_eq!(super::nansem(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15596    }
15597
15598    #[test]
15599    fn nanops_with_mixed_types() {
15600        let vals = vec![
15601            Scalar::Bool(true),
15602            Scalar::Int64(3),
15603            Scalar::Float64(6.0),
15604            Scalar::Null(NullKind::Null),
15605        ];
15606        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
15607        assert_eq!(super::nancount(&vals), Scalar::Int64(3));
15608    }
15609
15610    #[test]
15611    fn nanops_all_missing_returns_identity() {
15612        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15613        assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
15614        assert!(super::nanmean(&vals).is_missing());
15615        assert!(super::nanmedian(&vals).is_missing());
15616        assert!(super::nanvar(&vals, 0).is_missing());
15617        assert!(super::nanstd(&vals, 0).is_missing());
15618    }
15619
15620    // ── Timedelta tests ────────────────────────────────────────────────
15621
15622    #[test]
15623    fn timedelta_parse_simple_units() {
15624        use super::Timedelta;
15625        assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
15626        assert_eq!(
15627            Timedelta::parse("2h").unwrap(),
15628            2 * Timedelta::NANOS_PER_HOUR
15629        );
15630        assert_eq!(
15631            Timedelta::parse("30m").unwrap(),
15632            30 * Timedelta::NANOS_PER_MIN
15633        );
15634        assert_eq!(
15635            Timedelta::parse("45s").unwrap(),
15636            45 * Timedelta::NANOS_PER_SEC
15637        );
15638        assert_eq!(
15639            Timedelta::parse("100ms").unwrap(),
15640            100 * Timedelta::NANOS_PER_MILLI
15641        );
15642        assert_eq!(
15643            Timedelta::parse("500us").unwrap(),
15644            500 * Timedelta::NANOS_PER_MICRO
15645        );
15646        assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
15647    }
15648
15649    #[test]
15650    fn timedelta_parse_zero_valued_compound() {
15651        use super::Timedelta;
15652        // Each of these is a Timedelta of zero, not a parse failure. Verified
15653        // against live pandas 2.2.3: every form below yields
15654        // `Timedelta('0 days 00:00:00')`. A guard in `parse_compound` used to
15655        // reject them all except the bare "0", which made
15656        // `to_timedelta(["10 seconds", "1 second", "0 seconds"])` raise on the
15657        // third element only.
15658        for s in [
15659            "0 seconds",
15660            "0 second",
15661            "0 sec",
15662            "0s",
15663            "0 days",
15664            "0d",
15665            "0 hours",
15666            "0.0 hours",
15667            "0 minutes",
15668            "0ms",
15669            "0us",
15670            "0ns",
15671            "0",
15672            "0 days 0 seconds",
15673        ] {
15674            assert_eq!(Timedelta::parse(s).unwrap(), 0, "parse({s:?}) should be 0");
15675        }
15676        // The sign is carried by the caller, so a negative zero is still zero.
15677        assert_eq!(Timedelta::parse("-0 seconds").unwrap(), 0);
15678        // Removing the guard must NOT admit garbage: an unknown unit and a
15679        // missing number are still rejected inside the loop.
15680        assert!(Timedelta::parse("0 fortnights").is_err());
15681        assert!(Timedelta::parse("seconds").is_err());
15682    }
15683
15684    #[test]
15685    fn timedelta_parse_compound() {
15686        use super::Timedelta;
15687        let expected = Timedelta::NANOS_PER_DAY
15688            + 2 * Timedelta::NANOS_PER_HOUR
15689            + 30 * Timedelta::NANOS_PER_MIN;
15690        assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
15691        assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
15692    }
15693
15694    #[test]
15695    fn timedelta_parse_leading_sign_spares_the_clock_part() {
15696        use super::Timedelta;
15697        const S: i64 = Timedelta::NANOS_PER_SEC;
15698        // Verified vs pandas 2.2.3 Timedelta(...).total_seconds(); the second
15699        // is how pandas prints a negative Timedelta.
15700        assert_eq!(Timedelta::parse("-1 days 02:03:04").unwrap(), -79_016 * S);
15701        assert_eq!(Timedelta::parse("-1 days +02:03:04").unwrap(), -79_016 * S);
15702        assert_eq!(
15703            Timedelta::parse("-3 days +23:59:59.5").unwrap(),
15704            -172_800 * S - S / 2
15705        );
15706        assert_eq!(Timedelta::parse("-0 days 01:00:00").unwrap(), 3_600 * S);
15707        // Without a clock part after a unit, the whole value is negated.
15708        assert_eq!(Timedelta::parse("-1d2h").unwrap(), -93_600 * S);
15709        assert_eq!(Timedelta::parse("-02:03:04").unwrap(), -7_384 * S);
15710        // A sign inside the string is pandas' "only leading negative signs".
15711        assert!(Timedelta::parse("-1 days -02:03:04").is_err());
15712        assert!(Timedelta::parse("1 days -02:00:00").is_err());
15713    }
15714
15715    #[test]
15716    fn timedelta_parse_iso8601_matches_pandas_tdiso() {
15717        use super::Timedelta;
15718        // Verified vs pandas 2.2.3 Timedelta(...).value.
15719        assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
15720        assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
15721        assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
15722        assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
15723        assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
15724        assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
15725        // pandas quirks: T ignored, M is minutes everywhere, units in any order.
15726        assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
15727        assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
15728        assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
15729        assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
15730        assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
15731        // Rejected like pandas: years, lowercase, bare P/PT.
15732        assert!(Timedelta::parse("P1Y").is_err());
15733        assert!(Timedelta::parse("p1d").is_err());
15734        assert!(Timedelta::parse("P").is_err());
15735        assert!(Timedelta::parse("PT").is_err());
15736    }
15737
15738    #[test]
15739    fn timedelta_parse_time_format() {
15740        use super::Timedelta;
15741        let expected = Timedelta::NANOS_PER_HOUR
15742            + 30 * Timedelta::NANOS_PER_MIN
15743            + 45 * Timedelta::NANOS_PER_SEC;
15744        assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
15745    }
15746
15747    #[test]
15748    fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
15749        use super::{Timedelta, TimedeltaError};
15750        let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
15751            .expect_err("non-ASCII fractional seconds must reject");
15752        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15753    }
15754
15755    #[test]
15756    fn timedelta_parse_time_format_rejects_overflow_without_panic() {
15757        use super::{Timedelta, TimedeltaError};
15758        let err = Timedelta::parse("9223372036854775807:00")
15759            .expect_err("oversized hour component must reject");
15760        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15761    }
15762
15763    #[test]
15764    fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
15765        // Per br-frankenpandas-zw3mg: the compound parser used a raw
15766        // `as i64` cast that silently saturated to i64::MAX when the
15767        // product of (decimal-digit f64) × unit multiplier overflows.
15768        // Use a large literal (no scientific notation — the lexer only
15769        // accepts digits, '.', '-'). 1e18 days × NANOS_PER_DAY (~8.64e13)
15770        // overflows i64.
15771        use super::{Timedelta, TimedeltaError};
15772        let huge = format!("{} days", "9".repeat(18));
15773        assert!(matches!(
15774            Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
15775            TimedeltaError::Overflow
15776        ));
15777    }
15778
15779    #[test]
15780    fn timedelta_parse_nat() {
15781        use super::Timedelta;
15782        assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
15783        assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
15784    }
15785
15786    #[test]
15787    fn timedelta_parse_negative() {
15788        use super::Timedelta;
15789        assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
15790    }
15791
15792    #[test]
15793    fn timedelta_components() {
15794        use super::Timedelta;
15795        let nanos = Timedelta::NANOS_PER_DAY
15796            + Timedelta::NANOS_PER_HOUR
15797            + Timedelta::NANOS_PER_MIN
15798            + Timedelta::NANOS_PER_SEC
15799            + Timedelta::NANOS_PER_MILLI
15800            + 2 * Timedelta::NANOS_PER_MICRO
15801            + 3;
15802        let comp = Timedelta::components(nanos);
15803        assert_eq!(comp.days, 1);
15804        assert_eq!(comp.hours, 1);
15805        assert_eq!(comp.minutes, 1);
15806        assert_eq!(comp.seconds, 1);
15807        assert_eq!(comp.milliseconds, 1);
15808        assert_eq!(comp.microseconds, 2);
15809        assert_eq!(comp.nanoseconds, 3);
15810    }
15811
15812    #[test]
15813    fn timedelta_negative_components_floor_div() {
15814        use super::Timedelta;
15815        // pandas floor-normalizes negative timedeltas: pd.Timedelta(-1,'s') has
15816        // days=-1, seconds=86399, components=(-1, 23, 59, 59, 0, 0, 0).
15817        let neg_1s = -Timedelta::NANOS_PER_SEC;
15818        assert_eq!(Timedelta::days(neg_1s), Some(-1));
15819        assert_eq!(Timedelta::seconds(neg_1s), Some(86399));
15820        assert_eq!(Timedelta::microseconds(neg_1s), Some(0));
15821        assert_eq!(Timedelta::nanoseconds(neg_1s), Some(0));
15822        let comp = Timedelta::components(neg_1s);
15823        assert_eq!(
15824            (
15825                comp.days,
15826                comp.hours,
15827                comp.minutes,
15828                comp.seconds,
15829                comp.milliseconds,
15830                comp.microseconds,
15831                comp.nanoseconds
15832            ),
15833            (-1, 23, 59, 59, 0, 0, 0)
15834        );
15835
15836        // pd.Timedelta(-86401,'s'): days=-2, seconds=86399.
15837        let neg = -86_401 * Timedelta::NANOS_PER_SEC;
15838        assert_eq!(Timedelta::days(neg), Some(-2));
15839        assert_eq!(Timedelta::seconds(neg), Some(86399));
15840    }
15841
15842    /// br-frankenpandas-timedelta-nat-days-returns-zero-406ni.
15843    ///
15844    /// All four component helpers returned `0` for `NaT`, one of them behind a
15845    /// comment asserting "pandas returns 0 for NaT.days (no error)". MEASURED,
15846    /// live pandas 2.2.3: `pd.NaT.days` is **nan**, and
15847    /// `pd.to_timedelta([1, None, -1], unit='s').dt.days` is float64
15848    /// `[0.0, nan, -1.0]`.
15849    ///
15850    /// ⚠️ `0` IS THE ONE WRONG ANSWER THAT LOOKS RIGHT. It is a legal value for
15851    /// three of these four accessors — `seconds`, `microseconds` and
15852    /// `nanoseconds` all legitimately return 0 for a whole number of days — so a
15853    /// caller cannot distinguish "midnight" from "missing" by inspecting the
15854    /// result. That is the fail-open-as-plausible-data class, and it is why the
15855    /// fix is the return TYPE and not a corrected comment.
15856    #[test]
15857    fn timedelta_components_are_missing_for_nat_not_zero_406ni() {
15858        use super::Timedelta;
15859        assert_eq!(Timedelta::days(Timedelta::NAT), None);
15860        assert_eq!(Timedelta::seconds(Timedelta::NAT), None);
15861        assert_eq!(Timedelta::microseconds(Timedelta::NAT), None);
15862        assert_eq!(Timedelta::nanoseconds(Timedelta::NAT), None);
15863
15864        // NON-VACUITY: a whole number of days legitimately answers 0 for the
15865        // three sub-day components, so `Some(0)` and `None` must be reachable
15866        // from the same accessor. A test that only checked NaT could pass
15867        // against a helper that returned `None` unconditionally.
15868        let one_day = Timedelta::NANOS_PER_DAY;
15869        assert_eq!(Timedelta::days(one_day), Some(1));
15870        assert_eq!(Timedelta::seconds(one_day), Some(0));
15871        assert_eq!(Timedelta::microseconds(one_day), Some(0));
15872        assert_eq!(Timedelta::nanoseconds(one_day), Some(0));
15873    }
15874
15875    #[test]
15876    fn timedelta_total_seconds() {
15877        use super::Timedelta;
15878        let nanos = 90_000_000_000i64; // 90 seconds
15879        assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
15880        assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
15881    }
15882
15883    #[test]
15884    fn timedelta_format_basic() {
15885        use super::Timedelta;
15886        assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
15887        assert_eq!(
15888            Timedelta::format(Timedelta::NANOS_PER_DAY),
15889            "1 days 00:00:00"
15890        );
15891        assert_eq!(
15892            Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
15893            "1 days 02:00:00"
15894        );
15895    }
15896
15897    #[test]
15898    fn timedelta_format_subsecond_matches_pandas() {
15899        use super::Timedelta;
15900        // pandas str(Timedelta) uses 6 fractional digits (microseconds) unless a
15901        // sub-microsecond (nanosecond) component is present, then 9 digits.
15902        // Verified vs live pandas 2.2.3.
15903        assert_eq!(
15904            Timedelta::format(1_500_000_000), // 1.5s
15905            "0 days 00:00:01.500000"
15906        );
15907        assert_eq!(
15908            Timedelta::format(1_000_000), // 1ms
15909            "0 days 00:00:00.001000"
15910        );
15911        assert_eq!(
15912            Timedelta::format(123_456_000), // 123456us
15913            "0 days 00:00:00.123456"
15914        );
15915        // Nanosecond component -> 9 digits.
15916        assert_eq!(
15917            Timedelta::format(500), // 500ns
15918            "0 days 00:00:00.000000500"
15919        );
15920        assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
15921    }
15922
15923    #[test]
15924    fn timedelta_format_negative_uses_python_borrow_form() {
15925        use super::Timedelta;
15926        // pandas/Python normalize negatives via floor division: the days count
15927        // goes negative, the time remainder stays non-negative, and a '+' joins
15928        // them. Verified vs live pandas 2.2.3.
15929        assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
15930        assert_eq!(
15931            Timedelta::format(-Timedelta::NANOS_PER_DAY),
15932            "-1 days +00:00:00"
15933        );
15934        assert_eq!(
15935            Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
15936            "-2 days +23:00:00"
15937        );
15938        assert_eq!(
15939            Timedelta::format(-1_500_000_000),
15940            "-1 days +23:59:58.500000"
15941        );
15942        assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
15943        assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
15944    }
15945
15946    #[test]
15947    #[ignore = "foreground release attribution harness"]
15948    fn timedelta_format_single_buffer_ab_5ro9h() {
15949        use std::{hint::black_box, time::Instant};
15950
15951        use super::Timedelta;
15952
15953        fn former(nanos: i64) -> String {
15954            if nanos == Timedelta::NAT {
15955                return "NaT".to_string();
15956            }
15957
15958            let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
15959            let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
15960            let hours = rem / Timedelta::NANOS_PER_HOUR;
15961            let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
15962            let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
15963            let frac = rem % Timedelta::NANOS_PER_SEC;
15964
15965            let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
15966            let sep = if days < 0 { "+" } else { "" };
15967            if frac > 0 {
15968                if frac % 1_000 == 0 {
15969                    format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
15970                } else {
15971                    format!("{days} days {sep}{time_part}.{frac:09}")
15972                }
15973            } else {
15974                format!("{days} days {sep}{time_part}")
15975            }
15976        }
15977
15978        fn candidate(nanos: i64) -> String {
15979            Timedelta::format(nanos)
15980        }
15981
15982        fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
15983            let started = Instant::now();
15984            let mut digest = 0_usize;
15985            for &value in values {
15986                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
15987            }
15988            black_box(digest);
15989            started.elapsed().as_nanos()
15990        }
15991
15992        fn median(samples: &mut [u128]) -> u128 {
15993            samples.sort_unstable();
15994            samples[samples.len() / 2]
15995        }
15996
15997        let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
15998        let values: Vec<i64> = (0..16_384)
15999            .map(|i| {
16000                seed = seed
16001                    .wrapping_mul(6_364_136_223_846_793_005)
16002                    .wrapping_add(1_442_695_040_888_963_407);
16003                let magnitude = (seed & i64::MAX as u64) as i64;
16004                match i % 4 {
16005                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16006                    1 => magnitude,
16007                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16008                    _ => -magnitude,
16009                }
16010            })
16011            .collect();
16012
16013        for &value in &[
16014            Timedelta::NAT,
16015            0,
16016            1,
16017            -1,
16018            Timedelta::NANOS_PER_DAY,
16019            -Timedelta::NANOS_PER_DAY,
16020            i64::MAX,
16021            i64::MIN + 1,
16022        ] {
16023            assert_eq!(former(value), candidate(value));
16024        }
16025        for &value in &values {
16026            assert_eq!(former(value), candidate(value));
16027        }
16028
16029        for _ in 0..2 {
16030            black_box(elapsed(&values, former));
16031            black_box(elapsed(&values, candidate));
16032        }
16033
16034        let mut former_samples = Vec::with_capacity(18);
16035        let mut candidate_samples = Vec::with_capacity(18);
16036        for block in 0_usize..9 {
16037            if block.is_multiple_of(2) {
16038                former_samples.push(elapsed(&values, former));
16039                candidate_samples.push(elapsed(&values, candidate));
16040                candidate_samples.push(elapsed(&values, candidate));
16041                former_samples.push(elapsed(&values, former));
16042            } else {
16043                candidate_samples.push(elapsed(&values, candidate));
16044                former_samples.push(elapsed(&values, former));
16045                former_samples.push(elapsed(&values, former));
16046                candidate_samples.push(elapsed(&values, candidate));
16047            }
16048        }
16049
16050        let former_p50 = median(&mut former_samples);
16051        let candidate_p50 = median(&mut candidate_samples);
16052        eprintln!(
16053            "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
16054            values.len(),
16055            former_p50 as f64 / candidate_p50 as f64,
16056        );
16057        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
16058        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
16059    }
16060
16061    #[test]
16062    fn timedelta_isoformat_basic() {
16063        use super::Timedelta;
16064        assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
16065        assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
16066        assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
16067        assert_eq!(
16068            Timedelta::isoformat(
16069                Timedelta::NANOS_PER_DAY
16070                    + 2 * Timedelta::NANOS_PER_HOUR
16071                    + 30 * Timedelta::NANOS_PER_MIN
16072                    + 45 * Timedelta::NANOS_PER_SEC
16073            ),
16074            "P1DT2H30M45S"
16075        );
16076        assert_eq!(
16077            Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
16078            "P0DT0H0M1.5S"
16079        );
16080        // TEST-CHANGE (fvsao.68): this pinned "-P1DT1H0M0S"; pandas 2.2.3's
16081        // pd.Timedelta(-90000000000000).isoformat() is "P-2DT23H0M0S" (whole
16082        // days rounded down, then a non-negative clock), and -1ns is
16083        // "P-1DT23H59M59.999999999S" (both measured live).
16084        assert_eq!(
16085            Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
16086            "P-2DT23H0M0S"
16087        );
16088        assert_eq!(Timedelta::isoformat(-1), "P-1DT23H59M59.999999999S");
16089    }
16090
16091    #[test]
16092    #[ignore = "foreground release attribution harness"]
16093    fn timedelta_isoformat_single_buffer_ab_7jra1() {
16094        use std::{hint::black_box, time::Instant};
16095
16096        use super::Timedelta;
16097
16098        fn former_impl(nanos: i64) -> String {
16099            if nanos == Timedelta::NAT {
16100                return "NaT".to_string();
16101            }
16102
16103            let negative = nanos < 0;
16104            let abs_nanos = nanos.saturating_abs();
16105            let days = abs_nanos / Timedelta::NANOS_PER_DAY;
16106            let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
16107            let hours = remaining / Timedelta::NANOS_PER_HOUR;
16108            let remaining = remaining % Timedelta::NANOS_PER_HOUR;
16109            let minutes = remaining / Timedelta::NANOS_PER_MIN;
16110            let remaining = remaining % Timedelta::NANOS_PER_MIN;
16111            let seconds = remaining / Timedelta::NANOS_PER_SEC;
16112            let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
16113
16114            let mut result = String::new();
16115            if negative {
16116                result.push('-');
16117            }
16118
16119            result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
16120
16121            if sub_sec_nanos == 0 {
16122                result.push_str(&format!("{seconds}S"));
16123            } else {
16124                let frac = format!("{sub_sec_nanos:09}");
16125                let trimmed = frac.trim_end_matches('0');
16126                result.push_str(&format!("{seconds}.{trimmed}S"));
16127            }
16128
16129            result
16130        }
16131
16132        fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
16133            let start = Instant::now();
16134            let mut digest = 0_usize;
16135            for &value in values {
16136                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
16137            }
16138            black_box(digest);
16139            start.elapsed().as_nanos()
16140        }
16141
16142        fn median(values: &mut [u128]) -> u128 {
16143            values.sort_unstable();
16144            values[values.len() / 2]
16145        }
16146
16147        let mut seed = 0x7d5a_4c31_91e2_b607_u64;
16148        let values: Vec<i64> = (0..16_384)
16149            .map(|i| {
16150                seed = seed
16151                    .wrapping_mul(6_364_136_223_846_793_005)
16152                    .wrapping_add(1_442_695_040_888_963_407);
16153                let magnitude =
16154                    (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
16155                match i % 4 {
16156                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16157                    1 => magnitude,
16158                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16159                    _ => -magnitude,
16160                }
16161            })
16162            .collect();
16163
16164        // The former implementation wrote a negative duration "-P..."; since
16165        // fvsao.68 it is pandas' "P-..." form, so the two agree on
16166        // non-negative durations only (the timing still covers both signs).
16167        for &value in &[Timedelta::NAT, 0, 1, Timedelta::NANOS_PER_DAY, i64::MAX] {
16168            assert_eq!(former_impl(value), Timedelta::isoformat(value));
16169        }
16170        for &value in values.iter().filter(|value| **value >= 0) {
16171            assert_eq!(former_impl(value), Timedelta::isoformat(value));
16172        }
16173
16174        for _ in 0..2 {
16175            black_box(elapsed(&values, former_impl));
16176            black_box(elapsed(&values, Timedelta::isoformat));
16177        }
16178
16179        let mut former = Vec::with_capacity(18);
16180        let mut candidate = Vec::with_capacity(18);
16181        for block in 0..9 {
16182            if block % 2 == 0 {
16183                former.push(elapsed(&values, former_impl));
16184                candidate.push(elapsed(&values, Timedelta::isoformat));
16185                candidate.push(elapsed(&values, Timedelta::isoformat));
16186                former.push(elapsed(&values, former_impl));
16187            } else {
16188                candidate.push(elapsed(&values, Timedelta::isoformat));
16189                former.push(elapsed(&values, former_impl));
16190                former.push(elapsed(&values, former_impl));
16191                candidate.push(elapsed(&values, Timedelta::isoformat));
16192            }
16193        }
16194
16195        let former_p50 = median(&mut former);
16196        let candidate_p50 = median(&mut candidate);
16197        eprintln!(
16198            "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
16199            values.len(),
16200            former_p50,
16201            candidate_p50,
16202            former_p50 as f64 / candidate_p50 as f64,
16203            former_p50 as f64 / values.len() as f64,
16204            candidate_p50 as f64 / values.len() as f64,
16205        );
16206        eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
16207        eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
16208    }
16209
16210    #[test]
16211    fn timedelta_floor_ceil_round() {
16212        use super::Timedelta;
16213        let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
16214
16215        // floor: rounds down
16216        assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
16217        assert_eq!(Timedelta::floor(nanos, "d"), 0);
16218
16219        // ceil: rounds up
16220        assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16221        assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
16222
16223        // round: rounds to nearest (banker's rounding on tie)
16224        assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16225
16226        // NaT preserved
16227        assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
16228        assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
16229        assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
16230
16231        // Invalid freq returns NAT
16232        assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
16233    }
16234
16235    #[test]
16236    fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
16237        use super::Timedelta;
16238
16239        assert_eq!(
16240            Timedelta::floor(-1, "s"),
16241            -Timedelta::NANOS_PER_SEC,
16242            "floor(-1ns, 1s)"
16243        );
16244        assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
16245        assert_eq!(
16246            Timedelta::floor(-1_500_000_000, "s"),
16247            -2 * Timedelta::NANOS_PER_SEC
16248        );
16249        assert_eq!(
16250            Timedelta::ceil(-1_500_000_000, "s"),
16251            -Timedelta::NANOS_PER_SEC
16252        );
16253        assert_eq!(
16254            Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
16255            -Timedelta::NANOS_PER_SEC
16256        );
16257        assert_eq!(
16258            Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
16259            -Timedelta::NANOS_PER_SEC
16260        );
16261        assert_eq!(
16262            Timedelta::floor(1_500_000_000, "s"),
16263            Timedelta::NANOS_PER_SEC
16264        );
16265        assert_eq!(
16266            Timedelta::ceil(1_500_000_000, "s"),
16267            2 * Timedelta::NANOS_PER_SEC
16268        );
16269    }
16270
16271    #[test]
16272    fn timedelta_scalar_dtype() {
16273        let td = Scalar::Timedelta64(86_400_000_000_000);
16274        assert_eq!(td.dtype(), DType::Timedelta64);
16275    }
16276
16277    #[test]
16278    fn timedelta_scalar_is_missing() {
16279        use super::Timedelta;
16280        let valid = Scalar::Timedelta64(1000);
16281        let nat = Scalar::Timedelta64(Timedelta::NAT);
16282        assert!(!valid.is_missing());
16283        assert!(nat.is_missing());
16284    }
16285
16286    #[test]
16287    fn dtype_utf8_deserializes_legacy_aliases() {
16288        let dtype: DType = serde_json::from_str("\"str\"").unwrap();
16289        assert_eq!(dtype, DType::Utf8);
16290
16291        let dtype: DType = serde_json::from_str("\"string\"").unwrap();
16292        assert_eq!(dtype, DType::Utf8);
16293    }
16294
16295    #[test]
16296    fn datetime64_dtype_carries_timezone_00ze3() {
16297        let naive = DType::datetime64_naive();
16298        assert_eq!(naive.timezone(), None);
16299        assert_eq!(naive.display_name(), "datetime64[ns]");
16300
16301        let aware = DType::datetime64_tz("America/New_York");
16302        assert_eq!(aware.timezone(), Some("America/New_York"));
16303        assert_eq!(aware.display_name(), "datetime64[ns, America/New_York]");
16304        assert_ne!(aware, naive, "timezone must participate in dtype identity");
16305
16306        let json = serde_json::to_string(&aware).expect("serialize timezone dtype");
16307        assert_eq!(
16308            serde_json::from_str::<DType>(&json).expect("deserialize timezone dtype"),
16309            aware
16310        );
16311    }
16312
16313    #[test]
16314    fn scalar_utf8_deserializes_legacy_aliases() {
16315        let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
16316        assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
16317
16318        let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
16319        assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
16320    }
16321
16322    #[test]
16323    fn nancumsum_skips_nulls_and_accumulates() {
16324        let values = vec![
16325            Scalar::Float64(1.0),
16326            Scalar::Null(NullKind::NaN),
16327            Scalar::Float64(2.0),
16328            Scalar::Float64(3.0),
16329        ];
16330        let out = super::nancumsum(&values);
16331        assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
16332        assert!(out[1].is_missing());
16333        assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
16334        assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
16335    }
16336
16337    #[test]
16338    fn nancumprod_skips_nulls_and_multiplies() {
16339        let values = vec![
16340            Scalar::Float64(2.0),
16341            Scalar::Null(NullKind::NaN),
16342            Scalar::Float64(3.0),
16343            Scalar::Float64(4.0),
16344        ];
16345        let out = super::nancumprod(&values);
16346        assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16347        assert!(out[1].is_missing());
16348        assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
16349        assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
16350    }
16351
16352    #[test]
16353    fn nancummax_tracks_running_max() {
16354        let values = vec![
16355            Scalar::Float64(1.0),
16356            Scalar::Float64(3.0),
16357            Scalar::Null(NullKind::NaN),
16358            Scalar::Float64(2.0),
16359            Scalar::Float64(5.0),
16360        ];
16361        let out = super::nancummax(&values);
16362        assert_eq!(out[0], Scalar::Float64(1.0));
16363        assert_eq!(out[1], Scalar::Float64(3.0));
16364        assert!(out[2].is_missing());
16365        assert_eq!(out[3], Scalar::Float64(3.0));
16366        assert_eq!(out[4], Scalar::Float64(5.0));
16367    }
16368
16369    #[test]
16370    fn nancummin_tracks_running_min() {
16371        let values = vec![
16372            Scalar::Float64(5.0),
16373            Scalar::Float64(3.0),
16374            Scalar::Null(NullKind::NaN),
16375            Scalar::Float64(4.0),
16376            Scalar::Float64(1.0),
16377        ];
16378        let out = super::nancummin(&values);
16379        assert_eq!(out[0], Scalar::Float64(5.0));
16380        assert_eq!(out[1], Scalar::Float64(3.0));
16381        assert!(out[2].is_missing());
16382        assert_eq!(out[3], Scalar::Float64(3.0));
16383        assert_eq!(out[4], Scalar::Float64(1.0));
16384    }
16385
16386    #[test]
16387    fn nancumsum_timedelta64_preserves_dtype_x0x91() {
16388        // Per br-frankenpandas-x0x91: pandas td_series.cumsum() returns
16389        // Timedelta64 running sums. Was silently NaN before.
16390        let one_hour = 3_600 * 1_000_000_000_i64;
16391        let values = vec![
16392            Scalar::Timedelta64(one_hour),
16393            Scalar::Timedelta64(2 * one_hour),
16394            Scalar::Timedelta64(3 * one_hour),
16395        ];
16396        let out = super::nancumsum(&values);
16397        assert_eq!(out[0], Scalar::Timedelta64(one_hour));
16398        assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
16399        assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
16400    }
16401
16402    #[test]
16403    fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
16404        let one_hour = 3_600 * 1_000_000_000_i64;
16405        let values = vec![
16406            Scalar::Timedelta64(2 * one_hour),
16407            Scalar::Timedelta64(5 * one_hour),
16408            Scalar::Timedelta64(one_hour),
16409            Scalar::Timedelta64(3 * one_hour),
16410        ];
16411        let mx = super::nancummax(&values);
16412        assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
16413        assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
16414        assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
16415        assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
16416
16417        let mn = super::nancummin(&values);
16418        assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
16419        assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
16420        assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
16421        assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
16422    }
16423
16424    #[test]
16425    fn nancumulative_timedelta64_skips_nat_x0x91() {
16426        let one_hour = 3_600 * 1_000_000_000_i64;
16427        let values = vec![
16428            Scalar::Timedelta64(one_hour),
16429            Scalar::Timedelta64(Timedelta::NAT),
16430            Scalar::Timedelta64(2 * one_hour),
16431        ];
16432        let cs = super::nancumsum(&values);
16433        assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
16434        assert!(cs[1].is_missing());
16435        assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
16436    }
16437
16438    #[test]
16439    fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
16440        // Differential vs independent cumulative nanops oracles
16441        // (br-frankenpandas-k63oz). Seeded LCG, no mocks.
16442        fn next(seed: &mut u64) -> u64 {
16443            *seed = seed
16444                .wrapping_mul(3202034522624059733)
16445                .wrapping_add(4354685564936845319);
16446            *seed
16447        }
16448
16449        fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
16450            assert_eq!(
16451                actual.len(),
16452                expected.len(),
16453                "case={case} family={family} op={op}: length mismatch"
16454            );
16455            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
16456                assert!(
16457                    actual.semantic_eq(expected),
16458                    "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
16459                );
16460            }
16461        }
16462
16463        fn expected_numeric(
16464            values: &[Scalar],
16465        ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16466            let mut sum = Vec::with_capacity(values.len());
16467            let mut prod = Vec::with_capacity(values.len());
16468            let mut max = Vec::with_capacity(values.len());
16469            let mut min = Vec::with_capacity(values.len());
16470            let mut running_sum = 0.0_f64;
16471            let mut running_prod = 1.0_f64;
16472            let mut running_max: Option<f64> = None;
16473            let mut running_min: Option<f64> = None;
16474
16475            for value in values {
16476                if value.is_missing() {
16477                    sum.push(Scalar::Null(NullKind::NaN));
16478                    prod.push(Scalar::Null(NullKind::NaN));
16479                    max.push(Scalar::Null(NullKind::NaN));
16480                    min.push(Scalar::Null(NullKind::NaN));
16481                    continue;
16482                }
16483                let Ok(value) = value.to_f64() else {
16484                    sum.push(Scalar::Null(NullKind::NaN));
16485                    prod.push(Scalar::Null(NullKind::NaN));
16486                    max.push(Scalar::Null(NullKind::NaN));
16487                    min.push(Scalar::Null(NullKind::NaN));
16488                    continue;
16489                };
16490                if value.is_nan() {
16491                    sum.push(Scalar::Null(NullKind::NaN));
16492                    prod.push(Scalar::Null(NullKind::NaN));
16493                    max.push(Scalar::Null(NullKind::NaN));
16494                    min.push(Scalar::Null(NullKind::NaN));
16495                    continue;
16496                }
16497                running_sum += value;
16498                running_prod *= value;
16499                running_max = Some(running_max.map_or(value, |current| current.max(value)));
16500                running_min = Some(running_min.map_or(value, |current| current.min(value)));
16501                sum.push(Scalar::Float64(running_sum));
16502                prod.push(Scalar::Float64(running_prod));
16503                max.push(Scalar::Float64(running_max.expect("initialized")));
16504                min.push(Scalar::Float64(running_min.expect("initialized")));
16505            }
16506
16507            (sum, prod, max, min)
16508        }
16509
16510        fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16511            let mut sum = Vec::with_capacity(values.len());
16512            let mut max = Vec::with_capacity(values.len());
16513            let mut min = Vec::with_capacity(values.len());
16514            let mut running_sum = 0_i128;
16515            let mut running_max: Option<i64> = None;
16516            let mut running_min: Option<i64> = None;
16517
16518            for value in values {
16519                if value.is_missing() {
16520                    sum.push(Scalar::Null(NullKind::NaT));
16521                    max.push(Scalar::Null(NullKind::NaT));
16522                    min.push(Scalar::Null(NullKind::NaT));
16523                    continue;
16524                }
16525                let Scalar::Timedelta64(ns) = value else {
16526                    sum.push(Scalar::Null(NullKind::NaT));
16527                    max.push(Scalar::Null(NullKind::NaT));
16528                    min.push(Scalar::Null(NullKind::NaT));
16529                    continue;
16530                };
16531                running_sum = running_sum.saturating_add(i128::from(*ns));
16532                running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
16533                running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
16534                // br-frankenpandas-opz27: mirror the production contract (NaT
16535                // outside the representable range), not the old clamp.
16536                sum.push(super::timedelta_ns_to_scalar(running_sum));
16537                max.push(Scalar::Timedelta64(running_max.expect("initialized")));
16538                min.push(Scalar::Timedelta64(running_min.expect("initialized")));
16539            }
16540
16541            (sum, max, min)
16542        }
16543
16544        let mut seed = 0xc0de_c63a_5eed_0421_u64;
16545        for case in 0..260 {
16546            let len = (next(&mut seed) % 89 + 1) as usize;
16547
16548            let mut numeric = Vec::with_capacity(len);
16549            numeric.push(Scalar::Int64(case as i64 - 130));
16550            for _ in 1..len {
16551                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16552                numeric.push(match next(&mut seed) % 8 {
16553                    0 => Scalar::Null(NullKind::Null),
16554                    1 => Scalar::Null(NullKind::NaN),
16555                    2 => Scalar::Float64(f64::NAN),
16556                    3 => Scalar::Bool(raw & 1 == 0),
16557                    4 => Scalar::Int64(raw % 251),
16558                    5 => Scalar::Float64(raw as f64 / 79.0),
16559                    6 => Scalar::Float64(0.0),
16560                    _ => Scalar::Float64(-0.0),
16561                });
16562            }
16563            let (sum, prod, max, min) = expected_numeric(&numeric);
16564            assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
16565            assert_vec(
16566                case,
16567                "numeric",
16568                "cumprod",
16569                &super::nancumprod(&numeric),
16570                &prod,
16571            );
16572            assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
16573            assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
16574
16575            let mut timedeltas = Vec::with_capacity(len);
16576            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16577            for _ in 1..len {
16578                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16579                timedeltas.push(match next(&mut seed) % 7 {
16580                    0 => Scalar::Null(NullKind::Null),
16581                    1 => Scalar::Timedelta64(i64::MIN),
16582                    _ => Scalar::Timedelta64(raw),
16583                });
16584            }
16585            let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
16586            assert_vec(
16587                case,
16588                "timedelta",
16589                "cumsum",
16590                &super::nancumsum(&timedeltas),
16591                &td_sum,
16592            );
16593            assert_vec(
16594                case,
16595                "timedelta",
16596                "cummax",
16597                &super::nancummax(&timedeltas),
16598                &td_max,
16599            );
16600            assert_vec(
16601                case,
16602                "timedelta",
16603                "cummin",
16604                &super::nancummin(&timedeltas),
16605                &td_min,
16606            );
16607        }
16608    }
16609
16610    #[test]
16611    fn nanquantile_linear_interpolation_matches_numpy() {
16612        let values = vec![
16613            Scalar::Float64(1.0),
16614            Scalar::Float64(2.0),
16615            Scalar::Float64(3.0),
16616            Scalar::Float64(4.0),
16617            Scalar::Float64(5.0),
16618        ];
16619        // median
16620        let q = super::nanquantile(&values, 0.5);
16621        assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
16622        // 25th percentile: interpolate between 2.0 and 3.0 at pos 1.0 → 2.0
16623        let q25 = super::nanquantile(&values, 0.25);
16624        assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16625    }
16626
16627    #[test]
16628    fn nanquantile_ignores_nulls() {
16629        let values = vec![
16630            Scalar::Float64(1.0),
16631            Scalar::Null(NullKind::NaN),
16632            Scalar::Float64(3.0),
16633        ];
16634        let q = super::nanquantile(&values, 0.5);
16635        assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16636    }
16637
16638    #[test]
16639    fn nanquantile_empty_and_out_of_range_yield_null() {
16640        assert!(super::nanquantile(&[], 0.5).is_missing());
16641        assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
16642        assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
16643    }
16644
16645    #[test]
16646    fn nanquantile_timedelta64_preserves_dtype_5djk7() {
16647        // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
16648        // Timedelta64 — was silently NaN before via collect_finite.
16649        let one_hour: i64 = 3_600 * 1_000_000_000;
16650        let vals = vec![
16651            Scalar::Timedelta64(one_hour),
16652            Scalar::Timedelta64(2 * one_hour),
16653            Scalar::Timedelta64(3 * one_hour),
16654            Scalar::Timedelta64(4 * one_hour),
16655            Scalar::Timedelta64(5 * one_hour),
16656        ];
16657        assert_eq!(
16658            super::nanquantile(&vals, 0.5),
16659            Scalar::Timedelta64(3 * one_hour)
16660        );
16661        assert_eq!(
16662            super::nanquantile(&vals, 0.0),
16663            Scalar::Timedelta64(one_hour)
16664        );
16665        assert_eq!(
16666            super::nanquantile(&vals, 1.0),
16667            Scalar::Timedelta64(5 * one_hour)
16668        );
16669    }
16670
16671    #[test]
16672    fn nanquantile_timedelta64_linear_interpolation_5djk7() {
16673        let one_hour: i64 = 3_600 * 1_000_000_000;
16674        let vals = vec![
16675            Scalar::Timedelta64(one_hour),
16676            Scalar::Timedelta64(3 * one_hour),
16677        ];
16678        // Linear interpolation: at q=0.5, midpoint = 2h
16679        assert_eq!(
16680            super::nanquantile(&vals, 0.5),
16681            Scalar::Timedelta64(2 * one_hour)
16682        );
16683    }
16684
16685    #[test]
16686    fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
16687        // Differential vs independent sort-based quantile oracles
16688        // (br-frankenpandas-ecb7r). Seeded LCG, no mocks.
16689        fn next(seed: &mut u64) -> u64 {
16690            *seed = seed
16691                .wrapping_mul(3202034522624059733)
16692                .wrapping_add(4354685564936845319);
16693            *seed
16694        }
16695
16696        fn interpolated(sorted: &[f64], q: f64) -> f64 {
16697            if sorted.len() == 1 {
16698                return sorted[0];
16699            }
16700            let pos = q * (sorted.len() - 1) as f64;
16701            let lo = pos.floor() as usize;
16702            let hi = pos.ceil() as usize;
16703            if lo == hi {
16704                sorted[lo]
16705            } else {
16706                let weight = pos - lo as f64;
16707                sorted[lo] + (sorted[hi] - sorted[lo]) * weight
16708            }
16709        }
16710
16711        fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
16712            if !(0.0..=1.0).contains(&q) {
16713                return Scalar::Null(NullKind::NaN);
16714            }
16715            let mut samples = values
16716                .iter()
16717                .filter(|value| !value.is_missing())
16718                .filter_map(|value| value.to_f64().ok())
16719                .collect::<Vec<_>>();
16720            if samples.is_empty() {
16721                return Scalar::Null(NullKind::NaN);
16722            }
16723            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16724            Scalar::Float64(interpolated(&samples, q))
16725        }
16726
16727        fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
16728            if !(0.0..=1.0).contains(&q) {
16729                return Scalar::Null(NullKind::NaN);
16730            }
16731            let mut samples = values
16732                .iter()
16733                .filter_map(|value| match value {
16734                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
16735                    _ => None,
16736                })
16737                .collect::<Vec<_>>();
16738            if samples.is_empty() {
16739                // Per br-frankenpandas-k7apg: a NaT-only Timedelta input stays in
16740                // the Timedelta family (pandas returns NaT, not float NaN).
16741                return Scalar::Timedelta64(Timedelta::NAT);
16742            }
16743            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16744            Scalar::Timedelta64(interpolated(&samples, q) as i64)
16745        }
16746
16747        fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
16748            let actual = super::nanquantile(values, q);
16749            assert!(
16750                actual.semantic_eq(&expected),
16751                "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
16752            );
16753        }
16754
16755        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16756        assert_quantile(
16757            usize::MAX,
16758            "numeric_all_missing",
16759            &numeric_all_missing,
16760            0.5,
16761            expected_numeric(&numeric_all_missing, 0.5),
16762        );
16763        assert_quantile(
16764            usize::MAX - 1,
16765            "numeric_out_of_range",
16766            &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
16767            1.25,
16768            Scalar::Null(NullKind::NaN),
16769        );
16770
16771        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16772        assert_quantile(
16773            usize::MAX - 2,
16774            "timedelta_all_missing",
16775            &td_all_missing,
16776            0.5,
16777            expected_timedelta(&td_all_missing, 0.5),
16778        );
16779        assert_quantile(
16780            usize::MAX - 3,
16781            "timedelta_out_of_range",
16782            &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
16783            -0.25,
16784            Scalar::Null(NullKind::NaN),
16785        );
16786
16787        let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
16788        for case in 0..260 {
16789            let len = (next(&mut seed) % 83 + 1) as usize;
16790            let q = match next(&mut seed) % 8 {
16791                0 => 0.0,
16792                1 => 0.25,
16793                2 => 0.5,
16794                3 => 0.75,
16795                4 => 1.0,
16796                _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
16797            };
16798
16799            let mut numeric = Vec::with_capacity(len);
16800            numeric.push(Scalar::Int64(case as i64 - 130));
16801            for _ in 1..len {
16802                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16803                numeric.push(match next(&mut seed) % 8 {
16804                    0 => Scalar::Null(NullKind::Null),
16805                    1 => Scalar::Null(NullKind::NaN),
16806                    2 => Scalar::Float64(f64::NAN),
16807                    3 => Scalar::Bool(raw & 1 == 0),
16808                    4 => Scalar::Int64(raw % 251),
16809                    5 => Scalar::Float64(raw as f64 / 67.0),
16810                    6 => Scalar::Float64(0.0),
16811                    _ => Scalar::Float64(-0.0),
16812                });
16813            }
16814            assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
16815
16816            let mut timedeltas = Vec::with_capacity(len);
16817            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16818            for _ in 1..len {
16819                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16820                timedeltas.push(match next(&mut seed) % 7 {
16821                    0 => Scalar::Null(NullKind::Null),
16822                    1 => Scalar::Timedelta64(i64::MIN),
16823                    _ => Scalar::Timedelta64(raw),
16824                });
16825            }
16826            assert_quantile(
16827                case,
16828                "timedelta",
16829                &timedeltas,
16830                q,
16831                expected_timedelta(&timedeltas, q),
16832            );
16833        }
16834    }
16835
16836    #[test]
16837    fn nanargmax_returns_first_position() {
16838        let values = vec![
16839            Scalar::Float64(1.0),
16840            Scalar::Null(NullKind::NaN),
16841            Scalar::Float64(4.0),
16842            Scalar::Float64(4.0),
16843            Scalar::Float64(2.0),
16844        ];
16845        assert_eq!(super::nanargmax(&values), Some(2));
16846    }
16847
16848    #[test]
16849    fn nanargmin_returns_first_position() {
16850        let values = vec![
16851            Scalar::Float64(3.0),
16852            Scalar::Null(NullKind::NaN),
16853            Scalar::Float64(1.0),
16854            Scalar::Float64(1.0),
16855        ];
16856        assert_eq!(super::nanargmin(&values), Some(2));
16857    }
16858
16859    #[test]
16860    fn nanargmax_all_missing_returns_none() {
16861        let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
16862        assert_eq!(super::nanargmax(&values), None);
16863        assert_eq!(super::nanargmin(&values), None);
16864    }
16865
16866    #[test]
16867    fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
16868        // Differential vs independent first-tie arg oracles
16869        // (br-frankenpandas-unkj6). Seeded LCG, no mocks.
16870        fn next(seed: &mut u64) -> u64 {
16871            *seed = seed
16872                .wrapping_mul(2862933555777941757)
16873                .wrapping_add(3037000493);
16874            *seed
16875        }
16876
16877        fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
16878            let mut best: Option<(usize, f64)> = None;
16879            for (idx, value) in values.iter().enumerate() {
16880                if value.is_missing() {
16881                    continue;
16882                }
16883                let Ok(value) = value.to_f64() else {
16884                    continue;
16885                };
16886                if value.is_nan() {
16887                    continue;
16888                }
16889                match best {
16890                    None => best = Some((idx, value)),
16891                    Some((_, current))
16892                        if (find_max && value > current) || (!find_max && value < current) =>
16893                    {
16894                        best = Some((idx, value));
16895                    }
16896                    _ => {}
16897                }
16898            }
16899            best.map(|(idx, _)| idx)
16900        }
16901
16902        fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
16903            let mut best: Option<(usize, i64)> = None;
16904            for (idx, value) in values.iter().enumerate() {
16905                if value.is_missing() {
16906                    continue;
16907                }
16908                let Scalar::Timedelta64(ns) = value else {
16909                    continue;
16910                };
16911                match best {
16912                    None => best = Some((idx, *ns)),
16913                    Some((_, current))
16914                        if (find_max && *ns > current) || (!find_max && *ns < current) =>
16915                    {
16916                        best = Some((idx, *ns));
16917                    }
16918                    _ => {}
16919                }
16920            }
16921            best.map(|(idx, _)| idx)
16922        }
16923
16924        fn assert_args(
16925            case: usize,
16926            family: &str,
16927            values: &[Scalar],
16928            expected_min: Option<usize>,
16929            expected_max: Option<usize>,
16930        ) {
16931            assert_eq!(
16932                super::nanargmin(values),
16933                expected_min,
16934                "case={case} family={family}: nanargmin mismatch for {values:?}"
16935            );
16936            assert_eq!(
16937                super::nanargmax(values),
16938                expected_max,
16939                "case={case} family={family}: nanargmax mismatch for {values:?}"
16940            );
16941        }
16942
16943        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16944        assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
16945        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16946        assert_args(
16947            usize::MAX - 1,
16948            "timedelta_all_missing",
16949            &td_all_missing,
16950            None,
16951            None,
16952        );
16953        let positive_int64_endpoint = [
16954            Scalar::Int64(i64::MAX - 1),
16955            Scalar::Null(NullKind::Null),
16956            Scalar::Int64(i64::MAX),
16957        ];
16958        assert_args(
16959            usize::MAX - 2,
16960            "int64_positive_endpoint_exact_order",
16961            &positive_int64_endpoint,
16962            Some(0),
16963            Some(2),
16964        );
16965        let negative_int64_endpoint = [
16966            Scalar::Int64(i64::MIN + 2),
16967            Scalar::Null(NullKind::NaN),
16968            Scalar::Int64(i64::MIN + 1),
16969        ];
16970        assert_args(
16971            usize::MAX - 3,
16972            "int64_negative_endpoint_exact_order",
16973            &negative_int64_endpoint,
16974            Some(2),
16975            Some(0),
16976        );
16977
16978        let mut seed = 0xa126_5eed_ed9e_u64;
16979        for case in 0..260 {
16980            let len = (next(&mut seed) % 83 + 1) as usize;
16981
16982            let mut numeric = Vec::with_capacity(len);
16983            numeric.push(Scalar::Int64(case as i64 - 130));
16984            if len > 1 {
16985                numeric.push(Scalar::Int64(case as i64 - 130));
16986            }
16987            for _ in numeric.len()..len {
16988                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16989                numeric.push(match next(&mut seed) % 9 {
16990                    0 => Scalar::Null(NullKind::Null),
16991                    1 => Scalar::Null(NullKind::NaN),
16992                    2 => Scalar::Float64(f64::NAN),
16993                    3 => Scalar::Bool(raw & 1 == 0),
16994                    4 => Scalar::Int64(raw % 211),
16995                    5 => Scalar::Float64(raw as f64 / 47.0),
16996                    6 => Scalar::Float64(0.0),
16997                    7 => Scalar::Float64(-0.0),
16998                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
16999                });
17000            }
17001            assert_args(
17002                case,
17003                "numeric",
17004                &numeric,
17005                expected_numeric(&numeric, false),
17006                expected_numeric(&numeric, true),
17007            );
17008
17009            let mut timedeltas = Vec::with_capacity(len);
17010            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17011            if len > 1 {
17012                timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17013            }
17014            for _ in timedeltas.len()..len {
17015                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17016                timedeltas.push(match next(&mut seed) % 7 {
17017                    0 => Scalar::Null(NullKind::Null),
17018                    1 => Scalar::Timedelta64(i64::MIN),
17019                    _ => Scalar::Timedelta64(raw),
17020                });
17021            }
17022            assert_args(
17023                case,
17024                "timedelta",
17025                &timedeltas,
17026                expected_timedelta(&timedeltas, false),
17027                expected_timedelta(&timedeltas, true),
17028            );
17029        }
17030    }
17031
17032    #[test]
17033    fn nansem_matches_std_over_sqrt_n() {
17034        let values = vec![
17035            Scalar::Float64(2.0),
17036            Scalar::Float64(4.0),
17037            Scalar::Float64(4.0),
17038            Scalar::Float64(4.0),
17039            Scalar::Float64(5.0),
17040            Scalar::Float64(5.0),
17041            Scalar::Float64(7.0),
17042            Scalar::Float64(9.0),
17043        ];
17044        // numpy/scipy: std(ddof=1) = 2.138089935299395; sem = std/sqrt(8) = 0.7559
17045        let sem = super::nansem(&values, 1);
17046        assert!(matches!(sem, Scalar::Float64(_)));
17047        let Scalar::Float64(v) = sem else {
17048            return;
17049        };
17050        assert!((v - 0.7559289460184544).abs() < 1e-9);
17051    }
17052
17053    #[test]
17054    fn nansem_grouped_is_sqrt_var_over_n_7hxqv() {
17055        // pandas 2.2.3: Series([1.0, 4.0]).groupby([0, 0]).sem() == 1.5 while
17056        // Series([1.0, 4.0]).sem() == 1.4999999999999998.
17057        let values = [
17058            Scalar::Float64(1.0),
17059            Scalar::Null(NullKind::NaN),
17060            Scalar::Float64(4.0),
17061        ];
17062        assert_eq!(super::nansem_grouped(&values, 1), Scalar::Float64(1.5));
17063        // NEGATIVE: Series.sem keeps std / sqrt(n).
17064        assert_eq!(
17065            super::nansem(&values, 1),
17066            Scalar::Float64(1.499_999_999_999_999_8)
17067        );
17068        assert!(super::nansem_grouped(&values[..1], 1).is_missing());
17069    }
17070
17071    #[test]
17072    fn grouped_reducers_add_as_pandas_group_kernels_xhogl() {
17073        // pandas 2.2.3 groupby of ten 0.1: sum 1.0, mean 0.1, var 0.0 - a
17074        // plain fold gives 0.9999999999999999, 0.09999999999999999 and
17075        // 2.1e-34 (br-frankenpandas-xhogl).
17076        let tenths: Vec<Scalar> = (0..10).map(|_| Scalar::Float64(0.1)).collect();
17077        assert_eq!(super::nansum_grouped(&tenths), Scalar::Float64(1.0));
17078        assert_eq!(super::nanmean_grouped(&tenths), Scalar::Float64(0.1));
17079        assert_eq!(super::nanvar_grouped(&tenths, 1), Scalar::Float64(0.0));
17080        assert_eq!(super::nanstd_grouped(&tenths, 1), Scalar::Float64(0.0));
17081        // NEGATIVE: the Series reductions keep their plain fold.
17082        assert_eq!(
17083            super::nansum(&tenths),
17084            Scalar::Float64(0.999_999_999_999_999_9)
17085        );
17086        // An inf keeps the sum inf (the compensation would go NaN).
17087        let mut sum = super::KahanSum::default();
17088        for value in [1.0, f64::INFINITY, 2.0] {
17089            sum.add(value);
17090        }
17091        assert_eq!(sum.sum(), f64::INFINITY);
17092        // Missing values are skipped; too few for ddof is missing.
17093        let gapped = [
17094            Scalar::Float64(1.0),
17095            Scalar::Null(NullKind::NaN),
17096            Scalar::Float64(4.0),
17097        ];
17098        assert_eq!(super::nanmean_grouped(&gapped), Scalar::Float64(2.5));
17099        assert_eq!(super::nanvar_grouped(&gapped, 1), Scalar::Float64(4.5));
17100        assert!(super::nanvar_grouped(&gapped[..1], 1).is_missing());
17101        // Timedelta input keeps the exact integer paths.
17102        let spans = [Scalar::Timedelta64(1), Scalar::Timedelta64(2)];
17103        assert_eq!(super::nansum_grouped(&spans), super::nansum(&spans));
17104    }
17105
17106    #[test]
17107    fn grouped_skew_is_pandas_online_group_skew_vjfq9() {
17108        // pandas 2.2.3 groupby skew of [1, 4, 8] is 0.42327316026800615 - a
17109        // two-pass form gives 0.4232731602680071 (br-frankenpandas-vjfq9).
17110        let group = [
17111            Scalar::Float64(1.0),
17112            Scalar::Null(NullKind::NaN),
17113            Scalar::Float64(4.0),
17114            Scalar::Float64(8.0),
17115        ];
17116        assert_eq!(
17117            super::nanskew_grouped(&group),
17118            Scalar::Float64(0.423_273_160_268_006_15)
17119        );
17120        // 2922 values: pandas raises (n - 1) ** 0.5 with libm pow, which is not
17121        // sqrt's answer for n - 1 = 2921 (sqrt gives -0.002284383734800802).
17122        let long: Vec<Scalar> = (0..2922_i32)
17123            .map(|i| Scalar::Float64(f64::from((i * 7919) % 1000) / 7.0))
17124            .collect();
17125        let glibc_pow = Scalar::Float64(-0.002_284_383_734_800_801_4);
17126        // That is pandas on glibc, the oracle's platform. pandas' Cython
17127        // `** 0.5` calls the platform's pow, as fp does, and Apple's libm
17128        // returns sqrt's answer for 2921 (CI 36847809394 macos-latest), so
17129        // another libm may give that one - never anything else
17130        // (br-frankenpandas-3bo1g).
17131        if cfg!(all(target_os = "linux", target_env = "gnu")) {
17132            assert_eq!(super::nanskew_grouped(&long), glibc_pow);
17133        } else {
17134            let sqrt = Scalar::Float64(-0.002_284_383_734_800_802);
17135            assert!([glibc_pow, sqrt].contains(&super::nanskew_grouped(&long)));
17136        }
17137        // A constant group is 0; below 3 values missing; an inf poisons its
17138        // group (pandas skips only NaN), where dropping it would leave [1, 2, 5].
17139        let constant = [7.0; 3].map(Scalar::Float64);
17140        assert_eq!(super::nanskew_grouped(&constant), Scalar::Float64(0.0));
17141        assert!(super::nanskew_grouped(&group[..2]).is_missing());
17142        let with_inf = [1.0, f64::INFINITY, 2.0, 5.0].map(Scalar::Float64);
17143        assert!(super::nanskew_grouped(&with_inf).is_missing());
17144    }
17145
17146    #[test]
17147    fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
17148        fn former(values: &[Scalar], ddof: usize) -> Scalar {
17149            let nums = super::collect_finite(values);
17150            if nums.len() <= ddof {
17151                return Scalar::Null(NullKind::NaN);
17152            }
17153            match super::nanstd(values, ddof) {
17154                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17155                other => other,
17156            }
17157        }
17158
17159        fn assert_same_bits(values: &[Scalar], ddof: usize) {
17160            let expected = former(values, ddof);
17161            let actual = super::nansem(values, ddof);
17162            match (&expected, &actual) {
17163                (Scalar::Float64(expected), Scalar::Float64(actual)) => {
17164                    assert_eq!(
17165                        actual.to_bits(),
17166                        expected.to_bits(),
17167                        "values={values:?} ddof={ddof}"
17168                    );
17169                }
17170                _ => assert!(
17171                    actual.semantic_eq(&expected),
17172                    "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
17173                ),
17174            }
17175        }
17176
17177        let mut generated = Vec::with_capacity(4_096);
17178        for idx in 0..4_096_i64 {
17179            generated.push(match idx % 257 {
17180                0 => Scalar::Null(NullKind::NaN),
17181                1 => Scalar::Float64(-0.0),
17182                2 => Scalar::Float64(0.0),
17183                _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
17184                _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
17185            });
17186        }
17187
17188        let cases = [
17189            Vec::new(),
17190            vec![Scalar::Int64(1)],
17191            vec![
17192                Scalar::Null(NullKind::Null),
17193                Scalar::Float64(f64::NAN),
17194                Scalar::Int64(i64::MIN),
17195                Scalar::Int64(i64::MAX),
17196                Scalar::Float64(-0.0),
17197                Scalar::Float64(0.0),
17198            ],
17199            generated,
17200        ];
17201        for values in &cases {
17202            for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
17203                assert_same_bits(values, ddof);
17204            }
17205        }
17206    }
17207
17208    #[test]
17209    #[ignore = "foreground release A/B harness"]
17210    fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
17211        const ROWS: usize = 262_144;
17212        const BATCH: usize = 8;
17213        const BLOCKS: usize = 9;
17214        const PRECONDITION_CALLS: usize = 2;
17215
17216        fn former(values: &[Scalar], ddof: usize) -> Scalar {
17217            let nums = super::collect_finite(values);
17218            if nums.len() <= ddof {
17219                return Scalar::Null(NullKind::NaN);
17220            }
17221            match super::nanstd(values, ddof) {
17222                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17223                other => other,
17224            }
17225        }
17226
17227        fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
17228            let values = std::hint::black_box(values);
17229            if candidate {
17230                super::nansem(values, 1)
17231            } else {
17232                former(values, 1)
17233            }
17234        }
17235
17236        fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
17237            for _ in 0..PRECONDITION_CALLS {
17238                std::hint::black_box(evaluate(values, candidate));
17239            }
17240            let started = std::time::Instant::now();
17241            for _ in 0..BATCH {
17242                std::hint::black_box(evaluate(values, candidate));
17243            }
17244            started.elapsed().as_nanos()
17245        }
17246
17247        fn median(mut samples: Vec<u128>) -> u128 {
17248            samples.sort_unstable();
17249            samples[samples.len() / 2]
17250        }
17251
17252        fn spread(a: u128, b: u128) -> f64 {
17253            a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
17254        }
17255
17256        let values = (0..ROWS)
17257            .map(|idx| {
17258                if idx % 257 == 0 {
17259                    Scalar::Null(NullKind::NaN)
17260                } else {
17261                    Scalar::Int64((idx % 8_191) as i64 - 4_095)
17262                }
17263            })
17264            .collect::<Vec<_>>();
17265
17266        let expected_bits = match former(&values, 1) {
17267            Scalar::Float64(value) => Some(value.to_bits()),
17268            _ => None,
17269        };
17270        let actual_bits = match super::nansem(&values, 1) {
17271            Scalar::Float64(value) => Some(value.to_bits()),
17272            _ => None,
17273        };
17274        assert!(
17275            expected_bits.is_some(),
17276            "numeric nansem must return Float64"
17277        );
17278        assert_eq!(actual_bits, expected_bits, "A/B output bits");
17279
17280        std::hint::black_box(evaluate(&values, false));
17281        std::hint::black_box(evaluate(&values, true));
17282
17283        let body_started = std::time::Instant::now();
17284        let mut former_a = Vec::with_capacity(BLOCKS);
17285        let mut former_b = Vec::with_capacity(BLOCKS);
17286        let mut candidate_a = Vec::with_capacity(BLOCKS);
17287        let mut candidate_b = Vec::with_capacity(BLOCKS);
17288        for block in 0..BLOCKS {
17289            let order = if block % 2 == 0 {
17290                [(false, 0), (true, 0), (true, 1), (false, 1)]
17291            } else {
17292                [(true, 1), (false, 1), (false, 0), (true, 0)]
17293            };
17294            for (candidate, duplicate) in order {
17295                let elapsed = elapsed_ns(&values, candidate);
17296                match (candidate, duplicate) {
17297                    (false, 0) => former_a.push(elapsed),
17298                    (false, _) => former_b.push(elapsed),
17299                    (true, 0) => candidate_a.push(elapsed),
17300                    (true, _) => candidate_b.push(elapsed),
17301                }
17302            }
17303        }
17304
17305        let former_a = median(former_a) / BATCH as u128;
17306        let former_b = median(former_b) / BATCH as u128;
17307        let candidate_a = median(candidate_a) / BATCH as u128;
17308        let candidate_b = median(candidate_b) / BATCH as u128;
17309        let former_mean = (former_a + former_b) as f64 / 2.0;
17310        let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
17311        println!(
17312            "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}",
17313            spread(former_a, former_b),
17314            spread(candidate_a, candidate_b),
17315            former_mean / candidate_mean,
17316            body_started.elapsed().as_secs_f64()
17317        );
17318    }
17319
17320    #[test]
17321    fn nansem_empty_returns_null() {
17322        assert!(super::nansem(&[], 1).is_missing());
17323        assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
17324    }
17325
17326    #[test]
17327    fn nanptp_returns_max_minus_min() {
17328        let values = vec![
17329            Scalar::Float64(3.0),
17330            Scalar::Null(NullKind::NaN),
17331            Scalar::Float64(7.0),
17332            Scalar::Float64(1.0),
17333        ];
17334        assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
17335    }
17336
17337    #[test]
17338    fn nanptp_empty_returns_null() {
17339        assert!(super::nanptp(&[]).is_missing());
17340        assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
17341    }
17342
17343    #[test]
17344    fn nanptp_timedelta64_preserves_dtype_u2g0r() {
17345        // Per br-frankenpandas-u2g0r: ptp on Timedelta64 returns Timedelta64.
17346        let one_hour: i64 = 3_600 * 1_000_000_000;
17347        let values = vec![
17348            Scalar::Timedelta64(one_hour),
17349            Scalar::Timedelta64(5 * one_hour),
17350            Scalar::Timedelta64(2 * one_hour),
17351        ];
17352        assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
17353    }
17354
17355    #[test]
17356    fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
17357        // Differential vs independent max-min oracles
17358        // (br-frankenpandas-affjt). Seeded LCG, no mocks.
17359        fn next(seed: &mut u64) -> u64 {
17360            *seed = seed
17361                .wrapping_mul(3202034522624059733)
17362                .wrapping_add(4354685564936845319);
17363            *seed
17364        }
17365
17366        fn expected_numeric(values: &[Scalar]) -> Scalar {
17367            let mut lo = f64::INFINITY;
17368            let mut hi = f64::NEG_INFINITY;
17369            let mut seen = false;
17370            for value in values {
17371                if value.is_missing() {
17372                    continue;
17373                }
17374                if let Ok(value) = value.to_f64() {
17375                    seen = true;
17376                    lo = lo.min(value);
17377                    hi = hi.max(value);
17378                }
17379            }
17380            if seen {
17381                Scalar::Float64(hi - lo)
17382            } else {
17383                Scalar::Null(NullKind::NaN)
17384            }
17385        }
17386
17387        fn expected_timedelta(values: &[Scalar]) -> Scalar {
17388            let mut lo = i64::MAX;
17389            let mut hi = i64::MIN;
17390            let mut seen = false;
17391            for value in values {
17392                if let Scalar::Timedelta64(ns) = value
17393                    && !value.is_missing()
17394                {
17395                    seen = true;
17396                    lo = lo.min(*ns);
17397                    hi = hi.max(*ns);
17398                }
17399            }
17400            if seen {
17401                Scalar::Timedelta64(hi - lo)
17402            } else {
17403                Scalar::Null(NullKind::NaN)
17404            }
17405        }
17406
17407        fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
17408            let actual = super::nanptp(values);
17409            assert!(
17410                actual.semantic_eq(&expected),
17411                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
17412            );
17413        }
17414
17415        assert_ptp(
17416            usize::MAX,
17417            "numeric_all_missing",
17418            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17419            Scalar::Null(NullKind::NaN),
17420        );
17421        assert_ptp(
17422            usize::MAX - 1,
17423            "timedelta_all_missing",
17424            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
17425            Scalar::Null(NullKind::NaN),
17426        );
17427        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
17428        assert_ptp(
17429            usize::MAX - 2,
17430            "timedelta_one_ns_range_beyond_f64_exactness",
17431            &[
17432                Scalar::Timedelta64(beyond_f64_exact_ns),
17433                Scalar::Timedelta64(beyond_f64_exact_ns - 1),
17434                Scalar::Timedelta64(Timedelta::NAT),
17435            ],
17436            Scalar::Timedelta64(1),
17437        );
17438
17439        let mut seed = 0xa22f_17ed_57a7_15e5_u64;
17440        for case in 0..260 {
17441            let len = (next(&mut seed) % 83 + 1) as usize;
17442
17443            let mut numeric = Vec::with_capacity(len);
17444            numeric.push(Scalar::Int64(case as i64 - 130));
17445            for _ in 1..len {
17446                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17447                numeric.push(match next(&mut seed) % 9 {
17448                    0 => Scalar::Null(NullKind::Null),
17449                    1 => Scalar::Null(NullKind::NaN),
17450                    2 => Scalar::Float64(f64::NAN),
17451                    3 => Scalar::Bool(raw & 1 == 0),
17452                    4 => Scalar::Int64(raw),
17453                    5 => Scalar::Float64(raw as f64 / 53.0),
17454                    6 => Scalar::Float64(0.0),
17455                    7 => Scalar::Float64(-0.0),
17456                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
17457                });
17458            }
17459            assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
17460
17461            let mut timedeltas = Vec::with_capacity(len);
17462            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17463            for _ in 1..len {
17464                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17465                timedeltas.push(match next(&mut seed) % 7 {
17466                    0 => Scalar::Null(NullKind::Null),
17467                    1 => Scalar::Timedelta64(i64::MIN),
17468                    _ => Scalar::Timedelta64(raw),
17469                });
17470            }
17471            assert_ptp(
17472                case,
17473                "timedelta",
17474                &timedeltas,
17475                expected_timedelta(&timedeltas),
17476            );
17477        }
17478    }
17479
17480    #[test]
17481    fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
17482        // Per br-frankenpandas-ql1t5: argmax/argmin on Timedelta64 compare
17483        // i64 ns directly instead of silently skipping via to_f64.
17484        let one_hour: i64 = 3_600 * 1_000_000_000;
17485        let values = vec![
17486            Scalar::Timedelta64(2 * one_hour),
17487            Scalar::Timedelta64(5 * one_hour),
17488            Scalar::Timedelta64(one_hour),
17489            Scalar::Timedelta64(3 * one_hour),
17490        ];
17491        assert_eq!(super::nanargmax(&values), Some(1));
17492        assert_eq!(super::nanargmin(&values), Some(2));
17493    }
17494
17495    #[test]
17496    fn nanprod_timedelta64_returns_null_szq6a() {
17497        // Per br-frankenpandas-szq6a: pandas raises on Timedelta prod
17498        // (dimensionally undefined). We surface Null instead of the
17499        // misleading Float64(1.0) the old empty-iterator default emitted.
17500        let one_hour: i64 = 3_600 * 1_000_000_000;
17501        let values = vec![
17502            Scalar::Timedelta64(2 * one_hour),
17503            Scalar::Timedelta64(3 * one_hour),
17504        ];
17505        assert!(super::nanprod(&values).is_missing());
17506    }
17507
17508    #[test]
17509    fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
17510        // Differential vs independent product oracles
17511        // (br-frankenpandas-9938h). Seeded LCG, no mocks.
17512        fn next(seed: &mut u64) -> u64 {
17513            *seed = seed
17514                .wrapping_mul(6364136223846793005)
17515                .wrapping_add(1442695040888963407);
17516            *seed
17517        }
17518
17519        fn expected_numeric(values: &[Scalar]) -> Scalar {
17520            let mut product = 1.0_f64;
17521            for value in values {
17522                if value.is_missing() {
17523                    continue;
17524                }
17525                if let Ok(value) = value.to_f64() {
17526                    product *= value;
17527                }
17528            }
17529            Scalar::Float64(product)
17530        }
17531
17532        fn expected_timedelta(values: &[Scalar]) -> Scalar {
17533            if values
17534                .iter()
17535                .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
17536            {
17537                Scalar::Null(NullKind::NaN)
17538            } else {
17539                Scalar::Float64(1.0)
17540            }
17541        }
17542
17543        fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
17544            let actual = super::nanprod(values);
17545            assert!(
17546                actual.semantic_eq(&expected),
17547                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
17548            );
17549        }
17550
17551        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17552        assert_prod(
17553            usize::MAX,
17554            "numeric_all_missing",
17555            &all_missing,
17556            Scalar::Float64(1.0),
17557        );
17558
17559        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17560        assert_prod(
17561            usize::MAX - 1,
17562            "timedelta_all_missing",
17563            &td_all_missing,
17564            expected_timedelta(&td_all_missing),
17565        );
17566
17567        let mut seed = 0x6e0d_9938_a11c_0de5_u64;
17568        for case in 0..280 {
17569            let len = (next(&mut seed) % 89 + 1) as usize;
17570
17571            let mut numeric = Vec::with_capacity(len);
17572            numeric.push(Scalar::Int64((case % 17) as i64 - 8));
17573            for _ in 1..len {
17574                let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
17575                numeric.push(match next(&mut seed) % 9 {
17576                    0 => Scalar::Null(NullKind::Null),
17577                    1 => Scalar::Null(NullKind::NaN),
17578                    2 => Scalar::Float64(f64::NAN),
17579                    3 => Scalar::Bool(raw & 1 == 0),
17580                    4 => Scalar::Int64(raw % 19),
17581                    5 => Scalar::Float64(raw as f64 / 97.0),
17582                    6 => Scalar::Float64(0.0),
17583                    7 => Scalar::Float64(-0.0),
17584                    _ => Scalar::Float64(1.0),
17585                });
17586            }
17587            assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
17588
17589            let mut timedeltas = Vec::with_capacity(len);
17590            timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
17591            for _ in 1..len {
17592                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17593                timedeltas.push(match next(&mut seed) % 7 {
17594                    0 => Scalar::Null(NullKind::Null),
17595                    1 => Scalar::Timedelta64(i64::MIN),
17596                    _ => Scalar::Timedelta64(raw),
17597                });
17598            }
17599            assert_prod(
17600                case,
17601                "timedelta",
17602                &timedeltas,
17603                expected_timedelta(&timedeltas),
17604            );
17605        }
17606    }
17607
17608    #[test]
17609    fn nanskew_symmetric_distribution_near_zero() {
17610        let values = vec![
17611            Scalar::Float64(1.0),
17612            Scalar::Float64(2.0),
17613            Scalar::Float64(3.0),
17614            Scalar::Float64(4.0),
17615            Scalar::Float64(5.0),
17616        ];
17617        // Perfectly symmetric -> skew = 0
17618        let skew = super::nanskew(&values);
17619        assert!(matches!(skew, Scalar::Float64(_)));
17620        let Scalar::Float64(v) = skew else {
17621            return;
17622        };
17623        assert!(v.abs() < 1e-9);
17624    }
17625
17626    #[test]
17627    fn nanskew_too_few_values_returns_null() {
17628        assert!(super::nanskew(&[]).is_missing());
17629        assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
17630    }
17631
17632    #[test]
17633    fn nankurt_symmetric_uniform_distribution() {
17634        let values = vec![
17635            Scalar::Float64(1.0),
17636            Scalar::Float64(2.0),
17637            Scalar::Float64(3.0),
17638            Scalar::Float64(4.0),
17639            Scalar::Float64(5.0),
17640        ];
17641        // pandas kurt([1,2,3,4,5]) = -1.2
17642        let kurt = super::nankurt(&values);
17643        assert!(matches!(kurt, Scalar::Float64(_)));
17644        let Scalar::Float64(v) = kurt else {
17645            return;
17646        };
17647        assert!((v + 1.2).abs() < 1e-9);
17648    }
17649
17650    #[test]
17651    fn nankurt_too_few_values_returns_null() {
17652        let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
17653        assert!(super::nankurt(&vals).is_missing());
17654    }
17655
17656    #[test]
17657    fn nanskew_constant_series_returns_zero() {
17658        let values = vec![
17659            Scalar::Float64(5.0),
17660            Scalar::Float64(5.0),
17661            Scalar::Float64(5.0),
17662        ];
17663        assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
17664        assert_eq!(
17665            super::nankurt(&[
17666                Scalar::Float64(5.0),
17667                Scalar::Float64(5.0),
17668                Scalar::Float64(5.0),
17669                Scalar::Float64(5.0),
17670            ]),
17671            Scalar::Float64(0.0)
17672        );
17673    }
17674
17675    #[test]
17676    fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
17677        // Differential vs independent bias-corrected moment oracles
17678        // (br-frankenpandas-jr7zk). Seeded LCG, no mocks.
17679        fn next(seed: &mut u64) -> u64 {
17680            *seed = seed
17681                .wrapping_mul(2862933555777941757)
17682                .wrapping_add(3037000493);
17683            *seed
17684        }
17685
17686        fn samples(values: &[Scalar]) -> Vec<f64> {
17687            values
17688                .iter()
17689                .filter(|value| !value.is_missing())
17690                .filter_map(|value| value.to_f64().ok())
17691                .collect()
17692        }
17693
17694        fn expected_skew(values: &[Scalar]) -> Scalar {
17695            let samples = samples(values);
17696            let n = samples.len() as f64;
17697            if n < 3.0 {
17698                return Scalar::Null(NullKind::NaN);
17699            }
17700            let mean = samples.iter().sum::<f64>() / n;
17701            let m2 = samples
17702                .iter()
17703                .map(|value| (value - mean).powi(2))
17704                .sum::<f64>();
17705            let m3 = samples
17706                .iter()
17707                .map(|value| (value - mean).powi(3))
17708                .sum::<f64>();
17709            let s2 = m2 / (n - 1.0);
17710            if s2 == 0.0 {
17711                return Scalar::Float64(0.0);
17712            }
17713            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
17714        }
17715
17716        fn expected_kurt(values: &[Scalar]) -> Scalar {
17717            let samples = samples(values);
17718            let n = samples.len() as f64;
17719            if n < 4.0 {
17720                return Scalar::Null(NullKind::NaN);
17721            }
17722            let mean = samples.iter().sum::<f64>() / n;
17723            let m2 = samples
17724                .iter()
17725                .map(|value| (value - mean).powi(2))
17726                .sum::<f64>();
17727            let m4 = samples
17728                .iter()
17729                .map(|value| (value - mean).powi(4))
17730                .sum::<f64>();
17731            let s2 = m2 / (n - 1.0);
17732            if s2 == 0.0 {
17733                return Scalar::Float64(0.0);
17734            }
17735            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
17736            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
17737            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
17738        }
17739
17740        fn assert_moments(case: usize, values: &[Scalar]) {
17741            let expected_skew = expected_skew(values);
17742            let expected_kurt = expected_kurt(values);
17743            let actual_skew = super::nanskew(values);
17744            let actual_kurt = super::nankurt(values);
17745            assert!(
17746                actual_skew.semantic_eq(&expected_skew),
17747                "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
17748            );
17749            assert!(
17750                actual_kurt.semantic_eq(&expected_kurt),
17751                "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
17752            );
17753        }
17754
17755        assert_moments(
17756            usize::MAX,
17757            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17758        );
17759        assert_moments(
17760            usize::MAX - 1,
17761            &[
17762                Scalar::Float64(7.0),
17763                Scalar::Float64(7.0),
17764                Scalar::Float64(7.0),
17765                Scalar::Float64(7.0),
17766            ],
17767        );
17768
17769        let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
17770        for case in 0..260 {
17771            let len = (next(&mut seed) % 89 + 1) as usize;
17772            let mut values = Vec::with_capacity(len);
17773            if case % 11 == 0 {
17774                values.extend((0..len).map(|_| Scalar::Float64(3.0)));
17775            } else {
17776                values.push(Scalar::Float64(case as f64 / 19.0));
17777                for _ in 1..len {
17778                    let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17779                    values.push(match next(&mut seed) % 8 {
17780                        0 => Scalar::Null(NullKind::Null),
17781                        1 => Scalar::Null(NullKind::NaN),
17782                        2 => Scalar::Float64(f64::NAN),
17783                        3 => Scalar::Bool(raw & 1 == 0),
17784                        4 => Scalar::Int64(raw % 251),
17785                        5 => Scalar::Float64(raw as f64 / 83.0),
17786                        6 => Scalar::Float64(0.0),
17787                        _ => Scalar::Float64(-0.0),
17788                    });
17789                }
17790            }
17791            assert_moments(case, &values);
17792        }
17793    }
17794
17795    // ── Interval tests (br-frankenpandas-j8k4) ──────────────────────────
17796
17797    #[test]
17798    fn interval_default_closed_is_right() {
17799        assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
17800    }
17801
17802    #[test]
17803    fn interval_left_and_right_closed_helpers() {
17804        assert!(IntervalClosed::Left.left_closed());
17805        assert!(!IntervalClosed::Left.right_closed());
17806        assert!(!IntervalClosed::Right.left_closed());
17807        assert!(IntervalClosed::Right.right_closed());
17808        assert!(IntervalClosed::Both.left_closed());
17809        assert!(IntervalClosed::Both.right_closed());
17810        assert!(!IntervalClosed::Neither.left_closed());
17811        assert!(!IntervalClosed::Neither.right_closed());
17812    }
17813
17814    #[test]
17815    fn interval_display_matches_pandas_notation() {
17816        assert_eq!(
17817            Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
17818            "(0.0, 5.0]"
17819        );
17820        assert_eq!(
17821            Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
17822            "[0.0, 5.0)"
17823        );
17824        assert_eq!(
17825            Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
17826            "[0.0, 5.0]"
17827        );
17828        assert_eq!(
17829            Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
17830            "(0.0, 5.0)"
17831        );
17832        assert_eq!(
17833            Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
17834            "(2.5, 3.5]"
17835        );
17836        assert_eq!(
17837            Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
17838            "(-1.0, 0.0]"
17839        );
17840        assert_eq!(
17841            Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
17842            "(1e+20, 2e+20]"
17843        );
17844    }
17845
17846    #[test]
17847    fn interval_length_and_mid() {
17848        let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
17849        assert_eq!(i.length(), 8.0);
17850        assert_eq!(i.mid(), 6.0);
17851    }
17852
17853    #[test]
17854    fn interval_contains_matches_closed_policy() {
17855        let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
17856        assert!(!right.contains(0.0));
17857        assert!(right.contains(2.5));
17858        assert!(right.contains(5.0));
17859
17860        let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
17861        assert!(left.contains(0.0));
17862        assert!(left.contains(2.5));
17863        assert!(!left.contains(5.0));
17864
17865        let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
17866        assert!(both.contains(0.0));
17867        assert!(both.contains(5.0));
17868
17869        let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
17870        assert!(!neither.contains(0.0));
17871        assert!(!neither.contains(5.0));
17872        assert!(neither.contains(2.5));
17873    }
17874
17875    #[test]
17876    fn interval_contains_nan_returns_false() {
17877        let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
17878        assert!(!i.contains(f64::NAN));
17879    }
17880
17881    #[test]
17882    fn interval_is_empty_matches_pandas() {
17883        // pd.Interval(3, 3, 'right').is_empty → True
17884        assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
17885        assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
17886        assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
17887        // pd.Interval(3, 3, 'both').is_empty → False (single point)
17888        assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
17889        // Non-degenerate intervals are never empty.
17890        assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
17891    }
17892
17893    #[test]
17894    fn interval_overlaps_disjoint_returns_false() {
17895        let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
17896        let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
17897        assert!(!a.overlaps(&b));
17898        assert!(!b.overlaps(&a));
17899    }
17900
17901    #[test]
17902    fn interval_overlaps_nested_returns_true() {
17903        let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
17904        let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
17905        assert!(outer.overlaps(&inner));
17906        assert!(inner.overlaps(&outer));
17907    }
17908
17909    #[test]
17910    fn interval_overlaps_touching_respects_closed_policy() {
17911        // (0, 1] touching (1, 2] at point 1.
17912        let right_right = (
17913            Interval::new(0.0, 1.0, IntervalClosed::Right),
17914            Interval::new(1.0, 2.0, IntervalClosed::Right),
17915        );
17916        // right_right.0 is closed at 1; right_right.1 is open at 1 → no overlap.
17917        assert!(!right_right.0.overlaps(&right_right.1));
17918
17919        // [0, 1] touching [1, 2] — both closed at 1 → overlap.
17920        let both_both = (
17921            Interval::new(0.0, 1.0, IntervalClosed::Both),
17922            Interval::new(1.0, 2.0, IntervalClosed::Both),
17923        );
17924        assert!(both_both.0.overlaps(&both_both.1));
17925    }
17926
17927    #[test]
17928    fn interval_roundtrips_through_serde_json() {
17929        let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
17930        let json = serde_json::to_string(&i).expect("serialize");
17931        let back: Interval = serde_json::from_str(&json).expect("deserialize");
17932        assert_eq!(i, back);
17933    }
17934
17935    #[test]
17936    fn interval_serde_default_closed_is_right_when_missing() {
17937        // JSON payloads that omit `closed` deserialize with the pandas default.
17938        let back: Interval =
17939            serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
17940        assert_eq!(back.closed, IntervalClosed::Right);
17941    }
17942
17943    // ── Period tests (br-frankenpandas-epoj) ────────────────────────────
17944
17945    #[test]
17946    fn period_freq_parses_canonical_aliases() {
17947        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
17948        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
17949        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
17950        assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
17951        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
17952        assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
17953        assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
17954        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
17955        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
17956        assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
17957        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
17958    }
17959
17960    #[test]
17961    fn period_freq_parse_is_case_insensitive() {
17962        assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::QUARTERLY));
17963        assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
17964    }
17965
17966    #[test]
17967    fn period_freq_rejects_unknown_aliases() {
17968        assert_eq!(PeriodFreq::parse("nanosec"), None);
17969        assert_eq!(PeriodFreq::parse(""), None);
17970        assert_eq!(PeriodFreq::parse("xyz"), None);
17971    }
17972
17973    #[test]
17974    fn period_freq_alias_roundtrip() {
17975        for freq in [
17976            PeriodFreq::ANNUAL,
17977            PeriodFreq::QUARTERLY,
17978            PeriodFreq::Monthly,
17979            PeriodFreq::WEEKLY,
17980            PeriodFreq::Daily,
17981            PeriodFreq::Business,
17982            PeriodFreq::Hourly,
17983            PeriodFreq::Minutely,
17984            PeriodFreq::Secondly,
17985            PeriodFreq::Milliseconds,
17986            PeriodFreq::Microseconds,
17987            PeriodFreq::Nanoseconds,
17988        ] {
17989            assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
17990        }
17991    }
17992
17993    /// Anchored aliases parse to their anchor and print back; the shifts move
17994    /// a month count / week start onto the fiscal calendar; a W-MON label
17995    /// spans Tuesday..Monday (live pandas 2.2.3: Period('2024-03-01', 'W-MON')
17996    /// is '2024-02-27/2024-03-04', ordinal 2827; br-frankenpandas-39h5n).
17997    #[test]
17998    fn anchored_period_freqs_parse_print_and_shift_39h5n() {
17999        for month in 1..=12_u8 {
18000            for freq in [PeriodFreq::Annual(month), PeriodFreq::Quarterly(month)] {
18001                assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
18002            }
18003        }
18004        for day in 0..7_u8 {
18005            assert_eq!(
18006                PeriodFreq::parse(PeriodFreq::Weekly(day).alias()),
18007                Some(PeriodFreq::Weekly(day))
18008            );
18009        }
18010        assert_eq!(PeriodFreq::parse("Y-JUN"), Some(PeriodFreq::Annual(6)));
18011        assert_eq!(PeriodFreq::parse("A-JUN"), Some(PeriodFreq::Annual(6)));
18012        assert_eq!(PeriodFreq::parse("q-jan"), Some(PeriodFreq::Quarterly(1)));
18013        assert_eq!(PeriodFreq::parse("W-MON"), Some(PeriodFreq::Weekly(0)));
18014        assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18015        // NEGATIVE: not an anchor, or not an anchorable frequency.
18016        assert_eq!(PeriodFreq::parse("Q-XYZ"), None);
18017        assert_eq!(PeriodFreq::parse("M-JAN"), None);
18018        assert_eq!(PeriodFreq::parse("W-JAN"), None);
18019        assert_eq!(PeriodFreq::Annual(6).fiscal_month_shift(), 6);
18020        assert_eq!(PeriodFreq::Quarterly(1).fiscal_month_shift(), 11);
18021        assert_eq!(PeriodFreq::QUARTERLY.fiscal_month_shift(), 0);
18022        assert_eq!(PeriodFreq::Weekly(0).week_start_shift(), 1);
18023        assert_eq!(PeriodFreq::WEEKLY.week_start_shift(), 0);
18024        assert_eq!(
18025            Period::new(2827, PeriodFreq::Weekly(0)).to_string(),
18026            "2024-02-27/2024-03-04"
18027        );
18028        assert_eq!(
18029            Period::new(2826, PeriodFreq::Weekly(5)).to_string(),
18030            "2024-02-25/2024-03-02"
18031        );
18032        assert_eq!(
18033            Period::new(220, PeriodFreq::Quarterly(1)).to_string(),
18034            "2025Q1"
18035        );
18036    }
18037
18038    /// The three sub-second frequencies pandas' `to_period` accepts and this
18039    /// crate used to reject. Transcribed from live pandas 2.2.3 on
18040    /// `Timestamp('2024-03-15 10:30:45.123456789')`.
18041    #[test]
18042    fn period_freq_subsecond_units_match_pandas() {
18043        // Aliases and resolution words.
18044        assert_eq!(PeriodFreq::Milliseconds.alias(), "ms");
18045        assert_eq!(PeriodFreq::Microseconds.alias(), "us");
18046        assert_eq!(PeriodFreq::Nanoseconds.alias(), "ns");
18047        assert_eq!(PeriodFreq::Milliseconds.resolution(), Some("millisecond"));
18048        assert_eq!(PeriodFreq::Microseconds.resolution(), Some("microsecond"));
18049        assert_eq!(PeriodFreq::Nanoseconds.resolution(), Some("nanosecond"));
18050
18051        // ⚠️ THE ONE CASE-SENSITIVE ALIAS. pandas reads bare "MS" as month start
18052        // and refuses it here, while every other casing of "ms" is milliseconds.
18053        assert_eq!(PeriodFreq::parse("ms"), Some(PeriodFreq::Milliseconds));
18054        assert_eq!(PeriodFreq::parse("Ms"), Some(PeriodFreq::Milliseconds));
18055        assert_eq!(PeriodFreq::parse("mS"), Some(PeriodFreq::Milliseconds));
18056        assert_eq!(PeriodFreq::parse("MS"), None);
18057        // us/ns are case-insensitive in pandas, so both casings resolve.
18058        assert_eq!(PeriodFreq::parse("us"), Some(PeriodFreq::Microseconds));
18059        assert_eq!(PeriodFreq::parse("US"), Some(PeriodFreq::Microseconds));
18060        assert_eq!(PeriodFreq::parse("ns"), Some(PeriodFreq::Nanoseconds));
18061        assert_eq!(PeriodFreq::parse("NS"), Some(PeriodFreq::Nanoseconds));
18062
18063        // Ordinals are unit counts since the epoch; labels pad the fraction to
18064        // the full width of the frequency and never trim trailing zeros.
18065        assert_eq!(
18066            Period::new(1_710_498_645_123, PeriodFreq::Milliseconds).calendar_string(),
18067            "2024-03-15 10:30:45.123"
18068        );
18069        assert_eq!(
18070            Period::new(1_710_498_645_123_456, PeriodFreq::Microseconds).calendar_string(),
18071            "2024-03-15 10:30:45.123456"
18072        );
18073        assert_eq!(
18074            Period::new(1_710_498_645_123_456_789, PeriodFreq::Nanoseconds).calendar_string(),
18075            "2024-03-15 10:30:45.123456789"
18076        );
18077
18078        // A whole-second instant still shows its zero fraction, and the
18079        // pre-epoch ordinals are the FLOOR, not a truncation toward zero:
18080        // Timestamp('1969-12-31 23:59:59.999') at 'ms' has ordinal -1.
18081        assert_eq!(
18082            Period::new(0, PeriodFreq::Milliseconds).calendar_string(),
18083            "1970-01-01 00:00:00.000"
18084        );
18085        assert_eq!(
18086            Period::new(-1, PeriodFreq::Milliseconds).calendar_string(),
18087            "1969-12-31 23:59:59.999"
18088        );
18089        assert_eq!(
18090            Period::new(-1_000, PeriodFreq::Microseconds).calendar_string(),
18091            "1969-12-31 23:59:59.999000"
18092        );
18093        assert_eq!(
18094            Period::new(-999_999, PeriodFreq::Nanoseconds).calendar_string(),
18095            "1969-12-31 23:59:59.999000001"
18096        );
18097    }
18098
18099    #[test]
18100    fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
18101        assert_eq!(PeriodFreq::ANNUAL.alias(), "Y-DEC");
18102        assert_eq!(PeriodFreq::QUARTERLY.alias(), "Q-DEC");
18103        assert_eq!(PeriodFreq::WEEKLY.alias(), "W-SUN");
18104
18105        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
18106        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
18107        assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::ANNUAL));
18108        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
18109        assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18110        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
18111        assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::WEEKLY));
18112    }
18113
18114    #[test]
18115    fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
18116        assert_eq!(PeriodFreq::Hourly.alias(), "h");
18117        assert_eq!(PeriodFreq::Minutely.alias(), "min");
18118        assert_eq!(PeriodFreq::Secondly.alias(), "s");
18119
18120        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
18121        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
18122        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
18123    }
18124
18125    /// The resolution table is the COMPONENT WORD, never the frequency alias.
18126    /// Transcribed from live pandas 2.2.3: `pd.PeriodIndex([ts], freq=f).resolution`
18127    /// for each f, with W and B raising AttributeError.
18128    #[test]
18129    fn period_freq_resolution_is_the_component_word_not_the_alias() {
18130        assert_eq!(PeriodFreq::ANNUAL.resolution(), Some("year"));
18131        assert_eq!(PeriodFreq::QUARTERLY.resolution(), Some("quarter"));
18132        assert_eq!(PeriodFreq::Monthly.resolution(), Some("month"));
18133        assert_eq!(PeriodFreq::Daily.resolution(), Some("day"));
18134        assert_eq!(PeriodFreq::Hourly.resolution(), Some("hour"));
18135        assert_eq!(PeriodFreq::Minutely.resolution(), Some("minute"));
18136        assert_eq!(PeriodFreq::Secondly.resolution(), Some("second"));
18137
18138        // pandas raises AttributeError for these two rather than answering.
18139        assert_eq!(PeriodFreq::WEEKLY.resolution(), None);
18140        assert_eq!(PeriodFreq::Business.resolution(), None);
18141
18142        // The bug this replaces was the alias table copied into the resolution
18143        // slot, so pin the two apart: no frequency may report the same string
18144        // for both. (Every pandas alias is short and lowercase-ish; every
18145        // resolution word is a full English noun -- they never coincide.)
18146        for freq in [
18147            PeriodFreq::ANNUAL,
18148            PeriodFreq::QUARTERLY,
18149            PeriodFreq::Monthly,
18150            PeriodFreq::WEEKLY,
18151            PeriodFreq::Daily,
18152            PeriodFreq::Business,
18153            PeriodFreq::Hourly,
18154            PeriodFreq::Minutely,
18155            PeriodFreq::Secondly,
18156        ] {
18157            assert_ne!(
18158                Some(freq.alias()),
18159                freq.resolution(),
18160                "{freq:?} reports its alias as its resolution again"
18161            );
18162        }
18163    }
18164
18165    #[test]
18166    fn period_scalar_accessors_match_pandas_star8() {
18167        let period = Period::new(600, PeriodFreq::Monthly);
18168
18169        assert_eq!(period.ordinal(), 600);
18170        assert_eq!(period.freq(), PeriodFreq::Monthly);
18171        assert_eq!(period.freqstr(), "M");
18172    }
18173
18174    #[test]
18175    fn period_parse_common_pandas_ordinals_avm08() {
18176        assert_eq!(
18177            Period::parse("2024").unwrap(),
18178            Period::new(54, PeriodFreq::ANNUAL)
18179        );
18180        assert_eq!(
18181            Period::parse("2024Q1").unwrap(),
18182            Period::new(216, PeriodFreq::QUARTERLY)
18183        );
18184        assert_eq!(
18185            Period::parse("2024-01").unwrap(),
18186            Period::new(648, PeriodFreq::Monthly)
18187        );
18188        assert_eq!(
18189            Period::parse("2024-01-15").unwrap(),
18190            Period::new(19_737, PeriodFreq::Daily)
18191        );
18192        assert!(Period::parse("216").is_err());
18193    }
18194
18195    #[test]
18196    fn period_shift_advances_ordinal() {
18197        let q1 = Period::new(216, PeriodFreq::QUARTERLY);
18198        let q2 = q1.shift(1);
18199        assert_eq!(q2.ordinal, 217);
18200        assert_eq!(q2.freq, PeriodFreq::QUARTERLY);
18201        let q0 = q1.shift(-1);
18202        assert_eq!(q0.ordinal, 215);
18203    }
18204
18205    #[test]
18206    fn period_shift_saturates_on_overflow() {
18207        let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
18208        assert_eq!(p.shift(100).ordinal, i64::MAX);
18209        let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
18210        assert_eq!(p.shift(-100).ordinal, i64::MIN);
18211    }
18212
18213    #[test]
18214    fn period_diff_returns_period_count() {
18215        let a = Period::new(216, PeriodFreq::QUARTERLY);
18216        let b = Period::new(220, PeriodFreq::QUARTERLY);
18217        assert_eq!(b.diff(&a), Some(4));
18218        assert_eq!(a.diff(&b), Some(-4));
18219    }
18220
18221    #[test]
18222    fn period_diff_rejects_mismatched_freq() {
18223        let monthly = Period::new(100, PeriodFreq::Monthly);
18224        let quarterly = Period::new(100, PeriodFreq::QUARTERLY);
18225        assert_eq!(monthly.diff(&quarterly), None);
18226        assert_eq!(quarterly.diff(&monthly), None);
18227    }
18228
18229    #[test]
18230    fn period_cmp_same_freq_respects_ordinal_order() {
18231        use std::cmp::Ordering;
18232        let a = Period::new(10, PeriodFreq::Monthly);
18233        let b = Period::new(20, PeriodFreq::Monthly);
18234        assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
18235        assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
18236        assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
18237    }
18238
18239    #[test]
18240    fn period_cmp_cross_freq_returns_none() {
18241        let m = Period::new(1, PeriodFreq::Monthly);
18242        let q = Period::new(1, PeriodFreq::QUARTERLY);
18243        assert_eq!(m.cmp_same_freq(&q), None);
18244    }
18245
18246    #[test]
18247    fn period_arithmetic_matches_seeded_oracles_bac28() {
18248        use std::cmp::Ordering;
18249
18250        fn next(seed: &mut u64) -> u64 {
18251            *seed = seed
18252                .wrapping_mul(2862933555777941757)
18253                .wrapping_add(3037000493);
18254            *seed
18255        }
18256
18257        fn freq_for(raw: u64) -> PeriodFreq {
18258            // All TWELVE frequencies. This stopped at nine, so no property
18259            // test here ever generated a sub-second period.
18260            match raw % 12 {
18261                0 => PeriodFreq::ANNUAL,
18262                1 => PeriodFreq::QUARTERLY,
18263                2 => PeriodFreq::Monthly,
18264                3 => PeriodFreq::WEEKLY,
18265                4 => PeriodFreq::Daily,
18266                5 => PeriodFreq::Business,
18267                6 => PeriodFreq::Hourly,
18268                7 => PeriodFreq::Minutely,
18269                8 => PeriodFreq::Secondly,
18270                9 => PeriodFreq::Milliseconds,
18271                10 => PeriodFreq::Microseconds,
18272                _ => PeriodFreq::Nanoseconds,
18273            }
18274        }
18275
18276        fn different_freq(freq: PeriodFreq) -> PeriodFreq {
18277            match freq {
18278                PeriodFreq::Annual(_) => PeriodFreq::QUARTERLY,
18279                PeriodFreq::Quarterly(_) => PeriodFreq::Monthly,
18280                PeriodFreq::Monthly => PeriodFreq::WEEKLY,
18281                PeriodFreq::Weekly(_) => PeriodFreq::Daily,
18282                PeriodFreq::Daily => PeriodFreq::Business,
18283                PeriodFreq::Business => PeriodFreq::Hourly,
18284                PeriodFreq::Hourly => PeriodFreq::Minutely,
18285                PeriodFreq::Minutely => PeriodFreq::Secondly,
18286                // The cycle closes through the sub-second units, so every
18287                // frequency still maps to a DIFFERENT one — the only property
18288                // this helper owes its callers.
18289                PeriodFreq::Secondly => PeriodFreq::Milliseconds,
18290                PeriodFreq::Milliseconds => PeriodFreq::Microseconds,
18291                PeriodFreq::Microseconds => PeriodFreq::Nanoseconds,
18292                PeriodFreq::Nanoseconds => PeriodFreq::ANNUAL,
18293            }
18294        }
18295
18296        fn assert_period_case(
18297            case: usize,
18298            freq: PeriodFreq,
18299            ordinal: i64,
18300            shift_by: i64,
18301            other_ordinal: i64,
18302        ) {
18303            let period = Period::new(ordinal, freq);
18304            let shifted = period.shift(shift_by);
18305            assert_eq!(
18306                shifted.ordinal,
18307                ordinal.saturating_add(shift_by),
18308                "case {case}: shift ordinal"
18309            );
18310            assert_eq!(shifted.freq, freq, "case {case}: shift freq");
18311
18312            let same_freq_other = Period::new(other_ordinal, freq);
18313            assert_eq!(
18314                period.diff(&same_freq_other),
18315                Some(ordinal.saturating_sub(other_ordinal)),
18316                "case {case}: same-freq diff"
18317            );
18318            assert_eq!(
18319                period.cmp_same_freq(&same_freq_other),
18320                Some(ordinal.cmp(&other_ordinal)),
18321                "case {case}: same-freq cmp"
18322            );
18323
18324            let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
18325            assert_eq!(
18326                period.diff(&cross_freq_other),
18327                None,
18328                "case {case}: cross-freq diff"
18329            );
18330            assert_eq!(
18331                period.cmp_same_freq(&cross_freq_other),
18332                None,
18333                "case {case}: cross-freq cmp"
18334            );
18335        }
18336
18337        assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
18338        assert_period_case(
18339            usize::MAX - 1,
18340            PeriodFreq::Daily,
18341            i64::MIN + 2,
18342            -10,
18343            i64::MAX,
18344        );
18345        assert_eq!(
18346            Period::new(10, PeriodFreq::Monthly)
18347                .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
18348            Some(Ordering::Equal)
18349        );
18350
18351        let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
18352        for case in 0..260 {
18353            let freq = freq_for(next(&mut seed));
18354            let ordinal = match case % 53 {
18355                0 => i64::MAX - (next(&mut seed) % 8) as i64,
18356                1 => i64::MIN + (next(&mut seed) % 8) as i64,
18357                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
18358            };
18359            let shift_by = match case % 47 {
18360                0 => 512,
18361                1 => -512,
18362                _ => (next(&mut seed) % 4097) as i64 - 2048,
18363            };
18364            let other_ordinal = match case % 41 {
18365                0 => i64::MAX,
18366                1 => i64::MIN,
18367                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
18368            };
18369            assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
18370        }
18371    }
18372
18373    #[test]
18374    fn period_display_is_pandas_calendar_string() {
18375        // Ordinal 216 on the quarterly axis (1970Q1 == 0) is 1970 + 54y = 2024Q1.
18376        assert_eq!(
18377            Period::new(216, PeriodFreq::QUARTERLY).to_string(),
18378            "2024Q1"
18379        );
18380        // 1970 + 54 == 2024 on the annual axis.
18381        assert_eq!(Period::new(54, PeriodFreq::ANNUAL).to_string(), "2024");
18382        // 1970-01 == 0 -> 2024-03 is 54*12 + 2 == 650 months.
18383        assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
18384        // Day 0 == 1970-01-01; 2024-01-15.
18385        assert_eq!(
18386            Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
18387            "2024-01-15"
18388        );
18389        assert_eq!(
18390            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
18391            "NaT"
18392        );
18393    }
18394
18395    /// The two frequencies whose ordinal is NOT a day count. Both rendered
18396    /// through `civil_from_days` and came out decades wrong; the test above
18397    /// covered Y/Q/M/D and never touched either, which is how it survived.
18398    ///
18399    /// Every string is `str(pd.Period(ordinal=..., freq=...))` on live pandas
18400    /// 2.2.3, and FrankenPandas' own ordinals were confirmed to agree with
18401    /// pandas' at each sampled date before these were taken.
18402    #[test]
18403    fn weekly_and_business_periods_do_not_index_days() {
18404        // ⚠️ WEEKLY IS A RANGE, not a date: the ordinal counts WEEKS from the
18405        // Monday 1969-12-22, and pandas prints the seven days it spans.
18406        // Ordinal 2829 is the week of 2024-03-15 and used to render
18407        // "1977-09-30" — the result of reading a week count as a day count.
18408        for (ordinal, want) in [
18409            (0_i64, "1969-12-22/1969-12-28"),
18410            (1, "1969-12-29/1970-01-04"),
18411            (2829, "2024-03-11/2024-03-17"),
18412            (1540, "1999-06-28/1999-07-04"),
18413            (15237, "2261-12-30/2262-01-05"),
18414            // Pre-epoch, where Euclidean division matters.
18415            (-1, "1969-12-15/1969-12-21"),
18416            (-2829, "1915-10-04/1915-10-10"),
18417        ] {
18418            assert_eq!(
18419                Period::new(ordinal, PeriodFreq::WEEKLY).to_string(),
18420                want,
18421                "weekly ordinal {ordinal}"
18422            );
18423        }
18424
18425        // ⚠️ BUSINESS COUNTS BUSINESS DAYS — five per week — so consecutive
18426        // ordinals skip the weekend. Ordinal 14141 is 2024-03-15 and used to
18427        // render "2008-09-19".
18428        for (ordinal, want) in [
18429            (0_i64, "1970-01-01"), // a Thursday: the epoch anchors the cycle
18430            (1, "1970-01-02"),     // Friday
18431            (2, "1970-01-05"),     // Monday — the weekend is SKIPPED
18432            (3, "1970-01-06"),
18433            (4, "1970-01-07"),
18434            (5, "1970-01-08"),
18435            (14141, "2024-03-15"),
18436            (76179, "2262-01-01"),
18437            // A Sunday input rolls FORWARD when the ordinal is taken, so 7697
18438            // is the Monday 1999-07-05 rather than 1999-07-04.
18439            (7697, "1999-07-05"),
18440            (-1, "1969-12-31"),
18441            (-5, "1969-12-25"),
18442            (-6, "1969-12-24"),
18443        ] {
18444            assert_eq!(
18445                Period::new(ordinal, PeriodFreq::Business).to_string(),
18446                want,
18447                "business ordinal {ordinal}"
18448            );
18449        }
18450
18451        // Five business ordinals per seven calendar days, checked as a property
18452        // rather than as a table: the same arithmetic the forward map in
18453        // fp-index uses, read backwards.
18454        for ordinal in -400_i64..400 {
18455            let rendered = Period::new(ordinal, PeriodFreq::Business).to_string();
18456            let later = Period::new(ordinal + 5, PeriodFreq::Business).to_string();
18457            assert_ne!(rendered, later, "business ordinals must not repeat");
18458        }
18459
18460        assert_eq!(Period::new(i64::MIN, PeriodFreq::WEEKLY).to_string(), "NaT");
18461        assert_eq!(
18462            Period::new(i64::MIN, PeriodFreq::Business).to_string(),
18463            "NaT"
18464        );
18465    }
18466
18467    fn period_display_former_profile(period: &Period) -> String {
18468        let calendar = period.calendar_string();
18469        let mut rendered = String::new();
18470        rendered.push_str(&calendar);
18471        rendered
18472    }
18473
18474    fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
18475        use std::{hint::black_box, time::Instant};
18476
18477        let started = Instant::now();
18478        let mut checksum = 0usize;
18479        for period in periods {
18480            let rendered = render(black_box(period));
18481            checksum = checksum.wrapping_add(rendered.len());
18482            drop(black_box(rendered));
18483        }
18484        black_box(checksum);
18485        started.elapsed().as_nanos()
18486    }
18487
18488    #[test]
18489    #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
18490    fn profile_period_display_direct_sink_ab_6pqra() {
18491        const FREQUENCIES: [PeriodFreq; 9] = [
18492            PeriodFreq::ANNUAL,
18493            PeriodFreq::QUARTERLY,
18494            PeriodFreq::Monthly,
18495            PeriodFreq::WEEKLY,
18496            PeriodFreq::Daily,
18497            PeriodFreq::Business,
18498            PeriodFreq::Hourly,
18499            PeriodFreq::Minutely,
18500            PeriodFreq::Secondly,
18501        ];
18502        const SAMPLES: usize = 10;
18503
18504        let periods = (0..65_536)
18505            .map(|index| {
18506                let ordinal = if index % 4093 == 0 {
18507                    i64::MIN
18508                } else {
18509                    ((index as i64 * 7_919) % 4_000_001) - 2_000_000
18510                };
18511                Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
18512            })
18513            .collect::<Vec<_>>();
18514
18515        for period in &periods {
18516            assert_eq!(period_display_former_profile(period), period.to_string());
18517        }
18518
18519        for _ in 0..2 {
18520            measure_period_renderer(&periods, period_display_former_profile);
18521            measure_period_renderer(&periods, Period::to_string);
18522        }
18523
18524        let mut former_ns = Vec::with_capacity(SAMPLES);
18525        let mut public_ns = Vec::with_capacity(SAMPLES);
18526        for sample in 0..SAMPLES {
18527            if sample % 2 == 0 {
18528                former_ns.push(measure_period_renderer(
18529                    &periods,
18530                    period_display_former_profile,
18531                ));
18532                public_ns.push(measure_period_renderer(&periods, Period::to_string));
18533            } else {
18534                public_ns.push(measure_period_renderer(&periods, Period::to_string));
18535                former_ns.push(measure_period_renderer(
18536                    &periods,
18537                    period_display_former_profile,
18538                ));
18539            }
18540        }
18541        former_ns.sort_unstable();
18542        public_ns.sort_unstable();
18543        let former_p50 = former_ns[SAMPLES / 2];
18544        let public_p50 = public_ns[SAMPLES / 2];
18545        let former_p95 = former_ns[SAMPLES - 1];
18546        let public_p95 = public_ns[SAMPLES - 1];
18547        println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
18548        println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
18549        println!(
18550            "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
18551            former_p50 as f64 / public_p50 as f64
18552        );
18553        println!(
18554            "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
18555            former_p95 as f64 / public_p95 as f64
18556        );
18557    }
18558
18559    #[cfg(test)]
18560    fn fp_days(ymd: &str) -> i64 {
18561        Period::parse(ymd).expect("daily period").ordinal
18562    }
18563
18564    #[test]
18565    fn period_roundtrips_through_serde_json() {
18566        let p = Period::new(42, PeriodFreq::WEEKLY);
18567        let json = serde_json::to_string(&p).expect("serialize");
18568        let back: Period = serde_json::from_str(&json).expect("deserialize");
18569        assert_eq!(p, back);
18570    }
18571
18572    // ── period_range tests (br-frankenpandas-2jef — epoj Phase 2) ───────
18573
18574    use super::period_range;
18575
18576    #[test]
18577    fn period_range_zero_periods_is_empty() {
18578        let start = Period::new(216, PeriodFreq::QUARTERLY);
18579        assert!(period_range(start, 0).is_empty());
18580    }
18581
18582    #[test]
18583    fn period_range_single_period_returns_start_only() {
18584        let start = Period::new(216, PeriodFreq::QUARTERLY);
18585        let r = period_range(start, 1);
18586        assert_eq!(r.len(), 1);
18587        assert_eq!(r[0], start);
18588    }
18589
18590    #[test]
18591    fn period_range_increments_ordinal_by_one_per_step() {
18592        let start = Period::new(216, PeriodFreq::QUARTERLY);
18593        let r = period_range(start, 4);
18594        assert_eq!(r.len(), 4);
18595        assert_eq!(r[0].ordinal, 216);
18596        assert_eq!(r[1].ordinal, 217);
18597        assert_eq!(r[2].ordinal, 218);
18598        assert_eq!(r[3].ordinal, 219);
18599    }
18600
18601    #[test]
18602    fn period_range_preserves_frequency() {
18603        let start = Period::new(0, PeriodFreq::Monthly);
18604        let r = period_range(start, 12);
18605        assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
18606    }
18607
18608    #[test]
18609    fn period_range_negative_starting_ordinal_works() {
18610        // Ordinal axis is signed — pre-epoch periods are valid.
18611        let start = Period::new(-3, PeriodFreq::ANNUAL);
18612        let r = period_range(start, 5);
18613        assert_eq!(
18614            r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
18615            vec![-3, -2, -1, 0, 1]
18616        );
18617    }
18618
18619    #[test]
18620    fn period_range_large_n_does_not_panic() {
18621        // 1024 monthly periods — large enough to catch any allocation bug.
18622        let start = Period::new(0, PeriodFreq::Monthly);
18623        let r = period_range(start, 1024);
18624        assert_eq!(r.len(), 1024);
18625        assert_eq!(r[1023].ordinal, 1023);
18626    }
18627
18628    #[test]
18629    fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
18630        fn next(seed: &mut u64) -> u64 {
18631            *seed = seed
18632                .wrapping_mul(6364136223846793005)
18633                .wrapping_add(1442695040888963407);
18634            *seed
18635        }
18636
18637        fn freq_for(raw: u64) -> PeriodFreq {
18638            // All TWELVE frequencies. This stopped at nine, so no property
18639            // test here ever generated a sub-second period.
18640            match raw % 12 {
18641                0 => PeriodFreq::ANNUAL,
18642                1 => PeriodFreq::QUARTERLY,
18643                2 => PeriodFreq::Monthly,
18644                3 => PeriodFreq::WEEKLY,
18645                4 => PeriodFreq::Daily,
18646                5 => PeriodFreq::Business,
18647                6 => PeriodFreq::Hourly,
18648                7 => PeriodFreq::Minutely,
18649                8 => PeriodFreq::Secondly,
18650                9 => PeriodFreq::Milliseconds,
18651                10 => PeriodFreq::Microseconds,
18652                _ => PeriodFreq::Nanoseconds,
18653            }
18654        }
18655
18656        fn assert_oracle_case(case: usize, start: Period, periods: usize) {
18657            let got = period_range(start, periods);
18658            assert_eq!(got.len(), periods, "case {case}: length");
18659
18660            for (position, period) in got.iter().enumerate() {
18661                let expected_ordinal = start.ordinal.saturating_add(position as i64);
18662                assert_eq!(
18663                    period.ordinal, expected_ordinal,
18664                    "case {case}: ordinal at {position}"
18665                );
18666                assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
18667            }
18668        }
18669
18670        assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
18671        assert_oracle_case(
18672            usize::MAX - 1,
18673            Period::new(i64::MAX - 3, PeriodFreq::Daily),
18674            8,
18675        );
18676
18677        let mut seed = 0x9e21_0d1c_5eed_0421_u64;
18678        for case in 0..260 {
18679            let freq = freq_for(next(&mut seed));
18680            let periods = (next(&mut seed) % 80) as usize;
18681            let start_ordinal = if case % 37 == 0 {
18682                i64::MAX - 7
18683            } else {
18684                (next(&mut seed) % 20_001) as i64 - 10_000
18685            };
18686            assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
18687        }
18688    }
18689
18690    // ── interval_range tests (br-frankenpandas-xaom) ────────────────────
18691
18692    use super::{TypeError, interval_range, interval_range_by_periods, interval_range_by_step};
18693
18694    #[test]
18695    fn interval_range_by_periods_matches_pandas_default_case() {
18696        // pd.interval_range(0, 10, periods=5) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
18697        let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
18698        assert_eq!(bins.len(), 5);
18699        for (i, bin) in bins.iter().enumerate() {
18700            assert_eq!(bin.left, (i as f64) * 2.0);
18701            assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
18702            assert_eq!(bin.closed, IntervalClosed::Right);
18703        }
18704    }
18705
18706    #[test]
18707    fn interval_range_by_periods_final_edge_is_exact_end() {
18708        // Guards against accumulated float drift on the last right edge.
18709        let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
18710        assert_eq!(bins.last().unwrap().right, 1.0);
18711    }
18712
18713    #[test]
18714    fn interval_range_by_periods_zero_periods_is_empty() {
18715        assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
18716    }
18717
18718    #[test]
18719    fn interval_range_by_periods_reversed_range_is_empty() {
18720        // pandas: pd.interval_range(10, 0, periods=5) → IntervalIndex([]).
18721        assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
18722    }
18723
18724    #[test]
18725    fn interval_range_by_periods_preserves_closed_policy() {
18726        for closed in [
18727            IntervalClosed::Left,
18728            IntervalClosed::Right,
18729            IntervalClosed::Both,
18730            IntervalClosed::Neither,
18731        ] {
18732            let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
18733            assert!(bins.iter().all(|b| b.closed == closed));
18734        }
18735    }
18736
18737    #[test]
18738    fn interval_range_by_step_matches_pandas_default_case() {
18739        // pd.interval_range(0, 10, freq=2) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
18740        let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
18741        assert_eq!(bins.len(), 5);
18742        assert_eq!(bins[0].left, 0.0);
18743        assert_eq!(bins[4].right, 10.0);
18744    }
18745
18746    #[test]
18747    fn interval_range_by_step_rejects_non_positive_step() {
18748        assert!(matches!(
18749            interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
18750            Err(TypeError::InvalidIntervalStep { .. })
18751        ));
18752        assert!(matches!(
18753            interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
18754            Err(TypeError::InvalidIntervalStep { .. })
18755        ));
18756        assert!(matches!(
18757            interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
18758            Err(TypeError::InvalidIntervalStep { .. })
18759        ));
18760        assert!(matches!(
18761            interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
18762            Err(TypeError::InvalidIntervalStep { .. })
18763        ));
18764    }
18765
18766    #[test]
18767    fn interval_range_by_step_rejects_non_dividing_step() {
18768        // pandas: pd.interval_range(0, 10, freq=3) → ValueError
18769        // (span=10 not divisible by step=3). Reject with IntervalStepDoesNotDivide.
18770        assert!(matches!(
18771            interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
18772            Err(TypeError::IntervalStepDoesNotDivide { .. })
18773        ));
18774    }
18775
18776    #[test]
18777    fn interval_range_by_step_reversed_range_is_empty() {
18778        let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
18779        assert!(bins.is_empty());
18780    }
18781
18782    #[test]
18783    fn interval_range_by_step_degenerate_zero_span_is_empty() {
18784        let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
18785        assert!(bins.is_empty());
18786    }
18787
18788    #[test]
18789    fn interval_range_by_step_accepts_float_step_within_tolerance() {
18790        // step=0.1 ten times == 1.0 but float arithmetic produces 0.9999...
18791        let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
18792        assert_eq!(bins.len(), 10);
18793        assert_eq!(bins.last().unwrap().right, 1.0);
18794    }
18795
18796    #[test]
18797    fn interval_range_unified_api_tests() {
18798        // Case 1: start, end, periods
18799        let r1 = interval_range(Some(0.0), Some(10.0), Some(5), None, None).expect("ok");
18800        assert_eq!(r1.len(), 5);
18801        assert_eq!(r1[0].left, 0.0);
18802        assert_eq!(r1[0].right, 2.0);
18803        assert_eq!(r1[4].right, 10.0);
18804        assert_eq!(r1[0].closed, IntervalClosed::Right);
18805
18806        // Case 2: start, end, freq
18807        let r2 = interval_range(Some(0.0), Some(10.0), None, Some(2.0), None).expect("ok");
18808        assert_eq!(r2.len(), 5);
18809        assert_eq!(r2[0].left, 0.0);
18810        assert_eq!(r2[4].right, 10.0);
18811
18812        // Case 3: start, periods, freq
18813        let r3 = interval_range(
18814            Some(0.0),
18815            None,
18816            Some(5),
18817            Some(2.0),
18818            Some(IntervalClosed::Both),
18819        )
18820        .expect("ok");
18821        assert_eq!(r3.len(), 5);
18822        assert_eq!(r3[0].left, 0.0);
18823        assert_eq!(r3[4].right, 10.0);
18824        assert_eq!(r3[0].closed, IntervalClosed::Both);
18825
18826        // Case 4: end, periods, freq
18827        let r4 = interval_range(
18828            None,
18829            Some(10.0),
18830            Some(5),
18831            Some(2.0),
18832            Some(IntervalClosed::Left),
18833        )
18834        .expect("ok");
18835        assert_eq!(r4.len(), 5);
18836        assert_eq!(r4[0].left, 0.0);
18837        assert_eq!(r4[4].right, 10.0);
18838        assert_eq!(r4[0].closed, IntervalClosed::Left);
18839
18840        // Errors: not exactly 3 arguments
18841        assert!(matches!(
18842            interval_range(None, None, None, None, None),
18843            Err(TypeError::IntervalRangeParameterCount)
18844        ));
18845        assert!(matches!(
18846            interval_range(Some(0.0), Some(10.0), None, None, None),
18847            Err(TypeError::IntervalRangeParameterCount)
18848        ));
18849        assert!(matches!(
18850            interval_range(Some(0.0), Some(10.0), Some(5), Some(2.0), None),
18851            Err(TypeError::IntervalRangeParameterCount)
18852        ));
18853
18854        // Errors: non-positive freq
18855        assert!(matches!(
18856            interval_range(Some(0.0), None, Some(5), Some(-1.0), None),
18857            Err(TypeError::InvalidIntervalStep { .. })
18858        ));
18859        assert!(matches!(
18860            interval_range(Some(0.0), None, Some(5), Some(0.0), None),
18861            Err(TypeError::InvalidIntervalStep { .. })
18862        ));
18863    }
18864
18865    #[test]
18866    fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
18867        // Differential vs independent interval edge oracles
18868        // (br-frankenpandas-t9ozf). Seeded LCG, no mocks.
18869        fn next(seed: &mut u64) -> u64 {
18870            *seed = seed
18871                .wrapping_mul(2862933555777941757)
18872                .wrapping_add(3037000493);
18873            *seed
18874        }
18875
18876        fn closed_for(raw: u64) -> IntervalClosed {
18877            match raw % 4 {
18878                0 => IntervalClosed::Left,
18879                1 => IntervalClosed::Right,
18880                2 => IntervalClosed::Both,
18881                _ => IntervalClosed::Neither,
18882            }
18883        }
18884
18885        fn assert_interval(
18886            case: usize,
18887            kind: &str,
18888            pos: usize,
18889            actual: &Interval,
18890            expected: &Interval,
18891        ) {
18892            assert!(
18893                (actual.left - expected.left).abs() < 1e-12,
18894                "case={case} kind={kind} pos={pos}: expected left {}, got {}",
18895                expected.left,
18896                actual.left
18897            );
18898            assert!(
18899                (actual.right - expected.right).abs() < 1e-12,
18900                "case={case} kind={kind} pos={pos}: expected right {}, got {}",
18901                expected.right,
18902                actual.right
18903            );
18904            assert_eq!(
18905                actual.closed, expected.closed,
18906                "case={case} kind={kind} pos={pos}: closed mismatch"
18907            );
18908        }
18909
18910        fn expected_by_periods(
18911            start: f64,
18912            end: f64,
18913            periods: usize,
18914            closed: IntervalClosed,
18915        ) -> Vec<Interval> {
18916            if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
18917                return Vec::new();
18918            }
18919            let step = (end - start) / periods as f64;
18920            (0..periods)
18921                .map(|pos| {
18922                    let left = start + step * pos as f64;
18923                    let right = if pos + 1 == periods {
18924                        end
18925                    } else {
18926                        start + step * (pos + 1) as f64
18927                    };
18928                    Interval::new(left, right, closed)
18929                })
18930                .collect()
18931        }
18932
18933        fn expected_by_step(
18934            start: f64,
18935            end: f64,
18936            step: f64,
18937            closed: IntervalClosed,
18938        ) -> Vec<Interval> {
18939            if start >= end {
18940                return Vec::new();
18941            }
18942            let count = ((end - start) / step).round() as usize;
18943            (0..count)
18944                .map(|pos| {
18945                    let left = start + step * pos as f64;
18946                    let right = if pos + 1 == count {
18947                        end
18948                    } else {
18949                        start + step * (pos + 1) as f64
18950                    };
18951                    Interval::new(left, right, closed)
18952                })
18953                .collect()
18954        }
18955
18956        assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
18957        assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
18958        assert!(
18959            interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
18960                .expect("zero span")
18961                .is_empty()
18962        );
18963
18964        let mut seed = 0x171e_7a11_c0de_5eed_u64;
18965        for case in 0..220 {
18966            let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
18967            let periods = (next(&mut seed) % 24 + 1) as usize;
18968            let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
18969            let end = start + width;
18970            let closed = closed_for(next(&mut seed));
18971
18972            let actual = interval_range_by_periods(start, end, periods, closed);
18973            let expected = expected_by_periods(start, end, periods, closed);
18974            assert_eq!(
18975                actual.len(),
18976                expected.len(),
18977                "case={case} periods: length mismatch"
18978            );
18979            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18980                assert_interval(case, "periods", pos, actual, expected);
18981            }
18982
18983            let step_count = (next(&mut seed) % 20 + 1) as usize;
18984            let step = (next(&mut seed) % 25 + 1) as f64;
18985            let step_end = start + step * step_count as f64;
18986            let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
18987            let expected = expected_by_step(start, step_end, step, closed);
18988            assert_eq!(
18989                actual.len(),
18990                expected.len(),
18991                "case={case} step: length mismatch"
18992            );
18993            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18994                assert_interval(case, "step", pos, actual, expected);
18995            }
18996        }
18997    }
18998
18999    // ── Timedelta arithmetic tests (br-frankenpandas-4r56 Phase 1) ──────
19000
19001    use super::Timedelta;
19002
19003    #[test]
19004    fn timedelta_add_sums_non_nat() {
19005        let one_hour = Timedelta::NANOS_PER_HOUR;
19006        let one_day = Timedelta::NANOS_PER_DAY;
19007        assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
19008    }
19009
19010    #[test]
19011    fn timedelta_add_propagates_nat() {
19012        assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
19013        assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
19014        assert_eq!(
19015            Timedelta::add(Timedelta::NAT, Timedelta::NAT),
19016            Timedelta::NAT
19017        );
19018    }
19019
19020    #[test]
19021    fn timedelta_add_returns_nat_on_overflow() {
19022        // CORRECTED br-frankenpandas-lgyy8. This test previously asserted
19023        // `add(i64::MAX - 10, 100) == i64::MAX`, i.e. that positive overflow
19024        // yields a finite, plausible duration. Live pandas 2.2.3 raises
19025        // OverflowError for `pd.Timedelta.max + pd.Timedelta('1ns')` and never
19026        // returns a fabricated finite value, so the old expectation encoded a
19027        // fail-open bug. Overflow is now NaT in BOTH directions.
19028        assert_eq!(Timedelta::add(i64::MAX - 10, 100), Timedelta::NAT);
19029        // Negative side is unchanged: i64::MIN IS the NaT sentinel, so this
19030        // already surfaced as missing (pandas: Timedelta.min + -1ns -> NaT).
19031        assert_eq!(Timedelta::add(i64::MIN + 10, -100), Timedelta::NAT);
19032    }
19033
19034    #[test]
19035    fn timedelta_sub_subtracts_non_nat() {
19036        let one_hour = Timedelta::NANOS_PER_HOUR;
19037        assert_eq!(
19038            Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
19039            one_hour - Timedelta::NANOS_PER_MIN
19040        );
19041    }
19042
19043    #[test]
19044    fn timedelta_sub_propagates_nat() {
19045        assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
19046        assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
19047    }
19048
19049    #[test]
19050    fn timedelta_neg_flips_sign_non_nat() {
19051        assert_eq!(Timedelta::neg(5), -5);
19052        assert_eq!(Timedelta::neg(-5), 5);
19053        assert_eq!(Timedelta::neg(0), 0);
19054    }
19055
19056    #[test]
19057    fn timedelta_neg_preserves_nat() {
19058        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
19059    }
19060
19061    #[test]
19062    fn timedelta_abs_returns_magnitude() {
19063        assert_eq!(Timedelta::abs(-5), 5);
19064        assert_eq!(Timedelta::abs(5), 5);
19065        assert_eq!(Timedelta::abs(0), 0);
19066        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
19067    }
19068
19069    #[test]
19070    fn neg_and_abs_at_the_representable_floor_are_not_overflow_fyr1z() {
19071        // br-frankenpandas-fyr1z. Until this test existed, `neg`/`abs` were
19072        // only exercised at ±5 and 0, and the doc comment on `neg` asserted
19073        // the OPPOSITE of pandas: "pandas: `-pd.Timedelta.min` is NaT since
19074        // min == -max - 1 cannot be negated". Both halves are false, so an
19075        // implementer trusting the comment could have replaced
19076        // `saturating_neg()` with a NaT arm and broken parity without failing
19077        // a single existing assertion. Measured against the installed oracle,
19078        // pandas 2.2.3:
19079        //   pd.Timedelta.min.value                 == -9223372036854775807
19080        //   -pd.Timedelta.min                      -> Timedelta.max (NOT NaT)
19081        //   abs(pd.Timedelta.min)                  -> Timedelta.max (NOT NaT)
19082        //   -Series([Timedelta.min])               -> [Timedelta.max]
19083        //   Series([Timedelta.min]).abs()          -> [Timedelta.max]
19084        //
19085        // The reason there is no overflow to handle: pandas' representable
19086        // range is symmetric about zero because i64::MIN is spent on the NaT
19087        // sentinel, exactly as it is here.
19088        const MAX: i64 = i64::MAX;
19089        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
19090
19091        // The range really is symmetric — this is the premise the old comment
19092        // denied, and everything below follows from it.
19093        assert_eq!(MIN_OK, -MAX);
19094        assert_eq!(Timedelta::NAT, i64::MIN);
19095
19096        // The cases the false comment would have turned into NaT.
19097        assert_eq!(Timedelta::neg(MIN_OK), MAX);
19098        assert_eq!(Timedelta::neg(MAX), MIN_OK);
19099        assert_eq!(Timedelta::abs(MIN_OK), MAX);
19100        assert_eq!(Timedelta::abs(MAX), MAX);
19101
19102        // Round-tripping the floor must be exact, not sticky at a saturation
19103        // clamp: a `saturating_*` impl that ever clamped would land on
19104        // i64::MIN here and read as NaT.
19105        assert_eq!(Timedelta::neg(Timedelta::neg(MIN_OK)), MIN_OK);
19106        assert_ne!(Timedelta::neg(MIN_OK), Timedelta::NAT);
19107        assert_ne!(Timedelta::abs(MIN_OK), Timedelta::NAT);
19108
19109        // NaT itself is still the one input that stays NaT — the guard, not a
19110        // saturation branch, is what handles it.
19111        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
19112        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
19113    }
19114
19115    #[test]
19116    fn overflow_divergence_surface_is_only_where_pandas_refuses_fyr1z() {
19117        // br-frankenpandas-fyr1z, the decision bead for DISC-018. The bead was
19118        // filed on the premise "pandas raises; FP returns NaT", which would
19119        // make EVERY overflow a divergence. Probing live pandas 2.2.3 refutes
19120        // that: on the vectorized surface — the one users actually meet —
19121        // pandas returns NaT itself in several of these cases, so FP already
19122        // agrees there and a blanket "STRICT raises" mode would INTRODUCE
19123        // divergence rather than remove it.
19124        //
19125        // This test pins the agreement half. It is the negative control for
19126        // the divergence half already pinned by
19127        // `arithmetic_overflow_never_fabricates_a_finite_value_lgyy8`.
19128        const MAX: i64 = i64::MAX;
19129        const MIN_OK: i64 = i64::MIN + 1;
19130
19131        // ── AGREEMENT: pandas returns NaT here too, measured ───────────────
19132        // Series([Timedelta.max]) / 0    -> [NaT]
19133        // Series([Timedelta.max]) // 0   -> [NaT]
19134        // Series([Timedelta.max]) / 0.0  -> [NaT]
19135        assert_eq!(Timedelta::div_scalar(MAX, 0), Timedelta::NAT);
19136        assert_eq!(Timedelta::div_scalar(MIN_OK, 0), Timedelta::NAT);
19137        assert_eq!(Timedelta::div_scalar(0, 0), Timedelta::NAT);
19138
19139        // Series([Timedelta.min]) - Timedelta('1ns') -> [NaT], because the
19140        // result lands exactly on the i64::MIN sentinel. FP and pandas agree
19141        // — but only by SENTINEL COLLISION, not by policy. One further step
19142        // (`min - 2ns`) is `OverflowError: Overflow in int64 addition` in
19143        // pandas while FP still says NaT, which is the real divergence. A
19144        // test that only checked the 1ns case would therefore prove nothing;
19145        // both depths are asserted so the pair stays honest.
19146        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT); // pandas: NaT
19147        assert_eq!(Timedelta::sub(MIN_OK, 2), Timedelta::NAT); // pandas: RAISES
19148        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
19149        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(2).is_nat());
19150
19151        // ── DIVERGENCE: pandas refuses, FP surfaces NaT ────────────────────
19152        // Kept adjacent to the agreement cases so the boundary between the
19153        // two halves is visible in one place; DISC-018 is the prose record.
19154        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
19155        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
19156        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
19157
19158        // ── CONTROL: representable results are untouched by any of this ────
19159        assert_eq!(Timedelta::div_scalar(MAX, 1), MAX);
19160        assert_eq!(Timedelta::div_scalar(-100, 3), -34); // floor, not trunc
19161        assert_eq!(Timedelta::div_scalar(100, -3), -34);
19162        assert_eq!(Timedelta::sub(MIN_OK + 2, 1), MIN_OK + 1);
19163    }
19164
19165    #[test]
19166    fn timedelta_mul_scalar_scales() {
19167        let three_hours = Timedelta::NANOS_PER_HOUR * 3;
19168        assert_eq!(
19169            Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
19170            three_hours
19171        );
19172        assert_eq!(Timedelta::mul_scalar(100, 0), 0);
19173        assert_eq!(Timedelta::mul_scalar(100, -2), -200);
19174    }
19175
19176    #[test]
19177    fn timedelta_mul_scalar_returns_nat_on_overflow() {
19178        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX.
19179        // pandas `pd.Timedelta.max * 2` raises OverflowError.
19180        assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), Timedelta::NAT);
19181        assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), Timedelta::NAT);
19182    }
19183
19184    #[test]
19185    fn from_unit_nan_is_nat_and_overflow_is_err_8v92m() {
19186        use super::TimedeltaError;
19187
19188        // br-frankenpandas-8v92m. Rust's float->int `as` maps NaN to 0 and
19189        // saturates infinities, so the unguarded
19190        //     Ok((value * multiplier as f64).round() as i64)
19191        // failed OPEN twice: NaN became a ZERO DURATION, and inf/1e30 became a
19192        // finite plausible ~106751-day duration. Live pandas 2.2.3:
19193        //   pd.Timedelta(nan, unit='s')   -> NaT
19194        //   pd.Timedelta(inf, unit='s')   -> OutOfBoundsTimedelta
19195        //                                    "Cannot cast inf from s to 'ns' without overflow."
19196        //   pd.Timedelta(1e30, unit='s')  -> OutOfBoundsTimedelta
19197        //   pd.Timedelta(1.5, unit='s')   -> Timedelta('0 days 00:00:01.5')  <- must NOT change
19198        // The guard is copied from the two siblings that already had it
19199        // (br-frankenpandas-zw3mg), which is why `parse` behaviour is pinned
19200        // below too: all three copies must now agree.
19201
19202        // ── NaN -> NaT, NOT zero. This is the load-bearing case: an impl that
19203        // returns Ok(0) fails, and so does one that returns Err, because
19204        // pandas gives NaT rather than raising.
19205        assert_eq!(Timedelta::from_unit(f64::NAN, "s"), Ok(Timedelta::NAT));
19206        assert_ne!(Timedelta::from_unit(f64::NAN, "s"), Ok(0));
19207        assert_eq!(Timedelta::from_unit(f64::NAN, "D"), Ok(Timedelta::NAT));
19208
19209        // ── non-finite / out-of-range -> Overflow, not a saturated duration.
19210        assert_eq!(
19211            Timedelta::from_unit(f64::INFINITY, "s"),
19212            Err(TimedeltaError::Overflow)
19213        );
19214        assert_eq!(
19215            Timedelta::from_unit(f64::NEG_INFINITY, "s"),
19216            Err(TimedeltaError::Overflow)
19217        );
19218        assert_eq!(
19219            Timedelta::from_unit(1e30, "s"),
19220            Err(TimedeltaError::Overflow)
19221        );
19222        assert_eq!(
19223            Timedelta::from_unit(1e30, "D"),
19224            Err(TimedeltaError::Overflow)
19225        );
19226
19227        // ── CONTROL: ordinary values must be untouched, bit-for-bit. An
19228        // over-eager guard that rejected anything large would fail here.
19229        assert_eq!(Timedelta::from_unit(1.5, "s"), Ok(1_500_000_000));
19230        assert_eq!(Timedelta::from_unit(0.0, "s"), Ok(0));
19231        assert_eq!(Timedelta::from_unit(-2.5, "s"), Ok(-2_500_000_000));
19232        assert_eq!(Timedelta::from_unit(1.0, "D"), Ok(Timedelta::NANOS_PER_DAY));
19233        assert_eq!(
19234            Timedelta::from_unit(3.0, "h"),
19235            Ok(3 * Timedelta::NANOS_PER_HOUR)
19236        );
19237        // Just inside the representable range still returns its exact product,
19238        // so the boundary is pinned from the accepting side as well.
19239        let big_days = 100_000.0_f64;
19240        let expected = (big_days * Timedelta::NANOS_PER_DAY as f64).round() as i64;
19241        assert_eq!(Timedelta::from_unit(big_days, "D"), Ok(expected));
19242        assert!(expected > 0, "fixture must stay in range to be a control");
19243
19244        // ── an unknown unit is still InvalidFormat, NOT Overflow — the unit
19245        // check must keep running before the range check.
19246        assert!(matches!(
19247            Timedelta::from_unit(1.0, "nonsense-unit"),
19248            Err(TimedeltaError::InvalidFormat(_))
19249        ));
19250        assert!(matches!(
19251            Timedelta::from_unit(f64::NAN, "nonsense-unit"),
19252            Err(TimedeltaError::InvalidFormat(_)),
19253        ));
19254
19255        // ── the already-guarded sibling is unchanged. NOTE the input shape:
19256        // the compound lexer accepts only digits, '.' and '-', so scientific
19257        // notation is an InvalidFormat, not an Overflow — the overflow case
19258        // needs a long decimal literal (this is zw3mg's own fixture).
19259        let huge = format!("{} days", "9".repeat(18));
19260        assert!(matches!(
19261            Timedelta::parse(&huge),
19262            Err(TimedeltaError::Overflow)
19263        ));
19264        assert!(matches!(
19265            Timedelta::parse("1e100 days"),
19266            Err(TimedeltaError::InvalidFormat(_))
19267        ));
19268    }
19269
19270    #[test]
19271    fn rounding_and_ms_us_overflow_never_fabricates_a_finite_value_kyd16() {
19272        // br-frankenpandas-kyd16, the sibling sweep of lgyy8. Three defects:
19273        //   (1) Timedelta::round used UNCHECKED `(quotient + 1) * unit_nanos`
19274        //       on the round-up branch — debug PANIC, release WRAP to a
19275        //       large-negative duration.
19276        //   (2) Timedelta::floor/ceil and Timestamp::ceil_to/round_to
19277        //       saturated to i64::MAX, a finite plausible duration / ~year-2262
19278        //       instant handed back as real data — while their own sibling
19279        //       Timestamp::floor_to was ALREADY checked.
19280        //   (3) Timestamp::from_millis/from_micros saturated likewise, while
19281        //       their neighbour `fromtimestamp` already returned NaT.
19282        // Live pandas 2.2.3 raises on every one of these and names the cause:
19283        //   Timestamp.max.ceil('D')/round('D') -> OutOfBoundsDatetime
19284        //       "Cannot round 2262-04-11 23:47:16.854775807 to freq=<Day> without overflow"
19285        //   Timestamp.min.floor('D')           -> OutOfBoundsDatetime (same)
19286        //   Timedelta.max.ceil('D')/round('D') -> OutOfBoundsTimedelta (same shape)
19287        //   Timedelta.min.floor('D')           -> OutOfBoundsTimedelta (same)
19288        // ...but Timestamp.max.floor('D') is an ordinary in-range answer and
19289        // must NOT change. Both halves are asserted below.
19290        const MAX: i64 = i64::MAX;
19291        const MIN_OK: i64 = i64::MIN + 1;
19292        const DAY: i64 = Timedelta::NANOS_PER_DAY;
19293
19294        // ── (1) round(): must not panic, must not wrap negative ────────────
19295        let rounded = Timedelta::round(MAX, "D");
19296        assert_eq!(
19297            rounded,
19298            Timedelta::NAT,
19299            "rounding i64::MAX up to a whole day overflows; the old unchecked \
19300             multiply panicked in debug and wrapped in release"
19301        );
19302        // The wrap signature specifically: a positive input must never round
19303        // to a negative duration. This fails for a wrapping impl even if the
19304        // debug panic is somehow avoided.
19305        assert!(
19306            rounded == Timedelta::NAT || rounded > 0,
19307            "a positive duration must never round to a negative one"
19308        );
19309        assert_eq!(Timedelta::round(MIN_OK, "D"), Timedelta::NAT);
19310
19311        // ── (2) floor/ceil overflow -> NaT, not a fabricated finite value ──
19312        assert_eq!(Timedelta::ceil(MAX, "D"), Timedelta::NAT);
19313        assert_eq!(Timedelta::floor(MIN_OK, "D"), Timedelta::NAT);
19314        assert!(Timestamp::from_nanos(MAX).ceil_to(DAY).is_nat());
19315        assert!(Timestamp::from_nanos(MAX).round_to(DAY).is_nat());
19316        assert!(Timestamp::from_nanos(MIN_OK).floor_to(DAY).is_nat());
19317        assert!(Timestamp::from_nanos(MIN_OK).round_to(DAY).is_nat());
19318
19319        // ── (3) ms/us constructors out of range -> NaT ─────────────────────
19320        assert!(Timestamp::from_millis(MAX, None).is_nat());
19321        assert!(Timestamp::from_millis(MIN_OK, None).is_nat());
19322        assert!(Timestamp::from_micros(MAX, None).is_nat());
19323        assert!(Timestamp::from_micros(MIN_OK, Some("US/Eastern")).is_nat());
19324
19325        // ── CONTROL: in-range rounding is untouched. An implementation that
19326        // NaT'd too eagerly — or that treated "near the limit" as overflow —
19327        // fails every assertion below.
19328        //
19329        // Timestamp.max.floor('D') is the exact case pandas ANSWERS rather
19330        // than raising, so it pins the boundary from the other side.
19331        let max_floor = Timestamp::from_nanos(MAX).floor_to(DAY);
19332        assert!(!max_floor.is_nat(), "Timestamp.max.floor(D) must succeed");
19333        assert_eq!(max_floor.nanos, (MAX / DAY) * DAY);
19334        assert_eq!(Timedelta::floor(MAX, "D"), (MAX / DAY) * DAY);
19335        assert_eq!(
19336            Timedelta::ceil(MIN_OK, "D"),
19337            (MIN_OK.div_euclid(DAY) + 1) * DAY
19338        );
19339
19340        // Ordinary values, bit-for-bit.
19341        let hour = Timedelta::NANOS_PER_HOUR;
19342        assert_eq!(Timedelta::floor(90 * 60 * 1_000_000_000, "h"), hour);
19343        assert_eq!(Timedelta::ceil(90 * 60 * 1_000_000_000, "h"), 2 * hour);
19344        assert_eq!(Timedelta::round(90 * 60 * 1_000_000_000, "h"), 2 * hour);
19345        assert_eq!(Timedelta::round(-90 * 60 * 1_000_000_000, "h"), -2 * hour);
19346        assert_eq!(Timedelta::round(29 * 60 * 1_000_000_000, "h"), 0);
19347        assert_eq!(Timestamp::from_millis(1_500, None).nanos, 1_500_000_000);
19348        assert_eq!(Timestamp::from_micros(-2_000, None).nanos, -2_000_000);
19349        assert_eq!(
19350            Timestamp::from_nanos(hour + 1).floor_to(hour).nanos,
19351            hour,
19352            "in-range floor unchanged"
19353        );
19354        assert_eq!(
19355            Timestamp::from_nanos(hour + 1).ceil_to(hour).nanos,
19356            2 * hour,
19357            "in-range ceil unchanged"
19358        );
19359
19360        // NaT / degenerate-unit inputs unchanged.
19361        assert_eq!(Timedelta::round(Timedelta::NAT, "D"), Timedelta::NAT);
19362        assert_eq!(Timedelta::floor(Timedelta::NAT, "D"), Timedelta::NAT);
19363        assert_eq!(Timedelta::ceil(1_000, "nonsense-unit"), Timedelta::NAT);
19364        assert!(Timestamp::nat().ceil_to(DAY).is_nat());
19365        assert!(Timestamp::from_nanos(0).round_to(0).is_nat());
19366        // A non-overflowing round still carries its zone.
19367        assert_eq!(
19368            Timestamp::from_nanos_tz(hour + 1, "US/Eastern")
19369                .ceil_to(hour)
19370                .tz
19371                .as_deref(),
19372            Some("US/Eastern")
19373        );
19374    }
19375
19376    #[test]
19377    fn timedelta_mul_scalar_propagates_nat() {
19378        assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
19379    }
19380
19381    #[test]
19382    fn arithmetic_overflow_never_fabricates_a_finite_value_lgyy8() {
19383        // br-frankenpandas-lgyy8. The bug: these six helpers used
19384        // `saturating_*`, so POSITIVE overflow returned i64::MAX — a valid,
19385        // finite, plausible duration / ~year-2262 instant — as if it were real
19386        // data. (Negative overflow landed on i64::MIN, which IS the NaT
19387        // sentinel, so that direction already surfaced as missing.) Live
19388        // pandas 2.2.3 never returns a fabricated finite value on overflow in
19389        // either direction, scalar or vectorized:
19390        //   pd.Timedelta.max + Timedelta('1ns')  -> OverflowError
19391        //   pd.Timestamp.max + Timedelta('1ns')  -> OutOfBoundsDatetime
19392        //   pd.Timestamp.min - pd.Timestamp.max  -> OutOfBoundsDatetime
19393        //   pd.Timedelta.max * 2                 -> OverflowError
19394        //   pd.Timedelta.min + Timedelta('-1ns') -> NaT
19395        //
19396        // Every assertion below is a case a saturating implementation FAILS.
19397        const MAX: i64 = i64::MAX;
19398        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
19399
19400        // ── positive overflow: the actual bug ──────────────────────────────
19401        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
19402        assert_eq!(Timedelta::add(MAX - 10, 100), Timedelta::NAT);
19403        assert_eq!(Timedelta::sub(MAX, -1), Timedelta::NAT);
19404        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
19405        assert_eq!(Timedelta::mul_scalar(MAX / 2 + 2, 2), Timedelta::NAT);
19406        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
19407        assert!(Timestamp::from_nanos(MAX).sub_timedelta(-1).is_nat());
19408        // Timestamp.max - Timestamp.min: the true difference is ~2^64, far
19409        // outside i64. Saturation returned MAX (a ~292-year duration presented
19410        // as the real answer); pandas raises OutOfBoundsDatetime.
19411        assert_eq!(
19412            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(MIN_OK)),
19413            Timedelta::NAT
19414        );
19415
19416        // ── negative overflow: unchanged, still NaT ────────────────────────
19417        assert_eq!(Timedelta::add(MIN_OK, -1), Timedelta::NAT);
19418        assert_eq!(Timedelta::add(MIN_OK, -2), Timedelta::NAT);
19419        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
19420        assert_eq!(Timedelta::mul_scalar(MIN_OK, 2), Timedelta::NAT);
19421        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
19422        assert!(Timestamp::from_nanos(MIN_OK).add_timedelta(-1).is_nat());
19423        assert_eq!(
19424            Timestamp::from_nanos(MIN_OK).sub_timestamp(&Timestamp::from_nanos(MAX)),
19425            Timedelta::NAT
19426        );
19427
19428        // ── the boundary: the largest REPRESENTABLE results must still be
19429        // returned exactly. This is what stops the fix from being bought with
19430        // an over-eager NaT that swallows valid arithmetic — an implementation
19431        // that NaT'd one step early fails here, as does one that NaT'd on any
19432        // operand near the limits.
19433        assert_eq!(Timedelta::add(MAX - 1, 1), MAX);
19434        assert_eq!(Timedelta::add(MAX, 0), MAX);
19435        assert_eq!(Timedelta::sub(MAX, 1), MAX - 1);
19436        assert_eq!(Timedelta::add(MIN_OK + 1, -1), MIN_OK);
19437        assert_eq!(Timedelta::mul_scalar(MAX / 2, 2), (MAX / 2) * 2);
19438        assert_eq!(Timedelta::mul_scalar(MIN_OK, 1), MIN_OK);
19439        assert_eq!(Timestamp::from_nanos(MAX - 1).add_timedelta(1).nanos, MAX);
19440        assert_eq!(
19441            Timestamp::from_nanos(MIN_OK + 1).sub_timedelta(1).nanos,
19442            MIN_OK
19443        );
19444        assert_eq!(
19445            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(0)),
19446            MAX
19447        );
19448        // Ordinary values are untouched bit-for-bit.
19449        assert_eq!(Timedelta::add(1_000, 2_345), 3_345);
19450        assert_eq!(Timedelta::sub(1_000, 2_345), -1_345);
19451        assert_eq!(Timedelta::mul_scalar(-7, 6), -42);
19452
19453        // ── a result landing EXACTLY on i64::MIN is representable, but i64::MIN
19454        // IS the NaT sentinel, so it must read as NaT rather than as the most
19455        // negative duration. pandas agrees: Timedelta.min + -1ns -> NaT. Note
19456        // `MIN_OK - 1 == i64::MIN` does not overflow, so this case survives the
19457        // switch from saturating_* to checked_* only because the sentinel and
19458        // the clamp coincide — assert it explicitly rather than by accident.
19459        assert_eq!(MIN_OK - 1, i64::MIN);
19460        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
19461        assert_eq!(Timedelta::add(MIN_OK, 0), MIN_OK);
19462
19463        // ── NaT operands still propagate, and tz no longer rides along with a
19464        // fabricated instant: an overflowed Timestamp is the canonical NaT.
19465        assert!(Timestamp::nat().add_timedelta(1).is_nat());
19466        assert!(
19467            Timestamp::from_nanos(0)
19468                .add_timedelta(Timedelta::NAT)
19469                .is_nat()
19470        );
19471        let tzed = Timestamp::from_nanos_tz(MAX, "US/Eastern");
19472        let overflowed = tzed.add_timedelta(1);
19473        assert!(overflowed.is_nat());
19474        assert_eq!(overflowed.tz, None, "an overflow NaT carries no zone");
19475        // ...while a NON-overflowing shift still preserves the zone.
19476        assert_eq!(
19477            Timestamp::from_nanos_tz(0, "US/Eastern")
19478                .add_timedelta(Timedelta::NANOS_PER_DAY)
19479                .tz
19480                .as_deref(),
19481            Some("US/Eastern")
19482        );
19483    }
19484
19485    #[test]
19486    fn timedelta_div_scalar_floor_divides() {
19487        // Floor division (matches Python / pandas): -100 // 3 == -34, not -33.
19488        assert_eq!(Timedelta::div_scalar(100, 3), 33);
19489        assert_eq!(Timedelta::div_scalar(-100, 3), -34);
19490        assert_eq!(Timedelta::div_scalar(100, -3), -34);
19491        assert_eq!(Timedelta::div_scalar(-100, -3), 33);
19492    }
19493
19494    #[test]
19495    fn timedelta_div_scalar_zero_divisor_returns_nat() {
19496        assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
19497    }
19498
19499    #[test]
19500    fn timedelta_div_scalar_min_neg_one_propagates_nat() {
19501        // i64::MIN aliases NaT, so `div_scalar(i64::MIN, _)` propagates NaT
19502        // — the `i64::MIN / -1` arithmetic-overflow case is subsumed.
19503        assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
19504        // (i64::MIN + 1) is a real timedelta; `/ -1` does not overflow.
19505        assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
19506    }
19507
19508    #[test]
19509    fn timedelta_div_scalar_propagates_nat() {
19510        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
19511    }
19512
19513    #[test]
19514    fn timedelta_div_timedelta_returns_float_ratio() {
19515        let two_hours = Timedelta::NANOS_PER_HOUR * 2;
19516        let one_hour = Timedelta::NANOS_PER_HOUR;
19517        assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
19518        assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
19519    }
19520
19521    #[test]
19522    fn timedelta_div_timedelta_nat_returns_nan() {
19523        assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
19524        assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
19525    }
19526
19527    // ── Timestamp tests (br-frankenpandas-9p0u — 4r56 Phase 2) ──────────
19528
19529    use super::Timestamp;
19530
19531    #[test]
19532    fn timestamp_from_nanos_is_naive_utc() {
19533        let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
19534        assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
19535        assert_eq!(ts.tz, None);
19536        assert!(!ts.is_nat());
19537    }
19538
19539    #[test]
19540    fn timestamp_from_nanos_tz_carries_tz_name() {
19541        let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19542        assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
19543    }
19544
19545    #[test]
19546    fn timestamp_now_returns_current_time() {
19547        let before = std::time::SystemTime::now()
19548            .duration_since(std::time::UNIX_EPOCH)
19549            .unwrap()
19550            .as_nanos() as i64;
19551        let ts = Timestamp::now();
19552        let after = std::time::SystemTime::now()
19553            .duration_since(std::time::UNIX_EPOCH)
19554            .unwrap()
19555            .as_nanos() as i64;
19556        assert!(ts.nanos >= before);
19557        assert!(ts.nanos <= after);
19558        assert!(!ts.is_nat());
19559    }
19560
19561    #[test]
19562    fn timestamp_today_returns_midnight() {
19563        let ts = Timestamp::today();
19564        assert!(!ts.is_nat());
19565        // Today should be normalized (midnight), so hour/min/sec should be 0
19566        assert_eq!(ts.hour(), Some(0));
19567        assert_eq!(ts.minute(), Some(0));
19568        assert_eq!(ts.second(), Some(0));
19569    }
19570
19571    #[test]
19572    fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
19573        let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
19574        let one_day = Timedelta::NANOS_PER_DAY;
19575        let shifted = ts.add_timedelta(one_day);
19576        assert_eq!(shifted.nanos, one_day);
19577        assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
19578    }
19579
19580    #[test]
19581    fn timestamp_add_timedelta_returns_nat_on_overflow() {
19582        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX, i.e.
19583        // a finite ~year-2262 instant handed back as real data. pandas
19584        // `pd.Timestamp.max + pd.Timedelta('1ns')` raises OutOfBoundsDatetime.
19585        let ts = Timestamp::from_nanos(i64::MAX - 10);
19586        assert!(ts.add_timedelta(100).is_nat());
19587    }
19588
19589    #[test]
19590    fn timestamp_add_timedelta_propagates_nat() {
19591        // NaT Timestamp + anything = NaT.
19592        assert!(Timestamp::nat().add_timedelta(100).is_nat());
19593        // Timestamp + NaT Timedelta = NaT.
19594        assert!(
19595            Timestamp::from_nanos(0)
19596                .add_timedelta(Timedelta::NAT)
19597                .is_nat()
19598        );
19599    }
19600
19601    #[test]
19602    fn timestamp_sub_timedelta_shifts_backward() {
19603        let ts = Timestamp::from_nanos(1_000);
19604        let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
19605        assert_eq!(shifted.nanos, 0);
19606    }
19607
19608    #[test]
19609    fn timestamp_sub_timestamp_returns_timedelta_nanos() {
19610        let t0 = Timestamp::from_nanos(0);
19611        let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
19612        assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
19613        assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
19614    }
19615
19616    #[test]
19617    fn timestamp_sub_timestamp_nat_propagates() {
19618        let ts = Timestamp::from_nanos(1_000);
19619        assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
19620        assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
19621    }
19622
19623    #[test]
19624    fn timestamp_semantic_eq_treats_two_nat_as_equal() {
19625        assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
19626        assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
19627        assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
19628    }
19629
19630    #[test]
19631    fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
19632        use std::cmp::Ordering;
19633        let a = Timestamp::from_nanos(0);
19634        let b = Timestamp::from_nanos(100);
19635        assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
19636        assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
19637        assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
19638        assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
19639        assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
19640    }
19641
19642    #[test]
19643    fn time_zone_offsets_and_wall_clock_conversions_follow_pandas() {
19644        use crate::{
19645            TimeZoneError, tz_abbreviation, tz_canonical_name, tz_offset_seconds,
19646            tz_utc_to_wall_nanos, tz_validate, tz_wall_to_utc_nanos,
19647        };
19648        let hour = 3_600_000_000_000_i64;
19649        // 2024-03-10 14:30 UTC: Tokyo is +9h; New York is on EDT (-4h) after
19650        // 07:00 UTC that day and on EST (-5h) the day before.
19651        let instant = 1_710_081_000_000_000_000_i64;
19652        assert_eq!(tz_offset_seconds("Asia/Tokyo", instant), Ok(9 * 3_600));
19653        assert_eq!(tz_offset_seconds("US/Eastern", instant), Ok(-4 * 3_600));
19654        assert_eq!(
19655            tz_offset_seconds("US/Eastern", instant - 24 * hour),
19656            Ok(-5 * 3_600)
19657        );
19658        assert_eq!(tz_offset_seconds("+05:30", 0), Ok(19_800));
19659        assert_eq!(tz_offset_seconds("UTC+05:30", 0), Ok(19_800));
19660        assert_eq!(tz_offset_seconds("-03:00", 0), Ok(-10_800));
19661        assert_eq!(tz_offset_seconds("UTC", instant), Ok(0));
19662        assert_eq!(
19663            tz_utc_to_wall_nanos("Asia/Tokyo", instant),
19664            Ok(instant + 9 * hour)
19665        );
19666        // Wall 12:00 in New York on 2024-01-01 is 17:00 UTC, and back.
19667        let wall_noon = 19_723 * 24 * hour + 12 * hour;
19668        assert_eq!(
19669            tz_wall_to_utc_nanos("US/Eastern", wall_noon),
19670            Ok(wall_noon + 5 * hour)
19671        );
19672        assert_eq!(
19673            tz_utc_to_wall_nanos("US/Eastern", wall_noon + 5 * hour),
19674            Ok(wall_noon)
19675        );
19676        // NaT passes through both ways.
19677        assert_eq!(tz_wall_to_utc_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19678        assert_eq!(tz_utc_to_wall_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19679        // NEGATIVES: 02:30 on 2024-03-10 does not exist in New York; 01:30
19680        // on 2024-11-03 happens twice; unknown zones and malformed offsets
19681        // are pandas' UnknownTimeZoneError.
19682        let skipped = 19_792 * 24 * hour + 2 * hour + 30 * 60_000_000_000;
19683        assert_eq!(
19684            tz_wall_to_utc_nanos("US/Eastern", skipped),
19685            Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19686        );
19687        let repeated = 20_030 * 24 * hour + hour + 30 * 60_000_000_000;
19688        assert_eq!(
19689            tz_wall_to_utc_nanos("US/Eastern", repeated),
19690            Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19691        );
19692        assert_eq!(
19693            tz_offset_seconds("Mars/Olympus", 0),
19694            Err(TimeZoneError::Unknown("Mars/Olympus".to_owned()))
19695        );
19696        assert!(tz_validate("+24:00").is_err());
19697        assert!(tz_validate("+5:30").is_err());
19698        assert!(tz_validate("Europe/Paris").is_ok());
19699        // pandas' names: a fixed offset is UTC+HH:MM, a zero one UTC.
19700        assert_eq!(tz_canonical_name("+05:30").as_deref(), Ok("UTC+05:30"));
19701        assert_eq!(tz_canonical_name("UTC-03:00").as_deref(), Ok("UTC-03:00"));
19702        assert_eq!(tz_canonical_name("+00:00").as_deref(), Ok("UTC"));
19703        assert_eq!(tz_canonical_name("Z").as_deref(), Ok("UTC"));
19704        assert_eq!(tz_canonical_name("US/Eastern").as_deref(), Ok("US/Eastern"));
19705        // strftime('%Z'): the abbreviation in force at the instant.
19706        assert_eq!(tz_abbreviation("US/Eastern", instant).as_deref(), Ok("EDT"));
19707        assert_eq!(
19708            tz_abbreviation("US/Eastern", instant - 24 * hour).as_deref(),
19709            Ok("EST")
19710        );
19711        assert_eq!(tz_abbreviation("+05:30", 0).as_deref(), Ok("UTC+05:30"));
19712    }
19713
19714    /// pandas' `tz_localize(ambiguous=, nonexistent=)` for one wall time
19715    /// (br-frankenpandas-84w06), live pandas 2.2.3 in America/New_York:
19716    /// 02:30 on 2024-03-10 does not exist - shift_forward 03:00-04:00 (07:00
19717    /// UTC), shift_backward 01:59:59.999999999-05:00, NaT, or +1h 03:30-04:00;
19718    /// 01:30 on 2024-11-03 happens twice - True (DST) 05:30 UTC, False
19719    /// (standard) 06:30 UTC, NaT.
19720    #[test]
19721    fn tz_localize_policies_follow_pandas_84w06() {
19722        use super::{
19723            AmbiguousTime as A, NonexistentTime as N, TimeZoneError,
19724            tz_wall_to_utc_nanos_with as at,
19725        };
19726        let hour = 3_600_000_000_000_i64;
19727        let minute = 60_000_000_000_i64;
19728        let skipped = 19_792 * 24 * hour + 2 * hour + 30 * minute;
19729        let transition = 19_792 * 24 * hour + 7 * hour;
19730        let zone = "America/New_York";
19731        assert_eq!(at(zone, skipped, A::Raise, N::ShiftForward), Ok(transition));
19732        assert_eq!(
19733            at(zone, skipped, A::Raise, N::ShiftBackward),
19734            Ok(transition - 1)
19735        );
19736        assert_eq!(at(zone, skipped, A::Raise, N::NaT), Ok(i64::MIN));
19737        assert_eq!(
19738            at(zone, skipped, A::Raise, N::Shift(hour)),
19739            Ok(transition + 30 * minute)
19740        );
19741        let repeated = 20_030 * 24 * hour + hour + 30 * minute;
19742        assert_eq!(
19743            at(zone, repeated, A::Earliest, N::Raise),
19744            Ok(repeated + 4 * hour)
19745        );
19746        assert_eq!(
19747            at(zone, repeated, A::Latest, N::Raise),
19748            Ok(repeated + 5 * hour)
19749        );
19750        assert_eq!(at(zone, repeated, A::NaT, N::Raise), Ok(i64::MIN));
19751        // NEGATIVES: the policies leave a wall time that exists once alone,
19752        // and 'raise' still refuses as before.
19753        let noon = 19_723 * 24 * hour + 12 * hour;
19754        assert_eq!(at(zone, noon, A::NaT, N::NaT), Ok(noon + 5 * hour));
19755        assert_eq!(
19756            at(zone, skipped, A::NaT, N::Raise),
19757            Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19758        );
19759        assert_eq!(
19760            at(zone, repeated, A::Raise, N::NaT),
19761            Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19762        );
19763    }
19764
19765    /// The batch conversions answer as the per-value ones, value for value:
19766    /// whole-hour DST changes, Lord Howe's half hour, a fixed offset and UTC,
19767    /// over sorted minutes through each change, every hour's edges, random
19768    /// instants and NaT, under each policy (br-frankenpandas-6pqf3). NEGATIVE: 'raise' still
19769    /// refuses the first skipped wall time, a skipped one under 'NaT' is NaT
19770    /// (a reused hour's offset would place it), and a refused time's text
19771    /// keeps pandas' six or nine digits.
19772    #[test]
19773    fn batch_tz_conversions_match_each_value_6pqf3() {
19774        use super::{
19775            AmbiguousTime as A, NonexistentTime as N, TimeZoneError, tz_utc_to_wall_nanos,
19776            tz_utc_to_wall_nanos_all, tz_wall_to_utc_nanos_all, tz_wall_to_utc_nanos_with,
19777        };
19778        const HOUR: i64 = 3_600_000_000_000;
19779        const MINUTE: i64 = 60_000_000_000;
19780        const DAY: i64 = 24 * HOUR;
19781        let (year_start, year_end) = (19_723 * DAY, 20_089 * DAY);
19782        let mut values: Vec<i64> = (year_start..year_end)
19783            .step_by(usize::try_from(37 * MINUTE).unwrap())
19784            .collect();
19785        for hour in (year_start..year_end).step_by(usize::try_from(HOUR).unwrap()) {
19786            values.extend([hour - 1, hour, hour + 1]);
19787        }
19788        for change_day in [19_792, 20_030, 19_813, 20_023, 19_820, 20_002] {
19789            values.extend((0..2 * 24 * 60).map(|minute| (change_day - 1) * DAY + minute * MINUTE));
19790        }
19791        let mut state = 0x2545_f491_4f6c_dd1d_u64;
19792        for _ in 0..3_000 {
19793            state = state
19794                .wrapping_mul(6_364_136_223_846_793_005)
19795                .wrapping_add(1_442_695_040_888_963_407);
19796            values.push(i64::try_from(state >> 2).unwrap() - 2_000_000_000_000_000_000);
19797        }
19798        values.extend([i64::MIN, 19_792 * DAY, i64::MIN]);
19799        let policies = [
19800            (A::NaT, N::NaT),
19801            (A::Earliest, N::ShiftForward),
19802            (A::Latest, N::ShiftBackward),
19803            (A::NaT, N::Shift(30 * MINUTE)),
19804        ];
19805        for zone in [
19806            "US/Eastern",
19807            "Europe/London",
19808            "Australia/Lord_Howe",
19809            "+05:30",
19810            "UTC",
19811        ] {
19812            let one_by_one: Result<Vec<i64>, TimeZoneError> = values
19813                .iter()
19814                .map(|&nanos| tz_utc_to_wall_nanos(zone, nanos))
19815                .collect();
19816            assert_eq!(
19817                tz_utc_to_wall_nanos_all(zone, &values),
19818                one_by_one,
19819                "{zone}"
19820            );
19821            for (ambiguous, nonexistent) in policies {
19822                let one_by_one: Result<Vec<i64>, TimeZoneError> = values
19823                    .iter()
19824                    .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, ambiguous, nonexistent))
19825                    .collect();
19826                assert_eq!(
19827                    tz_wall_to_utc_nanos_all(zone, &values, ambiguous, nonexistent),
19828                    one_by_one,
19829                    "{zone} {ambiguous:?} {nonexistent:?}"
19830                );
19831            }
19832            let one_by_one: Result<Vec<i64>, TimeZoneError> = values
19833                .iter()
19834                .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, A::Raise, N::Raise))
19835                .collect();
19836            assert_eq!(
19837                tz_wall_to_utc_nanos_all(zone, &values, A::Raise, N::Raise),
19838                one_by_one,
19839                "{zone} raise"
19840            );
19841        }
19842        let skipped = 19_792 * DAY + 2 * HOUR + 30 * MINUTE;
19843        // 01:10 to 03:30 by 20 minutes: 02:00-03:00 is skipped.
19844        let run: Vec<i64> = (0..8)
19845            .map(|step| 19_792 * DAY + HOUR + 10 * MINUTE + step * 20 * MINUTE)
19846            .collect();
19847        assert_eq!(
19848            tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::Raise),
19849            Err(TimeZoneError::NonExistent("2024-03-10 02:10:00".to_owned()))
19850        );
19851        let placed = tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::NaT).unwrap();
19852        let expected: Vec<i64> = run
19853            .iter()
19854            .enumerate()
19855            .map(|(step, &wall)| match step {
19856                0..3 => wall + 5 * HOUR,
19857                3..6 => i64::MIN,
19858                _ => wall + 4 * HOUR,
19859            })
19860            .collect();
19861        assert_eq!(placed, expected);
19862        // Lord Howe's half-hour gap (02:00 -> 02:30 on 2024-10-06): pandas
19863        // moves 02:10 up to 03:00 (+11:00) or back to 01:59:59.999999999
19864        // (+10:30), not to the gap's end.
19865        let howe = 20_002 * DAY + 2 * HOUR + 10 * MINUTE;
19866        assert_eq!(
19867            tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftForward),
19868            Ok(vec![20_002 * DAY - 8 * HOUR])
19869        );
19870        assert_eq!(
19871            tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftBackward),
19872            Ok(vec![20_002 * DAY - 8 * HOUR - 30 * MINUTE - 1])
19873        );
19874        for (wall, text) in [
19875            (skipped + 500_000_000, "2024-03-10 02:30:00.500000"),
19876            (skipped + 1, "2024-03-10 02:30:00.000000001"),
19877        ] {
19878            assert_eq!(
19879                tz_wall_to_utc_nanos_all("US/Eastern", &[wall], A::Raise, N::Raise),
19880                Err(TimeZoneError::NonExistent(text.to_owned()))
19881            );
19882        }
19883    }
19884
19885    #[test]
19886    fn timestamp_display_matches_phase2_debug_format() {
19887        assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
19888        assert_eq!(
19889            Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
19890            "Timestamp[42, US/Eastern]"
19891        );
19892        assert_eq!(Timestamp::nat().to_string(), "NaT");
19893    }
19894
19895    #[test]
19896    fn a_naive_timestamp_cell_casts_to_its_str_srzqw() {
19897        // astype(str) of an object column's naive Timestamp is str(Timestamp)
19898        // - its own fraction, none when whole - not the 'Timestamp[<nanos>]'
19899        // placeholder (br-frankenpandas-srzqw).
19900        let text = |nanos: i64| cast_scalar(&Scalar::Datetime64(nanos), DType::Utf8);
19901        let midnight = 1_711_929_600_000_000_000;
19902        assert_eq!(
19903            text(midnight),
19904            Ok(Scalar::Utf8("2024-04-01 00:00:00".into()))
19905        );
19906        assert_eq!(
19907            text(midnight + 1_000),
19908            Ok(Scalar::Utf8("2024-04-01 00:00:00.000001".into()))
19909        );
19910        assert_eq!(
19911            text(midnight + 1),
19912            Ok(Scalar::Utf8("2024-04-01 00:00:00.000000001".into()))
19913        );
19914        assert_eq!(
19915            text(-1),
19916            Ok(Scalar::Utf8("1969-12-31 23:59:59.999999999".into()))
19917        );
19918        assert_eq!(text(Timestamp::NAT), Ok(Scalar::Utf8("NaT".into())));
19919        // The zoned spelling is the same wall clock and its offset.
19920        assert_eq!(
19921            crate::timestamp_text_in_zone(midnight, "US/Eastern"),
19922            "2024-03-31 20:00:00-04:00"
19923        );
19924    }
19925
19926    #[test]
19927    fn timestamp_value_and_unit_match_pandas_l0edr() {
19928        let ts = Timestamp::from_nanos(1_000_000_123);
19929        assert_eq!(ts.value(), 1_000_000_123);
19930        assert_eq!(ts.unit(), Some("ns"));
19931
19932        let nat = Timestamp::nat();
19933        assert_eq!(nat.value(), Timestamp::NAT);
19934        assert_eq!(nat.unit(), None);
19935    }
19936
19937    #[test]
19938    fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
19939        let ts = Timestamp::from_nanos(1_000_000_123);
19940        assert_eq!(ts.asm8(), ts.value());
19941        assert_eq!(ts.to_datetime64(), ts.value());
19942        assert_eq!(ts.to_numpy(), ts.value());
19943
19944        let nat = Timestamp::nat();
19945        assert_eq!(nat.asm8(), Timestamp::NAT);
19946        assert_eq!(nat.to_datetime64(), Timestamp::NAT);
19947        assert_eq!(nat.to_numpy(), Timestamp::NAT);
19948    }
19949
19950    #[test]
19951    fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
19952        assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
19953        assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
19954        assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
19955        assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
19956        assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
19957
19958        assert!(matches!(
19959            Timestamp::from_nanos(-500).timestamp(),
19960            Ok(value) if value == -0.0 && value.is_sign_negative()
19961        ));
19962        assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
19963        assert_eq!(
19964            Timestamp::nat().timestamp(),
19965            Err(TypeError::ValueIsMissing {
19966                kind: NullKind::NaT,
19967            })
19968        );
19969    }
19970
19971    #[test]
19972    fn timestamp_roundtrips_through_serde_json() {
19973        let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
19974        let json = serde_json::to_string(&naive).expect("serialize");
19975        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19976        assert_eq!(naive, back);
19977
19978        let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19979        let json = serde_json::to_string(&tz_aware).expect("serialize");
19980        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19981        assert_eq!(tz_aware, back);
19982    }
19983
19984    #[test]
19985    fn timestamp_is_send_and_sync() {
19986        fn assert_send_sync<T: Send + Sync>() {}
19987        assert_send_sync::<Timestamp>();
19988    }
19989
19990    // ── Timestamp rounding tests (br-frankenpandas-5h6n) ────────────────
19991
19992    #[test]
19993    fn timestamp_pre_epoch_accessors_floor_not_truncate() {
19994        // br-frankenpandas-wkjtw: pre-1970 instants with a sub-day part used to
19995        // truncate toward zero, landing on the wrong calendar day. -1 ns is
19996        // 1969-12-31 23:59:59.999999999 UTC.
19997        let ts = Timestamp::from_nanos(-1);
19998        assert_eq!(ts.year(), Some(1969));
19999        assert_eq!(ts.month(), Some(12));
20000        assert_eq!(ts.day(), Some(31));
20001        assert_eq!(ts.hour(), Some(23));
20002        assert_eq!(ts.minute(), Some(59));
20003        assert_eq!(ts.second(), Some(59));
20004        assert_eq!(ts.microsecond(), Some(999_999));
20005        assert_eq!(ts.nanosecond(), Some(999));
20006        // 1969-12-31 is a Wednesday (pandas Monday=0 -> 2).
20007        assert_eq!(ts.dayofweek(), Some(2));
20008
20009        // 1969-12-31 12:00:00 — the classic truncation case (-43200 s).
20010        let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
20011        assert_eq!(noon.year(), Some(1969));
20012        assert_eq!(noon.month(), Some(12));
20013        assert_eq!(noon.day(), Some(31));
20014        assert_eq!(noon.hour(), Some(12));
20015
20016        // Exact midnight pre-epoch was already correct; keep it green.
20017        let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
20018        assert_eq!(midnight.year(), Some(1969));
20019        assert_eq!(midnight.day(), Some(31));
20020        assert_eq!(midnight.hour(), Some(0));
20021    }
20022
20023    #[test]
20024    fn timestamp_floor_to_rounds_down() {
20025        // 12:34:56 → floor by 1H → 12:00:00
20026        let h = Timedelta::NANOS_PER_HOUR;
20027        let twelve_h = h * 12;
20028        let twelve_thirty_four =
20029            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20030        let ts = Timestamp::from_nanos(twelve_thirty_four);
20031        let floored = ts.floor_to(h);
20032        assert_eq!(floored.nanos, twelve_h);
20033    }
20034
20035    #[test]
20036    fn timestamp_floor_to_handles_already_aligned() {
20037        // 12:00:00 floored by 1H → 12:00:00 (no change).
20038        let h = Timedelta::NANOS_PER_HOUR;
20039        let twelve_h = h * 12;
20040        let ts = Timestamp::from_nanos(twelve_h);
20041        assert_eq!(ts.floor_to(h).nanos, twelve_h);
20042    }
20043
20044    #[test]
20045    fn timestamp_floor_to_handles_negative_nanos() {
20046        // -100 ns floored by 60 ns:
20047        //   div_euclid(-100, 60) = -2 (since -2*60=-120, rem=20 ≥ 0).
20048        //   result = -2 * 60 = -120.
20049        let ts = Timestamp::from_nanos(-100);
20050        assert_eq!(ts.floor_to(60).nanos, -120);
20051    }
20052
20053    #[test]
20054    fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
20055        let ts = Timestamp::from_nanos(i64::MIN + 1);
20056        assert!(ts.floor_to(10).is_nat());
20057
20058        let safe = Timestamp::from_nanos(i64::MIN + 10);
20059        assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
20060
20061        let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
20062        assert_eq!(tz.nanos, -120);
20063        assert_eq!(tz.tz.as_deref(), Some("UTC"));
20064    }
20065
20066    #[test]
20067    fn timestamp_ceil_to_rounds_up() {
20068        // 12:34:56 → ceil by 1H → 13:00:00.
20069        let h = Timedelta::NANOS_PER_HOUR;
20070        let twelve_h = h * 12;
20071        let thirteen_h = h * 13;
20072        let twelve_thirty_four =
20073            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20074        let ts = Timestamp::from_nanos(twelve_thirty_four);
20075        assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
20076    }
20077
20078    #[test]
20079    fn timestamp_ceil_to_no_op_on_aligned() {
20080        let h = Timedelta::NANOS_PER_HOUR;
20081        let twelve_h = h * 12;
20082        let ts = Timestamp::from_nanos(twelve_h);
20083        assert_eq!(ts.ceil_to(h).nanos, twelve_h);
20084    }
20085
20086    #[test]
20087    fn timestamp_round_to_rounds_to_nearest() {
20088        // 12:30:01 (one second past the half-hour): round to 1H → 13:00:00.
20089        let h = Timedelta::NANOS_PER_HOUR;
20090        let twelve_h = h * 12;
20091        let twelve_thirty_one_sec =
20092            twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
20093        let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
20094        assert_eq!(ts.round_to(h).nanos, h * 13);
20095
20096        // 12:29:59 (one second before half): round to 1H → 12:00:00.
20097        let twelve_twenty_nine_sec =
20098            twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
20099        let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
20100        assert_eq!(ts.round_to(h).nanos, twelve_h);
20101    }
20102
20103    #[test]
20104    fn timestamp_round_to_bankers_tie_to_even() {
20105        // Tie cases: rem == unit/2 exactly. Pick even-multiple floor.
20106        // unit=10, so half=5. nanos=5: floor=0 (even), so → 0.
20107        // nanos=15: floor=1 (odd), so → 20.
20108        // nanos=25: floor=2 (even), so → 20.
20109        // nanos=35: floor=3 (odd), so → 40.
20110        assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
20111        assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
20112        assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
20113        assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
20114    }
20115
20116    #[test]
20117    fn timestamp_round_to_zero_unit_returns_nat() {
20118        let ts = Timestamp::from_nanos(100);
20119        assert!(ts.round_to(0).is_nat());
20120        assert!(ts.floor_to(0).is_nat());
20121        assert!(ts.ceil_to(0).is_nat());
20122    }
20123
20124    #[test]
20125    fn timestamp_round_to_negative_unit_returns_nat() {
20126        let ts = Timestamp::from_nanos(100);
20127        assert!(ts.round_to(-10).is_nat());
20128        assert!(ts.floor_to(-10).is_nat());
20129        assert!(ts.ceil_to(-10).is_nat());
20130    }
20131
20132    #[test]
20133    fn timestamp_rounding_propagates_nat() {
20134        let nat = Timestamp::nat();
20135        assert!(nat.floor_to(60).is_nat());
20136        assert!(nat.ceil_to(60).is_nat());
20137        assert!(nat.round_to(60).is_nat());
20138    }
20139
20140    #[test]
20141    fn timestamp_rounding_preserves_tz() {
20142        let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
20143        assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
20144        assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
20145        assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
20146    }
20147
20148    // ── Timestamp string-unit rounding tests (br-frankenpandas-lbsx) ────
20149
20150    #[test]
20151    fn timestamp_floor_to_unit_h_rounds_to_hour() {
20152        let h = Timedelta::NANOS_PER_HOUR;
20153        let twelve_h = h * 12;
20154        let twelve_thirty_four =
20155            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20156        let ts = Timestamp::from_nanos(twelve_thirty_four);
20157        assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
20158        assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
20159        assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
20160        assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
20161        assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
20162    }
20163
20164    #[test]
20165    fn timestamp_ceil_to_unit_d_rounds_to_day() {
20166        // 12:34:56 → ceil to 1 day → 24:00:00 (next day).
20167        let h = Timedelta::NANOS_PER_HOUR;
20168        let d = Timedelta::NANOS_PER_DAY;
20169        let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
20170        let ts = Timestamp::from_nanos(twelve_thirty_four);
20171        assert_eq!(ts.ceil_to_unit("D").nanos, d);
20172        assert_eq!(ts.ceil_to_unit("day").nanos, d);
20173        assert_eq!(ts.ceil_to_unit("days").nanos, d);
20174    }
20175
20176    #[test]
20177    fn timestamp_round_to_unit_min_rounds_to_minute() {
20178        // 12:34:31 → round to 1 minute → 12:35:00.
20179        let m = Timedelta::NANOS_PER_MIN;
20180        let twelve_thirty_four_thirty_one =
20181            Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
20182        let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
20183        let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
20184        assert_eq!(ts.round_to_unit("min").nanos, expected);
20185        assert_eq!(ts.round_to_unit("T").nanos, expected); // pandas pre-2.2 alias
20186        assert_eq!(ts.round_to_unit("minute").nanos, expected);
20187    }
20188
20189    #[test]
20190    fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
20191        let ts = Timestamp::from_nanos(
20192            Timedelta::NANOS_PER_HOUR * 12
20193                + Timedelta::NANOS_PER_MIN * 34
20194                + Timedelta::NANOS_PER_SEC * 31,
20195        );
20196
20197        assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
20198        assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
20199        assert_eq!(ts.round("min"), ts.round_to_unit("min"));
20200    }
20201
20202    #[test]
20203    fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
20204        let ts = Timestamp::from_nanos_tz(
20205            Timedelta::NANOS_PER_DAY * 3
20206                + Timedelta::NANOS_PER_HOUR * 12
20207                + Timedelta::NANOS_PER_MIN * 34,
20208            "US/Eastern",
20209        );
20210        let normalized = ts.normalize();
20211
20212        assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
20213        assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
20214        assert!(Timestamp::nat().normalize().is_nat());
20215        for nanos in [
20216            i64::MIN + 1,
20217            -Timedelta::NANOS_PER_DAY - 1,
20218            -Timedelta::NANOS_PER_DAY,
20219            -1,
20220            0,
20221            Timedelta::NANOS_PER_DAY - 1,
20222            Timedelta::NANOS_PER_DAY,
20223            i64::MAX,
20224        ] {
20225            let timestamp = Timestamp::from_nanos(nanos);
20226            assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
20227        }
20228    }
20229
20230    #[test]
20231    #[ignore = "foreground profile-first A/B"]
20232    fn timestamp_normalize_direct_day_profile_dk721() {
20233        use std::{hint::black_box, time::Instant};
20234
20235        fn former(timestamp: &Timestamp) -> Timestamp {
20236            timestamp.floor_to_unit("D")
20237        }
20238
20239        fn candidate(timestamp: &Timestamp) -> Timestamp {
20240            timestamp.normalize()
20241        }
20242
20243        fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
20244            let started = Instant::now();
20245            let mut checksum = 0_u64;
20246            for timestamp in input {
20247                let normalized = normalize(black_box(timestamp));
20248                checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
20249            }
20250            black_box(checksum);
20251            started.elapsed().as_nanos()
20252        }
20253
20254        fn percentile(samples: &mut [u128], percent: usize) -> u128 {
20255            samples.sort_unstable();
20256            let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
20257            samples[rank]
20258        }
20259
20260        let parity_cases = [
20261            Timestamp::nat(),
20262            Timestamp::from_nanos(i64::MIN + 1),
20263            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
20264            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
20265            Timestamp::from_nanos(-1),
20266            Timestamp::from_nanos(0),
20267            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
20268            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
20269            Timestamp::from_nanos(i64::MAX),
20270            Timestamp::from_nanos_tz(-1, "US/Eastern"),
20271            Timestamp::from_nanos_tz(
20272                Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
20273                "Asia/Tokyo",
20274            ),
20275        ];
20276        for timestamp in &parity_cases {
20277            assert_eq!(former(timestamp), candidate(timestamp));
20278            assert_eq!(timestamp.normalize(), former(timestamp));
20279        }
20280
20281        const ROWS: usize = 16_384;
20282        const SAMPLES: usize = 20;
20283        let input = (0..ROWS)
20284            .map(|index| {
20285                let day = index as i64 % 4_096 - 2_048;
20286                let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
20287                    % Timedelta::NANOS_PER_DAY as u64) as i64;
20288                Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
20289            })
20290            .collect::<Vec<_>>();
20291        for timestamp in &input {
20292            assert_eq!(former(timestamp), candidate(timestamp));
20293        }
20294
20295        for _ in 0..3 {
20296            black_box(elapsed(&input, former));
20297            black_box(elapsed(&input, candidate));
20298        }
20299
20300        let mut former_ns = Vec::with_capacity(SAMPLES);
20301        let mut candidate_ns = Vec::with_capacity(SAMPLES);
20302        for sample in 0..SAMPLES {
20303            if sample % 2 == 0 {
20304                former_ns.push(elapsed(&input, former));
20305                candidate_ns.push(elapsed(&input, candidate));
20306            } else {
20307                candidate_ns.push(elapsed(&input, candidate));
20308                former_ns.push(elapsed(&input, former));
20309            }
20310        }
20311
20312        let mut former_sorted = former_ns.clone();
20313        let mut candidate_sorted = candidate_ns.clone();
20314        let former_p50 = percentile(&mut former_sorted, 50);
20315        let former_p95 = percentile(&mut former_sorted, 95);
20316        let former_p99 = percentile(&mut former_sorted, 99);
20317        let candidate_p50 = percentile(&mut candidate_sorted, 50);
20318        let candidate_p95 = percentile(&mut candidate_sorted, 95);
20319        let candidate_p99 = percentile(&mut candidate_sorted, 99);
20320        println!(
20321            "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:?}",
20322            former_p50 as f64 / candidate_p50 as f64,
20323            former_p95 as f64 / candidate_p95 as f64,
20324            former_p99 as f64 / candidate_p99 as f64,
20325        );
20326    }
20327
20328    #[test]
20329    fn timestamp_unit_rounding_unknown_unit_returns_nat() {
20330        let ts = Timestamp::from_nanos(100);
20331        assert!(ts.floor_to_unit("fortnight").is_nat());
20332        assert!(ts.ceil_to_unit("century").is_nat());
20333        assert!(ts.round_to_unit("xyz").is_nat());
20334    }
20335
20336    /// pd.Timestamp('2024-03-15 13:47:21').round('15min') is 13:45 (a
20337    /// multiple of a unit was unknown here: NaT).
20338    #[test]
20339    fn timestamp_rounding_reads_a_multiple_of_a_unit_3agof() {
20340        let (min, sec) = (Timedelta::NANOS_PER_MIN, Timedelta::NANOS_PER_SEC);
20341        let base = 1_710_460_800 * sec; // 2024-03-15 00:00:00
20342        let ts = Timestamp::from_nanos(base + 13 * Timedelta::NANOS_PER_HOUR + 47 * min + 21 * sec);
20343        let at = |minutes: i64, seconds: i64| base + minutes * min + seconds * sec;
20344        assert_eq!(ts.round("15min").nanos, at(13 * 60 + 45, 0));
20345        assert_eq!(ts.floor("15min").nanos, at(13 * 60 + 45, 0));
20346        assert_eq!(ts.ceil("15min").nanos, at(14 * 60, 0));
20347        assert_eq!(ts.round("30s").nanos, at(13 * 60 + 47, 30));
20348        assert_eq!(ts.ceil("1D").nanos, base + Timedelta::NANOS_PER_DAY);
20349        // 2024-03-15 is 19797 days after the epoch: the 7-day floor is day
20350        // 19796 (2024-03-14), as pandas'.
20351        assert_eq!(ts.floor("7D").nanos, 19_796 * Timedelta::NANOS_PER_DAY);
20352        // NEGATIVE: a calendar frequency is no fixed length.
20353        assert!(ts.round("ME").is_nat());
20354    }
20355
20356    #[test]
20357    fn timestamp_unit_rounding_propagates_nat() {
20358        let nat = Timestamp::nat();
20359        assert!(nat.floor_to_unit("H").is_nat());
20360        assert!(nat.ceil_to_unit("H").is_nat());
20361        assert!(nat.round_to_unit("H").is_nat());
20362    }
20363
20364    #[test]
20365    fn timestamp_unit_rounding_preserves_tz() {
20366        let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
20367        assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
20368        assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
20369        assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
20370    }
20371
20372    #[test]
20373    fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
20374        // Public surface check: pandas alias core set.
20375        assert_eq!(
20376            Timedelta::unit_to_nanos("W"),
20377            Some(Timedelta::NANOS_PER_WEEK)
20378        );
20379        assert_eq!(
20380            Timedelta::unit_to_nanos("D"),
20381            Some(Timedelta::NANOS_PER_DAY)
20382        );
20383        assert_eq!(
20384            Timedelta::unit_to_nanos("H"),
20385            Some(Timedelta::NANOS_PER_HOUR)
20386        );
20387        assert_eq!(
20388            Timedelta::unit_to_nanos("min"),
20389            Some(Timedelta::NANOS_PER_MIN)
20390        );
20391        assert_eq!(
20392            Timedelta::unit_to_nanos("s"),
20393            Some(Timedelta::NANOS_PER_SEC)
20394        );
20395        assert_eq!(
20396            Timedelta::unit_to_nanos("ms"),
20397            Some(Timedelta::NANOS_PER_MILLI)
20398        );
20399        assert_eq!(
20400            Timedelta::unit_to_nanos("us"),
20401            Some(Timedelta::NANOS_PER_MICRO)
20402        );
20403        assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
20404        // Empty string → days (pandas default).
20405        assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
20406        // Unknown alias → None.
20407        assert_eq!(Timedelta::unit_to_nanos("century"), None);
20408    }
20409
20410    #[test]
20411    fn timestamp_isoformat_basic() {
20412        let ts = Timestamp::from_nanos(0);
20413        assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
20414
20415        let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
20416        assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
20417
20418        let ts_fixed_offset = Timestamp::from_nanos_tz(0, "UTC+05:30");
20419        assert_eq!(
20420            ts_fixed_offset.isoformat(),
20421            "1970-01-01T05:30:00+05:30",
20422            "a fixed-offset timestamp must render local wall time rather than a UTC instant with an annotation"
20423        );
20424
20425        let ts_tz = Timestamp::from_nanos_tz(
20426            Timedelta::NANOS_PER_DAY
20427                + Timedelta::NANOS_PER_HOUR * 14
20428                + Timedelta::NANOS_PER_MIN * 30,
20429            "America/New_York",
20430        );
20431        assert!(ts_tz.isoformat().contains("1970-01-02T14:30:00"));
20432        assert!(ts_tz.isoformat().contains("[America/New_York]"));
20433
20434        assert_eq!(Timestamp::nat().isoformat(), "NaT");
20435    }
20436
20437    #[test]
20438    fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
20439        assert_eq!(
20440            Timestamp::from_nanos(-1).isoformat(),
20441            "1969-12-31T23:59:59.999999999"
20442        );
20443        assert_eq!(
20444            Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
20445            "1969-12-31T23:59:59"
20446        );
20447        assert_eq!(
20448            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
20449            "1969-12-31T00:00:00"
20450        );
20451        assert_eq!(
20452            Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
20453            "1969-12-31T23:59:59.999999999+00:00"
20454        );
20455    }
20456
20457    #[test]
20458    fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
20459        assert_eq!(
20460            Timestamp::from_nanos(123_456_789).isoformat(),
20461            "1970-01-01T00:00:00.123456789"
20462        );
20463        assert_eq!(
20464            Timestamp::from_nanos(123_456_000).isoformat(),
20465            "1970-01-01T00:00:00.123456"
20466        );
20467        assert_eq!(
20468            Timestamp::from_nanos(123_000_000).isoformat(),
20469            "1970-01-01T00:00:00.123000"
20470        );
20471        assert_eq!(
20472            Timestamp::from_nanos_tz(1, "UTC").isoformat(),
20473            "1970-01-01T00:00:00.000000001+00:00"
20474        );
20475    }
20476
20477    fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
20478        if timestamp.is_nat() {
20479            return "NaT".to_owned();
20480        }
20481        let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
20482        match &timestamp.tz {
20483            Some(tz) if tz == "UTC" => format!("{base}+00:00"),
20484            Some(tz) => format!("{base}[{tz}]"),
20485            None => base,
20486        }
20487    }
20488
20489    #[test]
20490    fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
20491        let nanos = [
20492            Timestamp::NAT,
20493            -Timedelta::NANOS_PER_DAY - 1,
20494            -Timedelta::NANOS_PER_SEC,
20495            -1,
20496            0,
20497            1,
20498            123_456_000,
20499            123_456_789,
20500            i64::MAX,
20501        ];
20502        let timezones = [
20503            None,
20504            Some("UTC"),
20505            Some("America/New_York"),
20506            Some(""),
20507            Some("Etc/Γ"),
20508        ];
20509        for value in nanos {
20510            for timezone in timezones {
20511                let timestamp = Timestamp {
20512                    nanos: value,
20513                    tz: timezone.map(str::to_owned),
20514                };
20515                assert_eq!(
20516                    timestamp.isoformat(),
20517                    timestamp_isoformat_former_q8g50(&timestamp),
20518                    "nanos={value} timezone={timezone:?}"
20519                );
20520            }
20521        }
20522    }
20523
20524    #[test]
20525    #[ignore = "foreground release A/B only"]
20526    fn timestamp_isoformat_one_buffer_ab_q8g50() {
20527        use std::{hint::black_box, time::Instant};
20528
20529        const ITEMS: usize = 8_192;
20530        const SAMPLES: usize = 10;
20531
20532        fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
20533            let started = Instant::now();
20534            let mut checksum = 0usize;
20535            for timestamp in black_box(values) {
20536                checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
20537            }
20538            black_box(checksum);
20539            started.elapsed().as_nanos()
20540        }
20541
20542        let values = (0..ITEMS)
20543            .map(|idx| {
20544                let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
20545                let timezone = if idx.is_multiple_of(2) {
20546                    "UTC"
20547                } else {
20548                    "America/New_York"
20549                };
20550                Timestamp::from_nanos_tz(nanos, timezone)
20551            })
20552            .collect::<Vec<_>>();
20553        for timestamp in &values {
20554            assert_eq!(
20555                timestamp.isoformat(),
20556                timestamp_isoformat_former_q8g50(timestamp)
20557            );
20558        }
20559
20560        black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
20561        black_box(elapsed(&values, Timestamp::isoformat));
20562
20563        let mut former_ns = Vec::with_capacity(SAMPLES);
20564        let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
20565        for sample in 0..SAMPLES {
20566            if sample.is_multiple_of(2) {
20567                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
20568                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
20569            } else {
20570                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
20571                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
20572            }
20573        }
20574        former_ns.sort_unstable();
20575        one_buffer_ns.sort_unstable();
20576        let former_p50 = former_ns[SAMPLES / 2];
20577        let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
20578        println!(
20579            "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
20580            former_p50 as f64 / one_buffer_p50 as f64
20581        );
20582        println!("former_samples_ns={former_ns:?}");
20583        println!("one_buffer_samples_ns={one_buffer_ns:?}");
20584    }
20585
20586    #[test]
20587    fn timestamp_strftime_basic() {
20588        let ts = Timestamp::from_nanos(
20589            Timedelta::NANOS_PER_DAY * 365
20590                + Timedelta::NANOS_PER_HOUR * 9
20591                + Timedelta::NANOS_PER_MIN * 15,
20592        );
20593        assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
20594        assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
20595        assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
20596        // TEST-CHANGE: this pinned `%%Y` -> `%1971`; Python (CPython 3.13,
20597        // measured) prints `%%` as a literal `%` and echoes unknown `%Q`.
20598        assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%Y|%01|%Q|%|λ");
20599        assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
20600    }
20601
20602    #[test]
20603    fn strftime_follows_python_directives_and_zones() {
20604        // 1971-01-01 09:15 (a Friday; ISO week 53 of 1970). Expected texts
20605        // are CPython 3.13's datetime.strftime on Linux.
20606        let ts = Timestamp::from_nanos(
20607            Timedelta::NANOS_PER_DAY * 365
20608                + Timedelta::NANOS_PER_HOUR * 9
20609                + Timedelta::NANOS_PER_MIN * 15,
20610        );
20611        assert_eq!(
20612            ts.strftime("%-d %_m %^a %e %k %l %P %C %g %D %F %T %R %r %h %n %t|"),
20613            "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|"
20614        );
20615        assert_eq!(
20616            ts.strftime("%a %A %b %B %c|%x %X|%I %p %j %U %W %w %y"),
20617            "Fri Friday Jan January Fri Jan  1 09:15:00 1971|01/01/71 09:15:00|09 AM 001 00 00 5 71"
20618        );
20619        // 2021-01-03: a Sunday, ISO 2020-W53-7.
20620        let sunday = Timestamp::parse("2021-01-03").expect("date");
20621        assert_eq!(sunday.strftime("%G-%V-%u %U %W %j"), "2020-53-7 01 00 003");
20622        // Microseconds only; a trailing lone percent stays; naive %z / %Z empty.
20623        let fraction = Timestamp::parse("2024-03-05 14:07:09.123456789").expect("ts");
20624        assert_eq!(fraction.strftime("%f|%z|%Z|abc%"), "123456|||abc%");
20625        // A tz-aware Timestamp prints its wall clock and zone.
20626        let eastern = Timestamp::from_nanos_tz(fraction.nanos, "US/Eastern");
20627        assert_eq!(
20628            eastern.strftime("%Y-%m-%d %H:%M %z %Z"),
20629            "2024-03-05 09:07 -0500 EST"
20630        );
20631        assert_eq!(
20632            crate::strftime_in_zone(fraction.nanos, "%H:%M %z", Some("+05:30")),
20633            "19:37 +0530"
20634        );
20635    }
20636
20637    #[test]
20638    fn timestamp_strftime_floors_pre_epoch_instants_1pmlp() {
20639        let apollo = Timestamp::parse("1969-07-20T20:17:40").unwrap();
20640        assert_eq!(
20641            apollo.strftime("%Y-%m-%d %H:%M:%S.%f"),
20642            "1969-07-20 20:17:40.000000"
20643        );
20644
20645        // The smallest negative instant catches both truncation defects:
20646        // second flooring and day flooring.
20647        let one_ns_before_epoch = Timestamp::from_nanos(-1);
20648        assert_eq!(
20649            one_ns_before_epoch.strftime("%Y-%m-%d %H:%M:%S.%f"),
20650            "1969-12-31 23:59:59.999999"
20651        );
20652    }
20653
20654    #[test]
20655    #[ignore = "foreground normal-release attribution harness"]
20656    fn timestamp_strftime_one_buffer_profile_8qzbo() {
20657        use std::{hint::black_box, time::Instant};
20658
20659        const ITEMS: usize = 8_192;
20660        const SAMPLES: usize = 10;
20661        const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
20662
20663        fn former(timestamp: &Timestamp, format: &str) -> String {
20664            if timestamp.is_nat() {
20665                return "NaT".to_string();
20666            }
20667            let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
20668            let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
20669
20670            let days_since_epoch = total_secs / 86400;
20671            let secs_of_day = (total_secs % 86400 + 86400) % 86400;
20672            let days = days_since_epoch + 719_468;
20673            let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
20674            let doe = days - era * 146_097;
20675            let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
20676            let y = yoe + era * 400;
20677            let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
20678            let mp = (5 * doy + 2) / 153;
20679            let d = doy - (153 * mp + 2) / 5 + 1;
20680            let m = if mp < 10 { mp + 3 } else { mp - 9 };
20681            let year = if m <= 2 { y + 1 } else { y };
20682            let hour = secs_of_day / 3600;
20683            let minute = (secs_of_day % 3600) / 60;
20684            let second = secs_of_day % 60;
20685            let micros = sub_nanos / 1000;
20686
20687            format
20688                .replace("%Y", &format!("{year:04}"))
20689                .replace("%m", &format!("{m:02}"))
20690                .replace("%d", &format!("{d:02}"))
20691                .replace("%H", &format!("{hour:02}"))
20692                .replace("%M", &format!("{minute:02}"))
20693                .replace("%S", &format!("{second:02}"))
20694                .replace("%f", &format!("{micros:06}"))
20695        }
20696
20697        fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
20698            let started = Instant::now();
20699            let mut digest = 0_usize;
20700            for timestamp in timestamps {
20701                let value = formatter(black_box(timestamp), black_box(FORMAT));
20702                digest = digest.wrapping_add(value.len());
20703                digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
20704                black_box(value);
20705            }
20706            black_box(digest);
20707            started.elapsed().as_nanos()
20708        }
20709
20710        fn percentile(samples: &mut [u128], pct: usize) -> u128 {
20711            samples.sort_unstable();
20712            let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
20713            samples[rank]
20714        }
20715
20716        let edge_timestamps = [
20717            Timestamp::nat(),
20718            Timestamp::from_nanos(i64::MIN + 1),
20719            Timestamp::from_nanos(-1_234_567_890),
20720            Timestamp::from_nanos(0),
20721            Timestamp::from_nanos(1_735_732_800_123_456_789),
20722            Timestamp::from_nanos(i64::MAX),
20723        ];
20724        let edge_formats = [
20725            "",
20726            "%Y-%m-%d %H:%M:%S.%f",
20727            "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
20728            "%%Y|%%%m|%Q|%|λ",
20729            FORMAT,
20730        ];
20731        for timestamp in &edge_timestamps {
20732            for format in edge_formats {
20733                assert_eq!(former(timestamp, format), timestamp.strftime(format));
20734            }
20735        }
20736
20737        let timestamps = (0..ITEMS)
20738            .map(|index| {
20739                let centered = index as i64 - ITEMS as i64 / 2;
20740                Timestamp::from_nanos(centered * 987_654_321_123_456)
20741            })
20742            .collect::<Vec<_>>();
20743        for timestamp in &timestamps {
20744            assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
20745        }
20746
20747        black_box(elapsed(&timestamps, former));
20748        black_box(elapsed(&timestamps, Timestamp::strftime));
20749
20750        let mut former_samples = Vec::with_capacity(SAMPLES);
20751        let mut public_samples = Vec::with_capacity(SAMPLES);
20752        for sample in 0..SAMPLES {
20753            if sample.is_multiple_of(2) {
20754                former_samples.push(elapsed(&timestamps, former));
20755                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
20756            } else {
20757                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
20758                former_samples.push(elapsed(&timestamps, former));
20759            }
20760        }
20761        let former_p50 = percentile(&mut former_samples, 50);
20762        let former_p95 = percentile(&mut former_samples, 95);
20763        let public_p50 = percentile(&mut public_samples, 50);
20764        let public_p95 = percentile(&mut public_samples, 95);
20765        println!(
20766            "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}",
20767            former_p50 as f64 / public_p50 as f64,
20768            former_p95 as f64 / public_p95 as f64,
20769        );
20770        println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
20771        println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
20772    }
20773
20774    #[test]
20775    fn timestamp_day_name_and_month_name() {
20776        let ts = Timestamp::from_nanos(0);
20777        assert_eq!(ts.day_name(), "Thursday");
20778        assert_eq!(ts.month_name(), "January");
20779
20780        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20781        assert_eq!(ts2.day_name(), "Friday");
20782        assert_eq!(ts2.month_name(), "January");
20783
20784        assert_eq!(Timestamp::nat().day_name(), "NaT");
20785        assert_eq!(Timestamp::nat().month_name(), "NaT");
20786    }
20787
20788    #[test]
20789    fn timestamp_replace_validates_components_zw0y2() {
20790        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20791        let replaced = ts.replace(
20792            Some(2024),
20793            Some(2),
20794            Some(29),
20795            Some(23),
20796            Some(59),
20797            Some(58),
20798            Some(987_654),
20799            Some(321),
20800        );
20801        assert_eq!(replaced.year(), Some(2024));
20802        assert_eq!(replaced.month(), Some(2));
20803        assert_eq!(replaced.day(), Some(29));
20804        assert_eq!(replaced.hour(), Some(23));
20805        assert_eq!(replaced.minute(), Some(59));
20806        assert_eq!(replaced.second(), Some(58));
20807        assert_eq!(replaced.microsecond(), Some(987_654));
20808        assert_eq!(replaced.nanosecond(), Some(321));
20809
20810        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20811        assert_eq!(
20812            tz.replace(None, Some(2), Some(29), None, None, None, None, None)
20813                .tz
20814                .as_deref(),
20815            Some("UTC")
20816        );
20817
20818        assert!(
20819            ts.replace(None, Some(13), None, None, None, None, None, None)
20820                .is_nat()
20821        );
20822        assert!(
20823            ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
20824                .is_nat()
20825        );
20826        assert!(
20827            ts.replace(None, None, None, Some(24), None, None, None, None)
20828                .is_nat()
20829        );
20830        assert!(
20831            ts.replace(None, None, None, None, Some(60), None, None, None)
20832                .is_nat()
20833        );
20834        assert!(
20835            ts.replace(None, None, None, None, None, Some(60), None, None)
20836                .is_nat()
20837        );
20838        assert!(
20839            ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
20840                .is_nat()
20841        );
20842        assert!(
20843            ts.replace(None, None, None, None, None, None, None, Some(1_000))
20844                .is_nat()
20845        );
20846        assert!(
20847            Timestamp::nat()
20848                .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
20849                .is_nat()
20850        );
20851    }
20852
20853    /// br-frankenpandas-dzz6x: `replace` validates every component EXCEPT the
20854    /// year, and i64 nanoseconds run out around year 2262. The old unchecked
20855    /// multiply wrapped in release mode and handed back a plausible-looking
20856    /// in-range instant for an unrepresentable year — the exact failure a naive
20857    /// implementation still produces, so each far-out year below is a real
20858    /// negative case, not a restatement of the code.
20859    #[test]
20860    fn timestamp_replace_returns_nat_on_nanosecond_overflow_dzz6x() {
20861        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20862
20863        for year in [3000, 10_000, 300_000, i64::MAX / 400] {
20864            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20865            assert!(
20866                out.is_nat(),
20867                "replace(year={year}) is unrepresentable in i64 ns and must be \
20868                 NaT, got nanos={:?} (year {:?}) — this is the silent wrap",
20869                out.nanos,
20870                out.year()
20871            );
20872        }
20873        for year in [-3000, -100_000, i64::MIN / 400] {
20874            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20875            assert!(out.is_nat(), "replace(year={year}) must be NaT");
20876        }
20877
20878        // Boundary: i64 ns tops out at 106_751 days from the epoch, so 2262 is
20879        // representable at the start of the year and 2263 is not. This pins the
20880        // fix to the real limit — a guard that merely rejected "big" years by
20881        // some rounder cutoff would fail one side of this pair.
20882        let in_range = ts.replace(
20883            Some(2262),
20884            Some(1),
20885            Some(1),
20886            Some(0),
20887            Some(0),
20888            Some(0),
20889            Some(0),
20890            Some(0),
20891        );
20892        assert!(
20893            !in_range.is_nat(),
20894            "2262-01-01 is representable and must survive"
20895        );
20896        assert_eq!(in_range.year(), Some(2262));
20897        assert!(
20898            ts.replace(
20899                Some(2263),
20900                Some(12),
20901                Some(31),
20902                Some(23),
20903                Some(59),
20904                Some(59),
20905                Some(999_999),
20906                Some(999)
20907            )
20908            .is_nat(),
20909            "end of 2263 exceeds the i64 ns axis and must be NaT"
20910        );
20911
20912        // In-range results are untouched by the checked arithmetic, including
20913        // the timezone, so the guard cannot have been bought with a behavior
20914        // change on the normal path.
20915        let unchanged = ts.replace(
20916            Some(1999),
20917            Some(6),
20918            Some(30),
20919            Some(12),
20920            Some(1),
20921            Some(2),
20922            Some(3),
20923            Some(4),
20924        );
20925        assert_eq!(unchanged.year(), Some(1999));
20926        assert_eq!(unchanged.month(), Some(6));
20927        assert_eq!(unchanged.day(), Some(30));
20928        assert_eq!(unchanged.hour(), Some(12));
20929        assert_eq!(unchanged.minute(), Some(1));
20930        assert_eq!(unchanged.second(), Some(2));
20931        assert_eq!(unchanged.microsecond(), Some(3));
20932        assert_eq!(unchanged.nanosecond(), Some(4));
20933        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20934        assert_eq!(
20935            tz.replace(Some(1999), None, None, None, None, None, None, None)
20936                .tz
20937                .as_deref(),
20938            Some("UTC")
20939        );
20940    }
20941
20942    #[test]
20943    fn timestamp_component_accessors() {
20944        let ts = Timestamp::from_nanos(0);
20945        assert_eq!(ts.year(), Some(1970));
20946        assert_eq!(ts.month(), Some(1));
20947        assert_eq!(ts.day(), Some(1));
20948        assert_eq!(ts.hour(), Some(0));
20949        assert_eq!(ts.minute(), Some(0));
20950        assert_eq!(ts.second(), Some(0));
20951        assert_eq!(ts.microsecond(), Some(0));
20952        assert_eq!(ts.nanosecond(), Some(0));
20953
20954        let ts2 = Timestamp::from_nanos(
20955            Timedelta::NANOS_PER_DAY * 365
20956                + Timedelta::NANOS_PER_HOUR * 14
20957                + Timedelta::NANOS_PER_MIN * 30
20958                + Timedelta::NANOS_PER_SEC * 45
20959                + 123_456_789,
20960        );
20961        assert_eq!(ts2.year(), Some(1971));
20962        assert_eq!(ts2.month(), Some(1));
20963        assert_eq!(ts2.day(), Some(1));
20964        assert_eq!(ts2.hour(), Some(14));
20965        assert_eq!(ts2.minute(), Some(30));
20966        assert_eq!(ts2.second(), Some(45));
20967        assert_eq!(ts2.microsecond(), Some(123456));
20968        assert_eq!(ts2.nanosecond(), Some(789));
20969
20970        assert_eq!(Timestamp::nat().year(), None);
20971        assert_eq!(Timestamp::nat().month(), None);
20972        assert_eq!(Timestamp::nat().day(), None);
20973    }
20974
20975    #[test]
20976    fn timestamp_dayofweek_dayofyear_quarter() {
20977        let ts = Timestamp::from_nanos(0);
20978        assert_eq!(ts.dayofweek(), Some(3));
20979        assert_eq!(ts.weekday(), Some(3));
20980        assert_eq!(ts.dayofyear(), Some(1));
20981        assert_eq!(ts.quarter(), Some(1));
20982
20983        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
20984        assert_eq!(ts2.quarter(), Some(2));
20985
20986        let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20987        assert_eq!(ts3.dayofyear(), Some(1));
20988        assert_eq!(ts3.dayofweek(), Some(4));
20989
20990        assert_eq!(Timestamp::nat().dayofweek(), None);
20991        assert_eq!(Timestamp::nat().dayofyear(), None);
20992        assert_eq!(Timestamp::nat().quarter(), None);
20993    }
20994
20995    #[test]
20996    fn timestamp_is_boundary_methods() {
20997        let jan1 = Timestamp::from_nanos(0);
20998        assert_eq!(jan1.is_leap_year(), Some(false));
20999        assert_eq!(jan1.is_month_start(), Some(true));
21000        assert_eq!(jan1.is_month_end(), Some(false));
21001        assert_eq!(jan1.is_quarter_start(), Some(true));
21002        assert_eq!(jan1.is_quarter_end(), Some(false));
21003        assert_eq!(jan1.is_year_start(), Some(true));
21004        assert_eq!(jan1.is_year_end(), Some(false));
21005
21006        let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
21007        assert_eq!(dec31.is_month_start(), Some(false));
21008        assert_eq!(dec31.is_month_end(), Some(true));
21009        assert_eq!(dec31.is_quarter_end(), Some(true));
21010        assert_eq!(dec31.is_year_end(), Some(true));
21011
21012        assert_eq!(Timestamp::nat().is_leap_year(), None);
21013        assert_eq!(Timestamp::nat().is_month_start(), None);
21014    }
21015
21016    #[test]
21017    fn timestamp_days_in_month() {
21018        let jan = Timestamp::from_nanos(0);
21019        assert_eq!(jan.days_in_month(), Some(31));
21020        assert_eq!(jan.daysinmonth(), Some(31));
21021
21022        let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
21023        assert_eq!(feb_non_leap.days_in_month(), Some(28));
21024
21025        assert_eq!(Timestamp::nat().days_in_month(), None);
21026    }
21027
21028    #[test]
21029    fn timestamp_weekofyear() {
21030        let jan1 = Timestamp::from_nanos(0);
21031        assert_eq!(jan1.weekofyear(), Some(1));
21032        assert_eq!(jan1.week(), Some(1));
21033
21034        let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
21035        assert_eq!(jan8.weekofyear(), Some(2));
21036
21037        assert_eq!(Timestamp::nat().weekofyear(), None);
21038        assert_eq!(Timestamp::nat().week(), None);
21039    }
21040
21041    #[test]
21042    fn timestamp_weekofyear_iso_53_week_boundaries() {
21043        // ISO-8601 53-week-year boundaries vs pandas 2.2.3 isocalendar().week.
21044        // (br-frankenpandas-xmfmd) Date -> nanos via days since 1970-01-01.
21045        fn week_of(date_days: i64) -> Option<i64> {
21046            Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
21047        }
21048        // Days from 1970-01-01 for each date (UTC, no tz).
21049        // 2021-01-01 -> week 53 (2020 is a 53-week year); FP used to give 52.
21050        assert_eq!(week_of(18_628), Some(53)); // 2021-01-01
21051        // 2016-01-01 -> week 53 (2015 is a 53-week year).
21052        assert_eq!(week_of(16_801), Some(53)); // 2016-01-01
21053        // 2026-12-31 -> week 53; FP used to give 1.
21054        assert_eq!(week_of(20_818), Some(53)); // 2026-12-31
21055        // 2020-12-31 -> week 53.
21056        assert_eq!(week_of(18_627), Some(53)); // 2020-12-31
21057        // Cases that must stay correct (non-53 boundaries):
21058        assert_eq!(week_of(19_358), Some(52)); // 2023-01-01 -> week 52
21059        assert_eq!(week_of(20_087), Some(1)); // 2024-12-30 -> week 1
21060        assert_eq!(week_of(18_260), Some(1)); // 2019-12-30 -> week 1
21061    }
21062
21063    #[test]
21064    fn iso_weeks_in_year_53_week_years() {
21065        use super::iso_weeks_in_year;
21066        // Known 53-week years; everything else is 52.
21067        for y in [2004, 2009, 2015, 2020, 2026] {
21068            assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
21069        }
21070        for y in [2018, 2019, 2021, 2022, 2023, 2024] {
21071            assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
21072        }
21073    }
21074
21075    #[test]
21076    fn timestamp_to_unit() {
21077        let ts = Timestamp::from_nanos(1_000_000_000);
21078        assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
21079        assert_eq!(ts.to_unit("us"), Some(1_000_000));
21080        assert_eq!(ts.to_unit("ms"), Some(1_000));
21081        assert_eq!(ts.to_unit("s"), Some(1));
21082        assert_eq!(ts.to_unit("invalid"), None);
21083
21084        assert_eq!(Timestamp::nat().to_unit("ns"), None);
21085    }
21086
21087    #[test]
21088    fn timestamp_toordinal() {
21089        // 2026-01-01 is ordinal 738886 (days since Jan 1, year 1)
21090        // Days from Unix epoch: 738886 - 719163 = 19723
21091        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
21092        let ts = Timestamp::from_nanos(nanos_2026_01_01);
21093        assert_eq!(ts.toordinal(), Some(738886));
21094
21095        // NaT returns None
21096        assert_eq!(Timestamp::nat().toordinal(), None);
21097    }
21098
21099    #[test]
21100    fn timestamp_fromordinal() {
21101        // Round-trip test: create a timestamp from ordinal derived from toordinal
21102        // First create a known timestamp
21103        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
21104        let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
21105        let ordinal = ts_orig.toordinal().unwrap();
21106
21107        // Now convert back using fromordinal
21108        let ts = Timestamp::fromordinal(ordinal);
21109        assert_eq!(ts.year(), ts_orig.year());
21110        assert_eq!(ts.month(), ts_orig.month());
21111        assert_eq!(ts.day(), ts_orig.day());
21112
21113        // Invalid ordinal returns NaT
21114        let nat = Timestamp::fromordinal(0);
21115        assert!(nat.is_nat());
21116    }
21117
21118    #[test]
21119    fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
21120        const EPOCH_ORDINAL: i64 = 719_163;
21121        let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
21122        let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
21123
21124        let max_valid = Timestamp::fromordinal(max_valid_ordinal);
21125        assert!(!max_valid.is_nat());
21126        assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
21127
21128        assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
21129        assert!(Timestamp::fromordinal(i64::MAX).is_nat());
21130    }
21131
21132    #[test]
21133    fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
21134        const EPOCH_ORDINAL: i64 = 719_163;
21135        const DAY: i64 = Timedelta::NANOS_PER_DAY;
21136
21137        fn next(seed: &mut u64) -> u64 {
21138            *seed = seed
21139                .wrapping_mul(3202034522624059733)
21140                .wrapping_add(4354685564936845319);
21141            *seed
21142        }
21143
21144        fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
21145            let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
21146            let ts = Timestamp::from_nanos(nanos);
21147            let expected_day_offset = nanos.div_euclid(DAY);
21148            let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
21149
21150            assert_eq!(
21151                ts.toordinal(),
21152                Some(expected_ordinal),
21153                "case {case}: toordinal"
21154            );
21155
21156            let midnight = Timestamp::fromordinal(expected_ordinal);
21157            assert_eq!(
21158                midnight.nanos,
21159                expected_day_offset * DAY,
21160                "case {case}: fromordinal nanos"
21161            );
21162            assert_eq!(
21163                midnight.toordinal(),
21164                Some(expected_ordinal),
21165                "case {case}: fromordinal roundtrip"
21166            );
21167        }
21168
21169        assert_eq!(Timestamp::nat().toordinal(), None);
21170        assert!(Timestamp::fromordinal(0).is_nat());
21171        assert!(Timestamp::fromordinal(-1).is_nat());
21172
21173        assert_ordinal_case(usize::MAX, -1, DAY - 1);
21174        assert_ordinal_case(usize::MAX - 1, 0, -1);
21175        assert_ordinal_case(usize::MAX - 2, 19_723, 0);
21176
21177        let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
21178        for case in 0..260 {
21179            let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
21180            let subday_nanos = match case % 7 {
21181                0 => 0,
21182                1 => DAY - 1,
21183                2 => -1,
21184                _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
21185            };
21186            assert_ordinal_case(case, day_offset, subday_nanos);
21187        }
21188    }
21189
21190    /// br-frankenpandas-94o1u: `parse_date` bounds the month and the day but
21191    /// parses the YEAR as an unbounded i64, and i64 nanoseconds top out around
21192    /// 2262. The old unchecked composition wrapped in release, so these inputs
21193    /// returned `Ok` holding a plausible in-range instant instead of failing —
21194    /// on the INGESTION path, where the input is untrusted. Each case below is
21195    /// a real negative case: a naive implementation still returns Ok here.
21196    #[test]
21197    fn timestamp_parse_rejects_unrepresentable_years_94o1u() {
21198        for s in [
21199            "300000-01-01",
21200            "10000000-06-15T12:30:45",
21201            "999999999-01-01",
21202            "-300000-01-01",
21203            "-99999999-12-31T23:59:59",
21204        ] {
21205            let got = Timestamp::parse(s);
21206            assert!(
21207                got.is_err(),
21208                "parse({s:?}) is unrepresentable in i64 ns and must be Err, got {:?} \
21209                 — this is the silent wrap",
21210                got.map(|ts| (ts.nanos, ts.year()))
21211            );
21212        }
21213
21214        // Boundary: the i64 ns axis reaches into 2262 but not 2263. Pins the
21215        // guard to the real limit — a cutoff at some rounder year fails a side.
21216        let ok = Timestamp::parse("2262-01-01").expect("2262-01-01 is representable");
21217        assert_eq!(ok.year(), Some(2262));
21218        assert!(
21219            Timestamp::parse("2263-12-31T23:59:59").is_err(),
21220            "end of 2263 exceeds the i64 ns axis and must be Err"
21221        );
21222
21223        // A rejected year must not poison the normal path: ordinary parses,
21224        // including every accepted shape (date-only, T- and space-separated,
21225        // fractional seconds, tz suffix), still succeed and are unchanged.
21226        assert_eq!(Timestamp::parse("2024-01-15").unwrap().year(), Some(2024));
21227        assert_eq!(
21228            Timestamp::parse("2024-01-15T10:30:45").unwrap().hour(),
21229            Some(10)
21230        );
21231        assert_eq!(
21232            Timestamp::parse("2024-01-15 10:30:45").unwrap().minute(),
21233            Some(30)
21234        );
21235        assert_eq!(
21236            Timestamp::parse("2024-01-15T10:30:45.123456789")
21237                .unwrap()
21238                .nanosecond(),
21239            Some(789)
21240        );
21241        assert_eq!(
21242            Timestamp::parse("2024-01-15T00:00:00Z").unwrap().year(),
21243            Some(2024)
21244        );
21245        // Pre-epoch (negative nanos) is representable and must keep working.
21246        assert_eq!(Timestamp::parse("1900-01-01").unwrap().year(), Some(1900));
21247    }
21248
21249    #[test]
21250    fn timestamp_parse_iso8601_date_only() {
21251        let ts = Timestamp::parse("2024-01-15").unwrap();
21252        assert_eq!(ts.year(), Some(2024));
21253        assert_eq!(ts.month(), Some(1));
21254        assert_eq!(ts.day(), Some(15));
21255        assert_eq!(ts.hour(), Some(0));
21256        assert_eq!(ts.minute(), Some(0));
21257        assert_eq!(ts.second(), Some(0));
21258    }
21259
21260    #[test]
21261    fn timestamp_parse_iso8601_datetime() {
21262        let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
21263        assert_eq!(ts.year(), Some(2024));
21264        assert_eq!(ts.month(), Some(1));
21265        assert_eq!(ts.day(), Some(15));
21266        assert_eq!(ts.hour(), Some(10));
21267        assert_eq!(ts.minute(), Some(30));
21268        assert_eq!(ts.second(), Some(45));
21269    }
21270
21271    #[test]
21272    fn timestamp_parse_space_separator() {
21273        let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
21274        assert_eq!(ts.year(), Some(2024));
21275        assert_eq!(ts.hour(), Some(10));
21276    }
21277
21278    #[test]
21279    fn timestamp_parse_with_fractional_seconds() {
21280        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
21281        assert_eq!(ts.second(), Some(45));
21282        assert_eq!(ts.microsecond(), Some(123456));
21283        assert_eq!(ts.nanosecond(), Some(789));
21284    }
21285
21286    #[test]
21287    fn timestamp_parse_utc_timezone() {
21288        let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
21289        assert_eq!(ts.tz, Some("UTC".to_string()));
21290    }
21291
21292    #[test]
21293    fn timestamp_parse_offset_timezone() {
21294        let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
21295        assert_eq!(ts.tz, Some("+05:30".to_string()));
21296        // The instant is the wall time less the offset (it was the wall
21297        // time read as UTC).
21298        let utc = |text: &str| Timestamp::parse(text).unwrap().nanos;
21299        assert_eq!(ts.nanos, utc("2024-01-15T05:00:45"));
21300
21301        let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
21302        assert_eq!(ts.tz, Some("-05:30".to_string()));
21303        assert_eq!(ts.nanos, utc("2024-01-15T16:00:45"));
21304        // 'Z' is UTC itself.
21305        assert_eq!(
21306            Timestamp::parse("2024-01-15T10:30:45Z").unwrap().nanos,
21307            utc("2024-01-15T10:30:45")
21308        );
21309    }
21310
21311    #[test]
21312    fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
21313        assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
21314        assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
21315        assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
21316        assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
21317        assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
21318    }
21319
21320    #[test]
21321    fn timestamp_parse_nat() {
21322        let ts = Timestamp::parse("NaT").unwrap();
21323        assert!(ts.is_nat());
21324        let ts2 = Timestamp::parse("nat").unwrap();
21325        assert!(ts2.is_nat());
21326    }
21327
21328    #[test]
21329    fn timestamp_parse_invalid() {
21330        assert!(Timestamp::parse("not a date").is_err());
21331        assert!(Timestamp::parse("2024-13-01").is_err()); // invalid month
21332        assert!(Timestamp::parse("2024-01-32").is_err()); // invalid day
21333    }
21334
21335    #[test]
21336    fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
21337        assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
21338        assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
21339        assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
21340        assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
21341        assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
21342
21343        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
21344        assert_eq!(ts.second(), Some(45));
21345        assert_eq!(ts.microsecond(), Some(123456));
21346        assert_eq!(ts.nanosecond(), Some(789));
21347    }
21348
21349    #[test]
21350    #[ignore = "foreground profile-first A/B"]
21351    fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
21352        use std::{hint::black_box, time::Instant};
21353
21354        const CALLS: usize = 131_072;
21355        const SAMPLES: usize = 12;
21356        type ParsedTime = Option<(u32, u32, u32, u64)>;
21357        const VALID: [&str; 16] = [
21358            "00:00:00.0",
21359            "01:02:03.1",
21360            "02:03:04.01",
21361            "03:04:05.001",
21362            "04:05:06.0001",
21363            "05:06:07.00001",
21364            "06:07:08.000001",
21365            "07:08:09.0000001",
21366            "08:09:10.00000001",
21367            "09:10:11.000000001",
21368            "10:11:12.123456789",
21369            "11:12:13.999999999",
21370            "12:13:14.123456789987",
21371            "13:14:15.000000000001",
21372            "14:15:16.101010101010",
21373            "23:59:59.987654321234",
21374        ];
21375
21376        #[inline(never)]
21377        fn former(s: &str) -> ParsedTime {
21378            let (time_str, frac_str) = match s.split_once('.') {
21379                Some((time, frac)) => (time, Some(frac)),
21380                None => (s, None),
21381            };
21382            let parts: Vec<&str> = time_str.split(':').collect();
21383            if parts.is_empty() || parts.len() > 3 {
21384                return None;
21385            }
21386            let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
21387            let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
21388            let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
21389
21390            if hour > 23 || minute > 59 || second > 59 {
21391                return None;
21392            }
21393
21394            let nanos = match frac_str {
21395                None => 0,
21396                Some(frac) => {
21397                    if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
21398                        return None;
21399                    }
21400                    let truncated = &frac[..frac.len().min(9)];
21401                    let padded = format!("{truncated:0<9}");
21402                    padded.parse::<u64>().ok()?
21403                }
21404            };
21405
21406            Some((hour, minute, second, nanos))
21407        }
21408
21409        #[inline(never)]
21410        fn candidate(s: &str) -> ParsedTime {
21411            Timestamp::parse_time(s)
21412        }
21413
21414        fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
21415            let started = Instant::now();
21416            for input in black_box(inputs) {
21417                black_box(parser(black_box(*input)));
21418            }
21419            started.elapsed().as_nanos()
21420        }
21421
21422        fn percentile(samples: &[u128], percent: usize) -> u128 {
21423            let mut sorted = samples.to_vec();
21424            sorted.sort_unstable();
21425            let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
21426            sorted[rank]
21427        }
21428
21429        let invalid = [
21430            "",
21431            "24:00:00.1",
21432            "12:60:00.1",
21433            "12:00:60.1",
21434            "12:00:00.",
21435            "12:00:00.abc",
21436            "12:00:00.-1",
21437            "12:00:00.123",
21438            "12:00:00.123456789x",
21439            "12:00:00.1.2",
21440            "12:00:00:01.1",
21441        ];
21442        for input in VALID.iter().chain(invalid.iter()) {
21443            assert_eq!(candidate(input), former(input), "input={input:?}");
21444        }
21445
21446        let inputs = (0..CALLS)
21447            .map(|index| VALID[index % VALID.len()])
21448            .collect::<Vec<_>>();
21449        for _ in 0..2 {
21450            black_box(elapsed(&inputs, former));
21451            black_box(elapsed(&inputs, candidate));
21452        }
21453
21454        let mut former_ns = Vec::with_capacity(SAMPLES);
21455        let mut candidate_ns = Vec::with_capacity(SAMPLES);
21456        for sample in 0..SAMPLES {
21457            if sample.is_multiple_of(2) {
21458                former_ns.push(elapsed(&inputs, former));
21459                candidate_ns.push(elapsed(&inputs, candidate));
21460            } else {
21461                candidate_ns.push(elapsed(&inputs, candidate));
21462                former_ns.push(elapsed(&inputs, former));
21463            }
21464        }
21465
21466        let former_p50 = percentile(&former_ns, 50);
21467        let former_p95 = percentile(&former_ns, 95);
21468        let former_p99 = percentile(&former_ns, 99);
21469        let candidate_p50 = percentile(&candidate_ns, 50);
21470        let candidate_p95 = percentile(&candidate_ns, 95);
21471        let candidate_p99 = percentile(&candidate_ns, 99);
21472        println!(
21473            "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:?}",
21474            former_p50 as f64 / candidate_p50 as f64,
21475            former_p95 as f64 / candidate_p95 as f64,
21476            former_p99 as f64 / candidate_p99 as f64,
21477        );
21478    }
21479
21480    #[test]
21481    fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
21482        fn next(seed: &mut u64) -> u64 {
21483            *seed = seed
21484                .wrapping_mul(3935559000370003845)
21485                .wrapping_add(2691343689449507681);
21486            *seed
21487        }
21488
21489        fn leap(year: i64) -> bool {
21490            (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
21491        }
21492
21493        fn month_len(year: i64, month: u32) -> u32 {
21494            match month {
21495                1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
21496                4 | 6 | 9 | 11 => 30,
21497                2 if leap(year) => 29,
21498                2 => 28,
21499                _ => 0,
21500            }
21501        }
21502
21503        struct Components {
21504            year: i64,
21505            month: u32,
21506            day: u32,
21507            hour: u32,
21508            minute: u32,
21509            second: u32,
21510            nanos: u64,
21511        }
21512
21513        fn assert_components(case: usize, text: &str, expected: Components) {
21514            let ts = Timestamp::parse(text).expect("seeded valid timestamp");
21515            let Components {
21516                year,
21517                month,
21518                day,
21519                hour,
21520                minute,
21521                second,
21522                nanos,
21523            } = expected;
21524            assert_eq!(ts.year(), Some(year), "case {case}: year");
21525            assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
21526            assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
21527            assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
21528            assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
21529            assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
21530            assert_eq!(
21531                ts.microsecond(),
21532                Some((nanos / 1000) as i64),
21533                "case {case}: microsecond"
21534            );
21535            assert_eq!(
21536                ts.nanosecond(),
21537                Some((nanos % 1000) as i64),
21538                "case {case}: nanosecond"
21539            );
21540        }
21541
21542        assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
21543        assert!(
21544            Timestamp::parse("nAt")
21545                .expect("mixed-case NaT parses")
21546                .is_nat()
21547        );
21548        assert!(Timestamp::parse("1900-02-29").is_err());
21549        assert!(Timestamp::parse("2001-04-31").is_err());
21550        assert!(Timestamp::parse("2024-00-15").is_err());
21551
21552        assert_components(
21553            usize::MAX,
21554            "2000-02-29",
21555            Components {
21556                year: 2000,
21557                month: 2,
21558                day: 29,
21559                hour: 0,
21560                minute: 0,
21561                second: 0,
21562                nanos: 0,
21563            },
21564        );
21565        assert_components(
21566            usize::MAX - 1,
21567            "2024-02-29T23:59:59.000000001",
21568            Components {
21569                year: 2024,
21570                month: 2,
21571                day: 29,
21572                hour: 23,
21573                minute: 59,
21574                second: 59,
21575                nanos: 1,
21576            },
21577        );
21578
21579        let mut seed = 0x15e0_1d50_1f0a_cade_u64;
21580        for case in 0..260 {
21581            let year = 1900 + (next(&mut seed) % 201) as i64;
21582            let month = 1 + (next(&mut seed) % 12) as u32;
21583            let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
21584            let hour = (next(&mut seed) % 24) as u32;
21585            let minute = (next(&mut seed) % 60) as u32;
21586            let second = (next(&mut seed) % 60) as u32;
21587            let nanos = next(&mut seed) % 1_000_000_000;
21588
21589            match case % 4 {
21590                0 => {
21591                    let text = format!("{year:04}-{month:02}-{day:02}");
21592                    assert_components(
21593                        case,
21594                        &text,
21595                        Components {
21596                            year,
21597                            month,
21598                            day,
21599                            hour: 0,
21600                            minute: 0,
21601                            second: 0,
21602                            nanos: 0,
21603                        },
21604                    );
21605                }
21606                1 => {
21607                    let text =
21608                        format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
21609                    assert_components(
21610                        case,
21611                        &text,
21612                        Components {
21613                            year,
21614                            month,
21615                            day,
21616                            hour,
21617                            minute,
21618                            second,
21619                            nanos: 0,
21620                        },
21621                    );
21622                }
21623                2 => {
21624                    let text =
21625                        format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
21626                    assert_components(
21627                        case,
21628                        &text,
21629                        Components {
21630                            year,
21631                            month,
21632                            day,
21633                            hour,
21634                            minute,
21635                            second,
21636                            nanos: 0,
21637                        },
21638                    );
21639                }
21640                _ => {
21641                    let text = format!(
21642                        "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
21643                    );
21644                    assert_components(
21645                        case,
21646                        &text,
21647                        Components {
21648                            year,
21649                            month,
21650                            day,
21651                            hour,
21652                            minute,
21653                            second,
21654                            nanos,
21655                        },
21656                    );
21657                }
21658            }
21659        }
21660    }
21661
21662    #[test]
21663    fn period_parse_annual() {
21664        let p = Period::parse("2024").unwrap();
21665        assert_eq!(p.freq(), PeriodFreq::ANNUAL);
21666        assert_eq!(p.ordinal(), 2024 - 1970);
21667    }
21668
21669    #[test]
21670    fn period_parse_quarterly() {
21671        let p = Period::parse("2024Q1").unwrap();
21672        assert_eq!(p.freq(), PeriodFreq::QUARTERLY);
21673        assert_eq!(p.ordinal(), (2024 - 1970) * 4);
21674
21675        let p2 = Period::parse("2024q3").unwrap();
21676        assert_eq!(p2.freq(), PeriodFreq::QUARTERLY);
21677        assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
21678    }
21679
21680    #[test]
21681    fn period_parse_monthly() {
21682        let p = Period::parse("2024-01").unwrap();
21683        assert_eq!(p.freq(), PeriodFreq::Monthly);
21684        assert_eq!(p.ordinal(), (2024 - 1970) * 12);
21685
21686        let p2 = Period::parse("2024-12").unwrap();
21687        assert_eq!(p2.freq(), PeriodFreq::Monthly);
21688        assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
21689    }
21690
21691    #[test]
21692    fn period_parse_nat() {
21693        let p = Period::parse("NaT").unwrap();
21694        assert_eq!(p.ordinal(), i64::MIN);
21695    }
21696
21697    #[test]
21698    fn period_parse_invalid() {
21699        assert!(Period::parse("not a period").is_err());
21700        assert!(Period::parse("2024Q5").is_err()); // invalid quarter
21701        assert!(Period::parse("2024-13").is_err()); // invalid month
21702    }
21703
21704    #[test]
21705    fn interval_parse_basic() {
21706        let i = Interval::parse("[0, 1]").unwrap();
21707        assert_eq!(i.left, 0.0);
21708        assert_eq!(i.right, 1.0);
21709        assert_eq!(i.closed, IntervalClosed::Both);
21710
21711        let i2 = Interval::parse("(0, 1)").unwrap();
21712        assert_eq!(i2.left, 0.0);
21713        assert_eq!(i2.right, 1.0);
21714        assert_eq!(i2.closed, IntervalClosed::Neither);
21715
21716        let i3 = Interval::parse("[0, 1)").unwrap();
21717        assert_eq!(i3.closed, IntervalClosed::Left);
21718
21719        let i4 = Interval::parse("(0, 1]").unwrap();
21720        assert_eq!(i4.closed, IntervalClosed::Right);
21721    }
21722
21723    #[test]
21724    fn interval_parse_floats() {
21725        let i = Interval::parse("[-1.5, 2.5)").unwrap();
21726        assert_eq!(i.left, -1.5);
21727        assert_eq!(i.right, 2.5);
21728        assert_eq!(i.closed, IntervalClosed::Left);
21729    }
21730
21731    #[test]
21732    fn interval_parse_invalid() {
21733        assert!(Interval::parse("invalid").is_err());
21734        assert!(Interval::parse("[0]").is_err());
21735        assert!(Interval::parse("0, 1").is_err()); // missing brackets
21736    }
21737
21738    fn interval_parse_error_profile(s: &str) -> super::TypeError {
21739        super::TypeError::ValueNotParseable {
21740            value: s.to_string(),
21741            target: "Interval".to_string(),
21742        }
21743    }
21744
21745    #[inline(never)]
21746    fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
21747        let s = std::hint::black_box(s).trim();
21748        if s.len() < 5 {
21749            return Err(interval_parse_error_profile(s));
21750        }
21751
21752        let first_char = s.chars().next().unwrap();
21753        let last_char = s.chars().last().unwrap();
21754        let left_closed = match first_char {
21755            '[' => true,
21756            '(' => false,
21757            _ => return Err(interval_parse_error_profile(s)),
21758        };
21759        let right_closed = match last_char {
21760            ']' => true,
21761            ')' => false,
21762            _ => return Err(interval_parse_error_profile(s)),
21763        };
21764        let closed = match (left_closed, right_closed) {
21765            (true, true) => IntervalClosed::Both,
21766            (true, false) => IntervalClosed::Left,
21767            (false, true) => IntervalClosed::Right,
21768            (false, false) => IntervalClosed::Neither,
21769        };
21770
21771        let inner = &s[1..s.len() - 1];
21772        let parts: Vec<&str> = inner.split(',').collect();
21773        if parts.len() != 2 {
21774            return Err(interval_parse_error_profile(s));
21775        }
21776        let left = parts[0]
21777            .trim()
21778            .parse()
21779            .map_err(|_| interval_parse_error_profile(s))?;
21780        let right = parts[1]
21781            .trim()
21782            .parse()
21783            .map_err(|_| interval_parse_error_profile(s))?;
21784        Ok(Interval::new(left, right, closed))
21785    }
21786
21787    #[inline(never)]
21788    fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
21789        Interval::parse(std::hint::black_box(s))
21790    }
21791
21792    fn assert_interval_parse_profile_parity(s: &str) {
21793        match (
21794            interval_parse_former_profile(s),
21795            interval_parse_split_once_profile(s),
21796        ) {
21797            (Ok(former), Ok(candidate)) => {
21798                assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
21799                assert_eq!(
21800                    former.right.to_bits(),
21801                    candidate.right.to_bits(),
21802                    "right: {s}"
21803                );
21804                assert_eq!(former.closed, candidate.closed, "closed: {s}");
21805            }
21806            (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
21807            (former, candidate) => assert_eq!(
21808                former.is_ok(),
21809                candidate.is_ok(),
21810                "parse result mismatch for {s}: {former:?} != {candidate:?}"
21811            ),
21812        }
21813    }
21814
21815    #[inline(never)]
21816    fn measure_interval_parser_profile(
21817        parser: fn(&str) -> Result<Interval, super::TypeError>,
21818        inputs: &[&str],
21819        rounds: usize,
21820    ) -> u128 {
21821        use std::{hint::black_box, time::Instant};
21822
21823        let started = Instant::now();
21824        let mut checksum = 0_u64;
21825        for _ in 0..rounds {
21826            for input in inputs {
21827                let parsed = parser(black_box(input)).expect("profile input must parse");
21828                let closed = match parsed.closed {
21829                    IntervalClosed::Left => 1_u64,
21830                    IntervalClosed::Right => 2,
21831                    IntervalClosed::Both => 3,
21832                    IntervalClosed::Neither => 4,
21833                };
21834                checksum = checksum
21835                    .wrapping_add(parsed.left.to_bits().rotate_left(7))
21836                    .wrapping_add(parsed.right.to_bits().rotate_right(11))
21837                    .wrapping_add(closed);
21838                black_box(parsed);
21839            }
21840        }
21841        black_box(checksum);
21842        started.elapsed().as_nanos()
21843    }
21844
21845    #[test]
21846    #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
21847    fn profile_interval_parse_endpoint_split_ab_81jjv() {
21848        const VALID: [&str; 8] = [
21849            "[0, 1]",
21850            "(-0.0, 0.0]",
21851            " [ -1.5e3 , 2.75E-4 ) ",
21852            "(NaN, -0]",
21853            "[-inf, inf)",
21854            "[9.25, -7.5]",
21855            "(4.9406564584124654e-324, 1.7976931348623157e308)",
21856            "[-42, 17.125)",
21857        ];
21858        const INVALID: [&str; 12] = [
21859            "invalid",
21860            "[0]",
21861            "0, 1",
21862            "[0 1]",
21863            "[0, 1, 2]",
21864            "[0, 1,]",
21865            "[0,,1]",
21866            "[, 1]",
21867            "[0, ]",
21868            "{0, 1}",
21869            "[0, 1}",
21870            "  ⟦0, 1⟧  ",
21871        ];
21872        const ROUNDS: usize = 16_384;
21873        const SAMPLES: usize = 10;
21874
21875        for input in VALID.iter().chain(INVALID.iter()) {
21876            assert_interval_parse_profile_parity(input);
21877        }
21878        for _ in 0..2 {
21879            measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
21880            measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
21881        }
21882
21883        let mut former_ns = Vec::with_capacity(SAMPLES);
21884        let mut candidate_ns = Vec::with_capacity(SAMPLES);
21885        for sample in 0..SAMPLES {
21886            if sample % 2 == 0 {
21887                former_ns.push(measure_interval_parser_profile(
21888                    interval_parse_former_profile,
21889                    &VALID,
21890                    ROUNDS,
21891                ));
21892                candidate_ns.push(measure_interval_parser_profile(
21893                    interval_parse_split_once_profile,
21894                    &VALID,
21895                    ROUNDS,
21896                ));
21897            } else {
21898                candidate_ns.push(measure_interval_parser_profile(
21899                    interval_parse_split_once_profile,
21900                    &VALID,
21901                    ROUNDS,
21902                ));
21903                former_ns.push(measure_interval_parser_profile(
21904                    interval_parse_former_profile,
21905                    &VALID,
21906                    ROUNDS,
21907                ));
21908            }
21909        }
21910        former_ns.sort_unstable();
21911        candidate_ns.sort_unstable();
21912        let former_p50 = former_ns[SAMPLES / 2];
21913        let candidate_p50 = candidate_ns[SAMPLES / 2];
21914        let former_p95 = former_ns[SAMPLES - 1];
21915        let candidate_p95 = candidate_ns[SAMPLES - 1];
21916        println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
21917        println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
21918        println!(
21919            "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
21920            former_p50 as f64 / candidate_p50 as f64
21921        );
21922        println!(
21923            "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
21924            former_p95 as f64 / candidate_p95 as f64
21925        );
21926    }
21927}
21928
21929/// `DType::Float64Nullable` — pandas' `Float64Dtype()`, the dtype a nullable
21930/// Int64 lane widens INTO (br-frankenpandas-qkqfb).
21931///
21932/// Every rule asserted here was measured against live pandas 2.2.3 before it was
21933/// written; the measurement is quoted next to the assertion it justifies.
21934#[cfg(test)]
21935mod float64_nullable_qkqfb {
21936    use super::{DType, NullKind, Scalar, cast_scalar, common_dtype};
21937
21938    /// THE POINT OF THE DTYPE. A numpy float lane's missing value is a real NaN;
21939    /// the extension lane's is pd.NA. If both mapped to the same marker the two
21940    /// flavours would be indistinguishable and the dtype would buy nothing.
21941    ///
21942    /// MEASURED, live pandas 2.2.3:
21943    /// ```text
21944    ///   pd.Series([1.5, None], dtype="Float64")[1]     -> <NA>   (is pd.NA)
21945    ///   pd.Series([1.5, None])[1]                      -> nan
21946    ///   pd.Series([float("nan")], dtype="Float64")[0]  -> <NA>   COERCED
21947    /// ```
21948    #[test]
21949    fn the_two_float_flavours_have_different_missing_markers_qkqfb() {
21950        assert_eq!(
21951            Scalar::missing_for_dtype(DType::Float64Nullable),
21952            Scalar::Null(NullKind::Null),
21953            "the extension lane stores pd.NA"
21954        );
21955        assert_eq!(
21956            Scalar::missing_for_dtype(DType::Float64),
21957            Scalar::Null(NullKind::NaN),
21958            "the numpy lane stores a real NaN"
21959        );
21960        // The negative case: collapsing these two is precisely the defect, so
21961        // assert they are NOT equal rather than only asserting each value.
21962        assert_ne!(
21963            Scalar::missing_for_dtype(DType::Float64Nullable),
21964            Scalar::missing_for_dtype(DType::Float64),
21965        );
21966    }
21967
21968    /// MEASURED: `str(pd.Float64Dtype())` is `"Float64"`, and the numpy dtype is
21969    /// `"float64"`. dtype-check fixtures assert pandas' SPELLING
21970    /// (br-frankenpandas-62d1s), so the capital F is load-bearing, not cosmetic.
21971    #[test]
21972    fn spelling_is_pandas_spelling_qkqfb() {
21973        assert_eq!(DType::Float64Nullable.name(), "Float64");
21974        assert_eq!(DType::Float64.name(), "float64");
21975        assert_ne!(DType::Float64Nullable.name(), DType::Float64.name());
21976    }
21977
21978    /// The serde spelling has to survive a round trip AND stay distinct from the
21979    /// numpy flavour. `rename_all = "snake_case"` turns `Float64` into
21980    /// `"float64"`, which is what leaves `"Float64"` free for the extension —
21981    /// the same trick `Int64Nullable` already relies on. A naive
21982    /// `#[serde(rename = "Float64")]` on the WRONG variant would collide, and
21983    /// this test is what would catch it.
21984    #[test]
21985    fn serde_round_trips_and_does_not_collide_with_numpy_float64_qkqfb() {
21986        let ext = serde_json::to_string(&DType::Float64Nullable).expect("serialize");
21987        let numpy = serde_json::to_string(&DType::Float64).expect("serialize");
21988        assert_eq!(ext, "\"Float64\"");
21989        assert_eq!(numpy, "\"float64\"");
21990        assert_ne!(ext, numpy);
21991
21992        assert_eq!(
21993            serde_json::from_str::<DType>(&ext).expect("deserialize"),
21994            DType::Float64Nullable
21995        );
21996        assert_eq!(
21997            serde_json::from_str::<DType>(&numpy).expect("deserialize"),
21998            DType::Float64
21999        );
22000    }
22001
22002    /// It is a float, it is numeric, and it is a nullable extension — all three,
22003    /// or downstream dtype dispatch silently skips it.
22004    #[test]
22005    fn predicates_place_it_in_the_right_families_qkqfb() {
22006        assert!(DType::Float64Nullable.is_floating());
22007        assert!(DType::Float64Nullable.is_numeric());
22008        assert!(DType::Float64Nullable.is_any_real_numeric());
22009        assert!(DType::Float64Nullable.is_nullable());
22010        assert!(DType::Float64Nullable.is_extension());
22011        // And NOT these: an integer predicate that accepted it would let a
22012        // float value through an int-only fast path.
22013        assert!(!DType::Float64Nullable.is_integer());
22014        assert!(!DType::Float64Nullable.is_signed_integer());
22015        assert!(!DType::Float64Nullable.is_bool());
22016        // MEASURED: pd.Float64Dtype().kind == 'f', matching numpy float64 --
22017        // the extension reports its UNDERLYING kind, as Int64Nullable does.
22018        assert_eq!(DType::Float64Nullable.kind(), 'f');
22019        assert_eq!(DType::Float64Nullable.kind(), DType::Float64.kind());
22020        assert_eq!(DType::Float64Nullable.itemsize(), 8);
22021    }
22022
22023    /// The nullable/non-nullable pairing must be a genuine involution, or a
22024    /// round trip through either accessor silently changes flavour.
22025    #[test]
22026    fn nullable_pairing_is_an_involution_qkqfb() {
22027        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
22028        assert_eq!(DType::Float64Nullable.to_non_nullable(), DType::Float64);
22029        // Idempotent at both ends.
22030        assert_eq!(DType::Float64Nullable.to_nullable(), DType::Float64Nullable);
22031        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
22032        // The other families are untouched by the new variant.
22033        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
22034        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
22035    }
22036
22037    /// MEASURED ARITHMETIC, live pandas 2.2.3 -- this function models arithmetic
22038    /// promotion, not `find_common_type` (see the Bool arms in `common_dtype`):
22039    /// ```text
22040    ///   Float64(ext) + float64(numpy)  -> Float64
22041    ///   Int64(ext)   + Float64(ext)    -> Float64
22042    ///   boolean(ext) + Float64(ext)    -> Float64
22043    ///   Float64(ext) - Float64(ext)    -> Float64
22044    /// ```
22045    /// The nullable float absorbs every other numeric flavour.
22046    #[test]
22047    fn the_nullable_float_absorbs_every_numeric_flavour_qkqfb() {
22048        for other in [
22049            DType::Float64,
22050            DType::Int64,
22051            DType::Int64Nullable,
22052            DType::Bool,
22053            DType::BoolNullable,
22054            DType::Float64Nullable,
22055        ] {
22056            assert_eq!(
22057                common_dtype(DType::Float64Nullable, other.clone()),
22058                Ok(DType::Float64Nullable),
22059                "Float64Nullable + {other:?}"
22060            );
22061            // Commutativity is asserted wholesale by
22062            // common_dtype_lattice_axioms_be314; repeated here because an
22063            // asymmetric arm makes df1+df2 disagree with df2+df1.
22064            assert_eq!(
22065                common_dtype(other.clone(), DType::Float64Nullable),
22066                Ok(DType::Float64Nullable),
22067                "{other:?} + Float64Nullable"
22068            );
22069        }
22070        // Null is the lattice identity and must not absorb it.
22071        assert_eq!(
22072            common_dtype(DType::Null, DType::Float64Nullable),
22073            Ok(DType::Float64Nullable)
22074        );
22075    }
22076
22077    /// A PRESENT value crosses between the two float flavours unchanged; only the
22078    /// MISSING marker is converted.
22079    ///
22080    /// MEASURED:
22081    /// ```text
22082    ///   pd.Series([1.5,None],dtype="Float64").astype("float64") -> [1.5, nan]
22083    ///   pd.Series([1,None],  dtype="Int64").astype("Float64")   -> [1.0, <NA>]
22084    /// ```
22085    #[test]
22086    fn casts_preserve_values_and_convert_only_the_marker_qkqfb() {
22087        let present = Scalar::Float64(1.5);
22088        assert_eq!(
22089            cast_scalar(&present, DType::Float64Nullable),
22090            Ok(Scalar::Float64(1.5))
22091        );
22092        assert_eq!(
22093            cast_scalar(&Scalar::Float64(1.5), DType::Float64),
22094            Ok(Scalar::Float64(1.5))
22095        );
22096        // Int -> nullable float widens the value, as pandas does.
22097        assert_eq!(
22098            cast_scalar(&Scalar::Int64(1), DType::Float64Nullable),
22099            Ok(Scalar::Float64(1.0))
22100        );
22101        assert_eq!(
22102            cast_scalar(&Scalar::Bool(true), DType::Float64Nullable),
22103            Ok(Scalar::Float64(1.0))
22104        );
22105
22106        // THE MARKER CONVERSION, in both directions. This is the assertion a
22107        // "just alias Float64Nullable to Float64" implementation fails.
22108        assert_eq!(
22109            cast_scalar(&Scalar::Null(NullKind::NaN), DType::Float64Nullable),
22110            Ok(Scalar::Null(NullKind::Null)),
22111            "numpy NaN entering an extension lane becomes pd.NA"
22112        );
22113        assert_eq!(
22114            cast_scalar(&Scalar::Null(NullKind::Null), DType::Float64),
22115            Ok(Scalar::Null(NullKind::NaN)),
22116            "pd.NA entering a numpy lane becomes NaN"
22117        );
22118    }
22119
22120    /// The slice boundary this test used to pin has now been crossed: a
22121    /// nullable lane widening against a numpy float answers the NULLABLE float.
22122    /// MEASURED, live pandas 2.2.3, both spellings:
22123    /// ```text
22124    ///   find_common_type([Int64, float64])                        ->  Float64
22125    ///   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5])  ->  Float64
22126    /// ```
22127    /// (`Float64` there is the EXTENSION dtype — `Float64Dtype()` — not numpy
22128    /// `float64`.) br-frankenpandas-qkqfb; unblocks br-frankenpandas-f0aaa.
22129    #[test]
22130    fn int64nullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
22131        assert_eq!(
22132            common_dtype(DType::Int64Nullable, DType::Float64),
22133            Ok(DType::Float64Nullable)
22134        );
22135        assert_eq!(
22136            common_dtype(DType::Float64, DType::Int64Nullable),
22137            Ok(DType::Float64Nullable)
22138        );
22139    }
22140
22141    /// The BoolNullable sibling, MEASURED on the same pandas:
22142    /// ```text
22143    ///   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
22144    ///       -> Float64   (extension)
22145    /// ```
22146    /// The numpy-bool lane is NOT affected and stays on numpy float64, which is
22147    /// the control that keeps this from being a blanket "nullable everywhere".
22148    #[test]
22149    fn boolnullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
22150        assert_eq!(
22151            common_dtype(DType::BoolNullable, DType::Float64),
22152            Ok(DType::Float64Nullable)
22153        );
22154        assert_eq!(
22155            common_dtype(DType::Bool, DType::Float64),
22156            Ok(DType::Float64),
22157            "numpy bool + numpy float stays entirely on the numpy side"
22158        );
22159    }
22160
22161    /// ⚠ WHY THOSE TWO ARMS CANNOT MOVE INDEPENDENTLY. This is the exact triple
22162    /// that fails if only the Int64Nullable arm is flipped, spelled out so the
22163    /// coupling survives someone later "simplifying" one arm back:
22164    /// ```text
22165    ///   (BoolNullable ∨ Int64) ∨ Float64 = Int64Nullable ∨ Float64 = Float64Nullable
22166    ///   BoolNullable ∨ (Int64 ∨ Float64) = BoolNullable  ∨ Float64 = ???
22167    /// ```
22168    /// `common_dtype_lattice_axioms_be314` sweeps this for all 14 dtypes; this
22169    /// test names the single witness so a failure is diagnosable without
22170    /// re-deriving it from a 14³ sweep. (br-frankenpandas-qkqfb)
22171    #[test]
22172    fn the_nullable_float_flip_is_associative_on_its_witness_triple_qkqfb() {
22173        let (bn, i64n, f64d) = (DType::BoolNullable, DType::Int64, DType::Float64);
22174
22175        let left = common_dtype(
22176            common_dtype(bn.clone(), i64n.clone()).unwrap(),
22177            f64d.clone(),
22178        )
22179        .unwrap();
22180        let right = common_dtype(bn, common_dtype(i64n, f64d).unwrap()).unwrap();
22181
22182        assert_eq!(left, right, "promotion order must not change the result");
22183        assert_eq!(left, DType::Float64Nullable);
22184    }
22185}
22186
22187/// br-frankenpandas-3gxc6: the Sparse dtype NAME is parameterized in pandas.
22188///
22189/// Every expectation below was read off live pandas 2.2.3 before the code was
22190/// written, via `str(dtype)` / `dtype.name` on a `pd.SparseDtype`.
22191#[cfg(test)]
22192mod sparse_dtype_pandas_name_3gxc6 {
22193    use super::{DType, Scalar, SparseDType};
22194
22195    fn name(value_dtype: DType, fill: Scalar) -> String {
22196        SparseDType::new(value_dtype, fill)
22197            .expect("sparse descriptor")
22198            .pandas_name()
22199    }
22200
22201    /// The row the corpus fixture `fp_p2d_017_series_dtype_sparse_strict`
22202    /// exercises. FrankenPandas used to answer the bare `"Sparse"`.
22203    #[test]
22204    fn int64_fill_zero_is_the_fixture_row() {
22205        assert_eq!(name(DType::Int64, Scalar::Int64(0)), "Sparse[int64, 0]");
22206    }
22207
22208    /// A non-default fill must appear, or the name would be a constant wearing
22209    /// a parameterized shape.
22210    #[test]
22211    fn the_fill_value_is_actually_rendered() {
22212        assert_eq!(name(DType::Int64, Scalar::Int64(7)), "Sparse[int64, 7]");
22213        assert_ne!(
22214            name(DType::Int64, Scalar::Int64(0)),
22215            name(DType::Int64, Scalar::Int64(7)),
22216            "two different fills must not collapse to one name"
22217        );
22218    }
22219
22220    /// pandas spells this `nan`, lowercase, not `NaN` and not `None`.
22221    #[test]
22222    fn float64_nan_fill_is_lowercase_nan() {
22223        assert_eq!(
22224            name(DType::Float64, Scalar::Float64(f64::NAN)),
22225            "Sparse[float64, nan]"
22226        );
22227    }
22228
22229    /// pandas keeps the trailing `.0` here. A `{}`-style float format would
22230    /// render `0` and silently make this name collide with the int64 one.
22231    #[test]
22232    fn float64_zero_fill_keeps_its_trailing_point_zero() {
22233        assert_eq!(
22234            name(DType::Float64, Scalar::Float64(0.0)),
22235            "Sparse[float64, 0.0]"
22236        );
22237        assert_ne!(
22238            name(DType::Float64, Scalar::Float64(0.0)),
22239            name(DType::Int64, Scalar::Int64(0)),
22240            "float64 and int64 zero fills are different dtypes"
22241        );
22242    }
22243
22244    /// Python capitalisation, not Rust's `false`.
22245    #[test]
22246    fn bool_fill_uses_python_capitalisation() {
22247        assert_eq!(
22248            name(DType::Bool, Scalar::Bool(false)),
22249            "Sparse[bool, False]"
22250        );
22251        assert_eq!(name(DType::Bool, Scalar::Bool(true)), "Sparse[bool, True]");
22252    }
22253
22254    /// FP spells its object dtype `object`, which is what pandas prints for a
22255    /// `SparseDtype(object, nan)`.
22256    #[test]
22257    fn utf8_subtype_renders_as_object() {
22258        let rendered = name(DType::Utf8, Scalar::Null(crate::NullKind::NaN));
22259        assert!(
22260            rendered.starts_with("Sparse[object, "),
22261            "expected an object subtype, got {rendered}"
22262        );
22263    }
22264
22265    /// The bare name is what this bead removed; guard against a regression
22266    /// that reintroduces it for any constructible descriptor.
22267    #[test]
22268    fn no_constructible_descriptor_renders_the_bare_name() {
22269        for (dtype, fill) in [
22270            (DType::Int64, Scalar::Int64(0)),
22271            (DType::Float64, Scalar::Float64(1.5)),
22272            (DType::Bool, Scalar::Bool(true)),
22273            (DType::Utf8, Scalar::Utf8("x".to_owned())),
22274        ] {
22275            let rendered = name(dtype.clone(), fill);
22276            assert_ne!(rendered, "Sparse", "bare name regressed for {dtype:?}");
22277            assert!(
22278                rendered.starts_with("Sparse[") && rendered.ends_with(']'),
22279                "malformed sparse name {rendered}"
22280            );
22281        }
22282    }
22283
22284    #[test]
22285    fn test_dtype_from_str_and_display() {
22286        use std::str::FromStr;
22287
22288        use crate::DType;
22289
22290        assert_eq!(DType::from_str("int64").unwrap(), DType::Int64);
22291        assert_eq!(DType::from_str("Int64").unwrap(), DType::Int64Nullable);
22292        assert_eq!(DType::from_str("float64").unwrap(), DType::Float64);
22293        assert_eq!(DType::from_str("Float64").unwrap(), DType::Float64Nullable);
22294        assert_eq!(DType::from_str("bool").unwrap(), DType::Bool);
22295        assert_eq!(DType::from_str("boolean").unwrap(), DType::BoolNullable);
22296        assert_eq!(DType::from_str("string").unwrap(), DType::Utf8);
22297        assert_eq!(DType::from_str("category").unwrap(), DType::Categorical);
22298        assert_eq!(
22299            DType::from_str("timedelta64[ns]").unwrap(),
22300            DType::Timedelta64
22301        );
22302        assert_eq!(
22303            DType::from_str("datetime64[ns]").unwrap(),
22304            DType::Datetime64 { tz: None }
22305        );
22306        assert_eq!(
22307            DType::from_str("datetime64[ns, UTC]").unwrap(),
22308            DType::Datetime64 {
22309                tz: Some("UTC".to_string())
22310            }
22311        );
22312        assert_eq!(DType::from_str("period").unwrap(), DType::Period);
22313        assert_eq!(DType::from_str("interval").unwrap(), DType::Interval);
22314        assert_eq!(DType::from_str("sparse").unwrap(), DType::Sparse);
22315
22316        assert_eq!(format!("{}", DType::Int64), "int64");
22317        assert_eq!(
22318            format!(
22319                "{}",
22320                DType::Datetime64 {
22321                    tz: Some("UTC".to_string())
22322                }
22323            ),
22324            "datetime64[ns, UTC]"
22325        );
22326    }
22327
22328    #[test]
22329    fn test_api_types_inspection_and_infer_dtype() {
22330        use crate::{
22331            DType, Scalar,
22332            api::types::{
22333                infer_dtype, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype,
22334                is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_int64_dtype,
22335                is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_object_dtype,
22336                is_period_dtype, is_scalar, is_signed_integer_dtype, is_sparse, is_string_dtype,
22337                is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype,
22338            },
22339        };
22340
22341        assert!(is_numeric_dtype(&DType::Int64));
22342        assert!(is_numeric_dtype(&DType::Float64));
22343        assert!(!is_numeric_dtype(&DType::Utf8));
22344        assert!(!is_numeric_dtype(&DType::Bool));
22345
22346        assert!(is_integer_dtype(&DType::Int64));
22347        assert!(is_integer_dtype(&DType::Int64Nullable));
22348        assert!(!is_integer_dtype(&DType::Float64));
22349
22350        assert!(is_int64_dtype(&DType::Int64));
22351        assert!(is_int64_dtype(&DType::Int64Nullable));
22352        assert!(!is_int64_dtype(&DType::Float64));
22353
22354        assert!(is_object_dtype(&DType::Utf8));
22355        assert!(!is_object_dtype(&DType::Int64));
22356
22357        assert!(is_dtype_equal(&DType::Int64, &DType::Int64));
22358        assert!(is_dtype_equal(&"int64", &DType::Int64));
22359        assert!(!is_dtype_equal(&DType::Int64, &DType::Float64));
22360
22361        assert!(is_signed_integer_dtype(&DType::Int64));
22362        assert!(!is_unsigned_integer_dtype(&DType::Int64));
22363
22364        assert!(is_float_dtype(&DType::Float64));
22365        assert!(is_bool_dtype(&DType::Bool));
22366        assert!(is_string_dtype(&DType::Utf8));
22367        assert!(is_datetime64_any_dtype(&DType::Datetime64 { tz: None }));
22368        assert!(is_timedelta64_dtype(&DType::Timedelta64));
22369        assert!(is_categorical_dtype(&DType::Categorical));
22370        assert!(is_period_dtype(&DType::Period));
22371        assert!(is_interval_dtype(&DType::Interval));
22372        assert!(is_sparse(&DType::Sparse));
22373        assert!(is_extension_array_dtype(&DType::Categorical));
22374        assert!(is_scalar(&Scalar::Int64(42)));
22375
22376        assert_eq!(pandas_dtype("float64").unwrap(), DType::Float64);
22377        assert!(pandas_dtype("invalid_dtype_xyz").is_err());
22378
22379        let ints = vec![Scalar::Int64(1), Scalar::Int64(2)];
22380        assert_eq!(infer_dtype(&ints, true), "integer");
22381
22382        let floats = vec![Scalar::Float64(1.0), Scalar::Float64(2.5)];
22383        assert_eq!(infer_dtype(&floats, true), "floating");
22384
22385        let bools = vec![Scalar::Bool(true), Scalar::Bool(false)];
22386        assert_eq!(infer_dtype(&bools, true), "boolean");
22387
22388        let strings = vec![Scalar::Utf8("a".to_string()), Scalar::Utf8("b".to_string())];
22389        assert_eq!(infer_dtype(&strings, true), "string");
22390
22391        let mixed = vec![Scalar::Int64(1), Scalar::Utf8("a".to_string())];
22392        assert_eq!(infer_dtype(&mixed, true), "mixed");
22393
22394        assert_eq!(infer_dtype(&[], true), "empty");
22395    }
22396
22397    #[test]
22398    fn test_na_nat_sentinels_and_eng_float_format() {
22399        use super::{
22400            NA, NAT, NaT, eng_float_format, get_eng_float_format, reset_eng_float_format,
22401            set_eng_float_format,
22402        };
22403
22404        // NA and NAT sentinels
22405        assert!(NA.is_null());
22406        assert!(NAT.is_null());
22407        assert_eq!(NAT, NaT);
22408        assert_eq!(format!("{NA}"), "None");
22409        assert_eq!(format!("{NAT}"), "NaT");
22410
22411        // Engineering float format tests
22412        assert_eq!(eng_float_format(1000.0, Some(3), false), "1.000E+03");
22413        assert_eq!(eng_float_format(0.005, Some(3), false), "5.000E-03");
22414        assert_eq!(eng_float_format(1234567.0, Some(3), false), "1.235E+06");
22415        assert_eq!(eng_float_format(-9876.54, Some(3), false), "-9.877E+03");
22416        assert_eq!(eng_float_format(0.0, Some(3), false), "0.000E+00");
22417
22418        // With prefixes
22419        assert_eq!(eng_float_format(1000.0, Some(3), true), "1.000k");
22420        assert_eq!(eng_float_format(0.005, Some(3), true), "5.000m");
22421        assert_eq!(eng_float_format(1234567.0, Some(3), true), "1.235M");
22422        assert_eq!(eng_float_format(-9876.54, Some(3), true), "-9.877k");
22423        assert_eq!(eng_float_format(0.0, Some(3), true), "0.000");
22424        assert_eq!(eng_float_format(1.5, Some(3), true), "1.500");
22425
22426        // Special numbers
22427        assert_eq!(eng_float_format(f64::NAN, Some(3), true), "NaN");
22428        assert_eq!(eng_float_format(f64::INFINITY, Some(3), true), "inf");
22429        assert_eq!(eng_float_format(f64::NEG_INFINITY, Some(3), true), "-inf");
22430
22431        // Configuration helpers
22432        reset_eng_float_format();
22433        assert_eq!(get_eng_float_format(), None);
22434        set_eng_float_format(4, true);
22435        assert_eq!(get_eng_float_format(), Some((4, true)));
22436        reset_eng_float_format();
22437        assert_eq!(get_eng_float_format(), None);
22438    }
22439
22440    #[test]
22441    fn test_options_system() {
22442        use super::{
22443            OptionError, OptionValue, describe_option, get_option, option_context, reset_option,
22444            set_option,
22445        };
22446
22447        // Reset to clean state
22448        reset_option(None).unwrap();
22449
22450        // 1. Default option checks
22451        let max_rows = get_option("display.max_rows").unwrap();
22452        assert_eq!(max_rows.as_int(), Some(60));
22453        assert_eq!(max_rows, OptionValue::Int(60));
22454        assert!(!max_rows.is_none());
22455
22456        // Partial key matching (suffix)
22457        let min_rows = get_option("min_rows").unwrap();
22458        assert_eq!(min_rows.as_int(), Some(10));
22459
22460        // 2. Setting options
22461        set_option("display.max_rows", 100).unwrap();
22462        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
22463
22464        set_option("mode.sim_interactive", true).unwrap();
22465        assert_eq!(
22466            get_option("mode.sim_interactive").unwrap().as_bool(),
22467            Some(true)
22468        );
22469
22470        set_option("mode.chained_assignment", "raise").unwrap();
22471        assert_eq!(
22472            get_option("mode.chained_assignment").unwrap().as_str(),
22473            Some("raise")
22474        );
22475
22476        // 3. OptionError handling
22477        assert!(matches!(
22478            get_option("nonexistent.option"),
22479            Err(OptionError::NotFound { .. })
22480        ));
22481        assert!(matches!(
22482            get_option("display"),
22483            Err(OptionError::Ambiguous { .. })
22484        ));
22485
22486        // 4. describe_option
22487        let desc = describe_option(Some("max_rows")).unwrap();
22488        assert!(desc.contains("display.max_rows : [currently: 100]"));
22489
22490        let desc_all = describe_option(None).unwrap();
22491        assert!(desc_all.contains("display.width"));
22492        assert!(desc_all.contains("compute.use_bottleneck"));
22493
22494        // 5. Scoped option_context
22495        {
22496            let _guard = option_context(&[
22497                ("display.max_rows", OptionValue::Int(999)),
22498                ("display.precision", OptionValue::Int(2)),
22499            ])
22500            .unwrap();
22501
22502            assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(999));
22503            assert_eq!(get_option("display.precision").unwrap().as_int(), Some(2));
22504        }
22505        // Restored after guard drop
22506        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
22507        assert_eq!(get_option("display.precision").unwrap().as_int(), Some(6));
22508
22509        // 6. Reset single option and all options
22510        reset_option(Some("display.max_rows")).unwrap();
22511        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(60));
22512
22513        reset_option(Some("all")).unwrap();
22514        assert_eq!(
22515            get_option("mode.chained_assignment").unwrap().as_str(),
22516            Some("warn")
22517        );
22518
22519        // 7. Expanded standard options
22520        assert_eq!(
22521            get_option("mode.copy_on_write").unwrap().as_bool(),
22522            Some(false)
22523        );
22524        assert_eq!(
22525            get_option("mode.data_manager").unwrap().as_str(),
22526            Some("block")
22527        );
22528        assert_eq!(
22529            get_option("display.large_repr").unwrap().as_str(),
22530            Some("truncate")
22531        );
22532        assert_eq!(
22533            get_option("display.max_info_columns").unwrap().as_int(),
22534            Some(100)
22535        );
22536        assert_eq!(
22537            get_option("display.memory_usage").unwrap().as_bool(),
22538            Some(true)
22539        );
22540        assert_eq!(
22541            get_option("display.colheader_justify").unwrap().as_str(),
22542            Some("right")
22543        );
22544        assert!(get_option("display.chop_threshold").unwrap().is_none());
22545        assert_eq!(
22546            get_option("io.parquet.engine").unwrap().as_str(),
22547            Some("auto")
22548        );
22549        assert_eq!(
22550            get_option("plotting.backend").unwrap().as_str(),
22551            Some("matplotlib")
22552        );
22553        assert_eq!(
22554            get_option("plotting.matplotlib.register_converters")
22555                .unwrap()
22556                .as_bool(),
22557            Some(true)
22558        );
22559
22560        // From<()> for OptionValue
22561        set_option("display.chop_threshold", ()).unwrap();
22562        assert!(get_option("display.chop_threshold").unwrap().is_none());
22563    }
22564
22565    #[test]
22566    fn test_scalar_typed_accessors() {
22567        use super::{Interval, IntervalClosed, Period, PeriodFreq, Scalar};
22568
22569        let s_i64 = Scalar::Int64(42);
22570        assert_eq!(s_i64.as_i64(), Some(42));
22571        assert_eq!(s_i64.as_int(), Some(42));
22572        assert_eq!(s_i64.as_f64(), None);
22573        assert_eq!(s_i64.as_float(), None);
22574        assert_eq!(s_i64.as_bool(), None);
22575        assert_eq!(s_i64.as_str(), None);
22576
22577        let s_f64 = Scalar::Float64(2.75);
22578        assert_eq!(s_f64.as_f64(), Some(2.75));
22579        assert_eq!(s_f64.as_float(), Some(2.75));
22580        assert_eq!(s_f64.as_i64(), None);
22581        assert_eq!(s_f64.as_int(), None);
22582
22583        let s_bool = Scalar::Bool(true);
22584        assert_eq!(s_bool.as_bool(), Some(true));
22585        assert_eq!(s_bool.as_int(), None);
22586
22587        let s_str = Scalar::Utf8("pandas".to_string());
22588        assert_eq!(s_str.as_str(), Some("pandas"));
22589        assert_eq!(s_str.as_bool(), None);
22590
22591        let s_dt = Scalar::Datetime64(1_000_000_000);
22592        assert_eq!(s_dt.as_datetime_nanos(), Some(1_000_000_000));
22593        assert_eq!(s_dt.as_str(), None);
22594
22595        let s_td = Scalar::Timedelta64(500_000);
22596        assert_eq!(s_td.as_timedelta_nanos(), Some(500_000));
22597        assert_eq!(s_td.as_int(), None);
22598
22599        let s_per = Scalar::Period(Period::new(2024, PeriodFreq::Daily));
22600        assert_eq!(s_per.as_period_ordinal(), Some(2024));
22601
22602        let s_iv = Scalar::Interval(Interval::new(0.0, 10.0, IntervalClosed::Both));
22603        assert_eq!(
22604            s_iv.as_interval(),
22605            Some(Interval::new(0.0, 10.0, IntervalClosed::Both))
22606        );
22607    }
22608
22609    #[test]
22610    fn test_api_submodules_and_types_inspectors() {
22611        use super::{
22612            DType, Scalar,
22613            api::{extensions, indexers, types},
22614        };
22615
22616        // api::types scalar inspectors
22617        assert!(types::is_number(&Scalar::Int64(42)));
22618        assert!(types::is_number(&Scalar::Float64(42.5)));
22619        assert!(types::is_number(&Scalar::Bool(true)));
22620        assert!(!types::is_number(&Scalar::Utf8("pandas".into())));
22621
22622        assert!(types::is_bool(&Scalar::Bool(false)));
22623        assert!(!types::is_bool(&Scalar::Int64(0)));
22624
22625        assert!(types::is_integer(&Scalar::Int64(10)));
22626        assert!(!types::is_integer(&Scalar::Float64(10.0)));
22627
22628        assert!(types::is_float(&Scalar::Float64(10.0)));
22629        assert!(!types::is_float(&Scalar::Int64(10)));
22630
22631        // api::types dtype inspectors
22632        assert!(types::is_float64_dtype(&DType::Float64));
22633        assert!(types::is_float64_dtype(&DType::Float64Nullable));
22634        assert!(!types::is_float64_dtype(&DType::Int64));
22635        assert!(!types::is_int32_dtype(&DType::Int64));
22636
22637        // api::extensions compatibility hooks
22638        extensions::register_dataframe_accessor("geo");
22639        extensions::register_series_accessor("geo");
22640        extensions::register_index_accessor("geo");
22641
22642        // api::indexers
22643        let base = indexers::BaseIndexer::new(5, 1);
22644        assert_eq!(base.window_size, 5);
22645        assert_eq!(base.step, 1);
22646
22647        let fwd = indexers::FixedForwardWindowIndexer::new(3);
22648        assert_eq!(fwd.window_size, 3);
22649
22650        let var = indexers::VariableOffsetWindowIndexer::new(100);
22651        assert_eq!(var.index_offset, 100);
22652    }
22653
22654    #[test]
22655    fn test_extension_dtypes_and_parameterized_parsing() {
22656        use super::{
22657            AsDType, CategoricalDtype, DType, IntervalClosed, IntervalDtype, PeriodDtype, Scalar,
22658            SparseDType, api::types, pandas_dtype,
22659        };
22660
22661        // CategoricalDtype
22662        let cat_default = CategoricalDtype::default();
22663        assert_eq!(cat_default.name(), "category");
22664        assert_eq!(cat_default.kind(), "O");
22665        assert!(!cat_default.ordered());
22666        assert_eq!(cat_default.categories(), None);
22667        assert_eq!(cat_default.as_dtype(), DType::Categorical);
22668        assert!(types::is_categorical_dtype(&cat_default));
22669        assert_eq!(
22670            cat_default.to_string(),
22671            "CategoricalDtype(categories=None, ordered=False)"
22672        );
22673
22674        let cat_custom =
22675            CategoricalDtype::new(Some(vec!["low".to_string(), "high".to_string()]), true);
22676        assert!(cat_custom.ordered());
22677        assert_eq!(
22678            cat_custom.categories(),
22679            Some(&["low".to_string(), "high".to_string()][..])
22680        );
22681        assert!(cat_custom.to_string().contains("ordered=True"));
22682
22683        // PeriodDtype
22684        let per_default = PeriodDtype::default();
22685        assert_eq!(per_default.freq(), "D");
22686        assert_eq!(per_default.name(), "period[D]");
22687        assert_eq!(per_default.kind(), "O");
22688        assert_eq!(per_default.as_dtype(), DType::Period);
22689        assert!(types::is_period_dtype(&per_default));
22690        assert_eq!(per_default.to_string(), "period[D]");
22691
22692        let per_custom = PeriodDtype::new("M");
22693        assert_eq!(per_custom.freq(), "M");
22694        assert_eq!(per_custom.to_string(), "period[M]");
22695
22696        // IntervalDtype
22697        let int_default = IntervalDtype::default();
22698        assert_eq!(*int_default.subtype(), DType::Float64);
22699        assert_eq!(int_default.closed(), Some(IntervalClosed::Right));
22700        assert_eq!(int_default.name(), "interval");
22701        assert_eq!(int_default.kind(), "O");
22702        assert_eq!(int_default.as_dtype(), DType::Interval);
22703        assert!(types::is_interval_dtype(&int_default));
22704        assert_eq!(int_default.to_string(), "interval[float64, right]");
22705
22706        let int_custom = IntervalDtype::new(DType::Int64, Some(IntervalClosed::Both));
22707        assert_eq!(*int_custom.subtype(), DType::Int64);
22708        assert_eq!(int_custom.closed(), Some(IntervalClosed::Both));
22709        assert_eq!(int_custom.to_string(), "interval[int64, both]");
22710
22711        // SparseDType AsDType
22712        let sp = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).unwrap();
22713        assert_eq!(sp.as_dtype(), DType::Sparse);
22714        assert!(types::is_sparse(&sp));
22715
22716        // Parameterized pandas_dtype parsing
22717        assert_eq!(pandas_dtype("period[D]").unwrap(), DType::Period);
22718        assert_eq!(pandas_dtype("Period[M]").unwrap(), DType::Period);
22719        assert_eq!(pandas_dtype("interval[float64]").unwrap(), DType::Interval);
22720        assert_eq!(pandas_dtype("Interval[int64]").unwrap(), DType::Interval);
22721        assert_eq!(pandas_dtype("sparse[float64]").unwrap(), DType::Sparse);
22722        assert_eq!(pandas_dtype("Sparse[int64, 0]").unwrap(), DType::Sparse);
22723    }
22724}
22725
22726/// `NumericWidth` / `NumpyNumeric` — numpy's narrow numeric dtypes and their
22727/// promotion (fvsao.23). Expected values are live pandas 2.2.3 / numpy 2.4.6.
22728#[cfg(test)]
22729mod numeric_width_fvsao23 {
22730    use super::{DType, NumericWidth, NumpyNumeric, numpy_pairwise_sum};
22731
22732    #[test]
22733    fn float32_sum_is_numpys_pairwise_sum_bit_for_bit() {
22734        // numpy 2.4.6: a = ((arange(n) * 37) % 1000).astype(float32) *
22735        // float32(0.013); a.sum().view(uint32). Lengths 5 and 64 are ones
22736        // where a float64 sum rounded once gives another float32 (NEGATIVE).
22737        let cases: [(usize, u32); 5] = [
22738            (5, 1_083_829_126),
22739            (64, 1_136_679_190),
22740            (129, 1_145_981_108),
22741            (1000, 1_170_926_592),
22742            (4097, 1_188_011_795),
22743        ];
22744        for (n, bits) in cases {
22745            #[allow(clippy::cast_precision_loss)] // below 1000
22746            let values: Vec<f32> = (0..n)
22747                .map(|k| ((k * 37) % 1000) as f32 * 0.013_f32)
22748                .collect();
22749            assert_eq!(numpy_pairwise_sum(&values).to_bits(), bits, "n={n}");
22750            if n < 100 {
22751                #[allow(clippy::cast_possible_truncation)]
22752                let rounded_once = values.iter().map(|&v| f64::from(v)).sum::<f64>() as f32;
22753                assert_ne!(rounded_once.to_bits(), bits, "n={n}");
22754            }
22755        }
22756        assert_eq!(numpy_pairwise_sum::<f32>(&[]), 0.0);
22757    }
22758
22759    #[test]
22760    fn names_parse_and_round_trip() {
22761        for width in NumericWidth::ALL {
22762            for nullable in [false, true] {
22763                assert_eq!(
22764                    NumericWidth::parse(width.name(nullable)),
22765                    Some((width, nullable))
22766                );
22767            }
22768        }
22769        for (name, expected) in [
22770            ("<i4", (NumericWidth::Int32, false)),
22771            ("f4", (NumericWidth::Float32, false)),
22772            ("UInt8Dtype", (NumericWidth::UInt8, true)),
22773        ] {
22774            assert_eq!(NumericWidth::parse(name), Some(expected), "{name}");
22775        }
22776        // The 64-bit names are DType's, not a width: 'i8' is numpy's int64.
22777        for name in ["int64", "Int64", "float64", "i8", "f8", "int", "float"] {
22778            assert_eq!(NumericWidth::parse(name), None, "{name}");
22779        }
22780    }
22781
22782    #[test]
22783    fn wrapping_is_numpys_modular_cast_not_saturation() {
22784        // pd.Series([1, 2, 300, -5]).astype('int8') -> [1, 2, 44, -5]
22785        assert_eq!(NumericWidth::Int8.wrap_int(300), Some(44));
22786        // .astype('uint8') -> [1, 2, 44, 251]; uint16 -5 -> 65531
22787        assert_eq!(NumericWidth::UInt8.wrap_int(-5), Some(251));
22788        assert_eq!(NumericWidth::UInt16.wrap_int(-5), Some(65531));
22789        assert_eq!(NumericWidth::UInt32.wrap_int(-5), Some(4_294_967_291));
22790        // int8 100 + 100 -> -56; 100 * 2 -> -56
22791        assert_eq!(NumericWidth::Int8.wrap_int(200), Some(-56));
22792        assert_eq!(
22793            NumericWidth::Int32.wrap_int(i64::from(i32::MAX) + 1),
22794            Some(i64::from(i32::MIN))
22795        );
22796        // A wrapped i64 product reduces to the width's product.
22797        let product = 50_000_i64.wrapping_pow(5);
22798        assert_eq!(
22799            NumericWidth::Int32.wrap_int(product),
22800            Some(i64::from(50_000_i32.wrapping_pow(5)))
22801        );
22802        // uint64 at or above 2**63 is refused, never stored negative.
22803        assert_eq!(NumericWidth::UInt64.wrap_int(-1), None);
22804        assert_eq!(NumericWidth::UInt64.wrap_int(7), Some(7));
22805        assert_eq!(NumericWidth::Float32.wrap_int(1), None);
22806        assert!(NumericWidth::Int8.holds_int(-128) && !NumericWidth::Int8.holds_int(128));
22807    }
22808
22809    #[test]
22810    fn float32_rounding_is_to_nearest_not_truncation() {
22811        // np.float32(0.1) as float64 -> 0.10000000149011612
22812        assert_eq!(NumericWidth::round_f32(0.1), 0.100_000_001_490_116_12);
22813        // float32 0.1 + 0.2 -> 0.30000001192092896 (not float64's
22814        // 0.30000000000000004)
22815        let sum =
22816            NumericWidth::round_f32(NumericWidth::round_f32(0.1) + NumericWidth::round_f32(0.2));
22817        assert_eq!(sum, 0.300_000_011_920_928_96);
22818        // 1 + 2**-24 is a tie between 1 and 1 + 2**-23: ties to even -> 1.
22819        // 1 + 3 * 2**-25 is above the tie: rounds up, where truncation stays 1.
22820        assert_eq!(NumericWidth::round_f32(1.0 + 2f64.powi(-24)), 1.0);
22821        let above_tie = 1.0 + 3.0 * 2f64.powi(-25);
22822        assert_eq!(NumericWidth::round_f32(above_tie), 1.0 + 2f64.powi(-23));
22823        assert!(NumericWidth::round_f32(f64::NAN).is_nan());
22824        assert_eq!(NumericWidth::round_f32(1e300), f64::INFINITY);
22825    }
22826
22827    #[test]
22828    fn result_type_matches_numpy_promotion() {
22829        use NumpyNumeric::{Bool, Float, Int, UInt};
22830        let cases = [
22831            (Int(32), Int(64), Int(64)), // int32 + int64 -> int64
22832            (Int(8), UInt(8), Int(16)),  // int8 + uint8 -> int16
22833            (Int(16), UInt(8), Int(16)),
22834            (Int(8), UInt(16), Int(32)),
22835            (Int(32), UInt(32), Int(64)),
22836            (Int(64), UInt(64), Float(64)), // no integer holds both
22837            (UInt(8), UInt(32), UInt(32)),
22838            (Float(32), Int(8), Float(32)), // float32 * int8 -> float32
22839            (Float(32), UInt(16), Float(32)),
22840            (Float(32), Int(32), Float(64)), // float32 * int32 -> float64
22841            (Float(32), Float(64), Float(64)),
22842            (Bool, Int(8), Int(8)),
22843            (Bool, Float(32), Float(32)),
22844        ];
22845        for (a, b, expected) in cases {
22846            assert_eq!(a.result_type(b), expected, "{a:?} {b:?}");
22847            assert_eq!(b.result_type(a), expected, "{b:?} {a:?}");
22848        }
22849        // NEP 50: int32 + 1 -> int32; int32 + 0.5 -> float64;
22850        // float32 + 0.2 -> float32
22851        assert_eq!(Int(32).with_python_int(), Int(32));
22852        assert_eq!(Int(32).with_python_float(), Float(64));
22853        assert_eq!(Float(32).with_python_float(), Float(32));
22854        assert_eq!(Bool.with_python_int(), Int(64));
22855    }
22856
22857    #[test]
22858    fn columns_map_to_numpy_dtypes() {
22859        let cases = [
22860            (DType::Int64, None, Some(NumpyNumeric::Int(64))),
22861            (
22862                DType::Int64Nullable,
22863                Some(NumericWidth::UInt8),
22864                Some(NumpyNumeric::UInt(8)),
22865            ),
22866            (
22867                DType::Float64,
22868                Some(NumericWidth::Float32),
22869                Some(NumpyNumeric::Float(32)),
22870            ),
22871            // A width its storage cannot carry is not a numpy dtype.
22872            (DType::Float64, Some(NumericWidth::Int8), None),
22873            (DType::Utf8, None, None),
22874        ];
22875        for (dtype, width, expected) in cases {
22876            assert_eq!(NumpyNumeric::of(&dtype, width), expected, "{dtype:?}");
22877        }
22878        for width in NumericWidth::ALL {
22879            assert_eq!(NumpyNumeric::of_width(width).width(), Some(width));
22880            assert!(width.fits_storage(&width.storage(false)));
22881            assert!(width.fits_storage(&width.storage(true)));
22882        }
22883        assert_eq!(NumpyNumeric::Int(64).width(), None);
22884    }
22885
22886    #[test]
22887    fn downcast_and_category_code_widths() {
22888        // to_numeric([1, 2], downcast='integer') -> int8; [1, 300] signed ->
22889        // int16, unsigned -> uint16
22890        let int32_max_plus_one = i64::from(i32::MAX) + 1;
22891        let signed = [
22892            ((1, 2), Some(NumericWidth::Int8)),
22893            ((1, 300), Some(NumericWidth::Int16)),
22894            ((0, int32_max_plus_one), None),
22895        ];
22896        for ((low, high), expected) in signed {
22897            assert_eq!(NumericWidth::smallest_signed(low, high), expected);
22898        }
22899        let unsigned = [((1, 300), Some(NumericWidth::UInt16)), ((-1, 3), None)];
22900        for ((low, high), expected) in unsigned {
22901            assert_eq!(NumericWidth::smallest_unsigned(low, high), expected);
22902        }
22903        // cat.codes: 2 categories int8, 200 int16; 126 int8, 127 int16
22904        for (categories, expected) in [
22905            (2, NumericWidth::Int8),
22906            (126, NumericWidth::Int8),
22907            (127, NumericWidth::Int16),
22908            (200, NumericWidth::Int16),
22909        ] {
22910            assert_eq!(NumericWidth::for_category_codes(categories), Some(expected));
22911        }
22912        assert_eq!(NumericWidth::itemsize(NumericWidth::Int8), 1);
22913        assert_eq!(NumericWidth::Float32.itemsize(), 4);
22914    }
22915}
22916
22917/// `PandasReductions` against live pandas 2.2.3 / numpy 2.3.5: the bits of
22918/// `Series(...).sum() / mean() / var() / std() / sem() / skew() / kurt()`
22919/// over data both sides build with the same integer arithmetic and one
22920/// division (br-frankenpandas-9iim6).
22921#[cfg(test)]
22922mod pandas_reductions_9iim6 {
22923    use super::{MissingLayout, PandasReductions, ReductionValues};
22924
22925    /// `((k * 7919 + 13) % 100003) / 7.0 - 7000.0`, times 1e6 where
22926    /// `k % 5 == 0`; missing where `k % 11 == 3`.
22927    #[allow(clippy::cast_precision_loss)] // below 100003
22928    fn floats(n: usize) -> (Vec<f64>, Vec<u64>) {
22929        let mut present = vec![0_u64; n.div_ceil(64)];
22930        let values = (0..n)
22931            .map(|k| {
22932                if k % 11 != 3 {
22933                    present[k / 64] |= 1 << (k % 64);
22934                }
22935                let base = ((k * 7919 + 13) % 100_003) as f64 / 7.0 - 7000.0;
22936                if k % 5 == 0 { base * 1e6 } else { base }
22937            })
22938            .collect();
22939        (values, present)
22940    }
22941
22942    /// `(k * 7919 + 13) % 100003 * 3_000_000_007`.
22943    fn ints(n: usize) -> Vec<i64> {
22944        (0..n)
22945            .map(|k| i64::try_from((k * 7919 + 13) % 100_003).unwrap() * 3_000_000_007)
22946            .collect()
22947    }
22948
22949    fn assert_bits(got: &[f64], expected: &[u64], case: &str) {
22950        let got: Vec<u64> = got.iter().map(|value| value.to_bits()).collect();
22951        assert_eq!(got, expected, "{case}");
22952    }
22953
22954    #[test]
22955    fn numpy_float64_with_nan_matches_pandas_bits() {
22956        // pandas: s = Series(floats(n)) with NaN at the missing slots.
22957        let cases: [(usize, [u64; 7]); 7] = [
22958            (
22959                7,
22960                [
22961                    0xc1ff_1185_2dcb_6db6,
22962                    0xc1d4_b658_c932_4924,
22963                    0x43db_301d_4a8d_87a3,
22964                    0x41e4_db58_e2f1_458e,
22965                    0x41d1_078f_09d3_9c5c,
22966                    0xc002_1f47_ceae_1b43,
22967                    0x4014_c8bc_93df_56e6,
22968                ],
22969            ),
22970            (
22971                8,
22972                [
22973                    0xc1ff_1184_f43d_b6da,
22974                    0xc1d1_c0de_426c_687d,
22975                    0x43d7_9d3c_ecd2_da2b,
22976                    0x41e3_7012_7d6c_71a5,
22977                    0x41cd_631d_3379_9929,
22978                    0xc003_b196_82f9_28dc,
22979                    0x4018_9de2_eba9_5ecc,
22980                ],
22981            ),
22982            (
22983                127,
22984                [
22985                    0x4200_324e_3389_2490,
22986                    0x4192_0704_ad1e_360d,
22987                    0x43c9_4a6b_3390_577d,
22988                    0x41dc_72bf_d6fa_9808,
22989                    0x41a5_38f5_8417_ae1e,
22990                    0x3fd0_b6bf_045c_e4d5,
22991                    0x4017_1585_bf13_21c4,
22992                ],
22993            ),
22994            (
22995                128,
22996                [
22997                    0x4200_324d_7236_db6e,
22998                    0x4191_df3a_f99d_a2ae,
22999                    0x43c9_1234_ffb7_4a93,
23000                    0x41dc_5310_c97c_292c,
23001                    0x41a5_09f4_cfcf_9206,
23002                    0x3fd0_d9df_0d68_00b0,
23003                    0x4017_61b6_5653_ae82,
23004                ],
23005            ),
23006            (
23007                129,
23008                [
23009                    0x4200_324c_d43e_db71,
23010                    0x4191_b81f_8a1d_61da,
23011                    0x43c8_daf6_85d3_386f,
23012                    0x41dc_33ca_af49_8c24,
23013                    0x41a4_dbc2_8609_a567,
23014                    0x3fd0_fcc5_39d9_6901,
23015                    0x4017_ade4_7855_7c25,
23016                ],
23017            ),
23018            (
23019                1000,
23020                [
23021                    0x421a_d4f6_8061_248e,
23022                    0x417e_39f9_3e1a_a248,
23023                    0x43c7_9481_cba1_263b,
23024                    0x41db_7825_28c0_37cc,
23025                    0x418d_27ba_a0ea_2f9a,
23026                    0x3fc8_e53a_e277_3d7f,
23027                    0x4018_3c97_3603_dfd0,
23028                ],
23029            ),
23030            (
23031                100_000,
23032                [
23033                    0x4283_088c_316e_46dc,
23034                    0x417b_7135_0c27_1185,
23035                    0x43c7_a0de_3b8e_ea34,
23036                    0x41db_7f57_6673_8d6b,
23037                    0x4157_58cc_33fd_4ae6,
23038                    0x3fc7_f1cf_b14a_14c8,
23039                    0x4018_06b5_f26a_c384,
23040                ],
23041            ),
23042        ];
23043        let all = |r: &PandasReductions<'_>| {
23044            [
23045                r.sum(),
23046                r.mean(),
23047                r.var(1),
23048                r.std(1),
23049                r.sem(1),
23050                r.skew(),
23051                r.kurt(),
23052            ]
23053        };
23054        for (n, expected) in cases {
23055            let (values, present) = floats(n);
23056            let r = PandasReductions::new(
23057                ReductionValues::Float(&values),
23058                Some(&present),
23059                MissingLayout::Numpy,
23060            );
23061            assert_bits(&all(&r), &expected, &format!("float64 n={n}"));
23062            // The same column holding NaN in its missing slots, whole and as
23063            // a concat's chunks.
23064            let with_nan: Vec<f64> = values
23065                .iter()
23066                .enumerate()
23067                .map(|(k, &value)| if k % 11 == 3 { f64::NAN } else { value })
23068                .collect();
23069            let r = PandasReductions::numpy_nan_missing(ReductionValues::Float(&with_nan));
23070            assert_bits(&all(&r), &expected, &format!("float64 NaN n={n}"));
23071            let (head, tail) = with_nan.split_at(n / 3);
23072            let chunks = [head, tail];
23073            let r = PandasReductions::numpy_nan_missing(ReductionValues::FloatChunks(&chunks));
23074            assert_bits(&all(&r), &expected, &format!("float64 NaN chunks n={n}"));
23075        }
23076        // NEGATIVE: the present values added left to right are not pandas'.
23077        let (values, present) = floats(100_000);
23078        let left_fold: f64 = values
23079            .iter()
23080            .enumerate()
23081            .filter(|&(k, _)| present[k / 64] >> (k % 64) & 1 == 1)
23082            .map(|(_, value)| value)
23083            .sum();
23084        assert_ne!(left_fold.to_bits(), 0x4283_088c_316e_46dc);
23085    }
23086
23087    #[test]
23088    fn numpy_int64_mean_sums_through_the_cast_buffer() {
23089        // pandas: Series(ints(n)) (int64): mean, var, sem, skew, kurt.
23090        let cases: [(usize, [u64; 5]); 3] = [
23091            (
23092                129,
23093                [
23094                    0x42e0_dda2_9987_3f9e,
23095                    0x45b9_0e2a_887d_aeda,
23096                    0x429c_34a1_c273_372f,
23097                    0x3f95_9e9d_c69e_ec88,
23098                    0xbff3_844b_ba13_eac1,
23099                ],
23100            ),
23101            (
23102                8193,
23103                [
23104                    0x42e1_0d5b_e407_5aa7,
23105                    0x45b8_3bf5_04f5_f2fc,
23106                    0x426b_d893_c5c9_85b1,
23107                    0x3f42_7452_ff15_86c7,
23108                    0xbff3_318c_611b_b59c,
23109                ],
23110            ),
23111            (
23112                20_000,
23113                [
23114                    0x42e1_0d17_ebf8_272d,
23115                    0x45b8_3c24_c921_82b6,
23116                    0x4261_d2a2_f139_68e2,
23117                    0x3f31_a21c_d4bb_ff52,
23118                    0xbff3_328c_4edc_26ee,
23119                ],
23120            ),
23121        ];
23122        for (n, expected) in cases {
23123            let values = ints(n);
23124            let r =
23125                PandasReductions::new(ReductionValues::Int(&values), None, MissingLayout::Numpy);
23126            let got = [r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()];
23127            assert_bits(&got, &expected, &format!("int64 n={n}"));
23128            // The same values read as chunks give the same bits.
23129            let (head, tail) = values.split_at(n / 3);
23130            let (middle, rest) = tail.split_at(1);
23131            let chunks = [head, middle, &[][..], rest];
23132            let chunked = PandasReductions::new(
23133                ReductionValues::IntChunks(&chunks),
23134                None,
23135                MissingLayout::Numpy,
23136            );
23137            let got = [
23138                chunked.mean(),
23139                chunked.var(1),
23140                chunked.sem(1),
23141                chunked.skew(),
23142                chunked.kurt(),
23143            ];
23144            assert_bits(&got, &expected, &format!("int64 chunks n={n}"));
23145        }
23146    }
23147
23148    #[test]
23149    fn masked_columns_add_runs_of_present_values() {
23150        // pandas: Series(pd.array(floats(n), dtype="Float64")) with NA at the
23151        // missing slots: sum, mean, var, sem. sum / mean differ from the
23152        // float64 column's above (n = 129: ...6e against ...71) - the runs.
23153        let cases: [(usize, [u64; 4]); 3] = [
23154            (
23155                129,
23156                [
23157                    0x4200_324c_d43e_db6e,
23158                    0x4191_b81f_8a1d_61d6,
23159                    0x43c8_daf6_85d3_3872,
23160                    0x41a4_dbc2_8609_a567,
23161                ],
23162            ),
23163            (
23164                1000,
23165                [
23166                    0x421a_d4f6_8061_2492,
23167                    0x417e_39f9_3e1a_a24c,
23168                    0x43c7_9481_cba1_263a,
23169                    0x418d_27ba_a0ea_2f9a,
23170                ],
23171            ),
23172            (
23173                100_000,
23174                [
23175                    0x4283_088c_316e_46de,
23176                    0x417b_7135_0c27_1188,
23177                    0x43c7_a0de_3b8e_ea37,
23178                    0x4157_58cc_33fd_4ae6,
23179                ],
23180            ),
23181        ];
23182        for (n, expected) in cases {
23183            let (values, present) = floats(n);
23184            let r = PandasReductions::new(
23185                ReductionValues::Float(&values),
23186                Some(&present),
23187                MissingLayout::Masked,
23188            );
23189            assert_bits(
23190                &[r.sum(), r.mean(), r.var(1), r.sem(1)],
23191                &expected,
23192                &format!("Float64 n={n}"),
23193            );
23194            let (head, tail) = values.split_at(n / 2 + 1);
23195            let chunks = [head, tail];
23196            let chunked = PandasReductions::new(
23197                ReductionValues::FloatChunks(&chunks),
23198                Some(&present),
23199                MissingLayout::Masked,
23200            );
23201            let got = [
23202                chunked.sum(),
23203                chunked.mean(),
23204                chunked.var(1),
23205                chunked.sem(1),
23206            ];
23207            assert_bits(&got, &expected, &format!("Float64 chunks n={n}"));
23208        }
23209        // pandas: pd.array(ints(n), dtype="Int64") with NA where k % 997 == 5:
23210        // mean and var, the runs summed within numpy's 8192-value buffers.
23211        for (n, expected) in [
23212            (8193, [0x42e1_0f35_29c2_807b_u64, 0x45b8_39ed_8746_bdcc]),
23213            (20_000, [0x42e1_0cf2_cc56_752a, 0x45b8_3c63_72fc_fad5]),
23214        ] {
23215            let values = ints(n);
23216            let mut present = vec![0_u64; n.div_ceil(64)];
23217            for k in (0..n).filter(|k| k % 997 != 5) {
23218                present[k / 64] |= 1 << (k % 64);
23219            }
23220            let r = PandasReductions::new(
23221                ReductionValues::Int(&values),
23222                Some(&present),
23223                MissingLayout::Masked,
23224            );
23225            assert_bits(&[r.mean(), r.var(1)], &expected, &format!("Int64 n={n}"));
23226        }
23227    }
23228
23229    #[test]
23230    fn edge_cases_match_pandas() {
23231        let reductions = |values: &[f64], present: Option<&[u64]>| {
23232            let r = PandasReductions::new(
23233                ReductionValues::Float(values),
23234                present,
23235                MissingLayout::Numpy,
23236            );
23237            [r.sum(), r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()]
23238        };
23239        // pandas: [1.5] * 10 -> 15.0 1.5 0.0 0.0 0.0 0.0 (a constant's kurt
23240        // is 0, not 0 minus the bias term); [2.0] * 3 kurt NaN.
23241        let constant = reductions(&[1.5; 10], None);
23242        assert_eq!(constant, [15.0, 1.5, 0.0, 0.0, 0.0, 0.0]);
23243        assert!(reductions(&[2.0; 3], None)[5].is_nan());
23244        // [1, 2] skew NaN; [1, 2, 4] skew 0.9352195295828237.
23245        assert!(reductions(&[1.0, 2.0], None)[4].is_nan());
23246        assert_eq!(
23247            reductions(&[1.0, 2.0, 4.0], None)[4],
23248            0.935_219_529_582_823_7
23249        );
23250        // Empty / all missing: sum 0.0, the rest NaN.
23251        let empty = reductions(&[], None);
23252        assert_eq!(empty[0], 0.0);
23253        assert!(empty[1..].iter().all(|value| value.is_nan()));
23254        let all_missing = reductions(&[3.0; 5], Some(&[0]));
23255        assert_eq!(all_missing[0], 0.0);
23256        assert!(all_missing[1].is_nan());
23257        // -0.0 * 10 sums to 0.0 (numpy adds onto the identity 0.0).
23258        assert_eq!(
23259            reductions(&[-0.0; 10], None)[0].to_bits(),
23260            0.0_f64.to_bits()
23261        );
23262        // An inf: sum / mean inf, the spread NaN.
23263        let inf = reductions(&[1.0, f64::INFINITY, 2.0, 5.0], None);
23264        assert_eq!(inf[0], f64::INFINITY);
23265        assert!(inf[2..].iter().all(|value| value.is_nan()));
23266    }
23267
23268    #[test]
23269    fn int64_mean_skipping_is_the_filled_mean_vk7y9() {
23270        // A datetime64 mean read straight off its nanos, NaT as 0, is the
23271        // bit-identical mean of the filled copy under its presence bits -
23272        // across cast-buffer chunks, with NaT anywhere (br-frankenpandas-vk7y9).
23273        const NAT: i64 = i64::MIN;
23274        let nanos: Vec<i64> = (0..20_000_i64)
23275            .map(|k| {
23276                if k % 13 == 5 {
23277                    NAT
23278                } else {
23279                    1_577_836_800_000_000_000 + k * 3_600_000_000_123
23280                }
23281            })
23282            .collect();
23283        let mut present = vec![0_u64; nanos.len().div_ceil(64)];
23284        let filled: Vec<i64> = nanos
23285            .iter()
23286            .enumerate()
23287            .map(|(i, &ns)| {
23288                if ns == NAT {
23289                    0
23290                } else {
23291                    present[i / 64] |= 1 << (i % 64);
23292                    ns
23293                }
23294            })
23295            .collect();
23296        let expected = PandasReductions::new(
23297            ReductionValues::Int(&filled),
23298            Some(&present),
23299            MissingLayout::Numpy,
23300        )
23301        .mean();
23302        assert_eq!(
23303            PandasReductions::int64_mean_skipping(&nanos, NAT).to_bits(),
23304            expected.to_bits()
23305        );
23306        // NEGATIVE: every slot missing is NaN, not a mean of the zeros.
23307        assert!(PandasReductions::int64_mean_skipping(&[NAT, NAT], NAT).is_nan());
23308        assert!(PandasReductions::int64_mean_skipping(&[], NAT).is_nan());
23309    }
23310}
23311
23312/// pandas' default text-to-float64 conversion against live pandas 2.2.3
23313/// bits: `read_csv(StringIO('x\n' + token), dtype={'x': 'float64'})`
23314/// (br-frankenpandas-py3c0).
23315#[cfg(test)]
23316mod pandas_decimal_py3c0 {
23317    use super::{PandasDecimal, pandas_decimal_to_f64, pandas_int_to_f64};
23318
23319    fn bits(token: &str) -> u64 {
23320        match pandas_decimal_to_f64(token.as_bytes()) {
23321            PandasDecimal::Value(value) => value.to_bits(),
23322            other => panic!("{token:?}: {other:?}"),
23323        }
23324    }
23325
23326    #[test]
23327    fn tokens_convert_to_pandas_bits() {
23328        let cases = [
23329            ("9.890295358649789", 0x4023_c7d4_cb12_5ce4),
23330            ("0.8690736625851781286570704999", 0x3feb_cf73_91d3_c8f1),
23331            ("0.000000068288360759838675650889", 0x3e72_54bd_8bcd_610b),
23332            ("-0.0080749473608410608782560", 0xbf80_8999_16a7_63f3),
23333            ("99999999999999999", 0x4376_3457_85d8_a001),
23334            ("1234567890123456789012345", 0x44f0_56e0_f36a_6444),
23335            // 17 leading zeros are the 17 digits kept.
23336            ("00000000000000000.5", 0x0000_0000_0000_0000),
23337            ("-00000000000000000.5", 0x8000_0000_0000_0000),
23338            ("1.5E+10", 0x420b_f08e_b000_0000),
23339            ("-.5e-3", 0xbf40_624d_d2f1_a9fc),
23340            ("5.", 0x4014_0000_0000_0000),
23341            ("1e-320", 0x0000_0000_0000_07e8),
23342            ("2.5e-310", 0x0000_2e05_5c9a_3f6c),
23343            ("-1e-400", 0x8000_0000_0000_0000),
23344            // Below 1e-616: +0.0, the sign dropped.
23345            ("-1e-700", 0x0000_0000_0000_0000),
23346            // The exponent wraps as a 32-bit integer.
23347            ("1e-4294967296", 0x3ff0_0000_0000_0000),
23348            ("1.7976931348623157e308", 0x7fef_ffff_ffff_ffff),
23349            ("0.001e310", 0x7fac_7b1f_3cac_7433),
23350        ];
23351        for (token, expected) in cases {
23352            assert_eq!(bits(token), expected, "{token:?}");
23353        }
23354        // NEGATIVE: the correctly rounded value is not pandas'.
23355        let correctly_rounded: f64 = "9.890295358649789".parse().unwrap();
23356        assert_ne!(correctly_rounded.to_bits(), 0x4023_c7d4_cb12_5ce4);
23357    }
23358
23359    #[test]
23360    fn what_pandas_does_not_read_as_a_float() {
23361        for token in [
23362            "1e309",
23363            "0e400",
23364            "1.8e308",
23365            "1e+0000000000000000001",
23366            "1e-2147483649",
23367            "1e",
23368            "1e+",
23369            "1.5d3",
23370            "0x10",
23371            "1_000.5",
23372            "1..5",
23373        ] {
23374            assert_eq!(
23375                pandas_decimal_to_f64(token.as_bytes()),
23376                PandasDecimal::Rejected,
23377                "{token:?}"
23378            );
23379        }
23380        for token in ["inf", "-Infinity", "nan", ".", "-", "e5", "+.e1", "--1", ""] {
23381            assert_eq!(
23382                pandas_decimal_to_f64(token.as_bytes()),
23383                PandasDecimal::NotDecimal,
23384                "{token:?}"
23385            );
23386        }
23387    }
23388
23389    #[test]
23390    fn an_integer_in_a_float_column_takes_the_same_conversion() {
23391        assert_eq!(pandas_int_to_f64(-42).to_bits(), (-42.0_f64).to_bits());
23392        assert_eq!(
23393            pandas_int_to_f64(99_999_999_999_999_999).to_bits(),
23394            0x4376_3457_85d8_a001
23395        );
23396        assert_eq!(
23397            pandas_int_to_f64(-99_999_999_999_999_999).to_bits(),
23398            0xc376_3457_85d8_a001
23399        );
23400    }
23401
23402    /// The civil-date month shift is chrono's relativedelta (a date made,
23403    /// moved and read back) for every day of the month at its edges, leap
23404    /// and plain years, before and after 1970, sub-second times and month
23405    /// counts of either sign (br-frankenpandas-4g57c). NEGATIVE: a shift past
23406    /// datetime64[ns] (either end, or a month count near i64) is None, as
23407    /// chrono's timestamp is out of range.
23408    #[test]
23409    fn calendar_months_match_chrono_relativedelta_4g57c() {
23410        use chrono::{Datelike, NaiveDate};
23411
23412        use super::add_calendar_months_nanos;
23413        let reference = |nanos: i64, months: i64| -> Option<i64> {
23414            let at = chrono::DateTime::from_timestamp(
23415                nanos.div_euclid(1_000_000_000),
23416                u32::try_from(nanos.rem_euclid(1_000_000_000)).ok()?,
23417            )?
23418            .naive_utc();
23419            let total = i64::from(at.year())
23420                .checked_mul(12)?
23421                .checked_add(i64::from(at.month0()))?
23422                .checked_add(months)?;
23423            let year = i32::try_from(total.div_euclid(12)).ok()?;
23424            let month = u32::try_from(total.rem_euclid(12)).ok()? + 1;
23425            let last = (28..=31)
23426                .rev()
23427                .find(|day| NaiveDate::from_ymd_opt(year, month, *day).is_some())?;
23428            NaiveDate::from_ymd_opt(year, month, at.day().min(last))?
23429                .and_time(at.time())
23430                .and_utc()
23431                .timestamp_nanos_opt()
23432        };
23433        let day_nanos = 86_400_000_000_000_i64;
23434        let mut checked = 0;
23435        for year in [1678, 1699, 1900, 1969, 1970, 2000, 2023, 2024, 2100, 2261] {
23436            for month in 1..=12 {
23437                for day in [1, 15, 27, 28, 29, 30, 31] {
23438                    let Some(date) = NaiveDate::from_ymd_opt(year, month, day) else {
23439                        continue;
23440                    };
23441                    let Some(midnight) = date
23442                        .and_hms_opt(0, 0, 0)
23443                        .and_then(|at| at.and_utc().timestamp_nanos_opt())
23444                    else {
23445                        continue;
23446                    };
23447                    for time in [0, 1, 37_123_456_789, day_nanos - 1] {
23448                        let nanos = midnight + time;
23449                        for months in [-2400, -13, -12, -1, 0, 1, 2, 11, 12, 25, 1200] {
23450                            assert_eq!(
23451                                add_calendar_months_nanos(nanos, months),
23452                                reference(nanos, months),
23453                                "{nanos} + {months} months"
23454                            );
23455                            checked += 1;
23456                        }
23457                    }
23458                }
23459            }
23460        }
23461        assert!(checked > 30_000, "{checked}");
23462        // NEGATIVE: out of range at both ends and for absurd month counts.
23463        let last = i64::MAX - 1;
23464        assert_eq!(add_calendar_months_nanos(last, 1), None);
23465        assert_eq!(reference(last, 1), None);
23466        assert_eq!(add_calendar_months_nanos(i64::MIN + 1, -1), None);
23467        assert_eq!(add_calendar_months_nanos(0, i64::MAX), None);
23468        assert_eq!(add_calendar_months_nanos(0, i64::MIN), None);
23469        assert_eq!(add_calendar_months_nanos(0, 12 * 400), None);
23470        assert_eq!(super::add_calendar_months_days(i64::MAX, 1), None);
23471        assert_eq!(super::add_calendar_months_days(0, i64::MAX), None);
23472        // The clipped day: Jan 31 2024 + 1 month is Feb 29.
23473        let jan31 = 19_753 * day_nanos;
23474        assert_eq!(
23475            add_calendar_months_nanos(jan31, 1),
23476            Some(19_782 * day_nanos)
23477        );
23478    }
23479
23480    /// A numbered host value equals another as their numbers and hashes as
23481    /// its number, the host's own eq not asked; an unnumbered one asks it
23482    /// (br-frankenpandas-jq8qb). NEGATIVE: numbered values of different
23483    /// numbers differ though the host calls them equal; a numbered value
23484    /// beside an unnumbered one takes the host's answer.
23485    #[test]
23486    fn numbered_host_values_compare_and_hash_by_number_jq8qb() {
23487        use std::hash::{Hash, Hasher};
23488
23489        use super::{HostObject, HostValue, ObjectValue};
23490
23491        struct Numbered(Option<i64>, &'static str);
23492        impl HostObject for Numbered {
23493            fn host_eq(&self, other: &dyn HostObject) -> bool {
23494                other
23495                    .as_any()
23496                    .downcast_ref::<Self>()
23497                    .is_some_and(|other| other.1 == self.1)
23498            }
23499            fn host_repr(&self) -> String {
23500                self.1.to_owned()
23501            }
23502            fn host_str(&self) -> String {
23503                self.1.to_owned()
23504            }
23505            fn host_hash(&self) -> Option<u64> {
23506                Some(self.1.len() as u64)
23507            }
23508            fn host_cmp(&self, _other: &dyn HostObject) -> Option<std::cmp::Ordering> {
23509                None
23510            }
23511            fn as_any(&self) -> &dyn std::any::Any {
23512                self
23513            }
23514            fn host_number(&self) -> Option<i64> {
23515                self.0
23516            }
23517        }
23518        let hash = |value: &ObjectValue| {
23519            let mut hasher = std::hash::DefaultHasher::new();
23520            value.hash(&mut hasher);
23521            hasher.finish()
23522        };
23523        let cell = |number, name| ObjectValue::Host(HostValue::new(Numbered(number, name)));
23524        assert_eq!(cell(Some(7), "a"), cell(Some(7), "b"));
23525        assert_eq!(hash(&cell(Some(7), "a")), hash(&cell(Some(7), "bb")));
23526        assert_ne!(cell(Some(7), "a"), cell(Some(8), "a"));
23527        assert_eq!(cell(Some(7), "a"), cell(None, "a"));
23528        assert_ne!(cell(Some(7), "a"), cell(None, "b"));
23529        assert_eq!(cell(None, "a"), cell(None, "a"));
23530        assert_ne!(cell(None, "a"), cell(None, "b"));
23531        assert_eq!(hash(&cell(None, "ab")), hash(&cell(None, "cd")));
23532    }
23533}