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.base() == PeriodFreq::Business {
11186            // A business span ends at the last business day's midnight +
11187            // one calendar day, not at the next business day's midnight.
11188            let last = self.ordinal.checked_add(self.freq.multiplier() - 1)?;
11189            let start = Self::new(last, PeriodFreq::Business).start_nanos()?;
11190            let end = start.checked_add(Timedelta::NANOS_PER_DAY - 1)?;
11191            return (end != Timestamp::NAT).then_some(end);
11192        }
11193        let next = Self::new(self.ordinal.checked_add(self.freq.multiplier())?, self.freq);
11194        let end = next.start_nanos()?.checked_sub(1)?;
11195        (end != Timestamp::NAT).then_some(end)
11196    }
11197
11198    /// Timestamp at the period's start boundary (`pd.Period.start_time`).
11199    /// Returns `Timestamp::nat()` for `NaT` or out-of-range ordinals.
11200    #[must_use]
11201    pub fn start_time(&self) -> Timestamp {
11202        self.start_nanos()
11203            .map_or_else(Timestamp::nat, Timestamp::from_nanos)
11204    }
11205
11206    /// Timestamp at the period's inclusive end boundary (`pd.Period.end_time`).
11207    /// Returns `Timestamp::nat()` for `NaT` or out-of-range ordinals.
11208    #[must_use]
11209    pub fn end_time(&self) -> Timestamp {
11210        self.end_nanos()
11211            .map_or_else(Timestamp::nat, Timestamp::from_nanos)
11212    }
11213
11214    /// Convert period to a `Timestamp` at the requested boundary (`"start"`/`"S"` or `"end"`/`"E"`),
11215    /// matching `pd.Period.to_timestamp(how=...)`.
11216    pub fn to_timestamp(&self, how: &str) -> Result<Timestamp, TypeError> {
11217        match how.trim().to_ascii_lowercase().as_str() {
11218            "" | "s" | "start" | "begin" | "b" => Ok(self.start_time()),
11219            "e" | "end" | "finish" => Ok(self.end_time()),
11220            _ => Err(TypeError::ValueNotParseable {
11221                value: how.to_owned(),
11222                target: "Period::to_timestamp how ('start' or 'end')".to_owned(),
11223            }),
11224        }
11225    }
11226
11227    /// Convert period to a new frequency using pandas' default `"end"` boundary,
11228    /// matching `pd.Period.asfreq(freq)`.
11229    pub fn asfreq(&self, freq: &str) -> Result<Self, TypeError> {
11230        self.asfreq_with_how(freq, "end")
11231    }
11232
11233    /// Convert period to a new frequency at the requested boundary (`"start"`/`"S"` or `"end"`/`"E"`),
11234    /// matching `pd.Period.asfreq(freq, how)`.
11235    pub fn asfreq_with_how(&self, freq: &str, how: &str) -> Result<Self, TypeError> {
11236        let target_freq = PeriodFreq::parse(freq).ok_or_else(|| TypeError::ValueNotParseable {
11237            value: freq.to_owned(),
11238            target: "PeriodFreq".to_owned(),
11239        })?;
11240        let is_start = match how.trim().to_ascii_lowercase().as_str() {
11241            "" | "e" | "end" | "finish" => false,
11242            "s" | "start" | "begin" | "b" => true,
11243            _ => {
11244                return Err(TypeError::ValueNotParseable {
11245                    value: how.to_owned(),
11246                    target: "Period::asfreq how ('start' or 'end')".to_owned(),
11247                });
11248            }
11249        };
11250        if self.is_nat() {
11251            return Ok(Self::new(i64::MIN, target_freq));
11252        }
11253        let boundary_nanos = if is_start {
11254            self.start_nanos()
11255        } else {
11256            self.end_nanos()
11257        }
11258        .ok_or_else(|| TypeError::ValueNotParseable {
11259            value: self.to_string(),
11260            target: "Period boundary Timestamp".to_owned(),
11261        })?;
11262        // pandas rolls a weekend day of a day-or-finer source to a business day
11263        // the opposite way from a week/month/quarter/year source: end rolls forward
11264        // to Monday, start rolls back to Friday; coarse sources roll end back to Friday.
11265        let flips = target_freq.base() == PeriodFreq::Business
11266            && Self::fixed_span_nanos(self.freq).is_some();
11267        let roll_business_forward = if flips { !is_start } else { is_start };
11268        Self::from_timestamp_nanos_with_business_roll(
11269            boundary_nanos,
11270            target_freq,
11271            roll_business_forward,
11272        )
11273        .ok_or_else(|| TypeError::ValueNotParseable {
11274            value: self.to_string(),
11275            target: format!("Period[{target_freq}]"),
11276        })
11277    }
11278
11279    /// Instant used by pandas `get_date_info` for date/time component accessors:
11280    /// sub-daily and daily/business periods use their start instant; coarser
11281    /// calendar periods (weekly, monthly, quarterly, annual) use midnight of
11282    /// their end date.
11283    fn field_timestamp(&self) -> Timestamp {
11284        if self.is_nat() {
11285            return Timestamp::nat();
11286        }
11287        // Calendar fields describe the first base period, not the far end
11288        // of its multiplied span: a 2M period starting in January still has
11289        // month=1 and day=31, although its end_time falls in February.
11290        let base = Self::new(self.ordinal, self.freq.base());
11291        let nanos = match base.freq {
11292            PeriodFreq::Daily
11293            | PeriodFreq::Business
11294            | PeriodFreq::Hourly
11295            | PeriodFreq::Minutely
11296            | PeriodFreq::Secondly
11297            | PeriodFreq::Milliseconds
11298            | PeriodFreq::Microseconds
11299            | PeriodFreq::Nanoseconds => base.start_nanos(),
11300            PeriodFreq::Weekly(_)
11301            | PeriodFreq::Monthly
11302            | PeriodFreq::Quarterly(_)
11303            | PeriodFreq::Annual(_) => base
11304                .end_nanos()
11305                .map(|end| end - end.rem_euclid(Timedelta::NANOS_PER_DAY)),
11306            PeriodFreq::Multiple(_) => None,
11307        };
11308        nanos.map_or_else(Timestamp::nat, Timestamp::from_nanos)
11309    }
11310
11311    /// Format period using strftime directives (`pd.Period.strftime`).
11312    /// Returns `"NaT"` for `NaT`.
11313    #[must_use]
11314    pub fn strftime(&self, fmt: &str) -> String {
11315        self.field_timestamp().strftime(fmt)
11316    }
11317
11318    /// Calendar year of the period (`pd.Period.year`). Returns `None` for `NaT`.
11319    #[must_use]
11320    pub fn year(&self) -> Option<i64> {
11321        self.field_timestamp().year()
11322    }
11323
11324    /// Calendar month (1-12) of the period (`pd.Period.month`). Returns `None` for `NaT`.
11325    #[must_use]
11326    pub fn month(&self) -> Option<i64> {
11327        self.field_timestamp().month()
11328    }
11329
11330    /// Calendar day of month (1-31) of the period (`pd.Period.day`). Returns `None` for `NaT`.
11331    #[must_use]
11332    pub fn day(&self) -> Option<i64> {
11333        self.field_timestamp().day()
11334    }
11335
11336    /// Hour component (0-23) of the period (`pd.Period.hour`). Returns `None` for `NaT`.
11337    #[must_use]
11338    pub fn hour(&self) -> Option<i64> {
11339        self.field_timestamp().hour()
11340    }
11341
11342    /// Minute component (0-59) of the period (`pd.Period.minute`). Returns `None` for `NaT`.
11343    #[must_use]
11344    pub fn minute(&self) -> Option<i64> {
11345        self.field_timestamp().minute()
11346    }
11347
11348    /// Second component (0-59) of the period (`pd.Period.second`). Returns `None` for `NaT`.
11349    #[must_use]
11350    pub fn second(&self) -> Option<i64> {
11351        self.field_timestamp().second()
11352    }
11353
11354    /// Quarter (1-4) of the period (`pd.Period.quarter`): fiscal quarter for
11355    /// `Quarterly` frequencies, calendar quarter of the end date otherwise.
11356    #[must_use]
11357    pub fn quarter(&self) -> Option<i64> {
11358        if self.is_nat() {
11359            return None;
11360        }
11361        match self.freq.base() {
11362            PeriodFreq::Quarterly(_) => Some(self.ordinal.rem_euclid(4) + 1),
11363            _ => self.field_timestamp().quarter(),
11364        }
11365    }
11366
11367    /// Fiscal year of the period (`pd.Period.qyear`). Returns `None` for `NaT`.
11368    #[must_use]
11369    pub fn qyear(&self) -> Option<i64> {
11370        if self.is_nat() {
11371            return None;
11372        }
11373        match self.freq.base() {
11374            PeriodFreq::Quarterly(_) => 1970_i64.checked_add(self.ordinal.div_euclid(4)),
11375            _ => self.year(),
11376        }
11377    }
11378
11379    /// Day of the week (Monday=0, Sunday=6), matching `pd.Period.dayofweek`.
11380    #[must_use]
11381    pub fn dayofweek(&self) -> Option<i64> {
11382        self.field_timestamp().dayofweek()
11383    }
11384
11385    /// Alias for [`dayofweek`](Self::dayofweek), matching `pd.Period.day_of_week`.
11386    #[must_use]
11387    pub fn day_of_week(&self) -> Option<i64> {
11388        self.dayofweek()
11389    }
11390
11391    /// Alias for [`dayofweek`](Self::dayofweek), matching `pd.Period.weekday`.
11392    #[must_use]
11393    pub fn weekday(&self) -> Option<i64> {
11394        self.dayofweek()
11395    }
11396
11397    /// Day of the year (1-366), matching `pd.Period.dayofyear`.
11398    #[must_use]
11399    pub fn dayofyear(&self) -> Option<i64> {
11400        self.field_timestamp().dayofyear()
11401    }
11402
11403    /// Alias for [`dayofyear`](Self::dayofyear), matching `pd.Period.day_of_year`.
11404    #[must_use]
11405    pub fn day_of_year(&self) -> Option<i64> {
11406        self.dayofyear()
11407    }
11408
11409    /// Number of days in the period's month (28-31), matching `pd.Period.days_in_month`.
11410    #[must_use]
11411    pub fn days_in_month(&self) -> Option<i64> {
11412        self.field_timestamp().days_in_month()
11413    }
11414
11415    /// Alias for [`days_in_month`](Self::days_in_month), matching `pd.Period.daysinmonth`.
11416    #[must_use]
11417    pub fn daysinmonth(&self) -> Option<i64> {
11418        self.days_in_month()
11419    }
11420
11421    /// ISO-8601 week number (1-53), matching `pd.Period.week`.
11422    #[must_use]
11423    pub fn week(&self) -> Option<i64> {
11424        self.field_timestamp().week()
11425    }
11426
11427    /// Alias for [`week`](Self::week), matching `pd.Period.weekofyear`.
11428    #[must_use]
11429    pub fn weekofyear(&self) -> Option<i64> {
11430        self.week()
11431    }
11432
11433    /// Whether the period's year is a leap year (`pd.Period.is_leap_year`).
11434    #[must_use]
11435    pub fn is_leap_year(&self) -> Option<bool> {
11436        self.field_timestamp().is_leap_year()
11437    }
11438
11439    /// Parse common pandas `Period(...)` strings and infer the frequency.
11440    ///
11441    /// Supported forms mirror pandas' unambiguous scalar constructor cases:
11442    /// annual (`"2024"`), quarterly (`"2024Q1"`), monthly (`"2024-01"`),
11443    /// and daily (`"2024-01-15"`). The ordinal axes match pandas:
11444    /// 1970, 1970Q1, 1970-01, and 1970-01-01 all have ordinal 0.
11445    pub fn parse(s: &str) -> Result<Self, TypeError> {
11446        let trimmed = s.trim();
11447        if trimmed.eq_ignore_ascii_case("nat") {
11448            return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
11449        }
11450
11451        if let Some((year, quarter)) = parse_quarter_period(trimmed) {
11452            let ordinal = year
11453                .checked_sub(1970)
11454                .and_then(|offset| offset.checked_mul(4))
11455                .and_then(|base| base.checked_add(i64::from(quarter) - 1))
11456                .ok_or_else(|| TypeError::ValueNotParseable {
11457                    value: s.to_owned(),
11458                    target: "Period".to_owned(),
11459                })?;
11460            return Ok(Self::new(ordinal, PeriodFreq::QUARTERLY));
11461        }
11462
11463        if let Some((year, month, day)) = parse_ymd_period(trimmed) {
11464            let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
11465            return Ok(Self::new(ordinal, PeriodFreq::Daily));
11466        }
11467
11468        if let Some((year, month)) = parse_year_month_period(trimmed) {
11469            let ordinal = year
11470                .checked_sub(1970)
11471                .and_then(|offset| offset.checked_mul(12))
11472                .and_then(|base| base.checked_add(i64::from(month) - 1))
11473                .ok_or_else(|| TypeError::ValueNotParseable {
11474                    value: s.to_owned(),
11475                    target: "Period".to_owned(),
11476                })?;
11477            return Ok(Self::new(ordinal, PeriodFreq::Monthly));
11478        }
11479
11480        if let Some(year) = parse_annual_period(trimmed) {
11481            let ordinal = year
11482                .checked_sub(1970)
11483                .ok_or_else(|| TypeError::ValueNotParseable {
11484                    value: s.to_owned(),
11485                    target: "Period".to_owned(),
11486                })?;
11487            return Ok(Self::new(ordinal, PeriodFreq::ANNUAL));
11488        }
11489
11490        Err(TypeError::ValueNotParseable {
11491            value: s.to_owned(),
11492            target: "Period".to_owned(),
11493        })
11494    }
11495
11496    /// Pandas calendar string for this period, matching `str(pd.Period)`.
11497    ///
11498    /// Inverts the frequency-specific ordinal axes anchored at 1970:
11499    /// `1970`/`1970Q1`/`1970-01`/`1970-01-01`/`1970-01-01 00:00` all have
11500    /// ordinal 0. Returns `"NaT"` for the missing sentinel (`i64::MIN`).
11501    ///
11502    /// EVERY frequency is exact, Weekly and Business included.
11503    ///
11504    /// ⚠️ THOSE TWO ARE NOT INDEXED IN DAYS, which is what made them wrong until
11505    /// 08363d42f: a weekly ordinal counts WEEKS from the Monday 1969-12-22 and
11506    /// renders as the RANGE it spans (`2024-03-11/2024-03-17`), and a business
11507    /// ordinal counts BUSINESS DAYS at five per week. Both used to be handed to
11508    /// `civil_from_days`, which reads its argument as days since the epoch, so
11509    /// ordinal 2829 rendered `1977-09-30` instead of the week of 2024-03-15.
11510    ///
11511    /// The note that used to sit here called them "best-effort" and said neither
11512    /// was "reachable through the current parse/cast paths". The first half was
11513    /// a real limitation; the second was too narrow a survey. [`Self::parse`]
11514    /// indeed cannot produce them and neither can `cast_scalar` — but
11515    /// `DatetimeIndex::to_period("W")` builds them directly, and fp-index then
11516    /// renders those values through `Display` in `PeriodIndex::format`,
11517    /// `to_index`, `to_flat_index`, the `.str` accessor and the `get_loc` error
11518    /// message. The frequencies were unreachable only from the two paths the
11519    /// note happened to check.
11520    #[must_use]
11521    pub fn calendar_string(&self) -> String {
11522        let mut rendered = String::new();
11523        // `fmt::Write for String` is infallible.
11524        let _ = self.write_calendar(&mut rendered);
11525        rendered
11526    }
11527
11528    fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
11529        if self.ordinal == i64::MIN {
11530            return rendered.write_str("NaT");
11531        }
11532        let ord = self.ordinal;
11533        match self.freq.base() {
11534            // An anchored year or quarter is labelled by the fiscal year its
11535            // ordinal counts (Period('2024', 'Y-JUN') ends 2024-06-30), so
11536            // the label does not depend on the anchor.
11537            PeriodFreq::Annual(_) => {
11538                let year = 1970 + ord;
11539                write!(rendered, "{year}")
11540            }
11541            PeriodFreq::Quarterly(_) => {
11542                let year = 1970 + ord.div_euclid(4);
11543                let quarter = ord.rem_euclid(4) + 1;
11544                write!(rendered, "{year}Q{quarter}")
11545            }
11546            PeriodFreq::Monthly => {
11547                let year = 1970 + ord.div_euclid(12);
11548                let month = ord.rem_euclid(12) + 1;
11549                write!(rendered, "{year:04}-{month:02}")
11550            }
11551            PeriodFreq::Daily => {
11552                let (y, m, d) = civil_from_days(ord);
11553                write!(rendered, "{y:04}-{m:02}-{d:02}")
11554            }
11555            // ⚠️ NOT DAYS SINCE THE EPOCH. A business ordinal counts BUSINESS
11556            // DAYS — five per week — so handing it to `civil_from_days` (which
11557            // wants a day count) put the label decades out: ordinal 14141 is
11558            // 2024-03-15 and rendered as 2008-09-19.
11559            //
11560            // The forward map in fp-index is
11561            //     days.div_euclid(7) * 5 + {Thu:0, Fri:1, Mon:2, Tue:3, Wed:4}
11562            // measured against pandas at every sampled date, so this is its
11563            // inverse: five ordinals per seven days, with the remainder naming a
11564            // weekday offset from the Thursday the epoch falls on.
11565            PeriodFreq::Business => {
11566                const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
11567                // Euclidean, so a pre-epoch ordinal keeps a remainder in 0..5:
11568                // ordinal -1 is 1969-12-31, not a negative weekday index.
11569                let offset = WEEKDAY_OFFSET[ord.rem_euclid(5) as usize];
11570                let days = ord.div_euclid(5).saturating_mul(7).saturating_add(offset);
11571                let (y, m, d) = civil_from_days(days);
11572                write!(rendered, "{y:04}-{m:02}-{d:02}")
11573            }
11574            // ⚠️ TWO BUGS IN ONE ARM. A weekly ordinal counts WEEKS from the
11575            // Monday 1969-12-22 (ten days before the epoch), and pandas renders a
11576            // weekly period as the RANGE it spans, not as one date:
11577            //     Period('2024-03-15', 'W') -> '2024-03-11/2024-03-17'
11578            // ordinal 2829, which this arm rendered as '1977-09-30'.
11579            //
11580            // fp-frame's `format_period_label` already produced the range form
11581            // for the same freq, so the two renderers disagreed on every weekly
11582            // period; this makes them agree.
11583            PeriodFreq::Weekly(_) => {
11584                // Days-since-epoch of the anchor Monday 1969-12-22; a week
11585                // ending on another weekday starts that many days later
11586                // (W-MON weeks run Tuesday..Monday).
11587                const WEEK_ANCHOR_DAY: i64 = -10;
11588                let start = ord
11589                    .saturating_mul(7)
11590                    .saturating_add(WEEK_ANCHOR_DAY + self.freq.week_start_shift());
11591                let (sy, sm, sd) = civil_from_days(start);
11592                let (ey, em, ed) = civil_from_days(start.saturating_add(6));
11593                write!(rendered, "{sy:04}-{sm:02}-{sd:02}/{ey:04}-{em:02}-{ed:02}")
11594            }
11595            PeriodFreq::Hourly => {
11596                let (y, m, d) = civil_from_days(ord.div_euclid(24));
11597                let hour = ord.rem_euclid(24);
11598                write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
11599            }
11600            PeriodFreq::Minutely => {
11601                let day = ord.div_euclid(1440);
11602                let mins = ord.rem_euclid(1440);
11603                let (y, m, d) = civil_from_days(day);
11604                write!(
11605                    rendered,
11606                    "{y:04}-{m:02}-{d:02} {:02}:{:02}",
11607                    mins / 60,
11608                    mins % 60
11609                )
11610            }
11611            PeriodFreq::Secondly => {
11612                let day = ord.div_euclid(86_400);
11613                let secs = ord.rem_euclid(86_400);
11614                let (y, m, d) = civil_from_days(day);
11615                write!(
11616                    rendered,
11617                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
11618                    secs / 3600,
11619                    (secs % 3600) / 60,
11620                    secs % 60
11621                )
11622            }
11623            // The three sub-second frequencies differ only in the divisor and
11624            // the FIXED fraction width -- pandas pads to the full width and
11625            // never trims trailing zeros. MEASURED on 2024-03-15 10:30:45.123456789:
11626            //     ms -> "2024-03-15 10:30:45.123"
11627            //     us -> "2024-03-15 10:30:45.123456"
11628            //     ns -> "2024-03-15 10:30:45.123456789"
11629            PeriodFreq::Milliseconds | PeriodFreq::Microseconds | PeriodFreq::Nanoseconds => {
11630                let (per_sec, width) = match self.freq.base() {
11631                    PeriodFreq::Milliseconds => (1_000_i64, 3_usize),
11632                    PeriodFreq::Microseconds => (1_000_000_i64, 6_usize),
11633                    _ => (1_000_000_000_i64, 9_usize),
11634                };
11635                // 86_400 * 1e9 = 8.64e13 -- the widest of these is well inside i64.
11636                let per_day = 86_400 * per_sec;
11637                let day = ord.div_euclid(per_day);
11638                let rest = ord.rem_euclid(per_day);
11639                let secs = rest / per_sec;
11640                let frac = rest % per_sec;
11641                let (y, m, d) = civil_from_days(day);
11642                write!(
11643                    rendered,
11644                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{:0width$}",
11645                    secs / 3600,
11646                    (secs % 3600) / 60,
11647                    secs % 60,
11648                    frac,
11649                    width = width
11650                )
11651            }
11652            PeriodFreq::Multiple(_) => Self::new(ord, self.freq.base()).write_calendar(rendered),
11653        }
11654    }
11655}
11656
11657/// Convert a day count (days since 1970-01-01) to a proleptic-Gregorian
11658/// `(year, month, day)`, using Howard Hinnant's civil-from-days algorithm
11659/// (same kernel as `Timestamp::isoformat`); the year astronomical (0 is 1
11660/// BC).
11661#[must_use]
11662pub fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
11663    let days = days_since_epoch + 719_468;
11664    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
11665    let doe = days - era * 146_097;
11666    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
11667    let y = yoe + era * 400;
11668    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
11669    let mp = (5 * doy + 2) / 153;
11670    let d = doy - (153 * mp + 2) / 5 + 1;
11671    let m = if mp < 10 { mp + 3 } else { mp - 9 };
11672    let year = if m <= 2 { y + 1 } else { y };
11673    (year, m as u32, d as u32)
11674}
11675
11676fn parse_annual_period(value: &str) -> Option<i64> {
11677    (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
11678        .then(|| value.parse::<i64>().ok())
11679        .flatten()
11680}
11681
11682fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
11683    let (year, month) = value.split_once('-')?;
11684    if year.len() != 4 || month.len() != 2 {
11685        return None;
11686    }
11687    let year = year.parse::<i64>().ok()?;
11688    let month = month.parse::<u32>().ok()?;
11689    (1..=12).contains(&month).then_some((year, month))
11690}
11691
11692fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
11693    let mut parts = value.split('-');
11694    let year = parts.next()?;
11695    let month = parts.next()?;
11696    let day = parts.next()?;
11697    if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
11698        return None;
11699    }
11700    let year = year.parse::<i64>().ok()?;
11701    let month = month.parse::<u32>().ok()?;
11702    let day = day.parse::<u32>().ok()?;
11703    (1..=days_in_month(year, month)?)
11704        .contains(&day)
11705        .then_some((year, month, day))
11706}
11707
11708fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
11709    let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
11710    if year.len() != 4 || quarter.len() != 1 {
11711        return None;
11712    }
11713    let year = year.parse::<i64>().ok()?;
11714    let quarter = quarter.parse::<u32>().ok()?;
11715    (1..=4).contains(&quarter).then_some((year, quarter))
11716}
11717
11718impl std::fmt::Display for Period {
11719    /// Pandas `str(Period)` form: the calendar string (`2024`, `2024Q1`,
11720    /// `2024-03`, `2024-01-15`, ...). NaT (ordinal `i64::MIN`) renders `NaT`.
11721    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11722        self.write_calendar(f)
11723    }
11724}
11725
11726/// Build `periods` consecutive Periods starting at `start`.
11727///
11728/// Matches `pd.period_range(start, periods=N, freq=start.freq)` for the
11729/// count-based form. The frequency is taken from `start` — pandas requires
11730/// `freq` to match when both are passed; mismatches are an error in
11731/// pandas, but here we sidestep ambiguity by deriving from `start.freq`.
11732///
11733/// Per br-frankenpandas-2jef (epoj Phase 2). Pure ordinal arithmetic — no
11734/// calendar conversion (Phase 3 wires chrono). `periods=0` returns empty.
11735///
11736/// ```
11737/// use fp_types::{period_range, Period, PeriodFreq};
11738/// let q1 = Period::new(216, PeriodFreq::QUARTERLY);
11739/// let year = period_range(q1, 4);
11740/// assert_eq!(year.len(), 4);
11741/// assert_eq!(year[0].ordinal, 216);
11742/// assert_eq!(year[3].ordinal, 219);
11743/// ```
11744#[must_use]
11745pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
11746    (0..periods).map(|i| start.shift(i as i64)).collect()
11747}
11748
11749#[cfg(test)]
11750mod tests {
11751    use super::{
11752        DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
11753        cast_scalar, common_dtype, infer_dtype,
11754    };
11755
11756    /// A host value for the tests: a named thing, equal by name, unhashable
11757    /// when the name is empty.
11758    struct Named(&'static str);
11759
11760    impl super::HostObject for Named {
11761        fn host_eq(&self, other: &dyn super::HostObject) -> bool {
11762            other
11763                .as_any()
11764                .downcast_ref::<Named>()
11765                .is_some_and(|other| other.0 == self.0)
11766        }
11767        fn host_repr(&self) -> String {
11768            format!("Named({:?})", self.0)
11769        }
11770        fn host_str(&self) -> String {
11771            self.0.to_owned()
11772        }
11773        fn host_hash(&self) -> Option<u64> {
11774            (!self.0.is_empty()).then_some(self.0.len() as u64)
11775        }
11776        // Names starting with '!' cannot be ordered (as a date against a time).
11777        fn host_cmp(&self, other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
11778            let other = other.as_any().downcast_ref::<Named>()?;
11779            (!self.0.starts_with('!') && !other.0.starts_with('!')).then(|| self.0.cmp(other.0))
11780        }
11781        fn as_any(&self) -> &dyn std::any::Any {
11782            self
11783        }
11784    }
11785
11786    #[test]
11787    fn host_values_block_workers_only_under_a_declared_host_lock_4qg5w_13() {
11788        use std::sync::atomic::Ordering;
11789
11790        use super::{HostValue, LIVE_HOST_VALUES, workers_blocked};
11791        // The rule: inline only when a host lock may be held AND a host value
11792        // is alive. NEGATIVE: without a declared lock (pure Rust callers, this
11793        // test process) nothing is blocked however many host values live.
11794        assert!(workers_blocked(true, 1));
11795        assert!(!workers_blocked(true, 0));
11796        assert!(!workers_blocked(false, 3));
11797        // The count: non-zero while a handle is held, clones included (other
11798        // tests may hold host values concurrently, so only "alive while held"
11799        // is asserted, never "dead after drop"; the lock is never declared
11800        // here, so no concurrent test loses its workers).
11801        let first = HostValue::new(Named("held"));
11802        assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11803        let clone = first.clone();
11804        drop(first);
11805        assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11806        assert_eq!(clone.object().host_str(), "held");
11807    }
11808
11809    #[test]
11810    fn object_cells_order_like_python_then_totally_fvsao_66() {
11811        use std::cmp::Ordering;
11812
11813        use super::{HostValue, ObjectValue};
11814        let host = |name: &'static str| ObjectValue::Host(HostValue::new(Named(name)));
11815        let list = |items: Vec<Scalar>| ObjectValue::list(items);
11816        // Host values order as the host orders them (a date before a later
11817        // date), not by their reprs.
11818        assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11819        assert!(host("b") > host("a"));
11820        assert_eq!(host("a").cmp(&host("a")), Ordering::Equal);
11821        // Lists item by item, numbers by value (1 < 10, where the reprs sort
11822        // "10" first), a shorter prefix first.
11823        let one_ten = list(vec![Scalar::Int64(1), Scalar::Int64(10)]);
11824        let one_two = list(vec![Scalar::Int64(1), Scalar::Int64(2)]);
11825        assert_eq!(one_two.python_cmp(&one_ten), Some(Ordering::Less));
11826        assert!(list(vec![Scalar::Int64(1)]) < one_two);
11827        // Python's 1 == 1.0: an equal item pair is skipped, not the answer.
11828        let mixed = list(vec![Scalar::Float64(1.0), Scalar::Int64(3)]);
11829        assert_eq!(one_two.python_cmp(&mixed), Some(Ordering::Less));
11830        // Where Python raises there is no python_cmp, but the total order
11831        // still separates the cells: a list before a host value, then reprs.
11832        assert_eq!(one_two.python_cmp(&host("a")), None);
11833        assert!(one_two < host("a"));
11834        assert_eq!(host("!z").python_cmp(&host("!a")), None);
11835        assert!(host("!a") < host("!z"));
11836        let text = list(vec![Scalar::Utf8("a".to_owned())]);
11837        assert_eq!(one_two.python_cmp(&text), None);
11838        assert_ne!(one_two.cmp(&text), Ordering::Equal);
11839        // NEGATIVE: unequal cells that print alike are never Equal (NaN is not
11840        // equal to itself), so an ordered map cannot merge them.
11841        let nan = || list(vec![Scalar::Float64(f64::NAN)]);
11842        let (first, second) = (nan(), nan());
11843        assert_ne!(first, second);
11844        assert_ne!(first.cmp(&second), Ordering::Equal);
11845        assert_eq!(first.cmp(&second), second.cmp(&first).reverse());
11846    }
11847
11848    #[test]
11849    fn bytes_cells_print_order_and_serialize_like_python_bytes_4qg5w_8() {
11850        use std::cmp::Ordering;
11851
11852        use super::ObjectValue;
11853        let bytes = |data: &[u8]| Scalar::Object(ObjectValue::bytes(data.to_vec()));
11854        // Python's repr: single quotes unless the bytes hold a ' and no ",
11855        // \xNN for the unprintable, \\ \t \n \r escaped.
11856        assert_eq!(bytes(b"ab").python_repr(), "b'ab'");
11857        assert_eq!(bytes(b"a'b").python_repr(), "b\"a'b\"");
11858        assert_eq!(bytes(b"a'\"").python_repr(), "b'a\\'\"'");
11859        assert_eq!(bytes(b"\x00\t\\\xff").python_repr(), "b'\\x00\\t\\\\\\xff'");
11860        assert_eq!(bytes(b"ab").python_type_name(), "bytes");
11861        // Ordered byte by byte, a prefix first; never equal to a str.
11862        assert_eq!(bytes(b"ab").python_cmp(&bytes(b"b")), Some(Ordering::Less));
11863        assert_eq!(bytes(b"a").python_cmp(&bytes(b"ab")), Some(Ordering::Less));
11864        assert_eq!(bytes(b"a").python_cmp(&Scalar::Utf8("a".to_owned())), None);
11865        assert_ne!(bytes(b"a"), Scalar::Utf8("a".to_owned()));
11866        assert!(!bytes(b"").to_bool().unwrap());
11867        // The serde form the conformance fixtures carry, both ways.
11868        let json = serde_json::to_string(&bytes(b"hi")).unwrap();
11869        assert_eq!(json, r#"{"kind":"object","value":{"bytes":[104,105]}}"#);
11870        let back: Scalar = serde_json::from_str(&json).unwrap();
11871        assert_eq!(back, bytes(b"hi"));
11872        // NEGATIVE: a list cell still (de)serializes as its items.
11873        let list: Scalar =
11874            serde_json::from_str(r#"{"kind":"object","value":[{"kind":"int64","value":1}]}"#)
11875                .unwrap();
11876        assert_eq!(
11877            list,
11878            Scalar::Object(ObjectValue::list(vec![Scalar::Int64(1)]))
11879        );
11880    }
11881
11882    #[test]
11883    fn values_order_and_name_their_types_as_python_does_fvsao_71() {
11884        use std::cmp::Ordering;
11885
11886        use super::{HostValue, ObjectValue};
11887        let text = |value: &str| Scalar::Utf8(value.to_owned());
11888        let host =
11889            |name: &'static str| Scalar::Object(ObjectValue::Host(HostValue::new(Named(name))));
11890        let list = |items: Vec<Scalar>| Scalar::Object(ObjectValue::list(items));
11891        // Numbers across kinds by value, text by code point, instants,
11892        // intervals by (left, right), cells as the host orders them.
11893        assert_eq!(
11894            Scalar::Bool(true).python_cmp(&Scalar::Float64(1.5)),
11895            Some(Ordering::Less)
11896        );
11897        assert_eq!(
11898            Scalar::Int64(2).python_cmp(&Scalar::Float64(2.0)),
11899            Some(Ordering::Equal)
11900        );
11901        assert_eq!(text("b").python_cmp(&text("a")), Some(Ordering::Greater));
11902        assert_eq!(
11903            Scalar::Datetime64(5).python_cmp(&Scalar::Datetime64(9)),
11904            Some(Ordering::Less)
11905        );
11906        let interval = |left: f64, right: f64| {
11907            Scalar::Interval(Interval::new(left, right, IntervalClosed::Right))
11908        };
11909        assert_eq!(
11910            interval(0.0, 5.0).python_cmp(&interval(0.0, 2.0)),
11911            Some(Ordering::Greater)
11912        );
11913        assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11914        // NEGATIVES: what Python cannot order - a str and an int, an instant
11915        // and a duration, a cell and a number, unorderable host values.
11916        assert_eq!(text("a").python_cmp(&Scalar::Int64(1)), None);
11917        assert_eq!(
11918            Scalar::Datetime64(1).python_cmp(&Scalar::Timedelta64(1)),
11919            None
11920        );
11921        assert_eq!(host("a").python_cmp(&Scalar::Int64(1)), None);
11922        assert_eq!(host("!a").python_cmp(&host("b")), None);
11923        // Their types as Python's TypeError names them; a host value by its
11924        // host (the default for a host that cannot say is 'object'), a list
11925        // pair by the first unequal items it holds.
11926        assert_eq!(text("a").python_type_name(), "str");
11927        assert_eq!(Scalar::Bool(true).python_type_name(), "bool");
11928        assert_eq!(Scalar::Datetime64(1).python_type_name(), "Timestamp");
11929        assert_eq!(list(vec![]).python_type_name(), "list");
11930        assert_eq!(host("a").python_type_name(), "object");
11931        let (left, right) = list(vec![Scalar::Int64(1), Scalar::Int64(2)])
11932            .python_cmp_type_names(&list(vec![Scalar::Int64(1), text("x")]));
11933        assert_eq!((left.as_str(), right.as_str()), ("int", "str"));
11934        let (left, right) = text("a").python_cmp_type_names(&list(vec![]));
11935        assert_eq!((left.as_str(), right.as_str()), ("str", "list"));
11936    }
11937
11938    #[test]
11939    fn object_cells_print_compare_and_hash_like_python_fvsao_33() {
11940        use std::hash::{Hash, Hasher};
11941
11942        use super::{HostValue, ObjectValue};
11943        let hash = |value: &ObjectValue| {
11944            let mut hasher = std::collections::hash_map::DefaultHasher::new();
11945            value.hash(&mut hasher);
11946            hasher.finish()
11947        };
11948        let list = ObjectValue::list(vec![
11949            Scalar::Int64(1),
11950            Scalar::Utf8("a".to_owned()),
11951            Scalar::Null(NullKind::Null),
11952            Scalar::Float64(2.0),
11953            Scalar::Object(ObjectValue::list(vec![Scalar::Utf8("b".to_owned())])),
11954        ]);
11955        // repr / str (astype(str), writers) quote strings; pandas' display
11956        // (pprint) does not.
11957        assert_eq!(list.repr(), "[1, 'a', None, 2.0, ['b']]");
11958        assert_eq!(list.to_string(), "[1, 'a', None, 2.0, ['b']]");
11959        assert_eq!(list.pprint(), "[1, a, None, 2.0, [b]]");
11960        // An object cell is object data (pandas' object dtype, Utf8 here).
11961        assert_eq!(Scalar::Object(list.clone()).dtype(), DType::Utf8);
11962        assert!(!Scalar::Object(list.clone()).is_missing());
11963        // Equal lists are equal and hash alike; a different item is not
11964        // equal; a list never equals a host value.
11965        let same = ObjectValue::list(list.as_list().unwrap().to_vec());
11966        assert_eq!(list, same);
11967        assert_eq!(hash(&list), hash(&same));
11968        let other = ObjectValue::list(vec![Scalar::Int64(1)]);
11969        assert_ne!(list, other);
11970        let host = ObjectValue::Host(HostValue::new(Named("x")));
11971        assert_ne!(list, host);
11972        // Host values compare and print through the host.
11973        assert_eq!(host, ObjectValue::Host(HostValue::new(Named("x"))));
11974        assert_ne!(host, ObjectValue::Host(HostValue::new(Named("y"))));
11975        assert_eq!(host.repr(), "Named(\"x\")");
11976        assert_eq!(host.to_string(), "x");
11977        // Python truth: an empty list is false, a host value true.
11978        assert!(
11979            !Scalar::Object(ObjectValue::list(Vec::new()))
11980                .to_bool()
11981                .unwrap()
11982        );
11983        assert!(Scalar::Object(host.clone()).to_bool().unwrap());
11984        // A list is not a number.
11985        assert!(Scalar::Object(list.clone()).to_f64().is_err());
11986        // A list cell serializes as its items and reads back; a host value
11987        // refuses to serialize.
11988        let json = serde_json::to_string(&Scalar::Object(other.clone())).unwrap();
11989        assert_eq!(
11990            serde_json::from_str::<Scalar>(&json).unwrap(),
11991            Scalar::Object(other)
11992        );
11993        assert!(serde_json::to_string(&Scalar::Object(host)).is_err());
11994    }
11995
11996    #[test]
11997    fn a_host_cell_displays_by_its_pprint_and_stringifies_by_its_str() {
11998        use super::{HostValue, ObjectValue};
11999
12000        /// A host tuple: Python's str quotes its items, pandas' display not.
12001        struct Pair;
12002        impl super::HostObject for Pair {
12003            fn host_eq(&self, _other: &dyn super::HostObject) -> bool {
12004                false
12005            }
12006            fn host_repr(&self) -> String {
12007                "('a', 1)".to_owned()
12008            }
12009            fn host_str(&self) -> String {
12010                "('a', 1)".to_owned()
12011            }
12012            fn host_pprint(&self) -> String {
12013                "(a, 1)".to_owned()
12014            }
12015            fn host_hash(&self) -> Option<u64> {
12016                None
12017            }
12018            fn host_cmp(&self, _other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
12019                None
12020            }
12021            fn as_any(&self) -> &dyn std::any::Any {
12022                self
12023            }
12024        }
12025        let pair = ObjectValue::Host(HostValue::new(Pair));
12026        assert_eq!(pair.pprint(), "(a, 1)");
12027        // Inside a list cell too.
12028        let list = ObjectValue::list(vec![Scalar::Object(pair.clone())]);
12029        assert_eq!(list.pprint(), "[(a, 1)]");
12030        // NEGATIVE: str (astype(str), writers) stays the host's str.
12031        assert_eq!(pair.to_string(), "('a', 1)");
12032        // NEGATIVE: a host without its own pprint displays by its str.
12033        let named = ObjectValue::Host(HostValue::new(Named("x")));
12034        assert_eq!(named.pprint(), "x");
12035    }
12036
12037    #[test]
12038    fn float64_json_spells_infinity_and_round_trips() {
12039        // br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.3: serde_json
12040        // wrote +-inf as `null` and could not read it back, so pandas'
12041        // division-by-zero answers could not reach a fixture.
12042        let json = |s: &Scalar| serde_json::to_string(s).expect("serialize");
12043        let back = |text: &str| serde_json::from_str::<Scalar>(text);
12044        assert_eq!(
12045            json(&Scalar::Float64(f64::INFINITY)),
12046            r#"{"kind":"float64","value":"inf"}"#
12047        );
12048        assert_eq!(
12049            json(&Scalar::Float64(f64::NEG_INFINITY)),
12050            r#"{"kind":"float64","value":"-inf"}"#
12051        );
12052        // Unchanged spellings: finite numbers, -0.0, and NaN as null.
12053        assert_eq!(
12054            json(&Scalar::Float64(1.5)),
12055            r#"{"kind":"float64","value":1.5}"#
12056        );
12057        assert_eq!(
12058            json(&Scalar::Float64(-0.0)),
12059            r#"{"kind":"float64","value":-0.0}"#
12060        );
12061        assert_eq!(
12062            json(&Scalar::Float64(f64::NAN)),
12063            r#"{"kind":"float64","value":null}"#
12064        );
12065        for value in [f64::INFINITY, f64::NEG_INFINITY, 1.5, -2.25e300] {
12066            let scalar = Scalar::Float64(value);
12067            assert_eq!(back(&json(&scalar)).expect("round trip"), scalar);
12068        }
12069        let negative_zero = back(r#"{"kind":"float64","value":-0.0}"#).expect("-0.0");
12070        assert!(matches!(negative_zero, Scalar::Float64(v) if v == 0.0 && v.is_sign_negative()));
12071        assert!(matches!(
12072            back(r#"{"kind":"float64","value":null}"#).expect("null"),
12073            Scalar::Float64(v) if v.is_nan()
12074        ));
12075        // Anything else is an error, not a silent NaN.
12076        assert!(back(r#"{"kind":"float64","value":"Infinity"}"#).is_err());
12077        assert!(back(r#"{"kind":"float64","value":"1.5"}"#).is_err());
12078    }
12079
12080    /// br-frankenpandas-ay8o9: Scalar::semantic_cmp underpins ALL ordering in
12081    /// the library (sort, min/max, is_monotonic, searchsorted, groupby key
12082    /// order) and is the reference the differential harnesses rely on. Property
12083    /// test of its total-order axioms over finite/non-NaT same-dtype scalars,
12084    /// plus the intentional NaN degeneracy. Deterministic seeded LCG — no rand
12085    /// crate, no mocks.
12086    /// br-frankenpandas-767ak: extends ay8o9's NaN pinning to the temporal NAT
12087    /// sentinels (i64::MIN). semantic_cmp treats NAT as degenerate (Equal to all
12088    /// same-dtype), which is why temporal ordering ops must treat NAT as missing.
12089    #[test]
12090    fn semantic_cmp_cross_numeric_int_float_cdpai() {
12091        // Property (br-frankenpandas-cdpai): semantic_cmp compares Int64 vs Float64
12092        // as f64, antisymmetric across the operand order. Seeded LCG, no mocks.
12093        use std::cmp::Ordering;
12094        let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
12095        let mut next = || {
12096            st = st
12097                .wrapping_mul(6_364_136_223_846_793_005)
12098                .wrapping_add(1_442_695_040_888_963_407);
12099            (st >> 33) as u32
12100        };
12101        for _ in 0..3000u32 {
12102            let i = (next() % 21) as i64 - 10;
12103            let f = (next() % 400) as f64 / 20.0 - 10.0; // finite
12104            let exp = (i as f64).partial_cmp(&f).unwrap();
12105            assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
12106            assert_eq!(
12107                Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
12108                exp.reverse()
12109            );
12110        }
12111        // Exact int/float equality compares Equal in both directions.
12112        assert_eq!(
12113            Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
12114            Ordering::Equal
12115        );
12116        assert_eq!(
12117            Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
12118            Ordering::Equal
12119        );
12120        assert_eq!(
12121            Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
12122            Ordering::Less
12123        );
12124        assert_eq!(
12125            Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
12126            Ordering::Greater
12127        );
12128    }
12129
12130    #[test]
12131    fn semantic_cmp_nat_degeneracy_temporal_767ak() {
12132        use std::cmp::Ordering;
12133        const NAT: i64 = i64::MIN;
12134
12135        // Timedelta64 NAT is degenerate (Equal to finite and to itself).
12136        let td_nat = Scalar::Timedelta64(NAT);
12137        for v in [-3i64, 0, 5, 99] {
12138            let td = Scalar::Timedelta64(v);
12139            assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
12140            assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
12141        }
12142        assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
12143
12144        // Datetime64 NAT likewise.
12145        let dt_nat = Scalar::Datetime64(NAT);
12146        for v in [-3i64, 0, 5, 99] {
12147            let dt = Scalar::Datetime64(v);
12148            assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
12149            assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
12150        }
12151        assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
12152
12153        // Non-NAT temporal values order normally (reflexive, antisymmetric, lt).
12154        for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
12155            let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
12156            assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
12157            assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); // a.cmp(b)
12158            assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
12159            let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
12160            assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
12161        }
12162    }
12163
12164    fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
12165        [
12166            Scalar::Null(NullKind::Null),
12167            Scalar::Bool(true),
12168            Scalar::Int64(-7),
12169            Scalar::Float64(3.5),
12170            Scalar::Utf8("mixed".to_owned()),
12171            Scalar::Timedelta64(11),
12172            Scalar::Datetime64(1_735_732_800_123_456_789),
12173            Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
12174            Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
12175        ]
12176    }
12177
12178    fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
12179        !matches!(
12180            (left, right),
12181            (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
12182        )
12183    }
12184
12185    #[test]
12186    fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
12187        let values = semantic_cmp_cross_variant_values_d5ikg();
12188        for (left_index, left) in values.iter().enumerate() {
12189            for (right_index, right) in values.iter().enumerate() {
12190                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12191                {
12192                    assert_eq!(
12193                        left.semantic_cmp(right),
12194                        format!("{left:?}").cmp(&format!("{right:?}")),
12195                        "cross-variant order mismatch: {left:?} vs {right:?}"
12196                    );
12197                }
12198            }
12199        }
12200    }
12201
12202    #[test]
12203    #[ignore = "foreground release attribution harness"]
12204    fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
12205        use std::cmp::Ordering;
12206
12207        const BATCH: usize = 4_096;
12208        const BLOCKS: usize = 9;
12209
12210        fn former(left: &Scalar, right: &Scalar) -> Ordering {
12211            format!("{left:?}").cmp(&format!("{right:?}"))
12212        }
12213
12214        fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
12215            left.semantic_cmp(right)
12216        }
12217
12218        fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
12219            let mut less = 0usize;
12220            let started = std::time::Instant::now();
12221            for _ in 0..BATCH {
12222                for (left_index, left) in values.iter().enumerate() {
12223                    for (right_index, right) in values.iter().enumerate() {
12224                        if left_index != right_index
12225                            && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12226                            && compare(std::hint::black_box(left), std::hint::black_box(right))
12227                                == Ordering::Less
12228                        {
12229                            less += 1;
12230                        }
12231                    }
12232                }
12233            }
12234            std::hint::black_box(less);
12235            started.elapsed().as_nanos()
12236        }
12237
12238        fn median(samples: &mut [u128]) -> u128 {
12239            samples.sort_unstable();
12240            samples[samples.len() / 2]
12241        }
12242
12243        let values = semantic_cmp_cross_variant_values_d5ikg();
12244
12245        for (left_index, left) in values.iter().enumerate() {
12246            for (right_index, right) in values.iter().enumerate() {
12247                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12248                {
12249                    assert_eq!(
12250                        former(left, right),
12251                        candidate(left, right),
12252                        "cross-variant order mismatch: {left:?} vs {right:?}"
12253                    );
12254                }
12255            }
12256        }
12257
12258        std::hint::black_box(elapsed(&values, former));
12259        std::hint::black_box(elapsed(&values, candidate));
12260
12261        let mut former_samples = Vec::with_capacity(BLOCKS * 2);
12262        let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
12263        for block in 0..BLOCKS {
12264            if block.is_multiple_of(2) {
12265                former_samples.push(elapsed(&values, former));
12266                candidate_samples.push(elapsed(&values, candidate));
12267                candidate_samples.push(elapsed(&values, candidate));
12268                former_samples.push(elapsed(&values, former));
12269            } else {
12270                candidate_samples.push(elapsed(&values, candidate));
12271                former_samples.push(elapsed(&values, former));
12272                former_samples.push(elapsed(&values, former));
12273                candidate_samples.push(elapsed(&values, candidate));
12274            }
12275        }
12276
12277        let former_p50 = median(&mut former_samples);
12278        let candidate_p50 = median(&mut candidate_samples);
12279        eprintln!(
12280            "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
12281            former_p50 as f64 / candidate_p50 as f64
12282        );
12283    }
12284
12285    #[test]
12286    fn semantic_cmp_total_order_axioms_ay8o9() {
12287        use std::cmp::Ordering;
12288
12289        let mut state: u64 = 0xc0ff_eeba_df00_d123;
12290        let mut next = || {
12291            state = state
12292                .wrapping_mul(6_364_136_223_846_793_005)
12293                .wrapping_add(1_442_695_040_888_963_407);
12294            (state >> 33) as u32
12295        };
12296
12297        for iter in 0..6000u32 {
12298            let dt = next() % 4;
12299            // Build a same-dtype, finite, non-NaT scalar from a random u32.
12300            let mk = |r: u32| match dt {
12301                0 => Scalar::Int64((r % 11) as i64 - 5),
12302                // finite, in -5.0..=5.0 by 0.5 — no NaN/inf.
12303                1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
12304                2 => Scalar::Utf8(format!("s{}", r % 5)),
12305                _ => Scalar::Bool(r.is_multiple_of(2)),
12306            };
12307            let a = mk(next());
12308            let b = mk(next());
12309            let c = mk(next());
12310            let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
12311
12312            // Reflexivity.
12313            assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
12314            // Antisymmetry.
12315            assert_eq!(
12316                a.semantic_cmp(&b),
12317                b.semantic_cmp(&a).reverse(),
12318                "antisymmetric {ctx}"
12319            );
12320            // le / ge / eq consistency with the ordering.
12321            let ab = a.semantic_cmp(&b);
12322            assert_eq!(
12323                a.semantic_le(&b),
12324                ab != Ordering::Greater,
12325                "le-consistent {ctx}"
12326            );
12327            assert_eq!(
12328                a.semantic_ge(&b),
12329                ab != Ordering::Less,
12330                "ge-consistent {ctx}"
12331            );
12332            assert_eq!(
12333                a.semantic_le(&b) && a.semantic_ge(&b),
12334                ab == Ordering::Equal,
12335                "le&ge<=>eq {ctx}"
12336            );
12337            // Transitivity: a<=b && b<=c  =>  a<=c.
12338            if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
12339                assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
12340            }
12341        }
12342
12343        // Pin the intentional NaN degeneracy: a Float64 NaN compares Equal to
12344        // every finite Float64 (and to itself) — this is why ordering ops must
12345        // treat NaN as missing rather than relying on semantic_cmp to order it.
12346        let nan = Scalar::Float64(f64::NAN);
12347        for v in [
12348            Scalar::Float64(-3.5),
12349            Scalar::Float64(0.0),
12350            Scalar::Float64(7.25),
12351        ] {
12352            assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
12353            assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
12354        }
12355        assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
12356    }
12357
12358    /// br-frankenpandas-be314: common_dtype is the dtype-promotion lattice
12359    /// underpinning every binary op, alignment, and concat (dtype coercion is a
12360    /// crown-jewel correctness area). Exhaustively (all 14x14 DType pairs) assert
12361    /// its lattice axioms — an asymmetric arm would make df1+df2 and df2+df1
12362    /// disagree on dtype.
12363    #[test]
12364    fn common_dtype_lattice_axioms_be314() {
12365        let all: [DType; 14] = [
12366            DType::Null,
12367            DType::Bool,
12368            DType::BoolNullable,
12369            DType::Int64,
12370            DType::Int64Nullable,
12371            DType::Float64,
12372            // br-frankenpandas-qkqfb: a new variant is only safe once the
12373            // commutativity and associativity sweeps below cover it.
12374            DType::Float64Nullable,
12375            DType::Utf8,
12376            DType::Categorical,
12377            DType::Timedelta64,
12378            DType::datetime64_naive(),
12379            DType::Period,
12380            DType::Interval,
12381            DType::Sparse,
12382        ];
12383
12384        for a in &all {
12385            // Idempotence: a promoted with itself is itself.
12386            assert_eq!(
12387                common_dtype(a.clone(), a.clone()),
12388                Ok(a.clone()),
12389                "idempotent {a:?}"
12390            );
12391            // Null is the identity element of the promotion lattice.
12392            assert_eq!(
12393                common_dtype(DType::Null, a.clone()),
12394                Ok(a.clone()),
12395                "null-left identity {a:?}"
12396            );
12397            assert_eq!(
12398                common_dtype(a.clone(), DType::Null),
12399                Ok(a.clone()),
12400                "null-right identity {a:?}"
12401            );
12402
12403            for b in &all {
12404                // Commutativity: same Ok value AND same ok-ness. An asymmetric
12405                // match arm would make binary-op output dtype order-dependent.
12406                assert_eq!(
12407                    common_dtype(a.clone(), b.clone()).ok(),
12408                    common_dtype(b.clone(), a.clone()).ok(),
12409                    "commutative value {a:?},{b:?}"
12410                );
12411                assert_eq!(
12412                    common_dtype(a.clone(), b.clone()).is_ok(),
12413                    common_dtype(b.clone(), a.clone()).is_ok(),
12414                    "commutative ok-ness {a:?},{b:?}"
12415                );
12416            }
12417        }
12418
12419        // Associativity over the Ok-closed subset: when both nestings succeed,
12420        // promotion order must not change the result.
12421        for a in &all {
12422            for b in &all {
12423                for c in &all {
12424                    if let (Ok(ab), Ok(bc)) = (
12425                        common_dtype(a.clone(), b.clone()),
12426                        common_dtype(b.clone(), c.clone()),
12427                    ) && let (Ok(left), Ok(right)) =
12428                        (common_dtype(ab, c.clone()), common_dtype(a.clone(), bc))
12429                    {
12430                        assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
12431                    }
12432                }
12433            }
12434        }
12435    }
12436
12437    /// br-frankenpandas-e3sfq: infer_dtype drives Column/Series construction
12438    /// dtype inference. Assert its homogeneous + mixed-coercion rules.
12439    #[test]
12440    fn infer_dtype_coercion_rules_e3sfq() {
12441        use DType::{Bool, Float64, Int64, Null, Utf8};
12442
12443        // Empty and all-null infer to Null.
12444        assert_eq!(infer_dtype(&[]), Ok(Null));
12445        assert_eq!(
12446            infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
12447            Ok(Null)
12448        );
12449
12450        // Homogeneous slices infer to their own dtype (random, seeded LCG).
12451        let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
12452        let mut next = || {
12453            s = s
12454                .wrapping_mul(6_364_136_223_846_793_005)
12455                .wrapping_add(1_442_695_040_888_963_407);
12456            (s >> 33) as u32
12457        };
12458        for _ in 0..600u32 {
12459            let n = (next() % 6) as usize + 1;
12460            let ints: Vec<Scalar> = (0..n)
12461                .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
12462                .collect();
12463            assert_eq!(infer_dtype(&ints), Ok(Int64));
12464            let floats: Vec<Scalar> = (0..n)
12465                .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
12466                .collect();
12467            assert_eq!(infer_dtype(&floats), Ok(Float64));
12468            let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
12469            assert_eq!(infer_dtype(&bools), Ok(Bool));
12470            let strs: Vec<Scalar> = (0..n)
12471                .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
12472                .collect();
12473            assert_eq!(infer_dtype(&strs), Ok(Utf8));
12474        }
12475
12476        // Mixed-coercion rules.
12477        assert_eq!(
12478            infer_dtype(&[
12479                Scalar::Int64(1),
12480                Scalar::Null(NullKind::Null),
12481                Scalar::Int64(2)
12482            ]),
12483            Ok(Int64),
12484            "Int64 + nulls -> Int64"
12485        );
12486        assert_eq!(
12487            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
12488            Ok(Float64),
12489            "Int64 + Float64 -> Float64"
12490        );
12491        // br-frankenpandas-rh1od: MEASURED live pandas 2.2.3 — a bool mixed
12492        // with numerics constructs OBJECT; the old Int64 coercion here was
12493        // numpy common-type behavior no pandas constructor path produces.
12494        assert_eq!(
12495            infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
12496            Ok(Utf8),
12497            "Bool + Int64 -> object bucket (pandas constructs object)"
12498        );
12499        assert_eq!(
12500            infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
12501            Ok(Utf8),
12502            "Utf8 + Int64 -> Utf8 (object fallback)"
12503        );
12504    }
12505
12506    /// br-frankenpandas-1ews0: missing_for_dtype is the canonical per-dtype
12507    /// missing sentinel (used by null-fill / with_validity / cast). Exhaustively
12508    /// assert it is always missing, and that casting any missing to any dtype
12509    /// stays missing.
12510    #[test]
12511    fn missing_for_dtype_always_missing_1ews0() {
12512        let all: [DType; 14] = [
12513            DType::Null,
12514            DType::Bool,
12515            DType::BoolNullable,
12516            DType::Int64,
12517            DType::Int64Nullable,
12518            DType::Float64,
12519            DType::Float64Nullable,
12520            DType::Utf8,
12521            DType::Categorical,
12522            DType::Timedelta64,
12523            DType::datetime64_naive(),
12524            DType::Period,
12525            DType::Interval,
12526            DType::Sparse,
12527        ];
12528        for dt in &all {
12529            let m = Scalar::missing_for_dtype(dt.clone());
12530            assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
12531            for target in &all {
12532                let cast = cast_scalar(&m, target.clone()).expect("cast of missing");
12533                if target == &DType::Utf8 {
12534                    // Casting a missing value to string follows pandas astype(str):
12535                    // it yields a string ("None"/"NaN"/"NaT"), NOT a missing value.
12536                    assert!(
12537                        matches!(cast, Scalar::Utf8(_)),
12538                        "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
12539                    );
12540                } else if matches!(dt, DType::Timedelta64 | DType::Datetime64 { .. })
12541                    && matches!(target, DType::Bool | DType::Int64)
12542                {
12543                    // ⚠️ TWO MORE PLACES pandas BREAKS this invariant, and both
12544                    // are the same underlying fact: NaT is not a separate
12545                    // representation, it IS i64::MIN, and the numpy casts read
12546                    // the bits. MEASURED, live pandas 2.2.3:
12547                    //
12548                    //   pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
12549                    //     -> -9223372036854775808      the SENTINEL, not a missing
12550                    //   pd.Series([pd.NaT], dtype='timedelta64[ns]').astype('bool')
12551                    //     -> True                      nonzero, so truthy
12552                    //
12553                    // Same shape as the Utf8 carve-out above: the invariant is
12554                    // FrankenPandas' own, and pandas does not honour it wherever
12555                    // a cast is defined to reinterpret rather than to convert.
12556                    // Narrowly scoped on purpose — every other missing, and these
12557                    // two toward every other target, still stay missing.
12558                    match target {
12559                        DType::Bool => assert_eq!(
12560                            cast,
12561                            Scalar::Bool(true),
12562                            "cast(missing {dt:?} -> Bool) is pandas' nonzero-truthy \
12563                             read of the NaT bits"
12564                        ),
12565                        _ => assert_eq!(
12566                            cast,
12567                            Scalar::Int64(i64::MIN),
12568                            "cast(missing {dt:?} -> Int64) is the NaT sentinel itself"
12569                        ),
12570                    }
12571                } else {
12572                    // Every other target preserves missingness via cast_scalar's
12573                    // value.is_missing() -> missing_for_dtype(target) branch.
12574                    assert!(
12575                        cast.is_missing(),
12576                        "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
12577                    );
12578                }
12579            }
12580        }
12581    }
12582
12583    #[test]
12584    fn cast_scalar_bool_int_roundtrip_6w07b() {
12585        use super::cast_scalar;
12586        // Property (br-frankenpandas-6w07b): Bool<->Int64 cast. Seeded LCG, no mocks.
12587        assert_eq!(
12588            cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
12589            Scalar::Int64(1)
12590        );
12591        assert_eq!(
12592            cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
12593            Scalar::Int64(0)
12594        );
12595        assert_eq!(
12596            cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
12597            Scalar::Bool(false)
12598        );
12599        let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
12600        let mut next = || {
12601            st = st
12602                .wrapping_mul(6_364_136_223_846_793_005)
12603                .wrapping_add(1_442_695_040_888_963_407);
12604            (st >> 33) as u32
12605        };
12606        for _ in 0..2000u32 {
12607            let v = (next() % 21) as i64 - 10;
12608            assert_eq!(
12609                cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
12610                Scalar::Bool(v != 0),
12611                "int->bool v={v}"
12612            );
12613        }
12614    }
12615
12616    /// br-frankenpandas-6a83t: cast_scalar is the scalar dtype-coercion path
12617    #[test]
12618    fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
12619        use super::cast_scalar;
12620        // Property (br-frankenpandas-u9lec): Float64->Int64 truncates toward zero, not
12621        // floor (-3.7 -> -3). Seeded LCG, no mocks.
12622        let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
12623        let mut next = || {
12624            st = st
12625                .wrapping_mul(6_364_136_223_846_793_005)
12626                .wrapping_add(1_442_695_040_888_963_407);
12627            (st >> 33) as u32
12628        };
12629        // Explicit negative-direction checks (the gotcha).
12630        for (f, exp) in [
12631            (-3.7, -3i64),
12632            (3.7, 3),
12633            (-3.2, -3),
12634            (3.2, 3),
12635            (-0.9, 0),
12636            (0.9, 0),
12637            (-5.0, -5),
12638            (5.0, 5),
12639        ] {
12640            assert_eq!(
12641                cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
12642                Scalar::Int64(exp),
12643                "cast {f}"
12644            );
12645        }
12646        // Property over random signed fractional values.
12647        for _ in 0..3000u32 {
12648            let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; // [-1000, 1000]
12649            let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
12650            assert_eq!(
12651                got,
12652                Scalar::Int64(v.trunc() as i64),
12653                "trunc-toward-zero v={v}"
12654            );
12655        }
12656    }
12657
12658    /// Float -> `datetime64[ns]` / `timedelta64[ns]` reinterprets the float as
12659    /// integer NANOSECONDS. Every value here is transcribed from live pandas
12660    /// 2.2.3, measured on both the constructor and `astype` paths.
12661    ///
12662    /// ⚠️ THE CONTRAST WITH `int64` IS THE POINT: the explicit constructor
12663    /// REFUSES a lossy float -> int64, and silently truncates the same float
12664    /// into a temporal dtype. Assuming one rule covers both is how this gets
12665    /// re-broken, so both are asserted here on the same input.
12666    #[test]
12667    fn cast_scalar_float_to_temporal_truncates_to_nanoseconds() {
12668        use super::{Timedelta, Timestamp, cast_scalar};
12669
12670        // TRUNCATION TOWARD ZERO, on both signs, where a floor would disagree.
12671        // pandas: 0.9 -> 0, -0.9 -> 0, 1.5 -> 1, -1.5 -> -1, -2.5 -> -2.
12672        for (input, want) in [
12673            (1.5_f64, 1_i64),
12674            (-1.5, -1),
12675            (0.9, 0),
12676            (-0.9, 0),
12677            (2.5, 2),
12678            (-2.5, -2),
12679            (1.999_999, 1),
12680            (-1.999_999, -1),
12681            (2.0, 2),
12682            (1e18, 1_000_000_000_000_000_000),
12683        ] {
12684            assert_eq!(
12685                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
12686                Scalar::Datetime64(want),
12687                "datetime64 cast of {input}"
12688            );
12689            assert_eq!(
12690                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
12691                Scalar::Timedelta64(want),
12692                "timedelta64 cast of {input}"
12693            );
12694        }
12695
12696        // ANYTHING NOT REPRESENTABLE AS i64 IS NaT — not a saturated i64::MAX,
12697        // and not the epoch. A bare `as i64` would produce both of those wrong
12698        // answers (saturation for the large values, 0 for NaN).
12699        for input in [
12700            f64::NAN,
12701            f64::INFINITY,
12702            f64::NEG_INFINITY,
12703            1e30,
12704            -1e30,
12705            9.3e18,
12706            -9.3e18,
12707            9_223_372_036_854_775_808.0,  // exactly 2^63
12708            -9_223_372_036_854_775_808.0, // exactly -2^63, which IS the NaT sentinel
12709        ] {
12710            assert_eq!(
12711                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
12712                Scalar::Datetime64(Timestamp::NAT),
12713                "datetime64 cast of {input} must be NaT"
12714            );
12715            assert_eq!(
12716                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
12717                Scalar::Timedelta64(Timedelta::NAT),
12718                "timedelta64 cast of {input} must be NaT"
12719            );
12720        }
12721
12722        // ...but the largest float BELOW 2^63 is representable and converts.
12723        // pandas renders it 2262-04-11 23:47:16.854774784.
12724        let just_inside = 9_223_372_036_854_774_784.0_f64; // 2^63 - 1024
12725        assert_eq!(
12726            cast_scalar(&Scalar::Float64(just_inside), DType::datetime64_naive()).unwrap(),
12727            Scalar::Datetime64(9_223_372_036_854_774_784),
12728            "the largest representable float must NOT be treated as NaT"
12729        );
12730
12731        // THE CONTRAST. Same input, three dtypes, two different rules — the
12732        // temporal ones truncate where int64 refuses outright.
12733        assert_eq!(
12734            cast_scalar(&Scalar::Float64(1.5), DType::datetime64_naive()).unwrap(),
12735            Scalar::Datetime64(1)
12736        );
12737        assert_eq!(
12738            cast_scalar(&Scalar::Float64(1.5), DType::Int64).unwrap(),
12739            Scalar::Int64(1),
12740            "the SHARED cast truncates here too; it is the explicit constructor \
12741             that refuses, via Column::new's LossyFloatToInt pre-check"
12742        );
12743    }
12744
12745    /// The MIRROR direction: `datetime64[ns]` / `timedelta64[ns]` -> numpy
12746    /// `int64` is the raw nanosecond count, and a bool is 0 or 1 nanoseconds
12747    /// going the other way. Every value transcribed from live pandas 2.2.3
12748    /// `astype`.
12749    #[test]
12750    fn cast_scalar_temporal_to_int64_is_raw_nanoseconds() {
12751        use super::{Timedelta, Timestamp, cast_scalar};
12752
12753        // Timestamp('2024-03-15 10:30:45.123456789') and
12754        // Timedelta('1 days 02:03:04.005006007').
12755        for nanos in [1_710_498_645_123_456_789_i64, 93_784_005_006_007, 0, -1] {
12756            assert_eq!(
12757                cast_scalar(&Scalar::Datetime64(nanos), DType::Int64).unwrap(),
12758                Scalar::Int64(nanos),
12759                "datetime64 -> int64 must be the raw nanos ({nanos})"
12760            );
12761            assert_eq!(
12762                cast_scalar(&Scalar::Timedelta64(nanos), DType::Int64).unwrap(),
12763                Scalar::Int64(nanos)
12764            );
12765        }
12766
12767        // ⚠️ NaT BECOMES THE SENTINEL, NOT A MISSING VALUE. pandas:
12768        //     pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
12769        //       -> -9223372036854775808
12770        // This is the assertion that pins the cast ABOVE the is_missing()
12771        // branch; move it below and both of these become Null.
12772        assert_eq!(
12773            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Int64).unwrap(),
12774            Scalar::Int64(i64::MIN),
12775            "NaT -> int64 is the sentinel i64::MIN, not a missing value"
12776        );
12777        assert_eq!(
12778            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Int64).unwrap(),
12779            Scalar::Int64(i64::MIN)
12780        );
12781
12782        // ⚠️ THE NULLABLE Int64 REFUSES WHAT numpy int64 ACCEPTS:
12783        //     .astype('Int64')   -> TypeError: datetime64[ns] cannot be
12784        //                          converted to IntegerDtype
12785        //     .astype('float64') -> TypeError: Cannot cast DatetimeArray
12786        // Both must stay refused, which is what makes the guard on the exact
12787        // target load-bearing rather than cosmetic.
12788        // `DType` stopped being `Copy` when `Datetime64 { tz }` landed
12789        // (2f159e68f), so the loop variable is cloned into each call.
12790        for target in [DType::Int64Nullable, DType::Float64, DType::Float64Nullable] {
12791            assert!(
12792                cast_scalar(
12793                    &Scalar::Datetime64(1_710_498_645_123_456_789),
12794                    target.clone()
12795                )
12796                .is_err(),
12797                "datetime64 -> {target:?} must stay refused"
12798            );
12799            assert!(
12800                cast_scalar(&Scalar::Timedelta64(93_784_005_006_007), target.clone()).is_err(),
12801                "timedelta64 -> {target:?} must stay refused"
12802            );
12803        }
12804
12805        // A bool is 0 or 1 NANOSECONDS on the astype path.
12806        for (flag, want) in [(true, 1_i64), (false, 0)] {
12807            assert_eq!(
12808                cast_scalar(&Scalar::Bool(flag), DType::datetime64_naive()).unwrap(),
12809                Scalar::Datetime64(want)
12810            );
12811            assert_eq!(
12812                cast_scalar(&Scalar::Bool(flag), DType::Timedelta64).unwrap(),
12813                Scalar::Timedelta64(want)
12814            );
12815        }
12816    }
12817
12818    /// The two halves of the column-width datetime formatter, checked apart:
12819    /// which rung a value NEEDS, and how a value RENDERS at a given rung.
12820    /// Transcribed from live pandas 2.2.3 `.astype(str)`, one column per rung.
12821    #[test]
12822    fn timestamp_string_resolution_and_formatting_match_pandas() {
12823        use super::{DatetimeStringResolution as Res, Timestamp};
12824
12825        const MIDNIGHT: i64 = 1_710_460_800_000_000_000; // 2024-03-15 00:00:00
12826
12827        // Which rung each value needs, on its own.
12828        assert_eq!(Timestamp::string_resolution(MIDNIGHT), Res::Date);
12829        assert_eq!(
12830            Timestamp::string_resolution(MIDNIGHT + 37_845_000_000_000),
12831            Res::Second
12832        );
12833        assert_eq!(
12834            Timestamp::string_resolution(MIDNIGHT + 37_845_123_000_000),
12835            Res::Milli
12836        );
12837        assert_eq!(
12838            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_000),
12839            Res::Micro
12840        );
12841        assert_eq!(
12842            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_789),
12843            Res::Nano
12844        );
12845        // A whole MINUTE is not its own rung — it still needs Second.
12846        assert_eq!(
12847            Timestamp::string_resolution(MIDNIGHT + 300_000_000_000),
12848            Res::Second
12849        );
12850        // NaT reports the coarsest rung, the identity of the `max` fold, which
12851        // is what keeps it from dragging a column to nanoseconds.
12852        assert_eq!(Timestamp::string_resolution(Timestamp::NAT), Res::Date);
12853
12854        // Coarsest-first ordering is what makes `max` mean "finest needed".
12855        assert!(Res::Date < Res::Second);
12856        assert!(Res::Second < Res::Milli);
12857        assert!(Res::Milli < Res::Micro);
12858        assert!(Res::Micro < Res::Nano);
12859
12860        // ...and how ONE value renders at each rung it might be forced into.
12861        let value = MIDNIGHT + 37_845_123_456_789;
12862        assert_eq!(
12863            Timestamp::format_at_resolution(value, Res::Date),
12864            "2024-03-15"
12865        );
12866        assert_eq!(
12867            Timestamp::format_at_resolution(value, Res::Second),
12868            "2024-03-15 10:30:45"
12869        );
12870        assert_eq!(
12871            Timestamp::format_at_resolution(value, Res::Milli),
12872            "2024-03-15 10:30:45.123"
12873        );
12874        assert_eq!(
12875            Timestamp::format_at_resolution(value, Res::Micro),
12876            "2024-03-15 10:30:45.123456"
12877        );
12878        assert_eq!(
12879            Timestamp::format_at_resolution(value, Res::Nano),
12880            "2024-03-15 10:30:45.123456789"
12881        );
12882
12883        // A midnight forced to the nanosecond rung keeps its zero fraction --
12884        // pandas pads, it does not trim.
12885        assert_eq!(
12886            Timestamp::format_at_resolution(MIDNIGHT, Res::Nano),
12887            "2024-03-15 00:00:00.000000000"
12888        );
12889
12890        // ⚠️ NOT isoformat: a SPACE separator, not a `T`.
12891        assert_eq!(
12892            Timestamp::format_at_resolution(MIDNIGHT, Res::Second),
12893            "2024-03-15 00:00:00"
12894        );
12895
12896        // NaT is the STRING "NaT" at every rung.
12897        for resolution in [Res::Date, Res::Second, Res::Milli, Res::Micro, Res::Nano] {
12898            assert_eq!(
12899                Timestamp::format_at_resolution(Timestamp::NAT, resolution),
12900                "NaT"
12901            );
12902        }
12903
12904        // Pre-epoch: rem_euclid must keep the fraction on the right side of
12905        // midnight, or -1ns renders as 1970-01-01 with a negative fraction.
12906        assert_eq!(
12907            Timestamp::format_at_resolution(-1, Res::Nano),
12908            "1969-12-31 23:59:59.999999999"
12909        );
12910
12911        // Both ends of pandas' datetime64[ns] range.
12912        assert_eq!(
12913            Timestamp::format_at_resolution(-9_223_372_036_854_775_806, Res::Nano),
12914            "1677-09-21 00:12:43.145224194"
12915        );
12916        assert_eq!(
12917            Timestamp::format_at_resolution(9_223_372_036_854_775_807, Res::Nano),
12918            "2262-04-11 23:47:16.854775807"
12919        );
12920    }
12921
12922    /// Temporal -> numpy `bool` is nonzero-truthy on the RAW NANOSECONDS, which
12923    /// makes NaT `true`. Transcribed from live pandas 2.2.3 `.astype('bool')`,
12924    /// measured beside `.astype('int64')` so the one rule is visible as one rule.
12925    #[test]
12926    fn cast_scalar_temporal_to_bool_is_nonzero_on_the_nanos() {
12927        use super::{Timedelta, Timestamp, cast_scalar};
12928
12929        // Only the epoch and a zero duration are false.
12930        for (nanos, want) in [
12931            (0_i64, false),
12932            (1_710_498_645_123_456_789, true),
12933            (-1, true),
12934            (86_400_000_000_000, true),
12935            (1, true),
12936        ] {
12937            assert_eq!(
12938                cast_scalar(&Scalar::Datetime64(nanos), DType::Bool).unwrap(),
12939                Scalar::Bool(want),
12940                "datetime64 {nanos} -> bool"
12941            );
12942            assert_eq!(
12943                cast_scalar(&Scalar::Timedelta64(nanos), DType::Bool).unwrap(),
12944                Scalar::Bool(want),
12945                "timedelta64 {nanos} -> bool"
12946            );
12947        }
12948
12949        // ⚠️ NaT IS TRUE, not missing. It needs no case of its own — NaT IS
12950        // i64::MIN, which is nonzero — but it only reaches the rule because the
12951        // cast sits ABOVE is_missing(); below it, both of these become Null.
12952        assert_eq!(
12953            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Bool).unwrap(),
12954            Scalar::Bool(true),
12955            "NaT -> bool is true in pandas, not a missing value"
12956        );
12957        assert_eq!(
12958            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Bool).unwrap(),
12959            Scalar::Bool(true)
12960        );
12961
12962        // ⚠️ THE NULLABLE `boolean` REFUSES THE WHOLE DTYPE, not just the odd
12963        // value: pandas raises "Need to pass bool-like values" for every row
12964        // above, INCLUDING the ones whose nanos are 0 or 1. That exclusion is
12965        // what the `DType::Bool` guard buys, so it is asserted rather than
12966        // assumed.
12967        //
12968        // NaT is deliberately NOT in this loop, and the reason is a KNOWN
12969        // DIVERGENCE rather than an oversight: `is_missing()` catches NaT before
12970        // any BoolNullable arm can refuse it, so FP answers `Null` where pandas
12971        // raises. Asserting `is_err()` for it here would fail. Left visible.
12972        for nanos in [0_i64, 1, -1, 1_710_498_645_123_456_789] {
12973            assert!(
12974                cast_scalar(&Scalar::Datetime64(nanos), DType::BoolNullable).is_err(),
12975                "datetime64 {nanos} -> nullable boolean must stay refused"
12976            );
12977            assert!(
12978                cast_scalar(&Scalar::Timedelta64(nanos), DType::BoolNullable).is_err(),
12979                "timedelta64 {nanos} -> nullable boolean must stay refused"
12980            );
12981        }
12982    }
12983
12984    #[test]
12985    fn nancount_nunique_prod_any_all_mx60x() {
12986        use super::{nanall, nanany, nancount, nannunique, nanprod};
12987        // br-frankenpandas-mx60x: nancount/nannunique/nanprod/nanany/nanall skip NaN
12988        // and match finite-only oracles. Seeded LCG, no mocks.
12989        let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
12990        let mut next = || {
12991            s = s
12992                .wrapping_mul(6_364_136_223_846_793_005)
12993                .wrapping_add(1_442_695_040_888_963_407);
12994            (s >> 33) as u32
12995        };
12996        let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
12997        let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
12998        for iter in 0..1000u32 {
12999            let n = (next() % 10) as usize + 1;
13000            let raw: Vec<f64> = (0..n)
13001                .map(|_| {
13002                    if next() % 4 == 0 {
13003                        f64::NAN
13004                    } else {
13005                        (next() % 5) as f64
13006                    }
13007                })
13008                .collect();
13009            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13010            if finite.is_empty() {
13011                continue;
13012            }
13013            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13014            let distinct: std::collections::HashSet<u64> =
13015                finite.iter().map(|x| x.to_bits()).collect();
13016            let prod: f64 = finite.iter().product();
13017            assert!(
13018                (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
13019                "nancount iter={iter}"
13020            );
13021            assert!(
13022                (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
13023                "nannunique iter={iter}"
13024            );
13025            assert!(
13026                (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
13027                "nanprod iter={iter}"
13028            );
13029            assert_eq!(
13030                asb(nanany(&scalars)),
13031                finite.iter().any(|&x| x != 0.0),
13032                "nanany iter={iter}"
13033            );
13034            assert_eq!(
13035                asb(nanall(&scalars)),
13036                finite.iter().all(|&x| x != 0.0),
13037                "nanall iter={iter}"
13038            );
13039        }
13040    }
13041
13042    #[test]
13043    fn nan_reduction_kernels_skip_correctness_1uagc() {
13044        use super::{nanmax, nanmedian, nanmin, nansum};
13045        // br-frankenpandas-1uagc: nansum/nanmin/nanmax/nanmedian skip NaN and match
13046        // finite-only oracles. Seeded LCG, no mocks.
13047        let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
13048        let mut next = || {
13049            s = s
13050                .wrapping_mul(6_364_136_223_846_793_005)
13051                .wrapping_add(1_442_695_040_888_963_407);
13052            (s >> 33) as u32
13053        };
13054        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
13055        for iter in 0..1000u32 {
13056            let n = (next() % 12) as usize + 1;
13057            let raw: Vec<f64> = (0..n)
13058                .map(|_| {
13059                    if next() % 4 == 0 {
13060                        f64::NAN
13061                    } else {
13062                        (next() % 200) as f64 - 100.0
13063                    }
13064                })
13065                .collect();
13066            let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13067            if finite.is_empty() {
13068                continue;
13069            }
13070            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13071            let sum: f64 = finite.iter().sum();
13072            let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
13073            let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
13074            finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
13075            let m = finite.len();
13076            let med = if m % 2 == 1 {
13077                finite[m / 2]
13078            } else {
13079                (finite[m / 2 - 1] + finite[m / 2]) / 2.0
13080            };
13081            assert!(
13082                (val(nansum(&scalars)) - sum).abs() < 1e-7,
13083                "nansum iter={iter}"
13084            );
13085            assert!(
13086                (val(nanmin(&scalars)) - mn).abs() < 1e-9,
13087                "nanmin iter={iter}"
13088            );
13089            assert!(
13090                (val(nanmax(&scalars)) - mx).abs() < 1e-9,
13091                "nanmax iter={iter}"
13092            );
13093            assert!(
13094                (val(nanmedian(&scalars)) - med).abs() < 1e-9,
13095                "nanmedian iter={iter}"
13096            );
13097        }
13098    }
13099
13100    #[test]
13101    fn nanvar_ddof_nanstd_nan_skip_p00ag() {
13102        use super::{nanmean, nanstd, nanvar};
13103        // br-frankenpandas-p00ag: nanmean/nanvar/nanstd skip NaN; ddof picks the
13104        // denominator; nanstd==sqrt(nanvar). Seeded LCG, no mocks.
13105        let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
13106        let mut next = || {
13107            s = s
13108                .wrapping_mul(6_364_136_223_846_793_005)
13109                .wrapping_add(1_442_695_040_888_963_407);
13110            (s >> 33) as u32
13111        };
13112        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
13113        for iter in 0..1000u32 {
13114            let n = (next() % 10) as usize + 2;
13115            let raw: Vec<f64> = (0..n)
13116                .map(|_| {
13117                    if next() % 4 == 0 {
13118                        f64::NAN
13119                    } else {
13120                        (next() % 200) as f64 / 7.0
13121                    }
13122                })
13123                .collect();
13124            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13125            if finite.len() < 2 {
13126                continue;
13127            }
13128            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13129            let nf = finite.len() as f64;
13130            let mean = finite.iter().sum::<f64>() / nf;
13131            let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
13132            assert!(
13133                (val(nanmean(&scalars)) - mean).abs() < 1e-7,
13134                "nanmean iter={iter}"
13135            );
13136            assert!(
13137                (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
13138                "nanvar ddof0 iter={iter}"
13139            );
13140            assert!(
13141                (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
13142                "nanvar ddof1 iter={iter}"
13143            );
13144            assert!(
13145                (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
13146                "nanstd ddof1 iter={iter}"
13147            );
13148        }
13149    }
13150
13151    #[test]
13152    fn nanskew_nankurt_min_sample_and_known_xybnq() {
13153        // br-frankenpandas-xybnq: guard nanskew/nankurt min-sample-size (NaN below
13154        // threshold) + known pandas G1/G2 values (the f4dc5540 inline-copy bug area).
13155        use super::{nankurt, nanskew};
13156        let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
13157        let val = |s: Scalar| -> Option<f64> {
13158            if s.is_missing() {
13159                None
13160            } else {
13161                s.to_f64().ok()
13162            }
13163        };
13164
13165        // skew needs >= 3 observations.
13166        assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
13167        let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
13168        assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
13169        let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
13170        assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
13171
13172        // kurt needs >= 4 observations.
13173        assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
13174        let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
13175        assert!(
13176            (k - (-1.2)).abs() < 1e-6,
13177            "pandas kurt([1..5]) == -1.2, got {k}"
13178        );
13179    }
13180
13181    #[test]
13182    #[ignore = "foreground release attribution harness"]
13183    fn nanskew_fused_moment_scan_ab_mavln() {
13184        const ROWS: usize = 100_000;
13185        const BATCH: usize = 8;
13186
13187        fn former(values: &[Scalar]) -> Scalar {
13188            let nums = super::collect_finite(values);
13189            let n = nums.len() as f64;
13190            if n < 3.0 {
13191                return Scalar::Null(NullKind::NaN);
13192            }
13193            let mean = nums.iter().sum::<f64>() / n;
13194            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
13195            let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
13196            let s2 = m2 / (n - 1.0);
13197            if s2 == 0.0 {
13198                return Scalar::Float64(0.0);
13199            }
13200            let s3 = s2.powf(1.5);
13201            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
13202        }
13203
13204        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
13205            match (former, candidate) {
13206                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
13207                (a, b) => assert_eq!(a, b),
13208            }
13209        }
13210
13211        fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
13212            std::hint::black_box(skew(std::hint::black_box(values)));
13213            let started = std::time::Instant::now();
13214            for _ in 0..BATCH {
13215                std::hint::black_box(skew(std::hint::black_box(values)));
13216            }
13217            started.elapsed().as_nanos()
13218        }
13219
13220        fn median(samples: &mut [u128]) -> u128 {
13221            samples.sort_unstable();
13222            samples[samples.len() / 2]
13223        }
13224
13225        for values in [
13226            vec![],
13227            vec![Scalar::Int64(1), Scalar::Int64(2)],
13228            vec![Scalar::Int64(7); 16],
13229            vec![
13230                Scalar::Int64(-3),
13231                Scalar::Null(NullKind::NaN),
13232                Scalar::Float64(2.5),
13233                Scalar::Utf8("skip".to_owned()),
13234                Scalar::Int64(11),
13235            ],
13236        ] {
13237            assert_bits_eq(former(&values), super::nanskew(&values));
13238        }
13239
13240        let values = (0..ROWS)
13241            .map(|i| {
13242                if i % 257 == 0 {
13243                    Scalar::Null(NullKind::NaN)
13244                } else {
13245                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
13246                }
13247            })
13248            .collect::<Vec<_>>();
13249        assert_bits_eq(former(&values), super::nanskew(&values));
13250
13251        for _ in 0..2 {
13252            std::hint::black_box(elapsed(&values, former));
13253            std::hint::black_box(elapsed(&values, super::nanskew));
13254        }
13255
13256        let mut former_samples = Vec::with_capacity(18);
13257        let mut candidate_samples = Vec::with_capacity(18);
13258        for block in 0_usize..9 {
13259            if block.is_multiple_of(2) {
13260                former_samples.push(elapsed(&values, former));
13261                candidate_samples.push(elapsed(&values, super::nanskew));
13262                candidate_samples.push(elapsed(&values, super::nanskew));
13263                former_samples.push(elapsed(&values, former));
13264            } else {
13265                candidate_samples.push(elapsed(&values, super::nanskew));
13266                former_samples.push(elapsed(&values, former));
13267                former_samples.push(elapsed(&values, former));
13268                candidate_samples.push(elapsed(&values, super::nanskew));
13269            }
13270        }
13271
13272        let former_p50 = median(&mut former_samples);
13273        let candidate_p50 = median(&mut candidate_samples);
13274        eprintln!(
13275            "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
13276            former_p50 as f64 / candidate_p50 as f64,
13277        );
13278        eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
13279        eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
13280    }
13281
13282    #[test]
13283    #[ignore = "foreground performance probe"]
13284    fn nankurt_fused_moment_scan_ab_idka7() {
13285        const ROWS: usize = 65_536;
13286        const BATCH: usize = 4;
13287
13288        fn former(values: &[Scalar]) -> Scalar {
13289            let nums = super::collect_finite(values);
13290            let n = nums.len() as f64;
13291            if n < 4.0 {
13292                return Scalar::Null(NullKind::NaN);
13293            }
13294            let mean = nums.iter().sum::<f64>() / n;
13295            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
13296            let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
13297            let s2 = m2 / (n - 1.0);
13298            if s2 == 0.0 {
13299                return Scalar::Float64(0.0);
13300            }
13301            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
13302            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
13303            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
13304        }
13305
13306        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
13307            match (former, candidate) {
13308                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
13309                (a, b) => assert_eq!(a, b),
13310            }
13311        }
13312
13313        fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
13314            let started = std::time::Instant::now();
13315            for _ in 0..BATCH {
13316                std::hint::black_box(kurt(std::hint::black_box(values)));
13317            }
13318            started.elapsed().as_nanos()
13319        }
13320
13321        fn median(samples: &mut [u128]) -> u128 {
13322            samples.sort_unstable();
13323            samples[samples.len() / 2]
13324        }
13325
13326        for values in [
13327            vec![],
13328            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13329            vec![Scalar::Int64(7); 16],
13330            vec![
13331                Scalar::Int64(-3),
13332                Scalar::Null(NullKind::NaN),
13333                Scalar::Float64(2.5),
13334                Scalar::Utf8("skip".to_owned()),
13335                Scalar::Int64(11),
13336                Scalar::Float64(-7.25),
13337            ],
13338        ] {
13339            assert_bits_eq(former(&values), super::nankurt(&values));
13340        }
13341
13342        let values = (0..ROWS)
13343            .map(|i| {
13344                if i % 257 == 0 {
13345                    Scalar::Null(NullKind::NaN)
13346                } else {
13347                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
13348                }
13349            })
13350            .collect::<Vec<_>>();
13351        assert_bits_eq(former(&values), super::nankurt(&values));
13352
13353        for _ in 0..2 {
13354            std::hint::black_box(elapsed(&values, former));
13355            std::hint::black_box(elapsed(&values, super::nankurt));
13356        }
13357
13358        let mut former_samples = Vec::with_capacity(10);
13359        let mut candidate_samples = Vec::with_capacity(10);
13360        for block in 0_usize..5 {
13361            if block.is_multiple_of(2) {
13362                former_samples.push(elapsed(&values, former));
13363                candidate_samples.push(elapsed(&values, super::nankurt));
13364                candidate_samples.push(elapsed(&values, super::nankurt));
13365                former_samples.push(elapsed(&values, former));
13366            } else {
13367                candidate_samples.push(elapsed(&values, super::nankurt));
13368                former_samples.push(elapsed(&values, former));
13369                former_samples.push(elapsed(&values, former));
13370                candidate_samples.push(elapsed(&values, super::nankurt));
13371            }
13372        }
13373
13374        let former_p50 = median(&mut former_samples);
13375        let candidate_p50 = median(&mut candidate_samples);
13376        eprintln!(
13377            "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
13378            former_p50 as f64 / candidate_p50 as f64,
13379        );
13380        eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
13381        eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
13382    }
13383
13384    /// behind astype/promotion. Property test of its confirmed identity +
13385    /// numeric/bool coercion rules over random scalars. Deterministic seeded LCG.
13386    #[test]
13387    fn cast_scalar_to_utf8_formatting_yes7i() {
13388        // Property (br-frankenpandas-yes7i): cast to Utf8 formats per pandas
13389        // astype(str): Int64 -> decimal, Bool -> True/False. Seeded LCG, no mocks.
13390        let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
13391        let mut next = || {
13392            st = st
13393                .wrapping_mul(6_364_136_223_846_793_005)
13394                .wrapping_add(1_442_695_040_888_963_407);
13395            (st >> 33) as u32
13396        };
13397        for _ in 0..3000u32 {
13398            let n = (next() % 4_000_001) as i64 - 2_000_000;
13399            assert_eq!(
13400                cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
13401                Scalar::Utf8(n.to_string())
13402            );
13403        }
13404        assert_eq!(
13405            cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
13406            Scalar::Utf8("True".to_string())
13407        );
13408        assert_eq!(
13409            cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
13410            Scalar::Utf8("False".to_string())
13411        );
13412    }
13413
13414    #[test]
13415    fn cast_scalar_coercion_rules_6a83t() {
13416        let mut state: u64 = 0x5a17_c0de_1234_abcd;
13417        let mut next = || {
13418            state = state
13419                .wrapping_mul(6_364_136_223_846_793_005)
13420                .wrapping_add(1_442_695_040_888_963_407);
13421            (state >> 33) as u32
13422        };
13423
13424        for _ in 0..4000u32 {
13425            let n = (next() % 21) as i64 - 10; // -10..=10, incl 0
13426            let b = next() % 2 == 0;
13427            let f = f64::from((next() % 41) as i32 - 20) / 4.0; // finite, incl 0.0
13428
13429            let i = Scalar::Int64(n);
13430            let bo = Scalar::Bool(b);
13431            let fl = Scalar::Float64(f);
13432
13433            // Identity casts.
13434            assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
13435            assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
13436            assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
13437
13438            // Representation-preserving nullable identities.
13439            assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
13440            assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
13441
13442            // Int64 coercions.
13443            assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
13444            assert_eq!(
13445                cast_scalar(&i, DType::Float64),
13446                Ok(Scalar::Float64(n as f64))
13447            );
13448
13449            // Bool coercions.
13450            assert_eq!(
13451                cast_scalar(&bo, DType::Int64),
13452                Ok(Scalar::Int64(i64::from(b)))
13453            );
13454            assert_eq!(
13455                cast_scalar(&bo, DType::Float64),
13456                Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
13457            );
13458
13459            // Finite Float64 -> Int64 truncates toward zero (x as i64).
13460            assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
13461        }
13462    }
13463
13464    /// br-frankenpandas-esjjy / fd90.182: ergonomic From impls for Scalar.
13465    #[test]
13466    fn scalar_from_primitive_types() {
13467        // Each primitive maps to its canonical Scalar variant.
13468        assert_eq!(Scalar::from(true), Scalar::Bool(true));
13469        assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
13470        assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
13471        assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
13472        assert_eq!(
13473            Scalar::from(String::from("world")),
13474            Scalar::Utf8("world".to_owned())
13475        );
13476
13477        // .into() works in mixed-type Vec<Scalar> contexts (the README's
13478        // case_when example pattern, and what fd90.181 needed for apply_row
13479        // closures).
13480        let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
13481        assert_eq!(mixed[0], Scalar::Int64(1));
13482        assert_eq!(mixed[1], Scalar::Float64(2.0));
13483        assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
13484    }
13485
13486    #[test]
13487    fn dtype_inference_routes_bool_numeric_mix_to_object_bucket_rh1od() {
13488        // Was `dtype_inference_coerces_numeric_values` (Bool+Int64+Float64 ->
13489        // Float64). br-frankenpandas-rh1od, MEASURED live pandas 2.2.3:
13490        // pd.Series([True, 7, 3.5]) constructs OBJECT — no pandas constructor
13491        // path produces the numpy common-type Float64 here.
13492        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
13493        assert_eq!(
13494            infer_dtype(&values).expect("dtype should infer"),
13495            DType::Utf8
13496        );
13497    }
13498
13499    #[test]
13500    fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
13501        let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
13502        let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
13503        assert_eq!(left.dtype(), DType::Interval);
13504        assert!(!left.is_missing());
13505        assert_eq!(
13506            infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
13507            DType::Interval
13508        );
13509        assert_eq!(
13510            common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
13511            DType::Interval
13512        );
13513        assert_eq!(
13514            cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
13515            Scalar::Null(NullKind::Null)
13516        );
13517        assert_eq!(
13518            cast_scalar(&left, DType::Utf8).expect("interval string cast"),
13519            Scalar::Utf8("(0.0, 1.0]".to_owned())
13520        );
13521        assert_eq!(
13522            super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
13523            Scalar::Int64(2)
13524        );
13525    }
13526
13527    #[test]
13528    fn cast_scalar_parses_temporal_extension_strings_avm08() {
13529        let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
13530            .expect("timestamp parse")
13531            .nanos;
13532        assert_eq!(
13533            cast_scalar(
13534                &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
13535                DType::datetime64_naive()
13536            )
13537            .expect("datetime cast"),
13538            Scalar::Datetime64(expected_nanos)
13539        );
13540        assert_eq!(
13541            cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
13542            Scalar::Period(Period::new(216, PeriodFreq::QUARTERLY))
13543        );
13544        assert_eq!(
13545            cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
13546                .expect("interval cast"),
13547            Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
13548        );
13549    }
13550
13551    #[test]
13552    fn missing_values_get_target_missing_marker() {
13553        let missing = Scalar::Null(NullKind::Null);
13554        let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
13555        assert_eq!(cast, Scalar::Null(NullKind::NaN));
13556    }
13557
13558    #[test]
13559    fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
13560        let cases = [
13561            (Scalar::Bool(true), "True"),
13562            (Scalar::Bool(false), "False"),
13563            (Scalar::Int64(-7), "-7"),
13564            (Scalar::Float64(1.0), "1.0"),
13565            (Scalar::Float64(1.5), "1.5"),
13566            (Scalar::Float64(f64::NAN), "nan"),
13567            (Scalar::Null(NullKind::Null), "None"),
13568            (Scalar::Null(NullKind::NaN), "nan"),
13569            (Scalar::Null(NullKind::NaT), "NaT"),
13570        ];
13571
13572        for (value, expected) in cases {
13573            assert_eq!(
13574                cast_scalar(&value, DType::Utf8).expect("cast"),
13575                Scalar::Utf8(expected.to_owned())
13576            );
13577        }
13578    }
13579
13580    #[test]
13581    fn semantic_eq_treats_nan_as_equal() {
13582        let left = Scalar::Float64(f64::NAN);
13583        let right = Scalar::Null(NullKind::NaN);
13584        assert!(left.semantic_eq(&right));
13585    }
13586
13587    #[test]
13588    fn semantic_eq_treats_nan_as_missing_null() {
13589        let left = Scalar::Float64(f64::NAN);
13590        let right = Scalar::Null(NullKind::Null);
13591        assert!(left.semantic_eq(&right));
13592    }
13593
13594    /// A DTYPE-SENTINEL missing equals a `Null` marker, for every dtype that
13595    /// has one.
13596    ///
13597    /// `missing_for_dtype` DEFINES the canonical missing for Timedelta64 as
13598    /// `Timedelta64(NAT)`, for Datetime64 as `Datetime64(NAT)` and for Period as
13599    /// ordinal `i64::MIN`, and `is_missing()` agrees — but `semantic_eq` used to
13600    /// unify only the `Null`/NaN flavours, so an oracle's `null` for pandas' NaT
13601    /// could never match FP's sentinel. Observed on
13602    /// `fp_p2d_021_series_to_timedelta_negative_null_hardened`, where the
13603    /// fixture pinned the raw `-9223372036854775808` as though it were data.
13604    ///
13605    /// THE NEGATIVE CASES ARE THE POINT — "both missing" must not become "any
13606    /// sentinel matches anything":
13607    /// - a NaT sentinel must NOT equal a PRESENT timedelta;
13608    /// - two DIFFERENT present timedeltas must stay unequal;
13609    /// - Period and Datetime64 must unify too, or the fix is Timedelta-only.
13610    ///
13611    /// (br-frankenpandas-xwxci)
13612    #[test]
13613    fn semantic_eq_unifies_dtype_sentinel_missing_with_null_xwxci() {
13614        for sentinel in [
13615            Scalar::Timedelta64(Timedelta::NAT),
13616            Scalar::Datetime64(Timestamp::NAT),
13617            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
13618        ] {
13619            assert!(sentinel.is_missing(), "{sentinel:?} must report missing");
13620            for marker in [
13621                Scalar::Null(NullKind::Null),
13622                Scalar::Null(NullKind::NaN),
13623                Scalar::Null(NullKind::NaT),
13624            ] {
13625                assert!(
13626                    sentinel.semantic_eq(&marker),
13627                    "{sentinel:?} vs {marker:?} are both missing"
13628                );
13629                assert!(marker.semantic_eq(&sentinel), "and symmetrically");
13630            }
13631        }
13632
13633        // NOT a blanket match: a sentinel differs from a PRESENT value.
13634        let present = Scalar::Timedelta64(-60);
13635        assert!(!Scalar::Timedelta64(Timedelta::NAT).semantic_eq(&present));
13636        assert!(!present.semantic_eq(&Scalar::Null(NullKind::Null)));
13637        // And two distinct present values stay distinct.
13638        assert!(!present.semantic_eq(&Scalar::Timedelta64(-61)));
13639    }
13640
13641    #[test]
13642    fn common_dtype_rejects_string_numeric_mix() {
13643        let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
13644        assert_eq!(
13645            err.to_string(),
13646            "dtype coercion from Utf8 to Int64 has no compatible common type"
13647        );
13648        let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
13649        assert_eq!(
13650            err.to_string(),
13651            "dtype coercion from Float64 to Utf8 has no compatible common type"
13652        );
13653    }
13654
13655    #[test]
13656    fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
13657        let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
13658
13659        assert_eq!(dtype.value_dtype, DType::Float64);
13660        assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
13661    }
13662
13663    #[test]
13664    fn sparse_dtype_rejects_sparse_value_dtype() {
13665        let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
13666
13667        assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
13668    }
13669
13670    #[test]
13671    fn common_dtype_rejects_sparse_dense_mix() {
13672        let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
13673
13674        assert_eq!(
13675            err.to_string(),
13676            "dtype coercion from Sparse to Int64 has no compatible common type"
13677        );
13678    }
13679
13680    // ── Nullable Int64/Bool dtype tests (br-frankenpandas-rg8ys.6.4) ────
13681
13682    #[test]
13683    fn nullable_int64_promotion_matrix() {
13684        // Int64 + Int64Nullable -> Int64Nullable (nullable absorbs)
13685        assert_eq!(
13686            common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
13687            DType::Int64Nullable
13688        );
13689        assert_eq!(
13690            common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
13691            DType::Int64Nullable
13692        );
13693
13694        // Int64Nullable + Float64 -> Float64Nullable. The old comment here said
13695        // "float always wins"; that is half right. The float wins, but the
13696        // NULLABLE flavour of it does — MEASURED, live pandas 2.2.3:
13697        //   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5]) -> Float64
13698        // where that Float64 is the extension dtype (missing = pd.NA), not
13699        // numpy float64 (missing = NaN). (br-frankenpandas-qkqfb)
13700        assert_eq!(
13701            common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
13702            DType::Float64Nullable
13703        );
13704        assert_eq!(
13705            common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
13706            DType::Float64Nullable
13707        );
13708
13709        // Int64Nullable + Int64Nullable -> Int64Nullable
13710        assert_eq!(
13711            common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
13712            DType::Int64Nullable
13713        );
13714
13715        // Bool + Int64Nullable -> Int64Nullable
13716        assert_eq!(
13717            common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
13718            DType::Int64Nullable
13719        );
13720
13721        // BoolNullable + Int64 -> Int64Nullable
13722        assert_eq!(
13723            common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
13724            DType::Int64Nullable
13725        );
13726    }
13727
13728    #[test]
13729    fn nullable_bool_promotion_matrix() {
13730        // Bool + BoolNullable -> BoolNullable
13731        assert_eq!(
13732            common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
13733            DType::BoolNullable
13734        );
13735        assert_eq!(
13736            common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
13737            DType::BoolNullable
13738        );
13739
13740        // BoolNullable + Float64 -> Float64Nullable. MEASURED, live pandas 2.2.3:
13741        //   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
13742        //     -> Float64   (extension)
13743        // This arm moves together with the Int64Nullable one in
13744        // nullable_int64_promotion_matrix; flipping either alone breaks lattice
13745        // associativity. (br-frankenpandas-qkqfb)
13746        assert_eq!(
13747            common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
13748            DType::Float64Nullable
13749        );
13750
13751        // CONTROL: the all-numpy pair is untouched and stays on the numpy side.
13752        //   pd.Series([True,False],dtype="bool") + pd.Series([1.5,2.5]) -> float64
13753        assert_eq!(
13754            common_dtype(DType::Bool, DType::Float64).unwrap(),
13755            DType::Float64
13756        );
13757    }
13758
13759    #[test]
13760    fn dtype_is_nullable_helper() {
13761        assert!(DType::Int64Nullable.is_nullable());
13762        assert!(DType::BoolNullable.is_nullable());
13763        assert!(!DType::Int64.is_nullable());
13764        assert!(!DType::Bool.is_nullable());
13765        assert!(!DType::Float64.is_nullable());
13766        assert!(!DType::Utf8.is_nullable());
13767    }
13768
13769    #[test]
13770    fn dtype_to_nullable_conversions() {
13771        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
13772        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
13773        // ⚠ THIS LINE WAS RED ON main SINCE fa6caee91 AND NOBODY SAW IT.
13774        // It used to read `Float64.to_nullable() == Float64  // unchanged`,
13775        // which was true only while FP had no nullable float at all. fa6caee91
13776        // (br-frankenpandas-qkqfb slice 1) added DType::Float64Nullable and
13777        // pointed to_nullable at it, but that commit was gated with
13778        // `cargo check --all-targets` plus a NAME-FILTERED test run, so this
13779        // pre-existing test was never executed and the break went unnoticed.
13780        // Float64's nullable flavour IS Float64Nullable — that is the dtype's
13781        // entire reason to exist — so the assertion is what was stale.
13782        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
13783        assert_eq!(
13784            DType::Float64Nullable.to_nullable(),
13785            DType::Float64Nullable,
13786            "idempotent: already nullable"
13787        );
13788        assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
13789    }
13790
13791    #[test]
13792    fn dtype_to_non_nullable_conversions() {
13793        assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
13794        assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
13795        assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); // unchanged
13796        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
13797    }
13798
13799    #[test]
13800    fn nullable_dtype_name_reports_pandas_style() {
13801        assert_eq!(DType::Int64.name(), "int64");
13802        assert_eq!(DType::Int64Nullable.name(), "Int64"); // capital I
13803        assert_eq!(DType::Bool.name(), "bool");
13804        assert_eq!(DType::BoolNullable.name(), "boolean");
13805    }
13806
13807    #[test]
13808    fn cast_scalar_int64_nullable_identity() {
13809        let val = Scalar::Int64(42);
13810        // Int64 -> Int64Nullable is identity (no actual conversion)
13811        let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
13812        assert_eq!(result, Scalar::Int64(42));
13813
13814        // Int64Nullable -> Int64 is also identity
13815        let result2 = cast_scalar(&val, DType::Int64).unwrap();
13816        assert_eq!(result2, Scalar::Int64(42));
13817    }
13818
13819    #[test]
13820    fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
13821        // pandas astype(str) of floats == Python str(float): whole -> ".0",
13822        // shortest round-trip decimals, scientific (e+NN/e-NN) for large/small,
13823        // inf -> "inf", NaN -> "nan". Verified vs live pandas 2.2.3. (Previously
13824        // large/small lost scientific notation, e.g. 1e16 -> "10000000000000000.0".)
13825        let cases: &[(f64, &str)] = &[
13826            (1.0, "1.0"),
13827            (2.5, "2.5"),
13828            (100.0, "100.0"),
13829            (0.1, "0.1"),
13830            (0.0001, "0.0001"),
13831            (1e16, "1e+16"),
13832            (1e20, "1e+20"),
13833            (1e-5, "1e-05"),
13834            (1e-7, "1e-07"),
13835            (f64::INFINITY, "inf"),
13836            (f64::NEG_INFINITY, "-inf"),
13837        ];
13838        for (v, expected) in cases {
13839            assert_eq!(
13840                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13841                Scalar::Utf8((*expected).to_owned()),
13842                "float {v} -> str"
13843            );
13844        }
13845    }
13846
13847    fn float_to_string_for_astype_former(value: f64) -> String {
13848        if value.is_nan() {
13849            return "nan".to_owned();
13850        }
13851        if value.is_infinite() {
13852            return value.to_string();
13853        }
13854        let rendered = format!("{value:?}");
13855        match rendered.split_once('e') {
13856            None => rendered,
13857            Some((mantissa, exponent)) => {
13858                let (sign, digits) = match exponent.strip_prefix('-') {
13859                    Some(digits) => ('-', digits),
13860                    None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
13861                };
13862                format!("{mantissa}e{sign}{digits:0>2}")
13863            }
13864        }
13865    }
13866
13867    fn scientific_astype_values(len: usize) -> Vec<f64> {
13868        const EXPONENTS: [i32; 16] = [
13869            -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
13870        ];
13871        (0..len)
13872            .map(|position| {
13873                let mantissa = 1.0 + (position % 997) as f64 / 997.0;
13874                let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
13875                if position.is_multiple_of(2) {
13876                    magnitude
13877                } else {
13878                    -magnitude
13879                }
13880            })
13881            .collect()
13882    }
13883
13884    #[test]
13885    fn float_to_string_for_astype_in_place_matches_former() {
13886        let fixed = [
13887            f64::NAN,
13888            f64::INFINITY,
13889            f64::NEG_INFINITY,
13890            0.0,
13891            -0.0,
13892            f64::MIN_POSITIVE,
13893            f64::MAX,
13894            f64::MIN,
13895            1e16,
13896            -1e16,
13897            1e-5,
13898            -1e-5,
13899            1.234_567_890_123_456_8e20,
13900            -9.876_543_210_987_654e-123,
13901        ];
13902        for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
13903            assert_eq!(
13904                super::float_to_string_for_astype(value),
13905                float_to_string_for_astype_former(value),
13906                "value={value:?}"
13907            );
13908        }
13909    }
13910
13911    #[test]
13912    #[ignore = "foreground performance probe"]
13913    fn float_to_string_for_astype_in_place_ab() {
13914        use std::time::Instant;
13915
13916        const VALUES: usize = 16_384;
13917        const SAMPLES: usize = 10;
13918        let values = scientific_astype_values(VALUES);
13919        for &value in &values {
13920            let former = float_to_string_for_astype_former(value);
13921            assert!(former.contains('e'), "benchmark value must be scientific");
13922            assert_eq!(super::float_to_string_for_astype(value), former);
13923        }
13924
13925        for _ in 0..2 {
13926            for &value in &values {
13927                std::hint::black_box(float_to_string_for_astype_former(value));
13928                std::hint::black_box(super::float_to_string_for_astype(value));
13929            }
13930        }
13931
13932        let mut former_ns = Vec::with_capacity(SAMPLES);
13933        let mut public_ns = Vec::with_capacity(SAMPLES);
13934        for sample in 0..SAMPLES {
13935            let run = |formatter: fn(f64) -> String| {
13936                let started = Instant::now();
13937                for &value in std::hint::black_box(&values) {
13938                    std::hint::black_box(formatter(std::hint::black_box(value)));
13939                }
13940                started.elapsed().as_nanos()
13941            };
13942            if sample.is_multiple_of(2) {
13943                former_ns.push(run(float_to_string_for_astype_former));
13944                public_ns.push(run(super::float_to_string_for_astype));
13945            } else {
13946                public_ns.push(run(super::float_to_string_for_astype));
13947                former_ns.push(run(float_to_string_for_astype_former));
13948            }
13949        }
13950
13951        former_ns.sort_unstable();
13952        public_ns.sort_unstable();
13953        let former_p50 = former_ns[SAMPLES / 2];
13954        let public_p50 = public_ns[SAMPLES / 2];
13955        println!(
13956            "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:?}",
13957            former_p50 as f64 / public_p50 as f64
13958        );
13959    }
13960
13961    #[test]
13962    fn cast_float_to_utf8_threshold_boundaries_match_python() {
13963        // Python str(float) switches to scientific notation only at |x| >= 1e16
13964        // or |x| < 1e-4. Values JUST INSIDE those bounds must stay decimal — a
13965        // formatter that switches to sci early (or late) diverges. All expected
13966        // values verified against Python 3 str()/repr (== pandas astype(str)).
13967        let cases: &[(f64, &str)] = &[
13968            (1e15, "1000000000000000.0"),
13969            (9_999_999_999_999_998.0, "9999999999999998.0"),
13970            (1_234_567_890_123_456.0, "1234567890123456.0"),
13971            (123_456_789_012_345.0, "123456789012345.0"),
13972            (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
13973            (1e16, "1e+16"),
13974            (1.5e16, "1.5e+16"),
13975            (1e17, "1e+17"),
13976            (1e-4, "0.0001"),
13977            (5e-5, "5e-05"),
13978            (-1e15, "-1000000000000000.0"),
13979            (-1e16, "-1e+16"),
13980            (-1e-5, "-1e-05"),
13981        ];
13982        for (v, expected) in cases {
13983            assert_eq!(
13984                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13985                Scalar::Utf8((*expected).to_owned()),
13986                "float {v} -> str"
13987            );
13988        }
13989    }
13990
13991    #[test]
13992    fn cast_to_bool_uses_pandas_nonzero_truthiness() {
13993        // pandas astype(bool): zero -> False, any nonzero -> True (not just 0/1),
13994        // -0.0 -> False, and NaN -> True (numpy bool(nan), br-cyi4h). Verified vs
13995        // live pandas 2.2.3.
13996        let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
13997        for (v, expected) in cases_int {
13998            assert_eq!(
13999                cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
14000                Scalar::Bool(*expected),
14001                "int {v} -> bool"
14002            );
14003        }
14004        let cases_float: &[(f64, bool)] = &[
14005            (0.0, false),
14006            (-0.0, false),
14007            (0.1, true),
14008            (2.5, true),
14009            (1.0, true),
14010            // pandas astype(bool): NaN is truthy -> True (numpy bool). br-cyi4h.
14011            (f64::NAN, true),
14012        ];
14013        for (v, expected) in cases_float {
14014            assert_eq!(
14015                cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
14016                Scalar::Bool(*expected),
14017                "float {v} -> bool"
14018            );
14019        }
14020    }
14021
14022    #[test]
14023    fn nullable_dtype_is_extension() {
14024        assert!(DType::Int64Nullable.is_extension());
14025        assert!(DType::BoolNullable.is_extension());
14026        assert!(!DType::Int64.is_extension());
14027        assert!(!DType::Bool.is_extension());
14028    }
14029
14030    #[test]
14031    fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
14032        let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
14033        assert_eq!(
14034            infer_dtype(&values).expect("dtype should infer"),
14035            DType::Utf8
14036        );
14037    }
14038
14039    #[test]
14040    fn infer_dtype_routes_bool_numeric_mix_to_utf8_object_bucket_rh1od() {
14041        // br-frankenpandas-rh1od, MEASURED live pandas 2.2.3: a bool mixed
14042        // with any numeric scalar constructs OBJECT ([True, 2] -> object,
14043        // payloads preserved); numpy's bool<int common-type never fires at
14044        // the constructor. Discriminating: before the change this inferred
14045        // Int64 and coerced True -> 1.
14046        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Bool(false)];
14047        assert_eq!(
14048            infer_dtype(&values).expect("dtype should infer"),
14049            DType::Utf8
14050        );
14051        let with_float = vec![Scalar::Int64(1), Scalar::Float64(2.5), Scalar::Bool(true)];
14052        assert_eq!(
14053            infer_dtype(&with_float).expect("dtype should infer"),
14054            DType::Utf8
14055        );
14056        let with_null = vec![
14057            Scalar::Bool(true),
14058            Scalar::Null(NullKind::Null),
14059            Scalar::Int64(2),
14060        ];
14061        assert_eq!(
14062            infer_dtype(&with_null).expect("dtype should infer"),
14063            DType::Utf8
14064        );
14065    }
14066
14067    #[test]
14068    fn infer_dtype_keeps_nonmixed_bool_and_numeric_paths_rh1od() {
14069        // Pure bool stays bool; numeric-only mixes keep the common_dtype
14070        // lattice (int+float -> float64) — the object bucket is ONLY for the
14071        // cross-family mix.
14072        assert_eq!(
14073            infer_dtype(&[Scalar::Bool(true), Scalar::Bool(false)]).expect("dtype should infer"),
14074            DType::Bool
14075        );
14076        assert_eq!(
14077            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]).expect("dtype should infer"),
14078            DType::Float64
14079        );
14080    }
14081
14082    // ── Scalar missingness methods ─────────────────────────────────────
14083
14084    #[test]
14085    fn is_null_detects_explicit_nulls() {
14086        assert!(Scalar::Null(NullKind::Null).is_null());
14087        assert!(Scalar::Null(NullKind::NaN).is_null());
14088        assert!(!Scalar::Int64(42).is_null());
14089        assert!(!Scalar::Float64(f64::NAN).is_null());
14090    }
14091
14092    #[test]
14093    fn is_na_matches_is_missing() {
14094        let vals = vec![
14095            Scalar::Null(NullKind::Null),
14096            Scalar::Float64(f64::NAN),
14097            Scalar::Int64(0),
14098            Scalar::Bool(false),
14099        ];
14100        for v in &vals {
14101            assert_eq!(v.is_na(), v.is_missing());
14102        }
14103    }
14104
14105    #[test]
14106    fn coalesce_picks_first_non_missing() {
14107        let null = Scalar::Null(NullKind::Null);
14108        let fill = Scalar::Int64(99);
14109        assert_eq!(null.coalesce(&fill), fill);
14110        assert_eq!(fill.coalesce(&null), fill);
14111    }
14112
14113    // ── Missingness utilities ──────────────────────────────────────────
14114
14115    #[test]
14116    fn isna_notna_complement() {
14117        let vals = vec![
14118            Scalar::Int64(1),
14119            Scalar::Null(NullKind::Null),
14120            Scalar::Float64(f64::NAN),
14121            Scalar::Float64(3.0),
14122        ];
14123        let na = super::isna(&vals);
14124        let not = super::notna(&vals);
14125        assert_eq!(na, vec![false, true, true, false]);
14126        for (a, b) in na.iter().zip(not.iter()) {
14127            assert_ne!(a, b);
14128        }
14129    }
14130
14131    #[test]
14132    fn count_na_counts_missing() {
14133        let vals = vec![
14134            Scalar::Int64(1),
14135            Scalar::Null(NullKind::Null),
14136            Scalar::Float64(f64::NAN),
14137        ];
14138        assert_eq!(super::count_na(&vals), 2);
14139    }
14140
14141    #[test]
14142    fn fill_na_replaces_missing() {
14143        let vals = vec![
14144            Scalar::Int64(1),
14145            Scalar::Null(NullKind::Null),
14146            Scalar::Float64(f64::NAN),
14147            Scalar::Int64(4),
14148        ];
14149        let filled = super::fill_na(&vals, &Scalar::Int64(0));
14150        assert_eq!(filled[0], Scalar::Int64(1));
14151        assert_eq!(filled[1], Scalar::Int64(0));
14152        assert_eq!(filled[2], Scalar::Int64(0));
14153        assert_eq!(filled[3], Scalar::Int64(4));
14154    }
14155
14156    #[test]
14157    fn dropna_removes_missing() {
14158        let vals = vec![
14159            Scalar::Int64(1),
14160            Scalar::Null(NullKind::Null),
14161            Scalar::Int64(3),
14162            Scalar::Float64(f64::NAN),
14163        ];
14164        let kept = super::dropna(&vals);
14165        assert_eq!(kept.len(), 2);
14166        assert_eq!(kept[0], Scalar::Int64(1));
14167        assert_eq!(kept[1], Scalar::Int64(3));
14168    }
14169
14170    #[test]
14171    fn null_helpers_match_scalar_oracle_imt0c() {
14172        // Differential vs independent scalar null-helper oracle
14173        // (br-frankenpandas-imt0c). Seeded LCG, no mocks.
14174        fn next(seed: &mut u64) -> u64 {
14175            *seed = seed
14176                .wrapping_mul(3202034522624059733)
14177                .wrapping_add(4354685564936845319);
14178            *seed
14179        }
14180
14181        fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
14182            let expected_missing = values.iter().filter(|value| value.is_missing()).count();
14183            let expected_dropped = values
14184                .iter()
14185                .filter(|value| !value.is_missing())
14186                .cloned()
14187                .collect::<Vec<_>>();
14188            let expected_filled = values
14189                .iter()
14190                .map(|value| {
14191                    if value.is_missing() {
14192                        fill.clone()
14193                    } else {
14194                        value.clone()
14195                    }
14196                })
14197                .collect::<Vec<_>>();
14198
14199            assert_eq!(
14200                super::count_na(values),
14201                expected_missing,
14202                "case={case}: count_na mismatch for {values:?}"
14203            );
14204
14205            let dropped = super::dropna(values);
14206            assert_eq!(
14207                dropped.len(),
14208                expected_dropped.len(),
14209                "case={case}: dropna length mismatch for {values:?}"
14210            );
14211            for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
14212            {
14213                assert!(
14214                    actual.semantic_eq(expected),
14215                    "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
14216                );
14217            }
14218
14219            let filled = super::fill_na(values, fill);
14220            assert_eq!(
14221                filled.len(),
14222                expected_filled.len(),
14223                "case={case}: fill_na length mismatch for {values:?}"
14224            );
14225            for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
14226                assert!(
14227                    actual.semantic_eq(expected),
14228                    "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
14229                );
14230            }
14231        }
14232
14233        let all_missing = [
14234            Scalar::Null(NullKind::Null),
14235            Scalar::Null(NullKind::NaN),
14236            Scalar::Float64(f64::NAN),
14237            Scalar::Timedelta64(i64::MIN),
14238        ];
14239        assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
14240
14241        let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
14242        for case in 0..260 {
14243            let len = (next(&mut seed) % 83 + 1) as usize;
14244            let mut values = Vec::with_capacity(len);
14245            for pos in 0..len {
14246                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14247                values.push(match next(&mut seed) % 11 {
14248                    0 => Scalar::Null(NullKind::Null),
14249                    1 => Scalar::Null(NullKind::NaN),
14250                    2 => Scalar::Float64(f64::NAN),
14251                    3 => Scalar::Timedelta64(i64::MIN),
14252                    4 => Scalar::Bool(raw & 1 == 0),
14253                    5 => Scalar::Int64(raw),
14254                    6 => Scalar::Float64(raw as f64 / 37.0),
14255                    7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
14256                    8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
14257                    9 => Scalar::Utf8(String::new()),
14258                    _ => Scalar::Timedelta64(raw),
14259                });
14260            }
14261
14262            let fill = match case % 5 {
14263                0 => Scalar::Bool(true),
14264                1 => Scalar::Int64(-777),
14265                2 => Scalar::Float64(12.5),
14266                3 => Scalar::Utf8("filled".into()),
14267                _ => Scalar::Timedelta64(123_456),
14268            };
14269            assert_null_helpers(case, &values, &fill);
14270        }
14271    }
14272
14273    // ── Nanops ─────────────────────────────────────────────────────────
14274
14275    #[test]
14276    fn nansum_skips_nulls() {
14277        let vals = vec![
14278            Scalar::Float64(1.0),
14279            Scalar::Null(NullKind::Null),
14280            Scalar::Float64(2.0),
14281            Scalar::Float64(f64::NAN),
14282            Scalar::Int64(7),
14283        ];
14284        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
14285    }
14286
14287    #[test]
14288    fn nansum_empty_returns_zero() {
14289        assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
14290    }
14291
14292    #[test]
14293    fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
14294        // Differential vs independent sum/mean oracles
14295        // (br-frankenpandas-1xmi7). Seeded LCG, no mocks.
14296        fn next(seed: &mut u64) -> u64 {
14297            *seed = seed
14298                .wrapping_mul(6364136223846793005)
14299                .wrapping_add(1442695040888963407);
14300            *seed
14301        }
14302
14303        fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
14304            let mut sum = 0.0;
14305            let mut count = 0usize;
14306            for value in values {
14307                if value.is_missing() {
14308                    continue;
14309                }
14310                if let Ok(value) = value.to_f64() {
14311                    sum += value;
14312                    count += 1;
14313                }
14314            }
14315            let mean = if count == 0 {
14316                Scalar::Null(NullKind::NaN)
14317            } else {
14318                Scalar::Float64(sum / count as f64)
14319            };
14320            (Scalar::Float64(sum), mean)
14321        }
14322
14323        fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
14324            let mut sum = 0_i128;
14325            let mut count = 0_i128;
14326            for value in values {
14327                if let Scalar::Timedelta64(ns) = value
14328                    && !value.is_missing()
14329                {
14330                    sum += i128::from(*ns);
14331                    count += 1;
14332                }
14333            }
14334            if count == 0 {
14335                return (Scalar::Timedelta64(0), Scalar::Timedelta64(Timedelta::NAT));
14336            }
14337            // br-frankenpandas-opz27: this reference oracle used to clamp, which
14338            // is the exact behaviour the production path was just fixed away
14339            // from. Keeping the clamp here would leave the oracle blessing a
14340            // contradicted rule (it only ever agreed because these inputs do
14341            // not overflow). Mirror the representable-range contract instead.
14342            (
14343                super::timedelta_ns_to_scalar(sum),
14344                super::timedelta_ns_to_scalar(sum / count),
14345            )
14346        }
14347
14348        fn assert_sum_mean(
14349            case: usize,
14350            family: &str,
14351            values: &[Scalar],
14352            expected_sum: Scalar,
14353            expected_mean: Scalar,
14354        ) {
14355            let actual_sum = super::nansum(values);
14356            let actual_mean = super::nanmean(values);
14357            assert!(
14358                actual_sum.semantic_eq(&expected_sum),
14359                "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
14360            );
14361            assert!(
14362                actual_mean.semantic_eq(&expected_mean),
14363                "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
14364            );
14365        }
14366
14367        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
14368        let (sum, mean) = expected_numeric(&all_missing);
14369        assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
14370
14371        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
14372        let (sum, mean) = expected_timedelta(&td_all_missing);
14373        assert_sum_mean(
14374            usize::MAX - 1,
14375            "timedelta_all_missing",
14376            &td_all_missing,
14377            sum,
14378            mean,
14379        );
14380
14381        let mut seed = 0x511d_ed5a_7a11_1a55_u64;
14382        for case in 0..260 {
14383            let len = (next(&mut seed) % 89 + 1) as usize;
14384
14385            let mut numeric = Vec::with_capacity(len);
14386            numeric.push(Scalar::Int64(case as i64 - 130));
14387            for _ in 1..len {
14388                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14389                numeric.push(match next(&mut seed) % 8 {
14390                    0 => Scalar::Null(NullKind::Null),
14391                    1 => Scalar::Null(NullKind::NaN),
14392                    2 => Scalar::Float64(f64::NAN),
14393                    3 => Scalar::Bool(raw & 1 == 0),
14394                    4 => Scalar::Int64(raw % 257),
14395                    5 => Scalar::Float64(raw as f64 / 67.0),
14396                    6 => Scalar::Float64(0.0),
14397                    _ => Scalar::Float64(-0.0),
14398                });
14399            }
14400            let (sum, mean) = expected_numeric(&numeric);
14401            assert_sum_mean(case, "numeric", &numeric, sum, mean);
14402
14403            let mut timedeltas = Vec::with_capacity(len);
14404            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
14405            for _ in 1..len {
14406                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14407                timedeltas.push(match next(&mut seed) % 7 {
14408                    0 => Scalar::Null(NullKind::Null),
14409                    1 => Scalar::Timedelta64(i64::MIN),
14410                    _ => Scalar::Timedelta64(raw),
14411                });
14412            }
14413            let (sum, mean) = expected_timedelta(&timedeltas);
14414            assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
14415        }
14416    }
14417
14418    #[test]
14419    fn nannunique_merges_negative_zero_and_zero() {
14420        let vals = vec![
14421            Scalar::Float64(-0.0),
14422            Scalar::Float64(0.0),
14423            Scalar::Float64(1.0),
14424        ];
14425        assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
14426    }
14427
14428    #[test]
14429    fn nannunique_matches_scalar_bucket_oracle_elvbg() {
14430        // Differential vs independent scalar unique-bucket oracle
14431        // (br-frankenpandas-elvbg). Seeded LCG, no mocks.
14432        fn next(seed: &mut u64) -> u64 {
14433            *seed = seed
14434                .wrapping_mul(2862933555777941757)
14435                .wrapping_add(3037000493);
14436            *seed
14437        }
14438
14439        fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
14440            match (left, right) {
14441                (Scalar::Float64(left), Scalar::Float64(right)) => {
14442                    let left = if *left == 0.0 { 0.0 } else { *left };
14443                    let right = if *right == 0.0 { 0.0 } else { *right };
14444                    left.to_bits() == right.to_bits()
14445                }
14446                _ => left == right,
14447            }
14448        }
14449
14450        fn expected_nunique(values: &[Scalar]) -> i64 {
14451            let mut seen = Vec::<Scalar>::new();
14452            for value in values {
14453                if value.is_missing() {
14454                    continue;
14455                }
14456                if !seen.iter().any(|existing| same_bucket(existing, value)) {
14457                    seen.push(value.clone());
14458                }
14459            }
14460            seen.len() as i64
14461        }
14462
14463        fn assert_nannunique(case: usize, values: &[Scalar]) {
14464            assert_eq!(
14465                super::nannunique(values),
14466                Scalar::Int64(expected_nunique(values)),
14467                "case={case}: nannunique mismatch for {values:?}"
14468            );
14469        }
14470
14471        assert_nannunique(
14472            usize::MAX,
14473            &[
14474                Scalar::Float64(-0.0),
14475                Scalar::Float64(0.0),
14476                Scalar::Float64(f64::NAN),
14477                Scalar::Null(NullKind::Null),
14478                Scalar::Timedelta64(i64::MIN),
14479            ],
14480        );
14481
14482        let mut seed = 0x0e1b_60d0_b5e7_u64;
14483        for case in 0..320 {
14484            let len = (next(&mut seed) % 97 + 1) as usize;
14485            let mut values = Vec::with_capacity(len);
14486            for pos in 0..len {
14487                let raw = (next(&mut seed) % 1_001) as i64 - 500;
14488                values.push(match next(&mut seed) % 11 {
14489                    0 => Scalar::Null(NullKind::Null),
14490                    1 => Scalar::Null(NullKind::NaN),
14491                    2 => Scalar::Float64(f64::NAN),
14492                    3 => Scalar::Bool(raw & 1 == 0),
14493                    4 => Scalar::Int64(raw % 37),
14494                    5 => Scalar::Float64(raw as f64 / 19.0),
14495                    6 => Scalar::Float64(0.0),
14496                    7 => Scalar::Float64(-0.0),
14497                    8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
14498                    9 => Scalar::Utf8(String::new()),
14499                    _ => Scalar::Timedelta64(raw % 41),
14500                });
14501            }
14502            assert_nannunique(case, &values);
14503        }
14504    }
14505
14506    #[test]
14507    fn nanmean_basic() {
14508        let vals = vec![
14509            Scalar::Float64(2.0),
14510            Scalar::Null(NullKind::Null),
14511            Scalar::Float64(4.0),
14512        ];
14513        assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
14514    }
14515
14516    #[test]
14517    fn nanmean_all_null_returns_nan() {
14518        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
14519        assert!(super::nanmean(&vals).is_missing());
14520    }
14521
14522    #[test]
14523    fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
14524        // Per br-frankenpandas-620mj: pandas td_series.sum()/mean() return
14525        // Timedelta64, not Float64(0.0). Was silently zero before because
14526        // collect_finite drops Timedelta64 (to_f64 errors).
14527        let one_hour = 3_600 * 1_000_000_000_i64;
14528        let vals = vec![
14529            Scalar::Timedelta64(one_hour),
14530            Scalar::Timedelta64(2 * one_hour),
14531            Scalar::Timedelta64(3 * one_hour),
14532        ];
14533        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
14534        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
14535    }
14536
14537    #[test]
14538    fn nansum_nanmean_timedelta64_skips_nat_620mj() {
14539        let one_hour = 3_600 * 1_000_000_000_i64;
14540        let vals = vec![
14541            Scalar::Timedelta64(Timedelta::NAT),
14542            Scalar::Timedelta64(one_hour),
14543            Scalar::Timedelta64(3 * one_hour),
14544            Scalar::Timedelta64(Timedelta::NAT),
14545        ];
14546        // NAT is missing → skipped. Sum: 1h+3h=4h; mean: 2h.
14547        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
14548        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
14549    }
14550
14551    /// br-frankenpandas-opz27: the Timedelta reduction surface used to narrow
14552    /// its exact i128 accumulator with `clamp(i64::MIN, i64::MAX)`, which
14553    /// fabricated a finite Timedelta.max on positive overflow. Live pandas
14554    /// 2.2.3 raises `ValueError: overflow in timedelta operation` here; FP
14555    /// surfaces NaT per the lgyy8 convention. A clamping implementation
14556    /// returns `Timedelta64(i64::MAX)` and fails this.
14557    #[test]
14558    fn nansum_timedelta_overflow_is_nat_not_fabricated_max_opz27() {
14559        let vals = vec![Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MAX)];
14560        let got = super::nansum(&vals);
14561        assert!(
14562            got.is_missing(),
14563            "overflowing sum must be missing, got {got:?}"
14564        );
14565        assert_eq!(got, Scalar::Timedelta64(Timedelta::NAT));
14566        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
14567    }
14568
14569    /// The negative direction used to reach NaT only *by accident*, because
14570    /// `Timedelta::NAT == i64::MIN` is exactly the clamp's lower bound — and
14571    /// that bound is off by one against the true minimum (`i64::MIN + 1`).
14572    /// Pin both the sentinel and the boundary so the accident becomes a rule.
14573    #[test]
14574    fn nansum_timedelta_negative_overflow_is_nat_opz27() {
14575        let min_repr = i64::MIN + 1; // Timedelta.min; i64::MIN is the NaT sentinel
14576        let vals = vec![Scalar::Timedelta64(min_repr), Scalar::Timedelta64(min_repr)];
14577        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(Timedelta::NAT));
14578
14579        // Exactly the most-negative representable total stays a real value and
14580        // must NOT collapse into the sentinel one nanosecond above it.
14581        let exact = vec![Scalar::Timedelta64(min_repr + 1), Scalar::Timedelta64(-1)];
14582        let got = super::nansum(&exact);
14583        assert_eq!(got, Scalar::Timedelta64(min_repr));
14584        assert!(!got.is_missing(), "Timedelta.min is representable, not NaT");
14585    }
14586
14587    /// pandas 2.2.3: `Series([Timedelta.min, Timedelta.max]).max() - .min()`
14588    /// raises OverflowError. FP used `saturating_sub`, fabricating
14589    /// Timedelta.max as a plausible range.
14590    #[test]
14591    fn nanptp_timedelta_overflow_is_nat_opz27() {
14592        let vals = vec![
14593            Scalar::Timedelta64(i64::MIN + 1),
14594            Scalar::Timedelta64(i64::MAX),
14595        ];
14596        let got = super::nanptp(&vals);
14597        assert!(
14598            got.is_missing(),
14599            "unrepresentable range must be NaT, got {got:?}"
14600        );
14601        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
14602
14603        // A representable range is still exact to the nanosecond (the reason
14604        // this path avoids f64 at all).
14605        let hour = 3_600 * 1_000_000_000_i64;
14606        let ok = vec![Scalar::Timedelta64(hour), Scalar::Timedelta64(4 * hour)];
14607        assert_eq!(super::nanptp(&ok), Scalar::Timedelta64(3 * hour));
14608    }
14609
14610    /// The load-bearing cumsum case: accumulation stays exact in i128, so only
14611    /// the *unrepresentable* index goes NaT and a later index that returns to
14612    /// range emits its true value. A clamping implementation pins `running` at
14613    /// i64::MAX and can never produce the final value, so it fails this test.
14614    #[test]
14615    fn nancumsum_timedelta_overflow_recovers_exact_value_opz27() {
14616        let vals = vec![
14617            Scalar::Timedelta64(i64::MAX),
14618            Scalar::Timedelta64(i64::MAX), // true total 2*i64::MAX: unrepresentable
14619            Scalar::Timedelta64(i64::MIN + 1), // back in range: total == i64::MAX
14620        ];
14621        let out = super::nancumsum(&vals);
14622        assert_eq!(out.len(), 3);
14623        assert_eq!(out[0], Scalar::Timedelta64(i64::MAX));
14624        assert!(
14625            out[1].is_missing(),
14626            "overflowed index must be NaT, got {:?}",
14627            out[1]
14628        );
14629        assert_eq!(
14630            out[2],
14631            Scalar::Timedelta64(i64::MAX),
14632            "exact i128 accumulation must recover; a clamped running sum cannot"
14633        );
14634    }
14635
14636    /// Non-overflowing cumsum is unchanged bit-for-bit, and input NaT still
14637    /// passes through without advancing the running total.
14638    #[test]
14639    fn nancumsum_timedelta_exact_path_unchanged_opz27() {
14640        let sec = 1_000_000_000_i64;
14641        let vals = vec![
14642            Scalar::Timedelta64(sec),
14643            Scalar::Timedelta64(Timedelta::NAT),
14644            Scalar::Timedelta64(2 * sec),
14645        ];
14646        let out = super::nancumsum(&vals);
14647        assert_eq!(out[0], Scalar::Timedelta64(sec));
14648        assert!(out[1].is_missing());
14649        assert_eq!(out[2], Scalar::Timedelta64(3 * sec));
14650    }
14651
14652    const DAY_NS: i64 = 86_400 * 1_000_000_000;
14653    /// 2020-01-01T00:00:00Z in epoch nanoseconds.
14654    const DT_2020: i64 = 1_577_836_800_000_000_000;
14655
14656    /// br-frankenpandas-axhhk: every one of these returned `Null(NaN)` (or
14657    /// `None`) before the Datetime64 arms existed, because `Datetime64::to_f64()`
14658    /// errors and each reduction fell through to the f64 catch-all. Expectations
14659    /// are the live pandas 2.2.3 answers for
14660    /// `Series([2020-01-01, +60d, +31d])`:
14661    ///   min 2020-01-01 · max 2020-03-01 · ptp Timedelta 60 days
14662    ///   argmin 0 · argmax 1 · cummax/cummin Timestamps
14663    #[test]
14664    fn datetime64_ordering_reductions_match_pandas_axhhk() {
14665        let d = Scalar::Datetime64;
14666        let vals = vec![
14667            d(DT_2020),
14668            d(DT_2020 + 60 * DAY_NS),
14669            d(DT_2020 + 31 * DAY_NS),
14670        ];
14671
14672        assert_eq!(super::nanmin(&vals), d(DT_2020));
14673        assert_eq!(super::nanmax(&vals), d(DT_2020 + 60 * DAY_NS));
14674        assert_eq!(super::nanargmin(&vals), Some(0));
14675        assert_eq!(super::nanargmax(&vals), Some(1));
14676
14677        // ptp of two INSTANTS is a DURATION: Timedelta64, not Datetime64.
14678        let span = super::nanptp(&vals);
14679        assert_eq!(span, Scalar::Timedelta64(60 * DAY_NS));
14680        assert_eq!(span.dtype(), DType::Timedelta64);
14681
14682        assert_eq!(
14683            super::nancummax(&vals),
14684            vec![
14685                d(DT_2020),
14686                d(DT_2020 + 60 * DAY_NS),
14687                d(DT_2020 + 60 * DAY_NS)
14688            ]
14689        );
14690        assert_eq!(
14691            super::nancummin(&vals),
14692            vec![d(DT_2020), d(DT_2020), d(DT_2020)]
14693        );
14694    }
14695
14696    /// The size-dependence is the part that made this bug quiet, so pin it
14697    /// explicitly rather than only asserting the headline. A ONE-element
14698    /// datetime slice was always correct (the `(None, _)` arm seeds `min`
14699    /// before any comparison runs); TWO elements hit the catch-all and
14700    /// returned NaN. A regression that drops the Datetime64 arm would still
14701    /// pass a single-element test.
14702    #[test]
14703    fn datetime64_min_max_size_dependence_pinned_axhhk() {
14704        let d = Scalar::Datetime64;
14705        let one = vec![d(DT_2020)];
14706        assert_eq!(super::nanmin(&one), d(DT_2020));
14707        assert_eq!(super::nanmax(&one), d(DT_2020));
14708
14709        let two = vec![d(DT_2020 + DAY_NS), d(DT_2020)];
14710        let got_min = super::nanmin(&two);
14711        assert!(
14712            !got_min.is_missing(),
14713            "2-element datetime min must not be missing, got {got_min:?}"
14714        );
14715        assert_eq!(got_min, d(DT_2020));
14716        assert_eq!(super::nanmax(&two), d(DT_2020 + DAY_NS));
14717    }
14718
14719    /// NaT still skips, and a datetime span too large for i64 surfaces NaT via
14720    /// the shared opz27 narrowing rather than a fabricated extreme.
14721    #[test]
14722    fn datetime64_reductions_skip_nat_and_guard_span_overflow_axhhk() {
14723        let d = Scalar::Datetime64;
14724        let with_nat = vec![
14725            d(Timestamp::NAT),
14726            d(DT_2020 + 31 * DAY_NS),
14727            d(DT_2020),
14728            d(Timestamp::NAT),
14729        ];
14730        assert_eq!(super::nanmin(&with_nat), d(DT_2020));
14731        assert_eq!(super::nanmax(&with_nat), d(DT_2020 + 31 * DAY_NS));
14732        assert_eq!(super::nanptp(&with_nat), Scalar::Timedelta64(31 * DAY_NS));
14733        // argmin/argmax report positions in the ORIGINAL slice, NaT skipped.
14734        assert_eq!(super::nanargmin(&with_nat), Some(2));
14735        assert_eq!(super::nanargmax(&with_nat), Some(1));
14736
14737        // Span exceeding i64 ns: NaT, never a fabricated Timedelta.max.
14738        let huge = vec![d(i64::MIN + 1), d(i64::MAX)];
14739        let span = super::nanptp(&huge);
14740        assert!(span.is_missing(), "unrepresentable span must be NaT");
14741        assert_ne!(span, Scalar::Timedelta64(i64::MAX));
14742    }
14743
14744    /// br-frankenpandas-adv58: mean/median/quantile returned `Null(NaN)` for
14745    /// datetime input. Expectations are the live pandas 2.2.3 answers for
14746    /// `Series([2020-01-01, +60d, +31d])`, which at day granularity pandas
14747    /// computes exactly:
14748    ///   mean 2020-01-31T08:00 · median 2020-02-01 · q0.5 2020-02-01
14749    ///   q0.25 2020-01-16T12:00
14750    #[test]
14751    fn datetime64_averaging_reductions_match_pandas_adv58() {
14752        let d = Scalar::Datetime64;
14753        let vals = vec![
14754            d(DT_2020),
14755            d(DT_2020 + 60 * DAY_NS),
14756            d(DT_2020 + 31 * DAY_NS),
14757        ];
14758        // 1580457600e9 / 1580515200e9 / 1579176000e9, straight from the probe.
14759        assert_eq!(super::nanmean(&vals), d(1_580_457_600_000_000_000));
14760        assert_eq!(super::nanmedian(&vals), d(1_580_515_200_000_000_000));
14761        assert_eq!(super::nanquantile(&vals, 0.5), d(1_580_515_200_000_000_000));
14762        assert_eq!(
14763            super::nanquantile(&vals, 0.25),
14764            d(1_579_176_000_000_000_000)
14765        );
14766    }
14767
14768    /// The even-count rounding rule, probed at 1 ns granularity where pandas is
14769    /// exact. It is TRUNCATION TOWARD ZERO — plain Rust integer division.
14770    /// `floor` would give -1 for [-1,0]; ties-to-even would give 2 for [1,2].
14771    /// Both are refuted by these cases, so this test discriminates against the
14772    /// two rounding rules a reimplementation is most likely to pick.
14773    #[test]
14774    fn datetime64_mean_median_round_toward_zero_adv58() {
14775        let d = Scalar::Datetime64;
14776        for (a, b, want) in [
14777            (0_i64, 1_i64, 0_i64),
14778            (0, 3, 1),
14779            (1, 2, 1),
14780            (-1, 0, 0),
14781            (-3, 0, -1),
14782            (-2, -1, -1),
14783            (0, 2, 1),
14784            (-2, 0, -1),
14785        ] {
14786            let vals = vec![d(a), d(b)];
14787            assert_eq!(
14788                super::nanmean(&vals),
14789                d(want),
14790                "mean of [{a}, {b}] should be {want}"
14791            );
14792            assert_eq!(
14793                super::nanmedian(&vals),
14794                d(want),
14795                "median of [{a}, {b}] should be {want}"
14796            );
14797        }
14798    }
14799
14800    /// NaT is skipped, and an all-NaT datetime input stays in the Datetime
14801    /// family rather than degrading to a numeric NaN.
14802    #[test]
14803    fn datetime64_averaging_skips_nat_adv58() {
14804        let d = Scalar::Datetime64;
14805        let vals = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14806        // pandas: mean == median == 2020-01-02, count 2.
14807        assert_eq!(super::nanmean(&vals), d(DT_2020 + DAY_NS));
14808        assert_eq!(super::nanmedian(&vals), d(DT_2020 + DAY_NS));
14809
14810        let all_nat = vec![d(Timestamp::NAT), d(Timestamp::NAT)];
14811        let got = super::nanmean(&all_nat);
14812        assert!(
14813            got.is_missing(),
14814            "all-NaT mean must be missing, got {got:?}"
14815        );
14816        assert_eq!(
14817            got.dtype(),
14818            DType::datetime64_naive(),
14819            "must stay Datetime64"
14820        );
14821    }
14822
14823    /// FP is EXACT here and pandas is not: pandas routes datetime
14824    /// mean/median/quantile through f64, so at 2020-era magnitudes (~1.58e18,
14825    /// f64 ULP 256 ns) it snaps to a 256 ns grid — it returns B+0 for the mean
14826    /// of the CONSTANT series [B+1, B+1], and for an odd-count median it can
14827    /// return a Timestamp that is not even one of the inputs. FP keeps the
14828    /// exact i128 treatment its Timedelta sibling already had. DISC-019.
14829    #[test]
14830    fn datetime64_averaging_is_exact_where_pandas_snaps_adv58() {
14831        let d = Scalar::Datetime64;
14832
14833        // Constant series: the answer is unambiguous; pandas still loses it.
14834        let constant = vec![d(DT_2020 + 1), d(DT_2020 + 1)];
14835        assert_eq!(super::nanmean(&constant), d(DT_2020 + 1));
14836        assert_eq!(super::nanmedian(&constant), d(DT_2020 + 1));
14837
14838        // Odd-count median is a SELECTION: the result must be an input value.
14839        let odd = vec![d(DT_2020), d(DT_2020 + 129), d(DT_2020 + 258)];
14840        let med = super::nanmedian(&odd);
14841        assert_eq!(med, d(DT_2020 + 129));
14842        assert!(
14843            odd.contains(&med),
14844            "odd-count median must be one of the inputs; pandas returns B+256, which is not"
14845        );
14846    }
14847
14848    /// br-frankenpandas-40ujm: datetime std returned `Null(NaN)`; pandas 2.2.3
14849    /// returns a Timedelta. Every value below is the probed oracle answer for
14850    /// `Series([2020-01-01, +60d, +31d])`, in raw ns:
14851    ///   ddof=1 (default) 2592479955563784   ddof=0 2116751019841492
14852    ///   ddof=2           3666320313338702   ddof=3 NaT (n - ddof <= 0)
14853    /// pandas truncates the sqrt toward zero (ddof=0 is 2116751019841492.8).
14854    #[test]
14855    fn datetime64_std_matches_pandas_ddof_variants_40ujm() {
14856        let d = Scalar::Datetime64;
14857        let vals = vec![
14858            d(DT_2020),
14859            d(DT_2020 + 60 * DAY_NS),
14860            d(DT_2020 + 31 * DAY_NS),
14861        ];
14862        // Dispersion of instants is a DURATION: Timedelta64, not Datetime64.
14863        let s1 = super::nanstd(&vals, 1);
14864        assert_eq!(s1, Scalar::Timedelta64(2_592_479_955_563_784));
14865        assert_eq!(s1.dtype(), DType::Timedelta64);
14866        assert_eq!(
14867            super::nanstd(&vals, 0),
14868            Scalar::Timedelta64(2_116_751_019_841_492)
14869        );
14870        assert_eq!(
14871            super::nanstd(&vals, 2),
14872            Scalar::Timedelta64(3_666_320_313_338_702)
14873        );
14874        // n - ddof <= 0 => NaT, matching pandas.
14875        assert!(super::nanstd(&vals, 3).is_missing());
14876    }
14877
14878    /// pandas returns the SAME std for a Datetime64 series and a Timedelta64
14879    /// series built from identical ns. That equivalence is the whole basis for
14880    /// routing both families through one computation, so pin it directly.
14881    #[test]
14882    fn datetime64_std_equals_timedelta64_std_on_same_ns_40ujm() {
14883        let offsets = [0_i64, 60 * DAY_NS, 31 * DAY_NS];
14884        let dt: Vec<Scalar> = offsets.iter().map(|o| Scalar::Datetime64(*o)).collect();
14885        let td: Vec<Scalar> = offsets.iter().map(|o| Scalar::Timedelta64(*o)).collect();
14886        assert_eq!(super::nanstd(&dt, 1), super::nanstd(&td, 1));
14887        assert_eq!(
14888            super::nanstd(&dt, 1),
14889            Scalar::Timedelta64(2_592_479_955_563_784)
14890        );
14891    }
14892
14893    /// NaT skips (a 3-element series with one NaT must equal the 2-element
14894    /// series without it), a single element gives NaT at the default ddof, and
14895    /// var/sem stay REFUSED for datetimes because pandas raises on them.
14896    #[test]
14897    fn datetime64_std_skips_nat_and_var_sem_stay_unsupported_40ujm() {
14898        let d = Scalar::Datetime64;
14899        let with_nat = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14900        let without = vec![d(DT_2020), d(DT_2020 + 2 * DAY_NS)];
14901        // pandas: both are Timedelta 1 days 09:56:28.051789035.
14902        assert_eq!(super::nanstd(&with_nat, 1), super::nanstd(&without, 1));
14903        assert_eq!(
14904            super::nanstd(&with_nat, 1),
14905            Scalar::Timedelta64(122_188_051_789_035)
14906        );
14907
14908        // n=1 with ddof=1 -> NaT, as pandas returns.
14909        assert!(super::nanstd(&[d(DT_2020)], 1).is_missing());
14910        assert!(super::nanstd(&[d(Timestamp::NAT)], 1).is_missing());
14911
14912        // pandas RAISES TypeError for datetime64 var and sem. FP must not
14913        // invent a value: these stay on the Timedelta-only gate and report
14914        // missing. A regression that widened them would return a number here.
14915        let vals = vec![d(DT_2020), d(DT_2020 + 60 * DAY_NS)];
14916        assert!(super::nanvar(&vals, 1).is_missing());
14917        assert!(super::nansem(&vals, 1).is_missing());
14918    }
14919
14920    /// br-frankenpandas-qoabs: Period is the THIRD dtype whose `to_f64()`
14921    /// errors, so min/max fell into the f64 catch-all and returned
14922    /// `Null(NaN)`. pandas 2.2.3 on `Series([2020-01, 2020-03, 2020-02], M)`
14923    /// gives min 2020-01 and max 2020-03; ordinals are 600/601/602.
14924    #[test]
14925    fn period_min_max_match_pandas_qoabs() {
14926        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14927        let vals = vec![p(600), p(602), p(601)];
14928        assert_eq!(super::nanmin(&vals), p(600));
14929        assert_eq!(super::nanmax(&vals), p(602));
14930
14931        // Size-dependence, exactly as in axhhk: ONE element always worked via
14932        // the `(None, _)` seed, so a test with a single value would pass even
14933        // with no Period arm at all. Assert both sizes.
14934        assert_eq!(super::nanmin(&[p(600)]), p(600));
14935        let two = vec![p(602), p(600)];
14936        assert!(!super::nanmin(&two).is_missing());
14937        assert_eq!(super::nanmin(&two), p(600));
14938        assert_eq!(super::nanmax(&two), p(602));
14939    }
14940
14941    /// A Period whose ordinal is the NaT sentinel is missing and skipped, and
14942    /// an all-missing Period input reports missing rather than a value.
14943    #[test]
14944    fn period_min_max_skip_nat_qoabs() {
14945        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14946        let nat = Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly));
14947        let vals = vec![nat.clone(), p(602), p(600), nat.clone()];
14948        assert_eq!(super::nanmin(&vals), p(600));
14949        assert_eq!(super::nanmax(&vals), p(602));
14950        assert!(super::nanmin(&[nat.clone(), nat]).is_missing());
14951    }
14952
14953    /// MIXED FREQ must not be ordered. pandas refuses it outright
14954    /// (`IncompatibleFrequency: Input has different freq=D from Period(freq=M)`),
14955    /// so FP reports missing rather than inventing an order. This is the test
14956    /// that discriminates: an implementation comparing raw ordinals would
14957    /// happily return a value here, because monthly 2020-01 is ordinal 600
14958    /// while daily 2020-01-05 is 18267 — it would call the daily period later.
14959    #[test]
14960    fn period_mixed_freq_is_not_ordered_qoabs() {
14961        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
14962        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
14963        let vals = vec![month.clone(), day.clone()];
14964        let got_min = super::nanmin(&vals);
14965        assert!(
14966            got_min.is_missing(),
14967            "mixed-freq Period min must not be ordered, got {got_min:?}"
14968        );
14969        assert_ne!(
14970            got_min, day,
14971            "must not rank the daily period by raw ordinal"
14972        );
14973        assert!(super::nanmax(&vals).is_missing());
14974    }
14975
14976    /// br-frankenpandas-d7zjp: the rest of the Period reduction family, which
14977    /// qoabs deferred because a `fn(i64) -> Scalar` constructor cannot carry a
14978    /// freq. Expectations are the probed pandas 2.2.3 answers for
14979    /// `Series([2020-01, 2020-03, 2020-02], freq=M)` (ordinals 600/601/602):
14980    ///   median 2020-02 · quantile(0.5) 2020-02 · idxmin 0 · idxmax 1
14981    ///   cummax ends 2020-03 · cummin ends 2020-01
14982    #[test]
14983    fn period_full_reduction_family_matches_pandas_d7zjp() {
14984        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14985        let vals = vec![p(600), p(602), p(601)];
14986
14987        assert_eq!(super::nanmedian(&vals), p(601));
14988        assert_eq!(super::nanquantile(&vals, 0.5), p(601));
14989        assert_eq!(super::nanargmin(&vals), Some(0));
14990        assert_eq!(super::nanargmax(&vals), Some(1));
14991        assert_eq!(super::nancummax(&vals), vec![p(600), p(602), p(602)]);
14992        assert_eq!(super::nancummin(&vals), vec![p(600), p(600), p(600)]);
14993    }
14994
14995    /// Even-count Period median picks by TRUNCATION TOWARD ZERO on the ordinal,
14996    /// the same rule the datetime family uses. Probed: pandas gives 2020-02 for
14997    /// [2020-01, 2020-04] (ordinals 600/603, midpoint 601.5) and 2020-01 for
14998    /// [2020-01, 2020-02] (600/601, midpoint 600.5).
14999    #[test]
15000    fn period_even_count_median_truncates_toward_zero_d7zjp() {
15001        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
15002        assert_eq!(super::nanmedian(&[p(600), p(603)]), p(601));
15003        assert_eq!(super::nanmedian(&[p(600), p(601)]), p(600));
15004    }
15005
15006    /// MIXED FREQ must not be ordered by ANY of these, for the same reason as
15007    /// in qoabs: pandas raises IncompatibleFrequency, and raw ordinals are not
15008    /// comparable across freqs (monthly 2020-01 is 600, daily 2020-01-05 is
15009    /// 18267). The family enum encodes the freq, so a mixed input is simply not
15010    /// one family and never reaches a typed arm.
15011    #[test]
15012    fn period_mixed_freq_not_ordered_by_any_reduction_d7zjp() {
15013        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
15014        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
15015        let vals = vec![month, day];
15016
15017        assert!(super::nanmedian(&vals).is_missing());
15018        assert!(super::nanquantile(&vals, 0.5).is_missing());
15019        assert_eq!(super::nanargmin(&vals), None);
15020        assert_eq!(super::nanargmax(&vals), None);
15021        // The cumulative ops must not emit an ordered Period column either.
15022        assert!(super::nancummax(&vals).iter().all(Scalar::is_missing));
15023        assert!(super::nancummin(&vals).iter().all(Scalar::is_missing));
15024    }
15025
15026    /// pandas RAISES for Period mean/sum/std/var ("does not support reduction",
15027    /// and for mean explicitly "the meaning is ambiguous"). FP must not invent
15028    /// values. `std` is the trap here: the family enum puts Period one line
15029    /// away from the Datetime64 arm that 40ujm deliberately widened, so this
15030    /// asserts the guard holds.
15031    #[test]
15032    fn period_unsupported_reductions_stay_missing_d7zjp() {
15033        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
15034        let vals = vec![p(600), p(602), p(601)];
15035        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
15036        assert!(super::nanvar(&vals, 1).is_missing(), "pandas raises var");
15037        assert!(super::nansem(&vals, 1).is_missing(), "pandas raises sem");
15038        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
15039    }
15040
15041    /// br-frankenpandas-srqdo: Interval is the FOURTH dtype whose `to_f64()`
15042    /// errors, so min/max fell into the f64 catch-all and returned
15043    /// `Null(NaN)`. pandas 2.2.3 on `IntervalArray.from_tuples([(0,1),(4,5),(2,3)])`
15044    /// gives min `(0, 1]` and max `(4, 5]`.
15045    #[test]
15046    fn interval_min_max_match_pandas_srqdo() {
15047        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15048        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
15049        assert_eq!(super::nanmin(&vals), iv(0.0, 1.0));
15050        assert_eq!(super::nanmax(&vals), iv(4.0, 5.0));
15051
15052        // Size-dependence, per the axhhk lesson: ONE element always worked via
15053        // the `(None, _)` seed, so a single-value test passes even with no arm.
15054        assert_eq!(super::nanmin(&[iv(2.0, 3.0)]), iv(2.0, 3.0));
15055        let two = vec![iv(4.0, 5.0), iv(0.0, 1.0)];
15056        assert!(!super::nanmin(&two).is_missing());
15057        assert_eq!(super::nanmin(&two), iv(0.0, 1.0));
15058        assert_eq!(super::nanmax(&two), iv(4.0, 5.0));
15059    }
15060
15061    /// The tie-on-left case, which is what discriminates a correct (left, right)
15062    /// comparison from one that only looks at `left`. pandas: Interval(0,2) <
15063    /// Interval(0,5) is True. An implementation comparing left alone keeps
15064    /// whichever came first and returns the wrong element here.
15065    #[test]
15066    fn interval_ties_on_left_order_by_right_srqdo() {
15067        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15068        let vals = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
15069        assert_eq!(super::nanmin(&vals), iv(0.0, 2.0));
15070        assert_eq!(super::nanmax(&vals), iv(0.0, 9.0));
15071    }
15072
15073    /// A NaN bound has no pandas counterpart — `IntervalArray` refuses to build
15074    /// one ("missing values must be missing in the same location both left and
15075    /// right") — so it must report missing rather than impose an arbitrary
15076    /// order. Critically this must NOT panic: the obvious
15077    /// `partial_cmp().unwrap()` implementation would.
15078    #[test]
15079    fn interval_nan_bound_is_not_ordered_srqdo() {
15080        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15081        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
15082        assert!(super::nanmin(&vals).is_missing());
15083        assert!(super::nanmax(&vals).is_missing());
15084    }
15085
15086    /// pandas RAISES or NotImplementedErrors every other reduction for
15087    /// Interval (median/mean/sum/std/quantile/cummax). FP must not invent
15088    /// values, so they stay missing.
15089    #[test]
15090    fn interval_unsupported_reductions_stay_missing_srqdo() {
15091        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15092        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
15093        assert!(super::nanmedian(&vals).is_missing(), "pandas raises median");
15094        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
15095        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
15096        assert!(
15097            super::nanquantile(&vals, 0.5).is_missing(),
15098            "pandas raises quantile"
15099        );
15100        assert!(
15101            super::nancummax(&vals).iter().all(Scalar::is_missing),
15102            "pandas NotImplementedErrors cummax"
15103        );
15104    }
15105
15106    /// br-frankenpandas-2h9dm: Interval argmin/argmax returned None, because
15107    /// `Interval::to_f64()` errors and the f64 fallback skipped every element.
15108    /// All four expectations are probed pandas 2.2.3 `idxmin`/`idxmax`.
15109    #[test]
15110    fn interval_argmin_argmax_match_pandas_2h9dm() {
15111        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15112        // pandas: idxmin 1, idxmax 0
15113        let vals = vec![iv(4.0, 5.0), iv(0.0, 1.0), iv(2.0, 3.0)];
15114        assert_eq!(super::nanargmin(&vals), Some(1));
15115        assert_eq!(super::nanargmax(&vals), Some(0));
15116
15117        // Left-tie resolves by RIGHT. pandas: idxmin 1, idxmax 2. An
15118        // implementation comparing only `left` keeps index 0 for both.
15119        let tie = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
15120        assert_eq!(super::nanargmin(&tie), Some(1));
15121        assert_eq!(super::nanargmax(&tie), Some(2));
15122    }
15123
15124    /// Duplicated extreme returns the FIRST occurrence (pandas idxmin 0 on
15125    /// [(0,1),(0,1),(9,9)]), and missing entries are skipped while the returned
15126    /// index stays a position in the ORIGINAL slice (pandas idxmin 2 / idxmax 0
15127    /// on [(4,5), None, (0,1)]).
15128    #[test]
15129    fn interval_arg_first_occurrence_and_missing_2h9dm() {
15130        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15131        let dup = vec![iv(0.0, 1.0), iv(0.0, 1.0), iv(9.0, 9.0)];
15132        assert_eq!(
15133            super::nanargmin(&dup),
15134            Some(0),
15135            "first occurrence, not last"
15136        );
15137        assert_eq!(super::nanargmax(&dup), Some(2));
15138
15139        let with_missing = vec![iv(4.0, 5.0), Scalar::Null(NullKind::NaN), iv(0.0, 1.0)];
15140        assert_eq!(super::nanargmin(&with_missing), Some(2));
15141        assert_eq!(super::nanargmax(&with_missing), Some(0));
15142    }
15143
15144    /// A NaN bound is not orderable, so decline rather than return an arbitrary
15145    /// index — and critically, do not panic the way `partial_cmp().unwrap()`
15146    /// would.
15147    #[test]
15148    fn interval_arg_nan_bound_declines_2h9dm() {
15149        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15150        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
15151        assert_eq!(super::nanargmin(&vals), None);
15152        assert_eq!(super::nanargmax(&vals), None);
15153    }
15154
15155    /// br-frankenpandas-fyr1z-policy-carrier-f29nz: the load-bearing guarantee
15156    /// of this bead is NO DEFAULT BEHAVIOR CHANGE. Prove it rather than assert
15157    /// it: over a seeded corpus that deliberately straddles the i64 boundary
15158    /// and the NaT sentinel, every infallible helper must equal its fallible
15159    /// sibling resolved under the default `SurfaceNat` policy — which is also
15160    /// exactly what the pre-f29nz bodies computed.
15161    #[test]
15162    fn overflow_policy_carrier_preserves_default_behavior_f29nz() {
15163        // Seeded LCG, no rand dependency (see [[differential-test-coverage]]).
15164        let mut state: u64 = 0x5DEE_CE66_D125_1F00;
15165        let mut next = || {
15166            state = state
15167                .wrapping_mul(6_364_136_223_846_793_005)
15168                .wrapping_add(1_442_695_040_888_963_407);
15169            state
15170        };
15171        // Edge values first, then random ones. i64::MIN is the NaT sentinel.
15172        let mut corpus: Vec<i64> = vec![
15173            0,
15174            1,
15175            -1,
15176            2,
15177            -2,
15178            i64::MAX,
15179            i64::MIN,
15180            i64::MIN + 1,
15181            i64::MAX - 1,
15182            i64::MAX / 2,
15183            -(i64::MAX / 2),
15184        ];
15185        for _ in 0..400 {
15186            let raw = next() as i64;
15187            corpus.push(raw);
15188            corpus.push(raw / 3);
15189        }
15190
15191        let policy = super::OverflowPolicy::default();
15192        assert_eq!(
15193            policy,
15194            super::OverflowPolicy::SurfaceNat,
15195            "default must not move"
15196        );
15197
15198        for &a in &corpus {
15199            for &b in &corpus {
15200                // Timedelta::add / sub / mul_scalar
15201                assert_eq!(
15202                    Timedelta::add(a, b),
15203                    policy
15204                        .resolve(Timedelta::try_add(a, b), Timedelta::NAT)
15205                        .expect("SurfaceNat never errors"),
15206                    "add({a}, {b}) diverged"
15207                );
15208                assert_eq!(
15209                    Timedelta::sub(a, b),
15210                    policy
15211                        .resolve(Timedelta::try_sub(a, b), Timedelta::NAT)
15212                        .expect("SurfaceNat never errors"),
15213                    "sub({a}, {b}) diverged"
15214                );
15215                assert_eq!(
15216                    Timedelta::mul_scalar(a, b),
15217                    policy
15218                        .resolve(Timedelta::try_mul_scalar(a, b), Timedelta::NAT)
15219                        .expect("SurfaceNat never errors"),
15220                    "mul_scalar({a}, {b}) diverged"
15221                );
15222
15223                // Timestamp::{add,sub}_timedelta / sub_timestamp — including tz,
15224                // since overflow deliberately drops it.
15225                let ts = Timestamp::from_nanos(a);
15226                assert_eq!(
15227                    ts.add_timedelta(b),
15228                    ts.try_add_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
15229                    "add_timedelta({a}, {b}) diverged"
15230                );
15231                assert_eq!(
15232                    ts.sub_timedelta(b),
15233                    ts.try_sub_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
15234                    "sub_timedelta({a}, {b}) diverged"
15235                );
15236                let other = Timestamp::from_nanos(b);
15237                assert_eq!(
15238                    ts.sub_timestamp(&other),
15239                    ts.try_sub_timestamp(&other).unwrap_or(Timedelta::NAT),
15240                    "sub_timestamp({a}, {b}) diverged"
15241                );
15242            }
15243        }
15244    }
15245
15246    /// The carrier must actually CARRY something: `Strict` propagates the
15247    /// overflow with the right op name and the pandas error class probed from
15248    /// live 2.2.3. Without this, `resolve` could ignore its policy and the
15249    /// equivalence test above would still pass.
15250    #[test]
15251    fn overflow_policy_strict_reports_op_and_pandas_class_f29nz() {
15252        use super::{OverflowPolicy, PandasTemporalError};
15253
15254        let strict = OverflowPolicy::Strict;
15255
15256        // pd.Timedelta.max + pd.Timedelta('1ns') -> OverflowError
15257        let err = strict
15258            .resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT)
15259            .expect_err("must surface under Strict");
15260        assert_eq!(err.op, "Timedelta::add");
15261        assert_eq!(err.pandas_error, PandasTemporalError::Overflow);
15262
15263        // pd.Timestamp.max + pd.Timedelta('1ns') -> OutOfBoundsDatetime
15264        let ts = Timestamp::from_nanos(i64::MAX);
15265        let err = strict
15266            .resolve(ts.try_add_timedelta(1), Timestamp::nat())
15267            .expect_err("must surface under Strict");
15268        assert_eq!(err.op, "Timestamp::add_timedelta");
15269        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
15270
15271        // pd.Timestamp.min - pd.Timestamp.max -> OutOfBoundsDatetime
15272        let err = strict
15273            .resolve(
15274                Timestamp::from_nanos(i64::MIN + 1)
15275                    .try_sub_timestamp(&Timestamp::from_nanos(i64::MAX)),
15276                Timedelta::NAT,
15277            )
15278            .expect_err("must surface under Strict");
15279        assert_eq!(err.op, "Timestamp::sub_timestamp");
15280        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
15281
15282        // A NaT operand is PROPAGATION, not overflow: Strict must still be Ok.
15283        assert_eq!(
15284            strict
15285                .resolve(Timedelta::try_add(Timedelta::NAT, 1), Timedelta::NAT)
15286                .expect("NaT propagation is not an overflow"),
15287            Timedelta::NAT
15288        );
15289        // And a representable result is untouched under either policy.
15290        assert_eq!(
15291            strict
15292                .resolve(Timedelta::try_add(2, 3), Timedelta::NAT)
15293                .expect("no overflow"),
15294            5
15295        );
15296    }
15297
15298    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2: the scalar divide-by-zero
15299    /// row, and the boundary a STRICT arm must not cross. All four expectations
15300    /// probed on live pandas 2.2.3:
15301    ///   SCALAR  Timedelta('1s') // 0   -> ZeroDivisionError
15302    ///   SCALAR  Timedelta('1s') / 0    -> ZeroDivisionError
15303    ///   VECTOR  Series([Td]) // 0      -> NaT   (must NOT raise)
15304    ///   VECTOR  Series([Td]) / 0       -> NaT   (must NOT raise)
15305    #[test]
15306    fn timedelta_scalar_zero_division_taxonomy_t7ht2() {
15307        use super::{OverflowPolicy, PandasTemporalError};
15308
15309        // The fallible scalar sibling reports ZeroDivision with its op name.
15310        let err = Timedelta::try_div_scalar(1_000_000_000, 0)
15311            .expect_err("scalar divide-by-zero must be reportable");
15312        assert_eq!(err.op, "Timedelta::div_scalar");
15313        assert_eq!(err.pandas_error, PandasTemporalError::ZeroDivision);
15314
15315        // THE BOUNDARY: the infallible helper the vectorized callers use keeps
15316        // returning NaT. If this ever starts raising, FrankenPandas diverges
15317        // from pandas on a row where it is currently bit-for-bit correct.
15318        assert_eq!(Timedelta::div_scalar(1_000_000_000, 0), Timedelta::NAT);
15319        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 0), Timedelta::NAT);
15320
15321        // Under the default policy the failure resolves back to NaT, so
15322        // nothing changes for existing callers.
15323        assert_eq!(
15324            OverflowPolicy::default()
15325                .resolve(Timedelta::try_div_scalar(1_000_000_000, 0), Timedelta::NAT)
15326                .expect("SurfaceNat never errors"),
15327            Timedelta::NAT
15328        );
15329
15330        // Non-zero divisors are untouched, including the floor-division
15331        // adjustment for mixed signs (-7 // 2 == -4, not -3).
15332        assert_eq!(Timedelta::try_div_scalar(-7, 2), Ok(-4));
15333        assert_eq!(Timedelta::div_scalar(-7, 2), -4);
15334        assert_eq!(Timedelta::try_div_scalar(7, 2), Ok(3));
15335        // NaT propagates as Ok, not as a failure.
15336        assert_eq!(
15337            Timedelta::try_div_scalar(Timedelta::NAT, 2),
15338            Ok(Timedelta::NAT)
15339        );
15340    }
15341
15342    /// The constructor row of the taxonomy. Probed:
15343    /// `pd.Timedelta(float('inf'), 's')` raises OutOfBoundsTimedelta —
15344    /// specifically NOT a bare OverflowError, which is why the mapping is
15345    /// explicit rather than assumed.
15346    #[test]
15347    fn timedelta_constructor_error_maps_to_out_of_bounds_t7ht2() {
15348        use super::{PandasTemporalError, TimedeltaError};
15349
15350        assert_eq!(
15351            TimedeltaError::Overflow.pandas_error(),
15352            Some(PandasTemporalError::OutOfBoundsTimedelta)
15353        );
15354        // A parse failure is not part of the arithmetic taxonomy.
15355        assert_eq!(
15356            TimedeltaError::InvalidFormat("nonsense".into()).pandas_error(),
15357            None
15358        );
15359        // And the live path still errors on a non-finite input (8v92m).
15360        assert!(Timedelta::from_unit(f64::INFINITY, "s").is_err());
15361        assert_eq!(
15362            Timedelta::from_unit(f64::INFINITY, "s")
15363                .unwrap_err()
15364                .pandas_error(),
15365            Some(PandasTemporalError::OutOfBoundsTimedelta)
15366        );
15367    }
15368
15369    /// br-frankenpandas-fyr1z-hardened-audit-vllv6: HARDENED mode adds
15370    /// observability, NEVER semantics. Every value it returns must be
15371    /// bit-for-bit what SurfaceNat returns — proven over the same seeded corpus
15372    /// the f29nz equivalence test uses, with the audit log ENABLED throughout so
15373    /// recording cannot perturb results.
15374    #[test]
15375    fn hardened_audit_values_are_bit_identical_to_surface_nat_vllv6() {
15376        use super::{OverflowPolicy, overflow_audit};
15377
15378        overflow_audit::enable();
15379        let mut state: u64 = 0x1234_5678_9ABC_DEF0;
15380        let mut next = || {
15381            state = state
15382                .wrapping_mul(6_364_136_223_846_793_005)
15383                .wrapping_add(1_442_695_040_888_963_407);
15384            state
15385        };
15386        let mut corpus: Vec<i64> = vec![
15387            0,
15388            1,
15389            -1,
15390            2,
15391            -2,
15392            i64::MAX,
15393            i64::MIN,
15394            i64::MIN + 1,
15395            i64::MAX - 1,
15396        ];
15397        for _ in 0..120 {
15398            corpus.push(next() as i64);
15399        }
15400
15401        for &a in &corpus {
15402            for &b in &corpus {
15403                for op in [
15404                    Timedelta::try_add as fn(i64, i64) -> Result<i64, super::TemporalFailure>,
15405                    Timedelta::try_sub,
15406                    Timedelta::try_mul_scalar,
15407                    Timedelta::try_div_scalar,
15408                ] {
15409                    let soft = OverflowPolicy::SurfaceNat
15410                        .resolve(op(a, b), Timedelta::NAT)
15411                        .expect("SurfaceNat never errors");
15412                    let hard = OverflowPolicy::HardenedNat
15413                        .resolve(op(a, b), Timedelta::NAT)
15414                        .expect("HardenedNat never errors");
15415                    assert_eq!(hard, soft, "HARDENED changed a value for ({a}, {b})");
15416                }
15417            }
15418        }
15419        overflow_audit::disable();
15420    }
15421
15422    /// The audit trail itself: HARDENED records the op, the pandas class it
15423    /// would have raised, the OPERANDS whose exact result left the
15424    /// representable range, and the value actually returned — deterministically
15425    /// and in order. SurfaceNat and Strict record nothing.
15426    #[test]
15427    fn hardened_audit_records_deterministic_recovery_entries_vllv6() {
15428        use super::{OverflowPolicy, PandasTemporalError, overflow_audit};
15429
15430        overflow_audit::enable();
15431        assert!(overflow_audit::is_enabled());
15432        assert!(overflow_audit::drain().is_empty(), "starts empty");
15433
15434        // Two overflows and one representable result, in a fixed order.
15435        let _ =
15436            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15437        let _ = OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(2, 3), Timedelta::NAT);
15438        let _ =
15439            OverflowPolicy::HardenedNat.resolve(Timedelta::try_div_scalar(5, 0), Timedelta::NAT);
15440
15441        let entries = overflow_audit::drain();
15442        assert_eq!(entries.len(), 2, "only the two failures are recorded");
15443
15444        assert_eq!(entries[0].op, "Timedelta::add");
15445        assert_eq!(entries[0].pandas_error, PandasTemporalError::Overflow);
15446        assert_eq!(entries[0].operands, Some((i64::MAX, 1)));
15447        assert_eq!(entries[0].recovered_as, i64::MIN);
15448
15449        assert_eq!(entries[1].op, "Timedelta::div_scalar");
15450        assert_eq!(entries[1].pandas_error, PandasTemporalError::ZeroDivision);
15451        assert_eq!(entries[1].operands, Some((5, 0)));
15452
15453        // Draining leaves recording enabled and empty.
15454        assert!(overflow_audit::drain().is_empty());
15455
15456        // The OTHER policies must stay silent — the audit is HARDENED-only.
15457        let _ = OverflowPolicy::SurfaceNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15458        let _ = OverflowPolicy::Strict.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15459        assert!(
15460            overflow_audit::drain().is_empty(),
15461            "SurfaceNat/Strict must not write to the audit trail"
15462        );
15463
15464        overflow_audit::disable();
15465        assert!(!overflow_audit::is_enabled());
15466        // Disabled: recording is a no-op and drain yields nothing.
15467        let _ =
15468            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15469        assert!(
15470            overflow_audit::drain().is_empty(),
15471            "disabled must not record"
15472        );
15473    }
15474
15475    /// br-frankenpandas-fyr1z-wrap-signoff-s4lkx.
15476    ///
15477    /// THIS TEST PINS A PANDAS QUIRK THAT WE REPRODUCE ON PURPOSE. The values
15478    /// below are NOT what a careful implementation would choose: multiplying a
15479    /// positive duration by 2 yields a NEGATIVE one. They are what live pandas
15480    /// 2.2.3 returns, because numpy int64 wraps silently, and the maintainer
15481    /// decided that STRICT means bit-for-bit observable parity with the
15482    /// incumbent INCLUDING its quirks — this being a port.
15483    ///
15484    /// So: if this test fails, do NOT "fix" the wrap. Either pandas changed, or
15485    /// someone routed a non-STRICT caller into the STRICT path. Both need
15486    /// investigating rather than correcting the arithmetic.
15487    ///
15488    /// Oracle values, probed directly:
15489    ///   Series([Timedelta.max]) * 2            -> -2 ns
15490    ///   Series([max, max]).cumsum()            -> [max, -2]
15491    ///   Series([max, max, max]).cumsum()       -> [max, -2, max - 2]
15492    #[test]
15493    fn strict_reproduces_pandas_silent_timedelta_wrap_s4lkx() {
15494        use super::{OverflowPolicy, nancumsum_with_policy};
15495
15496        // Series * int -- pandas returns -2, i.e. i64::MAX.wrapping_mul(2).
15497        assert_eq!(
15498            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::Strict),
15499            -2,
15500            "STRICT must reproduce pandas' wrap, not repair it"
15501        );
15502
15503        // cumsum -- and the THIRD element is the important one: it proves the
15504        // accumulator keeps wrapping rather than sticking at a bound.
15505        let max = Scalar::Timedelta64(i64::MAX);
15506        let out = nancumsum_with_policy(
15507            &[max.clone(), max.clone(), max.clone()],
15508            OverflowPolicy::Strict,
15509        );
15510        assert_eq!(
15511            out,
15512            vec![
15513                Scalar::Timedelta64(i64::MAX),
15514                Scalar::Timedelta64(-2),
15515                Scalar::Timedelta64(i64::MAX - 2),
15516            ],
15517            "STRICT cumsum must reproduce pandas' int64 wraparound exactly"
15518        );
15519
15520        // NaT still propagates; the wrap is about overflow, not missingness.
15521        assert_eq!(
15522            Timedelta::mul_scalar_with_policy(Timedelta::NAT, 2, OverflowPolicy::Strict),
15523            Timedelta::NAT
15524        );
15525    }
15526
15527    /// The other half of the s4lkx decision, and the reason reproducing a
15528    /// fail-open quirk is acceptable at all: it is reachable ONLY when a caller
15529    /// explicitly asks for STRICT incumbent parity. Every other policy — and
15530    /// crucially the DEFAULT — still refuses to fabricate a plausible value,
15531    /// keeping the br-frankenpandas-lgyy8 guarantee intact.
15532    #[test]
15533    fn non_strict_policies_still_refuse_to_wrap_s4lkx() {
15534        use super::{OverflowPolicy, nancumsum_with_policy, overflow_audit};
15535
15536        for policy in [OverflowPolicy::SurfaceNat, OverflowPolicy::HardenedNat] {
15537            assert_eq!(
15538                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
15539                Timedelta::NAT,
15540                "{policy:?} must NOT wrap"
15541            );
15542            assert_ne!(
15543                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
15544                -2,
15545                "{policy:?} must not reproduce the pandas quirk"
15546            );
15547        }
15548        // The bare default is SurfaceNat, so an unconfigured caller is safe.
15549        assert_eq!(
15550            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::default()),
15551            Timedelta::NAT
15552        );
15553
15554        // cumsum likewise keeps the exact-i128 / NaT behaviour off STRICT.
15555        let max = Scalar::Timedelta64(i64::MAX);
15556        let soft = nancumsum_with_policy(&[max.clone(), max.clone()], OverflowPolicy::SurfaceNat);
15557        assert!(soft[1].is_missing(), "non-STRICT cumsum must NaT, not wrap");
15558        assert_eq!(soft, super::nancumsum(&[max.clone(), max]));
15559
15560        // HARDENED wrapping would be doubly wrong: it would fabricate a value
15561        // AND leave nothing in the audit trail to explain it.
15562        overflow_audit::enable();
15563        let _ = Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::HardenedNat);
15564        assert_eq!(
15565            overflow_audit::drain().len(),
15566            1,
15567            "HARDENED must record the recovery it performed"
15568        );
15569        overflow_audit::disable();
15570    }
15571
15572    /// Mixed Datetime64 + another dtype must NOT take the typed arm — it falls
15573    /// back exactly as before, so this fix cannot change cross-type behavior.
15574    #[test]
15575    fn datetime64_mixed_input_still_falls_back_axhhk() {
15576        let vals = vec![Scalar::Datetime64(DT_2020), Scalar::Int64(5)];
15577        // `is_datetime_input` is false here, so both keep their PRE-EXISTING
15578        // cross-type behavior, which differs between the two by construction:
15579        //   nanmin  — the catch-all compares via to_f64(); the Datetime64 side
15580        //             errors, so it bails to Null(NaN).
15581        //   nanptp  — its f64 loop SKIPS values whose to_f64() errors, so the
15582        //             datetime is dropped and the range is taken over the lone
15583        //             Int64 => Float64(0.0). Same shape as the documented
15584        //             mixed-timedelta fallback in ..._620mj (which yields 5.0).
15585        // Neither is changed by this bead; pinning both stops the new typed arm
15586        // from silently widening to mixed input later.
15587        assert!(super::nanmin(&vals).is_missing());
15588        assert_eq!(super::nanptp(&vals), Scalar::Float64(0.0));
15589    }
15590
15591    #[test]
15592    fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
15593        // Mixed Timedelta64 + other type bails out of the Timedelta path
15594        // and uses Float64 collect_finite (which drops Timedelta).
15595        // Preserves existing cross-type behavior (effectively ignores TD).
15596        let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
15597        // Int64(5) makes it through to_f64 → 5.0; Timedelta is dropped.
15598        assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
15599    }
15600
15601    #[test]
15602    fn nancount_counts_non_missing() {
15603        let vals = vec![
15604            Scalar::Int64(1),
15605            Scalar::Null(NullKind::Null),
15606            Scalar::Float64(3.0),
15607        ];
15608        assert_eq!(super::nancount(&vals), Scalar::Int64(2));
15609    }
15610
15611    #[test]
15612    fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
15613        // Differential vs scalar truthiness/count oracle
15614        // (br-frankenpandas-zr2qg). Seeded LCG, no mocks.
15615        fn next(seed: &mut u64) -> u64 {
15616            *seed = seed
15617                .wrapping_mul(6364136223846793005)
15618                .wrapping_add(1442695040888963407);
15619            *seed
15620        }
15621
15622        fn truthy(value: &Scalar) -> Option<bool> {
15623            if value.is_missing() {
15624                return None;
15625            }
15626            match value {
15627                Scalar::Bool(value) => Some(*value),
15628                Scalar::Int64(value) => Some(*value != 0),
15629                Scalar::Float64(value) => Some(*value != 0.0),
15630                Scalar::Utf8(value) => Some(!value.is_empty()),
15631                Scalar::Timedelta64(value) => Some(*value != 0),
15632                _ => None,
15633            }
15634        }
15635
15636        fn assert_nanops(case: usize, values: &[Scalar]) {
15637            let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
15638            let expected_any = truth_values.iter().any(|value| *value);
15639            let expected_all = !truth_values.iter().any(|value| !*value);
15640            let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
15641
15642            assert_eq!(
15643                super::nanany(values),
15644                Scalar::Bool(expected_any),
15645                "case={case}: nanany mismatch for {values:?}"
15646            );
15647            assert_eq!(
15648                super::nanall(values),
15649                Scalar::Bool(expected_all),
15650                "case={case}: nanall mismatch for {values:?}"
15651            );
15652            assert_eq!(
15653                super::nancount(values),
15654                Scalar::Int64(expected_count),
15655                "case={case}: nancount mismatch for {values:?}"
15656            );
15657        }
15658
15659        assert_nanops(
15660            usize::MAX,
15661            &[
15662                Scalar::Null(NullKind::Null),
15663                Scalar::Null(NullKind::NaN),
15664                Scalar::Float64(f64::NAN),
15665                Scalar::Timedelta64(i64::MIN),
15666            ],
15667        );
15668
15669        let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
15670        for case in 0..320 {
15671            let len = (next(&mut seed) % 89 + 1) as usize;
15672            let mut values = Vec::with_capacity(len);
15673            for pos in 0..len {
15674                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
15675                let value = match next(&mut seed) % 12 {
15676                    0 => Scalar::Null(NullKind::Null),
15677                    1 => Scalar::Null(NullKind::NaN),
15678                    2 => Scalar::Float64(f64::NAN),
15679                    3 => Scalar::Bool(raw & 1 == 0),
15680                    4 => Scalar::Bool(false),
15681                    5 => Scalar::Int64(raw % 17),
15682                    6 => Scalar::Int64(0),
15683                    7 => Scalar::Float64(raw as f64 / 23.0),
15684                    8 => Scalar::Float64(0.0),
15685                    9 => Scalar::Utf8(if raw & 1 == 0 {
15686                        String::new()
15687                    } else {
15688                        format!("nanops_{case}_{pos}")
15689                    }),
15690                    10 => Scalar::Timedelta64(raw),
15691                    _ => Scalar::Timedelta64(0),
15692                };
15693                values.push(value);
15694            }
15695            assert_nanops(case, &values);
15696        }
15697    }
15698
15699    #[test]
15700    fn nanmin_basic() {
15701        let vals = vec![
15702            Scalar::Float64(5.0),
15703            Scalar::Null(NullKind::Null),
15704            Scalar::Float64(2.0),
15705            Scalar::Float64(8.0),
15706        ];
15707        assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
15708    }
15709
15710    #[test]
15711    fn nanmax_basic() {
15712        let vals = vec![
15713            Scalar::Float64(5.0),
15714            Scalar::Float64(f64::NAN),
15715            Scalar::Float64(8.0),
15716        ];
15717        assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
15718    }
15719
15720    #[test]
15721    fn nanmin_nanmax_empty_returns_nan() {
15722        assert!(super::nanmin(&[]).is_missing());
15723        assert!(super::nanmax(&[]).is_missing());
15724    }
15725
15726    #[test]
15727    fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
15728        // Differential vs independent same-family comparator oracle
15729        // (br-frankenpandas-vj7ds). Seeded LCG, no mocks.
15730        fn next(seed: &mut u64) -> u64 {
15731            *seed = seed
15732                .wrapping_mul(6364136223846793005)
15733                .wrapping_add(1442695040888963407);
15734            *seed
15735        }
15736
15737        fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
15738            match (left, right) {
15739                (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
15740                (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
15741                (Scalar::Float64(left), Scalar::Float64(right)) => {
15742                    left.partial_cmp(right).expect("finite floats")
15743                }
15744                (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
15745                (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
15746                // `assert_minmax` verifies that every present value belongs
15747                // to one generated family before it invokes this comparator.
15748                _ => std::cmp::Ordering::Equal,
15749            }
15750        }
15751
15752        fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
15753            let present = values
15754                .iter()
15755                .filter(|value| !value.is_missing())
15756                .cloned()
15757                .collect::<Vec<_>>();
15758            let actual_min = super::nanmin(values);
15759            let actual_max = super::nanmax(values);
15760            if present.is_empty() {
15761                assert!(
15762                    actual_min.is_missing(),
15763                    "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
15764                );
15765                assert!(
15766                    actual_max.is_missing(),
15767                    "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
15768                );
15769                return;
15770            }
15771
15772            let is_expected_family = |value: &Scalar| match family {
15773                "int" => matches!(value, Scalar::Int64(_)),
15774                "float" => matches!(value, Scalar::Float64(_)),
15775                "bool" => matches!(value, Scalar::Bool(_)),
15776                "utf8" => matches!(value, Scalar::Utf8(_)),
15777                "timedelta" => matches!(value, Scalar::Timedelta64(_)),
15778                _ => false,
15779            };
15780            assert!(
15781                present.iter().all(is_expected_family),
15782                "case={case} family={family}: mixed family escaped generator: {values:?}"
15783            );
15784
15785            let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
15786            let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
15787            assert!(
15788                actual_min.semantic_eq(expected_min.expect("min")),
15789                "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
15790                expected_min.expect("min")
15791            );
15792            assert!(
15793                actual_max.semantic_eq(expected_max.expect("max")),
15794                "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
15795                expected_max.expect("max")
15796            );
15797        }
15798
15799        let all_missing = [
15800            Scalar::Null(NullKind::Null),
15801            Scalar::Null(NullKind::NaN),
15802            Scalar::Float64(f64::NAN),
15803            Scalar::Timedelta64(i64::MIN),
15804        ];
15805        assert_minmax(usize::MAX, "all_missing", &all_missing);
15806
15807        let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
15808        for case in 0..240 {
15809            let len = (next(&mut seed) % 73 + 1) as usize;
15810
15811            let mut ints = Vec::with_capacity(len);
15812            ints.push(Scalar::Int64(case as i64 - 120));
15813            for _ in 1..len {
15814                let raw = (next(&mut seed) % 1_001) as i64 - 500;
15815                ints.push(match next(&mut seed) % 6 {
15816                    0 => Scalar::Null(NullKind::Null),
15817                    1 => Scalar::Null(NullKind::NaN),
15818                    _ => Scalar::Int64(raw),
15819                });
15820            }
15821            assert_minmax(case, "int", &ints);
15822
15823            let mut floats = Vec::with_capacity(len);
15824            floats.push(Scalar::Float64(case as f64 / 11.0));
15825            for _ in 1..len {
15826                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15827                floats.push(match next(&mut seed) % 8 {
15828                    0 | 1 => Scalar::Float64(f64::NAN),
15829                    2 => Scalar::Float64(f64::INFINITY),
15830                    3 => Scalar::Float64(f64::NEG_INFINITY),
15831                    4 => Scalar::Float64(0.0),
15832                    5 => Scalar::Float64(-0.0),
15833                    _ => Scalar::Float64(raw as f64 / 41.0),
15834                });
15835            }
15836            assert_minmax(case, "float", &floats);
15837
15838            let mut bools = Vec::with_capacity(len);
15839            bools.push(Scalar::Bool(case & 1 == 0));
15840            for _ in 1..len {
15841                bools.push(match next(&mut seed) % 5 {
15842                    0 => Scalar::Null(NullKind::Null),
15843                    1 => Scalar::Null(NullKind::NaN),
15844                    raw => Scalar::Bool(raw & 1 == 0),
15845                });
15846            }
15847            assert_minmax(case, "bool", &bools);
15848
15849            let mut utf8 = Vec::with_capacity(len);
15850            utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
15851            for pos in 1..len {
15852                utf8.push(match next(&mut seed) % 7 {
15853                    0 => Scalar::Null(NullKind::Null),
15854                    1 => Scalar::Null(NullKind::NaN),
15855                    raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
15856                });
15857            }
15858            assert_minmax(case, "utf8", &utf8);
15859
15860            let mut timedeltas = Vec::with_capacity(len);
15861            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15862            for _ in 1..len {
15863                let raw = (next(&mut seed) % 1_003) as i64 - 501;
15864                timedeltas.push(match next(&mut seed) % 7 {
15865                    0 => Scalar::Null(NullKind::Null),
15866                    1 => Scalar::Timedelta64(i64::MIN),
15867                    _ => Scalar::Timedelta64(raw),
15868                });
15869            }
15870            assert_minmax(case, "timedelta", &timedeltas);
15871        }
15872    }
15873
15874    #[test]
15875    fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
15876        let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
15877        assert!(super::nanmin(&vals).is_missing());
15878        assert!(super::nanmax(&vals).is_missing());
15879
15880        let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
15881        assert!(super::nanmin(&vals2).is_missing());
15882        assert!(super::nanmax(&vals2).is_missing());
15883    }
15884
15885    #[test]
15886    fn nanmin_nanmax_compatible_numeric_types_ok() {
15887        let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
15888        assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
15889        assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
15890    }
15891
15892    #[test]
15893    fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
15894        // Per br-frankenpandas-yic5m: nanmin/nanmax on Timedelta64 returns
15895        // the smallest/largest Timedelta64 — was silently NaN before
15896        // because Timedelta64.to_f64() errors and the catch-all swallowed it.
15897        let one_hour = 3_600 * 1_000_000_000_i64;
15898        let vals = vec![
15899            Scalar::Timedelta64(3 * one_hour),
15900            Scalar::Timedelta64(one_hour),
15901            Scalar::Timedelta64(2 * one_hour),
15902        ];
15903        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15904        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
15905    }
15906
15907    #[test]
15908    fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
15909        let one_hour = 3_600 * 1_000_000_000_i64;
15910        let vals = vec![
15911            Scalar::Timedelta64(Timedelta::NAT),
15912            Scalar::Timedelta64(one_hour),
15913            Scalar::Timedelta64(2 * one_hour),
15914            Scalar::Timedelta64(Timedelta::NAT),
15915        ];
15916        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15917        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
15918    }
15919
15920    #[test]
15921    fn nanmedian_odd_count() {
15922        let vals = vec![
15923            Scalar::Float64(3.0),
15924            Scalar::Null(NullKind::Null),
15925            Scalar::Float64(1.0),
15926            Scalar::Float64(2.0),
15927        ];
15928        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
15929    }
15930
15931    #[test]
15932    fn nanmedian_even_count() {
15933        let vals = vec![
15934            Scalar::Float64(1.0),
15935            Scalar::Float64(3.0),
15936            Scalar::Float64(2.0),
15937            Scalar::Float64(4.0),
15938        ];
15939        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
15940    }
15941
15942    #[test]
15943    fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
15944        // Differential vs independent sort-based median oracles
15945        // (br-frankenpandas-oabhi). Seeded LCG, no mocks.
15946        fn next(seed: &mut u64) -> u64 {
15947            *seed = seed
15948                .wrapping_mul(6364136223846793005)
15949                .wrapping_add(1442695040888963407);
15950            *seed
15951        }
15952
15953        fn expected_numeric(values: &[Scalar]) -> Scalar {
15954            let mut finite = values
15955                .iter()
15956                .filter(|value| !value.is_missing())
15957                .filter_map(|value| value.to_f64().ok())
15958                .filter(|value| !value.is_nan())
15959                .collect::<Vec<_>>();
15960            if finite.is_empty() {
15961                return Scalar::Null(NullKind::NaN);
15962            }
15963            finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
15964            let mid = finite.len() / 2;
15965            if finite.len().is_multiple_of(2) {
15966                Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
15967            } else {
15968                Scalar::Float64(finite[mid])
15969            }
15970        }
15971
15972        fn expected_timedelta(values: &[Scalar]) -> Scalar {
15973            let mut finite = values
15974                .iter()
15975                .filter_map(|value| match value {
15976                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns),
15977                    _ => None,
15978                })
15979                .collect::<Vec<_>>();
15980            if finite.is_empty() {
15981                return Scalar::Null(NullKind::NaN);
15982            }
15983            finite.sort_unstable();
15984            let mid = finite.len() / 2;
15985            let median = if finite.len().is_multiple_of(2) {
15986                (i128::from(finite[mid - 1]) + i128::from(finite[mid])) / 2
15987            } else {
15988                i128::from(finite[mid])
15989            };
15990            Scalar::Timedelta64(median as i64)
15991        }
15992
15993        fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
15994            let actual = super::nanmedian(values);
15995            assert!(
15996                actual.semantic_eq(&expected),
15997                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
15998            );
15999        }
16000
16001        assert_median(
16002            usize::MAX,
16003            "numeric_all_missing",
16004            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
16005            Scalar::Null(NullKind::NaN),
16006        );
16007        assert_median(
16008            usize::MAX - 1,
16009            "timedelta_all_missing",
16010            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
16011            Scalar::Null(NullKind::NaN),
16012        );
16013        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
16014        assert_median(
16015            usize::MAX - 2,
16016            "timedelta_odd_median_beyond_f64_exactness",
16017            &[
16018                Scalar::Timedelta64(beyond_f64_exact_ns),
16019                Scalar::Timedelta64(beyond_f64_exact_ns + 1),
16020                Scalar::Timedelta64(beyond_f64_exact_ns + 2),
16021                Scalar::Timedelta64(Timedelta::NAT),
16022            ],
16023            Scalar::Timedelta64(beyond_f64_exact_ns + 1),
16024        );
16025
16026        let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
16027        for case in 0..220 {
16028            let len = (next(&mut seed) % 79 + 1) as usize;
16029
16030            let mut numeric = Vec::with_capacity(len);
16031            numeric.push(Scalar::Int64(case as i64 - 110));
16032            for _ in 1..len {
16033                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16034                numeric.push(match next(&mut seed) % 8 {
16035                    0 => Scalar::Null(NullKind::Null),
16036                    1 => Scalar::Null(NullKind::NaN),
16037                    2 => Scalar::Float64(f64::NAN),
16038                    3 => Scalar::Bool(raw & 1 == 0),
16039                    4 => Scalar::Int64(raw % 251),
16040                    5 => Scalar::Float64(raw as f64 / 61.0),
16041                    6 => Scalar::Float64(0.0),
16042                    _ => Scalar::Float64(-0.0),
16043                });
16044            }
16045            assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
16046
16047            let mut timedeltas = Vec::with_capacity(len);
16048            timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
16049            for _ in 1..len {
16050                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16051                timedeltas.push(match next(&mut seed) % 7 {
16052                    0 => Scalar::Null(NullKind::Null),
16053                    1 => Scalar::Timedelta64(i64::MIN),
16054                    _ => Scalar::Timedelta64(raw),
16055                });
16056            }
16057            assert_median(
16058                case,
16059                "timedelta",
16060                &timedeltas,
16061                expected_timedelta(&timedeltas),
16062            );
16063        }
16064    }
16065
16066    #[test]
16067    fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
16068        // Differential vs independent variance/std/sem oracles
16069        // (br-frankenpandas-k7apg). Seeded LCG, no mocks.
16070        fn next(seed: &mut u64) -> u64 {
16071            *seed = seed
16072                .wrapping_mul(2862933555777941757)
16073                .wrapping_add(3037000493);
16074            *seed
16075        }
16076
16077        fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
16078            values
16079                .iter()
16080                .filter(|value| !value.is_missing())
16081                .filter_map(|value| value.to_f64().ok())
16082                .collect()
16083        }
16084
16085        fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
16086            values
16087                .iter()
16088                .filter_map(|value| match value {
16089                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
16090                    _ => None,
16091                })
16092                .collect()
16093        }
16094
16095        fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
16096            if samples.len() <= ddof {
16097                return None;
16098            }
16099            let mean = samples.iter().sum::<f64>() / samples.len() as f64;
16100            let sum_sq = samples
16101                .iter()
16102                .map(|value| (value - mean).powi(2))
16103                .sum::<f64>();
16104            let var = sum_sq / (samples.len() - ddof) as f64;
16105            let std = var.sqrt();
16106            let sem = std / (samples.len() as f64).sqrt();
16107            Some((var, std, sem))
16108        }
16109
16110        fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
16111            let samples = numeric_samples(values);
16112            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
16113                let missing = Scalar::Null(NullKind::NaN);
16114                return (missing.clone(), missing.clone(), missing);
16115            };
16116            (
16117                Scalar::Float64(var),
16118                Scalar::Float64(std),
16119                Scalar::Float64(sem),
16120            )
16121        }
16122
16123        fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
16124            let samples = timedelta_samples(values);
16125            if samples.is_empty() {
16126                let missing = Scalar::Timedelta64(Timedelta::NAT);
16127                return (missing.clone(), missing.clone(), missing);
16128            }
16129            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
16130                let missing = Scalar::Timedelta64(i64::MIN);
16131                return (missing.clone(), missing.clone(), missing);
16132            };
16133            (
16134                Scalar::Timedelta64(var as i64),
16135                Scalar::Timedelta64(std as i64),
16136                Scalar::Timedelta64(sem as i64),
16137            )
16138        }
16139
16140        fn assert_reductions(
16141            case: usize,
16142            family: &str,
16143            values: &[Scalar],
16144            ddof: usize,
16145            expected: (Scalar, Scalar, Scalar),
16146        ) {
16147            let (expected_var, expected_std, expected_sem) = expected;
16148            let actual_var = super::nanvar(values, ddof);
16149            let actual_std = super::nanstd(values, ddof);
16150            let actual_sem = super::nansem(values, ddof);
16151            assert!(
16152                actual_var.semantic_eq(&expected_var),
16153                "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
16154            );
16155            assert!(
16156                actual_std.semantic_eq(&expected_std),
16157                "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
16158            );
16159            assert!(
16160                actual_sem.semantic_eq(&expected_sem),
16161                "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
16162            );
16163        }
16164
16165        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16166        assert_reductions(
16167            usize::MAX,
16168            "numeric_all_missing",
16169            &numeric_all_missing,
16170            0,
16171            expected_numeric(&numeric_all_missing, 0),
16172        );
16173
16174        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16175        assert_reductions(
16176            usize::MAX - 1,
16177            "timedelta_all_missing",
16178            &td_all_missing,
16179            0,
16180            expected_timedelta(&td_all_missing, 0),
16181        );
16182
16183        let mut seed = 0x7a11_c0de_5eed_0421_u64;
16184        for case in 0..240 {
16185            let len = (next(&mut seed) % 83 + 1) as usize;
16186            let ddof = (next(&mut seed) % 4) as usize;
16187
16188            let mut numeric = Vec::with_capacity(len);
16189            numeric.push(Scalar::Float64(case as f64 / 13.0));
16190            for _ in 1..len {
16191                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16192                numeric.push(match next(&mut seed) % 8 {
16193                    0 => Scalar::Null(NullKind::Null),
16194                    1 => Scalar::Null(NullKind::NaN),
16195                    2 => Scalar::Float64(f64::NAN),
16196                    3 => Scalar::Bool(raw & 1 == 0),
16197                    4 => Scalar::Int64(raw % 251),
16198                    5 => Scalar::Float64(raw as f64 / 73.0),
16199                    6 => Scalar::Float64(0.0),
16200                    _ => Scalar::Float64(-0.0),
16201                });
16202            }
16203            assert_reductions(
16204                case,
16205                "numeric",
16206                &numeric,
16207                ddof,
16208                expected_numeric(&numeric, ddof),
16209            );
16210
16211            let mut timedeltas = Vec::with_capacity(len);
16212            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
16213            for _ in 1..len {
16214                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16215                timedeltas.push(match next(&mut seed) % 7 {
16216                    0 => Scalar::Null(NullKind::Null),
16217                    1 => Scalar::Timedelta64(i64::MIN),
16218                    _ => Scalar::Timedelta64(raw),
16219                });
16220            }
16221            assert_reductions(
16222                case,
16223                "timedelta",
16224                &timedeltas,
16225                ddof,
16226                expected_timedelta(&timedeltas, ddof),
16227            );
16228        }
16229    }
16230
16231    #[test]
16232    fn nanvar_population() {
16233        let vals = vec![
16234            Scalar::Float64(2.0),
16235            Scalar::Float64(4.0),
16236            Scalar::Float64(4.0),
16237            Scalar::Float64(4.0),
16238            Scalar::Float64(5.0),
16239            Scalar::Float64(5.0),
16240            Scalar::Float64(7.0),
16241            Scalar::Float64(9.0),
16242        ];
16243        let var = super::nanvar(&vals, 0);
16244        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
16245        if let Scalar::Float64(v) = var {
16246            assert!((v - 4.0).abs() < 1e-10);
16247        }
16248    }
16249
16250    #[test]
16251    fn nanvar_sample_ddof1() {
16252        let vals = vec![
16253            Scalar::Float64(2.0),
16254            Scalar::Float64(4.0),
16255            Scalar::Float64(4.0),
16256            Scalar::Float64(4.0),
16257            Scalar::Float64(5.0),
16258            Scalar::Float64(5.0),
16259            Scalar::Float64(7.0),
16260            Scalar::Float64(9.0),
16261        ];
16262        let var = super::nanvar(&vals, 1);
16263        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
16264        if let Scalar::Float64(v) = var {
16265            assert!((v - 32.0 / 7.0).abs() < 1e-10);
16266        }
16267    }
16268
16269    #[test]
16270    fn nanvar_insufficient_values_returns_nan() {
16271        let vals = vec![Scalar::Float64(5.0)];
16272        assert!(super::nanvar(&vals, 1).is_missing());
16273    }
16274
16275    #[test]
16276    fn nanstd_is_sqrt_of_var() {
16277        let vals = vec![
16278            Scalar::Float64(2.0),
16279            Scalar::Float64(4.0),
16280            Scalar::Float64(4.0),
16281            Scalar::Float64(4.0),
16282            Scalar::Float64(5.0),
16283            Scalar::Float64(5.0),
16284            Scalar::Float64(7.0),
16285            Scalar::Float64(9.0),
16286        ];
16287        let std = super::nanstd(&vals, 0);
16288        assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
16289        if let Scalar::Float64(v) = std {
16290            assert!((v - 2.0).abs() < 1e-10);
16291        }
16292    }
16293
16294    #[test]
16295    fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
16296        // Per br-frankenpandas-j8ntk: pandas td_series.median() returns
16297        // Timedelta64; was silently NaN before via collect_finite.
16298        let one_hour = 3_600 * 1_000_000_000_i64;
16299        let vals = vec![
16300            Scalar::Timedelta64(one_hour),
16301            Scalar::Timedelta64(2 * one_hour),
16302            Scalar::Timedelta64(3 * one_hour),
16303        ];
16304        assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
16305    }
16306
16307    #[test]
16308    fn nanstd_timedelta64_preserves_dtype_j8ntk() {
16309        // Per br-frankenpandas-j8ntk: pandas td_series.std() returns
16310        // Timedelta64. Check Timedelta64 output and reasonable magnitude
16311        // for population std of [1h, 2h, 3h] = sqrt(2/3) * 1h.
16312        let one_hour: i64 = 3_600 * 1_000_000_000;
16313        let vals = vec![
16314            Scalar::Timedelta64(one_hour),
16315            Scalar::Timedelta64(2 * one_hour),
16316            Scalar::Timedelta64(3 * one_hour),
16317        ];
16318        let std = super::nanstd(&vals, 0);
16319        assert!(matches!(std, Scalar::Timedelta64(_)));
16320        if let Scalar::Timedelta64(ns) = std {
16321            let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
16322            assert!(
16323                (ns as f64 - expected).abs() < 1e6,
16324                "expected ~{expected} ns, got {ns}"
16325            );
16326        }
16327    }
16328
16329    #[test]
16330    fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
16331        let one_hour = 3_600 * 1_000_000_000_i64;
16332        let vals = vec![Scalar::Timedelta64(one_hour)];
16333        // ddof=1 with n=1 → underflow, returns NaT
16334        assert_eq!(super::nanstd(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
16335        assert_eq!(super::nansem(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
16336    }
16337
16338    #[test]
16339    fn nanops_with_mixed_types() {
16340        let vals = vec![
16341            Scalar::Bool(true),
16342            Scalar::Int64(3),
16343            Scalar::Float64(6.0),
16344            Scalar::Null(NullKind::Null),
16345        ];
16346        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
16347        assert_eq!(super::nancount(&vals), Scalar::Int64(3));
16348    }
16349
16350    #[test]
16351    fn nanops_all_missing_returns_identity() {
16352        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16353        assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
16354        assert!(super::nanmean(&vals).is_missing());
16355        assert!(super::nanmedian(&vals).is_missing());
16356        assert!(super::nanvar(&vals, 0).is_missing());
16357        assert!(super::nanstd(&vals, 0).is_missing());
16358    }
16359
16360    // ── Timedelta tests ────────────────────────────────────────────────
16361
16362    #[test]
16363    fn timedelta_parse_simple_units() {
16364        use super::Timedelta;
16365        assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
16366        assert_eq!(
16367            Timedelta::parse("2h").unwrap(),
16368            2 * Timedelta::NANOS_PER_HOUR
16369        );
16370        assert_eq!(
16371            Timedelta::parse("30m").unwrap(),
16372            30 * Timedelta::NANOS_PER_MIN
16373        );
16374        assert_eq!(
16375            Timedelta::parse("45s").unwrap(),
16376            45 * Timedelta::NANOS_PER_SEC
16377        );
16378        assert_eq!(
16379            Timedelta::parse("100ms").unwrap(),
16380            100 * Timedelta::NANOS_PER_MILLI
16381        );
16382        assert_eq!(
16383            Timedelta::parse("500us").unwrap(),
16384            500 * Timedelta::NANOS_PER_MICRO
16385        );
16386        assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
16387    }
16388
16389    #[test]
16390    fn timedelta_parse_zero_valued_compound() {
16391        use super::Timedelta;
16392        // Each of these is a Timedelta of zero, not a parse failure. Verified
16393        // against live pandas 2.2.3: every form below yields
16394        // `Timedelta('0 days 00:00:00')`. A guard in `parse_compound` used to
16395        // reject them all except the bare "0", which made
16396        // `to_timedelta(["10 seconds", "1 second", "0 seconds"])` raise on the
16397        // third element only.
16398        for s in [
16399            "0 seconds",
16400            "0 second",
16401            "0 sec",
16402            "0s",
16403            "0 days",
16404            "0d",
16405            "0 hours",
16406            "0.0 hours",
16407            "0 minutes",
16408            "0ms",
16409            "0us",
16410            "0ns",
16411            "0",
16412            "0 days 0 seconds",
16413        ] {
16414            assert_eq!(Timedelta::parse(s).unwrap(), 0, "parse({s:?}) should be 0");
16415        }
16416        // The sign is carried by the caller, so a negative zero is still zero.
16417        assert_eq!(Timedelta::parse("-0 seconds").unwrap(), 0);
16418        // Removing the guard must NOT admit garbage: an unknown unit and a
16419        // missing number are still rejected inside the loop.
16420        assert!(Timedelta::parse("0 fortnights").is_err());
16421        assert!(Timedelta::parse("seconds").is_err());
16422    }
16423
16424    #[test]
16425    fn timedelta_parse_compound() {
16426        use super::Timedelta;
16427        let expected = Timedelta::NANOS_PER_DAY
16428            + 2 * Timedelta::NANOS_PER_HOUR
16429            + 30 * Timedelta::NANOS_PER_MIN;
16430        assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
16431        assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
16432    }
16433
16434    #[test]
16435    fn timedelta_parse_leading_sign_spares_the_clock_part() {
16436        use super::Timedelta;
16437        const S: i64 = Timedelta::NANOS_PER_SEC;
16438        // Verified vs pandas 2.2.3 Timedelta(...).total_seconds(); the second
16439        // is how pandas prints a negative Timedelta.
16440        assert_eq!(Timedelta::parse("-1 days 02:03:04").unwrap(), -79_016 * S);
16441        assert_eq!(Timedelta::parse("-1 days +02:03:04").unwrap(), -79_016 * S);
16442        assert_eq!(
16443            Timedelta::parse("-3 days +23:59:59.5").unwrap(),
16444            -172_800 * S - S / 2
16445        );
16446        assert_eq!(Timedelta::parse("-0 days 01:00:00").unwrap(), 3_600 * S);
16447        // Without a clock part after a unit, the whole value is negated.
16448        assert_eq!(Timedelta::parse("-1d2h").unwrap(), -93_600 * S);
16449        assert_eq!(Timedelta::parse("-02:03:04").unwrap(), -7_384 * S);
16450        // A sign inside the string is pandas' "only leading negative signs".
16451        assert!(Timedelta::parse("-1 days -02:03:04").is_err());
16452        assert!(Timedelta::parse("1 days -02:00:00").is_err());
16453    }
16454
16455    #[test]
16456    fn timedelta_parse_iso8601_matches_pandas_tdiso() {
16457        use super::Timedelta;
16458        // Verified vs pandas 2.2.3 Timedelta(...).value.
16459        assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
16460        assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
16461        assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
16462        assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
16463        assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
16464        assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
16465        // pandas quirks: T ignored, M is minutes everywhere, units in any order.
16466        assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
16467        assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
16468        assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
16469        assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
16470        assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
16471        // Rejected like pandas: years, lowercase, bare P/PT.
16472        assert!(Timedelta::parse("P1Y").is_err());
16473        assert!(Timedelta::parse("p1d").is_err());
16474        assert!(Timedelta::parse("P").is_err());
16475        assert!(Timedelta::parse("PT").is_err());
16476    }
16477
16478    #[test]
16479    fn timedelta_parse_time_format() {
16480        use super::Timedelta;
16481        let expected = Timedelta::NANOS_PER_HOUR
16482            + 30 * Timedelta::NANOS_PER_MIN
16483            + 45 * Timedelta::NANOS_PER_SEC;
16484        assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
16485    }
16486
16487    #[test]
16488    fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
16489        use super::{Timedelta, TimedeltaError};
16490        let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
16491            .expect_err("non-ASCII fractional seconds must reject");
16492        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
16493    }
16494
16495    #[test]
16496    fn timedelta_parse_time_format_rejects_overflow_without_panic() {
16497        use super::{Timedelta, TimedeltaError};
16498        let err = Timedelta::parse("9223372036854775807:00")
16499            .expect_err("oversized hour component must reject");
16500        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
16501    }
16502
16503    #[test]
16504    fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
16505        // Per br-frankenpandas-zw3mg: the compound parser used a raw
16506        // `as i64` cast that silently saturated to i64::MAX when the
16507        // product of (decimal-digit f64) × unit multiplier overflows.
16508        // Use a large literal (no scientific notation — the lexer only
16509        // accepts digits, '.', '-'). 1e18 days × NANOS_PER_DAY (~8.64e13)
16510        // overflows i64.
16511        use super::{Timedelta, TimedeltaError};
16512        let huge = format!("{} days", "9".repeat(18));
16513        assert!(matches!(
16514            Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
16515            TimedeltaError::Overflow
16516        ));
16517    }
16518
16519    #[test]
16520    fn timedelta_parse_nat() {
16521        use super::Timedelta;
16522        assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
16523        assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
16524    }
16525
16526    #[test]
16527    fn timedelta_parse_negative() {
16528        use super::Timedelta;
16529        assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
16530    }
16531
16532    #[test]
16533    fn timedelta_components() {
16534        use super::Timedelta;
16535        let nanos = Timedelta::NANOS_PER_DAY
16536            + Timedelta::NANOS_PER_HOUR
16537            + Timedelta::NANOS_PER_MIN
16538            + Timedelta::NANOS_PER_SEC
16539            + Timedelta::NANOS_PER_MILLI
16540            + 2 * Timedelta::NANOS_PER_MICRO
16541            + 3;
16542        let comp = Timedelta::components(nanos);
16543        assert_eq!(comp.days, 1);
16544        assert_eq!(comp.hours, 1);
16545        assert_eq!(comp.minutes, 1);
16546        assert_eq!(comp.seconds, 1);
16547        assert_eq!(comp.milliseconds, 1);
16548        assert_eq!(comp.microseconds, 2);
16549        assert_eq!(comp.nanoseconds, 3);
16550    }
16551
16552    #[test]
16553    fn timedelta_negative_components_floor_div() {
16554        use super::Timedelta;
16555        // pandas floor-normalizes negative timedeltas: pd.Timedelta(-1,'s') has
16556        // days=-1, seconds=86399, components=(-1, 23, 59, 59, 0, 0, 0).
16557        let neg_1s = -Timedelta::NANOS_PER_SEC;
16558        assert_eq!(Timedelta::days(neg_1s), Some(-1));
16559        assert_eq!(Timedelta::seconds(neg_1s), Some(86399));
16560        assert_eq!(Timedelta::microseconds(neg_1s), Some(0));
16561        assert_eq!(Timedelta::nanoseconds(neg_1s), Some(0));
16562        let comp = Timedelta::components(neg_1s);
16563        assert_eq!(
16564            (
16565                comp.days,
16566                comp.hours,
16567                comp.minutes,
16568                comp.seconds,
16569                comp.milliseconds,
16570                comp.microseconds,
16571                comp.nanoseconds
16572            ),
16573            (-1, 23, 59, 59, 0, 0, 0)
16574        );
16575
16576        // pd.Timedelta(-86401,'s'): days=-2, seconds=86399.
16577        let neg = -86_401 * Timedelta::NANOS_PER_SEC;
16578        assert_eq!(Timedelta::days(neg), Some(-2));
16579        assert_eq!(Timedelta::seconds(neg), Some(86399));
16580    }
16581
16582    /// br-frankenpandas-timedelta-nat-days-returns-zero-406ni.
16583    ///
16584    /// All four component helpers returned `0` for `NaT`, one of them behind a
16585    /// comment asserting "pandas returns 0 for NaT.days (no error)". MEASURED,
16586    /// live pandas 2.2.3: `pd.NaT.days` is **nan**, and
16587    /// `pd.to_timedelta([1, None, -1], unit='s').dt.days` is float64
16588    /// `[0.0, nan, -1.0]`.
16589    ///
16590    /// ⚠️ `0` IS THE ONE WRONG ANSWER THAT LOOKS RIGHT. It is a legal value for
16591    /// three of these four accessors — `seconds`, `microseconds` and
16592    /// `nanoseconds` all legitimately return 0 for a whole number of days — so a
16593    /// caller cannot distinguish "midnight" from "missing" by inspecting the
16594    /// result. That is the fail-open-as-plausible-data class, and it is why the
16595    /// fix is the return TYPE and not a corrected comment.
16596    #[test]
16597    fn timedelta_components_are_missing_for_nat_not_zero_406ni() {
16598        use super::Timedelta;
16599        assert_eq!(Timedelta::days(Timedelta::NAT), None);
16600        assert_eq!(Timedelta::seconds(Timedelta::NAT), None);
16601        assert_eq!(Timedelta::microseconds(Timedelta::NAT), None);
16602        assert_eq!(Timedelta::nanoseconds(Timedelta::NAT), None);
16603
16604        // NON-VACUITY: a whole number of days legitimately answers 0 for the
16605        // three sub-day components, so `Some(0)` and `None` must be reachable
16606        // from the same accessor. A test that only checked NaT could pass
16607        // against a helper that returned `None` unconditionally.
16608        let one_day = Timedelta::NANOS_PER_DAY;
16609        assert_eq!(Timedelta::days(one_day), Some(1));
16610        assert_eq!(Timedelta::seconds(one_day), Some(0));
16611        assert_eq!(Timedelta::microseconds(one_day), Some(0));
16612        assert_eq!(Timedelta::nanoseconds(one_day), Some(0));
16613    }
16614
16615    #[test]
16616    fn timedelta_total_seconds() {
16617        use super::Timedelta;
16618        let nanos = 90_000_000_000i64; // 90 seconds
16619        assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
16620        assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
16621    }
16622
16623    #[test]
16624    fn timedelta_format_basic() {
16625        use super::Timedelta;
16626        assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
16627        assert_eq!(
16628            Timedelta::format(Timedelta::NANOS_PER_DAY),
16629            "1 days 00:00:00"
16630        );
16631        assert_eq!(
16632            Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
16633            "1 days 02:00:00"
16634        );
16635    }
16636
16637    #[test]
16638    fn timedelta_format_subsecond_matches_pandas() {
16639        use super::Timedelta;
16640        // pandas str(Timedelta) uses 6 fractional digits (microseconds) unless a
16641        // sub-microsecond (nanosecond) component is present, then 9 digits.
16642        // Verified vs live pandas 2.2.3.
16643        assert_eq!(
16644            Timedelta::format(1_500_000_000), // 1.5s
16645            "0 days 00:00:01.500000"
16646        );
16647        assert_eq!(
16648            Timedelta::format(1_000_000), // 1ms
16649            "0 days 00:00:00.001000"
16650        );
16651        assert_eq!(
16652            Timedelta::format(123_456_000), // 123456us
16653            "0 days 00:00:00.123456"
16654        );
16655        // Nanosecond component -> 9 digits.
16656        assert_eq!(
16657            Timedelta::format(500), // 500ns
16658            "0 days 00:00:00.000000500"
16659        );
16660        assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
16661    }
16662
16663    #[test]
16664    fn timedelta_format_negative_uses_python_borrow_form() {
16665        use super::Timedelta;
16666        // pandas/Python normalize negatives via floor division: the days count
16667        // goes negative, the time remainder stays non-negative, and a '+' joins
16668        // them. Verified vs live pandas 2.2.3.
16669        assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
16670        assert_eq!(
16671            Timedelta::format(-Timedelta::NANOS_PER_DAY),
16672            "-1 days +00:00:00"
16673        );
16674        assert_eq!(
16675            Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
16676            "-2 days +23:00:00"
16677        );
16678        assert_eq!(
16679            Timedelta::format(-1_500_000_000),
16680            "-1 days +23:59:58.500000"
16681        );
16682        assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
16683        assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
16684    }
16685
16686    #[test]
16687    #[ignore = "foreground release attribution harness"]
16688    fn timedelta_format_single_buffer_ab_5ro9h() {
16689        use std::{hint::black_box, time::Instant};
16690
16691        use super::Timedelta;
16692
16693        fn former(nanos: i64) -> String {
16694            if nanos == Timedelta::NAT {
16695                return "NaT".to_string();
16696            }
16697
16698            let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
16699            let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
16700            let hours = rem / Timedelta::NANOS_PER_HOUR;
16701            let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
16702            let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
16703            let frac = rem % Timedelta::NANOS_PER_SEC;
16704
16705            let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
16706            let sep = if days < 0 { "+" } else { "" };
16707            if frac > 0 {
16708                if frac % 1_000 == 0 {
16709                    format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
16710                } else {
16711                    format!("{days} days {sep}{time_part}.{frac:09}")
16712                }
16713            } else {
16714                format!("{days} days {sep}{time_part}")
16715            }
16716        }
16717
16718        fn candidate(nanos: i64) -> String {
16719            Timedelta::format(nanos)
16720        }
16721
16722        fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
16723            let started = Instant::now();
16724            let mut digest = 0_usize;
16725            for &value in values {
16726                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
16727            }
16728            black_box(digest);
16729            started.elapsed().as_nanos()
16730        }
16731
16732        fn median(samples: &mut [u128]) -> u128 {
16733            samples.sort_unstable();
16734            samples[samples.len() / 2]
16735        }
16736
16737        let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
16738        let values: Vec<i64> = (0..16_384)
16739            .map(|i| {
16740                seed = seed
16741                    .wrapping_mul(6_364_136_223_846_793_005)
16742                    .wrapping_add(1_442_695_040_888_963_407);
16743                let magnitude = (seed & i64::MAX as u64) as i64;
16744                match i % 4 {
16745                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16746                    1 => magnitude,
16747                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16748                    _ => -magnitude,
16749                }
16750            })
16751            .collect();
16752
16753        for &value in &[
16754            Timedelta::NAT,
16755            0,
16756            1,
16757            -1,
16758            Timedelta::NANOS_PER_DAY,
16759            -Timedelta::NANOS_PER_DAY,
16760            i64::MAX,
16761            i64::MIN + 1,
16762        ] {
16763            assert_eq!(former(value), candidate(value));
16764        }
16765        for &value in &values {
16766            assert_eq!(former(value), candidate(value));
16767        }
16768
16769        for _ in 0..2 {
16770            black_box(elapsed(&values, former));
16771            black_box(elapsed(&values, candidate));
16772        }
16773
16774        let mut former_samples = Vec::with_capacity(18);
16775        let mut candidate_samples = Vec::with_capacity(18);
16776        for block in 0_usize..9 {
16777            if block.is_multiple_of(2) {
16778                former_samples.push(elapsed(&values, former));
16779                candidate_samples.push(elapsed(&values, candidate));
16780                candidate_samples.push(elapsed(&values, candidate));
16781                former_samples.push(elapsed(&values, former));
16782            } else {
16783                candidate_samples.push(elapsed(&values, candidate));
16784                former_samples.push(elapsed(&values, former));
16785                former_samples.push(elapsed(&values, former));
16786                candidate_samples.push(elapsed(&values, candidate));
16787            }
16788        }
16789
16790        let former_p50 = median(&mut former_samples);
16791        let candidate_p50 = median(&mut candidate_samples);
16792        eprintln!(
16793            "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
16794            values.len(),
16795            former_p50 as f64 / candidate_p50 as f64,
16796        );
16797        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
16798        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
16799    }
16800
16801    #[test]
16802    fn timedelta_isoformat_basic() {
16803        use super::Timedelta;
16804        assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
16805        assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
16806        assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
16807        assert_eq!(
16808            Timedelta::isoformat(
16809                Timedelta::NANOS_PER_DAY
16810                    + 2 * Timedelta::NANOS_PER_HOUR
16811                    + 30 * Timedelta::NANOS_PER_MIN
16812                    + 45 * Timedelta::NANOS_PER_SEC
16813            ),
16814            "P1DT2H30M45S"
16815        );
16816        assert_eq!(
16817            Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
16818            "P0DT0H0M1.5S"
16819        );
16820        // TEST-CHANGE (fvsao.68): this pinned "-P1DT1H0M0S"; pandas 2.2.3's
16821        // pd.Timedelta(-90000000000000).isoformat() is "P-2DT23H0M0S" (whole
16822        // days rounded down, then a non-negative clock), and -1ns is
16823        // "P-1DT23H59M59.999999999S" (both measured live).
16824        assert_eq!(
16825            Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
16826            "P-2DT23H0M0S"
16827        );
16828        assert_eq!(Timedelta::isoformat(-1), "P-1DT23H59M59.999999999S");
16829    }
16830
16831    #[test]
16832    #[ignore = "foreground release attribution harness"]
16833    fn timedelta_isoformat_single_buffer_ab_7jra1() {
16834        use std::{hint::black_box, time::Instant};
16835
16836        use super::Timedelta;
16837
16838        fn former_impl(nanos: i64) -> String {
16839            if nanos == Timedelta::NAT {
16840                return "NaT".to_string();
16841            }
16842
16843            let negative = nanos < 0;
16844            let abs_nanos = nanos.saturating_abs();
16845            let days = abs_nanos / Timedelta::NANOS_PER_DAY;
16846            let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
16847            let hours = remaining / Timedelta::NANOS_PER_HOUR;
16848            let remaining = remaining % Timedelta::NANOS_PER_HOUR;
16849            let minutes = remaining / Timedelta::NANOS_PER_MIN;
16850            let remaining = remaining % Timedelta::NANOS_PER_MIN;
16851            let seconds = remaining / Timedelta::NANOS_PER_SEC;
16852            let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
16853
16854            let mut result = String::new();
16855            if negative {
16856                result.push('-');
16857            }
16858
16859            result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
16860
16861            if sub_sec_nanos == 0 {
16862                result.push_str(&format!("{seconds}S"));
16863            } else {
16864                let frac = format!("{sub_sec_nanos:09}");
16865                let trimmed = frac.trim_end_matches('0');
16866                result.push_str(&format!("{seconds}.{trimmed}S"));
16867            }
16868
16869            result
16870        }
16871
16872        fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
16873            let start = Instant::now();
16874            let mut digest = 0_usize;
16875            for &value in values {
16876                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
16877            }
16878            black_box(digest);
16879            start.elapsed().as_nanos()
16880        }
16881
16882        fn median(values: &mut [u128]) -> u128 {
16883            values.sort_unstable();
16884            values[values.len() / 2]
16885        }
16886
16887        let mut seed = 0x7d5a_4c31_91e2_b607_u64;
16888        let values: Vec<i64> = (0..16_384)
16889            .map(|i| {
16890                seed = seed
16891                    .wrapping_mul(6_364_136_223_846_793_005)
16892                    .wrapping_add(1_442_695_040_888_963_407);
16893                let magnitude =
16894                    (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
16895                match i % 4 {
16896                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16897                    1 => magnitude,
16898                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16899                    _ => -magnitude,
16900                }
16901            })
16902            .collect();
16903
16904        // The former implementation wrote a negative duration "-P..."; since
16905        // fvsao.68 it is pandas' "P-..." form, so the two agree on
16906        // non-negative durations only (the timing still covers both signs).
16907        for &value in &[Timedelta::NAT, 0, 1, Timedelta::NANOS_PER_DAY, i64::MAX] {
16908            assert_eq!(former_impl(value), Timedelta::isoformat(value));
16909        }
16910        for &value in values.iter().filter(|value| **value >= 0) {
16911            assert_eq!(former_impl(value), Timedelta::isoformat(value));
16912        }
16913
16914        for _ in 0..2 {
16915            black_box(elapsed(&values, former_impl));
16916            black_box(elapsed(&values, Timedelta::isoformat));
16917        }
16918
16919        let mut former = Vec::with_capacity(18);
16920        let mut candidate = Vec::with_capacity(18);
16921        for block in 0..9 {
16922            if block % 2 == 0 {
16923                former.push(elapsed(&values, former_impl));
16924                candidate.push(elapsed(&values, Timedelta::isoformat));
16925                candidate.push(elapsed(&values, Timedelta::isoformat));
16926                former.push(elapsed(&values, former_impl));
16927            } else {
16928                candidate.push(elapsed(&values, Timedelta::isoformat));
16929                former.push(elapsed(&values, former_impl));
16930                former.push(elapsed(&values, former_impl));
16931                candidate.push(elapsed(&values, Timedelta::isoformat));
16932            }
16933        }
16934
16935        let former_p50 = median(&mut former);
16936        let candidate_p50 = median(&mut candidate);
16937        eprintln!(
16938            "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
16939            values.len(),
16940            former_p50,
16941            candidate_p50,
16942            former_p50 as f64 / candidate_p50 as f64,
16943            former_p50 as f64 / values.len() as f64,
16944            candidate_p50 as f64 / values.len() as f64,
16945        );
16946        eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
16947        eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
16948    }
16949
16950    #[test]
16951    fn timedelta_floor_ceil_round() {
16952        use super::Timedelta;
16953        let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
16954
16955        // floor: rounds down
16956        assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
16957        assert_eq!(Timedelta::floor(nanos, "d"), 0);
16958
16959        // ceil: rounds up
16960        assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16961        assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
16962
16963        // round: rounds to nearest (banker's rounding on tie)
16964        assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16965
16966        // NaT preserved
16967        assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
16968        assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
16969        assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
16970
16971        // Invalid freq returns NAT
16972        assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
16973    }
16974
16975    #[test]
16976    fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
16977        use super::Timedelta;
16978
16979        assert_eq!(
16980            Timedelta::floor(-1, "s"),
16981            -Timedelta::NANOS_PER_SEC,
16982            "floor(-1ns, 1s)"
16983        );
16984        assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
16985        assert_eq!(
16986            Timedelta::floor(-1_500_000_000, "s"),
16987            -2 * Timedelta::NANOS_PER_SEC
16988        );
16989        assert_eq!(
16990            Timedelta::ceil(-1_500_000_000, "s"),
16991            -Timedelta::NANOS_PER_SEC
16992        );
16993        assert_eq!(
16994            Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
16995            -Timedelta::NANOS_PER_SEC
16996        );
16997        assert_eq!(
16998            Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
16999            -Timedelta::NANOS_PER_SEC
17000        );
17001        assert_eq!(
17002            Timedelta::floor(1_500_000_000, "s"),
17003            Timedelta::NANOS_PER_SEC
17004        );
17005        assert_eq!(
17006            Timedelta::ceil(1_500_000_000, "s"),
17007            2 * Timedelta::NANOS_PER_SEC
17008        );
17009    }
17010
17011    #[test]
17012    fn timedelta_scalar_dtype() {
17013        let td = Scalar::Timedelta64(86_400_000_000_000);
17014        assert_eq!(td.dtype(), DType::Timedelta64);
17015    }
17016
17017    #[test]
17018    fn timedelta_scalar_is_missing() {
17019        use super::Timedelta;
17020        let valid = Scalar::Timedelta64(1000);
17021        let nat = Scalar::Timedelta64(Timedelta::NAT);
17022        assert!(!valid.is_missing());
17023        assert!(nat.is_missing());
17024    }
17025
17026    #[test]
17027    fn dtype_utf8_deserializes_legacy_aliases() {
17028        let dtype: DType = serde_json::from_str("\"str\"").unwrap();
17029        assert_eq!(dtype, DType::Utf8);
17030
17031        let dtype: DType = serde_json::from_str("\"string\"").unwrap();
17032        assert_eq!(dtype, DType::Utf8);
17033    }
17034
17035    #[test]
17036    fn datetime64_dtype_carries_timezone_00ze3() {
17037        let naive = DType::datetime64_naive();
17038        assert_eq!(naive.timezone(), None);
17039        assert_eq!(naive.display_name(), "datetime64[ns]");
17040
17041        let aware = DType::datetime64_tz("America/New_York");
17042        assert_eq!(aware.timezone(), Some("America/New_York"));
17043        assert_eq!(aware.display_name(), "datetime64[ns, America/New_York]");
17044        assert_ne!(aware, naive, "timezone must participate in dtype identity");
17045
17046        let json = serde_json::to_string(&aware).expect("serialize timezone dtype");
17047        assert_eq!(
17048            serde_json::from_str::<DType>(&json).expect("deserialize timezone dtype"),
17049            aware
17050        );
17051    }
17052
17053    #[test]
17054    fn scalar_utf8_deserializes_legacy_aliases() {
17055        let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
17056        assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
17057
17058        let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
17059        assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
17060    }
17061
17062    #[test]
17063    fn nancumsum_skips_nulls_and_accumulates() {
17064        let values = vec![
17065            Scalar::Float64(1.0),
17066            Scalar::Null(NullKind::NaN),
17067            Scalar::Float64(2.0),
17068            Scalar::Float64(3.0),
17069        ];
17070        let out = super::nancumsum(&values);
17071        assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
17072        assert!(out[1].is_missing());
17073        assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
17074        assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
17075    }
17076
17077    #[test]
17078    fn nancumprod_skips_nulls_and_multiplies() {
17079        let values = vec![
17080            Scalar::Float64(2.0),
17081            Scalar::Null(NullKind::NaN),
17082            Scalar::Float64(3.0),
17083            Scalar::Float64(4.0),
17084        ];
17085        let out = super::nancumprod(&values);
17086        assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17087        assert!(out[1].is_missing());
17088        assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
17089        assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
17090    }
17091
17092    #[test]
17093    fn nancummax_tracks_running_max() {
17094        let values = vec![
17095            Scalar::Float64(1.0),
17096            Scalar::Float64(3.0),
17097            Scalar::Null(NullKind::NaN),
17098            Scalar::Float64(2.0),
17099            Scalar::Float64(5.0),
17100        ];
17101        let out = super::nancummax(&values);
17102        assert_eq!(out[0], Scalar::Float64(1.0));
17103        assert_eq!(out[1], Scalar::Float64(3.0));
17104        assert!(out[2].is_missing());
17105        assert_eq!(out[3], Scalar::Float64(3.0));
17106        assert_eq!(out[4], Scalar::Float64(5.0));
17107    }
17108
17109    #[test]
17110    fn nancummin_tracks_running_min() {
17111        let values = vec![
17112            Scalar::Float64(5.0),
17113            Scalar::Float64(3.0),
17114            Scalar::Null(NullKind::NaN),
17115            Scalar::Float64(4.0),
17116            Scalar::Float64(1.0),
17117        ];
17118        let out = super::nancummin(&values);
17119        assert_eq!(out[0], Scalar::Float64(5.0));
17120        assert_eq!(out[1], Scalar::Float64(3.0));
17121        assert!(out[2].is_missing());
17122        assert_eq!(out[3], Scalar::Float64(3.0));
17123        assert_eq!(out[4], Scalar::Float64(1.0));
17124    }
17125
17126    #[test]
17127    fn nancumsum_timedelta64_preserves_dtype_x0x91() {
17128        // Per br-frankenpandas-x0x91: pandas td_series.cumsum() returns
17129        // Timedelta64 running sums. Was silently NaN before.
17130        let one_hour = 3_600 * 1_000_000_000_i64;
17131        let values = vec![
17132            Scalar::Timedelta64(one_hour),
17133            Scalar::Timedelta64(2 * one_hour),
17134            Scalar::Timedelta64(3 * one_hour),
17135        ];
17136        let out = super::nancumsum(&values);
17137        assert_eq!(out[0], Scalar::Timedelta64(one_hour));
17138        assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
17139        assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
17140    }
17141
17142    #[test]
17143    fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
17144        let one_hour = 3_600 * 1_000_000_000_i64;
17145        let values = vec![
17146            Scalar::Timedelta64(2 * one_hour),
17147            Scalar::Timedelta64(5 * one_hour),
17148            Scalar::Timedelta64(one_hour),
17149            Scalar::Timedelta64(3 * one_hour),
17150        ];
17151        let mx = super::nancummax(&values);
17152        assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
17153        assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
17154        assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
17155        assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
17156
17157        let mn = super::nancummin(&values);
17158        assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
17159        assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
17160        assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
17161        assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
17162    }
17163
17164    #[test]
17165    fn nancumulative_timedelta64_skips_nat_x0x91() {
17166        let one_hour = 3_600 * 1_000_000_000_i64;
17167        let values = vec![
17168            Scalar::Timedelta64(one_hour),
17169            Scalar::Timedelta64(Timedelta::NAT),
17170            Scalar::Timedelta64(2 * one_hour),
17171        ];
17172        let cs = super::nancumsum(&values);
17173        assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
17174        assert!(cs[1].is_missing());
17175        assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
17176    }
17177
17178    #[test]
17179    fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
17180        // Differential vs independent cumulative nanops oracles
17181        // (br-frankenpandas-k63oz). Seeded LCG, no mocks.
17182        fn next(seed: &mut u64) -> u64 {
17183            *seed = seed
17184                .wrapping_mul(3202034522624059733)
17185                .wrapping_add(4354685564936845319);
17186            *seed
17187        }
17188
17189        fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
17190            assert_eq!(
17191                actual.len(),
17192                expected.len(),
17193                "case={case} family={family} op={op}: length mismatch"
17194            );
17195            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
17196                assert!(
17197                    actual.semantic_eq(expected),
17198                    "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
17199                );
17200            }
17201        }
17202
17203        fn expected_numeric(
17204            values: &[Scalar],
17205        ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
17206            let mut sum = Vec::with_capacity(values.len());
17207            let mut prod = Vec::with_capacity(values.len());
17208            let mut max = Vec::with_capacity(values.len());
17209            let mut min = Vec::with_capacity(values.len());
17210            let mut running_sum = 0.0_f64;
17211            let mut running_prod = 1.0_f64;
17212            let mut running_max: Option<f64> = None;
17213            let mut running_min: Option<f64> = None;
17214
17215            for value in values {
17216                if value.is_missing() {
17217                    sum.push(Scalar::Null(NullKind::NaN));
17218                    prod.push(Scalar::Null(NullKind::NaN));
17219                    max.push(Scalar::Null(NullKind::NaN));
17220                    min.push(Scalar::Null(NullKind::NaN));
17221                    continue;
17222                }
17223                let Ok(value) = value.to_f64() else {
17224                    sum.push(Scalar::Null(NullKind::NaN));
17225                    prod.push(Scalar::Null(NullKind::NaN));
17226                    max.push(Scalar::Null(NullKind::NaN));
17227                    min.push(Scalar::Null(NullKind::NaN));
17228                    continue;
17229                };
17230                if value.is_nan() {
17231                    sum.push(Scalar::Null(NullKind::NaN));
17232                    prod.push(Scalar::Null(NullKind::NaN));
17233                    max.push(Scalar::Null(NullKind::NaN));
17234                    min.push(Scalar::Null(NullKind::NaN));
17235                    continue;
17236                }
17237                running_sum += value;
17238                running_prod *= value;
17239                running_max = Some(running_max.map_or(value, |current| current.max(value)));
17240                running_min = Some(running_min.map_or(value, |current| current.min(value)));
17241                sum.push(Scalar::Float64(running_sum));
17242                prod.push(Scalar::Float64(running_prod));
17243                max.push(Scalar::Float64(running_max.expect("initialized")));
17244                min.push(Scalar::Float64(running_min.expect("initialized")));
17245            }
17246
17247            (sum, prod, max, min)
17248        }
17249
17250        fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
17251            let mut sum = Vec::with_capacity(values.len());
17252            let mut max = Vec::with_capacity(values.len());
17253            let mut min = Vec::with_capacity(values.len());
17254            let mut running_sum = 0_i128;
17255            let mut running_max: Option<i64> = None;
17256            let mut running_min: Option<i64> = None;
17257
17258            for value in values {
17259                if value.is_missing() {
17260                    sum.push(Scalar::Null(NullKind::NaT));
17261                    max.push(Scalar::Null(NullKind::NaT));
17262                    min.push(Scalar::Null(NullKind::NaT));
17263                    continue;
17264                }
17265                let Scalar::Timedelta64(ns) = value else {
17266                    sum.push(Scalar::Null(NullKind::NaT));
17267                    max.push(Scalar::Null(NullKind::NaT));
17268                    min.push(Scalar::Null(NullKind::NaT));
17269                    continue;
17270                };
17271                running_sum = running_sum.saturating_add(i128::from(*ns));
17272                running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
17273                running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
17274                // br-frankenpandas-opz27: mirror the production contract (NaT
17275                // outside the representable range), not the old clamp.
17276                sum.push(super::timedelta_ns_to_scalar(running_sum));
17277                max.push(Scalar::Timedelta64(running_max.expect("initialized")));
17278                min.push(Scalar::Timedelta64(running_min.expect("initialized")));
17279            }
17280
17281            (sum, max, min)
17282        }
17283
17284        let mut seed = 0xc0de_c63a_5eed_0421_u64;
17285        for case in 0..260 {
17286            let len = (next(&mut seed) % 89 + 1) as usize;
17287
17288            let mut numeric = Vec::with_capacity(len);
17289            numeric.push(Scalar::Int64(case as i64 - 130));
17290            for _ in 1..len {
17291                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17292                numeric.push(match next(&mut seed) % 8 {
17293                    0 => Scalar::Null(NullKind::Null),
17294                    1 => Scalar::Null(NullKind::NaN),
17295                    2 => Scalar::Float64(f64::NAN),
17296                    3 => Scalar::Bool(raw & 1 == 0),
17297                    4 => Scalar::Int64(raw % 251),
17298                    5 => Scalar::Float64(raw as f64 / 79.0),
17299                    6 => Scalar::Float64(0.0),
17300                    _ => Scalar::Float64(-0.0),
17301                });
17302            }
17303            let (sum, prod, max, min) = expected_numeric(&numeric);
17304            assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
17305            assert_vec(
17306                case,
17307                "numeric",
17308                "cumprod",
17309                &super::nancumprod(&numeric),
17310                &prod,
17311            );
17312            assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
17313            assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
17314
17315            let mut timedeltas = Vec::with_capacity(len);
17316            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17317            for _ in 1..len {
17318                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17319                timedeltas.push(match next(&mut seed) % 7 {
17320                    0 => Scalar::Null(NullKind::Null),
17321                    1 => Scalar::Timedelta64(i64::MIN),
17322                    _ => Scalar::Timedelta64(raw),
17323                });
17324            }
17325            let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
17326            assert_vec(
17327                case,
17328                "timedelta",
17329                "cumsum",
17330                &super::nancumsum(&timedeltas),
17331                &td_sum,
17332            );
17333            assert_vec(
17334                case,
17335                "timedelta",
17336                "cummax",
17337                &super::nancummax(&timedeltas),
17338                &td_max,
17339            );
17340            assert_vec(
17341                case,
17342                "timedelta",
17343                "cummin",
17344                &super::nancummin(&timedeltas),
17345                &td_min,
17346            );
17347        }
17348    }
17349
17350    #[test]
17351    fn nanquantile_linear_interpolation_matches_numpy() {
17352        let values = vec![
17353            Scalar::Float64(1.0),
17354            Scalar::Float64(2.0),
17355            Scalar::Float64(3.0),
17356            Scalar::Float64(4.0),
17357            Scalar::Float64(5.0),
17358        ];
17359        // median
17360        let q = super::nanquantile(&values, 0.5);
17361        assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
17362        // 25th percentile: interpolate between 2.0 and 3.0 at pos 1.0 → 2.0
17363        let q25 = super::nanquantile(&values, 0.25);
17364        assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17365    }
17366
17367    #[test]
17368    fn nanquantile_ignores_nulls() {
17369        let values = vec![
17370            Scalar::Float64(1.0),
17371            Scalar::Null(NullKind::NaN),
17372            Scalar::Float64(3.0),
17373        ];
17374        let q = super::nanquantile(&values, 0.5);
17375        assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17376    }
17377
17378    #[test]
17379    fn nanquantile_empty_and_out_of_range_yield_null() {
17380        assert!(super::nanquantile(&[], 0.5).is_missing());
17381        assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
17382        assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
17383    }
17384
17385    #[test]
17386    fn nanquantile_timedelta64_preserves_dtype_5djk7() {
17387        // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
17388        // Timedelta64 — was silently NaN before via collect_finite.
17389        let one_hour: i64 = 3_600 * 1_000_000_000;
17390        let vals = vec![
17391            Scalar::Timedelta64(one_hour),
17392            Scalar::Timedelta64(2 * one_hour),
17393            Scalar::Timedelta64(3 * one_hour),
17394            Scalar::Timedelta64(4 * one_hour),
17395            Scalar::Timedelta64(5 * one_hour),
17396        ];
17397        assert_eq!(
17398            super::nanquantile(&vals, 0.5),
17399            Scalar::Timedelta64(3 * one_hour)
17400        );
17401        assert_eq!(
17402            super::nanquantile(&vals, 0.0),
17403            Scalar::Timedelta64(one_hour)
17404        );
17405        assert_eq!(
17406            super::nanquantile(&vals, 1.0),
17407            Scalar::Timedelta64(5 * one_hour)
17408        );
17409    }
17410
17411    #[test]
17412    fn nanquantile_timedelta64_linear_interpolation_5djk7() {
17413        let one_hour: i64 = 3_600 * 1_000_000_000;
17414        let vals = vec![
17415            Scalar::Timedelta64(one_hour),
17416            Scalar::Timedelta64(3 * one_hour),
17417        ];
17418        // Linear interpolation: at q=0.5, midpoint = 2h
17419        assert_eq!(
17420            super::nanquantile(&vals, 0.5),
17421            Scalar::Timedelta64(2 * one_hour)
17422        );
17423    }
17424
17425    #[test]
17426    fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
17427        // Differential vs independent sort-based quantile oracles
17428        // (br-frankenpandas-ecb7r). Seeded LCG, no mocks.
17429        fn next(seed: &mut u64) -> u64 {
17430            *seed = seed
17431                .wrapping_mul(3202034522624059733)
17432                .wrapping_add(4354685564936845319);
17433            *seed
17434        }
17435
17436        fn interpolated(sorted: &[f64], q: f64) -> f64 {
17437            if sorted.len() == 1 {
17438                return sorted[0];
17439            }
17440            let pos = q * (sorted.len() - 1) as f64;
17441            let lo = pos.floor() as usize;
17442            let hi = pos.ceil() as usize;
17443            if lo == hi {
17444                sorted[lo]
17445            } else {
17446                let weight = pos - lo as f64;
17447                sorted[lo] + (sorted[hi] - sorted[lo]) * weight
17448            }
17449        }
17450
17451        fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
17452            if !(0.0..=1.0).contains(&q) {
17453                return Scalar::Null(NullKind::NaN);
17454            }
17455            let mut samples = values
17456                .iter()
17457                .filter(|value| !value.is_missing())
17458                .filter_map(|value| value.to_f64().ok())
17459                .collect::<Vec<_>>();
17460            if samples.is_empty() {
17461                return Scalar::Null(NullKind::NaN);
17462            }
17463            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
17464            Scalar::Float64(interpolated(&samples, q))
17465        }
17466
17467        fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
17468            if !(0.0..=1.0).contains(&q) {
17469                return Scalar::Null(NullKind::NaN);
17470            }
17471            let mut samples = values
17472                .iter()
17473                .filter_map(|value| match value {
17474                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
17475                    _ => None,
17476                })
17477                .collect::<Vec<_>>();
17478            if samples.is_empty() {
17479                // Per br-frankenpandas-k7apg: a NaT-only Timedelta input stays in
17480                // the Timedelta family (pandas returns NaT, not float NaN).
17481                return Scalar::Timedelta64(Timedelta::NAT);
17482            }
17483            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
17484            Scalar::Timedelta64(interpolated(&samples, q) as i64)
17485        }
17486
17487        fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
17488            let actual = super::nanquantile(values, q);
17489            assert!(
17490                actual.semantic_eq(&expected),
17491                "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
17492            );
17493        }
17494
17495        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17496        assert_quantile(
17497            usize::MAX,
17498            "numeric_all_missing",
17499            &numeric_all_missing,
17500            0.5,
17501            expected_numeric(&numeric_all_missing, 0.5),
17502        );
17503        assert_quantile(
17504            usize::MAX - 1,
17505            "numeric_out_of_range",
17506            &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
17507            1.25,
17508            Scalar::Null(NullKind::NaN),
17509        );
17510
17511        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17512        assert_quantile(
17513            usize::MAX - 2,
17514            "timedelta_all_missing",
17515            &td_all_missing,
17516            0.5,
17517            expected_timedelta(&td_all_missing, 0.5),
17518        );
17519        assert_quantile(
17520            usize::MAX - 3,
17521            "timedelta_out_of_range",
17522            &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
17523            -0.25,
17524            Scalar::Null(NullKind::NaN),
17525        );
17526
17527        let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
17528        for case in 0..260 {
17529            let len = (next(&mut seed) % 83 + 1) as usize;
17530            let q = match next(&mut seed) % 8 {
17531                0 => 0.0,
17532                1 => 0.25,
17533                2 => 0.5,
17534                3 => 0.75,
17535                4 => 1.0,
17536                _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
17537            };
17538
17539            let mut numeric = Vec::with_capacity(len);
17540            numeric.push(Scalar::Int64(case as i64 - 130));
17541            for _ in 1..len {
17542                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17543                numeric.push(match next(&mut seed) % 8 {
17544                    0 => Scalar::Null(NullKind::Null),
17545                    1 => Scalar::Null(NullKind::NaN),
17546                    2 => Scalar::Float64(f64::NAN),
17547                    3 => Scalar::Bool(raw & 1 == 0),
17548                    4 => Scalar::Int64(raw % 251),
17549                    5 => Scalar::Float64(raw as f64 / 67.0),
17550                    6 => Scalar::Float64(0.0),
17551                    _ => Scalar::Float64(-0.0),
17552                });
17553            }
17554            assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
17555
17556            let mut timedeltas = Vec::with_capacity(len);
17557            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17558            for _ in 1..len {
17559                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17560                timedeltas.push(match next(&mut seed) % 7 {
17561                    0 => Scalar::Null(NullKind::Null),
17562                    1 => Scalar::Timedelta64(i64::MIN),
17563                    _ => Scalar::Timedelta64(raw),
17564                });
17565            }
17566            assert_quantile(
17567                case,
17568                "timedelta",
17569                &timedeltas,
17570                q,
17571                expected_timedelta(&timedeltas, q),
17572            );
17573        }
17574    }
17575
17576    #[test]
17577    fn nanargmax_returns_first_position() {
17578        let values = vec![
17579            Scalar::Float64(1.0),
17580            Scalar::Null(NullKind::NaN),
17581            Scalar::Float64(4.0),
17582            Scalar::Float64(4.0),
17583            Scalar::Float64(2.0),
17584        ];
17585        assert_eq!(super::nanargmax(&values), Some(2));
17586    }
17587
17588    #[test]
17589    fn nanargmin_returns_first_position() {
17590        let values = vec![
17591            Scalar::Float64(3.0),
17592            Scalar::Null(NullKind::NaN),
17593            Scalar::Float64(1.0),
17594            Scalar::Float64(1.0),
17595        ];
17596        assert_eq!(super::nanargmin(&values), Some(2));
17597    }
17598
17599    #[test]
17600    fn nanargmax_all_missing_returns_none() {
17601        let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
17602        assert_eq!(super::nanargmax(&values), None);
17603        assert_eq!(super::nanargmin(&values), None);
17604    }
17605
17606    #[test]
17607    fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
17608        // Differential vs independent first-tie arg oracles
17609        // (br-frankenpandas-unkj6). Seeded LCG, no mocks.
17610        fn next(seed: &mut u64) -> u64 {
17611            *seed = seed
17612                .wrapping_mul(2862933555777941757)
17613                .wrapping_add(3037000493);
17614            *seed
17615        }
17616
17617        fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
17618            let mut best: Option<(usize, f64)> = None;
17619            for (idx, value) in values.iter().enumerate() {
17620                if value.is_missing() {
17621                    continue;
17622                }
17623                let Ok(value) = value.to_f64() else {
17624                    continue;
17625                };
17626                if value.is_nan() {
17627                    continue;
17628                }
17629                match best {
17630                    None => best = Some((idx, value)),
17631                    Some((_, current))
17632                        if (find_max && value > current) || (!find_max && value < current) =>
17633                    {
17634                        best = Some((idx, value));
17635                    }
17636                    _ => {}
17637                }
17638            }
17639            best.map(|(idx, _)| idx)
17640        }
17641
17642        fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
17643            let mut best: Option<(usize, i64)> = None;
17644            for (idx, value) in values.iter().enumerate() {
17645                if value.is_missing() {
17646                    continue;
17647                }
17648                let Scalar::Timedelta64(ns) = value else {
17649                    continue;
17650                };
17651                match best {
17652                    None => best = Some((idx, *ns)),
17653                    Some((_, current))
17654                        if (find_max && *ns > current) || (!find_max && *ns < current) =>
17655                    {
17656                        best = Some((idx, *ns));
17657                    }
17658                    _ => {}
17659                }
17660            }
17661            best.map(|(idx, _)| idx)
17662        }
17663
17664        fn assert_args(
17665            case: usize,
17666            family: &str,
17667            values: &[Scalar],
17668            expected_min: Option<usize>,
17669            expected_max: Option<usize>,
17670        ) {
17671            assert_eq!(
17672                super::nanargmin(values),
17673                expected_min,
17674                "case={case} family={family}: nanargmin mismatch for {values:?}"
17675            );
17676            assert_eq!(
17677                super::nanargmax(values),
17678                expected_max,
17679                "case={case} family={family}: nanargmax mismatch for {values:?}"
17680            );
17681        }
17682
17683        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17684        assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
17685        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17686        assert_args(
17687            usize::MAX - 1,
17688            "timedelta_all_missing",
17689            &td_all_missing,
17690            None,
17691            None,
17692        );
17693        let positive_int64_endpoint = [
17694            Scalar::Int64(i64::MAX - 1),
17695            Scalar::Null(NullKind::Null),
17696            Scalar::Int64(i64::MAX),
17697        ];
17698        assert_args(
17699            usize::MAX - 2,
17700            "int64_positive_endpoint_exact_order",
17701            &positive_int64_endpoint,
17702            Some(0),
17703            Some(2),
17704        );
17705        let negative_int64_endpoint = [
17706            Scalar::Int64(i64::MIN + 2),
17707            Scalar::Null(NullKind::NaN),
17708            Scalar::Int64(i64::MIN + 1),
17709        ];
17710        assert_args(
17711            usize::MAX - 3,
17712            "int64_negative_endpoint_exact_order",
17713            &negative_int64_endpoint,
17714            Some(2),
17715            Some(0),
17716        );
17717
17718        let mut seed = 0xa126_5eed_ed9e_u64;
17719        for case in 0..260 {
17720            let len = (next(&mut seed) % 83 + 1) as usize;
17721
17722            let mut numeric = Vec::with_capacity(len);
17723            numeric.push(Scalar::Int64(case as i64 - 130));
17724            if len > 1 {
17725                numeric.push(Scalar::Int64(case as i64 - 130));
17726            }
17727            for _ in numeric.len()..len {
17728                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17729                numeric.push(match next(&mut seed) % 9 {
17730                    0 => Scalar::Null(NullKind::Null),
17731                    1 => Scalar::Null(NullKind::NaN),
17732                    2 => Scalar::Float64(f64::NAN),
17733                    3 => Scalar::Bool(raw & 1 == 0),
17734                    4 => Scalar::Int64(raw % 211),
17735                    5 => Scalar::Float64(raw as f64 / 47.0),
17736                    6 => Scalar::Float64(0.0),
17737                    7 => Scalar::Float64(-0.0),
17738                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
17739                });
17740            }
17741            assert_args(
17742                case,
17743                "numeric",
17744                &numeric,
17745                expected_numeric(&numeric, false),
17746                expected_numeric(&numeric, true),
17747            );
17748
17749            let mut timedeltas = Vec::with_capacity(len);
17750            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17751            if len > 1 {
17752                timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17753            }
17754            for _ in timedeltas.len()..len {
17755                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17756                timedeltas.push(match next(&mut seed) % 7 {
17757                    0 => Scalar::Null(NullKind::Null),
17758                    1 => Scalar::Timedelta64(i64::MIN),
17759                    _ => Scalar::Timedelta64(raw),
17760                });
17761            }
17762            assert_args(
17763                case,
17764                "timedelta",
17765                &timedeltas,
17766                expected_timedelta(&timedeltas, false),
17767                expected_timedelta(&timedeltas, true),
17768            );
17769        }
17770    }
17771
17772    #[test]
17773    fn nansem_matches_std_over_sqrt_n() {
17774        let values = vec![
17775            Scalar::Float64(2.0),
17776            Scalar::Float64(4.0),
17777            Scalar::Float64(4.0),
17778            Scalar::Float64(4.0),
17779            Scalar::Float64(5.0),
17780            Scalar::Float64(5.0),
17781            Scalar::Float64(7.0),
17782            Scalar::Float64(9.0),
17783        ];
17784        // numpy/scipy: std(ddof=1) = 2.138089935299395; sem = std/sqrt(8) = 0.7559
17785        let sem = super::nansem(&values, 1);
17786        assert!(matches!(sem, Scalar::Float64(_)));
17787        let Scalar::Float64(v) = sem else {
17788            return;
17789        };
17790        assert!((v - 0.7559289460184544).abs() < 1e-9);
17791    }
17792
17793    #[test]
17794    fn nansem_grouped_is_sqrt_var_over_n_7hxqv() {
17795        // pandas 2.2.3: Series([1.0, 4.0]).groupby([0, 0]).sem() == 1.5 while
17796        // Series([1.0, 4.0]).sem() == 1.4999999999999998.
17797        let values = [
17798            Scalar::Float64(1.0),
17799            Scalar::Null(NullKind::NaN),
17800            Scalar::Float64(4.0),
17801        ];
17802        assert_eq!(super::nansem_grouped(&values, 1), Scalar::Float64(1.5));
17803        // NEGATIVE: Series.sem keeps std / sqrt(n).
17804        assert_eq!(
17805            super::nansem(&values, 1),
17806            Scalar::Float64(1.499_999_999_999_999_8)
17807        );
17808        assert!(super::nansem_grouped(&values[..1], 1).is_missing());
17809    }
17810
17811    #[test]
17812    fn grouped_reducers_add_as_pandas_group_kernels_xhogl() {
17813        // pandas 2.2.3 groupby of ten 0.1: sum 1.0, mean 0.1, var 0.0 - a
17814        // plain fold gives 0.9999999999999999, 0.09999999999999999 and
17815        // 2.1e-34 (br-frankenpandas-xhogl).
17816        let tenths: Vec<Scalar> = (0..10).map(|_| Scalar::Float64(0.1)).collect();
17817        assert_eq!(super::nansum_grouped(&tenths), Scalar::Float64(1.0));
17818        assert_eq!(super::nanmean_grouped(&tenths), Scalar::Float64(0.1));
17819        assert_eq!(super::nanvar_grouped(&tenths, 1), Scalar::Float64(0.0));
17820        assert_eq!(super::nanstd_grouped(&tenths, 1), Scalar::Float64(0.0));
17821        // NEGATIVE: the Series reductions keep their plain fold.
17822        assert_eq!(
17823            super::nansum(&tenths),
17824            Scalar::Float64(0.999_999_999_999_999_9)
17825        );
17826        // An inf keeps the sum inf (the compensation would go NaN).
17827        let mut sum = super::KahanSum::default();
17828        for value in [1.0, f64::INFINITY, 2.0] {
17829            sum.add(value);
17830        }
17831        assert_eq!(sum.sum(), f64::INFINITY);
17832        // Missing values are skipped; too few for ddof is missing.
17833        let gapped = [
17834            Scalar::Float64(1.0),
17835            Scalar::Null(NullKind::NaN),
17836            Scalar::Float64(4.0),
17837        ];
17838        assert_eq!(super::nanmean_grouped(&gapped), Scalar::Float64(2.5));
17839        assert_eq!(super::nanvar_grouped(&gapped, 1), Scalar::Float64(4.5));
17840        assert!(super::nanvar_grouped(&gapped[..1], 1).is_missing());
17841        // Timedelta input keeps the exact integer paths.
17842        let spans = [Scalar::Timedelta64(1), Scalar::Timedelta64(2)];
17843        assert_eq!(super::nansum_grouped(&spans), super::nansum(&spans));
17844    }
17845
17846    #[test]
17847    fn grouped_skew_is_pandas_online_group_skew_vjfq9() {
17848        // pandas 2.2.3 groupby skew of [1, 4, 8] is 0.42327316026800615 - a
17849        // two-pass form gives 0.4232731602680071 (br-frankenpandas-vjfq9).
17850        let group = [
17851            Scalar::Float64(1.0),
17852            Scalar::Null(NullKind::NaN),
17853            Scalar::Float64(4.0),
17854            Scalar::Float64(8.0),
17855        ];
17856        assert_eq!(
17857            super::nanskew_grouped(&group),
17858            Scalar::Float64(0.423_273_160_268_006_15)
17859        );
17860        // 2922 values: pandas raises (n - 1) ** 0.5 with libm pow, which is not
17861        // sqrt's answer for n - 1 = 2921 (sqrt gives -0.002284383734800802).
17862        let long: Vec<Scalar> = (0..2922_i32)
17863            .map(|i| Scalar::Float64(f64::from((i * 7919) % 1000) / 7.0))
17864            .collect();
17865        let glibc_pow = Scalar::Float64(-0.002_284_383_734_800_801_4);
17866        // That is pandas on glibc, the oracle's platform. pandas' Cython
17867        // `** 0.5` calls the platform's pow, as fp does, and Apple's libm
17868        // returns sqrt's answer for 2921 (CI 36847809394 macos-latest), so
17869        // another libm may give that one - never anything else
17870        // (br-frankenpandas-3bo1g).
17871        if cfg!(all(target_os = "linux", target_env = "gnu")) {
17872            assert_eq!(super::nanskew_grouped(&long), glibc_pow);
17873        } else {
17874            let sqrt = Scalar::Float64(-0.002_284_383_734_800_802);
17875            assert!([glibc_pow, sqrt].contains(&super::nanskew_grouped(&long)));
17876        }
17877        // A constant group is 0; below 3 values missing; an inf poisons its
17878        // group (pandas skips only NaN), where dropping it would leave [1, 2, 5].
17879        let constant = [7.0; 3].map(Scalar::Float64);
17880        assert_eq!(super::nanskew_grouped(&constant), Scalar::Float64(0.0));
17881        assert!(super::nanskew_grouped(&group[..2]).is_missing());
17882        let with_inf = [1.0, f64::INFINITY, 2.0, 5.0].map(Scalar::Float64);
17883        assert!(super::nanskew_grouped(&with_inf).is_missing());
17884    }
17885
17886    #[test]
17887    fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
17888        fn former(values: &[Scalar], ddof: usize) -> Scalar {
17889            let nums = super::collect_finite(values);
17890            if nums.len() <= ddof {
17891                return Scalar::Null(NullKind::NaN);
17892            }
17893            match super::nanstd(values, ddof) {
17894                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17895                other => other,
17896            }
17897        }
17898
17899        fn assert_same_bits(values: &[Scalar], ddof: usize) {
17900            let expected = former(values, ddof);
17901            let actual = super::nansem(values, ddof);
17902            match (&expected, &actual) {
17903                (Scalar::Float64(expected), Scalar::Float64(actual)) => {
17904                    assert_eq!(
17905                        actual.to_bits(),
17906                        expected.to_bits(),
17907                        "values={values:?} ddof={ddof}"
17908                    );
17909                }
17910                _ => assert!(
17911                    actual.semantic_eq(&expected),
17912                    "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
17913                ),
17914            }
17915        }
17916
17917        let mut generated = Vec::with_capacity(4_096);
17918        for idx in 0..4_096_i64 {
17919            generated.push(match idx % 257 {
17920                0 => Scalar::Null(NullKind::NaN),
17921                1 => Scalar::Float64(-0.0),
17922                2 => Scalar::Float64(0.0),
17923                _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
17924                _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
17925            });
17926        }
17927
17928        let cases = [
17929            Vec::new(),
17930            vec![Scalar::Int64(1)],
17931            vec![
17932                Scalar::Null(NullKind::Null),
17933                Scalar::Float64(f64::NAN),
17934                Scalar::Int64(i64::MIN),
17935                Scalar::Int64(i64::MAX),
17936                Scalar::Float64(-0.0),
17937                Scalar::Float64(0.0),
17938            ],
17939            generated,
17940        ];
17941        for values in &cases {
17942            for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
17943                assert_same_bits(values, ddof);
17944            }
17945        }
17946    }
17947
17948    #[test]
17949    #[ignore = "foreground release A/B harness"]
17950    fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
17951        const ROWS: usize = 262_144;
17952        const BATCH: usize = 8;
17953        const BLOCKS: usize = 9;
17954        const PRECONDITION_CALLS: usize = 2;
17955
17956        fn former(values: &[Scalar], ddof: usize) -> Scalar {
17957            let nums = super::collect_finite(values);
17958            if nums.len() <= ddof {
17959                return Scalar::Null(NullKind::NaN);
17960            }
17961            match super::nanstd(values, ddof) {
17962                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17963                other => other,
17964            }
17965        }
17966
17967        fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
17968            let values = std::hint::black_box(values);
17969            if candidate {
17970                super::nansem(values, 1)
17971            } else {
17972                former(values, 1)
17973            }
17974        }
17975
17976        fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
17977            for _ in 0..PRECONDITION_CALLS {
17978                std::hint::black_box(evaluate(values, candidate));
17979            }
17980            let started = std::time::Instant::now();
17981            for _ in 0..BATCH {
17982                std::hint::black_box(evaluate(values, candidate));
17983            }
17984            started.elapsed().as_nanos()
17985        }
17986
17987        fn median(mut samples: Vec<u128>) -> u128 {
17988            samples.sort_unstable();
17989            samples[samples.len() / 2]
17990        }
17991
17992        fn spread(a: u128, b: u128) -> f64 {
17993            a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
17994        }
17995
17996        let values = (0..ROWS)
17997            .map(|idx| {
17998                if idx % 257 == 0 {
17999                    Scalar::Null(NullKind::NaN)
18000                } else {
18001                    Scalar::Int64((idx % 8_191) as i64 - 4_095)
18002                }
18003            })
18004            .collect::<Vec<_>>();
18005
18006        let expected_bits = match former(&values, 1) {
18007            Scalar::Float64(value) => Some(value.to_bits()),
18008            _ => None,
18009        };
18010        let actual_bits = match super::nansem(&values, 1) {
18011            Scalar::Float64(value) => Some(value.to_bits()),
18012            _ => None,
18013        };
18014        assert!(
18015            expected_bits.is_some(),
18016            "numeric nansem must return Float64"
18017        );
18018        assert_eq!(actual_bits, expected_bits, "A/B output bits");
18019
18020        std::hint::black_box(evaluate(&values, false));
18021        std::hint::black_box(evaluate(&values, true));
18022
18023        let body_started = std::time::Instant::now();
18024        let mut former_a = Vec::with_capacity(BLOCKS);
18025        let mut former_b = Vec::with_capacity(BLOCKS);
18026        let mut candidate_a = Vec::with_capacity(BLOCKS);
18027        let mut candidate_b = Vec::with_capacity(BLOCKS);
18028        for block in 0..BLOCKS {
18029            let order = if block % 2 == 0 {
18030                [(false, 0), (true, 0), (true, 1), (false, 1)]
18031            } else {
18032                [(true, 1), (false, 1), (false, 0), (true, 0)]
18033            };
18034            for (candidate, duplicate) in order {
18035                let elapsed = elapsed_ns(&values, candidate);
18036                match (candidate, duplicate) {
18037                    (false, 0) => former_a.push(elapsed),
18038                    (false, _) => former_b.push(elapsed),
18039                    (true, 0) => candidate_a.push(elapsed),
18040                    (true, _) => candidate_b.push(elapsed),
18041                }
18042            }
18043        }
18044
18045        let former_a = median(former_a) / BATCH as u128;
18046        let former_b = median(former_b) / BATCH as u128;
18047        let candidate_a = median(candidate_a) / BATCH as u128;
18048        let candidate_b = median(candidate_b) / BATCH as u128;
18049        let former_mean = (former_a + former_b) as f64 / 2.0;
18050        let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
18051        println!(
18052            "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}",
18053            spread(former_a, former_b),
18054            spread(candidate_a, candidate_b),
18055            former_mean / candidate_mean,
18056            body_started.elapsed().as_secs_f64()
18057        );
18058    }
18059
18060    #[test]
18061    fn nansem_empty_returns_null() {
18062        assert!(super::nansem(&[], 1).is_missing());
18063        assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
18064    }
18065
18066    #[test]
18067    fn nanptp_returns_max_minus_min() {
18068        let values = vec![
18069            Scalar::Float64(3.0),
18070            Scalar::Null(NullKind::NaN),
18071            Scalar::Float64(7.0),
18072            Scalar::Float64(1.0),
18073        ];
18074        assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
18075    }
18076
18077    #[test]
18078    fn nanptp_empty_returns_null() {
18079        assert!(super::nanptp(&[]).is_missing());
18080        assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
18081    }
18082
18083    #[test]
18084    fn nanptp_timedelta64_preserves_dtype_u2g0r() {
18085        // Per br-frankenpandas-u2g0r: ptp on Timedelta64 returns Timedelta64.
18086        let one_hour: i64 = 3_600 * 1_000_000_000;
18087        let values = vec![
18088            Scalar::Timedelta64(one_hour),
18089            Scalar::Timedelta64(5 * one_hour),
18090            Scalar::Timedelta64(2 * one_hour),
18091        ];
18092        assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
18093    }
18094
18095    #[test]
18096    fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
18097        // Differential vs independent max-min oracles
18098        // (br-frankenpandas-affjt). Seeded LCG, no mocks.
18099        fn next(seed: &mut u64) -> u64 {
18100            *seed = seed
18101                .wrapping_mul(3202034522624059733)
18102                .wrapping_add(4354685564936845319);
18103            *seed
18104        }
18105
18106        fn expected_numeric(values: &[Scalar]) -> Scalar {
18107            let mut lo = f64::INFINITY;
18108            let mut hi = f64::NEG_INFINITY;
18109            let mut seen = false;
18110            for value in values {
18111                if value.is_missing() {
18112                    continue;
18113                }
18114                if let Ok(value) = value.to_f64() {
18115                    seen = true;
18116                    lo = lo.min(value);
18117                    hi = hi.max(value);
18118                }
18119            }
18120            if seen {
18121                Scalar::Float64(hi - lo)
18122            } else {
18123                Scalar::Null(NullKind::NaN)
18124            }
18125        }
18126
18127        fn expected_timedelta(values: &[Scalar]) -> Scalar {
18128            let mut lo = i64::MAX;
18129            let mut hi = i64::MIN;
18130            let mut seen = false;
18131            for value in values {
18132                if let Scalar::Timedelta64(ns) = value
18133                    && !value.is_missing()
18134                {
18135                    seen = true;
18136                    lo = lo.min(*ns);
18137                    hi = hi.max(*ns);
18138                }
18139            }
18140            if seen {
18141                Scalar::Timedelta64(hi - lo)
18142            } else {
18143                Scalar::Null(NullKind::NaN)
18144            }
18145        }
18146
18147        fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
18148            let actual = super::nanptp(values);
18149            assert!(
18150                actual.semantic_eq(&expected),
18151                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
18152            );
18153        }
18154
18155        assert_ptp(
18156            usize::MAX,
18157            "numeric_all_missing",
18158            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
18159            Scalar::Null(NullKind::NaN),
18160        );
18161        assert_ptp(
18162            usize::MAX - 1,
18163            "timedelta_all_missing",
18164            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
18165            Scalar::Null(NullKind::NaN),
18166        );
18167        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
18168        assert_ptp(
18169            usize::MAX - 2,
18170            "timedelta_one_ns_range_beyond_f64_exactness",
18171            &[
18172                Scalar::Timedelta64(beyond_f64_exact_ns),
18173                Scalar::Timedelta64(beyond_f64_exact_ns - 1),
18174                Scalar::Timedelta64(Timedelta::NAT),
18175            ],
18176            Scalar::Timedelta64(1),
18177        );
18178
18179        let mut seed = 0xa22f_17ed_57a7_15e5_u64;
18180        for case in 0..260 {
18181            let len = (next(&mut seed) % 83 + 1) as usize;
18182
18183            let mut numeric = Vec::with_capacity(len);
18184            numeric.push(Scalar::Int64(case as i64 - 130));
18185            for _ in 1..len {
18186                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
18187                numeric.push(match next(&mut seed) % 9 {
18188                    0 => Scalar::Null(NullKind::Null),
18189                    1 => Scalar::Null(NullKind::NaN),
18190                    2 => Scalar::Float64(f64::NAN),
18191                    3 => Scalar::Bool(raw & 1 == 0),
18192                    4 => Scalar::Int64(raw),
18193                    5 => Scalar::Float64(raw as f64 / 53.0),
18194                    6 => Scalar::Float64(0.0),
18195                    7 => Scalar::Float64(-0.0),
18196                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
18197                });
18198            }
18199            assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
18200
18201            let mut timedeltas = Vec::with_capacity(len);
18202            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
18203            for _ in 1..len {
18204                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
18205                timedeltas.push(match next(&mut seed) % 7 {
18206                    0 => Scalar::Null(NullKind::Null),
18207                    1 => Scalar::Timedelta64(i64::MIN),
18208                    _ => Scalar::Timedelta64(raw),
18209                });
18210            }
18211            assert_ptp(
18212                case,
18213                "timedelta",
18214                &timedeltas,
18215                expected_timedelta(&timedeltas),
18216            );
18217        }
18218    }
18219
18220    #[test]
18221    fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
18222        // Per br-frankenpandas-ql1t5: argmax/argmin on Timedelta64 compare
18223        // i64 ns directly instead of silently skipping via to_f64.
18224        let one_hour: i64 = 3_600 * 1_000_000_000;
18225        let values = vec![
18226            Scalar::Timedelta64(2 * one_hour),
18227            Scalar::Timedelta64(5 * one_hour),
18228            Scalar::Timedelta64(one_hour),
18229            Scalar::Timedelta64(3 * one_hour),
18230        ];
18231        assert_eq!(super::nanargmax(&values), Some(1));
18232        assert_eq!(super::nanargmin(&values), Some(2));
18233    }
18234
18235    #[test]
18236    fn nanprod_timedelta64_returns_null_szq6a() {
18237        // Per br-frankenpandas-szq6a: pandas raises on Timedelta prod
18238        // (dimensionally undefined). We surface Null instead of the
18239        // misleading Float64(1.0) the old empty-iterator default emitted.
18240        let one_hour: i64 = 3_600 * 1_000_000_000;
18241        let values = vec![
18242            Scalar::Timedelta64(2 * one_hour),
18243            Scalar::Timedelta64(3 * one_hour),
18244        ];
18245        assert!(super::nanprod(&values).is_missing());
18246    }
18247
18248    #[test]
18249    fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
18250        // Differential vs independent product oracles
18251        // (br-frankenpandas-9938h). Seeded LCG, no mocks.
18252        fn next(seed: &mut u64) -> u64 {
18253            *seed = seed
18254                .wrapping_mul(6364136223846793005)
18255                .wrapping_add(1442695040888963407);
18256            *seed
18257        }
18258
18259        fn expected_numeric(values: &[Scalar]) -> Scalar {
18260            let mut product = 1.0_f64;
18261            for value in values {
18262                if value.is_missing() {
18263                    continue;
18264                }
18265                if let Ok(value) = value.to_f64() {
18266                    product *= value;
18267                }
18268            }
18269            Scalar::Float64(product)
18270        }
18271
18272        fn expected_timedelta(values: &[Scalar]) -> Scalar {
18273            if values
18274                .iter()
18275                .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
18276            {
18277                Scalar::Null(NullKind::NaN)
18278            } else {
18279                Scalar::Float64(1.0)
18280            }
18281        }
18282
18283        fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
18284            let actual = super::nanprod(values);
18285            assert!(
18286                actual.semantic_eq(&expected),
18287                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
18288            );
18289        }
18290
18291        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
18292        assert_prod(
18293            usize::MAX,
18294            "numeric_all_missing",
18295            &all_missing,
18296            Scalar::Float64(1.0),
18297        );
18298
18299        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
18300        assert_prod(
18301            usize::MAX - 1,
18302            "timedelta_all_missing",
18303            &td_all_missing,
18304            expected_timedelta(&td_all_missing),
18305        );
18306
18307        let mut seed = 0x6e0d_9938_a11c_0de5_u64;
18308        for case in 0..280 {
18309            let len = (next(&mut seed) % 89 + 1) as usize;
18310
18311            let mut numeric = Vec::with_capacity(len);
18312            numeric.push(Scalar::Int64((case % 17) as i64 - 8));
18313            for _ in 1..len {
18314                let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
18315                numeric.push(match next(&mut seed) % 9 {
18316                    0 => Scalar::Null(NullKind::Null),
18317                    1 => Scalar::Null(NullKind::NaN),
18318                    2 => Scalar::Float64(f64::NAN),
18319                    3 => Scalar::Bool(raw & 1 == 0),
18320                    4 => Scalar::Int64(raw % 19),
18321                    5 => Scalar::Float64(raw as f64 / 97.0),
18322                    6 => Scalar::Float64(0.0),
18323                    7 => Scalar::Float64(-0.0),
18324                    _ => Scalar::Float64(1.0),
18325                });
18326            }
18327            assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
18328
18329            let mut timedeltas = Vec::with_capacity(len);
18330            timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
18331            for _ in 1..len {
18332                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
18333                timedeltas.push(match next(&mut seed) % 7 {
18334                    0 => Scalar::Null(NullKind::Null),
18335                    1 => Scalar::Timedelta64(i64::MIN),
18336                    _ => Scalar::Timedelta64(raw),
18337                });
18338            }
18339            assert_prod(
18340                case,
18341                "timedelta",
18342                &timedeltas,
18343                expected_timedelta(&timedeltas),
18344            );
18345        }
18346    }
18347
18348    #[test]
18349    fn nanskew_symmetric_distribution_near_zero() {
18350        let values = vec![
18351            Scalar::Float64(1.0),
18352            Scalar::Float64(2.0),
18353            Scalar::Float64(3.0),
18354            Scalar::Float64(4.0),
18355            Scalar::Float64(5.0),
18356        ];
18357        // Perfectly symmetric -> skew = 0
18358        let skew = super::nanskew(&values);
18359        assert!(matches!(skew, Scalar::Float64(_)));
18360        let Scalar::Float64(v) = skew else {
18361            return;
18362        };
18363        assert!(v.abs() < 1e-9);
18364    }
18365
18366    #[test]
18367    fn nanskew_too_few_values_returns_null() {
18368        assert!(super::nanskew(&[]).is_missing());
18369        assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
18370    }
18371
18372    #[test]
18373    fn nankurt_symmetric_uniform_distribution() {
18374        let values = vec![
18375            Scalar::Float64(1.0),
18376            Scalar::Float64(2.0),
18377            Scalar::Float64(3.0),
18378            Scalar::Float64(4.0),
18379            Scalar::Float64(5.0),
18380        ];
18381        // pandas kurt([1,2,3,4,5]) = -1.2
18382        let kurt = super::nankurt(&values);
18383        assert!(matches!(kurt, Scalar::Float64(_)));
18384        let Scalar::Float64(v) = kurt else {
18385            return;
18386        };
18387        assert!((v + 1.2).abs() < 1e-9);
18388    }
18389
18390    #[test]
18391    fn nankurt_too_few_values_returns_null() {
18392        let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
18393        assert!(super::nankurt(&vals).is_missing());
18394    }
18395
18396    #[test]
18397    fn nanskew_constant_series_returns_zero() {
18398        let values = vec![
18399            Scalar::Float64(5.0),
18400            Scalar::Float64(5.0),
18401            Scalar::Float64(5.0),
18402        ];
18403        assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
18404        assert_eq!(
18405            super::nankurt(&[
18406                Scalar::Float64(5.0),
18407                Scalar::Float64(5.0),
18408                Scalar::Float64(5.0),
18409                Scalar::Float64(5.0),
18410            ]),
18411            Scalar::Float64(0.0)
18412        );
18413    }
18414
18415    #[test]
18416    fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
18417        // Differential vs independent bias-corrected moment oracles
18418        // (br-frankenpandas-jr7zk). Seeded LCG, no mocks.
18419        fn next(seed: &mut u64) -> u64 {
18420            *seed = seed
18421                .wrapping_mul(2862933555777941757)
18422                .wrapping_add(3037000493);
18423            *seed
18424        }
18425
18426        fn samples(values: &[Scalar]) -> Vec<f64> {
18427            values
18428                .iter()
18429                .filter(|value| !value.is_missing())
18430                .filter_map(|value| value.to_f64().ok())
18431                .collect()
18432        }
18433
18434        fn expected_skew(values: &[Scalar]) -> Scalar {
18435            let samples = samples(values);
18436            let n = samples.len() as f64;
18437            if n < 3.0 {
18438                return Scalar::Null(NullKind::NaN);
18439            }
18440            let mean = samples.iter().sum::<f64>() / n;
18441            let m2 = samples
18442                .iter()
18443                .map(|value| (value - mean).powi(2))
18444                .sum::<f64>();
18445            let m3 = samples
18446                .iter()
18447                .map(|value| (value - mean).powi(3))
18448                .sum::<f64>();
18449            let s2 = m2 / (n - 1.0);
18450            if s2 == 0.0 {
18451                return Scalar::Float64(0.0);
18452            }
18453            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
18454        }
18455
18456        fn expected_kurt(values: &[Scalar]) -> Scalar {
18457            let samples = samples(values);
18458            let n = samples.len() as f64;
18459            if n < 4.0 {
18460                return Scalar::Null(NullKind::NaN);
18461            }
18462            let mean = samples.iter().sum::<f64>() / n;
18463            let m2 = samples
18464                .iter()
18465                .map(|value| (value - mean).powi(2))
18466                .sum::<f64>();
18467            let m4 = samples
18468                .iter()
18469                .map(|value| (value - mean).powi(4))
18470                .sum::<f64>();
18471            let s2 = m2 / (n - 1.0);
18472            if s2 == 0.0 {
18473                return Scalar::Float64(0.0);
18474            }
18475            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
18476            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
18477            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
18478        }
18479
18480        fn assert_moments(case: usize, values: &[Scalar]) {
18481            let expected_skew = expected_skew(values);
18482            let expected_kurt = expected_kurt(values);
18483            let actual_skew = super::nanskew(values);
18484            let actual_kurt = super::nankurt(values);
18485            assert!(
18486                actual_skew.semantic_eq(&expected_skew),
18487                "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
18488            );
18489            assert!(
18490                actual_kurt.semantic_eq(&expected_kurt),
18491                "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
18492            );
18493        }
18494
18495        assert_moments(
18496            usize::MAX,
18497            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
18498        );
18499        assert_moments(
18500            usize::MAX - 1,
18501            &[
18502                Scalar::Float64(7.0),
18503                Scalar::Float64(7.0),
18504                Scalar::Float64(7.0),
18505                Scalar::Float64(7.0),
18506            ],
18507        );
18508
18509        let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
18510        for case in 0..260 {
18511            let len = (next(&mut seed) % 89 + 1) as usize;
18512            let mut values = Vec::with_capacity(len);
18513            if case % 11 == 0 {
18514                values.extend((0..len).map(|_| Scalar::Float64(3.0)));
18515            } else {
18516                values.push(Scalar::Float64(case as f64 / 19.0));
18517                for _ in 1..len {
18518                    let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
18519                    values.push(match next(&mut seed) % 8 {
18520                        0 => Scalar::Null(NullKind::Null),
18521                        1 => Scalar::Null(NullKind::NaN),
18522                        2 => Scalar::Float64(f64::NAN),
18523                        3 => Scalar::Bool(raw & 1 == 0),
18524                        4 => Scalar::Int64(raw % 251),
18525                        5 => Scalar::Float64(raw as f64 / 83.0),
18526                        6 => Scalar::Float64(0.0),
18527                        _ => Scalar::Float64(-0.0),
18528                    });
18529                }
18530            }
18531            assert_moments(case, &values);
18532        }
18533    }
18534
18535    // ── Interval tests (br-frankenpandas-j8k4) ──────────────────────────
18536
18537    #[test]
18538    fn interval_default_closed_is_right() {
18539        assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
18540    }
18541
18542    #[test]
18543    fn interval_left_and_right_closed_helpers() {
18544        assert!(IntervalClosed::Left.left_closed());
18545        assert!(!IntervalClosed::Left.right_closed());
18546        assert!(!IntervalClosed::Right.left_closed());
18547        assert!(IntervalClosed::Right.right_closed());
18548        assert!(IntervalClosed::Both.left_closed());
18549        assert!(IntervalClosed::Both.right_closed());
18550        assert!(!IntervalClosed::Neither.left_closed());
18551        assert!(!IntervalClosed::Neither.right_closed());
18552    }
18553
18554    #[test]
18555    fn interval_display_matches_pandas_notation() {
18556        assert_eq!(
18557            Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
18558            "(0.0, 5.0]"
18559        );
18560        assert_eq!(
18561            Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
18562            "[0.0, 5.0)"
18563        );
18564        assert_eq!(
18565            Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
18566            "[0.0, 5.0]"
18567        );
18568        assert_eq!(
18569            Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
18570            "(0.0, 5.0)"
18571        );
18572        assert_eq!(
18573            Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
18574            "(2.5, 3.5]"
18575        );
18576        assert_eq!(
18577            Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
18578            "(-1.0, 0.0]"
18579        );
18580        assert_eq!(
18581            Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
18582            "(1e+20, 2e+20]"
18583        );
18584    }
18585
18586    #[test]
18587    fn interval_length_and_mid() {
18588        let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
18589        assert_eq!(i.length(), 8.0);
18590        assert_eq!(i.mid(), 6.0);
18591    }
18592
18593    #[test]
18594    fn interval_contains_matches_closed_policy() {
18595        let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
18596        assert!(!right.contains(0.0));
18597        assert!(right.contains(2.5));
18598        assert!(right.contains(5.0));
18599
18600        let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
18601        assert!(left.contains(0.0));
18602        assert!(left.contains(2.5));
18603        assert!(!left.contains(5.0));
18604
18605        let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
18606        assert!(both.contains(0.0));
18607        assert!(both.contains(5.0));
18608
18609        let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
18610        assert!(!neither.contains(0.0));
18611        assert!(!neither.contains(5.0));
18612        assert!(neither.contains(2.5));
18613    }
18614
18615    #[test]
18616    fn interval_contains_nan_returns_false() {
18617        let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
18618        assert!(!i.contains(f64::NAN));
18619    }
18620
18621    #[test]
18622    fn interval_is_empty_matches_pandas() {
18623        // pd.Interval(3, 3, 'right').is_empty → True
18624        assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
18625        assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
18626        assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
18627        // pd.Interval(3, 3, 'both').is_empty → False (single point)
18628        assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
18629        // Non-degenerate intervals are never empty.
18630        assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
18631    }
18632
18633    #[test]
18634    fn interval_overlaps_disjoint_returns_false() {
18635        let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
18636        let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
18637        assert!(!a.overlaps(&b));
18638        assert!(!b.overlaps(&a));
18639    }
18640
18641    #[test]
18642    fn interval_overlaps_nested_returns_true() {
18643        let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
18644        let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
18645        assert!(outer.overlaps(&inner));
18646        assert!(inner.overlaps(&outer));
18647    }
18648
18649    #[test]
18650    fn interval_overlaps_touching_respects_closed_policy() {
18651        // (0, 1] touching (1, 2] at point 1.
18652        let right_right = (
18653            Interval::new(0.0, 1.0, IntervalClosed::Right),
18654            Interval::new(1.0, 2.0, IntervalClosed::Right),
18655        );
18656        // right_right.0 is closed at 1; right_right.1 is open at 1 → no overlap.
18657        assert!(!right_right.0.overlaps(&right_right.1));
18658
18659        // [0, 1] touching [1, 2] — both closed at 1 → overlap.
18660        let both_both = (
18661            Interval::new(0.0, 1.0, IntervalClosed::Both),
18662            Interval::new(1.0, 2.0, IntervalClosed::Both),
18663        );
18664        assert!(both_both.0.overlaps(&both_both.1));
18665    }
18666
18667    #[test]
18668    fn interval_roundtrips_through_serde_json() {
18669        let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
18670        let json = serde_json::to_string(&i).expect("serialize");
18671        let back: Interval = serde_json::from_str(&json).expect("deserialize");
18672        assert_eq!(i, back);
18673    }
18674
18675    #[test]
18676    fn interval_serde_default_closed_is_right_when_missing() {
18677        // JSON payloads that omit `closed` deserialize with the pandas default.
18678        let back: Interval =
18679            serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
18680        assert_eq!(back.closed, IntervalClosed::Right);
18681    }
18682
18683    // ── Period tests (br-frankenpandas-epoj) ────────────────────────────
18684
18685    #[test]
18686    fn period_freq_parses_canonical_aliases() {
18687        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
18688        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
18689        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
18690        assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
18691        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
18692        assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
18693        assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
18694        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
18695        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
18696        assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
18697        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
18698    }
18699
18700    #[test]
18701    fn period_freq_parse_is_case_insensitive() {
18702        assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::QUARTERLY));
18703        assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
18704    }
18705
18706    #[test]
18707    fn period_freq_rejects_unknown_aliases() {
18708        assert_eq!(PeriodFreq::parse("nanosec"), None);
18709        assert_eq!(PeriodFreq::parse(""), None);
18710        assert_eq!(PeriodFreq::parse("xyz"), None);
18711    }
18712
18713    #[test]
18714    fn period_freq_alias_roundtrip() {
18715        for freq in [
18716            PeriodFreq::ANNUAL,
18717            PeriodFreq::QUARTERLY,
18718            PeriodFreq::Monthly,
18719            PeriodFreq::WEEKLY,
18720            PeriodFreq::Daily,
18721            PeriodFreq::Business,
18722            PeriodFreq::Hourly,
18723            PeriodFreq::Minutely,
18724            PeriodFreq::Secondly,
18725            PeriodFreq::Milliseconds,
18726            PeriodFreq::Microseconds,
18727            PeriodFreq::Nanoseconds,
18728        ] {
18729            assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18730        }
18731    }
18732
18733    /// Anchored aliases parse to their anchor and print back; the shifts move
18734    /// a month count / week start onto the fiscal calendar; a W-MON label
18735    /// spans Tuesday..Monday (live pandas 2.2.3: Period('2024-03-01', 'W-MON')
18736    /// is '2024-02-27/2024-03-04', ordinal 2827; br-frankenpandas-39h5n).
18737    #[test]
18738    fn anchored_period_freqs_parse_print_and_shift_39h5n() {
18739        for month in 1..=12_u8 {
18740            for freq in [PeriodFreq::Annual(month), PeriodFreq::Quarterly(month)] {
18741                assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18742            }
18743        }
18744        for day in 0..7_u8 {
18745            assert_eq!(
18746                PeriodFreq::parse(&PeriodFreq::Weekly(day).alias()),
18747                Some(PeriodFreq::Weekly(day))
18748            );
18749        }
18750        assert_eq!(PeriodFreq::parse("Y-JUN"), Some(PeriodFreq::Annual(6)));
18751        assert_eq!(PeriodFreq::parse("A-JUN"), Some(PeriodFreq::Annual(6)));
18752        assert_eq!(PeriodFreq::parse("q-jan"), Some(PeriodFreq::Quarterly(1)));
18753        assert_eq!(PeriodFreq::parse("W-MON"), Some(PeriodFreq::Weekly(0)));
18754        assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18755        // NEGATIVE: not an anchor, or not an anchorable frequency.
18756        assert_eq!(PeriodFreq::parse("Q-XYZ"), None);
18757        assert_eq!(PeriodFreq::parse("M-JAN"), None);
18758        assert_eq!(PeriodFreq::parse("W-JAN"), None);
18759        assert_eq!(PeriodFreq::Annual(6).fiscal_month_shift(), 6);
18760        assert_eq!(PeriodFreq::Quarterly(1).fiscal_month_shift(), 11);
18761        assert_eq!(PeriodFreq::QUARTERLY.fiscal_month_shift(), 0);
18762        assert_eq!(PeriodFreq::Weekly(0).week_start_shift(), 1);
18763        assert_eq!(PeriodFreq::WEEKLY.week_start_shift(), 0);
18764        assert_eq!(
18765            Period::new(2827, PeriodFreq::Weekly(0)).to_string(),
18766            "2024-02-27/2024-03-04"
18767        );
18768        assert_eq!(
18769            Period::new(2826, PeriodFreq::Weekly(5)).to_string(),
18770            "2024-02-25/2024-03-02"
18771        );
18772        assert_eq!(
18773            Period::new(220, PeriodFreq::Quarterly(1)).to_string(),
18774            "2025Q1"
18775        );
18776    }
18777
18778    /// The three sub-second frequencies pandas' `to_period` accepts and this
18779    /// crate used to reject. Transcribed from live pandas 2.2.3 on
18780    /// `Timestamp('2024-03-15 10:30:45.123456789')`.
18781    #[test]
18782    fn period_freq_subsecond_units_match_pandas() {
18783        // Aliases and resolution words.
18784        assert_eq!(PeriodFreq::Milliseconds.alias(), "ms");
18785        assert_eq!(PeriodFreq::Microseconds.alias(), "us");
18786        assert_eq!(PeriodFreq::Nanoseconds.alias(), "ns");
18787        assert_eq!(PeriodFreq::Milliseconds.resolution(), Some("millisecond"));
18788        assert_eq!(PeriodFreq::Microseconds.resolution(), Some("microsecond"));
18789        assert_eq!(PeriodFreq::Nanoseconds.resolution(), Some("nanosecond"));
18790
18791        // ⚠️ THE ONE CASE-SENSITIVE ALIAS. pandas reads bare "MS" as month start
18792        // and refuses it here, while every other casing of "ms" is milliseconds.
18793        assert_eq!(PeriodFreq::parse("ms"), Some(PeriodFreq::Milliseconds));
18794        assert_eq!(PeriodFreq::parse("Ms"), Some(PeriodFreq::Milliseconds));
18795        assert_eq!(PeriodFreq::parse("mS"), Some(PeriodFreq::Milliseconds));
18796        assert_eq!(PeriodFreq::parse("MS"), None);
18797        // us/ns are case-insensitive in pandas, so both casings resolve.
18798        assert_eq!(PeriodFreq::parse("us"), Some(PeriodFreq::Microseconds));
18799        assert_eq!(PeriodFreq::parse("US"), Some(PeriodFreq::Microseconds));
18800        assert_eq!(PeriodFreq::parse("ns"), Some(PeriodFreq::Nanoseconds));
18801        assert_eq!(PeriodFreq::parse("NS"), Some(PeriodFreq::Nanoseconds));
18802
18803        // Ordinals are unit counts since the epoch; labels pad the fraction to
18804        // the full width of the frequency and never trim trailing zeros.
18805        assert_eq!(
18806            Period::new(1_710_498_645_123, PeriodFreq::Milliseconds).calendar_string(),
18807            "2024-03-15 10:30:45.123"
18808        );
18809        assert_eq!(
18810            Period::new(1_710_498_645_123_456, PeriodFreq::Microseconds).calendar_string(),
18811            "2024-03-15 10:30:45.123456"
18812        );
18813        assert_eq!(
18814            Period::new(1_710_498_645_123_456_789, PeriodFreq::Nanoseconds).calendar_string(),
18815            "2024-03-15 10:30:45.123456789"
18816        );
18817
18818        // A whole-second instant still shows its zero fraction, and the
18819        // pre-epoch ordinals are the FLOOR, not a truncation toward zero:
18820        // Timestamp('1969-12-31 23:59:59.999') at 'ms' has ordinal -1.
18821        assert_eq!(
18822            Period::new(0, PeriodFreq::Milliseconds).calendar_string(),
18823            "1970-01-01 00:00:00.000"
18824        );
18825        assert_eq!(
18826            Period::new(-1, PeriodFreq::Milliseconds).calendar_string(),
18827            "1969-12-31 23:59:59.999"
18828        );
18829        assert_eq!(
18830            Period::new(-1_000, PeriodFreq::Microseconds).calendar_string(),
18831            "1969-12-31 23:59:59.999000"
18832        );
18833        assert_eq!(
18834            Period::new(-999_999, PeriodFreq::Nanoseconds).calendar_string(),
18835            "1969-12-31 23:59:59.999000001"
18836        );
18837    }
18838
18839    #[test]
18840    fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
18841        assert_eq!(PeriodFreq::ANNUAL.alias(), "Y-DEC");
18842        assert_eq!(PeriodFreq::QUARTERLY.alias(), "Q-DEC");
18843        assert_eq!(PeriodFreq::WEEKLY.alias(), "W-SUN");
18844
18845        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
18846        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
18847        assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::ANNUAL));
18848        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
18849        assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18850        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
18851        assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::WEEKLY));
18852    }
18853
18854    #[test]
18855    fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
18856        assert_eq!(PeriodFreq::Hourly.alias(), "h");
18857        assert_eq!(PeriodFreq::Minutely.alias(), "min");
18858        assert_eq!(PeriodFreq::Secondly.alias(), "s");
18859
18860        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
18861        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
18862        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
18863    }
18864
18865    /// The resolution table is the COMPONENT WORD, never the frequency alias.
18866    /// Transcribed from live pandas 2.2.3: `pd.PeriodIndex([ts], freq=f).resolution`
18867    /// for each f, with W and B raising AttributeError.
18868    #[test]
18869    fn period_freq_resolution_is_the_component_word_not_the_alias() {
18870        assert_eq!(PeriodFreq::ANNUAL.resolution(), Some("year"));
18871        assert_eq!(PeriodFreq::QUARTERLY.resolution(), Some("quarter"));
18872        assert_eq!(PeriodFreq::Monthly.resolution(), Some("month"));
18873        assert_eq!(PeriodFreq::Daily.resolution(), Some("day"));
18874        assert_eq!(PeriodFreq::Hourly.resolution(), Some("hour"));
18875        assert_eq!(PeriodFreq::Minutely.resolution(), Some("minute"));
18876        assert_eq!(PeriodFreq::Secondly.resolution(), Some("second"));
18877
18878        // pandas raises AttributeError for these two rather than answering.
18879        assert_eq!(PeriodFreq::WEEKLY.resolution(), None);
18880        assert_eq!(PeriodFreq::Business.resolution(), None);
18881
18882        // The bug this replaces was the alias table copied into the resolution
18883        // slot, so pin the two apart: no frequency may report the same string
18884        // for both. (Every pandas alias is short and lowercase-ish; every
18885        // resolution word is a full English noun -- they never coincide.)
18886        for freq in [
18887            PeriodFreq::ANNUAL,
18888            PeriodFreq::QUARTERLY,
18889            PeriodFreq::Monthly,
18890            PeriodFreq::WEEKLY,
18891            PeriodFreq::Daily,
18892            PeriodFreq::Business,
18893            PeriodFreq::Hourly,
18894            PeriodFreq::Minutely,
18895            PeriodFreq::Secondly,
18896        ] {
18897            assert_ne!(
18898                Some(freq.alias().as_str()),
18899                freq.resolution(),
18900                "{freq:?} reports its alias as its resolution again"
18901            );
18902        }
18903    }
18904
18905    #[test]
18906    fn period_scalar_accessors_match_pandas_star8() {
18907        let period = Period::new(600, PeriodFreq::Monthly);
18908
18909        assert_eq!(period.ordinal(), 600);
18910        assert_eq!(period.freq(), PeriodFreq::Monthly);
18911        assert_eq!(period.freqstr(), "M");
18912    }
18913
18914    #[test]
18915    fn period_multiplied_frequencies_parse_and_roundtrip_tus8r() {
18916        for (alias, canonical, base, multiplier) in [
18917            ("2D", "2D", PeriodFreq::Daily, 2),
18918            ("+3H", "3h", PeriodFreq::Hourly, 3),
18919            ("15min", "15min", PeriodFreq::Minutely, 15),
18920            ("2W-FRI", "2W-FRI", PeriodFreq::Weekly(4), 2),
18921            ("2M", "2M", PeriodFreq::Monthly, 2),
18922            ("2Q-JAN", "2Q-JAN", PeriodFreq::Quarterly(1), 2),
18923            ("2Y-JUN", "2Y-JUN", PeriodFreq::Annual(6), 2),
18924            ("2B", "2B", PeriodFreq::Business, 2),
18925            ("2ms", "2ms", PeriodFreq::Milliseconds, 2),
18926            ("3us", "3us", PeriodFreq::Microseconds, 3),
18927            ("4ns", "4ns", PeriodFreq::Nanoseconds, 4),
18928        ] {
18929            let freq = PeriodFreq::parse(alias).expect("valid multiplied frequency");
18930            assert_eq!(freq.base(), base, "{alias}");
18931            assert_eq!(freq.multiplier(), multiplier, "{alias}");
18932            assert_eq!(freq.alias(), canonical, "{alias}");
18933            assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18934            assert_eq!(freq.resolution(), None);
18935            let encoded = serde_json::to_string(&freq).expect("serializable frequency");
18936            assert_eq!(serde_json::from_str::<PeriodFreq>(&encoded).unwrap(), freq);
18937        }
18938        assert_eq!(PeriodFreq::parse("1D"), Some(PeriodFreq::Daily));
18939        for invalid in ["0D", "-1D", "2MS", "2 3D", "2", "9223372036854775808D"] {
18940            assert_eq!(PeriodFreq::parse(invalid), None, "{invalid}");
18941        }
18942        assert!(
18943            serde_json::from_str::<PeriodFreq>(r#"{"MULTIPLE":{"unit":"DAILY","count":0}}"#,)
18944                .is_err()
18945        );
18946    }
18947
18948    /// Expected boundaries and labels measured against pandas 2.2.3 at
18949    /// Timestamp('2024-02-28 13:47:59.123456789'). The ordinal stays in base
18950    /// units, the label names the first base period, and the end spans n.
18951    #[test]
18952    fn period_multiplied_boundaries_and_labels_match_pandas_tus8r() {
18953        let nanos = 1_709_128_079_123_456_789;
18954        for (alias, ordinal, label, start, end) in [
18955            (
18956                "2D",
18957                19_781,
18958                "2024-02-28",
18959                1_709_078_400_000_000_000,
18960                1_709_251_199_999_999_999,
18961            ),
18962            (
18963                "3h",
18964                474_757,
18965                "2024-02-28 13:00",
18966                1_709_125_200_000_000_000,
18967                1_709_135_999_999_999_999,
18968            ),
18969            (
18970                "15min",
18971                28_485_467,
18972                "2024-02-28 13:47",
18973                1_709_128_020_000_000_000,
18974                1_709_128_919_999_999_999,
18975            ),
18976            (
18977                "2W-FRI",
18978                2_826,
18979                "2024-02-24/2024-03-01",
18980                1_708_732_800_000_000_000,
18981                1_709_942_399_999_999_999,
18982            ),
18983            (
18984                "2M",
18985                649,
18986                "2024-02",
18987                1_706_745_600_000_000_000,
18988                1_711_929_599_999_999_999,
18989            ),
18990            (
18991                "2Q-JAN",
18992                220,
18993                "2025Q1",
18994                1_706_745_600_000_000_000,
18995                1_722_470_399_999_999_999,
18996            ),
18997            (
18998                "2Y-JUN",
18999                54,
19000                "2024",
19001                1_688_169_600_000_000_000,
19002                1_751_327_999_999_999_999,
19003            ),
19004            (
19005                "2B",
19006                14_129,
19007                "2024-02-28",
19008                1_709_078_400_000_000_000,
19009                1_709_251_199_999_999_999,
19010            ),
19011            (
19012                "2ms",
19013                1_709_128_079_123,
19014                "2024-02-28 13:47:59.123",
19015                1_709_128_079_123_000_000,
19016                1_709_128_079_124_999_999,
19017            ),
19018            (
19019                "3us",
19020                1_709_128_079_123_456,
19021                "2024-02-28 13:47:59.123456",
19022                1_709_128_079_123_456_000,
19023                1_709_128_079_123_458_999,
19024            ),
19025            (
19026                "4ns",
19027                nanos,
19028                "2024-02-28 13:47:59.123456789",
19029                nanos,
19030                nanos + 3,
19031            ),
19032        ] {
19033            let freq = PeriodFreq::parse(alias).expect("valid multiplied frequency");
19034            let period = Period::from_timestamp_nanos(nanos, freq).expect("in-range timestamp");
19035            assert_eq!(period.ordinal, ordinal, "{alias}");
19036            assert_eq!(period.to_string(), label, "{alias}");
19037            assert_eq!(period.start_nanos(), Some(start), "{alias}");
19038            assert_eq!(period.end_nanos(), Some(end), "{alias}");
19039            assert_eq!(period.shift(1).ordinal, ordinal + freq.multiplier());
19040            assert_eq!(period.shift(-1).ordinal, ordinal - freq.multiplier());
19041            assert_eq!(period.shift(1).diff(&period), Some(freq.multiplier()));
19042            assert_eq!(
19043                period.asfreq(alias).unwrap().ordinal,
19044                ordinal + freq.multiplier() - 1
19045            );
19046            assert_eq!(period.asfreq_with_how(alias, "start").unwrap(), period);
19047        }
19048
19049        // Business spans exclude weekends, while calendar fields still
19050        // describe the first base day or month of a multi-period span.
19051        let business = Period::new(14_091, PeriodFreq::parse("2B").unwrap());
19052        assert_eq!(business.end_nanos(), Some(1_704_758_399_999_999_999));
19053        assert_eq!(business.shift(1).to_string(), "2024-01-09");
19054        let month = Period::new(649, PeriodFreq::parse("2M").unwrap());
19055        assert_eq!(
19056            (month.year(), month.month(), month.day()),
19057            (Some(2024), Some(2), Some(29))
19058        );
19059        let quarter = Period::new(220, PeriodFreq::parse("2Q-JAN").unwrap());
19060        assert_eq!(
19061            (quarter.year(), quarter.quarter(), quarter.qyear()),
19062            (Some(2024), Some(1), Some(2025))
19063        );
19064    }
19065
19066    #[test]
19067    fn period_multiplied_ranges_keep_negative_ordinals_and_nat_tus8r() {
19068        let freq = PeriodFreq::parse("3h").unwrap();
19069        let before_epoch = Period::from_timestamp_nanos(-1, freq).unwrap();
19070        assert_eq!(before_epoch.ordinal, -1);
19071        assert_eq!(before_epoch.start_nanos(), Some(-3_600_000_000_000));
19072        assert_eq!(before_epoch.end_nanos(), Some(7_199_999_999_999));
19073        assert_eq!(
19074            super::period_range(before_epoch, 3)
19075                .iter()
19076                .map(|period| period.ordinal)
19077                .collect::<Vec<_>>(),
19078            vec![-1, 2, 5],
19079        );
19080        assert!(super::period_range(before_epoch, 0).is_empty());
19081        let nat = Period::new(i64::MIN, freq);
19082        assert!(nat.shift(1).is_nat());
19083        assert!(nat.asfreq("2D").unwrap().is_nat());
19084        assert_eq!(nat.end_nanos(), None);
19085        assert_eq!(Period::new(i64::MAX, freq).end_nanos(), None);
19086        assert_eq!(Period::new(-100, freq).shift(i64::MAX).ordinal, i64::MAX);
19087    }
19088
19089    #[test]
19090    fn period_parse_common_pandas_ordinals_avm08() {
19091        assert_eq!(
19092            Period::parse("2024").unwrap(),
19093            Period::new(54, PeriodFreq::ANNUAL)
19094        );
19095        assert_eq!(
19096            Period::parse("2024Q1").unwrap(),
19097            Period::new(216, PeriodFreq::QUARTERLY)
19098        );
19099        assert_eq!(
19100            Period::parse("2024-01").unwrap(),
19101            Period::new(648, PeriodFreq::Monthly)
19102        );
19103        assert_eq!(
19104            Period::parse("2024-01-15").unwrap(),
19105            Period::new(19_737, PeriodFreq::Daily)
19106        );
19107        assert!(Period::parse("216").is_err());
19108    }
19109
19110    #[test]
19111    fn period_shift_advances_ordinal() {
19112        let q1 = Period::new(216, PeriodFreq::QUARTERLY);
19113        let q2 = q1.shift(1);
19114        assert_eq!(q2.ordinal, 217);
19115        assert_eq!(q2.freq, PeriodFreq::QUARTERLY);
19116        let q0 = q1.shift(-1);
19117        assert_eq!(q0.ordinal, 215);
19118    }
19119
19120    #[test]
19121    fn period_shift_saturates_on_overflow() {
19122        let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
19123        assert_eq!(p.shift(100).ordinal, i64::MAX);
19124        let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
19125        assert_eq!(p.shift(-100).ordinal, i64::MIN);
19126    }
19127
19128    #[test]
19129    fn period_diff_returns_period_count() {
19130        let a = Period::new(216, PeriodFreq::QUARTERLY);
19131        let b = Period::new(220, PeriodFreq::QUARTERLY);
19132        assert_eq!(b.diff(&a), Some(4));
19133        assert_eq!(a.diff(&b), Some(-4));
19134    }
19135
19136    #[test]
19137    fn period_diff_rejects_mismatched_freq() {
19138        let monthly = Period::new(100, PeriodFreq::Monthly);
19139        let quarterly = Period::new(100, PeriodFreq::QUARTERLY);
19140        assert_eq!(monthly.diff(&quarterly), None);
19141        assert_eq!(quarterly.diff(&monthly), None);
19142    }
19143
19144    #[test]
19145    fn period_cmp_same_freq_respects_ordinal_order() {
19146        use std::cmp::Ordering;
19147        let a = Period::new(10, PeriodFreq::Monthly);
19148        let b = Period::new(20, PeriodFreq::Monthly);
19149        assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
19150        assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
19151        assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
19152    }
19153
19154    #[test]
19155    fn period_cmp_cross_freq_returns_none() {
19156        let m = Period::new(1, PeriodFreq::Monthly);
19157        let q = Period::new(1, PeriodFreq::QUARTERLY);
19158        assert_eq!(m.cmp_same_freq(&q), None);
19159    }
19160
19161    #[test]
19162    fn period_arithmetic_matches_seeded_oracles_bac28() {
19163        use std::cmp::Ordering;
19164
19165        fn next(seed: &mut u64) -> u64 {
19166            *seed = seed
19167                .wrapping_mul(2862933555777941757)
19168                .wrapping_add(3037000493);
19169            *seed
19170        }
19171
19172        fn freq_for(raw: u64) -> PeriodFreq {
19173            // All TWELVE frequencies. This stopped at nine, so no property
19174            // test here ever generated a sub-second period.
19175            match raw % 12 {
19176                0 => PeriodFreq::ANNUAL,
19177                1 => PeriodFreq::QUARTERLY,
19178                2 => PeriodFreq::Monthly,
19179                3 => PeriodFreq::WEEKLY,
19180                4 => PeriodFreq::Daily,
19181                5 => PeriodFreq::Business,
19182                6 => PeriodFreq::Hourly,
19183                7 => PeriodFreq::Minutely,
19184                8 => PeriodFreq::Secondly,
19185                9 => PeriodFreq::Milliseconds,
19186                10 => PeriodFreq::Microseconds,
19187                _ => PeriodFreq::Nanoseconds,
19188            }
19189        }
19190
19191        fn different_freq(freq: PeriodFreq) -> PeriodFreq {
19192            match freq {
19193                PeriodFreq::Annual(_) => PeriodFreq::QUARTERLY,
19194                PeriodFreq::Quarterly(_) => PeriodFreq::Monthly,
19195                PeriodFreq::Monthly => PeriodFreq::WEEKLY,
19196                PeriodFreq::Weekly(_) => PeriodFreq::Daily,
19197                PeriodFreq::Daily => PeriodFreq::Business,
19198                PeriodFreq::Business => PeriodFreq::Hourly,
19199                PeriodFreq::Hourly => PeriodFreq::Minutely,
19200                PeriodFreq::Minutely => PeriodFreq::Secondly,
19201                // The cycle closes through the sub-second units, so every
19202                // frequency still maps to a DIFFERENT one — the only property
19203                // this helper owes its callers.
19204                PeriodFreq::Secondly => PeriodFreq::Milliseconds,
19205                PeriodFreq::Milliseconds => PeriodFreq::Microseconds,
19206                PeriodFreq::Microseconds => PeriodFreq::Nanoseconds,
19207                PeriodFreq::Nanoseconds => PeriodFreq::ANNUAL,
19208                PeriodFreq::Multiple(_) => freq.base(),
19209            }
19210        }
19211
19212        fn assert_period_case(
19213            case: usize,
19214            freq: PeriodFreq,
19215            ordinal: i64,
19216            shift_by: i64,
19217            other_ordinal: i64,
19218        ) {
19219            let period = Period::new(ordinal, freq);
19220            let shifted = period.shift(shift_by);
19221            assert_eq!(
19222                shifted.ordinal,
19223                ordinal.saturating_add(shift_by),
19224                "case {case}: shift ordinal"
19225            );
19226            assert_eq!(shifted.freq, freq, "case {case}: shift freq");
19227
19228            let same_freq_other = Period::new(other_ordinal, freq);
19229            assert_eq!(
19230                period.diff(&same_freq_other),
19231                Some(ordinal.saturating_sub(other_ordinal)),
19232                "case {case}: same-freq diff"
19233            );
19234            assert_eq!(
19235                period.cmp_same_freq(&same_freq_other),
19236                Some(ordinal.cmp(&other_ordinal)),
19237                "case {case}: same-freq cmp"
19238            );
19239
19240            let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
19241            assert_eq!(
19242                period.diff(&cross_freq_other),
19243                None,
19244                "case {case}: cross-freq diff"
19245            );
19246            assert_eq!(
19247                period.cmp_same_freq(&cross_freq_other),
19248                None,
19249                "case {case}: cross-freq cmp"
19250            );
19251        }
19252
19253        assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
19254        assert_period_case(
19255            usize::MAX - 1,
19256            PeriodFreq::Daily,
19257            i64::MIN + 2,
19258            -10,
19259            i64::MAX,
19260        );
19261        assert_eq!(
19262            Period::new(10, PeriodFreq::Monthly)
19263                .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
19264            Some(Ordering::Equal)
19265        );
19266
19267        let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
19268        for case in 0..260 {
19269            let freq = freq_for(next(&mut seed));
19270            let ordinal = match case % 53 {
19271                0 => i64::MAX - (next(&mut seed) % 8) as i64,
19272                1 => i64::MIN + (next(&mut seed) % 8) as i64,
19273                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
19274            };
19275            let shift_by = match case % 47 {
19276                0 => 512,
19277                1 => -512,
19278                _ => (next(&mut seed) % 4097) as i64 - 2048,
19279            };
19280            let other_ordinal = match case % 41 {
19281                0 => i64::MAX,
19282                1 => i64::MIN,
19283                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
19284            };
19285            assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
19286        }
19287    }
19288
19289    #[test]
19290    fn period_display_is_pandas_calendar_string() {
19291        // Ordinal 216 on the quarterly axis (1970Q1 == 0) is 1970 + 54y = 2024Q1.
19292        assert_eq!(
19293            Period::new(216, PeriodFreq::QUARTERLY).to_string(),
19294            "2024Q1"
19295        );
19296        // 1970 + 54 == 2024 on the annual axis.
19297        assert_eq!(Period::new(54, PeriodFreq::ANNUAL).to_string(), "2024");
19298        // 1970-01 == 0 -> 2024-03 is 54*12 + 2 == 650 months.
19299        assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
19300        // Day 0 == 1970-01-01; 2024-01-15.
19301        assert_eq!(
19302            Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
19303            "2024-01-15"
19304        );
19305        assert_eq!(
19306            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
19307            "NaT"
19308        );
19309    }
19310
19311    /// The two frequencies whose ordinal is NOT a day count. Both rendered
19312    /// through `civil_from_days` and came out decades wrong; the test above
19313    /// covered Y/Q/M/D and never touched either, which is how it survived.
19314    ///
19315    /// Every string is `str(pd.Period(ordinal=..., freq=...))` on live pandas
19316    /// 2.2.3, and FrankenPandas' own ordinals were confirmed to agree with
19317    /// pandas' at each sampled date before these were taken.
19318    #[test]
19319    fn weekly_and_business_periods_do_not_index_days() {
19320        // ⚠️ WEEKLY IS A RANGE, not a date: the ordinal counts WEEKS from the
19321        // Monday 1969-12-22, and pandas prints the seven days it spans.
19322        // Ordinal 2829 is the week of 2024-03-15 and used to render
19323        // "1977-09-30" — the result of reading a week count as a day count.
19324        for (ordinal, want) in [
19325            (0_i64, "1969-12-22/1969-12-28"),
19326            (1, "1969-12-29/1970-01-04"),
19327            (2829, "2024-03-11/2024-03-17"),
19328            (1540, "1999-06-28/1999-07-04"),
19329            (15237, "2261-12-30/2262-01-05"),
19330            // Pre-epoch, where Euclidean division matters.
19331            (-1, "1969-12-15/1969-12-21"),
19332            (-2829, "1915-10-04/1915-10-10"),
19333        ] {
19334            assert_eq!(
19335                Period::new(ordinal, PeriodFreq::WEEKLY).to_string(),
19336                want,
19337                "weekly ordinal {ordinal}"
19338            );
19339        }
19340
19341        // ⚠️ BUSINESS COUNTS BUSINESS DAYS — five per week — so consecutive
19342        // ordinals skip the weekend. Ordinal 14141 is 2024-03-15 and used to
19343        // render "2008-09-19".
19344        for (ordinal, want) in [
19345            (0_i64, "1970-01-01"), // a Thursday: the epoch anchors the cycle
19346            (1, "1970-01-02"),     // Friday
19347            (2, "1970-01-05"),     // Monday — the weekend is SKIPPED
19348            (3, "1970-01-06"),
19349            (4, "1970-01-07"),
19350            (5, "1970-01-08"),
19351            (14141, "2024-03-15"),
19352            (76179, "2262-01-01"),
19353            // A Sunday input rolls FORWARD when the ordinal is taken, so 7697
19354            // is the Monday 1999-07-05 rather than 1999-07-04.
19355            (7697, "1999-07-05"),
19356            (-1, "1969-12-31"),
19357            (-5, "1969-12-25"),
19358            (-6, "1969-12-24"),
19359        ] {
19360            assert_eq!(
19361                Period::new(ordinal, PeriodFreq::Business).to_string(),
19362                want,
19363                "business ordinal {ordinal}"
19364            );
19365        }
19366
19367        // Five business ordinals per seven calendar days, checked as a property
19368        // rather than as a table: the same arithmetic the forward map in
19369        // fp-index uses, read backwards.
19370        for ordinal in -400_i64..400 {
19371            let rendered = Period::new(ordinal, PeriodFreq::Business).to_string();
19372            let later = Period::new(ordinal + 5, PeriodFreq::Business).to_string();
19373            assert_ne!(rendered, later, "business ordinals must not repeat");
19374        }
19375
19376        assert_eq!(Period::new(i64::MIN, PeriodFreq::WEEKLY).to_string(), "NaT");
19377        assert_eq!(
19378            Period::new(i64::MIN, PeriodFreq::Business).to_string(),
19379            "NaT"
19380        );
19381    }
19382
19383    fn period_display_former_profile(period: &Period) -> String {
19384        let calendar = period.calendar_string();
19385        let mut rendered = String::new();
19386        rendered.push_str(&calendar);
19387        rendered
19388    }
19389
19390    fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
19391        use std::{hint::black_box, time::Instant};
19392
19393        let started = Instant::now();
19394        let mut checksum = 0usize;
19395        for period in periods {
19396            let rendered = render(black_box(period));
19397            checksum = checksum.wrapping_add(rendered.len());
19398            drop(black_box(rendered));
19399        }
19400        black_box(checksum);
19401        started.elapsed().as_nanos()
19402    }
19403
19404    #[test]
19405    #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
19406    fn profile_period_display_direct_sink_ab_6pqra() {
19407        const FREQUENCIES: [PeriodFreq; 9] = [
19408            PeriodFreq::ANNUAL,
19409            PeriodFreq::QUARTERLY,
19410            PeriodFreq::Monthly,
19411            PeriodFreq::WEEKLY,
19412            PeriodFreq::Daily,
19413            PeriodFreq::Business,
19414            PeriodFreq::Hourly,
19415            PeriodFreq::Minutely,
19416            PeriodFreq::Secondly,
19417        ];
19418        const SAMPLES: usize = 10;
19419
19420        let periods = (0..65_536)
19421            .map(|index| {
19422                let ordinal = if index % 4093 == 0 {
19423                    i64::MIN
19424                } else {
19425                    ((index as i64 * 7_919) % 4_000_001) - 2_000_000
19426                };
19427                Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
19428            })
19429            .collect::<Vec<_>>();
19430
19431        for period in &periods {
19432            assert_eq!(period_display_former_profile(period), period.to_string());
19433        }
19434
19435        for _ in 0..2 {
19436            measure_period_renderer(&periods, period_display_former_profile);
19437            measure_period_renderer(&periods, Period::to_string);
19438        }
19439
19440        let mut former_ns = Vec::with_capacity(SAMPLES);
19441        let mut public_ns = Vec::with_capacity(SAMPLES);
19442        for sample in 0..SAMPLES {
19443            if sample % 2 == 0 {
19444                former_ns.push(measure_period_renderer(
19445                    &periods,
19446                    period_display_former_profile,
19447                ));
19448                public_ns.push(measure_period_renderer(&periods, Period::to_string));
19449            } else {
19450                public_ns.push(measure_period_renderer(&periods, Period::to_string));
19451                former_ns.push(measure_period_renderer(
19452                    &periods,
19453                    period_display_former_profile,
19454                ));
19455            }
19456        }
19457        former_ns.sort_unstable();
19458        public_ns.sort_unstable();
19459        let former_p50 = former_ns[SAMPLES / 2];
19460        let public_p50 = public_ns[SAMPLES / 2];
19461        let former_p95 = former_ns[SAMPLES - 1];
19462        let public_p95 = public_ns[SAMPLES - 1];
19463        println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
19464        println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
19465        println!(
19466            "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
19467            former_p50 as f64 / public_p50 as f64
19468        );
19469        println!(
19470            "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
19471            former_p95 as f64 / public_p95 as f64
19472        );
19473    }
19474
19475    #[cfg(test)]
19476    fn fp_days(ymd: &str) -> i64 {
19477        Period::parse(ymd).expect("daily period").ordinal
19478    }
19479
19480    #[test]
19481    fn period_roundtrips_through_serde_json() {
19482        let p = Period::new(42, PeriodFreq::WEEKLY);
19483        let json = serde_json::to_string(&p).expect("serialize");
19484        let back: Period = serde_json::from_str(&json).expect("deserialize");
19485        assert_eq!(p, back);
19486    }
19487
19488    // ── period_range tests (br-frankenpandas-2jef — epoj Phase 2) ───────
19489
19490    use super::period_range;
19491
19492    #[test]
19493    fn period_range_zero_periods_is_empty() {
19494        let start = Period::new(216, PeriodFreq::QUARTERLY);
19495        assert!(period_range(start, 0).is_empty());
19496    }
19497
19498    #[test]
19499    fn period_range_single_period_returns_start_only() {
19500        let start = Period::new(216, PeriodFreq::QUARTERLY);
19501        let r = period_range(start, 1);
19502        assert_eq!(r.len(), 1);
19503        assert_eq!(r[0], start);
19504    }
19505
19506    #[test]
19507    fn period_range_increments_ordinal_by_one_per_step() {
19508        let start = Period::new(216, PeriodFreq::QUARTERLY);
19509        let r = period_range(start, 4);
19510        assert_eq!(r.len(), 4);
19511        assert_eq!(r[0].ordinal, 216);
19512        assert_eq!(r[1].ordinal, 217);
19513        assert_eq!(r[2].ordinal, 218);
19514        assert_eq!(r[3].ordinal, 219);
19515    }
19516
19517    #[test]
19518    fn period_range_preserves_frequency() {
19519        let start = Period::new(0, PeriodFreq::Monthly);
19520        let r = period_range(start, 12);
19521        assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
19522    }
19523
19524    #[test]
19525    fn period_range_negative_starting_ordinal_works() {
19526        // Ordinal axis is signed — pre-epoch periods are valid.
19527        let start = Period::new(-3, PeriodFreq::ANNUAL);
19528        let r = period_range(start, 5);
19529        assert_eq!(
19530            r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
19531            vec![-3, -2, -1, 0, 1]
19532        );
19533    }
19534
19535    #[test]
19536    fn period_range_large_n_does_not_panic() {
19537        // 1024 monthly periods — large enough to catch any allocation bug.
19538        let start = Period::new(0, PeriodFreq::Monthly);
19539        let r = period_range(start, 1024);
19540        assert_eq!(r.len(), 1024);
19541        assert_eq!(r[1023].ordinal, 1023);
19542    }
19543
19544    #[test]
19545    fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
19546        fn next(seed: &mut u64) -> u64 {
19547            *seed = seed
19548                .wrapping_mul(6364136223846793005)
19549                .wrapping_add(1442695040888963407);
19550            *seed
19551        }
19552
19553        fn freq_for(raw: u64) -> PeriodFreq {
19554            // All TWELVE frequencies. This stopped at nine, so no property
19555            // test here ever generated a sub-second period.
19556            match raw % 12 {
19557                0 => PeriodFreq::ANNUAL,
19558                1 => PeriodFreq::QUARTERLY,
19559                2 => PeriodFreq::Monthly,
19560                3 => PeriodFreq::WEEKLY,
19561                4 => PeriodFreq::Daily,
19562                5 => PeriodFreq::Business,
19563                6 => PeriodFreq::Hourly,
19564                7 => PeriodFreq::Minutely,
19565                8 => PeriodFreq::Secondly,
19566                9 => PeriodFreq::Milliseconds,
19567                10 => PeriodFreq::Microseconds,
19568                _ => PeriodFreq::Nanoseconds,
19569            }
19570        }
19571
19572        fn assert_oracle_case(case: usize, start: Period, periods: usize) {
19573            let got = period_range(start, periods);
19574            assert_eq!(got.len(), periods, "case {case}: length");
19575
19576            for (position, period) in got.iter().enumerate() {
19577                let expected_ordinal = start.ordinal.saturating_add(position as i64);
19578                assert_eq!(
19579                    period.ordinal, expected_ordinal,
19580                    "case {case}: ordinal at {position}"
19581                );
19582                assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
19583            }
19584        }
19585
19586        assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
19587        assert_oracle_case(
19588            usize::MAX - 1,
19589            Period::new(i64::MAX - 3, PeriodFreq::Daily),
19590            8,
19591        );
19592
19593        let mut seed = 0x9e21_0d1c_5eed_0421_u64;
19594        for case in 0..260 {
19595            let freq = freq_for(next(&mut seed));
19596            let periods = (next(&mut seed) % 80) as usize;
19597            let start_ordinal = if case % 37 == 0 {
19598                i64::MAX - 7
19599            } else {
19600                (next(&mut seed) % 20_001) as i64 - 10_000
19601            };
19602            assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
19603        }
19604    }
19605
19606    // ── interval_range tests (br-frankenpandas-xaom) ────────────────────
19607
19608    use super::{TypeError, interval_range, interval_range_by_periods, interval_range_by_step};
19609
19610    #[test]
19611    fn interval_range_by_periods_matches_pandas_default_case() {
19612        // pd.interval_range(0, 10, periods=5) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
19613        let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
19614        assert_eq!(bins.len(), 5);
19615        for (i, bin) in bins.iter().enumerate() {
19616            assert_eq!(bin.left, (i as f64) * 2.0);
19617            assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
19618            assert_eq!(bin.closed, IntervalClosed::Right);
19619        }
19620    }
19621
19622    #[test]
19623    fn interval_range_by_periods_final_edge_is_exact_end() {
19624        // Guards against accumulated float drift on the last right edge.
19625        let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
19626        assert_eq!(bins.last().unwrap().right, 1.0);
19627    }
19628
19629    #[test]
19630    fn interval_range_by_periods_zero_periods_is_empty() {
19631        assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
19632    }
19633
19634    #[test]
19635    fn interval_range_by_periods_reversed_range_is_empty() {
19636        // pandas: pd.interval_range(10, 0, periods=5) → IntervalIndex([]).
19637        assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
19638    }
19639
19640    #[test]
19641    fn interval_range_by_periods_preserves_closed_policy() {
19642        for closed in [
19643            IntervalClosed::Left,
19644            IntervalClosed::Right,
19645            IntervalClosed::Both,
19646            IntervalClosed::Neither,
19647        ] {
19648            let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
19649            assert!(bins.iter().all(|b| b.closed == closed));
19650        }
19651    }
19652
19653    #[test]
19654    fn interval_range_by_step_matches_pandas_default_case() {
19655        // pd.interval_range(0, 10, freq=2) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
19656        let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
19657        assert_eq!(bins.len(), 5);
19658        assert_eq!(bins[0].left, 0.0);
19659        assert_eq!(bins[4].right, 10.0);
19660    }
19661
19662    #[test]
19663    fn interval_range_by_step_rejects_non_positive_step() {
19664        assert!(matches!(
19665            interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
19666            Err(TypeError::InvalidIntervalStep { .. })
19667        ));
19668        assert!(matches!(
19669            interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
19670            Err(TypeError::InvalidIntervalStep { .. })
19671        ));
19672        assert!(matches!(
19673            interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
19674            Err(TypeError::InvalidIntervalStep { .. })
19675        ));
19676        assert!(matches!(
19677            interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
19678            Err(TypeError::InvalidIntervalStep { .. })
19679        ));
19680    }
19681
19682    #[test]
19683    fn interval_range_by_step_rejects_non_dividing_step() {
19684        // pandas: pd.interval_range(0, 10, freq=3) → ValueError
19685        // (span=10 not divisible by step=3). Reject with IntervalStepDoesNotDivide.
19686        assert!(matches!(
19687            interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
19688            Err(TypeError::IntervalStepDoesNotDivide { .. })
19689        ));
19690    }
19691
19692    #[test]
19693    fn interval_range_by_step_reversed_range_is_empty() {
19694        let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
19695        assert!(bins.is_empty());
19696    }
19697
19698    #[test]
19699    fn interval_range_by_step_degenerate_zero_span_is_empty() {
19700        let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
19701        assert!(bins.is_empty());
19702    }
19703
19704    #[test]
19705    fn interval_range_by_step_accepts_float_step_within_tolerance() {
19706        // step=0.1 ten times == 1.0 but float arithmetic produces 0.9999...
19707        let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
19708        assert_eq!(bins.len(), 10);
19709        assert_eq!(bins.last().unwrap().right, 1.0);
19710    }
19711
19712    #[test]
19713    fn interval_range_unified_api_tests() {
19714        // Case 1: start, end, periods
19715        let r1 = interval_range(Some(0.0), Some(10.0), Some(5), None, None).expect("ok");
19716        assert_eq!(r1.len(), 5);
19717        assert_eq!(r1[0].left, 0.0);
19718        assert_eq!(r1[0].right, 2.0);
19719        assert_eq!(r1[4].right, 10.0);
19720        assert_eq!(r1[0].closed, IntervalClosed::Right);
19721
19722        // Case 2: start, end, freq
19723        let r2 = interval_range(Some(0.0), Some(10.0), None, Some(2.0), None).expect("ok");
19724        assert_eq!(r2.len(), 5);
19725        assert_eq!(r2[0].left, 0.0);
19726        assert_eq!(r2[4].right, 10.0);
19727
19728        // Case 3: start, periods, freq
19729        let r3 = interval_range(
19730            Some(0.0),
19731            None,
19732            Some(5),
19733            Some(2.0),
19734            Some(IntervalClosed::Both),
19735        )
19736        .expect("ok");
19737        assert_eq!(r3.len(), 5);
19738        assert_eq!(r3[0].left, 0.0);
19739        assert_eq!(r3[4].right, 10.0);
19740        assert_eq!(r3[0].closed, IntervalClosed::Both);
19741
19742        // Case 4: end, periods, freq
19743        let r4 = interval_range(
19744            None,
19745            Some(10.0),
19746            Some(5),
19747            Some(2.0),
19748            Some(IntervalClosed::Left),
19749        )
19750        .expect("ok");
19751        assert_eq!(r4.len(), 5);
19752        assert_eq!(r4[0].left, 0.0);
19753        assert_eq!(r4[4].right, 10.0);
19754        assert_eq!(r4[0].closed, IntervalClosed::Left);
19755
19756        // Errors: not exactly 3 arguments
19757        assert!(matches!(
19758            interval_range(None, None, None, None, None),
19759            Err(TypeError::IntervalRangeParameterCount)
19760        ));
19761        assert!(matches!(
19762            interval_range(Some(0.0), Some(10.0), None, None, None),
19763            Err(TypeError::IntervalRangeParameterCount)
19764        ));
19765        assert!(matches!(
19766            interval_range(Some(0.0), Some(10.0), Some(5), Some(2.0), None),
19767            Err(TypeError::IntervalRangeParameterCount)
19768        ));
19769
19770        // Errors: non-positive freq
19771        assert!(matches!(
19772            interval_range(Some(0.0), None, Some(5), Some(-1.0), None),
19773            Err(TypeError::InvalidIntervalStep { .. })
19774        ));
19775        assert!(matches!(
19776            interval_range(Some(0.0), None, Some(5), Some(0.0), None),
19777            Err(TypeError::InvalidIntervalStep { .. })
19778        ));
19779    }
19780
19781    #[test]
19782    fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
19783        // Differential vs independent interval edge oracles
19784        // (br-frankenpandas-t9ozf). Seeded LCG, no mocks.
19785        fn next(seed: &mut u64) -> u64 {
19786            *seed = seed
19787                .wrapping_mul(2862933555777941757)
19788                .wrapping_add(3037000493);
19789            *seed
19790        }
19791
19792        fn closed_for(raw: u64) -> IntervalClosed {
19793            match raw % 4 {
19794                0 => IntervalClosed::Left,
19795                1 => IntervalClosed::Right,
19796                2 => IntervalClosed::Both,
19797                _ => IntervalClosed::Neither,
19798            }
19799        }
19800
19801        fn assert_interval(
19802            case: usize,
19803            kind: &str,
19804            pos: usize,
19805            actual: &Interval,
19806            expected: &Interval,
19807        ) {
19808            assert!(
19809                (actual.left - expected.left).abs() < 1e-12,
19810                "case={case} kind={kind} pos={pos}: expected left {}, got {}",
19811                expected.left,
19812                actual.left
19813            );
19814            assert!(
19815                (actual.right - expected.right).abs() < 1e-12,
19816                "case={case} kind={kind} pos={pos}: expected right {}, got {}",
19817                expected.right,
19818                actual.right
19819            );
19820            assert_eq!(
19821                actual.closed, expected.closed,
19822                "case={case} kind={kind} pos={pos}: closed mismatch"
19823            );
19824        }
19825
19826        fn expected_by_periods(
19827            start: f64,
19828            end: f64,
19829            periods: usize,
19830            closed: IntervalClosed,
19831        ) -> Vec<Interval> {
19832            if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
19833                return Vec::new();
19834            }
19835            let step = (end - start) / periods as f64;
19836            (0..periods)
19837                .map(|pos| {
19838                    let left = start + step * pos as f64;
19839                    let right = if pos + 1 == periods {
19840                        end
19841                    } else {
19842                        start + step * (pos + 1) as f64
19843                    };
19844                    Interval::new(left, right, closed)
19845                })
19846                .collect()
19847        }
19848
19849        fn expected_by_step(
19850            start: f64,
19851            end: f64,
19852            step: f64,
19853            closed: IntervalClosed,
19854        ) -> Vec<Interval> {
19855            if start >= end {
19856                return Vec::new();
19857            }
19858            let count = ((end - start) / step).round() as usize;
19859            (0..count)
19860                .map(|pos| {
19861                    let left = start + step * pos as f64;
19862                    let right = if pos + 1 == count {
19863                        end
19864                    } else {
19865                        start + step * (pos + 1) as f64
19866                    };
19867                    Interval::new(left, right, closed)
19868                })
19869                .collect()
19870        }
19871
19872        assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
19873        assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
19874        assert!(
19875            interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
19876                .expect("zero span")
19877                .is_empty()
19878        );
19879
19880        let mut seed = 0x171e_7a11_c0de_5eed_u64;
19881        for case in 0..220 {
19882            let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
19883            let periods = (next(&mut seed) % 24 + 1) as usize;
19884            let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
19885            let end = start + width;
19886            let closed = closed_for(next(&mut seed));
19887
19888            let actual = interval_range_by_periods(start, end, periods, closed);
19889            let expected = expected_by_periods(start, end, periods, closed);
19890            assert_eq!(
19891                actual.len(),
19892                expected.len(),
19893                "case={case} periods: length mismatch"
19894            );
19895            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
19896                assert_interval(case, "periods", pos, actual, expected);
19897            }
19898
19899            let step_count = (next(&mut seed) % 20 + 1) as usize;
19900            let step = (next(&mut seed) % 25 + 1) as f64;
19901            let step_end = start + step * step_count as f64;
19902            let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
19903            let expected = expected_by_step(start, step_end, step, closed);
19904            assert_eq!(
19905                actual.len(),
19906                expected.len(),
19907                "case={case} step: length mismatch"
19908            );
19909            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
19910                assert_interval(case, "step", pos, actual, expected);
19911            }
19912        }
19913    }
19914
19915    // ── Timedelta arithmetic tests (br-frankenpandas-4r56 Phase 1) ──────
19916
19917    use super::Timedelta;
19918
19919    #[test]
19920    fn timedelta_add_sums_non_nat() {
19921        let one_hour = Timedelta::NANOS_PER_HOUR;
19922        let one_day = Timedelta::NANOS_PER_DAY;
19923        assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
19924    }
19925
19926    #[test]
19927    fn timedelta_add_propagates_nat() {
19928        assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
19929        assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
19930        assert_eq!(
19931            Timedelta::add(Timedelta::NAT, Timedelta::NAT),
19932            Timedelta::NAT
19933        );
19934    }
19935
19936    #[test]
19937    fn timedelta_add_returns_nat_on_overflow() {
19938        // CORRECTED br-frankenpandas-lgyy8. This test previously asserted
19939        // `add(i64::MAX - 10, 100) == i64::MAX`, i.e. that positive overflow
19940        // yields a finite, plausible duration. Live pandas 2.2.3 raises
19941        // OverflowError for `pd.Timedelta.max + pd.Timedelta('1ns')` and never
19942        // returns a fabricated finite value, so the old expectation encoded a
19943        // fail-open bug. Overflow is now NaT in BOTH directions.
19944        assert_eq!(Timedelta::add(i64::MAX - 10, 100), Timedelta::NAT);
19945        // Negative side is unchanged: i64::MIN IS the NaT sentinel, so this
19946        // already surfaced as missing (pandas: Timedelta.min + -1ns -> NaT).
19947        assert_eq!(Timedelta::add(i64::MIN + 10, -100), Timedelta::NAT);
19948    }
19949
19950    #[test]
19951    fn timedelta_sub_subtracts_non_nat() {
19952        let one_hour = Timedelta::NANOS_PER_HOUR;
19953        assert_eq!(
19954            Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
19955            one_hour - Timedelta::NANOS_PER_MIN
19956        );
19957    }
19958
19959    #[test]
19960    fn timedelta_sub_propagates_nat() {
19961        assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
19962        assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
19963    }
19964
19965    #[test]
19966    fn timedelta_neg_flips_sign_non_nat() {
19967        assert_eq!(Timedelta::neg(5), -5);
19968        assert_eq!(Timedelta::neg(-5), 5);
19969        assert_eq!(Timedelta::neg(0), 0);
19970    }
19971
19972    #[test]
19973    fn timedelta_neg_preserves_nat() {
19974        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
19975    }
19976
19977    #[test]
19978    fn timedelta_abs_returns_magnitude() {
19979        assert_eq!(Timedelta::abs(-5), 5);
19980        assert_eq!(Timedelta::abs(5), 5);
19981        assert_eq!(Timedelta::abs(0), 0);
19982        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
19983    }
19984
19985    #[test]
19986    fn neg_and_abs_at_the_representable_floor_are_not_overflow_fyr1z() {
19987        // br-frankenpandas-fyr1z. Until this test existed, `neg`/`abs` were
19988        // only exercised at ±5 and 0, and the doc comment on `neg` asserted
19989        // the OPPOSITE of pandas: "pandas: `-pd.Timedelta.min` is NaT since
19990        // min == -max - 1 cannot be negated". Both halves are false, so an
19991        // implementer trusting the comment could have replaced
19992        // `saturating_neg()` with a NaT arm and broken parity without failing
19993        // a single existing assertion. Measured against the installed oracle,
19994        // pandas 2.2.3:
19995        //   pd.Timedelta.min.value                 == -9223372036854775807
19996        //   -pd.Timedelta.min                      -> Timedelta.max (NOT NaT)
19997        //   abs(pd.Timedelta.min)                  -> Timedelta.max (NOT NaT)
19998        //   -Series([Timedelta.min])               -> [Timedelta.max]
19999        //   Series([Timedelta.min]).abs()          -> [Timedelta.max]
20000        //
20001        // The reason there is no overflow to handle: pandas' representable
20002        // range is symmetric about zero because i64::MIN is spent on the NaT
20003        // sentinel, exactly as it is here.
20004        const MAX: i64 = i64::MAX;
20005        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
20006
20007        // The range really is symmetric — this is the premise the old comment
20008        // denied, and everything below follows from it.
20009        assert_eq!(MIN_OK, -MAX);
20010        assert_eq!(Timedelta::NAT, i64::MIN);
20011
20012        // The cases the false comment would have turned into NaT.
20013        assert_eq!(Timedelta::neg(MIN_OK), MAX);
20014        assert_eq!(Timedelta::neg(MAX), MIN_OK);
20015        assert_eq!(Timedelta::abs(MIN_OK), MAX);
20016        assert_eq!(Timedelta::abs(MAX), MAX);
20017
20018        // Round-tripping the floor must be exact, not sticky at a saturation
20019        // clamp: a `saturating_*` impl that ever clamped would land on
20020        // i64::MIN here and read as NaT.
20021        assert_eq!(Timedelta::neg(Timedelta::neg(MIN_OK)), MIN_OK);
20022        assert_ne!(Timedelta::neg(MIN_OK), Timedelta::NAT);
20023        assert_ne!(Timedelta::abs(MIN_OK), Timedelta::NAT);
20024
20025        // NaT itself is still the one input that stays NaT — the guard, not a
20026        // saturation branch, is what handles it.
20027        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
20028        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
20029    }
20030
20031    #[test]
20032    fn overflow_divergence_surface_is_only_where_pandas_refuses_fyr1z() {
20033        // br-frankenpandas-fyr1z, the decision bead for DISC-018. The bead was
20034        // filed on the premise "pandas raises; FP returns NaT", which would
20035        // make EVERY overflow a divergence. Probing live pandas 2.2.3 refutes
20036        // that: on the vectorized surface — the one users actually meet —
20037        // pandas returns NaT itself in several of these cases, so FP already
20038        // agrees there and a blanket "STRICT raises" mode would INTRODUCE
20039        // divergence rather than remove it.
20040        //
20041        // This test pins the agreement half. It is the negative control for
20042        // the divergence half already pinned by
20043        // `arithmetic_overflow_never_fabricates_a_finite_value_lgyy8`.
20044        const MAX: i64 = i64::MAX;
20045        const MIN_OK: i64 = i64::MIN + 1;
20046
20047        // ── AGREEMENT: pandas returns NaT here too, measured ───────────────
20048        // Series([Timedelta.max]) / 0    -> [NaT]
20049        // Series([Timedelta.max]) // 0   -> [NaT]
20050        // Series([Timedelta.max]) / 0.0  -> [NaT]
20051        assert_eq!(Timedelta::div_scalar(MAX, 0), Timedelta::NAT);
20052        assert_eq!(Timedelta::div_scalar(MIN_OK, 0), Timedelta::NAT);
20053        assert_eq!(Timedelta::div_scalar(0, 0), Timedelta::NAT);
20054
20055        // Series([Timedelta.min]) - Timedelta('1ns') -> [NaT], because the
20056        // result lands exactly on the i64::MIN sentinel. FP and pandas agree
20057        // — but only by SENTINEL COLLISION, not by policy. One further step
20058        // (`min - 2ns`) is `OverflowError: Overflow in int64 addition` in
20059        // pandas while FP still says NaT, which is the real divergence. A
20060        // test that only checked the 1ns case would therefore prove nothing;
20061        // both depths are asserted so the pair stays honest.
20062        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT); // pandas: NaT
20063        assert_eq!(Timedelta::sub(MIN_OK, 2), Timedelta::NAT); // pandas: RAISES
20064        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
20065        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(2).is_nat());
20066
20067        // ── DIVERGENCE: pandas refuses, FP surfaces NaT ────────────────────
20068        // Kept adjacent to the agreement cases so the boundary between the
20069        // two halves is visible in one place; DISC-018 is the prose record.
20070        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
20071        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
20072        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
20073
20074        // ── CONTROL: representable results are untouched by any of this ────
20075        assert_eq!(Timedelta::div_scalar(MAX, 1), MAX);
20076        assert_eq!(Timedelta::div_scalar(-100, 3), -34); // floor, not trunc
20077        assert_eq!(Timedelta::div_scalar(100, -3), -34);
20078        assert_eq!(Timedelta::sub(MIN_OK + 2, 1), MIN_OK + 1);
20079    }
20080
20081    #[test]
20082    fn timedelta_mul_scalar_scales() {
20083        let three_hours = Timedelta::NANOS_PER_HOUR * 3;
20084        assert_eq!(
20085            Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
20086            three_hours
20087        );
20088        assert_eq!(Timedelta::mul_scalar(100, 0), 0);
20089        assert_eq!(Timedelta::mul_scalar(100, -2), -200);
20090    }
20091
20092    #[test]
20093    fn timedelta_mul_scalar_returns_nat_on_overflow() {
20094        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX.
20095        // pandas `pd.Timedelta.max * 2` raises OverflowError.
20096        assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), Timedelta::NAT);
20097        assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), Timedelta::NAT);
20098    }
20099
20100    #[test]
20101    fn from_unit_nan_is_nat_and_overflow_is_err_8v92m() {
20102        use super::TimedeltaError;
20103
20104        // br-frankenpandas-8v92m. Rust's float->int `as` maps NaN to 0 and
20105        // saturates infinities, so the unguarded
20106        //     Ok((value * multiplier as f64).round() as i64)
20107        // failed OPEN twice: NaN became a ZERO DURATION, and inf/1e30 became a
20108        // finite plausible ~106751-day duration. Live pandas 2.2.3:
20109        //   pd.Timedelta(nan, unit='s')   -> NaT
20110        //   pd.Timedelta(inf, unit='s')   -> OutOfBoundsTimedelta
20111        //                                    "Cannot cast inf from s to 'ns' without overflow."
20112        //   pd.Timedelta(1e30, unit='s')  -> OutOfBoundsTimedelta
20113        //   pd.Timedelta(1.5, unit='s')   -> Timedelta('0 days 00:00:01.5')  <- must NOT change
20114        // The guard is copied from the two siblings that already had it
20115        // (br-frankenpandas-zw3mg), which is why `parse` behaviour is pinned
20116        // below too: all three copies must now agree.
20117
20118        // ── NaN -> NaT, NOT zero. This is the load-bearing case: an impl that
20119        // returns Ok(0) fails, and so does one that returns Err, because
20120        // pandas gives NaT rather than raising.
20121        assert_eq!(Timedelta::from_unit(f64::NAN, "s"), Ok(Timedelta::NAT));
20122        assert_ne!(Timedelta::from_unit(f64::NAN, "s"), Ok(0));
20123        assert_eq!(Timedelta::from_unit(f64::NAN, "D"), Ok(Timedelta::NAT));
20124
20125        // ── non-finite / out-of-range -> Overflow, not a saturated duration.
20126        assert_eq!(
20127            Timedelta::from_unit(f64::INFINITY, "s"),
20128            Err(TimedeltaError::Overflow)
20129        );
20130        assert_eq!(
20131            Timedelta::from_unit(f64::NEG_INFINITY, "s"),
20132            Err(TimedeltaError::Overflow)
20133        );
20134        assert_eq!(
20135            Timedelta::from_unit(1e30, "s"),
20136            Err(TimedeltaError::Overflow)
20137        );
20138        assert_eq!(
20139            Timedelta::from_unit(1e30, "D"),
20140            Err(TimedeltaError::Overflow)
20141        );
20142
20143        // ── CONTROL: ordinary values must be untouched, bit-for-bit. An
20144        // over-eager guard that rejected anything large would fail here.
20145        assert_eq!(Timedelta::from_unit(1.5, "s"), Ok(1_500_000_000));
20146        assert_eq!(Timedelta::from_unit(0.0, "s"), Ok(0));
20147        assert_eq!(Timedelta::from_unit(-2.5, "s"), Ok(-2_500_000_000));
20148        assert_eq!(Timedelta::from_unit(1.0, "D"), Ok(Timedelta::NANOS_PER_DAY));
20149        assert_eq!(
20150            Timedelta::from_unit(3.0, "h"),
20151            Ok(3 * Timedelta::NANOS_PER_HOUR)
20152        );
20153        // Just inside the representable range still returns its exact product,
20154        // so the boundary is pinned from the accepting side as well.
20155        let big_days = 100_000.0_f64;
20156        let expected = (big_days * Timedelta::NANOS_PER_DAY as f64).round() as i64;
20157        assert_eq!(Timedelta::from_unit(big_days, "D"), Ok(expected));
20158        assert!(expected > 0, "fixture must stay in range to be a control");
20159
20160        // ── an unknown unit is still InvalidFormat, NOT Overflow — the unit
20161        // check must keep running before the range check.
20162        assert!(matches!(
20163            Timedelta::from_unit(1.0, "nonsense-unit"),
20164            Err(TimedeltaError::InvalidFormat(_))
20165        ));
20166        assert!(matches!(
20167            Timedelta::from_unit(f64::NAN, "nonsense-unit"),
20168            Err(TimedeltaError::InvalidFormat(_)),
20169        ));
20170
20171        // ── the already-guarded sibling is unchanged. NOTE the input shape:
20172        // the compound lexer accepts only digits, '.' and '-', so scientific
20173        // notation is an InvalidFormat, not an Overflow — the overflow case
20174        // needs a long decimal literal (this is zw3mg's own fixture).
20175        let huge = format!("{} days", "9".repeat(18));
20176        assert!(matches!(
20177            Timedelta::parse(&huge),
20178            Err(TimedeltaError::Overflow)
20179        ));
20180        assert!(matches!(
20181            Timedelta::parse("1e100 days"),
20182            Err(TimedeltaError::InvalidFormat(_))
20183        ));
20184    }
20185
20186    #[test]
20187    fn rounding_and_ms_us_overflow_never_fabricates_a_finite_value_kyd16() {
20188        // br-frankenpandas-kyd16, the sibling sweep of lgyy8. Three defects:
20189        //   (1) Timedelta::round used UNCHECKED `(quotient + 1) * unit_nanos`
20190        //       on the round-up branch — debug PANIC, release WRAP to a
20191        //       large-negative duration.
20192        //   (2) Timedelta::floor/ceil and Timestamp::ceil_to/round_to
20193        //       saturated to i64::MAX, a finite plausible duration / ~year-2262
20194        //       instant handed back as real data — while their own sibling
20195        //       Timestamp::floor_to was ALREADY checked.
20196        //   (3) Timestamp::from_millis/from_micros saturated likewise, while
20197        //       their neighbour `fromtimestamp` already returned NaT.
20198        // Live pandas 2.2.3 raises on every one of these and names the cause:
20199        //   Timestamp.max.ceil('D')/round('D') -> OutOfBoundsDatetime
20200        //       "Cannot round 2262-04-11 23:47:16.854775807 to freq=<Day> without overflow"
20201        //   Timestamp.min.floor('D')           -> OutOfBoundsDatetime (same)
20202        //   Timedelta.max.ceil('D')/round('D') -> OutOfBoundsTimedelta (same shape)
20203        //   Timedelta.min.floor('D')           -> OutOfBoundsTimedelta (same)
20204        // ...but Timestamp.max.floor('D') is an ordinary in-range answer and
20205        // must NOT change. Both halves are asserted below.
20206        const MAX: i64 = i64::MAX;
20207        const MIN_OK: i64 = i64::MIN + 1;
20208        const DAY: i64 = Timedelta::NANOS_PER_DAY;
20209
20210        // ── (1) round(): must not panic, must not wrap negative ────────────
20211        let rounded = Timedelta::round(MAX, "D");
20212        assert_eq!(
20213            rounded,
20214            Timedelta::NAT,
20215            "rounding i64::MAX up to a whole day overflows; the old unchecked \
20216             multiply panicked in debug and wrapped in release"
20217        );
20218        // The wrap signature specifically: a positive input must never round
20219        // to a negative duration. This fails for a wrapping impl even if the
20220        // debug panic is somehow avoided.
20221        assert!(
20222            rounded == Timedelta::NAT || rounded > 0,
20223            "a positive duration must never round to a negative one"
20224        );
20225        assert_eq!(Timedelta::round(MIN_OK, "D"), Timedelta::NAT);
20226
20227        // ── (2) floor/ceil overflow -> NaT, not a fabricated finite value ──
20228        assert_eq!(Timedelta::ceil(MAX, "D"), Timedelta::NAT);
20229        assert_eq!(Timedelta::floor(MIN_OK, "D"), Timedelta::NAT);
20230        assert!(Timestamp::from_nanos(MAX).ceil_to(DAY).is_nat());
20231        assert!(Timestamp::from_nanos(MAX).round_to(DAY).is_nat());
20232        assert!(Timestamp::from_nanos(MIN_OK).floor_to(DAY).is_nat());
20233        assert!(Timestamp::from_nanos(MIN_OK).round_to(DAY).is_nat());
20234
20235        // ── (3) ms/us constructors out of range -> NaT ─────────────────────
20236        assert!(Timestamp::from_millis(MAX, None).is_nat());
20237        assert!(Timestamp::from_millis(MIN_OK, None).is_nat());
20238        assert!(Timestamp::from_micros(MAX, None).is_nat());
20239        assert!(Timestamp::from_micros(MIN_OK, Some("US/Eastern")).is_nat());
20240
20241        // ── CONTROL: in-range rounding is untouched. An implementation that
20242        // NaT'd too eagerly — or that treated "near the limit" as overflow —
20243        // fails every assertion below.
20244        //
20245        // Timestamp.max.floor('D') is the exact case pandas ANSWERS rather
20246        // than raising, so it pins the boundary from the other side.
20247        let max_floor = Timestamp::from_nanos(MAX).floor_to(DAY);
20248        assert!(!max_floor.is_nat(), "Timestamp.max.floor(D) must succeed");
20249        assert_eq!(max_floor.nanos, (MAX / DAY) * DAY);
20250        assert_eq!(Timedelta::floor(MAX, "D"), (MAX / DAY) * DAY);
20251        assert_eq!(
20252            Timedelta::ceil(MIN_OK, "D"),
20253            (MIN_OK.div_euclid(DAY) + 1) * DAY
20254        );
20255
20256        // Ordinary values, bit-for-bit.
20257        let hour = Timedelta::NANOS_PER_HOUR;
20258        assert_eq!(Timedelta::floor(90 * 60 * 1_000_000_000, "h"), hour);
20259        assert_eq!(Timedelta::ceil(90 * 60 * 1_000_000_000, "h"), 2 * hour);
20260        assert_eq!(Timedelta::round(90 * 60 * 1_000_000_000, "h"), 2 * hour);
20261        assert_eq!(Timedelta::round(-90 * 60 * 1_000_000_000, "h"), -2 * hour);
20262        assert_eq!(Timedelta::round(29 * 60 * 1_000_000_000, "h"), 0);
20263        assert_eq!(Timestamp::from_millis(1_500, None).nanos, 1_500_000_000);
20264        assert_eq!(Timestamp::from_micros(-2_000, None).nanos, -2_000_000);
20265        assert_eq!(
20266            Timestamp::from_nanos(hour + 1).floor_to(hour).nanos,
20267            hour,
20268            "in-range floor unchanged"
20269        );
20270        assert_eq!(
20271            Timestamp::from_nanos(hour + 1).ceil_to(hour).nanos,
20272            2 * hour,
20273            "in-range ceil unchanged"
20274        );
20275
20276        // NaT / degenerate-unit inputs unchanged.
20277        assert_eq!(Timedelta::round(Timedelta::NAT, "D"), Timedelta::NAT);
20278        assert_eq!(Timedelta::floor(Timedelta::NAT, "D"), Timedelta::NAT);
20279        assert_eq!(Timedelta::ceil(1_000, "nonsense-unit"), Timedelta::NAT);
20280        assert!(Timestamp::nat().ceil_to(DAY).is_nat());
20281        assert!(Timestamp::from_nanos(0).round_to(0).is_nat());
20282        // A non-overflowing round still carries its zone.
20283        assert_eq!(
20284            Timestamp::from_nanos_tz(hour + 1, "US/Eastern")
20285                .ceil_to(hour)
20286                .tz
20287                .as_deref(),
20288            Some("US/Eastern")
20289        );
20290    }
20291
20292    #[test]
20293    fn timedelta_mul_scalar_propagates_nat() {
20294        assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
20295    }
20296
20297    #[test]
20298    fn arithmetic_overflow_never_fabricates_a_finite_value_lgyy8() {
20299        // br-frankenpandas-lgyy8. The bug: these six helpers used
20300        // `saturating_*`, so POSITIVE overflow returned i64::MAX — a valid,
20301        // finite, plausible duration / ~year-2262 instant — as if it were real
20302        // data. (Negative overflow landed on i64::MIN, which IS the NaT
20303        // sentinel, so that direction already surfaced as missing.) Live
20304        // pandas 2.2.3 never returns a fabricated finite value on overflow in
20305        // either direction, scalar or vectorized:
20306        //   pd.Timedelta.max + Timedelta('1ns')  -> OverflowError
20307        //   pd.Timestamp.max + Timedelta('1ns')  -> OutOfBoundsDatetime
20308        //   pd.Timestamp.min - pd.Timestamp.max  -> OutOfBoundsDatetime
20309        //   pd.Timedelta.max * 2                 -> OverflowError
20310        //   pd.Timedelta.min + Timedelta('-1ns') -> NaT
20311        //
20312        // Every assertion below is a case a saturating implementation FAILS.
20313        const MAX: i64 = i64::MAX;
20314        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
20315
20316        // ── positive overflow: the actual bug ──────────────────────────────
20317        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
20318        assert_eq!(Timedelta::add(MAX - 10, 100), Timedelta::NAT);
20319        assert_eq!(Timedelta::sub(MAX, -1), Timedelta::NAT);
20320        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
20321        assert_eq!(Timedelta::mul_scalar(MAX / 2 + 2, 2), Timedelta::NAT);
20322        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
20323        assert!(Timestamp::from_nanos(MAX).sub_timedelta(-1).is_nat());
20324        // Timestamp.max - Timestamp.min: the true difference is ~2^64, far
20325        // outside i64. Saturation returned MAX (a ~292-year duration presented
20326        // as the real answer); pandas raises OutOfBoundsDatetime.
20327        assert_eq!(
20328            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(MIN_OK)),
20329            Timedelta::NAT
20330        );
20331
20332        // ── negative overflow: unchanged, still NaT ────────────────────────
20333        assert_eq!(Timedelta::add(MIN_OK, -1), Timedelta::NAT);
20334        assert_eq!(Timedelta::add(MIN_OK, -2), Timedelta::NAT);
20335        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
20336        assert_eq!(Timedelta::mul_scalar(MIN_OK, 2), Timedelta::NAT);
20337        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
20338        assert!(Timestamp::from_nanos(MIN_OK).add_timedelta(-1).is_nat());
20339        assert_eq!(
20340            Timestamp::from_nanos(MIN_OK).sub_timestamp(&Timestamp::from_nanos(MAX)),
20341            Timedelta::NAT
20342        );
20343
20344        // ── the boundary: the largest REPRESENTABLE results must still be
20345        // returned exactly. This is what stops the fix from being bought with
20346        // an over-eager NaT that swallows valid arithmetic — an implementation
20347        // that NaT'd one step early fails here, as does one that NaT'd on any
20348        // operand near the limits.
20349        assert_eq!(Timedelta::add(MAX - 1, 1), MAX);
20350        assert_eq!(Timedelta::add(MAX, 0), MAX);
20351        assert_eq!(Timedelta::sub(MAX, 1), MAX - 1);
20352        assert_eq!(Timedelta::add(MIN_OK + 1, -1), MIN_OK);
20353        assert_eq!(Timedelta::mul_scalar(MAX / 2, 2), (MAX / 2) * 2);
20354        assert_eq!(Timedelta::mul_scalar(MIN_OK, 1), MIN_OK);
20355        assert_eq!(Timestamp::from_nanos(MAX - 1).add_timedelta(1).nanos, MAX);
20356        assert_eq!(
20357            Timestamp::from_nanos(MIN_OK + 1).sub_timedelta(1).nanos,
20358            MIN_OK
20359        );
20360        assert_eq!(
20361            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(0)),
20362            MAX
20363        );
20364        // Ordinary values are untouched bit-for-bit.
20365        assert_eq!(Timedelta::add(1_000, 2_345), 3_345);
20366        assert_eq!(Timedelta::sub(1_000, 2_345), -1_345);
20367        assert_eq!(Timedelta::mul_scalar(-7, 6), -42);
20368
20369        // ── a result landing EXACTLY on i64::MIN is representable, but i64::MIN
20370        // IS the NaT sentinel, so it must read as NaT rather than as the most
20371        // negative duration. pandas agrees: Timedelta.min + -1ns -> NaT. Note
20372        // `MIN_OK - 1 == i64::MIN` does not overflow, so this case survives the
20373        // switch from saturating_* to checked_* only because the sentinel and
20374        // the clamp coincide — assert it explicitly rather than by accident.
20375        assert_eq!(MIN_OK - 1, i64::MIN);
20376        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
20377        assert_eq!(Timedelta::add(MIN_OK, 0), MIN_OK);
20378
20379        // ── NaT operands still propagate, and tz no longer rides along with a
20380        // fabricated instant: an overflowed Timestamp is the canonical NaT.
20381        assert!(Timestamp::nat().add_timedelta(1).is_nat());
20382        assert!(
20383            Timestamp::from_nanos(0)
20384                .add_timedelta(Timedelta::NAT)
20385                .is_nat()
20386        );
20387        let tzed = Timestamp::from_nanos_tz(MAX, "US/Eastern");
20388        let overflowed = tzed.add_timedelta(1);
20389        assert!(overflowed.is_nat());
20390        assert_eq!(overflowed.tz, None, "an overflow NaT carries no zone");
20391        // ...while a NON-overflowing shift still preserves the zone.
20392        assert_eq!(
20393            Timestamp::from_nanos_tz(0, "US/Eastern")
20394                .add_timedelta(Timedelta::NANOS_PER_DAY)
20395                .tz
20396                .as_deref(),
20397            Some("US/Eastern")
20398        );
20399    }
20400
20401    #[test]
20402    fn timedelta_div_scalar_floor_divides() {
20403        // Floor division (matches Python / pandas): -100 // 3 == -34, not -33.
20404        assert_eq!(Timedelta::div_scalar(100, 3), 33);
20405        assert_eq!(Timedelta::div_scalar(-100, 3), -34);
20406        assert_eq!(Timedelta::div_scalar(100, -3), -34);
20407        assert_eq!(Timedelta::div_scalar(-100, -3), 33);
20408    }
20409
20410    #[test]
20411    fn timedelta_div_scalar_zero_divisor_returns_nat() {
20412        assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
20413    }
20414
20415    #[test]
20416    fn timedelta_div_scalar_min_neg_one_propagates_nat() {
20417        // i64::MIN aliases NaT, so `div_scalar(i64::MIN, _)` propagates NaT
20418        // — the `i64::MIN / -1` arithmetic-overflow case is subsumed.
20419        assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
20420        // (i64::MIN + 1) is a real timedelta; `/ -1` does not overflow.
20421        assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
20422    }
20423
20424    #[test]
20425    fn timedelta_div_scalar_propagates_nat() {
20426        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
20427    }
20428
20429    #[test]
20430    fn timedelta_div_timedelta_returns_float_ratio() {
20431        let two_hours = Timedelta::NANOS_PER_HOUR * 2;
20432        let one_hour = Timedelta::NANOS_PER_HOUR;
20433        assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
20434        assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
20435    }
20436
20437    #[test]
20438    fn timedelta_div_timedelta_nat_returns_nan() {
20439        assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
20440        assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
20441    }
20442
20443    // ── Timestamp tests (br-frankenpandas-9p0u — 4r56 Phase 2) ──────────
20444
20445    use super::Timestamp;
20446
20447    #[test]
20448    fn timestamp_from_nanos_is_naive_utc() {
20449        let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
20450        assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
20451        assert_eq!(ts.tz, None);
20452        assert!(!ts.is_nat());
20453    }
20454
20455    #[test]
20456    fn timestamp_from_nanos_tz_carries_tz_name() {
20457        let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
20458        assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
20459    }
20460
20461    #[test]
20462    fn timestamp_now_returns_current_time() {
20463        let before = std::time::SystemTime::now()
20464            .duration_since(std::time::UNIX_EPOCH)
20465            .unwrap()
20466            .as_nanos() as i64;
20467        let ts = Timestamp::now();
20468        let after = std::time::SystemTime::now()
20469            .duration_since(std::time::UNIX_EPOCH)
20470            .unwrap()
20471            .as_nanos() as i64;
20472        assert!(ts.nanos >= before);
20473        assert!(ts.nanos <= after);
20474        assert!(!ts.is_nat());
20475    }
20476
20477    #[test]
20478    fn timestamp_today_returns_midnight() {
20479        let ts = Timestamp::today();
20480        assert!(!ts.is_nat());
20481        // Today should be normalized (midnight), so hour/min/sec should be 0
20482        assert_eq!(ts.hour(), Some(0));
20483        assert_eq!(ts.minute(), Some(0));
20484        assert_eq!(ts.second(), Some(0));
20485    }
20486
20487    #[test]
20488    fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
20489        let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
20490        let one_day = Timedelta::NANOS_PER_DAY;
20491        let shifted = ts.add_timedelta(one_day);
20492        assert_eq!(shifted.nanos, one_day);
20493        assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
20494    }
20495
20496    #[test]
20497    fn timestamp_add_timedelta_returns_nat_on_overflow() {
20498        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX, i.e.
20499        // a finite ~year-2262 instant handed back as real data. pandas
20500        // `pd.Timestamp.max + pd.Timedelta('1ns')` raises OutOfBoundsDatetime.
20501        let ts = Timestamp::from_nanos(i64::MAX - 10);
20502        assert!(ts.add_timedelta(100).is_nat());
20503    }
20504
20505    #[test]
20506    fn timestamp_add_timedelta_propagates_nat() {
20507        // NaT Timestamp + anything = NaT.
20508        assert!(Timestamp::nat().add_timedelta(100).is_nat());
20509        // Timestamp + NaT Timedelta = NaT.
20510        assert!(
20511            Timestamp::from_nanos(0)
20512                .add_timedelta(Timedelta::NAT)
20513                .is_nat()
20514        );
20515    }
20516
20517    #[test]
20518    fn timestamp_sub_timedelta_shifts_backward() {
20519        let ts = Timestamp::from_nanos(1_000);
20520        let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
20521        assert_eq!(shifted.nanos, 0);
20522    }
20523
20524    #[test]
20525    fn timestamp_sub_timestamp_returns_timedelta_nanos() {
20526        let t0 = Timestamp::from_nanos(0);
20527        let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
20528        assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
20529        assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
20530    }
20531
20532    #[test]
20533    fn timestamp_sub_timestamp_nat_propagates() {
20534        let ts = Timestamp::from_nanos(1_000);
20535        assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
20536        assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
20537    }
20538
20539    #[test]
20540    fn timestamp_semantic_eq_treats_two_nat_as_equal() {
20541        assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
20542        assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
20543        assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
20544    }
20545
20546    #[test]
20547    fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
20548        use std::cmp::Ordering;
20549        let a = Timestamp::from_nanos(0);
20550        let b = Timestamp::from_nanos(100);
20551        assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
20552        assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
20553        assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
20554        assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
20555        assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
20556    }
20557
20558    #[test]
20559    fn time_zone_offsets_and_wall_clock_conversions_follow_pandas() {
20560        use crate::{
20561            TimeZoneError, tz_abbreviation, tz_canonical_name, tz_offset_seconds,
20562            tz_utc_to_wall_nanos, tz_validate, tz_wall_to_utc_nanos,
20563        };
20564        let hour = 3_600_000_000_000_i64;
20565        // 2024-03-10 14:30 UTC: Tokyo is +9h; New York is on EDT (-4h) after
20566        // 07:00 UTC that day and on EST (-5h) the day before.
20567        let instant = 1_710_081_000_000_000_000_i64;
20568        assert_eq!(tz_offset_seconds("Asia/Tokyo", instant), Ok(9 * 3_600));
20569        assert_eq!(tz_offset_seconds("US/Eastern", instant), Ok(-4 * 3_600));
20570        assert_eq!(
20571            tz_offset_seconds("US/Eastern", instant - 24 * hour),
20572            Ok(-5 * 3_600)
20573        );
20574        assert_eq!(tz_offset_seconds("+05:30", 0), Ok(19_800));
20575        assert_eq!(tz_offset_seconds("UTC+05:30", 0), Ok(19_800));
20576        assert_eq!(tz_offset_seconds("-03:00", 0), Ok(-10_800));
20577        assert_eq!(tz_offset_seconds("UTC", instant), Ok(0));
20578        assert_eq!(
20579            tz_utc_to_wall_nanos("Asia/Tokyo", instant),
20580            Ok(instant + 9 * hour)
20581        );
20582        // Wall 12:00 in New York on 2024-01-01 is 17:00 UTC, and back.
20583        let wall_noon = 19_723 * 24 * hour + 12 * hour;
20584        assert_eq!(
20585            tz_wall_to_utc_nanos("US/Eastern", wall_noon),
20586            Ok(wall_noon + 5 * hour)
20587        );
20588        assert_eq!(
20589            tz_utc_to_wall_nanos("US/Eastern", wall_noon + 5 * hour),
20590            Ok(wall_noon)
20591        );
20592        // NaT passes through both ways.
20593        assert_eq!(tz_wall_to_utc_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
20594        assert_eq!(tz_utc_to_wall_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
20595        // NEGATIVES: 02:30 on 2024-03-10 does not exist in New York; 01:30
20596        // on 2024-11-03 happens twice; unknown zones and malformed offsets
20597        // are pandas' UnknownTimeZoneError.
20598        let skipped = 19_792 * 24 * hour + 2 * hour + 30 * 60_000_000_000;
20599        assert_eq!(
20600            tz_wall_to_utc_nanos("US/Eastern", skipped),
20601            Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
20602        );
20603        let repeated = 20_030 * 24 * hour + hour + 30 * 60_000_000_000;
20604        assert_eq!(
20605            tz_wall_to_utc_nanos("US/Eastern", repeated),
20606            Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
20607        );
20608        assert_eq!(
20609            tz_offset_seconds("Mars/Olympus", 0),
20610            Err(TimeZoneError::Unknown("Mars/Olympus".to_owned()))
20611        );
20612        assert!(tz_validate("+24:00").is_err());
20613        assert!(tz_validate("+5:30").is_err());
20614        assert!(tz_validate("Europe/Paris").is_ok());
20615        // pandas' names: a fixed offset is UTC+HH:MM, a zero one UTC.
20616        assert_eq!(tz_canonical_name("+05:30").as_deref(), Ok("UTC+05:30"));
20617        assert_eq!(tz_canonical_name("UTC-03:00").as_deref(), Ok("UTC-03:00"));
20618        assert_eq!(tz_canonical_name("+00:00").as_deref(), Ok("UTC"));
20619        assert_eq!(tz_canonical_name("Z").as_deref(), Ok("UTC"));
20620        assert_eq!(tz_canonical_name("US/Eastern").as_deref(), Ok("US/Eastern"));
20621        // strftime('%Z'): the abbreviation in force at the instant.
20622        assert_eq!(tz_abbreviation("US/Eastern", instant).as_deref(), Ok("EDT"));
20623        assert_eq!(
20624            tz_abbreviation("US/Eastern", instant - 24 * hour).as_deref(),
20625            Ok("EST")
20626        );
20627        assert_eq!(tz_abbreviation("+05:30", 0).as_deref(), Ok("UTC+05:30"));
20628    }
20629
20630    /// pandas' `tz_localize(ambiguous=, nonexistent=)` for one wall time
20631    /// (br-frankenpandas-84w06), live pandas 2.2.3 in America/New_York:
20632    /// 02:30 on 2024-03-10 does not exist - shift_forward 03:00-04:00 (07:00
20633    /// UTC), shift_backward 01:59:59.999999999-05:00, NaT, or +1h 03:30-04:00;
20634    /// 01:30 on 2024-11-03 happens twice - True (DST) 05:30 UTC, False
20635    /// (standard) 06:30 UTC, NaT.
20636    #[test]
20637    fn tz_localize_policies_follow_pandas_84w06() {
20638        use super::{
20639            AmbiguousTime as A, NonexistentTime as N, TimeZoneError,
20640            tz_wall_to_utc_nanos_with as at,
20641        };
20642        let hour = 3_600_000_000_000_i64;
20643        let minute = 60_000_000_000_i64;
20644        let skipped = 19_792 * 24 * hour + 2 * hour + 30 * minute;
20645        let transition = 19_792 * 24 * hour + 7 * hour;
20646        let zone = "America/New_York";
20647        assert_eq!(at(zone, skipped, A::Raise, N::ShiftForward), Ok(transition));
20648        assert_eq!(
20649            at(zone, skipped, A::Raise, N::ShiftBackward),
20650            Ok(transition - 1)
20651        );
20652        assert_eq!(at(zone, skipped, A::Raise, N::NaT), Ok(i64::MIN));
20653        assert_eq!(
20654            at(zone, skipped, A::Raise, N::Shift(hour)),
20655            Ok(transition + 30 * minute)
20656        );
20657        let repeated = 20_030 * 24 * hour + hour + 30 * minute;
20658        assert_eq!(
20659            at(zone, repeated, A::Earliest, N::Raise),
20660            Ok(repeated + 4 * hour)
20661        );
20662        assert_eq!(
20663            at(zone, repeated, A::Latest, N::Raise),
20664            Ok(repeated + 5 * hour)
20665        );
20666        assert_eq!(at(zone, repeated, A::NaT, N::Raise), Ok(i64::MIN));
20667        // NEGATIVES: the policies leave a wall time that exists once alone,
20668        // and 'raise' still refuses as before.
20669        let noon = 19_723 * 24 * hour + 12 * hour;
20670        assert_eq!(at(zone, noon, A::NaT, N::NaT), Ok(noon + 5 * hour));
20671        assert_eq!(
20672            at(zone, skipped, A::NaT, N::Raise),
20673            Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
20674        );
20675        assert_eq!(
20676            at(zone, repeated, A::Raise, N::NaT),
20677            Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
20678        );
20679    }
20680
20681    /// The batch conversions answer as the per-value ones, value for value:
20682    /// whole-hour DST changes, Lord Howe's half hour, a fixed offset and UTC,
20683    /// over sorted minutes through each change, every hour's edges, random
20684    /// instants and NaT, under each policy (br-frankenpandas-6pqf3). NEGATIVE: 'raise' still
20685    /// refuses the first skipped wall time, a skipped one under 'NaT' is NaT
20686    /// (a reused hour's offset would place it), and a refused time's text
20687    /// keeps pandas' six or nine digits.
20688    #[test]
20689    fn batch_tz_conversions_match_each_value_6pqf3() {
20690        use super::{
20691            AmbiguousTime as A, NonexistentTime as N, TimeZoneError, tz_utc_to_wall_nanos,
20692            tz_utc_to_wall_nanos_all, tz_wall_to_utc_nanos_all, tz_wall_to_utc_nanos_with,
20693        };
20694        const HOUR: i64 = 3_600_000_000_000;
20695        const MINUTE: i64 = 60_000_000_000;
20696        const DAY: i64 = 24 * HOUR;
20697        let (year_start, year_end) = (19_723 * DAY, 20_089 * DAY);
20698        let mut values: Vec<i64> = (year_start..year_end)
20699            .step_by(usize::try_from(37 * MINUTE).unwrap())
20700            .collect();
20701        for hour in (year_start..year_end).step_by(usize::try_from(HOUR).unwrap()) {
20702            values.extend([hour - 1, hour, hour + 1]);
20703        }
20704        for change_day in [19_792, 20_030, 19_813, 20_023, 19_820, 20_002] {
20705            values.extend((0..2 * 24 * 60).map(|minute| (change_day - 1) * DAY + minute * MINUTE));
20706        }
20707        let mut state = 0x2545_f491_4f6c_dd1d_u64;
20708        for _ in 0..3_000 {
20709            state = state
20710                .wrapping_mul(6_364_136_223_846_793_005)
20711                .wrapping_add(1_442_695_040_888_963_407);
20712            values.push(i64::try_from(state >> 2).unwrap() - 2_000_000_000_000_000_000);
20713        }
20714        values.extend([i64::MIN, 19_792 * DAY, i64::MIN]);
20715        let policies = [
20716            (A::NaT, N::NaT),
20717            (A::Earliest, N::ShiftForward),
20718            (A::Latest, N::ShiftBackward),
20719            (A::NaT, N::Shift(30 * MINUTE)),
20720        ];
20721        for zone in [
20722            "US/Eastern",
20723            "Europe/London",
20724            "Australia/Lord_Howe",
20725            "+05:30",
20726            "UTC",
20727        ] {
20728            let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20729                .iter()
20730                .map(|&nanos| tz_utc_to_wall_nanos(zone, nanos))
20731                .collect();
20732            assert_eq!(
20733                tz_utc_to_wall_nanos_all(zone, &values),
20734                one_by_one,
20735                "{zone}"
20736            );
20737            for (ambiguous, nonexistent) in policies {
20738                let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20739                    .iter()
20740                    .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, ambiguous, nonexistent))
20741                    .collect();
20742                assert_eq!(
20743                    tz_wall_to_utc_nanos_all(zone, &values, ambiguous, nonexistent),
20744                    one_by_one,
20745                    "{zone} {ambiguous:?} {nonexistent:?}"
20746                );
20747            }
20748            let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20749                .iter()
20750                .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, A::Raise, N::Raise))
20751                .collect();
20752            assert_eq!(
20753                tz_wall_to_utc_nanos_all(zone, &values, A::Raise, N::Raise),
20754                one_by_one,
20755                "{zone} raise"
20756            );
20757        }
20758        let skipped = 19_792 * DAY + 2 * HOUR + 30 * MINUTE;
20759        // 01:10 to 03:30 by 20 minutes: 02:00-03:00 is skipped.
20760        let run: Vec<i64> = (0..8)
20761            .map(|step| 19_792 * DAY + HOUR + 10 * MINUTE + step * 20 * MINUTE)
20762            .collect();
20763        assert_eq!(
20764            tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::Raise),
20765            Err(TimeZoneError::NonExistent("2024-03-10 02:10:00".to_owned()))
20766        );
20767        let placed = tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::NaT).unwrap();
20768        let expected: Vec<i64> = run
20769            .iter()
20770            .enumerate()
20771            .map(|(step, &wall)| match step {
20772                0..3 => wall + 5 * HOUR,
20773                3..6 => i64::MIN,
20774                _ => wall + 4 * HOUR,
20775            })
20776            .collect();
20777        assert_eq!(placed, expected);
20778        // Lord Howe's half-hour gap (02:00 -> 02:30 on 2024-10-06): pandas
20779        // moves 02:10 up to 03:00 (+11:00) or back to 01:59:59.999999999
20780        // (+10:30), not to the gap's end.
20781        let howe = 20_002 * DAY + 2 * HOUR + 10 * MINUTE;
20782        assert_eq!(
20783            tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftForward),
20784            Ok(vec![20_002 * DAY - 8 * HOUR])
20785        );
20786        assert_eq!(
20787            tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftBackward),
20788            Ok(vec![20_002 * DAY - 8 * HOUR - 30 * MINUTE - 1])
20789        );
20790        for (wall, text) in [
20791            (skipped + 500_000_000, "2024-03-10 02:30:00.500000"),
20792            (skipped + 1, "2024-03-10 02:30:00.000000001"),
20793        ] {
20794            assert_eq!(
20795                tz_wall_to_utc_nanos_all("US/Eastern", &[wall], A::Raise, N::Raise),
20796                Err(TimeZoneError::NonExistent(text.to_owned()))
20797            );
20798        }
20799    }
20800
20801    #[test]
20802    fn timestamp_display_matches_phase2_debug_format() {
20803        assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
20804        assert_eq!(
20805            Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
20806            "Timestamp[42, US/Eastern]"
20807        );
20808        assert_eq!(Timestamp::nat().to_string(), "NaT");
20809    }
20810
20811    #[test]
20812    fn a_naive_timestamp_cell_casts_to_its_str_srzqw() {
20813        // astype(str) of an object column's naive Timestamp is str(Timestamp)
20814        // - its own fraction, none when whole - not the 'Timestamp[<nanos>]'
20815        // placeholder (br-frankenpandas-srzqw).
20816        let text = |nanos: i64| cast_scalar(&Scalar::Datetime64(nanos), DType::Utf8);
20817        let midnight = 1_711_929_600_000_000_000;
20818        assert_eq!(
20819            text(midnight),
20820            Ok(Scalar::Utf8("2024-04-01 00:00:00".into()))
20821        );
20822        assert_eq!(
20823            text(midnight + 1_000),
20824            Ok(Scalar::Utf8("2024-04-01 00:00:00.000001".into()))
20825        );
20826        assert_eq!(
20827            text(midnight + 1),
20828            Ok(Scalar::Utf8("2024-04-01 00:00:00.000000001".into()))
20829        );
20830        assert_eq!(
20831            text(-1),
20832            Ok(Scalar::Utf8("1969-12-31 23:59:59.999999999".into()))
20833        );
20834        assert_eq!(text(Timestamp::NAT), Ok(Scalar::Utf8("NaT".into())));
20835        // The zoned spelling is the same wall clock and its offset.
20836        assert_eq!(
20837            crate::timestamp_text_in_zone(midnight, "US/Eastern"),
20838            "2024-03-31 20:00:00-04:00"
20839        );
20840    }
20841
20842    #[test]
20843    fn timestamp_value_and_unit_match_pandas_l0edr() {
20844        let ts = Timestamp::from_nanos(1_000_000_123);
20845        assert_eq!(ts.value(), 1_000_000_123);
20846        assert_eq!(ts.unit(), Some("ns"));
20847
20848        let nat = Timestamp::nat();
20849        assert_eq!(nat.value(), Timestamp::NAT);
20850        assert_eq!(nat.unit(), None);
20851    }
20852
20853    #[test]
20854    fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
20855        let ts = Timestamp::from_nanos(1_000_000_123);
20856        assert_eq!(ts.asm8(), ts.value());
20857        assert_eq!(ts.to_datetime64(), ts.value());
20858        assert_eq!(ts.to_numpy(), ts.value());
20859
20860        let nat = Timestamp::nat();
20861        assert_eq!(nat.asm8(), Timestamp::NAT);
20862        assert_eq!(nat.to_datetime64(), Timestamp::NAT);
20863        assert_eq!(nat.to_numpy(), Timestamp::NAT);
20864    }
20865
20866    #[test]
20867    fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
20868        assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
20869        assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
20870        assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
20871        assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
20872        assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
20873
20874        assert!(matches!(
20875            Timestamp::from_nanos(-500).timestamp(),
20876            Ok(value) if value == -0.0 && value.is_sign_negative()
20877        ));
20878        assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
20879        assert_eq!(
20880            Timestamp::nat().timestamp(),
20881            Err(TypeError::ValueIsMissing {
20882                kind: NullKind::NaT,
20883            })
20884        );
20885    }
20886
20887    #[test]
20888    fn timestamp_roundtrips_through_serde_json() {
20889        let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
20890        let json = serde_json::to_string(&naive).expect("serialize");
20891        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
20892        assert_eq!(naive, back);
20893
20894        let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
20895        let json = serde_json::to_string(&tz_aware).expect("serialize");
20896        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
20897        assert_eq!(tz_aware, back);
20898    }
20899
20900    #[test]
20901    fn timestamp_is_send_and_sync() {
20902        fn assert_send_sync<T: Send + Sync>() {}
20903        assert_send_sync::<Timestamp>();
20904    }
20905
20906    // ── Timestamp rounding tests (br-frankenpandas-5h6n) ────────────────
20907
20908    #[test]
20909    fn timestamp_pre_epoch_accessors_floor_not_truncate() {
20910        // br-frankenpandas-wkjtw: pre-1970 instants with a sub-day part used to
20911        // truncate toward zero, landing on the wrong calendar day. -1 ns is
20912        // 1969-12-31 23:59:59.999999999 UTC.
20913        let ts = Timestamp::from_nanos(-1);
20914        assert_eq!(ts.year(), Some(1969));
20915        assert_eq!(ts.month(), Some(12));
20916        assert_eq!(ts.day(), Some(31));
20917        assert_eq!(ts.hour(), Some(23));
20918        assert_eq!(ts.minute(), Some(59));
20919        assert_eq!(ts.second(), Some(59));
20920        assert_eq!(ts.microsecond(), Some(999_999));
20921        assert_eq!(ts.nanosecond(), Some(999));
20922        // 1969-12-31 is a Wednesday (pandas Monday=0 -> 2).
20923        assert_eq!(ts.dayofweek(), Some(2));
20924
20925        // 1969-12-31 12:00:00 — the classic truncation case (-43200 s).
20926        let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
20927        assert_eq!(noon.year(), Some(1969));
20928        assert_eq!(noon.month(), Some(12));
20929        assert_eq!(noon.day(), Some(31));
20930        assert_eq!(noon.hour(), Some(12));
20931
20932        // Exact midnight pre-epoch was already correct; keep it green.
20933        let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
20934        assert_eq!(midnight.year(), Some(1969));
20935        assert_eq!(midnight.day(), Some(31));
20936        assert_eq!(midnight.hour(), Some(0));
20937    }
20938
20939    #[test]
20940    fn timestamp_floor_to_rounds_down() {
20941        // 12:34:56 → floor by 1H → 12:00:00
20942        let h = Timedelta::NANOS_PER_HOUR;
20943        let twelve_h = h * 12;
20944        let twelve_thirty_four =
20945            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20946        let ts = Timestamp::from_nanos(twelve_thirty_four);
20947        let floored = ts.floor_to(h);
20948        assert_eq!(floored.nanos, twelve_h);
20949    }
20950
20951    #[test]
20952    fn timestamp_floor_to_handles_already_aligned() {
20953        // 12:00:00 floored by 1H → 12:00:00 (no change).
20954        let h = Timedelta::NANOS_PER_HOUR;
20955        let twelve_h = h * 12;
20956        let ts = Timestamp::from_nanos(twelve_h);
20957        assert_eq!(ts.floor_to(h).nanos, twelve_h);
20958    }
20959
20960    #[test]
20961    fn timestamp_floor_to_handles_negative_nanos() {
20962        // -100 ns floored by 60 ns:
20963        //   div_euclid(-100, 60) = -2 (since -2*60=-120, rem=20 ≥ 0).
20964        //   result = -2 * 60 = -120.
20965        let ts = Timestamp::from_nanos(-100);
20966        assert_eq!(ts.floor_to(60).nanos, -120);
20967    }
20968
20969    #[test]
20970    fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
20971        let ts = Timestamp::from_nanos(i64::MIN + 1);
20972        assert!(ts.floor_to(10).is_nat());
20973
20974        let safe = Timestamp::from_nanos(i64::MIN + 10);
20975        assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
20976
20977        let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
20978        assert_eq!(tz.nanos, -120);
20979        assert_eq!(tz.tz.as_deref(), Some("UTC"));
20980    }
20981
20982    #[test]
20983    fn timestamp_ceil_to_rounds_up() {
20984        // 12:34:56 → ceil by 1H → 13:00:00.
20985        let h = Timedelta::NANOS_PER_HOUR;
20986        let twelve_h = h * 12;
20987        let thirteen_h = h * 13;
20988        let twelve_thirty_four =
20989            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20990        let ts = Timestamp::from_nanos(twelve_thirty_four);
20991        assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
20992    }
20993
20994    #[test]
20995    fn timestamp_ceil_to_no_op_on_aligned() {
20996        let h = Timedelta::NANOS_PER_HOUR;
20997        let twelve_h = h * 12;
20998        let ts = Timestamp::from_nanos(twelve_h);
20999        assert_eq!(ts.ceil_to(h).nanos, twelve_h);
21000    }
21001
21002    #[test]
21003    fn timestamp_round_to_rounds_to_nearest() {
21004        // 12:30:01 (one second past the half-hour): round to 1H → 13:00:00.
21005        let h = Timedelta::NANOS_PER_HOUR;
21006        let twelve_h = h * 12;
21007        let twelve_thirty_one_sec =
21008            twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
21009        let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
21010        assert_eq!(ts.round_to(h).nanos, h * 13);
21011
21012        // 12:29:59 (one second before half): round to 1H → 12:00:00.
21013        let twelve_twenty_nine_sec =
21014            twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
21015        let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
21016        assert_eq!(ts.round_to(h).nanos, twelve_h);
21017    }
21018
21019    #[test]
21020    fn timestamp_round_to_bankers_tie_to_even() {
21021        // Tie cases: rem == unit/2 exactly. Pick even-multiple floor.
21022        // unit=10, so half=5. nanos=5: floor=0 (even), so → 0.
21023        // nanos=15: floor=1 (odd), so → 20.
21024        // nanos=25: floor=2 (even), so → 20.
21025        // nanos=35: floor=3 (odd), so → 40.
21026        assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
21027        assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
21028        assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
21029        assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
21030    }
21031
21032    #[test]
21033    fn timestamp_round_to_zero_unit_returns_nat() {
21034        let ts = Timestamp::from_nanos(100);
21035        assert!(ts.round_to(0).is_nat());
21036        assert!(ts.floor_to(0).is_nat());
21037        assert!(ts.ceil_to(0).is_nat());
21038    }
21039
21040    #[test]
21041    fn timestamp_round_to_negative_unit_returns_nat() {
21042        let ts = Timestamp::from_nanos(100);
21043        assert!(ts.round_to(-10).is_nat());
21044        assert!(ts.floor_to(-10).is_nat());
21045        assert!(ts.ceil_to(-10).is_nat());
21046    }
21047
21048    #[test]
21049    fn timestamp_rounding_propagates_nat() {
21050        let nat = Timestamp::nat();
21051        assert!(nat.floor_to(60).is_nat());
21052        assert!(nat.ceil_to(60).is_nat());
21053        assert!(nat.round_to(60).is_nat());
21054    }
21055
21056    #[test]
21057    fn timestamp_rounding_preserves_tz() {
21058        let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
21059        assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
21060        assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
21061        assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
21062    }
21063
21064    // ── Timestamp string-unit rounding tests (br-frankenpandas-lbsx) ────
21065
21066    #[test]
21067    fn timestamp_floor_to_unit_h_rounds_to_hour() {
21068        let h = Timedelta::NANOS_PER_HOUR;
21069        let twelve_h = h * 12;
21070        let twelve_thirty_four =
21071            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
21072        let ts = Timestamp::from_nanos(twelve_thirty_four);
21073        assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
21074        assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
21075        assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
21076        assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
21077        assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
21078    }
21079
21080    #[test]
21081    fn timestamp_ceil_to_unit_d_rounds_to_day() {
21082        // 12:34:56 → ceil to 1 day → 24:00:00 (next day).
21083        let h = Timedelta::NANOS_PER_HOUR;
21084        let d = Timedelta::NANOS_PER_DAY;
21085        let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
21086        let ts = Timestamp::from_nanos(twelve_thirty_four);
21087        assert_eq!(ts.ceil_to_unit("D").nanos, d);
21088        assert_eq!(ts.ceil_to_unit("day").nanos, d);
21089        assert_eq!(ts.ceil_to_unit("days").nanos, d);
21090    }
21091
21092    #[test]
21093    fn timestamp_round_to_unit_min_rounds_to_minute() {
21094        // 12:34:31 → round to 1 minute → 12:35:00.
21095        let m = Timedelta::NANOS_PER_MIN;
21096        let twelve_thirty_four_thirty_one =
21097            Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
21098        let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
21099        let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
21100        assert_eq!(ts.round_to_unit("min").nanos, expected);
21101        assert_eq!(ts.round_to_unit("T").nanos, expected); // pandas pre-2.2 alias
21102        assert_eq!(ts.round_to_unit("minute").nanos, expected);
21103    }
21104
21105    #[test]
21106    fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
21107        let ts = Timestamp::from_nanos(
21108            Timedelta::NANOS_PER_HOUR * 12
21109                + Timedelta::NANOS_PER_MIN * 34
21110                + Timedelta::NANOS_PER_SEC * 31,
21111        );
21112
21113        assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
21114        assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
21115        assert_eq!(ts.round("min"), ts.round_to_unit("min"));
21116    }
21117
21118    #[test]
21119    fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
21120        let ts = Timestamp::from_nanos_tz(
21121            Timedelta::NANOS_PER_DAY * 3
21122                + Timedelta::NANOS_PER_HOUR * 12
21123                + Timedelta::NANOS_PER_MIN * 34,
21124            "US/Eastern",
21125        );
21126        let normalized = ts.normalize();
21127
21128        assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
21129        assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
21130        assert!(Timestamp::nat().normalize().is_nat());
21131        for nanos in [
21132            i64::MIN + 1,
21133            -Timedelta::NANOS_PER_DAY - 1,
21134            -Timedelta::NANOS_PER_DAY,
21135            -1,
21136            0,
21137            Timedelta::NANOS_PER_DAY - 1,
21138            Timedelta::NANOS_PER_DAY,
21139            i64::MAX,
21140        ] {
21141            let timestamp = Timestamp::from_nanos(nanos);
21142            assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
21143        }
21144    }
21145
21146    #[test]
21147    #[ignore = "foreground profile-first A/B"]
21148    fn timestamp_normalize_direct_day_profile_dk721() {
21149        use std::{hint::black_box, time::Instant};
21150
21151        fn former(timestamp: &Timestamp) -> Timestamp {
21152            timestamp.floor_to_unit("D")
21153        }
21154
21155        fn candidate(timestamp: &Timestamp) -> Timestamp {
21156            timestamp.normalize()
21157        }
21158
21159        fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
21160            let started = Instant::now();
21161            let mut checksum = 0_u64;
21162            for timestamp in input {
21163                let normalized = normalize(black_box(timestamp));
21164                checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
21165            }
21166            black_box(checksum);
21167            started.elapsed().as_nanos()
21168        }
21169
21170        fn percentile(samples: &mut [u128], percent: usize) -> u128 {
21171            samples.sort_unstable();
21172            let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
21173            samples[rank]
21174        }
21175
21176        let parity_cases = [
21177            Timestamp::nat(),
21178            Timestamp::from_nanos(i64::MIN + 1),
21179            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
21180            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
21181            Timestamp::from_nanos(-1),
21182            Timestamp::from_nanos(0),
21183            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
21184            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
21185            Timestamp::from_nanos(i64::MAX),
21186            Timestamp::from_nanos_tz(-1, "US/Eastern"),
21187            Timestamp::from_nanos_tz(
21188                Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
21189                "Asia/Tokyo",
21190            ),
21191        ];
21192        for timestamp in &parity_cases {
21193            assert_eq!(former(timestamp), candidate(timestamp));
21194            assert_eq!(timestamp.normalize(), former(timestamp));
21195        }
21196
21197        const ROWS: usize = 16_384;
21198        const SAMPLES: usize = 20;
21199        let input = (0..ROWS)
21200            .map(|index| {
21201                let day = index as i64 % 4_096 - 2_048;
21202                let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
21203                    % Timedelta::NANOS_PER_DAY as u64) as i64;
21204                Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
21205            })
21206            .collect::<Vec<_>>();
21207        for timestamp in &input {
21208            assert_eq!(former(timestamp), candidate(timestamp));
21209        }
21210
21211        for _ in 0..3 {
21212            black_box(elapsed(&input, former));
21213            black_box(elapsed(&input, candidate));
21214        }
21215
21216        let mut former_ns = Vec::with_capacity(SAMPLES);
21217        let mut candidate_ns = Vec::with_capacity(SAMPLES);
21218        for sample in 0..SAMPLES {
21219            if sample % 2 == 0 {
21220                former_ns.push(elapsed(&input, former));
21221                candidate_ns.push(elapsed(&input, candidate));
21222            } else {
21223                candidate_ns.push(elapsed(&input, candidate));
21224                former_ns.push(elapsed(&input, former));
21225            }
21226        }
21227
21228        let mut former_sorted = former_ns.clone();
21229        let mut candidate_sorted = candidate_ns.clone();
21230        let former_p50 = percentile(&mut former_sorted, 50);
21231        let former_p95 = percentile(&mut former_sorted, 95);
21232        let former_p99 = percentile(&mut former_sorted, 99);
21233        let candidate_p50 = percentile(&mut candidate_sorted, 50);
21234        let candidate_p95 = percentile(&mut candidate_sorted, 95);
21235        let candidate_p99 = percentile(&mut candidate_sorted, 99);
21236        println!(
21237            "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:?}",
21238            former_p50 as f64 / candidate_p50 as f64,
21239            former_p95 as f64 / candidate_p95 as f64,
21240            former_p99 as f64 / candidate_p99 as f64,
21241        );
21242    }
21243
21244    #[test]
21245    fn timestamp_unit_rounding_unknown_unit_returns_nat() {
21246        let ts = Timestamp::from_nanos(100);
21247        assert!(ts.floor_to_unit("fortnight").is_nat());
21248        assert!(ts.ceil_to_unit("century").is_nat());
21249        assert!(ts.round_to_unit("xyz").is_nat());
21250    }
21251
21252    /// pd.Timestamp('2024-03-15 13:47:21').round('15min') is 13:45 (a
21253    /// multiple of a unit was unknown here: NaT).
21254    #[test]
21255    fn timestamp_rounding_reads_a_multiple_of_a_unit_3agof() {
21256        let (min, sec) = (Timedelta::NANOS_PER_MIN, Timedelta::NANOS_PER_SEC);
21257        let base = 1_710_460_800 * sec; // 2024-03-15 00:00:00
21258        let ts = Timestamp::from_nanos(base + 13 * Timedelta::NANOS_PER_HOUR + 47 * min + 21 * sec);
21259        let at = |minutes: i64, seconds: i64| base + minutes * min + seconds * sec;
21260        assert_eq!(ts.round("15min").nanos, at(13 * 60 + 45, 0));
21261        assert_eq!(ts.floor("15min").nanos, at(13 * 60 + 45, 0));
21262        assert_eq!(ts.ceil("15min").nanos, at(14 * 60, 0));
21263        assert_eq!(ts.round("30s").nanos, at(13 * 60 + 47, 30));
21264        assert_eq!(ts.ceil("1D").nanos, base + Timedelta::NANOS_PER_DAY);
21265        // 2024-03-15 is 19797 days after the epoch: the 7-day floor is day
21266        // 19796 (2024-03-14), as pandas'.
21267        assert_eq!(ts.floor("7D").nanos, 19_796 * Timedelta::NANOS_PER_DAY);
21268        // NEGATIVE: a calendar frequency is no fixed length.
21269        assert!(ts.round("ME").is_nat());
21270    }
21271
21272    #[test]
21273    fn timestamp_unit_rounding_propagates_nat() {
21274        let nat = Timestamp::nat();
21275        assert!(nat.floor_to_unit("H").is_nat());
21276        assert!(nat.ceil_to_unit("H").is_nat());
21277        assert!(nat.round_to_unit("H").is_nat());
21278    }
21279
21280    #[test]
21281    fn timestamp_unit_rounding_preserves_tz() {
21282        let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
21283        assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21284        assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21285        assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21286    }
21287
21288    #[test]
21289    fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
21290        // Public surface check: pandas alias core set.
21291        assert_eq!(
21292            Timedelta::unit_to_nanos("W"),
21293            Some(Timedelta::NANOS_PER_WEEK)
21294        );
21295        assert_eq!(
21296            Timedelta::unit_to_nanos("D"),
21297            Some(Timedelta::NANOS_PER_DAY)
21298        );
21299        assert_eq!(
21300            Timedelta::unit_to_nanos("H"),
21301            Some(Timedelta::NANOS_PER_HOUR)
21302        );
21303        assert_eq!(
21304            Timedelta::unit_to_nanos("min"),
21305            Some(Timedelta::NANOS_PER_MIN)
21306        );
21307        assert_eq!(
21308            Timedelta::unit_to_nanos("s"),
21309            Some(Timedelta::NANOS_PER_SEC)
21310        );
21311        assert_eq!(
21312            Timedelta::unit_to_nanos("ms"),
21313            Some(Timedelta::NANOS_PER_MILLI)
21314        );
21315        assert_eq!(
21316            Timedelta::unit_to_nanos("us"),
21317            Some(Timedelta::NANOS_PER_MICRO)
21318        );
21319        assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
21320        // Empty string → days (pandas default).
21321        assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
21322        // Unknown alias → None.
21323        assert_eq!(Timedelta::unit_to_nanos("century"), None);
21324    }
21325
21326    #[test]
21327    fn timestamp_isoformat_basic() {
21328        let ts = Timestamp::from_nanos(0);
21329        assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
21330
21331        let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
21332        assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
21333
21334        let ts_fixed_offset = Timestamp::from_nanos_tz(0, "UTC+05:30");
21335        assert_eq!(
21336            ts_fixed_offset.isoformat(),
21337            "1970-01-01T05:30:00+05:30",
21338            "a fixed-offset timestamp must render local wall time rather than a UTC instant with an annotation"
21339        );
21340
21341        let ts_tz = Timestamp::from_nanos_tz(
21342            Timedelta::NANOS_PER_DAY
21343                + Timedelta::NANOS_PER_HOUR * 14
21344                + Timedelta::NANOS_PER_MIN * 30,
21345            "America/New_York",
21346        );
21347        assert_eq!(ts_tz.isoformat(), "1970-01-02T09:30:00-05:00");
21348
21349        assert_eq!(Timestamp::nat().isoformat(), "NaT");
21350    }
21351
21352    #[test]
21353    fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
21354        assert_eq!(
21355            Timestamp::from_nanos(-1).isoformat(),
21356            "1969-12-31T23:59:59.999999999"
21357        );
21358        assert_eq!(
21359            Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
21360            "1969-12-31T23:59:59"
21361        );
21362        assert_eq!(
21363            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
21364            "1969-12-31T00:00:00"
21365        );
21366        assert_eq!(
21367            Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
21368            "1969-12-31T23:59:59.999999999+00:00"
21369        );
21370    }
21371
21372    #[test]
21373    fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
21374        assert_eq!(
21375            Timestamp::from_nanos(123_456_789).isoformat(),
21376            "1970-01-01T00:00:00.123456789"
21377        );
21378        assert_eq!(
21379            Timestamp::from_nanos(123_456_000).isoformat(),
21380            "1970-01-01T00:00:00.123456"
21381        );
21382        assert_eq!(
21383            Timestamp::from_nanos(123_000_000).isoformat(),
21384            "1970-01-01T00:00:00.123000"
21385        );
21386        assert_eq!(
21387            Timestamp::from_nanos_tz(1, "UTC").isoformat(),
21388            "1970-01-01T00:00:00.000000001+00:00"
21389        );
21390    }
21391
21392    fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
21393        if timestamp.is_nat() {
21394            return "NaT".to_owned();
21395        }
21396        let Some(tz) = &timestamp.tz else {
21397            return Timestamp::from_nanos(timestamp.nanos).isoformat();
21398        };
21399        if let Ok(offset_secs) = crate::tz_offset_seconds(tz, timestamp.nanos)
21400            && let Some(display_nanos) = timestamp
21401                .nanos
21402                .checked_add(i64::from(offset_secs) * Timedelta::NANOS_PER_SEC)
21403        {
21404            let base = Timestamp::from_nanos(display_nanos).isoformat();
21405            let sign = if offset_secs < 0 { '-' } else { '+' };
21406            let total_minutes = offset_secs.unsigned_abs() / 60;
21407            return format!(
21408                "{base}{sign}{:02}:{:02}",
21409                total_minutes / 60,
21410                total_minutes % 60
21411            );
21412        }
21413        let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
21414        format!("{base}[{tz}]")
21415    }
21416
21417    #[test]
21418    fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
21419        let nanos = [
21420            Timestamp::NAT,
21421            -Timedelta::NANOS_PER_DAY - 1,
21422            -Timedelta::NANOS_PER_SEC,
21423            -1,
21424            0,
21425            1,
21426            123_456_000,
21427            123_456_789,
21428            i64::MAX,
21429        ];
21430        let timezones = [
21431            None,
21432            Some("UTC"),
21433            Some("America/New_York"),
21434            Some(""),
21435            Some("Etc/Γ"),
21436        ];
21437        for value in nanos {
21438            for timezone in timezones {
21439                let timestamp = Timestamp {
21440                    nanos: value,
21441                    tz: timezone.map(str::to_owned),
21442                };
21443                assert_eq!(
21444                    timestamp.isoformat(),
21445                    timestamp_isoformat_former_q8g50(&timestamp),
21446                    "nanos={value} timezone={timezone:?}"
21447                );
21448            }
21449        }
21450    }
21451
21452    #[test]
21453    #[ignore = "foreground release A/B only"]
21454    fn timestamp_isoformat_one_buffer_ab_q8g50() {
21455        use std::{hint::black_box, time::Instant};
21456
21457        const ITEMS: usize = 8_192;
21458        const SAMPLES: usize = 10;
21459
21460        fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
21461            let started = Instant::now();
21462            let mut checksum = 0usize;
21463            for timestamp in black_box(values) {
21464                checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
21465            }
21466            black_box(checksum);
21467            started.elapsed().as_nanos()
21468        }
21469
21470        let values = (0..ITEMS)
21471            .map(|idx| {
21472                let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
21473                let timezone = if idx.is_multiple_of(2) {
21474                    "UTC"
21475                } else {
21476                    "America/New_York"
21477                };
21478                Timestamp::from_nanos_tz(nanos, timezone)
21479            })
21480            .collect::<Vec<_>>();
21481        for timestamp in &values {
21482            assert_eq!(
21483                timestamp.isoformat(),
21484                timestamp_isoformat_former_q8g50(timestamp)
21485            );
21486        }
21487
21488        black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
21489        black_box(elapsed(&values, Timestamp::isoformat));
21490
21491        let mut former_ns = Vec::with_capacity(SAMPLES);
21492        let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
21493        for sample in 0..SAMPLES {
21494            if sample.is_multiple_of(2) {
21495                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
21496                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
21497            } else {
21498                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
21499                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
21500            }
21501        }
21502        former_ns.sort_unstable();
21503        one_buffer_ns.sort_unstable();
21504        let former_p50 = former_ns[SAMPLES / 2];
21505        let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
21506        println!(
21507            "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
21508            former_p50 as f64 / one_buffer_p50 as f64
21509        );
21510        println!("former_samples_ns={former_ns:?}");
21511        println!("one_buffer_samples_ns={one_buffer_ns:?}");
21512    }
21513
21514    #[test]
21515    fn timestamp_strftime_basic() {
21516        let ts = Timestamp::from_nanos(
21517            Timedelta::NANOS_PER_DAY * 365
21518                + Timedelta::NANOS_PER_HOUR * 9
21519                + Timedelta::NANOS_PER_MIN * 15,
21520        );
21521        assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
21522        assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
21523        assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
21524        // TEST-CHANGE: this pinned `%%Y` -> `%1971`; Python (CPython 3.13,
21525        // measured) prints `%%` as a literal `%` and echoes unknown `%Q`.
21526        assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%Y|%01|%Q|%|λ");
21527        assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
21528    }
21529
21530    #[test]
21531    fn strftime_follows_python_directives_and_zones() {
21532        // 1971-01-01 09:15 (a Friday; ISO week 53 of 1970). Expected texts
21533        // are CPython 3.13's datetime.strftime on Linux.
21534        let ts = Timestamp::from_nanos(
21535            Timedelta::NANOS_PER_DAY * 365
21536                + Timedelta::NANOS_PER_HOUR * 9
21537                + Timedelta::NANOS_PER_MIN * 15,
21538        );
21539        assert_eq!(
21540            ts.strftime("%-d %_m %^a %e %k %l %P %C %g %D %F %T %R %r %h %n %t|"),
21541            "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|"
21542        );
21543        assert_eq!(
21544            ts.strftime("%a %A %b %B %c|%x %X|%I %p %j %U %W %w %y"),
21545            "Fri Friday Jan January Fri Jan  1 09:15:00 1971|01/01/71 09:15:00|09 AM 001 00 00 5 71"
21546        );
21547        // 2021-01-03: a Sunday, ISO 2020-W53-7.
21548        let sunday = Timestamp::parse("2021-01-03").expect("date");
21549        assert_eq!(sunday.strftime("%G-%V-%u %U %W %j"), "2020-53-7 01 00 003");
21550        // Microseconds only; a trailing lone percent stays; naive %z / %Z empty.
21551        let fraction = Timestamp::parse("2024-03-05 14:07:09.123456789").expect("ts");
21552        assert_eq!(fraction.strftime("%f|%z|%Z|abc%"), "123456|||abc%");
21553        // A tz-aware Timestamp prints its wall clock and zone.
21554        let eastern = Timestamp::from_nanos_tz(fraction.nanos, "US/Eastern");
21555        assert_eq!(
21556            eastern.strftime("%Y-%m-%d %H:%M %z %Z"),
21557            "2024-03-05 09:07 -0500 EST"
21558        );
21559        assert_eq!(
21560            crate::strftime_in_zone(fraction.nanos, "%H:%M %z", Some("+05:30")),
21561            "19:37 +0530"
21562        );
21563    }
21564
21565    #[test]
21566    fn timestamp_strftime_floors_pre_epoch_instants_1pmlp() {
21567        let apollo = Timestamp::parse("1969-07-20T20:17:40").unwrap();
21568        assert_eq!(
21569            apollo.strftime("%Y-%m-%d %H:%M:%S.%f"),
21570            "1969-07-20 20:17:40.000000"
21571        );
21572
21573        // The smallest negative instant catches both truncation defects:
21574        // second flooring and day flooring.
21575        let one_ns_before_epoch = Timestamp::from_nanos(-1);
21576        assert_eq!(
21577            one_ns_before_epoch.strftime("%Y-%m-%d %H:%M:%S.%f"),
21578            "1969-12-31 23:59:59.999999"
21579        );
21580    }
21581
21582    #[test]
21583    #[ignore = "foreground normal-release attribution harness"]
21584    fn timestamp_strftime_one_buffer_profile_8qzbo() {
21585        use std::{hint::black_box, time::Instant};
21586
21587        const ITEMS: usize = 8_192;
21588        const SAMPLES: usize = 10;
21589        const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
21590
21591        fn former(timestamp: &Timestamp, format: &str) -> String {
21592            if timestamp.is_nat() {
21593                return "NaT".to_string();
21594            }
21595            let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
21596            let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
21597
21598            let days_since_epoch = total_secs / 86400;
21599            let secs_of_day = (total_secs % 86400 + 86400) % 86400;
21600            let days = days_since_epoch + 719_468;
21601            let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
21602            let doe = days - era * 146_097;
21603            let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
21604            let y = yoe + era * 400;
21605            let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
21606            let mp = (5 * doy + 2) / 153;
21607            let d = doy - (153 * mp + 2) / 5 + 1;
21608            let m = if mp < 10 { mp + 3 } else { mp - 9 };
21609            let year = if m <= 2 { y + 1 } else { y };
21610            let hour = secs_of_day / 3600;
21611            let minute = (secs_of_day % 3600) / 60;
21612            let second = secs_of_day % 60;
21613            let micros = sub_nanos / 1000;
21614
21615            format
21616                .replace("%Y", &format!("{year:04}"))
21617                .replace("%m", &format!("{m:02}"))
21618                .replace("%d", &format!("{d:02}"))
21619                .replace("%H", &format!("{hour:02}"))
21620                .replace("%M", &format!("{minute:02}"))
21621                .replace("%S", &format!("{second:02}"))
21622                .replace("%f", &format!("{micros:06}"))
21623        }
21624
21625        fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
21626            let started = Instant::now();
21627            let mut digest = 0_usize;
21628            for timestamp in timestamps {
21629                let value = formatter(black_box(timestamp), black_box(FORMAT));
21630                digest = digest.wrapping_add(value.len());
21631                digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
21632                black_box(value);
21633            }
21634            black_box(digest);
21635            started.elapsed().as_nanos()
21636        }
21637
21638        fn percentile(samples: &mut [u128], pct: usize) -> u128 {
21639            samples.sort_unstable();
21640            let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
21641            samples[rank]
21642        }
21643
21644        let edge_timestamps = [
21645            Timestamp::nat(),
21646            Timestamp::from_nanos(i64::MIN + 1),
21647            Timestamp::from_nanos(-1_234_567_890),
21648            Timestamp::from_nanos(0),
21649            Timestamp::from_nanos(1_735_732_800_123_456_789),
21650            Timestamp::from_nanos(i64::MAX),
21651        ];
21652        let edge_formats = [
21653            "",
21654            "%Y-%m-%d %H:%M:%S.%f",
21655            "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
21656            "%%Y|%%%m|%Q|%|λ",
21657            FORMAT,
21658        ];
21659        for timestamp in &edge_timestamps {
21660            for format in edge_formats {
21661                assert_eq!(former(timestamp, format), timestamp.strftime(format));
21662            }
21663        }
21664
21665        let timestamps = (0..ITEMS)
21666            .map(|index| {
21667                let centered = index as i64 - ITEMS as i64 / 2;
21668                Timestamp::from_nanos(centered * 987_654_321_123_456)
21669            })
21670            .collect::<Vec<_>>();
21671        for timestamp in &timestamps {
21672            assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
21673        }
21674
21675        black_box(elapsed(&timestamps, former));
21676        black_box(elapsed(&timestamps, Timestamp::strftime));
21677
21678        let mut former_samples = Vec::with_capacity(SAMPLES);
21679        let mut public_samples = Vec::with_capacity(SAMPLES);
21680        for sample in 0..SAMPLES {
21681            if sample.is_multiple_of(2) {
21682                former_samples.push(elapsed(&timestamps, former));
21683                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
21684            } else {
21685                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
21686                former_samples.push(elapsed(&timestamps, former));
21687            }
21688        }
21689        let former_p50 = percentile(&mut former_samples, 50);
21690        let former_p95 = percentile(&mut former_samples, 95);
21691        let public_p50 = percentile(&mut public_samples, 50);
21692        let public_p95 = percentile(&mut public_samples, 95);
21693        println!(
21694            "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}",
21695            former_p50 as f64 / public_p50 as f64,
21696            former_p95 as f64 / public_p95 as f64,
21697        );
21698        println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
21699        println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
21700    }
21701
21702    #[test]
21703    fn timestamp_day_name_and_month_name() {
21704        let ts = Timestamp::from_nanos(0);
21705        assert_eq!(ts.day_name(), "Thursday");
21706        assert_eq!(ts.month_name(), "January");
21707
21708        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
21709        assert_eq!(ts2.day_name(), "Friday");
21710        assert_eq!(ts2.month_name(), "January");
21711
21712        assert_eq!(Timestamp::nat().day_name(), "NaT");
21713        assert_eq!(Timestamp::nat().month_name(), "NaT");
21714    }
21715
21716    #[test]
21717    fn timestamp_replace_validates_components_zw0y2() {
21718        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
21719        let replaced = ts.replace(
21720            Some(2024),
21721            Some(2),
21722            Some(29),
21723            Some(23),
21724            Some(59),
21725            Some(58),
21726            Some(987_654),
21727            Some(321),
21728        );
21729        assert_eq!(replaced.year(), Some(2024));
21730        assert_eq!(replaced.month(), Some(2));
21731        assert_eq!(replaced.day(), Some(29));
21732        assert_eq!(replaced.hour(), Some(23));
21733        assert_eq!(replaced.minute(), Some(59));
21734        assert_eq!(replaced.second(), Some(58));
21735        assert_eq!(replaced.microsecond(), Some(987_654));
21736        assert_eq!(replaced.nanosecond(), Some(321));
21737
21738        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
21739        assert_eq!(
21740            tz.replace(None, Some(2), Some(29), None, None, None, None, None)
21741                .tz
21742                .as_deref(),
21743            Some("UTC")
21744        );
21745
21746        assert!(
21747            ts.replace(None, Some(13), None, None, None, None, None, None)
21748                .is_nat()
21749        );
21750        assert!(
21751            ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
21752                .is_nat()
21753        );
21754        assert!(
21755            ts.replace(None, None, None, Some(24), None, None, None, None)
21756                .is_nat()
21757        );
21758        assert!(
21759            ts.replace(None, None, None, None, Some(60), None, None, None)
21760                .is_nat()
21761        );
21762        assert!(
21763            ts.replace(None, None, None, None, None, Some(60), None, None)
21764                .is_nat()
21765        );
21766        assert!(
21767            ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
21768                .is_nat()
21769        );
21770        assert!(
21771            ts.replace(None, None, None, None, None, None, None, Some(1_000))
21772                .is_nat()
21773        );
21774        assert!(
21775            Timestamp::nat()
21776                .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
21777                .is_nat()
21778        );
21779    }
21780
21781    /// br-frankenpandas-dzz6x: `replace` validates every component EXCEPT the
21782    /// year, and i64 nanoseconds run out around year 2262. The old unchecked
21783    /// multiply wrapped in release mode and handed back a plausible-looking
21784    /// in-range instant for an unrepresentable year — the exact failure a naive
21785    /// implementation still produces, so each far-out year below is a real
21786    /// negative case, not a restatement of the code.
21787    #[test]
21788    fn timestamp_replace_returns_nat_on_nanosecond_overflow_dzz6x() {
21789        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
21790
21791        for year in [3000, 10_000, 300_000, i64::MAX / 400] {
21792            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
21793            assert!(
21794                out.is_nat(),
21795                "replace(year={year}) is unrepresentable in i64 ns and must be \
21796                 NaT, got nanos={:?} (year {:?}) — this is the silent wrap",
21797                out.nanos,
21798                out.year()
21799            );
21800        }
21801        for year in [-3000, -100_000, i64::MIN / 400] {
21802            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
21803            assert!(out.is_nat(), "replace(year={year}) must be NaT");
21804        }
21805
21806        // Boundary: i64 ns tops out at 106_751 days from the epoch, so 2262 is
21807        // representable at the start of the year and 2263 is not. This pins the
21808        // fix to the real limit — a guard that merely rejected "big" years by
21809        // some rounder cutoff would fail one side of this pair.
21810        let in_range = ts.replace(
21811            Some(2262),
21812            Some(1),
21813            Some(1),
21814            Some(0),
21815            Some(0),
21816            Some(0),
21817            Some(0),
21818            Some(0),
21819        );
21820        assert!(
21821            !in_range.is_nat(),
21822            "2262-01-01 is representable and must survive"
21823        );
21824        assert_eq!(in_range.year(), Some(2262));
21825        assert!(
21826            ts.replace(
21827                Some(2263),
21828                Some(12),
21829                Some(31),
21830                Some(23),
21831                Some(59),
21832                Some(59),
21833                Some(999_999),
21834                Some(999)
21835            )
21836            .is_nat(),
21837            "end of 2263 exceeds the i64 ns axis and must be NaT"
21838        );
21839
21840        // In-range results are untouched by the checked arithmetic, including
21841        // the timezone, so the guard cannot have been bought with a behavior
21842        // change on the normal path.
21843        let unchanged = ts.replace(
21844            Some(1999),
21845            Some(6),
21846            Some(30),
21847            Some(12),
21848            Some(1),
21849            Some(2),
21850            Some(3),
21851            Some(4),
21852        );
21853        assert_eq!(unchanged.year(), Some(1999));
21854        assert_eq!(unchanged.month(), Some(6));
21855        assert_eq!(unchanged.day(), Some(30));
21856        assert_eq!(unchanged.hour(), Some(12));
21857        assert_eq!(unchanged.minute(), Some(1));
21858        assert_eq!(unchanged.second(), Some(2));
21859        assert_eq!(unchanged.microsecond(), Some(3));
21860        assert_eq!(unchanged.nanosecond(), Some(4));
21861        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
21862        assert_eq!(
21863            tz.replace(Some(1999), None, None, None, None, None, None, None)
21864                .tz
21865                .as_deref(),
21866            Some("UTC")
21867        );
21868    }
21869
21870    #[test]
21871    fn timestamp_component_accessors() {
21872        let ts = Timestamp::from_nanos(0);
21873        assert_eq!(ts.year(), Some(1970));
21874        assert_eq!(ts.month(), Some(1));
21875        assert_eq!(ts.day(), Some(1));
21876        assert_eq!(ts.hour(), Some(0));
21877        assert_eq!(ts.minute(), Some(0));
21878        assert_eq!(ts.second(), Some(0));
21879        assert_eq!(ts.microsecond(), Some(0));
21880        assert_eq!(ts.nanosecond(), Some(0));
21881
21882        let ts2 = Timestamp::from_nanos(
21883            Timedelta::NANOS_PER_DAY * 365
21884                + Timedelta::NANOS_PER_HOUR * 14
21885                + Timedelta::NANOS_PER_MIN * 30
21886                + Timedelta::NANOS_PER_SEC * 45
21887                + 123_456_789,
21888        );
21889        assert_eq!(ts2.year(), Some(1971));
21890        assert_eq!(ts2.month(), Some(1));
21891        assert_eq!(ts2.day(), Some(1));
21892        assert_eq!(ts2.hour(), Some(14));
21893        assert_eq!(ts2.minute(), Some(30));
21894        assert_eq!(ts2.second(), Some(45));
21895        assert_eq!(ts2.microsecond(), Some(123456));
21896        assert_eq!(ts2.nanosecond(), Some(789));
21897
21898        assert_eq!(Timestamp::nat().year(), None);
21899        assert_eq!(Timestamp::nat().month(), None);
21900        assert_eq!(Timestamp::nat().day(), None);
21901    }
21902
21903    #[test]
21904    fn timestamp_dayofweek_dayofyear_quarter() {
21905        let ts = Timestamp::from_nanos(0);
21906        assert_eq!(ts.dayofweek(), Some(3));
21907        assert_eq!(ts.weekday(), Some(3));
21908        assert_eq!(ts.dayofyear(), Some(1));
21909        assert_eq!(ts.quarter(), Some(1));
21910
21911        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
21912        assert_eq!(ts2.quarter(), Some(2));
21913
21914        let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
21915        assert_eq!(ts3.dayofyear(), Some(1));
21916        assert_eq!(ts3.dayofweek(), Some(4));
21917
21918        assert_eq!(Timestamp::nat().dayofweek(), None);
21919        assert_eq!(Timestamp::nat().dayofyear(), None);
21920        assert_eq!(Timestamp::nat().quarter(), None);
21921    }
21922
21923    #[test]
21924    fn timestamp_is_boundary_methods() {
21925        let jan1 = Timestamp::from_nanos(0);
21926        assert_eq!(jan1.is_leap_year(), Some(false));
21927        assert_eq!(jan1.is_month_start(), Some(true));
21928        assert_eq!(jan1.is_month_end(), Some(false));
21929        assert_eq!(jan1.is_quarter_start(), Some(true));
21930        assert_eq!(jan1.is_quarter_end(), Some(false));
21931        assert_eq!(jan1.is_year_start(), Some(true));
21932        assert_eq!(jan1.is_year_end(), Some(false));
21933
21934        let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
21935        assert_eq!(dec31.is_month_start(), Some(false));
21936        assert_eq!(dec31.is_month_end(), Some(true));
21937        assert_eq!(dec31.is_quarter_end(), Some(true));
21938        assert_eq!(dec31.is_year_end(), Some(true));
21939
21940        assert_eq!(Timestamp::nat().is_leap_year(), None);
21941        assert_eq!(Timestamp::nat().is_month_start(), None);
21942    }
21943
21944    #[test]
21945    fn timestamp_days_in_month() {
21946        let jan = Timestamp::from_nanos(0);
21947        assert_eq!(jan.days_in_month(), Some(31));
21948        assert_eq!(jan.daysinmonth(), Some(31));
21949
21950        let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
21951        assert_eq!(feb_non_leap.days_in_month(), Some(28));
21952
21953        assert_eq!(Timestamp::nat().days_in_month(), None);
21954    }
21955
21956    #[test]
21957    fn timestamp_weekofyear() {
21958        let jan1 = Timestamp::from_nanos(0);
21959        assert_eq!(jan1.weekofyear(), Some(1));
21960        assert_eq!(jan1.week(), Some(1));
21961
21962        let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
21963        assert_eq!(jan8.weekofyear(), Some(2));
21964
21965        assert_eq!(Timestamp::nat().weekofyear(), None);
21966        assert_eq!(Timestamp::nat().week(), None);
21967    }
21968
21969    #[test]
21970    fn timestamp_weekofyear_iso_53_week_boundaries() {
21971        // ISO-8601 53-week-year boundaries vs pandas 2.2.3 isocalendar().week.
21972        // (br-frankenpandas-xmfmd) Date -> nanos via days since 1970-01-01.
21973        fn week_of(date_days: i64) -> Option<i64> {
21974            Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
21975        }
21976        // Days from 1970-01-01 for each date (UTC, no tz).
21977        // 2021-01-01 -> week 53 (2020 is a 53-week year); FP used to give 52.
21978        assert_eq!(week_of(18_628), Some(53)); // 2021-01-01
21979        // 2016-01-01 -> week 53 (2015 is a 53-week year).
21980        assert_eq!(week_of(16_801), Some(53)); // 2016-01-01
21981        // 2026-12-31 -> week 53; FP used to give 1.
21982        assert_eq!(week_of(20_818), Some(53)); // 2026-12-31
21983        // 2020-12-31 -> week 53.
21984        assert_eq!(week_of(18_627), Some(53)); // 2020-12-31
21985        // Cases that must stay correct (non-53 boundaries):
21986        assert_eq!(week_of(19_358), Some(52)); // 2023-01-01 -> week 52
21987        assert_eq!(week_of(20_087), Some(1)); // 2024-12-30 -> week 1
21988        assert_eq!(week_of(18_260), Some(1)); // 2019-12-30 -> week 1
21989    }
21990
21991    #[test]
21992    fn iso_weeks_in_year_53_week_years() {
21993        use super::iso_weeks_in_year;
21994        // Known 53-week years; everything else is 52.
21995        for y in [2004, 2009, 2015, 2020, 2026] {
21996            assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
21997        }
21998        for y in [2018, 2019, 2021, 2022, 2023, 2024] {
21999            assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
22000        }
22001    }
22002
22003    #[test]
22004    fn timestamp_to_unit() {
22005        let ts = Timestamp::from_nanos(1_000_000_000);
22006        assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
22007        assert_eq!(ts.to_unit("us"), Some(1_000_000));
22008        assert_eq!(ts.to_unit("ms"), Some(1_000));
22009        assert_eq!(ts.to_unit("s"), Some(1));
22010        assert_eq!(ts.to_unit("invalid"), None);
22011
22012        assert_eq!(Timestamp::nat().to_unit("ns"), None);
22013    }
22014
22015    #[test]
22016    fn timestamp_toordinal() {
22017        // 2026-01-01 is ordinal 738886 (days since Jan 1, year 1)
22018        // Days from Unix epoch: 738886 - 719163 = 19723
22019        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
22020        let ts = Timestamp::from_nanos(nanos_2026_01_01);
22021        assert_eq!(ts.toordinal(), Some(738886));
22022
22023        // NaT returns None
22024        assert_eq!(Timestamp::nat().toordinal(), None);
22025    }
22026
22027    #[test]
22028    fn timestamp_fromordinal() {
22029        // Round-trip test: create a timestamp from ordinal derived from toordinal
22030        // First create a known timestamp
22031        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
22032        let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
22033        let ordinal = ts_orig.toordinal().unwrap();
22034
22035        // Now convert back using fromordinal
22036        let ts = Timestamp::fromordinal(ordinal);
22037        assert_eq!(ts.year(), ts_orig.year());
22038        assert_eq!(ts.month(), ts_orig.month());
22039        assert_eq!(ts.day(), ts_orig.day());
22040
22041        // Invalid ordinal returns NaT
22042        let nat = Timestamp::fromordinal(0);
22043        assert!(nat.is_nat());
22044    }
22045
22046    #[test]
22047    fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
22048        const EPOCH_ORDINAL: i64 = 719_163;
22049        let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
22050        let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
22051
22052        let max_valid = Timestamp::fromordinal(max_valid_ordinal);
22053        assert!(!max_valid.is_nat());
22054        assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
22055
22056        assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
22057        assert!(Timestamp::fromordinal(i64::MAX).is_nat());
22058    }
22059
22060    #[test]
22061    fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
22062        const EPOCH_ORDINAL: i64 = 719_163;
22063        const DAY: i64 = Timedelta::NANOS_PER_DAY;
22064
22065        fn next(seed: &mut u64) -> u64 {
22066            *seed = seed
22067                .wrapping_mul(3202034522624059733)
22068                .wrapping_add(4354685564936845319);
22069            *seed
22070        }
22071
22072        fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
22073            let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
22074            let ts = Timestamp::from_nanos(nanos);
22075            let expected_day_offset = nanos.div_euclid(DAY);
22076            let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
22077
22078            assert_eq!(
22079                ts.toordinal(),
22080                Some(expected_ordinal),
22081                "case {case}: toordinal"
22082            );
22083
22084            let midnight = Timestamp::fromordinal(expected_ordinal);
22085            assert_eq!(
22086                midnight.nanos,
22087                expected_day_offset * DAY,
22088                "case {case}: fromordinal nanos"
22089            );
22090            assert_eq!(
22091                midnight.toordinal(),
22092                Some(expected_ordinal),
22093                "case {case}: fromordinal roundtrip"
22094            );
22095        }
22096
22097        assert_eq!(Timestamp::nat().toordinal(), None);
22098        assert!(Timestamp::fromordinal(0).is_nat());
22099        assert!(Timestamp::fromordinal(-1).is_nat());
22100
22101        assert_ordinal_case(usize::MAX, -1, DAY - 1);
22102        assert_ordinal_case(usize::MAX - 1, 0, -1);
22103        assert_ordinal_case(usize::MAX - 2, 19_723, 0);
22104
22105        let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
22106        for case in 0..260 {
22107            let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
22108            let subday_nanos = match case % 7 {
22109                0 => 0,
22110                1 => DAY - 1,
22111                2 => -1,
22112                _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
22113            };
22114            assert_ordinal_case(case, day_offset, subday_nanos);
22115        }
22116    }
22117
22118    /// br-frankenpandas-94o1u: `parse_date` bounds the month and the day but
22119    /// parses the YEAR as an unbounded i64, and i64 nanoseconds top out around
22120    /// 2262. The old unchecked composition wrapped in release, so these inputs
22121    /// returned `Ok` holding a plausible in-range instant instead of failing —
22122    /// on the INGESTION path, where the input is untrusted. Each case below is
22123    /// a real negative case: a naive implementation still returns Ok here.
22124    #[test]
22125    fn timestamp_parse_rejects_unrepresentable_years_94o1u() {
22126        for s in [
22127            "300000-01-01",
22128            "10000000-06-15T12:30:45",
22129            "999999999-01-01",
22130            "-300000-01-01",
22131            "-99999999-12-31T23:59:59",
22132        ] {
22133            let got = Timestamp::parse(s);
22134            assert!(
22135                got.is_err(),
22136                "parse({s:?}) is unrepresentable in i64 ns and must be Err, got {:?} \
22137                 — this is the silent wrap",
22138                got.map(|ts| (ts.nanos, ts.year()))
22139            );
22140        }
22141
22142        // Boundary: the i64 ns axis reaches into 2262 but not 2263. Pins the
22143        // guard to the real limit — a cutoff at some rounder year fails a side.
22144        let ok = Timestamp::parse("2262-01-01").expect("2262-01-01 is representable");
22145        assert_eq!(ok.year(), Some(2262));
22146        assert!(
22147            Timestamp::parse("2263-12-31T23:59:59").is_err(),
22148            "end of 2263 exceeds the i64 ns axis and must be Err"
22149        );
22150
22151        // A rejected year must not poison the normal path: ordinary parses,
22152        // including every accepted shape (date-only, T- and space-separated,
22153        // fractional seconds, tz suffix), still succeed and are unchanged.
22154        assert_eq!(Timestamp::parse("2024-01-15").unwrap().year(), Some(2024));
22155        assert_eq!(
22156            Timestamp::parse("2024-01-15T10:30:45").unwrap().hour(),
22157            Some(10)
22158        );
22159        assert_eq!(
22160            Timestamp::parse("2024-01-15 10:30:45").unwrap().minute(),
22161            Some(30)
22162        );
22163        assert_eq!(
22164            Timestamp::parse("2024-01-15T10:30:45.123456789")
22165                .unwrap()
22166                .nanosecond(),
22167            Some(789)
22168        );
22169        assert_eq!(
22170            Timestamp::parse("2024-01-15T00:00:00Z").unwrap().year(),
22171            Some(2024)
22172        );
22173        // Pre-epoch (negative nanos) is representable and must keep working.
22174        assert_eq!(Timestamp::parse("1900-01-01").unwrap().year(), Some(1900));
22175    }
22176
22177    #[test]
22178    fn timestamp_parse_iso8601_date_only() {
22179        let ts = Timestamp::parse("2024-01-15").unwrap();
22180        assert_eq!(ts.year(), Some(2024));
22181        assert_eq!(ts.month(), Some(1));
22182        assert_eq!(ts.day(), Some(15));
22183        assert_eq!(ts.hour(), Some(0));
22184        assert_eq!(ts.minute(), Some(0));
22185        assert_eq!(ts.second(), Some(0));
22186    }
22187
22188    #[test]
22189    fn timestamp_parse_iso8601_datetime() {
22190        let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
22191        assert_eq!(ts.year(), Some(2024));
22192        assert_eq!(ts.month(), Some(1));
22193        assert_eq!(ts.day(), Some(15));
22194        assert_eq!(ts.hour(), Some(10));
22195        assert_eq!(ts.minute(), Some(30));
22196        assert_eq!(ts.second(), Some(45));
22197    }
22198
22199    #[test]
22200    fn timestamp_parse_space_separator() {
22201        let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
22202        assert_eq!(ts.year(), Some(2024));
22203        assert_eq!(ts.hour(), Some(10));
22204    }
22205
22206    #[test]
22207    fn timestamp_parse_with_fractional_seconds() {
22208        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
22209        assert_eq!(ts.second(), Some(45));
22210        assert_eq!(ts.microsecond(), Some(123456));
22211        assert_eq!(ts.nanosecond(), Some(789));
22212    }
22213
22214    #[test]
22215    fn timestamp_parse_utc_timezone() {
22216        let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
22217        assert_eq!(ts.tz, Some("UTC".to_string()));
22218    }
22219
22220    #[test]
22221    fn timestamp_parse_offset_timezone() {
22222        let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
22223        assert_eq!(ts.tz, Some("+05:30".to_string()));
22224        // The instant is the wall time less the offset (it was the wall
22225        // time read as UTC).
22226        let utc = |text: &str| Timestamp::parse(text).unwrap().nanos;
22227        assert_eq!(ts.nanos, utc("2024-01-15T05:00:45"));
22228
22229        let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
22230        assert_eq!(ts.tz, Some("-05:30".to_string()));
22231        assert_eq!(ts.nanos, utc("2024-01-15T16:00:45"));
22232        // 'Z' is UTC itself.
22233        assert_eq!(
22234            Timestamp::parse("2024-01-15T10:30:45Z").unwrap().nanos,
22235            utc("2024-01-15T10:30:45")
22236        );
22237    }
22238
22239    #[test]
22240    fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
22241        assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
22242        assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
22243        assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
22244        assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
22245        assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
22246    }
22247
22248    #[test]
22249    fn timestamp_parse_nat() {
22250        let ts = Timestamp::parse("NaT").unwrap();
22251        assert!(ts.is_nat());
22252        let ts2 = Timestamp::parse("nat").unwrap();
22253        assert!(ts2.is_nat());
22254    }
22255
22256    #[test]
22257    fn timestamp_parse_invalid() {
22258        assert!(Timestamp::parse("not a date").is_err());
22259        assert!(Timestamp::parse("2024-13-01").is_err()); // invalid month
22260        assert!(Timestamp::parse("2024-01-32").is_err()); // invalid day
22261    }
22262
22263    #[test]
22264    fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
22265        assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
22266        assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
22267        assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
22268        assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
22269        assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
22270
22271        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
22272        assert_eq!(ts.second(), Some(45));
22273        assert_eq!(ts.microsecond(), Some(123456));
22274        assert_eq!(ts.nanosecond(), Some(789));
22275    }
22276
22277    #[test]
22278    #[ignore = "foreground profile-first A/B"]
22279    fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
22280        use std::{hint::black_box, time::Instant};
22281
22282        const CALLS: usize = 131_072;
22283        const SAMPLES: usize = 12;
22284        type ParsedTime = Option<(u32, u32, u32, u64)>;
22285        const VALID: [&str; 16] = [
22286            "00:00:00.0",
22287            "01:02:03.1",
22288            "02:03:04.01",
22289            "03:04:05.001",
22290            "04:05:06.0001",
22291            "05:06:07.00001",
22292            "06:07:08.000001",
22293            "07:08:09.0000001",
22294            "08:09:10.00000001",
22295            "09:10:11.000000001",
22296            "10:11:12.123456789",
22297            "11:12:13.999999999",
22298            "12:13:14.123456789987",
22299            "13:14:15.000000000001",
22300            "14:15:16.101010101010",
22301            "23:59:59.987654321234",
22302        ];
22303
22304        #[inline(never)]
22305        fn former(s: &str) -> ParsedTime {
22306            let (time_str, frac_str) = match s.split_once('.') {
22307                Some((time, frac)) => (time, Some(frac)),
22308                None => (s, None),
22309            };
22310            let parts: Vec<&str> = time_str.split(':').collect();
22311            if parts.is_empty() || parts.len() > 3 {
22312                return None;
22313            }
22314            let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
22315            let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
22316            let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
22317
22318            if hour > 23 || minute > 59 || second > 59 {
22319                return None;
22320            }
22321
22322            let nanos = match frac_str {
22323                None => 0,
22324                Some(frac) => {
22325                    if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
22326                        return None;
22327                    }
22328                    let truncated = &frac[..frac.len().min(9)];
22329                    let padded = format!("{truncated:0<9}");
22330                    padded.parse::<u64>().ok()?
22331                }
22332            };
22333
22334            Some((hour, minute, second, nanos))
22335        }
22336
22337        #[inline(never)]
22338        fn candidate(s: &str) -> ParsedTime {
22339            Timestamp::parse_time(s)
22340        }
22341
22342        fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
22343            let started = Instant::now();
22344            for input in black_box(inputs) {
22345                black_box(parser(black_box(*input)));
22346            }
22347            started.elapsed().as_nanos()
22348        }
22349
22350        fn percentile(samples: &[u128], percent: usize) -> u128 {
22351            let mut sorted = samples.to_vec();
22352            sorted.sort_unstable();
22353            let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
22354            sorted[rank]
22355        }
22356
22357        let invalid = [
22358            "",
22359            "24:00:00.1",
22360            "12:60:00.1",
22361            "12:00:60.1",
22362            "12:00:00.",
22363            "12:00:00.abc",
22364            "12:00:00.-1",
22365            "12:00:00.123",
22366            "12:00:00.123456789x",
22367            "12:00:00.1.2",
22368            "12:00:00:01.1",
22369        ];
22370        for input in VALID.iter().chain(invalid.iter()) {
22371            assert_eq!(candidate(input), former(input), "input={input:?}");
22372        }
22373
22374        let inputs = (0..CALLS)
22375            .map(|index| VALID[index % VALID.len()])
22376            .collect::<Vec<_>>();
22377        for _ in 0..2 {
22378            black_box(elapsed(&inputs, former));
22379            black_box(elapsed(&inputs, candidate));
22380        }
22381
22382        let mut former_ns = Vec::with_capacity(SAMPLES);
22383        let mut candidate_ns = Vec::with_capacity(SAMPLES);
22384        for sample in 0..SAMPLES {
22385            if sample.is_multiple_of(2) {
22386                former_ns.push(elapsed(&inputs, former));
22387                candidate_ns.push(elapsed(&inputs, candidate));
22388            } else {
22389                candidate_ns.push(elapsed(&inputs, candidate));
22390                former_ns.push(elapsed(&inputs, former));
22391            }
22392        }
22393
22394        let former_p50 = percentile(&former_ns, 50);
22395        let former_p95 = percentile(&former_ns, 95);
22396        let former_p99 = percentile(&former_ns, 99);
22397        let candidate_p50 = percentile(&candidate_ns, 50);
22398        let candidate_p95 = percentile(&candidate_ns, 95);
22399        let candidate_p99 = percentile(&candidate_ns, 99);
22400        println!(
22401            "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:?}",
22402            former_p50 as f64 / candidate_p50 as f64,
22403            former_p95 as f64 / candidate_p95 as f64,
22404            former_p99 as f64 / candidate_p99 as f64,
22405        );
22406    }
22407
22408    #[test]
22409    fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
22410        fn next(seed: &mut u64) -> u64 {
22411            *seed = seed
22412                .wrapping_mul(3935559000370003845)
22413                .wrapping_add(2691343689449507681);
22414            *seed
22415        }
22416
22417        fn leap(year: i64) -> bool {
22418            (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
22419        }
22420
22421        fn month_len(year: i64, month: u32) -> u32 {
22422            match month {
22423                1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
22424                4 | 6 | 9 | 11 => 30,
22425                2 if leap(year) => 29,
22426                2 => 28,
22427                _ => 0,
22428            }
22429        }
22430
22431        struct Components {
22432            year: i64,
22433            month: u32,
22434            day: u32,
22435            hour: u32,
22436            minute: u32,
22437            second: u32,
22438            nanos: u64,
22439        }
22440
22441        fn assert_components(case: usize, text: &str, expected: Components) {
22442            let ts = Timestamp::parse(text).expect("seeded valid timestamp");
22443            let Components {
22444                year,
22445                month,
22446                day,
22447                hour,
22448                minute,
22449                second,
22450                nanos,
22451            } = expected;
22452            assert_eq!(ts.year(), Some(year), "case {case}: year");
22453            assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
22454            assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
22455            assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
22456            assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
22457            assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
22458            assert_eq!(
22459                ts.microsecond(),
22460                Some((nanos / 1000) as i64),
22461                "case {case}: microsecond"
22462            );
22463            assert_eq!(
22464                ts.nanosecond(),
22465                Some((nanos % 1000) as i64),
22466                "case {case}: nanosecond"
22467            );
22468        }
22469
22470        assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
22471        assert!(
22472            Timestamp::parse("nAt")
22473                .expect("mixed-case NaT parses")
22474                .is_nat()
22475        );
22476        assert!(Timestamp::parse("1900-02-29").is_err());
22477        assert!(Timestamp::parse("2001-04-31").is_err());
22478        assert!(Timestamp::parse("2024-00-15").is_err());
22479
22480        assert_components(
22481            usize::MAX,
22482            "2000-02-29",
22483            Components {
22484                year: 2000,
22485                month: 2,
22486                day: 29,
22487                hour: 0,
22488                minute: 0,
22489                second: 0,
22490                nanos: 0,
22491            },
22492        );
22493        assert_components(
22494            usize::MAX - 1,
22495            "2024-02-29T23:59:59.000000001",
22496            Components {
22497                year: 2024,
22498                month: 2,
22499                day: 29,
22500                hour: 23,
22501                minute: 59,
22502                second: 59,
22503                nanos: 1,
22504            },
22505        );
22506
22507        let mut seed = 0x15e0_1d50_1f0a_cade_u64;
22508        for case in 0..260 {
22509            let year = 1900 + (next(&mut seed) % 201) as i64;
22510            let month = 1 + (next(&mut seed) % 12) as u32;
22511            let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
22512            let hour = (next(&mut seed) % 24) as u32;
22513            let minute = (next(&mut seed) % 60) as u32;
22514            let second = (next(&mut seed) % 60) as u32;
22515            let nanos = next(&mut seed) % 1_000_000_000;
22516
22517            match case % 4 {
22518                0 => {
22519                    let text = format!("{year:04}-{month:02}-{day:02}");
22520                    assert_components(
22521                        case,
22522                        &text,
22523                        Components {
22524                            year,
22525                            month,
22526                            day,
22527                            hour: 0,
22528                            minute: 0,
22529                            second: 0,
22530                            nanos: 0,
22531                        },
22532                    );
22533                }
22534                1 => {
22535                    let text =
22536                        format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
22537                    assert_components(
22538                        case,
22539                        &text,
22540                        Components {
22541                            year,
22542                            month,
22543                            day,
22544                            hour,
22545                            minute,
22546                            second,
22547                            nanos: 0,
22548                        },
22549                    );
22550                }
22551                2 => {
22552                    let text =
22553                        format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
22554                    assert_components(
22555                        case,
22556                        &text,
22557                        Components {
22558                            year,
22559                            month,
22560                            day,
22561                            hour,
22562                            minute,
22563                            second,
22564                            nanos: 0,
22565                        },
22566                    );
22567                }
22568                _ => {
22569                    let text = format!(
22570                        "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
22571                    );
22572                    assert_components(
22573                        case,
22574                        &text,
22575                        Components {
22576                            year,
22577                            month,
22578                            day,
22579                            hour,
22580                            minute,
22581                            second,
22582                            nanos,
22583                        },
22584                    );
22585                }
22586            }
22587        }
22588    }
22589
22590    #[test]
22591    fn period_parse_annual() {
22592        let p = Period::parse("2024").unwrap();
22593        assert_eq!(p.freq(), PeriodFreq::ANNUAL);
22594        assert_eq!(p.ordinal(), 2024 - 1970);
22595    }
22596
22597    #[test]
22598    fn period_parse_quarterly() {
22599        let p = Period::parse("2024Q1").unwrap();
22600        assert_eq!(p.freq(), PeriodFreq::QUARTERLY);
22601        assert_eq!(p.ordinal(), (2024 - 1970) * 4);
22602
22603        let p2 = Period::parse("2024q3").unwrap();
22604        assert_eq!(p2.freq(), PeriodFreq::QUARTERLY);
22605        assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
22606    }
22607
22608    #[test]
22609    fn period_parse_monthly() {
22610        let p = Period::parse("2024-01").unwrap();
22611        assert_eq!(p.freq(), PeriodFreq::Monthly);
22612        assert_eq!(p.ordinal(), (2024 - 1970) * 12);
22613
22614        let p2 = Period::parse("2024-12").unwrap();
22615        assert_eq!(p2.freq(), PeriodFreq::Monthly);
22616        assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
22617    }
22618
22619    #[test]
22620    fn period_parse_nat() {
22621        let p = Period::parse("NaT").unwrap();
22622        assert_eq!(p.ordinal(), i64::MIN);
22623    }
22624
22625    #[test]
22626    fn period_parse_invalid() {
22627        assert!(Period::parse("not a period").is_err());
22628        assert!(Period::parse("2024Q5").is_err()); // invalid quarter
22629        assert!(Period::parse("2024-13").is_err()); // invalid month
22630    }
22631
22632    #[test]
22633    fn interval_parse_basic() {
22634        let i = Interval::parse("[0, 1]").unwrap();
22635        assert_eq!(i.left, 0.0);
22636        assert_eq!(i.right, 1.0);
22637        assert_eq!(i.closed, IntervalClosed::Both);
22638
22639        let i2 = Interval::parse("(0, 1)").unwrap();
22640        assert_eq!(i2.left, 0.0);
22641        assert_eq!(i2.right, 1.0);
22642        assert_eq!(i2.closed, IntervalClosed::Neither);
22643
22644        let i3 = Interval::parse("[0, 1)").unwrap();
22645        assert_eq!(i3.closed, IntervalClosed::Left);
22646
22647        let i4 = Interval::parse("(0, 1]").unwrap();
22648        assert_eq!(i4.closed, IntervalClosed::Right);
22649    }
22650
22651    #[test]
22652    fn interval_parse_floats() {
22653        let i = Interval::parse("[-1.5, 2.5)").unwrap();
22654        assert_eq!(i.left, -1.5);
22655        assert_eq!(i.right, 2.5);
22656        assert_eq!(i.closed, IntervalClosed::Left);
22657    }
22658
22659    #[test]
22660    fn interval_parse_invalid() {
22661        assert!(Interval::parse("invalid").is_err());
22662        assert!(Interval::parse("[0]").is_err());
22663        assert!(Interval::parse("0, 1").is_err()); // missing brackets
22664    }
22665
22666    fn interval_parse_error_profile(s: &str) -> super::TypeError {
22667        super::TypeError::ValueNotParseable {
22668            value: s.to_string(),
22669            target: "Interval".to_string(),
22670        }
22671    }
22672
22673    #[inline(never)]
22674    fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
22675        let s = std::hint::black_box(s).trim();
22676        if s.len() < 5 {
22677            return Err(interval_parse_error_profile(s));
22678        }
22679
22680        let first_char = s.chars().next().unwrap();
22681        let last_char = s.chars().last().unwrap();
22682        let left_closed = match first_char {
22683            '[' => true,
22684            '(' => false,
22685            _ => return Err(interval_parse_error_profile(s)),
22686        };
22687        let right_closed = match last_char {
22688            ']' => true,
22689            ')' => false,
22690            _ => return Err(interval_parse_error_profile(s)),
22691        };
22692        let closed = match (left_closed, right_closed) {
22693            (true, true) => IntervalClosed::Both,
22694            (true, false) => IntervalClosed::Left,
22695            (false, true) => IntervalClosed::Right,
22696            (false, false) => IntervalClosed::Neither,
22697        };
22698
22699        let inner = &s[1..s.len() - 1];
22700        let parts: Vec<&str> = inner.split(',').collect();
22701        if parts.len() != 2 {
22702            return Err(interval_parse_error_profile(s));
22703        }
22704        let left = parts[0]
22705            .trim()
22706            .parse()
22707            .map_err(|_| interval_parse_error_profile(s))?;
22708        let right = parts[1]
22709            .trim()
22710            .parse()
22711            .map_err(|_| interval_parse_error_profile(s))?;
22712        Ok(Interval::new(left, right, closed))
22713    }
22714
22715    #[inline(never)]
22716    fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
22717        Interval::parse(std::hint::black_box(s))
22718    }
22719
22720    fn assert_interval_parse_profile_parity(s: &str) {
22721        match (
22722            interval_parse_former_profile(s),
22723            interval_parse_split_once_profile(s),
22724        ) {
22725            (Ok(former), Ok(candidate)) => {
22726                assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
22727                assert_eq!(
22728                    former.right.to_bits(),
22729                    candidate.right.to_bits(),
22730                    "right: {s}"
22731                );
22732                assert_eq!(former.closed, candidate.closed, "closed: {s}");
22733            }
22734            (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
22735            (former, candidate) => assert_eq!(
22736                former.is_ok(),
22737                candidate.is_ok(),
22738                "parse result mismatch for {s}: {former:?} != {candidate:?}"
22739            ),
22740        }
22741    }
22742
22743    #[inline(never)]
22744    fn measure_interval_parser_profile(
22745        parser: fn(&str) -> Result<Interval, super::TypeError>,
22746        inputs: &[&str],
22747        rounds: usize,
22748    ) -> u128 {
22749        use std::{hint::black_box, time::Instant};
22750
22751        let started = Instant::now();
22752        let mut checksum = 0_u64;
22753        for _ in 0..rounds {
22754            for input in inputs {
22755                let parsed = parser(black_box(input)).expect("profile input must parse");
22756                let closed = match parsed.closed {
22757                    IntervalClosed::Left => 1_u64,
22758                    IntervalClosed::Right => 2,
22759                    IntervalClosed::Both => 3,
22760                    IntervalClosed::Neither => 4,
22761                };
22762                checksum = checksum
22763                    .wrapping_add(parsed.left.to_bits().rotate_left(7))
22764                    .wrapping_add(parsed.right.to_bits().rotate_right(11))
22765                    .wrapping_add(closed);
22766                black_box(parsed);
22767            }
22768        }
22769        black_box(checksum);
22770        started.elapsed().as_nanos()
22771    }
22772
22773    #[test]
22774    #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
22775    fn profile_interval_parse_endpoint_split_ab_81jjv() {
22776        const VALID: [&str; 8] = [
22777            "[0, 1]",
22778            "(-0.0, 0.0]",
22779            " [ -1.5e3 , 2.75E-4 ) ",
22780            "(NaN, -0]",
22781            "[-inf, inf)",
22782            "[9.25, -7.5]",
22783            "(4.9406564584124654e-324, 1.7976931348623157e308)",
22784            "[-42, 17.125)",
22785        ];
22786        const INVALID: [&str; 12] = [
22787            "invalid",
22788            "[0]",
22789            "0, 1",
22790            "[0 1]",
22791            "[0, 1, 2]",
22792            "[0, 1,]",
22793            "[0,,1]",
22794            "[, 1]",
22795            "[0, ]",
22796            "{0, 1}",
22797            "[0, 1}",
22798            "  ⟦0, 1⟧  ",
22799        ];
22800        const ROUNDS: usize = 16_384;
22801        const SAMPLES: usize = 10;
22802
22803        for input in VALID.iter().chain(INVALID.iter()) {
22804            assert_interval_parse_profile_parity(input);
22805        }
22806        for _ in 0..2 {
22807            measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
22808            measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
22809        }
22810
22811        let mut former_ns = Vec::with_capacity(SAMPLES);
22812        let mut candidate_ns = Vec::with_capacity(SAMPLES);
22813        for sample in 0..SAMPLES {
22814            if sample % 2 == 0 {
22815                former_ns.push(measure_interval_parser_profile(
22816                    interval_parse_former_profile,
22817                    &VALID,
22818                    ROUNDS,
22819                ));
22820                candidate_ns.push(measure_interval_parser_profile(
22821                    interval_parse_split_once_profile,
22822                    &VALID,
22823                    ROUNDS,
22824                ));
22825            } else {
22826                candidate_ns.push(measure_interval_parser_profile(
22827                    interval_parse_split_once_profile,
22828                    &VALID,
22829                    ROUNDS,
22830                ));
22831                former_ns.push(measure_interval_parser_profile(
22832                    interval_parse_former_profile,
22833                    &VALID,
22834                    ROUNDS,
22835                ));
22836            }
22837        }
22838        former_ns.sort_unstable();
22839        candidate_ns.sort_unstable();
22840        let former_p50 = former_ns[SAMPLES / 2];
22841        let candidate_p50 = candidate_ns[SAMPLES / 2];
22842        let former_p95 = former_ns[SAMPLES - 1];
22843        let candidate_p95 = candidate_ns[SAMPLES - 1];
22844        println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
22845        println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
22846        println!(
22847            "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
22848            former_p50 as f64 / candidate_p50 as f64
22849        );
22850        println!(
22851            "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
22852            former_p95 as f64 / candidate_p95 as f64
22853        );
22854    }
22855}
22856
22857/// `DType::Float64Nullable` — pandas' `Float64Dtype()`, the dtype a nullable
22858/// Int64 lane widens INTO (br-frankenpandas-qkqfb).
22859///
22860/// Every rule asserted here was measured against live pandas 2.2.3 before it was
22861/// written; the measurement is quoted next to the assertion it justifies.
22862#[cfg(test)]
22863mod float64_nullable_qkqfb {
22864    use super::{DType, NullKind, Scalar, cast_scalar, common_dtype};
22865
22866    /// THE POINT OF THE DTYPE. A numpy float lane's missing value is a real NaN;
22867    /// the extension lane's is pd.NA. If both mapped to the same marker the two
22868    /// flavours would be indistinguishable and the dtype would buy nothing.
22869    ///
22870    /// MEASURED, live pandas 2.2.3:
22871    /// ```text
22872    ///   pd.Series([1.5, None], dtype="Float64")[1]     -> <NA>   (is pd.NA)
22873    ///   pd.Series([1.5, None])[1]                      -> nan
22874    ///   pd.Series([float("nan")], dtype="Float64")[0]  -> <NA>   COERCED
22875    /// ```
22876    #[test]
22877    fn the_two_float_flavours_have_different_missing_markers_qkqfb() {
22878        assert_eq!(
22879            Scalar::missing_for_dtype(DType::Float64Nullable),
22880            Scalar::Null(NullKind::Null),
22881            "the extension lane stores pd.NA"
22882        );
22883        assert_eq!(
22884            Scalar::missing_for_dtype(DType::Float64),
22885            Scalar::Null(NullKind::NaN),
22886            "the numpy lane stores a real NaN"
22887        );
22888        // The negative case: collapsing these two is precisely the defect, so
22889        // assert they are NOT equal rather than only asserting each value.
22890        assert_ne!(
22891            Scalar::missing_for_dtype(DType::Float64Nullable),
22892            Scalar::missing_for_dtype(DType::Float64),
22893        );
22894    }
22895
22896    /// MEASURED: `str(pd.Float64Dtype())` is `"Float64"`, and the numpy dtype is
22897    /// `"float64"`. dtype-check fixtures assert pandas' SPELLING
22898    /// (br-frankenpandas-62d1s), so the capital F is load-bearing, not cosmetic.
22899    #[test]
22900    fn spelling_is_pandas_spelling_qkqfb() {
22901        assert_eq!(DType::Float64Nullable.name(), "Float64");
22902        assert_eq!(DType::Float64.name(), "float64");
22903        assert_ne!(DType::Float64Nullable.name(), DType::Float64.name());
22904    }
22905
22906    /// The serde spelling has to survive a round trip AND stay distinct from the
22907    /// numpy flavour. `rename_all = "snake_case"` turns `Float64` into
22908    /// `"float64"`, which is what leaves `"Float64"` free for the extension —
22909    /// the same trick `Int64Nullable` already relies on. A naive
22910    /// `#[serde(rename = "Float64")]` on the WRONG variant would collide, and
22911    /// this test is what would catch it.
22912    #[test]
22913    fn serde_round_trips_and_does_not_collide_with_numpy_float64_qkqfb() {
22914        let ext = serde_json::to_string(&DType::Float64Nullable).expect("serialize");
22915        let numpy = serde_json::to_string(&DType::Float64).expect("serialize");
22916        assert_eq!(ext, "\"Float64\"");
22917        assert_eq!(numpy, "\"float64\"");
22918        assert_ne!(ext, numpy);
22919
22920        assert_eq!(
22921            serde_json::from_str::<DType>(&ext).expect("deserialize"),
22922            DType::Float64Nullable
22923        );
22924        assert_eq!(
22925            serde_json::from_str::<DType>(&numpy).expect("deserialize"),
22926            DType::Float64
22927        );
22928    }
22929
22930    /// It is a float, it is numeric, and it is a nullable extension — all three,
22931    /// or downstream dtype dispatch silently skips it.
22932    #[test]
22933    fn predicates_place_it_in_the_right_families_qkqfb() {
22934        assert!(DType::Float64Nullable.is_floating());
22935        assert!(DType::Float64Nullable.is_numeric());
22936        assert!(DType::Float64Nullable.is_any_real_numeric());
22937        assert!(DType::Float64Nullable.is_nullable());
22938        assert!(DType::Float64Nullable.is_extension());
22939        // And NOT these: an integer predicate that accepted it would let a
22940        // float value through an int-only fast path.
22941        assert!(!DType::Float64Nullable.is_integer());
22942        assert!(!DType::Float64Nullable.is_signed_integer());
22943        assert!(!DType::Float64Nullable.is_bool());
22944        // MEASURED: pd.Float64Dtype().kind == 'f', matching numpy float64 --
22945        // the extension reports its UNDERLYING kind, as Int64Nullable does.
22946        assert_eq!(DType::Float64Nullable.kind(), 'f');
22947        assert_eq!(DType::Float64Nullable.kind(), DType::Float64.kind());
22948        assert_eq!(DType::Float64Nullable.itemsize(), 8);
22949    }
22950
22951    /// The nullable/non-nullable pairing must be a genuine involution, or a
22952    /// round trip through either accessor silently changes flavour.
22953    #[test]
22954    fn nullable_pairing_is_an_involution_qkqfb() {
22955        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
22956        assert_eq!(DType::Float64Nullable.to_non_nullable(), DType::Float64);
22957        // Idempotent at both ends.
22958        assert_eq!(DType::Float64Nullable.to_nullable(), DType::Float64Nullable);
22959        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
22960        // The other families are untouched by the new variant.
22961        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
22962        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
22963    }
22964
22965    /// MEASURED ARITHMETIC, live pandas 2.2.3 -- this function models arithmetic
22966    /// promotion, not `find_common_type` (see the Bool arms in `common_dtype`):
22967    /// ```text
22968    ///   Float64(ext) + float64(numpy)  -> Float64
22969    ///   Int64(ext)   + Float64(ext)    -> Float64
22970    ///   boolean(ext) + Float64(ext)    -> Float64
22971    ///   Float64(ext) - Float64(ext)    -> Float64
22972    /// ```
22973    /// The nullable float absorbs every other numeric flavour.
22974    #[test]
22975    fn the_nullable_float_absorbs_every_numeric_flavour_qkqfb() {
22976        for other in [
22977            DType::Float64,
22978            DType::Int64,
22979            DType::Int64Nullable,
22980            DType::Bool,
22981            DType::BoolNullable,
22982            DType::Float64Nullable,
22983        ] {
22984            assert_eq!(
22985                common_dtype(DType::Float64Nullable, other.clone()),
22986                Ok(DType::Float64Nullable),
22987                "Float64Nullable + {other:?}"
22988            );
22989            // Commutativity is asserted wholesale by
22990            // common_dtype_lattice_axioms_be314; repeated here because an
22991            // asymmetric arm makes df1+df2 disagree with df2+df1.
22992            assert_eq!(
22993                common_dtype(other.clone(), DType::Float64Nullable),
22994                Ok(DType::Float64Nullable),
22995                "{other:?} + Float64Nullable"
22996            );
22997        }
22998        // Null is the lattice identity and must not absorb it.
22999        assert_eq!(
23000            common_dtype(DType::Null, DType::Float64Nullable),
23001            Ok(DType::Float64Nullable)
23002        );
23003    }
23004
23005    /// A PRESENT value crosses between the two float flavours unchanged; only the
23006    /// MISSING marker is converted.
23007    ///
23008    /// MEASURED:
23009    /// ```text
23010    ///   pd.Series([1.5,None],dtype="Float64").astype("float64") -> [1.5, nan]
23011    ///   pd.Series([1,None],  dtype="Int64").astype("Float64")   -> [1.0, <NA>]
23012    /// ```
23013    #[test]
23014    fn casts_preserve_values_and_convert_only_the_marker_qkqfb() {
23015        let present = Scalar::Float64(1.5);
23016        assert_eq!(
23017            cast_scalar(&present, DType::Float64Nullable),
23018            Ok(Scalar::Float64(1.5))
23019        );
23020        assert_eq!(
23021            cast_scalar(&Scalar::Float64(1.5), DType::Float64),
23022            Ok(Scalar::Float64(1.5))
23023        );
23024        // Int -> nullable float widens the value, as pandas does.
23025        assert_eq!(
23026            cast_scalar(&Scalar::Int64(1), DType::Float64Nullable),
23027            Ok(Scalar::Float64(1.0))
23028        );
23029        assert_eq!(
23030            cast_scalar(&Scalar::Bool(true), DType::Float64Nullable),
23031            Ok(Scalar::Float64(1.0))
23032        );
23033
23034        // THE MARKER CONVERSION, in both directions. This is the assertion a
23035        // "just alias Float64Nullable to Float64" implementation fails.
23036        assert_eq!(
23037            cast_scalar(&Scalar::Null(NullKind::NaN), DType::Float64Nullable),
23038            Ok(Scalar::Null(NullKind::Null)),
23039            "numpy NaN entering an extension lane becomes pd.NA"
23040        );
23041        assert_eq!(
23042            cast_scalar(&Scalar::Null(NullKind::Null), DType::Float64),
23043            Ok(Scalar::Null(NullKind::NaN)),
23044            "pd.NA entering a numpy lane becomes NaN"
23045        );
23046    }
23047
23048    /// The slice boundary this test used to pin has now been crossed: a
23049    /// nullable lane widening against a numpy float answers the NULLABLE float.
23050    /// MEASURED, live pandas 2.2.3, both spellings:
23051    /// ```text
23052    ///   find_common_type([Int64, float64])                        ->  Float64
23053    ///   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5])  ->  Float64
23054    /// ```
23055    /// (`Float64` there is the EXTENSION dtype — `Float64Dtype()` — not numpy
23056    /// `float64`.) br-frankenpandas-qkqfb; unblocks br-frankenpandas-f0aaa.
23057    #[test]
23058    fn int64nullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
23059        assert_eq!(
23060            common_dtype(DType::Int64Nullable, DType::Float64),
23061            Ok(DType::Float64Nullable)
23062        );
23063        assert_eq!(
23064            common_dtype(DType::Float64, DType::Int64Nullable),
23065            Ok(DType::Float64Nullable)
23066        );
23067    }
23068
23069    /// The BoolNullable sibling, MEASURED on the same pandas:
23070    /// ```text
23071    ///   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
23072    ///       -> Float64   (extension)
23073    /// ```
23074    /// The numpy-bool lane is NOT affected and stays on numpy float64, which is
23075    /// the control that keeps this from being a blanket "nullable everywhere".
23076    #[test]
23077    fn boolnullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
23078        assert_eq!(
23079            common_dtype(DType::BoolNullable, DType::Float64),
23080            Ok(DType::Float64Nullable)
23081        );
23082        assert_eq!(
23083            common_dtype(DType::Bool, DType::Float64),
23084            Ok(DType::Float64),
23085            "numpy bool + numpy float stays entirely on the numpy side"
23086        );
23087    }
23088
23089    /// ⚠ WHY THOSE TWO ARMS CANNOT MOVE INDEPENDENTLY. This is the exact triple
23090    /// that fails if only the Int64Nullable arm is flipped, spelled out so the
23091    /// coupling survives someone later "simplifying" one arm back:
23092    /// ```text
23093    ///   (BoolNullable ∨ Int64) ∨ Float64 = Int64Nullable ∨ Float64 = Float64Nullable
23094    ///   BoolNullable ∨ (Int64 ∨ Float64) = BoolNullable  ∨ Float64 = ???
23095    /// ```
23096    /// `common_dtype_lattice_axioms_be314` sweeps this for all 14 dtypes; this
23097    /// test names the single witness so a failure is diagnosable without
23098    /// re-deriving it from a 14³ sweep. (br-frankenpandas-qkqfb)
23099    #[test]
23100    fn the_nullable_float_flip_is_associative_on_its_witness_triple_qkqfb() {
23101        let (bn, i64n, f64d) = (DType::BoolNullable, DType::Int64, DType::Float64);
23102
23103        let left = common_dtype(
23104            common_dtype(bn.clone(), i64n.clone()).unwrap(),
23105            f64d.clone(),
23106        )
23107        .unwrap();
23108        let right = common_dtype(bn, common_dtype(i64n, f64d).unwrap()).unwrap();
23109
23110        assert_eq!(left, right, "promotion order must not change the result");
23111        assert_eq!(left, DType::Float64Nullable);
23112    }
23113}
23114
23115/// br-frankenpandas-3gxc6: the Sparse dtype NAME is parameterized in pandas.
23116///
23117/// Every expectation below was read off live pandas 2.2.3 before the code was
23118/// written, via `str(dtype)` / `dtype.name` on a `pd.SparseDtype`.
23119#[cfg(test)]
23120mod sparse_dtype_pandas_name_3gxc6 {
23121    use super::{DType, Scalar, SparseDType};
23122
23123    fn name(value_dtype: DType, fill: Scalar) -> String {
23124        SparseDType::new(value_dtype, fill)
23125            .expect("sparse descriptor")
23126            .pandas_name()
23127    }
23128
23129    /// The row the corpus fixture `fp_p2d_017_series_dtype_sparse_strict`
23130    /// exercises. FrankenPandas used to answer the bare `"Sparse"`.
23131    #[test]
23132    fn int64_fill_zero_is_the_fixture_row() {
23133        assert_eq!(name(DType::Int64, Scalar::Int64(0)), "Sparse[int64, 0]");
23134    }
23135
23136    /// A non-default fill must appear, or the name would be a constant wearing
23137    /// a parameterized shape.
23138    #[test]
23139    fn the_fill_value_is_actually_rendered() {
23140        assert_eq!(name(DType::Int64, Scalar::Int64(7)), "Sparse[int64, 7]");
23141        assert_ne!(
23142            name(DType::Int64, Scalar::Int64(0)),
23143            name(DType::Int64, Scalar::Int64(7)),
23144            "two different fills must not collapse to one name"
23145        );
23146    }
23147
23148    /// pandas spells this `nan`, lowercase, not `NaN` and not `None`.
23149    #[test]
23150    fn float64_nan_fill_is_lowercase_nan() {
23151        assert_eq!(
23152            name(DType::Float64, Scalar::Float64(f64::NAN)),
23153            "Sparse[float64, nan]"
23154        );
23155    }
23156
23157    /// pandas keeps the trailing `.0` here. A `{}`-style float format would
23158    /// render `0` and silently make this name collide with the int64 one.
23159    #[test]
23160    fn float64_zero_fill_keeps_its_trailing_point_zero() {
23161        assert_eq!(
23162            name(DType::Float64, Scalar::Float64(0.0)),
23163            "Sparse[float64, 0.0]"
23164        );
23165        assert_ne!(
23166            name(DType::Float64, Scalar::Float64(0.0)),
23167            name(DType::Int64, Scalar::Int64(0)),
23168            "float64 and int64 zero fills are different dtypes"
23169        );
23170    }
23171
23172    /// Python capitalisation, not Rust's `false`.
23173    #[test]
23174    fn bool_fill_uses_python_capitalisation() {
23175        assert_eq!(
23176            name(DType::Bool, Scalar::Bool(false)),
23177            "Sparse[bool, False]"
23178        );
23179        assert_eq!(name(DType::Bool, Scalar::Bool(true)), "Sparse[bool, True]");
23180    }
23181
23182    /// FP spells its object dtype `object`, which is what pandas prints for a
23183    /// `SparseDtype(object, nan)`.
23184    #[test]
23185    fn utf8_subtype_renders_as_object() {
23186        let rendered = name(DType::Utf8, Scalar::Null(crate::NullKind::NaN));
23187        assert!(
23188            rendered.starts_with("Sparse[object, "),
23189            "expected an object subtype, got {rendered}"
23190        );
23191    }
23192
23193    /// The bare name is what this bead removed; guard against a regression
23194    /// that reintroduces it for any constructible descriptor.
23195    #[test]
23196    fn no_constructible_descriptor_renders_the_bare_name() {
23197        for (dtype, fill) in [
23198            (DType::Int64, Scalar::Int64(0)),
23199            (DType::Float64, Scalar::Float64(1.5)),
23200            (DType::Bool, Scalar::Bool(true)),
23201            (DType::Utf8, Scalar::Utf8("x".to_owned())),
23202        ] {
23203            let rendered = name(dtype.clone(), fill);
23204            assert_ne!(rendered, "Sparse", "bare name regressed for {dtype:?}");
23205            assert!(
23206                rendered.starts_with("Sparse[") && rendered.ends_with(']'),
23207                "malformed sparse name {rendered}"
23208            );
23209        }
23210    }
23211
23212    #[test]
23213    fn test_dtype_from_str_and_display() {
23214        use std::str::FromStr;
23215
23216        use crate::DType;
23217
23218        assert_eq!(DType::from_str("int64").unwrap(), DType::Int64);
23219        assert_eq!(DType::from_str("Int64").unwrap(), DType::Int64Nullable);
23220        assert_eq!(DType::from_str("float64").unwrap(), DType::Float64);
23221        assert_eq!(DType::from_str("Float64").unwrap(), DType::Float64Nullable);
23222        assert_eq!(DType::from_str("bool").unwrap(), DType::Bool);
23223        assert_eq!(DType::from_str("boolean").unwrap(), DType::BoolNullable);
23224        assert_eq!(DType::from_str("string").unwrap(), DType::Utf8);
23225        assert_eq!(DType::from_str("category").unwrap(), DType::Categorical);
23226        assert_eq!(
23227            DType::from_str("timedelta64[ns]").unwrap(),
23228            DType::Timedelta64
23229        );
23230        assert_eq!(
23231            DType::from_str("datetime64[ns]").unwrap(),
23232            DType::Datetime64 { tz: None }
23233        );
23234        assert_eq!(
23235            DType::from_str("datetime64[ns, UTC]").unwrap(),
23236            DType::Datetime64 {
23237                tz: Some("UTC".to_string())
23238            }
23239        );
23240        assert_eq!(DType::from_str("period").unwrap(), DType::Period);
23241        assert_eq!(DType::from_str("interval").unwrap(), DType::Interval);
23242        assert_eq!(DType::from_str("sparse").unwrap(), DType::Sparse);
23243
23244        assert_eq!(format!("{}", DType::Int64), "int64");
23245        assert_eq!(
23246            format!(
23247                "{}",
23248                DType::Datetime64 {
23249                    tz: Some("UTC".to_string())
23250                }
23251            ),
23252            "datetime64[ns, UTC]"
23253        );
23254    }
23255
23256    #[test]
23257    fn test_api_types_inspection_and_infer_dtype() {
23258        use crate::{
23259            DType, Scalar,
23260            api::types::{
23261                infer_dtype, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype,
23262                is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_int64_dtype,
23263                is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_object_dtype,
23264                is_period_dtype, is_scalar, is_signed_integer_dtype, is_sparse, is_string_dtype,
23265                is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype,
23266            },
23267        };
23268
23269        assert!(is_numeric_dtype(&DType::Int64));
23270        assert!(is_numeric_dtype(&DType::Float64));
23271        assert!(!is_numeric_dtype(&DType::Utf8));
23272        assert!(!is_numeric_dtype(&DType::Bool));
23273
23274        assert!(is_integer_dtype(&DType::Int64));
23275        assert!(is_integer_dtype(&DType::Int64Nullable));
23276        assert!(!is_integer_dtype(&DType::Float64));
23277
23278        assert!(is_int64_dtype(&DType::Int64));
23279        assert!(is_int64_dtype(&DType::Int64Nullable));
23280        assert!(!is_int64_dtype(&DType::Float64));
23281
23282        assert!(is_object_dtype(&DType::Utf8));
23283        assert!(!is_object_dtype(&DType::Int64));
23284
23285        assert!(is_dtype_equal(&DType::Int64, &DType::Int64));
23286        assert!(is_dtype_equal(&"int64", &DType::Int64));
23287        assert!(!is_dtype_equal(&DType::Int64, &DType::Float64));
23288
23289        assert!(is_signed_integer_dtype(&DType::Int64));
23290        assert!(!is_unsigned_integer_dtype(&DType::Int64));
23291
23292        assert!(is_float_dtype(&DType::Float64));
23293        assert!(is_bool_dtype(&DType::Bool));
23294        assert!(is_string_dtype(&DType::Utf8));
23295        assert!(is_datetime64_any_dtype(&DType::Datetime64 { tz: None }));
23296        assert!(is_timedelta64_dtype(&DType::Timedelta64));
23297        assert!(is_categorical_dtype(&DType::Categorical));
23298        assert!(is_period_dtype(&DType::Period));
23299        assert!(is_interval_dtype(&DType::Interval));
23300        assert!(is_sparse(&DType::Sparse));
23301        assert!(is_extension_array_dtype(&DType::Categorical));
23302        assert!(is_scalar(&Scalar::Int64(42)));
23303
23304        assert_eq!(pandas_dtype("float64").unwrap(), DType::Float64);
23305        assert!(pandas_dtype("invalid_dtype_xyz").is_err());
23306
23307        let ints = vec![Scalar::Int64(1), Scalar::Int64(2)];
23308        assert_eq!(infer_dtype(&ints, true), "integer");
23309
23310        let floats = vec![Scalar::Float64(1.0), Scalar::Float64(2.5)];
23311        assert_eq!(infer_dtype(&floats, true), "floating");
23312
23313        let bools = vec![Scalar::Bool(true), Scalar::Bool(false)];
23314        assert_eq!(infer_dtype(&bools, true), "boolean");
23315
23316        let strings = vec![Scalar::Utf8("a".to_string()), Scalar::Utf8("b".to_string())];
23317        assert_eq!(infer_dtype(&strings, true), "string");
23318
23319        let mixed = vec![Scalar::Int64(1), Scalar::Utf8("a".to_string())];
23320        assert_eq!(infer_dtype(&mixed, true), "mixed");
23321
23322        assert_eq!(infer_dtype(&[], true), "empty");
23323    }
23324
23325    #[test]
23326    fn test_na_nat_sentinels_and_eng_float_format() {
23327        use super::{
23328            NA, NAT, NaT, eng_float_format, get_eng_float_format, reset_eng_float_format,
23329            set_eng_float_format,
23330        };
23331
23332        // NA and NAT sentinels
23333        assert!(NA.is_null());
23334        assert!(NAT.is_null());
23335        assert_eq!(NAT, NaT);
23336        assert_eq!(format!("{NA}"), "None");
23337        assert_eq!(format!("{NAT}"), "NaT");
23338
23339        // Engineering float format tests
23340        assert_eq!(eng_float_format(1000.0, Some(3), false), "1.000E+03");
23341        assert_eq!(eng_float_format(0.005, Some(3), false), "5.000E-03");
23342        assert_eq!(eng_float_format(1234567.0, Some(3), false), "1.235E+06");
23343        assert_eq!(eng_float_format(-9876.54, Some(3), false), "-9.877E+03");
23344        assert_eq!(eng_float_format(0.0, Some(3), false), "0.000E+00");
23345
23346        // With prefixes
23347        assert_eq!(eng_float_format(1000.0, Some(3), true), "1.000k");
23348        assert_eq!(eng_float_format(0.005, Some(3), true), "5.000m");
23349        assert_eq!(eng_float_format(1234567.0, Some(3), true), "1.235M");
23350        assert_eq!(eng_float_format(-9876.54, Some(3), true), "-9.877k");
23351        assert_eq!(eng_float_format(0.0, Some(3), true), "0.000");
23352        assert_eq!(eng_float_format(1.5, Some(3), true), "1.500");
23353
23354        // Special numbers
23355        assert_eq!(eng_float_format(f64::NAN, Some(3), true), "NaN");
23356        assert_eq!(eng_float_format(f64::INFINITY, Some(3), true), "inf");
23357        assert_eq!(eng_float_format(f64::NEG_INFINITY, Some(3), true), "-inf");
23358
23359        // Configuration helpers
23360        reset_eng_float_format();
23361        assert_eq!(get_eng_float_format(), None);
23362        set_eng_float_format(4, true);
23363        assert_eq!(get_eng_float_format(), Some((4, true)));
23364        reset_eng_float_format();
23365        assert_eq!(get_eng_float_format(), None);
23366    }
23367
23368    #[test]
23369    fn test_options_system() {
23370        use super::{
23371            OptionError, OptionValue, describe_option, get_option, option_context, reset_option,
23372            set_option,
23373        };
23374
23375        // Reset to clean state
23376        reset_option(None).unwrap();
23377
23378        // 1. Default option checks
23379        let max_rows = get_option("display.max_rows").unwrap();
23380        assert_eq!(max_rows.as_int(), Some(60));
23381        assert_eq!(max_rows, OptionValue::Int(60));
23382        assert!(!max_rows.is_none());
23383
23384        // Partial key matching (suffix)
23385        let min_rows = get_option("min_rows").unwrap();
23386        assert_eq!(min_rows.as_int(), Some(10));
23387
23388        // 2. Setting options
23389        set_option("display.max_rows", 100).unwrap();
23390        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
23391
23392        set_option("mode.sim_interactive", true).unwrap();
23393        assert_eq!(
23394            get_option("mode.sim_interactive").unwrap().as_bool(),
23395            Some(true)
23396        );
23397
23398        set_option("mode.chained_assignment", "raise").unwrap();
23399        assert_eq!(
23400            get_option("mode.chained_assignment").unwrap().as_str(),
23401            Some("raise")
23402        );
23403
23404        // 3. OptionError handling
23405        assert!(matches!(
23406            get_option("nonexistent.option"),
23407            Err(OptionError::NotFound { .. })
23408        ));
23409        assert!(matches!(
23410            get_option("display"),
23411            Err(OptionError::Ambiguous { .. })
23412        ));
23413
23414        // 4. describe_option
23415        let desc = describe_option(Some("max_rows")).unwrap();
23416        assert!(desc.contains("display.max_rows : [currently: 100]"));
23417
23418        let desc_all = describe_option(None).unwrap();
23419        assert!(desc_all.contains("display.width"));
23420        assert!(desc_all.contains("compute.use_bottleneck"));
23421
23422        // 5. Scoped option_context
23423        {
23424            let _guard = option_context(&[
23425                ("display.max_rows", OptionValue::Int(999)),
23426                ("display.precision", OptionValue::Int(2)),
23427            ])
23428            .unwrap();
23429
23430            assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(999));
23431            assert_eq!(get_option("display.precision").unwrap().as_int(), Some(2));
23432        }
23433        // Restored after guard drop
23434        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
23435        assert_eq!(get_option("display.precision").unwrap().as_int(), Some(6));
23436
23437        // 6. Reset single option and all options
23438        reset_option(Some("display.max_rows")).unwrap();
23439        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(60));
23440
23441        reset_option(Some("all")).unwrap();
23442        assert_eq!(
23443            get_option("mode.chained_assignment").unwrap().as_str(),
23444            Some("warn")
23445        );
23446
23447        // 7. Expanded standard options
23448        assert_eq!(
23449            get_option("mode.copy_on_write").unwrap().as_bool(),
23450            Some(false)
23451        );
23452        assert_eq!(
23453            get_option("mode.data_manager").unwrap().as_str(),
23454            Some("block")
23455        );
23456        assert_eq!(
23457            get_option("display.large_repr").unwrap().as_str(),
23458            Some("truncate")
23459        );
23460        assert_eq!(
23461            get_option("display.max_info_columns").unwrap().as_int(),
23462            Some(100)
23463        );
23464        assert_eq!(
23465            get_option("display.memory_usage").unwrap().as_bool(),
23466            Some(true)
23467        );
23468        assert_eq!(
23469            get_option("display.colheader_justify").unwrap().as_str(),
23470            Some("right")
23471        );
23472        assert!(get_option("display.chop_threshold").unwrap().is_none());
23473        assert_eq!(
23474            get_option("io.parquet.engine").unwrap().as_str(),
23475            Some("auto")
23476        );
23477        assert_eq!(
23478            get_option("plotting.backend").unwrap().as_str(),
23479            Some("matplotlib")
23480        );
23481        assert_eq!(
23482            get_option("plotting.matplotlib.register_converters")
23483                .unwrap()
23484                .as_bool(),
23485            Some(true)
23486        );
23487
23488        // From<()> for OptionValue
23489        set_option("display.chop_threshold", ()).unwrap();
23490        assert!(get_option("display.chop_threshold").unwrap().is_none());
23491    }
23492
23493    #[test]
23494    fn test_scalar_typed_accessors() {
23495        use super::{Interval, IntervalClosed, Period, PeriodFreq, Scalar};
23496
23497        let s_i64 = Scalar::Int64(42);
23498        assert_eq!(s_i64.as_i64(), Some(42));
23499        assert_eq!(s_i64.as_int(), Some(42));
23500        assert_eq!(s_i64.as_f64(), None);
23501        assert_eq!(s_i64.as_float(), None);
23502        assert_eq!(s_i64.as_bool(), None);
23503        assert_eq!(s_i64.as_str(), None);
23504
23505        let s_f64 = Scalar::Float64(2.75);
23506        assert_eq!(s_f64.as_f64(), Some(2.75));
23507        assert_eq!(s_f64.as_float(), Some(2.75));
23508        assert_eq!(s_f64.as_i64(), None);
23509        assert_eq!(s_f64.as_int(), None);
23510
23511        let s_bool = Scalar::Bool(true);
23512        assert_eq!(s_bool.as_bool(), Some(true));
23513        assert_eq!(s_bool.as_int(), None);
23514
23515        let s_str = Scalar::Utf8("pandas".to_string());
23516        assert_eq!(s_str.as_str(), Some("pandas"));
23517        assert_eq!(s_str.as_bool(), None);
23518
23519        let s_dt = Scalar::Datetime64(1_000_000_000);
23520        assert_eq!(s_dt.as_datetime_nanos(), Some(1_000_000_000));
23521        assert_eq!(s_dt.as_str(), None);
23522
23523        let s_td = Scalar::Timedelta64(500_000);
23524        assert_eq!(s_td.as_timedelta_nanos(), Some(500_000));
23525        assert_eq!(s_td.as_int(), None);
23526
23527        let s_per = Scalar::Period(Period::new(2024, PeriodFreq::Daily));
23528        assert_eq!(s_per.as_period_ordinal(), Some(2024));
23529
23530        let s_iv = Scalar::Interval(Interval::new(0.0, 10.0, IntervalClosed::Both));
23531        assert_eq!(
23532            s_iv.as_interval(),
23533            Some(Interval::new(0.0, 10.0, IntervalClosed::Both))
23534        );
23535    }
23536
23537    #[test]
23538    fn test_api_submodules_and_types_inspectors() {
23539        use super::{
23540            DType, Scalar,
23541            api::{extensions, indexers, types},
23542        };
23543
23544        // api::types scalar inspectors
23545        assert!(types::is_number(&Scalar::Int64(42)));
23546        assert!(types::is_number(&Scalar::Float64(42.5)));
23547        assert!(types::is_number(&Scalar::Bool(true)));
23548        assert!(!types::is_number(&Scalar::Utf8("pandas".into())));
23549
23550        assert!(types::is_bool(&Scalar::Bool(false)));
23551        assert!(!types::is_bool(&Scalar::Int64(0)));
23552
23553        assert!(types::is_integer(&Scalar::Int64(10)));
23554        assert!(!types::is_integer(&Scalar::Float64(10.0)));
23555
23556        assert!(types::is_float(&Scalar::Float64(10.0)));
23557        assert!(!types::is_float(&Scalar::Int64(10)));
23558
23559        // api::types dtype inspectors
23560        assert!(types::is_float64_dtype(&DType::Float64));
23561        assert!(types::is_float64_dtype(&DType::Float64Nullable));
23562        assert!(!types::is_float64_dtype(&DType::Int64));
23563        assert!(!types::is_int32_dtype(&DType::Int64));
23564
23565        // api::extensions compatibility hooks
23566        extensions::register_dataframe_accessor("geo");
23567        extensions::register_series_accessor("geo");
23568        extensions::register_index_accessor("geo");
23569
23570        // api::indexers
23571        let base = indexers::BaseIndexer::new(5, 1);
23572        assert_eq!(base.window_size, 5);
23573        assert_eq!(base.step, 1);
23574
23575        let fwd = indexers::FixedForwardWindowIndexer::new(3);
23576        assert_eq!(fwd.window_size, 3);
23577
23578        let var = indexers::VariableOffsetWindowIndexer::new(100);
23579        assert_eq!(var.index_offset, 100);
23580    }
23581
23582    #[test]
23583    fn test_extension_dtypes_and_parameterized_parsing() {
23584        use super::{
23585            AsDType, CategoricalDtype, DType, IntervalClosed, IntervalDtype, PeriodDtype, Scalar,
23586            SparseDType, api::types, pandas_dtype,
23587        };
23588
23589        // CategoricalDtype
23590        let cat_default = CategoricalDtype::default();
23591        assert_eq!(cat_default.name(), "category");
23592        assert_eq!(cat_default.kind(), "O");
23593        assert!(!cat_default.ordered());
23594        assert_eq!(cat_default.categories(), None);
23595        assert_eq!(cat_default.as_dtype(), DType::Categorical);
23596        assert!(types::is_categorical_dtype(&cat_default));
23597        assert_eq!(
23598            cat_default.to_string(),
23599            "CategoricalDtype(categories=None, ordered=False)"
23600        );
23601
23602        let cat_custom =
23603            CategoricalDtype::new(Some(vec!["low".to_string(), "high".to_string()]), true);
23604        assert!(cat_custom.ordered());
23605        assert_eq!(
23606            cat_custom.categories(),
23607            Some(&["low".to_string(), "high".to_string()][..])
23608        );
23609        assert!(cat_custom.to_string().contains("ordered=True"));
23610
23611        // PeriodDtype
23612        let per_default = PeriodDtype::default();
23613        assert_eq!(per_default.freq(), "D");
23614        assert_eq!(per_default.name(), "period[D]");
23615        assert_eq!(per_default.kind(), "O");
23616        assert_eq!(per_default.as_dtype(), DType::Period);
23617        assert!(types::is_period_dtype(&per_default));
23618        assert_eq!(per_default.to_string(), "period[D]");
23619
23620        let per_custom = PeriodDtype::new("M");
23621        assert_eq!(per_custom.freq(), "M");
23622        assert_eq!(per_custom.to_string(), "period[M]");
23623
23624        // IntervalDtype
23625        let int_default = IntervalDtype::default();
23626        assert_eq!(*int_default.subtype(), DType::Float64);
23627        assert_eq!(int_default.closed(), Some(IntervalClosed::Right));
23628        assert_eq!(int_default.name(), "interval");
23629        assert_eq!(int_default.kind(), "O");
23630        assert_eq!(int_default.as_dtype(), DType::Interval);
23631        assert!(types::is_interval_dtype(&int_default));
23632        assert_eq!(int_default.to_string(), "interval[float64, right]");
23633
23634        let int_custom = IntervalDtype::new(DType::Int64, Some(IntervalClosed::Both));
23635        assert_eq!(*int_custom.subtype(), DType::Int64);
23636        assert_eq!(int_custom.closed(), Some(IntervalClosed::Both));
23637        assert_eq!(int_custom.to_string(), "interval[int64, both]");
23638
23639        // SparseDType AsDType
23640        let sp = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).unwrap();
23641        assert_eq!(sp.as_dtype(), DType::Sparse);
23642        assert!(types::is_sparse(&sp));
23643
23644        // Parameterized pandas_dtype parsing
23645        assert_eq!(pandas_dtype("period[D]").unwrap(), DType::Period);
23646        assert_eq!(pandas_dtype("Period[M]").unwrap(), DType::Period);
23647        assert_eq!(pandas_dtype("interval[float64]").unwrap(), DType::Interval);
23648        assert_eq!(pandas_dtype("Interval[int64]").unwrap(), DType::Interval);
23649        assert_eq!(pandas_dtype("sparse[float64]").unwrap(), DType::Sparse);
23650        assert_eq!(pandas_dtype("Sparse[int64, 0]").unwrap(), DType::Sparse);
23651    }
23652}
23653
23654/// `NumericWidth` / `NumpyNumeric` — numpy's narrow numeric dtypes and their
23655/// promotion (fvsao.23). Expected values are live pandas 2.2.3 / numpy 2.4.6.
23656#[cfg(test)]
23657mod numeric_width_fvsao23 {
23658    use super::{DType, NumericWidth, NumpyNumeric, numpy_pairwise_sum};
23659
23660    #[test]
23661    fn float32_sum_is_numpys_pairwise_sum_bit_for_bit() {
23662        // numpy 2.4.6: a = ((arange(n) * 37) % 1000).astype(float32) *
23663        // float32(0.013); a.sum().view(uint32). Lengths 5 and 64 are ones
23664        // where a float64 sum rounded once gives another float32 (NEGATIVE).
23665        let cases: [(usize, u32); 5] = [
23666            (5, 1_083_829_126),
23667            (64, 1_136_679_190),
23668            (129, 1_145_981_108),
23669            (1000, 1_170_926_592),
23670            (4097, 1_188_011_795),
23671        ];
23672        for (n, bits) in cases {
23673            #[allow(clippy::cast_precision_loss)] // below 1000
23674            let values: Vec<f32> = (0..n)
23675                .map(|k| ((k * 37) % 1000) as f32 * 0.013_f32)
23676                .collect();
23677            assert_eq!(numpy_pairwise_sum(&values).to_bits(), bits, "n={n}");
23678            if n < 100 {
23679                #[allow(clippy::cast_possible_truncation)]
23680                let rounded_once = values.iter().map(|&v| f64::from(v)).sum::<f64>() as f32;
23681                assert_ne!(rounded_once.to_bits(), bits, "n={n}");
23682            }
23683        }
23684        assert_eq!(numpy_pairwise_sum::<f32>(&[]), 0.0);
23685    }
23686
23687    #[test]
23688    fn names_parse_and_round_trip() {
23689        for width in NumericWidth::ALL {
23690            for nullable in [false, true] {
23691                assert_eq!(
23692                    NumericWidth::parse(width.name(nullable)),
23693                    Some((width, nullable))
23694                );
23695            }
23696        }
23697        for (name, expected) in [
23698            ("<i4", (NumericWidth::Int32, false)),
23699            ("f4", (NumericWidth::Float32, false)),
23700            ("UInt8Dtype", (NumericWidth::UInt8, true)),
23701        ] {
23702            assert_eq!(NumericWidth::parse(name), Some(expected), "{name}");
23703        }
23704        // The 64-bit names are DType's, not a width: 'i8' is numpy's int64.
23705        for name in ["int64", "Int64", "float64", "i8", "f8", "int", "float"] {
23706            assert_eq!(NumericWidth::parse(name), None, "{name}");
23707        }
23708    }
23709
23710    #[test]
23711    fn wrapping_is_numpys_modular_cast_not_saturation() {
23712        // pd.Series([1, 2, 300, -5]).astype('int8') -> [1, 2, 44, -5]
23713        assert_eq!(NumericWidth::Int8.wrap_int(300), Some(44));
23714        // .astype('uint8') -> [1, 2, 44, 251]; uint16 -5 -> 65531
23715        assert_eq!(NumericWidth::UInt8.wrap_int(-5), Some(251));
23716        assert_eq!(NumericWidth::UInt16.wrap_int(-5), Some(65531));
23717        assert_eq!(NumericWidth::UInt32.wrap_int(-5), Some(4_294_967_291));
23718        // int8 100 + 100 -> -56; 100 * 2 -> -56
23719        assert_eq!(NumericWidth::Int8.wrap_int(200), Some(-56));
23720        assert_eq!(
23721            NumericWidth::Int32.wrap_int(i64::from(i32::MAX) + 1),
23722            Some(i64::from(i32::MIN))
23723        );
23724        // A wrapped i64 product reduces to the width's product.
23725        let product = 50_000_i64.wrapping_pow(5);
23726        assert_eq!(
23727            NumericWidth::Int32.wrap_int(product),
23728            Some(i64::from(50_000_i32.wrapping_pow(5)))
23729        );
23730        // uint64 at or above 2**63 is refused, never stored negative.
23731        assert_eq!(NumericWidth::UInt64.wrap_int(-1), None);
23732        assert_eq!(NumericWidth::UInt64.wrap_int(7), Some(7));
23733        assert_eq!(NumericWidth::Float32.wrap_int(1), None);
23734        assert!(NumericWidth::Int8.holds_int(-128) && !NumericWidth::Int8.holds_int(128));
23735    }
23736
23737    #[test]
23738    fn float32_rounding_is_to_nearest_not_truncation() {
23739        // np.float32(0.1) as float64 -> 0.10000000149011612
23740        assert_eq!(NumericWidth::round_f32(0.1), 0.100_000_001_490_116_12);
23741        // float32 0.1 + 0.2 -> 0.30000001192092896 (not float64's
23742        // 0.30000000000000004)
23743        let sum =
23744            NumericWidth::round_f32(NumericWidth::round_f32(0.1) + NumericWidth::round_f32(0.2));
23745        assert_eq!(sum, 0.300_000_011_920_928_96);
23746        // 1 + 2**-24 is a tie between 1 and 1 + 2**-23: ties to even -> 1.
23747        // 1 + 3 * 2**-25 is above the tie: rounds up, where truncation stays 1.
23748        assert_eq!(NumericWidth::round_f32(1.0 + 2f64.powi(-24)), 1.0);
23749        let above_tie = 1.0 + 3.0 * 2f64.powi(-25);
23750        assert_eq!(NumericWidth::round_f32(above_tie), 1.0 + 2f64.powi(-23));
23751        assert!(NumericWidth::round_f32(f64::NAN).is_nan());
23752        assert_eq!(NumericWidth::round_f32(1e300), f64::INFINITY);
23753    }
23754
23755    #[test]
23756    fn result_type_matches_numpy_promotion() {
23757        use NumpyNumeric::{Bool, Float, Int, UInt};
23758        let cases = [
23759            (Int(32), Int(64), Int(64)), // int32 + int64 -> int64
23760            (Int(8), UInt(8), Int(16)),  // int8 + uint8 -> int16
23761            (Int(16), UInt(8), Int(16)),
23762            (Int(8), UInt(16), Int(32)),
23763            (Int(32), UInt(32), Int(64)),
23764            (Int(64), UInt(64), Float(64)), // no integer holds both
23765            (UInt(8), UInt(32), UInt(32)),
23766            (Float(32), Int(8), Float(32)), // float32 * int8 -> float32
23767            (Float(32), UInt(16), Float(32)),
23768            (Float(32), Int(32), Float(64)), // float32 * int32 -> float64
23769            (Float(32), Float(64), Float(64)),
23770            (Bool, Int(8), Int(8)),
23771            (Bool, Float(32), Float(32)),
23772        ];
23773        for (a, b, expected) in cases {
23774            assert_eq!(a.result_type(b), expected, "{a:?} {b:?}");
23775            assert_eq!(b.result_type(a), expected, "{b:?} {a:?}");
23776        }
23777        // NEP 50: int32 + 1 -> int32; int32 + 0.5 -> float64;
23778        // float32 + 0.2 -> float32
23779        assert_eq!(Int(32).with_python_int(), Int(32));
23780        assert_eq!(Int(32).with_python_float(), Float(64));
23781        assert_eq!(Float(32).with_python_float(), Float(32));
23782        assert_eq!(Bool.with_python_int(), Int(64));
23783    }
23784
23785    #[test]
23786    fn columns_map_to_numpy_dtypes() {
23787        let cases = [
23788            (DType::Int64, None, Some(NumpyNumeric::Int(64))),
23789            (
23790                DType::Int64Nullable,
23791                Some(NumericWidth::UInt8),
23792                Some(NumpyNumeric::UInt(8)),
23793            ),
23794            (
23795                DType::Float64,
23796                Some(NumericWidth::Float32),
23797                Some(NumpyNumeric::Float(32)),
23798            ),
23799            // A width its storage cannot carry is not a numpy dtype.
23800            (DType::Float64, Some(NumericWidth::Int8), None),
23801            (DType::Utf8, None, None),
23802        ];
23803        for (dtype, width, expected) in cases {
23804            assert_eq!(NumpyNumeric::of(&dtype, width), expected, "{dtype:?}");
23805        }
23806        for width in NumericWidth::ALL {
23807            assert_eq!(NumpyNumeric::of_width(width).width(), Some(width));
23808            assert!(width.fits_storage(&width.storage(false)));
23809            assert!(width.fits_storage(&width.storage(true)));
23810        }
23811        assert_eq!(NumpyNumeric::Int(64).width(), None);
23812    }
23813
23814    #[test]
23815    fn downcast_and_category_code_widths() {
23816        // to_numeric([1, 2], downcast='integer') -> int8; [1, 300] signed ->
23817        // int16, unsigned -> uint16
23818        let int32_max_plus_one = i64::from(i32::MAX) + 1;
23819        let signed = [
23820            ((1, 2), Some(NumericWidth::Int8)),
23821            ((1, 300), Some(NumericWidth::Int16)),
23822            ((0, int32_max_plus_one), None),
23823        ];
23824        for ((low, high), expected) in signed {
23825            assert_eq!(NumericWidth::smallest_signed(low, high), expected);
23826        }
23827        let unsigned = [((1, 300), Some(NumericWidth::UInt16)), ((-1, 3), None)];
23828        for ((low, high), expected) in unsigned {
23829            assert_eq!(NumericWidth::smallest_unsigned(low, high), expected);
23830        }
23831        // cat.codes: 2 categories int8, 200 int16; 126 int8, 127 int16
23832        for (categories, expected) in [
23833            (2, NumericWidth::Int8),
23834            (126, NumericWidth::Int8),
23835            (127, NumericWidth::Int16),
23836            (200, NumericWidth::Int16),
23837        ] {
23838            assert_eq!(NumericWidth::for_category_codes(categories), Some(expected));
23839        }
23840        assert_eq!(NumericWidth::itemsize(NumericWidth::Int8), 1);
23841        assert_eq!(NumericWidth::Float32.itemsize(), 4);
23842    }
23843}
23844
23845/// `PandasReductions` against live pandas 2.2.3 / numpy 2.3.5: the bits of
23846/// `Series(...).sum() / mean() / var() / std() / sem() / skew() / kurt()`
23847/// over data both sides build with the same integer arithmetic and one
23848/// division (br-frankenpandas-9iim6).
23849#[cfg(test)]
23850mod pandas_reductions_9iim6 {
23851    use super::{MissingLayout, PandasReductions, ReductionValues};
23852
23853    /// `((k * 7919 + 13) % 100003) / 7.0 - 7000.0`, times 1e6 where
23854    /// `k % 5 == 0`; missing where `k % 11 == 3`.
23855    #[allow(clippy::cast_precision_loss)] // below 100003
23856    fn floats(n: usize) -> (Vec<f64>, Vec<u64>) {
23857        let mut present = vec![0_u64; n.div_ceil(64)];
23858        let values = (0..n)
23859            .map(|k| {
23860                if k % 11 != 3 {
23861                    present[k / 64] |= 1 << (k % 64);
23862                }
23863                let base = ((k * 7919 + 13) % 100_003) as f64 / 7.0 - 7000.0;
23864                if k % 5 == 0 { base * 1e6 } else { base }
23865            })
23866            .collect();
23867        (values, present)
23868    }
23869
23870    /// `(k * 7919 + 13) % 100003 * 3_000_000_007`.
23871    fn ints(n: usize) -> Vec<i64> {
23872        (0..n)
23873            .map(|k| i64::try_from((k * 7919 + 13) % 100_003).unwrap() * 3_000_000_007)
23874            .collect()
23875    }
23876
23877    fn assert_bits(got: &[f64], expected: &[u64], case: &str) {
23878        let got: Vec<u64> = got.iter().map(|value| value.to_bits()).collect();
23879        assert_eq!(got, expected, "{case}");
23880    }
23881
23882    #[test]
23883    fn numpy_float64_with_nan_matches_pandas_bits() {
23884        // pandas: s = Series(floats(n)) with NaN at the missing slots.
23885        let cases: [(usize, [u64; 7]); 7] = [
23886            (
23887                7,
23888                [
23889                    0xc1ff_1185_2dcb_6db6,
23890                    0xc1d4_b658_c932_4924,
23891                    0x43db_301d_4a8d_87a3,
23892                    0x41e4_db58_e2f1_458e,
23893                    0x41d1_078f_09d3_9c5c,
23894                    0xc002_1f47_ceae_1b43,
23895                    0x4014_c8bc_93df_56e6,
23896                ],
23897            ),
23898            (
23899                8,
23900                [
23901                    0xc1ff_1184_f43d_b6da,
23902                    0xc1d1_c0de_426c_687d,
23903                    0x43d7_9d3c_ecd2_da2b,
23904                    0x41e3_7012_7d6c_71a5,
23905                    0x41cd_631d_3379_9929,
23906                    0xc003_b196_82f9_28dc,
23907                    0x4018_9de2_eba9_5ecc,
23908                ],
23909            ),
23910            (
23911                127,
23912                [
23913                    0x4200_324e_3389_2490,
23914                    0x4192_0704_ad1e_360d,
23915                    0x43c9_4a6b_3390_577d,
23916                    0x41dc_72bf_d6fa_9808,
23917                    0x41a5_38f5_8417_ae1e,
23918                    0x3fd0_b6bf_045c_e4d5,
23919                    0x4017_1585_bf13_21c4,
23920                ],
23921            ),
23922            (
23923                128,
23924                [
23925                    0x4200_324d_7236_db6e,
23926                    0x4191_df3a_f99d_a2ae,
23927                    0x43c9_1234_ffb7_4a93,
23928                    0x41dc_5310_c97c_292c,
23929                    0x41a5_09f4_cfcf_9206,
23930                    0x3fd0_d9df_0d68_00b0,
23931                    0x4017_61b6_5653_ae82,
23932                ],
23933            ),
23934            (
23935                129,
23936                [
23937                    0x4200_324c_d43e_db71,
23938                    0x4191_b81f_8a1d_61da,
23939                    0x43c8_daf6_85d3_386f,
23940                    0x41dc_33ca_af49_8c24,
23941                    0x41a4_dbc2_8609_a567,
23942                    0x3fd0_fcc5_39d9_6901,
23943                    0x4017_ade4_7855_7c25,
23944                ],
23945            ),
23946            (
23947                1000,
23948                [
23949                    0x421a_d4f6_8061_248e,
23950                    0x417e_39f9_3e1a_a248,
23951                    0x43c7_9481_cba1_263b,
23952                    0x41db_7825_28c0_37cc,
23953                    0x418d_27ba_a0ea_2f9a,
23954                    0x3fc8_e53a_e277_3d7f,
23955                    0x4018_3c97_3603_dfd0,
23956                ],
23957            ),
23958            (
23959                100_000,
23960                [
23961                    0x4283_088c_316e_46dc,
23962                    0x417b_7135_0c27_1185,
23963                    0x43c7_a0de_3b8e_ea34,
23964                    0x41db_7f57_6673_8d6b,
23965                    0x4157_58cc_33fd_4ae6,
23966                    0x3fc7_f1cf_b14a_14c8,
23967                    0x4018_06b5_f26a_c384,
23968                ],
23969            ),
23970        ];
23971        let all = |r: &PandasReductions<'_>| {
23972            [
23973                r.sum(),
23974                r.mean(),
23975                r.var(1),
23976                r.std(1),
23977                r.sem(1),
23978                r.skew(),
23979                r.kurt(),
23980            ]
23981        };
23982        for (n, expected) in cases {
23983            let (values, present) = floats(n);
23984            let r = PandasReductions::new(
23985                ReductionValues::Float(&values),
23986                Some(&present),
23987                MissingLayout::Numpy,
23988            );
23989            assert_bits(&all(&r), &expected, &format!("float64 n={n}"));
23990            // The same column holding NaN in its missing slots, whole and as
23991            // a concat's chunks.
23992            let with_nan: Vec<f64> = values
23993                .iter()
23994                .enumerate()
23995                .map(|(k, &value)| if k % 11 == 3 { f64::NAN } else { value })
23996                .collect();
23997            let r = PandasReductions::numpy_nan_missing(ReductionValues::Float(&with_nan));
23998            assert_bits(&all(&r), &expected, &format!("float64 NaN n={n}"));
23999            let (head, tail) = with_nan.split_at(n / 3);
24000            let chunks = [head, tail];
24001            let r = PandasReductions::numpy_nan_missing(ReductionValues::FloatChunks(&chunks));
24002            assert_bits(&all(&r), &expected, &format!("float64 NaN chunks n={n}"));
24003        }
24004        // NEGATIVE: the present values added left to right are not pandas'.
24005        let (values, present) = floats(100_000);
24006        let left_fold: f64 = values
24007            .iter()
24008            .enumerate()
24009            .filter(|&(k, _)| present[k / 64] >> (k % 64) & 1 == 1)
24010            .map(|(_, value)| value)
24011            .sum();
24012        assert_ne!(left_fold.to_bits(), 0x4283_088c_316e_46dc);
24013    }
24014
24015    #[test]
24016    fn numpy_int64_mean_sums_through_the_cast_buffer() {
24017        // pandas: Series(ints(n)) (int64): mean, var, sem, skew, kurt.
24018        let cases: [(usize, [u64; 5]); 3] = [
24019            (
24020                129,
24021                [
24022                    0x42e0_dda2_9987_3f9e,
24023                    0x45b9_0e2a_887d_aeda,
24024                    0x429c_34a1_c273_372f,
24025                    0x3f95_9e9d_c69e_ec88,
24026                    0xbff3_844b_ba13_eac1,
24027                ],
24028            ),
24029            (
24030                8193,
24031                [
24032                    0x42e1_0d5b_e407_5aa7,
24033                    0x45b8_3bf5_04f5_f2fc,
24034                    0x426b_d893_c5c9_85b1,
24035                    0x3f42_7452_ff15_86c7,
24036                    0xbff3_318c_611b_b59c,
24037                ],
24038            ),
24039            (
24040                20_000,
24041                [
24042                    0x42e1_0d17_ebf8_272d,
24043                    0x45b8_3c24_c921_82b6,
24044                    0x4261_d2a2_f139_68e2,
24045                    0x3f31_a21c_d4bb_ff52,
24046                    0xbff3_328c_4edc_26ee,
24047                ],
24048            ),
24049        ];
24050        for (n, expected) in cases {
24051            let values = ints(n);
24052            let r =
24053                PandasReductions::new(ReductionValues::Int(&values), None, MissingLayout::Numpy);
24054            let got = [r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()];
24055            assert_bits(&got, &expected, &format!("int64 n={n}"));
24056            // The same values read as chunks give the same bits.
24057            let (head, tail) = values.split_at(n / 3);
24058            let (middle, rest) = tail.split_at(1);
24059            let chunks = [head, middle, &[][..], rest];
24060            let chunked = PandasReductions::new(
24061                ReductionValues::IntChunks(&chunks),
24062                None,
24063                MissingLayout::Numpy,
24064            );
24065            let got = [
24066                chunked.mean(),
24067                chunked.var(1),
24068                chunked.sem(1),
24069                chunked.skew(),
24070                chunked.kurt(),
24071            ];
24072            assert_bits(&got, &expected, &format!("int64 chunks n={n}"));
24073        }
24074    }
24075
24076    #[test]
24077    fn masked_columns_add_runs_of_present_values() {
24078        // pandas: Series(pd.array(floats(n), dtype="Float64")) with NA at the
24079        // missing slots: sum, mean, var, sem. sum / mean differ from the
24080        // float64 column's above (n = 129: ...6e against ...71) - the runs.
24081        let cases: [(usize, [u64; 4]); 3] = [
24082            (
24083                129,
24084                [
24085                    0x4200_324c_d43e_db6e,
24086                    0x4191_b81f_8a1d_61d6,
24087                    0x43c8_daf6_85d3_3872,
24088                    0x41a4_dbc2_8609_a567,
24089                ],
24090            ),
24091            (
24092                1000,
24093                [
24094                    0x421a_d4f6_8061_2492,
24095                    0x417e_39f9_3e1a_a24c,
24096                    0x43c7_9481_cba1_263a,
24097                    0x418d_27ba_a0ea_2f9a,
24098                ],
24099            ),
24100            (
24101                100_000,
24102                [
24103                    0x4283_088c_316e_46de,
24104                    0x417b_7135_0c27_1188,
24105                    0x43c7_a0de_3b8e_ea37,
24106                    0x4157_58cc_33fd_4ae6,
24107                ],
24108            ),
24109        ];
24110        for (n, expected) in cases {
24111            let (values, present) = floats(n);
24112            let r = PandasReductions::new(
24113                ReductionValues::Float(&values),
24114                Some(&present),
24115                MissingLayout::Masked,
24116            );
24117            assert_bits(
24118                &[r.sum(), r.mean(), r.var(1), r.sem(1)],
24119                &expected,
24120                &format!("Float64 n={n}"),
24121            );
24122            let (head, tail) = values.split_at(n / 2 + 1);
24123            let chunks = [head, tail];
24124            let chunked = PandasReductions::new(
24125                ReductionValues::FloatChunks(&chunks),
24126                Some(&present),
24127                MissingLayout::Masked,
24128            );
24129            let got = [
24130                chunked.sum(),
24131                chunked.mean(),
24132                chunked.var(1),
24133                chunked.sem(1),
24134            ];
24135            assert_bits(&got, &expected, &format!("Float64 chunks n={n}"));
24136        }
24137        // pandas: pd.array(ints(n), dtype="Int64") with NA where k % 997 == 5:
24138        // mean and var, the runs summed within numpy's 8192-value buffers.
24139        for (n, expected) in [
24140            (8193, [0x42e1_0f35_29c2_807b_u64, 0x45b8_39ed_8746_bdcc]),
24141            (20_000, [0x42e1_0cf2_cc56_752a, 0x45b8_3c63_72fc_fad5]),
24142        ] {
24143            let values = ints(n);
24144            let mut present = vec![0_u64; n.div_ceil(64)];
24145            for k in (0..n).filter(|k| k % 997 != 5) {
24146                present[k / 64] |= 1 << (k % 64);
24147            }
24148            let r = PandasReductions::new(
24149                ReductionValues::Int(&values),
24150                Some(&present),
24151                MissingLayout::Masked,
24152            );
24153            assert_bits(&[r.mean(), r.var(1)], &expected, &format!("Int64 n={n}"));
24154        }
24155    }
24156
24157    #[test]
24158    fn edge_cases_match_pandas() {
24159        let reductions = |values: &[f64], present: Option<&[u64]>| {
24160            let r = PandasReductions::new(
24161                ReductionValues::Float(values),
24162                present,
24163                MissingLayout::Numpy,
24164            );
24165            [r.sum(), r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()]
24166        };
24167        // pandas: [1.5] * 10 -> 15.0 1.5 0.0 0.0 0.0 0.0 (a constant's kurt
24168        // is 0, not 0 minus the bias term); [2.0] * 3 kurt NaN.
24169        let constant = reductions(&[1.5; 10], None);
24170        assert_eq!(constant, [15.0, 1.5, 0.0, 0.0, 0.0, 0.0]);
24171        assert!(reductions(&[2.0; 3], None)[5].is_nan());
24172        // [1, 2] skew NaN; [1, 2, 4] skew 0.9352195295828237.
24173        assert!(reductions(&[1.0, 2.0], None)[4].is_nan());
24174        assert_eq!(
24175            reductions(&[1.0, 2.0, 4.0], None)[4],
24176            0.935_219_529_582_823_7
24177        );
24178        // Empty / all missing: sum 0.0, the rest NaN.
24179        let empty = reductions(&[], None);
24180        assert_eq!(empty[0], 0.0);
24181        assert!(empty[1..].iter().all(|value| value.is_nan()));
24182        let all_missing = reductions(&[3.0; 5], Some(&[0]));
24183        assert_eq!(all_missing[0], 0.0);
24184        assert!(all_missing[1].is_nan());
24185        // -0.0 * 10 sums to 0.0 (numpy adds onto the identity 0.0).
24186        assert_eq!(
24187            reductions(&[-0.0; 10], None)[0].to_bits(),
24188            0.0_f64.to_bits()
24189        );
24190        // An inf: sum / mean inf, the spread NaN.
24191        let inf = reductions(&[1.0, f64::INFINITY, 2.0, 5.0], None);
24192        assert_eq!(inf[0], f64::INFINITY);
24193        assert!(inf[2..].iter().all(|value| value.is_nan()));
24194    }
24195
24196    #[test]
24197    fn int64_mean_skipping_is_the_filled_mean_vk7y9() {
24198        // A datetime64 mean read straight off its nanos, NaT as 0, is the
24199        // bit-identical mean of the filled copy under its presence bits -
24200        // across cast-buffer chunks, with NaT anywhere (br-frankenpandas-vk7y9).
24201        const NAT: i64 = i64::MIN;
24202        let nanos: Vec<i64> = (0..20_000_i64)
24203            .map(|k| {
24204                if k % 13 == 5 {
24205                    NAT
24206                } else {
24207                    1_577_836_800_000_000_000 + k * 3_600_000_000_123
24208                }
24209            })
24210            .collect();
24211        let mut present = vec![0_u64; nanos.len().div_ceil(64)];
24212        let filled: Vec<i64> = nanos
24213            .iter()
24214            .enumerate()
24215            .map(|(i, &ns)| {
24216                if ns == NAT {
24217                    0
24218                } else {
24219                    present[i / 64] |= 1 << (i % 64);
24220                    ns
24221                }
24222            })
24223            .collect();
24224        let expected = PandasReductions::new(
24225            ReductionValues::Int(&filled),
24226            Some(&present),
24227            MissingLayout::Numpy,
24228        )
24229        .mean();
24230        assert_eq!(
24231            PandasReductions::int64_mean_skipping(&nanos, NAT).to_bits(),
24232            expected.to_bits()
24233        );
24234        // NEGATIVE: every slot missing is NaN, not a mean of the zeros.
24235        assert!(PandasReductions::int64_mean_skipping(&[NAT, NAT], NAT).is_nan());
24236        assert!(PandasReductions::int64_mean_skipping(&[], NAT).is_nan());
24237    }
24238}
24239
24240/// pandas' default text-to-float64 conversion against live pandas 2.2.3
24241/// bits: `read_csv(StringIO('x\n' + token), dtype={'x': 'float64'})`
24242/// (br-frankenpandas-py3c0).
24243#[cfg(test)]
24244mod pandas_decimal_py3c0 {
24245    use super::{PandasDecimal, pandas_decimal_to_f64, pandas_int_to_f64};
24246
24247    fn bits(token: &str) -> u64 {
24248        match pandas_decimal_to_f64(token.as_bytes()) {
24249            PandasDecimal::Value(value) => value.to_bits(),
24250            other => panic!("{token:?}: {other:?}"),
24251        }
24252    }
24253
24254    #[test]
24255    fn tokens_convert_to_pandas_bits() {
24256        let cases = [
24257            ("9.890295358649789", 0x4023_c7d4_cb12_5ce4),
24258            ("0.8690736625851781286570704999", 0x3feb_cf73_91d3_c8f1),
24259            ("0.000000068288360759838675650889", 0x3e72_54bd_8bcd_610b),
24260            ("-0.0080749473608410608782560", 0xbf80_8999_16a7_63f3),
24261            ("99999999999999999", 0x4376_3457_85d8_a001),
24262            ("1234567890123456789012345", 0x44f0_56e0_f36a_6444),
24263            // 17 leading zeros are the 17 digits kept.
24264            ("00000000000000000.5", 0x0000_0000_0000_0000),
24265            ("-00000000000000000.5", 0x8000_0000_0000_0000),
24266            ("1.5E+10", 0x420b_f08e_b000_0000),
24267            ("-.5e-3", 0xbf40_624d_d2f1_a9fc),
24268            ("5.", 0x4014_0000_0000_0000),
24269            ("1e-320", 0x0000_0000_0000_07e8),
24270            ("2.5e-310", 0x0000_2e05_5c9a_3f6c),
24271            ("-1e-400", 0x8000_0000_0000_0000),
24272            // Below 1e-616: +0.0, the sign dropped.
24273            ("-1e-700", 0x0000_0000_0000_0000),
24274            // The exponent wraps as a 32-bit integer.
24275            ("1e-4294967296", 0x3ff0_0000_0000_0000),
24276            ("1.7976931348623157e308", 0x7fef_ffff_ffff_ffff),
24277            ("0.001e310", 0x7fac_7b1f_3cac_7433),
24278        ];
24279        for (token, expected) in cases {
24280            assert_eq!(bits(token), expected, "{token:?}");
24281        }
24282        // NEGATIVE: the correctly rounded value is not pandas'.
24283        let correctly_rounded: f64 = "9.890295358649789".parse().unwrap();
24284        assert_ne!(correctly_rounded.to_bits(), 0x4023_c7d4_cb12_5ce4);
24285    }
24286
24287    #[test]
24288    fn what_pandas_does_not_read_as_a_float() {
24289        for token in [
24290            "1e309",
24291            "0e400",
24292            "1.8e308",
24293            "1e+0000000000000000001",
24294            "1e-2147483649",
24295            "1e",
24296            "1e+",
24297            "1.5d3",
24298            "0x10",
24299            "1_000.5",
24300            "1..5",
24301        ] {
24302            assert_eq!(
24303                pandas_decimal_to_f64(token.as_bytes()),
24304                PandasDecimal::Rejected,
24305                "{token:?}"
24306            );
24307        }
24308        for token in ["inf", "-Infinity", "nan", ".", "-", "e5", "+.e1", "--1", ""] {
24309            assert_eq!(
24310                pandas_decimal_to_f64(token.as_bytes()),
24311                PandasDecimal::NotDecimal,
24312                "{token:?}"
24313            );
24314        }
24315    }
24316
24317    #[test]
24318    fn an_integer_in_a_float_column_takes_the_same_conversion() {
24319        assert_eq!(pandas_int_to_f64(-42).to_bits(), (-42.0_f64).to_bits());
24320        assert_eq!(
24321            pandas_int_to_f64(99_999_999_999_999_999).to_bits(),
24322            0x4376_3457_85d8_a001
24323        );
24324        assert_eq!(
24325            pandas_int_to_f64(-99_999_999_999_999_999).to_bits(),
24326            0xc376_3457_85d8_a001
24327        );
24328    }
24329
24330    /// The civil-date month shift is chrono's relativedelta (a date made,
24331    /// moved and read back) for every day of the month at its edges, leap
24332    /// and plain years, before and after 1970, sub-second times and month
24333    /// counts of either sign (br-frankenpandas-4g57c). NEGATIVE: a shift past
24334    /// datetime64[ns] (either end, or a month count near i64) is None, as
24335    /// chrono's timestamp is out of range.
24336    #[test]
24337    fn calendar_months_match_chrono_relativedelta_4g57c() {
24338        use chrono::{Datelike, NaiveDate};
24339
24340        use super::add_calendar_months_nanos;
24341        let reference = |nanos: i64, months: i64| -> Option<i64> {
24342            let at = chrono::DateTime::from_timestamp(
24343                nanos.div_euclid(1_000_000_000),
24344                u32::try_from(nanos.rem_euclid(1_000_000_000)).ok()?,
24345            )?
24346            .naive_utc();
24347            let total = i64::from(at.year())
24348                .checked_mul(12)?
24349                .checked_add(i64::from(at.month0()))?
24350                .checked_add(months)?;
24351            let year = i32::try_from(total.div_euclid(12)).ok()?;
24352            let month = u32::try_from(total.rem_euclid(12)).ok()? + 1;
24353            let last = (28..=31)
24354                .rev()
24355                .find(|day| NaiveDate::from_ymd_opt(year, month, *day).is_some())?;
24356            NaiveDate::from_ymd_opt(year, month, at.day().min(last))?
24357                .and_time(at.time())
24358                .and_utc()
24359                .timestamp_nanos_opt()
24360        };
24361        let day_nanos = 86_400_000_000_000_i64;
24362        let mut checked = 0;
24363        for year in [1678, 1699, 1900, 1969, 1970, 2000, 2023, 2024, 2100, 2261] {
24364            for month in 1..=12 {
24365                for day in [1, 15, 27, 28, 29, 30, 31] {
24366                    let Some(date) = NaiveDate::from_ymd_opt(year, month, day) else {
24367                        continue;
24368                    };
24369                    let Some(midnight) = date
24370                        .and_hms_opt(0, 0, 0)
24371                        .and_then(|at| at.and_utc().timestamp_nanos_opt())
24372                    else {
24373                        continue;
24374                    };
24375                    for time in [0, 1, 37_123_456_789, day_nanos - 1] {
24376                        let nanos = midnight + time;
24377                        for months in [-2400, -13, -12, -1, 0, 1, 2, 11, 12, 25, 1200] {
24378                            assert_eq!(
24379                                add_calendar_months_nanos(nanos, months),
24380                                reference(nanos, months),
24381                                "{nanos} + {months} months"
24382                            );
24383                            checked += 1;
24384                        }
24385                    }
24386                }
24387            }
24388        }
24389        assert!(checked > 30_000, "{checked}");
24390        // NEGATIVE: out of range at both ends and for absurd month counts.
24391        let last = i64::MAX - 1;
24392        assert_eq!(add_calendar_months_nanos(last, 1), None);
24393        assert_eq!(reference(last, 1), None);
24394        assert_eq!(add_calendar_months_nanos(i64::MIN + 1, -1), None);
24395        assert_eq!(add_calendar_months_nanos(0, i64::MAX), None);
24396        assert_eq!(add_calendar_months_nanos(0, i64::MIN), None);
24397        assert_eq!(add_calendar_months_nanos(0, 12 * 400), None);
24398        assert_eq!(super::add_calendar_months_days(i64::MAX, 1), None);
24399        assert_eq!(super::add_calendar_months_days(0, i64::MAX), None);
24400        // The clipped day: Jan 31 2024 + 1 month is Feb 29.
24401        let jan31 = 19_753 * day_nanos;
24402        assert_eq!(
24403            add_calendar_months_nanos(jan31, 1),
24404            Some(19_782 * day_nanos)
24405        );
24406    }
24407
24408    /// A numbered host value equals another as their numbers and hashes as
24409    /// its number, the host's own eq not asked; an unnumbered one asks it
24410    /// (br-frankenpandas-jq8qb). NEGATIVE: numbered values of different
24411    /// numbers differ though the host calls them equal; a numbered value
24412    /// beside an unnumbered one takes the host's answer.
24413    #[test]
24414    fn numbered_host_values_compare_and_hash_by_number_jq8qb() {
24415        use std::hash::{Hash, Hasher};
24416
24417        use super::{HostObject, HostValue, ObjectValue};
24418
24419        struct Numbered(Option<i64>, &'static str);
24420        impl HostObject for Numbered {
24421            fn host_eq(&self, other: &dyn HostObject) -> bool {
24422                other
24423                    .as_any()
24424                    .downcast_ref::<Self>()
24425                    .is_some_and(|other| other.1 == self.1)
24426            }
24427            fn host_repr(&self) -> String {
24428                self.1.to_owned()
24429            }
24430            fn host_str(&self) -> String {
24431                self.1.to_owned()
24432            }
24433            fn host_hash(&self) -> Option<u64> {
24434                Some(self.1.len() as u64)
24435            }
24436            fn host_cmp(&self, _other: &dyn HostObject) -> Option<std::cmp::Ordering> {
24437                None
24438            }
24439            fn as_any(&self) -> &dyn std::any::Any {
24440                self
24441            }
24442            fn host_number(&self) -> Option<i64> {
24443                self.0
24444            }
24445        }
24446        let hash = |value: &ObjectValue| {
24447            let mut hasher = std::hash::DefaultHasher::new();
24448            value.hash(&mut hasher);
24449            hasher.finish()
24450        };
24451        let cell = |number, name| ObjectValue::Host(HostValue::new(Numbered(number, name)));
24452        assert_eq!(cell(Some(7), "a"), cell(Some(7), "b"));
24453        assert_eq!(hash(&cell(Some(7), "a")), hash(&cell(Some(7), "bb")));
24454        assert_ne!(cell(Some(7), "a"), cell(Some(8), "a"));
24455        assert_eq!(cell(Some(7), "a"), cell(None, "a"));
24456        assert_ne!(cell(Some(7), "a"), cell(None, "b"));
24457        assert_eq!(cell(None, "a"), cell(None, "a"));
24458        assert_ne!(cell(None, "a"), cell(None, "b"));
24459        assert_eq!(hash(&cell(None, "ab")), hash(&cell(None, "cd")));
24460    }
24461
24462    #[test]
24463    fn interval_parse_rejects_multibyte_and_malformed_inputs_without_panic_4qg5w_13() {
24464        use super::{Interval, IntervalClosed, TypeError};
24465        for bad in [
24466            "",
24467            "   ",
24468            "€€",
24469            "€€€€€",
24470            "[αβγ]",
24471            "(α, β]",
24472            "[1, 2, 3]",
24473            "[1 2]",
24474            "]1, 2[",
24475        ] {
24476            let err = Interval::parse(bad).expect_err("malformed interval must return Err");
24477            assert!(matches!(err, TypeError::ValueNotParseable { .. }));
24478        }
24479        // NEGATIVE: valid intervals still parse identically.
24480        let parsed = Interval::parse(" [1.5, 3.5) ").expect("valid interval");
24481        assert_eq!(parsed.left, 1.5);
24482        assert_eq!(parsed.right, 3.5);
24483        assert_eq!(parsed.closed, IntervalClosed::Left);
24484    }
24485
24486    #[test]
24487    fn period_scalar_calendar_asfreq_to_timestamp_and_interval_closed_open_match_pandas_uo1wg() {
24488        use super::{Interval, IntervalClosed, Period, PeriodFreq, Timestamp};
24489
24490        // 1. Interval closed_left / closed_right / open_left / open_right across all 4 variants
24491        let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
24492        assert!(!right.closed_left());
24493        assert!(right.closed_right());
24494        assert!(right.open_left());
24495        assert!(!right.open_right());
24496
24497        let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
24498        assert!(left.closed_left());
24499        assert!(!left.closed_right());
24500        assert!(!left.open_left());
24501        assert!(left.open_right());
24502
24503        let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
24504        assert!(both.closed_left());
24505        assert!(both.closed_right());
24506        assert!(!both.open_left());
24507        assert!(!both.open_right());
24508
24509        let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
24510        assert!(!neither.closed_left());
24511        assert!(!neither.closed_right());
24512        assert!(neither.open_left());
24513        assert!(neither.open_right());
24514
24515        // 2. Period("2024-03", freq="M")
24516        let p_m = Period::parse("2024-03").expect("2024-03");
24517        assert_eq!(p_m.year(), Some(2024));
24518        assert_eq!(p_m.month(), Some(3));
24519        assert_eq!(p_m.day(), Some(31));
24520        assert_eq!(p_m.hour(), Some(0));
24521        assert_eq!(p_m.minute(), Some(0));
24522        assert_eq!(p_m.second(), Some(0));
24523        assert_eq!(p_m.quarter(), Some(1));
24524        assert_eq!(p_m.qyear(), Some(2024));
24525        assert_eq!(p_m.weekday(), Some(6));
24526        assert_eq!(p_m.dayofweek(), Some(6));
24527        assert_eq!(p_m.day_of_week(), Some(6));
24528        assert_eq!(p_m.dayofyear(), Some(91));
24529        assert_eq!(p_m.day_of_year(), Some(91));
24530        assert_eq!(p_m.days_in_month(), Some(31));
24531        assert_eq!(p_m.daysinmonth(), Some(31));
24532        assert_eq!(p_m.week(), Some(13));
24533        assert_eq!(p_m.weekofyear(), Some(13));
24534        assert_eq!(p_m.is_leap_year(), Some(true));
24535        assert_eq!(p_m.start_time().value(), 1_709_251_200_000_000_000);
24536        assert_eq!(p_m.end_time().value(), 1_711_929_599_999_999_999);
24537        assert_eq!(p_m.to_timestamp("start").unwrap(), p_m.start_time());
24538        assert_eq!(p_m.to_timestamp("end").unwrap(), p_m.end_time());
24539        assert_eq!(
24540            p_m.asfreq("D").unwrap(),
24541            Period::parse("2024-03-31").unwrap()
24542        );
24543        assert_eq!(
24544            p_m.asfreq_with_how("D", "start").unwrap(),
24545            Period::parse("2024-03-01").unwrap()
24546        );
24547        assert_eq!(p_m.strftime("%Y-%m-%d"), "2024-03-31");
24548
24549        // 3. Fiscal Quarterly Period("2025Q1", freq="Q-JAN") -> ends 2024-04-30
24550        let ts_feb = Timestamp::parse("2024-02-15").unwrap();
24551        let p_qjan = ts_feb.to_period("Q-JAN").unwrap();
24552        assert_eq!(p_qjan.to_string(), "2025Q1");
24553        assert_eq!(p_qjan.year(), Some(2024));
24554        assert_eq!(p_qjan.qyear(), Some(2025));
24555        assert_eq!(p_qjan.quarter(), Some(1));
24556        assert_eq!(p_qjan.month(), Some(4));
24557        assert_eq!(p_qjan.day(), Some(30));
24558        assert_eq!(p_qjan.days_in_month(), Some(30));
24559        assert_eq!(p_qjan.start_time().value(), 1_706_745_600_000_000_000);
24560        assert_eq!(p_qjan.end_time().value(), 1_714_521_599_999_999_999);
24561        assert_eq!(p_qjan.strftime("%Y-%m-%d"), "2024-04-30");
24562
24563        // 4. Business Friday Period("2024-03-15", freq="B") -> end_time is Friday 23:59:59.999999999, NOT Sunday
24564        let p_fri = Timestamp::parse("2024-03-15")
24565            .unwrap()
24566            .to_period("B")
24567            .unwrap();
24568        assert_eq!(p_fri.day(), Some(15));
24569        assert_eq!(p_fri.weekday(), Some(4));
24570        assert_eq!(
24571            p_fri.end_time().value(),
24572            p_fri.start_time().value() + 86_400_000_000_000 - 1
24573        );
24574        assert_eq!(
24575            p_fri.asfreq_with_how("D", "E").unwrap(),
24576            Period::parse("2024-03-15").unwrap()
24577        );
24578
24579        // 5. Period::now("D") succeeds and matches Timestamp::now().to_period("D")
24580        let p_now = Period::now("D").expect("Period::now(D)");
24581        assert_eq!(p_now.freq(), PeriodFreq::Daily);
24582        assert!(!p_now.is_nat());
24583
24584        // 6. NEGATIVE cases: NaT propagation, invalid frequency, invalid `how`
24585        let p_nat = Period::new(i64::MIN, PeriodFreq::Monthly);
24586        assert!(p_nat.is_nat());
24587        assert_eq!(p_nat.year(), None);
24588        assert_eq!(p_nat.qyear(), None);
24589        assert_eq!(p_nat.quarter(), None);
24590        assert_eq!(p_nat.is_leap_year(), None);
24591        assert!(p_nat.start_time().is_nat());
24592        assert!(p_nat.end_time().is_nat());
24593        assert_eq!(p_nat.strftime("%Y-%m-%d"), "NaT");
24594        assert!(p_nat.asfreq("D").unwrap().is_nat());
24595        assert_eq!(p_nat.asfreq("D").unwrap().freq(), PeriodFreq::Daily);
24596        assert!(p_m.asfreq("NOT_A_FREQ").is_err());
24597        assert!(p_m.asfreq_with_how("D", "middle").is_err());
24598        assert!(p_m.to_timestamp("middle").is_err());
24599        assert!(Timestamp::nat().to_period("D").is_err());
24600    }
24601
24602    #[test]
24603    fn timestamp_tz_localize_convert_isoformat_tzname_and_getters_match_pandas_sddfo() {
24604        use crate::{TimeZoneError, Timestamp, TypeError};
24605
24606        // 1. Naive Timestamp("2024-01-01 03:30:00") localized to America/New_York (EST, -05:00)
24607        let ts_naive = Timestamp::parse("2024-01-01T03:30:00").unwrap();
24608        assert_eq!(ts_naive.value(), 1_704_079_800_000_000_000);
24609        assert_eq!(ts_naive.tzname(), None);
24610
24611        let ts_ny = ts_naive.tz_localize(Some("America/New_York"));
24612        assert_eq!(ts_ny.value(), 1_704_097_800_000_000_000);
24613        assert_eq!(ts_ny.isoformat(), "2024-01-01T03:30:00-05:00");
24614        assert_eq!(ts_ny.tzname().as_deref(), Some("EST"));
24615        assert_eq!(ts_ny.year(), Some(2024));
24616        assert_eq!(ts_ny.month(), Some(1));
24617        assert_eq!(ts_ny.day(), Some(1));
24618        assert_eq!(ts_ny.hour(), Some(3));
24619        assert_eq!(ts_ny.minute(), Some(30));
24620
24621        // 2. UTC Timestamp("2024-01-01 03:30:00Z") converted to America/New_York -> 2023-12-31 22:30:00-05:00
24622        let ts_utc = Timestamp::parse("2024-01-01T03:30:00Z").unwrap();
24623        let ts_from_utc = ts_utc.tz_convert("America/New_York");
24624        assert_eq!(ts_from_utc.value(), 1_704_079_800_000_000_000);
24625        assert_eq!(ts_from_utc.isoformat(), "2023-12-31T22:30:00-05:00");
24626        assert_eq!(ts_from_utc.tzname().as_deref(), Some("EST"));
24627        assert_eq!(ts_from_utc.year(), Some(2023));
24628        assert_eq!(ts_from_utc.month(), Some(12));
24629        assert_eq!(ts_from_utc.day(), Some(31));
24630        assert_eq!(ts_from_utc.hour(), Some(22));
24631        assert_eq!(ts_from_utc.minute(), Some(30));
24632        assert_eq!(ts_from_utc.dayofweek(), Some(6));
24633        assert_eq!(ts_from_utc.day_name(), "Sunday");
24634        assert_eq!(ts_from_utc.month_name(), "December");
24635        assert_eq!(ts_from_utc.toordinal(), Some(738_885));
24636        assert_eq!(ts_from_utc.is_year_end(), Some(true));
24637        assert_eq!(ts_from_utc.is_year_start(), Some(false));
24638
24639        // 3. Stripping timezone via tz_localize(None) preserves wall clock (2023-12-31 22:30:00 naive)
24640        let stripped = ts_from_utc.tz_localize(None);
24641        assert_eq!(stripped.tzinfo(), None);
24642        assert_eq!(stripped.value(), 1_704_061_800_000_000_000);
24643        assert_eq!(stripped.isoformat(), "2023-12-31T22:30:00");
24644
24645        // 4. Summer EDT timestamp has tzname "EDT" and "-04:00" offset
24646        let ts_summer = Timestamp::parse("2024-07-01T12:00:00")
24647            .unwrap()
24648            .tz_localize(Some("America/New_York"));
24649        assert_eq!(ts_summer.isoformat(), "2024-07-01T12:00:00-04:00");
24650        assert_eq!(ts_summer.tzname().as_deref(), Some("EDT"));
24651
24652        // 5. replace(year=2025) on tz-aware Timestamp preserves wall-clock hour/minute in target year
24653        let replaced = ts_from_utc.replace(Some(2025), None, None, None, None, None, None, None);
24654        assert_eq!(replaced.value(), 1_767_238_200_000_000_000);
24655        assert_eq!(replaced.isoformat(), "2025-12-31T22:30:00-05:00");
24656
24657        // 6. NEGATIVE cases: localizing already-aware or converting naive raises TypeError / folds to NaT
24658        assert_eq!(
24659            ts_ny.try_tz_localize(Some("UTC")),
24660            Err(TypeError::AlreadyTzAware)
24661        );
24662        assert!(ts_ny.tz_localize(Some("UTC")).is_nat());
24663        assert_eq!(
24664            ts_naive.try_tz_convert(Some("UTC")),
24665            Err(TypeError::TzNaiveCannotConvert)
24666        );
24667        assert!(ts_naive.tz_convert("UTC").is_nat());
24668        assert!(matches!(
24669            ts_naive.try_tz_localize(Some("Mars/Olympus")),
24670            Err(TypeError::TimeZone(TimeZoneError::Unknown(_)))
24671        ));
24672        assert!(matches!(
24673            ts_ny.try_tz_convert(Some("Mars/Olympus")),
24674            Err(TypeError::TimeZone(TimeZoneError::Unknown(_)))
24675        ));
24676    }
24677}