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    #[serde(default, skip_serializing_if = "Option::is_none")]
2059    pub width: Option<NumericWidth>,
2060    /// Numpy scalar type of the fill, when it is not a Python scalar.
2061    /// Kept with the descriptor so arithmetic, snapshots and gathers retain
2062    /// the fill's boxing and numpy promotion behavior independently of the
2063    /// stored subtype (e.g. float32 values with a numpy.float64 fill).
2064    #[serde(default, skip_serializing_if = "Option::is_none")]
2065    pub fill_numpy_dtype: Option<String>,
2066}
2067
2068impl SparseDType {
2069    /// Construct a pandas-style sparse dtype descriptor.
2070    ///
2071    /// This records the logical dense value dtype plus the scalar value that is
2072    /// elided from storage. The concrete sparse column representation lives in
2073    /// fp-columnar; this descriptor is the shared public contract.
2074    pub fn new(value_dtype: DType, fill_value: Scalar) -> Result<Self, TypeError> {
2075        if matches!(value_dtype, DType::Null | DType::Sparse) {
2076            return Err(TypeError::InvalidSparseValueDType { dtype: value_dtype });
2077        }
2078
2079        let fill_value = if fill_value.is_missing() {
2080            Scalar::missing_for_dtype(value_dtype.clone())
2081        } else {
2082            cast_scalar_owned(fill_value, value_dtype.clone())?
2083        };
2084
2085        Ok(Self {
2086            value_dtype,
2087            fill_value,
2088            width: None,
2089            fill_numpy_dtype: None,
2090        })
2091    }
2092
2093    /// Render the pandas dtype name, `Sparse[<subtype>, <fill>]`.
2094    ///
2095    /// br-frankenpandas-3gxc6. [`DType::name`] can only answer `"Sparse"`: it
2096    /// is a `const fn` returning `&'static str` and `DType::Sparse` carries no
2097    /// payload, so the subtype and fill value — which live here — are lost by
2098    /// the time a caller has a bare [`DType`]. pandas never spells the bare
2099    /// form; even `pd.Series([1.5, 0.0]).astype("Sparse")` resolves to
2100    /// `Sparse[float64, nan]`.
2101    ///
2102    /// MEASURED, live pandas 2.2.3, `str(dtype)` / `dtype.name`:
2103    ///
2104    /// ```text
2105    ///   SparseDtype("int64",   0)     -> Sparse[int64, 0]
2106    ///   SparseDtype("int64",   7)     -> Sparse[int64, 7]
2107    ///   SparseDtype("float64", nan)   -> Sparse[float64, nan]
2108    ///   SparseDtype("float64", 0.0)   -> Sparse[float64, 0.0]
2109    ///   SparseDtype("bool",    False) -> Sparse[bool, False]
2110    ///   SparseDtype(object,    nan)   -> Sparse[object, nan]
2111    /// ```
2112    ///
2113    /// The fill is rendered by `scalar_to_string_for_astype`, which already
2114    /// spells every one of those cases the way pandas does in this position:
2115    /// `True`/`False` capitalised, integers bare, lowercase `nan`, and the
2116    /// trailing `.0` preserved on whole floats. Deliberately reusing it rather
2117    /// than writing a second float formatter — a divergence between the two
2118    /// would surface as a dtype name that no longer round-trips.
2119    #[must_use]
2120    pub fn pandas_name(&self) -> String {
2121        let subtype = self
2122            .width
2123            .map_or(self.value_dtype.name(), |width| width.name(false));
2124        let fill = match &self.fill_value {
2125            Scalar::Utf8(value) if value.contains('\'') && !value.contains('"') => {
2126                format!("{value:?}")
2127            }
2128            Scalar::Utf8(value) => format!(
2129                "'{}'",
2130                value
2131                    .replace('\\', "\\\\")
2132                    .replace('\'', "\\'")
2133                    .replace('\n', "\\n")
2134                    .replace('\r', "\\r")
2135                    .replace('\t', "\\t")
2136            ),
2137            value => scalar_to_string_for_astype(value.clone()),
2138        };
2139        format!("Sparse[{}, {}]", subtype, fill)
2140    }
2141}
2142
2143impl AsDType for SparseDType {
2144    fn as_dtype(&self) -> DType {
2145        DType::Sparse
2146    }
2147}
2148
2149/// Pandas-equivalent categorical dtype descriptor (`pd.CategoricalDtype`).
2150///
2151/// Encapsulates the optional category vocabulary and ordering semantics.
2152#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
2153pub struct CategoricalDtype {
2154    pub categories: Option<Vec<String>>,
2155    pub ordered: bool,
2156}
2157
2158pub type CategoricalDType = CategoricalDtype;
2159
2160impl CategoricalDtype {
2161    /// Construct a new `CategoricalDtype`.
2162    #[must_use]
2163    pub const fn new(categories: Option<Vec<String>>, ordered: bool) -> Self {
2164        Self {
2165            categories,
2166            ordered,
2167        }
2168    }
2169
2170    /// Return categories if known.
2171    #[must_use]
2172    pub fn categories(&self) -> Option<&[String]> {
2173        self.categories.as_deref()
2174    }
2175
2176    /// Return whether this categorical is ordered.
2177    #[must_use]
2178    pub const fn ordered(&self) -> bool {
2179        self.ordered
2180    }
2181
2182    /// Return the pandas dtype string name (`"category"`).
2183    #[must_use]
2184    pub const fn name(&self) -> &'static str {
2185        "category"
2186    }
2187
2188    /// Return the pandas kind character (`"O"`).
2189    #[must_use]
2190    pub const fn kind(&self) -> &'static str {
2191        "O"
2192    }
2193}
2194
2195impl AsDType for CategoricalDtype {
2196    fn as_dtype(&self) -> DType {
2197        DType::Categorical
2198    }
2199}
2200
2201impl std::fmt::Display for CategoricalDtype {
2202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2203        let ord_str = if self.ordered { "True" } else { "False" };
2204        match &self.categories {
2205            Some(cats) => write!(
2206                f,
2207                "CategoricalDtype(categories={cats:?}, ordered={ord_str})"
2208            ),
2209            None => write!(f, "CategoricalDtype(categories=None, ordered={ord_str})"),
2210        }
2211    }
2212}
2213
2214/// Pandas-equivalent period dtype descriptor (`pd.PeriodDtype`).
2215///
2216/// Represents time period durations with a specific frequency (default `"D"`).
2217#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2218pub struct PeriodDtype {
2219    pub freq: String,
2220}
2221
2222pub type PeriodDType = PeriodDtype;
2223
2224impl PeriodDtype {
2225    /// Construct a new `PeriodDtype` with given frequency.
2226    #[must_use]
2227    pub fn new(freq: impl Into<String>) -> Self {
2228        Self { freq: freq.into() }
2229    }
2230
2231    /// Return the period frequency string.
2232    #[must_use]
2233    pub fn freq(&self) -> &str {
2234        &self.freq
2235    }
2236
2237    /// Return the pandas dtype string name (`period[<freq>]`).
2238    #[must_use]
2239    pub fn name(&self) -> String {
2240        format!("period[{}]", self.freq)
2241    }
2242
2243    /// Return the pandas kind character (`"O"`).
2244    #[must_use]
2245    pub const fn kind(&self) -> &'static str {
2246        "O"
2247    }
2248}
2249
2250impl Default for PeriodDtype {
2251    fn default() -> Self {
2252        Self {
2253            freq: "D".to_string(),
2254        }
2255    }
2256}
2257
2258impl AsDType for PeriodDtype {
2259    fn as_dtype(&self) -> DType {
2260        DType::Period
2261    }
2262}
2263
2264impl std::fmt::Display for PeriodDtype {
2265    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2266        write!(f, "period[{}]", self.freq)
2267    }
2268}
2269
2270/// Pandas-equivalent interval dtype descriptor (`pd.IntervalDtype`).
2271///
2272/// Encapsulates the interval subtype and endpoint closure behavior.
2273#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2274pub struct IntervalDtype {
2275    pub subtype: DType,
2276    pub closed: Option<IntervalClosed>,
2277}
2278
2279pub type IntervalDType = IntervalDtype;
2280
2281impl IntervalDtype {
2282    /// Construct a new `IntervalDtype`.
2283    #[must_use]
2284    pub const fn new(subtype: DType, closed: Option<IntervalClosed>) -> Self {
2285        Self { subtype, closed }
2286    }
2287
2288    /// Return the interval subtype.
2289    #[must_use]
2290    pub const fn subtype(&self) -> &DType {
2291        &self.subtype
2292    }
2293
2294    /// Return the endpoint closure convention.
2295    #[must_use]
2296    pub const fn closed(&self) -> Option<IntervalClosed> {
2297        self.closed
2298    }
2299
2300    /// Return the pandas dtype string name (`"interval"`).
2301    #[must_use]
2302    pub const fn name(&self) -> &'static str {
2303        "interval"
2304    }
2305
2306    /// Return the pandas kind character (`"O"`).
2307    #[must_use]
2308    pub const fn kind(&self) -> &'static str {
2309        "O"
2310    }
2311}
2312
2313impl Default for IntervalDtype {
2314    fn default() -> Self {
2315        Self {
2316            subtype: DType::Float64,
2317            closed: Some(IntervalClosed::Right),
2318        }
2319    }
2320}
2321
2322impl AsDType for IntervalDtype {
2323    fn as_dtype(&self) -> DType {
2324        DType::Interval
2325    }
2326}
2327
2328impl std::fmt::Display for IntervalDtype {
2329    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2330        match self.closed {
2331            Some(c) => write!(f, "interval[{}, {c}]", self.subtype.name()),
2332            None => write!(f, "interval[{}]", self.subtype.name()),
2333        }
2334    }
2335}
2336
2337#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
2338#[serde(rename_all = "snake_case")]
2339pub enum NullKind {
2340    Null,
2341    NaN,
2342    NaT,
2343}
2344
2345/// JSON spelling of a `Scalar::Float64` payload. JSON has no infinity:
2346/// serde_json writes a non-finite `f64` as `null` and cannot read that back,
2347/// so a division-by-zero answer could not travel through a fixture or the
2348/// oracle at all. ±inf is spelled `"inf"` / `"-inf"` (the pandas oracle emits
2349/// the same strings); finite values and NaN serialize exactly as before, and
2350/// the `null` serde_json writes for NaN now reads back as NaN.
2351/// (br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.3)
2352mod float64_json {
2353    use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
2354
2355    pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
2356        if value.is_infinite() {
2357            serializer.serialize_str(if value.is_sign_positive() {
2358                "inf"
2359            } else {
2360                "-inf"
2361            })
2362        } else {
2363            serializer.serialize_f64(*value)
2364        }
2365    }
2366
2367    #[derive(Deserialize)]
2368    #[serde(untagged)]
2369    enum Repr {
2370        Number(f64),
2371        Text(String),
2372        Null(()),
2373    }
2374
2375    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
2376        match Repr::deserialize(deserializer)? {
2377            Repr::Number(value) => Ok(value),
2378            Repr::Text(text) => match text.as_str() {
2379                "inf" => Ok(f64::INFINITY),
2380                "-inf" => Ok(f64::NEG_INFINITY),
2381                other => Err(D::Error::custom(format!(
2382                    "float64 value must be a number, \"inf\" or \"-inf\", got {other:?}"
2383                ))),
2384            },
2385            Repr::Null(()) => Ok(f64::NAN),
2386        }
2387    }
2388}
2389
2390#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2391#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
2392pub enum Scalar {
2393    Null(NullKind),
2394    Bool(bool),
2395    Int64(i64),
2396    Float64(#[serde(with = "float64_json")] f64),
2397    #[serde(alias = "string", alias = "str")]
2398    Utf8(String),
2399    Timedelta64(i64),
2400    /// Nanoseconds since Unix epoch. Matches pandas `datetime64[ns]`.
2401    /// Uses `Timestamp::NAT` (i64::MIN) for missing values.
2402    Datetime64(i64),
2403    /// Period value (ordinal + frequency). A `Period` whose `ordinal` is
2404    /// `i64::MIN` is NaT (missing). The frequency is carried so writers can
2405    /// render the pandas calendar string (`2024Q1`, `2024-03`, ...) — the
2406    /// calendar string is not recoverable from the ordinal alone, since
2407    /// different frequencies share overlapping ordinal axes.
2408    Period(Period),
2409    /// Numeric interval value. Missing values remain `Scalar::Null`.
2410    Interval(Interval),
2411    /// A pandas object cell none of the kinds above holds: a list
2412    /// (`str.split`'s cells, `Series([[1, 2], [3]])`) or a host-language
2413    /// value the core only carries (fvsao.33).
2414    Object(ObjectValue),
2415}
2416
2417/// A pandas object cell that is not one of [`Scalar`]'s value kinds: a list,
2418/// or a value of the host language (a Python `datetime.date`, dict, numpy
2419/// dtype) that the core carries without reading (fvsao.33).
2420#[derive(Clone)]
2421pub enum ObjectValue {
2422    /// A list of values, compared and printed as Python's list.
2423    List(std::sync::Arc<[Scalar]>),
2424    /// A bytes value, compared and printed as Python's bytes (`b'ab'`):
2425    /// `str.encode`'s cells. The core reads it, so a bytes column needs no
2426    /// host (4qg5w.8).
2427    Bytes(std::sync::Arc<[u8]>),
2428    /// A host-language value, opaque to the core.
2429    Host(HostValue),
2430}
2431
2432/// A host-language value an object cell carries - the Python binding's
2433/// objects: compared and printed by the host itself.
2434pub trait HostObject: Send + Sync {
2435    /// `self == other` in the host language.
2436    fn host_eq(&self, other: &dyn HostObject) -> bool;
2437    /// The host's `repr` (`datetime.date(2024, 1, 5)`).
2438    fn host_repr(&self) -> String;
2439    /// The host's `str` (`2024-01-05`), what `astype(str)` makes of it.
2440    fn host_str(&self) -> String;
2441    /// The cell as pandas displays it in a repr (`pprint_thing`), where that
2442    /// differs from its `str`: a tuple's or array's items unquoted (`(a, 1)`,
2443    /// `[1, 2]`); by default its `str`.
2444    fn host_pprint(&self) -> String {
2445        self.host_str()
2446    }
2447    /// The host's hash, None for an unhashable value (a dict).
2448    fn host_hash(&self) -> Option<u64>;
2449    /// `self` ordered against `other` in the host language (Python's `<` /
2450    /// `>` / `==`), None where the host cannot order them (a date against a
2451    /// time, two dicts).
2452    fn host_cmp(&self, other: &dyn HostObject) -> Option<std::cmp::Ordering>;
2453    /// `self == other` in the host language for a plain value (numpy's
2454    /// `dtype('float64') == 'float64'` is True); false unless the host says so.
2455    fn host_eq_scalar(&self, _other: &Scalar) -> bool {
2456        false
2457    }
2458    /// The value's type as the host's own errors name it (`datetime.date`,
2459    /// `dict`), for a refusal pandas lets the host raise.
2460    fn host_type_name(&self) -> String {
2461        "object".to_owned()
2462    }
2463    /// The value itself, for the host that made it to take back.
2464    fn as_any(&self) -> &dyn std::any::Any;
2465    /// A number standing for the value where the host's values of its kind
2466    /// are equal exactly when their numbers are, and equal to no value
2467    /// without one (a date's day): [`HostValue`] keeps it, and equal cells
2468    /// with one are found and hashed without the host (br-frankenpandas-jq8qb). None by
2469    /// default.
2470    fn host_number(&self) -> Option<i64> {
2471        None
2472    }
2473}
2474
2475/// How many host objects are alive (see [`host_values_block_workers`]).
2476static LIVE_HOST_VALUES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2477
2478/// Whether this process's callers may hold a host lock (see
2479/// [`declare_host_lock`]).
2480static HOST_LOCK_DECLARED: std::sync::atomic::AtomicBool =
2481    std::sync::atomic::AtomicBool::new(false);
2482
2483/// Declare that callers into the core may hold a host lock that host objects
2484/// need - the Python binding, whose every call holds the GIL, declares it
2485/// when its module loads. Without it no worker is ever blocked.
2486pub fn declare_host_lock() {
2487    HOST_LOCK_DECLARED.store(true, std::sync::atomic::Ordering::Relaxed);
2488}
2489
2490/// Whether a parallel kernel must run inline (one worker): a host value
2491/// compares, hashes and prints through its host (Python), which a worker
2492/// thread reaches only by taking the host's lock (the GIL); when the thread
2493/// that spawned the worker holds that lock while it waits for the worker,
2494/// both wait forever - `DataFrame.groupby(dates).rank()` hung that way
2495/// (4qg5w.13). So while any host object is alive in a process whose callers
2496/// may hold that lock, kernels size themselves to one worker.
2497#[must_use]
2498pub fn host_values_block_workers() -> bool {
2499    workers_blocked(
2500        HOST_LOCK_DECLARED.load(std::sync::atomic::Ordering::Relaxed),
2501        LIVE_HOST_VALUES.load(std::sync::atomic::Ordering::Relaxed),
2502    )
2503}
2504
2505/// The rule of [`host_values_block_workers`], free of process state.
2506const fn workers_blocked(host_lock_declared: bool, live_host_values: usize) -> bool {
2507    host_lock_declared && live_host_values > 0
2508}
2509
2510/// A host object, counted alive while any handle to it exists. The object
2511/// lives in the slot itself (one allocation a host value, where a boxed
2512/// object in a slot made two; br-frankenpandas-jq8qb).
2513struct HostSlot<T: ?Sized> {
2514    /// The object's [`HostObject::host_number`], read once.
2515    number: Option<i64>,
2516    object: T,
2517}
2518
2519impl<T: ?Sized> Drop for HostSlot<T> {
2520    fn drop(&mut self) {
2521        LIVE_HOST_VALUES.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2522    }
2523}
2524
2525/// A shared handle on a [`HostObject`].
2526#[derive(Clone)]
2527pub struct HostValue(std::sync::Arc<HostSlot<dyn HostObject>>);
2528
2529impl HostValue {
2530    #[must_use]
2531    pub fn new(object: impl HostObject + 'static) -> Self {
2532        LIVE_HOST_VALUES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2533        Self(std::sync::Arc::new(HostSlot {
2534            number: object.host_number(),
2535            object,
2536        }))
2537    }
2538
2539    #[must_use]
2540    pub fn object(&self) -> &dyn HostObject {
2541        &self.0.object
2542    }
2543
2544    /// The object's [`HostObject::host_number`].
2545    #[must_use]
2546    pub fn number(&self) -> Option<i64> {
2547        self.0.number
2548    }
2549}
2550
2551impl PartialEq for HostValue {
2552    fn eq(&self, other: &Self) -> bool {
2553        std::sync::Arc::ptr_eq(&self.0, &other.0)
2554            || match (self.number(), other.number()) {
2555                // Two numbered values: equal as their numbers, the host not
2556                // asked (a call into it and a downcast a compare; br-frankenpandas-jq8qb).
2557                (Some(left), Some(right)) => left == right,
2558                _ => self.object().host_eq(other.object()),
2559            }
2560    }
2561}
2562
2563impl std::fmt::Debug for HostValue {
2564    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2565        formatter.write_str(&self.object().host_repr())
2566    }
2567}
2568
2569impl ObjectValue {
2570    /// A list cell of `items`.
2571    #[must_use]
2572    pub fn list(items: Vec<Scalar>) -> Self {
2573        Self::List(items.into())
2574    }
2575
2576    /// The items of a list cell.
2577    #[must_use]
2578    pub fn as_list(&self) -> Option<&[Scalar]> {
2579        match self {
2580            Self::List(items) => Some(items),
2581            Self::Bytes(_) | Self::Host(_) => None,
2582        }
2583    }
2584
2585    /// A bytes cell of `data`.
2586    #[must_use]
2587    pub fn bytes(data: Vec<u8>) -> Self {
2588        Self::Bytes(data.into())
2589    }
2590
2591    /// The bytes of a bytes cell.
2592    #[must_use]
2593    pub fn as_bytes(&self) -> Option<&[u8]> {
2594        match self {
2595            Self::Bytes(data) => Some(data),
2596            Self::List(_) | Self::Host(_) => None,
2597        }
2598    }
2599
2600    /// The cell as Python's `repr` spells it (`[1, 'a', None]`, `b'ab'`).
2601    #[must_use]
2602    pub fn repr(&self) -> String {
2603        match self {
2604            Self::List(items) => {
2605                let parts: Vec<String> = items.iter().map(Scalar::python_repr).collect();
2606                format!("[{}]", parts.join(", "))
2607            }
2608            Self::Bytes(data) => python_bytes_repr(data),
2609            Self::Host(value) => value.object().host_repr(),
2610        }
2611    }
2612
2613    /// The cell as pandas displays it in a repr (pandas' `pprint_thing`): a
2614    /// list's items unquoted (`[1, a]`), a host value as the host pprints it.
2615    #[must_use]
2616    pub fn pprint(&self) -> String {
2617        match self {
2618            Self::List(items) => {
2619                let parts: Vec<String> = items
2620                    .iter()
2621                    .map(|item| match item {
2622                        Scalar::Utf8(text) => text.clone(),
2623                        Scalar::Object(object) => object.pprint(),
2624                        other => other.python_repr(),
2625                    })
2626                    .collect();
2627                format!("[{}]", parts.join(", "))
2628            }
2629            Self::Bytes(data) => python_bytes_repr(data),
2630            Self::Host(value) => value.object().host_pprint(),
2631        }
2632    }
2633
2634    /// The cell's Python type as Python's errors name it (`list`, `bytes`,
2635    /// `datetime.date`).
2636    #[must_use]
2637    pub fn type_name(&self) -> String {
2638        match self {
2639            Self::List(_) => "list".to_owned(),
2640            Self::Bytes(_) => "bytes".to_owned(),
2641            Self::Host(value) => value.object().host_type_name(),
2642        }
2643    }
2644
2645    /// Python's `==` between this cell and a plain value: a host value asks
2646    /// the host (a dtype equals its name), a list or bytes never equals one
2647    /// (`b'a' == 'a'` is False).
2648    #[must_use]
2649    pub fn python_eq_scalar(&self, other: &Scalar) -> bool {
2650        match self {
2651            Self::Host(value) => value.object().host_eq_scalar(other),
2652            Self::List(_) | Self::Bytes(_) => false,
2653        }
2654    }
2655
2656    /// Python's ordering of two cells, None where Python raises: host values
2657    /// by the host, lists item by item (a shorter prefix first), bytes by
2658    /// byte, and cells of different kinds unordered.
2659    #[must_use]
2660    pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2661        match (self, other) {
2662            (Self::Bytes(left), Self::Bytes(right)) => Some(left.cmp(right)),
2663            (Self::Host(left), Self::Host(right)) => {
2664                if left == right {
2665                    Some(std::cmp::Ordering::Equal)
2666                } else {
2667                    left.object().host_cmp(right.object())
2668                }
2669            }
2670            (Self::List(left), Self::List(right)) => {
2671                for (a, b) in left.iter().zip(right.iter()) {
2672                    if a != b {
2673                        let ordering = a.python_cmp(b)?;
2674                        if ordering.is_ne() {
2675                            return Some(ordering);
2676                        }
2677                    }
2678                }
2679                Some(left.len().cmp(&right.len()))
2680            }
2681            _ => None,
2682        }
2683    }
2684
2685    /// A total order over cells, for sorted labels and ordered maps: Python's
2686    /// ordering where it has one; otherwise a list before a host value, then
2687    /// the reprs, then identity - so two unequal cells are never Equal and
2688    /// equal cells always are.
2689    #[must_use]
2690    pub fn total_cmp(&self, other: &Self) -> std::cmp::Ordering {
2691        use std::cmp::Ordering;
2692        if self == other {
2693            return Ordering::Equal;
2694        }
2695        if let Some(ordering) = self.python_cmp(other).filter(|ordering| ordering.is_ne()) {
2696            return ordering;
2697        }
2698        let rank = |cell: &Self| match cell {
2699            Self::List(_) => 0_u8,
2700            Self::Bytes(_) => 1,
2701            Self::Host(_) => 2,
2702        };
2703        rank(self)
2704            .cmp(&rank(other))
2705            .then_with(|| self.repr().cmp(&other.repr()))
2706            .then_with(|| self.address().cmp(&other.address()))
2707    }
2708
2709    /// Where the cell's shared data lives: the last tie-break of
2710    /// [`Self::total_cmp`] between unequal cells that print alike.
2711    fn address(&self) -> usize {
2712        match self {
2713            Self::List(items) => items.as_ptr().addr(),
2714            Self::Bytes(data) => data.as_ptr().addr(),
2715            Self::Host(value) => std::sync::Arc::as_ptr(&value.0).cast::<()>().addr(),
2716        }
2717    }
2718}
2719
2720/// Python's `repr` of a bytes value: `b'...'` (double quotes when it holds a
2721/// `'` and no `"`), printable ASCII as itself, `\\`, `\t`, `\n`, `\r` and
2722/// the quote escaped, every other byte as `\xNN`.
2723#[must_use]
2724pub fn python_bytes_repr(data: &[u8]) -> String {
2725    let quote = if data.contains(&b'\'') && !data.contains(&b'"') {
2726        b'"'
2727    } else {
2728        b'\''
2729    };
2730    let mut out = String::with_capacity(data.len() + 3);
2731    out.push('b');
2732    out.push(char::from(quote));
2733    for &byte in data {
2734        match byte {
2735            b'\\' => out.push_str("\\\\"),
2736            b'\t' => out.push_str("\\t"),
2737            b'\n' => out.push_str("\\n"),
2738            b'\r' => out.push_str("\\r"),
2739            _ if byte == quote => {
2740                out.push('\\');
2741                out.push(char::from(byte));
2742            }
2743            0x20..=0x7e => out.push(char::from(byte)),
2744            _ => out.push_str(&format!("\\x{byte:02x}")),
2745        }
2746    }
2747    out.push(char::from(quote));
2748    out
2749}
2750
2751impl PartialOrd for ObjectValue {
2752    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2753        Some(self.cmp(other))
2754    }
2755}
2756
2757/// [`ObjectValue::total_cmp`], so a cell can be an ordered label.
2758impl Ord for ObjectValue {
2759    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2760        self.total_cmp(other)
2761    }
2762}
2763
2764impl PartialEq for ObjectValue {
2765    fn eq(&self, other: &Self) -> bool {
2766        match (self, other) {
2767            (Self::List(left), Self::List(right)) => left == right,
2768            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2769            (Self::Host(left), Self::Host(right)) => left == right,
2770            _ => false,
2771        }
2772    }
2773}
2774
2775/// So a cell can key a hash map (groupby, unique, isin): lists by their
2776/// items' reprs, host values by the host's hash (their repr when the host
2777/// has none).
2778impl Eq for ObjectValue {}
2779
2780impl std::hash::Hash for ObjectValue {
2781    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2782        match self {
2783            Self::List(items) => {
2784                0_u8.hash(state);
2785                for item in items.iter() {
2786                    item.python_repr().hash(state);
2787                }
2788            }
2789            Self::Bytes(data) => {
2790                2_u8.hash(state);
2791                data.hash(state);
2792            }
2793            Self::Host(value) => {
2794                1_u8.hash(state);
2795                // A numbered value hashes as its number, as it compares
2796                // (br-frankenpandas-jq8qb).
2797                if let Some(number) = value.number() {
2798                    number.hash(state);
2799                    return;
2800                }
2801                match value.object().host_hash() {
2802                    Some(hash) => hash.hash(state),
2803                    None => value.object().host_repr().hash(state),
2804                }
2805            }
2806        }
2807    }
2808}
2809
2810impl std::fmt::Debug for ObjectValue {
2811    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2812        formatter.write_str(&self.repr())
2813    }
2814}
2815
2816/// Python's `str` of the cell - what `astype(str)` and the writers produce:
2817/// a list or bytes as its repr (`['a', 1]`, `b'ab'`), a host value as its
2818/// str.
2819impl std::fmt::Display for ObjectValue {
2820    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2821        match self {
2822            Self::List(_) | Self::Bytes(_) => formatter.write_str(&self.repr()),
2823            Self::Host(value) => formatter.write_str(&value.object().host_str()),
2824        }
2825    }
2826}
2827
2828/// A list cell serializes as the sequence of its items, a bytes cell as
2829/// `{"bytes": [..]}`; a host value has no serialized form.
2830impl Serialize for ObjectValue {
2831    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2832        match self {
2833            Self::List(items) => items.as_ref().serialize(serializer),
2834            Self::Bytes(data) => SerializedObject::Bytes {
2835                bytes: data.to_vec(),
2836            }
2837            .serialize(serializer),
2838            Self::Host(_) => Err(serde::ser::Error::custom(
2839                "a host-language object cell cannot be serialized",
2840            )),
2841        }
2842    }
2843}
2844
2845/// The serialized forms of an object cell: a list's items, or a bytes
2846/// value's bytes.
2847#[derive(Serialize, Deserialize)]
2848#[serde(untagged)]
2849enum SerializedObject {
2850    List(Vec<Scalar>),
2851    Bytes { bytes: Vec<u8> },
2852}
2853
2854impl<'de> Deserialize<'de> for ObjectValue {
2855    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2856        Ok(match SerializedObject::deserialize(deserializer)? {
2857            SerializedObject::List(items) => Self::list(items),
2858            SerializedObject::Bytes { bytes } => Self::bytes(bytes),
2859        })
2860    }
2861}
2862
2863impl std::fmt::Display for Scalar {
2864    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2865        match self {
2866            Self::Null(NullKind::NaN) => write!(f, "NaN"),
2867            Self::Null(NullKind::NaT) => write!(f, "NaT"),
2868            Self::Null(NullKind::Null) => write!(f, "None"),
2869            Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
2870            Self::Int64(v) => write!(f, "{v}"),
2871            Self::Float64(v) => write!(f, "{v}"),
2872            Self::Utf8(s) => write!(f, "{s}"),
2873            Self::Timedelta64(nanos) => write!(f, "{}", Timedelta::format(*nanos)),
2874            Self::Datetime64(nanos) => {
2875                if *nanos == Timestamp::NAT {
2876                    write!(f, "NaT")
2877                } else {
2878                    write!(f, "Timestamp[{nanos}]")
2879                }
2880            }
2881            Self::Period(p) => {
2882                if p.ordinal == i64::MIN {
2883                    write!(f, "NaT")
2884                } else {
2885                    write!(f, "{}", p.calendar_string())
2886                }
2887            }
2888            Self::Interval(interval) => write!(f, "{interval}"),
2889            Self::Object(object) => write!(f, "{object}"),
2890        }
2891    }
2892}
2893
2894impl Scalar {
2895    /// Python's ordering of two values: numbers by value, text by code
2896    /// point, instants, durations and same-frequency periods by their
2897    /// payload, intervals by (left, right), object cells by
2898    /// [`ObjectValue::python_cmp`]; None where
2899    /// Python raises (a number against text, a list against a tuple, two
2900    /// dicts).
2901    #[must_use]
2902    pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2903        let numeric =
2904            |value: &Self| matches!(value, Self::Bool(_) | Self::Int64(_) | Self::Float64(_));
2905        match (self, other) {
2906            (Self::Utf8(a), Self::Utf8(b)) => Some(a.cmp(b)),
2907            (Self::Datetime64(a), Self::Datetime64(b))
2908            | (Self::Timedelta64(a), Self::Timedelta64(b)) => Some(a.cmp(b)),
2909            (Self::Period(a), Self::Period(b)) if a.freq == b.freq => {
2910                Some(a.ordinal.cmp(&b.ordinal))
2911            }
2912            (Self::Interval(a), Self::Interval(b)) => Some(
2913                a.left
2914                    .partial_cmp(&b.left)?
2915                    .then(a.right.partial_cmp(&b.right)?),
2916            ),
2917            (Self::Object(a), Self::Object(b)) => a.python_cmp(b),
2918            _ if numeric(self) && numeric(other) => {
2919                self.to_f64().ok()?.partial_cmp(&other.to_f64().ok()?)
2920            }
2921            _ => None,
2922        }
2923    }
2924
2925    /// The two types Python's TypeError names when it cannot order `self`
2926    /// against `other` (see [`Self::python_cmp`]): two lists by the first
2927    /// unequal items they hold (`[1] < ['a']` names 'int' and 'str'), any
2928    /// other pair by their own types.
2929    #[must_use]
2930    pub fn python_cmp_type_names(&self, other: &Self) -> (String, String) {
2931        if let (Self::Object(ObjectValue::List(left)), Self::Object(ObjectValue::List(right))) =
2932            (self, other)
2933            && let Some((a, b)) = left.iter().zip(right.iter()).find(|(a, b)| a != b)
2934        {
2935            return a.python_cmp_type_names(b);
2936        }
2937        (self.python_type_name(), other.python_type_name())
2938    }
2939
2940    /// The value's Python type as Python's errors name it (`str`, `int`,
2941    /// `Timestamp`, `list`), for a TypeError pandas lets Python raise.
2942    #[must_use]
2943    pub fn python_type_name(&self) -> String {
2944        match self {
2945            Self::Null(NullKind::NaN) | Self::Float64(_) => "float",
2946            Self::Null(NullKind::NaT) => "NaTType",
2947            Self::Null(NullKind::Null) => "NoneType",
2948            Self::Bool(_) => "bool",
2949            Self::Int64(_) => "int",
2950            Self::Utf8(_) => "str",
2951            Self::Timedelta64(_) => "Timedelta",
2952            Self::Datetime64(_) => "Timestamp",
2953            Self::Period(_) => "Period",
2954            Self::Interval(_) => "Interval",
2955            Self::Object(object) => return object.type_name(),
2956        }
2957        .to_owned()
2958    }
2959
2960    /// The value as Python's `repr` spells it inside a container (`'a'`,
2961    /// `1`, `1.5`, `None`, `nan`, `[1, 2]`) - how a list cell prints its
2962    /// items.
2963    #[must_use]
2964    pub fn python_repr(&self) -> String {
2965        match self {
2966            Self::Null(NullKind::NaN) => "nan".to_owned(),
2967            Self::Null(NullKind::NaT) => "NaT".to_owned(),
2968            Self::Null(NullKind::Null) => "None".to_owned(),
2969            Self::Utf8(text) => {
2970                let quote = if text.contains('\'') && !text.contains('"') {
2971                    '"'
2972                } else {
2973                    '\''
2974                };
2975                let mut out = String::with_capacity(text.len() + 2);
2976                out.push(quote);
2977                for ch in text.chars() {
2978                    match ch {
2979                        '\\' => out.push_str("\\\\"),
2980                        '\n' => out.push_str("\\n"),
2981                        '\r' => out.push_str("\\r"),
2982                        '\t' => out.push_str("\\t"),
2983                        c if c == quote => {
2984                            out.push('\\');
2985                            out.push(c);
2986                        }
2987                        c => out.push(c),
2988                    }
2989                }
2990                out.push(quote);
2991                out
2992            }
2993            Self::Float64(value) => {
2994                if value.is_nan() {
2995                    "nan".to_owned()
2996                } else if value.is_infinite() {
2997                    if *value > 0.0 { "inf" } else { "-inf" }.to_owned()
2998                } else if value.fract() == 0.0 && value.abs() < 1e16 {
2999                    format!("{value:.1}")
3000                } else {
3001                    format!("{value}")
3002                }
3003            }
3004            Self::Object(object) => object.repr(),
3005            other => other.to_string(),
3006        }
3007    }
3008}
3009
3010/// Pandas `pd.NA` singleton representing missing data in nullable dtypes.
3011pub const NA: Scalar = Scalar::Null(NullKind::Null);
3012
3013/// Pandas `pd.NaT` singleton representing Not-a-Time in datetime/timedelta data.
3014pub const NAT: Scalar = Scalar::Null(NullKind::NaT);
3015
3016/// Alias for [`NAT`] matching pandas capitalization `pd.NaT`.
3017#[allow(non_upper_case_globals)]
3018pub const NaT: Scalar = NAT;
3019
3020// Ergonomic From impls (br-frankenpandas-esjjy / fd90.182). Mirrors
3021// IndexLabel's From<i64>/From<&str>/From<String> so users can write
3022//   let v: Vec<Scalar> = vec![1i64.into(), 2.0.into(), "three".into()];
3023// instead of the explicit Scalar::Int64(...)/Scalar::Float64(...) form.
3024//
3025// i64 maps to Int64 (more common than Timedelta64 in pandas-style code).
3026// Users wanting Timedelta64 should construct it explicitly with
3027// Scalar::Timedelta64(nanos) or via Timedelta::parse / to_timedelta.
3028
3029impl From<bool> for Scalar {
3030    fn from(value: bool) -> Self {
3031        Self::Bool(value)
3032    }
3033}
3034
3035impl From<i64> for Scalar {
3036    fn from(value: i64) -> Self {
3037        Self::Int64(value)
3038    }
3039}
3040
3041impl From<f64> for Scalar {
3042    fn from(value: f64) -> Self {
3043        Self::Float64(value)
3044    }
3045}
3046
3047impl From<&str> for Scalar {
3048    fn from(value: &str) -> Self {
3049        Self::Utf8(value.to_owned())
3050    }
3051}
3052
3053impl From<String> for Scalar {
3054    fn from(value: String) -> Self {
3055        Self::Utf8(value)
3056    }
3057}
3058
3059impl Scalar {
3060    #[inline]
3061    const fn debug_variant_name(&self) -> &'static str {
3062        match self {
3063            Self::Null(_) => "Null",
3064            Self::Bool(_) => "Bool",
3065            Self::Int64(_) => "Int64",
3066            Self::Float64(_) => "Float64",
3067            Self::Utf8(_) => "Utf8",
3068            Self::Timedelta64(_) => "Timedelta64",
3069            Self::Datetime64(_) => "Datetime64",
3070            Self::Period(_) => "Period",
3071            Self::Interval(_) => "Interval",
3072            Self::Object(_) => "Object",
3073        }
3074    }
3075
3076    #[must_use]
3077    pub fn dtype(&self) -> DType {
3078        match self {
3079            Self::Null(_) => DType::Null,
3080            Self::Bool(_) => DType::Bool,
3081            Self::Int64(_) => DType::Int64,
3082            Self::Float64(_) => DType::Float64,
3083            Self::Utf8(_) => DType::Utf8,
3084            Self::Timedelta64(_) => DType::Timedelta64,
3085            Self::Datetime64(_) => DType::datetime64_naive(),
3086            Self::Period(_) => DType::Period,
3087            Self::Interval(_) => DType::Interval,
3088            // pandas' object dtype, which this crate spells Utf8.
3089            Self::Object(_) => DType::Utf8,
3090        }
3091    }
3092
3093    #[must_use]
3094    pub fn is_missing(&self) -> bool {
3095        match self {
3096            Self::Null(_) => true,
3097            Self::Float64(v) => v.is_nan(),
3098            Self::Timedelta64(v) => *v == Timedelta::NAT,
3099            Self::Datetime64(v) => *v == Timestamp::NAT,
3100            Self::Period(p) => p.ordinal == i64::MIN,
3101            _ => false,
3102        }
3103    }
3104
3105    #[must_use]
3106    pub fn is_nan(&self) -> bool {
3107        matches!(self, Self::Null(NullKind::NaN)) || matches!(self, Self::Float64(v) if v.is_nan())
3108    }
3109
3110    /// Returns true if this is a Bool scalar.
3111    #[must_use]
3112    pub const fn is_bool(&self) -> bool {
3113        matches!(self, Self::Bool(_))
3114    }
3115
3116    /// Returns true if this is an Int64 scalar.
3117    #[must_use]
3118    pub const fn is_integer(&self) -> bool {
3119        matches!(self, Self::Int64(_))
3120    }
3121
3122    /// Returns true if this is a Float64 scalar.
3123    #[must_use]
3124    pub const fn is_float(&self) -> bool {
3125        matches!(self, Self::Float64(_))
3126    }
3127
3128    /// Returns true if this is a numeric scalar (Int64 or Float64).
3129    #[must_use]
3130    pub const fn is_numeric(&self) -> bool {
3131        matches!(self, Self::Int64(_) | Self::Float64(_))
3132    }
3133
3134    /// Returns true if this is a Utf8 (string) scalar.
3135    #[must_use]
3136    pub const fn is_string(&self) -> bool {
3137        matches!(self, Self::Utf8(_))
3138    }
3139
3140    /// Returns true if this is a Datetime64 scalar.
3141    #[must_use]
3142    pub const fn is_datetime(&self) -> bool {
3143        matches!(self, Self::Datetime64(_))
3144    }
3145
3146    /// Returns true if this is a Timedelta64 scalar.
3147    #[must_use]
3148    pub const fn is_timedelta(&self) -> bool {
3149        matches!(self, Self::Timedelta64(_))
3150    }
3151
3152    /// Returns true if this is a Period scalar.
3153    #[must_use]
3154    pub const fn is_period(&self) -> bool {
3155        matches!(self, Self::Period(_))
3156    }
3157
3158    /// Returns true if this is an Interval scalar.
3159    #[must_use]
3160    pub const fn is_interval(&self) -> bool {
3161        matches!(self, Self::Interval(_))
3162    }
3163
3164    /// Returns the wrapped i64 if this is an [`Scalar::Int64`] variant.
3165    #[must_use]
3166    pub const fn as_i64(&self) -> Option<i64> {
3167        match self {
3168            Self::Int64(v) => Some(*v),
3169            _ => None,
3170        }
3171    }
3172
3173    /// Alias for [`Scalar::as_i64`].
3174    #[must_use]
3175    pub const fn as_int(&self) -> Option<i64> {
3176        self.as_i64()
3177    }
3178
3179    /// Returns the wrapped f64 if this is a [`Scalar::Float64`] variant.
3180    #[must_use]
3181    pub const fn as_f64(&self) -> Option<f64> {
3182        match self {
3183            Self::Float64(v) => Some(*v),
3184            _ => None,
3185        }
3186    }
3187
3188    /// Alias for [`Scalar::as_f64`].
3189    #[must_use]
3190    pub const fn as_float(&self) -> Option<f64> {
3191        self.as_f64()
3192    }
3193
3194    /// Returns the wrapped bool if this is a [`Scalar::Bool`] variant.
3195    #[must_use]
3196    pub const fn as_bool(&self) -> Option<bool> {
3197        match self {
3198            Self::Bool(v) => Some(*v),
3199            _ => None,
3200        }
3201    }
3202
3203    /// Returns a string slice if this is a [`Scalar::Utf8`] variant.
3204    #[must_use]
3205    pub fn as_str(&self) -> Option<&str> {
3206        match self {
3207            Self::Utf8(s) => Some(s.as_str()),
3208            _ => None,
3209        }
3210    }
3211
3212    /// Returns the raw nanoseconds timestamp if this is a [`Scalar::Datetime64`] variant.
3213    #[must_use]
3214    pub const fn as_datetime_nanos(&self) -> Option<i64> {
3215        match self {
3216            Self::Datetime64(v) => Some(*v),
3217            _ => None,
3218        }
3219    }
3220
3221    /// Returns the raw nanoseconds duration if this is a [`Scalar::Timedelta64`] variant.
3222    #[must_use]
3223    pub const fn as_timedelta_nanos(&self) -> Option<i64> {
3224        match self {
3225            Self::Timedelta64(v) => Some(*v),
3226            _ => None,
3227        }
3228    }
3229
3230    /// Returns the period ordinal if this is a [`Scalar::Period`] variant.
3231    #[must_use]
3232    pub const fn as_period_ordinal(&self) -> Option<i64> {
3233        match self {
3234            Self::Period(p) => Some(p.ordinal),
3235            _ => None,
3236        }
3237    }
3238
3239    /// Returns the [`Interval`] if this is a [`Scalar::Interval`] variant.
3240    #[must_use]
3241    pub const fn as_interval(&self) -> Option<Interval> {
3242        match self {
3243            Self::Interval(i) => Some(*i),
3244            _ => None,
3245        }
3246    }
3247
3248    #[must_use]
3249    pub fn missing_for_dtype(dtype: DType) -> Self {
3250        match dtype {
3251            DType::Float64 => Self::Null(NullKind::NaN),
3252            // NOT NaN, and this is the whole reason the dtype exists. MEASURED,
3253            // live pandas 2.2.3: a Float64 lane stores pd.NA, and it coerces an
3254            // explicit NaN INPUT to pd.NA —
3255            //     pd.Series([float("nan")], dtype="Float64")[0]  ->  <NA>
3256            // whereas the numpy lane above keeps a real NaN. Giving this dtype
3257            // NullKind::NaN would make the two flavours indistinguishable, which
3258            // is exactly the gap br-frankenpandas-qkqfb was filed for.
3259            DType::Float64Nullable => Self::Null(NullKind::Null),
3260            DType::Timedelta64 => Self::Timedelta64(Timedelta::NAT),
3261            DType::Datetime64 { .. } => Self::Datetime64(Timestamp::NAT),
3262            DType::Period => Self::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
3263            DType::Null => Self::Null(NullKind::Null),
3264            DType::Bool
3265            | DType::BoolNullable
3266            | DType::Int64
3267            | DType::Int64Nullable
3268            | DType::Utf8
3269            | DType::Categorical
3270            | DType::Interval
3271            | DType::Sparse => Self::Null(NullKind::Null),
3272        }
3273    }
3274
3275    #[must_use]
3276    pub fn semantic_eq(&self, other: &Self) -> bool {
3277        match (self, other) {
3278            (Self::Float64(a), Self::Float64(b)) => {
3279                if a.is_nan() && b.is_nan() {
3280                    return true;
3281                }
3282                if *a == *b {
3283                    return true;
3284                }
3285                let diff = (*a - *b).abs();
3286                let max_abs = a.abs().max(b.abs());
3287                if max_abs == 0.0 {
3288                    diff < f64::EPSILON
3289                } else {
3290                    diff / max_abs < 1e-14
3291                }
3292            }
3293            (Self::Null(_), Self::Float64(v)) | (Self::Float64(v), Self::Null(_)) => v.is_nan(),
3294            // All Null kinds (Null / NaN / NaT) mark missingness; they are
3295            // semantically indistinguishable for oracle-parity checks even
3296            // though derived PartialEq would reject a cross-kind pair.
3297            // fp-frame normalizes Float64 column missing cells to
3298            // Null(NaN) at Column::new time, while fixture oracles encode
3299            // the canonical missing marker as Null(Null).
3300            (Self::Null(_), Self::Null(_)) => true,
3301            // The DTYPE-SENTINEL missings are missing too, and this function
3302            // already says so for every other flavour. `missing_for_dtype`
3303            // DEFINES the canonical missing for Timedelta64 as
3304            // `Timedelta64(Timedelta::NAT)`, for Datetime64 as
3305            // `Datetime64(Timestamp::NAT)` and for Period as ordinal
3306            // `i64::MIN`, and `is_missing()` returns true for all three — but
3307            // without this arm none of them could ever equal the `Null` marker
3308            // an oracle records for pandas' NaT, so a parity check compared a
3309            // raw i64::MIN bit pattern against a null and called it a value
3310            // mismatch.
3311            //
3312            // OBSERVED on fp_p2d_021_series_to_timedelta_negative_null_hardened:
3313            //   FP     timedelta64:-9223372036854775808
3314            //   pandas null           (the format has no `na_t` marker, so
3315            //                          `null` IS NaT there)
3316            //
3317            // `compare_join_expected` in fp-conformance already carried this as
3318            // a manual `|| (left.is_missing() && right.is_missing())`; putting
3319            // it here makes that clause redundant instead of special, and
3320            // covers the series and dataframe comparators that lacked it.
3321            //
3322            // This is a COMPARISON rule only. It deliberately does not touch
3323            // `missing_for_dtype`: fp-columnar's 2026-07-14 NullKind TRAP note
3324            // records that the sentinel and `Null(NaT)` representations coexist
3325            // inside one column and a uniform gather cannot reproduce the mix,
3326            // which is a storage-model question. (br-frankenpandas-xwxci)
3327            _ if self.is_missing() && other.is_missing() => true,
3328            // An Interval's `==` ignores its subtype (pandas' Interval(0, 3)
3329            // == Interval(0.0, 3.0)), but interval[int64] and
3330            // interval[float64] are different pandas dtypes - '(0, 3]' and
3331            // '(0.0, 3.0]' (fvsao.54).
3332            (Self::Interval(a), Self::Interval(b)) => a == b && a.subtype == b.subtype,
3333            _ => self == other,
3334        }
3335    }
3336
3337    #[must_use]
3338    pub fn semantic_le(&self, other: &Self) -> bool {
3339        match self.semantic_cmp(other) {
3340            std::cmp::Ordering::Less | std::cmp::Ordering::Equal => true,
3341            std::cmp::Ordering::Greater => false,
3342        }
3343    }
3344
3345    #[must_use]
3346    pub fn semantic_ge(&self, other: &Self) -> bool {
3347        match self.semantic_cmp(other) {
3348            std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => true,
3349            std::cmp::Ordering::Less => false,
3350        }
3351    }
3352
3353    #[must_use]
3354    pub fn is_null(&self) -> bool {
3355        matches!(self, Self::Null(_))
3356    }
3357
3358    #[must_use]
3359    pub fn is_na(&self) -> bool {
3360        self.is_missing()
3361    }
3362
3363    /// Return `true` if this scalar is NA/missing (alias for [`Self::is_na`]).
3364    #[must_use]
3365    pub fn isna(&self) -> bool {
3366        self.is_missing()
3367    }
3368
3369    /// Return `true` if this scalar is null (alias for [`Self::is_null`]).
3370    #[must_use]
3371    pub fn isnull(&self) -> bool {
3372        self.is_null()
3373    }
3374
3375    /// Return `true` if this scalar is not NA/missing (matches pandas `notna`).
3376    #[must_use]
3377    pub fn notna(&self) -> bool {
3378        !self.is_missing()
3379    }
3380
3381    /// Return `true` if this scalar is not null/missing (matches pandas `notnull`).
3382    #[must_use]
3383    pub fn notnull(&self) -> bool {
3384        !self.is_missing()
3385    }
3386
3387    /// Return `true` if this scalar is not NA/missing.
3388    #[must_use]
3389    pub fn is_not_na(&self) -> bool {
3390        !self.is_missing()
3391    }
3392
3393    /// Return `true` if this scalar is not NA/missing.
3394    #[must_use]
3395    pub fn not_na(&self) -> bool {
3396        !self.is_missing()
3397    }
3398
3399    #[must_use]
3400    pub fn coalesce(&self, other: &Self) -> Self {
3401        if self.is_missing() {
3402            other.clone()
3403        } else {
3404            self.clone()
3405        }
3406    }
3407
3408    #[must_use]
3409    pub fn semantic_cmp(&self, other: &Self) -> std::cmp::Ordering {
3410        match (self, other) {
3411            (Self::Int64(a), Self::Int64(b)) => a.cmp(b),
3412            (Self::Float64(a), Self::Float64(b)) => {
3413                a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
3414            }
3415            (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
3416            (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
3417            (Self::Null(a), Self::Null(b)) => a.cmp(b),
3418            (Self::Timedelta64(a), Self::Timedelta64(b)) => {
3419                if *a == Timedelta::NAT || *b == Timedelta::NAT {
3420                    std::cmp::Ordering::Equal
3421                } else {
3422                    a.cmp(b)
3423                }
3424            }
3425            (Self::Datetime64(a), Self::Datetime64(b)) => {
3426                if *a == Timestamp::NAT || *b == Timestamp::NAT {
3427                    std::cmp::Ordering::Equal
3428                } else {
3429                    a.cmp(b)
3430                }
3431            }
3432            (Self::Period(a), Self::Period(b)) => {
3433                if a.ordinal == i64::MIN || b.ordinal == i64::MIN {
3434                    std::cmp::Ordering::Equal
3435                } else {
3436                    a.ordinal.cmp(&b.ordinal)
3437                }
3438            }
3439            (Self::Interval(a), Self::Interval(b)) => a
3440                .left
3441                .partial_cmp(&b.left)
3442                .unwrap_or(std::cmp::Ordering::Equal)
3443                .then_with(|| {
3444                    a.right
3445                        .partial_cmp(&b.right)
3446                        .unwrap_or(std::cmp::Ordering::Equal)
3447                })
3448                .then_with(|| a.closed.cmp(&b.closed)),
3449            // Object cells (dates, lists) in Python's order (fvsao.66).
3450            (Self::Object(a), Self::Object(b)) => a.cmp(b),
3451            // Cross-numeric comparison
3452            (Self::Int64(a), Self::Float64(b)) => (*a as f64)
3453                .partial_cmp(b)
3454                .unwrap_or(std::cmp::Ordering::Equal),
3455            (Self::Float64(a), Self::Int64(b)) => a
3456                .partial_cmp(&(*b as f64))
3457                .unwrap_or(std::cmp::Ordering::Equal),
3458            // Derived Debug starts every variant with its static variant name.
3459            // Different variants therefore order by that name before either
3460            // payload is observed; compare those names without allocating.
3461            (a, b) => a.debug_variant_name().cmp(b.debug_variant_name()),
3462        }
3463    }
3464
3465    pub fn to_f64(&self) -> Result<f64, TypeError> {
3466        match self {
3467            Self::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
3468            Self::Int64(v) => Ok(*v as f64),
3469            Self::Float64(v) => Ok(*v),
3470            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3471            Self::Utf8(v) => Err(TypeError::NonNumericValue {
3472                value: v.clone(),
3473                dtype: DType::Utf8,
3474            }),
3475            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3476                kind: NullKind::NaT,
3477            }),
3478            Self::Timedelta64(v) => Err(TypeError::NonNumericValue {
3479                value: Timedelta::format(*v),
3480                dtype: DType::Timedelta64,
3481            }),
3482            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3483                kind: NullKind::NaT,
3484            }),
3485            Self::Datetime64(v) => Err(TypeError::NonNumericValue {
3486                value: format!("Timestamp[{v}]"),
3487                dtype: DType::datetime64_naive(),
3488            }),
3489            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3490                kind: NullKind::NaT,
3491            }),
3492            Self::Period(p) => Err(TypeError::NonNumericValue {
3493                value: p.calendar_string(),
3494                dtype: DType::Period,
3495            }),
3496            Self::Interval(v) => Err(TypeError::NonNumericValue {
3497                value: v.to_string(),
3498                dtype: DType::Interval,
3499            }),
3500            Self::Object(object) => Err(TypeError::NonNumericValue {
3501                value: object.repr(),
3502                dtype: DType::Utf8,
3503            }),
3504        }
3505    }
3506
3507    /// Try to convert to i64. Returns error for missing or non-numeric values.
3508    pub fn to_i64(&self) -> Result<i64, TypeError> {
3509        match self {
3510            Self::Bool(v) => Ok(if *v { 1 } else { 0 }),
3511            Self::Int64(v) => Ok(*v),
3512            Self::Float64(v) => Ok(*v as i64),
3513            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3514            Self::Utf8(v) => Err(TypeError::NonNumericValue {
3515                value: v.clone(),
3516                dtype: DType::Utf8,
3517            }),
3518            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3519                kind: NullKind::NaT,
3520            }),
3521            Self::Timedelta64(v) => Ok(*v),
3522            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3523                kind: NullKind::NaT,
3524            }),
3525            Self::Datetime64(v) => Ok(*v),
3526            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3527                kind: NullKind::NaT,
3528            }),
3529            Self::Period(p) => Ok(p.ordinal),
3530            Self::Interval(v) => Err(TypeError::NonNumericValue {
3531                value: v.to_string(),
3532                dtype: DType::Interval,
3533            }),
3534            Self::Object(object) => Err(TypeError::NonNumericValue {
3535                value: object.repr(),
3536                dtype: DType::Utf8,
3537            }),
3538        }
3539    }
3540
3541    /// Try to convert to bool. Returns error for missing values.
3542    pub fn to_bool(&self) -> Result<bool, TypeError> {
3543        match self {
3544            Self::Bool(v) => Ok(*v),
3545            Self::Int64(v) => Ok(*v != 0),
3546            Self::Float64(v) => Ok(*v != 0.0 && !v.is_nan()),
3547            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3548            Self::Utf8(v) => Ok(!v.is_empty()),
3549            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3550                kind: NullKind::NaT,
3551            }),
3552            Self::Timedelta64(v) => Ok(*v != 0),
3553            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3554                kind: NullKind::NaT,
3555            }),
3556            Self::Datetime64(v) => Ok(*v != 0),
3557            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3558                kind: NullKind::NaT,
3559            }),
3560            Self::Period(p) => Ok(p.ordinal != 0),
3561            Self::Interval(_) => Ok(true),
3562            // Python's truth: a list or bytes is true when it has items, any
3563            // other object true.
3564            Self::Object(ObjectValue::List(items)) => Ok(!items.is_empty()),
3565            Self::Object(ObjectValue::Bytes(data)) => Ok(!data.is_empty()),
3566            Self::Object(ObjectValue::Host(_)) => Ok(true),
3567        }
3568    }
3569
3570    /// Try to convert to string representation.
3571    pub fn to_str(&self) -> String {
3572        match self {
3573            Self::Bool(v) => if *v { "True" } else { "False" }.to_string(),
3574            Self::Int64(v) => v.to_string(),
3575            Self::Float64(v) => {
3576                if v.is_nan() {
3577                    "nan".to_string()
3578                } else if v.is_infinite() {
3579                    if *v > 0.0 { "inf" } else { "-inf" }.to_string()
3580                } else {
3581                    v.to_string()
3582                }
3583            }
3584            Self::Null(_) => "NaN".to_string(),
3585            Self::Utf8(v) => v.clone(),
3586            Self::Timedelta64(v) => Timedelta::format(*v),
3587            Self::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_string(),
3588            Self::Datetime64(v) => Timestamp::from_nanos(*v).isoformat(),
3589            Self::Period(p) if p.ordinal == i64::MIN => "NaT".to_string(),
3590            Self::Period(p) => p.calendar_string(),
3591            Self::Interval(v) => v.to_string(),
3592            Self::Object(object) => object.to_string(),
3593        }
3594    }
3595}
3596
3597#[derive(Debug, Error, Clone, PartialEq)]
3598pub enum TypeError {
3599    #[error("dtype coercion from {left:?} to {right:?} has no compatible common type")]
3600    IncompatibleDtypes { left: DType, right: DType },
3601    #[error("cannot cast scalar of dtype {from:?} to {to:?}")]
3602    InvalidCast { from: DType, to: DType },
3603    #[error("cannot cast float {value} to int64 without loss")]
3604    LossyFloatToInt { value: f64 },
3605    #[error("expected 0/1 for bool cast from int64 but found {value}")]
3606    InvalidBoolInt { value: i64 },
3607    #[error("expected 0.0/1.0 for bool cast from float64 but found {value}")]
3608    InvalidBoolFloat { value: f64 },
3609    #[error("value {value:?} has non-numeric dtype {dtype:?}")]
3610    NonNumericValue { value: String, dtype: DType },
3611    #[error("value is missing ({kind:?})")]
3612    ValueIsMissing { kind: NullKind },
3613    #[error("sparse value dtype cannot be {dtype:?}")]
3614    InvalidSparseValueDType { dtype: DType },
3615    #[error("interval_range step must be finite, positive, and not NaN (got {step})")]
3616    InvalidIntervalStep { step: f64 },
3617    #[error("interval_range step {step} does not evenly divide range end-start={span}")]
3618    IntervalStepDoesNotDivide { step: f64, span: f64 },
3619    #[error("interval_range requires exactly 3 of (start, end, periods, freq) to be specified")]
3620    IntervalRangeParameterCount,
3621    #[error("cannot parse '{value}' as {target}")]
3622    ValueNotParseable { value: String, target: String },
3623    #[error("{0}")]
3624    TimeZone(#[from] TimeZoneError),
3625    #[error("Cannot localize tz-aware Timestamp, use tz_convert for conversions")]
3626    AlreadyTzAware,
3627    #[error("Cannot convert tz-naive Timestamp, use tz_localize to localize")]
3628    TzNaiveCannotConvert,
3629}
3630
3631pub fn common_dtype(left: DType, right: DType) -> Result<DType, TypeError> {
3632    use DType::{
3633        Bool, BoolNullable, Categorical, Float64, Float64Nullable, Int64, Int64Nullable, Null,
3634        Sparse, Timedelta64,
3635    };
3636
3637    let out = match (&left, &right) {
3638        (a, b) if a == b => a.clone(),
3639        (Null, other) | (other, Null) => other.clone(),
3640        (Categorical, Categorical) => Categorical,
3641
3642        // Bool promotions (nullable absorbs non-nullable)
3643        (Bool, Int64) | (Int64, Bool) => Int64,
3644        (Bool, Int64Nullable) | (Int64Nullable, Bool) => Int64Nullable,
3645        (BoolNullable, Int64) | (Int64, BoolNullable) => Int64Nullable,
3646        (BoolNullable, Int64Nullable) | (Int64Nullable, BoolNullable) => Int64Nullable,
3647        (Bool, BoolNullable) | (BoolNullable, Bool) => BoolNullable,
3648        (Bool, Float64) | (Float64, Bool) => Float64,
3649        // MEASURED, live pandas 2.2.3:
3650        //     pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
3651        //         -> Float64        (the EXTENSION dtype, not numpy float64)
3652        // Flipped together with the Int64Nullable arm below; see the
3653        // associativity note there for why they cannot move independently.
3654        (BoolNullable, Float64) | (Float64, BoolNullable) => Float64Nullable,
3655
3656        // Int64 promotions (nullable absorbs non-nullable)
3657        (Int64, Float64) | (Float64, Int64) => Float64,
3658        // MEASURED, live pandas 2.2.3, both spellings agree:
3659        //     find_common_type([Int64, float64])                        -> Float64
3660        //     pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5])  -> Float64
3661        // i.e. the NULLABLE flavour wins, so the answer is Float64Nullable.
3662        //
3663        // ⚠ THIS ARM AND THE BoolNullable ARM ABOVE ARE ONE ATOMIC CHANGE. The
3664        // lattice is checked for associativity over ALL dtypes by
3665        // `common_dtype_lattice_axioms_be314`, and flipping only this arm breaks
3666        // it on (BoolNullable, Int64, Float64):
3667        //     (BN ∨ I64) ∨ F64 = Int64Nullable ∨ Float64 = Float64Nullable
3668        //     BN ∨ (I64 ∨ F64) = BN ∨ Float64            = Float64      ✗
3669        // Both arms flip, or neither does. (br-frankenpandas-qkqfb, unblocks
3670        // br-frankenpandas-f0aaa)
3671        (Int64Nullable, Float64) | (Float64, Int64Nullable) => Float64Nullable,
3672        (Int64, Int64Nullable) | (Int64Nullable, Int64) => Int64Nullable,
3673
3674        // Float64Nullable promotions. These are now REACHABLE: the two arms
3675        // above produce Float64Nullable, so anything that folds a dtype list
3676        // (melt's try_fold, combine_first's target_dtype) can feed it back in
3677        // here. They are what makes that fold associative.
3678        //
3679        // MEASURED, live pandas 2.2.3 ARITHMETIC (which is what this function
3680        // models -- see the Bool arms above, which follow arithmetic rather than
3681        // find_common_type, since find_common_type answers `object` for every
3682        // bool+numeric pair and FrankenPandas has no object dtype yet, that
3683        // being br-frankenpandas-hlcgl):
3684        //     Float64(ext) + float64(numpy)          -> Float64
3685        //     Int64(ext)   + Float64(ext)            -> Float64
3686        //     boolean(ext) + Float64(ext)            -> Float64
3687        // The nullable float absorbs every other numeric flavour, which also
3688        // makes it the top of the numeric lattice and keeps promotion
3689        // associative.
3690        (Float64Nullable, Float64) | (Float64, Float64Nullable) => Float64Nullable,
3691        (Float64Nullable, Int64) | (Int64, Float64Nullable) => Float64Nullable,
3692        (Float64Nullable, Int64Nullable) | (Int64Nullable, Float64Nullable) => Float64Nullable,
3693        (Float64Nullable, Bool) | (Bool, Float64Nullable) => Float64Nullable,
3694        (Float64Nullable, BoolNullable) | (BoolNullable, Float64Nullable) => Float64Nullable,
3695
3696        // Datetime/Timedelta
3697        (Timedelta64, Timedelta64) => Timedelta64,
3698        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
3699            if left_tz == right_tz =>
3700        {
3701            DType::Datetime64 {
3702                tz: left_tz.clone(),
3703            }
3704        }
3705
3706        (Sparse, _) | (_, Sparse) => {
3707            return Err(TypeError::IncompatibleDtypes {
3708                left: left.clone(),
3709                right: right.clone(),
3710            });
3711        }
3712        _ => {
3713            return Err(TypeError::IncompatibleDtypes { left, right });
3714        }
3715    };
3716
3717    Ok(out)
3718}
3719
3720pub fn infer_dtype(values: &[Scalar]) -> Result<DType, TypeError> {
3721    let mut current = DType::Null;
3722    let mut saw_utf8 = false;
3723    let mut saw_timedelta = false;
3724    let mut saw_datetime = false;
3725    let mut saw_non_utf8_non_null = false;
3726    // br-frankenpandas-rh1od: pandas constructs OBJECT columns whenever a
3727    // Python bool mixes with any numeric scalar ([True, 2] -> object,
3728    // measured live 2.2.3); numpy's bool<int common-type never fires at the
3729    // constructor. FrankenPandas coerced to Int64 here, which no pandas
3730    // constructor path produces. Strings already take the object bucket
3731    // below (DISC-005); bool+numeric joins them.
3732    let mut saw_bool = false;
3733    let mut saw_numeric = false;
3734    // A PeriodArray holds one freq: periods of two are incompatible, pandas'
3735    // object column of the periods as they are (their column held the first
3736    // freq, and a copy read the others in it - 2024-01 came back 2132Q1;
3737    // br-frankenpandas-h4bak).
3738    let mut period_freq: Option<PeriodFreq> = None;
3739
3740    // NOTE (br-frankenpandas-nywa8): inferring Float64 from a NaN-KIND missing
3741    // looks like the right central fix for pandas' int64 -> float64 promotion,
3742    // and it is NOT. `NullKind::NaN` is used throughout FrankenPandas as the
3743    // GENERIC missing marker, not specifically as "a float NaN" — e.g. short-row
3744    // padding and `missing_for_dtype(Float64)` both produce it. Promoting on it
3745    // broke 19 pre-existing fp-columnar tests (ffill returning Float64(1.0)
3746    // where Int64(1) was pinned, isin flipping a bool) because those columns are
3747    // legitimately Int64 with a generic missing. Measured, then reverted.
3748    //
3749    // The promotion has to be applied where a gap is INTRODUCED and the
3750    // introducer knows it is inventing one — see `concat_dataframes_*`, which
3751    // promotes locally. Do not move it back here without first giving
3752    // "pandas-introduced gap" a marker distinct from generic missingness.
3753    for value in values {
3754        if let Scalar::Period(period) = value
3755            && period.ordinal != i64::MIN
3756        {
3757            match period_freq {
3758                None => period_freq = Some(period.freq),
3759                Some(freq) if freq != period.freq => {
3760                    return Err(TypeError::IncompatibleDtypes {
3761                        left: DType::Period,
3762                        right: DType::Period,
3763                    });
3764                }
3765                Some(_) => {}
3766            }
3767        }
3768        match value.dtype() {
3769            DType::Null => {}
3770            DType::Utf8 => saw_utf8 = true,
3771            DType::Bool => {
3772                saw_bool = true;
3773                saw_non_utf8_non_null = true;
3774                current = common_dtype(current, DType::Bool)?;
3775            }
3776            DType::Int64 | DType::Float64 => {
3777                saw_numeric = true;
3778                saw_non_utf8_non_null = true;
3779                current = common_dtype(current, value.dtype())?;
3780            }
3781            DType::Timedelta64 => {
3782                saw_timedelta = true;
3783                if current == DType::Null {
3784                    current = DType::Timedelta64;
3785                } else if current != DType::Timedelta64 {
3786                    return Err(TypeError::IncompatibleDtypes {
3787                        left: current,
3788                        right: DType::Timedelta64,
3789                    });
3790                }
3791            }
3792            DType::Datetime64 { .. } => {
3793                saw_datetime = true;
3794                if current == DType::Null {
3795                    current = DType::datetime64_naive();
3796                } else if !current.is_datetime() {
3797                    return Err(TypeError::IncompatibleDtypes {
3798                        left: current,
3799                        right: DType::datetime64_naive(),
3800                    });
3801                }
3802            }
3803            other => {
3804                saw_non_utf8_non_null = true;
3805                current = common_dtype(current, other)?;
3806            }
3807        }
3808
3809        if saw_bool && saw_numeric {
3810            // Constructor inference follows pandas object-dtype behavior for
3811            // heterogeneous string/scalar payloads while arithmetic coercion
3812            // remains governed by the stricter common_dtype lattice.
3813            return Ok(DType::Utf8);
3814        }
3815        if saw_utf8 && saw_non_utf8_non_null {
3816            // Constructor inference follows pandas object-dtype behavior for
3817            // heterogeneous string/scalar payloads while arithmetic coercion
3818            // remains governed by the stricter common_dtype lattice.
3819            return Ok(DType::Utf8);
3820        }
3821        if saw_timedelta && saw_non_utf8_non_null {
3822            return Err(TypeError::IncompatibleDtypes {
3823                left: DType::Timedelta64,
3824                right: current,
3825            });
3826        }
3827        if saw_datetime && saw_non_utf8_non_null {
3828            return Err(TypeError::IncompatibleDtypes {
3829                left: DType::datetime64_naive(),
3830                right: current,
3831            });
3832        }
3833    }
3834
3835    if saw_utf8 {
3836        Ok(DType::Utf8)
3837    } else {
3838        Ok(current)
3839    }
3840}
3841
3842/// Cast a scalar to a target dtype, taking ownership to avoid redundant clones
3843/// when the value already has the correct type (AG-03: identity-cast skip).
3844pub fn cast_scalar_owned(value: Scalar, target: DType) -> Result<Scalar, TypeError> {
3845    let from = value.dtype();
3846    if from == target {
3847        return Ok(value);
3848    }
3849    // Int64 <-> Int64Nullable: same representation, just different dtype tracking
3850    if (from == DType::Int64 && target == DType::Int64Nullable)
3851        || (from == DType::Int64Nullable && target == DType::Int64)
3852    {
3853        return Ok(value);
3854    }
3855    // Bool <-> BoolNullable: same representation
3856    if (from == DType::Bool && target == DType::BoolNullable)
3857        || (from == DType::BoolNullable && target == DType::Bool)
3858    {
3859        return Ok(value);
3860    }
3861    // Float64 <-> Float64Nullable: same 8-byte payload, and a PRESENT value
3862    // round-trips unchanged in both directions. MEASURED, live pandas 2.2.3:
3863    //     pd.Series([1.5, None], dtype="Float64").astype("float64") -> [1.5, nan]
3864    //     pd.Series([1.5, None]).astype("Float64")                  -> [1.5, <NA>]
3865    // Only the MISSING marker differs, and a missing input never reaches here --
3866    // `value.is_missing()` below routes it to `missing_for_dtype(target)`, which
3867    // is what converts NaN <-> pd.NA. (br-frankenpandas-qkqfb)
3868    if (from == DType::Float64 && target == DType::Float64Nullable)
3869        || (from == DType::Float64Nullable && target == DType::Float64)
3870    {
3871        return Ok(value);
3872    }
3873    // A datetime scalar is an instant and a zone is its column's metadata, so
3874    // it takes any datetime64 dtype as it is (a fill or set value on a
3875    // tz-aware column was refused as an invalid cast).
3876    if from.is_datetime() && target.is_datetime() {
3877        return Ok(value);
3878    }
3879    if target == DType::Utf8 {
3880        return Ok(Scalar::Utf8(scalar_to_string_for_astype(value)));
3881    }
3882    // Per br-frankenpandas-cyi4h: pandas astype(bool) (the numpy bool dtype)
3883    // treats a float NaN as truthy -> True (bool(nan) is True), unlike the
3884    // nullable 'boolean' dtype which keeps NA. FP's NaN=missing model would
3885    // otherwise fall through to the missing branch below and yield a null.
3886    // Verified vs live pandas 2.2.3.
3887    if target == DType::Bool
3888        && let Scalar::Float64(v) = &value
3889        && v.is_nan()
3890    {
3891        return Ok(Scalar::Bool(true));
3892    }
3893    // TEMPORAL -> NUMPY bool IS NONZERO-TRUTHY ON THE RAW NANOSECONDS, and it
3894    // sits here for exactly the reason the NaN check above does: FP's
3895    // missing-value model would otherwise swallow NaT below, and pandas does not
3896    // treat it as missing here.
3897    //
3898    // MEASURED, live pandas 2.2.3, `.astype('bool')` beside `.astype('int64')`
3899    // so the rule is visible as one rule rather than four cases:
3900    //
3901    //   value                                 nanos                  bool
3902    //   Timestamp(0)                              0                 False
3903    //   Timestamp('2024-03-15 10:30:45.123..')  1.71e18               True
3904    //   Timestamp('1969-12-31 23:59:59.999..')       -1               True
3905    //   NaT (either dtype)          -9223372036854775808              True
3906    //   Timedelta(0)                              0                 False
3907    //   Timedelta('1 days')          86400000000000                   True
3908    //   Timedelta('-1 ns')                       -1                   True
3909    //
3910    // So `nanos != 0` is the whole rule, and NaT needs no case of its own: it IS
3911    // i64::MIN, which is nonzero. Only the epoch and a zero duration are False.
3912    //
3913    // ⚠️ THE NULLABLE `boolean` REFUSES ALL OF THESE, including the ones whose
3914    // nanos are 0 or 1 — `.astype('boolean')` raises "Need to pass bool-like
3915    // values" for EVERY row above, so it is the dtype it rejects, not the value.
3916    // That is why this is guarded on `DType::Bool` alone and why the strict
3917    // `BoolNullable` arm below is left without a temporal case.
3918    if target == DType::Bool {
3919        match &value {
3920            Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3921                return Ok(Scalar::Bool(*nanos != 0));
3922            }
3923            _ => {}
3924        }
3925    }
3926    // TEMPORAL -> NUMPY int64 IS RAW NANOSECONDS, and this sits ABOVE the
3927    // missing-value branch on purpose.
3928    //
3929    // MEASURED, live pandas 2.2.3:
3930    //     pd.Series([Timestamp('2024-03-15 10:30:45.123456789')]).astype('int64')
3931    //       -> 1710498645123456789
3932    //     pd.Series([Timedelta('1 days 02:03:04.005006007')]).astype('int64')
3933    //       -> 93784005006007
3934    //     pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
3935    //       -> -9223372036854775808        <- THE SENTINEL, not a missing value
3936    //
3937    // ⚠️ NaT IS WHY THE ORDER MATTERS. Below this point `value.is_missing()`
3938    // would turn NaT into `Null(Null)`, and pandas emphatically does not: it
3939    // hands back i64::MIN, which is the same bit pattern NaT already IS. Doing
3940    // the cast here makes the sentinel round-trip by construction rather than by
3941    // a second special case.
3942    //
3943    // ⚠️ NUMPY `int64` ONLY — the NULLABLE `Int64` REFUSES this, and so must we:
3944    //     .astype('Int64')   -> TypeError: datetime64[ns] cannot be converted
3945    //                          to IntegerDtype
3946    //     .astype('float64') -> TypeError: Cannot cast DatetimeArray to dtype
3947    //                          float64
3948    // which is why this is guarded on the exact target rather than folded into
3949    // the `Int64 | Int64Nullable` arm below, and why no Float64 arm is added.
3950    if target == DType::Int64 {
3951        match &value {
3952            Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3953                return Ok(Scalar::Int64(*nanos));
3954            }
3955            _ => {}
3956        }
3957    }
3958    if value.is_missing() {
3959        return Ok(Scalar::missing_for_dtype(target));
3960    }
3961
3962    // Note: identity casts (from == target) are handled above, so same-type
3963    // arms are omitted from the match below.
3964    match target {
3965        DType::Null => Ok(Scalar::Null(NullKind::Null)),
3966        DType::Bool => match &value {
3967            // numpy bool: zero -> False, ANY nonzero -> True (it does not
3968            // restrict to 0/1). e.g. bool of -3 / 2.5 is True.
3969            Scalar::Int64(v) => Ok(Scalar::Bool(*v != 0)),
3970            // 0.0 and -0.0 -> False; every other value, INCLUDING NaN, -> True
3971            // (NaN != 0.0 is true), matching numpy/pandas truthiness.
3972            Scalar::Float64(v) => Ok(Scalar::Bool(*v != 0.0)),
3973            _ => Err(TypeError::InvalidCast { from, to: target }),
3974        },
3975        DType::BoolNullable => match &value {
3976            // pandas nullable Boolean ('boolean') is STRICT: only 0/1 (or
3977            // True/False) are accepted — any other value raises "Need to pass
3978            // bool-like values", UNLIKE numpy bool which is nonzero-truthy.
3979            // (br-frankenpandas-tjomg)
3980            Scalar::Bool(b) => Ok(Scalar::Bool(*b)),
3981            Scalar::Int64(0) => Ok(Scalar::Bool(false)),
3982            Scalar::Int64(1) => Ok(Scalar::Bool(true)),
3983            Scalar::Int64(v) => Err(TypeError::InvalidBoolInt { value: *v }),
3984            Scalar::Float64(v) if *v == 0.0 => Ok(Scalar::Bool(false)),
3985            Scalar::Float64(v) if *v == 1.0 => Ok(Scalar::Bool(true)),
3986            Scalar::Float64(v) => Err(TypeError::InvalidBoolFloat { value: *v }),
3987            _ => Err(TypeError::InvalidCast { from, to: target }),
3988        },
3989        DType::Int64 | DType::Int64Nullable => match &value {
3990            Scalar::Bool(v) => Ok(Scalar::Int64(i64::from(*v))),
3991            Scalar::Float64(v) => {
3992                // pandas astype(int64) truncates a finite float toward zero
3993                // (1.9 -> 1, -1.9 -> -1, 2.5 -> 2); only non-finite (NaN/±inf)
3994                // or out-of-i64-range values raise. Verified vs pandas 2.2.3
3995                // (br-frankenpandas-qcutc). NaN is handled as missing above, so
3996                // here non-finite means ±inf. `as i64` performs the toward-zero
3997                // truncation for in-range finite values.
3998                if !v.is_finite() {
3999                    return Err(TypeError::LossyFloatToInt { value: *v });
4000                }
4001                if *v < i64::MIN as f64 || *v >= 9223372036854775808.0 {
4002                    return Err(TypeError::LossyFloatToInt { value: *v });
4003                }
4004                Ok(Scalar::Int64(*v as i64))
4005            }
4006            Scalar::Utf8(s) => {
4007                // Try direct int parse first, then try float parse + truncate
4008                // (pandas accepts "1.0" as valid int via float intermediate)
4009                if let Ok(v) = s.parse::<i64>() {
4010                    return Ok(Scalar::Int64(v));
4011                }
4012                if let Ok(f) = s.parse::<f64>()
4013                    && f.is_finite()
4014                    && f.fract() == 0.0
4015                    && f >= i64::MIN as f64
4016                    && f < 9223372036854775808.0
4017                {
4018                    return Ok(Scalar::Int64(f as i64));
4019                }
4020                Err(TypeError::InvalidCast { from, to: target })
4021            }
4022            _ => Err(TypeError::InvalidCast { from, to: target }),
4023        },
4024        // Both float flavours accept the same source values; they differ only in
4025        // the missing marker, which is handled above. MEASURED:
4026        //     pd.Series([1,None],dtype="Int64").astype("Float64") -> [1.0, <NA>]
4027        DType::Float64 | DType::Float64Nullable => match &value {
4028            Scalar::Bool(v) => Ok(Scalar::Float64(if *v { 1.0 } else { 0.0 })),
4029            Scalar::Int64(v) => Ok(Scalar::Float64(*v as f64)),
4030            Scalar::Utf8(s) => s
4031                .parse::<f64>()
4032                .map(Scalar::Float64)
4033                .map_err(|_| TypeError::InvalidCast { from, to: target }),
4034            _ => Err(TypeError::InvalidCast { from, to: target }),
4035        },
4036        DType::Utf8 => Ok(Scalar::Utf8(scalar_to_string_for_astype(value))),
4037        DType::Categorical => Err(TypeError::InvalidCast { from, to: target }),
4038        DType::Timedelta64 => match &value {
4039            // A BOOL IS 0 OR 1 NANOSECONDS on the astype path. Measured:
4040            //     pd.Series([True]).astype('timedelta64[ns]') -> 1ns
4041            //     pd.Series([True]).astype('datetime64[ns]')  -> 1970-01-01 ...001
4042            // ⚠️ The CONSTRUCTOR refuses the same thing —
4043            //     pd.DataFrame([[True]], dtype='datetime64[ns]')
4044            //       -> TypeError: dtype bool cannot be converted to datetime64[ns]
4045            // -- the same astype/constructor split `float_to_temporal_nanos`
4046            // documents for non-finite input. This cast is shared, so it takes
4047            // astype's answer and the constructor's refusal belongs in
4048            // `DataFrame::with_constructor_dtype`.
4049            Scalar::Bool(v) => Ok(Scalar::Timedelta64(i64::from(*v))),
4050            Scalar::Int64(v) => Ok(Scalar::Timedelta64(*v)),
4051            Scalar::Float64(v) => Ok(Scalar::Timedelta64(float_to_temporal_nanos(*v))),
4052            Scalar::Utf8(s) => Timedelta::parse(s)
4053                .map(Scalar::Timedelta64)
4054                .map_err(|_| TypeError::InvalidCast { from, to: target }),
4055            _ => Err(TypeError::InvalidCast { from, to: target }),
4056        },
4057        DType::Datetime64 { .. } => match &value {
4058            // See the Timedelta64 arm above for the measurement and for why the
4059            // constructor's stricter refusal is not encoded here.
4060            Scalar::Bool(v) => Ok(Scalar::Datetime64(i64::from(*v))),
4061            Scalar::Int64(v) => Ok(Scalar::Datetime64(*v)),
4062            Scalar::Float64(v) => Ok(Scalar::Datetime64(float_to_temporal_nanos(*v))),
4063            Scalar::Utf8(s) => Timestamp::parse(s)
4064                .map(|timestamp| Scalar::Datetime64(timestamp.nanos))
4065                .map_err(|_| TypeError::InvalidCast { from, to: target }),
4066            _ => Err(TypeError::InvalidCast { from, to: target }),
4067        },
4068        DType::Period => match &value {
4069            // Int cast to a freq-less DType::Period: default to Daily (pandas
4070            // requires an explicit freq in the dtype; ours is freq-less).
4071            Scalar::Int64(v) => Ok(Scalar::Period(Period::new(*v, PeriodFreq::Daily))),
4072            Scalar::Utf8(s) => Period::parse(s)
4073                .map(Scalar::Period)
4074                .map_err(|_| TypeError::InvalidCast { from, to: target }),
4075            _ => Err(TypeError::InvalidCast { from, to: target }),
4076        },
4077        DType::Interval => match &value {
4078            Scalar::Utf8(s) => Interval::parse(s)
4079                .map(Scalar::Interval)
4080                .map_err(|_| TypeError::InvalidCast { from, to: target }),
4081            _ => Err(TypeError::InvalidCast { from, to: target }),
4082        },
4083        DType::Sparse => Err(TypeError::InvalidCast { from, to: target }),
4084    }
4085}
4086
4087/// A float reinterpreted as integer NANOSECONDS, the way pandas casts to
4088/// `datetime64[ns]` / `timedelta64[ns]`.
4089///
4090/// ⚠️ THIS IS NOT THE `int64` RULE, and the difference is the whole reason this
4091/// helper exists rather than a reuse. The explicit constructor REFUSES a lossy
4092/// float -> int64 (`TypeError::LossyFloatToInt`, mirroring pandas' "Trying to
4093/// coerce float values to integers"), but the temporal dtypes silently truncate.
4094/// MEASURED side by side, live pandas 2.2.3, on the single value `1.5`:
4095///
4096/// ```text
4097/// pd.DataFrame([[1.5]], dtype="int64")           -> ValueError
4098/// pd.DataFrame([[1.5]], dtype="datetime64[ns]")  -> 1ns
4099/// pd.DataFrame([[1.5]], dtype="timedelta64[ns]") -> 1ns
4100/// ```
4101///
4102/// TRUNCATION IS TOWARD ZERO, NOT FLOOR. Measured on both signs, where the two
4103/// disagree: 0.9 -> 0 and -0.9 -> 0; 1.5 -> 1 and -1.5 -> -1; -2.5 -> -2 (a
4104/// floor would give -1, -2 and -3). Rust's `as i64` is exactly this truncation.
4105///
4106/// ANYTHING NOT REPRESENTABLE AS `i64` BECOMES NaT, which is why this cannot be
4107/// a bare `as` — Rust's saturating cast would hand back `i64::MAX` where pandas
4108/// hands back NaT, and would map NaN to 0, i.e. the epoch. Measured, all NaT:
4109/// NaN, +inf, -inf, 1e30, -1e30, 9.3e18, and exactly 2^63 and -2^63; while
4110/// 2^63 - 1024 IS representable and converts (2262-04-11 23:47:16.854774784).
4111/// The bounds are therefore strict on both ends — `i64::MIN as f64` is exactly
4112/// -2^63, which pandas already reads as NaT because it IS the NaT sentinel.
4113///
4114/// ⚠️ ONE KNOWN DIVERGENCE, RECORDED RATHER THAN GUESSED. For `timedelta64[ns]`
4115/// pandas' two paths disagree on the non-finite input: `astype` yields NaT but
4116/// the constructor raises OverflowError. `datetime64[ns]` has no such split —
4117/// both give NaT. This cast is shared by both paths, so it takes the behaviour
4118/// they agree on for datetimes and `astype`'s for timedeltas; the constructor's
4119/// stricter refusal belongs in `DataFrame::with_constructor_dtype`, which is
4120/// already where the constructor-only `int64`-rejects-NA check lives, and for
4121/// the same reason.
4122fn float_to_temporal_nanos(value: f64) -> i64 {
4123    // Strict on both ends: `i64::MIN as f64` and `i64::MAX as f64` are -2^63 and
4124    // 2^63, and pandas reads both of those as NaT.
4125    if value.is_finite() && value > (i64::MIN as f64) && value < (i64::MAX as f64) {
4126        // Truncates toward zero, and the guard above means it cannot saturate.
4127        value as i64
4128    } else {
4129        // `Timestamp::NAT` and `Timedelta::NAT` are the same value (`i64::MIN`),
4130        // so this one sentinel is correct for both callers.
4131        Timestamp::NAT
4132    }
4133}
4134
4135fn scalar_to_string_for_astype(value: Scalar) -> String {
4136    match value {
4137        Scalar::Null(NullKind::Null) => "None".to_owned(),
4138        Scalar::Null(NullKind::NaN) => "nan".to_owned(),
4139        Scalar::Null(NullKind::NaT) => "NaT".to_owned(),
4140        Scalar::Bool(true) => "True".to_owned(),
4141        Scalar::Bool(false) => "False".to_owned(),
4142        Scalar::Int64(v) => v.to_string(),
4143        Scalar::Float64(v) => float_to_string_for_astype(v),
4144        Scalar::Utf8(s) => s,
4145        Scalar::Timedelta64(v) if v == Timedelta::NAT => "NaT".to_owned(),
4146        Scalar::Timedelta64(v) => Timedelta::format(v),
4147        Scalar::Datetime64(v) if v == Timestamp::NAT => "NaT".to_owned(),
4148        Scalar::Datetime64(v) => timestamp_text(v),
4149        Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
4150        Scalar::Period(p) => p.calendar_string(),
4151        Scalar::Interval(v) => v.to_string(),
4152        // astype(str) of a list cell is its repr, of a host value its str.
4153        Scalar::Object(object) => object.to_string(),
4154    }
4155}
4156
4157pub fn float_to_string_for_astype(value: f64) -> String {
4158    use std::fmt::Write as _;
4159
4160    if value.is_nan() {
4161        return "nan".to_owned();
4162    }
4163    if value.is_infinite() {
4164        return value.to_string(); // "inf" / "-inf"
4165    }
4166    // pandas astype(str) renders floats via Python str(float): whole numbers
4167    // keep ".0", decimals use the shortest round-trip, and extreme magnitudes use
4168    // scientific notation ("1e+16", "1e-05"). Rust's Debug formatter matches this
4169    // (shortest round-trip, ".0" on whole numbers, scientific at Python's
4170    // boundaries); only the exponent spelling differs (Rust "1e16"/"1e-5" vs
4171    // Python "1e+16"/"1e-05"), so normalize that. The old `{:.1}` whole / Display
4172    // decimal path lost scientific notation (1e16 -> "10000000000000000.0").
4173    // Leave enough spare capacity for the positive sign and one exponent pad
4174    // digit, then normalize the formatter output in place. The former branch
4175    // allocated a second String and copied the mantissa solely to change
4176    // `e16`/`e-5` into pandas' `e+16`/`e-05` spelling.
4177    let mut rendered = String::with_capacity(32);
4178    let _ = write!(rendered, "{value:?}");
4179    let Some(exponent_marker) = rendered.find('e') else {
4180        return rendered;
4181    };
4182
4183    let sign_position = exponent_marker + 1;
4184    let digits_position = match rendered.as_bytes().get(sign_position) {
4185        Some(b'+' | b'-') => sign_position + 1,
4186        _ => {
4187            rendered.insert(sign_position, '+');
4188            sign_position + 1
4189        }
4190    };
4191    if rendered.len() - digits_position == 1 {
4192        rendered.insert(digits_position, '0');
4193    }
4194    rendered
4195}
4196
4197static ENG_FLOAT_ACCURACY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(3);
4198static ENG_FLOAT_USE_PREFIX: std::sync::atomic::AtomicBool =
4199    std::sync::atomic::AtomicBool::new(false);
4200static ENG_FLOAT_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
4201
4202/// Format float values according to engineering format, matching pandas `EngFormatter`.
4203pub fn eng_float_format(num: f64, accuracy: Option<usize>, use_eng_prefix: bool) -> String {
4204    if num.is_nan() {
4205        return "NaN".to_string();
4206    }
4207    if num.is_infinite() {
4208        return if num < 0.0 {
4209            "-inf".to_string()
4210        } else {
4211            "inf".to_string()
4212        };
4213    }
4214
4215    let sign = if num < 0.0 { -1.0 } else { 1.0 };
4216    let abs_num = num.abs();
4217
4218    let pow10 = if abs_num != 0.0 {
4219        let p = (abs_num.log10() / 3.0).floor() as i32 * 3;
4220        p.clamp(-24, 24)
4221    } else {
4222        0
4223    };
4224
4225    let prefix = if use_eng_prefix {
4226        match pow10 {
4227            -24 => "y",
4228            -21 => "z",
4229            -18 => "a",
4230            -15 => "f",
4231            -12 => "p",
4232            -9 => "n",
4233            -6 => "u",
4234            -3 => "m",
4235            0 => "",
4236            3 => "k",
4237            6 => "M",
4238            9 => "G",
4239            12 => "T",
4240            15 => "P",
4241            18 => "E",
4242            21 => "Z",
4243            24 => "Y",
4244            _ => "",
4245        }
4246        .to_string()
4247    } else if pow10 < 0 {
4248        format!("E-{:02}", -pow10)
4249    } else {
4250        format!("E+{:02}", pow10)
4251    };
4252
4253    let mant = (sign * abs_num) / 10f64.powi(pow10);
4254
4255    if let Some(acc) = accuracy {
4256        format!("{mant:.acc$}{prefix}", acc = acc)
4257    } else {
4258        format!("{mant}{prefix}")
4259    }
4260}
4261
4262/// Set pandas-compatible engineering float formatting option.
4263/// Matches `pd.set_eng_float_format(accuracy=3, use_eng_prefix=False)`.
4264pub fn set_eng_float_format(accuracy: usize, use_eng_prefix: bool) {
4265    use std::sync::atomic::Ordering;
4266    ENG_FLOAT_ACCURACY.store(accuracy, Ordering::Relaxed);
4267    ENG_FLOAT_USE_PREFIX.store(use_eng_prefix, Ordering::Relaxed);
4268    ENG_FLOAT_ACTIVE.store(true, Ordering::Relaxed);
4269}
4270
4271/// Reset engineering float formatting back to default.
4272pub fn reset_eng_float_format() {
4273    use std::sync::atomic::Ordering;
4274    ENG_FLOAT_ACTIVE.store(false, Ordering::Relaxed);
4275}
4276
4277/// Get the current engineering float format configuration if active.
4278pub fn get_eng_float_format() -> Option<(usize, bool)> {
4279    use std::sync::atomic::Ordering;
4280    if ENG_FLOAT_ACTIVE.load(Ordering::Relaxed) {
4281        Some((
4282            ENG_FLOAT_ACCURACY.load(Ordering::Relaxed),
4283            ENG_FLOAT_USE_PREFIX.load(Ordering::Relaxed),
4284        ))
4285    } else {
4286        None
4287    }
4288}
4289
4290// ── Global Configuration Options (matching pd.options) ───────────────────
4291
4292/// Error encountered when inspecting or modifying configuration options.
4293#[derive(Debug, Error, Clone, PartialEq, Eq)]
4294pub enum OptionError {
4295    #[error("no such option: '{pat}'")]
4296    NotFound { pat: String },
4297    #[error("option pattern '{pat}' matches multiple options: {matches:?}")]
4298    Ambiguous { pat: String, matches: Vec<String> },
4299    #[error("invalid option value for '{pat}': {reason}")]
4300    InvalidValue { pat: String, reason: String },
4301}
4302
4303/// Represents a configuration option value, matching pandas `pd.options`.
4304#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4305pub enum OptionValue {
4306    None,
4307    Int(i64),
4308    Float(f64),
4309    Bool(bool),
4310    Str(String),
4311}
4312
4313impl OptionValue {
4314    #[must_use]
4315    pub const fn is_none(&self) -> bool {
4316        matches!(self, Self::None)
4317    }
4318
4319    #[must_use]
4320    pub const fn as_int(&self) -> Option<i64> {
4321        match self {
4322            Self::Int(i) => Some(*i),
4323            _ => None,
4324        }
4325    }
4326
4327    #[must_use]
4328    pub const fn as_float(&self) -> Option<f64> {
4329        match self {
4330            Self::Float(f) => Some(*f),
4331            _ => None,
4332        }
4333    }
4334
4335    #[must_use]
4336    pub const fn as_bool(&self) -> Option<bool> {
4337        match self {
4338            Self::Bool(b) => Some(*b),
4339            _ => None,
4340        }
4341    }
4342
4343    #[must_use]
4344    pub fn as_str(&self) -> Option<&str> {
4345        match self {
4346            Self::Str(s) => Some(s.as_str()),
4347            _ => None,
4348        }
4349    }
4350}
4351
4352impl std::fmt::Display for OptionValue {
4353    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4354        match self {
4355            Self::None => write!(f, "None"),
4356            Self::Int(i) => write!(f, "{i}"),
4357            Self::Float(fl) => write!(f, "{fl}"),
4358            Self::Bool(b) => write!(f, "{b}"),
4359            Self::Str(s) => write!(f, "{s}"),
4360        }
4361    }
4362}
4363
4364impl From<i64> for OptionValue {
4365    fn from(v: i64) -> Self {
4366        Self::Int(v)
4367    }
4368}
4369
4370impl From<i32> for OptionValue {
4371    fn from(v: i32) -> Self {
4372        Self::Int(i64::from(v))
4373    }
4374}
4375
4376impl From<usize> for OptionValue {
4377    fn from(v: usize) -> Self {
4378        Self::Int(i64::try_from(v).unwrap_or(i64::MAX))
4379    }
4380}
4381
4382impl From<f64> for OptionValue {
4383    fn from(v: f64) -> Self {
4384        Self::Float(v)
4385    }
4386}
4387
4388impl From<bool> for OptionValue {
4389    fn from(v: bool) -> Self {
4390        Self::Bool(v)
4391    }
4392}
4393
4394impl From<&str> for OptionValue {
4395    fn from(v: &str) -> Self {
4396        Self::Str(v.to_string())
4397    }
4398}
4399
4400impl From<String> for OptionValue {
4401    fn from(v: String) -> Self {
4402        Self::Str(v)
4403    }
4404}
4405
4406impl From<()> for OptionValue {
4407    fn from(_: ()) -> Self {
4408        Self::None
4409    }
4410}
4411
4412fn default_options_map() -> std::collections::BTreeMap<String, OptionValue> {
4413    let mut m = std::collections::BTreeMap::new();
4414    m.insert("display.max_rows".to_string(), OptionValue::Int(60));
4415    m.insert("display.min_rows".to_string(), OptionValue::Int(10));
4416    m.insert("display.max_columns".to_string(), OptionValue::Int(0));
4417    m.insert("display.width".to_string(), OptionValue::Int(80));
4418    m.insert("display.precision".to_string(), OptionValue::Int(6));
4419    m.insert("display.max_colwidth".to_string(), OptionValue::Int(50));
4420    m.insert(
4421        "display.show_dimensions".to_string(),
4422        OptionValue::Bool(true),
4423    );
4424    m.insert("display.float_format".to_string(), OptionValue::None);
4425    m.insert(
4426        "display.large_repr".to_string(),
4427        OptionValue::Str("truncate".to_string()),
4428    );
4429    m.insert(
4430        "display.max_info_columns".to_string(),
4431        OptionValue::Int(100),
4432    );
4433    m.insert(
4434        "display.max_info_rows".to_string(),
4435        OptionValue::Int(1690785),
4436    );
4437    m.insert("display.memory_usage".to_string(), OptionValue::Bool(true));
4438    m.insert(
4439        "display.colheader_justify".to_string(),
4440        OptionValue::Str("right".to_string()),
4441    );
4442    m.insert("display.chop_threshold".to_string(), OptionValue::None);
4443    m.insert(
4444        "display.date_dayfirst".to_string(),
4445        OptionValue::Bool(false),
4446    );
4447    m.insert(
4448        "display.date_yearfirst".to_string(),
4449        OptionValue::Bool(false),
4450    );
4451    m.insert(
4452        "display.encoding".to_string(),
4453        OptionValue::Str("utf-8".to_string()),
4454    );
4455    m.insert("mode.sim_interactive".to_string(), OptionValue::Bool(false));
4456    m.insert(
4457        "mode.chained_assignment".to_string(),
4458        OptionValue::Str("warn".to_string()),
4459    );
4460    m.insert("mode.use_inf_as_na".to_string(), OptionValue::Bool(false));
4461    m.insert("mode.copy_on_write".to_string(), OptionValue::Bool(false));
4462    m.insert(
4463        "mode.data_manager".to_string(),
4464        OptionValue::Str("block".to_string()),
4465    );
4466    m.insert(
4467        "compute.use_bottleneck".to_string(),
4468        OptionValue::Bool(true),
4469    );
4470    m.insert("compute.use_numba".to_string(), OptionValue::Bool(false));
4471    m.insert(
4472        "io.excel.zip.reader".to_string(),
4473        OptionValue::Str("zipfile".to_string()),
4474    );
4475    m.insert(
4476        "io.parquet.engine".to_string(),
4477        OptionValue::Str("auto".to_string()),
4478    );
4479    m.insert(
4480        "io.sql.engine".to_string(),
4481        OptionValue::Str("auto".to_string()),
4482    );
4483    m.insert(
4484        "plotting.backend".to_string(),
4485        OptionValue::Str("matplotlib".to_string()),
4486    );
4487    m.insert(
4488        "plotting.matplotlib.register_converters".to_string(),
4489        OptionValue::Bool(true),
4490    );
4491    m
4492}
4493
4494static GLOBAL_OPTIONS: std::sync::LazyLock<
4495    std::sync::Mutex<std::collections::BTreeMap<String, OptionValue>>,
4496> = std::sync::LazyLock::new(|| std::sync::Mutex::new(default_options_map()));
4497
4498fn resolve_option_key(
4499    pat: &str,
4500    map: &std::collections::BTreeMap<String, OptionValue>,
4501) -> Result<String, OptionError> {
4502    if map.contains_key(pat) {
4503        return Ok(pat.to_string());
4504    }
4505    let matches: Vec<String> = map
4506        .keys()
4507        .filter(|k| k.ends_with(pat) || k.contains(pat))
4508        .cloned()
4509        .collect();
4510    if matches.len() == 1 {
4511        Ok(matches[0].clone())
4512    } else if matches.is_empty() {
4513        Err(OptionError::NotFound {
4514            pat: pat.to_string(),
4515        })
4516    } else {
4517        Err(OptionError::Ambiguous {
4518            pat: pat.to_string(),
4519            matches,
4520        })
4521    }
4522}
4523
4524/// Retrieve the current value of a configuration option, matching `pd.get_option(pat)`.
4525///
4526/// # Errors
4527/// Returns [`OptionError::NotFound`] if `pat` does not match any known option,
4528/// or [`OptionError::Ambiguous`] if it matches multiple options.
4529pub fn get_option(pat: &str) -> Result<OptionValue, OptionError> {
4530    let map = GLOBAL_OPTIONS
4531        .lock()
4532        .unwrap_or_else(std::sync::PoisonError::into_inner);
4533    let key = resolve_option_key(pat, &map)?;
4534    Ok(map.get(&key).cloned().unwrap_or(OptionValue::None))
4535}
4536
4537/// Set the value of a configuration option, matching `pd.set_option(pat, value)`.
4538///
4539/// # Errors
4540/// Returns [`OptionError::NotFound`] if `pat` does not match any known option,
4541/// or [`OptionError::Ambiguous`] if it matches multiple options.
4542pub fn set_option(pat: &str, val: impl Into<OptionValue>) -> Result<(), OptionError> {
4543    let mut map = GLOBAL_OPTIONS
4544        .lock()
4545        .unwrap_or_else(std::sync::PoisonError::into_inner);
4546    let key = resolve_option_key(pat, &map)?;
4547    let v = val.into();
4548    map.insert(key, v);
4549    Ok(())
4550}
4551
4552/// Reset one or all configuration options to their defaults, matching `pd.reset_option(pat)`.
4553///
4554/// If `pat` is `None` or `"all"`, all options are reset to defaults.
4555///
4556/// # Errors
4557/// Returns [`OptionError::NotFound`] or [`OptionError::Ambiguous`] if `pat` does not uniquely match an option.
4558pub fn reset_option(pat: Option<&str>) -> Result<(), OptionError> {
4559    let mut map = GLOBAL_OPTIONS
4560        .lock()
4561        .unwrap_or_else(std::sync::PoisonError::into_inner);
4562    let defaults = default_options_map();
4563    let p = pat.unwrap_or("all");
4564    if p == "all" {
4565        *map = defaults;
4566        return Ok(());
4567    }
4568    let key = resolve_option_key(p, &defaults)?;
4569    if let Some(def_val) = defaults.get(&key) {
4570        map.insert(key, def_val.clone());
4571    }
4572    Ok(())
4573}
4574
4575/// Return formatted descriptions of one or all options, matching `pd.describe_option(pat)`.
4576///
4577/// # Errors
4578/// Returns [`OptionError::NotFound`] if `pat` is provided but matches no options.
4579pub fn describe_option(pat: Option<&str>) -> Result<String, OptionError> {
4580    use std::fmt::Write as _;
4581    let map = GLOBAL_OPTIONS
4582        .lock()
4583        .unwrap_or_else(std::sync::PoisonError::into_inner);
4584    let mut out = String::with_capacity(map.len() * 40);
4585    let mut matched = 0;
4586    for (k, v) in map.iter() {
4587        if let Some(p) = pat
4588            && !k.contains(p)
4589        {
4590            continue;
4591        }
4592        if matched > 0 {
4593            out.push('\n');
4594        }
4595        let _ = write!(out, "{k} : [currently: {v}]");
4596        matched += 1;
4597    }
4598    if matched == 0
4599        && let Some(p) = pat
4600    {
4601        return Err(OptionError::NotFound { pat: p.to_string() });
4602    }
4603    Ok(out)
4604}
4605
4606/// RAII scope guard that restores options to their prior values when dropped.
4607#[derive(Debug)]
4608pub struct OptionContextGuard {
4609    saved: Vec<(String, OptionValue)>,
4610}
4611
4612impl Drop for OptionContextGuard {
4613    fn drop(&mut self) {
4614        let mut map = GLOBAL_OPTIONS
4615            .lock()
4616            .unwrap_or_else(std::sync::PoisonError::into_inner);
4617        for (k, old) in self.saved.drain(..) {
4618            map.insert(k, old);
4619        }
4620    }
4621}
4622
4623/// Temporarily override options within a scoped context, matching `pd.option_context(...)`.
4624///
4625/// # Errors
4626/// Returns [`OptionError::NotFound`] or [`OptionError::Ambiguous`] if any pattern is invalid.
4627pub fn option_context(entries: &[(&str, OptionValue)]) -> Result<OptionContextGuard, OptionError> {
4628    let mut map = GLOBAL_OPTIONS
4629        .lock()
4630        .unwrap_or_else(std::sync::PoisonError::into_inner);
4631    let mut saved = Vec::with_capacity(entries.len());
4632    for (pat, new_val) in entries {
4633        let key = resolve_option_key(pat, &map)?;
4634        if let Some(old) = map.get(&key) {
4635            saved.push((key.clone(), old.clone()));
4636        }
4637        map.insert(key, new_val.clone());
4638    }
4639    Ok(OptionContextGuard { saved })
4640}
4641
4642/// Cast a scalar reference to a target dtype (clones only when conversion is needed).
4643pub fn cast_scalar(value: &Scalar, target: DType) -> Result<Scalar, TypeError> {
4644    cast_scalar_owned(value.clone(), target)
4645}
4646
4647// ── Timedelta support ──────────────────────────────────────────────────
4648
4649#[derive(Debug, Error, Clone, PartialEq)]
4650pub enum TimedeltaError {
4651    #[error("invalid timedelta string: {0}")]
4652    InvalidFormat(String),
4653    #[error("overflow in timedelta computation")]
4654    Overflow,
4655}
4656
4657impl TimedeltaError {
4658    /// The pandas exception class this corresponds to, per
4659    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2.
4660    ///
4661    /// Returns `None` for [`Self::InvalidFormat`], which is a parse failure
4662    /// rather than a member of the temporal-arithmetic taxonomy.
4663    #[must_use]
4664    pub const fn pandas_error(&self) -> Option<PandasTemporalError> {
4665        match self {
4666            // Probed: pd.Timedelta(float('inf'), 's') raises
4667            // OutOfBoundsTimedelta, NOT a bare OverflowError.
4668            Self::Overflow => Some(PandasTemporalError::OutOfBoundsTimedelta),
4669            Self::InvalidFormat(_) => None,
4670        }
4671    }
4672}
4673
4674#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4675pub struct CategoricalMetadata {
4676    /// The unique category values, in order.
4677    pub categories: Vec<Scalar>,
4678    /// Whether the categories have a meaningful total ordering.
4679    pub ordered: bool,
4680}
4681
4682impl CategoricalMetadata {
4683    #[must_use]
4684    pub fn new(categories: Vec<Scalar>, ordered: bool) -> Self {
4685        Self {
4686            categories,
4687            ordered,
4688        }
4689    }
4690}
4691
4692#[derive(Debug, Clone, Copy, Default)]
4693pub struct TimedeltaComponents {
4694    pub days: i64,
4695    pub hours: i64,
4696    pub minutes: i64,
4697    pub seconds: i64,
4698    pub milliseconds: i64,
4699    pub microseconds: i64,
4700    pub nanoseconds: i64,
4701}
4702
4703/// The pandas-side exception class a failed temporal operation corresponds to.
4704///
4705/// Introduced by br-frankenpandas-fyr1z-policy-carrier-f29nz and completed by
4706/// fyr1z.3, which established that pandas uses FIVE distinct classes here — so
4707/// a STRICT arm must raise the RIGHT one per op rather than a blanket type.
4708/// Every mapping below was probed against live pandas 2.2.3, not inferred.
4709///
4710/// Named `...TemporalError` rather than `...OverflowError` because
4711/// [`Self::ZeroDivision`] is not an overflow; a type whose name promised
4712/// "overflow" while carrying divide-by-zero would be exactly the kind of stale
4713/// label this codebase keeps having to correct.
4714#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4715pub enum PandasTemporalError {
4716    /// `OverflowError`. e.g. `pd.Timedelta.max + pd.Timedelta('1ns')`, and
4717    /// `Series + Timedelta` / `Series - Series` / `.diff()` which report
4718    /// "Overflow in int64 addition".
4719    Overflow,
4720    /// `OutOfBoundsDatetime`. e.g. `pd.Timestamp.max + pd.Timedelta('1ns')`
4721    /// and `pd.Timestamp.min - pd.Timestamp.max`.
4722    OutOfBoundsDatetime,
4723    /// `OutOfBoundsTimedelta`. Raised by the `pd.Timedelta(value, unit=...)`
4724    /// constructor path (see br-frankenpandas-8v92m), not by the six
4725    /// arithmetic helpers below. Probed: `pd.Timedelta(float('inf'), 's')` ->
4726    /// "Cannot cast inf from s to 'ns' without overflow."
4727    OutOfBoundsTimedelta,
4728    /// `ValueError("overflow in timedelta operation")`. Raised by the
4729    /// REDUCTIONS `Series.sum()` and `Series.std()` over timedelta64.
4730    OverflowInTimedeltaOperation,
4731    /// `ZeroDivisionError`. Raised by SCALAR `Timedelta // 0`, `Timedelta / 0`
4732    /// and `Timedelta // 0.0` ONLY.
4733    ///
4734    /// ⚠ The VECTORIZED division family does NOT raise: probed,
4735    /// `Series([Timedelta]) // 0` and `/ 0` both return NaT. A STRICT arm must
4736    /// not widen this class to the vectorized surface — doing so would create
4737    /// divergence where FrankenPandas is already bit-for-bit correct, which is
4738    /// the central finding of br-frankenpandas-fyr1z (see DISC-018).
4739    ZeroDivision,
4740}
4741
4742/// A temporal overflow, naming the operation that overflowed and the pandas
4743/// exception it corresponds to.
4744#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4745pub struct TemporalFailure {
4746    /// The FrankenPandas operation, e.g. `"Timedelta::add"`.
4747    pub op: &'static str,
4748    /// What pandas raises for this operation.
4749    pub pandas_error: PandasTemporalError,
4750    /// The operand pair whose exact result left the representable range, when
4751    /// the failing operation had one. Carried for the HARDENED audit trail
4752    /// (br-frankenpandas-fyr1z-hardened-audit-vllv6) so a recovery entry can
4753    /// name the range violation rather than merely that one occurred.
4754    pub operands: Option<(i64, i64)>,
4755}
4756
4757impl TemporalFailure {
4758    #[must_use]
4759    pub const fn new(op: &'static str, pandas_error: PandasTemporalError) -> Self {
4760        Self {
4761            op,
4762            pandas_error,
4763            operands: None,
4764        }
4765    }
4766
4767    /// Attach the operands that produced this failure.
4768    #[must_use]
4769    pub const fn with_operands(mut self, lhs: i64, rhs: i64) -> Self {
4770        self.operands = Some((lhs, rhs));
4771        self
4772    }
4773}
4774
4775/// A bounded defensive recovery that HARDENED mode performed, recorded so a run
4776/// can be audited after the fact.
4777///
4778/// br-frankenpandas-fyr1z-hardened-audit-vllv6. AGENTS.md's security doctrine
4779/// requires "deterministic audit logs for recoveries and policy overrides", and
4780/// overflow-to-NaT is exactly a bounded defensive recovery. Until now it was
4781/// SILENT: a caller could not distinguish a NaT produced by an overflow from a
4782/// NaT that was already in the input, which is the whole substance of the
4783/// DISC-018 impact statement.
4784#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4785pub struct TemporalRecovery {
4786    /// The operation that overflowed.
4787    pub op: &'static str,
4788    /// The pandas exception this would have been under STRICT.
4789    pub pandas_error: PandasTemporalError,
4790    /// The operands whose exact result was unrepresentable, when known.
4791    pub operands: Option<(i64, i64)>,
4792    /// The value actually returned. Always the family's NaT sentinel today.
4793    pub recovered_as: i64,
4794}
4795
4796/// Deterministic, opt-in audit trail for HARDENED-mode recoveries.
4797///
4798/// Disabled by default and costs one `Option` check when off, so the default
4799/// path is unchanged. The log is THREAD-LOCAL: FrankenPandas parallelises many
4800/// kernels, and a shared log would impose a lock on hot arithmetic and make the
4801/// entry ORDER nondeterministic — which would defeat the point. Each worker
4802/// therefore accumulates its own deterministic sequence; a caller auditing a
4803/// parallel op drains per thread.
4804pub mod overflow_audit {
4805    use std::cell::RefCell;
4806
4807    use super::TemporalRecovery;
4808
4809    thread_local! {
4810        static LOG: RefCell<Option<Vec<TemporalRecovery>>> = const { RefCell::new(None) };
4811    }
4812
4813    /// Begin recording on THIS thread, discarding anything already buffered.
4814    pub fn enable() {
4815        LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
4816    }
4817
4818    /// Stop recording on this thread and discard the buffer.
4819    pub fn disable() {
4820        LOG.with(|log| *log.borrow_mut() = None);
4821    }
4822
4823    /// Whether recording is active on this thread.
4824    #[must_use]
4825    pub fn is_enabled() -> bool {
4826        LOG.with(|log| log.borrow().is_some())
4827    }
4828
4829    /// Take the recorded recoveries, leaving recording enabled and empty.
4830    #[must_use]
4831    pub fn drain() -> Vec<TemporalRecovery> {
4832        LOG.with(|log| match log.borrow_mut().as_mut() {
4833            Some(entries) => std::mem::take(entries),
4834            None => Vec::new(),
4835        })
4836    }
4837
4838    /// Record a recovery. A no-op — and allocation-free — when disabled.
4839    pub(super) fn record(entry: TemporalRecovery) {
4840        LOG.with(|log| {
4841            if let Some(entries) = log.borrow_mut().as_mut() {
4842                entries.push(entry);
4843            }
4844        });
4845    }
4846}
4847
4848/// How a temporal overflow should be surfaced.
4849///
4850/// br-frankenpandas-fyr1z-policy-carrier-f29nz adds this carrier WITHOUT
4851/// changing any default behavior: every existing call site is on
4852/// [`OverflowPolicy::SurfaceNat`], which is exactly what the codebase did
4853/// before. `Strict` exists so fyr1z.3 can wire per-op raise arms in a separate,
4854/// reviewable step, and NOTHING routes to it yet.
4855///
4856/// Note DISC-018: a blanket "STRICT raises everywhere" is NOT pandas parity —
4857/// pandas silently wraps on `Series * int` and `.cumsum()`, and returns NaT for
4858/// `.mean()`. The strict arm therefore needs a per-op table, which is why the
4859/// policy is carried per operation rather than set globally.
4860#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
4861pub enum OverflowPolicy {
4862    /// Today's behavior, and the only arm currently wired up: overflow becomes
4863    /// the family's NaT sentinel.
4864    #[default]
4865    SurfaceNat,
4866    /// Reserved for fyr1z.3. Surfaces the [`TemporalFailure`] to the caller.
4867    Strict,
4868    /// HARDENED mode (br-frankenpandas-fyr1z-hardened-audit-vllv6): returns the
4869    /// SAME NaT as [`Self::SurfaceNat`], bit-for-bit, and additionally records a
4870    /// [`TemporalRecovery`] into [`overflow_audit`] when that log is enabled.
4871    ///
4872    /// This adds observability, never semantics. AGENTS.md defines hardened
4873    /// mode as "bounded defensive recovery" and requires a deterministic audit
4874    /// log for exactly that.
4875    HardenedNat,
4876}
4877
4878impl OverflowPolicy {
4879    /// Resolve a fallible temporal result under this policy.
4880    ///
4881    /// `SurfaceNat` discards the overflow and yields `nat`, reproducing the
4882    /// pre-f29nz behavior bit-for-bit. `Strict` propagates the overflow.
4883    ///
4884    /// # Errors
4885    /// Returns the [`TemporalFailure`] unchanged under [`Self::Strict`].
4886    pub fn resolve<T>(
4887        self,
4888        outcome: Result<T, TemporalFailure>,
4889        nat: T,
4890    ) -> Result<T, TemporalFailure> {
4891        self.resolve_recording(outcome, nat, i64::MIN)
4892    }
4893
4894    /// [`Self::resolve`] plus the sentinel value to record in the audit trail.
4895    ///
4896    /// Split out because the recovered value is generic (`T`) but the audit
4897    /// entry needs its i64 backing; `recovered_as` supplies that without
4898    /// constraining `T`.
4899    ///
4900    /// # Errors
4901    /// Returns the [`TemporalFailure`] unchanged under [`Self::Strict`].
4902    pub fn resolve_recording<T>(
4903        self,
4904        outcome: Result<T, TemporalFailure>,
4905        nat: T,
4906        recovered_as: i64,
4907    ) -> Result<T, TemporalFailure> {
4908        match (self, outcome) {
4909            (_, Ok(value)) => Ok(value),
4910            (Self::SurfaceNat, Err(_)) => Ok(nat),
4911            (Self::Strict, Err(failure)) => Err(failure),
4912            (Self::HardenedNat, Err(failure)) => {
4913                // Same value as SurfaceNat; the ONLY difference is the record.
4914                overflow_audit::record(TemporalRecovery {
4915                    op: failure.op,
4916                    pandas_error: failure.pandas_error,
4917                    operands: failure.operands,
4918                    recovered_as,
4919                });
4920                Ok(nat)
4921            }
4922        }
4923    }
4924}
4925
4926pub struct Timedelta;
4927
4928impl Timedelta {
4929    pub const NANOS_PER_MICRO: i64 = 1_000;
4930    pub const NANOS_PER_MILLI: i64 = 1_000_000;
4931    pub const NANOS_PER_SEC: i64 = 1_000_000_000;
4932    pub const NANOS_PER_MIN: i64 = 60 * Self::NANOS_PER_SEC;
4933    pub const NANOS_PER_HOUR: i64 = 60 * Self::NANOS_PER_MIN;
4934    pub const NANOS_PER_DAY: i64 = 24 * Self::NANOS_PER_HOUR;
4935    pub const NANOS_PER_WEEK: i64 = 7 * Self::NANOS_PER_DAY;
4936
4937    pub const NAT: i64 = i64::MIN;
4938
4939    pub fn parse(s: &str) -> Result<i64, TimedeltaError> {
4940        let s = s.trim();
4941
4942        if s.eq_ignore_ascii_case("nat") {
4943            return Ok(Self::NAT);
4944        }
4945
4946        let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
4947            (true, rest.trim())
4948        } else {
4949            (false, s)
4950        };
4951
4952        if let Some(nanos) = Self::try_parse_time_format(s) {
4953            return Ok(if negative { -nanos } else { nanos });
4954        }
4955
4956        if let Some(nanos) = Self::try_parse_iso8601_duration(s) {
4957            return Ok(if negative { -nanos } else { nanos });
4958        }
4959
4960        // pandas' leading '-' negates the unit values but not an HH:MM:SS
4961        // part that follows one: "-1 days +02:03:04" (how pandas prints a
4962        // negative Timedelta) is -1 day + 2:03:04. Negating the whole
4963        // compound read it as -(1 day 2:03:04), so a printed Timedelta did
4964        // not parse back to itself.
4965        let (units, clock) = Self::parse_compound(s)?;
4966        let units = if negative { -units } else { units };
4967        units.checked_add(clock).ok_or(TimedeltaError::Overflow)
4968    }
4969
4970    /// Parse an ISO-8601 duration the way pandas `Timedelta` accepts it:
4971    /// a leading uppercase `P`, an optional `T` separator that is otherwise
4972    /// ignored, and unit letters `W`/`D`/`H`/`M`/`S` in any position. `M` is
4973    /// always MINUTES (never months), and only seconds may be fractional —
4974    /// years/months and lowercase units are rejected, matching pandas.
4975    /// (pandas mis-handles fractional non-second components; those are rejected
4976    /// here rather than reproducing the buggy value.) (br-frankenpandas-c3p8b)
4977    fn try_parse_iso8601_duration(s: &str) -> Option<i64> {
4978        let mut rest = s.strip_prefix('P')?;
4979        if rest.is_empty() {
4980            return None;
4981        }
4982        let mut total: i64 = 0;
4983        let mut saw_component = false;
4984        while !rest.is_empty() {
4985            if let Some(after_t) = rest.strip_prefix('T') {
4986                rest = after_t;
4987                continue;
4988            }
4989            let num_end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')?;
4990            if num_end == 0 {
4991                return None;
4992            }
4993            let num_str = &rest[..num_end];
4994            let unit = rest.as_bytes()[num_end];
4995            let is_fractional = num_str.contains('.');
4996            rest = &rest[num_end + 1..];
4997
4998            let (multiplier, frac_ok) = match unit {
4999                b'W' => (Self::NANOS_PER_WEEK, false),
5000                b'D' => (Self::NANOS_PER_DAY, false),
5001                b'H' => (Self::NANOS_PER_HOUR, false),
5002                b'M' => (Self::NANOS_PER_MIN, false),
5003                b'S' => (Self::NANOS_PER_SEC, true),
5004                _ => return None,
5005            };
5006            if is_fractional {
5007                if !frac_ok {
5008                    return None;
5009                }
5010                let value: f64 = num_str.parse().ok()?;
5011                let product = value * multiplier as f64;
5012                if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5013                    return None;
5014                }
5015                total = total.checked_add(product.round() as i64)?;
5016            } else {
5017                let value: i64 = num_str.parse().ok()?;
5018                total = total.checked_add(value.checked_mul(multiplier)?)?;
5019            }
5020            saw_component = true;
5021        }
5022        saw_component.then_some(total)
5023    }
5024
5025    fn try_parse_time_format(s: &str) -> Option<i64> {
5026        let parts: Vec<&str> = s.split(':').collect();
5027        if parts.len() < 2 || parts.len() > 3 {
5028            return None;
5029        }
5030
5031        let hours: i64 = parts[0].parse().ok()?;
5032        let minutes: i64 = parts[1].parse().ok()?;
5033
5034        let (seconds, frac_nanos) = if parts.len() == 3 {
5035            if let Some((sec_str, frac_str)) = parts[2].split_once('.') {
5036                let sec: i64 = sec_str.parse().ok()?;
5037                if !frac_str.bytes().all(|byte| byte.is_ascii_digit()) {
5038                    return None;
5039                }
5040                let mut frac = 0_i64;
5041                let taken = frac_str.len().min(9);
5042                for byte in frac_str.bytes().take(9) {
5043                    frac = frac * 10 + i64::from(byte - b'0');
5044                }
5045                for _ in taken..9 {
5046                    frac *= 10;
5047                }
5048                (sec, frac)
5049            } else {
5050                let sec: i64 = parts[2].parse().ok()?;
5051                (sec, 0)
5052            }
5053        } else {
5054            (0, 0)
5055        };
5056
5057        hours
5058            .checked_mul(Self::NANOS_PER_HOUR)?
5059            .checked_add(minutes.checked_mul(Self::NANOS_PER_MIN)?)?
5060            .checked_add(seconds.checked_mul(Self::NANOS_PER_SEC)?)?
5061            .checked_add(frac_nanos)
5062    }
5063
5064    /// The number-and-unit values of a compound Timedelta string, and the
5065    /// HH:MM:SS part that may end it (which the leading sign does not
5066    /// negate; see [`Self::parse`]). A sign inside the string is pandas'
5067    /// "only leading negative signs are allowed" error ("1 days -02:00:00"
5068    /// read as 22 hours).
5069    fn parse_compound(s: &str) -> Result<(i64, i64), TimedeltaError> {
5070        let mut total: i64 = 0;
5071        let mut clock: i64 = 0;
5072        let mut remaining = s;
5073
5074        while !remaining.is_empty() {
5075            remaining = remaining.trim_start();
5076            if remaining.is_empty() {
5077                break;
5078            }
5079            if remaining.starts_with('-') {
5080                return Err(TimedeltaError::InvalidFormat(format!(
5081                    "only leading negative signs are allowed: {s}"
5082                )));
5083            }
5084
5085            // Per br-frankenpandas-i9bah: check if remaining is a time format
5086            // (HH:MM:SS) which can appear after "N days " in pandas timedelta strings.
5087            if remaining.contains(':')
5088                && let Some(time_nanos) = Self::try_parse_time_format(remaining)
5089            {
5090                clock = time_nanos;
5091                break;
5092            }
5093
5094            let num_end = remaining
5095                .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
5096                .unwrap_or(remaining.len());
5097
5098            if num_end == 0 {
5099                return Err(TimedeltaError::InvalidFormat(s.to_string()));
5100            }
5101
5102            let num_str = &remaining[..num_end];
5103            let num: f64 = num_str
5104                .parse()
5105                .map_err(|_| TimedeltaError::InvalidFormat(s.to_string()))?;
5106
5107            remaining = remaining[num_end..].trim_start();
5108
5109            let unit_end = remaining
5110                .find(|c: char| c.is_ascii_digit() || c.is_whitespace())
5111                .unwrap_or(remaining.len());
5112
5113            let unit = &remaining[..unit_end];
5114            remaining = &remaining[unit_end..];
5115
5116            let multiplier = Self::unit_to_nanos(unit)
5117                .ok_or_else(|| TimedeltaError::InvalidFormat(s.to_string()))?;
5118
5119            // Per br-frankenpandas-zw3mg: pandas raises OverflowError on
5120            // huge scientific-notation Timedeltas like "1e100 days". The
5121            // raw `as i64` cast silently saturated to i64::MAX, masking
5122            // overflow before checked_add could catch it.
5123            let product = num * multiplier as f64;
5124            if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5125                return Err(TimedeltaError::Overflow);
5126            }
5127            let nanos = product.round() as i64;
5128            total = total.checked_add(nanos).ok_or(TimedeltaError::Overflow)?;
5129        }
5130
5131        // NOTE: there is deliberately no "total == 0 is suspicious" guard here.
5132        // One used to live at this spot and rejected every legitimately-zero
5133        // compound -- `to_timedelta("0 seconds")` raised while `"1 second"` and
5134        // `"10 seconds"` parsed, because the only exemption was the literal
5135        // string "0". pandas 2.2.3 accepts all of `0 seconds` / `0 days` / `0s`
5136        // / `0.0 hours` / `-0 seconds` as a zero Timedelta. The guard was also
5137        // unnecessary: the loop above returns `InvalidFormat` on an unparseable
5138        // number AND on an unknown unit, so the only way to reach here with
5139        // `total == 0` is an input whose components genuinely sum to zero.
5140        Ok((total, clock))
5141    }
5142
5143    /// Map a pandas-style frequency-alias string to a nanosecond-count.
5144    ///
5145    /// Recognizes pandas's offset alias core set plus common word forms:
5146    /// W/week(s), D/day(s), H/hr/hour(s), m/T/min/minute(s), s/sec/second(s),
5147    /// ms/milli/millisecond(s)/L, us/µs/micro/microsecond(s)/U, ns/nano/
5148    /// nanosecond(s)/N. Empty string maps to days (matches pandas default).
5149    /// Returns `None` for unrecognized aliases — callers can choose to map
5150    /// that to NaT (consistent with the rest of fp-types) or surface as a
5151    /// typed error.
5152    ///
5153    /// Per br-frankenpandas-lbsx (9p0u Phase 2.6): public surface so
5154    /// downstream crates can consume the same alias map fp-types uses for
5155    /// `Timedelta::from_unit` / `Timestamp::*_to_unit`.
5156    #[must_use]
5157    pub fn unit_to_nanos(unit: &str) -> Option<i64> {
5158        match unit.to_lowercase().as_str() {
5159            "w" | "week" | "weeks" => Some(Self::NANOS_PER_WEEK),
5160            "d" | "day" | "days" => Some(Self::NANOS_PER_DAY),
5161            "h" | "hr" | "hour" | "hours" => Some(Self::NANOS_PER_HOUR),
5162            "m" | "min" | "minute" | "minutes" | "t" => Some(Self::NANOS_PER_MIN),
5163            "s" | "sec" | "second" | "seconds" => Some(Self::NANOS_PER_SEC),
5164            "ms" | "milli" | "millis" | "millisecond" | "milliseconds" | "l" => {
5165                Some(Self::NANOS_PER_MILLI)
5166            }
5167            "us" | "µs" | "micro" | "micros" | "microsecond" | "microseconds" | "u" => {
5168                Some(Self::NANOS_PER_MICRO)
5169            }
5170            "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" | "n" => Some(1),
5171            "" => Some(Self::NANOS_PER_DAY),
5172            _ => None,
5173        }
5174    }
5175
5176    pub fn components(nanos: i64) -> TimedeltaComponents {
5177        if nanos == Self::NAT {
5178            return TimedeltaComponents::default();
5179        }
5180
5181        // pandas/Python normalize via FLOOR division (like format()): the days
5182        // component can be negative while the time-of-day remainder is always in
5183        // [0, 1 day). So pd.Timedelta(-1,'s').components == (-1, 23, 59, 59, 0, 0, 0),
5184        // NOT the abs-based (0, 0, 0, 1, 0, 0, 0).
5185        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5186        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5187
5188        let hours = rem / Self::NANOS_PER_HOUR;
5189        let rem = rem % Self::NANOS_PER_HOUR;
5190
5191        let minutes = rem / Self::NANOS_PER_MIN;
5192        let rem = rem % Self::NANOS_PER_MIN;
5193
5194        let seconds = rem / Self::NANOS_PER_SEC;
5195        let rem = rem % Self::NANOS_PER_SEC;
5196
5197        let milliseconds = rem / Self::NANOS_PER_MILLI;
5198        let rem = rem % Self::NANOS_PER_MILLI;
5199
5200        let microseconds = rem / Self::NANOS_PER_MICRO;
5201        let nanoseconds = rem % Self::NANOS_PER_MICRO;
5202
5203        TimedeltaComponents {
5204            days,
5205            hours,
5206            minutes,
5207            seconds,
5208            milliseconds,
5209            microseconds,
5210            nanoseconds,
5211        }
5212    }
5213
5214    pub fn total_seconds(nanos: i64) -> f64 {
5215        if nanos == Self::NAT {
5216            f64::NAN
5217        } else {
5218            nanos as f64 / Self::NANOS_PER_SEC as f64
5219        }
5220    }
5221
5222    /// Convert to specified time unit.
5223    ///
5224    /// Matches pd.Timedelta.as_unit(). Supported units: ns, us, ms, s, m, h, D.
5225    #[must_use]
5226    pub fn as_unit(nanos: i64, unit: &str) -> f64 {
5227        if nanos == Self::NAT {
5228            return f64::NAN;
5229        }
5230        let nanos_f = nanos as f64;
5231        match unit {
5232            "ns" | "nanoseconds" => nanos_f,
5233            "us" | "microseconds" => nanos_f / Self::NANOS_PER_MICRO as f64,
5234            "ms" | "milliseconds" => nanos_f / Self::NANOS_PER_MILLI as f64,
5235            "s" | "seconds" => nanos_f / Self::NANOS_PER_SEC as f64,
5236            "m" | "minutes" => nanos_f / Self::NANOS_PER_MIN as f64,
5237            "h" | "hours" => nanos_f / Self::NANOS_PER_HOUR as f64,
5238            "D" | "days" => nanos_f / Self::NANOS_PER_DAY as f64,
5239            _ => f64::NAN,
5240        }
5241    }
5242
5243    /// Return the days component, or `None` for `NaT`. Matches
5244    /// `pd.Timedelta.days`.
5245    ///
5246    /// ⚠️ `None`, NOT `0`, AND THE TYPE IS THE FIX
5247    /// (br-frankenpandas-timedelta-nat-days-returns-zero-406ni). All four
5248    /// component helpers used to return `0` for `NaT`, one of them behind a
5249    /// comment asserting "pandas returns 0 for NaT.days (no error)". MEASURED,
5250    /// live pandas 2.2.3: `pd.NaT.days` is **nan**, and
5251    /// `pd.to_timedelta([1, None, -1], unit='s').dt.days` is float64
5252    /// `[0.0, nan, -1.0]` — pandas promotes the whole column because NaN cannot
5253    /// live in int64.
5254    ///
5255    /// An `i64` return cannot express that, so correctness depended on every
5256    /// caller remembering to test `NAT` first. It did — `timedelta_component`
5257    /// checked in three separate arms — but that is a convention, and the bead
5258    /// filed it as a landmine for the next person to wire a `.dt` accessor: a
5259    /// function whose doc says "matches pandas" handing back a plausible integer
5260    /// where pandas has a missing value. `Option<i64>` moves the fact into the
5261    /// type, so a caller cannot forget and the duplicated `NAT` tests go away.
5262    #[must_use]
5263    pub fn days(nanos: i64) -> Option<i64> {
5264        if nanos == Self::NAT {
5265            return None;
5266        }
5267        // FLOOR division like pandas: pd.Timedelta(-1,'s').days == -1, not 0.
5268        Some(nanos.div_euclid(Self::NANOS_PER_DAY))
5269    }
5270
5271    /// Return the seconds component (0-86399), or `None` for `NaT`. Matches
5272    /// `pd.Timedelta.seconds`. See [`Self::days`] for why this is an `Option`.
5273    #[must_use]
5274    pub fn seconds(nanos: i64) -> Option<i64> {
5275        if nanos == Self::NAT {
5276            return None;
5277        }
5278        // Floor-normalized time-of-day remainder: pd.Timedelta(-1,'s').seconds == 86399.
5279        Some(nanos.rem_euclid(Self::NANOS_PER_DAY) / Self::NANOS_PER_SEC)
5280    }
5281
5282    /// Return the microseconds component (0-999999), or `None` for `NaT`.
5283    /// Matches `pd.Timedelta.microseconds`. See [`Self::days`].
5284    #[must_use]
5285    pub fn microseconds(nanos: i64) -> Option<i64> {
5286        if nanos == Self::NAT {
5287            return None;
5288        }
5289        Some(nanos.rem_euclid(Self::NANOS_PER_SEC) / Self::NANOS_PER_MICRO)
5290    }
5291
5292    /// Return the nanoseconds component (0-999), or `None` for `NaT`. Matches
5293    /// `pd.Timedelta.nanoseconds`. See [`Self::days`].
5294    #[must_use]
5295    pub fn nanoseconds(nanos: i64) -> Option<i64> {
5296        if nanos == Self::NAT {
5297            return None;
5298        }
5299        Some(nanos.rem_euclid(Self::NANOS_PER_MICRO))
5300    }
5301
5302    /// The coarsest [`TimedeltaStringResolution`] that renders `nanos`
5303    /// losslessly. Fold over a column with `max`.
5304    ///
5305    /// `NaT` reports `Days`, the identity of that fold, because pandas excludes
5306    /// it from the scan: `[1 days, NaT]` still renders `['1 days', 'NaT']`.
5307    #[must_use]
5308    pub const fn string_resolution(nanos: i64) -> TimedeltaStringResolution {
5309        if nanos == Self::NAT || nanos.rem_euclid(Self::NANOS_PER_DAY) == 0 {
5310            TimedeltaStringResolution::Days
5311        } else {
5312            TimedeltaStringResolution::Full
5313        }
5314    }
5315
5316    /// Render `nanos` the way `astype(str)` does, at a resolution chosen for the
5317    /// whole column by [`Self::string_resolution`].
5318    ///
5319    /// The `Full` arm is [`Self::format`] verbatim — the per-value sub-second
5320    /// width was already right. Only the `Days` arm is new, and it exists
5321    /// because a column of whole days drops its time part completely:
5322    /// `'1 days'`, not `'1 days 00:00:00'`.
5323    #[must_use]
5324    pub fn format_at_resolution(nanos: i64, resolution: TimedeltaStringResolution) -> String {
5325        if nanos == Self::NAT {
5326            return "NaT".to_string();
5327        }
5328        match resolution {
5329            TimedeltaStringResolution::Full => Self::format(nanos),
5330            // Euclidean division, so a negative whole-day value keeps pandas'
5331            // spelling: -2 days is "-2 days", never "-1 days -24:00:00".
5332            TimedeltaStringResolution::Days => {
5333                format!("{} days", nanos.div_euclid(Self::NANOS_PER_DAY))
5334            }
5335        }
5336    }
5337
5338    pub fn format(nanos: i64) -> String {
5339        use std::fmt::Write as _;
5340
5341        if nanos == Self::NAT {
5342            return "NaT".to_string();
5343        }
5344
5345        // pandas / Python timedelta normalize via FLOOR division: the days
5346        // component can be negative while the time-of-day remainder is always
5347        // non-negative, and a negative-days value prints a '+' before the time
5348        // (e.g. -1s -> "-1 days +23:59:59", not "-0 days 00:00:01"). Compute the
5349        // components with Euclidean div/rem so the remainder is in [0, 1 day).
5350        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5351        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5352        let hours = rem / Self::NANOS_PER_HOUR;
5353        let minutes = (rem % Self::NANOS_PER_HOUR) / Self::NANOS_PER_MIN;
5354        let seconds = (rem % Self::NANOS_PER_MIN) / Self::NANOS_PER_SEC;
5355        let frac = rem % Self::NANOS_PER_SEC;
5356
5357        // Build directly into the returned allocation. The former path first
5358        // allocated an `HH:MM:SS` string, then copied it into the result.
5359        let mut result = String::with_capacity(32);
5360        let _ = write!(result, "{days} days ");
5361        // '+' joins the negative day count to the positive time remainder.
5362        if days < 0 {
5363            result.push('+');
5364        }
5365        let _ = write!(result, "{hours:02}:{minutes:02}:{seconds:02}");
5366        if frac > 0 {
5367            // pandas renders the sub-second part with microsecond precision
5368            // (6 digits) unless a sub-microsecond (nanosecond) component is
5369            // present, in which case it widens to 9 digits.
5370            if frac % 1_000 == 0 {
5371                let _ = write!(result, ".{:06}", frac / 1_000);
5372            } else {
5373                let _ = write!(result, ".{frac:09}");
5374            }
5375        }
5376        result
5377    }
5378
5379    /// Build a nanosecond Timedelta from a float quantity of `unit`.
5380    ///
5381    /// Matches `pd.Timedelta(value, unit=...)`:
5382    /// - `NaN` → `NAT`. pandas returns `NaT`, and `NAT` is how NaT is spelled
5383    ///   in this i64 representation. Rust's float→int `as` maps `NaN` to
5384    ///   **0**, so the unguarded cast used to hand back a ZERO DURATION for a
5385    ///   missing value (br-frankenpandas-8v92m).
5386    /// - non-finite or out-of-range product → [`TimedeltaError::Overflow`].
5387    ///   pandas raises `OutOfBoundsTimedelta` ("Cannot cast inf from s to 'ns'
5388    ///   without overflow"); the `as` cast used to SATURATE to `i64::MAX`,
5389    ///   returning a finite, plausible ~106751-day duration instead.
5390    /// - unknown unit → [`TimedeltaError::InvalidFormat`], unchanged.
5391    ///
5392    /// The overflow guard is the same one `parse` and the component parser
5393    /// already use (added by br-frankenpandas-zw3mg, which fixed two of the
5394    /// three sites sharing this expression and missed this one).
5395    pub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError> {
5396        let multiplier = Self::unit_to_nanos(unit)
5397            .ok_or_else(|| TimedeltaError::InvalidFormat(unit.to_string()))?;
5398        if value.is_nan() {
5399            return Ok(Self::NAT);
5400        }
5401        let product = value * multiplier as f64;
5402        if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5403            return Err(TimedeltaError::Overflow);
5404        }
5405        Ok(product.round() as i64)
5406    }
5407
5408    // ── Arithmetic (br-frankenpandas-4r56 Phase 1) ──────────────────────
5409    //
5410    // NaT propagation: any arithmetic with `NAT` returns `NAT`. Matches
5411    // pandas `pd.NaT + anything == NaT`, `pd.NaT - anything == NaT`, etc.
5412    //
5413    // Overflow (br-frankenpandas-lgyy8): i64 overflow yields `NAT` in BOTH
5414    // directions. It never wraps and never fabricates a finite value.
5415    //
5416    // These previously used `saturating_*`, which was asymmetric and failed
5417    // OPEN on one side. Because `NAT == i64::MIN`, negative overflow clamped
5418    // onto the sentinel and already surfaced as missing — but POSITIVE
5419    // overflow clamped to `i64::MAX`, a perfectly valid, finite, plausible
5420    // duration (and, for `Timestamp`, a ~year-2262 instant) returned as if it
5421    // were real data. Live pandas 2.2.3 never does that, in either the scalar
5422    // or the vectorized path:
5423    //
5424    //   pd.Timedelta.min + Timedelta('-1ns')      -> NaT  (lands on the sentinel)
5425    //   pd.Series[datetime64] + Timedelta('-1ns') -> [NaT, ...]
5426    //   pd.Timedelta.max + Timedelta('1ns')       -> raises OverflowError
5427    //   pd.Timestamp.max + Timedelta('1ns')       -> raises OutOfBoundsDatetime
5428    //   pd.Series[datetime64] + Timedelta('1ns')  -> raises OverflowError
5429    //   pd.Timestamp.min - pd.Timestamp.max       -> raises OutOfBoundsDatetime
5430    //   pd.Timedelta.max * 2                      -> raises OverflowError
5431    //
5432    // We surface NaT where pandas raises, rather than making these infallible
5433    // `#[must_use]` helpers fallible: that is the SAME documented divergence
5434    // `div_scalar` already takes for divide-by-zero ("matches pandas, which
5435    // raises, but we surface as NaT to avoid panics at the type-system
5436    // boundary"). Every input whose exact result is representable is
5437    // unaffected bit-for-bit; only overflow moves.
5438
5439    /// Add two Timedelta nanosecond values, reporting overflow.
5440    ///
5441    /// br-frankenpandas-fyr1z-policy-carrier-f29nz. NaT propagation is NOT an
5442    /// overflow — a NaT operand yields `Ok(NAT)`, exactly as before. Only an
5443    /// unrepresentable result is an `Err`.
5444    ///
5445    /// # Errors
5446    /// [`PandasTemporalError::Overflow`] when the sum exceeds i64.
5447    pub fn try_add(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5448        if a == Self::NAT || b == Self::NAT {
5449            return Ok(Self::NAT);
5450        }
5451        a.checked_add(b).ok_or(
5452            TemporalFailure::new("Timedelta::add", PandasTemporalError::Overflow)
5453                .with_operands(a, b),
5454        )
5455    }
5456
5457    /// Add two Timedelta nanosecond values. NaT propagates; overflow → NaT.
5458    #[must_use]
5459    pub fn add(a: i64, b: i64) -> i64 {
5460        Self::try_add(a, b).unwrap_or(Self::NAT)
5461    }
5462
5463    /// Subtract two Timedelta nanosecond values, reporting overflow.
5464    ///
5465    /// # Errors
5466    /// [`PandasTemporalError::Overflow`] when the difference exceeds i64.
5467    pub fn try_sub(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5468        if a == Self::NAT || b == Self::NAT {
5469            return Ok(Self::NAT);
5470        }
5471        a.checked_sub(b).ok_or(
5472            TemporalFailure::new("Timedelta::sub", PandasTemporalError::Overflow)
5473                .with_operands(a, b),
5474        )
5475    }
5476
5477    /// Subtract two Timedelta nanosecond values. NaT propagates; overflow → NaT.
5478    #[must_use]
5479    pub fn sub(a: i64, b: i64) -> i64 {
5480        Self::try_sub(a, b).unwrap_or(Self::NAT)
5481    }
5482
5483    /// Negate a Timedelta value. NaT stays NaT.
5484    ///
5485    /// There is no overflow case to handle, and the `saturating_` call is a
5486    /// belt-and-braces no-op: the only `i64` whose negation overflows is
5487    /// `i64::MIN`, and `i64::MIN` IS the NaT sentinel, so it is consumed by
5488    /// the guard above. The representable range is `[i64::MIN + 1, i64::MAX]`,
5489    /// which is symmetric about zero.
5490    ///
5491    /// CORRECTED br-frankenpandas-fyr1z: this used to claim "pandas:
5492    /// `-pd.Timedelta.min` is NaT since min == -max - 1 cannot be negated".
5493    /// That is false in both halves. pandas' `Timedelta.min.value` is
5494    /// `-9223372036854775807` == `-Timedelta.max.value`, NOT `-max - 1`
5495    /// (`-max - 1` is `i64::MIN`, which pandas also reserves for NaT), and
5496    /// live pandas 2.2.3 returns `Timedelta('106751 days 23:47:16.854775807')`
5497    /// — i.e. `Timedelta.max` — for `-pd.Timedelta.min`, `abs(pd.Timedelta
5498    /// .min)`, and the vectorized `-Series[timedelta64]` / `.abs()` forms.
5499    /// Do not "fix" this to return NaT; that would be the parity regression.
5500    #[must_use]
5501    pub fn neg(a: i64) -> i64 {
5502        if a == Self::NAT {
5503            return Self::NAT;
5504        }
5505        a.saturating_neg()
5506    }
5507
5508    /// Absolute value of a Timedelta. NaT stays NaT.
5509    ///
5510    /// As with [`Timedelta::neg`], no overflow is reachable: `i64::MIN` is the
5511    /// NaT sentinel and is consumed by the guard, and `|i64::MIN + 1|` is
5512    /// exactly `i64::MAX`. pandas agrees — `abs(pd.Timedelta.min)` is
5513    /// `Timedelta.max`, not NaT.
5514    #[must_use]
5515    pub fn abs(a: i64) -> i64 {
5516        if a == Self::NAT {
5517            return Self::NAT;
5518        }
5519        a.saturating_abs()
5520    }
5521
5522    /// Multiply a Timedelta value by an integer factor. NaT propagates;
5523    /// overflow → NaT (see the overflow note above).
5524    ///
5525    /// Matches pandas `pd.Timedelta(...) * int`, which raises `OverflowError`
5526    /// rather than returning a saturated duration.
5527    #[must_use]
5528    pub fn mul_scalar(a: i64, factor: i64) -> i64 {
5529        Self::try_mul_scalar(a, factor).unwrap_or(Self::NAT)
5530    }
5531
5532    /// Multiply a Timedelta by an integer factor under an explicit policy.
5533    ///
5534    /// br-frankenpandas-fyr1z-wrap-signoff-s4lkx, DECIDED BY THE MAINTAINER:
5535    /// **STRICT REPRODUCES PANDAS' SILENT WRAP.** The rationale is that this is
5536    /// a PORT — STRICT means bit-for-bit observable parity with the incumbent
5537    /// *including its quirks*, so the wrap is a deliberately reproduced pandas
5538    /// behaviour, not a defect of ours.
5539    ///
5540    /// Verified against live pandas 2.2.3: `Series([Timedelta.max]) * 2` returns
5541    /// `-2` ns (displayed `-1 days +23:59:59.999999998`), which is exactly
5542    /// `i64::MAX.wrapping_mul(2)`. Rust's wrapping arithmetic reproduces numpy's
5543    /// int64 wraparound bit-for-bit, so no emulation is needed.
5544    ///
5545    /// The wrap is INTEGER-MULTIPLIER ONLY: `Series * 2.0` returns NaT in
5546    /// pandas, so a float multiplier must not route here.
5547    ///
5548    /// Every other policy keeps today's behaviour — NaT, with HARDENED also
5549    /// recording the recovery. So the fail-open shape br-frankenpandas-lgyy8
5550    /// removed is reachable ONLY when a caller explicitly asks for STRICT
5551    /// incumbent parity, never by default. See DISC-020.
5552    #[must_use]
5553    pub fn mul_scalar_with_policy(a: i64, factor: i64, policy: OverflowPolicy) -> i64 {
5554        if a == Self::NAT {
5555            return Self::NAT;
5556        }
5557        if matches!(policy, OverflowPolicy::Strict) {
5558            return a.wrapping_mul(factor);
5559        }
5560        policy
5561            .resolve_recording(Self::try_mul_scalar(a, factor), Self::NAT, Self::NAT)
5562            .unwrap_or(Self::NAT)
5563    }
5564
5565    /// Multiply a Timedelta value by an integer factor, reporting overflow.
5566    ///
5567    /// # Errors
5568    /// [`PandasTemporalError::Overflow`] when the product exceeds i64 — which
5569    /// is what the SCALAR `pd.Timedelta.max * 2` raises. Note DISC-018: the
5570    /// VECTORIZED `Series * int` wraps silently instead, so a strict arm for
5571    /// this op must decide per-surface rather than inherit this class blindly.
5572    pub fn try_mul_scalar(a: i64, factor: i64) -> Result<i64, TemporalFailure> {
5573        if a == Self::NAT {
5574            return Ok(Self::NAT);
5575        }
5576        a.checked_mul(factor).ok_or(
5577            TemporalFailure::new("Timedelta::mul_scalar", PandasTemporalError::Overflow)
5578                .with_operands(a, factor),
5579        )
5580    }
5581
5582    /// Floor-divide a Timedelta value by an integer divisor. NaT propagates.
5583    /// Returns NaT on divide-by-zero (matches pandas, which raises, but we
5584    /// surface as NaT to avoid panics at the type-system boundary).
5585    ///
5586    /// Matches pandas / Python `pd.Timedelta(...) // int`: floor division,
5587    /// not truncation toward zero. `-100 // 3 == -34`, and `100 // -3 ==
5588    /// -34`. Rust's `/` truncates toward zero and `div_euclid` keeps the
5589    /// remainder non-negative — neither matches pandas when the divisor is
5590    /// negative. This helper adjusts trunc-toward-zero into floor.
5591    #[must_use]
5592    pub fn div_scalar(a: i64, divisor: i64) -> i64 {
5593        Self::try_div_scalar(a, divisor).unwrap_or(Self::NAT)
5594    }
5595
5596    /// Floor-divide a Timedelta by an integer divisor, reporting divide-by-zero.
5597    ///
5598    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2. NaT propagation is not a
5599    /// failure and yields `Ok(NAT)`; only a zero divisor is an `Err`.
5600    ///
5601    /// ⚠ SCALAR SEMANTICS ONLY. pandas raises `ZeroDivisionError` for the
5602    /// scalar `pd.Timedelta('1s') // 0`, but the VECTORIZED
5603    /// `Series([Timedelta]) // 0` returns NaT (both probed on 2.2.3). The
5604    /// infallible [`Self::div_scalar`] above keeps the NaT behavior that the
5605    /// vectorized callers depend on, and a STRICT arm must route only the
5606    /// scalar surface here.
5607    ///
5608    /// # Errors
5609    /// [`PandasTemporalError::ZeroDivision`] when `divisor == 0`.
5610    pub fn try_div_scalar(a: i64, divisor: i64) -> Result<i64, TemporalFailure> {
5611        if divisor == 0 {
5612            return Err(TemporalFailure::new(
5613                "Timedelta::div_scalar",
5614                PandasTemporalError::ZeroDivision,
5615            )
5616            .with_operands(a, divisor));
5617        }
5618        if a == Self::NAT {
5619            return Ok(Self::NAT);
5620        }
5621        Ok(Self::div_scalar_inner(a, divisor))
5622    }
5623
5624    fn div_scalar_inner(a: i64, divisor: i64) -> i64 {
5625        // NAT == i64::MIN so the classic `i64::MIN / -1` overflow path is
5626        // already handled by the NAT check above. `(i64::MIN + 1) / -1`
5627        // equals `i64::MAX` with no overflow, so we never need a
5628        // saturation branch here.
5629        let q = a / divisor;
5630        let r = a % divisor;
5631        // If remainder is non-zero and has opposite sign from divisor,
5632        // Rust's trunc-toward-zero `/` is one step above the floor. Adjust
5633        // down by 1 to match Python/pandas floor division.
5634        if r != 0 && (r < 0) != (divisor < 0) {
5635            q - 1
5636        } else {
5637            q
5638        }
5639    }
5640
5641    /// Divide two Timedelta values, returning the ratio as f64.
5642    /// Matches pandas `pd.Timedelta(...) / pd.Timedelta(...)` → float.
5643    /// NaT in either operand → NaN. Zero divisor → ±Inf (per IEEE 754).
5644    #[must_use]
5645    pub fn div_timedelta(a: i64, b: i64) -> f64 {
5646        if a == Self::NAT || b == Self::NAT {
5647            return f64::NAN;
5648        }
5649        (a as f64) / (b as f64)
5650    }
5651
5652    /// Returns ISO 8601 duration format string.
5653    ///
5654    /// Matches pandas `pd.Timedelta.isoformat()`. Returns format like
5655    /// "P1DT2H3M4.567890123S" for 1 day, 2 hours, 3 minutes, 4.567890123 seconds.
5656    /// A negative duration is pandas' components form: whole days rounded
5657    /// down, then a non-negative clock (-1 day -1 hour is "P-2DT23H0M0S";
5658    /// it was "-P1DT1H0M0S"). NaT returns "NaT".
5659    #[must_use]
5660    pub fn isoformat(nanos: i64) -> String {
5661        use std::fmt::Write as _;
5662
5663        if nanos == Self::NAT {
5664            return "NaT".to_string();
5665        }
5666
5667        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5668        let remaining = nanos.rem_euclid(Self::NANOS_PER_DAY);
5669
5670        let hours = remaining / Self::NANOS_PER_HOUR;
5671        let remaining = remaining % Self::NANOS_PER_HOUR;
5672
5673        let minutes = remaining / Self::NANOS_PER_MIN;
5674        let remaining = remaining % Self::NANOS_PER_MIN;
5675
5676        let seconds = remaining / Self::NANOS_PER_SEC;
5677        let sub_sec_nanos = remaining % Self::NANOS_PER_SEC;
5678
5679        // Build directly into the returned allocation. The former sequence of
5680        // `format!` calls allocated two temporary strings for integral values
5681        // and three for fractional values before copying them into `result`.
5682        let mut result = String::with_capacity(40);
5683        // `fmt::Write for String` is infallible.
5684        let _ = write!(result, "P{days}DT{hours}H{minutes}M{seconds}");
5685        if sub_sec_nanos != 0 {
5686            result.push('.');
5687            let _ = write!(result, "{sub_sec_nanos:09}");
5688            while result.ends_with('0') {
5689                result.pop();
5690            }
5691        }
5692        result.push('S');
5693        result
5694    }
5695
5696    /// Rounds down to the nearest frequency unit.
5697    ///
5698    /// Matches pandas `pd.Timedelta.floor(freq)`. NaT is preserved.
5699    #[must_use]
5700    pub fn floor(nanos: i64, freq: &str) -> i64 {
5701        if nanos == Self::NAT {
5702            return Self::NAT;
5703        }
5704        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5705            return Self::NAT;
5706        };
5707        if unit_nanos == 0 {
5708            return Self::NAT;
5709        }
5710        nanos
5711            .div_euclid(unit_nanos)
5712            .checked_mul(unit_nanos)
5713            .unwrap_or(Self::NAT)
5714    }
5715
5716    /// Rounds up to the nearest frequency unit.
5717    ///
5718    /// Matches pandas `pd.Timedelta.ceil(freq)`. NaT is preserved; overflow
5719    /// → NaT (`pd.Timedelta.max.ceil('D')` raises `OutOfBoundsTimedelta:
5720    /// Cannot round ... without overflow`, so a clamped `i64::MAX` would be a
5721    /// fabricated finite duration — see br-frankenpandas-kyd16).
5722    #[must_use]
5723    pub fn ceil(nanos: i64, freq: &str) -> i64 {
5724        if nanos == Self::NAT {
5725            return Self::NAT;
5726        }
5727        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5728            return Self::NAT;
5729        };
5730        if unit_nanos == 0 {
5731            return Self::NAT;
5732        }
5733        let remainder = nanos.rem_euclid(unit_nanos);
5734        if remainder == 0 {
5735            nanos
5736        } else {
5737            nanos
5738                .checked_add(unit_nanos - remainder)
5739                .unwrap_or(Self::NAT)
5740        }
5741    }
5742
5743    /// Rounds to the nearest frequency unit.
5744    ///
5745    /// Matches pandas `pd.Timedelta.round(freq)`. Uses banker's rounding
5746    /// (round half to even). NaT is preserved.
5747    #[must_use]
5748    pub fn round(nanos: i64, freq: &str) -> i64 {
5749        if nanos == Self::NAT {
5750            return Self::NAT;
5751        }
5752        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5753            return Self::NAT;
5754        };
5755        if unit_nanos == 0 {
5756            return Self::NAT;
5757        }
5758        let negative = nanos < 0;
5759        let abs_nanos = nanos.saturating_abs();
5760
5761        let quotient = abs_nanos / unit_nanos;
5762        let remainder = abs_nanos % unit_nanos;
5763        let half = unit_nanos / 2;
5764
5765        // Round-UP must be checked (br-frankenpandas-kyd16). `quotient *
5766        // unit_nanos` is always <= abs_nanos and cannot overflow, but
5767        // `(quotient + 1) * unit_nanos` can exceed i64::MAX — and this used
5768        // UNCHECKED arithmetic, so it panicked in debug and WRAPPED to a
5769        // large-negative duration in release. pandas raises
5770        // OutOfBoundsTimedelta ("Cannot round ... without overflow"); we
5771        // surface NaT, consistent with the rest of this block.
5772        let round_up = || {
5773            quotient
5774                .checked_add(1)
5775                .and_then(|q| q.checked_mul(unit_nanos))
5776        };
5777        let rounded = if remainder > half {
5778            round_up()
5779        } else if remainder < half {
5780            Some(quotient * unit_nanos)
5781        } else {
5782            // Exactly half: round to even
5783            if quotient % 2 == 0 {
5784                Some(quotient * unit_nanos)
5785            } else {
5786                round_up()
5787            }
5788        };
5789
5790        match rounded {
5791            // Negating is safe: `rounded` is non-negative and at most i64::MAX,
5792            // so `-rounded` is at worst i64::MIN + 1 — never the NaT sentinel.
5793            Some(rounded) => {
5794                if negative {
5795                    -rounded
5796                } else {
5797                    rounded
5798                }
5799            }
5800            None => Self::NAT,
5801        }
5802    }
5803}
5804
5805// ── Time zones ──────────────────────────────────────────────────────────
5806//
5807// A tz-aware value is a UTC instant plus a zone name; what the zone adds is
5808// the wall clock the instant shows there. These are the conversions every
5809// crate shares (Timestamp, DatetimeIndex, datetime columns).
5810
5811/// Why a time-zone conversion failed, as pandas (pytz) classifies it.
5812#[derive(Debug, Clone, PartialEq, Eq, Error)]
5813pub enum TimeZoneError {
5814    /// Neither 'UTC', a fixed offset ('+05:30') nor an IANA name - pandas'
5815    /// `UnknownTimeZoneError`, a `KeyError` whose message is the quoted name.
5816    #[error("'{0}'")]
5817    Unknown(String),
5818    /// A wall-clock time a DST change skips - pandas' `NonExistentTimeError`,
5819    /// whose message is the wall time.
5820    #[error("{0}")]
5821    NonExistent(String),
5822    /// A wall-clock time a DST change repeats - pandas' `AmbiguousTimeError`.
5823    #[error("Cannot infer dst time from {0}, try using the 'ambiguous' argument")]
5824    Ambiguous(String),
5825}
5826
5827/// A parsed zone: UTC or a fixed offset, or an IANA zone with DST rules.
5828enum Zone {
5829    Fixed(chrono::FixedOffset),
5830    Named(chrono_tz::Tz),
5831}
5832
5833impl Zone {
5834    /// pandas' zone spellings: 'UTC' / 'Z', a `+HH:MM` / `-HH:MM` offset (also
5835    /// as `UTC+HH:MM`, how a fixed-offset dtype names its zone), or an IANA
5836    /// name ('US/Eastern', 'Asia/Tokyo', 'Etc/GMT+5').
5837    fn parse(tz: &str) -> Result<Self, TimeZoneError> {
5838        use chrono::Offset;
5839        let name = tz.trim();
5840        if name == "UTC" || name == "Z" {
5841            return Ok(Self::Fixed(chrono::Utc.fix()));
5842        }
5843        let offset = name
5844            .strip_prefix("UTC")
5845            .filter(|rest| rest.starts_with(['+', '-']))
5846            .unwrap_or(name);
5847        let bytes = offset.as_bytes();
5848        if bytes.len() == 6
5849            && matches!(bytes[0], b'+' | b'-')
5850            && bytes[3] == b':'
5851            && [1, 2, 4, 5].iter().all(|&i| bytes[i].is_ascii_digit())
5852        {
5853            let hours: i32 = offset[1..3].parse().unwrap_or(24);
5854            let minutes: i32 = offset[4..6].parse().unwrap_or(60);
5855            let sign = if bytes[0] == b'-' { -1 } else { 1 };
5856            return (hours <= 23 && minutes <= 59)
5857                .then(|| chrono::FixedOffset::east_opt(sign * (hours * 3_600 + minutes * 60)))
5858                .flatten()
5859                .map(Self::Fixed)
5860                .ok_or_else(|| TimeZoneError::Unknown(name.to_owned()));
5861        }
5862        name.parse::<chrono_tz::Tz>()
5863            .map(Self::Named)
5864            .map_err(|_| TimeZoneError::Unknown(name.to_owned()))
5865    }
5866
5867    /// Seconds east of UTC this zone is at the UTC instant `utc_nanos`.
5868    fn offset_seconds(&self, utc_nanos: i64) -> i32 {
5869        use chrono::{Offset, TimeZone};
5870        match self {
5871            Self::Fixed(offset) => offset.local_minus_utc(),
5872            Self::Named(zone) => {
5873                let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5874                zone.offset_from_utc_datetime(&utc).fix().local_minus_utc()
5875            }
5876        }
5877    }
5878}
5879
5880/// Whether `tz` names a zone pandas accepts ('UTC', `+HH:MM`, an IANA name).
5881pub fn tz_validate(tz: &str) -> Result<(), TimeZoneError> {
5882    Zone::parse(tz).map(|_| ())
5883}
5884
5885/// The name pandas gives the zone `tz`: a fixed offset is `UTC+HH:MM`
5886/// ('+05:30' and 'UTC+05:30' alike; a zero offset or 'Z' is 'UTC'), an
5887/// IANA name stays as given.
5888pub fn tz_canonical_name(tz: &str) -> Result<String, TimeZoneError> {
5889    Ok(match Zone::parse(tz)? {
5890        Zone::Fixed(offset) if offset.local_minus_utc() == 0 => "UTC".to_owned(),
5891        Zone::Fixed(offset) => format!("UTC{offset}"),
5892        Zone::Named(_) => tz.trim().to_owned(),
5893    })
5894}
5895
5896/// The zone's name at the UTC instant `utc_nanos` as `strftime('%Z')` prints
5897/// it: an IANA zone's abbreviation then ('EST' / 'EDT'), a fixed offset's
5898/// `UTC+HH:MM` ('UTC' for zero).
5899pub fn tz_abbreviation(tz: &str, utc_nanos: i64) -> Result<String, TimeZoneError> {
5900    use chrono::TimeZone;
5901    match Zone::parse(tz)? {
5902        Zone::Named(zone) => {
5903            let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5904            let offset = zone.offset_from_utc_datetime(&utc);
5905            Ok(chrono_tz::OffsetName::abbreviation(&offset)
5906                .map_or_else(|| tz.trim().to_owned(), str::to_owned))
5907        }
5908        Zone::Fixed(_) => tz_canonical_name(tz),
5909    }
5910}
5911
5912/// The UTC offset, in seconds east of UTC, that `tz` has at the UTC instant
5913/// `utc_nanos` - what a tz-aware timestamp adds to its instant to show its
5914/// wall clock.
5915pub fn tz_offset_seconds(tz: &str, utc_nanos: i64) -> Result<i32, TimeZoneError> {
5916    Ok(Zone::parse(tz)?.offset_seconds(utc_nanos))
5917}
5918
5919/// The wall clock the UTC instant `utc_nanos` shows in `tz`, as naive
5920/// nanoseconds (NaT, `i64::MIN`, stays NaT).
5921pub fn tz_utc_to_wall_nanos(tz: &str, utc_nanos: i64) -> Result<i64, TimeZoneError> {
5922    if utc_nanos == i64::MIN {
5923        return Ok(utc_nanos);
5924    }
5925    let offset = Zone::parse(tz)?.offset_seconds(utc_nanos);
5926    Ok(utc_nanos.saturating_add(i64::from(offset) * 1_000_000_000))
5927}
5928
5929/// The UTC instant of the wall-clock time `wall_nanos` in `tz`, as pandas'
5930/// `tz_localize` with ambiguous / nonexistent = 'raise': a wall time a DST
5931/// change skips is [`TimeZoneError::NonExistent`], one it repeats
5932/// [`TimeZoneError::Ambiguous`]. NaT (`i64::MIN`) stays NaT.
5933pub fn tz_wall_to_utc_nanos(tz: &str, wall_nanos: i64) -> Result<i64, TimeZoneError> {
5934    tz_wall_to_utc_nanos_with(tz, wall_nanos, AmbiguousTime::Raise, NonexistentTime::Raise)
5935}
5936
5937/// What `tz_localize` does with a wall time a DST change repeats (pandas'
5938/// `ambiguous=`, for one value): refuse it, take its first occurrence (DST,
5939/// pandas' `True`) or its second (standard time, `False`), or make it NaT.
5940#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5941pub enum AmbiguousTime {
5942    Raise,
5943    Earliest,
5944    Latest,
5945    NaT,
5946}
5947
5948/// What `tz_localize` does with a wall time a DST change skips (pandas'
5949/// `nonexistent=`): refuse it, move it to the first instant after the gap
5950/// (`shift_forward`) or the last nanosecond before it (`shift_backward`),
5951/// make it NaT, or move the wall time by a duration (nanoseconds) and
5952/// localize that.
5953#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5954pub enum NonexistentTime {
5955    Raise,
5956    ShiftForward,
5957    ShiftBackward,
5958    NaT,
5959    Shift(i64),
5960}
5961
5962/// [`tz_wall_to_utc_nanos`] under pandas' `ambiguous` / `nonexistent`
5963/// policies; NaT (`i64::MIN`) where a policy says NaT.
5964pub fn tz_wall_to_utc_nanos_with(
5965    tz: &str,
5966    wall_nanos: i64,
5967    ambiguous: AmbiguousTime,
5968    nonexistent: NonexistentTime,
5969) -> Result<i64, TimeZoneError> {
5970    if wall_nanos == i64::MIN {
5971        return Ok(wall_nanos);
5972    }
5973    wall_to_utc_in(&Zone::parse(tz)?, wall_nanos, ambiguous, nonexistent)
5974}
5975
5976const NANOS_PER_HOUR: i64 = 3_600_000_000_000;
5977const NANOS_PER_SECOND: i64 = 1_000_000_000;
5978
5979/// Each of `utc`'s instants' wall clock in `tz` (NaT stays NaT), as
5980/// [`tz_utc_to_wall_nanos`] makes one: the zone parsed once, and an hour's
5981/// offset reused while the instants stay in an hour holding one offset -
5982/// the per-instant call parsed the zone's name and looked its offset up for
5983/// every instant (a zoned index's tz_localize(None) of a million 44 ms,
5984/// pandas 11; br-frankenpandas-6pqf3).
5985///
5986/// # Errors
5987/// An unknown zone.
5988pub fn tz_utc_to_wall_nanos_all(tz: &str, utc: &[i64]) -> Result<Vec<i64>, TimeZoneError> {
5989    let zone = Zone::parse(tz)?;
5990    let mut offsets = HourOffsets::new(&zone);
5991    Ok(utc
5992        .iter()
5993        .map(|&nanos| {
5994            if nanos == i64::MIN {
5995                nanos
5996            } else {
5997                nanos.saturating_add(i64::from(offsets.at(nanos)) * NANOS_PER_SECOND)
5998            }
5999        })
6000        .collect())
6001}
6002
6003/// Each of `walls`' wall-clock times placed in `tz` as
6004/// [`tz_wall_to_utc_nanos_with`] places one (the same `ambiguous` /
6005/// `nonexistent` rules; NaT stays NaT): the zone parsed once, and a local
6006/// hour holding no DST change mapped with its one offset while the times
6007/// stay in it (br-frankenpandas-6pqf3).
6008///
6009/// # Errors
6010/// An unknown zone, or a wall time the rules refuse.
6011pub fn tz_wall_to_utc_nanos_all(
6012    tz: &str,
6013    walls: &[i64],
6014    ambiguous: AmbiguousTime,
6015    nonexistent: NonexistentTime,
6016) -> Result<Vec<i64>, TimeZoneError> {
6017    let zone = Zone::parse(tz)?;
6018    let mut hour = i64::MIN;
6019    let mut checked = false;
6020    let mut simple: Option<i32> = None;
6021    walls
6022        .iter()
6023        .map(|&wall| {
6024            if wall == i64::MIN {
6025                return Ok(wall);
6026            }
6027            let at = wall.div_euclid(NANOS_PER_HOUR);
6028            if at == hour {
6029                if !checked {
6030                    checked = true;
6031                    simple = simple_local_hour(&zone, at);
6032                }
6033                if let Some(offset) = simple
6034                    && let Some(utc) = wall.checked_sub(i64::from(offset) * NANOS_PER_SECOND)
6035                {
6036                    return Ok(utc);
6037                }
6038            } else {
6039                hour = at;
6040                checked = false;
6041                simple = None;
6042            }
6043            wall_to_utc_in(&zone, wall, ambiguous, nonexistent)
6044        })
6045        .collect()
6046}
6047
6048/// The UTC offsets of a run of instants in one zone: the offset of the hour
6049/// the last instant fell in, kept while the next ones fall in it too and
6050/// the hour holds that one offset (checked once, at its first and last
6051/// nanosecond - a DST change inside makes them differ); any other instant's
6052/// looked up (br-frankenpandas-6pqf3). An instant run with no locality pays one lookup each,
6053/// as before.
6054struct HourOffsets<'a> {
6055    zone: &'a Zone,
6056    hour: i64,
6057    offset: i32,
6058    /// Whether `hour` holds `offset` throughout, once known.
6059    uniform: Option<bool>,
6060}
6061
6062impl<'a> HourOffsets<'a> {
6063    fn new(zone: &'a Zone) -> Self {
6064        Self {
6065            zone,
6066            hour: i64::MIN,
6067            offset: 0,
6068            uniform: None,
6069        }
6070    }
6071
6072    fn at(&mut self, utc: i64) -> i32 {
6073        if let Zone::Fixed(fixed) = self.zone {
6074            return fixed.local_minus_utc();
6075        }
6076        let hour = utc.div_euclid(NANOS_PER_HOUR);
6077        if hour != self.hour {
6078            self.hour = hour;
6079            self.uniform = None;
6080            self.offset = self.zone.offset_seconds(utc);
6081            return self.offset;
6082        }
6083        let uniform = *self.uniform.get_or_insert_with(|| {
6084            hour.checked_mul(NANOS_PER_HOUR).is_some_and(|start| {
6085                self.zone.offset_seconds(start) == self.offset
6086                    && start
6087                        .checked_add(NANOS_PER_HOUR - 1)
6088                        .is_some_and(|end| self.zone.offset_seconds(end) == self.offset)
6089            })
6090        });
6091        if uniform {
6092            self.offset
6093        } else {
6094            self.zone.offset_seconds(utc)
6095        }
6096    }
6097}
6098
6099/// The offset every wall time of local hour `hour` maps to UTC with, when
6100/// the hour holds no DST change: its first and last nanosecond each map to
6101/// one instant, at one offset (a gap or an overlap inside makes one of them
6102/// map otherwise or the offsets differ); None otherwise (br-frankenpandas-6pqf3).
6103fn simple_local_hour(zone: &Zone, hour: i64) -> Option<i32> {
6104    let start = hour.checked_mul(NANOS_PER_HOUR)?;
6105    let end = start.checked_add(NANOS_PER_HOUR - 1)?;
6106    let first = single_local_offset(zone, start)?;
6107    (single_local_offset(zone, end)? == first).then_some(first)
6108}
6109
6110/// The offset the wall time `wall_nanos` maps to UTC with when it maps to
6111/// exactly one instant.
6112fn single_local_offset(zone: &Zone, wall_nanos: i64) -> Option<i32> {
6113    use chrono::{LocalResult, Offset, TimeZone};
6114    let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6115    match zone {
6116        Zone::Fixed(offset) => Some(offset.local_minus_utc()),
6117        Zone::Named(zone) => match zone.from_local_datetime(&naive) {
6118            LocalResult::Single(at) => Some(at.offset().fix().local_minus_utc()),
6119            _ => None,
6120        },
6121    }
6122}
6123
6124/// A wall time as pandas names one it refuses to place: seconds, then the
6125/// microseconds as six digits when it has any and the nanoseconds as nine
6126/// when finer (chrono's text trimmed '.500000' to '.500'; br-frankenpandas-6pqf3).
6127fn wall_text(wall_nanos: i64) -> String {
6128    let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6129    let seconds = naive.format("%Y-%m-%d %H:%M:%S");
6130    let nanos = wall_nanos.rem_euclid(NANOS_PER_SECOND);
6131    if nanos == 0 {
6132        format!("{seconds}")
6133    } else if nanos % 1_000 == 0 {
6134        format!("{seconds}.{:06}", nanos / 1_000)
6135    } else {
6136        format!("{seconds}.{nanos:09}")
6137    }
6138}
6139
6140/// The offset pandas places a moved skipped wall time with: pytz's table
6141/// bisected at `moved` read as a UTC instant - the offset in force there
6142/// when moving forward onto an offset at or east of UTC, or when the zone's
6143/// first (local mean time) offset lies east and the move is forward or west
6144/// and it is backward; else the one after the next change (br-frankenpandas-6pqf3).
6145fn pandas_shift_offset(zone: &Zone, moved: i64, forward: bool) -> i32 {
6146    const DAY: i64 = 86_400 * NANOS_PER_SECOND;
6147    let here = zone.offset_seconds(moved);
6148    let first = zone.offset_seconds(i64::MIN + 1);
6149    let in_force = if forward {
6150        here >= 0 || first > 0
6151    } else {
6152        first < 0
6153    };
6154    if in_force {
6155        return here;
6156    }
6157    // The next change: the first day on whose offset differs (changes are
6158    // months apart), within three years.
6159    (1..=1_100_i64)
6160        .filter_map(|day| moved.checked_add(day * DAY))
6161        .map(|at| zone.offset_seconds(at))
6162        .find(|&offset| offset != here)
6163        .unwrap_or(here)
6164}
6165
6166/// [`tz_wall_to_utc_nanos_with`] in a zone already parsed.
6167fn wall_to_utc_in(
6168    zone: &Zone,
6169    wall_nanos: i64,
6170    ambiguous: AmbiguousTime,
6171    nonexistent: NonexistentTime,
6172) -> Result<i64, TimeZoneError> {
6173    use chrono::{LocalResult, TimeZone};
6174    let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6175    let local = match zone {
6176        Zone::Fixed(offset) => offset
6177            .from_local_datetime(&naive)
6178            .map(|at| at.fixed_offset()),
6179        Zone::Named(zone) => zone.from_local_datetime(&naive).map(|at| at.fixed_offset()),
6180    };
6181    let nanos_of = |at: chrono::DateTime<chrono::FixedOffset>| {
6182        at.timestamp_nanos_opt()
6183            .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))
6184    };
6185    match local {
6186        LocalResult::Single(at) => nanos_of(at),
6187        LocalResult::Ambiguous(earliest, latest) => match ambiguous {
6188            AmbiguousTime::Raise => Err(TimeZoneError::Ambiguous(wall_text(wall_nanos))),
6189            AmbiguousTime::Earliest => nanos_of(earliest),
6190            AmbiguousTime::Latest => nanos_of(latest),
6191            AmbiguousTime::NaT => Ok(i64::MIN),
6192        },
6193        LocalResult::None => match nonexistent {
6194            NonexistentTime::Raise => Err(TimeZoneError::NonExistent(wall_text(wall_nanos))),
6195            NonexistentTime::NaT => Ok(i64::MIN),
6196            NonexistentTime::Shift(delta) => {
6197                let shifted = wall_nanos
6198                    .checked_add(delta)
6199                    .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))?;
6200                if shifted == i64::MIN {
6201                    return Ok(shifted);
6202                }
6203                wall_to_utc_in(zone, shifted, ambiguous, NonexistentTime::Raise)
6204            }
6205            NonexistentTime::ShiftForward | NonexistentTime::ShiftBackward => {
6206                // pandas (pytz's tz_localize_to_utc) moves a skipped wall
6207                // time up to the next whole hour (shift_forward) or to a
6208                // nanosecond before its own hour (shift_backward), then
6209                // places that with the offset its table answers (see
6210                // [`pandas_shift_offset`]): the change's own instant for a
6211                // change on the hour, 03:00 (+11:00) where Lord Howe's
6212                // half-hour gap ends at 02:30 - this placed the gap's end
6213                // (br-frankenpandas-6pqf3).
6214                let forward = nonexistent == NonexistentTime::ShiftForward;
6215                let into_hour = wall_nanos.rem_euclid(NANOS_PER_HOUR);
6216                let moved = if forward {
6217                    wall_nanos.checked_add(NANOS_PER_HOUR - into_hour)
6218                } else {
6219                    wall_nanos.checked_sub(into_hour + 1)
6220                };
6221                moved
6222                    .and_then(|moved| {
6223                        let offset = pandas_shift_offset(zone, moved, forward);
6224                        moved.checked_sub(i64::from(offset) * NANOS_PER_SECOND)
6225                    })
6226                    .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))
6227            }
6228        },
6229    }
6230}
6231
6232/// `wall_nanos` formatted as Python's (glibc's) `strftime` does - what
6233/// pandas' `Timestamp.strftime` / `Series.dt.strftime` / `to_csv(date_format=)`
6234/// run per value: the C-locale directives (`%a %A %b %B %c %d %e %f %H %I
6235/// %j %m %M %p %S %U %w %W %x %X %y %Y %z %Z %%`), glibc's (`%C %D %F %g %G
6236/// %h %k %l %n %P %r %R %t %T %u %V`) and its `-` (no padding), `_` (space
6237/// padding), `0` and `^` (upper case) flags. An unknown directive is echoed
6238/// as written, as glibc does. `zone` is a tz-aware value's UTC offset (in
6239/// seconds) and abbreviation at that instant, which `%z` / `%Z` print (empty
6240/// for a naive value).
6241#[must_use]
6242pub fn strftime_python(wall_nanos: i64, format: &str, zone: Option<(i32, &str)>) -> String {
6243    const DAYS: [&str; 7] = [
6244        "Sunday",
6245        "Monday",
6246        "Tuesday",
6247        "Wednesday",
6248        "Thursday",
6249        "Friday",
6250        "Saturday",
6251    ];
6252    const MONTHS: [&str; 12] = [
6253        "January",
6254        "February",
6255        "March",
6256        "April",
6257        "May",
6258        "June",
6259        "July",
6260        "August",
6261        "September",
6262        "October",
6263        "November",
6264        "December",
6265    ];
6266    // Floor both boundaries so a pre-epoch instant keeps a consistent date
6267    // and time (1969-12-31 23:59:59.999999 for -1 ns).
6268    let total_secs = wall_nanos.div_euclid(1_000_000_000);
6269    let sub_nanos = wall_nanos.rem_euclid(1_000_000_000);
6270    let days = total_secs.div_euclid(86_400);
6271    let secs_of_day = total_secs.rem_euclid(86_400);
6272    let (year, month, day) = civil_from_days(days);
6273    let (hour, minute, second) = (
6274        secs_of_day / 3_600,
6275        (secs_of_day % 3_600) / 60,
6276        secs_of_day % 60,
6277    );
6278    let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
6279    let weekday = (days + 4).rem_euclid(7); // 0 = Sunday
6280    let yday = days - days_from_civil(year, 1, 1); // 0-based
6281    let iso_weekday = if weekday == 0 { 7 } else { weekday };
6282    let (iso_year, iso_week) = {
6283        let week = (yday + 1 - iso_weekday + 10).div_euclid(7);
6284        if week < 1 {
6285            (year - 1, iso_weeks_in_year(year - 1))
6286        } else if week > iso_weeks_in_year(year) {
6287            (year + 1, 1)
6288        } else {
6289            (year, week)
6290        }
6291    };
6292    let month_name = MONTHS[(month as usize).saturating_sub(1) % 12];
6293    let day_name = DAYS[weekday as usize];
6294
6295    let mut out = String::with_capacity(format.len().saturating_add(16));
6296    let mut chars = format.chars().peekable();
6297    while let Some(ch) = chars.next() {
6298        if ch != '%' {
6299            out.push(ch);
6300            continue;
6301        }
6302        let flag = chars.next_if(|c| matches!(c, '-' | '_' | '0' | '^'));
6303        let Some(conversion) = chars.next() else {
6304            out.push('%');
6305            if let Some(flag) = flag {
6306                out.push(flag);
6307            }
6308            break;
6309        };
6310        // A number `width` wide, padded with `pad` unless a flag says
6311        // otherwise.
6312        let number = |value: i64, width: usize, pad: char| -> String {
6313            match flag.unwrap_or(pad) {
6314                '-' => value.to_string(),
6315                '_' | ' ' => format!("{value:>width$}"),
6316                _ => format!("{value:0width$}"),
6317            }
6318        };
6319        let text = |value: &str| -> String {
6320            if flag == Some('^') {
6321                value.to_uppercase()
6322            } else {
6323                value.to_owned()
6324            }
6325        };
6326        let piece = match conversion {
6327            'a' => text(&day_name[..3]),
6328            'A' => text(day_name),
6329            'b' | 'h' => text(&month_name[..3]),
6330            'B' => text(month_name),
6331            'c' => text(&strftime_python(wall_nanos, "%a %b %e %H:%M:%S %Y", zone)),
6332            'C' => number(year.div_euclid(100), 2, '0'),
6333            'd' => number(i64::from(day), 2, '0'),
6334            'D' | 'x' => strftime_python(wall_nanos, "%m/%d/%y", zone),
6335            'e' => number(i64::from(day), 2, ' '),
6336            'f' => number(sub_nanos / 1_000, 6, '0'),
6337            'F' => strftime_python(wall_nanos, "%Y-%m-%d", zone),
6338            'g' => number(iso_year.rem_euclid(100), 2, '0'),
6339            'G' => number(iso_year, 1, '0'),
6340            'H' => number(hour, 2, '0'),
6341            'I' => number(hour12, 2, '0'),
6342            'j' => number(yday + 1, 3, '0'),
6343            'k' => number(hour, 2, ' '),
6344            'l' => number(hour12, 2, ' '),
6345            'm' => number(i64::from(month), 2, '0'),
6346            'M' => number(minute, 2, '0'),
6347            'n' => "\n".to_owned(),
6348            'p' => text(if hour < 12 { "AM" } else { "PM" }),
6349            'P' => (if hour < 12 { "am" } else { "pm" }).to_owned(),
6350            'r' => strftime_python(wall_nanos, "%I:%M:%S %p", zone),
6351            'R' => strftime_python(wall_nanos, "%H:%M", zone),
6352            'S' => number(second, 2, '0'),
6353            't' => "\t".to_owned(),
6354            'T' | 'X' => strftime_python(wall_nanos, "%H:%M:%S", zone),
6355            'u' => number(iso_weekday, 1, '0'),
6356            'U' => number((yday + 7 - weekday).div_euclid(7), 2, '0'),
6357            'V' => number(iso_week, 2, '0'),
6358            'w' => number(weekday, 1, '0'),
6359            'W' => number(
6360                (yday + 7 - (weekday + 6).rem_euclid(7)).div_euclid(7),
6361                2,
6362                '0',
6363            ),
6364            'y' => number(year.rem_euclid(100), 2, '0'),
6365            'Y' => number(year, 1, '0'),
6366            'z' => zone.map_or_else(String::new, |(offset, _)| {
6367                let sign = if offset < 0 { '-' } else { '+' };
6368                let offset = offset.unsigned_abs();
6369                let (h, m, s) = (offset / 3_600, (offset % 3_600) / 60, offset % 60);
6370                if s == 0 {
6371                    format!("{sign}{h:02}{m:02}")
6372                } else {
6373                    format!("{sign}{h:02}{m:02}{s:02}")
6374                }
6375            }),
6376            'Z' => zone.map_or_else(String::new, |(_, name)| text(name)),
6377            '%' => "%".to_owned(),
6378            other => {
6379                // glibc echoes a conversion it does not know.
6380                out.push('%');
6381                if let Some(flag) = flag {
6382                    out.push(flag);
6383                }
6384                out.push(other);
6385                continue;
6386            }
6387        };
6388        out.push_str(&piece);
6389    }
6390    out
6391}
6392
6393/// The instant `nanos` formatted by [`strftime_python`]: a naive value as
6394/// it is; in `tz` (a tz-aware value, `nanos` its UTC instant) on the zone's
6395/// wall clock with the offset and abbreviation of that instant.
6396#[must_use]
6397pub fn strftime_in_zone(nanos: i64, format: &str, tz: Option<&str>) -> String {
6398    let aware = tz.and_then(|zone| {
6399        let offset = tz_offset_seconds(zone, nanos).ok()?;
6400        let name = tz_abbreviation(zone, nanos).ok()?;
6401        Some((offset, name))
6402    });
6403    match aware {
6404        Some((offset, name)) => strftime_python(
6405            nanos.saturating_add(i64::from(offset) * 1_000_000_000),
6406            format,
6407            Some((offset, &name)),
6408        ),
6409        None => strftime_python(nanos, format, None),
6410    }
6411}
6412
6413/// `str(Timestamp)` of the naive instant `nanos`: its wall clock
6414/// 'YYYY-MM-DD HH:MM:SS' and its own fraction when it has one (six digits,
6415/// nine for nanoseconds) - how pandas prints a naive Timestamp an object
6416/// column holds (`astype(str)` spelled it 'Timestamp[<nanos>]';
6417/// br-frankenpandas-srzqw).
6418#[must_use]
6419pub fn timestamp_text(nanos: i64) -> String {
6420    let mut text = strftime_python(nanos, "%Y-%m-%d %H:%M:%S", None);
6421    let fraction = nanos.rem_euclid(1_000_000_000);
6422    if fraction % 1_000 != 0 {
6423        text.push_str(&format!(".{fraction:09}"));
6424    } else if fraction != 0 {
6425        text.push_str(&format!(".{:06}", fraction / 1_000));
6426    }
6427    text
6428}
6429
6430/// `str(Timestamp)` of the instant `nanos` in `tz`, as pandas prints a
6431/// tz-aware value (repr cells, `astype(str)`): its [`timestamp_text`] wall
6432/// clock and the zone's `+HH:MM` offset then.
6433#[must_use]
6434pub fn timestamp_text_in_zone(nanos: i64, tz: &str) -> String {
6435    let offset = tz_offset_seconds(tz, nanos).unwrap_or(0);
6436    let mut text = timestamp_text(nanos.saturating_add(i64::from(offset) * 1_000_000_000));
6437    let sign = if offset < 0 { '-' } else { '+' };
6438    let minutes = offset.unsigned_abs() / 60;
6439    text.push_str(&format!("{sign}{:02}:{:02}", minutes / 60, minutes % 60));
6440    text
6441}
6442
6443/// `nanos` (datetime64[ns]) plus `months` calendar months, the day clipped
6444/// to the target month's last day and the time of day kept - dateutil's
6445/// relativedelta, which pandas' `DateOffset(years=, months=)` applies (Jan
6446/// 31 + 1 month is Feb 29 in 2024). Civil-date arithmetic on the day count:
6447/// a chrono date made and read back a row was most of
6448/// s + DateOffset(months=1) (300k 12.9 ms, pandas 7.9; br-frankenpandas-4g57c).
6449/// None when the result leaves datetime64[ns].
6450#[must_use]
6451pub fn add_calendar_months_nanos(nanos: i64, months: i64) -> Option<i64> {
6452    const DAY: i64 = 86_400_000_000_000;
6453    let moved = add_calendar_months_days(nanos.div_euclid(DAY), months)?;
6454    i64::try_from(i128::from(moved) * i128::from(DAY) + i128::from(nanos.rem_euclid(DAY))).ok()
6455}
6456
6457/// The day (days since 1970-01-01) `months` calendar months after `day`,
6458/// the day of the month clipped to the target month's last day - the date
6459/// part of [`add_calendar_months_nanos`], which a column moving instants
6460/// that share a day computes once. None a million years out.
6461#[must_use]
6462pub fn add_calendar_months_days(day: i64, months: i64) -> Option<i64> {
6463    // No date is a million years out (and the day counts below would
6464    // overflow there).
6465    if day.unsigned_abs() > 365_000_000 {
6466        return None;
6467    }
6468    let (year, month, day) = civil_from_days(day);
6469    let total = year
6470        .checked_mul(12)?
6471        .checked_add(i64::from(month) - 1)?
6472        .checked_add(months)?;
6473    let year = total.div_euclid(12);
6474    if year.unsigned_abs() > 1_000_000 {
6475        return None;
6476    }
6477    let month = u32::try_from(total.rem_euclid(12)).ok()? + 1;
6478    let day = day.min(days_in_month(year, month)?);
6479    Some(days_from_civil(year, month, day))
6480}
6481
6482/// Days since 1970-01-01 of the proleptic-Gregorian date `(year, month,
6483/// day)` (Howard Hinnant's days-from-civil; the inverse of
6484/// `civil_from_days`).
6485fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
6486    let (month, day) = (i64::from(month), i64::from(day));
6487    let year = if month <= 2 { year - 1 } else { year };
6488    let era = if year >= 0 { year } else { year - 399 } / 400;
6489    let yoe = year - era * 400;
6490    let doy = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
6491    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
6492    era * 146_097 + doe - 719_468
6493}
6494
6495// ── Timestamp types (br-frankenpandas-9p0u — 4r56 Phase 2) ─────────────
6496//
6497// Nanosecond-precision i64 since Unix epoch + optional IANA tz name. The
6498// zone's DST-aware conversions are the time-zone functions above
6499// (`tz_offset_seconds`, `tz_wall_to_utc_nanos`); arithmetic here stays on
6500// the absolute nanos axis.
6501
6502/// Number of days in a given month (1-12) of a given year.
6503fn days_in_month(year: i64, month: u32) -> Option<u32> {
6504    if !(1..=12).contains(&month) {
6505        return None;
6506    }
6507    let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
6508    let days: [u32; 12] = [
6509        31,
6510        if is_leap { 29 } else { 28 },
6511        31,
6512        30,
6513        31,
6514        30,
6515        31,
6516        31,
6517        30,
6518        31,
6519        30,
6520        31,
6521    ];
6522    Some(days[(month - 1) as usize])
6523}
6524
6525/// Number of ISO-8601 weeks in a year (52 or 53).
6526///
6527/// A year has 53 ISO weeks iff its first day falls on a Thursday, or it is a
6528/// leap year whose first day is a Wednesday — captured by the dominical
6529/// closed form `p(year) == 4 || p(year - 1) == 3`, where
6530/// `p(y) = (y + ⌊y/4⌋ − ⌊y/100⌋ + ⌊y/400⌋) mod 7` is the weekday of Dec 31.
6531fn iso_weeks_in_year(year: i64) -> i64 {
6532    fn p(y: i64) -> i64 {
6533        (y + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400)).rem_euclid(7)
6534    }
6535    if p(year) == 4 || p(year - 1) == 3 {
6536        53
6537    } else {
6538        52
6539    }
6540}
6541
6542/// A nanosecond-precision point in time, Unix-epoch anchored.
6543///
6544/// Phase 2 scope: construction, arithmetic, equality, ordering, serde.
6545/// TZ semantics (IANA tz lookup, DST-aware shift) are deferred to Phase
6546/// 3 — see br-frankenpandas-4r56.
6547#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
6548pub struct Timestamp {
6549    /// Nanoseconds since Unix epoch. `i64::MIN` is NaT.
6550    pub nanos: i64,
6551    /// Optional IANA time-zone name (e.g. `"US/Eastern"`). `None` means
6552    /// naive / UTC-anchored. Phase 2 treats this as opaque metadata;
6553    /// Phase 3 wires chrono_tz interpretation.
6554    #[serde(default, skip_serializing_if = "Option::is_none")]
6555    pub tz: Option<String>,
6556}
6557
6558/// How `astype(str)` renders a `timedelta64[ns]` COLUMN.
6559///
6560/// ⚠️ THE TIMEDELTA LADDER IS NOT THE DATETIME ONE, and copying the sibling
6561/// across is the mistake this type exists to prevent. It has exactly TWO rungs,
6562/// and — unlike [`DatetimeStringResolution`] — THE SUB-SECOND WIDTH IS PER
6563/// VALUE, not per column. MEASURED, live pandas 2.2.3:
6564///
6565/// ```text
6566/// [1 days, 2 days]              -> ['1 days', '2 days']
6567/// [1 days, 5 ms]                -> ['1 days 00:00:00', '0 days 00:00:00.005000']
6568/// [1 days 02:03:04.005, 1 ns]   -> ['1 days 02:03:04.005000',
6569///                                   '0 days 00:00:00.000000001']
6570/// ```
6571///
6572/// That last row is the whole distinction: a millisecond value keeps its SIX
6573/// digits while its neighbour prints NINE. On the datetime side the same pair
6574/// would have been widened to a common nine. So the only column-wide question
6575/// here is whether the time-of-day part can be dropped entirely, which is what
6576/// [`Timedelta::string_resolution`] answers; [`Timedelta::format`] already gets
6577/// the per-value part right and is reused unchanged.
6578#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6579pub enum TimedeltaStringResolution {
6580    /// `1 days` / `-2 days` / `0 days` — every value is a whole day.
6581    Days,
6582    /// `1 days 02:03:04.005000` — the full rendering, sub-second width per value.
6583    Full,
6584}
6585
6586/// How wide `astype(str)` renders a `datetime64[ns]` value.
6587///
6588/// ⚠️ THIS IS A PROPERTY OF THE COLUMN, NOT OF THE VALUE, which is the whole
6589/// reason it is a separate type rather than a branch inside a per-scalar
6590/// formatter. MEASURED, live pandas 2.2.3 — the SAME midnight timestamp renders
6591/// three different ways depending only on what it shares a column with:
6592///
6593/// ```text
6594/// Series([midnight, midnight]).astype(str)   -> '2024-03-15'
6595/// Series([midnight, one_nanosecond]).astype(str)
6596///                                            -> '2024-03-15 00:00:00.000000000'
6597/// str(Timestamp(midnight))                   -> '2024-03-15 00:00:00'
6598/// ```
6599///
6600/// pandas picks the coarsest rung that is lossless for EVERY element and
6601/// imposes it on all of them. The `Ord` derive is the fold: scan the column
6602/// with `max` over [`Timestamp::string_resolution`], then format every value at
6603/// the winner. Variants are declared coarsest-first so that `max` means
6604/// "finest needed".
6605#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6606pub enum DatetimeStringResolution {
6607    /// `2024-03-15` — every value in the column is midnight.
6608    Date,
6609    /// `2024-03-15 10:30:45` — every value is a whole second.
6610    Second,
6611    /// `2024-03-15 10:30:45.123`
6612    Milli,
6613    /// `2024-03-15 10:30:45.123456`
6614    Micro,
6615    /// `2024-03-15 10:30:45.123456789`
6616    Nano,
6617}
6618
6619impl Timestamp {
6620    /// NaT sentinel, parallel to `Timedelta::NAT`.
6621    pub const NAT: i64 = i64::MIN;
6622
6623    /// Construct a UTC-anchored (tz=None) Timestamp from nanoseconds
6624    /// since Unix epoch.
6625    #[must_use]
6626    pub const fn from_nanos(nanos: i64) -> Self {
6627        Self { nanos, tz: None }
6628    }
6629
6630    /// Construct a Timestamp tagged with an IANA tz name.
6631    ///
6632    /// Phase 2 doesn't interpret the tz — it only carries the name
6633    /// through arithmetic + serde. Phase 3 wires chrono_tz conversion.
6634    #[must_use]
6635    pub fn from_nanos_tz(nanos: i64, tz_name: impl Into<String>) -> Self {
6636        Self {
6637            nanos,
6638            tz: Some(tz_name.into()),
6639        }
6640    }
6641
6642    /// Returns the current UTC timestamp.
6643    ///
6644    /// ⚠️ THIS MATCHES `pd.Timestamp.utcnow()`, NOT `pd.Timestamp.now()`, and the
6645    /// old doc claimed both. They are different functions: pandas' `now()` returns
6646    /// LOCAL time with no timezone attached, while `utcnow()` returns UTC.
6647    /// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-19) on a UTC-4 host:
6648    /// ```text
6649    ///   pd.Timestamp.now()    2026-08-19 07:17:07.266940        tz None
6650    ///   pd.Timestamp.utcnow() 2026-08-19 11:17:07.267100+00:00  tz UTC
6651    ///   difference: 14400 s
6652    /// ```
6653    /// A caller who trusted the old claim and ran on a non-UTC host would be off by
6654    /// their whole UTC offset — four hours here — with no error and no NaT to notice.
6655    /// This crate has no local-timezone concept, so the UTC answer is the only one it
6656    /// can give; only the false half of the claim is removed.
6657    #[must_use]
6658    pub fn now() -> Self {
6659        use std::time::{SystemTime, UNIX_EPOCH};
6660        let duration = SystemTime::now()
6661            .duration_since(UNIX_EPOCH)
6662            .unwrap_or_default();
6663        let nanos = duration.as_nanos() as i64;
6664        Self { nanos, tz: None }
6665    }
6666
6667    /// Alias for `now()`. Matches `pd.Timestamp.utcnow()`.
6668    #[must_use]
6669    pub fn utcnow() -> Self {
6670        Self::now()
6671    }
6672
6673    /// Returns today's date at midnight UTC.
6674    ///
6675    /// Matches `pd.Timestamp.today()`.
6676    #[must_use]
6677    pub fn today() -> Self {
6678        let now = Self::now();
6679        now.normalize()
6680    }
6681
6682    /// The NaT sentinel value for a Timestamp.
6683    #[must_use]
6684    pub const fn nat() -> Self {
6685        Self {
6686            nanos: Self::NAT,
6687            tz: None,
6688        }
6689    }
6690
6691    /// True iff this Timestamp is NaT.
6692    #[must_use]
6693    pub const fn is_nat(&self) -> bool {
6694        self.nanos == Self::NAT
6695    }
6696
6697    /// Nanoseconds since Unix epoch, matching `pd.Timestamp.value`.
6698    #[must_use]
6699    pub const fn value(&self) -> i64 {
6700        self.nanos
6701    }
6702
6703    /// Stored resolution unit, matching `pd.Timestamp.unit`.
6704    ///
6705    /// FrankenPandas `Timestamp` stores nanoseconds internally, so non-NaT
6706    /// values report `ns`. `NaT` has no unit.
6707    #[must_use]
6708    pub const fn unit(&self) -> Option<&'static str> {
6709        if self.is_nat() { None } else { Some("ns") }
6710    }
6711
6712    /// Return the resolution of the timestamp (always "ns" for nanoseconds).
6713    ///
6714    /// Matches `pd.Timestamp.resolution`. Returns None for NaT.
6715    #[must_use]
6716    pub const fn resolution(&self) -> Option<&'static str> {
6717        if self.is_nat() { None } else { Some("ns") }
6718    }
6719
6720    /// Numpy datetime64 scalar payload, matching `pd.Timestamp.asm8`.
6721    #[must_use]
6722    pub const fn asm8(&self) -> i64 {
6723        self.value()
6724    }
6725
6726    /// Convert to a datetime64 payload, matching `pd.Timestamp.to_datetime64()`.
6727    #[must_use]
6728    pub const fn to_datetime64(&self) -> i64 {
6729        self.value()
6730    }
6731
6732    /// Convert to a numpy scalar payload, matching `pd.Timestamp.to_numpy()`.
6733    #[must_use]
6734    pub const fn to_numpy(&self) -> i64 {
6735        self.value()
6736    }
6737
6738    /// POSIX timestamp in seconds, matching `pd.Timestamp.timestamp()`.
6739    ///
6740    /// Pandas exposes this through Python's datetime surface, so sub-microsecond
6741    /// nanoseconds are rounded to six decimal places. `NaT` raises in pandas;
6742    /// fp-types surfaces the same condition as a missing-value error.
6743    pub fn timestamp(&self) -> Result<f64, TypeError> {
6744        if self.is_nat() {
6745            return Err(TypeError::ValueIsMissing {
6746                kind: NullKind::NaT,
6747            });
6748        }
6749        let seconds = self.nanos as f64 / 1_000_000_000.0;
6750        let rounded = format!("{seconds:.6}").parse().unwrap_or(seconds);
6751        Ok(rounded)
6752    }
6753
6754    /// Add a Timedelta. NaT in either operand → NaT; overflow → NaT.
6755    /// TZ is preserved from `self`.
6756    ///
6757    /// Overflow is NaT in both directions (br-frankenpandas-lgyy8) — see the
6758    /// overflow note on [`Timedelta::add`]. A saturated `i64::MAX` would be a
6759    /// finite, plausible ~year-2262 instant returned as if it were real data;
6760    /// `pd.Timestamp.max + pd.Timedelta('1ns')` raises `OutOfBoundsDatetime`.
6761    #[must_use]
6762    pub fn add_timedelta(&self, td_nanos: i64) -> Self {
6763        self.try_add_timedelta(td_nanos)
6764            .unwrap_or_else(|_| Self::nat())
6765    }
6766
6767    /// Shift by a Timedelta, reporting overflow.
6768    ///
6769    /// br-frankenpandas-fyr1z-policy-carrier-f29nz. A NaT operand is
6770    /// propagation, not overflow, so it yields `Ok(nat())`. On overflow the
6771    /// caller gets the error INSTEAD of the tz-dropped NaT; the infallible
6772    /// `add_timedelta` above still produces that NaT, unchanged.
6773    ///
6774    /// # Errors
6775    /// [`PandasTemporalError::OutOfBoundsDatetime`], matching
6776    /// `pd.Timestamp.max + pd.Timedelta('1ns')`.
6777    pub fn try_add_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6778        if self.is_nat() || td_nanos == Timedelta::NAT {
6779            return Ok(Self::nat());
6780        }
6781        match self.nanos.checked_add(td_nanos) {
6782            Some(nanos) => Ok(Self {
6783                nanos,
6784                tz: self.tz.clone(),
6785            }),
6786            // Overflow drops the tz with the value: an out-of-range instant has
6787            // no zone, and `Self::nat()` is the one canonical NaT (matching the
6788            // NaT-operand arms above, which also return an untagged NaT).
6789            None => Err(TemporalFailure::new(
6790                "Timestamp::add_timedelta",
6791                PandasTemporalError::OutOfBoundsDatetime,
6792            )
6793            .with_operands(self.nanos, td_nanos)),
6794        }
6795    }
6796
6797    /// Subtract a Timedelta. NaT propagation; overflow → NaT. TZ preserved.
6798    #[must_use]
6799    pub fn sub_timedelta(&self, td_nanos: i64) -> Self {
6800        self.try_sub_timedelta(td_nanos)
6801            .unwrap_or_else(|_| Self::nat())
6802    }
6803
6804    /// Shift back by a Timedelta, reporting overflow. See
6805    /// [`Self::try_add_timedelta`].
6806    ///
6807    /// # Errors
6808    /// [`PandasTemporalError::OutOfBoundsDatetime`].
6809    pub fn try_sub_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6810        if self.is_nat() || td_nanos == Timedelta::NAT {
6811            return Ok(Self::nat());
6812        }
6813        match self.nanos.checked_sub(td_nanos) {
6814            Some(nanos) => Ok(Self {
6815                nanos,
6816                tz: self.tz.clone(),
6817            }),
6818            None => Err(TemporalFailure::new(
6819                "Timestamp::sub_timedelta",
6820                PandasTemporalError::OutOfBoundsDatetime,
6821            )
6822            .with_operands(self.nanos, td_nanos)),
6823        }
6824    }
6825
6826    /// Subtract another Timestamp. Returns a Timedelta (i64 nanos).
6827    /// NaT in either → `Timedelta::NAT`; overflow → `Timedelta::NAT`
6828    /// (`pd.Timestamp.min - pd.Timestamp.max` raises `OutOfBoundsDatetime`).
6829    #[must_use]
6830    pub fn sub_timestamp(&self, other: &Self) -> i64 {
6831        self.try_sub_timestamp(other).unwrap_or(Timedelta::NAT)
6832    }
6833
6834    /// Elapsed nanoseconds between two Timestamps, reporting overflow.
6835    ///
6836    /// # Errors
6837    /// [`PandasTemporalError::OutOfBoundsDatetime`], matching
6838    /// `pd.Timestamp.min - pd.Timestamp.max`.
6839    pub fn try_sub_timestamp(&self, other: &Self) -> Result<i64, TemporalFailure> {
6840        if self.is_nat() || other.is_nat() {
6841            return Ok(Timedelta::NAT);
6842        }
6843        self.nanos.checked_sub(other.nanos).ok_or(
6844            TemporalFailure::new(
6845                "Timestamp::sub_timestamp",
6846                PandasTemporalError::OutOfBoundsDatetime,
6847            )
6848            .with_operands(self.nanos, other.nanos),
6849        )
6850    }
6851
6852    /// NaT-aware semantic equality: two NaT Timestamps are equal to each
6853    /// other (matches pandas `pd.NaT == pd.NaT` under `equals()`, though
6854    /// pandas's `==` operator returns False for NaT==NaT — we follow the
6855    /// `semantic_eq` convention used elsewhere in fp-types).
6856    #[must_use]
6857    pub fn semantic_eq(&self, other: &Self) -> bool {
6858        if self.is_nat() && other.is_nat() {
6859            return true;
6860        }
6861        if self.is_nat() || other.is_nat() {
6862            return false;
6863        }
6864        self.nanos == other.nanos && self.tz == other.tz
6865    }
6866
6867    // ── Rounding to a Timedelta unit (br-frankenpandas-5h6n) ────────────
6868    //
6869    // Pure i64 arithmetic on the nanos axis. tz is preserved. Phase 3
6870    // chrono_tz integration will add a tz-aware variant that handles DST
6871    // boundaries correctly; these methods operate on the absolute time
6872    // axis, matching pandas's tz-naive `.floor` / `.ceil` / `.round`
6873    // semantics for unit values smaller than a day.
6874
6875    /// Round down to the nearest multiple of `unit_nanos`.
6876    ///
6877    /// Matches `pd.Timestamp(...).floor(unit)`. NaT in `self` or a
6878    /// non-positive `unit_nanos` returns NaT.
6879    #[must_use]
6880    pub fn floor_to(&self, unit_nanos: i64) -> Self {
6881        if self.is_nat() || unit_nanos <= 0 {
6882            return Self::nat();
6883        }
6884        let Some(nanos) = self.nanos.div_euclid(unit_nanos).checked_mul(unit_nanos) else {
6885            return Self::nat();
6886        };
6887        Self {
6888            nanos,
6889            tz: self.tz.clone(),
6890        }
6891    }
6892
6893    /// Round up to the nearest multiple of `unit_nanos`.
6894    ///
6895    /// Matches `pd.Timestamp(...).ceil(unit)`. NaT or non-positive
6896    /// `unit_nanos` returns NaT. Already-multiple inputs return self.
6897    #[must_use]
6898    pub fn ceil_to(&self, unit_nanos: i64) -> Self {
6899        if self.is_nat() || unit_nanos <= 0 {
6900            return Self::nat();
6901        }
6902        let rem = self.nanos.rem_euclid(unit_nanos);
6903        let nanos = if rem == 0 {
6904            self.nanos
6905        } else {
6906            // Checked, matching the sibling `floor_to` directly above
6907            // (br-frankenpandas-kyd16). A clamped i64::MAX would be a finite,
6908            // plausible ~year-2262 instant; `pd.Timestamp.max.ceil('D')`
6909            // raises OutOfBoundsDatetime "Cannot round ... without overflow".
6910            let Some(nanos) = self.nanos.checked_add(unit_nanos - rem) else {
6911                return Self::nat();
6912            };
6913            nanos
6914        };
6915        Self {
6916            nanos,
6917            tz: self.tz.clone(),
6918        }
6919    }
6920
6921    /// Round to the nearest multiple of `unit_nanos`, banker's rounding
6922    /// (half-to-even) on ties.
6923    ///
6924    /// Matches `pd.Timestamp(...).round(unit)`. NaT or non-positive
6925    /// `unit_nanos` returns NaT.
6926    #[must_use]
6927    pub fn round_to(&self, unit_nanos: i64) -> Self {
6928        if self.is_nat() || unit_nanos <= 0 {
6929            return Self::nat();
6930        }
6931        let floor = self.nanos.div_euclid(unit_nanos);
6932        let rem = self.nanos.rem_euclid(unit_nanos);
6933        let half = unit_nanos / 2;
6934        let chosen_floor = if rem < half {
6935            floor
6936        } else if rem > half {
6937            floor + 1
6938        } else if unit_nanos % 2 != 0 {
6939            // Odd unit can't have a true half; treat as round-up.
6940            floor + 1
6941        } else {
6942            // Tie: pick the even multiple.
6943            if floor % 2 == 0 { floor } else { floor + 1 }
6944        };
6945        // Checked, matching the sibling `floor_to` (br-frankenpandas-kyd16):
6946        // `pd.Timestamp.max.round('D')` raises OutOfBoundsDatetime rather than
6947        // returning the clamped i64::MAX instant.
6948        let Some(nanos) = chosen_floor.checked_mul(unit_nanos) else {
6949            return Self::nat();
6950        };
6951        Self {
6952            nanos,
6953            tz: self.tz.clone(),
6954        }
6955    }
6956
6957    // ── String-unit rounding (br-frankenpandas-lbsx) ────────────────────
6958    //
6959    // Pandas convenience: `.floor('H')` / `.ceil('1D')` / `.round('15min')`.
6960    // These read the frequency with `fixed_freq_nanos`, then delegate to
6961    // the nanos-based `floor_to`/`ceil_to`/`round_to`. Unknown unit strings
6962    // return NaT, matching the rest of fp-types' "missing-input → missing-
6963    // output" convention.
6964
6965    /// A fixed frequency's length: a bare unit (`Timedelta::unit_to_nanos`)
6966    /// or a multiple of one ('15min', '1D', '30s' - they were unknown, so
6967    /// `round('15min')` was NaT); None for anything else.
6968    fn fixed_freq_nanos(freq: &str) -> Option<i64> {
6969        Timedelta::unit_to_nanos(freq).or_else(|| Timedelta::parse(freq).ok())
6970    }
6971
6972    /// Round down to the nearest multiple of the named unit.
6973    ///
6974    /// Matches `pd.Timestamp(...).floor(unit)`. Unknown unit → NaT.
6975    #[must_use]
6976    pub fn floor_to_unit(&self, unit: &str) -> Self {
6977        match Self::fixed_freq_nanos(unit) {
6978            Some(unit_nanos) => self.floor_to(unit_nanos),
6979            None => Self::nat(),
6980        }
6981    }
6982
6983    /// Round up to the nearest multiple of the named unit.
6984    ///
6985    /// Matches `pd.Timestamp(...).ceil(unit)`. Unknown unit → NaT.
6986    #[must_use]
6987    pub fn ceil_to_unit(&self, unit: &str) -> Self {
6988        match Self::fixed_freq_nanos(unit) {
6989            Some(unit_nanos) => self.ceil_to(unit_nanos),
6990            None => Self::nat(),
6991        }
6992    }
6993
6994    /// Round to the nearest multiple of the named unit, banker's rounding.
6995    ///
6996    /// Matches `pd.Timestamp(...).round(unit)`. Unknown unit → NaT.
6997    #[must_use]
6998    pub fn round_to_unit(&self, unit: &str) -> Self {
6999        match Self::fixed_freq_nanos(unit) {
7000            Some(unit_nanos) => self.round_to(unit_nanos),
7001            None => Self::nat(),
7002        }
7003    }
7004
7005    /// Pandas-named alias for [`floor_to_unit`](Self::floor_to_unit).
7006    #[must_use]
7007    pub fn floor(&self, freq: &str) -> Self {
7008        self.floor_to_unit(freq)
7009    }
7010
7011    /// Pandas-named alias for [`ceil_to_unit`](Self::ceil_to_unit).
7012    #[must_use]
7013    pub fn ceil(&self, freq: &str) -> Self {
7014        self.ceil_to_unit(freq)
7015    }
7016
7017    /// Pandas-named alias for [`round_to_unit`](Self::round_to_unit).
7018    #[must_use]
7019    pub fn round(&self, freq: &str) -> Self {
7020        self.round_to_unit(freq)
7021    }
7022
7023    /// Return the local wall-clock nanoseconds for this timestamp.
7024    ///
7025    /// For tz-naive or NaT timestamps, returns `self.nanos`. For tz-aware
7026    /// timestamps, adds the timezone's UTC offset at `self.nanos` (falling
7027    /// back to `self.nanos` on overflow or if `self.tz` is not a recognized
7028    /// timezone).
7029    #[must_use]
7030    pub fn wall_nanos(&self) -> i64 {
7031        if self.is_nat() {
7032            return Self::NAT;
7033        }
7034        let Some(tz) = self.tz.as_deref() else {
7035            return self.nanos;
7036        };
7037        tz_offset_seconds(tz, self.nanos)
7038            .ok()
7039            .and_then(|offset_secs| {
7040                self.nanos
7041                    .checked_add(i64::from(offset_secs) * Timedelta::NANOS_PER_SEC)
7042            })
7043            .unwrap_or(self.nanos)
7044    }
7045
7046    /// Extract the year component from the timestamp.
7047    ///
7048    /// Matches `pd.Timestamp.year`. Returns None for NaT.
7049    #[must_use]
7050    pub fn year(&self) -> Option<i64> {
7051        if self.is_nat() {
7052            return None;
7053        }
7054        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
7055        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
7056        // for the post-1970 positive case.
7057        let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
7058        let days = days_since_epoch + 719_468;
7059        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7060        let doe = days - era * 146_097;
7061        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7062        let y = yoe + era * 400;
7063        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7064        let mp = (5 * doy + 2) / 153;
7065        let m = if mp < 10 { mp + 3 } else { mp - 9 };
7066        Some(if m <= 2 { y + 1 } else { y })
7067    }
7068
7069    /// Extract the month component (1-12) from the timestamp.
7070    ///
7071    /// Matches `pd.Timestamp.month`. Returns None for NaT.
7072    #[must_use]
7073    pub fn month(&self) -> Option<i64> {
7074        if self.is_nat() {
7075            return None;
7076        }
7077        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
7078        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
7079        // for the post-1970 positive case.
7080        let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
7081        let days = days_since_epoch + 719_468;
7082        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7083        let doe = days - era * 146_097;
7084        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7085        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7086        let mp = (5 * doy + 2) / 153;
7087        Some(if mp < 10 { mp + 3 } else { mp - 9 })
7088    }
7089
7090    /// Extract the day component (1-31) from the timestamp.
7091    ///
7092    /// Matches `pd.Timestamp.day`. Returns None for NaT.
7093    #[must_use]
7094    pub fn day(&self) -> Option<i64> {
7095        if self.is_nat() {
7096            return None;
7097        }
7098        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
7099        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
7100        // for the post-1970 positive case.
7101        let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
7102        let days = days_since_epoch + 719_468;
7103        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7104        let doe = days - era * 146_097;
7105        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7106        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7107        let mp = (5 * doy + 2) / 153;
7108        Some(doy - (153 * mp + 2) / 5 + 1)
7109    }
7110
7111    /// Extract the hour component (0-23) from the timestamp.
7112    ///
7113    /// Matches `pd.Timestamp.hour`. Returns None for NaT.
7114    #[must_use]
7115    pub fn hour(&self) -> Option<i64> {
7116        if self.is_nat() {
7117            return None;
7118        }
7119        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
7120        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
7121        // rem_euclid == `%` for the post-1970 positive case.
7122        let secs_of_day =
7123            self.wall_nanos().rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7124        Some(secs_of_day / 3600)
7125    }
7126
7127    /// Extract the minute component (0-59) from the timestamp.
7128    ///
7129    /// Matches `pd.Timestamp.minute`. Returns None for NaT.
7130    #[must_use]
7131    pub fn minute(&self) -> Option<i64> {
7132        if self.is_nat() {
7133            return None;
7134        }
7135        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
7136        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
7137        // rem_euclid == `%` for the post-1970 positive case.
7138        let secs_of_day =
7139            self.wall_nanos().rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7140        Some((secs_of_day % 3600) / 60)
7141    }
7142
7143    /// Extract the second component (0-59) from the timestamp.
7144    ///
7145    /// Matches `pd.Timestamp.second`. Returns None for NaT.
7146    #[must_use]
7147    pub fn second(&self) -> Option<i64> {
7148        if self.is_nat() {
7149            return None;
7150        }
7151        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
7152        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
7153        // rem_euclid == `%` for the post-1970 positive case.
7154        let secs_of_day =
7155            self.wall_nanos().rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7156        Some(secs_of_day % 60)
7157    }
7158
7159    /// Extract the microsecond component (0-999999) from the timestamp.
7160    ///
7161    /// Matches `pd.Timestamp.microsecond`. Returns None for NaT.
7162    #[must_use]
7163    pub fn microsecond(&self) -> Option<i64> {
7164        if self.is_nat() {
7165            return None;
7166        }
7167        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
7168        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
7169        let sub_nanos = self.wall_nanos().rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7170        Some((sub_nanos / 1000) as i64)
7171    }
7172
7173    /// Extract the nanosecond component (0-999) from the timestamp.
7174    ///
7175    /// Matches `pd.Timestamp.nanosecond`. Returns None for NaT.
7176    #[must_use]
7177    pub fn nanosecond(&self) -> Option<i64> {
7178        if self.is_nat() {
7179            return None;
7180        }
7181        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
7182        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
7183        let sub_nanos = self.wall_nanos().rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7184        Some((sub_nanos % 1000) as i64)
7185    }
7186
7187    /// Return the day of the week (Monday=0, Sunday=6).
7188    ///
7189    /// Matches `pd.Timestamp.dayofweek`. Returns None for NaT.
7190    #[must_use]
7191    pub fn dayofweek(&self) -> Option<i64> {
7192        if self.is_nat() {
7193            return None;
7194        }
7195        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
7196        let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
7197        let dow = ((days_since_epoch + 3) % 7 + 7) % 7;
7198        Some(dow)
7199    }
7200
7201    /// Alias for dayofweek(). Matches `pd.Timestamp.weekday`.
7202    #[must_use]
7203    pub fn weekday(&self) -> Option<i64> {
7204        self.dayofweek()
7205    }
7206
7207    /// Alias for dayofweek(). Matches `pd.Timestamp.day_of_week`.
7208    #[must_use]
7209    pub fn day_of_week(&self) -> Option<i64> {
7210        self.dayofweek()
7211    }
7212
7213    /// Return the day of the year (1-366).
7214    ///
7215    /// Matches `pd.Timestamp.dayofyear`. Returns None for NaT.
7216    #[must_use]
7217    pub fn dayofyear(&self) -> Option<i64> {
7218        if self.is_nat() {
7219            return None;
7220        }
7221        let m = self.month()?;
7222        let d = self.day()?;
7223        let y = self.year()?;
7224        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7225        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
7226        let base = days_before[(m - 1) as usize] + d;
7227        if is_leap && m > 2 {
7228            Some(base + 1)
7229        } else {
7230            Some(base)
7231        }
7232    }
7233
7234    /// Alias for dayofyear(). Matches `pd.Timestamp.day_of_year`.
7235    #[must_use]
7236    pub fn day_of_year(&self) -> Option<i64> {
7237        self.dayofyear()
7238    }
7239
7240    /// Return the proleptic Gregorian ordinal (number of days since Jan 1, year 1).
7241    ///
7242    /// Matches `pd.Timestamp.toordinal()`. Returns None for NaT.
7243    #[must_use]
7244    pub fn toordinal(&self) -> Option<i64> {
7245        if self.is_nat() {
7246            return None;
7247        }
7248        let y = self.year()?;
7249        let m = self.month()?;
7250        let d = self.day()?;
7251        // Algorithm: count days from year 1 to the start of the given year,
7252        // add days in the months before the given month, add the day of month.
7253        // Account for leap years.
7254        let y_minus_1 = y - 1;
7255        let mut ordinal = y_minus_1 * 365 + y_minus_1 / 4 - y_minus_1 / 100 + y_minus_1 / 400;
7256        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7257        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
7258        ordinal += days_before[(m - 1) as usize];
7259        if is_leap && m > 2 {
7260            ordinal += 1;
7261        }
7262        ordinal += d;
7263        Some(ordinal)
7264    }
7265
7266    /// Construct a Timestamp from a proleptic Gregorian ordinal.
7267    ///
7268    /// Matches `pd.Timestamp.fromordinal(ordinal)`. Returns NaT for invalid ordinals.
7269    #[must_use]
7270    pub fn fromordinal(ordinal: i64) -> Self {
7271        if ordinal <= 0 {
7272            return Self {
7273                nanos: Self::NAT,
7274                tz: None,
7275            };
7276        }
7277        // Convert y/m/d to days since Unix epoch, then to nanos
7278        // Unix epoch is 1970-01-01, which is ordinal 719163
7279        let days_since_epoch = ordinal - 719163;
7280        match days_since_epoch.checked_mul(Timedelta::NANOS_PER_DAY) {
7281            Some(nanos) => Self { nanos, tz: None },
7282            None => Self::nat(),
7283        }
7284    }
7285
7286    /// Return the Julian Date (astronomical day number).
7287    ///
7288    /// Matches `pd.Timestamp.to_julian_date()`. Returns NaN for NaT.
7289    /// The Julian Date is the continuous count of days since the beginning
7290    /// of the Julian Period (January 1, 4713 BC in the proleptic Julian calendar).
7291    #[must_use]
7292    pub fn to_julian_date(&self) -> f64 {
7293        if self.is_nat() {
7294            return f64::NAN;
7295        }
7296        // Gregorian ordinal 1 (Jan 1, year 1) corresponds to Julian Day 1721425.5
7297        // (at noon, since JD starts at noon)
7298        // For a timestamp at midnight, we subtract 0.5
7299        let ordinal = match self.toordinal() {
7300            Some(o) => o,
7301            None => return f64::NAN,
7302        };
7303        // Fractional day from time components
7304        let h = self.hour().unwrap_or(0) as f64;
7305        let m = self.minute().unwrap_or(0) as f64;
7306        let s = self.second().unwrap_or(0) as f64;
7307        let us = self.microsecond().unwrap_or(0) as f64;
7308        let ns = self.nanosecond().unwrap_or(0) as f64;
7309        let frac_day =
7310            (h + m / 60.0 + s / 3600.0 + us / 3_600_000_000.0 + ns / 3_600_000_000_000.0) / 24.0;
7311        // Julian day at midnight of ordinal 1 is 1721424.5
7312        1721424.5 + ordinal as f64 + frac_day
7313    }
7314
7315    /// Return the quarter (1-4) of the year.
7316    ///
7317    /// Matches `pd.Timestamp.quarter`. Returns None for NaT.
7318    #[must_use]
7319    pub fn quarter(&self) -> Option<i64> {
7320        self.month().map(|m| (m - 1) / 3 + 1)
7321    }
7322
7323    /// Return the ISO week number (1-53).
7324    ///
7325    /// Matches `pd.Timestamp.week`. Returns None for NaT.
7326    #[must_use]
7327    pub fn weekofyear(&self) -> Option<i64> {
7328        if self.is_nat() {
7329            return None;
7330        }
7331        let doy = self.dayofyear()?;
7332        let dow = self.dayofweek()?;
7333        let year = self.year()?;
7334        let iso_dow = if dow == 6 { 7 } else { dow + 1 };
7335        let week = (doy - iso_dow + 10) / 7;
7336        // ISO-8601 has 53-week years, so the clamps must consult the actual
7337        // week count, not hardcode 52/1: a week<1 belongs to the LAST week of
7338        // the previous year (52 OR 53), and a week beyond this year's count
7339        // wraps to week 1 of the next year. pandas isocalendar().week agrees:
7340        // 2021-01-01 -> 53 (2020 is a 53-week year), 2026-12-31 -> 53.
7341        if week < 1 {
7342            Some(iso_weeks_in_year(year - 1))
7343        } else if week > iso_weeks_in_year(year) {
7344            Some(1)
7345        } else {
7346            Some(week)
7347        }
7348    }
7349
7350    /// Alias for weekofyear(). Matches `pd.Timestamp.week`.
7351    #[must_use]
7352    pub fn week(&self) -> Option<i64> {
7353        self.weekofyear()
7354    }
7355
7356    /// Return the timestamp value in the specified unit.
7357    ///
7358    /// Matches `pd.Timestamp.value` when unit is nanoseconds.
7359    /// Supported units: "ns", "us", "ms", "s".
7360    #[must_use]
7361    pub fn to_unit(&self, unit: &str) -> Option<i64> {
7362        if self.is_nat() {
7363            return None;
7364        }
7365        match unit {
7366            "ns" | "nanosecond" | "nanoseconds" => Some(self.nanos),
7367            "us" | "microsecond" | "microseconds" => Some(self.nanos / 1_000),
7368            "ms" | "millisecond" | "milliseconds" => Some(self.nanos / 1_000_000),
7369            "s" | "second" | "seconds" => Some(self.nanos / 1_000_000_000),
7370            _ => None,
7371        }
7372    }
7373
7374    /// Whether the year is a leap year.
7375    ///
7376    /// Matches `pd.Timestamp.is_leap_year`. Returns None for NaT.
7377    #[must_use]
7378    pub fn is_leap_year(&self) -> Option<bool> {
7379        self.year()
7380            .map(|y| (y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
7381    }
7382
7383    /// Whether the day is the first day of the month.
7384    ///
7385    /// Matches `pd.Timestamp.is_month_start`. Returns None for NaT.
7386    #[must_use]
7387    pub fn is_month_start(&self) -> Option<bool> {
7388        self.day().map(|d| d == 1)
7389    }
7390
7391    /// Whether the day is the last day of the month.
7392    ///
7393    /// Matches `pd.Timestamp.is_month_end`. Returns None for NaT.
7394    #[must_use]
7395    pub fn is_month_end(&self) -> Option<bool> {
7396        let y = self.year()?;
7397        let m = self.month()?;
7398        let d = self.day()?;
7399        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7400        let days_in_month: [i64; 12] = [
7401            31,
7402            if is_leap { 29 } else { 28 },
7403            31,
7404            30,
7405            31,
7406            30,
7407            31,
7408            31,
7409            30,
7410            31,
7411            30,
7412            31,
7413        ];
7414        Some(d == days_in_month[(m - 1) as usize])
7415    }
7416
7417    /// Whether the day is the first day of a quarter.
7418    ///
7419    /// Matches `pd.Timestamp.is_quarter_start`. Returns None for NaT.
7420    #[must_use]
7421    pub fn is_quarter_start(&self) -> Option<bool> {
7422        let m = self.month()?;
7423        let d = self.day()?;
7424        Some(d == 1 && (m == 1 || m == 4 || m == 7 || m == 10))
7425    }
7426
7427    /// Whether the day is the last day of a quarter.
7428    ///
7429    /// Matches `pd.Timestamp.is_quarter_end`. Returns None for NaT.
7430    #[must_use]
7431    pub fn is_quarter_end(&self) -> Option<bool> {
7432        let m = self.month()?;
7433        let d = self.day()?;
7434        Some(
7435            (m == 3 && d == 31)
7436                || (m == 6 && d == 30)
7437                || (m == 9 && d == 30)
7438                || (m == 12 && d == 31),
7439        )
7440    }
7441
7442    /// Whether the day is the first day of the year (Jan 1).
7443    ///
7444    /// Matches `pd.Timestamp.is_year_start`. Returns None for NaT.
7445    #[must_use]
7446    pub fn is_year_start(&self) -> Option<bool> {
7447        let m = self.month()?;
7448        let d = self.day()?;
7449        Some(m == 1 && d == 1)
7450    }
7451
7452    /// Whether the day is the last day of the year (Dec 31).
7453    ///
7454    /// Matches `pd.Timestamp.is_year_end`. Returns None for NaT.
7455    #[must_use]
7456    pub fn is_year_end(&self) -> Option<bool> {
7457        let m = self.month()?;
7458        let d = self.day()?;
7459        Some(m == 12 && d == 31)
7460    }
7461
7462    /// Return the number of days in the month of this timestamp.
7463    ///
7464    /// Matches `pd.Timestamp.days_in_month`. Returns None for NaT.
7465    #[must_use]
7466    pub fn days_in_month(&self) -> Option<i64> {
7467        let y = self.year()?;
7468        let m = self.month()?;
7469        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7470        let days: [i64; 12] = [
7471            31,
7472            if is_leap { 29 } else { 28 },
7473            31,
7474            30,
7475            31,
7476            30,
7477            31,
7478            31,
7479            30,
7480            31,
7481            30,
7482            31,
7483        ];
7484        Some(days[(m - 1) as usize])
7485    }
7486
7487    /// Alias for days_in_month(). Matches `pd.Timestamp.daysinmonth`.
7488    #[must_use]
7489    pub fn daysinmonth(&self) -> Option<i64> {
7490        self.days_in_month()
7491    }
7492
7493    /// Normalize to midnight/day boundary, matching `pd.Timestamp.normalize()`.
7494    #[must_use]
7495    pub fn normalize(&self) -> Self {
7496        self.floor_to(Timedelta::NANOS_PER_DAY)
7497    }
7498
7499    /// Replace timestamp components with new values.
7500    ///
7501    /// Matches pd.Timestamp.replace(). None values keep the existing component.
7502    #[must_use]
7503    #[allow(clippy::too_many_arguments)]
7504    pub fn replace(
7505        &self,
7506        year: Option<i64>,
7507        month: Option<i64>,
7508        day: Option<i64>,
7509        hour: Option<i64>,
7510        minute: Option<i64>,
7511        second: Option<i64>,
7512        microsecond: Option<i64>,
7513        nanosecond: Option<i64>,
7514    ) -> Self {
7515        if self.is_nat() {
7516            return self.clone();
7517        }
7518        let cur_year = self.year().unwrap_or(1970);
7519        let cur_month = self.month().unwrap_or(1);
7520        let cur_day = self.day().unwrap_or(1);
7521        let cur_hour = self.hour().unwrap_or(0);
7522        let cur_minute = self.minute().unwrap_or(0);
7523        let cur_second = self.second().unwrap_or(0);
7524        let cur_micro = self.microsecond().unwrap_or(0);
7525        let cur_nano = self.nanosecond().unwrap_or(0);
7526
7527        let y = year.unwrap_or(cur_year);
7528        let mo = month.unwrap_or(cur_month);
7529        let d = day.unwrap_or(cur_day);
7530        let h = hour.unwrap_or(cur_hour);
7531        let mi = minute.unwrap_or(cur_minute);
7532        let s = second.unwrap_or(cur_second);
7533        let us = microsecond.unwrap_or(cur_micro);
7534        let ns = nanosecond.unwrap_or(cur_nano);
7535
7536        if !(1..=12).contains(&mo)
7537            || !(1..=days_in_month(y, mo as u32).unwrap_or(0) as i64).contains(&d)
7538            || !(0..=23).contains(&h)
7539            || !(0..=59).contains(&mi)
7540            || !(0..=59).contains(&s)
7541            || !(0..=999_999).contains(&us)
7542            || !(0..=999).contains(&ns)
7543        {
7544            return Self::nat();
7545        }
7546
7547        // Checked nanosecond arithmetic (br-frankenpandas-dzz6x). The component
7548        // validation above rejects an out-of-range month/day/hour/... but says
7549        // nothing about the YEAR, and i64 nanoseconds run out at
7550        // `i64::MAX / NANOS_PER_DAY` = 106_751 days from the epoch — about year
7551        // 2262, the same bound pandas documents for ns-resolution Timestamps.
7552        // Unchecked, `replace(year=3000)` wrapped in release mode and returned a
7553        // silently wrong, plausible-looking in-range instant. Overflow now folds
7554        // to NaT, matching both the validation arm above and the sibling
7555        // constructors `fromordinal` / `floor_to`, which already fail this way.
7556        // In-range results are unchanged: the checked ops return exactly the
7557        // value the plain operators produced whenever no overflow occurred.
7558        let days_from_epoch = Self::days_from_ymd(y, mo, d);
7559        let secs = h * 3600 + mi * 60 + s;
7560        let Some(total_nanos) = days_from_epoch
7561            .checked_mul(Timedelta::NANOS_PER_DAY)
7562            .and_then(|nanos| {
7563                secs.checked_mul(Timedelta::NANOS_PER_SEC)
7564                    .and_then(|s_nanos| nanos.checked_add(s_nanos))
7565            })
7566            .and_then(|nanos| {
7567                us.checked_mul(Timedelta::NANOS_PER_MICRO)
7568                    .and_then(|us_nanos| nanos.checked_add(us_nanos))
7569            })
7570            .and_then(|nanos| nanos.checked_add(ns))
7571        else {
7572            return Self::nat();
7573        };
7574
7575        let utc_nanos = match self.tz.as_deref() {
7576            Some(tz) => match tz_wall_to_utc_nanos(tz, total_nanos) {
7577                Ok(utc) => utc,
7578                Err(TimeZoneError::Unknown(_)) => total_nanos,
7579                Err(TimeZoneError::NonExistent(_) | TimeZoneError::Ambiguous(_)) => {
7580                    return Self::nat();
7581                }
7582            },
7583            None => total_nanos,
7584        };
7585
7586        Self {
7587            nanos: utc_nanos,
7588            tz: self.tz.clone(),
7589        }
7590    }
7591
7592    fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
7593        let y = if month <= 2 { year - 1 } else { year };
7594        let era = if y >= 0 { y } else { y - 399 } / 400;
7595        let yoe = y - era * 400;
7596        let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
7597        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
7598        era * 146097 + doe - 719468
7599    }
7600
7601    /// Return an ISO 8601 string representation of the timestamp.
7602    ///
7603    /// Matches `pd.Timestamp.isoformat()`. NaT returns "NaT".
7604    #[must_use]
7605    pub fn isoformat(&self) -> String {
7606        use std::fmt::Write as _;
7607
7608        if self.is_nat() {
7609            return "NaT".to_string();
7610        }
7611        let resolved_offset = self
7612            .tz
7613            .as_deref()
7614            .and_then(|tz| tz_offset_seconds(tz, self.nanos).ok())
7615            .and_then(|offset_secs| {
7616                self.nanos
7617                    .checked_add(i64::from(offset_secs) * Timedelta::NANOS_PER_SEC)
7618                    .map(|wall_nanos| (wall_nanos, offset_secs))
7619            });
7620        let display_nanos = resolved_offset.map_or(self.nanos, |(wall_nanos, _)| wall_nanos);
7621        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
7622        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
7623        let days_since_epoch = display_nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7624        let nanos_of_day = display_nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7625        let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7626        let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7627
7628        let days = days_since_epoch + 719_468;
7629        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7630        let doe = days - era * 146_097;
7631        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7632        let y = yoe + era * 400;
7633        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7634        let mp = (5 * doy + 2) / 153;
7635        let d = doy - (153 * mp + 2) / 5 + 1;
7636        let m = if mp < 10 { mp + 3 } else { mp - 9 };
7637        let year = if m <= 2 { y + 1 } else { y };
7638
7639        let hour = secs_of_day / 3600;
7640        let minute = (secs_of_day % 3600) / 60;
7641        let second = secs_of_day % 60;
7642
7643        // Build the timestamp and its optional timezone suffix in the returned
7644        // allocation. The former timezone-aware path first allocated `base`,
7645        // then allocated again to copy `base` into the suffixed result.
7646        let suffix_capacity = match (&self.tz, resolved_offset) {
7647            (Some(_), Some(_)) => 6,
7648            (Some(tz), None) => tz.len() + 2,
7649            (None, _) => 0,
7650        };
7651        let mut result = String::with_capacity(29 + suffix_capacity);
7652        if sub_nanos == 0 {
7653            let _ = write!(
7654                result,
7655                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}"
7656            );
7657        } else if sub_nanos.is_multiple_of(1_000) {
7658            let _ = write!(
7659                result,
7660                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{:06}",
7661                sub_nanos / 1_000
7662            );
7663        } else {
7664            let _ = write!(
7665                result,
7666                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{sub_nanos:09}"
7667            );
7668        }
7669        match (&self.tz, resolved_offset) {
7670            (Some(_), Some((_, offset_secs))) => {
7671                let sign = if offset_secs < 0 { '-' } else { '+' };
7672                let total_minutes = offset_secs.unsigned_abs() / 60;
7673                let _ = write!(
7674                    result,
7675                    "{sign}{:02}:{:02}",
7676                    total_minutes / 60,
7677                    total_minutes % 60
7678                );
7679            }
7680            (Some(tz), None) => {
7681                result.push('[');
7682                result.push_str(tz);
7683                result.push(']');
7684            }
7685            (None, _) => {}
7686        }
7687        result
7688    }
7689
7690    /// Alias for isoformat.
7691    #[must_use]
7692    pub fn to_iso8601(&self) -> String {
7693        self.isoformat()
7694    }
7695
7696    /// The coarsest [`DatetimeStringResolution`] that renders `nanos` losslessly.
7697    ///
7698    /// Fold this over a column with `max` to get the column's width — see
7699    /// [`DatetimeStringResolution`] for why the width is a property of the
7700    /// COLUMN and not of the value. `NaT` reports [`DatetimeStringResolution`]
7701    /// `::Date`, the identity for that fold, because pandas excludes it from the
7702    /// scan entirely: a column of one midnight plus one NaT still renders
7703    /// `['2024-03-15', 'NaT']`.
7704    #[must_use]
7705    pub const fn string_resolution(nanos: i64) -> DatetimeStringResolution {
7706        if nanos == Self::NAT {
7707            return DatetimeStringResolution::Date;
7708        }
7709        if nanos.rem_euclid(Timedelta::NANOS_PER_DAY) == 0 {
7710            DatetimeStringResolution::Date
7711        } else if nanos.rem_euclid(Timedelta::NANOS_PER_SEC) == 0 {
7712            DatetimeStringResolution::Second
7713        } else if nanos.rem_euclid(Timedelta::NANOS_PER_MILLI) == 0 {
7714            DatetimeStringResolution::Milli
7715        } else if nanos.rem_euclid(Timedelta::NANOS_PER_MICRO) == 0 {
7716            DatetimeStringResolution::Micro
7717        } else {
7718            DatetimeStringResolution::Nano
7719        }
7720    }
7721
7722    /// Render `nanos` the way `astype(str)` does, at a resolution chosen for the
7723    /// whole column by [`Self::string_resolution`].
7724    ///
7725    /// ⚠️ NOT [`Self::isoformat`]. That one is `pd.Timestamp.isoformat()` — a `T`
7726    /// separator, and a width chosen per VALUE. This is the array formatter:
7727    /// a SPACE separator, and a width imposed on every element alike. MEASURED,
7728    /// live pandas 2.2.3, one column per rung:
7729    ///
7730    /// ```text
7731    /// all midnight       -> '2024-03-15'
7732    /// all whole seconds  -> '2024-03-15 10:30:45'
7733    /// all whole millis   -> '2024-03-15 10:30:45.123'
7734    /// all whole micros   -> '2024-03-15 10:30:45.123456'
7735    /// anything finer     -> '2024-03-15 10:30:45.123456789'
7736    /// NaT                -> 'NaT'          (a STRING, not a missing value)
7737    /// ```
7738    ///
7739    /// There is NO minute rung: a column of whole minutes still renders its
7740    /// seconds (`'2024-01-01 00:05:00'`).
7741    #[must_use]
7742    pub fn format_at_resolution(nanos: i64, resolution: DatetimeStringResolution) -> String {
7743        use std::fmt::Write as _;
7744
7745        if nanos == Self::NAT {
7746            return "NaT".to_string();
7747        }
7748        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos,
7749        // the same correction isoformat makes (br-frankenpandas-wkjtw): a
7750        // pre-epoch value must render 1969-12-31 23:59:59.999999999, not a
7751        // negative fraction.
7752        let days_since_epoch = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7753        let nanos_of_day = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7754        let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7755        let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC);
7756        // The crate's existing Hinnant civil-from-days, NOT a second copy: two
7757        // implementations of a calendar algorithm are two chances to drift.
7758        let (year, month, day) = civil_from_days(days_since_epoch);
7759
7760        // pandas' datetime64[ns] range is 1677..=2262, so the year is always
7761        // four digits and `{:04}` never truncates.
7762        let mut result = String::with_capacity(30);
7763        // `fmt::Write for String` is infallible.
7764        let _ = write!(result, "{year:04}-{month:02}-{day:02}");
7765        if matches!(resolution, DatetimeStringResolution::Date) {
7766            return result;
7767        }
7768        let _ = write!(
7769            result,
7770            " {:02}:{:02}:{:02}",
7771            secs_of_day / 3600,
7772            (secs_of_day % 3600) / 60,
7773            secs_of_day % 60
7774        );
7775        let (fraction, width) = match resolution {
7776            DatetimeStringResolution::Date | DatetimeStringResolution::Second => return result,
7777            DatetimeStringResolution::Milli => (sub_nanos / Timedelta::NANOS_PER_MILLI, 3_usize),
7778            DatetimeStringResolution::Micro => (sub_nanos / Timedelta::NANOS_PER_MICRO, 6_usize),
7779            DatetimeStringResolution::Nano => (sub_nanos, 9_usize),
7780        };
7781        let _ = write!(result, ".{fraction:0width$}", width = width);
7782        result
7783    }
7784
7785    /// Parse a datetime string into a Timestamp.
7786    ///
7787    /// Supports ISO 8601 formats:
7788    /// - "2024-01-15" (date only, time defaults to 00:00:00)
7789    /// - "2024-01-15T10:30:00" (datetime)
7790    /// - "2024-01-15 10:30:00" (space separator)
7791    /// - "2024-01-15T10:30:00.123456" (with fractional seconds)
7792    /// - "2024-01-15T10:30:00Z" (UTC timezone)
7793    /// - "2024-01-15T10:30:00+05:30" (offset timezone)
7794    /// - "NaT" (Not a Timestamp)
7795    ///
7796    /// Matches `pd.Timestamp()` constructor behavior.
7797    pub fn parse(s: &str) -> Result<Self, TypeError> {
7798        let s = s.trim();
7799
7800        if s.eq_ignore_ascii_case("nat") {
7801            return Ok(Self::nat());
7802        }
7803
7804        let Some((datetime_part, tz)) = Self::split_timezone(s) else {
7805            return Err(TypeError::ValueNotParseable {
7806                value: s.to_string(),
7807                target: "Timestamp".to_string(),
7808            });
7809        };
7810
7811        let (date_part, time_part) = if datetime_part.contains('T') {
7812            datetime_part
7813                .split_once('T')
7814                .ok_or_else(|| TypeError::ValueNotParseable {
7815                    value: s.to_string(),
7816                    target: "Timestamp".to_string(),
7817                })?
7818        } else if datetime_part.contains(' ')
7819            && datetime_part.chars().filter(|&c| c == ' ').count() == 1
7820        {
7821            datetime_part
7822                .split_once(' ')
7823                .ok_or_else(|| TypeError::ValueNotParseable {
7824                    value: s.to_string(),
7825                    target: "Timestamp".to_string(),
7826                })?
7827        } else {
7828            (datetime_part, "00:00:00")
7829        };
7830
7831        let (year, month, day) =
7832            Self::parse_date(date_part).ok_or_else(|| TypeError::ValueNotParseable {
7833                value: s.to_string(),
7834                target: "Timestamp".to_string(),
7835            })?;
7836
7837        let (hour, minute, second, nanos) =
7838            Self::parse_time(time_part).ok_or_else(|| TypeError::ValueNotParseable {
7839                value: s.to_string(),
7840                target: "Timestamp".to_string(),
7841            })?;
7842
7843        // br-frankenpandas-94o1u: an unrepresentable instant is a parse
7844        // failure, not a wrapped value.
7845        let wall_nanos = Self::ymd_hms_to_nanos(year, month, day, hour, minute, second, nanos)
7846            .ok_or_else(|| TypeError::ValueNotParseable {
7847                value: s.to_string(),
7848                target: "Timestamp".to_string(),
7849            })?;
7850        // The digits are the wall clock at the offset; the instant is that
7851        // wall time less the offset ('10:00+09:00' is 01:00 UTC - it was
7852        // read as 10:00 UTC, so it showed as 19:00+09:00).
7853        let offset = tz
7854            .as_deref()
7855            .and_then(Self::fixed_utc_offset_seconds)
7856            .unwrap_or(0);
7857        let total_nanos = offset
7858            .checked_mul(1_000_000_000)
7859            .and_then(|offset| wall_nanos.checked_sub(offset))
7860            .ok_or_else(|| TypeError::ValueNotParseable {
7861                value: s.to_string(),
7862                target: "Timestamp".to_string(),
7863            })?;
7864
7865        Ok(if let Some(tz_name) = tz {
7866            Self::from_nanos_tz(total_nanos, tz_name)
7867        } else {
7868            Self::from_nanos(total_nanos)
7869        })
7870    }
7871
7872    fn split_timezone(s: &str) -> Option<(&str, Option<String>)> {
7873        if let Some(stripped) = s.strip_suffix('Z') {
7874            Some((stripped, Some("UTC".to_string())))
7875        } else if let Some(idx) = s.rfind('+') {
7876            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7877                Some((&s[..idx], Some(s[idx..].to_string())))
7878            } else if idx > 10 {
7879                None
7880            } else {
7881                Some((s, None))
7882            }
7883        } else if let Some(idx) = s.rfind('-') {
7884            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7885                Some((&s[..idx], Some(s[idx..].to_string())))
7886            } else if idx > 10 {
7887                None
7888            } else {
7889                Some((s, None))
7890            }
7891        } else {
7892            Some((s, None))
7893        }
7894    }
7895
7896    fn fixed_utc_offset_seconds(tz: &str) -> Option<i64> {
7897        if tz == "UTC" {
7898            return Some(0);
7899        }
7900        let offset = tz.strip_prefix("UTC").unwrap_or(tz);
7901        if !Self::is_timezone_offset(offset) {
7902            return None;
7903        }
7904        let sign = if offset.starts_with('+') { 1 } else { -1 };
7905        let hours = offset[1..3].parse::<i64>().ok()?;
7906        let minutes = offset[4..6].parse::<i64>().ok()?;
7907        Some(sign * (hours * 3_600 + minutes * 60))
7908    }
7909
7910    fn is_timezone_offset(s: &str) -> bool {
7911        let bytes = s.as_bytes();
7912        if bytes.len() != 6 || !matches!(bytes[0], b'+' | b'-') || bytes[3] != b':' {
7913            return false;
7914        }
7915        if !bytes[1..3].iter().all(u8::is_ascii_digit)
7916            || !bytes[4..6].iter().all(u8::is_ascii_digit)
7917        {
7918            return false;
7919        }
7920        let hour = u32::from(bytes[1] - b'0') * 10 + u32::from(bytes[2] - b'0');
7921        let minute = u32::from(bytes[4] - b'0') * 10 + u32::from(bytes[5] - b'0');
7922        hour <= 23 && minute <= 59
7923    }
7924
7925    fn parse_date(s: &str) -> Option<(i64, u32, u32)> {
7926        let parts: Vec<&str> = s.split('-').collect();
7927        if parts.len() != 3 {
7928            return None;
7929        }
7930        let year: i64 = parts[0].parse().ok()?;
7931        let month: u32 = parts[1].parse().ok()?;
7932        let day: u32 = parts[2].parse().ok()?;
7933        if !(1..=days_in_month(year, month)?).contains(&day) {
7934            return None;
7935        }
7936        Some((year, month, day))
7937    }
7938
7939    fn parse_time(s: &str) -> Option<(u32, u32, u32, u64)> {
7940        let (time_str, frac_str) = match s.split_once('.') {
7941            Some((time, frac)) => (time, Some(frac)),
7942            None => (s, None),
7943        };
7944        let parts: Vec<&str> = time_str.split(':').collect();
7945        if parts.is_empty() || parts.len() > 3 {
7946            return None;
7947        }
7948        let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
7949        let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
7950        let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
7951
7952        if hour > 23 || minute > 59 || second > 59 {
7953            return None;
7954        }
7955
7956        let nanos = match frac_str {
7957            None => 0,
7958            Some(frac) => {
7959                if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
7960                    return None;
7961                }
7962                let digits = frac.len().min(9);
7963                let mut nanos = 0_u64;
7964                for byte in frac.bytes().take(digits) {
7965                    nanos = nanos * 10 + u64::from(byte - b'0');
7966                }
7967                for _ in digits..9 {
7968                    nanos *= 10;
7969                }
7970                nanos
7971            }
7972        };
7973
7974        Some((hour, minute, second, nanos))
7975    }
7976
7977    /// Compose a civil date-time into i64 nanoseconds since the epoch, or
7978    /// `None` when the instant is not representable.
7979    ///
7980    /// Checked composition (br-frankenpandas-94o1u). `parse_date` validates the
7981    /// month and the day-of-month but parses the YEAR as an unbounded `i64`,
7982    /// and i64 nanoseconds top out around year 2262 — the bound pandas
7983    /// documents for ns-resolution Timestamps. Unchecked, the two multiplies
7984    /// below wrapped in release, so `Timestamp::parse("300000-01-01")` returned
7985    /// `Ok` holding a silently wrong, plausible-looking in-range instant.
7986    /// pandas raises `OutOfBoundsDatetime`.
7987    ///
7988    /// This is the ingestion path — CSV/JSON date columns and user strings —
7989    /// so failing OPEN with corrupt data is the failure mode the security
7990    /// doctrine specifically forbids. `None` here becomes the same
7991    /// `ValueNotParseable` the caller already returns for any other
7992    /// unparseable input, so no new error variant and no API change.
7993    ///
7994    /// The day-count arithmetic above the multiplies cannot overflow for any
7995    /// `year` that survives `str::parse::<i64>` minus the era arithmetic's own
7996    /// bounds, but it is routed through checked ops anyway so an extreme year
7997    /// is rejected rather than wrapped before it ever reaches the seconds step.
7998    fn ymd_hms_to_nanos(
7999        year: i64,
8000        month: u32,
8001        day: u32,
8002        hour: u32,
8003        minute: u32,
8004        second: u32,
8005        sub_nanos: u64,
8006    ) -> Option<i64> {
8007        let m = month as i64;
8008        let d = day as i64;
8009
8010        let y = if m <= 2 { year.checked_sub(1)? } else { year };
8011        let era = if y >= 0 { y } else { y.checked_sub(399)? } / 400;
8012        let yoe = y.checked_sub(era.checked_mul(400)?)?;
8013        let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
8014        let doe = yoe
8015            .checked_mul(365)?
8016            .checked_add(yoe / 4 - yoe / 100)?
8017            .checked_add(doy)?;
8018        let days_since_epoch = era
8019            .checked_mul(146_097)?
8020            .checked_add(doe)?
8021            .checked_sub(719_468)?;
8022
8023        let total_seconds = days_since_epoch
8024            .checked_mul(86400)?
8025            .checked_add(i64::from(hour) * 3600)?
8026            .checked_add(i64::from(minute) * 60)?
8027            .checked_add(i64::from(second))?;
8028        total_seconds
8029            .checked_mul(Timedelta::NANOS_PER_SEC)?
8030            .checked_add(sub_nanos as i64)
8031    }
8032
8033    /// Format timestamp using strftime directives.
8034    ///
8035    /// Matches `pd.Timestamp.strftime(format)`: Python's (glibc's) directive
8036    /// set, see [`strftime_python`] (it knew only %Y %m %d %H %M %S %f and
8037    /// printed `%%Y` as `%2024`). A tz-aware Timestamp formats its wall clock,
8038    /// `%z` / `%Z` its zone's offset and abbreviation then. NaT returns "NaT".
8039    #[must_use]
8040    pub fn strftime(&self, format: &str) -> String {
8041        if self.is_nat() {
8042            return "NaT".to_string();
8043        }
8044        strftime_in_zone(self.nanos, format, self.tz.as_deref())
8045    }
8046
8047    /// Return the day of the week as a string (e.g., "Monday").
8048    ///
8049    /// Matches `pd.Timestamp.day_name()`. NaT returns "NaT".
8050    #[must_use]
8051    pub fn day_name(&self) -> String {
8052        const NAMES: [&str; 7] = [
8053            "Thursday",
8054            "Friday",
8055            "Saturday",
8056            "Sunday",
8057            "Monday",
8058            "Tuesday",
8059            "Wednesday",
8060        ];
8061        if self.is_nat() {
8062            return "NaT".to_string();
8063        }
8064        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
8065        // Truncating `/` rounds a negative, non-midnight instant TOWARD zero, so
8066        // it lands on the following day and names the wrong weekday: pandas 2.2.3
8067        // gives 1969-07-20T20:17:40 -> "Sunday", truncation gave "Monday". The
8068        // wkjtw fix was applied to `dayofweek` but never here.
8069        let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
8070        let dow = ((days_since_epoch % 7) + 7) % 7;
8071        NAMES[dow as usize].to_string()
8072    }
8073
8074    /// Return the month name as a string (e.g., "January").
8075    ///
8076    /// Matches `pd.Timestamp.month_name()`. NaT returns "NaT".
8077    #[must_use]
8078    pub fn month_name(&self) -> String {
8079        const NAMES: [&str; 12] = [
8080            "January",
8081            "February",
8082            "March",
8083            "April",
8084            "May",
8085            "June",
8086            "July",
8087            "August",
8088            "September",
8089            "October",
8090            "November",
8091            "December",
8092        ];
8093        if self.is_nat() {
8094            return "NaT".to_string();
8095        }
8096        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
8097        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
8098        // for the post-1970 positive case.
8099        let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
8100        let days = days_since_epoch + 719_468;
8101        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
8102        let doe = days - era * 146_097;
8103        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
8104        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
8105        let mp = (5 * doy + 2) / 153;
8106        let m = if mp < 10 { mp + 3 } else { mp - 9 };
8107        NAMES[(m - 1) as usize].to_string()
8108    }
8109
8110    /// Localize a naive timestamp to a timezone, or strip the timezone from a
8111    /// timezone-aware timestamp while preserving its local wall clock (`tz = None`),
8112    /// under explicit `ambiguous` and `nonexistent` DST policies.
8113    ///
8114    /// Matches `pd.Timestamp.tz_localize(tz, ambiguous=..., nonexistent=...)`.
8115    pub fn try_tz_localize_with(
8116        &self,
8117        tz: Option<&str>,
8118        ambiguous: AmbiguousTime,
8119        nonexistent: NonexistentTime,
8120    ) -> Result<Self, TypeError> {
8121        match (tz, &self.tz) {
8122            (Some(_), Some(_)) => Err(TypeError::AlreadyTzAware),
8123            (None, _) => {
8124                if self.is_nat() {
8125                    return Ok(Self::nat());
8126                }
8127                Ok(Self::from_nanos(self.wall_nanos()))
8128            }
8129            (Some(zone), None) => {
8130                if self.is_nat() {
8131                    return Ok(Self::nat());
8132                }
8133                let nanos = tz_wall_to_utc_nanos_with(zone, self.nanos, ambiguous, nonexistent)?;
8134                if nanos == Self::NAT {
8135                    return Ok(Self::nat());
8136                }
8137                Ok(Self {
8138                    nanos,
8139                    tz: Some(zone.to_owned()),
8140                })
8141            }
8142        }
8143    }
8144
8145    /// Localize a naive timestamp to a timezone, or strip the timezone from a
8146    /// timezone-aware timestamp while preserving its local wall clock (`tz = None`).
8147    ///
8148    /// Matches `pd.Timestamp.tz_localize(tz)` with default `ambiguous='raise'`
8149    /// and `nonexistent='raise'`.
8150    pub fn try_tz_localize(&self, tz: Option<&str>) -> Result<Self, TypeError> {
8151        self.try_tz_localize_with(tz, AmbiguousTime::Raise, NonexistentTime::Raise)
8152    }
8153
8154    /// Localize a naive timestamp to a timezone (infallible convenience wrapper
8155    /// around [`Self::try_tz_localize`]; errors fold to `NaT`).
8156    #[must_use]
8157    pub fn tz_localize(&self, tz: Option<&str>) -> Self {
8158        self.try_tz_localize(tz).unwrap_or_else(|_| Self::nat())
8159    }
8160
8161    /// Convert a timezone-aware timestamp to another timezone (or `None` to
8162    /// convert to UTC and remove the timezone), preserving the absolute UTC
8163    /// instant.
8164    ///
8165    /// Matches `pd.Timestamp.tz_convert(tz)`. Returns `Err(TypeError::TzNaiveCannotConvert)`
8166    /// if `self` is timezone-naive.
8167    pub fn try_tz_convert(&self, tz: Option<&str>) -> Result<Self, TypeError> {
8168        if self.is_nat() {
8169            return Ok(Self::nat());
8170        }
8171        if self.tz.is_none() {
8172            return Err(TypeError::TzNaiveCannotConvert);
8173        }
8174        match tz {
8175            Some(zone) => {
8176                tz_validate(zone)?;
8177                Ok(Self {
8178                    nanos: self.nanos,
8179                    tz: Some(zone.to_owned()),
8180                })
8181            }
8182            None => Ok(Self {
8183                nanos: self.nanos,
8184                tz: None,
8185            }),
8186        }
8187    }
8188
8189    /// Convert timezone-aware timestamp to another timezone (infallible
8190    /// convenience wrapper around [`Self::try_tz_convert`]; errors fold to `NaT`).
8191    #[must_use]
8192    pub fn tz_convert(&self, tz: &str) -> Self {
8193        self.try_tz_convert(Some(tz))
8194            .unwrap_or_else(|_| Self::nat())
8195    }
8196
8197    /// Create a Timestamp from a Unix timestamp (seconds since epoch).
8198    ///
8199    /// Matches `pd.Timestamp.fromtimestamp(ts)`. The optional `tz` parameter
8200    /// specifies the timezone to localize to.
8201    #[must_use]
8202    pub fn fromtimestamp(ts: f64, tz: Option<&str>) -> Self {
8203        if ts.is_nan() || ts.is_infinite() {
8204            return Self::nat();
8205        }
8206        let nanos_f64 = ts * 1_000_000_000.0;
8207        // Check for overflow before casting - i64 range is roughly ±9.2e18
8208        const MAX_NANOS: f64 = i64::MAX as f64;
8209        const MIN_NANOS: f64 = i64::MIN as f64;
8210        if !(MIN_NANOS..=MAX_NANOS).contains(&nanos_f64) {
8211            return Self::nat();
8212        }
8213        Self {
8214            nanos: nanos_f64 as i64,
8215            tz: tz.map(String::from),
8216        }
8217    }
8218
8219    /// Create a Timestamp from milliseconds since epoch.
8220    ///
8221    /// Convenience constructor complementing fromtimestamp. An `ms` outside
8222    /// the representable nanosecond range → NaT, matching `fromtimestamp`
8223    /// directly above (br-frankenpandas-kyd16); the previous
8224    /// `saturating_mul` handed back a finite ~year-2262 instant instead.
8225    #[must_use]
8226    pub fn from_millis(ms: i64, tz: Option<&str>) -> Self {
8227        let Some(nanos) = ms.checked_mul(1_000_000) else {
8228            return Self::nat();
8229        };
8230        Self {
8231            nanos,
8232            tz: tz.map(String::from),
8233        }
8234    }
8235
8236    /// Create a Timestamp from microseconds since epoch.
8237    ///
8238    /// Convenience constructor complementing fromtimestamp.
8239    #[must_use]
8240    pub fn from_micros(us: i64, tz: Option<&str>) -> Self {
8241        let Some(nanos) = us.checked_mul(1_000) else {
8242            return Self::nat();
8243        };
8244        Self {
8245            nanos,
8246            tz: tz.map(String::from),
8247        }
8248    }
8249
8250    /// Return the timezone string, or None if naive.
8251    #[must_use]
8252    pub fn tzinfo(&self) -> Option<&str> {
8253        self.tz.as_deref()
8254    }
8255
8256    /// Return the timezone abbreviation at this timestamp's instant (e.g.,
8257    /// `"EST"` / `"EDT"` / `"UTC"` / `"UTC+05:30"`), or `None` if naive or `NaT`.
8258    ///
8259    /// Matches `pd.Timestamp.tzname()`.
8260    #[must_use]
8261    pub fn tzname(&self) -> Option<String> {
8262        if self.is_nat() {
8263            return None;
8264        }
8265        let tz = self.tz.as_deref()?;
8266        Some(tz_abbreviation(tz, self.nanos).unwrap_or_else(|_| tz.to_owned()))
8267    }
8268
8269    /// Convert this Timestamp to a [`Period`] at the given frequency, matching
8270    /// `pd.Timestamp.to_period(freq)`. Timezone-aware timestamps convert their
8271    /// local wall-clock instant and drop the timezone.
8272    pub fn to_period(&self, freq: &str) -> Result<Period, TypeError> {
8273        if self.is_nat() {
8274            return Err(TypeError::ValueIsMissing {
8275                kind: NullKind::NaT,
8276            });
8277        }
8278        let target_freq = PeriodFreq::parse(freq).ok_or_else(|| TypeError::ValueNotParseable {
8279            value: freq.to_owned(),
8280            target: "PeriodFreq".to_owned(),
8281        })?;
8282        let offset_secs = self
8283            .tz
8284            .as_deref()
8285            .and_then(|tz| {
8286                tz_offset_seconds(tz, self.nanos)
8287                    .ok()
8288                    .map(i64::from)
8289                    .or_else(|| Self::fixed_utc_offset_seconds(tz))
8290            })
8291            .unwrap_or(0);
8292        let wall_nanos = offset_secs
8293            .checked_mul(Timedelta::NANOS_PER_SEC)
8294            .and_then(|offset_nanos| self.nanos.checked_add(offset_nanos))
8295            .ok_or_else(|| TypeError::ValueNotParseable {
8296                value: self.to_string(),
8297                target: format!("Period[{target_freq}]"),
8298            })?;
8299        Period::from_timestamp_nanos(wall_nanos, target_freq).ok_or_else(|| {
8300            TypeError::ValueNotParseable {
8301                value: self.to_string(),
8302                target: format!("Period[{target_freq}]"),
8303            }
8304        })
8305    }
8306}
8307
8308impl std::fmt::Display for Timestamp {
8309    /// Phase 2 debug-style format; Phase 3 replaces with pandas ISO-8601
8310    /// notation once chrono interpretation lands.
8311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8312        if self.is_nat() {
8313            return f.write_str("NaT");
8314        }
8315        match &self.tz {
8316            Some(tz) => write!(f, "Timestamp[{}, {}]", self.nanos, tz),
8317            None => write!(f, "Timestamp[{}, UTC]", self.nanos),
8318        }
8319    }
8320}
8321
8322impl PartialOrd for Timestamp {
8323    /// Orders by nanos axis; NaT is incomparable (`None`). Tz difference
8324    /// does not affect ordering — two Timestamps at the same absolute
8325    /// nanos compare equal regardless of tz label (Phase 3 will revisit
8326    /// whether tz affects ordering semantics).
8327    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
8328        if self.is_nat() || other.is_nat() {
8329            return None;
8330        }
8331        Some(self.nanos.cmp(&other.nanos))
8332    }
8333}
8334
8335// ── Missingness utilities ──────────────────────────────────────────────
8336
8337pub fn isna(values: &[Scalar]) -> Vec<bool> {
8338    values.iter().map(Scalar::is_missing).collect()
8339}
8340
8341pub fn isnull(values: &[Scalar]) -> Vec<bool> {
8342    isna(values)
8343}
8344
8345pub fn notna(values: &[Scalar]) -> Vec<bool> {
8346    values.iter().map(|v| !v.is_missing()).collect()
8347}
8348
8349pub fn notnull(values: &[Scalar]) -> Vec<bool> {
8350    notna(values)
8351}
8352
8353pub fn count_na(values: &[Scalar]) -> usize {
8354    values.iter().filter(|v| v.is_missing()).count()
8355}
8356
8357pub fn fill_na(values: &[Scalar], fill: &Scalar) -> Vec<Scalar> {
8358    values
8359        .iter()
8360        .map(|v| {
8361            if v.is_missing() {
8362                fill.clone()
8363            } else {
8364                v.clone()
8365            }
8366        })
8367        .collect()
8368}
8369
8370pub fn dropna(values: &[Scalar]) -> Vec<Scalar> {
8371    values.iter().filter(|v| !v.is_missing()).cloned().collect()
8372}
8373
8374// ── Nanops: null-skipping numeric reductions ───────────────────────────
8375
8376fn collect_finite(values: &[Scalar]) -> Vec<f64> {
8377    values
8378        .iter()
8379        .filter(|v| !v.is_missing())
8380        .filter_map(|v| v.to_f64().ok())
8381        .collect()
8382}
8383
8384/// Per br-frankenpandas-620mj: if a column is uniformly Timedelta64
8385/// (with optional NAT/Null missing), sum/mean preserve Timedelta dtype
8386/// matching pandas — instead of silently coercing to Float64(0.0) via
8387/// the collect_finite path (which drops Timedelta64 because to_f64
8388/// errors). A NaT-only input remains a Timedelta family so sum returns
8389/// zero Timedelta and mean returns NaT. Returns Some(sum_in_ns,
8390/// observed_count) when applicable.
8391fn collect_timedelta_ns(values: &[Scalar]) -> Option<(i128, usize)> {
8392    let mut sum: i128 = 0;
8393    let mut count: usize = 0;
8394    let mut saw_timedelta = false;
8395    for v in values {
8396        match v {
8397            Scalar::Timedelta64(ns) => {
8398                saw_timedelta = true;
8399                if v.is_missing() {
8400                    continue;
8401                }
8402                sum += i128::from(*ns);
8403                count += 1;
8404            }
8405            _ if v.is_missing() => continue,
8406            // Any non-Timedelta non-missing value bails out to the
8407            // existing Float64 path, preserving cross-type behavior.
8408            _ => return None,
8409        }
8410    }
8411    if saw_timedelta {
8412        Some((sum, count))
8413    } else {
8414        None
8415    }
8416}
8417
8418/// Narrow an exact `i128` nanosecond quantity back to a `Timedelta64` scalar,
8419/// surfacing NaT when the value is not representable.
8420///
8421/// Per br-frankenpandas-opz27, this replaces the `clamp(i64::MIN, i64::MAX)`
8422/// the reduction paths used to do, which failed open twice over:
8423///
8424/// - a positive overflow became `i64::MAX`, a fabricated finite ~106751-day
8425///   Timedelta presented as real data (the br-frankenpandas-lgyy8 class);
8426/// - `Timedelta::NAT` *is* `i64::MIN`, so the clamp's lower bound landed
8427///   exactly on the missing sentinel — a negative overflow silently became
8428///   NaT by accident, and the bound was off by one against the true minimum.
8429///
8430/// The representable range is therefore `[i64::MIN + 1, i64::MAX]`, and both
8431/// overflow directions now yield NaT deliberately. Live pandas 2.2.3 raises
8432/// (`OverflowError` / `ValueError: overflow in timedelta operation`) where
8433/// these reductions overflow; FP surfaces NaT instead, matching the
8434/// infallible-helper convention established by `Timedelta::div_scalar` and
8435/// br-frankenpandas-lgyy8. Every exactly-representable result is unaffected.
8436fn timedelta_ns_to_scalar(ns: i128) -> Scalar {
8437    if ns > i128::from(i64::MAX) || ns <= i128::from(i64::MIN) {
8438        return Scalar::Timedelta64(Timedelta::NAT);
8439    }
8440    Scalar::Timedelta64(ns as i64)
8441}
8442
8443pub fn nansum(values: &[Scalar]) -> Scalar {
8444    if let Some((sum, _)) = collect_timedelta_ns(values) {
8445        return timedelta_ns_to_scalar(sum);
8446    }
8447    // Fused single-pass fold: filter missing / non-f64-coercible and accumulate
8448    // in one scan, avoiding the intermediate `collect_finite` Vec<f64> and its
8449    // second pass. Bit-identical to `collect_finite(..).iter().sum()`: same
8450    // finite values in the same order, same left-fold f64 `+` (empty -> 0.0).
8451    let mut sum = 0.0_f64;
8452    for v in values {
8453        if v.is_missing() {
8454            continue;
8455        }
8456        if let Ok(x) = v.to_f64() {
8457            sum += x;
8458        }
8459    }
8460    Scalar::Float64(sum)
8461}
8462
8463/// Sum of a STRING group: pandas concatenates, skipping missing entries.
8464///
8465/// br-frankenpandas-a7faz. `nansum` cannot serve this: it coerces through
8466/// `to_f64`, which fails for every `Utf8`, so a string column sums to
8467/// `Float64(0.0)` — a wrong value rather than a refusal. This is a separate
8468/// reducer rather than a branch inside `nansum` on purpose: the SUM SURFACES
8469/// DISAGREE in pandas and a shared change would silently move the others.
8470///
8471/// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18):
8472/// ```text
8473///   Series(['a','b','c']).sum()              -> 'abc'
8474///   Series(['a',None,'c']).sum()             -> TypeError: can only concatenate str
8475///   DataFrame({'v':['a',None]}).sum()        -> TypeError (same)
8476///   df.groupby(k)['v'].sum()  with a None    -> 'a'      SKIPS, does not raise
8477///   s.resample('ME').sum()    with a None    -> 'ps'     SKIPS, does not raise
8478/// ```
8479/// So the REDUCTION surfaces raise on a missing entry while the GROUPED surfaces
8480/// skip it. This function implements the grouped rule and must not be wired into
8481/// `Series::sum`/`DataFrame::sum` without implementing their raise.
8482///
8483/// ⚠️ AND AN EMPTY OR ALL-MISSING GROUP IS INTEGER `0`, NOT `""`. Measured:
8484/// ```text
8485///   Series(['p','q'], index=[Jan-01, Mar-01]).resample('ME').sum()
8486///     -> ['p', 0, 'q']        <- the empty February bucket is int 0
8487///   Series([None,None,'r','u'], ...).resample('ME').sum()
8488///     -> [0, 'ru']            <- an all-missing bucket is int 0 too
8489///   types: ['int', 'str']     <- the output column is genuinely MIXED
8490/// ```
8491/// That is pandas' `sum()` identity element leaking through unchanged, and it is
8492/// why this returns `Scalar::Int64(0)` rather than an empty string: matching the
8493/// incumbent here means reproducing a mixed-dtype column.
8494///
8495/// Concatenation is POSITIONAL, not sorted — `Series(['z','a','m']).sum()` is
8496/// `'zam'`. Callers that bucket by time therefore hand the values over in index
8497/// order, which is what produced `'psq'` for a Jan bucket holding Jan-01 'p',
8498/// Jan-05 's', Jan-15 'q'.
8499#[must_use]
8500pub fn nansum_utf8(values: &[Scalar]) -> Scalar {
8501    let mut out: Option<String> = None;
8502    for v in values {
8503        if v.is_missing() {
8504            continue;
8505        }
8506        if let Scalar::Utf8(part) = v {
8507            out.get_or_insert_with(String::new).push_str(part);
8508        }
8509    }
8510    match out {
8511        Some(joined) => Scalar::Utf8(joined),
8512        // Not `Utf8(String::new())`: pandas yields the integer identity here.
8513        None => Scalar::Int64(0),
8514    }
8515}
8516
8517pub fn nanmean(values: &[Scalar]) -> Scalar {
8518    if let Some((sum, count)) = collect_timedelta_ns(values) {
8519        if count == 0 {
8520            return Scalar::Timedelta64(Timedelta::NAT);
8521        }
8522        // |sum / count| <= max|ns| for count >= 1, so the mean of representable
8523        // inputs is always representable; the narrowing is defensive only.
8524        return timedelta_ns_to_scalar(sum / count as i128);
8525    }
8526    // br-frankenpandas-adv58: Datetime64 mean is the mean of the epoch-ns
8527    // backing, re-read as an instant. Accumulated in i128 and divided with
8528    // Rust's toward-zero integer division, which is exactly the rounding pandas
8529    // shows where it is exact ([0,1] -> 0, [0,3] -> 1, [-3,0] -> -1; floor and
8530    // ties-to-even are both refuted). Where pandas is NOT exact it snaps to its
8531    // f64 grid — even for a constant series — and FP stays exact. See DISC-019.
8532    if let Some((sum, count)) = collect_datetime_ns(values) {
8533        if count == 0 {
8534            return Scalar::Datetime64(Timestamp::NAT);
8535        }
8536        let mean = sum / count as i128;
8537        if mean > i128::from(i64::MAX) || mean <= i128::from(i64::MIN) {
8538            return Scalar::Datetime64(Timestamp::NAT);
8539        }
8540        return Scalar::Datetime64(mean as i64);
8541    }
8542    // Fused single-pass fold (see `nansum`): accumulate sum + count of finite
8543    // values in one scan. Bit-identical to the prior `collect_finite` two-pass:
8544    // count == nums.len(), sum folds the same values in the same order.
8545    let mut sum = 0.0_f64;
8546    let mut count = 0usize;
8547    for v in values {
8548        if v.is_missing() {
8549            continue;
8550        }
8551        if let Ok(x) = v.to_f64() {
8552            sum += x;
8553            count += 1;
8554        }
8555    }
8556    if count == 0 {
8557        return Scalar::Null(NullKind::NaN);
8558    }
8559    Scalar::Float64(sum / count as f64)
8560}
8561
8562pub fn nanany(values: &[Scalar]) -> Scalar {
8563    for v in values {
8564        if v.is_missing() {
8565            continue;
8566        }
8567        match v {
8568            Scalar::Bool(flag) if *flag => return Scalar::Bool(true),
8569            Scalar::Int64(val) if *val != 0 => return Scalar::Bool(true),
8570            Scalar::Float64(val) if !val.is_nan() && *val != 0.0 => return Scalar::Bool(true),
8571            Scalar::Utf8(val) if !val.is_empty() => return Scalar::Bool(true),
8572            // pandas Series([td]).any() returns True for any non-zero
8573            // Timedelta. NaT is already filtered by is_missing() above.
8574            Scalar::Timedelta64(ns) if *ns != 0 => return Scalar::Bool(true),
8575            _ => continue,
8576        }
8577    }
8578    Scalar::Bool(false)
8579}
8580
8581pub fn nanall(values: &[Scalar]) -> Scalar {
8582    for v in values {
8583        if v.is_missing() {
8584            continue;
8585        }
8586        match v {
8587            Scalar::Bool(flag) if !*flag => return Scalar::Bool(false),
8588            Scalar::Int64(val) if *val == 0 => return Scalar::Bool(false),
8589            Scalar::Float64(val) if val.is_nan() || *val == 0.0 => return Scalar::Bool(false),
8590            Scalar::Utf8(val) if val.is_empty() => return Scalar::Bool(false),
8591            // pandas Series([td(0)]).all() returns False; any non-zero
8592            // Timedelta is truthy. NaT is already filtered by is_missing.
8593            Scalar::Timedelta64(ns) if *ns == 0 => return Scalar::Bool(false),
8594            _ => continue,
8595        }
8596    }
8597    Scalar::Bool(true)
8598}
8599
8600pub fn nancount(values: &[Scalar]) -> Scalar {
8601    let n = values.iter().filter(|v| !v.is_missing()).count();
8602    Scalar::Int64(n as i64)
8603}
8604
8605pub fn nanmin(values: &[Scalar]) -> Scalar {
8606    let mut min: Option<&Scalar> = None;
8607    for v in values {
8608        if v.is_missing() {
8609            continue;
8610        }
8611        match (min, v) {
8612            (None, _) => min = Some(v),
8613            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8614                if b < a {
8615                    min = Some(v)
8616                }
8617            }
8618            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8619                if *b < *a {
8620                    min = Some(v)
8621                }
8622            }
8623            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8624                if b < a {
8625                    min = Some(v)
8626                }
8627            }
8628            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8629                if b < a {
8630                    min = Some(v)
8631                }
8632            }
8633            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
8634            // the catch-all below would silently return NaN. Compare ns
8635            // representations directly; NAT is already filtered by
8636            // is_missing() above.
8637            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8638                if b < a {
8639                    min = Some(v)
8640                }
8641            }
8642            // br-frankenpandas-axhhk: Datetime64 needs the same arm for the
8643            // same reason — its to_f64() errors too. Without it a 2+-element
8644            // datetime column returned Null(NaN), while a 1-element one
8645            // returned the right answer via the (None, _) seed above.
8646            (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8647                if b < a {
8648                    min = Some(v)
8649                }
8650            }
8651            // br-frankenpandas-qoabs: Period, third dtype with the same
8652            // to_f64() failure. Ordinals are ONLY comparable within one freq —
8653            // pandas refuses mixed freq outright (IncompatibleFrequency), so a
8654            // differing freq must NOT be ordered here. Comparing the raw
8655            // ordinals across freqs would invent an ordering pandas rejects
8656            // (monthly 2020-01 is ordinal 600, daily 2020-01-05 is 18267).
8657            // br-frankenpandas-qoabs: Period, third dtype with the same
8658            // to_f64() failure. Ordinals are ONLY comparable within one freq —
8659            // pandas refuses mixed freq outright (IncompatibleFrequency), so a
8660            // differing freq must NOT be ordered here. Comparing the raw
8661            // ordinals across freqs would invent an ordering pandas rejects
8662            // (monthly 2020-01 is ordinal 600, daily 2020-01-05 is 18267).
8663            (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8664                if a.freq != b.freq {
8665                    return Scalar::Null(NullKind::NaN);
8666                }
8667                if b.ordinal < a.ordinal {
8668                    min = Some(v)
8669                }
8670            }
8671            // br-frankenpandas-srqdo: Interval, fourth dtype whose to_f64()
8672            // errors. pandas orders Intervals by (left, right) — a tie on left
8673            // falls through to right. `closed` is NOT part of the comparison:
8674            // pandas does order scalar Intervals that tie on both bounds by an
8675            // internal `closed` ordering, but a real IntervalArray requires a
8676            // UNIFORM closed, so that case cannot arise from an Interval
8677            // column, and guessing an undocumented enum order would be worse
8678            // than keeping the first on an exact tie.
8679            //
8680            // A NaN bound is not orderable and has no pandas counterpart —
8681            // IntervalArray refuses to build one ("missing values must be
8682            // missing in the same location both left and right") — so bail to
8683            // missing rather than impose an arbitrary order. Note this avoids
8684            // `partial_cmp().unwrap()`, which would be a panic in library code.
8685            (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8686                if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8687                    return Scalar::Null(NullKind::NaN);
8688                }
8689                if (b.left, b.right) < (a.left, a.right) {
8690                    min = Some(v)
8691                }
8692            }
8693            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8694                (Ok(af), Ok(bf)) if bf < af => min = Some(v),
8695                (Ok(_), Ok(_)) => {}
8696                _ => return Scalar::Null(NullKind::NaN),
8697            },
8698        }
8699    }
8700    match min {
8701        Some(v) => v.clone(),
8702        None => Scalar::Null(NullKind::NaN),
8703    }
8704}
8705
8706pub fn nanmax(values: &[Scalar]) -> Scalar {
8707    let mut max: Option<&Scalar> = None;
8708    for v in values {
8709        if v.is_missing() {
8710            continue;
8711        }
8712        match (max, v) {
8713            (None, _) => max = Some(v),
8714            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8715                if b > a {
8716                    max = Some(v)
8717                }
8718            }
8719            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8720                if *b > *a {
8721                    max = Some(v)
8722                }
8723            }
8724            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8725                if b > a {
8726                    max = Some(v)
8727                }
8728            }
8729            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8730                if b > a {
8731                    max = Some(v)
8732                }
8733            }
8734            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
8735            // the catch-all below would silently return NaN. Compare ns
8736            // representations directly; NAT is already filtered above.
8737            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8738                if b > a {
8739                    max = Some(v)
8740                }
8741            }
8742            // br-frankenpandas-axhhk: Datetime64 sibling of the arm above.
8743            (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8744                if b > a {
8745                    max = Some(v)
8746                }
8747            }
8748            // br-frankenpandas-qoabs: Period, freq-guarded — see `nanmin`.
8749            (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8750                if a.freq != b.freq {
8751                    return Scalar::Null(NullKind::NaN);
8752                }
8753                if b.ordinal > a.ordinal {
8754                    max = Some(v)
8755                }
8756            }
8757            // br-frankenpandas-srqdo: Interval, ordered by (left, right) with
8758            // NaN bounds refused — see `nanmin` for the full reasoning.
8759            (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8760                if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8761                    return Scalar::Null(NullKind::NaN);
8762                }
8763                if (b.left, b.right) > (a.left, a.right) {
8764                    max = Some(v)
8765                }
8766            }
8767            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8768                (Ok(af), Ok(bf)) if bf > af => max = Some(v),
8769                (Ok(_), Ok(_)) => {}
8770                _ => return Scalar::Null(NullKind::NaN),
8771            },
8772        }
8773    }
8774    match max {
8775        Some(v) => v.clone(),
8776        None => Scalar::Null(NullKind::NaN),
8777    }
8778}
8779
8780/// Which temporal family a uniformly-temporal input belongs to, and everything
8781/// needed to rebuild a `Scalar` of it from a raw i64 backing.
8782///
8783/// br-frankenpandas-d7zjp replaced the previous `fn(i64) -> Scalar` constructor
8784/// with this enum for one reason: a plain fn pointer CANNOT CARRY A FREQ, and a
8785/// `Period` is `{ordinal, freq}`. That limitation is what blocked Period from
8786/// joining median/quantile/cummax/cummin when Datetime64 did.
8787///
8788/// The i64 payload is nanoseconds for Timedelta64/Datetime64 and an ORDINAL for
8789/// Period — different units, but every operation here is pure ordering or an
8790/// average over that backing, which is meaningful in both.
8791#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8792enum TemporalFamily {
8793    Timedelta,
8794    Datetime,
8795    /// Periods only compare within ONE freq; see [`collect_temporal_backing`].
8796    Period(PeriodFreq),
8797}
8798
8799impl TemporalFamily {
8800    /// Rebuild a scalar of this family from its raw backing.
8801    fn make(self, raw: i64) -> Scalar {
8802        match self {
8803            Self::Timedelta => Scalar::Timedelta64(raw),
8804            Self::Datetime => Scalar::Datetime64(raw),
8805            Self::Period(freq) => Scalar::Period(Period::new(raw, freq)),
8806        }
8807    }
8808
8809    /// The family's missing sentinel, dtype preserved.
8810    fn nat(self) -> Scalar {
8811        self.make(i64::MIN)
8812    }
8813}
8814
8815/// Per br-frankenpandas-j8ntk: harvest the raw backing of a uniformly-temporal
8816/// input as f64 (53 bits of mantissa, exact for ns spans up to ~104 days;
8817/// beyond that pandas itself loses precision the same way), together with the
8818/// family to rebuild results in. A NaT-only input keeps its family.
8819///
8820/// Returns `None` unless every non-missing value belongs to ONE family — which
8821/// for Period means one FREQ as well, because pandas refuses to order Periods
8822/// of differing freq at all (`IncompatibleFrequency`) and their ordinals are
8823/// not comparable across freqs.
8824///
8825/// br-frankenpandas-adv58 widened this to Datetime64 and d7zjp to Period. The
8826/// f64 hop is inherited deliberately: quantile interpolates by a fractional
8827/// weight, so the newer families keep the SAME accuracy contract the Timedelta
8828/// arm already had rather than inventing a stricter one per dtype.
8829fn collect_temporal_backing(values: &[Scalar]) -> Option<(Vec<f64>, TemporalFamily)> {
8830    let mut out = Vec::with_capacity(values.len());
8831    let mut family: Option<TemporalFamily> = None;
8832    for v in values {
8833        let (raw, this) = match v {
8834            Scalar::Timedelta64(ns) => (*ns, TemporalFamily::Timedelta),
8835            Scalar::Datetime64(ns) => (*ns, TemporalFamily::Datetime),
8836            Scalar::Period(p) => (p.ordinal, TemporalFamily::Period(p.freq)),
8837            _ if v.is_missing() => continue,
8838            _ => return None,
8839        };
8840        // Mixing families — or, for Period, mixing freqs — is not one family.
8841        match family {
8842            Some(existing) if existing != this => return None,
8843            _ => family = Some(this),
8844        }
8845        if v.is_missing() {
8846            continue;
8847        }
8848        out.push(raw as f64);
8849    }
8850    family.map(|f| (out, f))
8851}
8852
8853/// Timedelta64-ONLY view of [`collect_temporal_backing`].
8854///
8855/// var/sem keep this narrower gate on purpose: live pandas 2.2.3 RAISES
8856/// `TypeError: 'DatetimeArray' ... does not support reduction 'var'` (and the
8857/// same for 'sem', and for every one of them on Period), so widening them would
8858/// invent a value pandas refuses to produce.
8859fn collect_timedelta_ns_f64(values: &[Scalar]) -> Option<Vec<f64>> {
8860    match collect_temporal_backing(values) {
8861        Some((out, TemporalFamily::Timedelta)) => Some(out),
8862        _ => None,
8863    }
8864}
8865
8866/// Clamp an f64 result into i64 range and wrap as Scalar::Timedelta64.
8867fn float_ns_to_timedelta(value: f64) -> Scalar {
8868    float_ns_to_temporal(value, TemporalFamily::Timedelta)
8869}
8870
8871/// Family-generic form of [`float_ns_to_timedelta`], per br-frankenpandas-adv58:
8872/// NaT for a non-finite input, otherwise the value in the caller's family.
8873fn float_ns_to_temporal(value: f64, make: TemporalFamily) -> Scalar {
8874    if !value.is_finite() {
8875        return make.nat();
8876    }
8877    let clamped = value.clamp(i64::MIN as f64, i64::MAX as f64);
8878    make.make(clamped as i64)
8879}
8880
8881pub fn nanmedian(values: &[Scalar]) -> Scalar {
8882    // Preserve exact nanosecond ordering for uniformly-temporal input.
8883    // Converting to f64 loses distinct ticks beyond the 53-bit boundary.
8884    //
8885    // br-frankenpandas-adv58: Datetime64 joins Timedelta64 here, and keeps the
8886    // SAME exact i128 treatment its Timedelta sibling already had. Note that
8887    // this makes FP strictly more precise than pandas 2.2.3, which routes
8888    // datetime median through f64 and therefore snaps to a 256 ns grid at
8889    // 2020-era timestamps — returning, for an odd-count input, a Timestamp that
8890    // is not even one of the supplied values. See DISC-019.
8891    // br-frankenpandas-d7zjp: Period joins via the family enum, which — unlike
8892    // the fn-pointer constructor this replaced — can carry its freq. A
8893    // mixed-freq input is not one family, so it falls through rather than
8894    // being ordered by raw ordinal, matching pandas refusing it outright.
8895    let Some((_, make)) = collect_temporal_backing(values) else {
8896        // Not uniformly temporal: fall through to the numeric arm below.
8897        return nanmedian_numeric(values);
8898    };
8899    let mut td: Vec<i64> = values
8900        .iter()
8901        .filter(|value| !value.is_missing())
8902        .filter_map(|value| match value {
8903            Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
8904            Scalar::Period(p) => Some(p.ordinal),
8905            _ => None,
8906        })
8907        .collect();
8908    if td.is_empty() {
8909        // All-missing temporal input falls through to the numeric arm, which
8910        // yields Null(NaN). Do NOT "improve" this to a family-typed NaT: the
8911        // Null(NaN) result is pinned by the oracle test
8912        // `nanmedian_matches_numeric_and_timedelta_oracle_oabhi`, and the old
8913        // `is_timedelta_input` gate produced it by returning false for an
8914        // all-missing input. `collect_temporal_backing` marks the family on
8915        // seeing the VARIANT instead, so the fall-through has to be explicit.
8916        return nanmedian_numeric(values);
8917    }
8918    // O(n) selection instead of a full sort: order statistics depend only
8919    // on values, so the unstable partition yields the same middle values.
8920    let n = td.len();
8921    let mid = n / 2;
8922    let (left, mid_ref, _right) = td.select_nth_unstable(mid);
8923    let mid_val = *mid_ref;
8924    let median_ns = if n.is_multiple_of(2) {
8925        let lower = left.iter().copied().fold(i64::MIN, i64::max);
8926        // Toward-zero division, matching pandas where pandas is exact.
8927        (i128::from(lower) + i128::from(mid_val)) / 2
8928    } else {
8929        i128::from(mid_val)
8930    };
8931    make.make(median_ns as i64)
8932}
8933
8934/// Numeric (f64) median arm, split out of [`nanmedian`] by
8935/// br-frankenpandas-adv58 so the temporal arm can return early. Also the
8936/// fall-through for non-uniform input, e.g. mixed Datetime64 + Int64.
8937fn nanmedian_numeric(values: &[Scalar]) -> Scalar {
8938    let mut nums = collect_finite(values);
8939    if nums.is_empty() {
8940        return Scalar::Null(NullKind::NaN);
8941    }
8942    // O(n) selection instead of an O(n log n) full sort: select_nth_unstable_by
8943    // places the `mid`-th smallest at index `mid` with all smaller elements
8944    // (unordered) in the left partition. For even n the (mid-1)-th smallest is
8945    // the MAX of that left partition. Bit-identical to the sort path: order
8946    // statistics depend only on VALUES, and ties share a value, so the
8947    // unstable partition yields the same nums[mid-1]/nums[mid] the sort did.
8948    let n = nums.len();
8949    let mid = n / 2;
8950    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
8951    let (left, mid_ref, _right) = nums.select_nth_unstable_by(mid, cmp);
8952    let mid_val = *mid_ref;
8953    if n.is_multiple_of(2) {
8954        let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
8955        Scalar::Float64((lower + mid_val) / 2.0)
8956    } else {
8957        Scalar::Float64(mid_val)
8958    }
8959}
8960
8961pub fn nanvar(values: &[Scalar], ddof: usize) -> Scalar {
8962    // Per br-frankenpandas-j8ntk: Timedelta64 var preserves dtype — pandas
8963    // returns Timedelta even though variance is ns² conceptually; matching.
8964    if let Some(td) = collect_timedelta_ns_f64(values) {
8965        if td.len() <= ddof {
8966            return Scalar::Timedelta64(Timedelta::NAT);
8967        }
8968        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8969        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8970        return float_ns_to_timedelta(sum_sq / (td.len() - ddof) as f64);
8971    }
8972    let nums = collect_finite(values);
8973    if nums.len() <= ddof {
8974        return Scalar::Null(NullKind::NaN);
8975    }
8976    let mean: f64 = nums.iter().sum::<f64>() / nums.len() as f64;
8977    let sum_sq: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
8978    Scalar::Float64(sum_sq / (nums.len() - ddof) as f64)
8979}
8980
8981pub fn nanstd(values: &[Scalar], ddof: usize) -> Scalar {
8982    // Per br-frankenpandas-j8ntk: Timedelta64 std preserves dtype.
8983    //
8984    // br-frankenpandas-40ujm: Datetime64 is accepted here too, and the family
8985    // constructor is deliberately DISCARDED — the dispersion of a set of
8986    // instants is a DURATION, so datetime std returns a Timedelta, exactly as
8987    // pandas does. Verified against the oracle: pandas gives the identical
8988    // value for a Datetime64 series and a Timedelta64 series built from the
8989    // same ns (both 2592479955563784 for [0, 60d, 31d]).
8990    //
8991    // This is the ONLY reduction in the std/var/sem group that widens. pandas
8992    // RAISES for datetime64 var and sem ("does not support reduction"), so
8993    // those keep the Timedelta-only `collect_timedelta_ns_f64` gate rather than
8994    // inventing a value pandas refuses to produce.
8995    //
8996    // br-frankenpandas-d7zjp: PERIOD IS EXCLUDED HERE. pandas raises
8997    // "'PeriodArray' with dtype period[M] does not support reduction 'std'",
8998    // so widening std to Period alongside Datetime64 would invent a value —
8999    // and the family enum makes that mistake one line away, hence the guard.
9000    if let Some((td, family)) = collect_temporal_backing(values)
9001        && !matches!(family, TemporalFamily::Period(_))
9002    {
9003        if td.len() <= ddof {
9004            return Scalar::Timedelta64(Timedelta::NAT);
9005        }
9006        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
9007        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
9008        let var = sum_sq / (td.len() - ddof) as f64;
9009        return float_ns_to_timedelta(var.sqrt());
9010    }
9011    match nanvar(values, ddof) {
9012        Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
9013        other => other,
9014    }
9015}
9016
9017/// Standard error of the mean over non-missing values.
9018///
9019/// Matches `pd.Series.sem(ddof=1)` / `scipy.stats.sem`. Computed as
9020/// `std(values, ddof) / sqrt(n)` where `n` is the non-missing count.
9021/// Returns `Null(NaN)` when `n <= ddof`.
9022pub fn nansem(values: &[Scalar], ddof: usize) -> Scalar {
9023    // Per br-frankenpandas-j8ntk: Timedelta64 sem preserves dtype.
9024    if let Some(td) = collect_timedelta_ns_f64(values) {
9025        if td.len() <= ddof {
9026            return Scalar::Timedelta64(Timedelta::NAT);
9027        }
9028        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
9029        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
9030        let var = sum_sq / (td.len() - ddof) as f64;
9031        let std = var.sqrt();
9032        return float_ns_to_timedelta(std / (td.len() as f64).sqrt());
9033    }
9034    let nums = collect_finite(values);
9035    if nums.len() <= ddof {
9036        return Scalar::Null(NullKind::NaN);
9037    }
9038    let n = nums.len();
9039    let mean = nums.iter().sum::<f64>() / n as f64;
9040    let sum_sq = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
9041    let var = sum_sq / (n - ddof) as f64;
9042    let std = var.sqrt();
9043    Scalar::Float64(std / (n as f64).sqrt())
9044}
9045
9046/// Standard error of the mean as pandas' groupby, resample and pivot_table
9047/// compute it: `sqrt(var / n)` (libgroupby's `group_var(name="sem")`), which
9048/// can differ in the last bit from [`nansem`]'s `std / sqrt(n)` (Series.sem):
9049/// for `[1.0, 4.0]` this is `1.5` and nansem `1.4999999999999998`
9050/// (br-frankenpandas-7hxqv). Timedelta input keeps [`nansem`].
9051pub fn nansem_grouped(values: &[Scalar], ddof: usize) -> Scalar {
9052    if collect_timedelta_ns_f64(values).is_some() {
9053        return nansem(values, ddof);
9054    }
9055    grouped_moments(values)
9056        .sem(ddof)
9057        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9058}
9059
9060/// pandas' compensated running sum: its cython `group_sum`, `group_mean`
9061/// and `group_cumsum` add each float as `y = v - comp; t = sum + y;
9062/// comp = t - sum - y; sum = t` (Kahan), `comp` reset to 0 where it is NaN
9063/// (an inf added; GH#53606). A plain `+=` fold differs from it in the last
9064/// bits - groupby sum of ten 0.1 is 1.0 in pandas, 0.9999999999999999
9065/// naively (br-frankenpandas-xhogl).
9066#[derive(Clone, Copy, Debug, Default, PartialEq)]
9067pub struct KahanSum {
9068    sum: f64,
9069    compensation: f64,
9070}
9071
9072impl KahanSum {
9073    /// `value` added, as pandas' group kernels add it.
9074    #[inline]
9075    pub fn add(&mut self, value: f64) {
9076        let y = value - self.compensation;
9077        let t = self.sum + y;
9078        self.compensation = t - self.sum - y;
9079        if self.compensation.is_nan() {
9080            self.compensation = 0.0;
9081        }
9082        self.sum = t;
9083    }
9084
9085    /// The sum so far.
9086    #[inline]
9087    #[must_use]
9088    pub fn sum(self) -> f64 {
9089        self.sum
9090    }
9091}
9092
9093/// pandas' online variance: its cython `group_var` folds each float as
9094/// Welford (`mean += (v - old) / n; m2 += (v - mean) * (v - old)`) and
9095/// answers `m2 / (n - ddof)`, std its square root and sem
9096/// `sqrt(m2 / (n - ddof) / n)` - where the two-pass form differs in the
9097/// last bits (a constant group's var is 0.0, not 1e-34;
9098/// br-frankenpandas-xhogl).
9099#[derive(Clone, Copy, Debug, Default, PartialEq)]
9100pub struct WelfordVar {
9101    count: usize,
9102    mean: f64,
9103    m2: f64,
9104}
9105
9106impl WelfordVar {
9107    /// `value` folded in.
9108    #[inline]
9109    pub fn add(&mut self, value: f64) {
9110        self.count += 1;
9111        let old = self.mean;
9112        self.mean += (value - old) / self.count as f64;
9113        self.m2 += (value - self.mean) * (value - old);
9114    }
9115
9116    /// The values folded in.
9117    #[must_use]
9118    pub fn count(self) -> usize {
9119        self.count
9120    }
9121
9122    /// `m2 / (n - ddof)`; None while `n <= ddof`.
9123    #[must_use]
9124    pub fn var(self, ddof: usize) -> Option<f64> {
9125        (self.count > ddof).then(|| self.m2 / (self.count - ddof) as f64)
9126    }
9127
9128    /// The square root of [`Self::var`].
9129    #[must_use]
9130    pub fn std(self, ddof: usize) -> Option<f64> {
9131        self.var(ddof).map(f64::sqrt)
9132    }
9133
9134    /// `sqrt(var / n)`, pandas' grouped sem.
9135    #[must_use]
9136    pub fn sem(self, ddof: usize) -> Option<f64> {
9137        self.var(ddof).map(|var| (var / self.count as f64).sqrt())
9138    }
9139}
9140
9141/// pandas' online skewness: its cython `group_skew` folds each float into
9142/// running moments (`delta = v - m1; delta_n = delta / n; term1 = delta *
9143/// delta_n * (n - 1); m1 += delta_n; m3 += term1 * delta_n * (n - 2) -
9144/// 3 * delta_n * m2; m2 += term1`) and answers
9145/// `n * (n - 1) ** 0.5 / (n - 2) * (m3 / m2 ** 1.5)` - 0 when `m2` is 0,
9146/// missing below 3 values - where the two-pass [`nanskew`] (Series.skew)
9147/// differs in the last bits (br-frankenpandas-vjfq9).
9148#[derive(Clone, Copy, Debug, Default, PartialEq)]
9149pub struct SkewMoments {
9150    count: usize,
9151    m1: f64,
9152    m2: f64,
9153    m3: f64,
9154}
9155
9156impl SkewMoments {
9157    /// `value` folded in.
9158    #[inline]
9159    pub fn add(&mut self, value: f64) {
9160        let before = self.count as f64;
9161        self.count += 1;
9162        let n = self.count as f64;
9163        let delta = value - self.m1;
9164        let delta_n = delta / n;
9165        let term1 = delta * delta_n * before;
9166        self.m1 += delta_n;
9167        self.m3 += term1 * delta_n * (n - 2.0) - 3.0 * delta_n * self.m2;
9168        self.m2 += term1;
9169    }
9170
9171    /// The values folded in.
9172    #[must_use]
9173    pub fn count(self) -> usize {
9174        self.count
9175    }
9176
9177    /// The bias-corrected skewness; None below 3 values.
9178    #[must_use]
9179    pub fn skew(self) -> Option<f64> {
9180        if self.count < 3 {
9181            return None;
9182        }
9183        if self.m2 == 0.0 {
9184            return Some(0.0);
9185        }
9186        let n = self.count as f64;
9187        // pandas raises with libm pow: pow(n - 1, 0.5) is not always sqrt's
9188        // correctly rounded answer (n = 2922 differs), and a constant 0.5
9189        // exponent would let LLVM substitute sqrt.
9190        let half = std::hint::black_box(0.5);
9191        Some((n * (n - 1.0).powf(half) / (n - 2.0)) * (self.m3 / self.m2.powf(1.5)))
9192    }
9193}
9194
9195/// [`nanskew`] as pandas' grouped skew: [`SkewMoments`] over the present
9196/// values.
9197#[must_use]
9198pub fn nanskew_grouped(values: &[Scalar]) -> Scalar {
9199    let mut moments = SkewMoments::default();
9200    for value in values {
9201        if value.is_missing() {
9202            continue;
9203        }
9204        if let Ok(x) = value.to_f64() {
9205            moments.add(x);
9206        }
9207    }
9208    moments
9209        .skew()
9210        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9211}
9212
9213/// The present values' Welford moments, as [`nanvar_grouped`] reads them.
9214fn grouped_moments(values: &[Scalar]) -> WelfordVar {
9215    let mut moments = WelfordVar::default();
9216    for value in values {
9217        if value.is_missing() {
9218            continue;
9219        }
9220        if let Ok(x) = value.to_f64() {
9221            moments.add(x);
9222        }
9223    }
9224    moments
9225}
9226
9227/// [`nansum`] as pandas' groupby / resample / pivot_table add floats: the
9228/// compensated [`KahanSum`] (br-frankenpandas-xhogl). Timedelta input keeps
9229/// [`nansum`]'s exact integer sum.
9230#[must_use]
9231pub fn nansum_grouped(values: &[Scalar]) -> Scalar {
9232    if collect_timedelta_ns(values).is_some() {
9233        return nansum(values);
9234    }
9235    let mut sum = KahanSum::default();
9236    for value in values {
9237        if value.is_missing() {
9238            continue;
9239        }
9240        if let Ok(x) = value.to_f64() {
9241            sum.add(x);
9242        }
9243    }
9244    Scalar::Float64(sum.sum())
9245}
9246
9247/// [`nanmean`] as pandas' grouped mean: the [`KahanSum`] over the count.
9248/// Temporal input keeps [`nanmean`].
9249#[must_use]
9250pub fn nanmean_grouped(values: &[Scalar]) -> Scalar {
9251    if collect_timedelta_ns(values).is_some() || collect_datetime_ns(values).is_some() {
9252        return nanmean(values);
9253    }
9254    let mut sum = KahanSum::default();
9255    let mut count = 0_usize;
9256    for value in values {
9257        if value.is_missing() {
9258            continue;
9259        }
9260        if let Ok(x) = value.to_f64() {
9261            sum.add(x);
9262            count += 1;
9263        }
9264    }
9265    if count == 0 {
9266        return Scalar::Null(NullKind::NaN);
9267    }
9268    Scalar::Float64(sum.sum() / count as f64)
9269}
9270
9271/// [`nanvar`] as pandas' grouped var: [`WelfordVar`]. Timedelta input keeps
9272/// [`nanvar`].
9273#[must_use]
9274pub fn nanvar_grouped(values: &[Scalar], ddof: usize) -> Scalar {
9275    if collect_timedelta_ns_f64(values).is_some() {
9276        return nanvar(values, ddof);
9277    }
9278    grouped_moments(values)
9279        .var(ddof)
9280        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9281}
9282
9283/// [`nanstd`] as pandas' grouped std: [`WelfordVar`]. Temporal input keeps
9284/// [`nanstd`].
9285#[must_use]
9286pub fn nanstd_grouped(values: &[Scalar], ddof: usize) -> Scalar {
9287    if collect_temporal_backing(values).is_some() {
9288        return nanstd(values, ddof);
9289    }
9290    grouped_moments(values)
9291        .std(ddof)
9292        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9293}
9294
9295/// Peak-to-peak range of non-missing values (max − min).
9296///
9297/// Matches `np.ptp` behavior on nan-safe inputs. Returns `Null(NaN)`
9298/// for empty or all-missing inputs.
9299pub fn nanptp(values: &[Scalar]) -> Scalar {
9300    // br-frankenpandas-axhhk: Datetime64 ptp is NOT a dtype-preserving sibling
9301    // of the Timedelta64 arm below — the span between two instants is a
9302    // DURATION, so pandas returns a Timedelta here (`s.max() - s.min()` on a
9303    // datetime64 Series). Subtract in i128 and narrow through the shared
9304    // opz27 helper so an unrepresentable span becomes NaT rather than a
9305    // fabricated extreme. Previously to_f64() errored on every element, `seen`
9306    // stayed false, and this returned Null(NaN).
9307    if is_datetime_input(values) {
9308        let (mut lo, mut hi) = (i64::MAX, i64::MIN);
9309        for value in values {
9310            if value.is_missing() {
9311                continue;
9312            }
9313            if let Scalar::Datetime64(ns) = value {
9314                lo = lo.min(*ns);
9315                hi = hi.max(*ns);
9316            }
9317        }
9318        return timedelta_ns_to_scalar(i128::from(hi) - i128::from(lo));
9319    }
9320    // Preserve every nanosecond in the uniformly-Timedelta64 case. Converting
9321    // to f64 before subtracting loses ranges below one f64 ULP beyond 104 days.
9322    // The Scalar fallback below retains mixed-family behavior.
9323    let (mut td_lo, mut td_hi) = (i64::MAX, i64::MIN);
9324    let mut saw_timedelta = false;
9325    let mut all_timedelta = true;
9326    for value in values {
9327        if value.is_missing() {
9328            continue;
9329        }
9330        match value {
9331            Scalar::Timedelta64(ns) => {
9332                saw_timedelta = true;
9333                td_lo = td_lo.min(*ns);
9334                td_hi = td_hi.max(*ns);
9335            }
9336            _ => {
9337                all_timedelta = false;
9338                break;
9339            }
9340        }
9341    }
9342    if all_timedelta && saw_timedelta {
9343        // Subtract in i128: the true range of two representable Timedeltas can
9344        // exceed i64 (max - min overflows), where live pandas 2.2.3 raises
9345        // OverflowError. Saturating here fabricated a finite Timedelta.max.
9346        return timedelta_ns_to_scalar(i128::from(td_hi) - i128::from(td_lo));
9347    }
9348    // Fused single-pass min/max (see `nansum`): track lo/hi while filtering, no
9349    // intermediate Vec<f64>. Bit-identical to the prior collect_finite two-pass:
9350    // `seen` is true exactly when collect_finite would be non-empty, and the
9351    // lo/hi comparisons fold the same finite values in the same order.
9352    let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
9353    let mut seen = false;
9354    for v in values {
9355        if v.is_missing() {
9356            continue;
9357        }
9358        if let Ok(x) = v.to_f64() {
9359            seen = true;
9360            if x < lo {
9361                lo = x;
9362            }
9363            if x > hi {
9364                hi = x;
9365            }
9366        }
9367    }
9368    if !seen {
9369        return Scalar::Null(NullKind::NaN);
9370    }
9371    Scalar::Float64(hi - lo)
9372}
9373
9374/// Sample skewness (bias-corrected, Fisher-Pearson) over non-missing values.
9375///
9376/// Matches `pd.Series.skew()`. Requires at least 3 non-missing values;
9377/// returns `Null(NaN)` otherwise, and when the sample standard deviation
9378/// is zero.
9379pub fn nanskew(values: &[Scalar]) -> Scalar {
9380    let nums = collect_finite(values);
9381    let n = nums.len() as f64;
9382    if n < 3.0 {
9383        return Scalar::Null(NullKind::NaN);
9384    }
9385    let mean = nums.iter().sum::<f64>() / n;
9386    // Accumulate both central moments while the collected values are hot. Each
9387    // sum still observes the same terms in the same order as the former two
9388    // iterator passes, preserving floating-point results bit-for-bit.
9389    let (mut m2, mut m3) = (0.0_f64, 0.0_f64);
9390    for x in nums {
9391        let delta = x - mean;
9392        // d2 reuse: 2 multiplies per element instead of 3. powi(3) lowers to two
9393        // multiplies of {delta, delta*delta}, and float MULTIPLY is commutative
9394        // bit-for-bit, so both sums observe the identical terms — the comment above
9395        // about preserving results bit-for-bit still holds. No ADDITION order changed.
9396        // (br-frankenpandas-8s4mb)
9397        let d2 = delta * delta;
9398        m2 += d2;
9399        m3 += d2 * delta;
9400    }
9401    let s2 = m2 / (n - 1.0);
9402    if s2 == 0.0 {
9403        return Scalar::Float64(0.0);
9404    }
9405    let s3 = s2.powf(1.5);
9406    Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
9407}
9408
9409/// Excess sample kurtosis (Fisher's definition, bias-corrected) over
9410/// non-missing values.
9411///
9412/// Matches `pd.Series.kurt()`. Requires at least 4 non-missing values;
9413/// returns `Null(NaN)` otherwise, and when the sample standard deviation
9414/// is zero.
9415pub fn nankurt(values: &[Scalar]) -> Scalar {
9416    let nums = collect_finite(values);
9417    let n = nums.len() as f64;
9418    if n < 4.0 {
9419        return Scalar::Null(NullKind::NaN);
9420    }
9421    let mean = nums.iter().sum::<f64>() / n;
9422    // Accumulate both central moments while the collected values are hot. Each
9423    // sum still observes the same terms in the same order as the former two
9424    // iterator passes, preserving floating-point results bit-for-bit.
9425    let (mut m2, mut m4) = (0.0_f64, 0.0_f64);
9426    for x in nums {
9427        let delta = x - mean;
9428        // d2 reuse; see `nanskew`. powi(4) lowers to (d*d)*(d*d), which is exactly
9429        // d2 * d2, so this is bit-identical.
9430        let d2 = delta * delta;
9431        m2 += d2;
9432        m4 += d2 * d2;
9433    }
9434    let s2 = m2 / (n - 1.0);
9435    if s2 == 0.0 {
9436        return Scalar::Float64(0.0);
9437    }
9438    let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
9439    let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
9440    Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
9441}
9442
9443/// Product of non-missing values. Returns 1.0 for empty input (matching pandas).
9444pub fn nanprod(values: &[Scalar]) -> Scalar {
9445    // Per br-frankenpandas-szq6a: pandas raises TypeError on
9446    // td_series.prod() because Timedelta² has no dimension. Returning the
9447    // misleading Float64(1.0) (empty-iterator default after collect_finite
9448    // drops every Timedelta64) is worse than surfacing missing. NaT
9449    // propagates the "type-incompatible" signal in lieu of a Result-level
9450    // error.
9451    if is_timedelta_input(values) {
9452        return Scalar::Null(NullKind::NaN);
9453    }
9454    // Fused single-pass fold (see `nansum`): filter missing / non-coercible and
9455    // multiply in one scan, no intermediate Vec<f64>. Bit-identical to
9456    // `collect_finite(..).iter().product()`: same finite values, same order,
9457    // same f64 `*` (Product for f64 == fold(1.0, *)); empty -> 1.0.
9458    let mut prod = 1.0_f64;
9459    for v in values {
9460        if v.is_missing() {
9461            continue;
9462        }
9463        if let Ok(x) = v.to_f64() {
9464            prod *= x;
9465        }
9466    }
9467    Scalar::Float64(prod)
9468}
9469
9470/// Cumulative sum respecting null propagation.
9471///
9472/// Per br-frankenpandas-x0x91: detect uniformly-Timedelta64 input
9473/// (allowing Null/NAT missing markers). Returns true when at least one
9474/// non-missing value is Timedelta64 and no other dtype appears.
9475fn is_timedelta_input(values: &[Scalar]) -> bool {
9476    let mut saw_td = false;
9477    for v in values {
9478        if v.is_missing() {
9479            continue;
9480        }
9481        match v {
9482            Scalar::Timedelta64(_) => saw_td = true,
9483            _ => return false,
9484        }
9485    }
9486    saw_td
9487}
9488
9489/// Datetime64 mirror of [`collect_timedelta_ns`], per br-frankenpandas-adv58.
9490///
9491/// Note the deliberate difference from [`is_datetime_input`]: the family is
9492/// marked on seeing the *variant*, before the missing check, so an ALL-NaT
9493/// datetime input still reports as the Datetime family with `count == 0`. That
9494/// is what lets `nanmean` return `Datetime64(NaT)` — preserving dtype the way
9495/// pandas does — instead of degrading to a numeric NaN. `collect_timedelta_ns`
9496/// has used this convention all along; matching it keeps the two families
9497/// symmetric.
9498fn collect_datetime_ns(values: &[Scalar]) -> Option<(i128, usize)> {
9499    let mut sum: i128 = 0;
9500    let mut count: usize = 0;
9501    let mut saw_datetime = false;
9502    for v in values {
9503        match v {
9504            Scalar::Datetime64(ns) => {
9505                saw_datetime = true;
9506                if v.is_missing() {
9507                    continue;
9508                }
9509                sum += i128::from(*ns);
9510                count += 1;
9511            }
9512            _ if v.is_missing() => continue,
9513            _ => return None,
9514        }
9515    }
9516    if saw_datetime {
9517        Some((sum, count))
9518    } else {
9519        None
9520    }
9521}
9522
9523/// Sibling of [`is_timedelta_input`] for Datetime64, per br-frankenpandas-axhhk.
9524///
9525/// `Datetime64::to_f64()` errors exactly like `Timedelta64::to_f64()` does, so
9526/// every reduction that routed datetimes through the f64 catch-all silently
9527/// produced `Null(NaN)`. Datetime64 orders exactly like its i64 nanosecond
9528/// backing, and NaT (`Timestamp::NAT`) is already filtered by `is_missing`.
9529fn is_datetime_input(values: &[Scalar]) -> bool {
9530    let mut saw_dt = false;
9531    for v in values {
9532        if v.is_missing() {
9533            continue;
9534        }
9535        match v {
9536            Scalar::Datetime64(_) => saw_dt = true,
9537            _ => return false,
9538        }
9539    }
9540    saw_dt
9541}
9542
9543/// Returns true for uniformly-Int64 input with optional missing markers.
9544fn is_int64_input(values: &[Scalar]) -> bool {
9545    let mut saw_int = false;
9546    for value in values {
9547        if value.is_missing() {
9548            continue;
9549        }
9550        match value {
9551            Scalar::Int64(_) => saw_int = true,
9552            _ => return false,
9553        }
9554    }
9555    saw_int
9556}
9557
9558/// First-position arg-extremum over a uniformly i64-backed scalar family.
9559/// True when every non-missing value is an Interval, per br-frankenpandas-2h9dm.
9560fn is_interval_input(values: &[Scalar]) -> bool {
9561    let mut saw_interval = false;
9562    for v in values {
9563        if v.is_missing() {
9564            continue;
9565        }
9566        match v {
9567            Scalar::Interval(_) => saw_interval = true,
9568            _ => return false,
9569        }
9570    }
9571    saw_interval
9572}
9573
9574/// Positional extreme over a uniformly-Interval input, per br-frankenpandas-2h9dm.
9575///
9576/// Intervals cannot use [`nanarg_i64`] (they are two f64s, not an i64 newtype)
9577/// and cannot use the f64 fallback in the callers (`to_f64` errors on them), so
9578/// they get this dedicated lexicographic (left, right) walk. `closed` is not
9579/// part of the comparison, for the reasons documented on `nanmin`.
9580///
9581/// Returns `None` if any bound is NaN: such an interval is not orderable and
9582/// pandas will not even construct one, so an arbitrary index would be worse
9583/// than declining. This is also why the comparison is a plain `<`/`>` on a
9584/// tuple rather than `partial_cmp().unwrap()`, which would panic.
9585fn nanarg_interval(values: &[Scalar], find_max: bool) -> Option<usize> {
9586    let mut best: Option<(usize, (f64, f64))> = None;
9587    for (index, value) in values.iter().enumerate() {
9588        if value.is_missing() {
9589            continue;
9590        }
9591        let Scalar::Interval(iv) = value else {
9592            continue;
9593        };
9594        if iv.left.is_nan() || iv.right.is_nan() {
9595            return None;
9596        }
9597        let key = (iv.left, iv.right);
9598        match best {
9599            None => best = Some((index, key)),
9600            // Strict comparison keeps the FIRST occurrence of a duplicated
9601            // extreme, which is what pandas' idxmin/idxmax return.
9602            Some((_, current)) if (find_max && key > current) || (!find_max && key < current) => {
9603                best = Some((index, key));
9604            }
9605            _ => {}
9606        }
9607    }
9608    best.map(|(index, _)| index)
9609}
9610
9611fn nanarg_i64(values: &[Scalar], find_max: bool) -> Option<usize> {
9612    let mut best: Option<(usize, i64)> = None;
9613    for (index, value) in values.iter().enumerate() {
9614        if value.is_missing() {
9615            continue;
9616        }
9617        // br-frankenpandas-axhhk: Datetime64 joins the typed i64 families here.
9618        // Its ns backing orders identically, and routing it through the f64
9619        // path instead returned None for any 2+-element datetime input.
9620        //
9621        // br-frankenpandas-d7zjp: Period cannot join this or-pattern — it is a
9622        // STRUCT, not an i64 newtype — so it contributes its ordinal here. The
9623        // caller has already established a single freq via
9624        // `collect_temporal_backing`, so these ordinals are comparable.
9625        let candidate = match value {
9626            Scalar::Int64(raw) | Scalar::Timedelta64(raw) | Scalar::Datetime64(raw) => raw,
9627            Scalar::Period(p) => &p.ordinal,
9628            _ => continue,
9629        };
9630        match best {
9631            None => best = Some((index, *candidate)),
9632            Some((_, current))
9633                if (find_max && *candidate > current) || (!find_max && *candidate < current) =>
9634            {
9635                best = Some((index, *candidate));
9636            }
9637            _ => {}
9638        }
9639    }
9640    best.map(|(index, _)| index)
9641}
9642
9643/// Per br-frankenpandas-x0x91: cumulative running aggregation over a
9644/// uniformly-Timedelta64 input. NaT/Null positions emit NaT and skip
9645/// the accumulator. Saturating i128 keeps overflow contained at i64
9646/// bounds when emitting.
9647fn timedelta_cumulative<F>(values: &[Scalar], init: i128, mut step: F) -> Vec<Scalar>
9648where
9649    F: FnMut(i128, i128) -> i128,
9650{
9651    let mut out = Vec::with_capacity(values.len());
9652    let mut running: i128 = init;
9653    for v in values {
9654        if v.is_missing() {
9655            out.push(Scalar::Null(NullKind::NaT));
9656            continue;
9657        }
9658        if let Scalar::Timedelta64(ns) = v {
9659            // `running` is exact: i128 has enough headroom that folding i64
9660            // nanoseconds cannot overflow it for any constructible input. Only
9661            // the narrowing to the output element can fail, so a running sum
9662            // that overflows i64 and later returns to range emits its true
9663            // value again instead of poisoning the tail — nothing is
9664            // fabricated at any index.
9665            running = step(running, i128::from(*ns));
9666            out.push(timedelta_ns_to_scalar(running));
9667        } else {
9668            out.push(Scalar::Null(NullKind::NaT));
9669        }
9670    }
9671    out
9672}
9673
9674/// Per br-frankenpandas-x0x91: running extrema (min/max) over a
9675/// uniformly-Timedelta64 input. `sentinel` is the identity element
9676/// (i64::MAX for min, i64::MIN for max) used until the first
9677/// non-missing value initializes the accumulator.
9678/// `make` builds the output scalar from the running ns value, so the same
9679/// walk serves Timedelta64 and — per br-frankenpandas-axhhk — Datetime64,
9680/// whose running extrema are Timestamps rather than durations.
9681fn timedelta_cumulative_extrema<F>(
9682    values: &[Scalar],
9683    sentinel: i64,
9684    make: TemporalFamily,
9685    mut step: F,
9686) -> Vec<Scalar>
9687where
9688    F: FnMut(i64, i64) -> i64,
9689{
9690    let mut out = Vec::with_capacity(values.len());
9691    let mut running: Option<i64> = None;
9692    for v in values {
9693        if v.is_missing() {
9694            out.push(Scalar::Null(NullKind::NaT));
9695            continue;
9696        }
9697        // br-frankenpandas-d7zjp: a Period contributes its ordinal.
9698        let raw = match v {
9699            Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
9700            Scalar::Period(p) => Some(p.ordinal),
9701            _ => None,
9702        };
9703        if let Some(ns) = raw.as_ref() {
9704            let new_val = match running {
9705                Some(prev) => step(prev, *ns),
9706                None => *ns,
9707            };
9708            running = Some(new_val);
9709            out.push(make.make(new_val));
9710        } else {
9711            out.push(Scalar::Null(NullKind::NaT));
9712        }
9713    }
9714    let _ = sentinel; // silence unused warning if closure ignores it
9715    out
9716}
9717
9718/// Matches `np.nancumsum` / `pd.Series.cumsum()`. Missing input positions
9719/// pass through as `Null(NaN)` in the output; the running sum ignores
9720/// those positions when accumulating.
9721/// Cumulative sum under an explicit overflow policy.
9722///
9723/// br-frankenpandas-fyr1z-wrap-signoff-s4lkx, DECIDED BY THE MAINTAINER: under
9724/// [`OverflowPolicy::Strict`] this REPRODUCES pandas' silent int64 wraparound,
9725/// because STRICT means bit-for-bit observable parity with the incumbent
9726/// including its quirks.
9727///
9728/// Verified against live pandas 2.2.3:
9729/// `Series([Timedelta.max, Timedelta.max]).cumsum()` returns
9730/// `[9223372036854775807, -2]` and the three-element case
9731/// `[max, -2, 9223372036854775805]` — exactly `wrapping_add` accumulation in
9732/// i64. Note the third element proves the accumulator KEEPS WRAPPING rather
9733/// than sticking: it is `(-2).wrapping_add(max)`.
9734///
9735/// Under every other policy this delegates to [`nancumsum`], which keeps the
9736/// exact-i128 accumulation and NaT-on-unrepresentable behaviour from
9737/// br-frankenpandas-opz27. See DISC-020.
9738#[must_use]
9739pub fn nancumsum_with_policy(values: &[Scalar], policy: OverflowPolicy) -> Vec<Scalar> {
9740    if !matches!(policy, OverflowPolicy::Strict) || !is_timedelta_input(values) {
9741        return nancumsum(values);
9742    }
9743    let mut out = Vec::with_capacity(values.len());
9744    let mut running: i64 = 0;
9745    for value in values {
9746        if value.is_missing() {
9747            out.push(Scalar::Null(NullKind::NaT));
9748            continue;
9749        }
9750        if let Scalar::Timedelta64(ns) = value {
9751            // Deliberately WRAPPING, not checked: this is the incumbent's
9752            // observable behaviour and STRICT exists to reproduce it.
9753            running = running.wrapping_add(*ns);
9754            out.push(Scalar::Timedelta64(running));
9755        } else {
9756            out.push(Scalar::Null(NullKind::NaT));
9757        }
9758    }
9759    out
9760}
9761
9762pub fn nancumsum(values: &[Scalar]) -> Vec<Scalar> {
9763    // Per br-frankenpandas-x0x91: when input is uniformly Timedelta64 (with
9764    // optional NaT/Null missing markers), preserve Timedelta dtype to match
9765    // pandas td_series.cumsum() returning Timedelta64.
9766    if is_timedelta_input(values) {
9767        return timedelta_cumulative(values, 0_i128, |acc, x| acc.saturating_add(x));
9768    }
9769    let mut out = Vec::with_capacity(values.len());
9770    let mut running = 0.0_f64;
9771    for v in values {
9772        if v.is_missing() {
9773            out.push(Scalar::Null(NullKind::NaN));
9774            continue;
9775        }
9776        match v.to_f64() {
9777            Ok(x) if !x.is_nan() => {
9778                running += x;
9779                out.push(Scalar::Float64(running));
9780            }
9781            _ => out.push(Scalar::Null(NullKind::NaN)),
9782        }
9783    }
9784    out
9785}
9786
9787/// Cumulative product respecting null propagation.
9788///
9789/// Matches `np.nancumprod` / `pd.Series.cumprod()`. Missing positions
9790/// pass through as `Null(NaN)` without advancing the running product.
9791pub fn nancumprod(values: &[Scalar]) -> Vec<Scalar> {
9792    let mut out = Vec::with_capacity(values.len());
9793    let mut running = 1.0_f64;
9794    for v in values {
9795        if v.is_missing() {
9796            out.push(Scalar::Null(NullKind::NaN));
9797            continue;
9798        }
9799        match v.to_f64() {
9800            Ok(x) if !x.is_nan() => {
9801                running *= x;
9802                out.push(Scalar::Float64(running));
9803            }
9804            _ => out.push(Scalar::Null(NullKind::NaN)),
9805        }
9806    }
9807    out
9808}
9809
9810/// Cumulative maximum respecting null propagation.
9811///
9812/// Matches `pd.Series.cummax()`. Missing positions pass through as
9813/// `Null(NaN)` without updating the running maximum. The first
9814/// non-missing value initializes the running maximum.
9815pub fn nancummax(values: &[Scalar]) -> Vec<Scalar> {
9816    // Per br-frankenpandas-x0x91 (Timedelta64), -axhhk (Datetime64) and
9817    // -d7zjp (Period): every uniformly-temporal family preserves its dtype
9818    // here. Without this the f64 path below errors on every element and
9819    // produces an all-NaN column. A mixed-freq Period input is not one family,
9820    // so it correctly does not take this path.
9821    if let Some((_, family)) = collect_temporal_backing(values) {
9822        return timedelta_cumulative_extrema(values, i64::MAX, family, |acc, x| acc.max(x));
9823    }
9824    let mut out = Vec::with_capacity(values.len());
9825    let mut running: Option<f64> = None;
9826    for v in values {
9827        if v.is_missing() {
9828            out.push(Scalar::Null(NullKind::NaN));
9829            continue;
9830        }
9831        match v.to_f64() {
9832            Ok(x) if !x.is_nan() => {
9833                let new_val = match running {
9834                    Some(prev) => prev.max(x),
9835                    None => x,
9836                };
9837                running = Some(new_val);
9838                out.push(Scalar::Float64(new_val));
9839            }
9840            _ => out.push(Scalar::Null(NullKind::NaN)),
9841        }
9842    }
9843    out
9844}
9845
9846/// Cumulative minimum respecting null propagation.
9847///
9848/// Matches `pd.Series.cummin()`. Symmetric to `nancummax`.
9849pub fn nancummin(values: &[Scalar]) -> Vec<Scalar> {
9850    // Per br-frankenpandas-x0x91: Timedelta64 preserves dtype.
9851    if is_timedelta_input(values) {
9852        return timedelta_cumulative_extrema(
9853            values,
9854            i64::MIN,
9855            TemporalFamily::Timedelta,
9856            |acc, x| acc.min(x),
9857        );
9858    }
9859    // br-frankenpandas-axhhk / -d7zjp: Datetime64 and Period siblings.
9860    if let Some((_, family)) = collect_temporal_backing(values) {
9861        return timedelta_cumulative_extrema(values, i64::MIN, family, |acc, x| acc.min(x));
9862    }
9863    let mut out = Vec::with_capacity(values.len());
9864    let mut running: Option<f64> = None;
9865    for v in values {
9866        if v.is_missing() {
9867            out.push(Scalar::Null(NullKind::NaN));
9868            continue;
9869        }
9870        match v.to_f64() {
9871            Ok(x) if !x.is_nan() => {
9872                let new_val = match running {
9873                    Some(prev) => prev.min(x),
9874                    None => x,
9875                };
9876                running = Some(new_val);
9877                out.push(Scalar::Float64(new_val));
9878            }
9879            _ => out.push(Scalar::Null(NullKind::NaN)),
9880        }
9881    }
9882    out
9883}
9884
9885/// Linear-interpolation quantile over non-missing numeric values.
9886///
9887/// Matches `np.nanquantile(values, q)` with `interpolation='linear'`.
9888/// Returns `Null(NaN)` for empty inputs or when `q` is outside
9889/// `[0.0, 1.0]`.
9890pub fn nanquantile(values: &[Scalar], q: f64) -> Scalar {
9891    if !(0.0..=1.0).contains(&q) {
9892        return Scalar::Null(NullKind::NaN);
9893    }
9894    // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
9895    // Timedelta64 with linear-interpolated ns. Was silently NaN before.
9896    if let Some((mut td, make)) = collect_temporal_backing(values) {
9897        if td.is_empty() {
9898            return make.nat();
9899        }
9900        let n = td.len();
9901        if n == 1 {
9902            return float_ns_to_temporal(td[0], make);
9903        }
9904        let pos = q * (n - 1) as f64;
9905        let lo = pos.floor() as usize;
9906        let hi = pos.ceil() as usize;
9907        // O(n) selection instead of a full sort (see the numeric arm below):
9908        // select the lo-th order statistic; the (lo+1)-th is the MIN of the
9909        // right partition. Bit-identical (finite ns, values-only order stats).
9910        let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9911        let (_left, lo_ref, right) = td.select_nth_unstable_by(lo, cmp);
9912        let lo_val = *lo_ref;
9913        let ns = if lo == hi {
9914            lo_val
9915        } else {
9916            let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9917            let weight = pos - lo as f64;
9918            lo_val + (hi_val - lo_val) * weight
9919        };
9920        return float_ns_to_temporal(ns, make);
9921    }
9922    let mut nums = collect_finite(values);
9923    if nums.is_empty() {
9924        return Scalar::Null(NullKind::NaN);
9925    }
9926    let n = nums.len();
9927    if n == 1 {
9928        return Scalar::Float64(nums[0]);
9929    }
9930    let pos = q * (n - 1) as f64;
9931    let lo = pos.floor() as usize;
9932    let hi = pos.ceil() as usize;
9933    // O(n) selection instead of a full sort: select the `lo`-th order statistic;
9934    // when interpolation is needed (hi == lo+1) the (lo+1)-th smallest is the
9935    // MIN of the right partition. Bit-identical to the sort path (same
9936    // nums[lo]/nums[hi] values, since order statistics depend only on values).
9937    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9938    let (_left, lo_ref, right) = nums.select_nth_unstable_by(lo, cmp);
9939    let lo_val = *lo_ref;
9940    if lo == hi {
9941        return Scalar::Float64(lo_val);
9942    }
9943    let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9944    let weight = pos - lo as f64;
9945    Scalar::Float64(lo_val + (hi_val - lo_val) * weight)
9946}
9947
9948/// Position (in the original slice) of the non-missing maximum.
9949///
9950/// Matches `np.nanargmax`. Returns `None` if every value is missing.
9951/// Ties resolve to the first position seen (matching numpy).
9952pub fn nanargmax(values: &[Scalar]) -> Option<usize> {
9953    // Compare typed 64-bit families directly: f64 coercion loses ordering for
9954    // adjacent Int64 values beyond the 53-bit exactness boundary.
9955    // br-frankenpandas-axhhk: Datetime64 belongs here too — it not only loses
9956    // ordering under f64, its to_f64() errors outright, so it returned None.
9957    if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9958        return nanarg_i64(values, true);
9959    }
9960    // br-frankenpandas-2h9dm: Intervals order lexicographically by
9961    // (left, right) and fit neither the i64 walk above nor the f64 fallback
9962    // below, whose to_f64() errors on them — so they returned None.
9963    if is_interval_input(values) {
9964        return nanarg_interval(values, true);
9965    }
9966    let mut best: Option<(usize, f64)> = None;
9967    for (i, v) in values.iter().enumerate() {
9968        if v.is_missing() {
9969            continue;
9970        }
9971        if let Ok(x) = v.to_f64() {
9972            if x.is_nan() {
9973                continue;
9974            }
9975            match best {
9976                None => best = Some((i, x)),
9977                Some((_, cur)) if x > cur => best = Some((i, x)),
9978                _ => {}
9979            }
9980        }
9981    }
9982    best.map(|(i, _)| i)
9983}
9984
9985/// Position (in the original slice) of the non-missing minimum.
9986///
9987/// Matches `np.nanargmin`. Returns `None` if every value is missing.
9988pub fn nanargmin(values: &[Scalar]) -> Option<usize> {
9989    // See nanargmax: preserve exact ordering for typed 64-bit families
9990    // (Datetime64 included, per br-frankenpandas-axhhk).
9991    if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9992        return nanarg_i64(values, false);
9993    }
9994    // br-frankenpandas-2h9dm: Interval sibling of the branch in `nanargmax`.
9995    if is_interval_input(values) {
9996        return nanarg_interval(values, false);
9997    }
9998    let mut best: Option<(usize, f64)> = None;
9999    for (i, v) in values.iter().enumerate() {
10000        if v.is_missing() {
10001            continue;
10002        }
10003        if let Ok(x) = v.to_f64() {
10004            if x.is_nan() {
10005                continue;
10006            }
10007            match best {
10008                None => best = Some((i, x)),
10009                Some((_, cur)) if x < cur => best = Some((i, x)),
10010                _ => {}
10011            }
10012        }
10013    }
10014    best.map(|(i, _)| i)
10015}
10016
10017/// Count of unique non-missing values.
10018pub fn nannunique(values: &[Scalar]) -> Scalar {
10019    use rustc_hash::FxHashSet;
10020    #[derive(Hash, PartialEq, Eq)]
10021    enum ScalarKey<'a> {
10022        Bool(bool),
10023        Int64(i64),
10024        FloatBits(u64),
10025        Utf8(&'a str),
10026        Timedelta64(i64),
10027        Datetime64(i64),
10028        Period(i64, PeriodFreq),
10029        Interval(u64, u64, IntervalClosed),
10030        // An object cell counts by its repr (pandas hashes the object; a
10031        // list would be unhashable there).
10032        Object(String),
10033    }
10034
10035    let mut seen = FxHashSet::default();
10036    for val in values {
10037        if val.is_missing() {
10038            continue;
10039        }
10040        let key = match val {
10041            Scalar::Bool(v) => ScalarKey::Bool(*v),
10042            Scalar::Int64(v) => ScalarKey::Int64(*v),
10043            Scalar::Float64(v) => {
10044                let normalized = if *v == 0.0 { 0.0 } else { *v };
10045                ScalarKey::FloatBits(normalized.to_bits())
10046            }
10047            Scalar::Utf8(v) => ScalarKey::Utf8(v.as_str()),
10048            Scalar::Timedelta64(v) => ScalarKey::Timedelta64(*v),
10049            Scalar::Datetime64(v) => ScalarKey::Datetime64(*v),
10050            Scalar::Period(p) => ScalarKey::Period(p.ordinal, p.freq),
10051            Scalar::Interval(v) => ScalarKey::Interval(
10052                normalized_float_bits(v.left),
10053                normalized_float_bits(v.right),
10054                v.closed,
10055            ),
10056            Scalar::Object(object) => ScalarKey::Object(object.repr()),
10057            Scalar::Null(_) => continue,
10058        };
10059        seen.insert(key);
10060    }
10061    Scalar::Int64(seen.len() as i64)
10062}
10063
10064fn normalized_float_bits(value: f64) -> u64 {
10065    let normalized = if value == 0.0 { 0.0 } else { value };
10066    normalized.to_bits()
10067}
10068
10069// ── Interval types (br-frankenpandas-j8k4 Phase 1) ──────────────────────
10070//
10071// Scaffolding for pandas `pd.Interval` / `pd.IntervalIndex` / `pd.IntervalDtype`.
10072//
10073// Phase 1 ships float-valued intervals only (matches `cut`/`qcut` output on
10074// numeric bins — the dominant pandas use case). Generic-subtype intervals
10075// over Int64 / Timestamp are deferred to Phase 2 alongside the DType::Interval
10076// enum-variant wiring. See br-j8k4 for the phased roadmap.
10077//
10078// Semantics mirror pandas: closed tells which endpoints are included.
10079//   Left    → [left, right)
10080//   Right   → (left, right]       ← pandas default
10081//   Both    → [left, right]
10082//   Neither → (left, right)
10083
10084/// Endpoint-inclusion policy for an `Interval`.
10085///
10086/// Matches pandas `pd.Interval.closed` / `pd.IntervalDtype.closed` string
10087/// values ("left" / "right" / "both" / "neither").
10088#[derive(
10089    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
10090)]
10091#[serde(rename_all = "snake_case")]
10092#[non_exhaustive]
10093pub enum IntervalClosed {
10094    /// `[left, right)` — left-inclusive, right-exclusive.
10095    Left,
10096    /// `(left, right]` — left-exclusive, right-inclusive. Pandas default.
10097    #[default]
10098    Right,
10099    /// `[left, right]` — both endpoints included.
10100    Both,
10101    /// `(left, right)` — neither endpoint included.
10102    Neither,
10103}
10104
10105impl IntervalClosed {
10106    /// Left endpoint included?
10107    #[must_use]
10108    pub const fn left_closed(self) -> bool {
10109        matches!(self, Self::Left | Self::Both)
10110    }
10111
10112    /// Right endpoint included?
10113    #[must_use]
10114    pub const fn right_closed(self) -> bool {
10115        matches!(self, Self::Right | Self::Both)
10116    }
10117}
10118
10119impl std::fmt::Display for IntervalClosed {
10120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10121        match self {
10122            Self::Left => write!(f, "left"),
10123            Self::Right => write!(f, "right"),
10124            Self::Both => write!(f, "both"),
10125            Self::Neither => write!(f, "neither"),
10126        }
10127    }
10128}
10129
10130/// The type of an interval's endpoints, pandas' `interval[int64]` or
10131/// `interval[float64]` subtype: integer endpoints print without '.0'
10132/// (`pd.cut(s, [0, 3, 6])` is `(0, 3]`, where float edges are `(0.0, 3.0]`).
10133/// The endpoints themselves are `f64` either way (fvsao.54).
10134#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
10135#[serde(rename_all = "snake_case")]
10136pub enum IntervalSubtype {
10137    #[default]
10138    Float64,
10139    Int64,
10140}
10141
10142impl IntervalSubtype {
10143    /// Whether this is the float subtype (serde skips it, the default).
10144    #[must_use]
10145    pub const fn is_float(&self) -> bool {
10146        matches!(self, Self::Float64)
10147    }
10148
10149    /// The subtype's dtype name ('int64' / 'float64').
10150    #[must_use]
10151    pub const fn name(&self) -> &'static str {
10152        match self {
10153            Self::Float64 => "float64",
10154            Self::Int64 => "int64",
10155        }
10156    }
10157}
10158
10159/// A bounded numeric interval between two `f64` endpoints.
10160///
10161/// Matches `pd.Interval(left, right, closed)` on the numeric-subtype path.
10162/// Accessors match pandas: `.left`, `.right`, `.closed`, `.length`, `.mid`,
10163/// `.contains`, `.is_empty`, `.overlaps`. Equality ignores the `subtype`, as
10164/// pandas' `Interval(0, 3) == Interval(0.0, 3.0)`.
10165#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
10166pub struct Interval {
10167    pub left: f64,
10168    pub right: f64,
10169    #[serde(default)]
10170    pub closed: IntervalClosed,
10171    /// The endpoints' type as pandas reports and prints it.
10172    #[serde(default, skip_serializing_if = "IntervalSubtype::is_float")]
10173    pub subtype: IntervalSubtype,
10174}
10175
10176impl PartialEq for Interval {
10177    fn eq(&self, other: &Self) -> bool {
10178        self.left == other.left && self.right == other.right && self.closed == other.closed
10179    }
10180}
10181
10182/// An interval as a label (an IntervalIndex's; br-frankenpandas-c27hq): its
10183/// endpoints compare as floats, so only an interval with a NaN endpoint,
10184/// which pandas never builds, is unequal to itself.
10185impl Eq for Interval {}
10186
10187impl Interval {
10188    /// An endpoint as it compares: -0.0 is 0.0, as `==` has it.
10189    fn endpoint_key(value: f64) -> f64 {
10190        if value == 0.0 { 0.0 } else { value }
10191    }
10192}
10193
10194/// Hashed as it compares: the endpoints (-0.0 as 0.0) and the closed side;
10195/// the subtype is not part of the value.
10196impl std::hash::Hash for Interval {
10197    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
10198        Self::endpoint_key(self.left).to_bits().hash(state);
10199        Self::endpoint_key(self.right).to_bits().hash(state);
10200        self.closed.hash(state);
10201    }
10202}
10203
10204/// pandas' IntervalIndex order: by the left endpoint, then the right, then
10205/// the closed side.
10206impl Ord for Interval {
10207    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
10208        Self::endpoint_key(self.left)
10209            .total_cmp(&Self::endpoint_key(other.left))
10210            .then_with(|| {
10211                Self::endpoint_key(self.right).total_cmp(&Self::endpoint_key(other.right))
10212            })
10213            .then_with(|| self.closed.cmp(&other.closed))
10214    }
10215}
10216
10217impl PartialOrd for Interval {
10218    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
10219        Some(self.cmp(other))
10220    }
10221}
10222
10223impl Interval {
10224    /// Construct an interval. No validation on `left <= right` — pandas also
10225    /// accepts reversed intervals (they're non-empty only if empty-by-design).
10226    #[must_use]
10227    pub const fn new(left: f64, right: f64, closed: IntervalClosed) -> Self {
10228        Self {
10229            left,
10230            right,
10231            closed,
10232            subtype: IntervalSubtype::Float64,
10233        }
10234    }
10235
10236    /// This interval with integer endpoints (pandas' `interval[int64]`)
10237    /// when both are whole numbers; unchanged otherwise.
10238    #[must_use]
10239    pub fn with_int_endpoints(self) -> Self {
10240        if self.left.fract() == 0.0 && self.right.fract() == 0.0 {
10241            Self {
10242                subtype: IntervalSubtype::Int64,
10243                ..self
10244            }
10245        } else {
10246            self
10247        }
10248    }
10249
10250    /// `right - left` (pandas `.length`). Negative for reversed intervals.
10251    #[must_use]
10252    pub fn length(&self) -> f64 {
10253        self.right - self.left
10254    }
10255
10256    /// Midpoint `(left + right) / 2` (pandas `.mid`).
10257    #[must_use]
10258    pub fn mid(&self) -> f64 {
10259        (self.left + self.right) / 2.0
10260    }
10261
10262    /// Empty iff endpoints coincide AND at least one side is open.
10263    /// Pandas semantics: `pd.Interval(3, 3, 'right').is_empty → True`.
10264    #[must_use]
10265    pub fn is_empty(&self) -> bool {
10266        self.left == self.right && !matches!(self.closed, IntervalClosed::Both)
10267    }
10268
10269    /// Whether the interval is closed on the left side (`pd.Interval.closed_left`).
10270    #[must_use]
10271    pub const fn closed_left(&self) -> bool {
10272        self.closed.left_closed()
10273    }
10274
10275    /// Whether the interval is closed on the right side (`pd.Interval.closed_right`).
10276    #[must_use]
10277    pub const fn closed_right(&self) -> bool {
10278        self.closed.right_closed()
10279    }
10280
10281    /// Whether the interval is open on the left side (`pd.Interval.open_left`).
10282    #[must_use]
10283    pub const fn open_left(&self) -> bool {
10284        !self.closed.left_closed()
10285    }
10286
10287    /// Whether the interval is open on the right side (`pd.Interval.open_right`).
10288    #[must_use]
10289    pub const fn open_right(&self) -> bool {
10290        !self.closed.right_closed()
10291    }
10292
10293    /// Does `value` fall inside this interval?
10294    ///
10295    /// NaN always returns false, matching pandas `pd.Interval.__contains__`
10296    /// behavior (NaN doesn't compare equal to anything).
10297    #[must_use]
10298    pub fn contains(&self, value: f64) -> bool {
10299        if value.is_nan() {
10300            return false;
10301        }
10302        let left_ok = if self.closed.left_closed() {
10303            value >= self.left
10304        } else {
10305            value > self.left
10306        };
10307        let right_ok = if self.closed.right_closed() {
10308            value <= self.right
10309        } else {
10310            value < self.right
10311        };
10312        left_ok && right_ok
10313    }
10314
10315    /// Do `self` and `other` share any point?
10316    ///
10317    /// Matches `pd.Interval.overlaps(other)`. Two intervals overlap iff the
10318    /// max of their lefts is less than the min of their rights, with
10319    /// endpoint-inclusion determining the strictness of the comparison when
10320    /// they touch exactly.
10321    #[must_use]
10322    pub fn overlaps(&self, other: &Self) -> bool {
10323        if self.left > other.right || other.left > self.right {
10324            return false;
10325        }
10326        // Touching-at-a-point: overlap iff both sides at that touchpoint are closed.
10327        if self.right == other.left {
10328            return self.closed.right_closed() && other.closed.left_closed();
10329        }
10330        if other.right == self.left {
10331            return other.closed.right_closed() && self.closed.left_closed();
10332        }
10333        true
10334    }
10335
10336    /// Parse an interval string. Supports bracket notation:
10337    /// - '[0, 1]' -> closed on both ends
10338    /// - '(0, 1)' -> open on both ends
10339    /// - '[0, 1)' -> closed left, open right (pandas default)
10340    /// - '(0, 1]' -> open left, closed right
10341    pub fn parse(s: &str) -> Result<Self, TypeError> {
10342        let s = s.trim();
10343        let (left_closed, after_left) = if let Some(rest) = s.strip_prefix('[') {
10344            (true, rest)
10345        } else if let Some(rest) = s.strip_prefix('(') {
10346            (false, rest)
10347        } else {
10348            return Err(TypeError::ValueNotParseable {
10349                value: s.to_string(),
10350                target: "Interval".to_string(),
10351            });
10352        };
10353
10354        let (right_closed, inner) = if let Some(rest) = after_left.strip_suffix(']') {
10355            (true, rest)
10356        } else if let Some(rest) = after_left.strip_suffix(')') {
10357            (false, rest)
10358        } else {
10359            return Err(TypeError::ValueNotParseable {
10360                value: s.to_string(),
10361                target: "Interval".to_string(),
10362            });
10363        };
10364
10365        let closed = match (left_closed, right_closed) {
10366            (true, true) => IntervalClosed::Both,
10367            (true, false) => IntervalClosed::Left,
10368            (false, true) => IntervalClosed::Right,
10369            (false, false) => IntervalClosed::Neither,
10370        };
10371
10372        let Some((left_text, right_text)) = inner.split_once(',') else {
10373            return Err(TypeError::ValueNotParseable {
10374                value: s.to_string(),
10375                target: "Interval".to_string(),
10376            });
10377        };
10378        if right_text.contains(',') {
10379            return Err(TypeError::ValueNotParseable {
10380                value: s.to_string(),
10381                target: "Interval".to_string(),
10382            });
10383        }
10384
10385        let left: f64 = left_text
10386            .trim()
10387            .parse()
10388            .map_err(|_| TypeError::ValueNotParseable {
10389                value: s.to_string(),
10390                target: "Interval".to_string(),
10391            })?;
10392
10393        let right: f64 = right_text
10394            .trim()
10395            .parse()
10396            .map_err(|_| TypeError::ValueNotParseable {
10397                value: s.to_string(),
10398                target: "Interval".to_string(),
10399            })?;
10400
10401        Ok(Self::new(left, right, closed))
10402    }
10403}
10404
10405impl std::fmt::Display for Interval {
10406    /// Matches `str(pd.Interval(...))`: `interval[float64]` endpoints render
10407    /// with Python `str(float)` semantics, so whole numbers KEEP ".0"
10408    /// (`str(pd.Interval(0.0, 5.0, 'right'))` is `"(0.0, 5.0]"`, not `"(0, 5]"`).
10409    /// Verified vs pandas 2.2.3 across whole/fractional/negative/scientific
10410    /// endpoints. (br-frankenpandas-5xw1b) The `interval[int64]` subtype
10411    /// prints integers (`"(0, 5]"`).
10412    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10413        let left_bracket = if self.closed.left_closed() { '[' } else { '(' };
10414        let right_bracket = if self.closed.right_closed() { ']' } else { ')' };
10415        // The int64 subtype prints its endpoints as integers ('(0, 3]').
10416        #[allow(clippy::cast_possible_truncation)] // whole numbers, checked
10417        let endpoint = |value: f64| match self.subtype {
10418            IntervalSubtype::Int64 if value.fract() == 0.0 => format!("{}", value as i64),
10419            _ => float_to_string_for_astype(value),
10420        };
10421        write!(
10422            f,
10423            "{left_bracket}{}, {}{right_bracket}",
10424            endpoint(self.left),
10425            endpoint(self.right)
10426        )
10427    }
10428}
10429
10430// ── interval_range builders (br-frankenpandas-xaom — Phase 2 of j8k4) ────
10431
10432/// Build `periods` equal-width intervals spanning `[start, end]`.
10433///
10434/// Matches `pd.interval_range(start, end, periods=N, closed=...)` for the
10435/// numeric-subtype case. Returns exactly `periods` intervals; when
10436/// `periods == 0` or `start >= end`, returns an empty vector (matches
10437/// pandas's empty IntervalIndex).
10438///
10439/// ```
10440/// use fp_types::{interval_range_by_periods, IntervalClosed};
10441/// let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
10442/// assert_eq!(bins.len(), 5);
10443/// assert_eq!(bins[0].left, 0.0);
10444/// assert_eq!(bins[0].right, 2.0);
10445/// assert_eq!(bins[4].right, 10.0);
10446/// ```
10447#[must_use]
10448pub fn interval_range_by_periods(
10449    start: f64,
10450    end: f64,
10451    periods: usize,
10452    closed: IntervalClosed,
10453) -> Vec<Interval> {
10454    if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
10455        return Vec::new();
10456    }
10457    let step = (end - start) / (periods as f64);
10458    let mut out = Vec::with_capacity(periods);
10459    for i in 0..periods {
10460        let left = start + step * (i as f64);
10461        // Use end exactly for the final right edge to avoid float drift.
10462        let right = if i + 1 == periods {
10463            end
10464        } else {
10465            start + step * ((i + 1) as f64)
10466        };
10467        out.push(Interval::new(left, right, closed));
10468    }
10469    out
10470}
10471
10472/// Build equal-`step`-width intervals spanning `[start, end]`.
10473///
10474/// Matches `pd.interval_range(start, end, freq=step, closed=...)` for the
10475/// numeric-subtype case. `step` must be finite and positive; `(end - start)`
10476/// must be an integer multiple of `step` (within float tolerance) — pandas
10477/// raises `ValueError` otherwise; this fn returns `Err(TypeError::IntervalStepDoesNotDivide)`.
10478///
10479/// Returns an empty vector when `start == end` (matches pandas' zero-bin
10480/// IntervalIndex); returns an empty vector when `start > end` (pandas also
10481/// returns empty rather than erroring in this case).
10482pub fn interval_range_by_step(
10483    start: f64,
10484    end: f64,
10485    step: f64,
10486    closed: IntervalClosed,
10487) -> Result<Vec<Interval>, TypeError> {
10488    if !step.is_finite() || !step.is_sign_positive() || step == 0.0 {
10489        return Err(TypeError::InvalidIntervalStep { step });
10490    }
10491    if !start.is_finite() || !end.is_finite() || start >= end {
10492        return Ok(Vec::new());
10493    }
10494    let span = end - start;
10495    let periods_f = span / step;
10496    let periods = periods_f.round() as i64;
10497    if periods <= 0 {
10498        return Ok(Vec::new());
10499    }
10500    let reconstructed = step * (periods as f64);
10501    // Relative tolerance: allow float-rounding noise proportional to span.
10502    if (span - reconstructed).abs() > span.abs() * 1e-9 + 1e-12 {
10503        return Err(TypeError::IntervalStepDoesNotDivide { step, span });
10504    }
10505    let periods = periods as usize;
10506    let mut out = Vec::with_capacity(periods);
10507    for i in 0..periods {
10508        let left = start + step * (i as f64);
10509        let right = if i + 1 == periods {
10510            end
10511        } else {
10512            start + step * ((i + 1) as f64)
10513        };
10514        out.push(Interval::new(left, right, closed));
10515    }
10516    Ok(out)
10517}
10518
10519/// Build equal-width intervals spanning a range, matching `pd.interval_range`.
10520///
10521/// Of the four parameters `start`, `end`, `periods`, and `freq`, exactly three must
10522/// be specified (`Some`). `closed` defaults to `IntervalClosed::Right` when `None`.
10523///
10524/// # Errors
10525/// Returns `TypeError::IntervalRangeParameterCount` if not exactly 3 of the 4 parameters
10526/// are specified.
10527/// Returns `TypeError::InvalidIntervalStep` if `freq` is not finite, not positive, or zero.
10528/// Returns `TypeError::IntervalStepDoesNotDivide` if `start`, `end`, and `freq` are given
10529/// but `(end - start)` is not an integer multiple of `freq`.
10530pub fn interval_range(
10531    start: Option<f64>,
10532    end: Option<f64>,
10533    periods: Option<usize>,
10534    freq: Option<f64>,
10535    closed: Option<IntervalClosed>,
10536) -> Result<Vec<Interval>, TypeError> {
10537    let count = usize::from(start.is_some())
10538        + usize::from(end.is_some())
10539        + usize::from(periods.is_some())
10540        + usize::from(freq.is_some());
10541    if count != 3 {
10542        return Err(TypeError::IntervalRangeParameterCount);
10543    }
10544    let closed = closed.unwrap_or(IntervalClosed::Right);
10545
10546    match (start, end, periods, freq) {
10547        (Some(start), Some(end), Some(periods), None) => {
10548            Ok(interval_range_by_periods(start, end, periods, closed))
10549        }
10550        (Some(start), Some(end), None, Some(freq)) => {
10551            interval_range_by_step(start, end, freq, closed)
10552        }
10553        (Some(start), None, Some(periods), Some(freq)) => {
10554            if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10555                return Err(TypeError::InvalidIntervalStep { step: freq });
10556            }
10557            if !start.is_finite() || periods == 0 {
10558                return Ok(Vec::new());
10559            }
10560            let mut out = Vec::with_capacity(periods);
10561            for i in 0..periods {
10562                let left = start + freq * (i as f64);
10563                let right = start + freq * ((i + 1) as f64);
10564                out.push(Interval::new(left, right, closed));
10565            }
10566            Ok(out)
10567        }
10568        (None, Some(end), Some(periods), Some(freq)) => {
10569            if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10570                return Err(TypeError::InvalidIntervalStep { step: freq });
10571            }
10572            if !end.is_finite() || periods == 0 {
10573                return Ok(Vec::new());
10574            }
10575            let start = end - freq * (periods as f64);
10576            let mut out = Vec::with_capacity(periods);
10577            for i in 0..periods {
10578                let left = start + freq * (i as f64);
10579                let right = if i + 1 == periods {
10580                    end
10581                } else {
10582                    start + freq * ((i + 1) as f64)
10583                };
10584                out.push(Interval::new(left, right, closed));
10585            }
10586            Ok(out)
10587        }
10588        _ => Err(TypeError::IntervalRangeParameterCount),
10589    }
10590}
10591
10592// ── Period types (br-frankenpandas-epoj Phase 1) ────────────────────────
10593//
10594// Scaffolding for pandas `pd.Period` / `pd.PeriodIndex` / `pd.PeriodDtype`.
10595//
10596// A Period is a calendar *span* (Q1 2024, Jan 2024, 2024-03-15), distinct
10597// from a Timestamp (an instant). Phase 1 ships the PeriodFreq enum +
10598// Period struct with ordinal-based arithmetic (Period + n, Period - Period),
10599// Display in pandas notation, and parse from standard strings. Calendar-
10600// conversion (ordinal ↔ ymd) and DType::Period wiring land in Phase 2.
10601
10602/// Period frequency code. Matches pandas offset alias core set.
10603///
10604/// The ordinal axis is frequency-specific: for Monthly, ordinal 0 is a
10605/// fixed anchor (pandas uses months since 1970-01). Phase 1 doesn't
10606/// commit to a specific epoch yet — the ordinal scheme is opaque until
10607/// Phase 2 wires calendar arithmetic. What Phase 1 DOES nail down is:
10608/// same-freq Periods compare + subtract; Period + i64 shifts by `n`
10609/// periods of the declared frequency.
10610#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10611#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
10612#[non_exhaustive]
10613pub enum PeriodFreq {
10614    /// `Y-<MON>` / `A` / `Y` — annual periods of a fiscal year ending in the
10615    /// month carried (1-12; `Y` is `Y-DEC`). The ordinal counts fiscal years
10616    /// from 1970: `Period('2024', 'Y-JUN')` spans 2023-07-01..2024-06-30.
10617    Annual(u8),
10618    /// `Q-<MON>` / `Q` — quarters of a fiscal year ending in the month
10619    /// carried (1-12; `Q` is `Q-DEC`): `Period('2025Q1', 'Q-JAN')` spans
10620    /// 2024-02-01..2024-04-30.
10621    Quarterly(u8),
10622    /// `M` — monthly periods.
10623    Monthly,
10624    /// `W-<DAY>` / `W` — weeks ending on the weekday carried (0 = Monday ..
10625    /// 6 = Sunday; `W` is `W-SUN`).
10626    Weekly(u8),
10627    /// `D` — daily periods.
10628    Daily,
10629    /// `B` — business-day periods.
10630    Business,
10631    /// `h` / `H` — hourly periods.
10632    Hourly,
10633    /// `min` / `T` — minutely periods.
10634    Minutely,
10635    /// `s` / `S` — secondly periods.
10636    Secondly,
10637    /// `ms` — millisecond periods. NOT `MS`, which pandas reads as month start.
10638    Milliseconds,
10639    /// `us` / `US` — microsecond periods.
10640    Microseconds,
10641    /// `ns` / `NS` — nanosecond periods.
10642    Nanoseconds,
10643    /// A span of several base periods. Ordinals still count the base unit:
10644    /// `2D` at ordinal 1 starts on 1970-01-02 and covers two days.
10645    Multiple(PeriodMultiple),
10646}
10647
10648/// The finite base of a multiplied frequency. Keeping it separate from
10649/// `PeriodFreq` avoids recursive storage and keeps period scalars `Copy`.
10650#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10651#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
10652enum PeriodUnit {
10653    Annual(u8),
10654    Quarterly(u8),
10655    Monthly,
10656    Weekly(u8),
10657    Daily,
10658    Business,
10659    Hourly,
10660    Minutely,
10661    Secondly,
10662    Milliseconds,
10663    Microseconds,
10664    Nanoseconds,
10665}
10666
10667/// A positive period span, constructed through [`PeriodFreq::with_multiplier`].
10668#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10669#[serde(try_from = "PeriodMultipleRepr")]
10670pub struct PeriodMultiple {
10671    unit: PeriodUnit,
10672    count: i64,
10673}
10674
10675#[derive(Deserialize)]
10676struct PeriodMultipleRepr {
10677    unit: PeriodUnit,
10678    count: i64,
10679}
10680
10681impl TryFrom<PeriodMultipleRepr> for PeriodMultiple {
10682    type Error = &'static str;
10683
10684    fn try_from(value: PeriodMultipleRepr) -> Result<Self, Self::Error> {
10685        if value.count <= 1 {
10686            return Err("a multiplied period frequency must span at least two base periods");
10687        }
10688        Ok(Self {
10689            unit: value.unit,
10690            count: value.count,
10691        })
10692    }
10693}
10694
10695/// The month abbreviations pandas anchors annual / quarterly frequencies on.
10696const PERIOD_MONTHS: [&str; 12] = [
10697    "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
10698];
10699/// The weekday abbreviations pandas anchors weekly frequencies on, Monday 0.
10700const PERIOD_WEEKDAYS: [&str; 7] = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];
10701
10702impl PeriodFreq {
10703    /// `Y` / `Y-DEC`: calendar years.
10704    pub const ANNUAL: Self = Self::Annual(12);
10705    /// `Q` / `Q-DEC`: calendar quarters.
10706    pub const QUARTERLY: Self = Self::Quarterly(12);
10707    /// `W` / `W-SUN`: weeks Monday to Sunday.
10708    pub const WEEKLY: Self = Self::Weekly(6);
10709
10710    /// The frequency of one base period. A multiplied period's ordinal and
10711    /// calendar fields use this unit, independently of its span.
10712    #[must_use]
10713    pub const fn base(self) -> Self {
10714        match self {
10715            Self::Multiple(multiple) => match multiple.unit {
10716                PeriodUnit::Annual(month) => Self::Annual(month),
10717                PeriodUnit::Quarterly(month) => Self::Quarterly(month),
10718                PeriodUnit::Monthly => Self::Monthly,
10719                PeriodUnit::Weekly(day) => Self::Weekly(day),
10720                PeriodUnit::Daily => Self::Daily,
10721                PeriodUnit::Business => Self::Business,
10722                PeriodUnit::Hourly => Self::Hourly,
10723                PeriodUnit::Minutely => Self::Minutely,
10724                PeriodUnit::Secondly => Self::Secondly,
10725                PeriodUnit::Milliseconds => Self::Milliseconds,
10726                PeriodUnit::Microseconds => Self::Microseconds,
10727                PeriodUnit::Nanoseconds => Self::Nanoseconds,
10728            },
10729            base => base,
10730        }
10731    }
10732
10733    /// Number of base periods in the span. Always positive.
10734    #[must_use]
10735    pub const fn multiplier(self) -> i64 {
10736        match self {
10737            Self::Multiple(multiple) => multiple.count,
10738            _ => 1,
10739        }
10740    }
10741
10742    /// Set the span in units of this frequency's base. Zero and negative
10743    /// spans are invalid for periods, and a span of one has the base form.
10744    #[must_use]
10745    pub const fn with_multiplier(self, count: i64) -> Option<Self> {
10746        if count < 1 {
10747            return None;
10748        }
10749        let base = self.base();
10750        if count == 1 {
10751            return Some(base);
10752        }
10753        let unit = match base {
10754            Self::Annual(month) => PeriodUnit::Annual(month),
10755            Self::Quarterly(month) => PeriodUnit::Quarterly(month),
10756            Self::Monthly => PeriodUnit::Monthly,
10757            Self::Weekly(day) => PeriodUnit::Weekly(day),
10758            Self::Daily => PeriodUnit::Daily,
10759            Self::Business => PeriodUnit::Business,
10760            Self::Hourly => PeriodUnit::Hourly,
10761            Self::Minutely => PeriodUnit::Minutely,
10762            Self::Secondly => PeriodUnit::Secondly,
10763            Self::Milliseconds => PeriodUnit::Milliseconds,
10764            Self::Microseconds => PeriodUnit::Microseconds,
10765            Self::Nanoseconds => PeriodUnit::Nanoseconds,
10766            Self::Multiple(_) => return None,
10767        };
10768        Some(Self::Multiple(PeriodMultiple { unit, count }))
10769    }
10770
10771    /// Months a date's month count moves forward to land on its fiscal
10772    /// calendar: a fiscal year ending in month `m` starts in month `m + 1`,
10773    /// so `(months since 1970-01 + shift)` divided by 12 (3) is the annual
10774    /// (quarterly) ordinal. 0 for a year ending in December and for every
10775    /// unanchored frequency.
10776    #[must_use]
10777    pub const fn fiscal_month_shift(self) -> i64 {
10778        match self.base() {
10779            Self::Annual(month) | Self::Quarterly(month) => (12 - (month as i64 % 12)) % 12,
10780            _ => 0,
10781        }
10782    }
10783
10784    /// Days a week starts after the Monday of `W-SUN`'s week: a week ending
10785    /// on weekday `d` (Monday 0) starts on `d + 1`, so `W-MON` weeks start a
10786    /// day later and `W-SAT` ones six days later (a Sunday). 0 for `W-SUN`
10787    /// and every other frequency.
10788    #[must_use]
10789    pub const fn week_start_shift(self) -> i64 {
10790        match self.base() {
10791            Self::Weekly(day) => (day as i64 % 7 + 1) % 7,
10792            _ => 0,
10793        }
10794    }
10795
10796    /// The anchored form `prefix-ANCHOR` of a frequency alias (`Y-JUN`,
10797    /// `Q-JAN`, `W-MON`), with pandas' deprecated `A-` annual spelling.
10798    fn parse_anchored(alias: &str) -> Option<Self> {
10799        let (prefix, anchor) = alias.split_once('-')?;
10800        let month = PERIOD_MONTHS.iter().position(|name| *name == anchor);
10801        let day = PERIOD_WEEKDAYS.iter().position(|name| *name == anchor);
10802        match (prefix, month, day) {
10803            ("A" | "Y", Some(month), _) => Some(Self::Annual(month as u8 + 1)),
10804            ("Q", Some(month), _) => Some(Self::Quarterly(month as u8 + 1)),
10805            ("W", _, Some(day)) => Some(Self::Weekly(day as u8)),
10806            _ => None,
10807        }
10808    }
10809
10810    /// Parse a pandas-style frequency alias. Recognizes the common subset
10811    /// (Y-<MON>/A/Y, Q-<MON>/Q, M, W-<DAY>/W, D, B, h/H, min/T, s/S) plus the
10812    /// sub-second units ms, us/US, ns/NS.
10813    ///
10814    /// Case-insensitive with ONE exception: bare `MS` is month start in pandas,
10815    /// not milliseconds, and is refused here the way pandas refuses it for
10816    /// `to_period`. See the check at the top of the body.
10817    pub fn parse(alias: &str) -> Option<Self> {
10818        let alias = alias.trim();
10819        let digits_end = alias
10820            .char_indices()
10821            .find(|&(position, ch)| {
10822                !(ch.is_ascii_digit() || (position == 0 && matches!(ch, '+' | '-')))
10823            })
10824            .map_or(alias.len(), |(position, _)| position);
10825        if digits_end > 0 {
10826            let count = alias[..digits_end].parse::<i64>().ok()?;
10827            return Self::parse_base(alias[digits_end..].trim())?.with_multiplier(count);
10828        }
10829        Self::parse_base(alias)
10830    }
10831
10832    fn parse_base(alias: &str) -> Option<Self> {
10833        // ⚠️ CASE MATTERS FOR EXACTLY ONE ALIAS, and this parser uppercases
10834        // everything. MEASURED, live pandas 2.2.3, Timestamp.to_period(f):
10835        //     'ms' -> millisecond      'Ms' -> millisecond
10836        //     'MS' -> ValueError       (it is month start, a date_range-only freq)
10837        //     'us' -> microsecond      'US' -> microsecond
10838        //     'ns' -> nanosecond       'NS' -> nanosecond
10839        // So only the fully-capitalised `MS` is excluded; every other casing of
10840        // "ms" is milliseconds, while us/ns are case-insensitive and belong in
10841        // the table below. Checked here, before the uppercase collapses it.
10842        if alias.eq_ignore_ascii_case("ms") && alias != "MS" {
10843            return Some(Self::Milliseconds);
10844        }
10845        match alias.to_ascii_uppercase().as_str() {
10846            "A" | "Y" | "ANNUAL" | "YEARLY" => Some(Self::ANNUAL),
10847            "Q" | "QUARTERLY" => Some(Self::QUARTERLY),
10848            "M" | "MONTHLY" => Some(Self::Monthly),
10849            "W" | "WEEKLY" => Some(Self::WEEKLY),
10850            "D" | "DAILY" => Some(Self::Daily),
10851            "B" | "BUSINESS" => Some(Self::Business),
10852            "H" | "HOURLY" => Some(Self::Hourly),
10853            "T" | "MIN" | "MINUTELY" => Some(Self::Minutely),
10854            "S" | "SECONDLY" => Some(Self::Secondly),
10855            "US" | "MICROSECOND" | "MICROSECONDS" => Some(Self::Microseconds),
10856            "NS" | "NANOSECOND" | "NANOSECONDS" => Some(Self::Nanoseconds),
10857            // The spelled-out form only; bare "MS" is deliberately absent, and
10858            // every other casing of it was taken above.
10859            "MILLISECOND" | "MILLISECONDS" => Some(Self::Milliseconds),
10860            anchored => Self::parse_anchored(anchored),
10861        }
10862    }
10863
10864    /// Canonical pandas alias string.
10865    #[must_use]
10866    pub fn alias(self) -> String {
10867        self.to_string()
10868    }
10869
10870    const fn base_alias(self) -> &'static str {
10871        const ANNUAL: [&str; 12] = [
10872            "Y-JAN", "Y-FEB", "Y-MAR", "Y-APR", "Y-MAY", "Y-JUN", "Y-JUL", "Y-AUG", "Y-SEP",
10873            "Y-OCT", "Y-NOV", "Y-DEC",
10874        ];
10875        const QUARTERLY: [&str; 12] = [
10876            "Q-JAN", "Q-FEB", "Q-MAR", "Q-APR", "Q-MAY", "Q-JUN", "Q-JUL", "Q-AUG", "Q-SEP",
10877            "Q-OCT", "Q-NOV", "Q-DEC",
10878        ];
10879        const WEEKLY: [&str; 7] = [
10880            "W-MON", "W-TUE", "W-WED", "W-THU", "W-FRI", "W-SAT", "W-SUN",
10881        ];
10882        match self {
10883            Self::Annual(month) => ANNUAL[(month as usize + 11) % 12],
10884            Self::Quarterly(month) => QUARTERLY[(month as usize + 11) % 12],
10885            Self::Monthly => "M",
10886            Self::Weekly(day) => WEEKLY[day as usize % 7],
10887            Self::Daily => "D",
10888            Self::Business => "B",
10889            Self::Hourly => "h",
10890            Self::Minutely => "min",
10891            Self::Secondly => "s",
10892            Self::Milliseconds => "ms",
10893            Self::Microseconds => "us",
10894            Self::Nanoseconds => "ns",
10895            Self::Multiple(_) => self.base().base_alias(),
10896        }
10897    }
10898
10899    /// Resolution word for `PeriodIndex.resolution`, or `None` where pandas has
10900    /// no answer.
10901    ///
10902    /// ⚠️ THIS IS NOT THE ALIAS TABLE. pandas' `.resolution` names the period's
10903    /// *component*, in the same vocabulary `DatetimeIndex::resolution` already
10904    /// uses here -- it is not the frequency string, which is what
10905    /// [`PeriodFreq::alias`] is for. MEASURED, live pandas 2.2.3, one-element
10906    /// `PeriodIndex` per freq:
10907    ///     Y   -> 'year'        Q   -> 'quarter'     M  -> 'month'
10908    ///     D   -> 'day'         h   -> 'hour'        min-> 'minute'
10909    ///     s   -> 'second'
10910    ///     W   -> raises AttributeError
10911    ///     B   -> raises AttributeError
10912    /// Every arm below previously returned the alias instead ("A-DEC", "M", "H",
10913    /// "T", "S", ...), so all nine disagreed with the incumbent; W and B answered
10914    /// where pandas refuses. The refusal is modelled as `None` rather than a
10915    /// wrong word, because the caller already returns `Option` for the empty
10916    /// index and pandas' own failure there is an absence, not a value.
10917    #[must_use]
10918    pub const fn resolution(self) -> Option<&'static str> {
10919        match self {
10920            Self::Annual(_) => Some("year"),
10921            Self::Quarterly(_) => Some("quarter"),
10922            Self::Monthly => Some("month"),
10923            Self::Daily => Some("day"),
10924            Self::Hourly => Some("hour"),
10925            Self::Minutely => Some("minute"),
10926            Self::Secondly => Some("second"),
10927            Self::Milliseconds => Some("millisecond"),
10928            Self::Microseconds => Some("microsecond"),
10929            Self::Nanoseconds => Some("nanosecond"),
10930            // pandas' Week and BusinessDay offsets carry no `_resolution_obj`,
10931            // so `.resolution` raises AttributeError rather than answering.
10932            Self::Weekly(_) | Self::Business => None,
10933            Self::Multiple(_) => None,
10934        }
10935    }
10936}
10937
10938impl std::fmt::Display for PeriodFreq {
10939    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10940        if self.multiplier() != 1 {
10941            write!(f, "{}", self.multiplier())?;
10942        }
10943        f.write_str(self.base_alias())
10944    }
10945}
10946
10947/// A single pandas-style Period value.
10948///
10949/// Stored as an integer ordinal on a frequency-specific axis plus the
10950/// frequency code. Two Periods with different `freq` are incompatible —
10951/// arithmetic and comparison require same-freq operands. The derived order
10952/// (ordinal, then freq) is a total one for index labels (45fzr): within one
10953/// freq it is the periods' own.
10954#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10955pub struct Period {
10956    pub ordinal: i64,
10957    pub freq: PeriodFreq,
10958}
10959
10960impl Period {
10961    #[must_use]
10962    pub const fn new(ordinal: i64, freq: PeriodFreq) -> Self {
10963        Self { ordinal, freq }
10964    }
10965
10966    /// Whether this is NaT: the missing period, ordinal `i64::MIN` (what a
10967    /// missing element of a PeriodIndex holds and what renders `NaT`).
10968    #[must_use]
10969    pub const fn is_nat(&self) -> bool {
10970        self.ordinal == i64::MIN
10971    }
10972
10973    /// Integer position on this period's frequency axis, matching
10974    /// `pd.Period.ordinal`.
10975    #[must_use]
10976    pub const fn ordinal(&self) -> i64 {
10977        self.ordinal
10978    }
10979
10980    /// Frequency code for this period, matching `pd.Period.freq`.
10981    #[must_use]
10982    pub const fn freq(&self) -> PeriodFreq {
10983        self.freq
10984    }
10985
10986    /// Canonical pandas frequency alias, matching `pd.Period.freqstr`.
10987    #[must_use]
10988    pub fn freqstr(&self) -> String {
10989        self.freq.alias()
10990    }
10991
10992    /// Same-freq ordinal comparison. Returns `None` if `freq` differs —
10993    /// caller decides whether that's an error or a panic site.
10994    #[must_use]
10995    pub fn cmp_same_freq(&self, other: &Self) -> Option<std::cmp::Ordering> {
10996        if self.freq != other.freq {
10997            return None;
10998        }
10999        Some(self.ordinal.cmp(&other.ordinal))
11000    }
11001
11002    /// Shift by `n` periods of the current frequency.
11003    /// Matches `pd.Period + n` and `pd.Period - n`.
11004    #[must_use]
11005    pub fn shift(&self, n: i64) -> Self {
11006        if self.is_nat() {
11007            return *self;
11008        }
11009        let ordinal = i128::from(self.ordinal) + i128::from(n) * i128::from(self.freq.multiplier());
11010        Self {
11011            ordinal: ordinal.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64,
11012            freq: self.freq,
11013        }
11014    }
11015
11016    /// Period-difference in units of the shared frequency.
11017    /// Returns `None` if `freq` differs (pandas raises IncompatibleFrequency).
11018    #[must_use]
11019    pub fn diff(&self, other: &Self) -> Option<i64> {
11020        if self.freq != other.freq {
11021            return None;
11022        }
11023        Some(self.ordinal.saturating_sub(other.ordinal))
11024    }
11025
11026    const fn fixed_span_nanos(freq: PeriodFreq) -> Option<i64> {
11027        match freq.base() {
11028            PeriodFreq::Daily => Some(Timedelta::NANOS_PER_DAY),
11029            PeriodFreq::Hourly => Some(Timedelta::NANOS_PER_HOUR),
11030            PeriodFreq::Minutely => Some(Timedelta::NANOS_PER_MIN),
11031            PeriodFreq::Secondly => Some(Timedelta::NANOS_PER_SEC),
11032            PeriodFreq::Milliseconds => Some(Timedelta::NANOS_PER_MILLI),
11033            PeriodFreq::Microseconds => Some(Timedelta::NANOS_PER_MICRO),
11034            PeriodFreq::Nanoseconds => Some(1),
11035            _ => None,
11036        }
11037    }
11038
11039    /// Construct a `Period` at `freq` containing the wall-clock instant `nanos`.
11040    /// Returns `None` if `nanos` is `Timestamp::NAT` or overflows the ordinal axis.
11041    #[must_use]
11042    pub fn from_timestamp_nanos(nanos: i64, freq: PeriodFreq) -> Option<Self> {
11043        Self::from_timestamp_nanos_with_business_roll(nanos, freq, true)
11044    }
11045
11046    fn from_timestamp_nanos_with_business_roll(
11047        nanos: i64,
11048        freq: PeriodFreq,
11049        roll_business_forward: bool,
11050    ) -> Option<Self> {
11051        if nanos == Timestamp::NAT {
11052            return None;
11053        }
11054        let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
11055        let (year, month, _day) = civil_from_days(days);
11056        let ordinal = match freq.base() {
11057            PeriodFreq::Annual(_) => {
11058                let months = year
11059                    .checked_sub(1970)?
11060                    .checked_mul(12)?
11061                    .checked_add(i64::from(month) - 1)?
11062                    .checked_add(freq.fiscal_month_shift())?;
11063                months.div_euclid(12)
11064            }
11065            PeriodFreq::Quarterly(_) => {
11066                let months = year
11067                    .checked_sub(1970)?
11068                    .checked_mul(12)?
11069                    .checked_add(i64::from(month) - 1)?
11070                    .checked_add(freq.fiscal_month_shift())?;
11071                months.div_euclid(3)
11072            }
11073            PeriodFreq::Monthly => year
11074                .checked_sub(1970)?
11075                .checked_mul(12)?
11076                .checked_add(i64::from(month) - 1)?,
11077            PeriodFreq::Weekly(_) => {
11078                const WEEK_ANCHOR_DAY: i64 = -10;
11079                days.checked_sub(WEEK_ANCHOR_DAY + freq.week_start_shift())?
11080                    .div_euclid(7)
11081            }
11082            PeriodFreq::Daily => days,
11083            PeriodFreq::Business => {
11084                let dow = (days + 3).rem_euclid(7);
11085                let adjusted_days = match (dow, roll_business_forward) {
11086                    (5, true) => days.checked_add(2)?,
11087                    (6, true) => days.checked_add(1)?,
11088                    (5, false) => days.checked_sub(1)?,
11089                    (6, false) => days.checked_sub(2)?,
11090                    _ => days,
11091                };
11092                let rem_ordinal = match adjusted_days.rem_euclid(7) {
11093                    0 => 0,
11094                    1 => 1,
11095                    4 => 2,
11096                    5 => 3,
11097                    6 => 4,
11098                    _ => return None,
11099                };
11100                adjusted_days
11101                    .div_euclid(7)
11102                    .checked_mul(5)?
11103                    .checked_add(rem_ordinal)?
11104            }
11105            PeriodFreq::Hourly => nanos.div_euclid(Timedelta::NANOS_PER_HOUR),
11106            PeriodFreq::Minutely => nanos.div_euclid(Timedelta::NANOS_PER_MIN),
11107            PeriodFreq::Secondly => nanos.div_euclid(Timedelta::NANOS_PER_SEC),
11108            PeriodFreq::Milliseconds => nanos.div_euclid(Timedelta::NANOS_PER_MILLI),
11109            PeriodFreq::Microseconds => nanos.div_euclid(Timedelta::NANOS_PER_MICRO),
11110            PeriodFreq::Nanoseconds => nanos,
11111            PeriodFreq::Multiple(_) => return None,
11112        };
11113        (ordinal != i64::MIN).then_some(Self::new(ordinal, freq))
11114    }
11115
11116    /// Return the current UTC period for `freq`, matching `pd.Period.now(freq)`.
11117    pub fn now(freq: &str) -> Result<Self, TypeError> {
11118        Timestamp::now().to_period(freq)
11119    }
11120
11121    /// Epoch nanoseconds of this period's inclusive start boundary (`pd.Period.start_time`).
11122    /// Returns `None` for `NaT` or out-of-range ordinals.
11123    #[must_use]
11124    pub fn start_nanos(&self) -> Option<i64> {
11125        if self.is_nat() {
11126            return None;
11127        }
11128        let nanos = match self.freq.base() {
11129            PeriodFreq::Annual(_) | PeriodFreq::Quarterly(_) => {
11130                let months = if matches!(self.freq.base(), PeriodFreq::Annual(_)) {
11131                    12_i64
11132                } else {
11133                    3_i64
11134                };
11135                let month_ordinal = self
11136                    .ordinal
11137                    .checked_mul(months)?
11138                    .checked_sub(self.freq.fiscal_month_shift())?;
11139                let year = 1970_i64.checked_add(month_ordinal.div_euclid(12))?;
11140                let month = u32::try_from(month_ordinal.rem_euclid(12) + 1).ok()?;
11141                days_from_civil(year, month, 1).checked_mul(Timedelta::NANOS_PER_DAY)?
11142            }
11143            PeriodFreq::Monthly => {
11144                let year = 1970_i64.checked_add(self.ordinal.div_euclid(12))?;
11145                let month = u32::try_from(self.ordinal.rem_euclid(12) + 1).ok()?;
11146                days_from_civil(year, month, 1).checked_mul(Timedelta::NANOS_PER_DAY)?
11147            }
11148            PeriodFreq::Weekly(_) => {
11149                const WEEK_ANCHOR_DAY: i64 = -10;
11150                let days = self
11151                    .ordinal
11152                    .checked_mul(7)?
11153                    .checked_add(WEEK_ANCHOR_DAY + self.freq.week_start_shift())?;
11154                days.checked_mul(Timedelta::NANOS_PER_DAY)?
11155            }
11156            PeriodFreq::Daily => self.ordinal.checked_mul(Timedelta::NANOS_PER_DAY)?,
11157            PeriodFreq::Business => {
11158                const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
11159                let offset = WEEKDAY_OFFSET[self.ordinal.rem_euclid(5) as usize];
11160                let days = self
11161                    .ordinal
11162                    .div_euclid(5)
11163                    .checked_mul(7)?
11164                    .checked_add(offset)?;
11165                days.checked_mul(Timedelta::NANOS_PER_DAY)?
11166            }
11167            PeriodFreq::Hourly => self.ordinal.checked_mul(Timedelta::NANOS_PER_HOUR)?,
11168            PeriodFreq::Minutely => self.ordinal.checked_mul(Timedelta::NANOS_PER_MIN)?,
11169            PeriodFreq::Secondly => self.ordinal.checked_mul(Timedelta::NANOS_PER_SEC)?,
11170            PeriodFreq::Milliseconds => self.ordinal.checked_mul(Timedelta::NANOS_PER_MILLI)?,
11171            PeriodFreq::Microseconds => self.ordinal.checked_mul(Timedelta::NANOS_PER_MICRO)?,
11172            PeriodFreq::Nanoseconds => self.ordinal,
11173            PeriodFreq::Multiple(_) => return None,
11174        };
11175        (nanos != Timestamp::NAT).then_some(nanos)
11176    }
11177
11178    /// Epoch nanoseconds of this period's inclusive end boundary (`pd.Period.end_time`).
11179    /// Returns `None` for `NaT` or out-of-range ordinals.
11180    #[must_use]
11181    pub fn end_nanos(&self) -> Option<i64> {
11182        if self.is_nat() {
11183            return None;
11184        }
11185        if self.freq == PeriodFreq::Business {
11186            // A single business day ends at its own day's last nanosecond;
11187            // multiplied business spans (2B, 3B, ...) span up to next_start - 1ns.
11188            let start = self.start_nanos()?;
11189            let end = start.checked_add(Timedelta::NANOS_PER_DAY - 1)?;
11190            return (end != Timestamp::NAT).then_some(end);
11191        }
11192        let next = Self::new(self.ordinal.checked_add(self.freq.multiplier())?, self.freq);
11193        let end = next.start_nanos()?.checked_sub(1)?;
11194        (end != Timestamp::NAT).then_some(end)
11195    }
11196
11197    /// Timestamp at the period's start boundary (`pd.Period.start_time`).
11198    /// Returns `Timestamp::nat()` for `NaT` or out-of-range ordinals.
11199    #[must_use]
11200    pub fn start_time(&self) -> Timestamp {
11201        self.start_nanos()
11202            .map_or_else(Timestamp::nat, Timestamp::from_nanos)
11203    }
11204
11205    /// Timestamp at the period's inclusive end boundary (`pd.Period.end_time`).
11206    /// Returns `Timestamp::nat()` for `NaT` or out-of-range ordinals.
11207    #[must_use]
11208    pub fn end_time(&self) -> Timestamp {
11209        self.end_nanos()
11210            .map_or_else(Timestamp::nat, Timestamp::from_nanos)
11211    }
11212
11213    /// Convert period to a `Timestamp` at the requested boundary (`"start"`/`"S"` or `"end"`/`"E"`),
11214    /// matching `pd.Period.to_timestamp(how=...)`.
11215    pub fn to_timestamp(&self, how: &str) -> Result<Timestamp, TypeError> {
11216        match how.trim().to_ascii_lowercase().as_str() {
11217            "" | "s" | "start" | "begin" | "b" => Ok(self.start_time()),
11218            "e" | "end" | "finish" => Ok(self.end_time()),
11219            _ => Err(TypeError::ValueNotParseable {
11220                value: how.to_owned(),
11221                target: "Period::to_timestamp how ('start' or 'end')".to_owned(),
11222            }),
11223        }
11224    }
11225
11226    /// Convert period to a new frequency using pandas' default `"end"` boundary,
11227    /// matching `pd.Period.asfreq(freq)`.
11228    pub fn asfreq(&self, freq: &str) -> Result<Self, TypeError> {
11229        self.asfreq_with_how(freq, "end")
11230    }
11231
11232    /// Convert period to a new frequency at the requested boundary (`"start"`/`"S"` or `"end"`/`"E"`),
11233    /// matching `pd.Period.asfreq(freq, how)`.
11234    pub fn asfreq_with_how(&self, freq: &str, how: &str) -> Result<Self, TypeError> {
11235        let target_freq = PeriodFreq::parse(freq).ok_or_else(|| TypeError::ValueNotParseable {
11236            value: freq.to_owned(),
11237            target: "PeriodFreq".to_owned(),
11238        })?;
11239        let is_start = match how.trim().to_ascii_lowercase().as_str() {
11240            "" | "e" | "end" | "finish" => false,
11241            "s" | "start" | "begin" | "b" => true,
11242            _ => {
11243                return Err(TypeError::ValueNotParseable {
11244                    value: how.to_owned(),
11245                    target: "Period::asfreq how ('start' or 'end')".to_owned(),
11246                });
11247            }
11248        };
11249        if self.is_nat() {
11250            return Ok(Self::new(i64::MIN, target_freq));
11251        }
11252        let boundary_nanos = if is_start {
11253            self.start_nanos()
11254        } else if self.freq.base() == PeriodFreq::Business && self.freq != PeriodFreq::Business {
11255            self.ordinal
11256                .checked_add(self.freq.multiplier() - 1)
11257                .and_then(|last| Self::new(last, PeriodFreq::Business).end_nanos())
11258        } else {
11259            self.end_nanos()
11260        }
11261        .ok_or_else(|| TypeError::ValueNotParseable {
11262            value: self.to_string(),
11263            target: "Period boundary Timestamp".to_owned(),
11264        })?;
11265        // pandas rolls a weekend day of a day-or-finer source to a business day
11266        // the opposite way from a week/month/quarter/year source: end rolls forward
11267        // to Monday, start rolls back to Friday; coarse sources roll end back to Friday.
11268        let flips = target_freq.base() == PeriodFreq::Business
11269            && Self::fixed_span_nanos(self.freq).is_some();
11270        let roll_business_forward = if flips { !is_start } else { is_start };
11271        Self::from_timestamp_nanos_with_business_roll(
11272            boundary_nanos,
11273            target_freq,
11274            roll_business_forward,
11275        )
11276        .ok_or_else(|| TypeError::ValueNotParseable {
11277            value: self.to_string(),
11278            target: format!("Period[{target_freq}]"),
11279        })
11280    }
11281
11282    /// Instant used by pandas `get_date_info` for date/time component accessors:
11283    /// sub-daily and daily/business periods use their start instant; coarser
11284    /// calendar periods (weekly, monthly, quarterly, annual) use midnight of
11285    /// their end date.
11286    fn field_timestamp(&self) -> Timestamp {
11287        if self.is_nat() {
11288            return Timestamp::nat();
11289        }
11290        // Calendar fields describe the first base period, not the far end
11291        // of its multiplied span: a 2M period starting in January still has
11292        // month=1 and day=31, although its end_time falls in February.
11293        let base = Self::new(self.ordinal, self.freq.base());
11294        let nanos = match base.freq {
11295            PeriodFreq::Daily
11296            | PeriodFreq::Business
11297            | PeriodFreq::Hourly
11298            | PeriodFreq::Minutely
11299            | PeriodFreq::Secondly
11300            | PeriodFreq::Milliseconds
11301            | PeriodFreq::Microseconds
11302            | PeriodFreq::Nanoseconds => base.start_nanos(),
11303            PeriodFreq::Weekly(_)
11304            | PeriodFreq::Monthly
11305            | PeriodFreq::Quarterly(_)
11306            | PeriodFreq::Annual(_) => base
11307                .end_nanos()
11308                .map(|end| end - end.rem_euclid(Timedelta::NANOS_PER_DAY)),
11309            PeriodFreq::Multiple(_) => None,
11310        };
11311        nanos.map_or_else(Timestamp::nat, Timestamp::from_nanos)
11312    }
11313
11314    /// Format period using strftime directives (`pd.Period.strftime`).
11315    /// Returns `"NaT"` for `NaT`.
11316    #[must_use]
11317    pub fn strftime(&self, fmt: &str) -> String {
11318        self.field_timestamp().strftime(fmt)
11319    }
11320
11321    /// Calendar year of the period (`pd.Period.year`). Returns `None` for `NaT`.
11322    #[must_use]
11323    pub fn year(&self) -> Option<i64> {
11324        self.field_timestamp().year()
11325    }
11326
11327    /// Calendar month (1-12) of the period (`pd.Period.month`). Returns `None` for `NaT`.
11328    #[must_use]
11329    pub fn month(&self) -> Option<i64> {
11330        self.field_timestamp().month()
11331    }
11332
11333    /// Calendar day of month (1-31) of the period (`pd.Period.day`). Returns `None` for `NaT`.
11334    #[must_use]
11335    pub fn day(&self) -> Option<i64> {
11336        self.field_timestamp().day()
11337    }
11338
11339    /// Hour component (0-23) of the period (`pd.Period.hour`). Returns `None` for `NaT`.
11340    #[must_use]
11341    pub fn hour(&self) -> Option<i64> {
11342        self.field_timestamp().hour()
11343    }
11344
11345    /// Minute component (0-59) of the period (`pd.Period.minute`). Returns `None` for `NaT`.
11346    #[must_use]
11347    pub fn minute(&self) -> Option<i64> {
11348        self.field_timestamp().minute()
11349    }
11350
11351    /// Second component (0-59) of the period (`pd.Period.second`). Returns `None` for `NaT`.
11352    #[must_use]
11353    pub fn second(&self) -> Option<i64> {
11354        self.field_timestamp().second()
11355    }
11356
11357    /// Quarter (1-4) of the period (`pd.Period.quarter`): fiscal quarter for
11358    /// `Quarterly` frequencies, calendar quarter of the end date otherwise.
11359    #[must_use]
11360    pub fn quarter(&self) -> Option<i64> {
11361        if self.is_nat() {
11362            return None;
11363        }
11364        match self.freq.base() {
11365            PeriodFreq::Quarterly(_) => Some(self.ordinal.rem_euclid(4) + 1),
11366            _ => self.field_timestamp().quarter(),
11367        }
11368    }
11369
11370    /// Fiscal year of the period (`pd.Period.qyear`). Returns `None` for `NaT`.
11371    #[must_use]
11372    pub fn qyear(&self) -> Option<i64> {
11373        if self.is_nat() {
11374            return None;
11375        }
11376        match self.freq.base() {
11377            PeriodFreq::Quarterly(_) => 1970_i64.checked_add(self.ordinal.div_euclid(4)),
11378            _ => self.year(),
11379        }
11380    }
11381
11382    /// Day of the week (Monday=0, Sunday=6), matching `pd.Period.dayofweek`.
11383    #[must_use]
11384    pub fn dayofweek(&self) -> Option<i64> {
11385        self.field_timestamp().dayofweek()
11386    }
11387
11388    /// Alias for [`dayofweek`](Self::dayofweek), matching `pd.Period.day_of_week`.
11389    #[must_use]
11390    pub fn day_of_week(&self) -> Option<i64> {
11391        self.dayofweek()
11392    }
11393
11394    /// Alias for [`dayofweek`](Self::dayofweek), matching `pd.Period.weekday`.
11395    #[must_use]
11396    pub fn weekday(&self) -> Option<i64> {
11397        self.dayofweek()
11398    }
11399
11400    /// Day of the year (1-366), matching `pd.Period.dayofyear`.
11401    #[must_use]
11402    pub fn dayofyear(&self) -> Option<i64> {
11403        self.field_timestamp().dayofyear()
11404    }
11405
11406    /// Alias for [`dayofyear`](Self::dayofyear), matching `pd.Period.day_of_year`.
11407    #[must_use]
11408    pub fn day_of_year(&self) -> Option<i64> {
11409        self.dayofyear()
11410    }
11411
11412    /// Number of days in the period's month (28-31), matching `pd.Period.days_in_month`.
11413    #[must_use]
11414    pub fn days_in_month(&self) -> Option<i64> {
11415        self.field_timestamp().days_in_month()
11416    }
11417
11418    /// Alias for [`days_in_month`](Self::days_in_month), matching `pd.Period.daysinmonth`.
11419    #[must_use]
11420    pub fn daysinmonth(&self) -> Option<i64> {
11421        self.days_in_month()
11422    }
11423
11424    /// ISO-8601 week number (1-53), matching `pd.Period.week`.
11425    #[must_use]
11426    pub fn week(&self) -> Option<i64> {
11427        self.field_timestamp().week()
11428    }
11429
11430    /// Alias for [`week`](Self::week), matching `pd.Period.weekofyear`.
11431    #[must_use]
11432    pub fn weekofyear(&self) -> Option<i64> {
11433        self.week()
11434    }
11435
11436    /// Whether the period's year is a leap year (`pd.Period.is_leap_year`).
11437    #[must_use]
11438    pub fn is_leap_year(&self) -> Option<bool> {
11439        self.field_timestamp().is_leap_year()
11440    }
11441
11442    /// Parse common pandas `Period(...)` strings and infer the frequency.
11443    ///
11444    /// Supported forms mirror pandas' unambiguous scalar constructor cases:
11445    /// annual (`"2024"`), quarterly (`"2024Q1"`), monthly (`"2024-01"`),
11446    /// and daily (`"2024-01-15"`). The ordinal axes match pandas:
11447    /// 1970, 1970Q1, 1970-01, and 1970-01-01 all have ordinal 0.
11448    pub fn parse(s: &str) -> Result<Self, TypeError> {
11449        let trimmed = s.trim();
11450        if trimmed.eq_ignore_ascii_case("nat") {
11451            return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
11452        }
11453
11454        if let Some((year, quarter)) = parse_quarter_period(trimmed) {
11455            let ordinal = year
11456                .checked_sub(1970)
11457                .and_then(|offset| offset.checked_mul(4))
11458                .and_then(|base| base.checked_add(i64::from(quarter) - 1))
11459                .ok_or_else(|| TypeError::ValueNotParseable {
11460                    value: s.to_owned(),
11461                    target: "Period".to_owned(),
11462                })?;
11463            return Ok(Self::new(ordinal, PeriodFreq::QUARTERLY));
11464        }
11465
11466        if let Some((year, month, day)) = parse_ymd_period(trimmed) {
11467            let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
11468            return Ok(Self::new(ordinal, PeriodFreq::Daily));
11469        }
11470
11471        if let Some((year, month)) = parse_year_month_period(trimmed) {
11472            let ordinal = year
11473                .checked_sub(1970)
11474                .and_then(|offset| offset.checked_mul(12))
11475                .and_then(|base| base.checked_add(i64::from(month) - 1))
11476                .ok_or_else(|| TypeError::ValueNotParseable {
11477                    value: s.to_owned(),
11478                    target: "Period".to_owned(),
11479                })?;
11480            return Ok(Self::new(ordinal, PeriodFreq::Monthly));
11481        }
11482
11483        if let Some(year) = parse_annual_period(trimmed) {
11484            let ordinal = year
11485                .checked_sub(1970)
11486                .ok_or_else(|| TypeError::ValueNotParseable {
11487                    value: s.to_owned(),
11488                    target: "Period".to_owned(),
11489                })?;
11490            return Ok(Self::new(ordinal, PeriodFreq::ANNUAL));
11491        }
11492
11493        Err(TypeError::ValueNotParseable {
11494            value: s.to_owned(),
11495            target: "Period".to_owned(),
11496        })
11497    }
11498
11499    /// Pandas calendar string for this period, matching `str(pd.Period)`.
11500    ///
11501    /// Inverts the frequency-specific ordinal axes anchored at 1970:
11502    /// `1970`/`1970Q1`/`1970-01`/`1970-01-01`/`1970-01-01 00:00` all have
11503    /// ordinal 0. Returns `"NaT"` for the missing sentinel (`i64::MIN`).
11504    ///
11505    /// EVERY frequency is exact, Weekly and Business included.
11506    ///
11507    /// ⚠️ THOSE TWO ARE NOT INDEXED IN DAYS, which is what made them wrong until
11508    /// 08363d42f: a weekly ordinal counts WEEKS from the Monday 1969-12-22 and
11509    /// renders as the RANGE it spans (`2024-03-11/2024-03-17`), and a business
11510    /// ordinal counts BUSINESS DAYS at five per week. Both used to be handed to
11511    /// `civil_from_days`, which reads its argument as days since the epoch, so
11512    /// ordinal 2829 rendered `1977-09-30` instead of the week of 2024-03-15.
11513    ///
11514    /// The note that used to sit here called them "best-effort" and said neither
11515    /// was "reachable through the current parse/cast paths". The first half was
11516    /// a real limitation; the second was too narrow a survey. [`Self::parse`]
11517    /// indeed cannot produce them and neither can `cast_scalar` — but
11518    /// `DatetimeIndex::to_period("W")` builds them directly, and fp-index then
11519    /// renders those values through `Display` in `PeriodIndex::format`,
11520    /// `to_index`, `to_flat_index`, the `.str` accessor and the `get_loc` error
11521    /// message. The frequencies were unreachable only from the two paths the
11522    /// note happened to check.
11523    #[must_use]
11524    pub fn calendar_string(&self) -> String {
11525        let mut rendered = String::new();
11526        // `fmt::Write for String` is infallible.
11527        let _ = self.write_calendar(&mut rendered);
11528        rendered
11529    }
11530
11531    fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
11532        if self.ordinal == i64::MIN {
11533            return rendered.write_str("NaT");
11534        }
11535        let ord = self.ordinal;
11536        match self.freq.base() {
11537            // An anchored year or quarter is labelled by the fiscal year its
11538            // ordinal counts (Period('2024', 'Y-JUN') ends 2024-06-30), so
11539            // the label does not depend on the anchor.
11540            PeriodFreq::Annual(_) => {
11541                let year = 1970 + ord;
11542                write!(rendered, "{year}")
11543            }
11544            PeriodFreq::Quarterly(_) => {
11545                let year = 1970 + ord.div_euclid(4);
11546                let quarter = ord.rem_euclid(4) + 1;
11547                write!(rendered, "{year}Q{quarter}")
11548            }
11549            PeriodFreq::Monthly => {
11550                let year = 1970 + ord.div_euclid(12);
11551                let month = ord.rem_euclid(12) + 1;
11552                write!(rendered, "{year:04}-{month:02}")
11553            }
11554            PeriodFreq::Daily => {
11555                let (y, m, d) = civil_from_days(ord);
11556                write!(rendered, "{y:04}-{m:02}-{d:02}")
11557            }
11558            // ⚠️ NOT DAYS SINCE THE EPOCH. A business ordinal counts BUSINESS
11559            // DAYS — five per week — so handing it to `civil_from_days` (which
11560            // wants a day count) put the label decades out: ordinal 14141 is
11561            // 2024-03-15 and rendered as 2008-09-19.
11562            //
11563            // The forward map in fp-index is
11564            //     days.div_euclid(7) * 5 + {Thu:0, Fri:1, Mon:2, Tue:3, Wed:4}
11565            // measured against pandas at every sampled date, so this is its
11566            // inverse: five ordinals per seven days, with the remainder naming a
11567            // weekday offset from the Thursday the epoch falls on.
11568            PeriodFreq::Business => {
11569                const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
11570                // Euclidean, so a pre-epoch ordinal keeps a remainder in 0..5:
11571                // ordinal -1 is 1969-12-31, not a negative weekday index.
11572                let offset = WEEKDAY_OFFSET[ord.rem_euclid(5) as usize];
11573                let days = ord.div_euclid(5).saturating_mul(7).saturating_add(offset);
11574                let (y, m, d) = civil_from_days(days);
11575                write!(rendered, "{y:04}-{m:02}-{d:02}")
11576            }
11577            // ⚠️ TWO BUGS IN ONE ARM. A weekly ordinal counts WEEKS from the
11578            // Monday 1969-12-22 (ten days before the epoch), and pandas renders a
11579            // weekly period as the RANGE it spans, not as one date:
11580            //     Period('2024-03-15', 'W') -> '2024-03-11/2024-03-17'
11581            // ordinal 2829, which this arm rendered as '1977-09-30'.
11582            //
11583            // fp-frame's `format_period_label` already produced the range form
11584            // for the same freq, so the two renderers disagreed on every weekly
11585            // period; this makes them agree.
11586            PeriodFreq::Weekly(_) => {
11587                // Days-since-epoch of the anchor Monday 1969-12-22; a week
11588                // ending on another weekday starts that many days later
11589                // (W-MON weeks run Tuesday..Monday).
11590                const WEEK_ANCHOR_DAY: i64 = -10;
11591                let start = ord
11592                    .saturating_mul(7)
11593                    .saturating_add(WEEK_ANCHOR_DAY + self.freq.week_start_shift());
11594                let (sy, sm, sd) = civil_from_days(start);
11595                let (ey, em, ed) = civil_from_days(start.saturating_add(6));
11596                write!(rendered, "{sy:04}-{sm:02}-{sd:02}/{ey:04}-{em:02}-{ed:02}")
11597            }
11598            PeriodFreq::Hourly => {
11599                let (y, m, d) = civil_from_days(ord.div_euclid(24));
11600                let hour = ord.rem_euclid(24);
11601                write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
11602            }
11603            PeriodFreq::Minutely => {
11604                let day = ord.div_euclid(1440);
11605                let mins = ord.rem_euclid(1440);
11606                let (y, m, d) = civil_from_days(day);
11607                write!(
11608                    rendered,
11609                    "{y:04}-{m:02}-{d:02} {:02}:{:02}",
11610                    mins / 60,
11611                    mins % 60
11612                )
11613            }
11614            PeriodFreq::Secondly => {
11615                let day = ord.div_euclid(86_400);
11616                let secs = ord.rem_euclid(86_400);
11617                let (y, m, d) = civil_from_days(day);
11618                write!(
11619                    rendered,
11620                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
11621                    secs / 3600,
11622                    (secs % 3600) / 60,
11623                    secs % 60
11624                )
11625            }
11626            // The three sub-second frequencies differ only in the divisor and
11627            // the FIXED fraction width -- pandas pads to the full width and
11628            // never trims trailing zeros. MEASURED on 2024-03-15 10:30:45.123456789:
11629            //     ms -> "2024-03-15 10:30:45.123"
11630            //     us -> "2024-03-15 10:30:45.123456"
11631            //     ns -> "2024-03-15 10:30:45.123456789"
11632            PeriodFreq::Milliseconds | PeriodFreq::Microseconds | PeriodFreq::Nanoseconds => {
11633                let (per_sec, width) = match self.freq.base() {
11634                    PeriodFreq::Milliseconds => (1_000_i64, 3_usize),
11635                    PeriodFreq::Microseconds => (1_000_000_i64, 6_usize),
11636                    _ => (1_000_000_000_i64, 9_usize),
11637                };
11638                // 86_400 * 1e9 = 8.64e13 -- the widest of these is well inside i64.
11639                let per_day = 86_400 * per_sec;
11640                let day = ord.div_euclid(per_day);
11641                let rest = ord.rem_euclid(per_day);
11642                let secs = rest / per_sec;
11643                let frac = rest % per_sec;
11644                let (y, m, d) = civil_from_days(day);
11645                write!(
11646                    rendered,
11647                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{:0width$}",
11648                    secs / 3600,
11649                    (secs % 3600) / 60,
11650                    secs % 60,
11651                    frac,
11652                    width = width
11653                )
11654            }
11655            PeriodFreq::Multiple(_) => Self::new(ord, self.freq.base()).write_calendar(rendered),
11656        }
11657    }
11658}
11659
11660/// Convert a day count (days since 1970-01-01) to a proleptic-Gregorian
11661/// `(year, month, day)`, using Howard Hinnant's civil-from-days algorithm
11662/// (same kernel as `Timestamp::isoformat`); the year astronomical (0 is 1
11663/// BC).
11664#[must_use]
11665pub fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
11666    let days = days_since_epoch + 719_468;
11667    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
11668    let doe = days - era * 146_097;
11669    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
11670    let y = yoe + era * 400;
11671    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
11672    let mp = (5 * doy + 2) / 153;
11673    let d = doy - (153 * mp + 2) / 5 + 1;
11674    let m = if mp < 10 { mp + 3 } else { mp - 9 };
11675    let year = if m <= 2 { y + 1 } else { y };
11676    (year, m as u32, d as u32)
11677}
11678
11679fn parse_annual_period(value: &str) -> Option<i64> {
11680    (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
11681        .then(|| value.parse::<i64>().ok())
11682        .flatten()
11683}
11684
11685fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
11686    let (year, month) = value.split_once('-')?;
11687    if year.len() != 4 || month.len() != 2 {
11688        return None;
11689    }
11690    let year = year.parse::<i64>().ok()?;
11691    let month = month.parse::<u32>().ok()?;
11692    (1..=12).contains(&month).then_some((year, month))
11693}
11694
11695fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
11696    let mut parts = value.split('-');
11697    let year = parts.next()?;
11698    let month = parts.next()?;
11699    let day = parts.next()?;
11700    if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
11701        return None;
11702    }
11703    let year = year.parse::<i64>().ok()?;
11704    let month = month.parse::<u32>().ok()?;
11705    let day = day.parse::<u32>().ok()?;
11706    (1..=days_in_month(year, month)?)
11707        .contains(&day)
11708        .then_some((year, month, day))
11709}
11710
11711fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
11712    let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
11713    if year.len() != 4 || quarter.len() != 1 {
11714        return None;
11715    }
11716    let year = year.parse::<i64>().ok()?;
11717    let quarter = quarter.parse::<u32>().ok()?;
11718    (1..=4).contains(&quarter).then_some((year, quarter))
11719}
11720
11721impl std::fmt::Display for Period {
11722    /// Pandas `str(Period)` form: the calendar string (`2024`, `2024Q1`,
11723    /// `2024-03`, `2024-01-15`, ...). NaT (ordinal `i64::MIN`) renders `NaT`.
11724    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11725        self.write_calendar(f)
11726    }
11727}
11728
11729/// Build `periods` consecutive Periods starting at `start`.
11730///
11731/// Matches `pd.period_range(start, periods=N, freq=start.freq)` for the
11732/// count-based form. The frequency is taken from `start` — pandas requires
11733/// `freq` to match when both are passed; mismatches are an error in
11734/// pandas, but here we sidestep ambiguity by deriving from `start.freq`.
11735///
11736/// Per br-frankenpandas-2jef (epoj Phase 2). Pure ordinal arithmetic — no
11737/// calendar conversion (Phase 3 wires chrono). `periods=0` returns empty.
11738///
11739/// ```
11740/// use fp_types::{period_range, Period, PeriodFreq};
11741/// let q1 = Period::new(216, PeriodFreq::QUARTERLY);
11742/// let year = period_range(q1, 4);
11743/// assert_eq!(year.len(), 4);
11744/// assert_eq!(year[0].ordinal, 216);
11745/// assert_eq!(year[3].ordinal, 219);
11746/// ```
11747#[must_use]
11748pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
11749    (0..periods).map(|i| start.shift(i as i64)).collect()
11750}
11751
11752#[cfg(test)]
11753mod tests {
11754    use super::{
11755        DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
11756        cast_scalar, common_dtype, infer_dtype,
11757    };
11758
11759    /// A host value for the tests: a named thing, equal by name, unhashable
11760    /// when the name is empty.
11761    struct Named(&'static str);
11762
11763    impl super::HostObject for Named {
11764        fn host_eq(&self, other: &dyn super::HostObject) -> bool {
11765            other
11766                .as_any()
11767                .downcast_ref::<Named>()
11768                .is_some_and(|other| other.0 == self.0)
11769        }
11770        fn host_repr(&self) -> String {
11771            format!("Named({:?})", self.0)
11772        }
11773        fn host_str(&self) -> String {
11774            self.0.to_owned()
11775        }
11776        fn host_hash(&self) -> Option<u64> {
11777            (!self.0.is_empty()).then_some(self.0.len() as u64)
11778        }
11779        // Names starting with '!' cannot be ordered (as a date against a time).
11780        fn host_cmp(&self, other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
11781            let other = other.as_any().downcast_ref::<Named>()?;
11782            (!self.0.starts_with('!') && !other.0.starts_with('!')).then(|| self.0.cmp(other.0))
11783        }
11784        fn as_any(&self) -> &dyn std::any::Any {
11785            self
11786        }
11787    }
11788
11789    #[test]
11790    fn host_values_block_workers_only_under_a_declared_host_lock_4qg5w_13() {
11791        use std::sync::atomic::Ordering;
11792
11793        use super::{HostValue, LIVE_HOST_VALUES, workers_blocked};
11794        // The rule: inline only when a host lock may be held AND a host value
11795        // is alive. NEGATIVE: without a declared lock (pure Rust callers, this
11796        // test process) nothing is blocked however many host values live.
11797        assert!(workers_blocked(true, 1));
11798        assert!(!workers_blocked(true, 0));
11799        assert!(!workers_blocked(false, 3));
11800        // The count: non-zero while a handle is held, clones included (other
11801        // tests may hold host values concurrently, so only "alive while held"
11802        // is asserted, never "dead after drop"; the lock is never declared
11803        // here, so no concurrent test loses its workers).
11804        let first = HostValue::new(Named("held"));
11805        assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11806        let clone = first.clone();
11807        drop(first);
11808        assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11809        assert_eq!(clone.object().host_str(), "held");
11810    }
11811
11812    #[test]
11813    fn object_cells_order_like_python_then_totally_fvsao_66() {
11814        use std::cmp::Ordering;
11815
11816        use super::{HostValue, ObjectValue};
11817        let host = |name: &'static str| ObjectValue::Host(HostValue::new(Named(name)));
11818        let list = |items: Vec<Scalar>| ObjectValue::list(items);
11819        // Host values order as the host orders them (a date before a later
11820        // date), not by their reprs.
11821        assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11822        assert!(host("b") > host("a"));
11823        assert_eq!(host("a").cmp(&host("a")), Ordering::Equal);
11824        // Lists item by item, numbers by value (1 < 10, where the reprs sort
11825        // "10" first), a shorter prefix first.
11826        let one_ten = list(vec![Scalar::Int64(1), Scalar::Int64(10)]);
11827        let one_two = list(vec![Scalar::Int64(1), Scalar::Int64(2)]);
11828        assert_eq!(one_two.python_cmp(&one_ten), Some(Ordering::Less));
11829        assert!(list(vec![Scalar::Int64(1)]) < one_two);
11830        // Python's 1 == 1.0: an equal item pair is skipped, not the answer.
11831        let mixed = list(vec![Scalar::Float64(1.0), Scalar::Int64(3)]);
11832        assert_eq!(one_two.python_cmp(&mixed), Some(Ordering::Less));
11833        // Where Python raises there is no python_cmp, but the total order
11834        // still separates the cells: a list before a host value, then reprs.
11835        assert_eq!(one_two.python_cmp(&host("a")), None);
11836        assert!(one_two < host("a"));
11837        assert_eq!(host("!z").python_cmp(&host("!a")), None);
11838        assert!(host("!a") < host("!z"));
11839        let text = list(vec![Scalar::Utf8("a".to_owned())]);
11840        assert_eq!(one_two.python_cmp(&text), None);
11841        assert_ne!(one_two.cmp(&text), Ordering::Equal);
11842        // NEGATIVE: unequal cells that print alike are never Equal (NaN is not
11843        // equal to itself), so an ordered map cannot merge them.
11844        let nan = || list(vec![Scalar::Float64(f64::NAN)]);
11845        let (first, second) = (nan(), nan());
11846        assert_ne!(first, second);
11847        assert_ne!(first.cmp(&second), Ordering::Equal);
11848        assert_eq!(first.cmp(&second), second.cmp(&first).reverse());
11849    }
11850
11851    #[test]
11852    fn bytes_cells_print_order_and_serialize_like_python_bytes_4qg5w_8() {
11853        use std::cmp::Ordering;
11854
11855        use super::ObjectValue;
11856        let bytes = |data: &[u8]| Scalar::Object(ObjectValue::bytes(data.to_vec()));
11857        // Python's repr: single quotes unless the bytes hold a ' and no ",
11858        // \xNN for the unprintable, \\ \t \n \r escaped.
11859        assert_eq!(bytes(b"ab").python_repr(), "b'ab'");
11860        assert_eq!(bytes(b"a'b").python_repr(), "b\"a'b\"");
11861        assert_eq!(bytes(b"a'\"").python_repr(), "b'a\\'\"'");
11862        assert_eq!(bytes(b"\x00\t\\\xff").python_repr(), "b'\\x00\\t\\\\\\xff'");
11863        assert_eq!(bytes(b"ab").python_type_name(), "bytes");
11864        // Ordered byte by byte, a prefix first; never equal to a str.
11865        assert_eq!(bytes(b"ab").python_cmp(&bytes(b"b")), Some(Ordering::Less));
11866        assert_eq!(bytes(b"a").python_cmp(&bytes(b"ab")), Some(Ordering::Less));
11867        assert_eq!(bytes(b"a").python_cmp(&Scalar::Utf8("a".to_owned())), None);
11868        assert_ne!(bytes(b"a"), Scalar::Utf8("a".to_owned()));
11869        assert!(!bytes(b"").to_bool().unwrap());
11870        // The serde form the conformance fixtures carry, both ways.
11871        let json = serde_json::to_string(&bytes(b"hi")).unwrap();
11872        assert_eq!(json, r#"{"kind":"object","value":{"bytes":[104,105]}}"#);
11873        let back: Scalar = serde_json::from_str(&json).unwrap();
11874        assert_eq!(back, bytes(b"hi"));
11875        // NEGATIVE: a list cell still (de)serializes as its items.
11876        let list: Scalar =
11877            serde_json::from_str(r#"{"kind":"object","value":[{"kind":"int64","value":1}]}"#)
11878                .unwrap();
11879        assert_eq!(
11880            list,
11881            Scalar::Object(ObjectValue::list(vec![Scalar::Int64(1)]))
11882        );
11883    }
11884
11885    #[test]
11886    fn values_order_and_name_their_types_as_python_does_fvsao_71() {
11887        use std::cmp::Ordering;
11888
11889        use super::{HostValue, ObjectValue};
11890        let text = |value: &str| Scalar::Utf8(value.to_owned());
11891        let host =
11892            |name: &'static str| Scalar::Object(ObjectValue::Host(HostValue::new(Named(name))));
11893        let list = |items: Vec<Scalar>| Scalar::Object(ObjectValue::list(items));
11894        // Numbers across kinds by value, text by code point, instants,
11895        // intervals by (left, right), cells as the host orders them.
11896        assert_eq!(
11897            Scalar::Bool(true).python_cmp(&Scalar::Float64(1.5)),
11898            Some(Ordering::Less)
11899        );
11900        assert_eq!(
11901            Scalar::Int64(2).python_cmp(&Scalar::Float64(2.0)),
11902            Some(Ordering::Equal)
11903        );
11904        assert_eq!(text("b").python_cmp(&text("a")), Some(Ordering::Greater));
11905        assert_eq!(
11906            Scalar::Datetime64(5).python_cmp(&Scalar::Datetime64(9)),
11907            Some(Ordering::Less)
11908        );
11909        let interval = |left: f64, right: f64| {
11910            Scalar::Interval(Interval::new(left, right, IntervalClosed::Right))
11911        };
11912        assert_eq!(
11913            interval(0.0, 5.0).python_cmp(&interval(0.0, 2.0)),
11914            Some(Ordering::Greater)
11915        );
11916        assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11917        // NEGATIVES: what Python cannot order - a str and an int, an instant
11918        // and a duration, a cell and a number, unorderable host values.
11919        assert_eq!(text("a").python_cmp(&Scalar::Int64(1)), None);
11920        assert_eq!(
11921            Scalar::Datetime64(1).python_cmp(&Scalar::Timedelta64(1)),
11922            None
11923        );
11924        assert_eq!(host("a").python_cmp(&Scalar::Int64(1)), None);
11925        assert_eq!(host("!a").python_cmp(&host("b")), None);
11926        // Their types as Python's TypeError names them; a host value by its
11927        // host (the default for a host that cannot say is 'object'), a list
11928        // pair by the first unequal items it holds.
11929        assert_eq!(text("a").python_type_name(), "str");
11930        assert_eq!(Scalar::Bool(true).python_type_name(), "bool");
11931        assert_eq!(Scalar::Datetime64(1).python_type_name(), "Timestamp");
11932        assert_eq!(list(vec![]).python_type_name(), "list");
11933        assert_eq!(host("a").python_type_name(), "object");
11934        let (left, right) = list(vec![Scalar::Int64(1), Scalar::Int64(2)])
11935            .python_cmp_type_names(&list(vec![Scalar::Int64(1), text("x")]));
11936        assert_eq!((left.as_str(), right.as_str()), ("int", "str"));
11937        let (left, right) = text("a").python_cmp_type_names(&list(vec![]));
11938        assert_eq!((left.as_str(), right.as_str()), ("str", "list"));
11939    }
11940
11941    #[test]
11942    fn object_cells_print_compare_and_hash_like_python_fvsao_33() {
11943        use std::hash::{Hash, Hasher};
11944
11945        use super::{HostValue, ObjectValue};
11946        let hash = |value: &ObjectValue| {
11947            let mut hasher = std::collections::hash_map::DefaultHasher::new();
11948            value.hash(&mut hasher);
11949            hasher.finish()
11950        };
11951        let list = ObjectValue::list(vec![
11952            Scalar::Int64(1),
11953            Scalar::Utf8("a".to_owned()),
11954            Scalar::Null(NullKind::Null),
11955            Scalar::Float64(2.0),
11956            Scalar::Object(ObjectValue::list(vec![Scalar::Utf8("b".to_owned())])),
11957        ]);
11958        // repr / str (astype(str), writers) quote strings; pandas' display
11959        // (pprint) does not.
11960        assert_eq!(list.repr(), "[1, 'a', None, 2.0, ['b']]");
11961        assert_eq!(list.to_string(), "[1, 'a', None, 2.0, ['b']]");
11962        assert_eq!(list.pprint(), "[1, a, None, 2.0, [b]]");
11963        // An object cell is object data (pandas' object dtype, Utf8 here).
11964        assert_eq!(Scalar::Object(list.clone()).dtype(), DType::Utf8);
11965        assert!(!Scalar::Object(list.clone()).is_missing());
11966        // Equal lists are equal and hash alike; a different item is not
11967        // equal; a list never equals a host value.
11968        let same = ObjectValue::list(list.as_list().unwrap().to_vec());
11969        assert_eq!(list, same);
11970        assert_eq!(hash(&list), hash(&same));
11971        let other = ObjectValue::list(vec![Scalar::Int64(1)]);
11972        assert_ne!(list, other);
11973        let host = ObjectValue::Host(HostValue::new(Named("x")));
11974        assert_ne!(list, host);
11975        // Host values compare and print through the host.
11976        assert_eq!(host, ObjectValue::Host(HostValue::new(Named("x"))));
11977        assert_ne!(host, ObjectValue::Host(HostValue::new(Named("y"))));
11978        assert_eq!(host.repr(), "Named(\"x\")");
11979        assert_eq!(host.to_string(), "x");
11980        // Python truth: an empty list is false, a host value true.
11981        assert!(
11982            !Scalar::Object(ObjectValue::list(Vec::new()))
11983                .to_bool()
11984                .unwrap()
11985        );
11986        assert!(Scalar::Object(host.clone()).to_bool().unwrap());
11987        // A list is not a number.
11988        assert!(Scalar::Object(list.clone()).to_f64().is_err());
11989        // A list cell serializes as its items and reads back; a host value
11990        // refuses to serialize.
11991        let json = serde_json::to_string(&Scalar::Object(other.clone())).unwrap();
11992        assert_eq!(
11993            serde_json::from_str::<Scalar>(&json).unwrap(),
11994            Scalar::Object(other)
11995        );
11996        assert!(serde_json::to_string(&Scalar::Object(host)).is_err());
11997    }
11998
11999    #[test]
12000    fn a_host_cell_displays_by_its_pprint_and_stringifies_by_its_str() {
12001        use super::{HostValue, ObjectValue};
12002
12003        /// A host tuple: Python's str quotes its items, pandas' display not.
12004        struct Pair;
12005        impl super::HostObject for Pair {
12006            fn host_eq(&self, _other: &dyn super::HostObject) -> bool {
12007                false
12008            }
12009            fn host_repr(&self) -> String {
12010                "('a', 1)".to_owned()
12011            }
12012            fn host_str(&self) -> String {
12013                "('a', 1)".to_owned()
12014            }
12015            fn host_pprint(&self) -> String {
12016                "(a, 1)".to_owned()
12017            }
12018            fn host_hash(&self) -> Option<u64> {
12019                None
12020            }
12021            fn host_cmp(&self, _other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
12022                None
12023            }
12024            fn as_any(&self) -> &dyn std::any::Any {
12025                self
12026            }
12027        }
12028        let pair = ObjectValue::Host(HostValue::new(Pair));
12029        assert_eq!(pair.pprint(), "(a, 1)");
12030        // Inside a list cell too.
12031        let list = ObjectValue::list(vec![Scalar::Object(pair.clone())]);
12032        assert_eq!(list.pprint(), "[(a, 1)]");
12033        // NEGATIVE: str (astype(str), writers) stays the host's str.
12034        assert_eq!(pair.to_string(), "('a', 1)");
12035        // NEGATIVE: a host without its own pprint displays by its str.
12036        let named = ObjectValue::Host(HostValue::new(Named("x")));
12037        assert_eq!(named.pprint(), "x");
12038    }
12039
12040    #[test]
12041    fn float64_json_spells_infinity_and_round_trips() {
12042        // br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.3: serde_json
12043        // wrote +-inf as `null` and could not read it back, so pandas'
12044        // division-by-zero answers could not reach a fixture.
12045        let json = |s: &Scalar| serde_json::to_string(s).expect("serialize");
12046        let back = |text: &str| serde_json::from_str::<Scalar>(text);
12047        assert_eq!(
12048            json(&Scalar::Float64(f64::INFINITY)),
12049            r#"{"kind":"float64","value":"inf"}"#
12050        );
12051        assert_eq!(
12052            json(&Scalar::Float64(f64::NEG_INFINITY)),
12053            r#"{"kind":"float64","value":"-inf"}"#
12054        );
12055        // Unchanged spellings: finite numbers, -0.0, and NaN as null.
12056        assert_eq!(
12057            json(&Scalar::Float64(1.5)),
12058            r#"{"kind":"float64","value":1.5}"#
12059        );
12060        assert_eq!(
12061            json(&Scalar::Float64(-0.0)),
12062            r#"{"kind":"float64","value":-0.0}"#
12063        );
12064        assert_eq!(
12065            json(&Scalar::Float64(f64::NAN)),
12066            r#"{"kind":"float64","value":null}"#
12067        );
12068        for value in [f64::INFINITY, f64::NEG_INFINITY, 1.5, -2.25e300] {
12069            let scalar = Scalar::Float64(value);
12070            assert_eq!(back(&json(&scalar)).expect("round trip"), scalar);
12071        }
12072        let negative_zero = back(r#"{"kind":"float64","value":-0.0}"#).expect("-0.0");
12073        assert!(matches!(negative_zero, Scalar::Float64(v) if v == 0.0 && v.is_sign_negative()));
12074        assert!(matches!(
12075            back(r#"{"kind":"float64","value":null}"#).expect("null"),
12076            Scalar::Float64(v) if v.is_nan()
12077        ));
12078        // Anything else is an error, not a silent NaN.
12079        assert!(back(r#"{"kind":"float64","value":"Infinity"}"#).is_err());
12080        assert!(back(r#"{"kind":"float64","value":"1.5"}"#).is_err());
12081    }
12082
12083    /// br-frankenpandas-ay8o9: Scalar::semantic_cmp underpins ALL ordering in
12084    /// the library (sort, min/max, is_monotonic, searchsorted, groupby key
12085    /// order) and is the reference the differential harnesses rely on. Property
12086    /// test of its total-order axioms over finite/non-NaT same-dtype scalars,
12087    /// plus the intentional NaN degeneracy. Deterministic seeded LCG — no rand
12088    /// crate, no mocks.
12089    /// br-frankenpandas-767ak: extends ay8o9's NaN pinning to the temporal NAT
12090    /// sentinels (i64::MIN). semantic_cmp treats NAT as degenerate (Equal to all
12091    /// same-dtype), which is why temporal ordering ops must treat NAT as missing.
12092    #[test]
12093    fn semantic_cmp_cross_numeric_int_float_cdpai() {
12094        // Property (br-frankenpandas-cdpai): semantic_cmp compares Int64 vs Float64
12095        // as f64, antisymmetric across the operand order. Seeded LCG, no mocks.
12096        use std::cmp::Ordering;
12097        let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
12098        let mut next = || {
12099            st = st
12100                .wrapping_mul(6_364_136_223_846_793_005)
12101                .wrapping_add(1_442_695_040_888_963_407);
12102            (st >> 33) as u32
12103        };
12104        for _ in 0..3000u32 {
12105            let i = (next() % 21) as i64 - 10;
12106            let f = (next() % 400) as f64 / 20.0 - 10.0; // finite
12107            let exp = (i as f64).partial_cmp(&f).unwrap();
12108            assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
12109            assert_eq!(
12110                Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
12111                exp.reverse()
12112            );
12113        }
12114        // Exact int/float equality compares Equal in both directions.
12115        assert_eq!(
12116            Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
12117            Ordering::Equal
12118        );
12119        assert_eq!(
12120            Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
12121            Ordering::Equal
12122        );
12123        assert_eq!(
12124            Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
12125            Ordering::Less
12126        );
12127        assert_eq!(
12128            Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
12129            Ordering::Greater
12130        );
12131    }
12132
12133    #[test]
12134    fn semantic_cmp_nat_degeneracy_temporal_767ak() {
12135        use std::cmp::Ordering;
12136        const NAT: i64 = i64::MIN;
12137
12138        // Timedelta64 NAT is degenerate (Equal to finite and to itself).
12139        let td_nat = Scalar::Timedelta64(NAT);
12140        for v in [-3i64, 0, 5, 99] {
12141            let td = Scalar::Timedelta64(v);
12142            assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
12143            assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
12144        }
12145        assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
12146
12147        // Datetime64 NAT likewise.
12148        let dt_nat = Scalar::Datetime64(NAT);
12149        for v in [-3i64, 0, 5, 99] {
12150            let dt = Scalar::Datetime64(v);
12151            assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
12152            assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
12153        }
12154        assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
12155
12156        // Non-NAT temporal values order normally (reflexive, antisymmetric, lt).
12157        for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
12158            let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
12159            assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
12160            assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); // a.cmp(b)
12161            assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
12162            let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
12163            assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
12164        }
12165    }
12166
12167    fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
12168        [
12169            Scalar::Null(NullKind::Null),
12170            Scalar::Bool(true),
12171            Scalar::Int64(-7),
12172            Scalar::Float64(3.5),
12173            Scalar::Utf8("mixed".to_owned()),
12174            Scalar::Timedelta64(11),
12175            Scalar::Datetime64(1_735_732_800_123_456_789),
12176            Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
12177            Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
12178        ]
12179    }
12180
12181    fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
12182        !matches!(
12183            (left, right),
12184            (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
12185        )
12186    }
12187
12188    #[test]
12189    fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
12190        let values = semantic_cmp_cross_variant_values_d5ikg();
12191        for (left_index, left) in values.iter().enumerate() {
12192            for (right_index, right) in values.iter().enumerate() {
12193                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12194                {
12195                    assert_eq!(
12196                        left.semantic_cmp(right),
12197                        format!("{left:?}").cmp(&format!("{right:?}")),
12198                        "cross-variant order mismatch: {left:?} vs {right:?}"
12199                    );
12200                }
12201            }
12202        }
12203    }
12204
12205    #[test]
12206    #[ignore = "foreground release attribution harness"]
12207    fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
12208        use std::cmp::Ordering;
12209
12210        const BATCH: usize = 4_096;
12211        const BLOCKS: usize = 9;
12212
12213        fn former(left: &Scalar, right: &Scalar) -> Ordering {
12214            format!("{left:?}").cmp(&format!("{right:?}"))
12215        }
12216
12217        fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
12218            left.semantic_cmp(right)
12219        }
12220
12221        fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
12222            let mut less = 0usize;
12223            let started = std::time::Instant::now();
12224            for _ in 0..BATCH {
12225                for (left_index, left) in values.iter().enumerate() {
12226                    for (right_index, right) in values.iter().enumerate() {
12227                        if left_index != right_index
12228                            && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12229                            && compare(std::hint::black_box(left), std::hint::black_box(right))
12230                                == Ordering::Less
12231                        {
12232                            less += 1;
12233                        }
12234                    }
12235                }
12236            }
12237            std::hint::black_box(less);
12238            started.elapsed().as_nanos()
12239        }
12240
12241        fn median(samples: &mut [u128]) -> u128 {
12242            samples.sort_unstable();
12243            samples[samples.len() / 2]
12244        }
12245
12246        let values = semantic_cmp_cross_variant_values_d5ikg();
12247
12248        for (left_index, left) in values.iter().enumerate() {
12249            for (right_index, right) in values.iter().enumerate() {
12250                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12251                {
12252                    assert_eq!(
12253                        former(left, right),
12254                        candidate(left, right),
12255                        "cross-variant order mismatch: {left:?} vs {right:?}"
12256                    );
12257                }
12258            }
12259        }
12260
12261        std::hint::black_box(elapsed(&values, former));
12262        std::hint::black_box(elapsed(&values, candidate));
12263
12264        let mut former_samples = Vec::with_capacity(BLOCKS * 2);
12265        let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
12266        for block in 0..BLOCKS {
12267            if block.is_multiple_of(2) {
12268                former_samples.push(elapsed(&values, former));
12269                candidate_samples.push(elapsed(&values, candidate));
12270                candidate_samples.push(elapsed(&values, candidate));
12271                former_samples.push(elapsed(&values, former));
12272            } else {
12273                candidate_samples.push(elapsed(&values, candidate));
12274                former_samples.push(elapsed(&values, former));
12275                former_samples.push(elapsed(&values, former));
12276                candidate_samples.push(elapsed(&values, candidate));
12277            }
12278        }
12279
12280        let former_p50 = median(&mut former_samples);
12281        let candidate_p50 = median(&mut candidate_samples);
12282        eprintln!(
12283            "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
12284            former_p50 as f64 / candidate_p50 as f64
12285        );
12286    }
12287
12288    #[test]
12289    fn semantic_cmp_total_order_axioms_ay8o9() {
12290        use std::cmp::Ordering;
12291
12292        let mut state: u64 = 0xc0ff_eeba_df00_d123;
12293        let mut next = || {
12294            state = state
12295                .wrapping_mul(6_364_136_223_846_793_005)
12296                .wrapping_add(1_442_695_040_888_963_407);
12297            (state >> 33) as u32
12298        };
12299
12300        for iter in 0..6000u32 {
12301            let dt = next() % 4;
12302            // Build a same-dtype, finite, non-NaT scalar from a random u32.
12303            let mk = |r: u32| match dt {
12304                0 => Scalar::Int64((r % 11) as i64 - 5),
12305                // finite, in -5.0..=5.0 by 0.5 — no NaN/inf.
12306                1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
12307                2 => Scalar::Utf8(format!("s{}", r % 5)),
12308                _ => Scalar::Bool(r.is_multiple_of(2)),
12309            };
12310            let a = mk(next());
12311            let b = mk(next());
12312            let c = mk(next());
12313            let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
12314
12315            // Reflexivity.
12316            assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
12317            // Antisymmetry.
12318            assert_eq!(
12319                a.semantic_cmp(&b),
12320                b.semantic_cmp(&a).reverse(),
12321                "antisymmetric {ctx}"
12322            );
12323            // le / ge / eq consistency with the ordering.
12324            let ab = a.semantic_cmp(&b);
12325            assert_eq!(
12326                a.semantic_le(&b),
12327                ab != Ordering::Greater,
12328                "le-consistent {ctx}"
12329            );
12330            assert_eq!(
12331                a.semantic_ge(&b),
12332                ab != Ordering::Less,
12333                "ge-consistent {ctx}"
12334            );
12335            assert_eq!(
12336                a.semantic_le(&b) && a.semantic_ge(&b),
12337                ab == Ordering::Equal,
12338                "le&ge<=>eq {ctx}"
12339            );
12340            // Transitivity: a<=b && b<=c  =>  a<=c.
12341            if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
12342                assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
12343            }
12344        }
12345
12346        // Pin the intentional NaN degeneracy: a Float64 NaN compares Equal to
12347        // every finite Float64 (and to itself) — this is why ordering ops must
12348        // treat NaN as missing rather than relying on semantic_cmp to order it.
12349        let nan = Scalar::Float64(f64::NAN);
12350        for v in [
12351            Scalar::Float64(-3.5),
12352            Scalar::Float64(0.0),
12353            Scalar::Float64(7.25),
12354        ] {
12355            assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
12356            assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
12357        }
12358        assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
12359    }
12360
12361    /// br-frankenpandas-be314: common_dtype is the dtype-promotion lattice
12362    /// underpinning every binary op, alignment, and concat (dtype coercion is a
12363    /// crown-jewel correctness area). Exhaustively (all 14x14 DType pairs) assert
12364    /// its lattice axioms — an asymmetric arm would make df1+df2 and df2+df1
12365    /// disagree on dtype.
12366    #[test]
12367    fn common_dtype_lattice_axioms_be314() {
12368        let all: [DType; 14] = [
12369            DType::Null,
12370            DType::Bool,
12371            DType::BoolNullable,
12372            DType::Int64,
12373            DType::Int64Nullable,
12374            DType::Float64,
12375            // br-frankenpandas-qkqfb: a new variant is only safe once the
12376            // commutativity and associativity sweeps below cover it.
12377            DType::Float64Nullable,
12378            DType::Utf8,
12379            DType::Categorical,
12380            DType::Timedelta64,
12381            DType::datetime64_naive(),
12382            DType::Period,
12383            DType::Interval,
12384            DType::Sparse,
12385        ];
12386
12387        for a in &all {
12388            // Idempotence: a promoted with itself is itself.
12389            assert_eq!(
12390                common_dtype(a.clone(), a.clone()),
12391                Ok(a.clone()),
12392                "idempotent {a:?}"
12393            );
12394            // Null is the identity element of the promotion lattice.
12395            assert_eq!(
12396                common_dtype(DType::Null, a.clone()),
12397                Ok(a.clone()),
12398                "null-left identity {a:?}"
12399            );
12400            assert_eq!(
12401                common_dtype(a.clone(), DType::Null),
12402                Ok(a.clone()),
12403                "null-right identity {a:?}"
12404            );
12405
12406            for b in &all {
12407                // Commutativity: same Ok value AND same ok-ness. An asymmetric
12408                // match arm would make binary-op output dtype order-dependent.
12409                assert_eq!(
12410                    common_dtype(a.clone(), b.clone()).ok(),
12411                    common_dtype(b.clone(), a.clone()).ok(),
12412                    "commutative value {a:?},{b:?}"
12413                );
12414                assert_eq!(
12415                    common_dtype(a.clone(), b.clone()).is_ok(),
12416                    common_dtype(b.clone(), a.clone()).is_ok(),
12417                    "commutative ok-ness {a:?},{b:?}"
12418                );
12419            }
12420        }
12421
12422        // Associativity over the Ok-closed subset: when both nestings succeed,
12423        // promotion order must not change the result.
12424        for a in &all {
12425            for b in &all {
12426                for c in &all {
12427                    if let (Ok(ab), Ok(bc)) = (
12428                        common_dtype(a.clone(), b.clone()),
12429                        common_dtype(b.clone(), c.clone()),
12430                    ) && let (Ok(left), Ok(right)) =
12431                        (common_dtype(ab, c.clone()), common_dtype(a.clone(), bc))
12432                    {
12433                        assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
12434                    }
12435                }
12436            }
12437        }
12438    }
12439
12440    /// br-frankenpandas-e3sfq: infer_dtype drives Column/Series construction
12441    /// dtype inference. Assert its homogeneous + mixed-coercion rules.
12442    #[test]
12443    fn infer_dtype_coercion_rules_e3sfq() {
12444        use DType::{Bool, Float64, Int64, Null, Utf8};
12445
12446        // Empty and all-null infer to Null.
12447        assert_eq!(infer_dtype(&[]), Ok(Null));
12448        assert_eq!(
12449            infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
12450            Ok(Null)
12451        );
12452
12453        // Homogeneous slices infer to their own dtype (random, seeded LCG).
12454        let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
12455        let mut next = || {
12456            s = s
12457                .wrapping_mul(6_364_136_223_846_793_005)
12458                .wrapping_add(1_442_695_040_888_963_407);
12459            (s >> 33) as u32
12460        };
12461        for _ in 0..600u32 {
12462            let n = (next() % 6) as usize + 1;
12463            let ints: Vec<Scalar> = (0..n)
12464                .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
12465                .collect();
12466            assert_eq!(infer_dtype(&ints), Ok(Int64));
12467            let floats: Vec<Scalar> = (0..n)
12468                .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
12469                .collect();
12470            assert_eq!(infer_dtype(&floats), Ok(Float64));
12471            let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
12472            assert_eq!(infer_dtype(&bools), Ok(Bool));
12473            let strs: Vec<Scalar> = (0..n)
12474                .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
12475                .collect();
12476            assert_eq!(infer_dtype(&strs), Ok(Utf8));
12477        }
12478
12479        // Mixed-coercion rules.
12480        assert_eq!(
12481            infer_dtype(&[
12482                Scalar::Int64(1),
12483                Scalar::Null(NullKind::Null),
12484                Scalar::Int64(2)
12485            ]),
12486            Ok(Int64),
12487            "Int64 + nulls -> Int64"
12488        );
12489        assert_eq!(
12490            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
12491            Ok(Float64),
12492            "Int64 + Float64 -> Float64"
12493        );
12494        // br-frankenpandas-rh1od: MEASURED live pandas 2.2.3 — a bool mixed
12495        // with numerics constructs OBJECT; the old Int64 coercion here was
12496        // numpy common-type behavior no pandas constructor path produces.
12497        assert_eq!(
12498            infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
12499            Ok(Utf8),
12500            "Bool + Int64 -> object bucket (pandas constructs object)"
12501        );
12502        assert_eq!(
12503            infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
12504            Ok(Utf8),
12505            "Utf8 + Int64 -> Utf8 (object fallback)"
12506        );
12507    }
12508
12509    /// br-frankenpandas-1ews0: missing_for_dtype is the canonical per-dtype
12510    /// missing sentinel (used by null-fill / with_validity / cast). Exhaustively
12511    /// assert it is always missing, and that casting any missing to any dtype
12512    /// stays missing.
12513    #[test]
12514    fn missing_for_dtype_always_missing_1ews0() {
12515        let all: [DType; 14] = [
12516            DType::Null,
12517            DType::Bool,
12518            DType::BoolNullable,
12519            DType::Int64,
12520            DType::Int64Nullable,
12521            DType::Float64,
12522            DType::Float64Nullable,
12523            DType::Utf8,
12524            DType::Categorical,
12525            DType::Timedelta64,
12526            DType::datetime64_naive(),
12527            DType::Period,
12528            DType::Interval,
12529            DType::Sparse,
12530        ];
12531        for dt in &all {
12532            let m = Scalar::missing_for_dtype(dt.clone());
12533            assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
12534            for target in &all {
12535                let cast = cast_scalar(&m, target.clone()).expect("cast of missing");
12536                if target == &DType::Utf8 {
12537                    // Casting a missing value to string follows pandas astype(str):
12538                    // it yields a string ("None"/"NaN"/"NaT"), NOT a missing value.
12539                    assert!(
12540                        matches!(cast, Scalar::Utf8(_)),
12541                        "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
12542                    );
12543                } else if matches!(dt, DType::Timedelta64 | DType::Datetime64 { .. })
12544                    && matches!(target, DType::Bool | DType::Int64)
12545                {
12546                    // ⚠️ TWO MORE PLACES pandas BREAKS this invariant, and both
12547                    // are the same underlying fact: NaT is not a separate
12548                    // representation, it IS i64::MIN, and the numpy casts read
12549                    // the bits. MEASURED, live pandas 2.2.3:
12550                    //
12551                    //   pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
12552                    //     -> -9223372036854775808      the SENTINEL, not a missing
12553                    //   pd.Series([pd.NaT], dtype='timedelta64[ns]').astype('bool')
12554                    //     -> True                      nonzero, so truthy
12555                    //
12556                    // Same shape as the Utf8 carve-out above: the invariant is
12557                    // FrankenPandas' own, and pandas does not honour it wherever
12558                    // a cast is defined to reinterpret rather than to convert.
12559                    // Narrowly scoped on purpose — every other missing, and these
12560                    // two toward every other target, still stay missing.
12561                    match target {
12562                        DType::Bool => assert_eq!(
12563                            cast,
12564                            Scalar::Bool(true),
12565                            "cast(missing {dt:?} -> Bool) is pandas' nonzero-truthy \
12566                             read of the NaT bits"
12567                        ),
12568                        _ => assert_eq!(
12569                            cast,
12570                            Scalar::Int64(i64::MIN),
12571                            "cast(missing {dt:?} -> Int64) is the NaT sentinel itself"
12572                        ),
12573                    }
12574                } else {
12575                    // Every other target preserves missingness via cast_scalar's
12576                    // value.is_missing() -> missing_for_dtype(target) branch.
12577                    assert!(
12578                        cast.is_missing(),
12579                        "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
12580                    );
12581                }
12582            }
12583        }
12584    }
12585
12586    #[test]
12587    fn cast_scalar_bool_int_roundtrip_6w07b() {
12588        use super::cast_scalar;
12589        // Property (br-frankenpandas-6w07b): Bool<->Int64 cast. Seeded LCG, no mocks.
12590        assert_eq!(
12591            cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
12592            Scalar::Int64(1)
12593        );
12594        assert_eq!(
12595            cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
12596            Scalar::Int64(0)
12597        );
12598        assert_eq!(
12599            cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
12600            Scalar::Bool(false)
12601        );
12602        let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
12603        let mut next = || {
12604            st = st
12605                .wrapping_mul(6_364_136_223_846_793_005)
12606                .wrapping_add(1_442_695_040_888_963_407);
12607            (st >> 33) as u32
12608        };
12609        for _ in 0..2000u32 {
12610            let v = (next() % 21) as i64 - 10;
12611            assert_eq!(
12612                cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
12613                Scalar::Bool(v != 0),
12614                "int->bool v={v}"
12615            );
12616        }
12617    }
12618
12619    /// br-frankenpandas-6a83t: cast_scalar is the scalar dtype-coercion path
12620    #[test]
12621    fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
12622        use super::cast_scalar;
12623        // Property (br-frankenpandas-u9lec): Float64->Int64 truncates toward zero, not
12624        // floor (-3.7 -> -3). Seeded LCG, no mocks.
12625        let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
12626        let mut next = || {
12627            st = st
12628                .wrapping_mul(6_364_136_223_846_793_005)
12629                .wrapping_add(1_442_695_040_888_963_407);
12630            (st >> 33) as u32
12631        };
12632        // Explicit negative-direction checks (the gotcha).
12633        for (f, exp) in [
12634            (-3.7, -3i64),
12635            (3.7, 3),
12636            (-3.2, -3),
12637            (3.2, 3),
12638            (-0.9, 0),
12639            (0.9, 0),
12640            (-5.0, -5),
12641            (5.0, 5),
12642        ] {
12643            assert_eq!(
12644                cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
12645                Scalar::Int64(exp),
12646                "cast {f}"
12647            );
12648        }
12649        // Property over random signed fractional values.
12650        for _ in 0..3000u32 {
12651            let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; // [-1000, 1000]
12652            let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
12653            assert_eq!(
12654                got,
12655                Scalar::Int64(v.trunc() as i64),
12656                "trunc-toward-zero v={v}"
12657            );
12658        }
12659    }
12660
12661    /// Float -> `datetime64[ns]` / `timedelta64[ns]` reinterprets the float as
12662    /// integer NANOSECONDS. Every value here is transcribed from live pandas
12663    /// 2.2.3, measured on both the constructor and `astype` paths.
12664    ///
12665    /// ⚠️ THE CONTRAST WITH `int64` IS THE POINT: the explicit constructor
12666    /// REFUSES a lossy float -> int64, and silently truncates the same float
12667    /// into a temporal dtype. Assuming one rule covers both is how this gets
12668    /// re-broken, so both are asserted here on the same input.
12669    #[test]
12670    fn cast_scalar_float_to_temporal_truncates_to_nanoseconds() {
12671        use super::{Timedelta, Timestamp, cast_scalar};
12672
12673        // TRUNCATION TOWARD ZERO, on both signs, where a floor would disagree.
12674        // pandas: 0.9 -> 0, -0.9 -> 0, 1.5 -> 1, -1.5 -> -1, -2.5 -> -2.
12675        for (input, want) in [
12676            (1.5_f64, 1_i64),
12677            (-1.5, -1),
12678            (0.9, 0),
12679            (-0.9, 0),
12680            (2.5, 2),
12681            (-2.5, -2),
12682            (1.999_999, 1),
12683            (-1.999_999, -1),
12684            (2.0, 2),
12685            (1e18, 1_000_000_000_000_000_000),
12686        ] {
12687            assert_eq!(
12688                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
12689                Scalar::Datetime64(want),
12690                "datetime64 cast of {input}"
12691            );
12692            assert_eq!(
12693                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
12694                Scalar::Timedelta64(want),
12695                "timedelta64 cast of {input}"
12696            );
12697        }
12698
12699        // ANYTHING NOT REPRESENTABLE AS i64 IS NaT — not a saturated i64::MAX,
12700        // and not the epoch. A bare `as i64` would produce both of those wrong
12701        // answers (saturation for the large values, 0 for NaN).
12702        for input in [
12703            f64::NAN,
12704            f64::INFINITY,
12705            f64::NEG_INFINITY,
12706            1e30,
12707            -1e30,
12708            9.3e18,
12709            -9.3e18,
12710            9_223_372_036_854_775_808.0,  // exactly 2^63
12711            -9_223_372_036_854_775_808.0, // exactly -2^63, which IS the NaT sentinel
12712        ] {
12713            assert_eq!(
12714                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
12715                Scalar::Datetime64(Timestamp::NAT),
12716                "datetime64 cast of {input} must be NaT"
12717            );
12718            assert_eq!(
12719                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
12720                Scalar::Timedelta64(Timedelta::NAT),
12721                "timedelta64 cast of {input} must be NaT"
12722            );
12723        }
12724
12725        // ...but the largest float BELOW 2^63 is representable and converts.
12726        // pandas renders it 2262-04-11 23:47:16.854774784.
12727        let just_inside = 9_223_372_036_854_774_784.0_f64; // 2^63 - 1024
12728        assert_eq!(
12729            cast_scalar(&Scalar::Float64(just_inside), DType::datetime64_naive()).unwrap(),
12730            Scalar::Datetime64(9_223_372_036_854_774_784),
12731            "the largest representable float must NOT be treated as NaT"
12732        );
12733
12734        // THE CONTRAST. Same input, three dtypes, two different rules — the
12735        // temporal ones truncate where int64 refuses outright.
12736        assert_eq!(
12737            cast_scalar(&Scalar::Float64(1.5), DType::datetime64_naive()).unwrap(),
12738            Scalar::Datetime64(1)
12739        );
12740        assert_eq!(
12741            cast_scalar(&Scalar::Float64(1.5), DType::Int64).unwrap(),
12742            Scalar::Int64(1),
12743            "the SHARED cast truncates here too; it is the explicit constructor \
12744             that refuses, via Column::new's LossyFloatToInt pre-check"
12745        );
12746    }
12747
12748    /// The MIRROR direction: `datetime64[ns]` / `timedelta64[ns]` -> numpy
12749    /// `int64` is the raw nanosecond count, and a bool is 0 or 1 nanoseconds
12750    /// going the other way. Every value transcribed from live pandas 2.2.3
12751    /// `astype`.
12752    #[test]
12753    fn cast_scalar_temporal_to_int64_is_raw_nanoseconds() {
12754        use super::{Timedelta, Timestamp, cast_scalar};
12755
12756        // Timestamp('2024-03-15 10:30:45.123456789') and
12757        // Timedelta('1 days 02:03:04.005006007').
12758        for nanos in [1_710_498_645_123_456_789_i64, 93_784_005_006_007, 0, -1] {
12759            assert_eq!(
12760                cast_scalar(&Scalar::Datetime64(nanos), DType::Int64).unwrap(),
12761                Scalar::Int64(nanos),
12762                "datetime64 -> int64 must be the raw nanos ({nanos})"
12763            );
12764            assert_eq!(
12765                cast_scalar(&Scalar::Timedelta64(nanos), DType::Int64).unwrap(),
12766                Scalar::Int64(nanos)
12767            );
12768        }
12769
12770        // ⚠️ NaT BECOMES THE SENTINEL, NOT A MISSING VALUE. pandas:
12771        //     pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
12772        //       -> -9223372036854775808
12773        // This is the assertion that pins the cast ABOVE the is_missing()
12774        // branch; move it below and both of these become Null.
12775        assert_eq!(
12776            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Int64).unwrap(),
12777            Scalar::Int64(i64::MIN),
12778            "NaT -> int64 is the sentinel i64::MIN, not a missing value"
12779        );
12780        assert_eq!(
12781            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Int64).unwrap(),
12782            Scalar::Int64(i64::MIN)
12783        );
12784
12785        // ⚠️ THE NULLABLE Int64 REFUSES WHAT numpy int64 ACCEPTS:
12786        //     .astype('Int64')   -> TypeError: datetime64[ns] cannot be
12787        //                          converted to IntegerDtype
12788        //     .astype('float64') -> TypeError: Cannot cast DatetimeArray
12789        // Both must stay refused, which is what makes the guard on the exact
12790        // target load-bearing rather than cosmetic.
12791        // `DType` stopped being `Copy` when `Datetime64 { tz }` landed
12792        // (2f159e68f), so the loop variable is cloned into each call.
12793        for target in [DType::Int64Nullable, DType::Float64, DType::Float64Nullable] {
12794            assert!(
12795                cast_scalar(
12796                    &Scalar::Datetime64(1_710_498_645_123_456_789),
12797                    target.clone()
12798                )
12799                .is_err(),
12800                "datetime64 -> {target:?} must stay refused"
12801            );
12802            assert!(
12803                cast_scalar(&Scalar::Timedelta64(93_784_005_006_007), target.clone()).is_err(),
12804                "timedelta64 -> {target:?} must stay refused"
12805            );
12806        }
12807
12808        // A bool is 0 or 1 NANOSECONDS on the astype path.
12809        for (flag, want) in [(true, 1_i64), (false, 0)] {
12810            assert_eq!(
12811                cast_scalar(&Scalar::Bool(flag), DType::datetime64_naive()).unwrap(),
12812                Scalar::Datetime64(want)
12813            );
12814            assert_eq!(
12815                cast_scalar(&Scalar::Bool(flag), DType::Timedelta64).unwrap(),
12816                Scalar::Timedelta64(want)
12817            );
12818        }
12819    }
12820
12821    /// The two halves of the column-width datetime formatter, checked apart:
12822    /// which rung a value NEEDS, and how a value RENDERS at a given rung.
12823    /// Transcribed from live pandas 2.2.3 `.astype(str)`, one column per rung.
12824    #[test]
12825    fn timestamp_string_resolution_and_formatting_match_pandas() {
12826        use super::{DatetimeStringResolution as Res, Timestamp};
12827
12828        const MIDNIGHT: i64 = 1_710_460_800_000_000_000; // 2024-03-15 00:00:00
12829
12830        // Which rung each value needs, on its own.
12831        assert_eq!(Timestamp::string_resolution(MIDNIGHT), Res::Date);
12832        assert_eq!(
12833            Timestamp::string_resolution(MIDNIGHT + 37_845_000_000_000),
12834            Res::Second
12835        );
12836        assert_eq!(
12837            Timestamp::string_resolution(MIDNIGHT + 37_845_123_000_000),
12838            Res::Milli
12839        );
12840        assert_eq!(
12841            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_000),
12842            Res::Micro
12843        );
12844        assert_eq!(
12845            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_789),
12846            Res::Nano
12847        );
12848        // A whole MINUTE is not its own rung — it still needs Second.
12849        assert_eq!(
12850            Timestamp::string_resolution(MIDNIGHT + 300_000_000_000),
12851            Res::Second
12852        );
12853        // NaT reports the coarsest rung, the identity of the `max` fold, which
12854        // is what keeps it from dragging a column to nanoseconds.
12855        assert_eq!(Timestamp::string_resolution(Timestamp::NAT), Res::Date);
12856
12857        // Coarsest-first ordering is what makes `max` mean "finest needed".
12858        assert!(Res::Date < Res::Second);
12859        assert!(Res::Second < Res::Milli);
12860        assert!(Res::Milli < Res::Micro);
12861        assert!(Res::Micro < Res::Nano);
12862
12863        // ...and how ONE value renders at each rung it might be forced into.
12864        let value = MIDNIGHT + 37_845_123_456_789;
12865        assert_eq!(
12866            Timestamp::format_at_resolution(value, Res::Date),
12867            "2024-03-15"
12868        );
12869        assert_eq!(
12870            Timestamp::format_at_resolution(value, Res::Second),
12871            "2024-03-15 10:30:45"
12872        );
12873        assert_eq!(
12874            Timestamp::format_at_resolution(value, Res::Milli),
12875            "2024-03-15 10:30:45.123"
12876        );
12877        assert_eq!(
12878            Timestamp::format_at_resolution(value, Res::Micro),
12879            "2024-03-15 10:30:45.123456"
12880        );
12881        assert_eq!(
12882            Timestamp::format_at_resolution(value, Res::Nano),
12883            "2024-03-15 10:30:45.123456789"
12884        );
12885
12886        // A midnight forced to the nanosecond rung keeps its zero fraction --
12887        // pandas pads, it does not trim.
12888        assert_eq!(
12889            Timestamp::format_at_resolution(MIDNIGHT, Res::Nano),
12890            "2024-03-15 00:00:00.000000000"
12891        );
12892
12893        // ⚠️ NOT isoformat: a SPACE separator, not a `T`.
12894        assert_eq!(
12895            Timestamp::format_at_resolution(MIDNIGHT, Res::Second),
12896            "2024-03-15 00:00:00"
12897        );
12898
12899        // NaT is the STRING "NaT" at every rung.
12900        for resolution in [Res::Date, Res::Second, Res::Milli, Res::Micro, Res::Nano] {
12901            assert_eq!(
12902                Timestamp::format_at_resolution(Timestamp::NAT, resolution),
12903                "NaT"
12904            );
12905        }
12906
12907        // Pre-epoch: rem_euclid must keep the fraction on the right side of
12908        // midnight, or -1ns renders as 1970-01-01 with a negative fraction.
12909        assert_eq!(
12910            Timestamp::format_at_resolution(-1, Res::Nano),
12911            "1969-12-31 23:59:59.999999999"
12912        );
12913
12914        // Both ends of pandas' datetime64[ns] range.
12915        assert_eq!(
12916            Timestamp::format_at_resolution(-9_223_372_036_854_775_806, Res::Nano),
12917            "1677-09-21 00:12:43.145224194"
12918        );
12919        assert_eq!(
12920            Timestamp::format_at_resolution(9_223_372_036_854_775_807, Res::Nano),
12921            "2262-04-11 23:47:16.854775807"
12922        );
12923    }
12924
12925    /// Temporal -> numpy `bool` is nonzero-truthy on the RAW NANOSECONDS, which
12926    /// makes NaT `true`. Transcribed from live pandas 2.2.3 `.astype('bool')`,
12927    /// measured beside `.astype('int64')` so the one rule is visible as one rule.
12928    #[test]
12929    fn cast_scalar_temporal_to_bool_is_nonzero_on_the_nanos() {
12930        use super::{Timedelta, Timestamp, cast_scalar};
12931
12932        // Only the epoch and a zero duration are false.
12933        for (nanos, want) in [
12934            (0_i64, false),
12935            (1_710_498_645_123_456_789, true),
12936            (-1, true),
12937            (86_400_000_000_000, true),
12938            (1, true),
12939        ] {
12940            assert_eq!(
12941                cast_scalar(&Scalar::Datetime64(nanos), DType::Bool).unwrap(),
12942                Scalar::Bool(want),
12943                "datetime64 {nanos} -> bool"
12944            );
12945            assert_eq!(
12946                cast_scalar(&Scalar::Timedelta64(nanos), DType::Bool).unwrap(),
12947                Scalar::Bool(want),
12948                "timedelta64 {nanos} -> bool"
12949            );
12950        }
12951
12952        // ⚠️ NaT IS TRUE, not missing. It needs no case of its own — NaT IS
12953        // i64::MIN, which is nonzero — but it only reaches the rule because the
12954        // cast sits ABOVE is_missing(); below it, both of these become Null.
12955        assert_eq!(
12956            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Bool).unwrap(),
12957            Scalar::Bool(true),
12958            "NaT -> bool is true in pandas, not a missing value"
12959        );
12960        assert_eq!(
12961            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Bool).unwrap(),
12962            Scalar::Bool(true)
12963        );
12964
12965        // ⚠️ THE NULLABLE `boolean` REFUSES THE WHOLE DTYPE, not just the odd
12966        // value: pandas raises "Need to pass bool-like values" for every row
12967        // above, INCLUDING the ones whose nanos are 0 or 1. That exclusion is
12968        // what the `DType::Bool` guard buys, so it is asserted rather than
12969        // assumed.
12970        //
12971        // NaT is deliberately NOT in this loop, and the reason is a KNOWN
12972        // DIVERGENCE rather than an oversight: `is_missing()` catches NaT before
12973        // any BoolNullable arm can refuse it, so FP answers `Null` where pandas
12974        // raises. Asserting `is_err()` for it here would fail. Left visible.
12975        for nanos in [0_i64, 1, -1, 1_710_498_645_123_456_789] {
12976            assert!(
12977                cast_scalar(&Scalar::Datetime64(nanos), DType::BoolNullable).is_err(),
12978                "datetime64 {nanos} -> nullable boolean must stay refused"
12979            );
12980            assert!(
12981                cast_scalar(&Scalar::Timedelta64(nanos), DType::BoolNullable).is_err(),
12982                "timedelta64 {nanos} -> nullable boolean must stay refused"
12983            );
12984        }
12985    }
12986
12987    #[test]
12988    fn nancount_nunique_prod_any_all_mx60x() {
12989        use super::{nanall, nanany, nancount, nannunique, nanprod};
12990        // br-frankenpandas-mx60x: nancount/nannunique/nanprod/nanany/nanall skip NaN
12991        // and match finite-only oracles. Seeded LCG, no mocks.
12992        let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
12993        let mut next = || {
12994            s = s
12995                .wrapping_mul(6_364_136_223_846_793_005)
12996                .wrapping_add(1_442_695_040_888_963_407);
12997            (s >> 33) as u32
12998        };
12999        let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
13000        let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
13001        for iter in 0..1000u32 {
13002            let n = (next() % 10) as usize + 1;
13003            let raw: Vec<f64> = (0..n)
13004                .map(|_| {
13005                    if next() % 4 == 0 {
13006                        f64::NAN
13007                    } else {
13008                        (next() % 5) as f64
13009                    }
13010                })
13011                .collect();
13012            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13013            if finite.is_empty() {
13014                continue;
13015            }
13016            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13017            let distinct: std::collections::HashSet<u64> =
13018                finite.iter().map(|x| x.to_bits()).collect();
13019            let prod: f64 = finite.iter().product();
13020            assert!(
13021                (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
13022                "nancount iter={iter}"
13023            );
13024            assert!(
13025                (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
13026                "nannunique iter={iter}"
13027            );
13028            assert!(
13029                (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
13030                "nanprod iter={iter}"
13031            );
13032            assert_eq!(
13033                asb(nanany(&scalars)),
13034                finite.iter().any(|&x| x != 0.0),
13035                "nanany iter={iter}"
13036            );
13037            assert_eq!(
13038                asb(nanall(&scalars)),
13039                finite.iter().all(|&x| x != 0.0),
13040                "nanall iter={iter}"
13041            );
13042        }
13043    }
13044
13045    #[test]
13046    fn nan_reduction_kernels_skip_correctness_1uagc() {
13047        use super::{nanmax, nanmedian, nanmin, nansum};
13048        // br-frankenpandas-1uagc: nansum/nanmin/nanmax/nanmedian skip NaN and match
13049        // finite-only oracles. Seeded LCG, no mocks.
13050        let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
13051        let mut next = || {
13052            s = s
13053                .wrapping_mul(6_364_136_223_846_793_005)
13054                .wrapping_add(1_442_695_040_888_963_407);
13055            (s >> 33) as u32
13056        };
13057        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
13058        for iter in 0..1000u32 {
13059            let n = (next() % 12) as usize + 1;
13060            let raw: Vec<f64> = (0..n)
13061                .map(|_| {
13062                    if next() % 4 == 0 {
13063                        f64::NAN
13064                    } else {
13065                        (next() % 200) as f64 - 100.0
13066                    }
13067                })
13068                .collect();
13069            let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13070            if finite.is_empty() {
13071                continue;
13072            }
13073            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13074            let sum: f64 = finite.iter().sum();
13075            let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
13076            let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
13077            finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
13078            let m = finite.len();
13079            let med = if m % 2 == 1 {
13080                finite[m / 2]
13081            } else {
13082                (finite[m / 2 - 1] + finite[m / 2]) / 2.0
13083            };
13084            assert!(
13085                (val(nansum(&scalars)) - sum).abs() < 1e-7,
13086                "nansum iter={iter}"
13087            );
13088            assert!(
13089                (val(nanmin(&scalars)) - mn).abs() < 1e-9,
13090                "nanmin iter={iter}"
13091            );
13092            assert!(
13093                (val(nanmax(&scalars)) - mx).abs() < 1e-9,
13094                "nanmax iter={iter}"
13095            );
13096            assert!(
13097                (val(nanmedian(&scalars)) - med).abs() < 1e-9,
13098                "nanmedian iter={iter}"
13099            );
13100        }
13101    }
13102
13103    #[test]
13104    fn nanvar_ddof_nanstd_nan_skip_p00ag() {
13105        use super::{nanmean, nanstd, nanvar};
13106        // br-frankenpandas-p00ag: nanmean/nanvar/nanstd skip NaN; ddof picks the
13107        // denominator; nanstd==sqrt(nanvar). Seeded LCG, no mocks.
13108        let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
13109        let mut next = || {
13110            s = s
13111                .wrapping_mul(6_364_136_223_846_793_005)
13112                .wrapping_add(1_442_695_040_888_963_407);
13113            (s >> 33) as u32
13114        };
13115        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
13116        for iter in 0..1000u32 {
13117            let n = (next() % 10) as usize + 2;
13118            let raw: Vec<f64> = (0..n)
13119                .map(|_| {
13120                    if next() % 4 == 0 {
13121                        f64::NAN
13122                    } else {
13123                        (next() % 200) as f64 / 7.0
13124                    }
13125                })
13126                .collect();
13127            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13128            if finite.len() < 2 {
13129                continue;
13130            }
13131            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13132            let nf = finite.len() as f64;
13133            let mean = finite.iter().sum::<f64>() / nf;
13134            let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
13135            assert!(
13136                (val(nanmean(&scalars)) - mean).abs() < 1e-7,
13137                "nanmean iter={iter}"
13138            );
13139            assert!(
13140                (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
13141                "nanvar ddof0 iter={iter}"
13142            );
13143            assert!(
13144                (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
13145                "nanvar ddof1 iter={iter}"
13146            );
13147            assert!(
13148                (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
13149                "nanstd ddof1 iter={iter}"
13150            );
13151        }
13152    }
13153
13154    #[test]
13155    fn nanskew_nankurt_min_sample_and_known_xybnq() {
13156        // br-frankenpandas-xybnq: guard nanskew/nankurt min-sample-size (NaN below
13157        // threshold) + known pandas G1/G2 values (the f4dc5540 inline-copy bug area).
13158        use super::{nankurt, nanskew};
13159        let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
13160        let val = |s: Scalar| -> Option<f64> {
13161            if s.is_missing() {
13162                None
13163            } else {
13164                s.to_f64().ok()
13165            }
13166        };
13167
13168        // skew needs >= 3 observations.
13169        assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
13170        let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
13171        assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
13172        let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
13173        assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
13174
13175        // kurt needs >= 4 observations.
13176        assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
13177        let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
13178        assert!(
13179            (k - (-1.2)).abs() < 1e-6,
13180            "pandas kurt([1..5]) == -1.2, got {k}"
13181        );
13182    }
13183
13184    #[test]
13185    #[ignore = "foreground release attribution harness"]
13186    fn nanskew_fused_moment_scan_ab_mavln() {
13187        const ROWS: usize = 100_000;
13188        const BATCH: usize = 8;
13189
13190        fn former(values: &[Scalar]) -> Scalar {
13191            let nums = super::collect_finite(values);
13192            let n = nums.len() as f64;
13193            if n < 3.0 {
13194                return Scalar::Null(NullKind::NaN);
13195            }
13196            let mean = nums.iter().sum::<f64>() / n;
13197            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
13198            let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
13199            let s2 = m2 / (n - 1.0);
13200            if s2 == 0.0 {
13201                return Scalar::Float64(0.0);
13202            }
13203            let s3 = s2.powf(1.5);
13204            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
13205        }
13206
13207        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
13208            match (former, candidate) {
13209                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
13210                (a, b) => assert_eq!(a, b),
13211            }
13212        }
13213
13214        fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
13215            std::hint::black_box(skew(std::hint::black_box(values)));
13216            let started = std::time::Instant::now();
13217            for _ in 0..BATCH {
13218                std::hint::black_box(skew(std::hint::black_box(values)));
13219            }
13220            started.elapsed().as_nanos()
13221        }
13222
13223        fn median(samples: &mut [u128]) -> u128 {
13224            samples.sort_unstable();
13225            samples[samples.len() / 2]
13226        }
13227
13228        for values in [
13229            vec![],
13230            vec![Scalar::Int64(1), Scalar::Int64(2)],
13231            vec![Scalar::Int64(7); 16],
13232            vec![
13233                Scalar::Int64(-3),
13234                Scalar::Null(NullKind::NaN),
13235                Scalar::Float64(2.5),
13236                Scalar::Utf8("skip".to_owned()),
13237                Scalar::Int64(11),
13238            ],
13239        ] {
13240            assert_bits_eq(former(&values), super::nanskew(&values));
13241        }
13242
13243        let values = (0..ROWS)
13244            .map(|i| {
13245                if i % 257 == 0 {
13246                    Scalar::Null(NullKind::NaN)
13247                } else {
13248                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
13249                }
13250            })
13251            .collect::<Vec<_>>();
13252        assert_bits_eq(former(&values), super::nanskew(&values));
13253
13254        for _ in 0..2 {
13255            std::hint::black_box(elapsed(&values, former));
13256            std::hint::black_box(elapsed(&values, super::nanskew));
13257        }
13258
13259        let mut former_samples = Vec::with_capacity(18);
13260        let mut candidate_samples = Vec::with_capacity(18);
13261        for block in 0_usize..9 {
13262            if block.is_multiple_of(2) {
13263                former_samples.push(elapsed(&values, former));
13264                candidate_samples.push(elapsed(&values, super::nanskew));
13265                candidate_samples.push(elapsed(&values, super::nanskew));
13266                former_samples.push(elapsed(&values, former));
13267            } else {
13268                candidate_samples.push(elapsed(&values, super::nanskew));
13269                former_samples.push(elapsed(&values, former));
13270                former_samples.push(elapsed(&values, former));
13271                candidate_samples.push(elapsed(&values, super::nanskew));
13272            }
13273        }
13274
13275        let former_p50 = median(&mut former_samples);
13276        let candidate_p50 = median(&mut candidate_samples);
13277        eprintln!(
13278            "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
13279            former_p50 as f64 / candidate_p50 as f64,
13280        );
13281        eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
13282        eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
13283    }
13284
13285    #[test]
13286    #[ignore = "foreground performance probe"]
13287    fn nankurt_fused_moment_scan_ab_idka7() {
13288        const ROWS: usize = 65_536;
13289        const BATCH: usize = 4;
13290
13291        fn former(values: &[Scalar]) -> Scalar {
13292            let nums = super::collect_finite(values);
13293            let n = nums.len() as f64;
13294            if n < 4.0 {
13295                return Scalar::Null(NullKind::NaN);
13296            }
13297            let mean = nums.iter().sum::<f64>() / n;
13298            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
13299            let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
13300            let s2 = m2 / (n - 1.0);
13301            if s2 == 0.0 {
13302                return Scalar::Float64(0.0);
13303            }
13304            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
13305            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
13306            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
13307        }
13308
13309        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
13310            match (former, candidate) {
13311                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
13312                (a, b) => assert_eq!(a, b),
13313            }
13314        }
13315
13316        fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
13317            let started = std::time::Instant::now();
13318            for _ in 0..BATCH {
13319                std::hint::black_box(kurt(std::hint::black_box(values)));
13320            }
13321            started.elapsed().as_nanos()
13322        }
13323
13324        fn median(samples: &mut [u128]) -> u128 {
13325            samples.sort_unstable();
13326            samples[samples.len() / 2]
13327        }
13328
13329        for values in [
13330            vec![],
13331            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13332            vec![Scalar::Int64(7); 16],
13333            vec![
13334                Scalar::Int64(-3),
13335                Scalar::Null(NullKind::NaN),
13336                Scalar::Float64(2.5),
13337                Scalar::Utf8("skip".to_owned()),
13338                Scalar::Int64(11),
13339                Scalar::Float64(-7.25),
13340            ],
13341        ] {
13342            assert_bits_eq(former(&values), super::nankurt(&values));
13343        }
13344
13345        let values = (0..ROWS)
13346            .map(|i| {
13347                if i % 257 == 0 {
13348                    Scalar::Null(NullKind::NaN)
13349                } else {
13350                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
13351                }
13352            })
13353            .collect::<Vec<_>>();
13354        assert_bits_eq(former(&values), super::nankurt(&values));
13355
13356        for _ in 0..2 {
13357            std::hint::black_box(elapsed(&values, former));
13358            std::hint::black_box(elapsed(&values, super::nankurt));
13359        }
13360
13361        let mut former_samples = Vec::with_capacity(10);
13362        let mut candidate_samples = Vec::with_capacity(10);
13363        for block in 0_usize..5 {
13364            if block.is_multiple_of(2) {
13365                former_samples.push(elapsed(&values, former));
13366                candidate_samples.push(elapsed(&values, super::nankurt));
13367                candidate_samples.push(elapsed(&values, super::nankurt));
13368                former_samples.push(elapsed(&values, former));
13369            } else {
13370                candidate_samples.push(elapsed(&values, super::nankurt));
13371                former_samples.push(elapsed(&values, former));
13372                former_samples.push(elapsed(&values, former));
13373                candidate_samples.push(elapsed(&values, super::nankurt));
13374            }
13375        }
13376
13377        let former_p50 = median(&mut former_samples);
13378        let candidate_p50 = median(&mut candidate_samples);
13379        eprintln!(
13380            "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
13381            former_p50 as f64 / candidate_p50 as f64,
13382        );
13383        eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
13384        eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
13385    }
13386
13387    /// behind astype/promotion. Property test of its confirmed identity +
13388    /// numeric/bool coercion rules over random scalars. Deterministic seeded LCG.
13389    #[test]
13390    fn cast_scalar_to_utf8_formatting_yes7i() {
13391        // Property (br-frankenpandas-yes7i): cast to Utf8 formats per pandas
13392        // astype(str): Int64 -> decimal, Bool -> True/False. Seeded LCG, no mocks.
13393        let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
13394        let mut next = || {
13395            st = st
13396                .wrapping_mul(6_364_136_223_846_793_005)
13397                .wrapping_add(1_442_695_040_888_963_407);
13398            (st >> 33) as u32
13399        };
13400        for _ in 0..3000u32 {
13401            let n = (next() % 4_000_001) as i64 - 2_000_000;
13402            assert_eq!(
13403                cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
13404                Scalar::Utf8(n.to_string())
13405            );
13406        }
13407        assert_eq!(
13408            cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
13409            Scalar::Utf8("True".to_string())
13410        );
13411        assert_eq!(
13412            cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
13413            Scalar::Utf8("False".to_string())
13414        );
13415    }
13416
13417    #[test]
13418    fn cast_scalar_coercion_rules_6a83t() {
13419        let mut state: u64 = 0x5a17_c0de_1234_abcd;
13420        let mut next = || {
13421            state = state
13422                .wrapping_mul(6_364_136_223_846_793_005)
13423                .wrapping_add(1_442_695_040_888_963_407);
13424            (state >> 33) as u32
13425        };
13426
13427        for _ in 0..4000u32 {
13428            let n = (next() % 21) as i64 - 10; // -10..=10, incl 0
13429            let b = next() % 2 == 0;
13430            let f = f64::from((next() % 41) as i32 - 20) / 4.0; // finite, incl 0.0
13431
13432            let i = Scalar::Int64(n);
13433            let bo = Scalar::Bool(b);
13434            let fl = Scalar::Float64(f);
13435
13436            // Identity casts.
13437            assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
13438            assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
13439            assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
13440
13441            // Representation-preserving nullable identities.
13442            assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
13443            assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
13444
13445            // Int64 coercions.
13446            assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
13447            assert_eq!(
13448                cast_scalar(&i, DType::Float64),
13449                Ok(Scalar::Float64(n as f64))
13450            );
13451
13452            // Bool coercions.
13453            assert_eq!(
13454                cast_scalar(&bo, DType::Int64),
13455                Ok(Scalar::Int64(i64::from(b)))
13456            );
13457            assert_eq!(
13458                cast_scalar(&bo, DType::Float64),
13459                Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
13460            );
13461
13462            // Finite Float64 -> Int64 truncates toward zero (x as i64).
13463            assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
13464        }
13465    }
13466
13467    /// br-frankenpandas-esjjy / fd90.182: ergonomic From impls for Scalar.
13468    #[test]
13469    fn scalar_from_primitive_types() {
13470        // Each primitive maps to its canonical Scalar variant.
13471        assert_eq!(Scalar::from(true), Scalar::Bool(true));
13472        assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
13473        assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
13474        assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
13475        assert_eq!(
13476            Scalar::from(String::from("world")),
13477            Scalar::Utf8("world".to_owned())
13478        );
13479
13480        // .into() works in mixed-type Vec<Scalar> contexts (the README's
13481        // case_when example pattern, and what fd90.181 needed for apply_row
13482        // closures).
13483        let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
13484        assert_eq!(mixed[0], Scalar::Int64(1));
13485        assert_eq!(mixed[1], Scalar::Float64(2.0));
13486        assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
13487    }
13488
13489    #[test]
13490    fn dtype_inference_routes_bool_numeric_mix_to_object_bucket_rh1od() {
13491        // Was `dtype_inference_coerces_numeric_values` (Bool+Int64+Float64 ->
13492        // Float64). br-frankenpandas-rh1od, MEASURED live pandas 2.2.3:
13493        // pd.Series([True, 7, 3.5]) constructs OBJECT — no pandas constructor
13494        // path produces the numpy common-type Float64 here.
13495        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
13496        assert_eq!(
13497            infer_dtype(&values).expect("dtype should infer"),
13498            DType::Utf8
13499        );
13500    }
13501
13502    #[test]
13503    fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
13504        let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
13505        let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
13506        assert_eq!(left.dtype(), DType::Interval);
13507        assert!(!left.is_missing());
13508        assert_eq!(
13509            infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
13510            DType::Interval
13511        );
13512        assert_eq!(
13513            common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
13514            DType::Interval
13515        );
13516        assert_eq!(
13517            cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
13518            Scalar::Null(NullKind::Null)
13519        );
13520        assert_eq!(
13521            cast_scalar(&left, DType::Utf8).expect("interval string cast"),
13522            Scalar::Utf8("(0.0, 1.0]".to_owned())
13523        );
13524        assert_eq!(
13525            super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
13526            Scalar::Int64(2)
13527        );
13528    }
13529
13530    #[test]
13531    fn cast_scalar_parses_temporal_extension_strings_avm08() {
13532        let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
13533            .expect("timestamp parse")
13534            .nanos;
13535        assert_eq!(
13536            cast_scalar(
13537                &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
13538                DType::datetime64_naive()
13539            )
13540            .expect("datetime cast"),
13541            Scalar::Datetime64(expected_nanos)
13542        );
13543        assert_eq!(
13544            cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
13545            Scalar::Period(Period::new(216, PeriodFreq::QUARTERLY))
13546        );
13547        assert_eq!(
13548            cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
13549                .expect("interval cast"),
13550            Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
13551        );
13552    }
13553
13554    #[test]
13555    fn missing_values_get_target_missing_marker() {
13556        let missing = Scalar::Null(NullKind::Null);
13557        let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
13558        assert_eq!(cast, Scalar::Null(NullKind::NaN));
13559    }
13560
13561    #[test]
13562    fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
13563        let cases = [
13564            (Scalar::Bool(true), "True"),
13565            (Scalar::Bool(false), "False"),
13566            (Scalar::Int64(-7), "-7"),
13567            (Scalar::Float64(1.0), "1.0"),
13568            (Scalar::Float64(1.5), "1.5"),
13569            (Scalar::Float64(f64::NAN), "nan"),
13570            (Scalar::Null(NullKind::Null), "None"),
13571            (Scalar::Null(NullKind::NaN), "nan"),
13572            (Scalar::Null(NullKind::NaT), "NaT"),
13573        ];
13574
13575        for (value, expected) in cases {
13576            assert_eq!(
13577                cast_scalar(&value, DType::Utf8).expect("cast"),
13578                Scalar::Utf8(expected.to_owned())
13579            );
13580        }
13581    }
13582
13583    #[test]
13584    fn semantic_eq_treats_nan_as_equal() {
13585        let left = Scalar::Float64(f64::NAN);
13586        let right = Scalar::Null(NullKind::NaN);
13587        assert!(left.semantic_eq(&right));
13588    }
13589
13590    #[test]
13591    fn semantic_eq_treats_nan_as_missing_null() {
13592        let left = Scalar::Float64(f64::NAN);
13593        let right = Scalar::Null(NullKind::Null);
13594        assert!(left.semantic_eq(&right));
13595    }
13596
13597    /// A DTYPE-SENTINEL missing equals a `Null` marker, for every dtype that
13598    /// has one.
13599    ///
13600    /// `missing_for_dtype` DEFINES the canonical missing for Timedelta64 as
13601    /// `Timedelta64(NAT)`, for Datetime64 as `Datetime64(NAT)` and for Period as
13602    /// ordinal `i64::MIN`, and `is_missing()` agrees — but `semantic_eq` used to
13603    /// unify only the `Null`/NaN flavours, so an oracle's `null` for pandas' NaT
13604    /// could never match FP's sentinel. Observed on
13605    /// `fp_p2d_021_series_to_timedelta_negative_null_hardened`, where the
13606    /// fixture pinned the raw `-9223372036854775808` as though it were data.
13607    ///
13608    /// THE NEGATIVE CASES ARE THE POINT — "both missing" must not become "any
13609    /// sentinel matches anything":
13610    /// - a NaT sentinel must NOT equal a PRESENT timedelta;
13611    /// - two DIFFERENT present timedeltas must stay unequal;
13612    /// - Period and Datetime64 must unify too, or the fix is Timedelta-only.
13613    ///
13614    /// (br-frankenpandas-xwxci)
13615    #[test]
13616    fn semantic_eq_unifies_dtype_sentinel_missing_with_null_xwxci() {
13617        for sentinel in [
13618            Scalar::Timedelta64(Timedelta::NAT),
13619            Scalar::Datetime64(Timestamp::NAT),
13620            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
13621        ] {
13622            assert!(sentinel.is_missing(), "{sentinel:?} must report missing");
13623            for marker in [
13624                Scalar::Null(NullKind::Null),
13625                Scalar::Null(NullKind::NaN),
13626                Scalar::Null(NullKind::NaT),
13627            ] {
13628                assert!(
13629                    sentinel.semantic_eq(&marker),
13630                    "{sentinel:?} vs {marker:?} are both missing"
13631                );
13632                assert!(marker.semantic_eq(&sentinel), "and symmetrically");
13633            }
13634        }
13635
13636        // NOT a blanket match: a sentinel differs from a PRESENT value.
13637        let present = Scalar::Timedelta64(-60);
13638        assert!(!Scalar::Timedelta64(Timedelta::NAT).semantic_eq(&present));
13639        assert!(!present.semantic_eq(&Scalar::Null(NullKind::Null)));
13640        // And two distinct present values stay distinct.
13641        assert!(!present.semantic_eq(&Scalar::Timedelta64(-61)));
13642    }
13643
13644    #[test]
13645    fn common_dtype_rejects_string_numeric_mix() {
13646        let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
13647        assert_eq!(
13648            err.to_string(),
13649            "dtype coercion from Utf8 to Int64 has no compatible common type"
13650        );
13651        let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
13652        assert_eq!(
13653            err.to_string(),
13654            "dtype coercion from Float64 to Utf8 has no compatible common type"
13655        );
13656    }
13657
13658    #[test]
13659    fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
13660        let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
13661
13662        assert_eq!(dtype.value_dtype, DType::Float64);
13663        assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
13664    }
13665
13666    #[test]
13667    fn sparse_dtype_rejects_sparse_value_dtype() {
13668        let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
13669
13670        assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
13671    }
13672
13673    #[test]
13674    fn common_dtype_rejects_sparse_dense_mix() {
13675        let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
13676
13677        assert_eq!(
13678            err.to_string(),
13679            "dtype coercion from Sparse to Int64 has no compatible common type"
13680        );
13681    }
13682
13683    // ── Nullable Int64/Bool dtype tests (br-frankenpandas-rg8ys.6.4) ────
13684
13685    #[test]
13686    fn nullable_int64_promotion_matrix() {
13687        // Int64 + Int64Nullable -> Int64Nullable (nullable absorbs)
13688        assert_eq!(
13689            common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
13690            DType::Int64Nullable
13691        );
13692        assert_eq!(
13693            common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
13694            DType::Int64Nullable
13695        );
13696
13697        // Int64Nullable + Float64 -> Float64Nullable. The old comment here said
13698        // "float always wins"; that is half right. The float wins, but the
13699        // NULLABLE flavour of it does — MEASURED, live pandas 2.2.3:
13700        //   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5]) -> Float64
13701        // where that Float64 is the extension dtype (missing = pd.NA), not
13702        // numpy float64 (missing = NaN). (br-frankenpandas-qkqfb)
13703        assert_eq!(
13704            common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
13705            DType::Float64Nullable
13706        );
13707        assert_eq!(
13708            common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
13709            DType::Float64Nullable
13710        );
13711
13712        // Int64Nullable + Int64Nullable -> Int64Nullable
13713        assert_eq!(
13714            common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
13715            DType::Int64Nullable
13716        );
13717
13718        // Bool + Int64Nullable -> Int64Nullable
13719        assert_eq!(
13720            common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
13721            DType::Int64Nullable
13722        );
13723
13724        // BoolNullable + Int64 -> Int64Nullable
13725        assert_eq!(
13726            common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
13727            DType::Int64Nullable
13728        );
13729    }
13730
13731    #[test]
13732    fn nullable_bool_promotion_matrix() {
13733        // Bool + BoolNullable -> BoolNullable
13734        assert_eq!(
13735            common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
13736            DType::BoolNullable
13737        );
13738        assert_eq!(
13739            common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
13740            DType::BoolNullable
13741        );
13742
13743        // BoolNullable + Float64 -> Float64Nullable. MEASURED, live pandas 2.2.3:
13744        //   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
13745        //     -> Float64   (extension)
13746        // This arm moves together with the Int64Nullable one in
13747        // nullable_int64_promotion_matrix; flipping either alone breaks lattice
13748        // associativity. (br-frankenpandas-qkqfb)
13749        assert_eq!(
13750            common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
13751            DType::Float64Nullable
13752        );
13753
13754        // CONTROL: the all-numpy pair is untouched and stays on the numpy side.
13755        //   pd.Series([True,False],dtype="bool") + pd.Series([1.5,2.5]) -> float64
13756        assert_eq!(
13757            common_dtype(DType::Bool, DType::Float64).unwrap(),
13758            DType::Float64
13759        );
13760    }
13761
13762    #[test]
13763    fn dtype_is_nullable_helper() {
13764        assert!(DType::Int64Nullable.is_nullable());
13765        assert!(DType::BoolNullable.is_nullable());
13766        assert!(!DType::Int64.is_nullable());
13767        assert!(!DType::Bool.is_nullable());
13768        assert!(!DType::Float64.is_nullable());
13769        assert!(!DType::Utf8.is_nullable());
13770    }
13771
13772    #[test]
13773    fn dtype_to_nullable_conversions() {
13774        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
13775        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
13776        // ⚠ THIS LINE WAS RED ON main SINCE fa6caee91 AND NOBODY SAW IT.
13777        // It used to read `Float64.to_nullable() == Float64  // unchanged`,
13778        // which was true only while FP had no nullable float at all. fa6caee91
13779        // (br-frankenpandas-qkqfb slice 1) added DType::Float64Nullable and
13780        // pointed to_nullable at it, but that commit was gated with
13781        // `cargo check --all-targets` plus a NAME-FILTERED test run, so this
13782        // pre-existing test was never executed and the break went unnoticed.
13783        // Float64's nullable flavour IS Float64Nullable — that is the dtype's
13784        // entire reason to exist — so the assertion is what was stale.
13785        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
13786        assert_eq!(
13787            DType::Float64Nullable.to_nullable(),
13788            DType::Float64Nullable,
13789            "idempotent: already nullable"
13790        );
13791        assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
13792    }
13793
13794    #[test]
13795    fn dtype_to_non_nullable_conversions() {
13796        assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
13797        assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
13798        assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); // unchanged
13799        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
13800    }
13801
13802    #[test]
13803    fn nullable_dtype_name_reports_pandas_style() {
13804        assert_eq!(DType::Int64.name(), "int64");
13805        assert_eq!(DType::Int64Nullable.name(), "Int64"); // capital I
13806        assert_eq!(DType::Bool.name(), "bool");
13807        assert_eq!(DType::BoolNullable.name(), "boolean");
13808    }
13809
13810    #[test]
13811    fn cast_scalar_int64_nullable_identity() {
13812        let val = Scalar::Int64(42);
13813        // Int64 -> Int64Nullable is identity (no actual conversion)
13814        let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
13815        assert_eq!(result, Scalar::Int64(42));
13816
13817        // Int64Nullable -> Int64 is also identity
13818        let result2 = cast_scalar(&val, DType::Int64).unwrap();
13819        assert_eq!(result2, Scalar::Int64(42));
13820    }
13821
13822    #[test]
13823    fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
13824        // pandas astype(str) of floats == Python str(float): whole -> ".0",
13825        // shortest round-trip decimals, scientific (e+NN/e-NN) for large/small,
13826        // inf -> "inf", NaN -> "nan". Verified vs live pandas 2.2.3. (Previously
13827        // large/small lost scientific notation, e.g. 1e16 -> "10000000000000000.0".)
13828        let cases: &[(f64, &str)] = &[
13829            (1.0, "1.0"),
13830            (2.5, "2.5"),
13831            (100.0, "100.0"),
13832            (0.1, "0.1"),
13833            (0.0001, "0.0001"),
13834            (1e16, "1e+16"),
13835            (1e20, "1e+20"),
13836            (1e-5, "1e-05"),
13837            (1e-7, "1e-07"),
13838            (f64::INFINITY, "inf"),
13839            (f64::NEG_INFINITY, "-inf"),
13840        ];
13841        for (v, expected) in cases {
13842            assert_eq!(
13843                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13844                Scalar::Utf8((*expected).to_owned()),
13845                "float {v} -> str"
13846            );
13847        }
13848    }
13849
13850    fn float_to_string_for_astype_former(value: f64) -> String {
13851        if value.is_nan() {
13852            return "nan".to_owned();
13853        }
13854        if value.is_infinite() {
13855            return value.to_string();
13856        }
13857        let rendered = format!("{value:?}");
13858        match rendered.split_once('e') {
13859            None => rendered,
13860            Some((mantissa, exponent)) => {
13861                let (sign, digits) = match exponent.strip_prefix('-') {
13862                    Some(digits) => ('-', digits),
13863                    None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
13864                };
13865                format!("{mantissa}e{sign}{digits:0>2}")
13866            }
13867        }
13868    }
13869
13870    fn scientific_astype_values(len: usize) -> Vec<f64> {
13871        const EXPONENTS: [i32; 16] = [
13872            -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
13873        ];
13874        (0..len)
13875            .map(|position| {
13876                let mantissa = 1.0 + (position % 997) as f64 / 997.0;
13877                let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
13878                if position.is_multiple_of(2) {
13879                    magnitude
13880                } else {
13881                    -magnitude
13882                }
13883            })
13884            .collect()
13885    }
13886
13887    #[test]
13888    fn float_to_string_for_astype_in_place_matches_former() {
13889        let fixed = [
13890            f64::NAN,
13891            f64::INFINITY,
13892            f64::NEG_INFINITY,
13893            0.0,
13894            -0.0,
13895            f64::MIN_POSITIVE,
13896            f64::MAX,
13897            f64::MIN,
13898            1e16,
13899            -1e16,
13900            1e-5,
13901            -1e-5,
13902            1.234_567_890_123_456_8e20,
13903            -9.876_543_210_987_654e-123,
13904        ];
13905        for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
13906            assert_eq!(
13907                super::float_to_string_for_astype(value),
13908                float_to_string_for_astype_former(value),
13909                "value={value:?}"
13910            );
13911        }
13912    }
13913
13914    #[test]
13915    #[ignore = "foreground performance probe"]
13916    fn float_to_string_for_astype_in_place_ab() {
13917        use std::time::Instant;
13918
13919        const VALUES: usize = 16_384;
13920        const SAMPLES: usize = 10;
13921        let values = scientific_astype_values(VALUES);
13922        for &value in &values {
13923            let former = float_to_string_for_astype_former(value);
13924            assert!(former.contains('e'), "benchmark value must be scientific");
13925            assert_eq!(super::float_to_string_for_astype(value), former);
13926        }
13927
13928        for _ in 0..2 {
13929            for &value in &values {
13930                std::hint::black_box(float_to_string_for_astype_former(value));
13931                std::hint::black_box(super::float_to_string_for_astype(value));
13932            }
13933        }
13934
13935        let mut former_ns = Vec::with_capacity(SAMPLES);
13936        let mut public_ns = Vec::with_capacity(SAMPLES);
13937        for sample in 0..SAMPLES {
13938            let run = |formatter: fn(f64) -> String| {
13939                let started = Instant::now();
13940                for &value in std::hint::black_box(&values) {
13941                    std::hint::black_box(formatter(std::hint::black_box(value)));
13942                }
13943                started.elapsed().as_nanos()
13944            };
13945            if sample.is_multiple_of(2) {
13946                former_ns.push(run(float_to_string_for_astype_former));
13947                public_ns.push(run(super::float_to_string_for_astype));
13948            } else {
13949                public_ns.push(run(super::float_to_string_for_astype));
13950                former_ns.push(run(float_to_string_for_astype_former));
13951            }
13952        }
13953
13954        former_ns.sort_unstable();
13955        public_ns.sort_unstable();
13956        let former_p50 = former_ns[SAMPLES / 2];
13957        let public_p50 = public_ns[SAMPLES / 2];
13958        println!(
13959            "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:?}",
13960            former_p50 as f64 / public_p50 as f64
13961        );
13962    }
13963
13964    #[test]
13965    fn cast_float_to_utf8_threshold_boundaries_match_python() {
13966        // Python str(float) switches to scientific notation only at |x| >= 1e16
13967        // or |x| < 1e-4. Values JUST INSIDE those bounds must stay decimal — a
13968        // formatter that switches to sci early (or late) diverges. All expected
13969        // values verified against Python 3 str()/repr (== pandas astype(str)).
13970        let cases: &[(f64, &str)] = &[
13971            (1e15, "1000000000000000.0"),
13972            (9_999_999_999_999_998.0, "9999999999999998.0"),
13973            (1_234_567_890_123_456.0, "1234567890123456.0"),
13974            (123_456_789_012_345.0, "123456789012345.0"),
13975            (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
13976            (1e16, "1e+16"),
13977            (1.5e16, "1.5e+16"),
13978            (1e17, "1e+17"),
13979            (1e-4, "0.0001"),
13980            (5e-5, "5e-05"),
13981            (-1e15, "-1000000000000000.0"),
13982            (-1e16, "-1e+16"),
13983            (-1e-5, "-1e-05"),
13984        ];
13985        for (v, expected) in cases {
13986            assert_eq!(
13987                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13988                Scalar::Utf8((*expected).to_owned()),
13989                "float {v} -> str"
13990            );
13991        }
13992    }
13993
13994    #[test]
13995    fn cast_to_bool_uses_pandas_nonzero_truthiness() {
13996        // pandas astype(bool): zero -> False, any nonzero -> True (not just 0/1),
13997        // -0.0 -> False, and NaN -> True (numpy bool(nan), br-cyi4h). Verified vs
13998        // live pandas 2.2.3.
13999        let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
14000        for (v, expected) in cases_int {
14001            assert_eq!(
14002                cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
14003                Scalar::Bool(*expected),
14004                "int {v} -> bool"
14005            );
14006        }
14007        let cases_float: &[(f64, bool)] = &[
14008            (0.0, false),
14009            (-0.0, false),
14010            (0.1, true),
14011            (2.5, true),
14012            (1.0, true),
14013            // pandas astype(bool): NaN is truthy -> True (numpy bool). br-cyi4h.
14014            (f64::NAN, true),
14015        ];
14016        for (v, expected) in cases_float {
14017            assert_eq!(
14018                cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
14019                Scalar::Bool(*expected),
14020                "float {v} -> bool"
14021            );
14022        }
14023    }
14024
14025    #[test]
14026    fn nullable_dtype_is_extension() {
14027        assert!(DType::Int64Nullable.is_extension());
14028        assert!(DType::BoolNullable.is_extension());
14029        assert!(!DType::Int64.is_extension());
14030        assert!(!DType::Bool.is_extension());
14031    }
14032
14033    #[test]
14034    fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
14035        let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
14036        assert_eq!(
14037            infer_dtype(&values).expect("dtype should infer"),
14038            DType::Utf8
14039        );
14040    }
14041
14042    #[test]
14043    fn infer_dtype_routes_bool_numeric_mix_to_utf8_object_bucket_rh1od() {
14044        // br-frankenpandas-rh1od, MEASURED live pandas 2.2.3: a bool mixed
14045        // with any numeric scalar constructs OBJECT ([True, 2] -> object,
14046        // payloads preserved); numpy's bool<int common-type never fires at
14047        // the constructor. Discriminating: before the change this inferred
14048        // Int64 and coerced True -> 1.
14049        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Bool(false)];
14050        assert_eq!(
14051            infer_dtype(&values).expect("dtype should infer"),
14052            DType::Utf8
14053        );
14054        let with_float = vec![Scalar::Int64(1), Scalar::Float64(2.5), Scalar::Bool(true)];
14055        assert_eq!(
14056            infer_dtype(&with_float).expect("dtype should infer"),
14057            DType::Utf8
14058        );
14059        let with_null = vec![
14060            Scalar::Bool(true),
14061            Scalar::Null(NullKind::Null),
14062            Scalar::Int64(2),
14063        ];
14064        assert_eq!(
14065            infer_dtype(&with_null).expect("dtype should infer"),
14066            DType::Utf8
14067        );
14068    }
14069
14070    #[test]
14071    fn infer_dtype_keeps_nonmixed_bool_and_numeric_paths_rh1od() {
14072        // Pure bool stays bool; numeric-only mixes keep the common_dtype
14073        // lattice (int+float -> float64) — the object bucket is ONLY for the
14074        // cross-family mix.
14075        assert_eq!(
14076            infer_dtype(&[Scalar::Bool(true), Scalar::Bool(false)]).expect("dtype should infer"),
14077            DType::Bool
14078        );
14079        assert_eq!(
14080            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]).expect("dtype should infer"),
14081            DType::Float64
14082        );
14083    }
14084
14085    // ── Scalar missingness methods ─────────────────────────────────────
14086
14087    #[test]
14088    fn is_null_detects_explicit_nulls() {
14089        assert!(Scalar::Null(NullKind::Null).is_null());
14090        assert!(Scalar::Null(NullKind::NaN).is_null());
14091        assert!(!Scalar::Int64(42).is_null());
14092        assert!(!Scalar::Float64(f64::NAN).is_null());
14093    }
14094
14095    #[test]
14096    fn is_na_matches_is_missing() {
14097        let vals = vec![
14098            Scalar::Null(NullKind::Null),
14099            Scalar::Float64(f64::NAN),
14100            Scalar::Int64(0),
14101            Scalar::Bool(false),
14102        ];
14103        for v in &vals {
14104            assert_eq!(v.is_na(), v.is_missing());
14105        }
14106    }
14107
14108    #[test]
14109    fn coalesce_picks_first_non_missing() {
14110        let null = Scalar::Null(NullKind::Null);
14111        let fill = Scalar::Int64(99);
14112        assert_eq!(null.coalesce(&fill), fill);
14113        assert_eq!(fill.coalesce(&null), fill);
14114    }
14115
14116    // ── Missingness utilities ──────────────────────────────────────────
14117
14118    #[test]
14119    fn isna_notna_complement() {
14120        let vals = vec![
14121            Scalar::Int64(1),
14122            Scalar::Null(NullKind::Null),
14123            Scalar::Float64(f64::NAN),
14124            Scalar::Float64(3.0),
14125        ];
14126        let na = super::isna(&vals);
14127        let not = super::notna(&vals);
14128        assert_eq!(na, vec![false, true, true, false]);
14129        for (a, b) in na.iter().zip(not.iter()) {
14130            assert_ne!(a, b);
14131        }
14132    }
14133
14134    #[test]
14135    fn count_na_counts_missing() {
14136        let vals = vec![
14137            Scalar::Int64(1),
14138            Scalar::Null(NullKind::Null),
14139            Scalar::Float64(f64::NAN),
14140        ];
14141        assert_eq!(super::count_na(&vals), 2);
14142    }
14143
14144    #[test]
14145    fn fill_na_replaces_missing() {
14146        let vals = vec![
14147            Scalar::Int64(1),
14148            Scalar::Null(NullKind::Null),
14149            Scalar::Float64(f64::NAN),
14150            Scalar::Int64(4),
14151        ];
14152        let filled = super::fill_na(&vals, &Scalar::Int64(0));
14153        assert_eq!(filled[0], Scalar::Int64(1));
14154        assert_eq!(filled[1], Scalar::Int64(0));
14155        assert_eq!(filled[2], Scalar::Int64(0));
14156        assert_eq!(filled[3], Scalar::Int64(4));
14157    }
14158
14159    #[test]
14160    fn dropna_removes_missing() {
14161        let vals = vec![
14162            Scalar::Int64(1),
14163            Scalar::Null(NullKind::Null),
14164            Scalar::Int64(3),
14165            Scalar::Float64(f64::NAN),
14166        ];
14167        let kept = super::dropna(&vals);
14168        assert_eq!(kept.len(), 2);
14169        assert_eq!(kept[0], Scalar::Int64(1));
14170        assert_eq!(kept[1], Scalar::Int64(3));
14171    }
14172
14173    #[test]
14174    fn null_helpers_match_scalar_oracle_imt0c() {
14175        // Differential vs independent scalar null-helper oracle
14176        // (br-frankenpandas-imt0c). Seeded LCG, no mocks.
14177        fn next(seed: &mut u64) -> u64 {
14178            *seed = seed
14179                .wrapping_mul(3202034522624059733)
14180                .wrapping_add(4354685564936845319);
14181            *seed
14182        }
14183
14184        fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
14185            let expected_missing = values.iter().filter(|value| value.is_missing()).count();
14186            let expected_dropped = values
14187                .iter()
14188                .filter(|value| !value.is_missing())
14189                .cloned()
14190                .collect::<Vec<_>>();
14191            let expected_filled = values
14192                .iter()
14193                .map(|value| {
14194                    if value.is_missing() {
14195                        fill.clone()
14196                    } else {
14197                        value.clone()
14198                    }
14199                })
14200                .collect::<Vec<_>>();
14201
14202            assert_eq!(
14203                super::count_na(values),
14204                expected_missing,
14205                "case={case}: count_na mismatch for {values:?}"
14206            );
14207
14208            let dropped = super::dropna(values);
14209            assert_eq!(
14210                dropped.len(),
14211                expected_dropped.len(),
14212                "case={case}: dropna length mismatch for {values:?}"
14213            );
14214            for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
14215            {
14216                assert!(
14217                    actual.semantic_eq(expected),
14218                    "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
14219                );
14220            }
14221
14222            let filled = super::fill_na(values, fill);
14223            assert_eq!(
14224                filled.len(),
14225                expected_filled.len(),
14226                "case={case}: fill_na length mismatch for {values:?}"
14227            );
14228            for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
14229                assert!(
14230                    actual.semantic_eq(expected),
14231                    "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
14232                );
14233            }
14234        }
14235
14236        let all_missing = [
14237            Scalar::Null(NullKind::Null),
14238            Scalar::Null(NullKind::NaN),
14239            Scalar::Float64(f64::NAN),
14240            Scalar::Timedelta64(i64::MIN),
14241        ];
14242        assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
14243
14244        let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
14245        for case in 0..260 {
14246            let len = (next(&mut seed) % 83 + 1) as usize;
14247            let mut values = Vec::with_capacity(len);
14248            for pos in 0..len {
14249                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14250                values.push(match next(&mut seed) % 11 {
14251                    0 => Scalar::Null(NullKind::Null),
14252                    1 => Scalar::Null(NullKind::NaN),
14253                    2 => Scalar::Float64(f64::NAN),
14254                    3 => Scalar::Timedelta64(i64::MIN),
14255                    4 => Scalar::Bool(raw & 1 == 0),
14256                    5 => Scalar::Int64(raw),
14257                    6 => Scalar::Float64(raw as f64 / 37.0),
14258                    7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
14259                    8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
14260                    9 => Scalar::Utf8(String::new()),
14261                    _ => Scalar::Timedelta64(raw),
14262                });
14263            }
14264
14265            let fill = match case % 5 {
14266                0 => Scalar::Bool(true),
14267                1 => Scalar::Int64(-777),
14268                2 => Scalar::Float64(12.5),
14269                3 => Scalar::Utf8("filled".into()),
14270                _ => Scalar::Timedelta64(123_456),
14271            };
14272            assert_null_helpers(case, &values, &fill);
14273        }
14274    }
14275
14276    // ── Nanops ─────────────────────────────────────────────────────────
14277
14278    #[test]
14279    fn nansum_skips_nulls() {
14280        let vals = vec![
14281            Scalar::Float64(1.0),
14282            Scalar::Null(NullKind::Null),
14283            Scalar::Float64(2.0),
14284            Scalar::Float64(f64::NAN),
14285            Scalar::Int64(7),
14286        ];
14287        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
14288    }
14289
14290    #[test]
14291    fn nansum_empty_returns_zero() {
14292        assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
14293    }
14294
14295    #[test]
14296    fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
14297        // Differential vs independent sum/mean oracles
14298        // (br-frankenpandas-1xmi7). Seeded LCG, no mocks.
14299        fn next(seed: &mut u64) -> u64 {
14300            *seed = seed
14301                .wrapping_mul(6364136223846793005)
14302                .wrapping_add(1442695040888963407);
14303            *seed
14304        }
14305
14306        fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
14307            let mut sum = 0.0;
14308            let mut count = 0usize;
14309            for value in values {
14310                if value.is_missing() {
14311                    continue;
14312                }
14313                if let Ok(value) = value.to_f64() {
14314                    sum += value;
14315                    count += 1;
14316                }
14317            }
14318            let mean = if count == 0 {
14319                Scalar::Null(NullKind::NaN)
14320            } else {
14321                Scalar::Float64(sum / count as f64)
14322            };
14323            (Scalar::Float64(sum), mean)
14324        }
14325
14326        fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
14327            let mut sum = 0_i128;
14328            let mut count = 0_i128;
14329            for value in values {
14330                if let Scalar::Timedelta64(ns) = value
14331                    && !value.is_missing()
14332                {
14333                    sum += i128::from(*ns);
14334                    count += 1;
14335                }
14336            }
14337            if count == 0 {
14338                return (Scalar::Timedelta64(0), Scalar::Timedelta64(Timedelta::NAT));
14339            }
14340            // br-frankenpandas-opz27: this reference oracle used to clamp, which
14341            // is the exact behaviour the production path was just fixed away
14342            // from. Keeping the clamp here would leave the oracle blessing a
14343            // contradicted rule (it only ever agreed because these inputs do
14344            // not overflow). Mirror the representable-range contract instead.
14345            (
14346                super::timedelta_ns_to_scalar(sum),
14347                super::timedelta_ns_to_scalar(sum / count),
14348            )
14349        }
14350
14351        fn assert_sum_mean(
14352            case: usize,
14353            family: &str,
14354            values: &[Scalar],
14355            expected_sum: Scalar,
14356            expected_mean: Scalar,
14357        ) {
14358            let actual_sum = super::nansum(values);
14359            let actual_mean = super::nanmean(values);
14360            assert!(
14361                actual_sum.semantic_eq(&expected_sum),
14362                "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
14363            );
14364            assert!(
14365                actual_mean.semantic_eq(&expected_mean),
14366                "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
14367            );
14368        }
14369
14370        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
14371        let (sum, mean) = expected_numeric(&all_missing);
14372        assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
14373
14374        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
14375        let (sum, mean) = expected_timedelta(&td_all_missing);
14376        assert_sum_mean(
14377            usize::MAX - 1,
14378            "timedelta_all_missing",
14379            &td_all_missing,
14380            sum,
14381            mean,
14382        );
14383
14384        let mut seed = 0x511d_ed5a_7a11_1a55_u64;
14385        for case in 0..260 {
14386            let len = (next(&mut seed) % 89 + 1) as usize;
14387
14388            let mut numeric = Vec::with_capacity(len);
14389            numeric.push(Scalar::Int64(case as i64 - 130));
14390            for _ in 1..len {
14391                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14392                numeric.push(match next(&mut seed) % 8 {
14393                    0 => Scalar::Null(NullKind::Null),
14394                    1 => Scalar::Null(NullKind::NaN),
14395                    2 => Scalar::Float64(f64::NAN),
14396                    3 => Scalar::Bool(raw & 1 == 0),
14397                    4 => Scalar::Int64(raw % 257),
14398                    5 => Scalar::Float64(raw as f64 / 67.0),
14399                    6 => Scalar::Float64(0.0),
14400                    _ => Scalar::Float64(-0.0),
14401                });
14402            }
14403            let (sum, mean) = expected_numeric(&numeric);
14404            assert_sum_mean(case, "numeric", &numeric, sum, mean);
14405
14406            let mut timedeltas = Vec::with_capacity(len);
14407            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
14408            for _ in 1..len {
14409                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14410                timedeltas.push(match next(&mut seed) % 7 {
14411                    0 => Scalar::Null(NullKind::Null),
14412                    1 => Scalar::Timedelta64(i64::MIN),
14413                    _ => Scalar::Timedelta64(raw),
14414                });
14415            }
14416            let (sum, mean) = expected_timedelta(&timedeltas);
14417            assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
14418        }
14419    }
14420
14421    #[test]
14422    fn nannunique_merges_negative_zero_and_zero() {
14423        let vals = vec![
14424            Scalar::Float64(-0.0),
14425            Scalar::Float64(0.0),
14426            Scalar::Float64(1.0),
14427        ];
14428        assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
14429    }
14430
14431    #[test]
14432    fn nannunique_matches_scalar_bucket_oracle_elvbg() {
14433        // Differential vs independent scalar unique-bucket oracle
14434        // (br-frankenpandas-elvbg). Seeded LCG, no mocks.
14435        fn next(seed: &mut u64) -> u64 {
14436            *seed = seed
14437                .wrapping_mul(2862933555777941757)
14438                .wrapping_add(3037000493);
14439            *seed
14440        }
14441
14442        fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
14443            match (left, right) {
14444                (Scalar::Float64(left), Scalar::Float64(right)) => {
14445                    let left = if *left == 0.0 { 0.0 } else { *left };
14446                    let right = if *right == 0.0 { 0.0 } else { *right };
14447                    left.to_bits() == right.to_bits()
14448                }
14449                _ => left == right,
14450            }
14451        }
14452
14453        fn expected_nunique(values: &[Scalar]) -> i64 {
14454            let mut seen = Vec::<Scalar>::new();
14455            for value in values {
14456                if value.is_missing() {
14457                    continue;
14458                }
14459                if !seen.iter().any(|existing| same_bucket(existing, value)) {
14460                    seen.push(value.clone());
14461                }
14462            }
14463            seen.len() as i64
14464        }
14465
14466        fn assert_nannunique(case: usize, values: &[Scalar]) {
14467            assert_eq!(
14468                super::nannunique(values),
14469                Scalar::Int64(expected_nunique(values)),
14470                "case={case}: nannunique mismatch for {values:?}"
14471            );
14472        }
14473
14474        assert_nannunique(
14475            usize::MAX,
14476            &[
14477                Scalar::Float64(-0.0),
14478                Scalar::Float64(0.0),
14479                Scalar::Float64(f64::NAN),
14480                Scalar::Null(NullKind::Null),
14481                Scalar::Timedelta64(i64::MIN),
14482            ],
14483        );
14484
14485        let mut seed = 0x0e1b_60d0_b5e7_u64;
14486        for case in 0..320 {
14487            let len = (next(&mut seed) % 97 + 1) as usize;
14488            let mut values = Vec::with_capacity(len);
14489            for pos in 0..len {
14490                let raw = (next(&mut seed) % 1_001) as i64 - 500;
14491                values.push(match next(&mut seed) % 11 {
14492                    0 => Scalar::Null(NullKind::Null),
14493                    1 => Scalar::Null(NullKind::NaN),
14494                    2 => Scalar::Float64(f64::NAN),
14495                    3 => Scalar::Bool(raw & 1 == 0),
14496                    4 => Scalar::Int64(raw % 37),
14497                    5 => Scalar::Float64(raw as f64 / 19.0),
14498                    6 => Scalar::Float64(0.0),
14499                    7 => Scalar::Float64(-0.0),
14500                    8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
14501                    9 => Scalar::Utf8(String::new()),
14502                    _ => Scalar::Timedelta64(raw % 41),
14503                });
14504            }
14505            assert_nannunique(case, &values);
14506        }
14507    }
14508
14509    #[test]
14510    fn nanmean_basic() {
14511        let vals = vec![
14512            Scalar::Float64(2.0),
14513            Scalar::Null(NullKind::Null),
14514            Scalar::Float64(4.0),
14515        ];
14516        assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
14517    }
14518
14519    #[test]
14520    fn nanmean_all_null_returns_nan() {
14521        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
14522        assert!(super::nanmean(&vals).is_missing());
14523    }
14524
14525    #[test]
14526    fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
14527        // Per br-frankenpandas-620mj: pandas td_series.sum()/mean() return
14528        // Timedelta64, not Float64(0.0). Was silently zero before because
14529        // collect_finite drops Timedelta64 (to_f64 errors).
14530        let one_hour = 3_600 * 1_000_000_000_i64;
14531        let vals = vec![
14532            Scalar::Timedelta64(one_hour),
14533            Scalar::Timedelta64(2 * one_hour),
14534            Scalar::Timedelta64(3 * one_hour),
14535        ];
14536        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
14537        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
14538    }
14539
14540    #[test]
14541    fn nansum_nanmean_timedelta64_skips_nat_620mj() {
14542        let one_hour = 3_600 * 1_000_000_000_i64;
14543        let vals = vec![
14544            Scalar::Timedelta64(Timedelta::NAT),
14545            Scalar::Timedelta64(one_hour),
14546            Scalar::Timedelta64(3 * one_hour),
14547            Scalar::Timedelta64(Timedelta::NAT),
14548        ];
14549        // NAT is missing → skipped. Sum: 1h+3h=4h; mean: 2h.
14550        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
14551        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
14552    }
14553
14554    /// br-frankenpandas-opz27: the Timedelta reduction surface used to narrow
14555    /// its exact i128 accumulator with `clamp(i64::MIN, i64::MAX)`, which
14556    /// fabricated a finite Timedelta.max on positive overflow. Live pandas
14557    /// 2.2.3 raises `ValueError: overflow in timedelta operation` here; FP
14558    /// surfaces NaT per the lgyy8 convention. A clamping implementation
14559    /// returns `Timedelta64(i64::MAX)` and fails this.
14560    #[test]
14561    fn nansum_timedelta_overflow_is_nat_not_fabricated_max_opz27() {
14562        let vals = vec![Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MAX)];
14563        let got = super::nansum(&vals);
14564        assert!(
14565            got.is_missing(),
14566            "overflowing sum must be missing, got {got:?}"
14567        );
14568        assert_eq!(got, Scalar::Timedelta64(Timedelta::NAT));
14569        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
14570    }
14571
14572    /// The negative direction used to reach NaT only *by accident*, because
14573    /// `Timedelta::NAT == i64::MIN` is exactly the clamp's lower bound — and
14574    /// that bound is off by one against the true minimum (`i64::MIN + 1`).
14575    /// Pin both the sentinel and the boundary so the accident becomes a rule.
14576    #[test]
14577    fn nansum_timedelta_negative_overflow_is_nat_opz27() {
14578        let min_repr = i64::MIN + 1; // Timedelta.min; i64::MIN is the NaT sentinel
14579        let vals = vec![Scalar::Timedelta64(min_repr), Scalar::Timedelta64(min_repr)];
14580        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(Timedelta::NAT));
14581
14582        // Exactly the most-negative representable total stays a real value and
14583        // must NOT collapse into the sentinel one nanosecond above it.
14584        let exact = vec![Scalar::Timedelta64(min_repr + 1), Scalar::Timedelta64(-1)];
14585        let got = super::nansum(&exact);
14586        assert_eq!(got, Scalar::Timedelta64(min_repr));
14587        assert!(!got.is_missing(), "Timedelta.min is representable, not NaT");
14588    }
14589
14590    /// pandas 2.2.3: `Series([Timedelta.min, Timedelta.max]).max() - .min()`
14591    /// raises OverflowError. FP used `saturating_sub`, fabricating
14592    /// Timedelta.max as a plausible range.
14593    #[test]
14594    fn nanptp_timedelta_overflow_is_nat_opz27() {
14595        let vals = vec![
14596            Scalar::Timedelta64(i64::MIN + 1),
14597            Scalar::Timedelta64(i64::MAX),
14598        ];
14599        let got = super::nanptp(&vals);
14600        assert!(
14601            got.is_missing(),
14602            "unrepresentable range must be NaT, got {got:?}"
14603        );
14604        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
14605
14606        // A representable range is still exact to the nanosecond (the reason
14607        // this path avoids f64 at all).
14608        let hour = 3_600 * 1_000_000_000_i64;
14609        let ok = vec![Scalar::Timedelta64(hour), Scalar::Timedelta64(4 * hour)];
14610        assert_eq!(super::nanptp(&ok), Scalar::Timedelta64(3 * hour));
14611    }
14612
14613    /// The load-bearing cumsum case: accumulation stays exact in i128, so only
14614    /// the *unrepresentable* index goes NaT and a later index that returns to
14615    /// range emits its true value. A clamping implementation pins `running` at
14616    /// i64::MAX and can never produce the final value, so it fails this test.
14617    #[test]
14618    fn nancumsum_timedelta_overflow_recovers_exact_value_opz27() {
14619        let vals = vec![
14620            Scalar::Timedelta64(i64::MAX),
14621            Scalar::Timedelta64(i64::MAX), // true total 2*i64::MAX: unrepresentable
14622            Scalar::Timedelta64(i64::MIN + 1), // back in range: total == i64::MAX
14623        ];
14624        let out = super::nancumsum(&vals);
14625        assert_eq!(out.len(), 3);
14626        assert_eq!(out[0], Scalar::Timedelta64(i64::MAX));
14627        assert!(
14628            out[1].is_missing(),
14629            "overflowed index must be NaT, got {:?}",
14630            out[1]
14631        );
14632        assert_eq!(
14633            out[2],
14634            Scalar::Timedelta64(i64::MAX),
14635            "exact i128 accumulation must recover; a clamped running sum cannot"
14636        );
14637    }
14638
14639    /// Non-overflowing cumsum is unchanged bit-for-bit, and input NaT still
14640    /// passes through without advancing the running total.
14641    #[test]
14642    fn nancumsum_timedelta_exact_path_unchanged_opz27() {
14643        let sec = 1_000_000_000_i64;
14644        let vals = vec![
14645            Scalar::Timedelta64(sec),
14646            Scalar::Timedelta64(Timedelta::NAT),
14647            Scalar::Timedelta64(2 * sec),
14648        ];
14649        let out = super::nancumsum(&vals);
14650        assert_eq!(out[0], Scalar::Timedelta64(sec));
14651        assert!(out[1].is_missing());
14652        assert_eq!(out[2], Scalar::Timedelta64(3 * sec));
14653    }
14654
14655    const DAY_NS: i64 = 86_400 * 1_000_000_000;
14656    /// 2020-01-01T00:00:00Z in epoch nanoseconds.
14657    const DT_2020: i64 = 1_577_836_800_000_000_000;
14658
14659    /// br-frankenpandas-axhhk: every one of these returned `Null(NaN)` (or
14660    /// `None`) before the Datetime64 arms existed, because `Datetime64::to_f64()`
14661    /// errors and each reduction fell through to the f64 catch-all. Expectations
14662    /// are the live pandas 2.2.3 answers for
14663    /// `Series([2020-01-01, +60d, +31d])`:
14664    ///   min 2020-01-01 · max 2020-03-01 · ptp Timedelta 60 days
14665    ///   argmin 0 · argmax 1 · cummax/cummin Timestamps
14666    #[test]
14667    fn datetime64_ordering_reductions_match_pandas_axhhk() {
14668        let d = Scalar::Datetime64;
14669        let vals = vec![
14670            d(DT_2020),
14671            d(DT_2020 + 60 * DAY_NS),
14672            d(DT_2020 + 31 * DAY_NS),
14673        ];
14674
14675        assert_eq!(super::nanmin(&vals), d(DT_2020));
14676        assert_eq!(super::nanmax(&vals), d(DT_2020 + 60 * DAY_NS));
14677        assert_eq!(super::nanargmin(&vals), Some(0));
14678        assert_eq!(super::nanargmax(&vals), Some(1));
14679
14680        // ptp of two INSTANTS is a DURATION: Timedelta64, not Datetime64.
14681        let span = super::nanptp(&vals);
14682        assert_eq!(span, Scalar::Timedelta64(60 * DAY_NS));
14683        assert_eq!(span.dtype(), DType::Timedelta64);
14684
14685        assert_eq!(
14686            super::nancummax(&vals),
14687            vec![
14688                d(DT_2020),
14689                d(DT_2020 + 60 * DAY_NS),
14690                d(DT_2020 + 60 * DAY_NS)
14691            ]
14692        );
14693        assert_eq!(
14694            super::nancummin(&vals),
14695            vec![d(DT_2020), d(DT_2020), d(DT_2020)]
14696        );
14697    }
14698
14699    /// The size-dependence is the part that made this bug quiet, so pin it
14700    /// explicitly rather than only asserting the headline. A ONE-element
14701    /// datetime slice was always correct (the `(None, _)` arm seeds `min`
14702    /// before any comparison runs); TWO elements hit the catch-all and
14703    /// returned NaN. A regression that drops the Datetime64 arm would still
14704    /// pass a single-element test.
14705    #[test]
14706    fn datetime64_min_max_size_dependence_pinned_axhhk() {
14707        let d = Scalar::Datetime64;
14708        let one = vec![d(DT_2020)];
14709        assert_eq!(super::nanmin(&one), d(DT_2020));
14710        assert_eq!(super::nanmax(&one), d(DT_2020));
14711
14712        let two = vec![d(DT_2020 + DAY_NS), d(DT_2020)];
14713        let got_min = super::nanmin(&two);
14714        assert!(
14715            !got_min.is_missing(),
14716            "2-element datetime min must not be missing, got {got_min:?}"
14717        );
14718        assert_eq!(got_min, d(DT_2020));
14719        assert_eq!(super::nanmax(&two), d(DT_2020 + DAY_NS));
14720    }
14721
14722    /// NaT still skips, and a datetime span too large for i64 surfaces NaT via
14723    /// the shared opz27 narrowing rather than a fabricated extreme.
14724    #[test]
14725    fn datetime64_reductions_skip_nat_and_guard_span_overflow_axhhk() {
14726        let d = Scalar::Datetime64;
14727        let with_nat = vec![
14728            d(Timestamp::NAT),
14729            d(DT_2020 + 31 * DAY_NS),
14730            d(DT_2020),
14731            d(Timestamp::NAT),
14732        ];
14733        assert_eq!(super::nanmin(&with_nat), d(DT_2020));
14734        assert_eq!(super::nanmax(&with_nat), d(DT_2020 + 31 * DAY_NS));
14735        assert_eq!(super::nanptp(&with_nat), Scalar::Timedelta64(31 * DAY_NS));
14736        // argmin/argmax report positions in the ORIGINAL slice, NaT skipped.
14737        assert_eq!(super::nanargmin(&with_nat), Some(2));
14738        assert_eq!(super::nanargmax(&with_nat), Some(1));
14739
14740        // Span exceeding i64 ns: NaT, never a fabricated Timedelta.max.
14741        let huge = vec![d(i64::MIN + 1), d(i64::MAX)];
14742        let span = super::nanptp(&huge);
14743        assert!(span.is_missing(), "unrepresentable span must be NaT");
14744        assert_ne!(span, Scalar::Timedelta64(i64::MAX));
14745    }
14746
14747    /// br-frankenpandas-adv58: mean/median/quantile returned `Null(NaN)` for
14748    /// datetime input. Expectations are the live pandas 2.2.3 answers for
14749    /// `Series([2020-01-01, +60d, +31d])`, which at day granularity pandas
14750    /// computes exactly:
14751    ///   mean 2020-01-31T08:00 · median 2020-02-01 · q0.5 2020-02-01
14752    ///   q0.25 2020-01-16T12:00
14753    #[test]
14754    fn datetime64_averaging_reductions_match_pandas_adv58() {
14755        let d = Scalar::Datetime64;
14756        let vals = vec![
14757            d(DT_2020),
14758            d(DT_2020 + 60 * DAY_NS),
14759            d(DT_2020 + 31 * DAY_NS),
14760        ];
14761        // 1580457600e9 / 1580515200e9 / 1579176000e9, straight from the probe.
14762        assert_eq!(super::nanmean(&vals), d(1_580_457_600_000_000_000));
14763        assert_eq!(super::nanmedian(&vals), d(1_580_515_200_000_000_000));
14764        assert_eq!(super::nanquantile(&vals, 0.5), d(1_580_515_200_000_000_000));
14765        assert_eq!(
14766            super::nanquantile(&vals, 0.25),
14767            d(1_579_176_000_000_000_000)
14768        );
14769    }
14770
14771    /// The even-count rounding rule, probed at 1 ns granularity where pandas is
14772    /// exact. It is TRUNCATION TOWARD ZERO — plain Rust integer division.
14773    /// `floor` would give -1 for [-1,0]; ties-to-even would give 2 for [1,2].
14774    /// Both are refuted by these cases, so this test discriminates against the
14775    /// two rounding rules a reimplementation is most likely to pick.
14776    #[test]
14777    fn datetime64_mean_median_round_toward_zero_adv58() {
14778        let d = Scalar::Datetime64;
14779        for (a, b, want) in [
14780            (0_i64, 1_i64, 0_i64),
14781            (0, 3, 1),
14782            (1, 2, 1),
14783            (-1, 0, 0),
14784            (-3, 0, -1),
14785            (-2, -1, -1),
14786            (0, 2, 1),
14787            (-2, 0, -1),
14788        ] {
14789            let vals = vec![d(a), d(b)];
14790            assert_eq!(
14791                super::nanmean(&vals),
14792                d(want),
14793                "mean of [{a}, {b}] should be {want}"
14794            );
14795            assert_eq!(
14796                super::nanmedian(&vals),
14797                d(want),
14798                "median of [{a}, {b}] should be {want}"
14799            );
14800        }
14801    }
14802
14803    /// NaT is skipped, and an all-NaT datetime input stays in the Datetime
14804    /// family rather than degrading to a numeric NaN.
14805    #[test]
14806    fn datetime64_averaging_skips_nat_adv58() {
14807        let d = Scalar::Datetime64;
14808        let vals = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14809        // pandas: mean == median == 2020-01-02, count 2.
14810        assert_eq!(super::nanmean(&vals), d(DT_2020 + DAY_NS));
14811        assert_eq!(super::nanmedian(&vals), d(DT_2020 + DAY_NS));
14812
14813        let all_nat = vec![d(Timestamp::NAT), d(Timestamp::NAT)];
14814        let got = super::nanmean(&all_nat);
14815        assert!(
14816            got.is_missing(),
14817            "all-NaT mean must be missing, got {got:?}"
14818        );
14819        assert_eq!(
14820            got.dtype(),
14821            DType::datetime64_naive(),
14822            "must stay Datetime64"
14823        );
14824    }
14825
14826    /// FP is EXACT here and pandas is not: pandas routes datetime
14827    /// mean/median/quantile through f64, so at 2020-era magnitudes (~1.58e18,
14828    /// f64 ULP 256 ns) it snaps to a 256 ns grid — it returns B+0 for the mean
14829    /// of the CONSTANT series [B+1, B+1], and for an odd-count median it can
14830    /// return a Timestamp that is not even one of the inputs. FP keeps the
14831    /// exact i128 treatment its Timedelta sibling already had. DISC-019.
14832    #[test]
14833    fn datetime64_averaging_is_exact_where_pandas_snaps_adv58() {
14834        let d = Scalar::Datetime64;
14835
14836        // Constant series: the answer is unambiguous; pandas still loses it.
14837        let constant = vec![d(DT_2020 + 1), d(DT_2020 + 1)];
14838        assert_eq!(super::nanmean(&constant), d(DT_2020 + 1));
14839        assert_eq!(super::nanmedian(&constant), d(DT_2020 + 1));
14840
14841        // Odd-count median is a SELECTION: the result must be an input value.
14842        let odd = vec![d(DT_2020), d(DT_2020 + 129), d(DT_2020 + 258)];
14843        let med = super::nanmedian(&odd);
14844        assert_eq!(med, d(DT_2020 + 129));
14845        assert!(
14846            odd.contains(&med),
14847            "odd-count median must be one of the inputs; pandas returns B+256, which is not"
14848        );
14849    }
14850
14851    /// br-frankenpandas-40ujm: datetime std returned `Null(NaN)`; pandas 2.2.3
14852    /// returns a Timedelta. Every value below is the probed oracle answer for
14853    /// `Series([2020-01-01, +60d, +31d])`, in raw ns:
14854    ///   ddof=1 (default) 2592479955563784   ddof=0 2116751019841492
14855    ///   ddof=2           3666320313338702   ddof=3 NaT (n - ddof <= 0)
14856    /// pandas truncates the sqrt toward zero (ddof=0 is 2116751019841492.8).
14857    #[test]
14858    fn datetime64_std_matches_pandas_ddof_variants_40ujm() {
14859        let d = Scalar::Datetime64;
14860        let vals = vec![
14861            d(DT_2020),
14862            d(DT_2020 + 60 * DAY_NS),
14863            d(DT_2020 + 31 * DAY_NS),
14864        ];
14865        // Dispersion of instants is a DURATION: Timedelta64, not Datetime64.
14866        let s1 = super::nanstd(&vals, 1);
14867        assert_eq!(s1, Scalar::Timedelta64(2_592_479_955_563_784));
14868        assert_eq!(s1.dtype(), DType::Timedelta64);
14869        assert_eq!(
14870            super::nanstd(&vals, 0),
14871            Scalar::Timedelta64(2_116_751_019_841_492)
14872        );
14873        assert_eq!(
14874            super::nanstd(&vals, 2),
14875            Scalar::Timedelta64(3_666_320_313_338_702)
14876        );
14877        // n - ddof <= 0 => NaT, matching pandas.
14878        assert!(super::nanstd(&vals, 3).is_missing());
14879    }
14880
14881    /// pandas returns the SAME std for a Datetime64 series and a Timedelta64
14882    /// series built from identical ns. That equivalence is the whole basis for
14883    /// routing both families through one computation, so pin it directly.
14884    #[test]
14885    fn datetime64_std_equals_timedelta64_std_on_same_ns_40ujm() {
14886        let offsets = [0_i64, 60 * DAY_NS, 31 * DAY_NS];
14887        let dt: Vec<Scalar> = offsets.iter().map(|o| Scalar::Datetime64(*o)).collect();
14888        let td: Vec<Scalar> = offsets.iter().map(|o| Scalar::Timedelta64(*o)).collect();
14889        assert_eq!(super::nanstd(&dt, 1), super::nanstd(&td, 1));
14890        assert_eq!(
14891            super::nanstd(&dt, 1),
14892            Scalar::Timedelta64(2_592_479_955_563_784)
14893        );
14894    }
14895
14896    /// NaT skips (a 3-element series with one NaT must equal the 2-element
14897    /// series without it), a single element gives NaT at the default ddof, and
14898    /// var/sem stay REFUSED for datetimes because pandas raises on them.
14899    #[test]
14900    fn datetime64_std_skips_nat_and_var_sem_stay_unsupported_40ujm() {
14901        let d = Scalar::Datetime64;
14902        let with_nat = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14903        let without = vec![d(DT_2020), d(DT_2020 + 2 * DAY_NS)];
14904        // pandas: both are Timedelta 1 days 09:56:28.051789035.
14905        assert_eq!(super::nanstd(&with_nat, 1), super::nanstd(&without, 1));
14906        assert_eq!(
14907            super::nanstd(&with_nat, 1),
14908            Scalar::Timedelta64(122_188_051_789_035)
14909        );
14910
14911        // n=1 with ddof=1 -> NaT, as pandas returns.
14912        assert!(super::nanstd(&[d(DT_2020)], 1).is_missing());
14913        assert!(super::nanstd(&[d(Timestamp::NAT)], 1).is_missing());
14914
14915        // pandas RAISES TypeError for datetime64 var and sem. FP must not
14916        // invent a value: these stay on the Timedelta-only gate and report
14917        // missing. A regression that widened them would return a number here.
14918        let vals = vec![d(DT_2020), d(DT_2020 + 60 * DAY_NS)];
14919        assert!(super::nanvar(&vals, 1).is_missing());
14920        assert!(super::nansem(&vals, 1).is_missing());
14921    }
14922
14923    /// br-frankenpandas-qoabs: Period is the THIRD dtype whose `to_f64()`
14924    /// errors, so min/max fell into the f64 catch-all and returned
14925    /// `Null(NaN)`. pandas 2.2.3 on `Series([2020-01, 2020-03, 2020-02], M)`
14926    /// gives min 2020-01 and max 2020-03; ordinals are 600/601/602.
14927    #[test]
14928    fn period_min_max_match_pandas_qoabs() {
14929        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14930        let vals = vec![p(600), p(602), p(601)];
14931        assert_eq!(super::nanmin(&vals), p(600));
14932        assert_eq!(super::nanmax(&vals), p(602));
14933
14934        // Size-dependence, exactly as in axhhk: ONE element always worked via
14935        // the `(None, _)` seed, so a test with a single value would pass even
14936        // with no Period arm at all. Assert both sizes.
14937        assert_eq!(super::nanmin(&[p(600)]), p(600));
14938        let two = vec![p(602), p(600)];
14939        assert!(!super::nanmin(&two).is_missing());
14940        assert_eq!(super::nanmin(&two), p(600));
14941        assert_eq!(super::nanmax(&two), p(602));
14942    }
14943
14944    /// A Period whose ordinal is the NaT sentinel is missing and skipped, and
14945    /// an all-missing Period input reports missing rather than a value.
14946    #[test]
14947    fn period_min_max_skip_nat_qoabs() {
14948        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14949        let nat = Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly));
14950        let vals = vec![nat.clone(), p(602), p(600), nat.clone()];
14951        assert_eq!(super::nanmin(&vals), p(600));
14952        assert_eq!(super::nanmax(&vals), p(602));
14953        assert!(super::nanmin(&[nat.clone(), nat]).is_missing());
14954    }
14955
14956    /// MIXED FREQ must not be ordered. pandas refuses it outright
14957    /// (`IncompatibleFrequency: Input has different freq=D from Period(freq=M)`),
14958    /// so FP reports missing rather than inventing an order. This is the test
14959    /// that discriminates: an implementation comparing raw ordinals would
14960    /// happily return a value here, because monthly 2020-01 is ordinal 600
14961    /// while daily 2020-01-05 is 18267 — it would call the daily period later.
14962    #[test]
14963    fn period_mixed_freq_is_not_ordered_qoabs() {
14964        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
14965        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
14966        let vals = vec![month.clone(), day.clone()];
14967        let got_min = super::nanmin(&vals);
14968        assert!(
14969            got_min.is_missing(),
14970            "mixed-freq Period min must not be ordered, got {got_min:?}"
14971        );
14972        assert_ne!(
14973            got_min, day,
14974            "must not rank the daily period by raw ordinal"
14975        );
14976        assert!(super::nanmax(&vals).is_missing());
14977    }
14978
14979    /// br-frankenpandas-d7zjp: the rest of the Period reduction family, which
14980    /// qoabs deferred because a `fn(i64) -> Scalar` constructor cannot carry a
14981    /// freq. Expectations are the probed pandas 2.2.3 answers for
14982    /// `Series([2020-01, 2020-03, 2020-02], freq=M)` (ordinals 600/601/602):
14983    ///   median 2020-02 · quantile(0.5) 2020-02 · idxmin 0 · idxmax 1
14984    ///   cummax ends 2020-03 · cummin ends 2020-01
14985    #[test]
14986    fn period_full_reduction_family_matches_pandas_d7zjp() {
14987        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14988        let vals = vec![p(600), p(602), p(601)];
14989
14990        assert_eq!(super::nanmedian(&vals), p(601));
14991        assert_eq!(super::nanquantile(&vals, 0.5), p(601));
14992        assert_eq!(super::nanargmin(&vals), Some(0));
14993        assert_eq!(super::nanargmax(&vals), Some(1));
14994        assert_eq!(super::nancummax(&vals), vec![p(600), p(602), p(602)]);
14995        assert_eq!(super::nancummin(&vals), vec![p(600), p(600), p(600)]);
14996    }
14997
14998    /// Even-count Period median picks by TRUNCATION TOWARD ZERO on the ordinal,
14999    /// the same rule the datetime family uses. Probed: pandas gives 2020-02 for
15000    /// [2020-01, 2020-04] (ordinals 600/603, midpoint 601.5) and 2020-01 for
15001    /// [2020-01, 2020-02] (600/601, midpoint 600.5).
15002    #[test]
15003    fn period_even_count_median_truncates_toward_zero_d7zjp() {
15004        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
15005        assert_eq!(super::nanmedian(&[p(600), p(603)]), p(601));
15006        assert_eq!(super::nanmedian(&[p(600), p(601)]), p(600));
15007    }
15008
15009    /// MIXED FREQ must not be ordered by ANY of these, for the same reason as
15010    /// in qoabs: pandas raises IncompatibleFrequency, and raw ordinals are not
15011    /// comparable across freqs (monthly 2020-01 is 600, daily 2020-01-05 is
15012    /// 18267). The family enum encodes the freq, so a mixed input is simply not
15013    /// one family and never reaches a typed arm.
15014    #[test]
15015    fn period_mixed_freq_not_ordered_by_any_reduction_d7zjp() {
15016        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
15017        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
15018        let vals = vec![month, day];
15019
15020        assert!(super::nanmedian(&vals).is_missing());
15021        assert!(super::nanquantile(&vals, 0.5).is_missing());
15022        assert_eq!(super::nanargmin(&vals), None);
15023        assert_eq!(super::nanargmax(&vals), None);
15024        // The cumulative ops must not emit an ordered Period column either.
15025        assert!(super::nancummax(&vals).iter().all(Scalar::is_missing));
15026        assert!(super::nancummin(&vals).iter().all(Scalar::is_missing));
15027    }
15028
15029    /// pandas RAISES for Period mean/sum/std/var ("does not support reduction",
15030    /// and for mean explicitly "the meaning is ambiguous"). FP must not invent
15031    /// values. `std` is the trap here: the family enum puts Period one line
15032    /// away from the Datetime64 arm that 40ujm deliberately widened, so this
15033    /// asserts the guard holds.
15034    #[test]
15035    fn period_unsupported_reductions_stay_missing_d7zjp() {
15036        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
15037        let vals = vec![p(600), p(602), p(601)];
15038        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
15039        assert!(super::nanvar(&vals, 1).is_missing(), "pandas raises var");
15040        assert!(super::nansem(&vals, 1).is_missing(), "pandas raises sem");
15041        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
15042    }
15043
15044    /// br-frankenpandas-srqdo: Interval is the FOURTH dtype whose `to_f64()`
15045    /// errors, so min/max fell into the f64 catch-all and returned
15046    /// `Null(NaN)`. pandas 2.2.3 on `IntervalArray.from_tuples([(0,1),(4,5),(2,3)])`
15047    /// gives min `(0, 1]` and max `(4, 5]`.
15048    #[test]
15049    fn interval_min_max_match_pandas_srqdo() {
15050        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15051        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
15052        assert_eq!(super::nanmin(&vals), iv(0.0, 1.0));
15053        assert_eq!(super::nanmax(&vals), iv(4.0, 5.0));
15054
15055        // Size-dependence, per the axhhk lesson: ONE element always worked via
15056        // the `(None, _)` seed, so a single-value test passes even with no arm.
15057        assert_eq!(super::nanmin(&[iv(2.0, 3.0)]), iv(2.0, 3.0));
15058        let two = vec![iv(4.0, 5.0), iv(0.0, 1.0)];
15059        assert!(!super::nanmin(&two).is_missing());
15060        assert_eq!(super::nanmin(&two), iv(0.0, 1.0));
15061        assert_eq!(super::nanmax(&two), iv(4.0, 5.0));
15062    }
15063
15064    /// The tie-on-left case, which is what discriminates a correct (left, right)
15065    /// comparison from one that only looks at `left`. pandas: Interval(0,2) <
15066    /// Interval(0,5) is True. An implementation comparing left alone keeps
15067    /// whichever came first and returns the wrong element here.
15068    #[test]
15069    fn interval_ties_on_left_order_by_right_srqdo() {
15070        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15071        let vals = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
15072        assert_eq!(super::nanmin(&vals), iv(0.0, 2.0));
15073        assert_eq!(super::nanmax(&vals), iv(0.0, 9.0));
15074    }
15075
15076    /// A NaN bound has no pandas counterpart — `IntervalArray` refuses to build
15077    /// one ("missing values must be missing in the same location both left and
15078    /// right") — so it must report missing rather than impose an arbitrary
15079    /// order. Critically this must NOT panic: the obvious
15080    /// `partial_cmp().unwrap()` implementation would.
15081    #[test]
15082    fn interval_nan_bound_is_not_ordered_srqdo() {
15083        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15084        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
15085        assert!(super::nanmin(&vals).is_missing());
15086        assert!(super::nanmax(&vals).is_missing());
15087    }
15088
15089    /// pandas RAISES or NotImplementedErrors every other reduction for
15090    /// Interval (median/mean/sum/std/quantile/cummax). FP must not invent
15091    /// values, so they stay missing.
15092    #[test]
15093    fn interval_unsupported_reductions_stay_missing_srqdo() {
15094        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15095        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
15096        assert!(super::nanmedian(&vals).is_missing(), "pandas raises median");
15097        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
15098        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
15099        assert!(
15100            super::nanquantile(&vals, 0.5).is_missing(),
15101            "pandas raises quantile"
15102        );
15103        assert!(
15104            super::nancummax(&vals).iter().all(Scalar::is_missing),
15105            "pandas NotImplementedErrors cummax"
15106        );
15107    }
15108
15109    /// br-frankenpandas-2h9dm: Interval argmin/argmax returned None, because
15110    /// `Interval::to_f64()` errors and the f64 fallback skipped every element.
15111    /// All four expectations are probed pandas 2.2.3 `idxmin`/`idxmax`.
15112    #[test]
15113    fn interval_argmin_argmax_match_pandas_2h9dm() {
15114        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15115        // pandas: idxmin 1, idxmax 0
15116        let vals = vec![iv(4.0, 5.0), iv(0.0, 1.0), iv(2.0, 3.0)];
15117        assert_eq!(super::nanargmin(&vals), Some(1));
15118        assert_eq!(super::nanargmax(&vals), Some(0));
15119
15120        // Left-tie resolves by RIGHT. pandas: idxmin 1, idxmax 2. An
15121        // implementation comparing only `left` keeps index 0 for both.
15122        let tie = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
15123        assert_eq!(super::nanargmin(&tie), Some(1));
15124        assert_eq!(super::nanargmax(&tie), Some(2));
15125    }
15126
15127    /// Duplicated extreme returns the FIRST occurrence (pandas idxmin 0 on
15128    /// [(0,1),(0,1),(9,9)]), and missing entries are skipped while the returned
15129    /// index stays a position in the ORIGINAL slice (pandas idxmin 2 / idxmax 0
15130    /// on [(4,5), None, (0,1)]).
15131    #[test]
15132    fn interval_arg_first_occurrence_and_missing_2h9dm() {
15133        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15134        let dup = vec![iv(0.0, 1.0), iv(0.0, 1.0), iv(9.0, 9.0)];
15135        assert_eq!(
15136            super::nanargmin(&dup),
15137            Some(0),
15138            "first occurrence, not last"
15139        );
15140        assert_eq!(super::nanargmax(&dup), Some(2));
15141
15142        let with_missing = vec![iv(4.0, 5.0), Scalar::Null(NullKind::NaN), iv(0.0, 1.0)];
15143        assert_eq!(super::nanargmin(&with_missing), Some(2));
15144        assert_eq!(super::nanargmax(&with_missing), Some(0));
15145    }
15146
15147    /// A NaN bound is not orderable, so decline rather than return an arbitrary
15148    /// index — and critically, do not panic the way `partial_cmp().unwrap()`
15149    /// would.
15150    #[test]
15151    fn interval_arg_nan_bound_declines_2h9dm() {
15152        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15153        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
15154        assert_eq!(super::nanargmin(&vals), None);
15155        assert_eq!(super::nanargmax(&vals), None);
15156    }
15157
15158    /// br-frankenpandas-fyr1z-policy-carrier-f29nz: the load-bearing guarantee
15159    /// of this bead is NO DEFAULT BEHAVIOR CHANGE. Prove it rather than assert
15160    /// it: over a seeded corpus that deliberately straddles the i64 boundary
15161    /// and the NaT sentinel, every infallible helper must equal its fallible
15162    /// sibling resolved under the default `SurfaceNat` policy — which is also
15163    /// exactly what the pre-f29nz bodies computed.
15164    #[test]
15165    fn overflow_policy_carrier_preserves_default_behavior_f29nz() {
15166        // Seeded LCG, no rand dependency (see [[differential-test-coverage]]).
15167        let mut state: u64 = 0x5DEE_CE66_D125_1F00;
15168        let mut next = || {
15169            state = state
15170                .wrapping_mul(6_364_136_223_846_793_005)
15171                .wrapping_add(1_442_695_040_888_963_407);
15172            state
15173        };
15174        // Edge values first, then random ones. i64::MIN is the NaT sentinel.
15175        let mut corpus: Vec<i64> = vec![
15176            0,
15177            1,
15178            -1,
15179            2,
15180            -2,
15181            i64::MAX,
15182            i64::MIN,
15183            i64::MIN + 1,
15184            i64::MAX - 1,
15185            i64::MAX / 2,
15186            -(i64::MAX / 2),
15187        ];
15188        for _ in 0..400 {
15189            let raw = next() as i64;
15190            corpus.push(raw);
15191            corpus.push(raw / 3);
15192        }
15193
15194        let policy = super::OverflowPolicy::default();
15195        assert_eq!(
15196            policy,
15197            super::OverflowPolicy::SurfaceNat,
15198            "default must not move"
15199        );
15200
15201        for &a in &corpus {
15202            for &b in &corpus {
15203                // Timedelta::add / sub / mul_scalar
15204                assert_eq!(
15205                    Timedelta::add(a, b),
15206                    policy
15207                        .resolve(Timedelta::try_add(a, b), Timedelta::NAT)
15208                        .expect("SurfaceNat never errors"),
15209                    "add({a}, {b}) diverged"
15210                );
15211                assert_eq!(
15212                    Timedelta::sub(a, b),
15213                    policy
15214                        .resolve(Timedelta::try_sub(a, b), Timedelta::NAT)
15215                        .expect("SurfaceNat never errors"),
15216                    "sub({a}, {b}) diverged"
15217                );
15218                assert_eq!(
15219                    Timedelta::mul_scalar(a, b),
15220                    policy
15221                        .resolve(Timedelta::try_mul_scalar(a, b), Timedelta::NAT)
15222                        .expect("SurfaceNat never errors"),
15223                    "mul_scalar({a}, {b}) diverged"
15224                );
15225
15226                // Timestamp::{add,sub}_timedelta / sub_timestamp — including tz,
15227                // since overflow deliberately drops it.
15228                let ts = Timestamp::from_nanos(a);
15229                assert_eq!(
15230                    ts.add_timedelta(b),
15231                    ts.try_add_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
15232                    "add_timedelta({a}, {b}) diverged"
15233                );
15234                assert_eq!(
15235                    ts.sub_timedelta(b),
15236                    ts.try_sub_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
15237                    "sub_timedelta({a}, {b}) diverged"
15238                );
15239                let other = Timestamp::from_nanos(b);
15240                assert_eq!(
15241                    ts.sub_timestamp(&other),
15242                    ts.try_sub_timestamp(&other).unwrap_or(Timedelta::NAT),
15243                    "sub_timestamp({a}, {b}) diverged"
15244                );
15245            }
15246        }
15247    }
15248
15249    /// The carrier must actually CARRY something: `Strict` propagates the
15250    /// overflow with the right op name and the pandas error class probed from
15251    /// live 2.2.3. Without this, `resolve` could ignore its policy and the
15252    /// equivalence test above would still pass.
15253    #[test]
15254    fn overflow_policy_strict_reports_op_and_pandas_class_f29nz() {
15255        use super::{OverflowPolicy, PandasTemporalError};
15256
15257        let strict = OverflowPolicy::Strict;
15258
15259        // pd.Timedelta.max + pd.Timedelta('1ns') -> OverflowError
15260        let err = strict
15261            .resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT)
15262            .expect_err("must surface under Strict");
15263        assert_eq!(err.op, "Timedelta::add");
15264        assert_eq!(err.pandas_error, PandasTemporalError::Overflow);
15265
15266        // pd.Timestamp.max + pd.Timedelta('1ns') -> OutOfBoundsDatetime
15267        let ts = Timestamp::from_nanos(i64::MAX);
15268        let err = strict
15269            .resolve(ts.try_add_timedelta(1), Timestamp::nat())
15270            .expect_err("must surface under Strict");
15271        assert_eq!(err.op, "Timestamp::add_timedelta");
15272        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
15273
15274        // pd.Timestamp.min - pd.Timestamp.max -> OutOfBoundsDatetime
15275        let err = strict
15276            .resolve(
15277                Timestamp::from_nanos(i64::MIN + 1)
15278                    .try_sub_timestamp(&Timestamp::from_nanos(i64::MAX)),
15279                Timedelta::NAT,
15280            )
15281            .expect_err("must surface under Strict");
15282        assert_eq!(err.op, "Timestamp::sub_timestamp");
15283        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
15284
15285        // A NaT operand is PROPAGATION, not overflow: Strict must still be Ok.
15286        assert_eq!(
15287            strict
15288                .resolve(Timedelta::try_add(Timedelta::NAT, 1), Timedelta::NAT)
15289                .expect("NaT propagation is not an overflow"),
15290            Timedelta::NAT
15291        );
15292        // And a representable result is untouched under either policy.
15293        assert_eq!(
15294            strict
15295                .resolve(Timedelta::try_add(2, 3), Timedelta::NAT)
15296                .expect("no overflow"),
15297            5
15298        );
15299    }
15300
15301    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2: the scalar divide-by-zero
15302    /// row, and the boundary a STRICT arm must not cross. All four expectations
15303    /// probed on live pandas 2.2.3:
15304    ///   SCALAR  Timedelta('1s') // 0   -> ZeroDivisionError
15305    ///   SCALAR  Timedelta('1s') / 0    -> ZeroDivisionError
15306    ///   VECTOR  Series([Td]) // 0      -> NaT   (must NOT raise)
15307    ///   VECTOR  Series([Td]) / 0       -> NaT   (must NOT raise)
15308    #[test]
15309    fn timedelta_scalar_zero_division_taxonomy_t7ht2() {
15310        use super::{OverflowPolicy, PandasTemporalError};
15311
15312        // The fallible scalar sibling reports ZeroDivision with its op name.
15313        let err = Timedelta::try_div_scalar(1_000_000_000, 0)
15314            .expect_err("scalar divide-by-zero must be reportable");
15315        assert_eq!(err.op, "Timedelta::div_scalar");
15316        assert_eq!(err.pandas_error, PandasTemporalError::ZeroDivision);
15317
15318        // THE BOUNDARY: the infallible helper the vectorized callers use keeps
15319        // returning NaT. If this ever starts raising, FrankenPandas diverges
15320        // from pandas on a row where it is currently bit-for-bit correct.
15321        assert_eq!(Timedelta::div_scalar(1_000_000_000, 0), Timedelta::NAT);
15322        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 0), Timedelta::NAT);
15323
15324        // Under the default policy the failure resolves back to NaT, so
15325        // nothing changes for existing callers.
15326        assert_eq!(
15327            OverflowPolicy::default()
15328                .resolve(Timedelta::try_div_scalar(1_000_000_000, 0), Timedelta::NAT)
15329                .expect("SurfaceNat never errors"),
15330            Timedelta::NAT
15331        );
15332
15333        // Non-zero divisors are untouched, including the floor-division
15334        // adjustment for mixed signs (-7 // 2 == -4, not -3).
15335        assert_eq!(Timedelta::try_div_scalar(-7, 2), Ok(-4));
15336        assert_eq!(Timedelta::div_scalar(-7, 2), -4);
15337        assert_eq!(Timedelta::try_div_scalar(7, 2), Ok(3));
15338        // NaT propagates as Ok, not as a failure.
15339        assert_eq!(
15340            Timedelta::try_div_scalar(Timedelta::NAT, 2),
15341            Ok(Timedelta::NAT)
15342        );
15343    }
15344
15345    /// The constructor row of the taxonomy. Probed:
15346    /// `pd.Timedelta(float('inf'), 's')` raises OutOfBoundsTimedelta —
15347    /// specifically NOT a bare OverflowError, which is why the mapping is
15348    /// explicit rather than assumed.
15349    #[test]
15350    fn timedelta_constructor_error_maps_to_out_of_bounds_t7ht2() {
15351        use super::{PandasTemporalError, TimedeltaError};
15352
15353        assert_eq!(
15354            TimedeltaError::Overflow.pandas_error(),
15355            Some(PandasTemporalError::OutOfBoundsTimedelta)
15356        );
15357        // A parse failure is not part of the arithmetic taxonomy.
15358        assert_eq!(
15359            TimedeltaError::InvalidFormat("nonsense".into()).pandas_error(),
15360            None
15361        );
15362        // And the live path still errors on a non-finite input (8v92m).
15363        assert!(Timedelta::from_unit(f64::INFINITY, "s").is_err());
15364        assert_eq!(
15365            Timedelta::from_unit(f64::INFINITY, "s")
15366                .unwrap_err()
15367                .pandas_error(),
15368            Some(PandasTemporalError::OutOfBoundsTimedelta)
15369        );
15370    }
15371
15372    /// br-frankenpandas-fyr1z-hardened-audit-vllv6: HARDENED mode adds
15373    /// observability, NEVER semantics. Every value it returns must be
15374    /// bit-for-bit what SurfaceNat returns — proven over the same seeded corpus
15375    /// the f29nz equivalence test uses, with the audit log ENABLED throughout so
15376    /// recording cannot perturb results.
15377    #[test]
15378    fn hardened_audit_values_are_bit_identical_to_surface_nat_vllv6() {
15379        use super::{OverflowPolicy, overflow_audit};
15380
15381        overflow_audit::enable();
15382        let mut state: u64 = 0x1234_5678_9ABC_DEF0;
15383        let mut next = || {
15384            state = state
15385                .wrapping_mul(6_364_136_223_846_793_005)
15386                .wrapping_add(1_442_695_040_888_963_407);
15387            state
15388        };
15389        let mut corpus: Vec<i64> = vec![
15390            0,
15391            1,
15392            -1,
15393            2,
15394            -2,
15395            i64::MAX,
15396            i64::MIN,
15397            i64::MIN + 1,
15398            i64::MAX - 1,
15399        ];
15400        for _ in 0..120 {
15401            corpus.push(next() as i64);
15402        }
15403
15404        for &a in &corpus {
15405            for &b in &corpus {
15406                for op in [
15407                    Timedelta::try_add as fn(i64, i64) -> Result<i64, super::TemporalFailure>,
15408                    Timedelta::try_sub,
15409                    Timedelta::try_mul_scalar,
15410                    Timedelta::try_div_scalar,
15411                ] {
15412                    let soft = OverflowPolicy::SurfaceNat
15413                        .resolve(op(a, b), Timedelta::NAT)
15414                        .expect("SurfaceNat never errors");
15415                    let hard = OverflowPolicy::HardenedNat
15416                        .resolve(op(a, b), Timedelta::NAT)
15417                        .expect("HardenedNat never errors");
15418                    assert_eq!(hard, soft, "HARDENED changed a value for ({a}, {b})");
15419                }
15420            }
15421        }
15422        overflow_audit::disable();
15423    }
15424
15425    /// The audit trail itself: HARDENED records the op, the pandas class it
15426    /// would have raised, the OPERANDS whose exact result left the
15427    /// representable range, and the value actually returned — deterministically
15428    /// and in order. SurfaceNat and Strict record nothing.
15429    #[test]
15430    fn hardened_audit_records_deterministic_recovery_entries_vllv6() {
15431        use super::{OverflowPolicy, PandasTemporalError, overflow_audit};
15432
15433        overflow_audit::enable();
15434        assert!(overflow_audit::is_enabled());
15435        assert!(overflow_audit::drain().is_empty(), "starts empty");
15436
15437        // Two overflows and one representable result, in a fixed order.
15438        let _ =
15439            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15440        let _ = OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(2, 3), Timedelta::NAT);
15441        let _ =
15442            OverflowPolicy::HardenedNat.resolve(Timedelta::try_div_scalar(5, 0), Timedelta::NAT);
15443
15444        let entries = overflow_audit::drain();
15445        assert_eq!(entries.len(), 2, "only the two failures are recorded");
15446
15447        assert_eq!(entries[0].op, "Timedelta::add");
15448        assert_eq!(entries[0].pandas_error, PandasTemporalError::Overflow);
15449        assert_eq!(entries[0].operands, Some((i64::MAX, 1)));
15450        assert_eq!(entries[0].recovered_as, i64::MIN);
15451
15452        assert_eq!(entries[1].op, "Timedelta::div_scalar");
15453        assert_eq!(entries[1].pandas_error, PandasTemporalError::ZeroDivision);
15454        assert_eq!(entries[1].operands, Some((5, 0)));
15455
15456        // Draining leaves recording enabled and empty.
15457        assert!(overflow_audit::drain().is_empty());
15458
15459        // The OTHER policies must stay silent — the audit is HARDENED-only.
15460        let _ = OverflowPolicy::SurfaceNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15461        let _ = OverflowPolicy::Strict.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15462        assert!(
15463            overflow_audit::drain().is_empty(),
15464            "SurfaceNat/Strict must not write to the audit trail"
15465        );
15466
15467        overflow_audit::disable();
15468        assert!(!overflow_audit::is_enabled());
15469        // Disabled: recording is a no-op and drain yields nothing.
15470        let _ =
15471            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15472        assert!(
15473            overflow_audit::drain().is_empty(),
15474            "disabled must not record"
15475        );
15476    }
15477
15478    /// br-frankenpandas-fyr1z-wrap-signoff-s4lkx.
15479    ///
15480    /// THIS TEST PINS A PANDAS QUIRK THAT WE REPRODUCE ON PURPOSE. The values
15481    /// below are NOT what a careful implementation would choose: multiplying a
15482    /// positive duration by 2 yields a NEGATIVE one. They are what live pandas
15483    /// 2.2.3 returns, because numpy int64 wraps silently, and the maintainer
15484    /// decided that STRICT means bit-for-bit observable parity with the
15485    /// incumbent INCLUDING its quirks — this being a port.
15486    ///
15487    /// So: if this test fails, do NOT "fix" the wrap. Either pandas changed, or
15488    /// someone routed a non-STRICT caller into the STRICT path. Both need
15489    /// investigating rather than correcting the arithmetic.
15490    ///
15491    /// Oracle values, probed directly:
15492    ///   Series([Timedelta.max]) * 2            -> -2 ns
15493    ///   Series([max, max]).cumsum()            -> [max, -2]
15494    ///   Series([max, max, max]).cumsum()       -> [max, -2, max - 2]
15495    #[test]
15496    fn strict_reproduces_pandas_silent_timedelta_wrap_s4lkx() {
15497        use super::{OverflowPolicy, nancumsum_with_policy};
15498
15499        // Series * int -- pandas returns -2, i.e. i64::MAX.wrapping_mul(2).
15500        assert_eq!(
15501            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::Strict),
15502            -2,
15503            "STRICT must reproduce pandas' wrap, not repair it"
15504        );
15505
15506        // cumsum -- and the THIRD element is the important one: it proves the
15507        // accumulator keeps wrapping rather than sticking at a bound.
15508        let max = Scalar::Timedelta64(i64::MAX);
15509        let out = nancumsum_with_policy(
15510            &[max.clone(), max.clone(), max.clone()],
15511            OverflowPolicy::Strict,
15512        );
15513        assert_eq!(
15514            out,
15515            vec![
15516                Scalar::Timedelta64(i64::MAX),
15517                Scalar::Timedelta64(-2),
15518                Scalar::Timedelta64(i64::MAX - 2),
15519            ],
15520            "STRICT cumsum must reproduce pandas' int64 wraparound exactly"
15521        );
15522
15523        // NaT still propagates; the wrap is about overflow, not missingness.
15524        assert_eq!(
15525            Timedelta::mul_scalar_with_policy(Timedelta::NAT, 2, OverflowPolicy::Strict),
15526            Timedelta::NAT
15527        );
15528    }
15529
15530    /// The other half of the s4lkx decision, and the reason reproducing a
15531    /// fail-open quirk is acceptable at all: it is reachable ONLY when a caller
15532    /// explicitly asks for STRICT incumbent parity. Every other policy — and
15533    /// crucially the DEFAULT — still refuses to fabricate a plausible value,
15534    /// keeping the br-frankenpandas-lgyy8 guarantee intact.
15535    #[test]
15536    fn non_strict_policies_still_refuse_to_wrap_s4lkx() {
15537        use super::{OverflowPolicy, nancumsum_with_policy, overflow_audit};
15538
15539        for policy in [OverflowPolicy::SurfaceNat, OverflowPolicy::HardenedNat] {
15540            assert_eq!(
15541                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
15542                Timedelta::NAT,
15543                "{policy:?} must NOT wrap"
15544            );
15545            assert_ne!(
15546                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
15547                -2,
15548                "{policy:?} must not reproduce the pandas quirk"
15549            );
15550        }
15551        // The bare default is SurfaceNat, so an unconfigured caller is safe.
15552        assert_eq!(
15553            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::default()),
15554            Timedelta::NAT
15555        );
15556
15557        // cumsum likewise keeps the exact-i128 / NaT behaviour off STRICT.
15558        let max = Scalar::Timedelta64(i64::MAX);
15559        let soft = nancumsum_with_policy(&[max.clone(), max.clone()], OverflowPolicy::SurfaceNat);
15560        assert!(soft[1].is_missing(), "non-STRICT cumsum must NaT, not wrap");
15561        assert_eq!(soft, super::nancumsum(&[max.clone(), max]));
15562
15563        // HARDENED wrapping would be doubly wrong: it would fabricate a value
15564        // AND leave nothing in the audit trail to explain it.
15565        overflow_audit::enable();
15566        let _ = Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::HardenedNat);
15567        assert_eq!(
15568            overflow_audit::drain().len(),
15569            1,
15570            "HARDENED must record the recovery it performed"
15571        );
15572        overflow_audit::disable();
15573    }
15574
15575    /// Mixed Datetime64 + another dtype must NOT take the typed arm — it falls
15576    /// back exactly as before, so this fix cannot change cross-type behavior.
15577    #[test]
15578    fn datetime64_mixed_input_still_falls_back_axhhk() {
15579        let vals = vec![Scalar::Datetime64(DT_2020), Scalar::Int64(5)];
15580        // `is_datetime_input` is false here, so both keep their PRE-EXISTING
15581        // cross-type behavior, which differs between the two by construction:
15582        //   nanmin  — the catch-all compares via to_f64(); the Datetime64 side
15583        //             errors, so it bails to Null(NaN).
15584        //   nanptp  — its f64 loop SKIPS values whose to_f64() errors, so the
15585        //             datetime is dropped and the range is taken over the lone
15586        //             Int64 => Float64(0.0). Same shape as the documented
15587        //             mixed-timedelta fallback in ..._620mj (which yields 5.0).
15588        // Neither is changed by this bead; pinning both stops the new typed arm
15589        // from silently widening to mixed input later.
15590        assert!(super::nanmin(&vals).is_missing());
15591        assert_eq!(super::nanptp(&vals), Scalar::Float64(0.0));
15592    }
15593
15594    #[test]
15595    fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
15596        // Mixed Timedelta64 + other type bails out of the Timedelta path
15597        // and uses Float64 collect_finite (which drops Timedelta).
15598        // Preserves existing cross-type behavior (effectively ignores TD).
15599        let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
15600        // Int64(5) makes it through to_f64 → 5.0; Timedelta is dropped.
15601        assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
15602    }
15603
15604    #[test]
15605    fn nancount_counts_non_missing() {
15606        let vals = vec![
15607            Scalar::Int64(1),
15608            Scalar::Null(NullKind::Null),
15609            Scalar::Float64(3.0),
15610        ];
15611        assert_eq!(super::nancount(&vals), Scalar::Int64(2));
15612    }
15613
15614    #[test]
15615    fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
15616        // Differential vs scalar truthiness/count oracle
15617        // (br-frankenpandas-zr2qg). Seeded LCG, no mocks.
15618        fn next(seed: &mut u64) -> u64 {
15619            *seed = seed
15620                .wrapping_mul(6364136223846793005)
15621                .wrapping_add(1442695040888963407);
15622            *seed
15623        }
15624
15625        fn truthy(value: &Scalar) -> Option<bool> {
15626            if value.is_missing() {
15627                return None;
15628            }
15629            match value {
15630                Scalar::Bool(value) => Some(*value),
15631                Scalar::Int64(value) => Some(*value != 0),
15632                Scalar::Float64(value) => Some(*value != 0.0),
15633                Scalar::Utf8(value) => Some(!value.is_empty()),
15634                Scalar::Timedelta64(value) => Some(*value != 0),
15635                _ => None,
15636            }
15637        }
15638
15639        fn assert_nanops(case: usize, values: &[Scalar]) {
15640            let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
15641            let expected_any = truth_values.iter().any(|value| *value);
15642            let expected_all = !truth_values.iter().any(|value| !*value);
15643            let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
15644
15645            assert_eq!(
15646                super::nanany(values),
15647                Scalar::Bool(expected_any),
15648                "case={case}: nanany mismatch for {values:?}"
15649            );
15650            assert_eq!(
15651                super::nanall(values),
15652                Scalar::Bool(expected_all),
15653                "case={case}: nanall mismatch for {values:?}"
15654            );
15655            assert_eq!(
15656                super::nancount(values),
15657                Scalar::Int64(expected_count),
15658                "case={case}: nancount mismatch for {values:?}"
15659            );
15660        }
15661
15662        assert_nanops(
15663            usize::MAX,
15664            &[
15665                Scalar::Null(NullKind::Null),
15666                Scalar::Null(NullKind::NaN),
15667                Scalar::Float64(f64::NAN),
15668                Scalar::Timedelta64(i64::MIN),
15669            ],
15670        );
15671
15672        let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
15673        for case in 0..320 {
15674            let len = (next(&mut seed) % 89 + 1) as usize;
15675            let mut values = Vec::with_capacity(len);
15676            for pos in 0..len {
15677                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
15678                let value = match next(&mut seed) % 12 {
15679                    0 => Scalar::Null(NullKind::Null),
15680                    1 => Scalar::Null(NullKind::NaN),
15681                    2 => Scalar::Float64(f64::NAN),
15682                    3 => Scalar::Bool(raw & 1 == 0),
15683                    4 => Scalar::Bool(false),
15684                    5 => Scalar::Int64(raw % 17),
15685                    6 => Scalar::Int64(0),
15686                    7 => Scalar::Float64(raw as f64 / 23.0),
15687                    8 => Scalar::Float64(0.0),
15688                    9 => Scalar::Utf8(if raw & 1 == 0 {
15689                        String::new()
15690                    } else {
15691                        format!("nanops_{case}_{pos}")
15692                    }),
15693                    10 => Scalar::Timedelta64(raw),
15694                    _ => Scalar::Timedelta64(0),
15695                };
15696                values.push(value);
15697            }
15698            assert_nanops(case, &values);
15699        }
15700    }
15701
15702    #[test]
15703    fn nanmin_basic() {
15704        let vals = vec![
15705            Scalar::Float64(5.0),
15706            Scalar::Null(NullKind::Null),
15707            Scalar::Float64(2.0),
15708            Scalar::Float64(8.0),
15709        ];
15710        assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
15711    }
15712
15713    #[test]
15714    fn nanmax_basic() {
15715        let vals = vec![
15716            Scalar::Float64(5.0),
15717            Scalar::Float64(f64::NAN),
15718            Scalar::Float64(8.0),
15719        ];
15720        assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
15721    }
15722
15723    #[test]
15724    fn nanmin_nanmax_empty_returns_nan() {
15725        assert!(super::nanmin(&[]).is_missing());
15726        assert!(super::nanmax(&[]).is_missing());
15727    }
15728
15729    #[test]
15730    fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
15731        // Differential vs independent same-family comparator oracle
15732        // (br-frankenpandas-vj7ds). Seeded LCG, no mocks.
15733        fn next(seed: &mut u64) -> u64 {
15734            *seed = seed
15735                .wrapping_mul(6364136223846793005)
15736                .wrapping_add(1442695040888963407);
15737            *seed
15738        }
15739
15740        fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
15741            match (left, right) {
15742                (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
15743                (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
15744                (Scalar::Float64(left), Scalar::Float64(right)) => {
15745                    left.partial_cmp(right).expect("finite floats")
15746                }
15747                (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
15748                (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
15749                // `assert_minmax` verifies that every present value belongs
15750                // to one generated family before it invokes this comparator.
15751                _ => std::cmp::Ordering::Equal,
15752            }
15753        }
15754
15755        fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
15756            let present = values
15757                .iter()
15758                .filter(|value| !value.is_missing())
15759                .cloned()
15760                .collect::<Vec<_>>();
15761            let actual_min = super::nanmin(values);
15762            let actual_max = super::nanmax(values);
15763            if present.is_empty() {
15764                assert!(
15765                    actual_min.is_missing(),
15766                    "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
15767                );
15768                assert!(
15769                    actual_max.is_missing(),
15770                    "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
15771                );
15772                return;
15773            }
15774
15775            let is_expected_family = |value: &Scalar| match family {
15776                "int" => matches!(value, Scalar::Int64(_)),
15777                "float" => matches!(value, Scalar::Float64(_)),
15778                "bool" => matches!(value, Scalar::Bool(_)),
15779                "utf8" => matches!(value, Scalar::Utf8(_)),
15780                "timedelta" => matches!(value, Scalar::Timedelta64(_)),
15781                _ => false,
15782            };
15783            assert!(
15784                present.iter().all(is_expected_family),
15785                "case={case} family={family}: mixed family escaped generator: {values:?}"
15786            );
15787
15788            let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
15789            let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
15790            assert!(
15791                actual_min.semantic_eq(expected_min.expect("min")),
15792                "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
15793                expected_min.expect("min")
15794            );
15795            assert!(
15796                actual_max.semantic_eq(expected_max.expect("max")),
15797                "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
15798                expected_max.expect("max")
15799            );
15800        }
15801
15802        let all_missing = [
15803            Scalar::Null(NullKind::Null),
15804            Scalar::Null(NullKind::NaN),
15805            Scalar::Float64(f64::NAN),
15806            Scalar::Timedelta64(i64::MIN),
15807        ];
15808        assert_minmax(usize::MAX, "all_missing", &all_missing);
15809
15810        let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
15811        for case in 0..240 {
15812            let len = (next(&mut seed) % 73 + 1) as usize;
15813
15814            let mut ints = Vec::with_capacity(len);
15815            ints.push(Scalar::Int64(case as i64 - 120));
15816            for _ in 1..len {
15817                let raw = (next(&mut seed) % 1_001) as i64 - 500;
15818                ints.push(match next(&mut seed) % 6 {
15819                    0 => Scalar::Null(NullKind::Null),
15820                    1 => Scalar::Null(NullKind::NaN),
15821                    _ => Scalar::Int64(raw),
15822                });
15823            }
15824            assert_minmax(case, "int", &ints);
15825
15826            let mut floats = Vec::with_capacity(len);
15827            floats.push(Scalar::Float64(case as f64 / 11.0));
15828            for _ in 1..len {
15829                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15830                floats.push(match next(&mut seed) % 8 {
15831                    0 | 1 => Scalar::Float64(f64::NAN),
15832                    2 => Scalar::Float64(f64::INFINITY),
15833                    3 => Scalar::Float64(f64::NEG_INFINITY),
15834                    4 => Scalar::Float64(0.0),
15835                    5 => Scalar::Float64(-0.0),
15836                    _ => Scalar::Float64(raw as f64 / 41.0),
15837                });
15838            }
15839            assert_minmax(case, "float", &floats);
15840
15841            let mut bools = Vec::with_capacity(len);
15842            bools.push(Scalar::Bool(case & 1 == 0));
15843            for _ in 1..len {
15844                bools.push(match next(&mut seed) % 5 {
15845                    0 => Scalar::Null(NullKind::Null),
15846                    1 => Scalar::Null(NullKind::NaN),
15847                    raw => Scalar::Bool(raw & 1 == 0),
15848                });
15849            }
15850            assert_minmax(case, "bool", &bools);
15851
15852            let mut utf8 = Vec::with_capacity(len);
15853            utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
15854            for pos in 1..len {
15855                utf8.push(match next(&mut seed) % 7 {
15856                    0 => Scalar::Null(NullKind::Null),
15857                    1 => Scalar::Null(NullKind::NaN),
15858                    raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
15859                });
15860            }
15861            assert_minmax(case, "utf8", &utf8);
15862
15863            let mut timedeltas = Vec::with_capacity(len);
15864            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15865            for _ in 1..len {
15866                let raw = (next(&mut seed) % 1_003) as i64 - 501;
15867                timedeltas.push(match next(&mut seed) % 7 {
15868                    0 => Scalar::Null(NullKind::Null),
15869                    1 => Scalar::Timedelta64(i64::MIN),
15870                    _ => Scalar::Timedelta64(raw),
15871                });
15872            }
15873            assert_minmax(case, "timedelta", &timedeltas);
15874        }
15875    }
15876
15877    #[test]
15878    fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
15879        let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
15880        assert!(super::nanmin(&vals).is_missing());
15881        assert!(super::nanmax(&vals).is_missing());
15882
15883        let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
15884        assert!(super::nanmin(&vals2).is_missing());
15885        assert!(super::nanmax(&vals2).is_missing());
15886    }
15887
15888    #[test]
15889    fn nanmin_nanmax_compatible_numeric_types_ok() {
15890        let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
15891        assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
15892        assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
15893    }
15894
15895    #[test]
15896    fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
15897        // Per br-frankenpandas-yic5m: nanmin/nanmax on Timedelta64 returns
15898        // the smallest/largest Timedelta64 — was silently NaN before
15899        // because Timedelta64.to_f64() errors and the catch-all swallowed it.
15900        let one_hour = 3_600 * 1_000_000_000_i64;
15901        let vals = vec![
15902            Scalar::Timedelta64(3 * one_hour),
15903            Scalar::Timedelta64(one_hour),
15904            Scalar::Timedelta64(2 * one_hour),
15905        ];
15906        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15907        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
15908    }
15909
15910    #[test]
15911    fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
15912        let one_hour = 3_600 * 1_000_000_000_i64;
15913        let vals = vec![
15914            Scalar::Timedelta64(Timedelta::NAT),
15915            Scalar::Timedelta64(one_hour),
15916            Scalar::Timedelta64(2 * one_hour),
15917            Scalar::Timedelta64(Timedelta::NAT),
15918        ];
15919        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15920        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
15921    }
15922
15923    #[test]
15924    fn nanmedian_odd_count() {
15925        let vals = vec![
15926            Scalar::Float64(3.0),
15927            Scalar::Null(NullKind::Null),
15928            Scalar::Float64(1.0),
15929            Scalar::Float64(2.0),
15930        ];
15931        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
15932    }
15933
15934    #[test]
15935    fn nanmedian_even_count() {
15936        let vals = vec![
15937            Scalar::Float64(1.0),
15938            Scalar::Float64(3.0),
15939            Scalar::Float64(2.0),
15940            Scalar::Float64(4.0),
15941        ];
15942        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
15943    }
15944
15945    #[test]
15946    fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
15947        // Differential vs independent sort-based median oracles
15948        // (br-frankenpandas-oabhi). Seeded LCG, no mocks.
15949        fn next(seed: &mut u64) -> u64 {
15950            *seed = seed
15951                .wrapping_mul(6364136223846793005)
15952                .wrapping_add(1442695040888963407);
15953            *seed
15954        }
15955
15956        fn expected_numeric(values: &[Scalar]) -> Scalar {
15957            let mut finite = values
15958                .iter()
15959                .filter(|value| !value.is_missing())
15960                .filter_map(|value| value.to_f64().ok())
15961                .filter(|value| !value.is_nan())
15962                .collect::<Vec<_>>();
15963            if finite.is_empty() {
15964                return Scalar::Null(NullKind::NaN);
15965            }
15966            finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
15967            let mid = finite.len() / 2;
15968            if finite.len().is_multiple_of(2) {
15969                Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
15970            } else {
15971                Scalar::Float64(finite[mid])
15972            }
15973        }
15974
15975        fn expected_timedelta(values: &[Scalar]) -> Scalar {
15976            let mut finite = values
15977                .iter()
15978                .filter_map(|value| match value {
15979                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns),
15980                    _ => None,
15981                })
15982                .collect::<Vec<_>>();
15983            if finite.is_empty() {
15984                return Scalar::Null(NullKind::NaN);
15985            }
15986            finite.sort_unstable();
15987            let mid = finite.len() / 2;
15988            let median = if finite.len().is_multiple_of(2) {
15989                (i128::from(finite[mid - 1]) + i128::from(finite[mid])) / 2
15990            } else {
15991                i128::from(finite[mid])
15992            };
15993            Scalar::Timedelta64(median as i64)
15994        }
15995
15996        fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
15997            let actual = super::nanmedian(values);
15998            assert!(
15999                actual.semantic_eq(&expected),
16000                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
16001            );
16002        }
16003
16004        assert_median(
16005            usize::MAX,
16006            "numeric_all_missing",
16007            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
16008            Scalar::Null(NullKind::NaN),
16009        );
16010        assert_median(
16011            usize::MAX - 1,
16012            "timedelta_all_missing",
16013            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
16014            Scalar::Null(NullKind::NaN),
16015        );
16016        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
16017        assert_median(
16018            usize::MAX - 2,
16019            "timedelta_odd_median_beyond_f64_exactness",
16020            &[
16021                Scalar::Timedelta64(beyond_f64_exact_ns),
16022                Scalar::Timedelta64(beyond_f64_exact_ns + 1),
16023                Scalar::Timedelta64(beyond_f64_exact_ns + 2),
16024                Scalar::Timedelta64(Timedelta::NAT),
16025            ],
16026            Scalar::Timedelta64(beyond_f64_exact_ns + 1),
16027        );
16028
16029        let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
16030        for case in 0..220 {
16031            let len = (next(&mut seed) % 79 + 1) as usize;
16032
16033            let mut numeric = Vec::with_capacity(len);
16034            numeric.push(Scalar::Int64(case as i64 - 110));
16035            for _ in 1..len {
16036                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16037                numeric.push(match next(&mut seed) % 8 {
16038                    0 => Scalar::Null(NullKind::Null),
16039                    1 => Scalar::Null(NullKind::NaN),
16040                    2 => Scalar::Float64(f64::NAN),
16041                    3 => Scalar::Bool(raw & 1 == 0),
16042                    4 => Scalar::Int64(raw % 251),
16043                    5 => Scalar::Float64(raw as f64 / 61.0),
16044                    6 => Scalar::Float64(0.0),
16045                    _ => Scalar::Float64(-0.0),
16046                });
16047            }
16048            assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
16049
16050            let mut timedeltas = Vec::with_capacity(len);
16051            timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
16052            for _ in 1..len {
16053                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16054                timedeltas.push(match next(&mut seed) % 7 {
16055                    0 => Scalar::Null(NullKind::Null),
16056                    1 => Scalar::Timedelta64(i64::MIN),
16057                    _ => Scalar::Timedelta64(raw),
16058                });
16059            }
16060            assert_median(
16061                case,
16062                "timedelta",
16063                &timedeltas,
16064                expected_timedelta(&timedeltas),
16065            );
16066        }
16067    }
16068
16069    #[test]
16070    fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
16071        // Differential vs independent variance/std/sem oracles
16072        // (br-frankenpandas-k7apg). Seeded LCG, no mocks.
16073        fn next(seed: &mut u64) -> u64 {
16074            *seed = seed
16075                .wrapping_mul(2862933555777941757)
16076                .wrapping_add(3037000493);
16077            *seed
16078        }
16079
16080        fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
16081            values
16082                .iter()
16083                .filter(|value| !value.is_missing())
16084                .filter_map(|value| value.to_f64().ok())
16085                .collect()
16086        }
16087
16088        fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
16089            values
16090                .iter()
16091                .filter_map(|value| match value {
16092                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
16093                    _ => None,
16094                })
16095                .collect()
16096        }
16097
16098        fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
16099            if samples.len() <= ddof {
16100                return None;
16101            }
16102            let mean = samples.iter().sum::<f64>() / samples.len() as f64;
16103            let sum_sq = samples
16104                .iter()
16105                .map(|value| (value - mean).powi(2))
16106                .sum::<f64>();
16107            let var = sum_sq / (samples.len() - ddof) as f64;
16108            let std = var.sqrt();
16109            let sem = std / (samples.len() as f64).sqrt();
16110            Some((var, std, sem))
16111        }
16112
16113        fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
16114            let samples = numeric_samples(values);
16115            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
16116                let missing = Scalar::Null(NullKind::NaN);
16117                return (missing.clone(), missing.clone(), missing);
16118            };
16119            (
16120                Scalar::Float64(var),
16121                Scalar::Float64(std),
16122                Scalar::Float64(sem),
16123            )
16124        }
16125
16126        fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
16127            let samples = timedelta_samples(values);
16128            if samples.is_empty() {
16129                let missing = Scalar::Timedelta64(Timedelta::NAT);
16130                return (missing.clone(), missing.clone(), missing);
16131            }
16132            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
16133                let missing = Scalar::Timedelta64(i64::MIN);
16134                return (missing.clone(), missing.clone(), missing);
16135            };
16136            (
16137                Scalar::Timedelta64(var as i64),
16138                Scalar::Timedelta64(std as i64),
16139                Scalar::Timedelta64(sem as i64),
16140            )
16141        }
16142
16143        fn assert_reductions(
16144            case: usize,
16145            family: &str,
16146            values: &[Scalar],
16147            ddof: usize,
16148            expected: (Scalar, Scalar, Scalar),
16149        ) {
16150            let (expected_var, expected_std, expected_sem) = expected;
16151            let actual_var = super::nanvar(values, ddof);
16152            let actual_std = super::nanstd(values, ddof);
16153            let actual_sem = super::nansem(values, ddof);
16154            assert!(
16155                actual_var.semantic_eq(&expected_var),
16156                "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
16157            );
16158            assert!(
16159                actual_std.semantic_eq(&expected_std),
16160                "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
16161            );
16162            assert!(
16163                actual_sem.semantic_eq(&expected_sem),
16164                "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
16165            );
16166        }
16167
16168        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16169        assert_reductions(
16170            usize::MAX,
16171            "numeric_all_missing",
16172            &numeric_all_missing,
16173            0,
16174            expected_numeric(&numeric_all_missing, 0),
16175        );
16176
16177        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16178        assert_reductions(
16179            usize::MAX - 1,
16180            "timedelta_all_missing",
16181            &td_all_missing,
16182            0,
16183            expected_timedelta(&td_all_missing, 0),
16184        );
16185
16186        let mut seed = 0x7a11_c0de_5eed_0421_u64;
16187        for case in 0..240 {
16188            let len = (next(&mut seed) % 83 + 1) as usize;
16189            let ddof = (next(&mut seed) % 4) as usize;
16190
16191            let mut numeric = Vec::with_capacity(len);
16192            numeric.push(Scalar::Float64(case as f64 / 13.0));
16193            for _ in 1..len {
16194                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16195                numeric.push(match next(&mut seed) % 8 {
16196                    0 => Scalar::Null(NullKind::Null),
16197                    1 => Scalar::Null(NullKind::NaN),
16198                    2 => Scalar::Float64(f64::NAN),
16199                    3 => Scalar::Bool(raw & 1 == 0),
16200                    4 => Scalar::Int64(raw % 251),
16201                    5 => Scalar::Float64(raw as f64 / 73.0),
16202                    6 => Scalar::Float64(0.0),
16203                    _ => Scalar::Float64(-0.0),
16204                });
16205            }
16206            assert_reductions(
16207                case,
16208                "numeric",
16209                &numeric,
16210                ddof,
16211                expected_numeric(&numeric, ddof),
16212            );
16213
16214            let mut timedeltas = Vec::with_capacity(len);
16215            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
16216            for _ in 1..len {
16217                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16218                timedeltas.push(match next(&mut seed) % 7 {
16219                    0 => Scalar::Null(NullKind::Null),
16220                    1 => Scalar::Timedelta64(i64::MIN),
16221                    _ => Scalar::Timedelta64(raw),
16222                });
16223            }
16224            assert_reductions(
16225                case,
16226                "timedelta",
16227                &timedeltas,
16228                ddof,
16229                expected_timedelta(&timedeltas, ddof),
16230            );
16231        }
16232    }
16233
16234    #[test]
16235    fn nanvar_population() {
16236        let vals = vec![
16237            Scalar::Float64(2.0),
16238            Scalar::Float64(4.0),
16239            Scalar::Float64(4.0),
16240            Scalar::Float64(4.0),
16241            Scalar::Float64(5.0),
16242            Scalar::Float64(5.0),
16243            Scalar::Float64(7.0),
16244            Scalar::Float64(9.0),
16245        ];
16246        let var = super::nanvar(&vals, 0);
16247        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
16248        if let Scalar::Float64(v) = var {
16249            assert!((v - 4.0).abs() < 1e-10);
16250        }
16251    }
16252
16253    #[test]
16254    fn nanvar_sample_ddof1() {
16255        let vals = vec![
16256            Scalar::Float64(2.0),
16257            Scalar::Float64(4.0),
16258            Scalar::Float64(4.0),
16259            Scalar::Float64(4.0),
16260            Scalar::Float64(5.0),
16261            Scalar::Float64(5.0),
16262            Scalar::Float64(7.0),
16263            Scalar::Float64(9.0),
16264        ];
16265        let var = super::nanvar(&vals, 1);
16266        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
16267        if let Scalar::Float64(v) = var {
16268            assert!((v - 32.0 / 7.0).abs() < 1e-10);
16269        }
16270    }
16271
16272    #[test]
16273    fn nanvar_insufficient_values_returns_nan() {
16274        let vals = vec![Scalar::Float64(5.0)];
16275        assert!(super::nanvar(&vals, 1).is_missing());
16276    }
16277
16278    #[test]
16279    fn nanstd_is_sqrt_of_var() {
16280        let vals = vec![
16281            Scalar::Float64(2.0),
16282            Scalar::Float64(4.0),
16283            Scalar::Float64(4.0),
16284            Scalar::Float64(4.0),
16285            Scalar::Float64(5.0),
16286            Scalar::Float64(5.0),
16287            Scalar::Float64(7.0),
16288            Scalar::Float64(9.0),
16289        ];
16290        let std = super::nanstd(&vals, 0);
16291        assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
16292        if let Scalar::Float64(v) = std {
16293            assert!((v - 2.0).abs() < 1e-10);
16294        }
16295    }
16296
16297    #[test]
16298    fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
16299        // Per br-frankenpandas-j8ntk: pandas td_series.median() returns
16300        // Timedelta64; was silently NaN before via collect_finite.
16301        let one_hour = 3_600 * 1_000_000_000_i64;
16302        let vals = vec![
16303            Scalar::Timedelta64(one_hour),
16304            Scalar::Timedelta64(2 * one_hour),
16305            Scalar::Timedelta64(3 * one_hour),
16306        ];
16307        assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
16308    }
16309
16310    #[test]
16311    fn nanstd_timedelta64_preserves_dtype_j8ntk() {
16312        // Per br-frankenpandas-j8ntk: pandas td_series.std() returns
16313        // Timedelta64. Check Timedelta64 output and reasonable magnitude
16314        // for population std of [1h, 2h, 3h] = sqrt(2/3) * 1h.
16315        let one_hour: i64 = 3_600 * 1_000_000_000;
16316        let vals = vec![
16317            Scalar::Timedelta64(one_hour),
16318            Scalar::Timedelta64(2 * one_hour),
16319            Scalar::Timedelta64(3 * one_hour),
16320        ];
16321        let std = super::nanstd(&vals, 0);
16322        assert!(matches!(std, Scalar::Timedelta64(_)));
16323        if let Scalar::Timedelta64(ns) = std {
16324            let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
16325            assert!(
16326                (ns as f64 - expected).abs() < 1e6,
16327                "expected ~{expected} ns, got {ns}"
16328            );
16329        }
16330    }
16331
16332    #[test]
16333    fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
16334        let one_hour = 3_600 * 1_000_000_000_i64;
16335        let vals = vec![Scalar::Timedelta64(one_hour)];
16336        // ddof=1 with n=1 → underflow, returns NaT
16337        assert_eq!(super::nanstd(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
16338        assert_eq!(super::nansem(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
16339    }
16340
16341    #[test]
16342    fn nanops_with_mixed_types() {
16343        let vals = vec![
16344            Scalar::Bool(true),
16345            Scalar::Int64(3),
16346            Scalar::Float64(6.0),
16347            Scalar::Null(NullKind::Null),
16348        ];
16349        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
16350        assert_eq!(super::nancount(&vals), Scalar::Int64(3));
16351    }
16352
16353    #[test]
16354    fn nanops_all_missing_returns_identity() {
16355        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16356        assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
16357        assert!(super::nanmean(&vals).is_missing());
16358        assert!(super::nanmedian(&vals).is_missing());
16359        assert!(super::nanvar(&vals, 0).is_missing());
16360        assert!(super::nanstd(&vals, 0).is_missing());
16361    }
16362
16363    // ── Timedelta tests ────────────────────────────────────────────────
16364
16365    #[test]
16366    fn timedelta_parse_simple_units() {
16367        use super::Timedelta;
16368        assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
16369        assert_eq!(
16370            Timedelta::parse("2h").unwrap(),
16371            2 * Timedelta::NANOS_PER_HOUR
16372        );
16373        assert_eq!(
16374            Timedelta::parse("30m").unwrap(),
16375            30 * Timedelta::NANOS_PER_MIN
16376        );
16377        assert_eq!(
16378            Timedelta::parse("45s").unwrap(),
16379            45 * Timedelta::NANOS_PER_SEC
16380        );
16381        assert_eq!(
16382            Timedelta::parse("100ms").unwrap(),
16383            100 * Timedelta::NANOS_PER_MILLI
16384        );
16385        assert_eq!(
16386            Timedelta::parse("500us").unwrap(),
16387            500 * Timedelta::NANOS_PER_MICRO
16388        );
16389        assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
16390    }
16391
16392    #[test]
16393    fn timedelta_parse_zero_valued_compound() {
16394        use super::Timedelta;
16395        // Each of these is a Timedelta of zero, not a parse failure. Verified
16396        // against live pandas 2.2.3: every form below yields
16397        // `Timedelta('0 days 00:00:00')`. A guard in `parse_compound` used to
16398        // reject them all except the bare "0", which made
16399        // `to_timedelta(["10 seconds", "1 second", "0 seconds"])` raise on the
16400        // third element only.
16401        for s in [
16402            "0 seconds",
16403            "0 second",
16404            "0 sec",
16405            "0s",
16406            "0 days",
16407            "0d",
16408            "0 hours",
16409            "0.0 hours",
16410            "0 minutes",
16411            "0ms",
16412            "0us",
16413            "0ns",
16414            "0",
16415            "0 days 0 seconds",
16416        ] {
16417            assert_eq!(Timedelta::parse(s).unwrap(), 0, "parse({s:?}) should be 0");
16418        }
16419        // The sign is carried by the caller, so a negative zero is still zero.
16420        assert_eq!(Timedelta::parse("-0 seconds").unwrap(), 0);
16421        // Removing the guard must NOT admit garbage: an unknown unit and a
16422        // missing number are still rejected inside the loop.
16423        assert!(Timedelta::parse("0 fortnights").is_err());
16424        assert!(Timedelta::parse("seconds").is_err());
16425    }
16426
16427    #[test]
16428    fn timedelta_parse_compound() {
16429        use super::Timedelta;
16430        let expected = Timedelta::NANOS_PER_DAY
16431            + 2 * Timedelta::NANOS_PER_HOUR
16432            + 30 * Timedelta::NANOS_PER_MIN;
16433        assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
16434        assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
16435    }
16436
16437    #[test]
16438    fn timedelta_parse_leading_sign_spares_the_clock_part() {
16439        use super::Timedelta;
16440        const S: i64 = Timedelta::NANOS_PER_SEC;
16441        // Verified vs pandas 2.2.3 Timedelta(...).total_seconds(); the second
16442        // is how pandas prints a negative Timedelta.
16443        assert_eq!(Timedelta::parse("-1 days 02:03:04").unwrap(), -79_016 * S);
16444        assert_eq!(Timedelta::parse("-1 days +02:03:04").unwrap(), -79_016 * S);
16445        assert_eq!(
16446            Timedelta::parse("-3 days +23:59:59.5").unwrap(),
16447            -172_800 * S - S / 2
16448        );
16449        assert_eq!(Timedelta::parse("-0 days 01:00:00").unwrap(), 3_600 * S);
16450        // Without a clock part after a unit, the whole value is negated.
16451        assert_eq!(Timedelta::parse("-1d2h").unwrap(), -93_600 * S);
16452        assert_eq!(Timedelta::parse("-02:03:04").unwrap(), -7_384 * S);
16453        // A sign inside the string is pandas' "only leading negative signs".
16454        assert!(Timedelta::parse("-1 days -02:03:04").is_err());
16455        assert!(Timedelta::parse("1 days -02:00:00").is_err());
16456    }
16457
16458    #[test]
16459    fn timedelta_parse_iso8601_matches_pandas_tdiso() {
16460        use super::Timedelta;
16461        // Verified vs pandas 2.2.3 Timedelta(...).value.
16462        assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
16463        assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
16464        assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
16465        assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
16466        assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
16467        assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
16468        // pandas quirks: T ignored, M is minutes everywhere, units in any order.
16469        assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
16470        assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
16471        assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
16472        assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
16473        assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
16474        // Rejected like pandas: years, lowercase, bare P/PT.
16475        assert!(Timedelta::parse("P1Y").is_err());
16476        assert!(Timedelta::parse("p1d").is_err());
16477        assert!(Timedelta::parse("P").is_err());
16478        assert!(Timedelta::parse("PT").is_err());
16479    }
16480
16481    #[test]
16482    fn timedelta_parse_time_format() {
16483        use super::Timedelta;
16484        let expected = Timedelta::NANOS_PER_HOUR
16485            + 30 * Timedelta::NANOS_PER_MIN
16486            + 45 * Timedelta::NANOS_PER_SEC;
16487        assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
16488    }
16489
16490    #[test]
16491    fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
16492        use super::{Timedelta, TimedeltaError};
16493        let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
16494            .expect_err("non-ASCII fractional seconds must reject");
16495        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
16496    }
16497
16498    #[test]
16499    fn timedelta_parse_time_format_rejects_overflow_without_panic() {
16500        use super::{Timedelta, TimedeltaError};
16501        let err = Timedelta::parse("9223372036854775807:00")
16502            .expect_err("oversized hour component must reject");
16503        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
16504    }
16505
16506    #[test]
16507    fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
16508        // Per br-frankenpandas-zw3mg: the compound parser used a raw
16509        // `as i64` cast that silently saturated to i64::MAX when the
16510        // product of (decimal-digit f64) × unit multiplier overflows.
16511        // Use a large literal (no scientific notation — the lexer only
16512        // accepts digits, '.', '-'). 1e18 days × NANOS_PER_DAY (~8.64e13)
16513        // overflows i64.
16514        use super::{Timedelta, TimedeltaError};
16515        let huge = format!("{} days", "9".repeat(18));
16516        assert!(matches!(
16517            Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
16518            TimedeltaError::Overflow
16519        ));
16520    }
16521
16522    #[test]
16523    fn timedelta_parse_nat() {
16524        use super::Timedelta;
16525        assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
16526        assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
16527    }
16528
16529    #[test]
16530    fn timedelta_parse_negative() {
16531        use super::Timedelta;
16532        assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
16533    }
16534
16535    #[test]
16536    fn timedelta_components() {
16537        use super::Timedelta;
16538        let nanos = Timedelta::NANOS_PER_DAY
16539            + Timedelta::NANOS_PER_HOUR
16540            + Timedelta::NANOS_PER_MIN
16541            + Timedelta::NANOS_PER_SEC
16542            + Timedelta::NANOS_PER_MILLI
16543            + 2 * Timedelta::NANOS_PER_MICRO
16544            + 3;
16545        let comp = Timedelta::components(nanos);
16546        assert_eq!(comp.days, 1);
16547        assert_eq!(comp.hours, 1);
16548        assert_eq!(comp.minutes, 1);
16549        assert_eq!(comp.seconds, 1);
16550        assert_eq!(comp.milliseconds, 1);
16551        assert_eq!(comp.microseconds, 2);
16552        assert_eq!(comp.nanoseconds, 3);
16553    }
16554
16555    #[test]
16556    fn timedelta_negative_components_floor_div() {
16557        use super::Timedelta;
16558        // pandas floor-normalizes negative timedeltas: pd.Timedelta(-1,'s') has
16559        // days=-1, seconds=86399, components=(-1, 23, 59, 59, 0, 0, 0).
16560        let neg_1s = -Timedelta::NANOS_PER_SEC;
16561        assert_eq!(Timedelta::days(neg_1s), Some(-1));
16562        assert_eq!(Timedelta::seconds(neg_1s), Some(86399));
16563        assert_eq!(Timedelta::microseconds(neg_1s), Some(0));
16564        assert_eq!(Timedelta::nanoseconds(neg_1s), Some(0));
16565        let comp = Timedelta::components(neg_1s);
16566        assert_eq!(
16567            (
16568                comp.days,
16569                comp.hours,
16570                comp.minutes,
16571                comp.seconds,
16572                comp.milliseconds,
16573                comp.microseconds,
16574                comp.nanoseconds
16575            ),
16576            (-1, 23, 59, 59, 0, 0, 0)
16577        );
16578
16579        // pd.Timedelta(-86401,'s'): days=-2, seconds=86399.
16580        let neg = -86_401 * Timedelta::NANOS_PER_SEC;
16581        assert_eq!(Timedelta::days(neg), Some(-2));
16582        assert_eq!(Timedelta::seconds(neg), Some(86399));
16583    }
16584
16585    /// br-frankenpandas-timedelta-nat-days-returns-zero-406ni.
16586    ///
16587    /// All four component helpers returned `0` for `NaT`, one of them behind a
16588    /// comment asserting "pandas returns 0 for NaT.days (no error)". MEASURED,
16589    /// live pandas 2.2.3: `pd.NaT.days` is **nan**, and
16590    /// `pd.to_timedelta([1, None, -1], unit='s').dt.days` is float64
16591    /// `[0.0, nan, -1.0]`.
16592    ///
16593    /// ⚠️ `0` IS THE ONE WRONG ANSWER THAT LOOKS RIGHT. It is a legal value for
16594    /// three of these four accessors — `seconds`, `microseconds` and
16595    /// `nanoseconds` all legitimately return 0 for a whole number of days — so a
16596    /// caller cannot distinguish "midnight" from "missing" by inspecting the
16597    /// result. That is the fail-open-as-plausible-data class, and it is why the
16598    /// fix is the return TYPE and not a corrected comment.
16599    #[test]
16600    fn timedelta_components_are_missing_for_nat_not_zero_406ni() {
16601        use super::Timedelta;
16602        assert_eq!(Timedelta::days(Timedelta::NAT), None);
16603        assert_eq!(Timedelta::seconds(Timedelta::NAT), None);
16604        assert_eq!(Timedelta::microseconds(Timedelta::NAT), None);
16605        assert_eq!(Timedelta::nanoseconds(Timedelta::NAT), None);
16606
16607        // NON-VACUITY: a whole number of days legitimately answers 0 for the
16608        // three sub-day components, so `Some(0)` and `None` must be reachable
16609        // from the same accessor. A test that only checked NaT could pass
16610        // against a helper that returned `None` unconditionally.
16611        let one_day = Timedelta::NANOS_PER_DAY;
16612        assert_eq!(Timedelta::days(one_day), Some(1));
16613        assert_eq!(Timedelta::seconds(one_day), Some(0));
16614        assert_eq!(Timedelta::microseconds(one_day), Some(0));
16615        assert_eq!(Timedelta::nanoseconds(one_day), Some(0));
16616    }
16617
16618    #[test]
16619    fn timedelta_total_seconds() {
16620        use super::Timedelta;
16621        let nanos = 90_000_000_000i64; // 90 seconds
16622        assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
16623        assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
16624    }
16625
16626    #[test]
16627    fn timedelta_format_basic() {
16628        use super::Timedelta;
16629        assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
16630        assert_eq!(
16631            Timedelta::format(Timedelta::NANOS_PER_DAY),
16632            "1 days 00:00:00"
16633        );
16634        assert_eq!(
16635            Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
16636            "1 days 02:00:00"
16637        );
16638    }
16639
16640    #[test]
16641    fn timedelta_format_subsecond_matches_pandas() {
16642        use super::Timedelta;
16643        // pandas str(Timedelta) uses 6 fractional digits (microseconds) unless a
16644        // sub-microsecond (nanosecond) component is present, then 9 digits.
16645        // Verified vs live pandas 2.2.3.
16646        assert_eq!(
16647            Timedelta::format(1_500_000_000), // 1.5s
16648            "0 days 00:00:01.500000"
16649        );
16650        assert_eq!(
16651            Timedelta::format(1_000_000), // 1ms
16652            "0 days 00:00:00.001000"
16653        );
16654        assert_eq!(
16655            Timedelta::format(123_456_000), // 123456us
16656            "0 days 00:00:00.123456"
16657        );
16658        // Nanosecond component -> 9 digits.
16659        assert_eq!(
16660            Timedelta::format(500), // 500ns
16661            "0 days 00:00:00.000000500"
16662        );
16663        assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
16664    }
16665
16666    #[test]
16667    fn timedelta_format_negative_uses_python_borrow_form() {
16668        use super::Timedelta;
16669        // pandas/Python normalize negatives via floor division: the days count
16670        // goes negative, the time remainder stays non-negative, and a '+' joins
16671        // them. Verified vs live pandas 2.2.3.
16672        assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
16673        assert_eq!(
16674            Timedelta::format(-Timedelta::NANOS_PER_DAY),
16675            "-1 days +00:00:00"
16676        );
16677        assert_eq!(
16678            Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
16679            "-2 days +23:00:00"
16680        );
16681        assert_eq!(
16682            Timedelta::format(-1_500_000_000),
16683            "-1 days +23:59:58.500000"
16684        );
16685        assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
16686        assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
16687    }
16688
16689    #[test]
16690    #[ignore = "foreground release attribution harness"]
16691    fn timedelta_format_single_buffer_ab_5ro9h() {
16692        use std::{hint::black_box, time::Instant};
16693
16694        use super::Timedelta;
16695
16696        fn former(nanos: i64) -> String {
16697            if nanos == Timedelta::NAT {
16698                return "NaT".to_string();
16699            }
16700
16701            let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
16702            let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
16703            let hours = rem / Timedelta::NANOS_PER_HOUR;
16704            let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
16705            let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
16706            let frac = rem % Timedelta::NANOS_PER_SEC;
16707
16708            let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
16709            let sep = if days < 0 { "+" } else { "" };
16710            if frac > 0 {
16711                if frac % 1_000 == 0 {
16712                    format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
16713                } else {
16714                    format!("{days} days {sep}{time_part}.{frac:09}")
16715                }
16716            } else {
16717                format!("{days} days {sep}{time_part}")
16718            }
16719        }
16720
16721        fn candidate(nanos: i64) -> String {
16722            Timedelta::format(nanos)
16723        }
16724
16725        fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
16726            let started = Instant::now();
16727            let mut digest = 0_usize;
16728            for &value in values {
16729                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
16730            }
16731            black_box(digest);
16732            started.elapsed().as_nanos()
16733        }
16734
16735        fn median(samples: &mut [u128]) -> u128 {
16736            samples.sort_unstable();
16737            samples[samples.len() / 2]
16738        }
16739
16740        let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
16741        let values: Vec<i64> = (0..16_384)
16742            .map(|i| {
16743                seed = seed
16744                    .wrapping_mul(6_364_136_223_846_793_005)
16745                    .wrapping_add(1_442_695_040_888_963_407);
16746                let magnitude = (seed & i64::MAX as u64) as i64;
16747                match i % 4 {
16748                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16749                    1 => magnitude,
16750                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16751                    _ => -magnitude,
16752                }
16753            })
16754            .collect();
16755
16756        for &value in &[
16757            Timedelta::NAT,
16758            0,
16759            1,
16760            -1,
16761            Timedelta::NANOS_PER_DAY,
16762            -Timedelta::NANOS_PER_DAY,
16763            i64::MAX,
16764            i64::MIN + 1,
16765        ] {
16766            assert_eq!(former(value), candidate(value));
16767        }
16768        for &value in &values {
16769            assert_eq!(former(value), candidate(value));
16770        }
16771
16772        for _ in 0..2 {
16773            black_box(elapsed(&values, former));
16774            black_box(elapsed(&values, candidate));
16775        }
16776
16777        let mut former_samples = Vec::with_capacity(18);
16778        let mut candidate_samples = Vec::with_capacity(18);
16779        for block in 0_usize..9 {
16780            if block.is_multiple_of(2) {
16781                former_samples.push(elapsed(&values, former));
16782                candidate_samples.push(elapsed(&values, candidate));
16783                candidate_samples.push(elapsed(&values, candidate));
16784                former_samples.push(elapsed(&values, former));
16785            } else {
16786                candidate_samples.push(elapsed(&values, candidate));
16787                former_samples.push(elapsed(&values, former));
16788                former_samples.push(elapsed(&values, former));
16789                candidate_samples.push(elapsed(&values, candidate));
16790            }
16791        }
16792
16793        let former_p50 = median(&mut former_samples);
16794        let candidate_p50 = median(&mut candidate_samples);
16795        eprintln!(
16796            "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
16797            values.len(),
16798            former_p50 as f64 / candidate_p50 as f64,
16799        );
16800        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
16801        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
16802    }
16803
16804    #[test]
16805    fn timedelta_isoformat_basic() {
16806        use super::Timedelta;
16807        assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
16808        assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
16809        assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
16810        assert_eq!(
16811            Timedelta::isoformat(
16812                Timedelta::NANOS_PER_DAY
16813                    + 2 * Timedelta::NANOS_PER_HOUR
16814                    + 30 * Timedelta::NANOS_PER_MIN
16815                    + 45 * Timedelta::NANOS_PER_SEC
16816            ),
16817            "P1DT2H30M45S"
16818        );
16819        assert_eq!(
16820            Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
16821            "P0DT0H0M1.5S"
16822        );
16823        // TEST-CHANGE (fvsao.68): this pinned "-P1DT1H0M0S"; pandas 2.2.3's
16824        // pd.Timedelta(-90000000000000).isoformat() is "P-2DT23H0M0S" (whole
16825        // days rounded down, then a non-negative clock), and -1ns is
16826        // "P-1DT23H59M59.999999999S" (both measured live).
16827        assert_eq!(
16828            Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
16829            "P-2DT23H0M0S"
16830        );
16831        assert_eq!(Timedelta::isoformat(-1), "P-1DT23H59M59.999999999S");
16832    }
16833
16834    #[test]
16835    #[ignore = "foreground release attribution harness"]
16836    fn timedelta_isoformat_single_buffer_ab_7jra1() {
16837        use std::{hint::black_box, time::Instant};
16838
16839        use super::Timedelta;
16840
16841        fn former_impl(nanos: i64) -> String {
16842            if nanos == Timedelta::NAT {
16843                return "NaT".to_string();
16844            }
16845
16846            let negative = nanos < 0;
16847            let abs_nanos = nanos.saturating_abs();
16848            let days = abs_nanos / Timedelta::NANOS_PER_DAY;
16849            let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
16850            let hours = remaining / Timedelta::NANOS_PER_HOUR;
16851            let remaining = remaining % Timedelta::NANOS_PER_HOUR;
16852            let minutes = remaining / Timedelta::NANOS_PER_MIN;
16853            let remaining = remaining % Timedelta::NANOS_PER_MIN;
16854            let seconds = remaining / Timedelta::NANOS_PER_SEC;
16855            let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
16856
16857            let mut result = String::new();
16858            if negative {
16859                result.push('-');
16860            }
16861
16862            result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
16863
16864            if sub_sec_nanos == 0 {
16865                result.push_str(&format!("{seconds}S"));
16866            } else {
16867                let frac = format!("{sub_sec_nanos:09}");
16868                let trimmed = frac.trim_end_matches('0');
16869                result.push_str(&format!("{seconds}.{trimmed}S"));
16870            }
16871
16872            result
16873        }
16874
16875        fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
16876            let start = Instant::now();
16877            let mut digest = 0_usize;
16878            for &value in values {
16879                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
16880            }
16881            black_box(digest);
16882            start.elapsed().as_nanos()
16883        }
16884
16885        fn median(values: &mut [u128]) -> u128 {
16886            values.sort_unstable();
16887            values[values.len() / 2]
16888        }
16889
16890        let mut seed = 0x7d5a_4c31_91e2_b607_u64;
16891        let values: Vec<i64> = (0..16_384)
16892            .map(|i| {
16893                seed = seed
16894                    .wrapping_mul(6_364_136_223_846_793_005)
16895                    .wrapping_add(1_442_695_040_888_963_407);
16896                let magnitude =
16897                    (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
16898                match i % 4 {
16899                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16900                    1 => magnitude,
16901                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16902                    _ => -magnitude,
16903                }
16904            })
16905            .collect();
16906
16907        // The former implementation wrote a negative duration "-P..."; since
16908        // fvsao.68 it is pandas' "P-..." form, so the two agree on
16909        // non-negative durations only (the timing still covers both signs).
16910        for &value in &[Timedelta::NAT, 0, 1, Timedelta::NANOS_PER_DAY, i64::MAX] {
16911            assert_eq!(former_impl(value), Timedelta::isoformat(value));
16912        }
16913        for &value in values.iter().filter(|value| **value >= 0) {
16914            assert_eq!(former_impl(value), Timedelta::isoformat(value));
16915        }
16916
16917        for _ in 0..2 {
16918            black_box(elapsed(&values, former_impl));
16919            black_box(elapsed(&values, Timedelta::isoformat));
16920        }
16921
16922        let mut former = Vec::with_capacity(18);
16923        let mut candidate = Vec::with_capacity(18);
16924        for block in 0..9 {
16925            if block % 2 == 0 {
16926                former.push(elapsed(&values, former_impl));
16927                candidate.push(elapsed(&values, Timedelta::isoformat));
16928                candidate.push(elapsed(&values, Timedelta::isoformat));
16929                former.push(elapsed(&values, former_impl));
16930            } else {
16931                candidate.push(elapsed(&values, Timedelta::isoformat));
16932                former.push(elapsed(&values, former_impl));
16933                former.push(elapsed(&values, former_impl));
16934                candidate.push(elapsed(&values, Timedelta::isoformat));
16935            }
16936        }
16937
16938        let former_p50 = median(&mut former);
16939        let candidate_p50 = median(&mut candidate);
16940        eprintln!(
16941            "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
16942            values.len(),
16943            former_p50,
16944            candidate_p50,
16945            former_p50 as f64 / candidate_p50 as f64,
16946            former_p50 as f64 / values.len() as f64,
16947            candidate_p50 as f64 / values.len() as f64,
16948        );
16949        eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
16950        eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
16951    }
16952
16953    #[test]
16954    fn timedelta_floor_ceil_round() {
16955        use super::Timedelta;
16956        let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
16957
16958        // floor: rounds down
16959        assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
16960        assert_eq!(Timedelta::floor(nanos, "d"), 0);
16961
16962        // ceil: rounds up
16963        assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16964        assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
16965
16966        // round: rounds to nearest (banker's rounding on tie)
16967        assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16968
16969        // NaT preserved
16970        assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
16971        assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
16972        assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
16973
16974        // Invalid freq returns NAT
16975        assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
16976    }
16977
16978    #[test]
16979    fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
16980        use super::Timedelta;
16981
16982        assert_eq!(
16983            Timedelta::floor(-1, "s"),
16984            -Timedelta::NANOS_PER_SEC,
16985            "floor(-1ns, 1s)"
16986        );
16987        assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
16988        assert_eq!(
16989            Timedelta::floor(-1_500_000_000, "s"),
16990            -2 * Timedelta::NANOS_PER_SEC
16991        );
16992        assert_eq!(
16993            Timedelta::ceil(-1_500_000_000, "s"),
16994            -Timedelta::NANOS_PER_SEC
16995        );
16996        assert_eq!(
16997            Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
16998            -Timedelta::NANOS_PER_SEC
16999        );
17000        assert_eq!(
17001            Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
17002            -Timedelta::NANOS_PER_SEC
17003        );
17004        assert_eq!(
17005            Timedelta::floor(1_500_000_000, "s"),
17006            Timedelta::NANOS_PER_SEC
17007        );
17008        assert_eq!(
17009            Timedelta::ceil(1_500_000_000, "s"),
17010            2 * Timedelta::NANOS_PER_SEC
17011        );
17012    }
17013
17014    #[test]
17015    fn timedelta_scalar_dtype() {
17016        let td = Scalar::Timedelta64(86_400_000_000_000);
17017        assert_eq!(td.dtype(), DType::Timedelta64);
17018    }
17019
17020    #[test]
17021    fn timedelta_scalar_is_missing() {
17022        use super::Timedelta;
17023        let valid = Scalar::Timedelta64(1000);
17024        let nat = Scalar::Timedelta64(Timedelta::NAT);
17025        assert!(!valid.is_missing());
17026        assert!(nat.is_missing());
17027    }
17028
17029    #[test]
17030    fn dtype_utf8_deserializes_legacy_aliases() {
17031        let dtype: DType = serde_json::from_str("\"str\"").unwrap();
17032        assert_eq!(dtype, DType::Utf8);
17033
17034        let dtype: DType = serde_json::from_str("\"string\"").unwrap();
17035        assert_eq!(dtype, DType::Utf8);
17036    }
17037
17038    #[test]
17039    fn datetime64_dtype_carries_timezone_00ze3() {
17040        let naive = DType::datetime64_naive();
17041        assert_eq!(naive.timezone(), None);
17042        assert_eq!(naive.display_name(), "datetime64[ns]");
17043
17044        let aware = DType::datetime64_tz("America/New_York");
17045        assert_eq!(aware.timezone(), Some("America/New_York"));
17046        assert_eq!(aware.display_name(), "datetime64[ns, America/New_York]");
17047        assert_ne!(aware, naive, "timezone must participate in dtype identity");
17048
17049        let json = serde_json::to_string(&aware).expect("serialize timezone dtype");
17050        assert_eq!(
17051            serde_json::from_str::<DType>(&json).expect("deserialize timezone dtype"),
17052            aware
17053        );
17054    }
17055
17056    #[test]
17057    fn scalar_utf8_deserializes_legacy_aliases() {
17058        let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
17059        assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
17060
17061        let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
17062        assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
17063    }
17064
17065    #[test]
17066    fn nancumsum_skips_nulls_and_accumulates() {
17067        let values = vec![
17068            Scalar::Float64(1.0),
17069            Scalar::Null(NullKind::NaN),
17070            Scalar::Float64(2.0),
17071            Scalar::Float64(3.0),
17072        ];
17073        let out = super::nancumsum(&values);
17074        assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
17075        assert!(out[1].is_missing());
17076        assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
17077        assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
17078    }
17079
17080    #[test]
17081    fn nancumprod_skips_nulls_and_multiplies() {
17082        let values = vec![
17083            Scalar::Float64(2.0),
17084            Scalar::Null(NullKind::NaN),
17085            Scalar::Float64(3.0),
17086            Scalar::Float64(4.0),
17087        ];
17088        let out = super::nancumprod(&values);
17089        assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17090        assert!(out[1].is_missing());
17091        assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
17092        assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
17093    }
17094
17095    #[test]
17096    fn nancummax_tracks_running_max() {
17097        let values = vec![
17098            Scalar::Float64(1.0),
17099            Scalar::Float64(3.0),
17100            Scalar::Null(NullKind::NaN),
17101            Scalar::Float64(2.0),
17102            Scalar::Float64(5.0),
17103        ];
17104        let out = super::nancummax(&values);
17105        assert_eq!(out[0], Scalar::Float64(1.0));
17106        assert_eq!(out[1], Scalar::Float64(3.0));
17107        assert!(out[2].is_missing());
17108        assert_eq!(out[3], Scalar::Float64(3.0));
17109        assert_eq!(out[4], Scalar::Float64(5.0));
17110    }
17111
17112    #[test]
17113    fn nancummin_tracks_running_min() {
17114        let values = vec![
17115            Scalar::Float64(5.0),
17116            Scalar::Float64(3.0),
17117            Scalar::Null(NullKind::NaN),
17118            Scalar::Float64(4.0),
17119            Scalar::Float64(1.0),
17120        ];
17121        let out = super::nancummin(&values);
17122        assert_eq!(out[0], Scalar::Float64(5.0));
17123        assert_eq!(out[1], Scalar::Float64(3.0));
17124        assert!(out[2].is_missing());
17125        assert_eq!(out[3], Scalar::Float64(3.0));
17126        assert_eq!(out[4], Scalar::Float64(1.0));
17127    }
17128
17129    #[test]
17130    fn nancumsum_timedelta64_preserves_dtype_x0x91() {
17131        // Per br-frankenpandas-x0x91: pandas td_series.cumsum() returns
17132        // Timedelta64 running sums. Was silently NaN before.
17133        let one_hour = 3_600 * 1_000_000_000_i64;
17134        let values = vec![
17135            Scalar::Timedelta64(one_hour),
17136            Scalar::Timedelta64(2 * one_hour),
17137            Scalar::Timedelta64(3 * one_hour),
17138        ];
17139        let out = super::nancumsum(&values);
17140        assert_eq!(out[0], Scalar::Timedelta64(one_hour));
17141        assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
17142        assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
17143    }
17144
17145    #[test]
17146    fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
17147        let one_hour = 3_600 * 1_000_000_000_i64;
17148        let values = vec![
17149            Scalar::Timedelta64(2 * one_hour),
17150            Scalar::Timedelta64(5 * one_hour),
17151            Scalar::Timedelta64(one_hour),
17152            Scalar::Timedelta64(3 * one_hour),
17153        ];
17154        let mx = super::nancummax(&values);
17155        assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
17156        assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
17157        assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
17158        assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
17159
17160        let mn = super::nancummin(&values);
17161        assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
17162        assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
17163        assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
17164        assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
17165    }
17166
17167    #[test]
17168    fn nancumulative_timedelta64_skips_nat_x0x91() {
17169        let one_hour = 3_600 * 1_000_000_000_i64;
17170        let values = vec![
17171            Scalar::Timedelta64(one_hour),
17172            Scalar::Timedelta64(Timedelta::NAT),
17173            Scalar::Timedelta64(2 * one_hour),
17174        ];
17175        let cs = super::nancumsum(&values);
17176        assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
17177        assert!(cs[1].is_missing());
17178        assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
17179    }
17180
17181    #[test]
17182    fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
17183        // Differential vs independent cumulative nanops oracles
17184        // (br-frankenpandas-k63oz). Seeded LCG, no mocks.
17185        fn next(seed: &mut u64) -> u64 {
17186            *seed = seed
17187                .wrapping_mul(3202034522624059733)
17188                .wrapping_add(4354685564936845319);
17189            *seed
17190        }
17191
17192        fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
17193            assert_eq!(
17194                actual.len(),
17195                expected.len(),
17196                "case={case} family={family} op={op}: length mismatch"
17197            );
17198            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
17199                assert!(
17200                    actual.semantic_eq(expected),
17201                    "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
17202                );
17203            }
17204        }
17205
17206        fn expected_numeric(
17207            values: &[Scalar],
17208        ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
17209            let mut sum = Vec::with_capacity(values.len());
17210            let mut prod = Vec::with_capacity(values.len());
17211            let mut max = Vec::with_capacity(values.len());
17212            let mut min = Vec::with_capacity(values.len());
17213            let mut running_sum = 0.0_f64;
17214            let mut running_prod = 1.0_f64;
17215            let mut running_max: Option<f64> = None;
17216            let mut running_min: Option<f64> = None;
17217
17218            for value in values {
17219                if value.is_missing() {
17220                    sum.push(Scalar::Null(NullKind::NaN));
17221                    prod.push(Scalar::Null(NullKind::NaN));
17222                    max.push(Scalar::Null(NullKind::NaN));
17223                    min.push(Scalar::Null(NullKind::NaN));
17224                    continue;
17225                }
17226                let Ok(value) = value.to_f64() else {
17227                    sum.push(Scalar::Null(NullKind::NaN));
17228                    prod.push(Scalar::Null(NullKind::NaN));
17229                    max.push(Scalar::Null(NullKind::NaN));
17230                    min.push(Scalar::Null(NullKind::NaN));
17231                    continue;
17232                };
17233                if value.is_nan() {
17234                    sum.push(Scalar::Null(NullKind::NaN));
17235                    prod.push(Scalar::Null(NullKind::NaN));
17236                    max.push(Scalar::Null(NullKind::NaN));
17237                    min.push(Scalar::Null(NullKind::NaN));
17238                    continue;
17239                }
17240                running_sum += value;
17241                running_prod *= value;
17242                running_max = Some(running_max.map_or(value, |current| current.max(value)));
17243                running_min = Some(running_min.map_or(value, |current| current.min(value)));
17244                sum.push(Scalar::Float64(running_sum));
17245                prod.push(Scalar::Float64(running_prod));
17246                max.push(Scalar::Float64(running_max.expect("initialized")));
17247                min.push(Scalar::Float64(running_min.expect("initialized")));
17248            }
17249
17250            (sum, prod, max, min)
17251        }
17252
17253        fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
17254            let mut sum = Vec::with_capacity(values.len());
17255            let mut max = Vec::with_capacity(values.len());
17256            let mut min = Vec::with_capacity(values.len());
17257            let mut running_sum = 0_i128;
17258            let mut running_max: Option<i64> = None;
17259            let mut running_min: Option<i64> = None;
17260
17261            for value in values {
17262                if value.is_missing() {
17263                    sum.push(Scalar::Null(NullKind::NaT));
17264                    max.push(Scalar::Null(NullKind::NaT));
17265                    min.push(Scalar::Null(NullKind::NaT));
17266                    continue;
17267                }
17268                let Scalar::Timedelta64(ns) = value else {
17269                    sum.push(Scalar::Null(NullKind::NaT));
17270                    max.push(Scalar::Null(NullKind::NaT));
17271                    min.push(Scalar::Null(NullKind::NaT));
17272                    continue;
17273                };
17274                running_sum = running_sum.saturating_add(i128::from(*ns));
17275                running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
17276                running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
17277                // br-frankenpandas-opz27: mirror the production contract (NaT
17278                // outside the representable range), not the old clamp.
17279                sum.push(super::timedelta_ns_to_scalar(running_sum));
17280                max.push(Scalar::Timedelta64(running_max.expect("initialized")));
17281                min.push(Scalar::Timedelta64(running_min.expect("initialized")));
17282            }
17283
17284            (sum, max, min)
17285        }
17286
17287        let mut seed = 0xc0de_c63a_5eed_0421_u64;
17288        for case in 0..260 {
17289            let len = (next(&mut seed) % 89 + 1) as usize;
17290
17291            let mut numeric = Vec::with_capacity(len);
17292            numeric.push(Scalar::Int64(case as i64 - 130));
17293            for _ in 1..len {
17294                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17295                numeric.push(match next(&mut seed) % 8 {
17296                    0 => Scalar::Null(NullKind::Null),
17297                    1 => Scalar::Null(NullKind::NaN),
17298                    2 => Scalar::Float64(f64::NAN),
17299                    3 => Scalar::Bool(raw & 1 == 0),
17300                    4 => Scalar::Int64(raw % 251),
17301                    5 => Scalar::Float64(raw as f64 / 79.0),
17302                    6 => Scalar::Float64(0.0),
17303                    _ => Scalar::Float64(-0.0),
17304                });
17305            }
17306            let (sum, prod, max, min) = expected_numeric(&numeric);
17307            assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
17308            assert_vec(
17309                case,
17310                "numeric",
17311                "cumprod",
17312                &super::nancumprod(&numeric),
17313                &prod,
17314            );
17315            assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
17316            assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
17317
17318            let mut timedeltas = Vec::with_capacity(len);
17319            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17320            for _ in 1..len {
17321                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17322                timedeltas.push(match next(&mut seed) % 7 {
17323                    0 => Scalar::Null(NullKind::Null),
17324                    1 => Scalar::Timedelta64(i64::MIN),
17325                    _ => Scalar::Timedelta64(raw),
17326                });
17327            }
17328            let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
17329            assert_vec(
17330                case,
17331                "timedelta",
17332                "cumsum",
17333                &super::nancumsum(&timedeltas),
17334                &td_sum,
17335            );
17336            assert_vec(
17337                case,
17338                "timedelta",
17339                "cummax",
17340                &super::nancummax(&timedeltas),
17341                &td_max,
17342            );
17343            assert_vec(
17344                case,
17345                "timedelta",
17346                "cummin",
17347                &super::nancummin(&timedeltas),
17348                &td_min,
17349            );
17350        }
17351    }
17352
17353    #[test]
17354    fn nanquantile_linear_interpolation_matches_numpy() {
17355        let values = vec![
17356            Scalar::Float64(1.0),
17357            Scalar::Float64(2.0),
17358            Scalar::Float64(3.0),
17359            Scalar::Float64(4.0),
17360            Scalar::Float64(5.0),
17361        ];
17362        // median
17363        let q = super::nanquantile(&values, 0.5);
17364        assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
17365        // 25th percentile: interpolate between 2.0 and 3.0 at pos 1.0 → 2.0
17366        let q25 = super::nanquantile(&values, 0.25);
17367        assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17368    }
17369
17370    #[test]
17371    fn nanquantile_ignores_nulls() {
17372        let values = vec![
17373            Scalar::Float64(1.0),
17374            Scalar::Null(NullKind::NaN),
17375            Scalar::Float64(3.0),
17376        ];
17377        let q = super::nanquantile(&values, 0.5);
17378        assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17379    }
17380
17381    #[test]
17382    fn nanquantile_empty_and_out_of_range_yield_null() {
17383        assert!(super::nanquantile(&[], 0.5).is_missing());
17384        assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
17385        assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
17386    }
17387
17388    #[test]
17389    fn nanquantile_timedelta64_preserves_dtype_5djk7() {
17390        // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
17391        // Timedelta64 — was silently NaN before via collect_finite.
17392        let one_hour: i64 = 3_600 * 1_000_000_000;
17393        let vals = vec![
17394            Scalar::Timedelta64(one_hour),
17395            Scalar::Timedelta64(2 * one_hour),
17396            Scalar::Timedelta64(3 * one_hour),
17397            Scalar::Timedelta64(4 * one_hour),
17398            Scalar::Timedelta64(5 * one_hour),
17399        ];
17400        assert_eq!(
17401            super::nanquantile(&vals, 0.5),
17402            Scalar::Timedelta64(3 * one_hour)
17403        );
17404        assert_eq!(
17405            super::nanquantile(&vals, 0.0),
17406            Scalar::Timedelta64(one_hour)
17407        );
17408        assert_eq!(
17409            super::nanquantile(&vals, 1.0),
17410            Scalar::Timedelta64(5 * one_hour)
17411        );
17412    }
17413
17414    #[test]
17415    fn nanquantile_timedelta64_linear_interpolation_5djk7() {
17416        let one_hour: i64 = 3_600 * 1_000_000_000;
17417        let vals = vec![
17418            Scalar::Timedelta64(one_hour),
17419            Scalar::Timedelta64(3 * one_hour),
17420        ];
17421        // Linear interpolation: at q=0.5, midpoint = 2h
17422        assert_eq!(
17423            super::nanquantile(&vals, 0.5),
17424            Scalar::Timedelta64(2 * one_hour)
17425        );
17426    }
17427
17428    #[test]
17429    fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
17430        // Differential vs independent sort-based quantile oracles
17431        // (br-frankenpandas-ecb7r). Seeded LCG, no mocks.
17432        fn next(seed: &mut u64) -> u64 {
17433            *seed = seed
17434                .wrapping_mul(3202034522624059733)
17435                .wrapping_add(4354685564936845319);
17436            *seed
17437        }
17438
17439        fn interpolated(sorted: &[f64], q: f64) -> f64 {
17440            if sorted.len() == 1 {
17441                return sorted[0];
17442            }
17443            let pos = q * (sorted.len() - 1) as f64;
17444            let lo = pos.floor() as usize;
17445            let hi = pos.ceil() as usize;
17446            if lo == hi {
17447                sorted[lo]
17448            } else {
17449                let weight = pos - lo as f64;
17450                sorted[lo] + (sorted[hi] - sorted[lo]) * weight
17451            }
17452        }
17453
17454        fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
17455            if !(0.0..=1.0).contains(&q) {
17456                return Scalar::Null(NullKind::NaN);
17457            }
17458            let mut samples = values
17459                .iter()
17460                .filter(|value| !value.is_missing())
17461                .filter_map(|value| value.to_f64().ok())
17462                .collect::<Vec<_>>();
17463            if samples.is_empty() {
17464                return Scalar::Null(NullKind::NaN);
17465            }
17466            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
17467            Scalar::Float64(interpolated(&samples, q))
17468        }
17469
17470        fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
17471            if !(0.0..=1.0).contains(&q) {
17472                return Scalar::Null(NullKind::NaN);
17473            }
17474            let mut samples = values
17475                .iter()
17476                .filter_map(|value| match value {
17477                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
17478                    _ => None,
17479                })
17480                .collect::<Vec<_>>();
17481            if samples.is_empty() {
17482                // Per br-frankenpandas-k7apg: a NaT-only Timedelta input stays in
17483                // the Timedelta family (pandas returns NaT, not float NaN).
17484                return Scalar::Timedelta64(Timedelta::NAT);
17485            }
17486            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
17487            Scalar::Timedelta64(interpolated(&samples, q) as i64)
17488        }
17489
17490        fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
17491            let actual = super::nanquantile(values, q);
17492            assert!(
17493                actual.semantic_eq(&expected),
17494                "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
17495            );
17496        }
17497
17498        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17499        assert_quantile(
17500            usize::MAX,
17501            "numeric_all_missing",
17502            &numeric_all_missing,
17503            0.5,
17504            expected_numeric(&numeric_all_missing, 0.5),
17505        );
17506        assert_quantile(
17507            usize::MAX - 1,
17508            "numeric_out_of_range",
17509            &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
17510            1.25,
17511            Scalar::Null(NullKind::NaN),
17512        );
17513
17514        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17515        assert_quantile(
17516            usize::MAX - 2,
17517            "timedelta_all_missing",
17518            &td_all_missing,
17519            0.5,
17520            expected_timedelta(&td_all_missing, 0.5),
17521        );
17522        assert_quantile(
17523            usize::MAX - 3,
17524            "timedelta_out_of_range",
17525            &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
17526            -0.25,
17527            Scalar::Null(NullKind::NaN),
17528        );
17529
17530        let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
17531        for case in 0..260 {
17532            let len = (next(&mut seed) % 83 + 1) as usize;
17533            let q = match next(&mut seed) % 8 {
17534                0 => 0.0,
17535                1 => 0.25,
17536                2 => 0.5,
17537                3 => 0.75,
17538                4 => 1.0,
17539                _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
17540            };
17541
17542            let mut numeric = Vec::with_capacity(len);
17543            numeric.push(Scalar::Int64(case as i64 - 130));
17544            for _ in 1..len {
17545                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17546                numeric.push(match next(&mut seed) % 8 {
17547                    0 => Scalar::Null(NullKind::Null),
17548                    1 => Scalar::Null(NullKind::NaN),
17549                    2 => Scalar::Float64(f64::NAN),
17550                    3 => Scalar::Bool(raw & 1 == 0),
17551                    4 => Scalar::Int64(raw % 251),
17552                    5 => Scalar::Float64(raw as f64 / 67.0),
17553                    6 => Scalar::Float64(0.0),
17554                    _ => Scalar::Float64(-0.0),
17555                });
17556            }
17557            assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
17558
17559            let mut timedeltas = Vec::with_capacity(len);
17560            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17561            for _ in 1..len {
17562                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17563                timedeltas.push(match next(&mut seed) % 7 {
17564                    0 => Scalar::Null(NullKind::Null),
17565                    1 => Scalar::Timedelta64(i64::MIN),
17566                    _ => Scalar::Timedelta64(raw),
17567                });
17568            }
17569            assert_quantile(
17570                case,
17571                "timedelta",
17572                &timedeltas,
17573                q,
17574                expected_timedelta(&timedeltas, q),
17575            );
17576        }
17577    }
17578
17579    #[test]
17580    fn nanargmax_returns_first_position() {
17581        let values = vec![
17582            Scalar::Float64(1.0),
17583            Scalar::Null(NullKind::NaN),
17584            Scalar::Float64(4.0),
17585            Scalar::Float64(4.0),
17586            Scalar::Float64(2.0),
17587        ];
17588        assert_eq!(super::nanargmax(&values), Some(2));
17589    }
17590
17591    #[test]
17592    fn nanargmin_returns_first_position() {
17593        let values = vec![
17594            Scalar::Float64(3.0),
17595            Scalar::Null(NullKind::NaN),
17596            Scalar::Float64(1.0),
17597            Scalar::Float64(1.0),
17598        ];
17599        assert_eq!(super::nanargmin(&values), Some(2));
17600    }
17601
17602    #[test]
17603    fn nanargmax_all_missing_returns_none() {
17604        let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
17605        assert_eq!(super::nanargmax(&values), None);
17606        assert_eq!(super::nanargmin(&values), None);
17607    }
17608
17609    #[test]
17610    fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
17611        // Differential vs independent first-tie arg oracles
17612        // (br-frankenpandas-unkj6). Seeded LCG, no mocks.
17613        fn next(seed: &mut u64) -> u64 {
17614            *seed = seed
17615                .wrapping_mul(2862933555777941757)
17616                .wrapping_add(3037000493);
17617            *seed
17618        }
17619
17620        fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
17621            let mut best: Option<(usize, f64)> = None;
17622            for (idx, value) in values.iter().enumerate() {
17623                if value.is_missing() {
17624                    continue;
17625                }
17626                let Ok(value) = value.to_f64() else {
17627                    continue;
17628                };
17629                if value.is_nan() {
17630                    continue;
17631                }
17632                match best {
17633                    None => best = Some((idx, value)),
17634                    Some((_, current))
17635                        if (find_max && value > current) || (!find_max && value < current) =>
17636                    {
17637                        best = Some((idx, value));
17638                    }
17639                    _ => {}
17640                }
17641            }
17642            best.map(|(idx, _)| idx)
17643        }
17644
17645        fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
17646            let mut best: Option<(usize, i64)> = None;
17647            for (idx, value) in values.iter().enumerate() {
17648                if value.is_missing() {
17649                    continue;
17650                }
17651                let Scalar::Timedelta64(ns) = value else {
17652                    continue;
17653                };
17654                match best {
17655                    None => best = Some((idx, *ns)),
17656                    Some((_, current))
17657                        if (find_max && *ns > current) || (!find_max && *ns < current) =>
17658                    {
17659                        best = Some((idx, *ns));
17660                    }
17661                    _ => {}
17662                }
17663            }
17664            best.map(|(idx, _)| idx)
17665        }
17666
17667        fn assert_args(
17668            case: usize,
17669            family: &str,
17670            values: &[Scalar],
17671            expected_min: Option<usize>,
17672            expected_max: Option<usize>,
17673        ) {
17674            assert_eq!(
17675                super::nanargmin(values),
17676                expected_min,
17677                "case={case} family={family}: nanargmin mismatch for {values:?}"
17678            );
17679            assert_eq!(
17680                super::nanargmax(values),
17681                expected_max,
17682                "case={case} family={family}: nanargmax mismatch for {values:?}"
17683            );
17684        }
17685
17686        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17687        assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
17688        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17689        assert_args(
17690            usize::MAX - 1,
17691            "timedelta_all_missing",
17692            &td_all_missing,
17693            None,
17694            None,
17695        );
17696        let positive_int64_endpoint = [
17697            Scalar::Int64(i64::MAX - 1),
17698            Scalar::Null(NullKind::Null),
17699            Scalar::Int64(i64::MAX),
17700        ];
17701        assert_args(
17702            usize::MAX - 2,
17703            "int64_positive_endpoint_exact_order",
17704            &positive_int64_endpoint,
17705            Some(0),
17706            Some(2),
17707        );
17708        let negative_int64_endpoint = [
17709            Scalar::Int64(i64::MIN + 2),
17710            Scalar::Null(NullKind::NaN),
17711            Scalar::Int64(i64::MIN + 1),
17712        ];
17713        assert_args(
17714            usize::MAX - 3,
17715            "int64_negative_endpoint_exact_order",
17716            &negative_int64_endpoint,
17717            Some(2),
17718            Some(0),
17719        );
17720
17721        let mut seed = 0xa126_5eed_ed9e_u64;
17722        for case in 0..260 {
17723            let len = (next(&mut seed) % 83 + 1) as usize;
17724
17725            let mut numeric = Vec::with_capacity(len);
17726            numeric.push(Scalar::Int64(case as i64 - 130));
17727            if len > 1 {
17728                numeric.push(Scalar::Int64(case as i64 - 130));
17729            }
17730            for _ in numeric.len()..len {
17731                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17732                numeric.push(match next(&mut seed) % 9 {
17733                    0 => Scalar::Null(NullKind::Null),
17734                    1 => Scalar::Null(NullKind::NaN),
17735                    2 => Scalar::Float64(f64::NAN),
17736                    3 => Scalar::Bool(raw & 1 == 0),
17737                    4 => Scalar::Int64(raw % 211),
17738                    5 => Scalar::Float64(raw as f64 / 47.0),
17739                    6 => Scalar::Float64(0.0),
17740                    7 => Scalar::Float64(-0.0),
17741                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
17742                });
17743            }
17744            assert_args(
17745                case,
17746                "numeric",
17747                &numeric,
17748                expected_numeric(&numeric, false),
17749                expected_numeric(&numeric, true),
17750            );
17751
17752            let mut timedeltas = Vec::with_capacity(len);
17753            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17754            if len > 1 {
17755                timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17756            }
17757            for _ in timedeltas.len()..len {
17758                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17759                timedeltas.push(match next(&mut seed) % 7 {
17760                    0 => Scalar::Null(NullKind::Null),
17761                    1 => Scalar::Timedelta64(i64::MIN),
17762                    _ => Scalar::Timedelta64(raw),
17763                });
17764            }
17765            assert_args(
17766                case,
17767                "timedelta",
17768                &timedeltas,
17769                expected_timedelta(&timedeltas, false),
17770                expected_timedelta(&timedeltas, true),
17771            );
17772        }
17773    }
17774
17775    #[test]
17776    fn nansem_matches_std_over_sqrt_n() {
17777        let values = vec![
17778            Scalar::Float64(2.0),
17779            Scalar::Float64(4.0),
17780            Scalar::Float64(4.0),
17781            Scalar::Float64(4.0),
17782            Scalar::Float64(5.0),
17783            Scalar::Float64(5.0),
17784            Scalar::Float64(7.0),
17785            Scalar::Float64(9.0),
17786        ];
17787        // numpy/scipy: std(ddof=1) = 2.138089935299395; sem = std/sqrt(8) = 0.7559
17788        let sem = super::nansem(&values, 1);
17789        assert!(matches!(sem, Scalar::Float64(_)));
17790        let Scalar::Float64(v) = sem else {
17791            return;
17792        };
17793        assert!((v - 0.7559289460184544).abs() < 1e-9);
17794    }
17795
17796    #[test]
17797    fn nansem_grouped_is_sqrt_var_over_n_7hxqv() {
17798        // pandas 2.2.3: Series([1.0, 4.0]).groupby([0, 0]).sem() == 1.5 while
17799        // Series([1.0, 4.0]).sem() == 1.4999999999999998.
17800        let values = [
17801            Scalar::Float64(1.0),
17802            Scalar::Null(NullKind::NaN),
17803            Scalar::Float64(4.0),
17804        ];
17805        assert_eq!(super::nansem_grouped(&values, 1), Scalar::Float64(1.5));
17806        // NEGATIVE: Series.sem keeps std / sqrt(n).
17807        assert_eq!(
17808            super::nansem(&values, 1),
17809            Scalar::Float64(1.499_999_999_999_999_8)
17810        );
17811        assert!(super::nansem_grouped(&values[..1], 1).is_missing());
17812    }
17813
17814    #[test]
17815    fn grouped_reducers_add_as_pandas_group_kernels_xhogl() {
17816        // pandas 2.2.3 groupby of ten 0.1: sum 1.0, mean 0.1, var 0.0 - a
17817        // plain fold gives 0.9999999999999999, 0.09999999999999999 and
17818        // 2.1e-34 (br-frankenpandas-xhogl).
17819        let tenths: Vec<Scalar> = (0..10).map(|_| Scalar::Float64(0.1)).collect();
17820        assert_eq!(super::nansum_grouped(&tenths), Scalar::Float64(1.0));
17821        assert_eq!(super::nanmean_grouped(&tenths), Scalar::Float64(0.1));
17822        assert_eq!(super::nanvar_grouped(&tenths, 1), Scalar::Float64(0.0));
17823        assert_eq!(super::nanstd_grouped(&tenths, 1), Scalar::Float64(0.0));
17824        // NEGATIVE: the Series reductions keep their plain fold.
17825        assert_eq!(
17826            super::nansum(&tenths),
17827            Scalar::Float64(0.999_999_999_999_999_9)
17828        );
17829        // An inf keeps the sum inf (the compensation would go NaN).
17830        let mut sum = super::KahanSum::default();
17831        for value in [1.0, f64::INFINITY, 2.0] {
17832            sum.add(value);
17833        }
17834        assert_eq!(sum.sum(), f64::INFINITY);
17835        // Missing values are skipped; too few for ddof is missing.
17836        let gapped = [
17837            Scalar::Float64(1.0),
17838            Scalar::Null(NullKind::NaN),
17839            Scalar::Float64(4.0),
17840        ];
17841        assert_eq!(super::nanmean_grouped(&gapped), Scalar::Float64(2.5));
17842        assert_eq!(super::nanvar_grouped(&gapped, 1), Scalar::Float64(4.5));
17843        assert!(super::nanvar_grouped(&gapped[..1], 1).is_missing());
17844        // Timedelta input keeps the exact integer paths.
17845        let spans = [Scalar::Timedelta64(1), Scalar::Timedelta64(2)];
17846        assert_eq!(super::nansum_grouped(&spans), super::nansum(&spans));
17847    }
17848
17849    #[test]
17850    fn grouped_skew_is_pandas_online_group_skew_vjfq9() {
17851        // pandas 2.2.3 groupby skew of [1, 4, 8] is 0.42327316026800615 - a
17852        // two-pass form gives 0.4232731602680071 (br-frankenpandas-vjfq9).
17853        let group = [
17854            Scalar::Float64(1.0),
17855            Scalar::Null(NullKind::NaN),
17856            Scalar::Float64(4.0),
17857            Scalar::Float64(8.0),
17858        ];
17859        assert_eq!(
17860            super::nanskew_grouped(&group),
17861            Scalar::Float64(0.423_273_160_268_006_15)
17862        );
17863        // 2922 values: pandas raises (n - 1) ** 0.5 with libm pow, which is not
17864        // sqrt's answer for n - 1 = 2921 (sqrt gives -0.002284383734800802).
17865        let long: Vec<Scalar> = (0..2922_i32)
17866            .map(|i| Scalar::Float64(f64::from((i * 7919) % 1000) / 7.0))
17867            .collect();
17868        let glibc_pow = Scalar::Float64(-0.002_284_383_734_800_801_4);
17869        // That is pandas on glibc, the oracle's platform. pandas' Cython
17870        // `** 0.5` calls the platform's pow, as fp does, and Apple's libm
17871        // returns sqrt's answer for 2921 (CI 36847809394 macos-latest), so
17872        // another libm may give that one - never anything else
17873        // (br-frankenpandas-3bo1g).
17874        if cfg!(all(target_os = "linux", target_env = "gnu")) {
17875            assert_eq!(super::nanskew_grouped(&long), glibc_pow);
17876        } else {
17877            let sqrt = Scalar::Float64(-0.002_284_383_734_800_802);
17878            assert!([glibc_pow, sqrt].contains(&super::nanskew_grouped(&long)));
17879        }
17880        // A constant group is 0; below 3 values missing; an inf poisons its
17881        // group (pandas skips only NaN), where dropping it would leave [1, 2, 5].
17882        let constant = [7.0; 3].map(Scalar::Float64);
17883        assert_eq!(super::nanskew_grouped(&constant), Scalar::Float64(0.0));
17884        assert!(super::nanskew_grouped(&group[..2]).is_missing());
17885        let with_inf = [1.0, f64::INFINITY, 2.0, 5.0].map(Scalar::Float64);
17886        assert!(super::nanskew_grouped(&with_inf).is_missing());
17887    }
17888
17889    #[test]
17890    fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
17891        fn former(values: &[Scalar], ddof: usize) -> Scalar {
17892            let nums = super::collect_finite(values);
17893            if nums.len() <= ddof {
17894                return Scalar::Null(NullKind::NaN);
17895            }
17896            match super::nanstd(values, ddof) {
17897                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17898                other => other,
17899            }
17900        }
17901
17902        fn assert_same_bits(values: &[Scalar], ddof: usize) {
17903            let expected = former(values, ddof);
17904            let actual = super::nansem(values, ddof);
17905            match (&expected, &actual) {
17906                (Scalar::Float64(expected), Scalar::Float64(actual)) => {
17907                    assert_eq!(
17908                        actual.to_bits(),
17909                        expected.to_bits(),
17910                        "values={values:?} ddof={ddof}"
17911                    );
17912                }
17913                _ => assert!(
17914                    actual.semantic_eq(&expected),
17915                    "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
17916                ),
17917            }
17918        }
17919
17920        let mut generated = Vec::with_capacity(4_096);
17921        for idx in 0..4_096_i64 {
17922            generated.push(match idx % 257 {
17923                0 => Scalar::Null(NullKind::NaN),
17924                1 => Scalar::Float64(-0.0),
17925                2 => Scalar::Float64(0.0),
17926                _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
17927                _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
17928            });
17929        }
17930
17931        let cases = [
17932            Vec::new(),
17933            vec![Scalar::Int64(1)],
17934            vec![
17935                Scalar::Null(NullKind::Null),
17936                Scalar::Float64(f64::NAN),
17937                Scalar::Int64(i64::MIN),
17938                Scalar::Int64(i64::MAX),
17939                Scalar::Float64(-0.0),
17940                Scalar::Float64(0.0),
17941            ],
17942            generated,
17943        ];
17944        for values in &cases {
17945            for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
17946                assert_same_bits(values, ddof);
17947            }
17948        }
17949    }
17950
17951    #[test]
17952    #[ignore = "foreground release A/B harness"]
17953    fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
17954        const ROWS: usize = 262_144;
17955        const BATCH: usize = 8;
17956        const BLOCKS: usize = 9;
17957        const PRECONDITION_CALLS: usize = 2;
17958
17959        fn former(values: &[Scalar], ddof: usize) -> Scalar {
17960            let nums = super::collect_finite(values);
17961            if nums.len() <= ddof {
17962                return Scalar::Null(NullKind::NaN);
17963            }
17964            match super::nanstd(values, ddof) {
17965                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17966                other => other,
17967            }
17968        }
17969
17970        fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
17971            let values = std::hint::black_box(values);
17972            if candidate {
17973                super::nansem(values, 1)
17974            } else {
17975                former(values, 1)
17976            }
17977        }
17978
17979        fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
17980            for _ in 0..PRECONDITION_CALLS {
17981                std::hint::black_box(evaluate(values, candidate));
17982            }
17983            let started = std::time::Instant::now();
17984            for _ in 0..BATCH {
17985                std::hint::black_box(evaluate(values, candidate));
17986            }
17987            started.elapsed().as_nanos()
17988        }
17989
17990        fn median(mut samples: Vec<u128>) -> u128 {
17991            samples.sort_unstable();
17992            samples[samples.len() / 2]
17993        }
17994
17995        fn spread(a: u128, b: u128) -> f64 {
17996            a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
17997        }
17998
17999        let values = (0..ROWS)
18000            .map(|idx| {
18001                if idx % 257 == 0 {
18002                    Scalar::Null(NullKind::NaN)
18003                } else {
18004                    Scalar::Int64((idx % 8_191) as i64 - 4_095)
18005                }
18006            })
18007            .collect::<Vec<_>>();
18008
18009        let expected_bits = match former(&values, 1) {
18010            Scalar::Float64(value) => Some(value.to_bits()),
18011            _ => None,
18012        };
18013        let actual_bits = match super::nansem(&values, 1) {
18014            Scalar::Float64(value) => Some(value.to_bits()),
18015            _ => None,
18016        };
18017        assert!(
18018            expected_bits.is_some(),
18019            "numeric nansem must return Float64"
18020        );
18021        assert_eq!(actual_bits, expected_bits, "A/B output bits");
18022
18023        std::hint::black_box(evaluate(&values, false));
18024        std::hint::black_box(evaluate(&values, true));
18025
18026        let body_started = std::time::Instant::now();
18027        let mut former_a = Vec::with_capacity(BLOCKS);
18028        let mut former_b = Vec::with_capacity(BLOCKS);
18029        let mut candidate_a = Vec::with_capacity(BLOCKS);
18030        let mut candidate_b = Vec::with_capacity(BLOCKS);
18031        for block in 0..BLOCKS {
18032            let order = if block % 2 == 0 {
18033                [(false, 0), (true, 0), (true, 1), (false, 1)]
18034            } else {
18035                [(true, 1), (false, 1), (false, 0), (true, 0)]
18036            };
18037            for (candidate, duplicate) in order {
18038                let elapsed = elapsed_ns(&values, candidate);
18039                match (candidate, duplicate) {
18040                    (false, 0) => former_a.push(elapsed),
18041                    (false, _) => former_b.push(elapsed),
18042                    (true, 0) => candidate_a.push(elapsed),
18043                    (true, _) => candidate_b.push(elapsed),
18044                }
18045            }
18046        }
18047
18048        let former_a = median(former_a) / BATCH as u128;
18049        let former_b = median(former_b) / BATCH as u128;
18050        let candidate_a = median(candidate_a) / BATCH as u128;
18051        let candidate_b = median(candidate_b) / BATCH as u128;
18052        let former_mean = (former_a + former_b) as f64 / 2.0;
18053        let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
18054        println!(
18055            "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}",
18056            spread(former_a, former_b),
18057            spread(candidate_a, candidate_b),
18058            former_mean / candidate_mean,
18059            body_started.elapsed().as_secs_f64()
18060        );
18061    }
18062
18063    #[test]
18064    fn nansem_empty_returns_null() {
18065        assert!(super::nansem(&[], 1).is_missing());
18066        assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
18067    }
18068
18069    #[test]
18070    fn nanptp_returns_max_minus_min() {
18071        let values = vec![
18072            Scalar::Float64(3.0),
18073            Scalar::Null(NullKind::NaN),
18074            Scalar::Float64(7.0),
18075            Scalar::Float64(1.0),
18076        ];
18077        assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
18078    }
18079
18080    #[test]
18081    fn nanptp_empty_returns_null() {
18082        assert!(super::nanptp(&[]).is_missing());
18083        assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
18084    }
18085
18086    #[test]
18087    fn nanptp_timedelta64_preserves_dtype_u2g0r() {
18088        // Per br-frankenpandas-u2g0r: ptp on Timedelta64 returns Timedelta64.
18089        let one_hour: i64 = 3_600 * 1_000_000_000;
18090        let values = vec![
18091            Scalar::Timedelta64(one_hour),
18092            Scalar::Timedelta64(5 * one_hour),
18093            Scalar::Timedelta64(2 * one_hour),
18094        ];
18095        assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
18096    }
18097
18098    #[test]
18099    fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
18100        // Differential vs independent max-min oracles
18101        // (br-frankenpandas-affjt). Seeded LCG, no mocks.
18102        fn next(seed: &mut u64) -> u64 {
18103            *seed = seed
18104                .wrapping_mul(3202034522624059733)
18105                .wrapping_add(4354685564936845319);
18106            *seed
18107        }
18108
18109        fn expected_numeric(values: &[Scalar]) -> Scalar {
18110            let mut lo = f64::INFINITY;
18111            let mut hi = f64::NEG_INFINITY;
18112            let mut seen = false;
18113            for value in values {
18114                if value.is_missing() {
18115                    continue;
18116                }
18117                if let Ok(value) = value.to_f64() {
18118                    seen = true;
18119                    lo = lo.min(value);
18120                    hi = hi.max(value);
18121                }
18122            }
18123            if seen {
18124                Scalar::Float64(hi - lo)
18125            } else {
18126                Scalar::Null(NullKind::NaN)
18127            }
18128        }
18129
18130        fn expected_timedelta(values: &[Scalar]) -> Scalar {
18131            let mut lo = i64::MAX;
18132            let mut hi = i64::MIN;
18133            let mut seen = false;
18134            for value in values {
18135                if let Scalar::Timedelta64(ns) = value
18136                    && !value.is_missing()
18137                {
18138                    seen = true;
18139                    lo = lo.min(*ns);
18140                    hi = hi.max(*ns);
18141                }
18142            }
18143            if seen {
18144                Scalar::Timedelta64(hi - lo)
18145            } else {
18146                Scalar::Null(NullKind::NaN)
18147            }
18148        }
18149
18150        fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
18151            let actual = super::nanptp(values);
18152            assert!(
18153                actual.semantic_eq(&expected),
18154                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
18155            );
18156        }
18157
18158        assert_ptp(
18159            usize::MAX,
18160            "numeric_all_missing",
18161            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
18162            Scalar::Null(NullKind::NaN),
18163        );
18164        assert_ptp(
18165            usize::MAX - 1,
18166            "timedelta_all_missing",
18167            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
18168            Scalar::Null(NullKind::NaN),
18169        );
18170        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
18171        assert_ptp(
18172            usize::MAX - 2,
18173            "timedelta_one_ns_range_beyond_f64_exactness",
18174            &[
18175                Scalar::Timedelta64(beyond_f64_exact_ns),
18176                Scalar::Timedelta64(beyond_f64_exact_ns - 1),
18177                Scalar::Timedelta64(Timedelta::NAT),
18178            ],
18179            Scalar::Timedelta64(1),
18180        );
18181
18182        let mut seed = 0xa22f_17ed_57a7_15e5_u64;
18183        for case in 0..260 {
18184            let len = (next(&mut seed) % 83 + 1) as usize;
18185
18186            let mut numeric = Vec::with_capacity(len);
18187            numeric.push(Scalar::Int64(case as i64 - 130));
18188            for _ in 1..len {
18189                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
18190                numeric.push(match next(&mut seed) % 9 {
18191                    0 => Scalar::Null(NullKind::Null),
18192                    1 => Scalar::Null(NullKind::NaN),
18193                    2 => Scalar::Float64(f64::NAN),
18194                    3 => Scalar::Bool(raw & 1 == 0),
18195                    4 => Scalar::Int64(raw),
18196                    5 => Scalar::Float64(raw as f64 / 53.0),
18197                    6 => Scalar::Float64(0.0),
18198                    7 => Scalar::Float64(-0.0),
18199                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
18200                });
18201            }
18202            assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
18203
18204            let mut timedeltas = Vec::with_capacity(len);
18205            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
18206            for _ in 1..len {
18207                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
18208                timedeltas.push(match next(&mut seed) % 7 {
18209                    0 => Scalar::Null(NullKind::Null),
18210                    1 => Scalar::Timedelta64(i64::MIN),
18211                    _ => Scalar::Timedelta64(raw),
18212                });
18213            }
18214            assert_ptp(
18215                case,
18216                "timedelta",
18217                &timedeltas,
18218                expected_timedelta(&timedeltas),
18219            );
18220        }
18221    }
18222
18223    #[test]
18224    fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
18225        // Per br-frankenpandas-ql1t5: argmax/argmin on Timedelta64 compare
18226        // i64 ns directly instead of silently skipping via to_f64.
18227        let one_hour: i64 = 3_600 * 1_000_000_000;
18228        let values = vec![
18229            Scalar::Timedelta64(2 * one_hour),
18230            Scalar::Timedelta64(5 * one_hour),
18231            Scalar::Timedelta64(one_hour),
18232            Scalar::Timedelta64(3 * one_hour),
18233        ];
18234        assert_eq!(super::nanargmax(&values), Some(1));
18235        assert_eq!(super::nanargmin(&values), Some(2));
18236    }
18237
18238    #[test]
18239    fn nanprod_timedelta64_returns_null_szq6a() {
18240        // Per br-frankenpandas-szq6a: pandas raises on Timedelta prod
18241        // (dimensionally undefined). We surface Null instead of the
18242        // misleading Float64(1.0) the old empty-iterator default emitted.
18243        let one_hour: i64 = 3_600 * 1_000_000_000;
18244        let values = vec![
18245            Scalar::Timedelta64(2 * one_hour),
18246            Scalar::Timedelta64(3 * one_hour),
18247        ];
18248        assert!(super::nanprod(&values).is_missing());
18249    }
18250
18251    #[test]
18252    fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
18253        // Differential vs independent product oracles
18254        // (br-frankenpandas-9938h). Seeded LCG, no mocks.
18255        fn next(seed: &mut u64) -> u64 {
18256            *seed = seed
18257                .wrapping_mul(6364136223846793005)
18258                .wrapping_add(1442695040888963407);
18259            *seed
18260        }
18261
18262        fn expected_numeric(values: &[Scalar]) -> Scalar {
18263            let mut product = 1.0_f64;
18264            for value in values {
18265                if value.is_missing() {
18266                    continue;
18267                }
18268                if let Ok(value) = value.to_f64() {
18269                    product *= value;
18270                }
18271            }
18272            Scalar::Float64(product)
18273        }
18274
18275        fn expected_timedelta(values: &[Scalar]) -> Scalar {
18276            if values
18277                .iter()
18278                .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
18279            {
18280                Scalar::Null(NullKind::NaN)
18281            } else {
18282                Scalar::Float64(1.0)
18283            }
18284        }
18285
18286        fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
18287            let actual = super::nanprod(values);
18288            assert!(
18289                actual.semantic_eq(&expected),
18290                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
18291            );
18292        }
18293
18294        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
18295        assert_prod(
18296            usize::MAX,
18297            "numeric_all_missing",
18298            &all_missing,
18299            Scalar::Float64(1.0),
18300        );
18301
18302        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
18303        assert_prod(
18304            usize::MAX - 1,
18305            "timedelta_all_missing",
18306            &td_all_missing,
18307            expected_timedelta(&td_all_missing),
18308        );
18309
18310        let mut seed = 0x6e0d_9938_a11c_0de5_u64;
18311        for case in 0..280 {
18312            let len = (next(&mut seed) % 89 + 1) as usize;
18313
18314            let mut numeric = Vec::with_capacity(len);
18315            numeric.push(Scalar::Int64((case % 17) as i64 - 8));
18316            for _ in 1..len {
18317                let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
18318                numeric.push(match next(&mut seed) % 9 {
18319                    0 => Scalar::Null(NullKind::Null),
18320                    1 => Scalar::Null(NullKind::NaN),
18321                    2 => Scalar::Float64(f64::NAN),
18322                    3 => Scalar::Bool(raw & 1 == 0),
18323                    4 => Scalar::Int64(raw % 19),
18324                    5 => Scalar::Float64(raw as f64 / 97.0),
18325                    6 => Scalar::Float64(0.0),
18326                    7 => Scalar::Float64(-0.0),
18327                    _ => Scalar::Float64(1.0),
18328                });
18329            }
18330            assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
18331
18332            let mut timedeltas = Vec::with_capacity(len);
18333            timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
18334            for _ in 1..len {
18335                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
18336                timedeltas.push(match next(&mut seed) % 7 {
18337                    0 => Scalar::Null(NullKind::Null),
18338                    1 => Scalar::Timedelta64(i64::MIN),
18339                    _ => Scalar::Timedelta64(raw),
18340                });
18341            }
18342            assert_prod(
18343                case,
18344                "timedelta",
18345                &timedeltas,
18346                expected_timedelta(&timedeltas),
18347            );
18348        }
18349    }
18350
18351    #[test]
18352    fn nanskew_symmetric_distribution_near_zero() {
18353        let values = vec![
18354            Scalar::Float64(1.0),
18355            Scalar::Float64(2.0),
18356            Scalar::Float64(3.0),
18357            Scalar::Float64(4.0),
18358            Scalar::Float64(5.0),
18359        ];
18360        // Perfectly symmetric -> skew = 0
18361        let skew = super::nanskew(&values);
18362        assert!(matches!(skew, Scalar::Float64(_)));
18363        let Scalar::Float64(v) = skew else {
18364            return;
18365        };
18366        assert!(v.abs() < 1e-9);
18367    }
18368
18369    #[test]
18370    fn nanskew_too_few_values_returns_null() {
18371        assert!(super::nanskew(&[]).is_missing());
18372        assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
18373    }
18374
18375    #[test]
18376    fn nankurt_symmetric_uniform_distribution() {
18377        let values = vec![
18378            Scalar::Float64(1.0),
18379            Scalar::Float64(2.0),
18380            Scalar::Float64(3.0),
18381            Scalar::Float64(4.0),
18382            Scalar::Float64(5.0),
18383        ];
18384        // pandas kurt([1,2,3,4,5]) = -1.2
18385        let kurt = super::nankurt(&values);
18386        assert!(matches!(kurt, Scalar::Float64(_)));
18387        let Scalar::Float64(v) = kurt else {
18388            return;
18389        };
18390        assert!((v + 1.2).abs() < 1e-9);
18391    }
18392
18393    #[test]
18394    fn nankurt_too_few_values_returns_null() {
18395        let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
18396        assert!(super::nankurt(&vals).is_missing());
18397    }
18398
18399    #[test]
18400    fn nanskew_constant_series_returns_zero() {
18401        let values = vec![
18402            Scalar::Float64(5.0),
18403            Scalar::Float64(5.0),
18404            Scalar::Float64(5.0),
18405        ];
18406        assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
18407        assert_eq!(
18408            super::nankurt(&[
18409                Scalar::Float64(5.0),
18410                Scalar::Float64(5.0),
18411                Scalar::Float64(5.0),
18412                Scalar::Float64(5.0),
18413            ]),
18414            Scalar::Float64(0.0)
18415        );
18416    }
18417
18418    #[test]
18419    fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
18420        // Differential vs independent bias-corrected moment oracles
18421        // (br-frankenpandas-jr7zk). Seeded LCG, no mocks.
18422        fn next(seed: &mut u64) -> u64 {
18423            *seed = seed
18424                .wrapping_mul(2862933555777941757)
18425                .wrapping_add(3037000493);
18426            *seed
18427        }
18428
18429        fn samples(values: &[Scalar]) -> Vec<f64> {
18430            values
18431                .iter()
18432                .filter(|value| !value.is_missing())
18433                .filter_map(|value| value.to_f64().ok())
18434                .collect()
18435        }
18436
18437        fn expected_skew(values: &[Scalar]) -> Scalar {
18438            let samples = samples(values);
18439            let n = samples.len() as f64;
18440            if n < 3.0 {
18441                return Scalar::Null(NullKind::NaN);
18442            }
18443            let mean = samples.iter().sum::<f64>() / n;
18444            let m2 = samples
18445                .iter()
18446                .map(|value| (value - mean).powi(2))
18447                .sum::<f64>();
18448            let m3 = samples
18449                .iter()
18450                .map(|value| (value - mean).powi(3))
18451                .sum::<f64>();
18452            let s2 = m2 / (n - 1.0);
18453            if s2 == 0.0 {
18454                return Scalar::Float64(0.0);
18455            }
18456            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
18457        }
18458
18459        fn expected_kurt(values: &[Scalar]) -> Scalar {
18460            let samples = samples(values);
18461            let n = samples.len() as f64;
18462            if n < 4.0 {
18463                return Scalar::Null(NullKind::NaN);
18464            }
18465            let mean = samples.iter().sum::<f64>() / n;
18466            let m2 = samples
18467                .iter()
18468                .map(|value| (value - mean).powi(2))
18469                .sum::<f64>();
18470            let m4 = samples
18471                .iter()
18472                .map(|value| (value - mean).powi(4))
18473                .sum::<f64>();
18474            let s2 = m2 / (n - 1.0);
18475            if s2 == 0.0 {
18476                return Scalar::Float64(0.0);
18477            }
18478            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
18479            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
18480            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
18481        }
18482
18483        fn assert_moments(case: usize, values: &[Scalar]) {
18484            let expected_skew = expected_skew(values);
18485            let expected_kurt = expected_kurt(values);
18486            let actual_skew = super::nanskew(values);
18487            let actual_kurt = super::nankurt(values);
18488            assert!(
18489                actual_skew.semantic_eq(&expected_skew),
18490                "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
18491            );
18492            assert!(
18493                actual_kurt.semantic_eq(&expected_kurt),
18494                "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
18495            );
18496        }
18497
18498        assert_moments(
18499            usize::MAX,
18500            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
18501        );
18502        assert_moments(
18503            usize::MAX - 1,
18504            &[
18505                Scalar::Float64(7.0),
18506                Scalar::Float64(7.0),
18507                Scalar::Float64(7.0),
18508                Scalar::Float64(7.0),
18509            ],
18510        );
18511
18512        let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
18513        for case in 0..260 {
18514            let len = (next(&mut seed) % 89 + 1) as usize;
18515            let mut values = Vec::with_capacity(len);
18516            if case % 11 == 0 {
18517                values.extend((0..len).map(|_| Scalar::Float64(3.0)));
18518            } else {
18519                values.push(Scalar::Float64(case as f64 / 19.0));
18520                for _ in 1..len {
18521                    let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
18522                    values.push(match next(&mut seed) % 8 {
18523                        0 => Scalar::Null(NullKind::Null),
18524                        1 => Scalar::Null(NullKind::NaN),
18525                        2 => Scalar::Float64(f64::NAN),
18526                        3 => Scalar::Bool(raw & 1 == 0),
18527                        4 => Scalar::Int64(raw % 251),
18528                        5 => Scalar::Float64(raw as f64 / 83.0),
18529                        6 => Scalar::Float64(0.0),
18530                        _ => Scalar::Float64(-0.0),
18531                    });
18532                }
18533            }
18534            assert_moments(case, &values);
18535        }
18536    }
18537
18538    // ── Interval tests (br-frankenpandas-j8k4) ──────────────────────────
18539
18540    #[test]
18541    fn interval_default_closed_is_right() {
18542        assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
18543    }
18544
18545    #[test]
18546    fn interval_left_and_right_closed_helpers() {
18547        assert!(IntervalClosed::Left.left_closed());
18548        assert!(!IntervalClosed::Left.right_closed());
18549        assert!(!IntervalClosed::Right.left_closed());
18550        assert!(IntervalClosed::Right.right_closed());
18551        assert!(IntervalClosed::Both.left_closed());
18552        assert!(IntervalClosed::Both.right_closed());
18553        assert!(!IntervalClosed::Neither.left_closed());
18554        assert!(!IntervalClosed::Neither.right_closed());
18555    }
18556
18557    #[test]
18558    fn interval_display_matches_pandas_notation() {
18559        assert_eq!(
18560            Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
18561            "(0.0, 5.0]"
18562        );
18563        assert_eq!(
18564            Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
18565            "[0.0, 5.0)"
18566        );
18567        assert_eq!(
18568            Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
18569            "[0.0, 5.0]"
18570        );
18571        assert_eq!(
18572            Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
18573            "(0.0, 5.0)"
18574        );
18575        assert_eq!(
18576            Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
18577            "(2.5, 3.5]"
18578        );
18579        assert_eq!(
18580            Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
18581            "(-1.0, 0.0]"
18582        );
18583        assert_eq!(
18584            Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
18585            "(1e+20, 2e+20]"
18586        );
18587    }
18588
18589    #[test]
18590    fn interval_length_and_mid() {
18591        let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
18592        assert_eq!(i.length(), 8.0);
18593        assert_eq!(i.mid(), 6.0);
18594    }
18595
18596    #[test]
18597    fn interval_contains_matches_closed_policy() {
18598        let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
18599        assert!(!right.contains(0.0));
18600        assert!(right.contains(2.5));
18601        assert!(right.contains(5.0));
18602
18603        let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
18604        assert!(left.contains(0.0));
18605        assert!(left.contains(2.5));
18606        assert!(!left.contains(5.0));
18607
18608        let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
18609        assert!(both.contains(0.0));
18610        assert!(both.contains(5.0));
18611
18612        let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
18613        assert!(!neither.contains(0.0));
18614        assert!(!neither.contains(5.0));
18615        assert!(neither.contains(2.5));
18616    }
18617
18618    #[test]
18619    fn interval_contains_nan_returns_false() {
18620        let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
18621        assert!(!i.contains(f64::NAN));
18622    }
18623
18624    #[test]
18625    fn interval_is_empty_matches_pandas() {
18626        // pd.Interval(3, 3, 'right').is_empty → True
18627        assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
18628        assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
18629        assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
18630        // pd.Interval(3, 3, 'both').is_empty → False (single point)
18631        assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
18632        // Non-degenerate intervals are never empty.
18633        assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
18634    }
18635
18636    #[test]
18637    fn interval_overlaps_disjoint_returns_false() {
18638        let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
18639        let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
18640        assert!(!a.overlaps(&b));
18641        assert!(!b.overlaps(&a));
18642    }
18643
18644    #[test]
18645    fn interval_overlaps_nested_returns_true() {
18646        let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
18647        let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
18648        assert!(outer.overlaps(&inner));
18649        assert!(inner.overlaps(&outer));
18650    }
18651
18652    #[test]
18653    fn interval_overlaps_touching_respects_closed_policy() {
18654        // (0, 1] touching (1, 2] at point 1.
18655        let right_right = (
18656            Interval::new(0.0, 1.0, IntervalClosed::Right),
18657            Interval::new(1.0, 2.0, IntervalClosed::Right),
18658        );
18659        // right_right.0 is closed at 1; right_right.1 is open at 1 → no overlap.
18660        assert!(!right_right.0.overlaps(&right_right.1));
18661
18662        // [0, 1] touching [1, 2] — both closed at 1 → overlap.
18663        let both_both = (
18664            Interval::new(0.0, 1.0, IntervalClosed::Both),
18665            Interval::new(1.0, 2.0, IntervalClosed::Both),
18666        );
18667        assert!(both_both.0.overlaps(&both_both.1));
18668    }
18669
18670    #[test]
18671    fn interval_roundtrips_through_serde_json() {
18672        let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
18673        let json = serde_json::to_string(&i).expect("serialize");
18674        let back: Interval = serde_json::from_str(&json).expect("deserialize");
18675        assert_eq!(i, back);
18676    }
18677
18678    #[test]
18679    fn interval_serde_default_closed_is_right_when_missing() {
18680        // JSON payloads that omit `closed` deserialize with the pandas default.
18681        let back: Interval =
18682            serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
18683        assert_eq!(back.closed, IntervalClosed::Right);
18684    }
18685
18686    // ── Period tests (br-frankenpandas-epoj) ────────────────────────────
18687
18688    #[test]
18689    fn period_freq_parses_canonical_aliases() {
18690        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
18691        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
18692        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
18693        assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
18694        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
18695        assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
18696        assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
18697        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
18698        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
18699        assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
18700        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
18701    }
18702
18703    #[test]
18704    fn period_freq_parse_is_case_insensitive() {
18705        assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::QUARTERLY));
18706        assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
18707    }
18708
18709    #[test]
18710    fn period_freq_rejects_unknown_aliases() {
18711        assert_eq!(PeriodFreq::parse("nanosec"), None);
18712        assert_eq!(PeriodFreq::parse(""), None);
18713        assert_eq!(PeriodFreq::parse("xyz"), None);
18714    }
18715
18716    #[test]
18717    fn period_freq_alias_roundtrip() {
18718        for freq in [
18719            PeriodFreq::ANNUAL,
18720            PeriodFreq::QUARTERLY,
18721            PeriodFreq::Monthly,
18722            PeriodFreq::WEEKLY,
18723            PeriodFreq::Daily,
18724            PeriodFreq::Business,
18725            PeriodFreq::Hourly,
18726            PeriodFreq::Minutely,
18727            PeriodFreq::Secondly,
18728            PeriodFreq::Milliseconds,
18729            PeriodFreq::Microseconds,
18730            PeriodFreq::Nanoseconds,
18731        ] {
18732            assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18733        }
18734    }
18735
18736    /// Anchored aliases parse to their anchor and print back; the shifts move
18737    /// a month count / week start onto the fiscal calendar; a W-MON label
18738    /// spans Tuesday..Monday (live pandas 2.2.3: Period('2024-03-01', 'W-MON')
18739    /// is '2024-02-27/2024-03-04', ordinal 2827; br-frankenpandas-39h5n).
18740    #[test]
18741    fn anchored_period_freqs_parse_print_and_shift_39h5n() {
18742        for month in 1..=12_u8 {
18743            for freq in [PeriodFreq::Annual(month), PeriodFreq::Quarterly(month)] {
18744                assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18745            }
18746        }
18747        for day in 0..7_u8 {
18748            assert_eq!(
18749                PeriodFreq::parse(&PeriodFreq::Weekly(day).alias()),
18750                Some(PeriodFreq::Weekly(day))
18751            );
18752        }
18753        assert_eq!(PeriodFreq::parse("Y-JUN"), Some(PeriodFreq::Annual(6)));
18754        assert_eq!(PeriodFreq::parse("A-JUN"), Some(PeriodFreq::Annual(6)));
18755        assert_eq!(PeriodFreq::parse("q-jan"), Some(PeriodFreq::Quarterly(1)));
18756        assert_eq!(PeriodFreq::parse("W-MON"), Some(PeriodFreq::Weekly(0)));
18757        assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18758        // NEGATIVE: not an anchor, or not an anchorable frequency.
18759        assert_eq!(PeriodFreq::parse("Q-XYZ"), None);
18760        assert_eq!(PeriodFreq::parse("M-JAN"), None);
18761        assert_eq!(PeriodFreq::parse("W-JAN"), None);
18762        assert_eq!(PeriodFreq::Annual(6).fiscal_month_shift(), 6);
18763        assert_eq!(PeriodFreq::Quarterly(1).fiscal_month_shift(), 11);
18764        assert_eq!(PeriodFreq::QUARTERLY.fiscal_month_shift(), 0);
18765        assert_eq!(PeriodFreq::Weekly(0).week_start_shift(), 1);
18766        assert_eq!(PeriodFreq::WEEKLY.week_start_shift(), 0);
18767        assert_eq!(
18768            Period::new(2827, PeriodFreq::Weekly(0)).to_string(),
18769            "2024-02-27/2024-03-04"
18770        );
18771        assert_eq!(
18772            Period::new(2826, PeriodFreq::Weekly(5)).to_string(),
18773            "2024-02-25/2024-03-02"
18774        );
18775        assert_eq!(
18776            Period::new(220, PeriodFreq::Quarterly(1)).to_string(),
18777            "2025Q1"
18778        );
18779    }
18780
18781    /// The three sub-second frequencies pandas' `to_period` accepts and this
18782    /// crate used to reject. Transcribed from live pandas 2.2.3 on
18783    /// `Timestamp('2024-03-15 10:30:45.123456789')`.
18784    #[test]
18785    fn period_freq_subsecond_units_match_pandas() {
18786        // Aliases and resolution words.
18787        assert_eq!(PeriodFreq::Milliseconds.alias(), "ms");
18788        assert_eq!(PeriodFreq::Microseconds.alias(), "us");
18789        assert_eq!(PeriodFreq::Nanoseconds.alias(), "ns");
18790        assert_eq!(PeriodFreq::Milliseconds.resolution(), Some("millisecond"));
18791        assert_eq!(PeriodFreq::Microseconds.resolution(), Some("microsecond"));
18792        assert_eq!(PeriodFreq::Nanoseconds.resolution(), Some("nanosecond"));
18793
18794        // ⚠️ THE ONE CASE-SENSITIVE ALIAS. pandas reads bare "MS" as month start
18795        // and refuses it here, while every other casing of "ms" is milliseconds.
18796        assert_eq!(PeriodFreq::parse("ms"), Some(PeriodFreq::Milliseconds));
18797        assert_eq!(PeriodFreq::parse("Ms"), Some(PeriodFreq::Milliseconds));
18798        assert_eq!(PeriodFreq::parse("mS"), Some(PeriodFreq::Milliseconds));
18799        assert_eq!(PeriodFreq::parse("MS"), None);
18800        // us/ns are case-insensitive in pandas, so both casings resolve.
18801        assert_eq!(PeriodFreq::parse("us"), Some(PeriodFreq::Microseconds));
18802        assert_eq!(PeriodFreq::parse("US"), Some(PeriodFreq::Microseconds));
18803        assert_eq!(PeriodFreq::parse("ns"), Some(PeriodFreq::Nanoseconds));
18804        assert_eq!(PeriodFreq::parse("NS"), Some(PeriodFreq::Nanoseconds));
18805
18806        // Ordinals are unit counts since the epoch; labels pad the fraction to
18807        // the full width of the frequency and never trim trailing zeros.
18808        assert_eq!(
18809            Period::new(1_710_498_645_123, PeriodFreq::Milliseconds).calendar_string(),
18810            "2024-03-15 10:30:45.123"
18811        );
18812        assert_eq!(
18813            Period::new(1_710_498_645_123_456, PeriodFreq::Microseconds).calendar_string(),
18814            "2024-03-15 10:30:45.123456"
18815        );
18816        assert_eq!(
18817            Period::new(1_710_498_645_123_456_789, PeriodFreq::Nanoseconds).calendar_string(),
18818            "2024-03-15 10:30:45.123456789"
18819        );
18820
18821        // A whole-second instant still shows its zero fraction, and the
18822        // pre-epoch ordinals are the FLOOR, not a truncation toward zero:
18823        // Timestamp('1969-12-31 23:59:59.999') at 'ms' has ordinal -1.
18824        assert_eq!(
18825            Period::new(0, PeriodFreq::Milliseconds).calendar_string(),
18826            "1970-01-01 00:00:00.000"
18827        );
18828        assert_eq!(
18829            Period::new(-1, PeriodFreq::Milliseconds).calendar_string(),
18830            "1969-12-31 23:59:59.999"
18831        );
18832        assert_eq!(
18833            Period::new(-1_000, PeriodFreq::Microseconds).calendar_string(),
18834            "1969-12-31 23:59:59.999000"
18835        );
18836        assert_eq!(
18837            Period::new(-999_999, PeriodFreq::Nanoseconds).calendar_string(),
18838            "1969-12-31 23:59:59.999000001"
18839        );
18840    }
18841
18842    #[test]
18843    fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
18844        assert_eq!(PeriodFreq::ANNUAL.alias(), "Y-DEC");
18845        assert_eq!(PeriodFreq::QUARTERLY.alias(), "Q-DEC");
18846        assert_eq!(PeriodFreq::WEEKLY.alias(), "W-SUN");
18847
18848        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
18849        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
18850        assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::ANNUAL));
18851        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
18852        assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18853        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
18854        assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::WEEKLY));
18855    }
18856
18857    #[test]
18858    fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
18859        assert_eq!(PeriodFreq::Hourly.alias(), "h");
18860        assert_eq!(PeriodFreq::Minutely.alias(), "min");
18861        assert_eq!(PeriodFreq::Secondly.alias(), "s");
18862
18863        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
18864        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
18865        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
18866    }
18867
18868    /// The resolution table is the COMPONENT WORD, never the frequency alias.
18869    /// Transcribed from live pandas 2.2.3: `pd.PeriodIndex([ts], freq=f).resolution`
18870    /// for each f, with W and B raising AttributeError.
18871    #[test]
18872    fn period_freq_resolution_is_the_component_word_not_the_alias() {
18873        assert_eq!(PeriodFreq::ANNUAL.resolution(), Some("year"));
18874        assert_eq!(PeriodFreq::QUARTERLY.resolution(), Some("quarter"));
18875        assert_eq!(PeriodFreq::Monthly.resolution(), Some("month"));
18876        assert_eq!(PeriodFreq::Daily.resolution(), Some("day"));
18877        assert_eq!(PeriodFreq::Hourly.resolution(), Some("hour"));
18878        assert_eq!(PeriodFreq::Minutely.resolution(), Some("minute"));
18879        assert_eq!(PeriodFreq::Secondly.resolution(), Some("second"));
18880
18881        // pandas raises AttributeError for these two rather than answering.
18882        assert_eq!(PeriodFreq::WEEKLY.resolution(), None);
18883        assert_eq!(PeriodFreq::Business.resolution(), None);
18884
18885        // The bug this replaces was the alias table copied into the resolution
18886        // slot, so pin the two apart: no frequency may report the same string
18887        // for both. (Every pandas alias is short and lowercase-ish; every
18888        // resolution word is a full English noun -- they never coincide.)
18889        for freq in [
18890            PeriodFreq::ANNUAL,
18891            PeriodFreq::QUARTERLY,
18892            PeriodFreq::Monthly,
18893            PeriodFreq::WEEKLY,
18894            PeriodFreq::Daily,
18895            PeriodFreq::Business,
18896            PeriodFreq::Hourly,
18897            PeriodFreq::Minutely,
18898            PeriodFreq::Secondly,
18899        ] {
18900            assert_ne!(
18901                Some(freq.alias().as_str()),
18902                freq.resolution(),
18903                "{freq:?} reports its alias as its resolution again"
18904            );
18905        }
18906    }
18907
18908    #[test]
18909    fn period_scalar_accessors_match_pandas_star8() {
18910        let period = Period::new(600, PeriodFreq::Monthly);
18911
18912        assert_eq!(period.ordinal(), 600);
18913        assert_eq!(period.freq(), PeriodFreq::Monthly);
18914        assert_eq!(period.freqstr(), "M");
18915    }
18916
18917    #[test]
18918    fn period_multiplied_frequencies_parse_and_roundtrip_tus8r() {
18919        for (alias, canonical, base, multiplier) in [
18920            ("2D", "2D", PeriodFreq::Daily, 2),
18921            ("+3H", "3h", PeriodFreq::Hourly, 3),
18922            ("15min", "15min", PeriodFreq::Minutely, 15),
18923            ("2W-FRI", "2W-FRI", PeriodFreq::Weekly(4), 2),
18924            ("2M", "2M", PeriodFreq::Monthly, 2),
18925            ("2Q-JAN", "2Q-JAN", PeriodFreq::Quarterly(1), 2),
18926            ("2Y-JUN", "2Y-JUN", PeriodFreq::Annual(6), 2),
18927            ("2B", "2B", PeriodFreq::Business, 2),
18928            ("2ms", "2ms", PeriodFreq::Milliseconds, 2),
18929            ("3us", "3us", PeriodFreq::Microseconds, 3),
18930            ("4ns", "4ns", PeriodFreq::Nanoseconds, 4),
18931        ] {
18932            let freq = PeriodFreq::parse(alias).expect("valid multiplied frequency");
18933            assert_eq!(freq.base(), base, "{alias}");
18934            assert_eq!(freq.multiplier(), multiplier, "{alias}");
18935            assert_eq!(freq.alias(), canonical, "{alias}");
18936            assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18937            assert_eq!(freq.resolution(), None);
18938            let encoded = serde_json::to_string(&freq).expect("serializable frequency");
18939            assert_eq!(serde_json::from_str::<PeriodFreq>(&encoded).unwrap(), freq);
18940        }
18941        assert_eq!(PeriodFreq::parse("1D"), Some(PeriodFreq::Daily));
18942        for invalid in ["0D", "-1D", "2MS", "2 3D", "2", "9223372036854775808D"] {
18943            assert_eq!(PeriodFreq::parse(invalid), None, "{invalid}");
18944        }
18945        assert!(
18946            serde_json::from_str::<PeriodFreq>(r#"{"MULTIPLE":{"unit":"DAILY","count":0}}"#,)
18947                .is_err()
18948        );
18949    }
18950
18951    /// Expected boundaries and labels measured against pandas 2.2.3 at
18952    /// Timestamp('2024-02-28 13:47:59.123456789'). The ordinal stays in base
18953    /// units, the label names the first base period, and the end spans n.
18954    #[test]
18955    fn period_multiplied_boundaries_and_labels_match_pandas_tus8r() {
18956        let nanos = 1_709_128_079_123_456_789;
18957        for (alias, ordinal, label, start, end) in [
18958            (
18959                "2D",
18960                19_781,
18961                "2024-02-28",
18962                1_709_078_400_000_000_000,
18963                1_709_251_199_999_999_999,
18964            ),
18965            (
18966                "3h",
18967                474_757,
18968                "2024-02-28 13:00",
18969                1_709_125_200_000_000_000,
18970                1_709_135_999_999_999_999,
18971            ),
18972            (
18973                "15min",
18974                28_485_467,
18975                "2024-02-28 13:47",
18976                1_709_128_020_000_000_000,
18977                1_709_128_919_999_999_999,
18978            ),
18979            (
18980                "2W-FRI",
18981                2_826,
18982                "2024-02-24/2024-03-01",
18983                1_708_732_800_000_000_000,
18984                1_709_942_399_999_999_999,
18985            ),
18986            (
18987                "2M",
18988                649,
18989                "2024-02",
18990                1_706_745_600_000_000_000,
18991                1_711_929_599_999_999_999,
18992            ),
18993            (
18994                "2Q-JAN",
18995                220,
18996                "2025Q1",
18997                1_706_745_600_000_000_000,
18998                1_722_470_399_999_999_999,
18999            ),
19000            (
19001                "2Y-JUN",
19002                54,
19003                "2024",
19004                1_688_169_600_000_000_000,
19005                1_751_327_999_999_999_999,
19006            ),
19007            (
19008                "2B",
19009                14_129,
19010                "2024-02-28",
19011                1_709_078_400_000_000_000,
19012                1_709_251_199_999_999_999,
19013            ),
19014            (
19015                "2ms",
19016                1_709_128_079_123,
19017                "2024-02-28 13:47:59.123",
19018                1_709_128_079_123_000_000,
19019                1_709_128_079_124_999_999,
19020            ),
19021            (
19022                "3us",
19023                1_709_128_079_123_456,
19024                "2024-02-28 13:47:59.123456",
19025                1_709_128_079_123_456_000,
19026                1_709_128_079_123_458_999,
19027            ),
19028            (
19029                "4ns",
19030                nanos,
19031                "2024-02-28 13:47:59.123456789",
19032                nanos,
19033                nanos + 3,
19034            ),
19035        ] {
19036            let freq = PeriodFreq::parse(alias).expect("valid multiplied frequency");
19037            let period = Period::from_timestamp_nanos(nanos, freq).expect("in-range timestamp");
19038            assert_eq!(period.ordinal, ordinal, "{alias}");
19039            assert_eq!(period.to_string(), label, "{alias}");
19040            assert_eq!(period.start_nanos(), Some(start), "{alias}");
19041            assert_eq!(period.end_nanos(), Some(end), "{alias}");
19042            assert_eq!(period.shift(1).ordinal, ordinal + freq.multiplier());
19043            assert_eq!(period.shift(-1).ordinal, ordinal - freq.multiplier());
19044            assert_eq!(period.shift(1).diff(&period), Some(freq.multiplier()));
19045            assert_eq!(
19046                period.asfreq(alias).unwrap().ordinal,
19047                ordinal + freq.multiplier() - 1
19048            );
19049            assert_eq!(period.asfreq_with_how(alias, "start").unwrap(), period);
19050        }
19051
19052        // Business spans exclude weekends, while calendar fields still
19053        // describe the first base day or month of a multi-period span.
19054        let business = Period::new(14_091, PeriodFreq::parse("2B").unwrap());
19055        assert_eq!(business.end_nanos(), Some(1_704_758_399_999_999_999));
19056        assert_eq!(business.shift(1).to_string(), "2024-01-09");
19057        let month = Period::new(649, PeriodFreq::parse("2M").unwrap());
19058        assert_eq!(
19059            (month.year(), month.month(), month.day()),
19060            (Some(2024), Some(2), Some(29))
19061        );
19062        let quarter = Period::new(220, PeriodFreq::parse("2Q-JAN").unwrap());
19063        assert_eq!(
19064            (quarter.year(), quarter.quarter(), quarter.qyear()),
19065            (Some(2024), Some(1), Some(2025))
19066        );
19067    }
19068
19069    #[test]
19070    fn period_multiplied_ranges_keep_negative_ordinals_and_nat_tus8r() {
19071        let freq = PeriodFreq::parse("3h").unwrap();
19072        let before_epoch = Period::from_timestamp_nanos(-1, freq).unwrap();
19073        assert_eq!(before_epoch.ordinal, -1);
19074        assert_eq!(before_epoch.start_nanos(), Some(-3_600_000_000_000));
19075        assert_eq!(before_epoch.end_nanos(), Some(7_199_999_999_999));
19076        assert_eq!(
19077            super::period_range(before_epoch, 3)
19078                .iter()
19079                .map(|period| period.ordinal)
19080                .collect::<Vec<_>>(),
19081            vec![-1, 2, 5],
19082        );
19083        assert!(super::period_range(before_epoch, 0).is_empty());
19084        let nat = Period::new(i64::MIN, freq);
19085        assert!(nat.shift(1).is_nat());
19086        assert!(nat.asfreq("2D").unwrap().is_nat());
19087        assert_eq!(nat.end_nanos(), None);
19088        assert_eq!(Period::new(i64::MAX, freq).end_nanos(), None);
19089        assert_eq!(Period::new(-100, freq).shift(i64::MAX).ordinal, i64::MAX);
19090    }
19091
19092    #[test]
19093    fn period_parse_common_pandas_ordinals_avm08() {
19094        assert_eq!(
19095            Period::parse("2024").unwrap(),
19096            Period::new(54, PeriodFreq::ANNUAL)
19097        );
19098        assert_eq!(
19099            Period::parse("2024Q1").unwrap(),
19100            Period::new(216, PeriodFreq::QUARTERLY)
19101        );
19102        assert_eq!(
19103            Period::parse("2024-01").unwrap(),
19104            Period::new(648, PeriodFreq::Monthly)
19105        );
19106        assert_eq!(
19107            Period::parse("2024-01-15").unwrap(),
19108            Period::new(19_737, PeriodFreq::Daily)
19109        );
19110        assert!(Period::parse("216").is_err());
19111    }
19112
19113    #[test]
19114    fn period_shift_advances_ordinal() {
19115        let q1 = Period::new(216, PeriodFreq::QUARTERLY);
19116        let q2 = q1.shift(1);
19117        assert_eq!(q2.ordinal, 217);
19118        assert_eq!(q2.freq, PeriodFreq::QUARTERLY);
19119        let q0 = q1.shift(-1);
19120        assert_eq!(q0.ordinal, 215);
19121    }
19122
19123    #[test]
19124    fn period_shift_saturates_on_overflow() {
19125        let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
19126        assert_eq!(p.shift(100).ordinal, i64::MAX);
19127        let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
19128        assert_eq!(p.shift(-100).ordinal, i64::MIN);
19129    }
19130
19131    #[test]
19132    fn period_diff_returns_period_count() {
19133        let a = Period::new(216, PeriodFreq::QUARTERLY);
19134        let b = Period::new(220, PeriodFreq::QUARTERLY);
19135        assert_eq!(b.diff(&a), Some(4));
19136        assert_eq!(a.diff(&b), Some(-4));
19137    }
19138
19139    #[test]
19140    fn period_diff_rejects_mismatched_freq() {
19141        let monthly = Period::new(100, PeriodFreq::Monthly);
19142        let quarterly = Period::new(100, PeriodFreq::QUARTERLY);
19143        assert_eq!(monthly.diff(&quarterly), None);
19144        assert_eq!(quarterly.diff(&monthly), None);
19145    }
19146
19147    #[test]
19148    fn period_cmp_same_freq_respects_ordinal_order() {
19149        use std::cmp::Ordering;
19150        let a = Period::new(10, PeriodFreq::Monthly);
19151        let b = Period::new(20, PeriodFreq::Monthly);
19152        assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
19153        assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
19154        assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
19155    }
19156
19157    #[test]
19158    fn period_cmp_cross_freq_returns_none() {
19159        let m = Period::new(1, PeriodFreq::Monthly);
19160        let q = Period::new(1, PeriodFreq::QUARTERLY);
19161        assert_eq!(m.cmp_same_freq(&q), None);
19162    }
19163
19164    #[test]
19165    fn period_arithmetic_matches_seeded_oracles_bac28() {
19166        use std::cmp::Ordering;
19167
19168        fn next(seed: &mut u64) -> u64 {
19169            *seed = seed
19170                .wrapping_mul(2862933555777941757)
19171                .wrapping_add(3037000493);
19172            *seed
19173        }
19174
19175        fn freq_for(raw: u64) -> PeriodFreq {
19176            // All TWELVE frequencies. This stopped at nine, so no property
19177            // test here ever generated a sub-second period.
19178            match raw % 12 {
19179                0 => PeriodFreq::ANNUAL,
19180                1 => PeriodFreq::QUARTERLY,
19181                2 => PeriodFreq::Monthly,
19182                3 => PeriodFreq::WEEKLY,
19183                4 => PeriodFreq::Daily,
19184                5 => PeriodFreq::Business,
19185                6 => PeriodFreq::Hourly,
19186                7 => PeriodFreq::Minutely,
19187                8 => PeriodFreq::Secondly,
19188                9 => PeriodFreq::Milliseconds,
19189                10 => PeriodFreq::Microseconds,
19190                _ => PeriodFreq::Nanoseconds,
19191            }
19192        }
19193
19194        fn different_freq(freq: PeriodFreq) -> PeriodFreq {
19195            match freq {
19196                PeriodFreq::Annual(_) => PeriodFreq::QUARTERLY,
19197                PeriodFreq::Quarterly(_) => PeriodFreq::Monthly,
19198                PeriodFreq::Monthly => PeriodFreq::WEEKLY,
19199                PeriodFreq::Weekly(_) => PeriodFreq::Daily,
19200                PeriodFreq::Daily => PeriodFreq::Business,
19201                PeriodFreq::Business => PeriodFreq::Hourly,
19202                PeriodFreq::Hourly => PeriodFreq::Minutely,
19203                PeriodFreq::Minutely => PeriodFreq::Secondly,
19204                // The cycle closes through the sub-second units, so every
19205                // frequency still maps to a DIFFERENT one — the only property
19206                // this helper owes its callers.
19207                PeriodFreq::Secondly => PeriodFreq::Milliseconds,
19208                PeriodFreq::Milliseconds => PeriodFreq::Microseconds,
19209                PeriodFreq::Microseconds => PeriodFreq::Nanoseconds,
19210                PeriodFreq::Nanoseconds => PeriodFreq::ANNUAL,
19211                PeriodFreq::Multiple(_) => freq.base(),
19212            }
19213        }
19214
19215        fn assert_period_case(
19216            case: usize,
19217            freq: PeriodFreq,
19218            ordinal: i64,
19219            shift_by: i64,
19220            other_ordinal: i64,
19221        ) {
19222            let period = Period::new(ordinal, freq);
19223            let shifted = period.shift(shift_by);
19224            assert_eq!(
19225                shifted.ordinal,
19226                ordinal.saturating_add(shift_by),
19227                "case {case}: shift ordinal"
19228            );
19229            assert_eq!(shifted.freq, freq, "case {case}: shift freq");
19230
19231            let same_freq_other = Period::new(other_ordinal, freq);
19232            assert_eq!(
19233                period.diff(&same_freq_other),
19234                Some(ordinal.saturating_sub(other_ordinal)),
19235                "case {case}: same-freq diff"
19236            );
19237            assert_eq!(
19238                period.cmp_same_freq(&same_freq_other),
19239                Some(ordinal.cmp(&other_ordinal)),
19240                "case {case}: same-freq cmp"
19241            );
19242
19243            let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
19244            assert_eq!(
19245                period.diff(&cross_freq_other),
19246                None,
19247                "case {case}: cross-freq diff"
19248            );
19249            assert_eq!(
19250                period.cmp_same_freq(&cross_freq_other),
19251                None,
19252                "case {case}: cross-freq cmp"
19253            );
19254        }
19255
19256        assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
19257        assert_period_case(
19258            usize::MAX - 1,
19259            PeriodFreq::Daily,
19260            i64::MIN + 2,
19261            -10,
19262            i64::MAX,
19263        );
19264        assert_eq!(
19265            Period::new(10, PeriodFreq::Monthly)
19266                .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
19267            Some(Ordering::Equal)
19268        );
19269
19270        let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
19271        for case in 0..260 {
19272            let freq = freq_for(next(&mut seed));
19273            let ordinal = match case % 53 {
19274                0 => i64::MAX - (next(&mut seed) % 8) as i64,
19275                1 => i64::MIN + (next(&mut seed) % 8) as i64,
19276                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
19277            };
19278            let shift_by = match case % 47 {
19279                0 => 512,
19280                1 => -512,
19281                _ => (next(&mut seed) % 4097) as i64 - 2048,
19282            };
19283            let other_ordinal = match case % 41 {
19284                0 => i64::MAX,
19285                1 => i64::MIN,
19286                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
19287            };
19288            assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
19289        }
19290    }
19291
19292    #[test]
19293    fn period_display_is_pandas_calendar_string() {
19294        // Ordinal 216 on the quarterly axis (1970Q1 == 0) is 1970 + 54y = 2024Q1.
19295        assert_eq!(
19296            Period::new(216, PeriodFreq::QUARTERLY).to_string(),
19297            "2024Q1"
19298        );
19299        // 1970 + 54 == 2024 on the annual axis.
19300        assert_eq!(Period::new(54, PeriodFreq::ANNUAL).to_string(), "2024");
19301        // 1970-01 == 0 -> 2024-03 is 54*12 + 2 == 650 months.
19302        assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
19303        // Day 0 == 1970-01-01; 2024-01-15.
19304        assert_eq!(
19305            Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
19306            "2024-01-15"
19307        );
19308        assert_eq!(
19309            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
19310            "NaT"
19311        );
19312    }
19313
19314    /// The two frequencies whose ordinal is NOT a day count. Both rendered
19315    /// through `civil_from_days` and came out decades wrong; the test above
19316    /// covered Y/Q/M/D and never touched either, which is how it survived.
19317    ///
19318    /// Every string is `str(pd.Period(ordinal=..., freq=...))` on live pandas
19319    /// 2.2.3, and FrankenPandas' own ordinals were confirmed to agree with
19320    /// pandas' at each sampled date before these were taken.
19321    #[test]
19322    fn weekly_and_business_periods_do_not_index_days() {
19323        // ⚠️ WEEKLY IS A RANGE, not a date: the ordinal counts WEEKS from the
19324        // Monday 1969-12-22, and pandas prints the seven days it spans.
19325        // Ordinal 2829 is the week of 2024-03-15 and used to render
19326        // "1977-09-30" — the result of reading a week count as a day count.
19327        for (ordinal, want) in [
19328            (0_i64, "1969-12-22/1969-12-28"),
19329            (1, "1969-12-29/1970-01-04"),
19330            (2829, "2024-03-11/2024-03-17"),
19331            (1540, "1999-06-28/1999-07-04"),
19332            (15237, "2261-12-30/2262-01-05"),
19333            // Pre-epoch, where Euclidean division matters.
19334            (-1, "1969-12-15/1969-12-21"),
19335            (-2829, "1915-10-04/1915-10-10"),
19336        ] {
19337            assert_eq!(
19338                Period::new(ordinal, PeriodFreq::WEEKLY).to_string(),
19339                want,
19340                "weekly ordinal {ordinal}"
19341            );
19342        }
19343
19344        // ⚠️ BUSINESS COUNTS BUSINESS DAYS — five per week — so consecutive
19345        // ordinals skip the weekend. Ordinal 14141 is 2024-03-15 and used to
19346        // render "2008-09-19".
19347        for (ordinal, want) in [
19348            (0_i64, "1970-01-01"), // a Thursday: the epoch anchors the cycle
19349            (1, "1970-01-02"),     // Friday
19350            (2, "1970-01-05"),     // Monday — the weekend is SKIPPED
19351            (3, "1970-01-06"),
19352            (4, "1970-01-07"),
19353            (5, "1970-01-08"),
19354            (14141, "2024-03-15"),
19355            (76179, "2262-01-01"),
19356            // A Sunday input rolls FORWARD when the ordinal is taken, so 7697
19357            // is the Monday 1999-07-05 rather than 1999-07-04.
19358            (7697, "1999-07-05"),
19359            (-1, "1969-12-31"),
19360            (-5, "1969-12-25"),
19361            (-6, "1969-12-24"),
19362        ] {
19363            assert_eq!(
19364                Period::new(ordinal, PeriodFreq::Business).to_string(),
19365                want,
19366                "business ordinal {ordinal}"
19367            );
19368        }
19369
19370        // Five business ordinals per seven calendar days, checked as a property
19371        // rather than as a table: the same arithmetic the forward map in
19372        // fp-index uses, read backwards.
19373        for ordinal in -400_i64..400 {
19374            let rendered = Period::new(ordinal, PeriodFreq::Business).to_string();
19375            let later = Period::new(ordinal + 5, PeriodFreq::Business).to_string();
19376            assert_ne!(rendered, later, "business ordinals must not repeat");
19377        }
19378
19379        assert_eq!(Period::new(i64::MIN, PeriodFreq::WEEKLY).to_string(), "NaT");
19380        assert_eq!(
19381            Period::new(i64::MIN, PeriodFreq::Business).to_string(),
19382            "NaT"
19383        );
19384    }
19385
19386    fn period_display_former_profile(period: &Period) -> String {
19387        let calendar = period.calendar_string();
19388        let mut rendered = String::new();
19389        rendered.push_str(&calendar);
19390        rendered
19391    }
19392
19393    fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
19394        use std::{hint::black_box, time::Instant};
19395
19396        let started = Instant::now();
19397        let mut checksum = 0usize;
19398        for period in periods {
19399            let rendered = render(black_box(period));
19400            checksum = checksum.wrapping_add(rendered.len());
19401            drop(black_box(rendered));
19402        }
19403        black_box(checksum);
19404        started.elapsed().as_nanos()
19405    }
19406
19407    #[test]
19408    #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
19409    fn profile_period_display_direct_sink_ab_6pqra() {
19410        const FREQUENCIES: [PeriodFreq; 9] = [
19411            PeriodFreq::ANNUAL,
19412            PeriodFreq::QUARTERLY,
19413            PeriodFreq::Monthly,
19414            PeriodFreq::WEEKLY,
19415            PeriodFreq::Daily,
19416            PeriodFreq::Business,
19417            PeriodFreq::Hourly,
19418            PeriodFreq::Minutely,
19419            PeriodFreq::Secondly,
19420        ];
19421        const SAMPLES: usize = 10;
19422
19423        let periods = (0..65_536)
19424            .map(|index| {
19425                let ordinal = if index % 4093 == 0 {
19426                    i64::MIN
19427                } else {
19428                    ((index as i64 * 7_919) % 4_000_001) - 2_000_000
19429                };
19430                Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
19431            })
19432            .collect::<Vec<_>>();
19433
19434        for period in &periods {
19435            assert_eq!(period_display_former_profile(period), period.to_string());
19436        }
19437
19438        for _ in 0..2 {
19439            measure_period_renderer(&periods, period_display_former_profile);
19440            measure_period_renderer(&periods, Period::to_string);
19441        }
19442
19443        let mut former_ns = Vec::with_capacity(SAMPLES);
19444        let mut public_ns = Vec::with_capacity(SAMPLES);
19445        for sample in 0..SAMPLES {
19446            if sample % 2 == 0 {
19447                former_ns.push(measure_period_renderer(
19448                    &periods,
19449                    period_display_former_profile,
19450                ));
19451                public_ns.push(measure_period_renderer(&periods, Period::to_string));
19452            } else {
19453                public_ns.push(measure_period_renderer(&periods, Period::to_string));
19454                former_ns.push(measure_period_renderer(
19455                    &periods,
19456                    period_display_former_profile,
19457                ));
19458            }
19459        }
19460        former_ns.sort_unstable();
19461        public_ns.sort_unstable();
19462        let former_p50 = former_ns[SAMPLES / 2];
19463        let public_p50 = public_ns[SAMPLES / 2];
19464        let former_p95 = former_ns[SAMPLES - 1];
19465        let public_p95 = public_ns[SAMPLES - 1];
19466        println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
19467        println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
19468        println!(
19469            "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
19470            former_p50 as f64 / public_p50 as f64
19471        );
19472        println!(
19473            "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
19474            former_p95 as f64 / public_p95 as f64
19475        );
19476    }
19477
19478    #[cfg(test)]
19479    fn fp_days(ymd: &str) -> i64 {
19480        Period::parse(ymd).expect("daily period").ordinal
19481    }
19482
19483    #[test]
19484    fn period_roundtrips_through_serde_json() {
19485        let p = Period::new(42, PeriodFreq::WEEKLY);
19486        let json = serde_json::to_string(&p).expect("serialize");
19487        let back: Period = serde_json::from_str(&json).expect("deserialize");
19488        assert_eq!(p, back);
19489    }
19490
19491    // ── period_range tests (br-frankenpandas-2jef — epoj Phase 2) ───────
19492
19493    use super::period_range;
19494
19495    #[test]
19496    fn period_range_zero_periods_is_empty() {
19497        let start = Period::new(216, PeriodFreq::QUARTERLY);
19498        assert!(period_range(start, 0).is_empty());
19499    }
19500
19501    #[test]
19502    fn period_range_single_period_returns_start_only() {
19503        let start = Period::new(216, PeriodFreq::QUARTERLY);
19504        let r = period_range(start, 1);
19505        assert_eq!(r.len(), 1);
19506        assert_eq!(r[0], start);
19507    }
19508
19509    #[test]
19510    fn period_range_increments_ordinal_by_one_per_step() {
19511        let start = Period::new(216, PeriodFreq::QUARTERLY);
19512        let r = period_range(start, 4);
19513        assert_eq!(r.len(), 4);
19514        assert_eq!(r[0].ordinal, 216);
19515        assert_eq!(r[1].ordinal, 217);
19516        assert_eq!(r[2].ordinal, 218);
19517        assert_eq!(r[3].ordinal, 219);
19518    }
19519
19520    #[test]
19521    fn period_range_preserves_frequency() {
19522        let start = Period::new(0, PeriodFreq::Monthly);
19523        let r = period_range(start, 12);
19524        assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
19525    }
19526
19527    #[test]
19528    fn period_range_negative_starting_ordinal_works() {
19529        // Ordinal axis is signed — pre-epoch periods are valid.
19530        let start = Period::new(-3, PeriodFreq::ANNUAL);
19531        let r = period_range(start, 5);
19532        assert_eq!(
19533            r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
19534            vec![-3, -2, -1, 0, 1]
19535        );
19536    }
19537
19538    #[test]
19539    fn period_range_large_n_does_not_panic() {
19540        // 1024 monthly periods — large enough to catch any allocation bug.
19541        let start = Period::new(0, PeriodFreq::Monthly);
19542        let r = period_range(start, 1024);
19543        assert_eq!(r.len(), 1024);
19544        assert_eq!(r[1023].ordinal, 1023);
19545    }
19546
19547    #[test]
19548    fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
19549        fn next(seed: &mut u64) -> u64 {
19550            *seed = seed
19551                .wrapping_mul(6364136223846793005)
19552                .wrapping_add(1442695040888963407);
19553            *seed
19554        }
19555
19556        fn freq_for(raw: u64) -> PeriodFreq {
19557            // All TWELVE frequencies. This stopped at nine, so no property
19558            // test here ever generated a sub-second period.
19559            match raw % 12 {
19560                0 => PeriodFreq::ANNUAL,
19561                1 => PeriodFreq::QUARTERLY,
19562                2 => PeriodFreq::Monthly,
19563                3 => PeriodFreq::WEEKLY,
19564                4 => PeriodFreq::Daily,
19565                5 => PeriodFreq::Business,
19566                6 => PeriodFreq::Hourly,
19567                7 => PeriodFreq::Minutely,
19568                8 => PeriodFreq::Secondly,
19569                9 => PeriodFreq::Milliseconds,
19570                10 => PeriodFreq::Microseconds,
19571                _ => PeriodFreq::Nanoseconds,
19572            }
19573        }
19574
19575        fn assert_oracle_case(case: usize, start: Period, periods: usize) {
19576            let got = period_range(start, periods);
19577            assert_eq!(got.len(), periods, "case {case}: length");
19578
19579            for (position, period) in got.iter().enumerate() {
19580                let expected_ordinal = start.ordinal.saturating_add(position as i64);
19581                assert_eq!(
19582                    period.ordinal, expected_ordinal,
19583                    "case {case}: ordinal at {position}"
19584                );
19585                assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
19586            }
19587        }
19588
19589        assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
19590        assert_oracle_case(
19591            usize::MAX - 1,
19592            Period::new(i64::MAX - 3, PeriodFreq::Daily),
19593            8,
19594        );
19595
19596        let mut seed = 0x9e21_0d1c_5eed_0421_u64;
19597        for case in 0..260 {
19598            let freq = freq_for(next(&mut seed));
19599            let periods = (next(&mut seed) % 80) as usize;
19600            let start_ordinal = if case % 37 == 0 {
19601                i64::MAX - 7
19602            } else {
19603                (next(&mut seed) % 20_001) as i64 - 10_000
19604            };
19605            assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
19606        }
19607    }
19608
19609    // ── interval_range tests (br-frankenpandas-xaom) ────────────────────
19610
19611    use super::{TypeError, interval_range, interval_range_by_periods, interval_range_by_step};
19612
19613    #[test]
19614    fn interval_range_by_periods_matches_pandas_default_case() {
19615        // pd.interval_range(0, 10, periods=5) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
19616        let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
19617        assert_eq!(bins.len(), 5);
19618        for (i, bin) in bins.iter().enumerate() {
19619            assert_eq!(bin.left, (i as f64) * 2.0);
19620            assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
19621            assert_eq!(bin.closed, IntervalClosed::Right);
19622        }
19623    }
19624
19625    #[test]
19626    fn interval_range_by_periods_final_edge_is_exact_end() {
19627        // Guards against accumulated float drift on the last right edge.
19628        let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
19629        assert_eq!(bins.last().unwrap().right, 1.0);
19630    }
19631
19632    #[test]
19633    fn interval_range_by_periods_zero_periods_is_empty() {
19634        assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
19635    }
19636
19637    #[test]
19638    fn interval_range_by_periods_reversed_range_is_empty() {
19639        // pandas: pd.interval_range(10, 0, periods=5) → IntervalIndex([]).
19640        assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
19641    }
19642
19643    #[test]
19644    fn interval_range_by_periods_preserves_closed_policy() {
19645        for closed in [
19646            IntervalClosed::Left,
19647            IntervalClosed::Right,
19648            IntervalClosed::Both,
19649            IntervalClosed::Neither,
19650        ] {
19651            let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
19652            assert!(bins.iter().all(|b| b.closed == closed));
19653        }
19654    }
19655
19656    #[test]
19657    fn interval_range_by_step_matches_pandas_default_case() {
19658        // pd.interval_range(0, 10, freq=2) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
19659        let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
19660        assert_eq!(bins.len(), 5);
19661        assert_eq!(bins[0].left, 0.0);
19662        assert_eq!(bins[4].right, 10.0);
19663    }
19664
19665    #[test]
19666    fn interval_range_by_step_rejects_non_positive_step() {
19667        assert!(matches!(
19668            interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
19669            Err(TypeError::InvalidIntervalStep { .. })
19670        ));
19671        assert!(matches!(
19672            interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
19673            Err(TypeError::InvalidIntervalStep { .. })
19674        ));
19675        assert!(matches!(
19676            interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
19677            Err(TypeError::InvalidIntervalStep { .. })
19678        ));
19679        assert!(matches!(
19680            interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
19681            Err(TypeError::InvalidIntervalStep { .. })
19682        ));
19683    }
19684
19685    #[test]
19686    fn interval_range_by_step_rejects_non_dividing_step() {
19687        // pandas: pd.interval_range(0, 10, freq=3) → ValueError
19688        // (span=10 not divisible by step=3). Reject with IntervalStepDoesNotDivide.
19689        assert!(matches!(
19690            interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
19691            Err(TypeError::IntervalStepDoesNotDivide { .. })
19692        ));
19693    }
19694
19695    #[test]
19696    fn interval_range_by_step_reversed_range_is_empty() {
19697        let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
19698        assert!(bins.is_empty());
19699    }
19700
19701    #[test]
19702    fn interval_range_by_step_degenerate_zero_span_is_empty() {
19703        let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
19704        assert!(bins.is_empty());
19705    }
19706
19707    #[test]
19708    fn interval_range_by_step_accepts_float_step_within_tolerance() {
19709        // step=0.1 ten times == 1.0 but float arithmetic produces 0.9999...
19710        let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
19711        assert_eq!(bins.len(), 10);
19712        assert_eq!(bins.last().unwrap().right, 1.0);
19713    }
19714
19715    #[test]
19716    fn interval_range_unified_api_tests() {
19717        // Case 1: start, end, periods
19718        let r1 = interval_range(Some(0.0), Some(10.0), Some(5), None, None).expect("ok");
19719        assert_eq!(r1.len(), 5);
19720        assert_eq!(r1[0].left, 0.0);
19721        assert_eq!(r1[0].right, 2.0);
19722        assert_eq!(r1[4].right, 10.0);
19723        assert_eq!(r1[0].closed, IntervalClosed::Right);
19724
19725        // Case 2: start, end, freq
19726        let r2 = interval_range(Some(0.0), Some(10.0), None, Some(2.0), None).expect("ok");
19727        assert_eq!(r2.len(), 5);
19728        assert_eq!(r2[0].left, 0.0);
19729        assert_eq!(r2[4].right, 10.0);
19730
19731        // Case 3: start, periods, freq
19732        let r3 = interval_range(
19733            Some(0.0),
19734            None,
19735            Some(5),
19736            Some(2.0),
19737            Some(IntervalClosed::Both),
19738        )
19739        .expect("ok");
19740        assert_eq!(r3.len(), 5);
19741        assert_eq!(r3[0].left, 0.0);
19742        assert_eq!(r3[4].right, 10.0);
19743        assert_eq!(r3[0].closed, IntervalClosed::Both);
19744
19745        // Case 4: end, periods, freq
19746        let r4 = interval_range(
19747            None,
19748            Some(10.0),
19749            Some(5),
19750            Some(2.0),
19751            Some(IntervalClosed::Left),
19752        )
19753        .expect("ok");
19754        assert_eq!(r4.len(), 5);
19755        assert_eq!(r4[0].left, 0.0);
19756        assert_eq!(r4[4].right, 10.0);
19757        assert_eq!(r4[0].closed, IntervalClosed::Left);
19758
19759        // Errors: not exactly 3 arguments
19760        assert!(matches!(
19761            interval_range(None, None, None, None, None),
19762            Err(TypeError::IntervalRangeParameterCount)
19763        ));
19764        assert!(matches!(
19765            interval_range(Some(0.0), Some(10.0), None, None, None),
19766            Err(TypeError::IntervalRangeParameterCount)
19767        ));
19768        assert!(matches!(
19769            interval_range(Some(0.0), Some(10.0), Some(5), Some(2.0), None),
19770            Err(TypeError::IntervalRangeParameterCount)
19771        ));
19772
19773        // Errors: non-positive freq
19774        assert!(matches!(
19775            interval_range(Some(0.0), None, Some(5), Some(-1.0), None),
19776            Err(TypeError::InvalidIntervalStep { .. })
19777        ));
19778        assert!(matches!(
19779            interval_range(Some(0.0), None, Some(5), Some(0.0), None),
19780            Err(TypeError::InvalidIntervalStep { .. })
19781        ));
19782    }
19783
19784    #[test]
19785    fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
19786        // Differential vs independent interval edge oracles
19787        // (br-frankenpandas-t9ozf). Seeded LCG, no mocks.
19788        fn next(seed: &mut u64) -> u64 {
19789            *seed = seed
19790                .wrapping_mul(2862933555777941757)
19791                .wrapping_add(3037000493);
19792            *seed
19793        }
19794
19795        fn closed_for(raw: u64) -> IntervalClosed {
19796            match raw % 4 {
19797                0 => IntervalClosed::Left,
19798                1 => IntervalClosed::Right,
19799                2 => IntervalClosed::Both,
19800                _ => IntervalClosed::Neither,
19801            }
19802        }
19803
19804        fn assert_interval(
19805            case: usize,
19806            kind: &str,
19807            pos: usize,
19808            actual: &Interval,
19809            expected: &Interval,
19810        ) {
19811            assert!(
19812                (actual.left - expected.left).abs() < 1e-12,
19813                "case={case} kind={kind} pos={pos}: expected left {}, got {}",
19814                expected.left,
19815                actual.left
19816            );
19817            assert!(
19818                (actual.right - expected.right).abs() < 1e-12,
19819                "case={case} kind={kind} pos={pos}: expected right {}, got {}",
19820                expected.right,
19821                actual.right
19822            );
19823            assert_eq!(
19824                actual.closed, expected.closed,
19825                "case={case} kind={kind} pos={pos}: closed mismatch"
19826            );
19827        }
19828
19829        fn expected_by_periods(
19830            start: f64,
19831            end: f64,
19832            periods: usize,
19833            closed: IntervalClosed,
19834        ) -> Vec<Interval> {
19835            if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
19836                return Vec::new();
19837            }
19838            let step = (end - start) / periods as f64;
19839            (0..periods)
19840                .map(|pos| {
19841                    let left = start + step * pos as f64;
19842                    let right = if pos + 1 == periods {
19843                        end
19844                    } else {
19845                        start + step * (pos + 1) as f64
19846                    };
19847                    Interval::new(left, right, closed)
19848                })
19849                .collect()
19850        }
19851
19852        fn expected_by_step(
19853            start: f64,
19854            end: f64,
19855            step: f64,
19856            closed: IntervalClosed,
19857        ) -> Vec<Interval> {
19858            if start >= end {
19859                return Vec::new();
19860            }
19861            let count = ((end - start) / step).round() as usize;
19862            (0..count)
19863                .map(|pos| {
19864                    let left = start + step * pos as f64;
19865                    let right = if pos + 1 == count {
19866                        end
19867                    } else {
19868                        start + step * (pos + 1) as f64
19869                    };
19870                    Interval::new(left, right, closed)
19871                })
19872                .collect()
19873        }
19874
19875        assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
19876        assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
19877        assert!(
19878            interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
19879                .expect("zero span")
19880                .is_empty()
19881        );
19882
19883        let mut seed = 0x171e_7a11_c0de_5eed_u64;
19884        for case in 0..220 {
19885            let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
19886            let periods = (next(&mut seed) % 24 + 1) as usize;
19887            let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
19888            let end = start + width;
19889            let closed = closed_for(next(&mut seed));
19890
19891            let actual = interval_range_by_periods(start, end, periods, closed);
19892            let expected = expected_by_periods(start, end, periods, closed);
19893            assert_eq!(
19894                actual.len(),
19895                expected.len(),
19896                "case={case} periods: length mismatch"
19897            );
19898            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
19899                assert_interval(case, "periods", pos, actual, expected);
19900            }
19901
19902            let step_count = (next(&mut seed) % 20 + 1) as usize;
19903            let step = (next(&mut seed) % 25 + 1) as f64;
19904            let step_end = start + step * step_count as f64;
19905            let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
19906            let expected = expected_by_step(start, step_end, step, closed);
19907            assert_eq!(
19908                actual.len(),
19909                expected.len(),
19910                "case={case} step: length mismatch"
19911            );
19912            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
19913                assert_interval(case, "step", pos, actual, expected);
19914            }
19915        }
19916    }
19917
19918    // ── Timedelta arithmetic tests (br-frankenpandas-4r56 Phase 1) ──────
19919
19920    use super::Timedelta;
19921
19922    #[test]
19923    fn timedelta_add_sums_non_nat() {
19924        let one_hour = Timedelta::NANOS_PER_HOUR;
19925        let one_day = Timedelta::NANOS_PER_DAY;
19926        assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
19927    }
19928
19929    #[test]
19930    fn timedelta_add_propagates_nat() {
19931        assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
19932        assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
19933        assert_eq!(
19934            Timedelta::add(Timedelta::NAT, Timedelta::NAT),
19935            Timedelta::NAT
19936        );
19937    }
19938
19939    #[test]
19940    fn timedelta_add_returns_nat_on_overflow() {
19941        // CORRECTED br-frankenpandas-lgyy8. This test previously asserted
19942        // `add(i64::MAX - 10, 100) == i64::MAX`, i.e. that positive overflow
19943        // yields a finite, plausible duration. Live pandas 2.2.3 raises
19944        // OverflowError for `pd.Timedelta.max + pd.Timedelta('1ns')` and never
19945        // returns a fabricated finite value, so the old expectation encoded a
19946        // fail-open bug. Overflow is now NaT in BOTH directions.
19947        assert_eq!(Timedelta::add(i64::MAX - 10, 100), Timedelta::NAT);
19948        // Negative side is unchanged: i64::MIN IS the NaT sentinel, so this
19949        // already surfaced as missing (pandas: Timedelta.min + -1ns -> NaT).
19950        assert_eq!(Timedelta::add(i64::MIN + 10, -100), Timedelta::NAT);
19951    }
19952
19953    #[test]
19954    fn timedelta_sub_subtracts_non_nat() {
19955        let one_hour = Timedelta::NANOS_PER_HOUR;
19956        assert_eq!(
19957            Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
19958            one_hour - Timedelta::NANOS_PER_MIN
19959        );
19960    }
19961
19962    #[test]
19963    fn timedelta_sub_propagates_nat() {
19964        assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
19965        assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
19966    }
19967
19968    #[test]
19969    fn timedelta_neg_flips_sign_non_nat() {
19970        assert_eq!(Timedelta::neg(5), -5);
19971        assert_eq!(Timedelta::neg(-5), 5);
19972        assert_eq!(Timedelta::neg(0), 0);
19973    }
19974
19975    #[test]
19976    fn timedelta_neg_preserves_nat() {
19977        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
19978    }
19979
19980    #[test]
19981    fn timedelta_abs_returns_magnitude() {
19982        assert_eq!(Timedelta::abs(-5), 5);
19983        assert_eq!(Timedelta::abs(5), 5);
19984        assert_eq!(Timedelta::abs(0), 0);
19985        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
19986    }
19987
19988    #[test]
19989    fn neg_and_abs_at_the_representable_floor_are_not_overflow_fyr1z() {
19990        // br-frankenpandas-fyr1z. Until this test existed, `neg`/`abs` were
19991        // only exercised at ±5 and 0, and the doc comment on `neg` asserted
19992        // the OPPOSITE of pandas: "pandas: `-pd.Timedelta.min` is NaT since
19993        // min == -max - 1 cannot be negated". Both halves are false, so an
19994        // implementer trusting the comment could have replaced
19995        // `saturating_neg()` with a NaT arm and broken parity without failing
19996        // a single existing assertion. Measured against the installed oracle,
19997        // pandas 2.2.3:
19998        //   pd.Timedelta.min.value                 == -9223372036854775807
19999        //   -pd.Timedelta.min                      -> Timedelta.max (NOT NaT)
20000        //   abs(pd.Timedelta.min)                  -> Timedelta.max (NOT NaT)
20001        //   -Series([Timedelta.min])               -> [Timedelta.max]
20002        //   Series([Timedelta.min]).abs()          -> [Timedelta.max]
20003        //
20004        // The reason there is no overflow to handle: pandas' representable
20005        // range is symmetric about zero because i64::MIN is spent on the NaT
20006        // sentinel, exactly as it is here.
20007        const MAX: i64 = i64::MAX;
20008        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
20009
20010        // The range really is symmetric — this is the premise the old comment
20011        // denied, and everything below follows from it.
20012        assert_eq!(MIN_OK, -MAX);
20013        assert_eq!(Timedelta::NAT, i64::MIN);
20014
20015        // The cases the false comment would have turned into NaT.
20016        assert_eq!(Timedelta::neg(MIN_OK), MAX);
20017        assert_eq!(Timedelta::neg(MAX), MIN_OK);
20018        assert_eq!(Timedelta::abs(MIN_OK), MAX);
20019        assert_eq!(Timedelta::abs(MAX), MAX);
20020
20021        // Round-tripping the floor must be exact, not sticky at a saturation
20022        // clamp: a `saturating_*` impl that ever clamped would land on
20023        // i64::MIN here and read as NaT.
20024        assert_eq!(Timedelta::neg(Timedelta::neg(MIN_OK)), MIN_OK);
20025        assert_ne!(Timedelta::neg(MIN_OK), Timedelta::NAT);
20026        assert_ne!(Timedelta::abs(MIN_OK), Timedelta::NAT);
20027
20028        // NaT itself is still the one input that stays NaT — the guard, not a
20029        // saturation branch, is what handles it.
20030        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
20031        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
20032    }
20033
20034    #[test]
20035    fn overflow_divergence_surface_is_only_where_pandas_refuses_fyr1z() {
20036        // br-frankenpandas-fyr1z, the decision bead for DISC-018. The bead was
20037        // filed on the premise "pandas raises; FP returns NaT", which would
20038        // make EVERY overflow a divergence. Probing live pandas 2.2.3 refutes
20039        // that: on the vectorized surface — the one users actually meet —
20040        // pandas returns NaT itself in several of these cases, so FP already
20041        // agrees there and a blanket "STRICT raises" mode would INTRODUCE
20042        // divergence rather than remove it.
20043        //
20044        // This test pins the agreement half. It is the negative control for
20045        // the divergence half already pinned by
20046        // `arithmetic_overflow_never_fabricates_a_finite_value_lgyy8`.
20047        const MAX: i64 = i64::MAX;
20048        const MIN_OK: i64 = i64::MIN + 1;
20049
20050        // ── AGREEMENT: pandas returns NaT here too, measured ───────────────
20051        // Series([Timedelta.max]) / 0    -> [NaT]
20052        // Series([Timedelta.max]) // 0   -> [NaT]
20053        // Series([Timedelta.max]) / 0.0  -> [NaT]
20054        assert_eq!(Timedelta::div_scalar(MAX, 0), Timedelta::NAT);
20055        assert_eq!(Timedelta::div_scalar(MIN_OK, 0), Timedelta::NAT);
20056        assert_eq!(Timedelta::div_scalar(0, 0), Timedelta::NAT);
20057
20058        // Series([Timedelta.min]) - Timedelta('1ns') -> [NaT], because the
20059        // result lands exactly on the i64::MIN sentinel. FP and pandas agree
20060        // — but only by SENTINEL COLLISION, not by policy. One further step
20061        // (`min - 2ns`) is `OverflowError: Overflow in int64 addition` in
20062        // pandas while FP still says NaT, which is the real divergence. A
20063        // test that only checked the 1ns case would therefore prove nothing;
20064        // both depths are asserted so the pair stays honest.
20065        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT); // pandas: NaT
20066        assert_eq!(Timedelta::sub(MIN_OK, 2), Timedelta::NAT); // pandas: RAISES
20067        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
20068        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(2).is_nat());
20069
20070        // ── DIVERGENCE: pandas refuses, FP surfaces NaT ────────────────────
20071        // Kept adjacent to the agreement cases so the boundary between the
20072        // two halves is visible in one place; DISC-018 is the prose record.
20073        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
20074        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
20075        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
20076
20077        // ── CONTROL: representable results are untouched by any of this ────
20078        assert_eq!(Timedelta::div_scalar(MAX, 1), MAX);
20079        assert_eq!(Timedelta::div_scalar(-100, 3), -34); // floor, not trunc
20080        assert_eq!(Timedelta::div_scalar(100, -3), -34);
20081        assert_eq!(Timedelta::sub(MIN_OK + 2, 1), MIN_OK + 1);
20082    }
20083
20084    #[test]
20085    fn timedelta_mul_scalar_scales() {
20086        let three_hours = Timedelta::NANOS_PER_HOUR * 3;
20087        assert_eq!(
20088            Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
20089            three_hours
20090        );
20091        assert_eq!(Timedelta::mul_scalar(100, 0), 0);
20092        assert_eq!(Timedelta::mul_scalar(100, -2), -200);
20093    }
20094
20095    #[test]
20096    fn timedelta_mul_scalar_returns_nat_on_overflow() {
20097        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX.
20098        // pandas `pd.Timedelta.max * 2` raises OverflowError.
20099        assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), Timedelta::NAT);
20100        assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), Timedelta::NAT);
20101    }
20102
20103    #[test]
20104    fn from_unit_nan_is_nat_and_overflow_is_err_8v92m() {
20105        use super::TimedeltaError;
20106
20107        // br-frankenpandas-8v92m. Rust's float->int `as` maps NaN to 0 and
20108        // saturates infinities, so the unguarded
20109        //     Ok((value * multiplier as f64).round() as i64)
20110        // failed OPEN twice: NaN became a ZERO DURATION, and inf/1e30 became a
20111        // finite plausible ~106751-day duration. Live pandas 2.2.3:
20112        //   pd.Timedelta(nan, unit='s')   -> NaT
20113        //   pd.Timedelta(inf, unit='s')   -> OutOfBoundsTimedelta
20114        //                                    "Cannot cast inf from s to 'ns' without overflow."
20115        //   pd.Timedelta(1e30, unit='s')  -> OutOfBoundsTimedelta
20116        //   pd.Timedelta(1.5, unit='s')   -> Timedelta('0 days 00:00:01.5')  <- must NOT change
20117        // The guard is copied from the two siblings that already had it
20118        // (br-frankenpandas-zw3mg), which is why `parse` behaviour is pinned
20119        // below too: all three copies must now agree.
20120
20121        // ── NaN -> NaT, NOT zero. This is the load-bearing case: an impl that
20122        // returns Ok(0) fails, and so does one that returns Err, because
20123        // pandas gives NaT rather than raising.
20124        assert_eq!(Timedelta::from_unit(f64::NAN, "s"), Ok(Timedelta::NAT));
20125        assert_ne!(Timedelta::from_unit(f64::NAN, "s"), Ok(0));
20126        assert_eq!(Timedelta::from_unit(f64::NAN, "D"), Ok(Timedelta::NAT));
20127
20128        // ── non-finite / out-of-range -> Overflow, not a saturated duration.
20129        assert_eq!(
20130            Timedelta::from_unit(f64::INFINITY, "s"),
20131            Err(TimedeltaError::Overflow)
20132        );
20133        assert_eq!(
20134            Timedelta::from_unit(f64::NEG_INFINITY, "s"),
20135            Err(TimedeltaError::Overflow)
20136        );
20137        assert_eq!(
20138            Timedelta::from_unit(1e30, "s"),
20139            Err(TimedeltaError::Overflow)
20140        );
20141        assert_eq!(
20142            Timedelta::from_unit(1e30, "D"),
20143            Err(TimedeltaError::Overflow)
20144        );
20145
20146        // ── CONTROL: ordinary values must be untouched, bit-for-bit. An
20147        // over-eager guard that rejected anything large would fail here.
20148        assert_eq!(Timedelta::from_unit(1.5, "s"), Ok(1_500_000_000));
20149        assert_eq!(Timedelta::from_unit(0.0, "s"), Ok(0));
20150        assert_eq!(Timedelta::from_unit(-2.5, "s"), Ok(-2_500_000_000));
20151        assert_eq!(Timedelta::from_unit(1.0, "D"), Ok(Timedelta::NANOS_PER_DAY));
20152        assert_eq!(
20153            Timedelta::from_unit(3.0, "h"),
20154            Ok(3 * Timedelta::NANOS_PER_HOUR)
20155        );
20156        // Just inside the representable range still returns its exact product,
20157        // so the boundary is pinned from the accepting side as well.
20158        let big_days = 100_000.0_f64;
20159        let expected = (big_days * Timedelta::NANOS_PER_DAY as f64).round() as i64;
20160        assert_eq!(Timedelta::from_unit(big_days, "D"), Ok(expected));
20161        assert!(expected > 0, "fixture must stay in range to be a control");
20162
20163        // ── an unknown unit is still InvalidFormat, NOT Overflow — the unit
20164        // check must keep running before the range check.
20165        assert!(matches!(
20166            Timedelta::from_unit(1.0, "nonsense-unit"),
20167            Err(TimedeltaError::InvalidFormat(_))
20168        ));
20169        assert!(matches!(
20170            Timedelta::from_unit(f64::NAN, "nonsense-unit"),
20171            Err(TimedeltaError::InvalidFormat(_)),
20172        ));
20173
20174        // ── the already-guarded sibling is unchanged. NOTE the input shape:
20175        // the compound lexer accepts only digits, '.' and '-', so scientific
20176        // notation is an InvalidFormat, not an Overflow — the overflow case
20177        // needs a long decimal literal (this is zw3mg's own fixture).
20178        let huge = format!("{} days", "9".repeat(18));
20179        assert!(matches!(
20180            Timedelta::parse(&huge),
20181            Err(TimedeltaError::Overflow)
20182        ));
20183        assert!(matches!(
20184            Timedelta::parse("1e100 days"),
20185            Err(TimedeltaError::InvalidFormat(_))
20186        ));
20187    }
20188
20189    #[test]
20190    fn rounding_and_ms_us_overflow_never_fabricates_a_finite_value_kyd16() {
20191        // br-frankenpandas-kyd16, the sibling sweep of lgyy8. Three defects:
20192        //   (1) Timedelta::round used UNCHECKED `(quotient + 1) * unit_nanos`
20193        //       on the round-up branch — debug PANIC, release WRAP to a
20194        //       large-negative duration.
20195        //   (2) Timedelta::floor/ceil and Timestamp::ceil_to/round_to
20196        //       saturated to i64::MAX, a finite plausible duration / ~year-2262
20197        //       instant handed back as real data — while their own sibling
20198        //       Timestamp::floor_to was ALREADY checked.
20199        //   (3) Timestamp::from_millis/from_micros saturated likewise, while
20200        //       their neighbour `fromtimestamp` already returned NaT.
20201        // Live pandas 2.2.3 raises on every one of these and names the cause:
20202        //   Timestamp.max.ceil('D')/round('D') -> OutOfBoundsDatetime
20203        //       "Cannot round 2262-04-11 23:47:16.854775807 to freq=<Day> without overflow"
20204        //   Timestamp.min.floor('D')           -> OutOfBoundsDatetime (same)
20205        //   Timedelta.max.ceil('D')/round('D') -> OutOfBoundsTimedelta (same shape)
20206        //   Timedelta.min.floor('D')           -> OutOfBoundsTimedelta (same)
20207        // ...but Timestamp.max.floor('D') is an ordinary in-range answer and
20208        // must NOT change. Both halves are asserted below.
20209        const MAX: i64 = i64::MAX;
20210        const MIN_OK: i64 = i64::MIN + 1;
20211        const DAY: i64 = Timedelta::NANOS_PER_DAY;
20212
20213        // ── (1) round(): must not panic, must not wrap negative ────────────
20214        let rounded = Timedelta::round(MAX, "D");
20215        assert_eq!(
20216            rounded,
20217            Timedelta::NAT,
20218            "rounding i64::MAX up to a whole day overflows; the old unchecked \
20219             multiply panicked in debug and wrapped in release"
20220        );
20221        // The wrap signature specifically: a positive input must never round
20222        // to a negative duration. This fails for a wrapping impl even if the
20223        // debug panic is somehow avoided.
20224        assert!(
20225            rounded == Timedelta::NAT || rounded > 0,
20226            "a positive duration must never round to a negative one"
20227        );
20228        assert_eq!(Timedelta::round(MIN_OK, "D"), Timedelta::NAT);
20229
20230        // ── (2) floor/ceil overflow -> NaT, not a fabricated finite value ──
20231        assert_eq!(Timedelta::ceil(MAX, "D"), Timedelta::NAT);
20232        assert_eq!(Timedelta::floor(MIN_OK, "D"), Timedelta::NAT);
20233        assert!(Timestamp::from_nanos(MAX).ceil_to(DAY).is_nat());
20234        assert!(Timestamp::from_nanos(MAX).round_to(DAY).is_nat());
20235        assert!(Timestamp::from_nanos(MIN_OK).floor_to(DAY).is_nat());
20236        assert!(Timestamp::from_nanos(MIN_OK).round_to(DAY).is_nat());
20237
20238        // ── (3) ms/us constructors out of range -> NaT ─────────────────────
20239        assert!(Timestamp::from_millis(MAX, None).is_nat());
20240        assert!(Timestamp::from_millis(MIN_OK, None).is_nat());
20241        assert!(Timestamp::from_micros(MAX, None).is_nat());
20242        assert!(Timestamp::from_micros(MIN_OK, Some("US/Eastern")).is_nat());
20243
20244        // ── CONTROL: in-range rounding is untouched. An implementation that
20245        // NaT'd too eagerly — or that treated "near the limit" as overflow —
20246        // fails every assertion below.
20247        //
20248        // Timestamp.max.floor('D') is the exact case pandas ANSWERS rather
20249        // than raising, so it pins the boundary from the other side.
20250        let max_floor = Timestamp::from_nanos(MAX).floor_to(DAY);
20251        assert!(!max_floor.is_nat(), "Timestamp.max.floor(D) must succeed");
20252        assert_eq!(max_floor.nanos, (MAX / DAY) * DAY);
20253        assert_eq!(Timedelta::floor(MAX, "D"), (MAX / DAY) * DAY);
20254        assert_eq!(
20255            Timedelta::ceil(MIN_OK, "D"),
20256            (MIN_OK.div_euclid(DAY) + 1) * DAY
20257        );
20258
20259        // Ordinary values, bit-for-bit.
20260        let hour = Timedelta::NANOS_PER_HOUR;
20261        assert_eq!(Timedelta::floor(90 * 60 * 1_000_000_000, "h"), hour);
20262        assert_eq!(Timedelta::ceil(90 * 60 * 1_000_000_000, "h"), 2 * hour);
20263        assert_eq!(Timedelta::round(90 * 60 * 1_000_000_000, "h"), 2 * hour);
20264        assert_eq!(Timedelta::round(-90 * 60 * 1_000_000_000, "h"), -2 * hour);
20265        assert_eq!(Timedelta::round(29 * 60 * 1_000_000_000, "h"), 0);
20266        assert_eq!(Timestamp::from_millis(1_500, None).nanos, 1_500_000_000);
20267        assert_eq!(Timestamp::from_micros(-2_000, None).nanos, -2_000_000);
20268        assert_eq!(
20269            Timestamp::from_nanos(hour + 1).floor_to(hour).nanos,
20270            hour,
20271            "in-range floor unchanged"
20272        );
20273        assert_eq!(
20274            Timestamp::from_nanos(hour + 1).ceil_to(hour).nanos,
20275            2 * hour,
20276            "in-range ceil unchanged"
20277        );
20278
20279        // NaT / degenerate-unit inputs unchanged.
20280        assert_eq!(Timedelta::round(Timedelta::NAT, "D"), Timedelta::NAT);
20281        assert_eq!(Timedelta::floor(Timedelta::NAT, "D"), Timedelta::NAT);
20282        assert_eq!(Timedelta::ceil(1_000, "nonsense-unit"), Timedelta::NAT);
20283        assert!(Timestamp::nat().ceil_to(DAY).is_nat());
20284        assert!(Timestamp::from_nanos(0).round_to(0).is_nat());
20285        // A non-overflowing round still carries its zone.
20286        assert_eq!(
20287            Timestamp::from_nanos_tz(hour + 1, "US/Eastern")
20288                .ceil_to(hour)
20289                .tz
20290                .as_deref(),
20291            Some("US/Eastern")
20292        );
20293    }
20294
20295    #[test]
20296    fn timedelta_mul_scalar_propagates_nat() {
20297        assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
20298    }
20299
20300    #[test]
20301    fn arithmetic_overflow_never_fabricates_a_finite_value_lgyy8() {
20302        // br-frankenpandas-lgyy8. The bug: these six helpers used
20303        // `saturating_*`, so POSITIVE overflow returned i64::MAX — a valid,
20304        // finite, plausible duration / ~year-2262 instant — as if it were real
20305        // data. (Negative overflow landed on i64::MIN, which IS the NaT
20306        // sentinel, so that direction already surfaced as missing.) Live
20307        // pandas 2.2.3 never returns a fabricated finite value on overflow in
20308        // either direction, scalar or vectorized:
20309        //   pd.Timedelta.max + Timedelta('1ns')  -> OverflowError
20310        //   pd.Timestamp.max + Timedelta('1ns')  -> OutOfBoundsDatetime
20311        //   pd.Timestamp.min - pd.Timestamp.max  -> OutOfBoundsDatetime
20312        //   pd.Timedelta.max * 2                 -> OverflowError
20313        //   pd.Timedelta.min + Timedelta('-1ns') -> NaT
20314        //
20315        // Every assertion below is a case a saturating implementation FAILS.
20316        const MAX: i64 = i64::MAX;
20317        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
20318
20319        // ── positive overflow: the actual bug ──────────────────────────────
20320        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
20321        assert_eq!(Timedelta::add(MAX - 10, 100), Timedelta::NAT);
20322        assert_eq!(Timedelta::sub(MAX, -1), Timedelta::NAT);
20323        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
20324        assert_eq!(Timedelta::mul_scalar(MAX / 2 + 2, 2), Timedelta::NAT);
20325        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
20326        assert!(Timestamp::from_nanos(MAX).sub_timedelta(-1).is_nat());
20327        // Timestamp.max - Timestamp.min: the true difference is ~2^64, far
20328        // outside i64. Saturation returned MAX (a ~292-year duration presented
20329        // as the real answer); pandas raises OutOfBoundsDatetime.
20330        assert_eq!(
20331            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(MIN_OK)),
20332            Timedelta::NAT
20333        );
20334
20335        // ── negative overflow: unchanged, still NaT ────────────────────────
20336        assert_eq!(Timedelta::add(MIN_OK, -1), Timedelta::NAT);
20337        assert_eq!(Timedelta::add(MIN_OK, -2), Timedelta::NAT);
20338        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
20339        assert_eq!(Timedelta::mul_scalar(MIN_OK, 2), Timedelta::NAT);
20340        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
20341        assert!(Timestamp::from_nanos(MIN_OK).add_timedelta(-1).is_nat());
20342        assert_eq!(
20343            Timestamp::from_nanos(MIN_OK).sub_timestamp(&Timestamp::from_nanos(MAX)),
20344            Timedelta::NAT
20345        );
20346
20347        // ── the boundary: the largest REPRESENTABLE results must still be
20348        // returned exactly. This is what stops the fix from being bought with
20349        // an over-eager NaT that swallows valid arithmetic — an implementation
20350        // that NaT'd one step early fails here, as does one that NaT'd on any
20351        // operand near the limits.
20352        assert_eq!(Timedelta::add(MAX - 1, 1), MAX);
20353        assert_eq!(Timedelta::add(MAX, 0), MAX);
20354        assert_eq!(Timedelta::sub(MAX, 1), MAX - 1);
20355        assert_eq!(Timedelta::add(MIN_OK + 1, -1), MIN_OK);
20356        assert_eq!(Timedelta::mul_scalar(MAX / 2, 2), (MAX / 2) * 2);
20357        assert_eq!(Timedelta::mul_scalar(MIN_OK, 1), MIN_OK);
20358        assert_eq!(Timestamp::from_nanos(MAX - 1).add_timedelta(1).nanos, MAX);
20359        assert_eq!(
20360            Timestamp::from_nanos(MIN_OK + 1).sub_timedelta(1).nanos,
20361            MIN_OK
20362        );
20363        assert_eq!(
20364            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(0)),
20365            MAX
20366        );
20367        // Ordinary values are untouched bit-for-bit.
20368        assert_eq!(Timedelta::add(1_000, 2_345), 3_345);
20369        assert_eq!(Timedelta::sub(1_000, 2_345), -1_345);
20370        assert_eq!(Timedelta::mul_scalar(-7, 6), -42);
20371
20372        // ── a result landing EXACTLY on i64::MIN is representable, but i64::MIN
20373        // IS the NaT sentinel, so it must read as NaT rather than as the most
20374        // negative duration. pandas agrees: Timedelta.min + -1ns -> NaT. Note
20375        // `MIN_OK - 1 == i64::MIN` does not overflow, so this case survives the
20376        // switch from saturating_* to checked_* only because the sentinel and
20377        // the clamp coincide — assert it explicitly rather than by accident.
20378        assert_eq!(MIN_OK - 1, i64::MIN);
20379        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
20380        assert_eq!(Timedelta::add(MIN_OK, 0), MIN_OK);
20381
20382        // ── NaT operands still propagate, and tz no longer rides along with a
20383        // fabricated instant: an overflowed Timestamp is the canonical NaT.
20384        assert!(Timestamp::nat().add_timedelta(1).is_nat());
20385        assert!(
20386            Timestamp::from_nanos(0)
20387                .add_timedelta(Timedelta::NAT)
20388                .is_nat()
20389        );
20390        let tzed = Timestamp::from_nanos_tz(MAX, "US/Eastern");
20391        let overflowed = tzed.add_timedelta(1);
20392        assert!(overflowed.is_nat());
20393        assert_eq!(overflowed.tz, None, "an overflow NaT carries no zone");
20394        // ...while a NON-overflowing shift still preserves the zone.
20395        assert_eq!(
20396            Timestamp::from_nanos_tz(0, "US/Eastern")
20397                .add_timedelta(Timedelta::NANOS_PER_DAY)
20398                .tz
20399                .as_deref(),
20400            Some("US/Eastern")
20401        );
20402    }
20403
20404    #[test]
20405    fn timedelta_div_scalar_floor_divides() {
20406        // Floor division (matches Python / pandas): -100 // 3 == -34, not -33.
20407        assert_eq!(Timedelta::div_scalar(100, 3), 33);
20408        assert_eq!(Timedelta::div_scalar(-100, 3), -34);
20409        assert_eq!(Timedelta::div_scalar(100, -3), -34);
20410        assert_eq!(Timedelta::div_scalar(-100, -3), 33);
20411    }
20412
20413    #[test]
20414    fn timedelta_div_scalar_zero_divisor_returns_nat() {
20415        assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
20416    }
20417
20418    #[test]
20419    fn timedelta_div_scalar_min_neg_one_propagates_nat() {
20420        // i64::MIN aliases NaT, so `div_scalar(i64::MIN, _)` propagates NaT
20421        // — the `i64::MIN / -1` arithmetic-overflow case is subsumed.
20422        assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
20423        // (i64::MIN + 1) is a real timedelta; `/ -1` does not overflow.
20424        assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
20425    }
20426
20427    #[test]
20428    fn timedelta_div_scalar_propagates_nat() {
20429        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
20430    }
20431
20432    #[test]
20433    fn timedelta_div_timedelta_returns_float_ratio() {
20434        let two_hours = Timedelta::NANOS_PER_HOUR * 2;
20435        let one_hour = Timedelta::NANOS_PER_HOUR;
20436        assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
20437        assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
20438    }
20439
20440    #[test]
20441    fn timedelta_div_timedelta_nat_returns_nan() {
20442        assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
20443        assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
20444    }
20445
20446    // ── Timestamp tests (br-frankenpandas-9p0u — 4r56 Phase 2) ──────────
20447
20448    use super::Timestamp;
20449
20450    #[test]
20451    fn timestamp_from_nanos_is_naive_utc() {
20452        let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
20453        assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
20454        assert_eq!(ts.tz, None);
20455        assert!(!ts.is_nat());
20456    }
20457
20458    #[test]
20459    fn timestamp_from_nanos_tz_carries_tz_name() {
20460        let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
20461        assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
20462    }
20463
20464    #[test]
20465    fn timestamp_now_returns_current_time() {
20466        let before = std::time::SystemTime::now()
20467            .duration_since(std::time::UNIX_EPOCH)
20468            .unwrap()
20469            .as_nanos() as i64;
20470        let ts = Timestamp::now();
20471        let after = std::time::SystemTime::now()
20472            .duration_since(std::time::UNIX_EPOCH)
20473            .unwrap()
20474            .as_nanos() as i64;
20475        assert!(ts.nanos >= before);
20476        assert!(ts.nanos <= after);
20477        assert!(!ts.is_nat());
20478    }
20479
20480    #[test]
20481    fn timestamp_today_returns_midnight() {
20482        let ts = Timestamp::today();
20483        assert!(!ts.is_nat());
20484        // Today should be normalized (midnight), so hour/min/sec should be 0
20485        assert_eq!(ts.hour(), Some(0));
20486        assert_eq!(ts.minute(), Some(0));
20487        assert_eq!(ts.second(), Some(0));
20488    }
20489
20490    #[test]
20491    fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
20492        let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
20493        let one_day = Timedelta::NANOS_PER_DAY;
20494        let shifted = ts.add_timedelta(one_day);
20495        assert_eq!(shifted.nanos, one_day);
20496        assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
20497    }
20498
20499    #[test]
20500    fn timestamp_add_timedelta_returns_nat_on_overflow() {
20501        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX, i.e.
20502        // a finite ~year-2262 instant handed back as real data. pandas
20503        // `pd.Timestamp.max + pd.Timedelta('1ns')` raises OutOfBoundsDatetime.
20504        let ts = Timestamp::from_nanos(i64::MAX - 10);
20505        assert!(ts.add_timedelta(100).is_nat());
20506    }
20507
20508    #[test]
20509    fn timestamp_add_timedelta_propagates_nat() {
20510        // NaT Timestamp + anything = NaT.
20511        assert!(Timestamp::nat().add_timedelta(100).is_nat());
20512        // Timestamp + NaT Timedelta = NaT.
20513        assert!(
20514            Timestamp::from_nanos(0)
20515                .add_timedelta(Timedelta::NAT)
20516                .is_nat()
20517        );
20518    }
20519
20520    #[test]
20521    fn timestamp_sub_timedelta_shifts_backward() {
20522        let ts = Timestamp::from_nanos(1_000);
20523        let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
20524        assert_eq!(shifted.nanos, 0);
20525    }
20526
20527    #[test]
20528    fn timestamp_sub_timestamp_returns_timedelta_nanos() {
20529        let t0 = Timestamp::from_nanos(0);
20530        let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
20531        assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
20532        assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
20533    }
20534
20535    #[test]
20536    fn timestamp_sub_timestamp_nat_propagates() {
20537        let ts = Timestamp::from_nanos(1_000);
20538        assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
20539        assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
20540    }
20541
20542    #[test]
20543    fn timestamp_semantic_eq_treats_two_nat_as_equal() {
20544        assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
20545        assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
20546        assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
20547    }
20548
20549    #[test]
20550    fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
20551        use std::cmp::Ordering;
20552        let a = Timestamp::from_nanos(0);
20553        let b = Timestamp::from_nanos(100);
20554        assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
20555        assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
20556        assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
20557        assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
20558        assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
20559    }
20560
20561    #[test]
20562    fn time_zone_offsets_and_wall_clock_conversions_follow_pandas() {
20563        use crate::{
20564            TimeZoneError, tz_abbreviation, tz_canonical_name, tz_offset_seconds,
20565            tz_utc_to_wall_nanos, tz_validate, tz_wall_to_utc_nanos,
20566        };
20567        let hour = 3_600_000_000_000_i64;
20568        // 2024-03-10 14:30 UTC: Tokyo is +9h; New York is on EDT (-4h) after
20569        // 07:00 UTC that day and on EST (-5h) the day before.
20570        let instant = 1_710_081_000_000_000_000_i64;
20571        assert_eq!(tz_offset_seconds("Asia/Tokyo", instant), Ok(9 * 3_600));
20572        assert_eq!(tz_offset_seconds("US/Eastern", instant), Ok(-4 * 3_600));
20573        assert_eq!(
20574            tz_offset_seconds("US/Eastern", instant - 24 * hour),
20575            Ok(-5 * 3_600)
20576        );
20577        assert_eq!(tz_offset_seconds("+05:30", 0), Ok(19_800));
20578        assert_eq!(tz_offset_seconds("UTC+05:30", 0), Ok(19_800));
20579        assert_eq!(tz_offset_seconds("-03:00", 0), Ok(-10_800));
20580        assert_eq!(tz_offset_seconds("UTC", instant), Ok(0));
20581        assert_eq!(
20582            tz_utc_to_wall_nanos("Asia/Tokyo", instant),
20583            Ok(instant + 9 * hour)
20584        );
20585        // Wall 12:00 in New York on 2024-01-01 is 17:00 UTC, and back.
20586        let wall_noon = 19_723 * 24 * hour + 12 * hour;
20587        assert_eq!(
20588            tz_wall_to_utc_nanos("US/Eastern", wall_noon),
20589            Ok(wall_noon + 5 * hour)
20590        );
20591        assert_eq!(
20592            tz_utc_to_wall_nanos("US/Eastern", wall_noon + 5 * hour),
20593            Ok(wall_noon)
20594        );
20595        // NaT passes through both ways.
20596        assert_eq!(tz_wall_to_utc_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
20597        assert_eq!(tz_utc_to_wall_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
20598        // NEGATIVES: 02:30 on 2024-03-10 does not exist in New York; 01:30
20599        // on 2024-11-03 happens twice; unknown zones and malformed offsets
20600        // are pandas' UnknownTimeZoneError.
20601        let skipped = 19_792 * 24 * hour + 2 * hour + 30 * 60_000_000_000;
20602        assert_eq!(
20603            tz_wall_to_utc_nanos("US/Eastern", skipped),
20604            Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
20605        );
20606        let repeated = 20_030 * 24 * hour + hour + 30 * 60_000_000_000;
20607        assert_eq!(
20608            tz_wall_to_utc_nanos("US/Eastern", repeated),
20609            Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
20610        );
20611        assert_eq!(
20612            tz_offset_seconds("Mars/Olympus", 0),
20613            Err(TimeZoneError::Unknown("Mars/Olympus".to_owned()))
20614        );
20615        assert!(tz_validate("+24:00").is_err());
20616        assert!(tz_validate("+5:30").is_err());
20617        assert!(tz_validate("Europe/Paris").is_ok());
20618        // pandas' names: a fixed offset is UTC+HH:MM, a zero one UTC.
20619        assert_eq!(tz_canonical_name("+05:30").as_deref(), Ok("UTC+05:30"));
20620        assert_eq!(tz_canonical_name("UTC-03:00").as_deref(), Ok("UTC-03:00"));
20621        assert_eq!(tz_canonical_name("+00:00").as_deref(), Ok("UTC"));
20622        assert_eq!(tz_canonical_name("Z").as_deref(), Ok("UTC"));
20623        assert_eq!(tz_canonical_name("US/Eastern").as_deref(), Ok("US/Eastern"));
20624        // strftime('%Z'): the abbreviation in force at the instant.
20625        assert_eq!(tz_abbreviation("US/Eastern", instant).as_deref(), Ok("EDT"));
20626        assert_eq!(
20627            tz_abbreviation("US/Eastern", instant - 24 * hour).as_deref(),
20628            Ok("EST")
20629        );
20630        assert_eq!(tz_abbreviation("+05:30", 0).as_deref(), Ok("UTC+05:30"));
20631    }
20632
20633    /// pandas' `tz_localize(ambiguous=, nonexistent=)` for one wall time
20634    /// (br-frankenpandas-84w06), live pandas 2.2.3 in America/New_York:
20635    /// 02:30 on 2024-03-10 does not exist - shift_forward 03:00-04:00 (07:00
20636    /// UTC), shift_backward 01:59:59.999999999-05:00, NaT, or +1h 03:30-04:00;
20637    /// 01:30 on 2024-11-03 happens twice - True (DST) 05:30 UTC, False
20638    /// (standard) 06:30 UTC, NaT.
20639    #[test]
20640    fn tz_localize_policies_follow_pandas_84w06() {
20641        use super::{
20642            AmbiguousTime as A, NonexistentTime as N, TimeZoneError,
20643            tz_wall_to_utc_nanos_with as at,
20644        };
20645        let hour = 3_600_000_000_000_i64;
20646        let minute = 60_000_000_000_i64;
20647        let skipped = 19_792 * 24 * hour + 2 * hour + 30 * minute;
20648        let transition = 19_792 * 24 * hour + 7 * hour;
20649        let zone = "America/New_York";
20650        assert_eq!(at(zone, skipped, A::Raise, N::ShiftForward), Ok(transition));
20651        assert_eq!(
20652            at(zone, skipped, A::Raise, N::ShiftBackward),
20653            Ok(transition - 1)
20654        );
20655        assert_eq!(at(zone, skipped, A::Raise, N::NaT), Ok(i64::MIN));
20656        assert_eq!(
20657            at(zone, skipped, A::Raise, N::Shift(hour)),
20658            Ok(transition + 30 * minute)
20659        );
20660        let repeated = 20_030 * 24 * hour + hour + 30 * minute;
20661        assert_eq!(
20662            at(zone, repeated, A::Earliest, N::Raise),
20663            Ok(repeated + 4 * hour)
20664        );
20665        assert_eq!(
20666            at(zone, repeated, A::Latest, N::Raise),
20667            Ok(repeated + 5 * hour)
20668        );
20669        assert_eq!(at(zone, repeated, A::NaT, N::Raise), Ok(i64::MIN));
20670        // NEGATIVES: the policies leave a wall time that exists once alone,
20671        // and 'raise' still refuses as before.
20672        let noon = 19_723 * 24 * hour + 12 * hour;
20673        assert_eq!(at(zone, noon, A::NaT, N::NaT), Ok(noon + 5 * hour));
20674        assert_eq!(
20675            at(zone, skipped, A::NaT, N::Raise),
20676            Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
20677        );
20678        assert_eq!(
20679            at(zone, repeated, A::Raise, N::NaT),
20680            Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
20681        );
20682    }
20683
20684    /// The batch conversions answer as the per-value ones, value for value:
20685    /// whole-hour DST changes, Lord Howe's half hour, a fixed offset and UTC,
20686    /// over sorted minutes through each change, every hour's edges, random
20687    /// instants and NaT, under each policy (br-frankenpandas-6pqf3). NEGATIVE: 'raise' still
20688    /// refuses the first skipped wall time, a skipped one under 'NaT' is NaT
20689    /// (a reused hour's offset would place it), and a refused time's text
20690    /// keeps pandas' six or nine digits.
20691    #[test]
20692    fn batch_tz_conversions_match_each_value_6pqf3() {
20693        use super::{
20694            AmbiguousTime as A, NonexistentTime as N, TimeZoneError, tz_utc_to_wall_nanos,
20695            tz_utc_to_wall_nanos_all, tz_wall_to_utc_nanos_all, tz_wall_to_utc_nanos_with,
20696        };
20697        const HOUR: i64 = 3_600_000_000_000;
20698        const MINUTE: i64 = 60_000_000_000;
20699        const DAY: i64 = 24 * HOUR;
20700        let (year_start, year_end) = (19_723 * DAY, 20_089 * DAY);
20701        let mut values: Vec<i64> = (year_start..year_end)
20702            .step_by(usize::try_from(37 * MINUTE).unwrap())
20703            .collect();
20704        for hour in (year_start..year_end).step_by(usize::try_from(HOUR).unwrap()) {
20705            values.extend([hour - 1, hour, hour + 1]);
20706        }
20707        for change_day in [19_792, 20_030, 19_813, 20_023, 19_820, 20_002] {
20708            values.extend((0..2 * 24 * 60).map(|minute| (change_day - 1) * DAY + minute * MINUTE));
20709        }
20710        let mut state = 0x2545_f491_4f6c_dd1d_u64;
20711        for _ in 0..3_000 {
20712            state = state
20713                .wrapping_mul(6_364_136_223_846_793_005)
20714                .wrapping_add(1_442_695_040_888_963_407);
20715            values.push(i64::try_from(state >> 2).unwrap() - 2_000_000_000_000_000_000);
20716        }
20717        values.extend([i64::MIN, 19_792 * DAY, i64::MIN]);
20718        let policies = [
20719            (A::NaT, N::NaT),
20720            (A::Earliest, N::ShiftForward),
20721            (A::Latest, N::ShiftBackward),
20722            (A::NaT, N::Shift(30 * MINUTE)),
20723        ];
20724        for zone in [
20725            "US/Eastern",
20726            "Europe/London",
20727            "Australia/Lord_Howe",
20728            "+05:30",
20729            "UTC",
20730        ] {
20731            let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20732                .iter()
20733                .map(|&nanos| tz_utc_to_wall_nanos(zone, nanos))
20734                .collect();
20735            assert_eq!(
20736                tz_utc_to_wall_nanos_all(zone, &values),
20737                one_by_one,
20738                "{zone}"
20739            );
20740            for (ambiguous, nonexistent) in policies {
20741                let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20742                    .iter()
20743                    .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, ambiguous, nonexistent))
20744                    .collect();
20745                assert_eq!(
20746                    tz_wall_to_utc_nanos_all(zone, &values, ambiguous, nonexistent),
20747                    one_by_one,
20748                    "{zone} {ambiguous:?} {nonexistent:?}"
20749                );
20750            }
20751            let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20752                .iter()
20753                .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, A::Raise, N::Raise))
20754                .collect();
20755            assert_eq!(
20756                tz_wall_to_utc_nanos_all(zone, &values, A::Raise, N::Raise),
20757                one_by_one,
20758                "{zone} raise"
20759            );
20760        }
20761        let skipped = 19_792 * DAY + 2 * HOUR + 30 * MINUTE;
20762        // 01:10 to 03:30 by 20 minutes: 02:00-03:00 is skipped.
20763        let run: Vec<i64> = (0..8)
20764            .map(|step| 19_792 * DAY + HOUR + 10 * MINUTE + step * 20 * MINUTE)
20765            .collect();
20766        assert_eq!(
20767            tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::Raise),
20768            Err(TimeZoneError::NonExistent("2024-03-10 02:10:00".to_owned()))
20769        );
20770        let placed = tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::NaT).unwrap();
20771        let expected: Vec<i64> = run
20772            .iter()
20773            .enumerate()
20774            .map(|(step, &wall)| match step {
20775                0..3 => wall + 5 * HOUR,
20776                3..6 => i64::MIN,
20777                _ => wall + 4 * HOUR,
20778            })
20779            .collect();
20780        assert_eq!(placed, expected);
20781        // Lord Howe's half-hour gap (02:00 -> 02:30 on 2024-10-06): pandas
20782        // moves 02:10 up to 03:00 (+11:00) or back to 01:59:59.999999999
20783        // (+10:30), not to the gap's end.
20784        let howe = 20_002 * DAY + 2 * HOUR + 10 * MINUTE;
20785        assert_eq!(
20786            tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftForward),
20787            Ok(vec![20_002 * DAY - 8 * HOUR])
20788        );
20789        assert_eq!(
20790            tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftBackward),
20791            Ok(vec![20_002 * DAY - 8 * HOUR - 30 * MINUTE - 1])
20792        );
20793        for (wall, text) in [
20794            (skipped + 500_000_000, "2024-03-10 02:30:00.500000"),
20795            (skipped + 1, "2024-03-10 02:30:00.000000001"),
20796        ] {
20797            assert_eq!(
20798                tz_wall_to_utc_nanos_all("US/Eastern", &[wall], A::Raise, N::Raise),
20799                Err(TimeZoneError::NonExistent(text.to_owned()))
20800            );
20801        }
20802    }
20803
20804    #[test]
20805    fn timestamp_display_matches_phase2_debug_format() {
20806        assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
20807        assert_eq!(
20808            Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
20809            "Timestamp[42, US/Eastern]"
20810        );
20811        assert_eq!(Timestamp::nat().to_string(), "NaT");
20812    }
20813
20814    #[test]
20815    fn a_naive_timestamp_cell_casts_to_its_str_srzqw() {
20816        // astype(str) of an object column's naive Timestamp is str(Timestamp)
20817        // - its own fraction, none when whole - not the 'Timestamp[<nanos>]'
20818        // placeholder (br-frankenpandas-srzqw).
20819        let text = |nanos: i64| cast_scalar(&Scalar::Datetime64(nanos), DType::Utf8);
20820        let midnight = 1_711_929_600_000_000_000;
20821        assert_eq!(
20822            text(midnight),
20823            Ok(Scalar::Utf8("2024-04-01 00:00:00".into()))
20824        );
20825        assert_eq!(
20826            text(midnight + 1_000),
20827            Ok(Scalar::Utf8("2024-04-01 00:00:00.000001".into()))
20828        );
20829        assert_eq!(
20830            text(midnight + 1),
20831            Ok(Scalar::Utf8("2024-04-01 00:00:00.000000001".into()))
20832        );
20833        assert_eq!(
20834            text(-1),
20835            Ok(Scalar::Utf8("1969-12-31 23:59:59.999999999".into()))
20836        );
20837        assert_eq!(text(Timestamp::NAT), Ok(Scalar::Utf8("NaT".into())));
20838        // The zoned spelling is the same wall clock and its offset.
20839        assert_eq!(
20840            crate::timestamp_text_in_zone(midnight, "US/Eastern"),
20841            "2024-03-31 20:00:00-04:00"
20842        );
20843    }
20844
20845    #[test]
20846    fn timestamp_value_and_unit_match_pandas_l0edr() {
20847        let ts = Timestamp::from_nanos(1_000_000_123);
20848        assert_eq!(ts.value(), 1_000_000_123);
20849        assert_eq!(ts.unit(), Some("ns"));
20850
20851        let nat = Timestamp::nat();
20852        assert_eq!(nat.value(), Timestamp::NAT);
20853        assert_eq!(nat.unit(), None);
20854    }
20855
20856    #[test]
20857    fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
20858        let ts = Timestamp::from_nanos(1_000_000_123);
20859        assert_eq!(ts.asm8(), ts.value());
20860        assert_eq!(ts.to_datetime64(), ts.value());
20861        assert_eq!(ts.to_numpy(), ts.value());
20862
20863        let nat = Timestamp::nat();
20864        assert_eq!(nat.asm8(), Timestamp::NAT);
20865        assert_eq!(nat.to_datetime64(), Timestamp::NAT);
20866        assert_eq!(nat.to_numpy(), Timestamp::NAT);
20867    }
20868
20869    #[test]
20870    fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
20871        assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
20872        assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
20873        assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
20874        assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
20875        assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
20876
20877        assert!(matches!(
20878            Timestamp::from_nanos(-500).timestamp(),
20879            Ok(value) if value == -0.0 && value.is_sign_negative()
20880        ));
20881        assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
20882        assert_eq!(
20883            Timestamp::nat().timestamp(),
20884            Err(TypeError::ValueIsMissing {
20885                kind: NullKind::NaT,
20886            })
20887        );
20888    }
20889
20890    #[test]
20891    fn timestamp_roundtrips_through_serde_json() {
20892        let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
20893        let json = serde_json::to_string(&naive).expect("serialize");
20894        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
20895        assert_eq!(naive, back);
20896
20897        let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
20898        let json = serde_json::to_string(&tz_aware).expect("serialize");
20899        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
20900        assert_eq!(tz_aware, back);
20901    }
20902
20903    #[test]
20904    fn timestamp_is_send_and_sync() {
20905        fn assert_send_sync<T: Send + Sync>() {}
20906        assert_send_sync::<Timestamp>();
20907    }
20908
20909    // ── Timestamp rounding tests (br-frankenpandas-5h6n) ────────────────
20910
20911    #[test]
20912    fn timestamp_pre_epoch_accessors_floor_not_truncate() {
20913        // br-frankenpandas-wkjtw: pre-1970 instants with a sub-day part used to
20914        // truncate toward zero, landing on the wrong calendar day. -1 ns is
20915        // 1969-12-31 23:59:59.999999999 UTC.
20916        let ts = Timestamp::from_nanos(-1);
20917        assert_eq!(ts.year(), Some(1969));
20918        assert_eq!(ts.month(), Some(12));
20919        assert_eq!(ts.day(), Some(31));
20920        assert_eq!(ts.hour(), Some(23));
20921        assert_eq!(ts.minute(), Some(59));
20922        assert_eq!(ts.second(), Some(59));
20923        assert_eq!(ts.microsecond(), Some(999_999));
20924        assert_eq!(ts.nanosecond(), Some(999));
20925        // 1969-12-31 is a Wednesday (pandas Monday=0 -> 2).
20926        assert_eq!(ts.dayofweek(), Some(2));
20927
20928        // 1969-12-31 12:00:00 — the classic truncation case (-43200 s).
20929        let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
20930        assert_eq!(noon.year(), Some(1969));
20931        assert_eq!(noon.month(), Some(12));
20932        assert_eq!(noon.day(), Some(31));
20933        assert_eq!(noon.hour(), Some(12));
20934
20935        // Exact midnight pre-epoch was already correct; keep it green.
20936        let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
20937        assert_eq!(midnight.year(), Some(1969));
20938        assert_eq!(midnight.day(), Some(31));
20939        assert_eq!(midnight.hour(), Some(0));
20940    }
20941
20942    #[test]
20943    fn timestamp_floor_to_rounds_down() {
20944        // 12:34:56 → floor by 1H → 12:00:00
20945        let h = Timedelta::NANOS_PER_HOUR;
20946        let twelve_h = h * 12;
20947        let twelve_thirty_four =
20948            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20949        let ts = Timestamp::from_nanos(twelve_thirty_four);
20950        let floored = ts.floor_to(h);
20951        assert_eq!(floored.nanos, twelve_h);
20952    }
20953
20954    #[test]
20955    fn timestamp_floor_to_handles_already_aligned() {
20956        // 12:00:00 floored by 1H → 12:00:00 (no change).
20957        let h = Timedelta::NANOS_PER_HOUR;
20958        let twelve_h = h * 12;
20959        let ts = Timestamp::from_nanos(twelve_h);
20960        assert_eq!(ts.floor_to(h).nanos, twelve_h);
20961    }
20962
20963    #[test]
20964    fn timestamp_floor_to_handles_negative_nanos() {
20965        // -100 ns floored by 60 ns:
20966        //   div_euclid(-100, 60) = -2 (since -2*60=-120, rem=20 ≥ 0).
20967        //   result = -2 * 60 = -120.
20968        let ts = Timestamp::from_nanos(-100);
20969        assert_eq!(ts.floor_to(60).nanos, -120);
20970    }
20971
20972    #[test]
20973    fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
20974        let ts = Timestamp::from_nanos(i64::MIN + 1);
20975        assert!(ts.floor_to(10).is_nat());
20976
20977        let safe = Timestamp::from_nanos(i64::MIN + 10);
20978        assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
20979
20980        let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
20981        assert_eq!(tz.nanos, -120);
20982        assert_eq!(tz.tz.as_deref(), Some("UTC"));
20983    }
20984
20985    #[test]
20986    fn timestamp_ceil_to_rounds_up() {
20987        // 12:34:56 → ceil by 1H → 13:00:00.
20988        let h = Timedelta::NANOS_PER_HOUR;
20989        let twelve_h = h * 12;
20990        let thirteen_h = h * 13;
20991        let twelve_thirty_four =
20992            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20993        let ts = Timestamp::from_nanos(twelve_thirty_four);
20994        assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
20995    }
20996
20997    #[test]
20998    fn timestamp_ceil_to_no_op_on_aligned() {
20999        let h = Timedelta::NANOS_PER_HOUR;
21000        let twelve_h = h * 12;
21001        let ts = Timestamp::from_nanos(twelve_h);
21002        assert_eq!(ts.ceil_to(h).nanos, twelve_h);
21003    }
21004
21005    #[test]
21006    fn timestamp_round_to_rounds_to_nearest() {
21007        // 12:30:01 (one second past the half-hour): round to 1H → 13:00:00.
21008        let h = Timedelta::NANOS_PER_HOUR;
21009        let twelve_h = h * 12;
21010        let twelve_thirty_one_sec =
21011            twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
21012        let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
21013        assert_eq!(ts.round_to(h).nanos, h * 13);
21014
21015        // 12:29:59 (one second before half): round to 1H → 12:00:00.
21016        let twelve_twenty_nine_sec =
21017            twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
21018        let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
21019        assert_eq!(ts.round_to(h).nanos, twelve_h);
21020    }
21021
21022    #[test]
21023    fn timestamp_round_to_bankers_tie_to_even() {
21024        // Tie cases: rem == unit/2 exactly. Pick even-multiple floor.
21025        // unit=10, so half=5. nanos=5: floor=0 (even), so → 0.
21026        // nanos=15: floor=1 (odd), so → 20.
21027        // nanos=25: floor=2 (even), so → 20.
21028        // nanos=35: floor=3 (odd), so → 40.
21029        assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
21030        assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
21031        assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
21032        assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
21033    }
21034
21035    #[test]
21036    fn timestamp_round_to_zero_unit_returns_nat() {
21037        let ts = Timestamp::from_nanos(100);
21038        assert!(ts.round_to(0).is_nat());
21039        assert!(ts.floor_to(0).is_nat());
21040        assert!(ts.ceil_to(0).is_nat());
21041    }
21042
21043    #[test]
21044    fn timestamp_round_to_negative_unit_returns_nat() {
21045        let ts = Timestamp::from_nanos(100);
21046        assert!(ts.round_to(-10).is_nat());
21047        assert!(ts.floor_to(-10).is_nat());
21048        assert!(ts.ceil_to(-10).is_nat());
21049    }
21050
21051    #[test]
21052    fn timestamp_rounding_propagates_nat() {
21053        let nat = Timestamp::nat();
21054        assert!(nat.floor_to(60).is_nat());
21055        assert!(nat.ceil_to(60).is_nat());
21056        assert!(nat.round_to(60).is_nat());
21057    }
21058
21059    #[test]
21060    fn timestamp_rounding_preserves_tz() {
21061        let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
21062        assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
21063        assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
21064        assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
21065    }
21066
21067    // ── Timestamp string-unit rounding tests (br-frankenpandas-lbsx) ────
21068
21069    #[test]
21070    fn timestamp_floor_to_unit_h_rounds_to_hour() {
21071        let h = Timedelta::NANOS_PER_HOUR;
21072        let twelve_h = h * 12;
21073        let twelve_thirty_four =
21074            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
21075        let ts = Timestamp::from_nanos(twelve_thirty_four);
21076        assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
21077        assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
21078        assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
21079        assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
21080        assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
21081    }
21082
21083    #[test]
21084    fn timestamp_ceil_to_unit_d_rounds_to_day() {
21085        // 12:34:56 → ceil to 1 day → 24:00:00 (next day).
21086        let h = Timedelta::NANOS_PER_HOUR;
21087        let d = Timedelta::NANOS_PER_DAY;
21088        let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
21089        let ts = Timestamp::from_nanos(twelve_thirty_four);
21090        assert_eq!(ts.ceil_to_unit("D").nanos, d);
21091        assert_eq!(ts.ceil_to_unit("day").nanos, d);
21092        assert_eq!(ts.ceil_to_unit("days").nanos, d);
21093    }
21094
21095    #[test]
21096    fn timestamp_round_to_unit_min_rounds_to_minute() {
21097        // 12:34:31 → round to 1 minute → 12:35:00.
21098        let m = Timedelta::NANOS_PER_MIN;
21099        let twelve_thirty_four_thirty_one =
21100            Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
21101        let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
21102        let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
21103        assert_eq!(ts.round_to_unit("min").nanos, expected);
21104        assert_eq!(ts.round_to_unit("T").nanos, expected); // pandas pre-2.2 alias
21105        assert_eq!(ts.round_to_unit("minute").nanos, expected);
21106    }
21107
21108    #[test]
21109    fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
21110        let ts = Timestamp::from_nanos(
21111            Timedelta::NANOS_PER_HOUR * 12
21112                + Timedelta::NANOS_PER_MIN * 34
21113                + Timedelta::NANOS_PER_SEC * 31,
21114        );
21115
21116        assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
21117        assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
21118        assert_eq!(ts.round("min"), ts.round_to_unit("min"));
21119    }
21120
21121    #[test]
21122    fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
21123        let ts = Timestamp::from_nanos_tz(
21124            Timedelta::NANOS_PER_DAY * 3
21125                + Timedelta::NANOS_PER_HOUR * 12
21126                + Timedelta::NANOS_PER_MIN * 34,
21127            "US/Eastern",
21128        );
21129        let normalized = ts.normalize();
21130
21131        assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
21132        assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
21133        assert!(Timestamp::nat().normalize().is_nat());
21134        for nanos in [
21135            i64::MIN + 1,
21136            -Timedelta::NANOS_PER_DAY - 1,
21137            -Timedelta::NANOS_PER_DAY,
21138            -1,
21139            0,
21140            Timedelta::NANOS_PER_DAY - 1,
21141            Timedelta::NANOS_PER_DAY,
21142            i64::MAX,
21143        ] {
21144            let timestamp = Timestamp::from_nanos(nanos);
21145            assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
21146        }
21147    }
21148
21149    #[test]
21150    #[ignore = "foreground profile-first A/B"]
21151    fn timestamp_normalize_direct_day_profile_dk721() {
21152        use std::{hint::black_box, time::Instant};
21153
21154        fn former(timestamp: &Timestamp) -> Timestamp {
21155            timestamp.floor_to_unit("D")
21156        }
21157
21158        fn candidate(timestamp: &Timestamp) -> Timestamp {
21159            timestamp.normalize()
21160        }
21161
21162        fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
21163            let started = Instant::now();
21164            let mut checksum = 0_u64;
21165            for timestamp in input {
21166                let normalized = normalize(black_box(timestamp));
21167                checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
21168            }
21169            black_box(checksum);
21170            started.elapsed().as_nanos()
21171        }
21172
21173        fn percentile(samples: &mut [u128], percent: usize) -> u128 {
21174            samples.sort_unstable();
21175            let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
21176            samples[rank]
21177        }
21178
21179        let parity_cases = [
21180            Timestamp::nat(),
21181            Timestamp::from_nanos(i64::MIN + 1),
21182            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
21183            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
21184            Timestamp::from_nanos(-1),
21185            Timestamp::from_nanos(0),
21186            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
21187            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
21188            Timestamp::from_nanos(i64::MAX),
21189            Timestamp::from_nanos_tz(-1, "US/Eastern"),
21190            Timestamp::from_nanos_tz(
21191                Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
21192                "Asia/Tokyo",
21193            ),
21194        ];
21195        for timestamp in &parity_cases {
21196            assert_eq!(former(timestamp), candidate(timestamp));
21197            assert_eq!(timestamp.normalize(), former(timestamp));
21198        }
21199
21200        const ROWS: usize = 16_384;
21201        const SAMPLES: usize = 20;
21202        let input = (0..ROWS)
21203            .map(|index| {
21204                let day = index as i64 % 4_096 - 2_048;
21205                let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
21206                    % Timedelta::NANOS_PER_DAY as u64) as i64;
21207                Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
21208            })
21209            .collect::<Vec<_>>();
21210        for timestamp in &input {
21211            assert_eq!(former(timestamp), candidate(timestamp));
21212        }
21213
21214        for _ in 0..3 {
21215            black_box(elapsed(&input, former));
21216            black_box(elapsed(&input, candidate));
21217        }
21218
21219        let mut former_ns = Vec::with_capacity(SAMPLES);
21220        let mut candidate_ns = Vec::with_capacity(SAMPLES);
21221        for sample in 0..SAMPLES {
21222            if sample % 2 == 0 {
21223                former_ns.push(elapsed(&input, former));
21224                candidate_ns.push(elapsed(&input, candidate));
21225            } else {
21226                candidate_ns.push(elapsed(&input, candidate));
21227                former_ns.push(elapsed(&input, former));
21228            }
21229        }
21230
21231        let mut former_sorted = former_ns.clone();
21232        let mut candidate_sorted = candidate_ns.clone();
21233        let former_p50 = percentile(&mut former_sorted, 50);
21234        let former_p95 = percentile(&mut former_sorted, 95);
21235        let former_p99 = percentile(&mut former_sorted, 99);
21236        let candidate_p50 = percentile(&mut candidate_sorted, 50);
21237        let candidate_p95 = percentile(&mut candidate_sorted, 95);
21238        let candidate_p99 = percentile(&mut candidate_sorted, 99);
21239        println!(
21240            "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:?}",
21241            former_p50 as f64 / candidate_p50 as f64,
21242            former_p95 as f64 / candidate_p95 as f64,
21243            former_p99 as f64 / candidate_p99 as f64,
21244        );
21245    }
21246
21247    #[test]
21248    fn timestamp_unit_rounding_unknown_unit_returns_nat() {
21249        let ts = Timestamp::from_nanos(100);
21250        assert!(ts.floor_to_unit("fortnight").is_nat());
21251        assert!(ts.ceil_to_unit("century").is_nat());
21252        assert!(ts.round_to_unit("xyz").is_nat());
21253    }
21254
21255    /// pd.Timestamp('2024-03-15 13:47:21').round('15min') is 13:45 (a
21256    /// multiple of a unit was unknown here: NaT).
21257    #[test]
21258    fn timestamp_rounding_reads_a_multiple_of_a_unit_3agof() {
21259        let (min, sec) = (Timedelta::NANOS_PER_MIN, Timedelta::NANOS_PER_SEC);
21260        let base = 1_710_460_800 * sec; // 2024-03-15 00:00:00
21261        let ts = Timestamp::from_nanos(base + 13 * Timedelta::NANOS_PER_HOUR + 47 * min + 21 * sec);
21262        let at = |minutes: i64, seconds: i64| base + minutes * min + seconds * sec;
21263        assert_eq!(ts.round("15min").nanos, at(13 * 60 + 45, 0));
21264        assert_eq!(ts.floor("15min").nanos, at(13 * 60 + 45, 0));
21265        assert_eq!(ts.ceil("15min").nanos, at(14 * 60, 0));
21266        assert_eq!(ts.round("30s").nanos, at(13 * 60 + 47, 30));
21267        assert_eq!(ts.ceil("1D").nanos, base + Timedelta::NANOS_PER_DAY);
21268        // 2024-03-15 is 19797 days after the epoch: the 7-day floor is day
21269        // 19796 (2024-03-14), as pandas'.
21270        assert_eq!(ts.floor("7D").nanos, 19_796 * Timedelta::NANOS_PER_DAY);
21271        // NEGATIVE: a calendar frequency is no fixed length.
21272        assert!(ts.round("ME").is_nat());
21273    }
21274
21275    #[test]
21276    fn timestamp_unit_rounding_propagates_nat() {
21277        let nat = Timestamp::nat();
21278        assert!(nat.floor_to_unit("H").is_nat());
21279        assert!(nat.ceil_to_unit("H").is_nat());
21280        assert!(nat.round_to_unit("H").is_nat());
21281    }
21282
21283    #[test]
21284    fn timestamp_unit_rounding_preserves_tz() {
21285        let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
21286        assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21287        assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21288        assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21289    }
21290
21291    #[test]
21292    fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
21293        // Public surface check: pandas alias core set.
21294        assert_eq!(
21295            Timedelta::unit_to_nanos("W"),
21296            Some(Timedelta::NANOS_PER_WEEK)
21297        );
21298        assert_eq!(
21299            Timedelta::unit_to_nanos("D"),
21300            Some(Timedelta::NANOS_PER_DAY)
21301        );
21302        assert_eq!(
21303            Timedelta::unit_to_nanos("H"),
21304            Some(Timedelta::NANOS_PER_HOUR)
21305        );
21306        assert_eq!(
21307            Timedelta::unit_to_nanos("min"),
21308            Some(Timedelta::NANOS_PER_MIN)
21309        );
21310        assert_eq!(
21311            Timedelta::unit_to_nanos("s"),
21312            Some(Timedelta::NANOS_PER_SEC)
21313        );
21314        assert_eq!(
21315            Timedelta::unit_to_nanos("ms"),
21316            Some(Timedelta::NANOS_PER_MILLI)
21317        );
21318        assert_eq!(
21319            Timedelta::unit_to_nanos("us"),
21320            Some(Timedelta::NANOS_PER_MICRO)
21321        );
21322        assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
21323        // Empty string → days (pandas default).
21324        assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
21325        // Unknown alias → None.
21326        assert_eq!(Timedelta::unit_to_nanos("century"), None);
21327    }
21328
21329    #[test]
21330    fn timestamp_isoformat_basic() {
21331        let ts = Timestamp::from_nanos(0);
21332        assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
21333
21334        let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
21335        assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
21336
21337        let ts_fixed_offset = Timestamp::from_nanos_tz(0, "UTC+05:30");
21338        assert_eq!(
21339            ts_fixed_offset.isoformat(),
21340            "1970-01-01T05:30:00+05:30",
21341            "a fixed-offset timestamp must render local wall time rather than a UTC instant with an annotation"
21342        );
21343
21344        let ts_tz = Timestamp::from_nanos_tz(
21345            Timedelta::NANOS_PER_DAY
21346                + Timedelta::NANOS_PER_HOUR * 14
21347                + Timedelta::NANOS_PER_MIN * 30,
21348            "America/New_York",
21349        );
21350        assert_eq!(ts_tz.isoformat(), "1970-01-02T09:30:00-05:00");
21351
21352        assert_eq!(Timestamp::nat().isoformat(), "NaT");
21353    }
21354
21355    #[test]
21356    fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
21357        assert_eq!(
21358            Timestamp::from_nanos(-1).isoformat(),
21359            "1969-12-31T23:59:59.999999999"
21360        );
21361        assert_eq!(
21362            Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
21363            "1969-12-31T23:59:59"
21364        );
21365        assert_eq!(
21366            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
21367            "1969-12-31T00:00:00"
21368        );
21369        assert_eq!(
21370            Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
21371            "1969-12-31T23:59:59.999999999+00:00"
21372        );
21373    }
21374
21375    #[test]
21376    fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
21377        assert_eq!(
21378            Timestamp::from_nanos(123_456_789).isoformat(),
21379            "1970-01-01T00:00:00.123456789"
21380        );
21381        assert_eq!(
21382            Timestamp::from_nanos(123_456_000).isoformat(),
21383            "1970-01-01T00:00:00.123456"
21384        );
21385        assert_eq!(
21386            Timestamp::from_nanos(123_000_000).isoformat(),
21387            "1970-01-01T00:00:00.123000"
21388        );
21389        assert_eq!(
21390            Timestamp::from_nanos_tz(1, "UTC").isoformat(),
21391            "1970-01-01T00:00:00.000000001+00:00"
21392        );
21393    }
21394
21395    fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
21396        if timestamp.is_nat() {
21397            return "NaT".to_owned();
21398        }
21399        let Some(tz) = &timestamp.tz else {
21400            return Timestamp::from_nanos(timestamp.nanos).isoformat();
21401        };
21402        if let Ok(offset_secs) = crate::tz_offset_seconds(tz, timestamp.nanos)
21403            && let Some(display_nanos) = timestamp
21404                .nanos
21405                .checked_add(i64::from(offset_secs) * Timedelta::NANOS_PER_SEC)
21406        {
21407            let base = Timestamp::from_nanos(display_nanos).isoformat();
21408            let sign = if offset_secs < 0 { '-' } else { '+' };
21409            let total_minutes = offset_secs.unsigned_abs() / 60;
21410            return format!(
21411                "{base}{sign}{:02}:{:02}",
21412                total_minutes / 60,
21413                total_minutes % 60
21414            );
21415        }
21416        let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
21417        format!("{base}[{tz}]")
21418    }
21419
21420    #[test]
21421    fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
21422        let nanos = [
21423            Timestamp::NAT,
21424            -Timedelta::NANOS_PER_DAY - 1,
21425            -Timedelta::NANOS_PER_SEC,
21426            -1,
21427            0,
21428            1,
21429            123_456_000,
21430            123_456_789,
21431            i64::MAX,
21432        ];
21433        let timezones = [
21434            None,
21435            Some("UTC"),
21436            Some("America/New_York"),
21437            Some(""),
21438            Some("Etc/Γ"),
21439        ];
21440        for value in nanos {
21441            for timezone in timezones {
21442                let timestamp = Timestamp {
21443                    nanos: value,
21444                    tz: timezone.map(str::to_owned),
21445                };
21446                assert_eq!(
21447                    timestamp.isoformat(),
21448                    timestamp_isoformat_former_q8g50(&timestamp),
21449                    "nanos={value} timezone={timezone:?}"
21450                );
21451            }
21452        }
21453    }
21454
21455    #[test]
21456    #[ignore = "foreground release A/B only"]
21457    fn timestamp_isoformat_one_buffer_ab_q8g50() {
21458        use std::{hint::black_box, time::Instant};
21459
21460        const ITEMS: usize = 8_192;
21461        const SAMPLES: usize = 10;
21462
21463        fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
21464            let started = Instant::now();
21465            let mut checksum = 0usize;
21466            for timestamp in black_box(values) {
21467                checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
21468            }
21469            black_box(checksum);
21470            started.elapsed().as_nanos()
21471        }
21472
21473        let values = (0..ITEMS)
21474            .map(|idx| {
21475                let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
21476                let timezone = if idx.is_multiple_of(2) {
21477                    "UTC"
21478                } else {
21479                    "America/New_York"
21480                };
21481                Timestamp::from_nanos_tz(nanos, timezone)
21482            })
21483            .collect::<Vec<_>>();
21484        for timestamp in &values {
21485            assert_eq!(
21486                timestamp.isoformat(),
21487                timestamp_isoformat_former_q8g50(timestamp)
21488            );
21489        }
21490
21491        black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
21492        black_box(elapsed(&values, Timestamp::isoformat));
21493
21494        let mut former_ns = Vec::with_capacity(SAMPLES);
21495        let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
21496        for sample in 0..SAMPLES {
21497            if sample.is_multiple_of(2) {
21498                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
21499                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
21500            } else {
21501                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
21502                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
21503            }
21504        }
21505        former_ns.sort_unstable();
21506        one_buffer_ns.sort_unstable();
21507        let former_p50 = former_ns[SAMPLES / 2];
21508        let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
21509        println!(
21510            "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
21511            former_p50 as f64 / one_buffer_p50 as f64
21512        );
21513        println!("former_samples_ns={former_ns:?}");
21514        println!("one_buffer_samples_ns={one_buffer_ns:?}");
21515    }
21516
21517    #[test]
21518    fn timestamp_strftime_basic() {
21519        let ts = Timestamp::from_nanos(
21520            Timedelta::NANOS_PER_DAY * 365
21521                + Timedelta::NANOS_PER_HOUR * 9
21522                + Timedelta::NANOS_PER_MIN * 15,
21523        );
21524        assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
21525        assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
21526        assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
21527        // TEST-CHANGE: this pinned `%%Y` -> `%1971`; Python (CPython 3.13,
21528        // measured) prints `%%` as a literal `%` and echoes unknown `%Q`.
21529        assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%Y|%01|%Q|%|λ");
21530        assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
21531    }
21532
21533    #[test]
21534    fn strftime_follows_python_directives_and_zones() {
21535        // 1971-01-01 09:15 (a Friday; ISO week 53 of 1970). Expected texts
21536        // are CPython 3.13's datetime.strftime on Linux.
21537        let ts = Timestamp::from_nanos(
21538            Timedelta::NANOS_PER_DAY * 365
21539                + Timedelta::NANOS_PER_HOUR * 9
21540                + Timedelta::NANOS_PER_MIN * 15,
21541        );
21542        assert_eq!(
21543            ts.strftime("%-d %_m %^a %e %k %l %P %C %g %D %F %T %R %r %h %n %t|"),
21544            "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|"
21545        );
21546        assert_eq!(
21547            ts.strftime("%a %A %b %B %c|%x %X|%I %p %j %U %W %w %y"),
21548            "Fri Friday Jan January Fri Jan  1 09:15:00 1971|01/01/71 09:15:00|09 AM 001 00 00 5 71"
21549        );
21550        // 2021-01-03: a Sunday, ISO 2020-W53-7.
21551        let sunday = Timestamp::parse("2021-01-03").expect("date");
21552        assert_eq!(sunday.strftime("%G-%V-%u %U %W %j"), "2020-53-7 01 00 003");
21553        // Microseconds only; a trailing lone percent stays; naive %z / %Z empty.
21554        let fraction = Timestamp::parse("2024-03-05 14:07:09.123456789").expect("ts");
21555        assert_eq!(fraction.strftime("%f|%z|%Z|abc%"), "123456|||abc%");
21556        // A tz-aware Timestamp prints its wall clock and zone.
21557        let eastern = Timestamp::from_nanos_tz(fraction.nanos, "US/Eastern");
21558        assert_eq!(
21559            eastern.strftime("%Y-%m-%d %H:%M %z %Z"),
21560            "2024-03-05 09:07 -0500 EST"
21561        );
21562        assert_eq!(
21563            crate::strftime_in_zone(fraction.nanos, "%H:%M %z", Some("+05:30")),
21564            "19:37 +0530"
21565        );
21566    }
21567
21568    #[test]
21569    fn timestamp_strftime_floors_pre_epoch_instants_1pmlp() {
21570        let apollo = Timestamp::parse("1969-07-20T20:17:40").unwrap();
21571        assert_eq!(
21572            apollo.strftime("%Y-%m-%d %H:%M:%S.%f"),
21573            "1969-07-20 20:17:40.000000"
21574        );
21575
21576        // The smallest negative instant catches both truncation defects:
21577        // second flooring and day flooring.
21578        let one_ns_before_epoch = Timestamp::from_nanos(-1);
21579        assert_eq!(
21580            one_ns_before_epoch.strftime("%Y-%m-%d %H:%M:%S.%f"),
21581            "1969-12-31 23:59:59.999999"
21582        );
21583    }
21584
21585    #[test]
21586    #[ignore = "foreground normal-release attribution harness"]
21587    fn timestamp_strftime_one_buffer_profile_8qzbo() {
21588        use std::{hint::black_box, time::Instant};
21589
21590        const ITEMS: usize = 8_192;
21591        const SAMPLES: usize = 10;
21592        const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
21593
21594        fn former(timestamp: &Timestamp, format: &str) -> String {
21595            if timestamp.is_nat() {
21596                return "NaT".to_string();
21597            }
21598            let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
21599            let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
21600
21601            let days_since_epoch = total_secs / 86400;
21602            let secs_of_day = (total_secs % 86400 + 86400) % 86400;
21603            let days = days_since_epoch + 719_468;
21604            let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
21605            let doe = days - era * 146_097;
21606            let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
21607            let y = yoe + era * 400;
21608            let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
21609            let mp = (5 * doy + 2) / 153;
21610            let d = doy - (153 * mp + 2) / 5 + 1;
21611            let m = if mp < 10 { mp + 3 } else { mp - 9 };
21612            let year = if m <= 2 { y + 1 } else { y };
21613            let hour = secs_of_day / 3600;
21614            let minute = (secs_of_day % 3600) / 60;
21615            let second = secs_of_day % 60;
21616            let micros = sub_nanos / 1000;
21617
21618            format
21619                .replace("%Y", &format!("{year:04}"))
21620                .replace("%m", &format!("{m:02}"))
21621                .replace("%d", &format!("{d:02}"))
21622                .replace("%H", &format!("{hour:02}"))
21623                .replace("%M", &format!("{minute:02}"))
21624                .replace("%S", &format!("{second:02}"))
21625                .replace("%f", &format!("{micros:06}"))
21626        }
21627
21628        fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
21629            let started = Instant::now();
21630            let mut digest = 0_usize;
21631            for timestamp in timestamps {
21632                let value = formatter(black_box(timestamp), black_box(FORMAT));
21633                digest = digest.wrapping_add(value.len());
21634                digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
21635                black_box(value);
21636            }
21637            black_box(digest);
21638            started.elapsed().as_nanos()
21639        }
21640
21641        fn percentile(samples: &mut [u128], pct: usize) -> u128 {
21642            samples.sort_unstable();
21643            let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
21644            samples[rank]
21645        }
21646
21647        let edge_timestamps = [
21648            Timestamp::nat(),
21649            Timestamp::from_nanos(i64::MIN + 1),
21650            Timestamp::from_nanos(-1_234_567_890),
21651            Timestamp::from_nanos(0),
21652            Timestamp::from_nanos(1_735_732_800_123_456_789),
21653            Timestamp::from_nanos(i64::MAX),
21654        ];
21655        let edge_formats = [
21656            "",
21657            "%Y-%m-%d %H:%M:%S.%f",
21658            "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
21659            "%%Y|%%%m|%Q|%|λ",
21660            FORMAT,
21661        ];
21662        for timestamp in &edge_timestamps {
21663            for format in edge_formats {
21664                assert_eq!(former(timestamp, format), timestamp.strftime(format));
21665            }
21666        }
21667
21668        let timestamps = (0..ITEMS)
21669            .map(|index| {
21670                let centered = index as i64 - ITEMS as i64 / 2;
21671                Timestamp::from_nanos(centered * 987_654_321_123_456)
21672            })
21673            .collect::<Vec<_>>();
21674        for timestamp in &timestamps {
21675            assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
21676        }
21677
21678        black_box(elapsed(&timestamps, former));
21679        black_box(elapsed(&timestamps, Timestamp::strftime));
21680
21681        let mut former_samples = Vec::with_capacity(SAMPLES);
21682        let mut public_samples = Vec::with_capacity(SAMPLES);
21683        for sample in 0..SAMPLES {
21684            if sample.is_multiple_of(2) {
21685                former_samples.push(elapsed(&timestamps, former));
21686                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
21687            } else {
21688                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
21689                former_samples.push(elapsed(&timestamps, former));
21690            }
21691        }
21692        let former_p50 = percentile(&mut former_samples, 50);
21693        let former_p95 = percentile(&mut former_samples, 95);
21694        let public_p50 = percentile(&mut public_samples, 50);
21695        let public_p95 = percentile(&mut public_samples, 95);
21696        println!(
21697            "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}",
21698            former_p50 as f64 / public_p50 as f64,
21699            former_p95 as f64 / public_p95 as f64,
21700        );
21701        println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
21702        println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
21703    }
21704
21705    #[test]
21706    fn timestamp_day_name_and_month_name() {
21707        let ts = Timestamp::from_nanos(0);
21708        assert_eq!(ts.day_name(), "Thursday");
21709        assert_eq!(ts.month_name(), "January");
21710
21711        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
21712        assert_eq!(ts2.day_name(), "Friday");
21713        assert_eq!(ts2.month_name(), "January");
21714
21715        assert_eq!(Timestamp::nat().day_name(), "NaT");
21716        assert_eq!(Timestamp::nat().month_name(), "NaT");
21717    }
21718
21719    #[test]
21720    fn timestamp_replace_validates_components_zw0y2() {
21721        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
21722        let replaced = ts.replace(
21723            Some(2024),
21724            Some(2),
21725            Some(29),
21726            Some(23),
21727            Some(59),
21728            Some(58),
21729            Some(987_654),
21730            Some(321),
21731        );
21732        assert_eq!(replaced.year(), Some(2024));
21733        assert_eq!(replaced.month(), Some(2));
21734        assert_eq!(replaced.day(), Some(29));
21735        assert_eq!(replaced.hour(), Some(23));
21736        assert_eq!(replaced.minute(), Some(59));
21737        assert_eq!(replaced.second(), Some(58));
21738        assert_eq!(replaced.microsecond(), Some(987_654));
21739        assert_eq!(replaced.nanosecond(), Some(321));
21740
21741        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
21742        assert_eq!(
21743            tz.replace(None, Some(2), Some(29), None, None, None, None, None)
21744                .tz
21745                .as_deref(),
21746            Some("UTC")
21747        );
21748
21749        assert!(
21750            ts.replace(None, Some(13), None, None, None, None, None, None)
21751                .is_nat()
21752        );
21753        assert!(
21754            ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
21755                .is_nat()
21756        );
21757        assert!(
21758            ts.replace(None, None, None, Some(24), None, None, None, None)
21759                .is_nat()
21760        );
21761        assert!(
21762            ts.replace(None, None, None, None, Some(60), None, None, None)
21763                .is_nat()
21764        );
21765        assert!(
21766            ts.replace(None, None, None, None, None, Some(60), None, None)
21767                .is_nat()
21768        );
21769        assert!(
21770            ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
21771                .is_nat()
21772        );
21773        assert!(
21774            ts.replace(None, None, None, None, None, None, None, Some(1_000))
21775                .is_nat()
21776        );
21777        assert!(
21778            Timestamp::nat()
21779                .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
21780                .is_nat()
21781        );
21782    }
21783
21784    /// br-frankenpandas-dzz6x: `replace` validates every component EXCEPT the
21785    /// year, and i64 nanoseconds run out around year 2262. The old unchecked
21786    /// multiply wrapped in release mode and handed back a plausible-looking
21787    /// in-range instant for an unrepresentable year — the exact failure a naive
21788    /// implementation still produces, so each far-out year below is a real
21789    /// negative case, not a restatement of the code.
21790    #[test]
21791    fn timestamp_replace_returns_nat_on_nanosecond_overflow_dzz6x() {
21792        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
21793
21794        for year in [3000, 10_000, 300_000, i64::MAX / 400] {
21795            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
21796            assert!(
21797                out.is_nat(),
21798                "replace(year={year}) is unrepresentable in i64 ns and must be \
21799                 NaT, got nanos={:?} (year {:?}) — this is the silent wrap",
21800                out.nanos,
21801                out.year()
21802            );
21803        }
21804        for year in [-3000, -100_000, i64::MIN / 400] {
21805            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
21806            assert!(out.is_nat(), "replace(year={year}) must be NaT");
21807        }
21808
21809        // Boundary: i64 ns tops out at 106_751 days from the epoch, so 2262 is
21810        // representable at the start of the year and 2263 is not. This pins the
21811        // fix to the real limit — a guard that merely rejected "big" years by
21812        // some rounder cutoff would fail one side of this pair.
21813        let in_range = ts.replace(
21814            Some(2262),
21815            Some(1),
21816            Some(1),
21817            Some(0),
21818            Some(0),
21819            Some(0),
21820            Some(0),
21821            Some(0),
21822        );
21823        assert!(
21824            !in_range.is_nat(),
21825            "2262-01-01 is representable and must survive"
21826        );
21827        assert_eq!(in_range.year(), Some(2262));
21828        assert!(
21829            ts.replace(
21830                Some(2263),
21831                Some(12),
21832                Some(31),
21833                Some(23),
21834                Some(59),
21835                Some(59),
21836                Some(999_999),
21837                Some(999)
21838            )
21839            .is_nat(),
21840            "end of 2263 exceeds the i64 ns axis and must be NaT"
21841        );
21842
21843        // In-range results are untouched by the checked arithmetic, including
21844        // the timezone, so the guard cannot have been bought with a behavior
21845        // change on the normal path.
21846        let unchanged = ts.replace(
21847            Some(1999),
21848            Some(6),
21849            Some(30),
21850            Some(12),
21851            Some(1),
21852            Some(2),
21853            Some(3),
21854            Some(4),
21855        );
21856        assert_eq!(unchanged.year(), Some(1999));
21857        assert_eq!(unchanged.month(), Some(6));
21858        assert_eq!(unchanged.day(), Some(30));
21859        assert_eq!(unchanged.hour(), Some(12));
21860        assert_eq!(unchanged.minute(), Some(1));
21861        assert_eq!(unchanged.second(), Some(2));
21862        assert_eq!(unchanged.microsecond(), Some(3));
21863        assert_eq!(unchanged.nanosecond(), Some(4));
21864        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
21865        assert_eq!(
21866            tz.replace(Some(1999), None, None, None, None, None, None, None)
21867                .tz
21868                .as_deref(),
21869            Some("UTC")
21870        );
21871    }
21872
21873    #[test]
21874    fn timestamp_component_accessors() {
21875        let ts = Timestamp::from_nanos(0);
21876        assert_eq!(ts.year(), Some(1970));
21877        assert_eq!(ts.month(), Some(1));
21878        assert_eq!(ts.day(), Some(1));
21879        assert_eq!(ts.hour(), Some(0));
21880        assert_eq!(ts.minute(), Some(0));
21881        assert_eq!(ts.second(), Some(0));
21882        assert_eq!(ts.microsecond(), Some(0));
21883        assert_eq!(ts.nanosecond(), Some(0));
21884
21885        let ts2 = Timestamp::from_nanos(
21886            Timedelta::NANOS_PER_DAY * 365
21887                + Timedelta::NANOS_PER_HOUR * 14
21888                + Timedelta::NANOS_PER_MIN * 30
21889                + Timedelta::NANOS_PER_SEC * 45
21890                + 123_456_789,
21891        );
21892        assert_eq!(ts2.year(), Some(1971));
21893        assert_eq!(ts2.month(), Some(1));
21894        assert_eq!(ts2.day(), Some(1));
21895        assert_eq!(ts2.hour(), Some(14));
21896        assert_eq!(ts2.minute(), Some(30));
21897        assert_eq!(ts2.second(), Some(45));
21898        assert_eq!(ts2.microsecond(), Some(123456));
21899        assert_eq!(ts2.nanosecond(), Some(789));
21900
21901        assert_eq!(Timestamp::nat().year(), None);
21902        assert_eq!(Timestamp::nat().month(), None);
21903        assert_eq!(Timestamp::nat().day(), None);
21904    }
21905
21906    #[test]
21907    fn timestamp_dayofweek_dayofyear_quarter() {
21908        let ts = Timestamp::from_nanos(0);
21909        assert_eq!(ts.dayofweek(), Some(3));
21910        assert_eq!(ts.weekday(), Some(3));
21911        assert_eq!(ts.dayofyear(), Some(1));
21912        assert_eq!(ts.quarter(), Some(1));
21913
21914        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
21915        assert_eq!(ts2.quarter(), Some(2));
21916
21917        let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
21918        assert_eq!(ts3.dayofyear(), Some(1));
21919        assert_eq!(ts3.dayofweek(), Some(4));
21920
21921        assert_eq!(Timestamp::nat().dayofweek(), None);
21922        assert_eq!(Timestamp::nat().dayofyear(), None);
21923        assert_eq!(Timestamp::nat().quarter(), None);
21924    }
21925
21926    #[test]
21927    fn timestamp_is_boundary_methods() {
21928        let jan1 = Timestamp::from_nanos(0);
21929        assert_eq!(jan1.is_leap_year(), Some(false));
21930        assert_eq!(jan1.is_month_start(), Some(true));
21931        assert_eq!(jan1.is_month_end(), Some(false));
21932        assert_eq!(jan1.is_quarter_start(), Some(true));
21933        assert_eq!(jan1.is_quarter_end(), Some(false));
21934        assert_eq!(jan1.is_year_start(), Some(true));
21935        assert_eq!(jan1.is_year_end(), Some(false));
21936
21937        let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
21938        assert_eq!(dec31.is_month_start(), Some(false));
21939        assert_eq!(dec31.is_month_end(), Some(true));
21940        assert_eq!(dec31.is_quarter_end(), Some(true));
21941        assert_eq!(dec31.is_year_end(), Some(true));
21942
21943        assert_eq!(Timestamp::nat().is_leap_year(), None);
21944        assert_eq!(Timestamp::nat().is_month_start(), None);
21945    }
21946
21947    #[test]
21948    fn timestamp_days_in_month() {
21949        let jan = Timestamp::from_nanos(0);
21950        assert_eq!(jan.days_in_month(), Some(31));
21951        assert_eq!(jan.daysinmonth(), Some(31));
21952
21953        let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
21954        assert_eq!(feb_non_leap.days_in_month(), Some(28));
21955
21956        assert_eq!(Timestamp::nat().days_in_month(), None);
21957    }
21958
21959    #[test]
21960    fn timestamp_weekofyear() {
21961        let jan1 = Timestamp::from_nanos(0);
21962        assert_eq!(jan1.weekofyear(), Some(1));
21963        assert_eq!(jan1.week(), Some(1));
21964
21965        let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
21966        assert_eq!(jan8.weekofyear(), Some(2));
21967
21968        assert_eq!(Timestamp::nat().weekofyear(), None);
21969        assert_eq!(Timestamp::nat().week(), None);
21970    }
21971
21972    #[test]
21973    fn timestamp_weekofyear_iso_53_week_boundaries() {
21974        // ISO-8601 53-week-year boundaries vs pandas 2.2.3 isocalendar().week.
21975        // (br-frankenpandas-xmfmd) Date -> nanos via days since 1970-01-01.
21976        fn week_of(date_days: i64) -> Option<i64> {
21977            Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
21978        }
21979        // Days from 1970-01-01 for each date (UTC, no tz).
21980        // 2021-01-01 -> week 53 (2020 is a 53-week year); FP used to give 52.
21981        assert_eq!(week_of(18_628), Some(53)); // 2021-01-01
21982        // 2016-01-01 -> week 53 (2015 is a 53-week year).
21983        assert_eq!(week_of(16_801), Some(53)); // 2016-01-01
21984        // 2026-12-31 -> week 53; FP used to give 1.
21985        assert_eq!(week_of(20_818), Some(53)); // 2026-12-31
21986        // 2020-12-31 -> week 53.
21987        assert_eq!(week_of(18_627), Some(53)); // 2020-12-31
21988        // Cases that must stay correct (non-53 boundaries):
21989        assert_eq!(week_of(19_358), Some(52)); // 2023-01-01 -> week 52
21990        assert_eq!(week_of(20_087), Some(1)); // 2024-12-30 -> week 1
21991        assert_eq!(week_of(18_260), Some(1)); // 2019-12-30 -> week 1
21992    }
21993
21994    #[test]
21995    fn iso_weeks_in_year_53_week_years() {
21996        use super::iso_weeks_in_year;
21997        // Known 53-week years; everything else is 52.
21998        for y in [2004, 2009, 2015, 2020, 2026] {
21999            assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
22000        }
22001        for y in [2018, 2019, 2021, 2022, 2023, 2024] {
22002            assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
22003        }
22004    }
22005
22006    #[test]
22007    fn timestamp_to_unit() {
22008        let ts = Timestamp::from_nanos(1_000_000_000);
22009        assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
22010        assert_eq!(ts.to_unit("us"), Some(1_000_000));
22011        assert_eq!(ts.to_unit("ms"), Some(1_000));
22012        assert_eq!(ts.to_unit("s"), Some(1));
22013        assert_eq!(ts.to_unit("invalid"), None);
22014
22015        assert_eq!(Timestamp::nat().to_unit("ns"), None);
22016    }
22017
22018    #[test]
22019    fn timestamp_toordinal() {
22020        // 2026-01-01 is ordinal 738886 (days since Jan 1, year 1)
22021        // Days from Unix epoch: 738886 - 719163 = 19723
22022        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
22023        let ts = Timestamp::from_nanos(nanos_2026_01_01);
22024        assert_eq!(ts.toordinal(), Some(738886));
22025
22026        // NaT returns None
22027        assert_eq!(Timestamp::nat().toordinal(), None);
22028    }
22029
22030    #[test]
22031    fn timestamp_fromordinal() {
22032        // Round-trip test: create a timestamp from ordinal derived from toordinal
22033        // First create a known timestamp
22034        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
22035        let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
22036        let ordinal = ts_orig.toordinal().unwrap();
22037
22038        // Now convert back using fromordinal
22039        let ts = Timestamp::fromordinal(ordinal);
22040        assert_eq!(ts.year(), ts_orig.year());
22041        assert_eq!(ts.month(), ts_orig.month());
22042        assert_eq!(ts.day(), ts_orig.day());
22043
22044        // Invalid ordinal returns NaT
22045        let nat = Timestamp::fromordinal(0);
22046        assert!(nat.is_nat());
22047    }
22048
22049    #[test]
22050    fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
22051        const EPOCH_ORDINAL: i64 = 719_163;
22052        let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
22053        let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
22054
22055        let max_valid = Timestamp::fromordinal(max_valid_ordinal);
22056        assert!(!max_valid.is_nat());
22057        assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
22058
22059        assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
22060        assert!(Timestamp::fromordinal(i64::MAX).is_nat());
22061    }
22062
22063    #[test]
22064    fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
22065        const EPOCH_ORDINAL: i64 = 719_163;
22066        const DAY: i64 = Timedelta::NANOS_PER_DAY;
22067
22068        fn next(seed: &mut u64) -> u64 {
22069            *seed = seed
22070                .wrapping_mul(3202034522624059733)
22071                .wrapping_add(4354685564936845319);
22072            *seed
22073        }
22074
22075        fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
22076            let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
22077            let ts = Timestamp::from_nanos(nanos);
22078            let expected_day_offset = nanos.div_euclid(DAY);
22079            let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
22080
22081            assert_eq!(
22082                ts.toordinal(),
22083                Some(expected_ordinal),
22084                "case {case}: toordinal"
22085            );
22086
22087            let midnight = Timestamp::fromordinal(expected_ordinal);
22088            assert_eq!(
22089                midnight.nanos,
22090                expected_day_offset * DAY,
22091                "case {case}: fromordinal nanos"
22092            );
22093            assert_eq!(
22094                midnight.toordinal(),
22095                Some(expected_ordinal),
22096                "case {case}: fromordinal roundtrip"
22097            );
22098        }
22099
22100        assert_eq!(Timestamp::nat().toordinal(), None);
22101        assert!(Timestamp::fromordinal(0).is_nat());
22102        assert!(Timestamp::fromordinal(-1).is_nat());
22103
22104        assert_ordinal_case(usize::MAX, -1, DAY - 1);
22105        assert_ordinal_case(usize::MAX - 1, 0, -1);
22106        assert_ordinal_case(usize::MAX - 2, 19_723, 0);
22107
22108        let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
22109        for case in 0..260 {
22110            let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
22111            let subday_nanos = match case % 7 {
22112                0 => 0,
22113                1 => DAY - 1,
22114                2 => -1,
22115                _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
22116            };
22117            assert_ordinal_case(case, day_offset, subday_nanos);
22118        }
22119    }
22120
22121    /// br-frankenpandas-94o1u: `parse_date` bounds the month and the day but
22122    /// parses the YEAR as an unbounded i64, and i64 nanoseconds top out around
22123    /// 2262. The old unchecked composition wrapped in release, so these inputs
22124    /// returned `Ok` holding a plausible in-range instant instead of failing —
22125    /// on the INGESTION path, where the input is untrusted. Each case below is
22126    /// a real negative case: a naive implementation still returns Ok here.
22127    #[test]
22128    fn timestamp_parse_rejects_unrepresentable_years_94o1u() {
22129        for s in [
22130            "300000-01-01",
22131            "10000000-06-15T12:30:45",
22132            "999999999-01-01",
22133            "-300000-01-01",
22134            "-99999999-12-31T23:59:59",
22135        ] {
22136            let got = Timestamp::parse(s);
22137            assert!(
22138                got.is_err(),
22139                "parse({s:?}) is unrepresentable in i64 ns and must be Err, got {:?} \
22140                 — this is the silent wrap",
22141                got.map(|ts| (ts.nanos, ts.year()))
22142            );
22143        }
22144
22145        // Boundary: the i64 ns axis reaches into 2262 but not 2263. Pins the
22146        // guard to the real limit — a cutoff at some rounder year fails a side.
22147        let ok = Timestamp::parse("2262-01-01").expect("2262-01-01 is representable");
22148        assert_eq!(ok.year(), Some(2262));
22149        assert!(
22150            Timestamp::parse("2263-12-31T23:59:59").is_err(),
22151            "end of 2263 exceeds the i64 ns axis and must be Err"
22152        );
22153
22154        // A rejected year must not poison the normal path: ordinary parses,
22155        // including every accepted shape (date-only, T- and space-separated,
22156        // fractional seconds, tz suffix), still succeed and are unchanged.
22157        assert_eq!(Timestamp::parse("2024-01-15").unwrap().year(), Some(2024));
22158        assert_eq!(
22159            Timestamp::parse("2024-01-15T10:30:45").unwrap().hour(),
22160            Some(10)
22161        );
22162        assert_eq!(
22163            Timestamp::parse("2024-01-15 10:30:45").unwrap().minute(),
22164            Some(30)
22165        );
22166        assert_eq!(
22167            Timestamp::parse("2024-01-15T10:30:45.123456789")
22168                .unwrap()
22169                .nanosecond(),
22170            Some(789)
22171        );
22172        assert_eq!(
22173            Timestamp::parse("2024-01-15T00:00:00Z").unwrap().year(),
22174            Some(2024)
22175        );
22176        // Pre-epoch (negative nanos) is representable and must keep working.
22177        assert_eq!(Timestamp::parse("1900-01-01").unwrap().year(), Some(1900));
22178    }
22179
22180    #[test]
22181    fn timestamp_parse_iso8601_date_only() {
22182        let ts = Timestamp::parse("2024-01-15").unwrap();
22183        assert_eq!(ts.year(), Some(2024));
22184        assert_eq!(ts.month(), Some(1));
22185        assert_eq!(ts.day(), Some(15));
22186        assert_eq!(ts.hour(), Some(0));
22187        assert_eq!(ts.minute(), Some(0));
22188        assert_eq!(ts.second(), Some(0));
22189    }
22190
22191    #[test]
22192    fn timestamp_parse_iso8601_datetime() {
22193        let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
22194        assert_eq!(ts.year(), Some(2024));
22195        assert_eq!(ts.month(), Some(1));
22196        assert_eq!(ts.day(), Some(15));
22197        assert_eq!(ts.hour(), Some(10));
22198        assert_eq!(ts.minute(), Some(30));
22199        assert_eq!(ts.second(), Some(45));
22200    }
22201
22202    #[test]
22203    fn timestamp_parse_space_separator() {
22204        let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
22205        assert_eq!(ts.year(), Some(2024));
22206        assert_eq!(ts.hour(), Some(10));
22207    }
22208
22209    #[test]
22210    fn timestamp_parse_with_fractional_seconds() {
22211        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
22212        assert_eq!(ts.second(), Some(45));
22213        assert_eq!(ts.microsecond(), Some(123456));
22214        assert_eq!(ts.nanosecond(), Some(789));
22215    }
22216
22217    #[test]
22218    fn timestamp_parse_utc_timezone() {
22219        let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
22220        assert_eq!(ts.tz, Some("UTC".to_string()));
22221    }
22222
22223    #[test]
22224    fn timestamp_parse_offset_timezone() {
22225        let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
22226        assert_eq!(ts.tz, Some("+05:30".to_string()));
22227        // The instant is the wall time less the offset (it was the wall
22228        // time read as UTC).
22229        let utc = |text: &str| Timestamp::parse(text).unwrap().nanos;
22230        assert_eq!(ts.nanos, utc("2024-01-15T05:00:45"));
22231
22232        let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
22233        assert_eq!(ts.tz, Some("-05:30".to_string()));
22234        assert_eq!(ts.nanos, utc("2024-01-15T16:00:45"));
22235        // 'Z' is UTC itself.
22236        assert_eq!(
22237            Timestamp::parse("2024-01-15T10:30:45Z").unwrap().nanos,
22238            utc("2024-01-15T10:30:45")
22239        );
22240    }
22241
22242    #[test]
22243    fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
22244        assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
22245        assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
22246        assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
22247        assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
22248        assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
22249    }
22250
22251    #[test]
22252    fn timestamp_parse_nat() {
22253        let ts = Timestamp::parse("NaT").unwrap();
22254        assert!(ts.is_nat());
22255        let ts2 = Timestamp::parse("nat").unwrap();
22256        assert!(ts2.is_nat());
22257    }
22258
22259    #[test]
22260    fn timestamp_parse_invalid() {
22261        assert!(Timestamp::parse("not a date").is_err());
22262        assert!(Timestamp::parse("2024-13-01").is_err()); // invalid month
22263        assert!(Timestamp::parse("2024-01-32").is_err()); // invalid day
22264    }
22265
22266    #[test]
22267    fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
22268        assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
22269        assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
22270        assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
22271        assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
22272        assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
22273
22274        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
22275        assert_eq!(ts.second(), Some(45));
22276        assert_eq!(ts.microsecond(), Some(123456));
22277        assert_eq!(ts.nanosecond(), Some(789));
22278    }
22279
22280    #[test]
22281    #[ignore = "foreground profile-first A/B"]
22282    fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
22283        use std::{hint::black_box, time::Instant};
22284
22285        const CALLS: usize = 131_072;
22286        const SAMPLES: usize = 12;
22287        type ParsedTime = Option<(u32, u32, u32, u64)>;
22288        const VALID: [&str; 16] = [
22289            "00:00:00.0",
22290            "01:02:03.1",
22291            "02:03:04.01",
22292            "03:04:05.001",
22293            "04:05:06.0001",
22294            "05:06:07.00001",
22295            "06:07:08.000001",
22296            "07:08:09.0000001",
22297            "08:09:10.00000001",
22298            "09:10:11.000000001",
22299            "10:11:12.123456789",
22300            "11:12:13.999999999",
22301            "12:13:14.123456789987",
22302            "13:14:15.000000000001",
22303            "14:15:16.101010101010",
22304            "23:59:59.987654321234",
22305        ];
22306
22307        #[inline(never)]
22308        fn former(s: &str) -> ParsedTime {
22309            let (time_str, frac_str) = match s.split_once('.') {
22310                Some((time, frac)) => (time, Some(frac)),
22311                None => (s, None),
22312            };
22313            let parts: Vec<&str> = time_str.split(':').collect();
22314            if parts.is_empty() || parts.len() > 3 {
22315                return None;
22316            }
22317            let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
22318            let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
22319            let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
22320
22321            if hour > 23 || minute > 59 || second > 59 {
22322                return None;
22323            }
22324
22325            let nanos = match frac_str {
22326                None => 0,
22327                Some(frac) => {
22328                    if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
22329                        return None;
22330                    }
22331                    let truncated = &frac[..frac.len().min(9)];
22332                    let padded = format!("{truncated:0<9}");
22333                    padded.parse::<u64>().ok()?
22334                }
22335            };
22336
22337            Some((hour, minute, second, nanos))
22338        }
22339
22340        #[inline(never)]
22341        fn candidate(s: &str) -> ParsedTime {
22342            Timestamp::parse_time(s)
22343        }
22344
22345        fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
22346            let started = Instant::now();
22347            for input in black_box(inputs) {
22348                black_box(parser(black_box(*input)));
22349            }
22350            started.elapsed().as_nanos()
22351        }
22352
22353        fn percentile(samples: &[u128], percent: usize) -> u128 {
22354            let mut sorted = samples.to_vec();
22355            sorted.sort_unstable();
22356            let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
22357            sorted[rank]
22358        }
22359
22360        let invalid = [
22361            "",
22362            "24:00:00.1",
22363            "12:60:00.1",
22364            "12:00:60.1",
22365            "12:00:00.",
22366            "12:00:00.abc",
22367            "12:00:00.-1",
22368            "12:00:00.123",
22369            "12:00:00.123456789x",
22370            "12:00:00.1.2",
22371            "12:00:00:01.1",
22372        ];
22373        for input in VALID.iter().chain(invalid.iter()) {
22374            assert_eq!(candidate(input), former(input), "input={input:?}");
22375        }
22376
22377        let inputs = (0..CALLS)
22378            .map(|index| VALID[index % VALID.len()])
22379            .collect::<Vec<_>>();
22380        for _ in 0..2 {
22381            black_box(elapsed(&inputs, former));
22382            black_box(elapsed(&inputs, candidate));
22383        }
22384
22385        let mut former_ns = Vec::with_capacity(SAMPLES);
22386        let mut candidate_ns = Vec::with_capacity(SAMPLES);
22387        for sample in 0..SAMPLES {
22388            if sample.is_multiple_of(2) {
22389                former_ns.push(elapsed(&inputs, former));
22390                candidate_ns.push(elapsed(&inputs, candidate));
22391            } else {
22392                candidate_ns.push(elapsed(&inputs, candidate));
22393                former_ns.push(elapsed(&inputs, former));
22394            }
22395        }
22396
22397        let former_p50 = percentile(&former_ns, 50);
22398        let former_p95 = percentile(&former_ns, 95);
22399        let former_p99 = percentile(&former_ns, 99);
22400        let candidate_p50 = percentile(&candidate_ns, 50);
22401        let candidate_p95 = percentile(&candidate_ns, 95);
22402        let candidate_p99 = percentile(&candidate_ns, 99);
22403        println!(
22404            "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:?}",
22405            former_p50 as f64 / candidate_p50 as f64,
22406            former_p95 as f64 / candidate_p95 as f64,
22407            former_p99 as f64 / candidate_p99 as f64,
22408        );
22409    }
22410
22411    #[test]
22412    fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
22413        fn next(seed: &mut u64) -> u64 {
22414            *seed = seed
22415                .wrapping_mul(3935559000370003845)
22416                .wrapping_add(2691343689449507681);
22417            *seed
22418        }
22419
22420        fn leap(year: i64) -> bool {
22421            (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
22422        }
22423
22424        fn month_len(year: i64, month: u32) -> u32 {
22425            match month {
22426                1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
22427                4 | 6 | 9 | 11 => 30,
22428                2 if leap(year) => 29,
22429                2 => 28,
22430                _ => 0,
22431            }
22432        }
22433
22434        struct Components {
22435            year: i64,
22436            month: u32,
22437            day: u32,
22438            hour: u32,
22439            minute: u32,
22440            second: u32,
22441            nanos: u64,
22442        }
22443
22444        fn assert_components(case: usize, text: &str, expected: Components) {
22445            let ts = Timestamp::parse(text).expect("seeded valid timestamp");
22446            let Components {
22447                year,
22448                month,
22449                day,
22450                hour,
22451                minute,
22452                second,
22453                nanos,
22454            } = expected;
22455            assert_eq!(ts.year(), Some(year), "case {case}: year");
22456            assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
22457            assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
22458            assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
22459            assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
22460            assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
22461            assert_eq!(
22462                ts.microsecond(),
22463                Some((nanos / 1000) as i64),
22464                "case {case}: microsecond"
22465            );
22466            assert_eq!(
22467                ts.nanosecond(),
22468                Some((nanos % 1000) as i64),
22469                "case {case}: nanosecond"
22470            );
22471        }
22472
22473        assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
22474        assert!(
22475            Timestamp::parse("nAt")
22476                .expect("mixed-case NaT parses")
22477                .is_nat()
22478        );
22479        assert!(Timestamp::parse("1900-02-29").is_err());
22480        assert!(Timestamp::parse("2001-04-31").is_err());
22481        assert!(Timestamp::parse("2024-00-15").is_err());
22482
22483        assert_components(
22484            usize::MAX,
22485            "2000-02-29",
22486            Components {
22487                year: 2000,
22488                month: 2,
22489                day: 29,
22490                hour: 0,
22491                minute: 0,
22492                second: 0,
22493                nanos: 0,
22494            },
22495        );
22496        assert_components(
22497            usize::MAX - 1,
22498            "2024-02-29T23:59:59.000000001",
22499            Components {
22500                year: 2024,
22501                month: 2,
22502                day: 29,
22503                hour: 23,
22504                minute: 59,
22505                second: 59,
22506                nanos: 1,
22507            },
22508        );
22509
22510        let mut seed = 0x15e0_1d50_1f0a_cade_u64;
22511        for case in 0..260 {
22512            let year = 1900 + (next(&mut seed) % 201) as i64;
22513            let month = 1 + (next(&mut seed) % 12) as u32;
22514            let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
22515            let hour = (next(&mut seed) % 24) as u32;
22516            let minute = (next(&mut seed) % 60) as u32;
22517            let second = (next(&mut seed) % 60) as u32;
22518            let nanos = next(&mut seed) % 1_000_000_000;
22519
22520            match case % 4 {
22521                0 => {
22522                    let text = format!("{year:04}-{month:02}-{day:02}");
22523                    assert_components(
22524                        case,
22525                        &text,
22526                        Components {
22527                            year,
22528                            month,
22529                            day,
22530                            hour: 0,
22531                            minute: 0,
22532                            second: 0,
22533                            nanos: 0,
22534                        },
22535                    );
22536                }
22537                1 => {
22538                    let text =
22539                        format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
22540                    assert_components(
22541                        case,
22542                        &text,
22543                        Components {
22544                            year,
22545                            month,
22546                            day,
22547                            hour,
22548                            minute,
22549                            second,
22550                            nanos: 0,
22551                        },
22552                    );
22553                }
22554                2 => {
22555                    let text =
22556                        format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
22557                    assert_components(
22558                        case,
22559                        &text,
22560                        Components {
22561                            year,
22562                            month,
22563                            day,
22564                            hour,
22565                            minute,
22566                            second,
22567                            nanos: 0,
22568                        },
22569                    );
22570                }
22571                _ => {
22572                    let text = format!(
22573                        "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
22574                    );
22575                    assert_components(
22576                        case,
22577                        &text,
22578                        Components {
22579                            year,
22580                            month,
22581                            day,
22582                            hour,
22583                            minute,
22584                            second,
22585                            nanos,
22586                        },
22587                    );
22588                }
22589            }
22590        }
22591    }
22592
22593    #[test]
22594    fn period_parse_annual() {
22595        let p = Period::parse("2024").unwrap();
22596        assert_eq!(p.freq(), PeriodFreq::ANNUAL);
22597        assert_eq!(p.ordinal(), 2024 - 1970);
22598    }
22599
22600    #[test]
22601    fn period_parse_quarterly() {
22602        let p = Period::parse("2024Q1").unwrap();
22603        assert_eq!(p.freq(), PeriodFreq::QUARTERLY);
22604        assert_eq!(p.ordinal(), (2024 - 1970) * 4);
22605
22606        let p2 = Period::parse("2024q3").unwrap();
22607        assert_eq!(p2.freq(), PeriodFreq::QUARTERLY);
22608        assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
22609    }
22610
22611    #[test]
22612    fn period_parse_monthly() {
22613        let p = Period::parse("2024-01").unwrap();
22614        assert_eq!(p.freq(), PeriodFreq::Monthly);
22615        assert_eq!(p.ordinal(), (2024 - 1970) * 12);
22616
22617        let p2 = Period::parse("2024-12").unwrap();
22618        assert_eq!(p2.freq(), PeriodFreq::Monthly);
22619        assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
22620    }
22621
22622    #[test]
22623    fn period_parse_nat() {
22624        let p = Period::parse("NaT").unwrap();
22625        assert_eq!(p.ordinal(), i64::MIN);
22626    }
22627
22628    #[test]
22629    fn period_parse_invalid() {
22630        assert!(Period::parse("not a period").is_err());
22631        assert!(Period::parse("2024Q5").is_err()); // invalid quarter
22632        assert!(Period::parse("2024-13").is_err()); // invalid month
22633    }
22634
22635    #[test]
22636    fn interval_parse_basic() {
22637        let i = Interval::parse("[0, 1]").unwrap();
22638        assert_eq!(i.left, 0.0);
22639        assert_eq!(i.right, 1.0);
22640        assert_eq!(i.closed, IntervalClosed::Both);
22641
22642        let i2 = Interval::parse("(0, 1)").unwrap();
22643        assert_eq!(i2.left, 0.0);
22644        assert_eq!(i2.right, 1.0);
22645        assert_eq!(i2.closed, IntervalClosed::Neither);
22646
22647        let i3 = Interval::parse("[0, 1)").unwrap();
22648        assert_eq!(i3.closed, IntervalClosed::Left);
22649
22650        let i4 = Interval::parse("(0, 1]").unwrap();
22651        assert_eq!(i4.closed, IntervalClosed::Right);
22652    }
22653
22654    #[test]
22655    fn interval_parse_floats() {
22656        let i = Interval::parse("[-1.5, 2.5)").unwrap();
22657        assert_eq!(i.left, -1.5);
22658        assert_eq!(i.right, 2.5);
22659        assert_eq!(i.closed, IntervalClosed::Left);
22660    }
22661
22662    #[test]
22663    fn interval_parse_invalid() {
22664        assert!(Interval::parse("invalid").is_err());
22665        assert!(Interval::parse("[0]").is_err());
22666        assert!(Interval::parse("0, 1").is_err()); // missing brackets
22667    }
22668
22669    fn interval_parse_error_profile(s: &str) -> super::TypeError {
22670        super::TypeError::ValueNotParseable {
22671            value: s.to_string(),
22672            target: "Interval".to_string(),
22673        }
22674    }
22675
22676    #[inline(never)]
22677    fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
22678        let s = std::hint::black_box(s).trim();
22679        if s.len() < 5 {
22680            return Err(interval_parse_error_profile(s));
22681        }
22682
22683        let first_char = s.chars().next().unwrap();
22684        let last_char = s.chars().last().unwrap();
22685        let left_closed = match first_char {
22686            '[' => true,
22687            '(' => false,
22688            _ => return Err(interval_parse_error_profile(s)),
22689        };
22690        let right_closed = match last_char {
22691            ']' => true,
22692            ')' => false,
22693            _ => return Err(interval_parse_error_profile(s)),
22694        };
22695        let closed = match (left_closed, right_closed) {
22696            (true, true) => IntervalClosed::Both,
22697            (true, false) => IntervalClosed::Left,
22698            (false, true) => IntervalClosed::Right,
22699            (false, false) => IntervalClosed::Neither,
22700        };
22701
22702        let inner = &s[1..s.len() - 1];
22703        let parts: Vec<&str> = inner.split(',').collect();
22704        if parts.len() != 2 {
22705            return Err(interval_parse_error_profile(s));
22706        }
22707        let left = parts[0]
22708            .trim()
22709            .parse()
22710            .map_err(|_| interval_parse_error_profile(s))?;
22711        let right = parts[1]
22712            .trim()
22713            .parse()
22714            .map_err(|_| interval_parse_error_profile(s))?;
22715        Ok(Interval::new(left, right, closed))
22716    }
22717
22718    #[inline(never)]
22719    fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
22720        Interval::parse(std::hint::black_box(s))
22721    }
22722
22723    fn assert_interval_parse_profile_parity(s: &str) {
22724        match (
22725            interval_parse_former_profile(s),
22726            interval_parse_split_once_profile(s),
22727        ) {
22728            (Ok(former), Ok(candidate)) => {
22729                assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
22730                assert_eq!(
22731                    former.right.to_bits(),
22732                    candidate.right.to_bits(),
22733                    "right: {s}"
22734                );
22735                assert_eq!(former.closed, candidate.closed, "closed: {s}");
22736            }
22737            (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
22738            (former, candidate) => assert_eq!(
22739                former.is_ok(),
22740                candidate.is_ok(),
22741                "parse result mismatch for {s}: {former:?} != {candidate:?}"
22742            ),
22743        }
22744    }
22745
22746    #[inline(never)]
22747    fn measure_interval_parser_profile(
22748        parser: fn(&str) -> Result<Interval, super::TypeError>,
22749        inputs: &[&str],
22750        rounds: usize,
22751    ) -> u128 {
22752        use std::{hint::black_box, time::Instant};
22753
22754        let started = Instant::now();
22755        let mut checksum = 0_u64;
22756        for _ in 0..rounds {
22757            for input in inputs {
22758                let parsed = parser(black_box(input)).expect("profile input must parse");
22759                let closed = match parsed.closed {
22760                    IntervalClosed::Left => 1_u64,
22761                    IntervalClosed::Right => 2,
22762                    IntervalClosed::Both => 3,
22763                    IntervalClosed::Neither => 4,
22764                };
22765                checksum = checksum
22766                    .wrapping_add(parsed.left.to_bits().rotate_left(7))
22767                    .wrapping_add(parsed.right.to_bits().rotate_right(11))
22768                    .wrapping_add(closed);
22769                black_box(parsed);
22770            }
22771        }
22772        black_box(checksum);
22773        started.elapsed().as_nanos()
22774    }
22775
22776    #[test]
22777    #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
22778    fn profile_interval_parse_endpoint_split_ab_81jjv() {
22779        const VALID: [&str; 8] = [
22780            "[0, 1]",
22781            "(-0.0, 0.0]",
22782            " [ -1.5e3 , 2.75E-4 ) ",
22783            "(NaN, -0]",
22784            "[-inf, inf)",
22785            "[9.25, -7.5]",
22786            "(4.9406564584124654e-324, 1.7976931348623157e308)",
22787            "[-42, 17.125)",
22788        ];
22789        const INVALID: [&str; 12] = [
22790            "invalid",
22791            "[0]",
22792            "0, 1",
22793            "[0 1]",
22794            "[0, 1, 2]",
22795            "[0, 1,]",
22796            "[0,,1]",
22797            "[, 1]",
22798            "[0, ]",
22799            "{0, 1}",
22800            "[0, 1}",
22801            "  ⟦0, 1⟧  ",
22802        ];
22803        const ROUNDS: usize = 16_384;
22804        const SAMPLES: usize = 10;
22805
22806        for input in VALID.iter().chain(INVALID.iter()) {
22807            assert_interval_parse_profile_parity(input);
22808        }
22809        for _ in 0..2 {
22810            measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
22811            measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
22812        }
22813
22814        let mut former_ns = Vec::with_capacity(SAMPLES);
22815        let mut candidate_ns = Vec::with_capacity(SAMPLES);
22816        for sample in 0..SAMPLES {
22817            if sample % 2 == 0 {
22818                former_ns.push(measure_interval_parser_profile(
22819                    interval_parse_former_profile,
22820                    &VALID,
22821                    ROUNDS,
22822                ));
22823                candidate_ns.push(measure_interval_parser_profile(
22824                    interval_parse_split_once_profile,
22825                    &VALID,
22826                    ROUNDS,
22827                ));
22828            } else {
22829                candidate_ns.push(measure_interval_parser_profile(
22830                    interval_parse_split_once_profile,
22831                    &VALID,
22832                    ROUNDS,
22833                ));
22834                former_ns.push(measure_interval_parser_profile(
22835                    interval_parse_former_profile,
22836                    &VALID,
22837                    ROUNDS,
22838                ));
22839            }
22840        }
22841        former_ns.sort_unstable();
22842        candidate_ns.sort_unstable();
22843        let former_p50 = former_ns[SAMPLES / 2];
22844        let candidate_p50 = candidate_ns[SAMPLES / 2];
22845        let former_p95 = former_ns[SAMPLES - 1];
22846        let candidate_p95 = candidate_ns[SAMPLES - 1];
22847        println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
22848        println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
22849        println!(
22850            "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
22851            former_p50 as f64 / candidate_p50 as f64
22852        );
22853        println!(
22854            "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
22855            former_p95 as f64 / candidate_p95 as f64
22856        );
22857    }
22858}
22859
22860/// `DType::Float64Nullable` — pandas' `Float64Dtype()`, the dtype a nullable
22861/// Int64 lane widens INTO (br-frankenpandas-qkqfb).
22862///
22863/// Every rule asserted here was measured against live pandas 2.2.3 before it was
22864/// written; the measurement is quoted next to the assertion it justifies.
22865#[cfg(test)]
22866mod float64_nullable_qkqfb {
22867    use super::{DType, NullKind, Scalar, cast_scalar, common_dtype};
22868
22869    /// THE POINT OF THE DTYPE. A numpy float lane's missing value is a real NaN;
22870    /// the extension lane's is pd.NA. If both mapped to the same marker the two
22871    /// flavours would be indistinguishable and the dtype would buy nothing.
22872    ///
22873    /// MEASURED, live pandas 2.2.3:
22874    /// ```text
22875    ///   pd.Series([1.5, None], dtype="Float64")[1]     -> <NA>   (is pd.NA)
22876    ///   pd.Series([1.5, None])[1]                      -> nan
22877    ///   pd.Series([float("nan")], dtype="Float64")[0]  -> <NA>   COERCED
22878    /// ```
22879    #[test]
22880    fn the_two_float_flavours_have_different_missing_markers_qkqfb() {
22881        assert_eq!(
22882            Scalar::missing_for_dtype(DType::Float64Nullable),
22883            Scalar::Null(NullKind::Null),
22884            "the extension lane stores pd.NA"
22885        );
22886        assert_eq!(
22887            Scalar::missing_for_dtype(DType::Float64),
22888            Scalar::Null(NullKind::NaN),
22889            "the numpy lane stores a real NaN"
22890        );
22891        // The negative case: collapsing these two is precisely the defect, so
22892        // assert they are NOT equal rather than only asserting each value.
22893        assert_ne!(
22894            Scalar::missing_for_dtype(DType::Float64Nullable),
22895            Scalar::missing_for_dtype(DType::Float64),
22896        );
22897    }
22898
22899    /// MEASURED: `str(pd.Float64Dtype())` is `"Float64"`, and the numpy dtype is
22900    /// `"float64"`. dtype-check fixtures assert pandas' SPELLING
22901    /// (br-frankenpandas-62d1s), so the capital F is load-bearing, not cosmetic.
22902    #[test]
22903    fn spelling_is_pandas_spelling_qkqfb() {
22904        assert_eq!(DType::Float64Nullable.name(), "Float64");
22905        assert_eq!(DType::Float64.name(), "float64");
22906        assert_ne!(DType::Float64Nullable.name(), DType::Float64.name());
22907    }
22908
22909    /// The serde spelling has to survive a round trip AND stay distinct from the
22910    /// numpy flavour. `rename_all = "snake_case"` turns `Float64` into
22911    /// `"float64"`, which is what leaves `"Float64"` free for the extension —
22912    /// the same trick `Int64Nullable` already relies on. A naive
22913    /// `#[serde(rename = "Float64")]` on the WRONG variant would collide, and
22914    /// this test is what would catch it.
22915    #[test]
22916    fn serde_round_trips_and_does_not_collide_with_numpy_float64_qkqfb() {
22917        let ext = serde_json::to_string(&DType::Float64Nullable).expect("serialize");
22918        let numpy = serde_json::to_string(&DType::Float64).expect("serialize");
22919        assert_eq!(ext, "\"Float64\"");
22920        assert_eq!(numpy, "\"float64\"");
22921        assert_ne!(ext, numpy);
22922
22923        assert_eq!(
22924            serde_json::from_str::<DType>(&ext).expect("deserialize"),
22925            DType::Float64Nullable
22926        );
22927        assert_eq!(
22928            serde_json::from_str::<DType>(&numpy).expect("deserialize"),
22929            DType::Float64
22930        );
22931    }
22932
22933    /// It is a float, it is numeric, and it is a nullable extension — all three,
22934    /// or downstream dtype dispatch silently skips it.
22935    #[test]
22936    fn predicates_place_it_in_the_right_families_qkqfb() {
22937        assert!(DType::Float64Nullable.is_floating());
22938        assert!(DType::Float64Nullable.is_numeric());
22939        assert!(DType::Float64Nullable.is_any_real_numeric());
22940        assert!(DType::Float64Nullable.is_nullable());
22941        assert!(DType::Float64Nullable.is_extension());
22942        // And NOT these: an integer predicate that accepted it would let a
22943        // float value through an int-only fast path.
22944        assert!(!DType::Float64Nullable.is_integer());
22945        assert!(!DType::Float64Nullable.is_signed_integer());
22946        assert!(!DType::Float64Nullable.is_bool());
22947        // MEASURED: pd.Float64Dtype().kind == 'f', matching numpy float64 --
22948        // the extension reports its UNDERLYING kind, as Int64Nullable does.
22949        assert_eq!(DType::Float64Nullable.kind(), 'f');
22950        assert_eq!(DType::Float64Nullable.kind(), DType::Float64.kind());
22951        assert_eq!(DType::Float64Nullable.itemsize(), 8);
22952    }
22953
22954    /// The nullable/non-nullable pairing must be a genuine involution, or a
22955    /// round trip through either accessor silently changes flavour.
22956    #[test]
22957    fn nullable_pairing_is_an_involution_qkqfb() {
22958        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
22959        assert_eq!(DType::Float64Nullable.to_non_nullable(), DType::Float64);
22960        // Idempotent at both ends.
22961        assert_eq!(DType::Float64Nullable.to_nullable(), DType::Float64Nullable);
22962        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
22963        // The other families are untouched by the new variant.
22964        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
22965        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
22966    }
22967
22968    /// MEASURED ARITHMETIC, live pandas 2.2.3 -- this function models arithmetic
22969    /// promotion, not `find_common_type` (see the Bool arms in `common_dtype`):
22970    /// ```text
22971    ///   Float64(ext) + float64(numpy)  -> Float64
22972    ///   Int64(ext)   + Float64(ext)    -> Float64
22973    ///   boolean(ext) + Float64(ext)    -> Float64
22974    ///   Float64(ext) - Float64(ext)    -> Float64
22975    /// ```
22976    /// The nullable float absorbs every other numeric flavour.
22977    #[test]
22978    fn the_nullable_float_absorbs_every_numeric_flavour_qkqfb() {
22979        for other in [
22980            DType::Float64,
22981            DType::Int64,
22982            DType::Int64Nullable,
22983            DType::Bool,
22984            DType::BoolNullable,
22985            DType::Float64Nullable,
22986        ] {
22987            assert_eq!(
22988                common_dtype(DType::Float64Nullable, other.clone()),
22989                Ok(DType::Float64Nullable),
22990                "Float64Nullable + {other:?}"
22991            );
22992            // Commutativity is asserted wholesale by
22993            // common_dtype_lattice_axioms_be314; repeated here because an
22994            // asymmetric arm makes df1+df2 disagree with df2+df1.
22995            assert_eq!(
22996                common_dtype(other.clone(), DType::Float64Nullable),
22997                Ok(DType::Float64Nullable),
22998                "{other:?} + Float64Nullable"
22999            );
23000        }
23001        // Null is the lattice identity and must not absorb it.
23002        assert_eq!(
23003            common_dtype(DType::Null, DType::Float64Nullable),
23004            Ok(DType::Float64Nullable)
23005        );
23006    }
23007
23008    /// A PRESENT value crosses between the two float flavours unchanged; only the
23009    /// MISSING marker is converted.
23010    ///
23011    /// MEASURED:
23012    /// ```text
23013    ///   pd.Series([1.5,None],dtype="Float64").astype("float64") -> [1.5, nan]
23014    ///   pd.Series([1,None],  dtype="Int64").astype("Float64")   -> [1.0, <NA>]
23015    /// ```
23016    #[test]
23017    fn casts_preserve_values_and_convert_only_the_marker_qkqfb() {
23018        let present = Scalar::Float64(1.5);
23019        assert_eq!(
23020            cast_scalar(&present, DType::Float64Nullable),
23021            Ok(Scalar::Float64(1.5))
23022        );
23023        assert_eq!(
23024            cast_scalar(&Scalar::Float64(1.5), DType::Float64),
23025            Ok(Scalar::Float64(1.5))
23026        );
23027        // Int -> nullable float widens the value, as pandas does.
23028        assert_eq!(
23029            cast_scalar(&Scalar::Int64(1), DType::Float64Nullable),
23030            Ok(Scalar::Float64(1.0))
23031        );
23032        assert_eq!(
23033            cast_scalar(&Scalar::Bool(true), DType::Float64Nullable),
23034            Ok(Scalar::Float64(1.0))
23035        );
23036
23037        // THE MARKER CONVERSION, in both directions. This is the assertion a
23038        // "just alias Float64Nullable to Float64" implementation fails.
23039        assert_eq!(
23040            cast_scalar(&Scalar::Null(NullKind::NaN), DType::Float64Nullable),
23041            Ok(Scalar::Null(NullKind::Null)),
23042            "numpy NaN entering an extension lane becomes pd.NA"
23043        );
23044        assert_eq!(
23045            cast_scalar(&Scalar::Null(NullKind::Null), DType::Float64),
23046            Ok(Scalar::Null(NullKind::NaN)),
23047            "pd.NA entering a numpy lane becomes NaN"
23048        );
23049    }
23050
23051    /// The slice boundary this test used to pin has now been crossed: a
23052    /// nullable lane widening against a numpy float answers the NULLABLE float.
23053    /// MEASURED, live pandas 2.2.3, both spellings:
23054    /// ```text
23055    ///   find_common_type([Int64, float64])                        ->  Float64
23056    ///   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5])  ->  Float64
23057    /// ```
23058    /// (`Float64` there is the EXTENSION dtype — `Float64Dtype()` — not numpy
23059    /// `float64`.) br-frankenpandas-qkqfb; unblocks br-frankenpandas-f0aaa.
23060    #[test]
23061    fn int64nullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
23062        assert_eq!(
23063            common_dtype(DType::Int64Nullable, DType::Float64),
23064            Ok(DType::Float64Nullable)
23065        );
23066        assert_eq!(
23067            common_dtype(DType::Float64, DType::Int64Nullable),
23068            Ok(DType::Float64Nullable)
23069        );
23070    }
23071
23072    /// The BoolNullable sibling, MEASURED on the same pandas:
23073    /// ```text
23074    ///   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
23075    ///       -> Float64   (extension)
23076    /// ```
23077    /// The numpy-bool lane is NOT affected and stays on numpy float64, which is
23078    /// the control that keeps this from being a blanket "nullable everywhere".
23079    #[test]
23080    fn boolnullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
23081        assert_eq!(
23082            common_dtype(DType::BoolNullable, DType::Float64),
23083            Ok(DType::Float64Nullable)
23084        );
23085        assert_eq!(
23086            common_dtype(DType::Bool, DType::Float64),
23087            Ok(DType::Float64),
23088            "numpy bool + numpy float stays entirely on the numpy side"
23089        );
23090    }
23091
23092    /// ⚠ WHY THOSE TWO ARMS CANNOT MOVE INDEPENDENTLY. This is the exact triple
23093    /// that fails if only the Int64Nullable arm is flipped, spelled out so the
23094    /// coupling survives someone later "simplifying" one arm back:
23095    /// ```text
23096    ///   (BoolNullable ∨ Int64) ∨ Float64 = Int64Nullable ∨ Float64 = Float64Nullable
23097    ///   BoolNullable ∨ (Int64 ∨ Float64) = BoolNullable  ∨ Float64 = ???
23098    /// ```
23099    /// `common_dtype_lattice_axioms_be314` sweeps this for all 14 dtypes; this
23100    /// test names the single witness so a failure is diagnosable without
23101    /// re-deriving it from a 14³ sweep. (br-frankenpandas-qkqfb)
23102    #[test]
23103    fn the_nullable_float_flip_is_associative_on_its_witness_triple_qkqfb() {
23104        let (bn, i64n, f64d) = (DType::BoolNullable, DType::Int64, DType::Float64);
23105
23106        let left = common_dtype(
23107            common_dtype(bn.clone(), i64n.clone()).unwrap(),
23108            f64d.clone(),
23109        )
23110        .unwrap();
23111        let right = common_dtype(bn, common_dtype(i64n, f64d).unwrap()).unwrap();
23112
23113        assert_eq!(left, right, "promotion order must not change the result");
23114        assert_eq!(left, DType::Float64Nullable);
23115    }
23116}
23117
23118/// br-frankenpandas-3gxc6: the Sparse dtype NAME is parameterized in pandas.
23119///
23120/// Every expectation below was read off live pandas 2.2.3 before the code was
23121/// written, via `str(dtype)` / `dtype.name` on a `pd.SparseDtype`.
23122#[cfg(test)]
23123mod sparse_dtype_pandas_name_3gxc6 {
23124    use super::{DType, Scalar, SparseDType};
23125
23126    fn name(value_dtype: DType, fill: Scalar) -> String {
23127        SparseDType::new(value_dtype, fill)
23128            .expect("sparse descriptor")
23129            .pandas_name()
23130    }
23131
23132    /// The row the corpus fixture `fp_p2d_017_series_dtype_sparse_strict`
23133    /// exercises. FrankenPandas used to answer the bare `"Sparse"`.
23134    #[test]
23135    fn int64_fill_zero_is_the_fixture_row() {
23136        assert_eq!(name(DType::Int64, Scalar::Int64(0)), "Sparse[int64, 0]");
23137    }
23138
23139    /// A non-default fill must appear, or the name would be a constant wearing
23140    /// a parameterized shape.
23141    #[test]
23142    fn the_fill_value_is_actually_rendered() {
23143        assert_eq!(name(DType::Int64, Scalar::Int64(7)), "Sparse[int64, 7]");
23144        assert_ne!(
23145            name(DType::Int64, Scalar::Int64(0)),
23146            name(DType::Int64, Scalar::Int64(7)),
23147            "two different fills must not collapse to one name"
23148        );
23149    }
23150
23151    /// pandas spells this `nan`, lowercase, not `NaN` and not `None`.
23152    #[test]
23153    fn float64_nan_fill_is_lowercase_nan() {
23154        assert_eq!(
23155            name(DType::Float64, Scalar::Float64(f64::NAN)),
23156            "Sparse[float64, nan]"
23157        );
23158    }
23159
23160    /// pandas keeps the trailing `.0` here. A `{}`-style float format would
23161    /// render `0` and silently make this name collide with the int64 one.
23162    #[test]
23163    fn float64_zero_fill_keeps_its_trailing_point_zero() {
23164        assert_eq!(
23165            name(DType::Float64, Scalar::Float64(0.0)),
23166            "Sparse[float64, 0.0]"
23167        );
23168        assert_ne!(
23169            name(DType::Float64, Scalar::Float64(0.0)),
23170            name(DType::Int64, Scalar::Int64(0)),
23171            "float64 and int64 zero fills are different dtypes"
23172        );
23173    }
23174
23175    /// Python capitalisation, not Rust's `false`.
23176    #[test]
23177    fn bool_fill_uses_python_capitalisation() {
23178        assert_eq!(
23179            name(DType::Bool, Scalar::Bool(false)),
23180            "Sparse[bool, False]"
23181        );
23182        assert_eq!(name(DType::Bool, Scalar::Bool(true)), "Sparse[bool, True]");
23183    }
23184
23185    /// FP spells its object dtype `object`, which is what pandas prints for a
23186    /// `SparseDtype(object, nan)`.
23187    #[test]
23188    fn utf8_subtype_renders_as_object() {
23189        let rendered = name(DType::Utf8, Scalar::Null(crate::NullKind::NaN));
23190        assert!(
23191            rendered.starts_with("Sparse[object, "),
23192            "expected an object subtype, got {rendered}"
23193        );
23194    }
23195
23196    /// The bare name is what this bead removed; guard against a regression
23197    /// that reintroduces it for any constructible descriptor.
23198    #[test]
23199    fn no_constructible_descriptor_renders_the_bare_name() {
23200        for (dtype, fill) in [
23201            (DType::Int64, Scalar::Int64(0)),
23202            (DType::Float64, Scalar::Float64(1.5)),
23203            (DType::Bool, Scalar::Bool(true)),
23204            (DType::Utf8, Scalar::Utf8("x".to_owned())),
23205        ] {
23206            let rendered = name(dtype.clone(), fill);
23207            assert_ne!(rendered, "Sparse", "bare name regressed for {dtype:?}");
23208            assert!(
23209                rendered.starts_with("Sparse[") && rendered.ends_with(']'),
23210                "malformed sparse name {rendered}"
23211            );
23212        }
23213    }
23214
23215    #[test]
23216    fn test_dtype_from_str_and_display() {
23217        use std::str::FromStr;
23218
23219        use crate::DType;
23220
23221        assert_eq!(DType::from_str("int64").unwrap(), DType::Int64);
23222        assert_eq!(DType::from_str("Int64").unwrap(), DType::Int64Nullable);
23223        assert_eq!(DType::from_str("float64").unwrap(), DType::Float64);
23224        assert_eq!(DType::from_str("Float64").unwrap(), DType::Float64Nullable);
23225        assert_eq!(DType::from_str("bool").unwrap(), DType::Bool);
23226        assert_eq!(DType::from_str("boolean").unwrap(), DType::BoolNullable);
23227        assert_eq!(DType::from_str("string").unwrap(), DType::Utf8);
23228        assert_eq!(DType::from_str("category").unwrap(), DType::Categorical);
23229        assert_eq!(
23230            DType::from_str("timedelta64[ns]").unwrap(),
23231            DType::Timedelta64
23232        );
23233        assert_eq!(
23234            DType::from_str("datetime64[ns]").unwrap(),
23235            DType::Datetime64 { tz: None }
23236        );
23237        assert_eq!(
23238            DType::from_str("datetime64[ns, UTC]").unwrap(),
23239            DType::Datetime64 {
23240                tz: Some("UTC".to_string())
23241            }
23242        );
23243        assert_eq!(DType::from_str("period").unwrap(), DType::Period);
23244        assert_eq!(DType::from_str("interval").unwrap(), DType::Interval);
23245        assert_eq!(DType::from_str("sparse").unwrap(), DType::Sparse);
23246
23247        assert_eq!(format!("{}", DType::Int64), "int64");
23248        assert_eq!(
23249            format!(
23250                "{}",
23251                DType::Datetime64 {
23252                    tz: Some("UTC".to_string())
23253                }
23254            ),
23255            "datetime64[ns, UTC]"
23256        );
23257    }
23258
23259    #[test]
23260    fn test_api_types_inspection_and_infer_dtype() {
23261        use crate::{
23262            DType, Scalar,
23263            api::types::{
23264                infer_dtype, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype,
23265                is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_int64_dtype,
23266                is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_object_dtype,
23267                is_period_dtype, is_scalar, is_signed_integer_dtype, is_sparse, is_string_dtype,
23268                is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype,
23269            },
23270        };
23271
23272        assert!(is_numeric_dtype(&DType::Int64));
23273        assert!(is_numeric_dtype(&DType::Float64));
23274        assert!(!is_numeric_dtype(&DType::Utf8));
23275        assert!(!is_numeric_dtype(&DType::Bool));
23276
23277        assert!(is_integer_dtype(&DType::Int64));
23278        assert!(is_integer_dtype(&DType::Int64Nullable));
23279        assert!(!is_integer_dtype(&DType::Float64));
23280
23281        assert!(is_int64_dtype(&DType::Int64));
23282        assert!(is_int64_dtype(&DType::Int64Nullable));
23283        assert!(!is_int64_dtype(&DType::Float64));
23284
23285        assert!(is_object_dtype(&DType::Utf8));
23286        assert!(!is_object_dtype(&DType::Int64));
23287
23288        assert!(is_dtype_equal(&DType::Int64, &DType::Int64));
23289        assert!(is_dtype_equal(&"int64", &DType::Int64));
23290        assert!(!is_dtype_equal(&DType::Int64, &DType::Float64));
23291
23292        assert!(is_signed_integer_dtype(&DType::Int64));
23293        assert!(!is_unsigned_integer_dtype(&DType::Int64));
23294
23295        assert!(is_float_dtype(&DType::Float64));
23296        assert!(is_bool_dtype(&DType::Bool));
23297        assert!(is_string_dtype(&DType::Utf8));
23298        assert!(is_datetime64_any_dtype(&DType::Datetime64 { tz: None }));
23299        assert!(is_timedelta64_dtype(&DType::Timedelta64));
23300        assert!(is_categorical_dtype(&DType::Categorical));
23301        assert!(is_period_dtype(&DType::Period));
23302        assert!(is_interval_dtype(&DType::Interval));
23303        assert!(is_sparse(&DType::Sparse));
23304        assert!(is_extension_array_dtype(&DType::Categorical));
23305        assert!(is_scalar(&Scalar::Int64(42)));
23306
23307        assert_eq!(pandas_dtype("float64").unwrap(), DType::Float64);
23308        assert!(pandas_dtype("invalid_dtype_xyz").is_err());
23309
23310        let ints = vec![Scalar::Int64(1), Scalar::Int64(2)];
23311        assert_eq!(infer_dtype(&ints, true), "integer");
23312
23313        let floats = vec![Scalar::Float64(1.0), Scalar::Float64(2.5)];
23314        assert_eq!(infer_dtype(&floats, true), "floating");
23315
23316        let bools = vec![Scalar::Bool(true), Scalar::Bool(false)];
23317        assert_eq!(infer_dtype(&bools, true), "boolean");
23318
23319        let strings = vec![Scalar::Utf8("a".to_string()), Scalar::Utf8("b".to_string())];
23320        assert_eq!(infer_dtype(&strings, true), "string");
23321
23322        let mixed = vec![Scalar::Int64(1), Scalar::Utf8("a".to_string())];
23323        assert_eq!(infer_dtype(&mixed, true), "mixed");
23324
23325        assert_eq!(infer_dtype(&[], true), "empty");
23326    }
23327
23328    #[test]
23329    fn test_na_nat_sentinels_and_eng_float_format() {
23330        use super::{
23331            NA, NAT, NaT, eng_float_format, get_eng_float_format, reset_eng_float_format,
23332            set_eng_float_format,
23333        };
23334
23335        // NA and NAT sentinels
23336        assert!(NA.is_null());
23337        assert!(NAT.is_null());
23338        assert_eq!(NAT, NaT);
23339        assert_eq!(format!("{NA}"), "None");
23340        assert_eq!(format!("{NAT}"), "NaT");
23341
23342        // Engineering float format tests
23343        assert_eq!(eng_float_format(1000.0, Some(3), false), "1.000E+03");
23344        assert_eq!(eng_float_format(0.005, Some(3), false), "5.000E-03");
23345        assert_eq!(eng_float_format(1234567.0, Some(3), false), "1.235E+06");
23346        assert_eq!(eng_float_format(-9876.54, Some(3), false), "-9.877E+03");
23347        assert_eq!(eng_float_format(0.0, Some(3), false), "0.000E+00");
23348
23349        // With prefixes
23350        assert_eq!(eng_float_format(1000.0, Some(3), true), "1.000k");
23351        assert_eq!(eng_float_format(0.005, Some(3), true), "5.000m");
23352        assert_eq!(eng_float_format(1234567.0, Some(3), true), "1.235M");
23353        assert_eq!(eng_float_format(-9876.54, Some(3), true), "-9.877k");
23354        assert_eq!(eng_float_format(0.0, Some(3), true), "0.000");
23355        assert_eq!(eng_float_format(1.5, Some(3), true), "1.500");
23356
23357        // Special numbers
23358        assert_eq!(eng_float_format(f64::NAN, Some(3), true), "NaN");
23359        assert_eq!(eng_float_format(f64::INFINITY, Some(3), true), "inf");
23360        assert_eq!(eng_float_format(f64::NEG_INFINITY, Some(3), true), "-inf");
23361
23362        // Configuration helpers
23363        reset_eng_float_format();
23364        assert_eq!(get_eng_float_format(), None);
23365        set_eng_float_format(4, true);
23366        assert_eq!(get_eng_float_format(), Some((4, true)));
23367        reset_eng_float_format();
23368        assert_eq!(get_eng_float_format(), None);
23369    }
23370
23371    #[test]
23372    fn test_options_system() {
23373        use super::{
23374            OptionError, OptionValue, describe_option, get_option, option_context, reset_option,
23375            set_option,
23376        };
23377
23378        // Reset to clean state
23379        reset_option(None).unwrap();
23380
23381        // 1. Default option checks
23382        let max_rows = get_option("display.max_rows").unwrap();
23383        assert_eq!(max_rows.as_int(), Some(60));
23384        assert_eq!(max_rows, OptionValue::Int(60));
23385        assert!(!max_rows.is_none());
23386
23387        // Partial key matching (suffix)
23388        let min_rows = get_option("min_rows").unwrap();
23389        assert_eq!(min_rows.as_int(), Some(10));
23390
23391        // 2. Setting options
23392        set_option("display.max_rows", 100).unwrap();
23393        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
23394
23395        set_option("mode.sim_interactive", true).unwrap();
23396        assert_eq!(
23397            get_option("mode.sim_interactive").unwrap().as_bool(),
23398            Some(true)
23399        );
23400
23401        set_option("mode.chained_assignment", "raise").unwrap();
23402        assert_eq!(
23403            get_option("mode.chained_assignment").unwrap().as_str(),
23404            Some("raise")
23405        );
23406
23407        // 3. OptionError handling
23408        assert!(matches!(
23409            get_option("nonexistent.option"),
23410            Err(OptionError::NotFound { .. })
23411        ));
23412        assert!(matches!(
23413            get_option("display"),
23414            Err(OptionError::Ambiguous { .. })
23415        ));
23416
23417        // 4. describe_option
23418        let desc = describe_option(Some("max_rows")).unwrap();
23419        assert!(desc.contains("display.max_rows : [currently: 100]"));
23420
23421        let desc_all = describe_option(None).unwrap();
23422        assert!(desc_all.contains("display.width"));
23423        assert!(desc_all.contains("compute.use_bottleneck"));
23424
23425        // 5. Scoped option_context
23426        {
23427            let _guard = option_context(&[
23428                ("display.max_rows", OptionValue::Int(999)),
23429                ("display.precision", OptionValue::Int(2)),
23430            ])
23431            .unwrap();
23432
23433            assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(999));
23434            assert_eq!(get_option("display.precision").unwrap().as_int(), Some(2));
23435        }
23436        // Restored after guard drop
23437        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
23438        assert_eq!(get_option("display.precision").unwrap().as_int(), Some(6));
23439
23440        // 6. Reset single option and all options
23441        reset_option(Some("display.max_rows")).unwrap();
23442        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(60));
23443
23444        reset_option(Some("all")).unwrap();
23445        assert_eq!(
23446            get_option("mode.chained_assignment").unwrap().as_str(),
23447            Some("warn")
23448        );
23449
23450        // 7. Expanded standard options
23451        assert_eq!(
23452            get_option("mode.copy_on_write").unwrap().as_bool(),
23453            Some(false)
23454        );
23455        assert_eq!(
23456            get_option("mode.data_manager").unwrap().as_str(),
23457            Some("block")
23458        );
23459        assert_eq!(
23460            get_option("display.large_repr").unwrap().as_str(),
23461            Some("truncate")
23462        );
23463        assert_eq!(
23464            get_option("display.max_info_columns").unwrap().as_int(),
23465            Some(100)
23466        );
23467        assert_eq!(
23468            get_option("display.memory_usage").unwrap().as_bool(),
23469            Some(true)
23470        );
23471        assert_eq!(
23472            get_option("display.colheader_justify").unwrap().as_str(),
23473            Some("right")
23474        );
23475        assert!(get_option("display.chop_threshold").unwrap().is_none());
23476        assert_eq!(
23477            get_option("io.parquet.engine").unwrap().as_str(),
23478            Some("auto")
23479        );
23480        assert_eq!(
23481            get_option("plotting.backend").unwrap().as_str(),
23482            Some("matplotlib")
23483        );
23484        assert_eq!(
23485            get_option("plotting.matplotlib.register_converters")
23486                .unwrap()
23487                .as_bool(),
23488            Some(true)
23489        );
23490
23491        // From<()> for OptionValue
23492        set_option("display.chop_threshold", ()).unwrap();
23493        assert!(get_option("display.chop_threshold").unwrap().is_none());
23494    }
23495
23496    #[test]
23497    fn test_scalar_typed_accessors() {
23498        use super::{Interval, IntervalClosed, Period, PeriodFreq, Scalar};
23499
23500        let s_i64 = Scalar::Int64(42);
23501        assert_eq!(s_i64.as_i64(), Some(42));
23502        assert_eq!(s_i64.as_int(), Some(42));
23503        assert_eq!(s_i64.as_f64(), None);
23504        assert_eq!(s_i64.as_float(), None);
23505        assert_eq!(s_i64.as_bool(), None);
23506        assert_eq!(s_i64.as_str(), None);
23507
23508        let s_f64 = Scalar::Float64(2.75);
23509        assert_eq!(s_f64.as_f64(), Some(2.75));
23510        assert_eq!(s_f64.as_float(), Some(2.75));
23511        assert_eq!(s_f64.as_i64(), None);
23512        assert_eq!(s_f64.as_int(), None);
23513
23514        let s_bool = Scalar::Bool(true);
23515        assert_eq!(s_bool.as_bool(), Some(true));
23516        assert_eq!(s_bool.as_int(), None);
23517
23518        let s_str = Scalar::Utf8("pandas".to_string());
23519        assert_eq!(s_str.as_str(), Some("pandas"));
23520        assert_eq!(s_str.as_bool(), None);
23521
23522        let s_dt = Scalar::Datetime64(1_000_000_000);
23523        assert_eq!(s_dt.as_datetime_nanos(), Some(1_000_000_000));
23524        assert_eq!(s_dt.as_str(), None);
23525
23526        let s_td = Scalar::Timedelta64(500_000);
23527        assert_eq!(s_td.as_timedelta_nanos(), Some(500_000));
23528        assert_eq!(s_td.as_int(), None);
23529
23530        let s_per = Scalar::Period(Period::new(2024, PeriodFreq::Daily));
23531        assert_eq!(s_per.as_period_ordinal(), Some(2024));
23532
23533        let s_iv = Scalar::Interval(Interval::new(0.0, 10.0, IntervalClosed::Both));
23534        assert_eq!(
23535            s_iv.as_interval(),
23536            Some(Interval::new(0.0, 10.0, IntervalClosed::Both))
23537        );
23538    }
23539
23540    #[test]
23541    fn test_api_submodules_and_types_inspectors() {
23542        use super::{
23543            DType, Scalar,
23544            api::{extensions, indexers, types},
23545        };
23546
23547        // api::types scalar inspectors
23548        assert!(types::is_number(&Scalar::Int64(42)));
23549        assert!(types::is_number(&Scalar::Float64(42.5)));
23550        assert!(types::is_number(&Scalar::Bool(true)));
23551        assert!(!types::is_number(&Scalar::Utf8("pandas".into())));
23552
23553        assert!(types::is_bool(&Scalar::Bool(false)));
23554        assert!(!types::is_bool(&Scalar::Int64(0)));
23555
23556        assert!(types::is_integer(&Scalar::Int64(10)));
23557        assert!(!types::is_integer(&Scalar::Float64(10.0)));
23558
23559        assert!(types::is_float(&Scalar::Float64(10.0)));
23560        assert!(!types::is_float(&Scalar::Int64(10)));
23561
23562        // api::types dtype inspectors
23563        assert!(types::is_float64_dtype(&DType::Float64));
23564        assert!(types::is_float64_dtype(&DType::Float64Nullable));
23565        assert!(!types::is_float64_dtype(&DType::Int64));
23566        assert!(!types::is_int32_dtype(&DType::Int64));
23567
23568        // api::extensions compatibility hooks
23569        extensions::register_dataframe_accessor("geo");
23570        extensions::register_series_accessor("geo");
23571        extensions::register_index_accessor("geo");
23572
23573        // api::indexers
23574        let base = indexers::BaseIndexer::new(5, 1);
23575        assert_eq!(base.window_size, 5);
23576        assert_eq!(base.step, 1);
23577
23578        let fwd = indexers::FixedForwardWindowIndexer::new(3);
23579        assert_eq!(fwd.window_size, 3);
23580
23581        let var = indexers::VariableOffsetWindowIndexer::new(100);
23582        assert_eq!(var.index_offset, 100);
23583    }
23584
23585    #[test]
23586    fn test_extension_dtypes_and_parameterized_parsing() {
23587        use super::{
23588            AsDType, CategoricalDtype, DType, IntervalClosed, IntervalDtype, PeriodDtype, Scalar,
23589            SparseDType, api::types, pandas_dtype,
23590        };
23591
23592        // CategoricalDtype
23593        let cat_default = CategoricalDtype::default();
23594        assert_eq!(cat_default.name(), "category");
23595        assert_eq!(cat_default.kind(), "O");
23596        assert!(!cat_default.ordered());
23597        assert_eq!(cat_default.categories(), None);
23598        assert_eq!(cat_default.as_dtype(), DType::Categorical);
23599        assert!(types::is_categorical_dtype(&cat_default));
23600        assert_eq!(
23601            cat_default.to_string(),
23602            "CategoricalDtype(categories=None, ordered=False)"
23603        );
23604
23605        let cat_custom =
23606            CategoricalDtype::new(Some(vec!["low".to_string(), "high".to_string()]), true);
23607        assert!(cat_custom.ordered());
23608        assert_eq!(
23609            cat_custom.categories(),
23610            Some(&["low".to_string(), "high".to_string()][..])
23611        );
23612        assert!(cat_custom.to_string().contains("ordered=True"));
23613
23614        // PeriodDtype
23615        let per_default = PeriodDtype::default();
23616        assert_eq!(per_default.freq(), "D");
23617        assert_eq!(per_default.name(), "period[D]");
23618        assert_eq!(per_default.kind(), "O");
23619        assert_eq!(per_default.as_dtype(), DType::Period);
23620        assert!(types::is_period_dtype(&per_default));
23621        assert_eq!(per_default.to_string(), "period[D]");
23622
23623        let per_custom = PeriodDtype::new("M");
23624        assert_eq!(per_custom.freq(), "M");
23625        assert_eq!(per_custom.to_string(), "period[M]");
23626
23627        // IntervalDtype
23628        let int_default = IntervalDtype::default();
23629        assert_eq!(*int_default.subtype(), DType::Float64);
23630        assert_eq!(int_default.closed(), Some(IntervalClosed::Right));
23631        assert_eq!(int_default.name(), "interval");
23632        assert_eq!(int_default.kind(), "O");
23633        assert_eq!(int_default.as_dtype(), DType::Interval);
23634        assert!(types::is_interval_dtype(&int_default));
23635        assert_eq!(int_default.to_string(), "interval[float64, right]");
23636
23637        let int_custom = IntervalDtype::new(DType::Int64, Some(IntervalClosed::Both));
23638        assert_eq!(*int_custom.subtype(), DType::Int64);
23639        assert_eq!(int_custom.closed(), Some(IntervalClosed::Both));
23640        assert_eq!(int_custom.to_string(), "interval[int64, both]");
23641
23642        // SparseDType AsDType
23643        let sp = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).unwrap();
23644        assert_eq!(sp.as_dtype(), DType::Sparse);
23645        assert!(types::is_sparse(&sp));
23646
23647        // Parameterized pandas_dtype parsing
23648        assert_eq!(pandas_dtype("period[D]").unwrap(), DType::Period);
23649        assert_eq!(pandas_dtype("Period[M]").unwrap(), DType::Period);
23650        assert_eq!(pandas_dtype("interval[float64]").unwrap(), DType::Interval);
23651        assert_eq!(pandas_dtype("Interval[int64]").unwrap(), DType::Interval);
23652        assert_eq!(pandas_dtype("sparse[float64]").unwrap(), DType::Sparse);
23653        assert_eq!(pandas_dtype("Sparse[int64, 0]").unwrap(), DType::Sparse);
23654    }
23655}
23656
23657/// `NumericWidth` / `NumpyNumeric` — numpy's narrow numeric dtypes and their
23658/// promotion (fvsao.23). Expected values are live pandas 2.2.3 / numpy 2.4.6.
23659#[cfg(test)]
23660mod numeric_width_fvsao23 {
23661    use super::{DType, NumericWidth, NumpyNumeric, numpy_pairwise_sum};
23662
23663    #[test]
23664    fn float32_sum_is_numpys_pairwise_sum_bit_for_bit() {
23665        // numpy 2.4.6: a = ((arange(n) * 37) % 1000).astype(float32) *
23666        // float32(0.013); a.sum().view(uint32). Lengths 5 and 64 are ones
23667        // where a float64 sum rounded once gives another float32 (NEGATIVE).
23668        let cases: [(usize, u32); 5] = [
23669            (5, 1_083_829_126),
23670            (64, 1_136_679_190),
23671            (129, 1_145_981_108),
23672            (1000, 1_170_926_592),
23673            (4097, 1_188_011_795),
23674        ];
23675        for (n, bits) in cases {
23676            #[allow(clippy::cast_precision_loss)] // below 1000
23677            let values: Vec<f32> = (0..n)
23678                .map(|k| ((k * 37) % 1000) as f32 * 0.013_f32)
23679                .collect();
23680            assert_eq!(numpy_pairwise_sum(&values).to_bits(), bits, "n={n}");
23681            if n < 100 {
23682                #[allow(clippy::cast_possible_truncation)]
23683                let rounded_once = values.iter().map(|&v| f64::from(v)).sum::<f64>() as f32;
23684                assert_ne!(rounded_once.to_bits(), bits, "n={n}");
23685            }
23686        }
23687        assert_eq!(numpy_pairwise_sum::<f32>(&[]), 0.0);
23688    }
23689
23690    #[test]
23691    fn names_parse_and_round_trip() {
23692        for width in NumericWidth::ALL {
23693            for nullable in [false, true] {
23694                assert_eq!(
23695                    NumericWidth::parse(width.name(nullable)),
23696                    Some((width, nullable))
23697                );
23698            }
23699        }
23700        for (name, expected) in [
23701            ("<i4", (NumericWidth::Int32, false)),
23702            ("f4", (NumericWidth::Float32, false)),
23703            ("UInt8Dtype", (NumericWidth::UInt8, true)),
23704        ] {
23705            assert_eq!(NumericWidth::parse(name), Some(expected), "{name}");
23706        }
23707        // The 64-bit names are DType's, not a width: 'i8' is numpy's int64.
23708        for name in ["int64", "Int64", "float64", "i8", "f8", "int", "float"] {
23709            assert_eq!(NumericWidth::parse(name), None, "{name}");
23710        }
23711    }
23712
23713    #[test]
23714    fn wrapping_is_numpys_modular_cast_not_saturation() {
23715        // pd.Series([1, 2, 300, -5]).astype('int8') -> [1, 2, 44, -5]
23716        assert_eq!(NumericWidth::Int8.wrap_int(300), Some(44));
23717        // .astype('uint8') -> [1, 2, 44, 251]; uint16 -5 -> 65531
23718        assert_eq!(NumericWidth::UInt8.wrap_int(-5), Some(251));
23719        assert_eq!(NumericWidth::UInt16.wrap_int(-5), Some(65531));
23720        assert_eq!(NumericWidth::UInt32.wrap_int(-5), Some(4_294_967_291));
23721        // int8 100 + 100 -> -56; 100 * 2 -> -56
23722        assert_eq!(NumericWidth::Int8.wrap_int(200), Some(-56));
23723        assert_eq!(
23724            NumericWidth::Int32.wrap_int(i64::from(i32::MAX) + 1),
23725            Some(i64::from(i32::MIN))
23726        );
23727        // A wrapped i64 product reduces to the width's product.
23728        let product = 50_000_i64.wrapping_pow(5);
23729        assert_eq!(
23730            NumericWidth::Int32.wrap_int(product),
23731            Some(i64::from(50_000_i32.wrapping_pow(5)))
23732        );
23733        // uint64 at or above 2**63 is refused, never stored negative.
23734        assert_eq!(NumericWidth::UInt64.wrap_int(-1), None);
23735        assert_eq!(NumericWidth::UInt64.wrap_int(7), Some(7));
23736        assert_eq!(NumericWidth::Float32.wrap_int(1), None);
23737        assert!(NumericWidth::Int8.holds_int(-128) && !NumericWidth::Int8.holds_int(128));
23738    }
23739
23740    #[test]
23741    fn float32_rounding_is_to_nearest_not_truncation() {
23742        // np.float32(0.1) as float64 -> 0.10000000149011612
23743        assert_eq!(NumericWidth::round_f32(0.1), 0.100_000_001_490_116_12);
23744        // float32 0.1 + 0.2 -> 0.30000001192092896 (not float64's
23745        // 0.30000000000000004)
23746        let sum =
23747            NumericWidth::round_f32(NumericWidth::round_f32(0.1) + NumericWidth::round_f32(0.2));
23748        assert_eq!(sum, 0.300_000_011_920_928_96);
23749        // 1 + 2**-24 is a tie between 1 and 1 + 2**-23: ties to even -> 1.
23750        // 1 + 3 * 2**-25 is above the tie: rounds up, where truncation stays 1.
23751        assert_eq!(NumericWidth::round_f32(1.0 + 2f64.powi(-24)), 1.0);
23752        let above_tie = 1.0 + 3.0 * 2f64.powi(-25);
23753        assert_eq!(NumericWidth::round_f32(above_tie), 1.0 + 2f64.powi(-23));
23754        assert!(NumericWidth::round_f32(f64::NAN).is_nan());
23755        assert_eq!(NumericWidth::round_f32(1e300), f64::INFINITY);
23756    }
23757
23758    #[test]
23759    fn result_type_matches_numpy_promotion() {
23760        use NumpyNumeric::{Bool, Float, Int, UInt};
23761        let cases = [
23762            (Int(32), Int(64), Int(64)), // int32 + int64 -> int64
23763            (Int(8), UInt(8), Int(16)),  // int8 + uint8 -> int16
23764            (Int(16), UInt(8), Int(16)),
23765            (Int(8), UInt(16), Int(32)),
23766            (Int(32), UInt(32), Int(64)),
23767            (Int(64), UInt(64), Float(64)), // no integer holds both
23768            (UInt(8), UInt(32), UInt(32)),
23769            (Float(32), Int(8), Float(32)), // float32 * int8 -> float32
23770            (Float(32), UInt(16), Float(32)),
23771            (Float(32), Int(32), Float(64)), // float32 * int32 -> float64
23772            (Float(32), Float(64), Float(64)),
23773            (Bool, Int(8), Int(8)),
23774            (Bool, Float(32), Float(32)),
23775        ];
23776        for (a, b, expected) in cases {
23777            assert_eq!(a.result_type(b), expected, "{a:?} {b:?}");
23778            assert_eq!(b.result_type(a), expected, "{b:?} {a:?}");
23779        }
23780        // NEP 50: int32 + 1 -> int32; int32 + 0.5 -> float64;
23781        // float32 + 0.2 -> float32
23782        assert_eq!(Int(32).with_python_int(), Int(32));
23783        assert_eq!(Int(32).with_python_float(), Float(64));
23784        assert_eq!(Float(32).with_python_float(), Float(32));
23785        assert_eq!(Bool.with_python_int(), Int(64));
23786    }
23787
23788    #[test]
23789    fn columns_map_to_numpy_dtypes() {
23790        let cases = [
23791            (DType::Int64, None, Some(NumpyNumeric::Int(64))),
23792            (
23793                DType::Int64Nullable,
23794                Some(NumericWidth::UInt8),
23795                Some(NumpyNumeric::UInt(8)),
23796            ),
23797            (
23798                DType::Float64,
23799                Some(NumericWidth::Float32),
23800                Some(NumpyNumeric::Float(32)),
23801            ),
23802            // A width its storage cannot carry is not a numpy dtype.
23803            (DType::Float64, Some(NumericWidth::Int8), None),
23804            (DType::Utf8, None, None),
23805        ];
23806        for (dtype, width, expected) in cases {
23807            assert_eq!(NumpyNumeric::of(&dtype, width), expected, "{dtype:?}");
23808        }
23809        for width in NumericWidth::ALL {
23810            assert_eq!(NumpyNumeric::of_width(width).width(), Some(width));
23811            assert!(width.fits_storage(&width.storage(false)));
23812            assert!(width.fits_storage(&width.storage(true)));
23813        }
23814        assert_eq!(NumpyNumeric::Int(64).width(), None);
23815    }
23816
23817    #[test]
23818    fn downcast_and_category_code_widths() {
23819        // to_numeric([1, 2], downcast='integer') -> int8; [1, 300] signed ->
23820        // int16, unsigned -> uint16
23821        let int32_max_plus_one = i64::from(i32::MAX) + 1;
23822        let signed = [
23823            ((1, 2), Some(NumericWidth::Int8)),
23824            ((1, 300), Some(NumericWidth::Int16)),
23825            ((0, int32_max_plus_one), None),
23826        ];
23827        for ((low, high), expected) in signed {
23828            assert_eq!(NumericWidth::smallest_signed(low, high), expected);
23829        }
23830        let unsigned = [((1, 300), Some(NumericWidth::UInt16)), ((-1, 3), None)];
23831        for ((low, high), expected) in unsigned {
23832            assert_eq!(NumericWidth::smallest_unsigned(low, high), expected);
23833        }
23834        // cat.codes: 2 categories int8, 200 int16; 126 int8, 127 int16
23835        for (categories, expected) in [
23836            (2, NumericWidth::Int8),
23837            (126, NumericWidth::Int8),
23838            (127, NumericWidth::Int16),
23839            (200, NumericWidth::Int16),
23840        ] {
23841            assert_eq!(NumericWidth::for_category_codes(categories), Some(expected));
23842        }
23843        assert_eq!(NumericWidth::itemsize(NumericWidth::Int8), 1);
23844        assert_eq!(NumericWidth::Float32.itemsize(), 4);
23845    }
23846}
23847
23848/// `PandasReductions` against live pandas 2.2.3 / numpy 2.3.5: the bits of
23849/// `Series(...).sum() / mean() / var() / std() / sem() / skew() / kurt()`
23850/// over data both sides build with the same integer arithmetic and one
23851/// division (br-frankenpandas-9iim6).
23852#[cfg(test)]
23853mod pandas_reductions_9iim6 {
23854    use super::{MissingLayout, PandasReductions, ReductionValues};
23855
23856    /// `((k * 7919 + 13) % 100003) / 7.0 - 7000.0`, times 1e6 where
23857    /// `k % 5 == 0`; missing where `k % 11 == 3`.
23858    #[allow(clippy::cast_precision_loss)] // below 100003
23859    fn floats(n: usize) -> (Vec<f64>, Vec<u64>) {
23860        let mut present = vec![0_u64; n.div_ceil(64)];
23861        let values = (0..n)
23862            .map(|k| {
23863                if k % 11 != 3 {
23864                    present[k / 64] |= 1 << (k % 64);
23865                }
23866                let base = ((k * 7919 + 13) % 100_003) as f64 / 7.0 - 7000.0;
23867                if k % 5 == 0 { base * 1e6 } else { base }
23868            })
23869            .collect();
23870        (values, present)
23871    }
23872
23873    /// `(k * 7919 + 13) % 100003 * 3_000_000_007`.
23874    fn ints(n: usize) -> Vec<i64> {
23875        (0..n)
23876            .map(|k| i64::try_from((k * 7919 + 13) % 100_003).unwrap() * 3_000_000_007)
23877            .collect()
23878    }
23879
23880    fn assert_bits(got: &[f64], expected: &[u64], case: &str) {
23881        let got: Vec<u64> = got.iter().map(|value| value.to_bits()).collect();
23882        assert_eq!(got, expected, "{case}");
23883    }
23884
23885    #[test]
23886    fn numpy_float64_with_nan_matches_pandas_bits() {
23887        // pandas: s = Series(floats(n)) with NaN at the missing slots.
23888        let cases: [(usize, [u64; 7]); 7] = [
23889            (
23890                7,
23891                [
23892                    0xc1ff_1185_2dcb_6db6,
23893                    0xc1d4_b658_c932_4924,
23894                    0x43db_301d_4a8d_87a3,
23895                    0x41e4_db58_e2f1_458e,
23896                    0x41d1_078f_09d3_9c5c,
23897                    0xc002_1f47_ceae_1b43,
23898                    0x4014_c8bc_93df_56e6,
23899                ],
23900            ),
23901            (
23902                8,
23903                [
23904                    0xc1ff_1184_f43d_b6da,
23905                    0xc1d1_c0de_426c_687d,
23906                    0x43d7_9d3c_ecd2_da2b,
23907                    0x41e3_7012_7d6c_71a5,
23908                    0x41cd_631d_3379_9929,
23909                    0xc003_b196_82f9_28dc,
23910                    0x4018_9de2_eba9_5ecc,
23911                ],
23912            ),
23913            (
23914                127,
23915                [
23916                    0x4200_324e_3389_2490,
23917                    0x4192_0704_ad1e_360d,
23918                    0x43c9_4a6b_3390_577d,
23919                    0x41dc_72bf_d6fa_9808,
23920                    0x41a5_38f5_8417_ae1e,
23921                    0x3fd0_b6bf_045c_e4d5,
23922                    0x4017_1585_bf13_21c4,
23923                ],
23924            ),
23925            (
23926                128,
23927                [
23928                    0x4200_324d_7236_db6e,
23929                    0x4191_df3a_f99d_a2ae,
23930                    0x43c9_1234_ffb7_4a93,
23931                    0x41dc_5310_c97c_292c,
23932                    0x41a5_09f4_cfcf_9206,
23933                    0x3fd0_d9df_0d68_00b0,
23934                    0x4017_61b6_5653_ae82,
23935                ],
23936            ),
23937            (
23938                129,
23939                [
23940                    0x4200_324c_d43e_db71,
23941                    0x4191_b81f_8a1d_61da,
23942                    0x43c8_daf6_85d3_386f,
23943                    0x41dc_33ca_af49_8c24,
23944                    0x41a4_dbc2_8609_a567,
23945                    0x3fd0_fcc5_39d9_6901,
23946                    0x4017_ade4_7855_7c25,
23947                ],
23948            ),
23949            (
23950                1000,
23951                [
23952                    0x421a_d4f6_8061_248e,
23953                    0x417e_39f9_3e1a_a248,
23954                    0x43c7_9481_cba1_263b,
23955                    0x41db_7825_28c0_37cc,
23956                    0x418d_27ba_a0ea_2f9a,
23957                    0x3fc8_e53a_e277_3d7f,
23958                    0x4018_3c97_3603_dfd0,
23959                ],
23960            ),
23961            (
23962                100_000,
23963                [
23964                    0x4283_088c_316e_46dc,
23965                    0x417b_7135_0c27_1185,
23966                    0x43c7_a0de_3b8e_ea34,
23967                    0x41db_7f57_6673_8d6b,
23968                    0x4157_58cc_33fd_4ae6,
23969                    0x3fc7_f1cf_b14a_14c8,
23970                    0x4018_06b5_f26a_c384,
23971                ],
23972            ),
23973        ];
23974        let all = |r: &PandasReductions<'_>| {
23975            [
23976                r.sum(),
23977                r.mean(),
23978                r.var(1),
23979                r.std(1),
23980                r.sem(1),
23981                r.skew(),
23982                r.kurt(),
23983            ]
23984        };
23985        for (n, expected) in cases {
23986            let (values, present) = floats(n);
23987            let r = PandasReductions::new(
23988                ReductionValues::Float(&values),
23989                Some(&present),
23990                MissingLayout::Numpy,
23991            );
23992            assert_bits(&all(&r), &expected, &format!("float64 n={n}"));
23993            // The same column holding NaN in its missing slots, whole and as
23994            // a concat's chunks.
23995            let with_nan: Vec<f64> = values
23996                .iter()
23997                .enumerate()
23998                .map(|(k, &value)| if k % 11 == 3 { f64::NAN } else { value })
23999                .collect();
24000            let r = PandasReductions::numpy_nan_missing(ReductionValues::Float(&with_nan));
24001            assert_bits(&all(&r), &expected, &format!("float64 NaN n={n}"));
24002            let (head, tail) = with_nan.split_at(n / 3);
24003            let chunks = [head, tail];
24004            let r = PandasReductions::numpy_nan_missing(ReductionValues::FloatChunks(&chunks));
24005            assert_bits(&all(&r), &expected, &format!("float64 NaN chunks n={n}"));
24006        }
24007        // NEGATIVE: the present values added left to right are not pandas'.
24008        let (values, present) = floats(100_000);
24009        let left_fold: f64 = values
24010            .iter()
24011            .enumerate()
24012            .filter(|&(k, _)| present[k / 64] >> (k % 64) & 1 == 1)
24013            .map(|(_, value)| value)
24014            .sum();
24015        assert_ne!(left_fold.to_bits(), 0x4283_088c_316e_46dc);
24016    }
24017
24018    #[test]
24019    fn numpy_int64_mean_sums_through_the_cast_buffer() {
24020        // pandas: Series(ints(n)) (int64): mean, var, sem, skew, kurt.
24021        let cases: [(usize, [u64; 5]); 3] = [
24022            (
24023                129,
24024                [
24025                    0x42e0_dda2_9987_3f9e,
24026                    0x45b9_0e2a_887d_aeda,
24027                    0x429c_34a1_c273_372f,
24028                    0x3f95_9e9d_c69e_ec88,
24029                    0xbff3_844b_ba13_eac1,
24030                ],
24031            ),
24032            (
24033                8193,
24034                [
24035                    0x42e1_0d5b_e407_5aa7,
24036                    0x45b8_3bf5_04f5_f2fc,
24037                    0x426b_d893_c5c9_85b1,
24038                    0x3f42_7452_ff15_86c7,
24039                    0xbff3_318c_611b_b59c,
24040                ],
24041            ),
24042            (
24043                20_000,
24044                [
24045                    0x42e1_0d17_ebf8_272d,
24046                    0x45b8_3c24_c921_82b6,
24047                    0x4261_d2a2_f139_68e2,
24048                    0x3f31_a21c_d4bb_ff52,
24049                    0xbff3_328c_4edc_26ee,
24050                ],
24051            ),
24052        ];
24053        for (n, expected) in cases {
24054            let values = ints(n);
24055            let r =
24056                PandasReductions::new(ReductionValues::Int(&values), None, MissingLayout::Numpy);
24057            let got = [r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()];
24058            assert_bits(&got, &expected, &format!("int64 n={n}"));
24059            // The same values read as chunks give the same bits.
24060            let (head, tail) = values.split_at(n / 3);
24061            let (middle, rest) = tail.split_at(1);
24062            let chunks = [head, middle, &[][..], rest];
24063            let chunked = PandasReductions::new(
24064                ReductionValues::IntChunks(&chunks),
24065                None,
24066                MissingLayout::Numpy,
24067            );
24068            let got = [
24069                chunked.mean(),
24070                chunked.var(1),
24071                chunked.sem(1),
24072                chunked.skew(),
24073                chunked.kurt(),
24074            ];
24075            assert_bits(&got, &expected, &format!("int64 chunks n={n}"));
24076        }
24077    }
24078
24079    #[test]
24080    fn masked_columns_add_runs_of_present_values() {
24081        // pandas: Series(pd.array(floats(n), dtype="Float64")) with NA at the
24082        // missing slots: sum, mean, var, sem. sum / mean differ from the
24083        // float64 column's above (n = 129: ...6e against ...71) - the runs.
24084        let cases: [(usize, [u64; 4]); 3] = [
24085            (
24086                129,
24087                [
24088                    0x4200_324c_d43e_db6e,
24089                    0x4191_b81f_8a1d_61d6,
24090                    0x43c8_daf6_85d3_3872,
24091                    0x41a4_dbc2_8609_a567,
24092                ],
24093            ),
24094            (
24095                1000,
24096                [
24097                    0x421a_d4f6_8061_2492,
24098                    0x417e_39f9_3e1a_a24c,
24099                    0x43c7_9481_cba1_263a,
24100                    0x418d_27ba_a0ea_2f9a,
24101                ],
24102            ),
24103            (
24104                100_000,
24105                [
24106                    0x4283_088c_316e_46de,
24107                    0x417b_7135_0c27_1188,
24108                    0x43c7_a0de_3b8e_ea37,
24109                    0x4157_58cc_33fd_4ae6,
24110                ],
24111            ),
24112        ];
24113        for (n, expected) in cases {
24114            let (values, present) = floats(n);
24115            let r = PandasReductions::new(
24116                ReductionValues::Float(&values),
24117                Some(&present),
24118                MissingLayout::Masked,
24119            );
24120            assert_bits(
24121                &[r.sum(), r.mean(), r.var(1), r.sem(1)],
24122                &expected,
24123                &format!("Float64 n={n}"),
24124            );
24125            let (head, tail) = values.split_at(n / 2 + 1);
24126            let chunks = [head, tail];
24127            let chunked = PandasReductions::new(
24128                ReductionValues::FloatChunks(&chunks),
24129                Some(&present),
24130                MissingLayout::Masked,
24131            );
24132            let got = [
24133                chunked.sum(),
24134                chunked.mean(),
24135                chunked.var(1),
24136                chunked.sem(1),
24137            ];
24138            assert_bits(&got, &expected, &format!("Float64 chunks n={n}"));
24139        }
24140        // pandas: pd.array(ints(n), dtype="Int64") with NA where k % 997 == 5:
24141        // mean and var, the runs summed within numpy's 8192-value buffers.
24142        for (n, expected) in [
24143            (8193, [0x42e1_0f35_29c2_807b_u64, 0x45b8_39ed_8746_bdcc]),
24144            (20_000, [0x42e1_0cf2_cc56_752a, 0x45b8_3c63_72fc_fad5]),
24145        ] {
24146            let values = ints(n);
24147            let mut present = vec![0_u64; n.div_ceil(64)];
24148            for k in (0..n).filter(|k| k % 997 != 5) {
24149                present[k / 64] |= 1 << (k % 64);
24150            }
24151            let r = PandasReductions::new(
24152                ReductionValues::Int(&values),
24153                Some(&present),
24154                MissingLayout::Masked,
24155            );
24156            assert_bits(&[r.mean(), r.var(1)], &expected, &format!("Int64 n={n}"));
24157        }
24158    }
24159
24160    #[test]
24161    fn edge_cases_match_pandas() {
24162        let reductions = |values: &[f64], present: Option<&[u64]>| {
24163            let r = PandasReductions::new(
24164                ReductionValues::Float(values),
24165                present,
24166                MissingLayout::Numpy,
24167            );
24168            [r.sum(), r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()]
24169        };
24170        // pandas: [1.5] * 10 -> 15.0 1.5 0.0 0.0 0.0 0.0 (a constant's kurt
24171        // is 0, not 0 minus the bias term); [2.0] * 3 kurt NaN.
24172        let constant = reductions(&[1.5; 10], None);
24173        assert_eq!(constant, [15.0, 1.5, 0.0, 0.0, 0.0, 0.0]);
24174        assert!(reductions(&[2.0; 3], None)[5].is_nan());
24175        // [1, 2] skew NaN; [1, 2, 4] skew 0.9352195295828237.
24176        assert!(reductions(&[1.0, 2.0], None)[4].is_nan());
24177        assert_eq!(
24178            reductions(&[1.0, 2.0, 4.0], None)[4],
24179            0.935_219_529_582_823_7
24180        );
24181        // Empty / all missing: sum 0.0, the rest NaN.
24182        let empty = reductions(&[], None);
24183        assert_eq!(empty[0], 0.0);
24184        assert!(empty[1..].iter().all(|value| value.is_nan()));
24185        let all_missing = reductions(&[3.0; 5], Some(&[0]));
24186        assert_eq!(all_missing[0], 0.0);
24187        assert!(all_missing[1].is_nan());
24188        // -0.0 * 10 sums to 0.0 (numpy adds onto the identity 0.0).
24189        assert_eq!(
24190            reductions(&[-0.0; 10], None)[0].to_bits(),
24191            0.0_f64.to_bits()
24192        );
24193        // An inf: sum / mean inf, the spread NaN.
24194        let inf = reductions(&[1.0, f64::INFINITY, 2.0, 5.0], None);
24195        assert_eq!(inf[0], f64::INFINITY);
24196        assert!(inf[2..].iter().all(|value| value.is_nan()));
24197    }
24198
24199    #[test]
24200    fn int64_mean_skipping_is_the_filled_mean_vk7y9() {
24201        // A datetime64 mean read straight off its nanos, NaT as 0, is the
24202        // bit-identical mean of the filled copy under its presence bits -
24203        // across cast-buffer chunks, with NaT anywhere (br-frankenpandas-vk7y9).
24204        const NAT: i64 = i64::MIN;
24205        let nanos: Vec<i64> = (0..20_000_i64)
24206            .map(|k| {
24207                if k % 13 == 5 {
24208                    NAT
24209                } else {
24210                    1_577_836_800_000_000_000 + k * 3_600_000_000_123
24211                }
24212            })
24213            .collect();
24214        let mut present = vec![0_u64; nanos.len().div_ceil(64)];
24215        let filled: Vec<i64> = nanos
24216            .iter()
24217            .enumerate()
24218            .map(|(i, &ns)| {
24219                if ns == NAT {
24220                    0
24221                } else {
24222                    present[i / 64] |= 1 << (i % 64);
24223                    ns
24224                }
24225            })
24226            .collect();
24227        let expected = PandasReductions::new(
24228            ReductionValues::Int(&filled),
24229            Some(&present),
24230            MissingLayout::Numpy,
24231        )
24232        .mean();
24233        assert_eq!(
24234            PandasReductions::int64_mean_skipping(&nanos, NAT).to_bits(),
24235            expected.to_bits()
24236        );
24237        // NEGATIVE: every slot missing is NaN, not a mean of the zeros.
24238        assert!(PandasReductions::int64_mean_skipping(&[NAT, NAT], NAT).is_nan());
24239        assert!(PandasReductions::int64_mean_skipping(&[], NAT).is_nan());
24240    }
24241}
24242
24243/// pandas' default text-to-float64 conversion against live pandas 2.2.3
24244/// bits: `read_csv(StringIO('x\n' + token), dtype={'x': 'float64'})`
24245/// (br-frankenpandas-py3c0).
24246#[cfg(test)]
24247mod pandas_decimal_py3c0 {
24248    use super::{PandasDecimal, pandas_decimal_to_f64, pandas_int_to_f64};
24249
24250    fn bits(token: &str) -> u64 {
24251        match pandas_decimal_to_f64(token.as_bytes()) {
24252            PandasDecimal::Value(value) => value.to_bits(),
24253            other => panic!("{token:?}: {other:?}"),
24254        }
24255    }
24256
24257    #[test]
24258    fn tokens_convert_to_pandas_bits() {
24259        let cases = [
24260            ("9.890295358649789", 0x4023_c7d4_cb12_5ce4),
24261            ("0.8690736625851781286570704999", 0x3feb_cf73_91d3_c8f1),
24262            ("0.000000068288360759838675650889", 0x3e72_54bd_8bcd_610b),
24263            ("-0.0080749473608410608782560", 0xbf80_8999_16a7_63f3),
24264            ("99999999999999999", 0x4376_3457_85d8_a001),
24265            ("1234567890123456789012345", 0x44f0_56e0_f36a_6444),
24266            // 17 leading zeros are the 17 digits kept.
24267            ("00000000000000000.5", 0x0000_0000_0000_0000),
24268            ("-00000000000000000.5", 0x8000_0000_0000_0000),
24269            ("1.5E+10", 0x420b_f08e_b000_0000),
24270            ("-.5e-3", 0xbf40_624d_d2f1_a9fc),
24271            ("5.", 0x4014_0000_0000_0000),
24272            ("1e-320", 0x0000_0000_0000_07e8),
24273            ("2.5e-310", 0x0000_2e05_5c9a_3f6c),
24274            ("-1e-400", 0x8000_0000_0000_0000),
24275            // Below 1e-616: +0.0, the sign dropped.
24276            ("-1e-700", 0x0000_0000_0000_0000),
24277            // The exponent wraps as a 32-bit integer.
24278            ("1e-4294967296", 0x3ff0_0000_0000_0000),
24279            ("1.7976931348623157e308", 0x7fef_ffff_ffff_ffff),
24280            ("0.001e310", 0x7fac_7b1f_3cac_7433),
24281        ];
24282        for (token, expected) in cases {
24283            assert_eq!(bits(token), expected, "{token:?}");
24284        }
24285        // NEGATIVE: the correctly rounded value is not pandas'.
24286        let correctly_rounded: f64 = "9.890295358649789".parse().unwrap();
24287        assert_ne!(correctly_rounded.to_bits(), 0x4023_c7d4_cb12_5ce4);
24288    }
24289
24290    #[test]
24291    fn what_pandas_does_not_read_as_a_float() {
24292        for token in [
24293            "1e309",
24294            "0e400",
24295            "1.8e308",
24296            "1e+0000000000000000001",
24297            "1e-2147483649",
24298            "1e",
24299            "1e+",
24300            "1.5d3",
24301            "0x10",
24302            "1_000.5",
24303            "1..5",
24304        ] {
24305            assert_eq!(
24306                pandas_decimal_to_f64(token.as_bytes()),
24307                PandasDecimal::Rejected,
24308                "{token:?}"
24309            );
24310        }
24311        for token in ["inf", "-Infinity", "nan", ".", "-", "e5", "+.e1", "--1", ""] {
24312            assert_eq!(
24313                pandas_decimal_to_f64(token.as_bytes()),
24314                PandasDecimal::NotDecimal,
24315                "{token:?}"
24316            );
24317        }
24318    }
24319
24320    #[test]
24321    fn an_integer_in_a_float_column_takes_the_same_conversion() {
24322        assert_eq!(pandas_int_to_f64(-42).to_bits(), (-42.0_f64).to_bits());
24323        assert_eq!(
24324            pandas_int_to_f64(99_999_999_999_999_999).to_bits(),
24325            0x4376_3457_85d8_a001
24326        );
24327        assert_eq!(
24328            pandas_int_to_f64(-99_999_999_999_999_999).to_bits(),
24329            0xc376_3457_85d8_a001
24330        );
24331    }
24332
24333    /// The civil-date month shift is chrono's relativedelta (a date made,
24334    /// moved and read back) for every day of the month at its edges, leap
24335    /// and plain years, before and after 1970, sub-second times and month
24336    /// counts of either sign (br-frankenpandas-4g57c). NEGATIVE: a shift past
24337    /// datetime64[ns] (either end, or a month count near i64) is None, as
24338    /// chrono's timestamp is out of range.
24339    #[test]
24340    fn calendar_months_match_chrono_relativedelta_4g57c() {
24341        use chrono::{Datelike, NaiveDate};
24342
24343        use super::add_calendar_months_nanos;
24344        let reference = |nanos: i64, months: i64| -> Option<i64> {
24345            let at = chrono::DateTime::from_timestamp(
24346                nanos.div_euclid(1_000_000_000),
24347                u32::try_from(nanos.rem_euclid(1_000_000_000)).ok()?,
24348            )?
24349            .naive_utc();
24350            let total = i64::from(at.year())
24351                .checked_mul(12)?
24352                .checked_add(i64::from(at.month0()))?
24353                .checked_add(months)?;
24354            let year = i32::try_from(total.div_euclid(12)).ok()?;
24355            let month = u32::try_from(total.rem_euclid(12)).ok()? + 1;
24356            let last = (28..=31)
24357                .rev()
24358                .find(|day| NaiveDate::from_ymd_opt(year, month, *day).is_some())?;
24359            NaiveDate::from_ymd_opt(year, month, at.day().min(last))?
24360                .and_time(at.time())
24361                .and_utc()
24362                .timestamp_nanos_opt()
24363        };
24364        let day_nanos = 86_400_000_000_000_i64;
24365        let mut checked = 0;
24366        for year in [1678, 1699, 1900, 1969, 1970, 2000, 2023, 2024, 2100, 2261] {
24367            for month in 1..=12 {
24368                for day in [1, 15, 27, 28, 29, 30, 31] {
24369                    let Some(date) = NaiveDate::from_ymd_opt(year, month, day) else {
24370                        continue;
24371                    };
24372                    let Some(midnight) = date
24373                        .and_hms_opt(0, 0, 0)
24374                        .and_then(|at| at.and_utc().timestamp_nanos_opt())
24375                    else {
24376                        continue;
24377                    };
24378                    for time in [0, 1, 37_123_456_789, day_nanos - 1] {
24379                        let nanos = midnight + time;
24380                        for months in [-2400, -13, -12, -1, 0, 1, 2, 11, 12, 25, 1200] {
24381                            assert_eq!(
24382                                add_calendar_months_nanos(nanos, months),
24383                                reference(nanos, months),
24384                                "{nanos} + {months} months"
24385                            );
24386                            checked += 1;
24387                        }
24388                    }
24389                }
24390            }
24391        }
24392        assert!(checked > 30_000, "{checked}");
24393        // NEGATIVE: out of range at both ends and for absurd month counts.
24394        let last = i64::MAX - 1;
24395        assert_eq!(add_calendar_months_nanos(last, 1), None);
24396        assert_eq!(reference(last, 1), None);
24397        assert_eq!(add_calendar_months_nanos(i64::MIN + 1, -1), None);
24398        assert_eq!(add_calendar_months_nanos(0, i64::MAX), None);
24399        assert_eq!(add_calendar_months_nanos(0, i64::MIN), None);
24400        assert_eq!(add_calendar_months_nanos(0, 12 * 400), None);
24401        assert_eq!(super::add_calendar_months_days(i64::MAX, 1), None);
24402        assert_eq!(super::add_calendar_months_days(0, i64::MAX), None);
24403        // The clipped day: Jan 31 2024 + 1 month is Feb 29.
24404        let jan31 = 19_753 * day_nanos;
24405        assert_eq!(
24406            add_calendar_months_nanos(jan31, 1),
24407            Some(19_782 * day_nanos)
24408        );
24409    }
24410
24411    /// A numbered host value equals another as their numbers and hashes as
24412    /// its number, the host's own eq not asked; an unnumbered one asks it
24413    /// (br-frankenpandas-jq8qb). NEGATIVE: numbered values of different
24414    /// numbers differ though the host calls them equal; a numbered value
24415    /// beside an unnumbered one takes the host's answer.
24416    #[test]
24417    fn numbered_host_values_compare_and_hash_by_number_jq8qb() {
24418        use std::hash::{Hash, Hasher};
24419
24420        use super::{HostObject, HostValue, ObjectValue};
24421
24422        struct Numbered(Option<i64>, &'static str);
24423        impl HostObject for Numbered {
24424            fn host_eq(&self, other: &dyn HostObject) -> bool {
24425                other
24426                    .as_any()
24427                    .downcast_ref::<Self>()
24428                    .is_some_and(|other| other.1 == self.1)
24429            }
24430            fn host_repr(&self) -> String {
24431                self.1.to_owned()
24432            }
24433            fn host_str(&self) -> String {
24434                self.1.to_owned()
24435            }
24436            fn host_hash(&self) -> Option<u64> {
24437                Some(self.1.len() as u64)
24438            }
24439            fn host_cmp(&self, _other: &dyn HostObject) -> Option<std::cmp::Ordering> {
24440                None
24441            }
24442            fn as_any(&self) -> &dyn std::any::Any {
24443                self
24444            }
24445            fn host_number(&self) -> Option<i64> {
24446                self.0
24447            }
24448        }
24449        let hash = |value: &ObjectValue| {
24450            let mut hasher = std::hash::DefaultHasher::new();
24451            value.hash(&mut hasher);
24452            hasher.finish()
24453        };
24454        let cell = |number, name| ObjectValue::Host(HostValue::new(Numbered(number, name)));
24455        assert_eq!(cell(Some(7), "a"), cell(Some(7), "b"));
24456        assert_eq!(hash(&cell(Some(7), "a")), hash(&cell(Some(7), "bb")));
24457        assert_ne!(cell(Some(7), "a"), cell(Some(8), "a"));
24458        assert_eq!(cell(Some(7), "a"), cell(None, "a"));
24459        assert_ne!(cell(Some(7), "a"), cell(None, "b"));
24460        assert_eq!(cell(None, "a"), cell(None, "a"));
24461        assert_ne!(cell(None, "a"), cell(None, "b"));
24462        assert_eq!(hash(&cell(None, "ab")), hash(&cell(None, "cd")));
24463    }
24464
24465    #[test]
24466    fn interval_parse_rejects_multibyte_and_malformed_inputs_without_panic_4qg5w_13() {
24467        use super::{Interval, IntervalClosed, TypeError};
24468        for bad in [
24469            "",
24470            "   ",
24471            "€€",
24472            "€€€€€",
24473            "[αβγ]",
24474            "(α, β]",
24475            "[1, 2, 3]",
24476            "[1 2]",
24477            "]1, 2[",
24478        ] {
24479            let err = Interval::parse(bad).expect_err("malformed interval must return Err");
24480            assert!(matches!(err, TypeError::ValueNotParseable { .. }));
24481        }
24482        // NEGATIVE: valid intervals still parse identically.
24483        let parsed = Interval::parse(" [1.5, 3.5) ").expect("valid interval");
24484        assert_eq!(parsed.left, 1.5);
24485        assert_eq!(parsed.right, 3.5);
24486        assert_eq!(parsed.closed, IntervalClosed::Left);
24487    }
24488
24489    #[test]
24490    fn period_scalar_calendar_asfreq_to_timestamp_and_interval_closed_open_match_pandas_uo1wg() {
24491        use super::{Interval, IntervalClosed, Period, PeriodFreq, Timestamp};
24492
24493        // 1. Interval closed_left / closed_right / open_left / open_right across all 4 variants
24494        let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
24495        assert!(!right.closed_left());
24496        assert!(right.closed_right());
24497        assert!(right.open_left());
24498        assert!(!right.open_right());
24499
24500        let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
24501        assert!(left.closed_left());
24502        assert!(!left.closed_right());
24503        assert!(!left.open_left());
24504        assert!(left.open_right());
24505
24506        let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
24507        assert!(both.closed_left());
24508        assert!(both.closed_right());
24509        assert!(!both.open_left());
24510        assert!(!both.open_right());
24511
24512        let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
24513        assert!(!neither.closed_left());
24514        assert!(!neither.closed_right());
24515        assert!(neither.open_left());
24516        assert!(neither.open_right());
24517
24518        // 2. Period("2024-03", freq="M")
24519        let p_m = Period::parse("2024-03").expect("2024-03");
24520        assert_eq!(p_m.year(), Some(2024));
24521        assert_eq!(p_m.month(), Some(3));
24522        assert_eq!(p_m.day(), Some(31));
24523        assert_eq!(p_m.hour(), Some(0));
24524        assert_eq!(p_m.minute(), Some(0));
24525        assert_eq!(p_m.second(), Some(0));
24526        assert_eq!(p_m.quarter(), Some(1));
24527        assert_eq!(p_m.qyear(), Some(2024));
24528        assert_eq!(p_m.weekday(), Some(6));
24529        assert_eq!(p_m.dayofweek(), Some(6));
24530        assert_eq!(p_m.day_of_week(), Some(6));
24531        assert_eq!(p_m.dayofyear(), Some(91));
24532        assert_eq!(p_m.day_of_year(), Some(91));
24533        assert_eq!(p_m.days_in_month(), Some(31));
24534        assert_eq!(p_m.daysinmonth(), Some(31));
24535        assert_eq!(p_m.week(), Some(13));
24536        assert_eq!(p_m.weekofyear(), Some(13));
24537        assert_eq!(p_m.is_leap_year(), Some(true));
24538        assert_eq!(p_m.start_time().value(), 1_709_251_200_000_000_000);
24539        assert_eq!(p_m.end_time().value(), 1_711_929_599_999_999_999);
24540        assert_eq!(p_m.to_timestamp("start").unwrap(), p_m.start_time());
24541        assert_eq!(p_m.to_timestamp("end").unwrap(), p_m.end_time());
24542        assert_eq!(
24543            p_m.asfreq("D").unwrap(),
24544            Period::parse("2024-03-31").unwrap()
24545        );
24546        assert_eq!(
24547            p_m.asfreq_with_how("D", "start").unwrap(),
24548            Period::parse("2024-03-01").unwrap()
24549        );
24550        assert_eq!(p_m.strftime("%Y-%m-%d"), "2024-03-31");
24551
24552        // 3. Fiscal Quarterly Period("2025Q1", freq="Q-JAN") -> ends 2024-04-30
24553        let ts_feb = Timestamp::parse("2024-02-15").unwrap();
24554        let p_qjan = ts_feb.to_period("Q-JAN").unwrap();
24555        assert_eq!(p_qjan.to_string(), "2025Q1");
24556        assert_eq!(p_qjan.year(), Some(2024));
24557        assert_eq!(p_qjan.qyear(), Some(2025));
24558        assert_eq!(p_qjan.quarter(), Some(1));
24559        assert_eq!(p_qjan.month(), Some(4));
24560        assert_eq!(p_qjan.day(), Some(30));
24561        assert_eq!(p_qjan.days_in_month(), Some(30));
24562        assert_eq!(p_qjan.start_time().value(), 1_706_745_600_000_000_000);
24563        assert_eq!(p_qjan.end_time().value(), 1_714_521_599_999_999_999);
24564        assert_eq!(p_qjan.strftime("%Y-%m-%d"), "2024-04-30");
24565
24566        // 4. Business Friday Period("2024-03-15", freq="B") -> end_time is Friday 23:59:59.999999999, NOT Sunday
24567        let p_fri = Timestamp::parse("2024-03-15")
24568            .unwrap()
24569            .to_period("B")
24570            .unwrap();
24571        assert_eq!(p_fri.day(), Some(15));
24572        assert_eq!(p_fri.weekday(), Some(4));
24573        assert_eq!(
24574            p_fri.end_time().value(),
24575            p_fri.start_time().value() + 86_400_000_000_000 - 1
24576        );
24577        assert_eq!(
24578            p_fri.asfreq_with_how("D", "E").unwrap(),
24579            Period::parse("2024-03-15").unwrap()
24580        );
24581
24582        // 5. Period::now("D") succeeds and matches Timestamp::now().to_period("D")
24583        let p_now = Period::now("D").expect("Period::now(D)");
24584        assert_eq!(p_now.freq(), PeriodFreq::Daily);
24585        assert!(!p_now.is_nat());
24586
24587        // 6. NEGATIVE cases: NaT propagation, invalid frequency, invalid `how`
24588        let p_nat = Period::new(i64::MIN, PeriodFreq::Monthly);
24589        assert!(p_nat.is_nat());
24590        assert_eq!(p_nat.year(), None);
24591        assert_eq!(p_nat.qyear(), None);
24592        assert_eq!(p_nat.quarter(), None);
24593        assert_eq!(p_nat.is_leap_year(), None);
24594        assert!(p_nat.start_time().is_nat());
24595        assert!(p_nat.end_time().is_nat());
24596        assert_eq!(p_nat.strftime("%Y-%m-%d"), "NaT");
24597        assert!(p_nat.asfreq("D").unwrap().is_nat());
24598        assert_eq!(p_nat.asfreq("D").unwrap().freq(), PeriodFreq::Daily);
24599        assert!(p_m.asfreq("NOT_A_FREQ").is_err());
24600        assert!(p_m.asfreq_with_how("D", "middle").is_err());
24601        assert!(p_m.to_timestamp("middle").is_err());
24602        assert!(Timestamp::nat().to_period("D").is_err());
24603    }
24604
24605    #[test]
24606    fn timestamp_tz_localize_convert_isoformat_tzname_and_getters_match_pandas_sddfo() {
24607        use crate::{TimeZoneError, Timestamp, TypeError};
24608
24609        // 1. Naive Timestamp("2024-01-01 03:30:00") localized to America/New_York (EST, -05:00)
24610        let ts_naive = Timestamp::parse("2024-01-01T03:30:00").unwrap();
24611        assert_eq!(ts_naive.value(), 1_704_079_800_000_000_000);
24612        assert_eq!(ts_naive.tzname(), None);
24613
24614        let ts_ny = ts_naive.tz_localize(Some("America/New_York"));
24615        assert_eq!(ts_ny.value(), 1_704_097_800_000_000_000);
24616        assert_eq!(ts_ny.isoformat(), "2024-01-01T03:30:00-05:00");
24617        assert_eq!(ts_ny.tzname().as_deref(), Some("EST"));
24618        assert_eq!(ts_ny.year(), Some(2024));
24619        assert_eq!(ts_ny.month(), Some(1));
24620        assert_eq!(ts_ny.day(), Some(1));
24621        assert_eq!(ts_ny.hour(), Some(3));
24622        assert_eq!(ts_ny.minute(), Some(30));
24623
24624        // 2. UTC Timestamp("2024-01-01 03:30:00Z") converted to America/New_York -> 2023-12-31 22:30:00-05:00
24625        let ts_utc = Timestamp::parse("2024-01-01T03:30:00Z").unwrap();
24626        let ts_from_utc = ts_utc.tz_convert("America/New_York");
24627        assert_eq!(ts_from_utc.value(), 1_704_079_800_000_000_000);
24628        assert_eq!(ts_from_utc.isoformat(), "2023-12-31T22:30:00-05:00");
24629        assert_eq!(ts_from_utc.tzname().as_deref(), Some("EST"));
24630        assert_eq!(ts_from_utc.year(), Some(2023));
24631        assert_eq!(ts_from_utc.month(), Some(12));
24632        assert_eq!(ts_from_utc.day(), Some(31));
24633        assert_eq!(ts_from_utc.hour(), Some(22));
24634        assert_eq!(ts_from_utc.minute(), Some(30));
24635        assert_eq!(ts_from_utc.dayofweek(), Some(6));
24636        assert_eq!(ts_from_utc.day_name(), "Sunday");
24637        assert_eq!(ts_from_utc.month_name(), "December");
24638        assert_eq!(ts_from_utc.toordinal(), Some(738_885));
24639        assert_eq!(ts_from_utc.is_year_end(), Some(true));
24640        assert_eq!(ts_from_utc.is_year_start(), Some(false));
24641
24642        // 3. Stripping timezone via tz_localize(None) preserves wall clock (2023-12-31 22:30:00 naive)
24643        let stripped = ts_from_utc.tz_localize(None);
24644        assert_eq!(stripped.tzinfo(), None);
24645        assert_eq!(stripped.value(), 1_704_061_800_000_000_000);
24646        assert_eq!(stripped.isoformat(), "2023-12-31T22:30:00");
24647
24648        // 4. Summer EDT timestamp has tzname "EDT" and "-04:00" offset
24649        let ts_summer = Timestamp::parse("2024-07-01T12:00:00")
24650            .unwrap()
24651            .tz_localize(Some("America/New_York"));
24652        assert_eq!(ts_summer.isoformat(), "2024-07-01T12:00:00-04:00");
24653        assert_eq!(ts_summer.tzname().as_deref(), Some("EDT"));
24654
24655        // 5. replace(year=2025) on tz-aware Timestamp preserves wall-clock hour/minute in target year
24656        let replaced = ts_from_utc.replace(Some(2025), None, None, None, None, None, None, None);
24657        assert_eq!(replaced.value(), 1_767_238_200_000_000_000);
24658        assert_eq!(replaced.isoformat(), "2025-12-31T22:30:00-05:00");
24659
24660        // 6. NEGATIVE cases: localizing already-aware or converting naive raises TypeError / folds to NaT
24661        assert_eq!(
24662            ts_ny.try_tz_localize(Some("UTC")),
24663            Err(TypeError::AlreadyTzAware)
24664        );
24665        assert!(ts_ny.tz_localize(Some("UTC")).is_nat());
24666        assert_eq!(
24667            ts_naive.try_tz_convert(Some("UTC")),
24668            Err(TypeError::TzNaiveCannotConvert)
24669        );
24670        assert!(ts_naive.tz_convert("UTC").is_nat());
24671        assert!(matches!(
24672            ts_naive.try_tz_localize(Some("Mars/Olympus")),
24673            Err(TypeError::TimeZone(TimeZoneError::Unknown(_)))
24674        ));
24675        assert!(matches!(
24676            ts_ny.try_tz_convert(Some("Mars/Olympus")),
24677            Err(TypeError::TimeZone(TimeZoneError::Unknown(_)))
24678        ));
24679    }
24680}