Skip to main content

fp_index/
lib.rs

1// MultiIndex level walks index several parallel arrays by the same counter; rewriting to
2// iterators would obscure the level arithmetic without changing behaviour.
3#![allow(clippy::needless_range_loop)]
4#![forbid(unsafe_code)]
5#![warn(rustdoc::broken_intra_doc_links)]
6
7//! Row-label / index machinery for **frankenpandas** — every
8//! `DataFrame` and `Series` in fp-frame carries an [`Index`] that
9//! pairs labels with positional row indices, plus the alignment
10//! algebra that pandas users expect from `Series + Series` and
11//! `DataFrame.align()`.
12//!
13//! ## Core types
14//!
15//! - [`Index`]: the canonical row-label container. Internally a
16//!   typed `Vec<IndexLabel>` plus an O(1) label-lookup hashmap
17//!   built lazily on first use. Pandas `Index` shape: monotonic
18//!   probes, duplicate handling, range-style construction
19//!   (`Index::from_range(0..N)`), name metadata.
20//! - [`IndexLabel`]: typed label enum — `Int64(i64)`, `Float64(f64)`,
21//!   `Utf8(String)`, `Bool(bool)`, `Datetime64(i64)`,
22//!   `Timedelta64(i64)`. Lets one `Index` carry mixed-type labels
23//!   without erasing to strings.
24//! - [`MultiIndex`]: hierarchical multi-level index for
25//!   pandas-style row MultiIndex DataFrames. Each level is itself
26//!   a `Vec<IndexLabel>` plus an integer codes array.
27//! - [`MultiIndexOrIndex`]: sum-type for code paths that accept
28//!   either flat `Index` or `MultiIndex`.
29//! - [`DuplicateKeep`]: enum controlling `keep='first' | 'last'
30//!   | False` semantics in `Index.duplicated` /
31//!   `Index.drop_duplicates` etc.
32//!
33//! ## Alignment algebra
34//!
35//! Binary ops between two pandas-shaped frames need to align rows
36//! by label. The aligner builds an [`AlignmentPlan`] (or
37//! [`MultiAlignmentPlan`] for N-way joins) that the caller then
38//! applies to each side's value buffers:
39//!
40//! - [`align`] dispatches on [`AlignMode`] (`Left`, `Right`,
41//!   `Inner`, `Outer`).
42//! - [`align_inner`], [`align_left`], [`align_union`]: direct
43//!   single-mode entry points.
44//! - [`leapfrog_union`] / [`leapfrog_intersection`]: N-way row
45//!   alignment via a leapfrog merge over already-sorted indexes
46//!   (used by [`multi_way_align`]).
47//! - [`validate_alignment_plan`]: sanity check (lengths match,
48//!   indices in bounds).
49//!
50//! ## Date / time helpers
51//!
52//! Pandas `pd.date_range` / `pd.timedelta_range` analogs:
53//!
54//! - [`timedelta_range`]: pandas-style timedelta range builder.
55//! - [`apply_date_offset`] / [`apply_date_offset_to_nanos`]:
56//!   evaluate a [`DateOffset`] against an anchor timestamp.
57//! - [`infer_freq`] / [`infer_freq_from_timestamps`] /
58//!   [`infer_freq_from_nanos`]: pandas-style frequency inference
59//!   from a sample of timestamps.
60//! - [`format_datetime_ns`]: render a nanosecond-since-epoch i64
61//!   as the canonical `YYYY-MM-DD HH:MM:SS[.f]` string used in
62//!   IndexLabel display and IO formatters.
63//!
64//! ## Error reporting
65//!
66//! - [`IndexError`]: structural / lookup failures (not-monotonic,
67//!   not-unique, missing-label, validation-mismatch).
68//! - [`TimedeltaRangeError`] / [`DateRangeError`]: range builder
69//!   parse / step / overflow errors.
70//!
71//! ## Relationship to other crates
72//!
73//! - **fp-types** supplies [`Scalar`] / [`Timedelta`] /
74//!   `format_datetime_ns` primitives.
75//! - **fp-frame** stores an `Index` per DataFrame / Series and uses
76//!   the alignment algebra here for binary ops.
77//! - **fp-join** consumes alignment plans for merge-style joins.
78
79use std::{
80    borrow::Cow,
81    collections::HashMap,
82    fmt,
83    sync::{
84        Arc, Mutex, OnceLock,
85        atomic::{AtomicU64, Ordering as AtomicOrdering},
86    },
87};
88
89use chrono::Datelike;
90use fp_types::{
91    Interval, IntervalClosed, Period, PeriodFreq, Scalar, Timedelta, TimedeltaComponents,
92    Timestamp, interval_range,
93};
94// Dedup / set-op seen-sets key on &IndexLabel and read output order from the
95// INPUT scan (first-seen filter / positional bool), never from map iteration —
96// so the hasher is observationally invisible. FxHash (rustc-hash, pure safe
97// Rust) replaces the std SipHasher on these hot membership maps; public-return
98// maps (position_map_first, groupby) keep std HashMap to avoid an API change.
99use rustc_hash::{FxHashMap, FxHashSet};
100use serde::{Deserialize, Deserializer, Serialize, Serializer};
101use thiserror::Error;
102
103/// A total-ordering, hashable `f64` wrapper for use as an index label
104/// (br-frankenpandas-i10en). `-0.0` is normalized to `+0.0` and all NaNs
105/// collapse to one bucket, so `Eq`/`Hash`/`Ord` are mutually consistent
106/// (a == b implies cmp == Equal) — matching pandas' Float64Index. NaN sorts
107/// after every finite value (pandas NaN-last).
108#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
109#[serde(transparent)]
110pub struct OrderedF64(pub f64);
111
112impl OrderedF64 {
113    #[inline]
114    fn canonical_bits(self) -> u64 {
115        if self.0.is_nan() {
116            f64::NAN.to_bits()
117        } else if self.0 == 0.0 {
118            0.0_f64.to_bits()
119        } else {
120            self.0.to_bits()
121        }
122    }
123}
124
125impl PartialEq for OrderedF64 {
126    fn eq(&self, other: &Self) -> bool {
127        self.canonical_bits() == other.canonical_bits()
128    }
129}
130impl Eq for OrderedF64 {}
131/// The canonical bits spread ([`fp_types::spread_float_bits`]): a round
132/// float's raw bits end in zeros FxHash keeps where its tables take their
133/// buckets from (br-frankenpandas-bss5q.3). Equal labels still hash equal.
134impl std::hash::Hash for OrderedF64 {
135    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
136        fp_types::spread_float_bits(self.canonical_bits()).hash(state);
137    }
138}
139impl Ord for OrderedF64 {
140    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
141        use std::cmp::Ordering;
142        let (a, b) = (self.0, other.0);
143        match (a.is_nan(), b.is_nan()) {
144            (true, true) => Ordering::Equal,
145            (true, false) => Ordering::Greater,
146            (false, true) => Ordering::Less,
147            (false, false) => a.partial_cmp(&b).unwrap_or(Ordering::Equal),
148        }
149    }
150}
151impl PartialOrd for OrderedF64 {
152    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
153        Some(self.cmp(other))
154    }
155}
156
157/// Labels compare as pandas' do: an int and a float are one number (`1 ==
158/// 1.0`, hashed alike, as Python's), ordered by value beside each other;
159/// every other kind equals only its own kind, and kinds order as declared
160/// below with the numbers first (br-frankenpandas-l5sed: `Int64(1)` and
161/// `Float64(1.0)` were different labels, so `s.loc[2.0]` missed an int
162/// index).
163#[derive(Debug, Clone, Serialize, Deserialize)]
164#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
165pub enum IndexLabel {
166    Int64(i64),
167    Utf8(String),
168    Timedelta64(i64),
169    Datetime64(i64),
170    /// pandas Float64Index label (br-frankenpandas-i10en). Placed before
171    /// `Null` so the derived cross-variant order keeps every concrete label
172    /// before nulls.
173    Float64(OrderedF64),
174    /// pandas boolean index label.
175    Bool(bool),
176    /// An object cell as a label (fvsao.66): a `datetime.date` from
177    /// `groupby(s.dt.date)`, kept as that object rather than its text.
178    /// Ordered by [`fp_types::ObjectValue::total_cmp`] (Python's own order
179    /// where it has one); before `Null` so null labels still sort last.
180    Object(fp_types::ObjectValue),
181    /// A period, a PeriodIndex's label (br-frankenpandas-45fzr): a Series /
182    /// DataFrame row index, groupby keys and value_counts over periods keep
183    /// them (they were their text). Ordered by ordinal (then freq); NaT
184    /// (ordinal `i64::MIN`) is missing. Before `Null` so null labels still
185    /// sort last.
186    Period(fp_types::Period),
187    /// An interval, an IntervalIndex's label (br-frankenpandas-c27hq): a
188    /// Series / DataFrame row index, value_counts(bins=), groupby over
189    /// pd.cut and a cut column's value_counts keep them (they were their
190    /// text). Ordered by left, then right endpoint; before `Null` so null
191    /// labels still sort last.
192    Interval(fp_types::Interval),
193    /// Typed missing label (br-frankenpandas-joeff): lets value_counts
194    /// (dropna=False) and friends keep pandas' distinct None / nan / NaT
195    /// buckets instead of collapsing them or colliding with genuine
196    /// "None"/"nan" strings. Appended LAST so the derived `Ord` sorts null
197    /// labels after every concrete label (pandas NaN-last sort order) without
198    /// disturbing the existing cross-variant order. `Eq`/`Hash` are
199    /// kind-SENSITIVE (None != nan != NaT), matching `ScalarKey::Null`
200    /// bucket identity.
201    Null(fp_types::NullKind),
202}
203
204/// `value` as the int it equals exactly, if it is one (no fraction, inside
205/// i64's range).
206#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)] // checked round trip
207fn exact_i64(value: f64) -> Option<i64> {
208    // 2^63 is the first float past i64's range.
209    const LIMIT: f64 = 9_223_372_036_854_775_808.0;
210    (value.fract() == 0.0 && (-LIMIT..LIMIT).contains(&value)).then_some(value as i64)
211}
212
213/// An int against a float, exactly: NaN after every number, as a float
214/// index orders it.
215#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)] // checked range
216fn cmp_int_float(int: i64, float: f64) -> std::cmp::Ordering {
217    use std::cmp::Ordering;
218    const LIMIT: f64 = 9_223_372_036_854_775_808.0;
219    if float.is_nan() || float >= LIMIT {
220        return Ordering::Less;
221    }
222    if float < -LIMIT {
223        return Ordering::Greater;
224    }
225    let whole = float.trunc();
226    match int.cmp(&(whole as i64)) {
227        Ordering::Equal if float > whole => Ordering::Less,
228        Ordering::Equal if float < whole => Ordering::Greater,
229        other => other,
230    }
231}
232
233impl IndexLabel {
234    /// The int this label equals: an int's own value, an integral float's
235    /// (`2.0` is `2`, as pandas looks it up in an int index); None for any
236    /// other label.
237    #[must_use]
238    pub fn exact_int(&self) -> Option<i64> {
239        match self {
240            Self::Int64(value) => Some(*value),
241            Self::Float64(value) => exact_i64(value.0),
242            _ => None,
243        }
244    }
245
246    /// The label's kind in the cross-kind order: numbers first (ints and
247    /// floats together), then the kinds as declared, missing last.
248    fn kind_rank(&self) -> u8 {
249        match self {
250            Self::Int64(_) | Self::Float64(_) => 0,
251            Self::Utf8(_) => 1,
252            Self::Timedelta64(_) => 2,
253            Self::Datetime64(_) => 3,
254            Self::Bool(_) => 4,
255            Self::Object(_) => 5,
256            Self::Period(_) => 6,
257            Self::Interval(_) => 7,
258            Self::Null(_) => 8,
259        }
260    }
261}
262
263impl PartialEq for IndexLabel {
264    fn eq(&self, other: &Self) -> bool {
265        match (self, other) {
266            (Self::Int64(a), Self::Int64(b))
267            | (Self::Timedelta64(a), Self::Timedelta64(b))
268            | (Self::Datetime64(a), Self::Datetime64(b)) => a == b,
269            (Self::Int64(int), Self::Float64(float)) | (Self::Float64(float), Self::Int64(int)) => {
270                exact_i64(float.0) == Some(*int)
271            }
272            (Self::Float64(a), Self::Float64(b)) => a == b,
273            (Self::Utf8(a), Self::Utf8(b)) => a == b,
274            (Self::Bool(a), Self::Bool(b)) => a == b,
275            (Self::Object(a), Self::Object(b)) => a == b,
276            (Self::Period(a), Self::Period(b)) => a == b,
277            (Self::Interval(a), Self::Interval(b)) => a == b,
278            (Self::Null(a), Self::Null(b)) => a == b,
279            _ => false,
280        }
281    }
282}
283
284impl Eq for IndexLabel {}
285
286impl std::hash::Hash for IndexLabel {
287    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
288        // An integral float hashes as the int it equals.
289        let integral = match self {
290            Self::Int64(value) => Some(*value),
291            Self::Float64(value) => exact_i64(value.0),
292            _ => None,
293        };
294        if let Some(value) = integral {
295            0_u8.hash(state);
296            value.hash(state);
297            return;
298        }
299        std::mem::discriminant(self).hash(state);
300        match self {
301            Self::Int64(_) => {}
302            Self::Utf8(text) => text.hash(state),
303            Self::Timedelta64(value) | Self::Datetime64(value) => value.hash(state),
304            Self::Float64(value) => value.hash(state),
305            Self::Bool(flag) => flag.hash(state),
306            Self::Object(object) => object.hash(state),
307            Self::Period(period) => period.hash(state),
308            Self::Interval(interval) => interval.hash(state),
309            Self::Null(kind) => kind.hash(state),
310        }
311    }
312}
313
314impl Ord for IndexLabel {
315    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
316        match (self, other) {
317            (Self::Int64(a), Self::Int64(b))
318            | (Self::Timedelta64(a), Self::Timedelta64(b))
319            | (Self::Datetime64(a), Self::Datetime64(b)) => a.cmp(b),
320            (Self::Int64(int), Self::Float64(float)) => cmp_int_float(*int, float.0),
321            (Self::Float64(float), Self::Int64(int)) => cmp_int_float(*int, float.0).reverse(),
322            (Self::Float64(a), Self::Float64(b)) => a.cmp(b),
323            (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
324            (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
325            (Self::Object(a), Self::Object(b)) => a.cmp(b),
326            (Self::Period(a), Self::Period(b)) => a.cmp(b),
327            (Self::Interval(a), Self::Interval(b)) => a.cmp(b),
328            (Self::Null(a), Self::Null(b)) => a.cmp(b),
329            _ => self.kind_rank().cmp(&other.kind_rank()),
330        }
331    }
332}
333
334impl PartialOrd for IndexLabel {
335    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
336        Some(self.cmp(other))
337    }
338}
339
340impl From<i64> for IndexLabel {
341    fn from(value: i64) -> Self {
342        Self::Int64(value)
343    }
344}
345
346impl From<&str> for IndexLabel {
347    fn from(value: &str) -> Self {
348        Self::Utf8(value.to_owned())
349    }
350}
351
352impl From<String> for IndexLabel {
353    fn from(value: String) -> Self {
354        Self::Utf8(value)
355    }
356}
357
358impl IndexLabel {
359    #[must_use]
360    pub fn is_missing(&self) -> bool {
361        match self {
362            Self::Timedelta64(value) => *value == Timedelta::NAT,
363            Self::Datetime64(value) => *value == i64::MIN,
364            Self::Float64(v) => v.0.is_nan(),
365            Self::Period(period) => period.is_nat(),
366            Self::Int64(_)
367            | Self::Utf8(_)
368            | Self::Bool(_)
369            | Self::Object(_)
370            | Self::Interval(_) => false,
371            Self::Null(_) => true,
372        }
373    }
374}
375
376/// `std::thread::available_parallelism()`, resolved ONCE per process.
377///
378/// br-frankenpandas-q1evw. A local copy of `fp_columnar::cached_available_parallelism`
379/// rather than a shared call, because `fp-index` deliberately does not depend on
380/// `fp-columnar` and six lines are cheaper than a new edge in the crate graph. Keep
381/// the two in step.
382///
383/// WHY THIS IS CACHED AT ALL, measured on `fp-columnar` (br-frankenpandas-kko5z):
384/// `available_parallelism` honours cgroup CPU quota by WALKING THE CGROUP HIERARCHY
385/// ON THE FILESYSTEM — `/proc/self/cgroup` plus `cpu.max` at every level, 7 opens and
386/// ~10 reads per call, six levels deep for a tmux-spawned process. That cost 66-68us
387/// per elementwise call there.
388///
389/// `fp-index`'s two call sites were NOT the bug — both already sit inside an
390/// `n >= FLATIDX_PAR_MIN_ROWS` (50_000) gate, so a small call never reached the walk.
391/// That is the shape `fp-columnar` got wrong by calling it BEFORE its size check.
392/// Caching is still worth it at the boundary, where the walk was a real fraction of
393/// the parallel work it was sizing.
394///
395/// Caching means this will not notice an affinity or quota change made from outside a
396/// running process; that is the right trade for sizing a worker pool. One worker while
397/// a Python object cell is alive in the binding's process, as
398/// `fp_columnar::cached_available_parallelism` (a worker touching one would wait on the
399/// GIL its caller holds; 4qg5w.13).
400fn cached_available_parallelism() -> usize {
401    static AVAILABLE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
402    if fp_types::host_values_block_workers() {
403        return 1;
404    }
405    *AVAILABLE
406        .get_or_init(|| std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get))
407}
408
409/// numpy's `around`: scale by 10^decimals (or divide, for a negative
410/// `decimals`), round halves to even, scale back.
411fn round_half_even(x: f64, decimals: i32) -> f64 {
412    if decimals >= 0 {
413        let scale = 10_f64.powi(decimals);
414        (x * scale).round_ties_even() / scale
415    } else {
416        let scale = 10_f64.powi(-decimals);
417        (x / scale).round_ties_even() * scale
418    }
419}
420
421fn index_label_is_truthy(label: &IndexLabel) -> bool {
422    if label.is_missing() {
423        return false;
424    }
425    match label {
426        IndexLabel::Int64(v) => *v != 0,
427        IndexLabel::Float64(v) => v.0 != 0.0,
428        IndexLabel::Bool(b) => *b,
429        IndexLabel::Utf8(s) => !s.is_empty(),
430        IndexLabel::Timedelta64(v) => *v != 0,
431        IndexLabel::Datetime64(v) => *v != 0,
432        // Python truth: an empty list is false, any other object true.
433        IndexLabel::Object(object) => object.as_list().is_none_or(|items| !items.is_empty()),
434        // A Period object is true (its NaT was missing above), an Interval
435        // object too.
436        IndexLabel::Period(_) | IndexLabel::Interval(_) => true,
437        // Unreachable: is_missing() returned true above for every Null.
438        IndexLabel::Null(_) => false,
439    }
440}
441
442/// Hand-rolled decimal itoa straight into a byte buffer, bit-identical to
443/// `v.to_string()` (and therefore to `write!(buf, "{v}")`) for every `i64`.
444/// Mirrored from `fp-columnar`'s proven `push_i64_decimal`; `fp-index` depends
445/// only on `fp-types`, so it cannot reuse that one directly.
446#[inline]
447fn push_i64_decimal(buf: &mut Vec<u8>, v: i64) {
448    const LUT: &[u8; 200] = b"0001020304050607080910111213141516171819\
44920212223242526272829303132333435363738394041424344454647484950515253545556575859\
45060616263646566676869707172737475767778798081828384858687888990919293949596979899";
451    let mut n: u64 = if v < 0 {
452        buf.push(b'-');
453        v.unsigned_abs()
454    } else {
455        v as u64
456    };
457    let mut tmp = [0u8; 20];
458    let mut i = 20usize;
459    while n >= 100 {
460        let r = (n % 100) as usize * 2;
461        n /= 100;
462        i -= 2;
463        tmp[i] = LUT[r];
464        tmp[i + 1] = LUT[r + 1];
465    }
466    if n >= 10 {
467        let r = (n as usize) * 2;
468        i -= 2;
469        tmp[i] = LUT[r];
470        tmp[i + 1] = LUT[r + 1];
471    } else {
472        i -= 1;
473        tmp[i] = b'0' + n as u8;
474    }
475    buf.extend_from_slice(&tmp[i..]);
476}
477
478impl fmt::Display for IndexLabel {
479    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480        match self {
481            Self::Int64(v) => write!(f, "{v}"),
482            Self::Float64(v) => {
483                if v.0.is_nan() {
484                    return write!(f, "NaN");
485                }
486                let t = format!("{}", v.0);
487                if t.contains('.') || t.contains('e') || t.contains("inf") {
488                    write!(f, "{t}")
489                } else {
490                    write!(f, "{t}.0")
491                }
492            }
493            Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
494            Self::Utf8(v) => write!(f, "{v}"),
495            Self::Timedelta64(v) => write!(f, "{}", Timedelta::format(*v)),
496            Self::Datetime64(v) => write!(f, "{}", format_datetime_ns(*v)),
497            // pandas prints an object label as its cell (`2020-01-05`).
498            Self::Object(object) => f.write_str(&object.pprint()),
499            // A period as its calendar text (`2024-03`, `2024Q1`, NaT).
500            Self::Period(period) => write!(f, "{period}"),
501            // An interval as pandas prints it (`(0, 1]`).
502            Self::Interval(interval) => write!(f, "{interval}"),
503            // Matches pandas' REPR of missing labels in an index (None / NaN /
504            // NaT — note uppercase NaN: the formatter surface, unlike
505            // str(nan)=='nan' which astype(str) uses). Verified pandas 2.2.3.
506            Self::Null(fp_types::NullKind::Null) => write!(f, "None"),
507            Self::Null(fp_types::NullKind::NaN) => write!(f, "NaN"),
508            Self::Null(fp_types::NullKind::NaT) => write!(f, "NaT"),
509        }
510    }
511}
512
513/// The canonical name a typed column label keys its column under: its
514/// pandas text (`0`, `1.5`, `True`, `2024-01-01 00:00:00`), the string
515/// itself for a string label. The binding keys columns by it, so a label
516/// and its name always agree.
517#[must_use]
518pub fn column_key(label: &IndexLabel) -> String {
519    label.to_string()
520}
521
522/// A pandas name - a Series' name, an index's or a column axis' name: its
523/// text - what it is keyed and printed as - and, when it is not a string,
524/// the typed pandas label it stands for (`df[0]`'s name is the integer 0,
525/// `df.set_index(0).index.name` too; they were the strings '0'; fvsao.32,
526/// fvsao.64). It reads as the text (Deref, Display, Debug, serde,
527/// comparison with a string), and the label rides along wherever the name
528/// is cloned; a name rebuilt from text alone is a string.
529#[derive(Clone, Default)]
530pub struct LabelName {
531    text: String,
532    label: Option<IndexLabel>,
533}
534
535impl LabelName {
536    /// The name standing for `label`, keyed by its text (see
537    /// [`column_key`]); a string label is plain text.
538    #[must_use]
539    pub fn typed(label: IndexLabel) -> Self {
540        match label {
541            IndexLabel::Utf8(text) => Self { text, label: None },
542            label => Self {
543                text: column_key(&label),
544                label: Some(label),
545            },
546        }
547    }
548
549    /// The typed label this name stands for; the text as a string label for
550    /// a plain name.
551    #[must_use]
552    pub fn label(&self) -> IndexLabel {
553        self.label
554            .clone()
555            .filter(|label| column_key(label) == self.text)
556            .unwrap_or_else(|| IndexLabel::Utf8(self.text.clone()))
557    }
558}
559
560impl std::ops::Deref for LabelName {
561    type Target = String;
562
563    fn deref(&self) -> &String {
564        &self.text
565    }
566}
567
568impl AsRef<str> for LabelName {
569    fn as_ref(&self) -> &str {
570        &self.text
571    }
572}
573
574impl From<String> for LabelName {
575    fn from(text: String) -> Self {
576        Self { text, label: None }
577    }
578}
579
580impl From<&str> for LabelName {
581    fn from(text: &str) -> Self {
582        text.to_owned().into()
583    }
584}
585
586impl From<&String> for LabelName {
587    fn from(text: &String) -> Self {
588        text.clone().into()
589    }
590}
591
592impl From<&Self> for LabelName {
593    fn from(name: &Self) -> Self {
594        name.clone()
595    }
596}
597
598impl From<LabelName> for String {
599    fn from(name: LabelName) -> Self {
600        name.text
601    }
602}
603
604impl From<&LabelName> for String {
605    fn from(name: &LabelName) -> Self {
606        name.text.clone()
607    }
608}
609
610impl fmt::Display for LabelName {
611    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
612        fmt::Display::fmt(&self.text, formatter)
613    }
614}
615
616impl fmt::Debug for LabelName {
617    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
618        fmt::Debug::fmt(&self.text, formatter)
619    }
620}
621
622/// Names are equal when their labels are: 0 and '0' differ, as in pandas
623/// (whose `s + t` of those is unnamed).
624impl PartialEq for LabelName {
625    fn eq(&self, other: &Self) -> bool {
626        self.text == other.text && self.label == other.label
627    }
628}
629
630impl Eq for LabelName {}
631
632impl PartialEq<str> for LabelName {
633    fn eq(&self, other: &str) -> bool {
634        self.text == other
635    }
636}
637
638impl PartialEq<&str> for LabelName {
639    fn eq(&self, other: &&str) -> bool {
640        self.text == *other
641    }
642}
643
644impl PartialEq<String> for LabelName {
645    fn eq(&self, other: &String) -> bool {
646        &self.text == other
647    }
648}
649
650impl Serialize for LabelName {
651    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
652        self.text.serialize(serializer)
653    }
654}
655
656impl<'de> Deserialize<'de> for LabelName {
657    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
658        String::deserialize(deserializer).map(Self::from)
659    }
660}
661
662/// Hinnant `civil_from_days`: proleptic-Gregorian (year, month, day) for a day
663/// count since the 1970-01-01 epoch. Floor-correct for negative (pre-epoch)
664/// days. Identical algorithm to `fp-frame`'s `datetime64_civil_from_nanos`.
665#[inline]
666fn civil_from_epoch_days(days_since_epoch: i64) -> (i64, i64, i64) {
667    let days = days_since_epoch + 719_468;
668    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
669    let doe = days - era * 146_097;
670    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
671    let y = yoe + era * 400;
672    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
673    let mp = (5 * doy + 2) / 153;
674    let day = doy - (153 * mp + 2) / 5 + 1;
675    let month = if mp < 10 { mp + 3 } else { mp - 9 };
676    let year = if month <= 2 { y + 1 } else { y };
677    (year, month, day)
678}
679
680/// Append exactly two decimal digits of `n` (0..=99) — `{:02}`.
681#[inline]
682fn push_2d_str(buf: &mut String, n: i64) {
683    buf.push((b'0' + (n / 10 % 10) as u8) as char);
684    buf.push((b'0' + (n % 10) as u8) as char);
685}
686
687/// Append exactly four decimal digits of `n` (0..=9999) — `{:04}`.
688#[inline]
689fn push_4d_str(buf: &mut String, n: i64) {
690    buf.push((b'0' + (n / 1000 % 10) as u8) as char);
691    buf.push((b'0' + (n / 100 % 10) as u8) as char);
692    buf.push((b'0' + (n / 10 % 10) as u8) as char);
693    buf.push((b'0' + (n % 10) as u8) as char);
694}
695
696pub fn format_datetime_ns(nanos: i64) -> String {
697    if nanos == i64::MIN {
698        return "NaT".to_owned();
699    }
700    // Hand-rolled civil + ASCII (br-frankenpandas-dtns), bit-identical to the
701    // prior `chrono::from_timestamp_nanos(nanos).format("%Y-%m-%d %H:%M:%S")` +
702    // trailing-zero-trimmed subsecond fraction, but without the per-call chrono
703    // DateTime construction, the `DelayedFormat` strftime machinery, and the two
704    // `String`/`format!` allocations. `div_euclid`/`rem_euclid` reproduce
705    // chrono's floor semantics for pre-epoch instants (-0.5s renders as
706    // 1969-12-31 23:59:59.5). A datetime64[ns] year is always in [1677, 2262]
707    // (the i64-ns range) so `%Y` is exactly 4 digits, and the time fields are 2.
708    let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
709    let (y, m, d) = civil_from_epoch_days(days);
710    let secs_of_day = nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
711    let h = secs_of_day / 3600;
712    let mi = (secs_of_day % 3600) / 60;
713    let sec = secs_of_day % 60;
714    let subsec = nanos.rem_euclid(Timedelta::NANOS_PER_SEC); // 0..=999_999_999
715
716    let mut rendered = String::with_capacity(if subsec != 0 { 29 } else { 19 });
717    push_4d_str(&mut rendered, y);
718    rendered.push('-');
719    push_2d_str(&mut rendered, m);
720    rendered.push('-');
721    push_2d_str(&mut rendered, d);
722    rendered.push(' ');
723    push_2d_str(&mut rendered, h);
724    rendered.push(':');
725    push_2d_str(&mut rendered, mi);
726    rendered.push(':');
727    push_2d_str(&mut rendered, sec);
728    if subsec != 0 {
729        // Nine zero-padded fraction digits with trailing zeros trimmed, matching
730        // the prior `format!("{subsec:09}")` + pop-'0' loop exactly.
731        let mut frac = [0u8; 9];
732        let mut v = subsec;
733        for slot in frac.iter_mut().rev() {
734            *slot = b'0' + (v % 10) as u8;
735            v /= 10;
736        }
737        let mut end = 9usize;
738        while end > 0 && frac[end - 1] == b'0' {
739            end -= 1;
740        }
741        rendered.push('.');
742        // SAFETY-FREE: frac[..end] is all ASCII digits.
743        rendered.push_str(std::str::from_utf8(&frac[..end]).unwrap_or(""));
744    }
745    rendered
746}
747
748/// AG-13: Detected sort order of an index's labels.
749///
750/// Enables adaptive backend selection: binary search for sorted indexes,
751/// HashMap fallback for unsorted. Computed lazily via `OnceLock`.
752#[derive(Debug, Clone, Copy, PartialEq, Eq)]
753enum SortOrder {
754    /// Labels are not in any recognized sorted order.
755    Unsorted,
756    /// All labels are `Int64` and strictly ascending (no duplicates).
757    AscendingInt64,
758    /// All labels are `Utf8` and strictly ascending (no duplicates).
759    AscendingUtf8,
760    /// All labels are `Timedelta64` and strictly ascending (no duplicates).
761    AscendingTimedelta64,
762    /// All labels are `Datetime64` and strictly ascending (no duplicates).
763    AscendingDatetime64,
764}
765
766/// Which set operation a two-pointer sorted merge should emit
767/// (br-frankenpandas-idxdup). Both inputs are strictly ascending and unique.
768#[derive(Debug, Clone, Copy, PartialEq, Eq)]
769enum SetMergeKind {
770    /// Keep `self` labels that also appear in `other`.
771    Intersection,
772    /// Keep `self` labels that do NOT appear in `other`.
773    Difference,
774}
775
776/// Detect the sort order of the label slice.
777fn detect_sort_order(labels: &[IndexLabel]) -> SortOrder {
778    if labels.len() <= 1 {
779        return match labels.first() {
780            Some(IndexLabel::Int64(_)) | None => SortOrder::AscendingInt64,
781            Some(IndexLabel::Utf8(_)) => SortOrder::AscendingUtf8,
782            Some(IndexLabel::Timedelta64(_)) => SortOrder::AscendingTimedelta64,
783            Some(IndexLabel::Datetime64(_)) => SortOrder::AscendingDatetime64,
784            // Float64/Bool/Object/Period/Interval/Null labels use the general
785            // (non-typed) backend.
786            Some(
787                IndexLabel::Float64(_)
788                | IndexLabel::Bool(_)
789                | IndexLabel::Object(_)
790                | IndexLabel::Period(_)
791                | IndexLabel::Interval(_)
792                | IndexLabel::Null(_),
793            ) => SortOrder::Unsorted,
794        };
795    }
796
797    // Check if all Int64 and strictly ascending.
798    let all_int = labels.iter().all(|l| matches!(l, IndexLabel::Int64(_)));
799    if all_int {
800        let is_sorted = labels.windows(2).all(|w| {
801            if let (IndexLabel::Int64(a), IndexLabel::Int64(b)) = (&w[0], &w[1]) {
802                a < b
803            } else {
804                false
805            }
806        });
807        if is_sorted {
808            return SortOrder::AscendingInt64;
809        }
810    }
811
812    // Check if all Utf8 and strictly ascending.
813    let all_utf8 = labels.iter().all(|l| matches!(l, IndexLabel::Utf8(_)));
814    if all_utf8 {
815        let is_sorted = labels.windows(2).all(|w| {
816            if let (IndexLabel::Utf8(a), IndexLabel::Utf8(b)) = (&w[0], &w[1]) {
817                a < b
818            } else {
819                false
820            }
821        });
822        if is_sorted {
823            return SortOrder::AscendingUtf8;
824        }
825    }
826
827    // Check if all Timedelta64 and strictly ascending.
828    let all_td = labels
829        .iter()
830        .all(|l| matches!(l, IndexLabel::Timedelta64(_)));
831    if all_td {
832        let is_sorted = labels.windows(2).all(|w| {
833            if let (IndexLabel::Timedelta64(a), IndexLabel::Timedelta64(b)) = (&w[0], &w[1]) {
834                a < b
835            } else {
836                false
837            }
838        });
839        if is_sorted {
840            return SortOrder::AscendingTimedelta64;
841        }
842    }
843
844    // Check if all Datetime64 and strictly ascending.
845    let all_dt = labels
846        .iter()
847        .all(|l| matches!(l, IndexLabel::Datetime64(_)));
848    if all_dt {
849        let is_sorted = labels.windows(2).all(|w| {
850            if let (IndexLabel::Datetime64(a), IndexLabel::Datetime64(b)) = (&w[0], &w[1]) {
851                a < b
852            } else {
853                false
854            }
855        });
856        if is_sorted {
857            return SortOrder::AscendingDatetime64;
858        }
859    }
860
861    SortOrder::Unsorted
862}
863
864#[derive(Debug, Clone, Copy, PartialEq, Eq)]
865pub enum DuplicateKeep {
866    First,
867    Last,
868    None,
869}
870
871static INDEX_LABEL_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
872static INDEX_LABEL_EQUALITY_CACHE: OnceLock<Mutex<FxHashMap<(u64, u64), bool>>> = OnceLock::new();
873
874const INDEX_LABEL_EQUALITY_CACHE_MAX: usize = 4096;
875
876/// [`Index::label_kinds`] by the index's runtime label identity (labels never
877/// change under one), as `INDEX_LABEL_EQUALITY_CACHE` keeps equality.
878static INDEX_LABEL_KINDS_CACHE: OnceLock<Mutex<FxHashMap<u64, LabelKinds>>> = OnceLock::new();
879
880const INDEX_LABEL_KINDS_CACHE_MAX: usize = 4096;
881
882/// The kinds of label an index holds ([`Index::label_kinds`]): which
883/// [`IndexLabel`] variants occur, a missing one split into NaT and any other
884/// null (NaN, None). A set of kinds is itself a `LabelKinds` (`union`).
885#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
886pub struct LabelKinds(u16);
887
888impl LabelKinds {
889    pub const INT64: Self = Self(1);
890    pub const UTF8: Self = Self(1 << 1);
891    pub const TIMEDELTA64: Self = Self(1 << 2);
892    pub const DATETIME64: Self = Self(1 << 3);
893    pub const FLOAT64: Self = Self(1 << 4);
894    pub const BOOL: Self = Self(1 << 5);
895    pub const OBJECT: Self = Self(1 << 6);
896    pub const PERIOD: Self = Self(1 << 7);
897    pub const INTERVAL: Self = Self(1 << 8);
898    pub const NAT: Self = Self(1 << 9);
899    /// A missing label other than NaT: NaN or None.
900    pub const OTHER_NULL: Self = Self(1 << 10);
901
902    /// The kind of `label`.
903    #[must_use]
904    pub const fn of(label: &IndexLabel) -> Self {
905        match label {
906            IndexLabel::Int64(_) => Self::INT64,
907            IndexLabel::Utf8(_) => Self::UTF8,
908            IndexLabel::Timedelta64(_) => Self::TIMEDELTA64,
909            IndexLabel::Datetime64(_) => Self::DATETIME64,
910            IndexLabel::Float64(_) => Self::FLOAT64,
911            IndexLabel::Bool(_) => Self::BOOL,
912            IndexLabel::Object(_) => Self::OBJECT,
913            IndexLabel::Period(_) => Self::PERIOD,
914            IndexLabel::Interval(_) => Self::INTERVAL,
915            IndexLabel::Null(fp_types::NullKind::NaT) => Self::NAT,
916            IndexLabel::Null(_) => Self::OTHER_NULL,
917        }
918    }
919
920    /// Both sets of kinds.
921    #[must_use]
922    pub const fn union(self, other: Self) -> Self {
923        Self(self.0 | other.0)
924    }
925
926    /// Whether a label of a kind in `kinds` occurs.
927    #[must_use]
928    pub const fn intersects(self, kinds: Self) -> bool {
929        self.0 & kinds.0 != 0
930    }
931
932    /// Whether every label is of a kind in `kinds` (true of no label).
933    #[must_use]
934    pub const fn within(self, kinds: Self) -> bool {
935        self.0 & !kinds.0 == 0
936    }
937}
938
939type Int64PositionLookup = FxHashMap<i64, usize>;
940type Utf8PositionLookup = FxHashMap<Box<str>, usize>;
941type SharedInt64PositionLookup = Arc<Int64PositionLookup>;
942type SharedUtf8PositionLookup = Arc<Utf8PositionLookup>;
943type Int64PositionLookupCache = FxHashMap<u64, SharedInt64PositionLookup>;
944type Utf8PositionLookupCache = FxHashMap<u64, Option<SharedUtf8PositionLookup>>;
945type Datetime64PositionLookupCache = FxHashMap<u64, Option<SharedInt64PositionLookup>>;
946type Timedelta64PositionLookupCache = FxHashMap<u64, Option<SharedInt64PositionLookup>>;
947
948/// First-occurrence `i64 -> position` lookup tables for unsorted unique Int64
949/// indexes, cached by the index's runtime label identity (mirrors
950/// `INDEX_LABEL_EQUALITY_CACHE`). Lets repeated `loc[[labels]]` resolve each
951/// requested label in O(1) without rebuilding the per-call pointer-key
952/// `FxHashMap<&IndexLabel, Vec<usize>>` over the whole index every time.
953static INDEX_INT64_POS_LOOKUP_CACHE: OnceLock<Mutex<Int64PositionLookupCache>> = OnceLock::new();
954
955/// Each entry can hold a whole-index hashtable (O(n) memory), so bound the
956/// entry count far more tightly than the boolean equality cache. The common
957/// case is a handful of distinct loc'd frames; the cap only trips under
958/// pathological churn, where a full clear (rebuild on next miss) is cheaper
959/// than unbounded retention.
960const INDEX_INT64_POS_LOOKUP_CACHE_MAX: usize = 64;
961
962fn next_index_label_identity() -> u64 {
963    INDEX_LABEL_ID_COUNTER.fetch_add(1, AtomicOrdering::Relaxed)
964}
965
966/// Build-or-fetch the cached first-occurrence `i64 -> position` table for an
967/// index lineage. `values` must be the index's raw `i64` view. Duplicate labels
968/// retain their first position, matching pandas `get_loc` scalar lookup
969/// semantics.
970fn int64_position_lookup_cached(identity: u64, values: &[i64]) -> SharedInt64PositionLookup {
971    let cache = INDEX_INT64_POS_LOOKUP_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
972    if let Some(existing) = cache
973        .lock()
974        .expect("index int64 position lookup cache poisoned")
975        .get(&identity)
976        .cloned()
977    {
978        return existing;
979    }
980    let mut map: Int64PositionLookup = FxHashMap::default();
981    map.reserve(values.len());
982    for (pos, &value) in values.iter().enumerate() {
983        map.entry(value).or_insert(pos);
984    }
985    let arc = Arc::new(map);
986    let mut guard = cache
987        .lock()
988        .expect("index int64 position lookup cache poisoned");
989    if guard.len() >= INDEX_INT64_POS_LOOKUP_CACHE_MAX {
990        guard.clear();
991    }
992    Arc::clone(guard.entry(identity).or_insert(arc))
993}
994
995/// First-occurrence `String -> position` lookup tables for unique all-Utf8
996/// indexes, cached by runtime label identity. The value is `Option`: `None`
997/// records "this index is not all-Utf8" so the warm path stays O(1) instead of
998/// rescanning a non-Utf8 index on every `loc` call.
999static INDEX_UTF8_POS_LOOKUP_CACHE: OnceLock<Mutex<Utf8PositionLookupCache>> = OnceLock::new();
1000
1001/// Each entry can hold a whole index's worth of boxed strings, so cap the entry
1002/// count tightly (utf8 entries are heavier than the i64 ones).
1003const INDEX_UTF8_POS_LOOKUP_CACHE_MAX: usize = 16;
1004
1005/// Build-or-fetch the cached first-occurrence `String -> position` table for an
1006/// index lineage. Returns `None` (and caches that verdict) when the index is
1007/// not entirely Utf8. The caller has already proven the index is unique, so
1008/// first occurrence == only occurrence.
1009fn utf8_position_lookup_cached(
1010    identity: u64,
1011    index_labels: &[IndexLabel],
1012) -> Option<SharedUtf8PositionLookup> {
1013    let cache = INDEX_UTF8_POS_LOOKUP_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
1014    if let Some(existing) = cache
1015        .lock()
1016        .expect("index utf8 position lookup cache poisoned")
1017        .get(&identity)
1018        .cloned()
1019    {
1020        return existing;
1021    }
1022    let mut map: Utf8PositionLookup = FxHashMap::default();
1023    map.reserve(index_labels.len());
1024    let mut all_utf8 = true;
1025    for (pos, label) in index_labels.iter().enumerate() {
1026        match label {
1027            IndexLabel::Utf8(value) => {
1028                map.insert(value.as_str().into(), pos);
1029            }
1030            _ => {
1031                all_utf8 = false;
1032                break;
1033            }
1034        }
1035    }
1036    let result = if all_utf8 { Some(Arc::new(map)) } else { None };
1037    let mut guard = cache
1038        .lock()
1039        .expect("index utf8 position lookup cache poisoned");
1040    if guard.len() >= INDEX_UTF8_POS_LOOKUP_CACHE_MAX {
1041        guard.clear();
1042    }
1043    guard.entry(identity).or_insert(result).clone()
1044}
1045
1046/// First-occurrence `Datetime64-ns -> position` lookup tables for unique
1047/// all-Datetime64 indexes (the common pandas time-series index), cached by
1048/// runtime label identity. `Datetime64(i64)` is ns-backed, so this mirrors the
1049/// Int64 lookup but reads the `Datetime64` label variant. The value is
1050/// `Option`: `None` records "not all Datetime64" so the warm path stays O(1).
1051static INDEX_DATETIME_POS_LOOKUP_CACHE: OnceLock<Mutex<Datetime64PositionLookupCache>> =
1052    OnceLock::new();
1053
1054const INDEX_DATETIME_POS_LOOKUP_CACHE_MAX: usize = 64;
1055
1056/// Build-or-fetch the cached first-occurrence ns->position table for a
1057/// Datetime64 index lineage. Returns `None` (and caches that verdict) when the
1058/// index is not entirely Datetime64. Caller has proven uniqueness, so first ==
1059/// only occurrence.
1060fn datetime64_position_lookup_cached(
1061    identity: u64,
1062    index_labels: &[IndexLabel],
1063) -> Option<SharedInt64PositionLookup> {
1064    let cache = INDEX_DATETIME_POS_LOOKUP_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
1065    if let Some(existing) = cache
1066        .lock()
1067        .expect("index datetime position lookup cache poisoned")
1068        .get(&identity)
1069        .cloned()
1070    {
1071        return existing;
1072    }
1073    let mut map: Int64PositionLookup = FxHashMap::default();
1074    map.reserve(index_labels.len());
1075    let mut all_datetime = true;
1076    for (pos, label) in index_labels.iter().enumerate() {
1077        match label {
1078            IndexLabel::Datetime64(ns) => {
1079                map.insert(*ns, pos);
1080            }
1081            _ => {
1082                all_datetime = false;
1083                break;
1084            }
1085        }
1086    }
1087    let result = if all_datetime {
1088        Some(Arc::new(map))
1089    } else {
1090        None
1091    };
1092    let mut guard = cache
1093        .lock()
1094        .expect("index datetime position lookup cache poisoned");
1095    if guard.len() >= INDEX_DATETIME_POS_LOOKUP_CACHE_MAX {
1096        guard.clear();
1097    }
1098    guard.entry(identity).or_insert(result).clone()
1099}
1100
1101/// Per-lineage first-occurrence ns->position table for a Timedelta64 index.
1102/// Exact sibling of `INDEX_DATETIME_POS_LOOKUP_CACHE`: `Timedelta64(i64)` is
1103/// also ns-backed, so the same i64->pos table serves `loc[[td]]` on a
1104/// TimedeltaIndex (the deferred mirror of the Datetime64 batch resolver).
1105static INDEX_TIMEDELTA_POS_LOOKUP_CACHE: OnceLock<Mutex<Timedelta64PositionLookupCache>> =
1106    OnceLock::new();
1107
1108const INDEX_TIMEDELTA_POS_LOOKUP_CACHE_MAX: usize = 64;
1109
1110/// Build-or-fetch the cached first-occurrence ns->position table for a
1111/// Timedelta64 index lineage. Returns `None` (and caches that verdict) when the
1112/// index is not entirely Timedelta64. Caller has proven uniqueness, so first ==
1113/// only occurrence.
1114fn timedelta64_position_lookup_cached(
1115    identity: u64,
1116    index_labels: &[IndexLabel],
1117) -> Option<SharedInt64PositionLookup> {
1118    let cache = INDEX_TIMEDELTA_POS_LOOKUP_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
1119    if let Some(existing) = cache
1120        .lock()
1121        .expect("index timedelta position lookup cache poisoned")
1122        .get(&identity)
1123        .cloned()
1124    {
1125        return existing;
1126    }
1127    let mut map: Int64PositionLookup = FxHashMap::default();
1128    map.reserve(index_labels.len());
1129    let mut all_timedelta = true;
1130    for (pos, label) in index_labels.iter().enumerate() {
1131        match label {
1132            IndexLabel::Timedelta64(ns) => {
1133                map.insert(*ns, pos);
1134            }
1135            _ => {
1136                all_timedelta = false;
1137                break;
1138            }
1139        }
1140    }
1141    let result = if all_timedelta {
1142        Some(Arc::new(map))
1143    } else {
1144        None
1145    };
1146    let mut guard = cache
1147        .lock()
1148        .expect("index timedelta position lookup cache poisoned");
1149    if guard.len() >= INDEX_TIMEDELTA_POS_LOOKUP_CACHE_MAX {
1150        guard.clear();
1151    }
1152    guard.entry(identity).or_insert(result).clone()
1153}
1154
1155/// Shared contiguous-Utf8 label backing: a byte buffer + `n+1` offsets, row `i`
1156/// being `bytes[offsets[i]..offsets[i+1]]` (br-frankenpandas-nbspq).
1157type Utf8LabelBacking = (Arc<[u8]>, Arc<[usize]>);
1158
1159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1160struct Int64UnitRangeLabels {
1161    start: i64,
1162    len: usize,
1163}
1164
1165impl Int64UnitRangeLabels {
1166    fn new(start: i64, len: usize) -> Option<Self> {
1167        if len > 0 {
1168            let last_offset = i64::try_from(len.checked_sub(1)?).ok()?;
1169            start.checked_add(last_offset)?;
1170        }
1171        Some(Self { start, len })
1172    }
1173
1174    fn materialize(self) -> Vec<IndexLabel> {
1175        let mut labels = Vec::with_capacity(self.len);
1176        for offset in 0..self.len {
1177            let offset = i64::try_from(offset).expect("validated Int64 unit range length");
1178            labels.push(IndexLabel::Int64(
1179                self.start
1180                    .checked_add(offset)
1181                    .expect("validated Int64 unit range end"),
1182            ));
1183        }
1184        labels
1185    }
1186}
1187
1188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1189struct Int64AffineLabels {
1190    start: i64,
1191    step: i64,
1192    len: usize,
1193}
1194
1195impl Int64AffineLabels {
1196    fn new(start: i64, step: i64, len: usize) -> Option<Self> {
1197        if len > 1 && step == 0 {
1198            return None;
1199        }
1200        if len > 0 {
1201            let last_index = i64::try_from(len.checked_sub(1)?).ok()?;
1202            let span = step.checked_mul(last_index)?;
1203            start.checked_add(span)?;
1204        }
1205        Some(Self { start, step, len })
1206    }
1207
1208    fn materialize(self) -> Vec<IndexLabel> {
1209        let mut labels = Vec::with_capacity(self.len);
1210        let mut value = self.start;
1211        for offset in 0..self.len {
1212            labels.push(IndexLabel::Int64(value));
1213            if offset + 1 < self.len {
1214                value = value
1215                    .checked_add(self.step)
1216                    .expect("validated Int64 affine range end");
1217            }
1218        }
1219        labels
1220    }
1221
1222    fn materialize_datetime64(self) -> Vec<IndexLabel> {
1223        let mut labels = Vec::with_capacity(self.len);
1224        let mut value = self.start;
1225        for offset in 0..self.len {
1226            labels.push(IndexLabel::Datetime64(value));
1227            if offset + 1 < self.len {
1228                value = value
1229                    .checked_add(self.step)
1230                    .expect("validated Datetime64 affine range end");
1231            }
1232        }
1233        labels
1234    }
1235
1236    fn materialize_i64(self) -> Vec<i64> {
1237        let mut labels = Vec::with_capacity(self.len);
1238        let mut value = self.start;
1239        for offset in 0..self.len {
1240            labels.push(value);
1241            if offset + 1 < self.len {
1242                value = value
1243                    .checked_add(self.step)
1244                    .expect("validated Int64 affine range end");
1245            }
1246        }
1247        labels
1248    }
1249
1250    fn value_at(self, position: usize) -> i64 {
1251        let offset = i64::try_from(position).expect("validated Int64 affine range length");
1252        let delta = self
1253            .step
1254            .checked_mul(offset)
1255            .expect("validated Int64 affine range end");
1256        self.start
1257            .checked_add(delta)
1258            .expect("validated Int64 affine range end")
1259    }
1260
1261    fn position(self, target: i64) -> Option<usize> {
1262        if self.len == 0 {
1263            return None;
1264        }
1265        if self.step == 0 {
1266            return (self.len == 1 && target == self.start).then_some(0);
1267        }
1268        let offset = target.checked_sub(self.start)?;
1269        if offset.checked_rem(self.step)? != 0 {
1270            return None;
1271        }
1272        let pos = offset.checked_div(self.step)?;
1273        let pos = usize::try_from(pos).ok()?;
1274        (pos < self.len).then_some(pos)
1275    }
1276
1277    fn equals_slice(self, labels: &[IndexLabel]) -> bool {
1278        labels.len() == self.len
1279            && labels.iter().enumerate().all(|(offset, label)| {
1280                let Ok(offset) = i64::try_from(offset) else {
1281                    return false;
1282                };
1283                let Some(delta) = self.step.checked_mul(offset) else {
1284                    return false;
1285                };
1286                matches!(
1287                    label,
1288                    IndexLabel::Int64(value)
1289                        if self.start.checked_add(delta).is_some_and(|expected| *value == expected)
1290                )
1291            })
1292    }
1293}
1294
1295#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1296struct Int64TwoAffineLabels {
1297    first: Int64AffineLabels,
1298    second: Int64AffineLabels,
1299}
1300
1301impl Int64TwoAffineLabels {
1302    fn new(first: Int64AffineLabels, second: Int64AffineLabels) -> Option<Self> {
1303        first.len.checked_add(second.len)?;
1304        Some(Self { first, second })
1305    }
1306
1307    fn len(self) -> usize {
1308        self.first
1309            .len
1310            .checked_add(self.second.len)
1311            .expect("validated two-run Int64 index length")
1312    }
1313
1314    fn value_at(self, position: usize) -> i64 {
1315        if position < self.first.len {
1316            self.first.value_at(position)
1317        } else {
1318            self.second.value_at(position - self.first.len)
1319        }
1320    }
1321
1322    fn materialize(self) -> Vec<IndexLabel> {
1323        let mut labels = Vec::with_capacity(self.len());
1324        labels.extend(self.first.materialize());
1325        labels.extend(self.second.materialize());
1326        labels
1327    }
1328
1329    fn materialize_i64(self) -> Vec<i64> {
1330        let mut labels = Vec::with_capacity(self.len());
1331        labels.extend(self.first.materialize_i64());
1332        labels.extend(self.second.materialize_i64());
1333        labels
1334    }
1335}
1336
1337#[derive(Debug, Clone)]
1338struct Int64StridedLabels {
1339    values: Arc<Vec<i64>>,
1340    start: usize,
1341    step: usize,
1342    len: usize,
1343}
1344
1345impl Int64StridedLabels {
1346    fn new(values: Arc<Vec<i64>>, start: usize, step: usize, len: usize) -> Option<Self> {
1347        if len > 1 && step == 0 {
1348            return None;
1349        }
1350        if len > 0 {
1351            let last = start.checked_add(step.checked_mul(len.checked_sub(1)?)?)?;
1352            if last >= values.len() {
1353                return None;
1354            }
1355        }
1356        Some(Self {
1357            values,
1358            start,
1359            step,
1360            len,
1361        })
1362    }
1363
1364    fn materialize(self) -> Vec<IndexLabel> {
1365        let mut labels = Vec::with_capacity(self.len);
1366        let mut pos = self.start;
1367        for offset in 0..self.len {
1368            labels.push(IndexLabel::Int64(self.values[pos]));
1369            if offset + 1 < self.len {
1370                pos = pos
1371                    .checked_add(self.step)
1372                    .expect("validated Int64 strided range end");
1373            }
1374        }
1375        labels
1376    }
1377
1378    fn materialize_i64(self) -> Vec<i64> {
1379        let mut labels = Vec::with_capacity(self.len);
1380        let mut pos = self.start;
1381        for offset in 0..self.len {
1382            labels.push(self.values[pos]);
1383            if offset + 1 < self.len {
1384                pos = pos
1385                    .checked_add(self.step)
1386                    .expect("validated Int64 strided range end");
1387            }
1388        }
1389        labels
1390    }
1391}
1392
1393#[derive(Debug, Clone)]
1394struct MaterializedLabelSlice {
1395    labels: Arc<Vec<IndexLabel>>,
1396    start: usize,
1397    len: usize,
1398}
1399
1400impl MaterializedLabelSlice {
1401    fn new(labels: Arc<Vec<IndexLabel>>, start: usize, len: usize) -> Option<Self> {
1402        start.checked_add(len).filter(|end| *end <= labels.len())?;
1403        Some(Self { labels, start, len })
1404    }
1405
1406    fn as_slice(&self) -> &[IndexLabel] {
1407        &self.labels[self.start..self.start + self.len]
1408    }
1409}
1410
1411struct IndexLabels {
1412    /// Shared immutable label vector (br-frankenpandas-idxclone). Behind `Arc`
1413    /// so cloning an `Index` is an O(1) refcount bump instead of an O(n)
1414    /// `Vec<IndexLabel>` deep copy — the dominant cost of same-index binary ops
1415    /// (`a + b` re-uses the operand index). Set once, never mutated, so sharing
1416    /// is observationally identical to a private copy. The cell itself is
1417    /// shared by clones too: a lazy backing's labels made by any clone (a
1418    /// Series of a date_range resampled, sliced by label) serve them all,
1419    /// where each clone made its own million again (br-frankenpandas-so0mr).
1420    materialized: Arc<OnceLock<Arc<Vec<IndexLabel>>>>,
1421    materialized_slice: Option<Arc<MaterializedLabelSlice>>,
1422    int64_unit_range: Option<Int64UnitRangeLabels>,
1423    int64_affine: Option<Int64AffineLabels>,
1424    int64_two_affine: Option<Box<Int64TwoAffineLabels>>,
1425    int64_strided: Option<Int64StridedLabels>,
1426    datetime64_affine: Option<Int64AffineLabels>,
1427    /// Lazy typed Int64 backing (br-frankenpandas-dxqpm). `Some(values)` once
1428    /// computed means every label is `IndexLabel::Int64` and `values` is the
1429    /// raw `i64` view; `None` once computed means the labels are not all
1430    /// Int64. Pre-seeded by typed constructors so gathers/clones/drops of
1431    /// Int64-labelled indexes stay on contiguous `i64` storage instead of the
1432    /// 32 B enum representation.
1433    int64_typed: OnceLock<Option<Arc<Vec<i64>>>>,
1434    /// Lazy contiguous-Utf8 backing (br-frankenpandas-nbspq): `Some((bytes,
1435    /// offsets))` means every label is `IndexLabel::Utf8(bytes[off[i]..off[i+1]])`
1436    /// (valid UTF-8 by construction). Pre-seeded by `new_utf8_contiguous` so a
1437    /// string-keyed result index (groupby keys, sort_values, set-ops) avoids the
1438    /// per-label `String` alloc + `from_utf8` re-validation until something
1439    /// actually needs the `Vec<IndexLabel>` view.
1440    utf8_contiguous: Option<Utf8LabelBacking>,
1441}
1442
1443impl IndexLabels {
1444    fn new(labels: Vec<IndexLabel>) -> Self {
1445        let materialized = OnceLock::new();
1446        let _ = materialized.set(Arc::new(labels));
1447        Self {
1448            materialized: Arc::new(materialized),
1449            materialized_slice: None,
1450            int64_unit_range: None,
1451            int64_affine: None,
1452            int64_two_affine: None,
1453            int64_strided: None,
1454            datetime64_affine: None,
1455            int64_typed: OnceLock::new(),
1456            utf8_contiguous: None,
1457        }
1458    }
1459
1460    fn new_int64_unit_range(start: i64, len: usize) -> Option<Self> {
1461        Some(Self {
1462            materialized: Arc::default(),
1463            materialized_slice: None,
1464            int64_unit_range: Some(Int64UnitRangeLabels::new(start, len)?),
1465            int64_affine: None,
1466            int64_two_affine: None,
1467            int64_strided: None,
1468            datetime64_affine: None,
1469            int64_typed: OnceLock::new(),
1470            utf8_contiguous: None,
1471        })
1472    }
1473
1474    fn new_int64_affine(start: i64, step: i64, len: usize) -> Option<Self> {
1475        if step == 1 {
1476            return Self::new_int64_unit_range(start, len);
1477        }
1478        Some(Self {
1479            materialized: Arc::default(),
1480            materialized_slice: None,
1481            int64_unit_range: None,
1482            int64_affine: Some(Int64AffineLabels::new(start, step, len)?),
1483            int64_two_affine: None,
1484            int64_strided: None,
1485            datetime64_affine: None,
1486            int64_typed: OnceLock::new(),
1487            utf8_contiguous: None,
1488        })
1489    }
1490
1491    fn new_int64_two_affine(first: Int64AffineLabels, second: Int64AffineLabels) -> Option<Self> {
1492        Some(Self {
1493            materialized: Arc::default(),
1494            materialized_slice: None,
1495            int64_unit_range: None,
1496            int64_affine: None,
1497            int64_two_affine: Some(Box::new(Int64TwoAffineLabels::new(first, second)?)),
1498            int64_strided: None,
1499            datetime64_affine: None,
1500            int64_typed: OnceLock::new(),
1501            utf8_contiguous: None,
1502        })
1503    }
1504
1505    fn new_int64_strided(
1506        values: Arc<Vec<i64>>,
1507        start: usize,
1508        step: usize,
1509        len: usize,
1510    ) -> Option<Self> {
1511        Some(Self {
1512            materialized: Arc::default(),
1513            materialized_slice: None,
1514            int64_unit_range: None,
1515            int64_affine: None,
1516            int64_two_affine: None,
1517            int64_strided: Some(Int64StridedLabels::new(values, start, step, len)?),
1518            datetime64_affine: None,
1519            int64_typed: OnceLock::new(),
1520            utf8_contiguous: None,
1521        })
1522    }
1523
1524    fn new_int64_values(values: Arc<Vec<i64>>) -> Self {
1525        let int64_typed = OnceLock::new();
1526        let _ = int64_typed.set(Some(values));
1527        Self {
1528            materialized: Arc::default(),
1529            materialized_slice: None,
1530            int64_unit_range: None,
1531            int64_affine: None,
1532            int64_two_affine: None,
1533            int64_strided: None,
1534            datetime64_affine: None,
1535            int64_typed,
1536            utf8_contiguous: None,
1537        }
1538    }
1539
1540    fn new_datetime64_affine(start: i64, step: i64, len: usize) -> Option<Self> {
1541        Some(Self {
1542            materialized: Arc::default(),
1543            materialized_slice: None,
1544            int64_unit_range: None,
1545            int64_affine: None,
1546            int64_two_affine: None,
1547            int64_strided: None,
1548            datetime64_affine: Some(Int64AffineLabels::new(start, step, len)?),
1549            int64_typed: OnceLock::new(),
1550            utf8_contiguous: None,
1551        })
1552    }
1553
1554    fn new_utf8_contiguous(bytes: Arc<[u8]>, offsets: Arc<[usize]>) -> Self {
1555        debug_assert!(!offsets.is_empty());
1556        debug_assert_eq!(*offsets.last().expect("non-empty"), bytes.len());
1557        Self {
1558            materialized: Arc::default(),
1559            materialized_slice: None,
1560            int64_unit_range: None,
1561            int64_affine: None,
1562            int64_two_affine: None,
1563            int64_strided: None,
1564            datetime64_affine: None,
1565            int64_typed: OnceLock::new(),
1566            utf8_contiguous: Some((bytes, offsets)),
1567        }
1568    }
1569
1570    fn as_slice(&self) -> &[IndexLabel] {
1571        if let Some(slice) = &self.materialized_slice {
1572            return slice.as_slice();
1573        }
1574        self.materialized
1575            .get_or_init(|| {
1576                if let Some(range) = self.int64_unit_range {
1577                    return Arc::new(range.materialize());
1578                }
1579                if let Some(range) = self.int64_affine {
1580                    return Arc::new(range.materialize());
1581                }
1582                if let Some(runs) = &self.int64_two_affine {
1583                    let runs = **runs;
1584                    return Arc::new(runs.materialize());
1585                }
1586                if let Some((bytes, offsets)) = &self.utf8_contiguous {
1587                    return Arc::new(
1588                        offsets
1589                            .windows(2)
1590                            .map(|w| {
1591                                IndexLabel::Utf8(
1592                                    std::str::from_utf8(&bytes[w[0]..w[1]])
1593                                        .expect("contiguous utf8 index buffer is valid")
1594                                        .to_owned(),
1595                                )
1596                            })
1597                            .collect(),
1598                    );
1599                }
1600                if let Some(range) = self.datetime64_affine {
1601                    return Arc::new(range.materialize_datetime64());
1602                }
1603                if let Some(strided) = self.int64_strided.clone() {
1604                    return Arc::new(strided.materialize());
1605                }
1606                let values = self
1607                    .int64_typed
1608                    .get()
1609                    .and_then(Option::as_ref)
1610                    .expect("lazy index labels require a typed or range backing");
1611                Arc::new(values.iter().copied().map(IndexLabel::Int64).collect())
1612            })
1613            .as_slice()
1614    }
1615
1616    fn to_owned_labels(&self) -> Vec<IndexLabel> {
1617        if let Some(slice) = &self.materialized_slice {
1618            return slice.as_slice().to_vec();
1619        }
1620        if let Some(range) = self.int64_unit_range {
1621            return range.materialize();
1622        }
1623        if let Some(range) = self.int64_affine {
1624            return range.materialize();
1625        }
1626        if let Some(runs) = &self.int64_two_affine {
1627            return runs.materialize();
1628        }
1629        if let Some(strided) = self.int64_strided.clone() {
1630            return strided.materialize();
1631        }
1632        if let Some(range) = self.datetime64_affine {
1633            return range.materialize_datetime64();
1634        }
1635        if let Some((bytes, offsets)) = &self.utf8_contiguous {
1636            return offsets
1637                .windows(2)
1638                .map(|w| {
1639                    IndexLabel::Utf8(
1640                        std::str::from_utf8(&bytes[w[0]..w[1]])
1641                            .expect("contiguous utf8 index buffer is valid")
1642                            .to_owned(),
1643                    )
1644                })
1645                .collect();
1646        }
1647        if let Some(Some(values)) = self.int64_typed.get() {
1648            return values.iter().copied().map(IndexLabel::Int64).collect();
1649        }
1650        self.as_slice().to_vec()
1651    }
1652
1653    fn len(&self) -> usize {
1654        if let Some(slice) = &self.materialized_slice {
1655            return slice.len;
1656        }
1657        if let Some(range) = self.int64_unit_range {
1658            return range.len;
1659        }
1660        if let Some(range) = self.int64_affine {
1661            return range.len;
1662        }
1663        if let Some(runs) = &self.int64_two_affine {
1664            let runs = **runs;
1665            return runs.len();
1666        }
1667        if let Some(strided) = &self.int64_strided {
1668            return strided.len;
1669        }
1670        if let Some(range) = self.datetime64_affine {
1671            return range.len;
1672        }
1673        if let Some((_, offsets)) = &self.utf8_contiguous {
1674            return offsets.len() - 1;
1675        }
1676        if let Some(labels) = self.materialized.get() {
1677            return labels.len();
1678        }
1679        if let Some(Some(values)) = self.int64_typed.get() {
1680            return values.len();
1681        }
1682        self.as_slice().len()
1683    }
1684
1685    fn slice(&self, start: usize, len: usize) -> Self {
1686        let total_len = self.len();
1687        let start = start.min(total_len);
1688        let end = start.saturating_add(len).min(total_len);
1689        let len = end - start;
1690
1691        if let Some(range) = self.int64_unit_range {
1692            let offset = i64::try_from(start).expect("start within index length");
1693            if let Some(next_start) = range.start.checked_add(offset)
1694                && let Some(labels) = Self::new_int64_unit_range(next_start, len)
1695            {
1696                return labels;
1697            }
1698        }
1699
1700        if let Some(range) = self.int64_affine {
1701            let offset = i64::try_from(start).expect("start within index length");
1702            if let Some(delta) = range.step.checked_mul(offset)
1703                && let Some(next_start) = range.start.checked_add(delta)
1704                && let Some(labels) = Self::new_int64_affine(next_start, range.step, len)
1705            {
1706                return labels;
1707            }
1708        }
1709
1710        if let Some(runs) = &self.int64_two_affine {
1711            let runs = **runs;
1712            if len == 0 {
1713                if let Some(labels) = Self::new_int64_affine(runs.first.start, runs.first.step, 0) {
1714                    return labels;
1715                }
1716            } else if start + len <= runs.first.len {
1717                let offset = i64::try_from(start).expect("start within index length");
1718                if let Some(delta) = runs.first.step.checked_mul(offset)
1719                    && let Some(next_start) = runs.first.start.checked_add(delta)
1720                    && let Some(labels) = Self::new_int64_affine(next_start, runs.first.step, len)
1721                {
1722                    return labels;
1723                }
1724            } else if start >= runs.first.len {
1725                let second_start = start - runs.first.len;
1726                let offset = i64::try_from(second_start).expect("start within index length");
1727                if let Some(delta) = runs.second.step.checked_mul(offset)
1728                    && let Some(next_start) = runs.second.start.checked_add(delta)
1729                    && let Some(labels) = Self::new_int64_affine(next_start, runs.second.step, len)
1730                {
1731                    return labels;
1732                }
1733            }
1734        }
1735
1736        if let Some(strided) = &self.int64_strided
1737            && let Some(offset) = strided.step.checked_mul(start)
1738            && let Some(next_start) = strided.start.checked_add(offset)
1739            && let Some(labels) =
1740                Self::new_int64_strided(Arc::clone(&strided.values), next_start, strided.step, len)
1741        {
1742            return labels;
1743        }
1744
1745        if let Some(Some(values)) = self.int64_typed.get()
1746            && let Some(labels) = Self::new_int64_strided(Arc::clone(values), start, 1, len)
1747        {
1748            return labels;
1749        }
1750
1751        if let Some(range) = self.datetime64_affine {
1752            let offset = i64::try_from(start).expect("start within index length");
1753            if let Some(delta) = range.step.checked_mul(offset)
1754                && let Some(next_start) = range.start.checked_add(delta)
1755                && let Some(labels) = Self::new_datetime64_affine(next_start, range.step, len)
1756            {
1757                return labels;
1758            }
1759        }
1760
1761        if let Some(slice) = &self.materialized_slice
1762            && let Some(next_start) = slice.start.checked_add(start)
1763            && let Some(view) =
1764                MaterializedLabelSlice::new(Arc::clone(&slice.labels), next_start, len)
1765        {
1766            return Self {
1767                materialized: Arc::default(),
1768                materialized_slice: Some(Arc::new(view)),
1769                int64_unit_range: None,
1770                int64_affine: None,
1771                int64_two_affine: None,
1772                int64_strided: None,
1773                datetime64_affine: None,
1774                int64_typed: OnceLock::new(),
1775                utf8_contiguous: None,
1776            };
1777        }
1778
1779        if let Some(labels) = self.materialized.get()
1780            && let Some(view) = MaterializedLabelSlice::new(Arc::clone(labels), start, len)
1781        {
1782            return Self {
1783                materialized: Arc::default(),
1784                materialized_slice: Some(Arc::new(view)),
1785                int64_unit_range: None,
1786                int64_affine: None,
1787                int64_two_affine: None,
1788                int64_strided: None,
1789                datetime64_affine: None,
1790                int64_typed: OnceLock::new(),
1791                utf8_contiguous: None,
1792            };
1793        }
1794
1795        Self::new(self.as_slice()[start..end].to_vec())
1796    }
1797
1798    fn is_empty(&self) -> bool {
1799        self.len() == 0
1800    }
1801
1802    /// Whether this is a Datetime64-backed index containing the NaT sentinel.
1803    ///
1804    /// Pandas treats every DatetimeIndex containing NaT as non-monotonic in
1805    /// either direction. Keep the affine witness lazy while checking its
1806    /// reserved sentinel; eager and sliced DatetimeIndex storage is scanned
1807    /// directly without materializing any unrelated typed backing.
1808    fn has_datetime64_nat(&self) -> bool {
1809        if let Some(range) = self.datetime64_affine {
1810            return range.position(i64::MIN).is_some();
1811        }
1812        if let Some(slice) = &self.materialized_slice {
1813            return slice
1814                .as_slice()
1815                .iter()
1816                .any(|label| matches!(label, IndexLabel::Datetime64(value) if *value == i64::MIN));
1817        }
1818        self.materialized.get().is_some_and(|labels| {
1819            labels
1820                .iter()
1821                .any(|label| matches!(label, IndexLabel::Datetime64(value) if *value == i64::MIN))
1822        })
1823    }
1824
1825    /// The labels when they are held - materialized, or a slice of held
1826    /// ones - without materializing a lazy backing.
1827    fn held(&self) -> Option<&[IndexLabel]> {
1828        if let Some(slice) = &self.materialized_slice {
1829            return Some(slice.as_slice());
1830        }
1831        self.materialized.get().map(|labels| labels.as_slice())
1832    }
1833
1834    fn int64_unit_range(&self) -> Option<Int64UnitRangeLabels> {
1835        self.int64_unit_range
1836    }
1837
1838    fn int64_affine_range(&self) -> Option<Int64AffineLabels> {
1839        self.int64_unit_range
1840            .map(|range| Int64AffineLabels {
1841                start: range.start,
1842                step: 1,
1843                len: range.len,
1844            })
1845            .or(self.int64_affine)
1846    }
1847
1848    fn datetime64_affine_range(&self) -> Option<Int64AffineLabels> {
1849        self.datetime64_affine
1850    }
1851
1852    /// The raw `i64` view of an all-Int64 label vector, computing and caching
1853    /// it on first request. `None` means at least one label is not Int64.
1854    fn int64_view(&self) -> Option<Arc<Vec<i64>>> {
1855        self.int64_typed
1856            .get_or_init(|| {
1857                if let Some(range) = self.int64_unit_range {
1858                    let mut values = Vec::with_capacity(range.len);
1859                    for offset in 0..range.len {
1860                        let offset =
1861                            i64::try_from(offset).expect("validated Int64 unit range length");
1862                        values.push(
1863                            range
1864                                .start
1865                                .checked_add(offset)
1866                                .expect("validated Int64 unit range end"),
1867                        );
1868                    }
1869                    return Some(Arc::new(values));
1870                }
1871                if let Some(range) = self.int64_affine {
1872                    return Some(Arc::new(range.materialize_i64()));
1873                }
1874                if let Some(runs) = &self.int64_two_affine {
1875                    let runs = **runs;
1876                    return Some(Arc::new(runs.materialize_i64()));
1877                }
1878                if let Some(strided) = self.int64_strided.clone() {
1879                    return Some(Arc::new(strided.materialize_i64()));
1880                }
1881                if let Some(slice) = &self.materialized_slice {
1882                    let labels = slice.as_slice();
1883                    let mut values = Vec::with_capacity(labels.len());
1884                    for label in labels {
1885                        match label {
1886                            IndexLabel::Int64(value) => values.push(*value),
1887                            _ => return None,
1888                        }
1889                    }
1890                    return Some(Arc::new(values));
1891                }
1892                let labels = self.materialized.get()?;
1893                let mut values = Vec::with_capacity(labels.len());
1894                for label in labels.iter() {
1895                    match label {
1896                        IndexLabel::Int64(value) => values.push(*value),
1897                        _ => return None,
1898                    }
1899                }
1900                Some(Arc::new(values))
1901            })
1902            .clone()
1903    }
1904
1905    /// Resolve this label collection against a lazy affine Int64 source without
1906    /// materializing either affine range into an `i64` vector.  The source is
1907    /// unique by construction, so each raw target value has at most one
1908    /// position; non-Int64 labels are necessarily misses.
1909    fn affine_int64_indexer(&self, source: Int64AffineLabels) -> Vec<Option<usize>> {
1910        let mut out = Vec::with_capacity(self.len());
1911        let mut push_affine = |range: Int64AffineLabels| {
1912            for position in 0..range.len {
1913                out.push(source.position(range.value_at(position)));
1914            }
1915        };
1916
1917        if let Some(range) = self.int64_affine_range() {
1918            push_affine(range);
1919            return out;
1920        }
1921        if let Some(runs) = &self.int64_two_affine {
1922            push_affine(runs.first);
1923            push_affine(runs.second);
1924            return out;
1925        }
1926        if let Some(strided) = &self.int64_strided {
1927            for position in 0..strided.len {
1928                let offset = strided
1929                    .step
1930                    .checked_mul(position)
1931                    .expect("validated Int64 strided range");
1932                let index = strided
1933                    .start
1934                    .checked_add(offset)
1935                    .expect("validated Int64 strided range");
1936                out.push(source.position(strided.values[index]));
1937            }
1938            return out;
1939        }
1940        if let Some(Some(values)) = self.int64_typed.get() {
1941            out.extend(values.iter().map(|&value| source.position(value)));
1942            return out;
1943        }
1944
1945        // An integral float target is the int it equals (l5sed).
1946        out.extend(
1947            self.as_slice()
1948                .iter()
1949                .map(|label| label.exact_int().and_then(|value| source.position(value))),
1950        );
1951        out
1952    }
1953
1954    /// The cached `i64` view if it has already been computed (never computes).
1955    /// Outer `None` = not yet computed; `Some(None)` = known non-Int64.
1956    fn cached_int64_view(&self) -> Option<Option<Arc<Vec<i64>>>> {
1957        self.int64_typed.get().cloned()
1958    }
1959
1960    fn has_lazy_int64_backing(&self) -> bool {
1961        self.int64_unit_range.is_some()
1962            || self.int64_affine.is_some()
1963            || self.int64_two_affine.is_some()
1964            || self.int64_strided.is_some()
1965            || matches!(self.int64_typed.get(), Some(Some(_)))
1966    }
1967
1968    fn take_i64_values(&self, indices: &[usize]) -> Option<Vec<i64>> {
1969        let mut out = Vec::with_capacity(indices.len());
1970
1971        if let Some(range) = self.int64_unit_range {
1972            for &idx in indices {
1973                if idx >= range.len {
1974                    return None;
1975                }
1976                let offset = i64::try_from(idx).ok()?;
1977                out.push(range.start.checked_add(offset)?);
1978            }
1979            return Some(out);
1980        }
1981
1982        if let Some(range) = self.int64_affine {
1983            for &idx in indices {
1984                if idx >= range.len {
1985                    return None;
1986                }
1987                let offset = i64::try_from(idx).ok()?;
1988                let delta = range.step.checked_mul(offset)?;
1989                out.push(range.start.checked_add(delta)?);
1990            }
1991            return Some(out);
1992        }
1993
1994        if let Some(runs) = &self.int64_two_affine {
1995            let runs = **runs;
1996            for &idx in indices {
1997                if idx >= runs.len() {
1998                    return None;
1999                }
2000                out.push(runs.value_at(idx));
2001            }
2002            return Some(out);
2003        }
2004
2005        if let Some(strided) = &self.int64_strided {
2006            for &idx in indices {
2007                if idx >= strided.len {
2008                    return None;
2009                }
2010                let offset = strided.step.checked_mul(idx)?;
2011                let pos = strided.start.checked_add(offset)?;
2012                out.push(*strided.values.get(pos)?);
2013            }
2014            return Some(out);
2015        }
2016
2017        if let Some(Some(values)) = self.int64_typed.get() {
2018            for &idx in indices {
2019                if idx >= values.len() {
2020                    return None;
2021                }
2022                out.push(*values.get(idx)?);
2023            }
2024            return Some(out);
2025        }
2026
2027        None
2028    }
2029}
2030
2031impl Clone for IndexLabels {
2032    fn clone(&self) -> Self {
2033        let int64_typed = OnceLock::new();
2034        if let Some(view) = self.int64_typed.get() {
2035            let _ = int64_typed.set(view.clone());
2036        }
2037        Self {
2038            // One cell for every clone: labels made by any serve all.
2039            materialized: Arc::clone(&self.materialized),
2040            materialized_slice: self.materialized_slice.clone(),
2041            int64_unit_range: self.int64_unit_range,
2042            int64_affine: self.int64_affine,
2043            int64_two_affine: self.int64_two_affine.clone(),
2044            int64_strided: self.int64_strided.clone(),
2045            datetime64_affine: self.datetime64_affine,
2046            int64_typed,
2047            utf8_contiguous: self.utf8_contiguous.clone(),
2048        }
2049    }
2050}
2051
2052impl Default for IndexLabels {
2053    fn default() -> Self {
2054        Self::new(Vec::new())
2055    }
2056}
2057
2058impl fmt::Debug for IndexLabels {
2059    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2060        self.as_slice().fmt(f)
2061    }
2062}
2063
2064impl PartialEq for IndexLabels {
2065    fn eq(&self, other: &Self) -> bool {
2066        match (self.int64_affine_range(), other.int64_affine_range()) {
2067            (Some(left), Some(right)) => left == right,
2068            (Some(range), None) => range.equals_slice(other.as_slice()),
2069            (None, Some(range)) => range.equals_slice(self.as_slice()),
2070            (None, None) => self.as_slice() == other.as_slice(),
2071        }
2072    }
2073}
2074
2075impl Eq for IndexLabels {}
2076
2077/// Whether held datetime labels never descend (`INCREASING`) or never
2078/// ascend, in one pass comparing each stamp inline; NaT (i64::MIN) anywhere
2079/// answers false, as pandas' monotonic flags. None at the first label that
2080/// is not a datetime before any answer, for the generic order to decide.
2081/// The flags scanned the labels for NaT, then compared each pair through
2082/// IndexLabel::cmp, a call per pair: a fifth of a one-shot resample, which
2083/// asks at construction (br-frankenpandas-pirog).
2084fn held_datetimes_monotonic<const INCREASING: bool>(labels: &[IndexLabel]) -> Option<bool> {
2085    let mut previous = if INCREASING { i64::MIN } else { i64::MAX };
2086    for label in labels {
2087        let IndexLabel::Datetime64(stamp) = *label else {
2088            return None;
2089        };
2090        let reversed = if INCREASING {
2091            stamp < previous
2092        } else {
2093            stamp > previous
2094        };
2095        if stamp == i64::MIN || reversed {
2096            return Some(false);
2097        }
2098        previous = stamp;
2099    }
2100    Some(true)
2101}
2102
2103impl std::ops::Deref for IndexLabels {
2104    type Target = [IndexLabel];
2105
2106    fn deref(&self) -> &Self::Target {
2107        self.as_slice()
2108    }
2109}
2110
2111impl<'a> IntoIterator for &'a IndexLabels {
2112    type Item = &'a IndexLabel;
2113    type IntoIter = std::slice::Iter<'a, IndexLabel>;
2114
2115    fn into_iter(self) -> Self::IntoIter {
2116        self.as_slice().iter()
2117    }
2118}
2119
2120impl Serialize for IndexLabels {
2121    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2122    where
2123        S: Serializer,
2124    {
2125        self.as_slice().serialize(serializer)
2126    }
2127}
2128
2129impl<'de> Deserialize<'de> for IndexLabels {
2130    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2131    where
2132        D: Deserializer<'de>,
2133    {
2134        Vec::<IndexLabel>::deserialize(deserializer).map(Self::new)
2135    }
2136}
2137
2138#[derive(Clone, Serialize, Deserialize)]
2139pub struct Index {
2140    #[serde(default)]
2141    labels: IndexLabels,
2142    /// Optional name for the index (matches pandas `Index.name`), typed:
2143    /// `set_index(0)` names it the integer 0 (fvsao.64).
2144    #[serde(default, skip_serializing_if = "Option::is_none")]
2145    name: Option<LabelName>,
2146    /// Runtime-only immutable identity for this label vector lineage.
2147    #[serde(skip, default = "next_index_label_identity")]
2148    label_identity: u64,
2149    #[serde(skip)]
2150    duplicate_cache: OnceLock<bool>,
2151    /// AG-13: Cached sort order for adaptive backend selection.
2152    #[serde(skip)]
2153    sort_order_cache: OnceLock<SortOrder>,
2154    /// The monotonic flags (increasing, decreasing) once asked, shared by
2155    /// clones as the labels are: the labels never change, and pandas keeps
2156    /// them on its engine - a repeated `is_monotonic_increasing` rescanned
2157    /// the labels (0.12 ms over 200k stamps against pandas' 0.2 us), and a
2158    /// resampler asked a clone each time (br-frankenpandas-pirog).
2159    #[serde(skip)]
2160    monotonic_cache: Arc<[OnceLock<bool>; 2]>,
2161    /// Runtime-only cache for labels-derived AACE semantic fingerprints.
2162    #[serde(skip)]
2163    semantic_fingerprint_cache: OnceLock<String>,
2164    /// The levels of the row `MultiIndex` whose flattened labels these are (a
2165    /// multi-key groupby result, a column of a frame indexed by several
2166    /// columns). The labels stay the flat keys every kernel handles; the levels
2167    /// ride with them. Only [`Self::with_row_multiindex`] attaches them and only
2168    /// `take`/`slice` carry them to new labels, so any other operation that
2169    /// builds labels returns a flat index rather than mislabelled levels
2170    /// (br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.9).
2171    #[serde(
2172        default,
2173        skip_serializing_if = "Option::is_none",
2174        with = "row_multiindex_serde"
2175    )]
2176    row_multiindex: Option<Arc<MultiIndex>>,
2177    /// The time zone of datetime labels (pandas `DatetimeIndex.tz`): the
2178    /// labels stay UTC nanoseconds and the zone is the wall clock they show.
2179    /// Only [`Self::with_tz`] attaches it; [`Self::propagate_name`] carries it
2180    /// to an index built from these labels while that index still holds
2181    /// datetimes (take, slice, sort, unique, ...).
2182    #[serde(default, skip_serializing_if = "Option::is_none")]
2183    tz: Option<String>,
2184    /// pandas' `DatetimeIndex.freq` as its freqstr ('D', '2D', 'W-SUN',
2185    /// 'ME', '-1D'). Only [`Self::with_freq`] sets it; it survives a clone,
2186    /// [`Self::slice`] and a [`Self::take`] of consecutive ascending
2187    /// positions (pandas keeps it through a slice and a mask that selects a
2188    /// run), and every other operation that builds labels drops it. Equality
2189    /// ignores it, as pandas' `equals` does.
2190    #[serde(default, skip_serializing_if = "Option::is_none")]
2191    freq: Option<String>,
2192    /// The `range(start, stop, step)` these labels are when they are a
2193    /// pandas RangeIndex - a default index (a Series or DataFrame built
2194    /// without one, reset_index, a matrix) or a slice of one - rather than
2195    /// an Index that happens to hold 0..n. The stop is pandas' own (a
2196    /// strided slice of `range(4)` is `range(1, 4, 2)`, an empty one
2197    /// `range(3, 1)`). Only the range constructors ([`Self::from_range`],
2198    /// [`Self::with_range_span`]) set it; a clone and a
2199    /// slice keep it; a take, a mask or any rebuild of the labels drops it,
2200    /// as pandas turns those into an Index. Equality ignores it.
2201    #[serde(default, skip_serializing_if = "Option::is_none")]
2202    range: Option<(i64, i64, i64)>,
2203    /// pandas' dtype where the labels alone would read another (see
2204    /// [`DeclaredDtype`]): object over numbers, an empty index's source
2205    /// dtype, numpy's int32. Only [`Self::with_declared_dtype`] sets it;
2206    /// [`Self::propagate_name`] carries it to an index built from these
2207    /// labels. Equality ignores it, as pandas' `equals` does.
2208    #[serde(default, skip_serializing_if = "Option::is_none")]
2209    declared: Option<DeclaredDtype>,
2210    /// pandas' `CategoricalIndex` metadata (see [`IndexCategories`]) when
2211    /// these labels are one: a Series' or frame's index can be categorical
2212    /// (it was a plain Index; br-frankenpandas-cld41). Only
2213    /// [`Self::with_categories`] sets it; [`Self::propagate_name`] carries
2214    /// it while every label is still one of the categories. Runtime
2215    /// metadata, as the label identity; equality ignores it.
2216    #[serde(skip)]
2217    categories: Option<Arc<IndexCategories>>,
2218}
2219
2220/// The categories a categorical [`Index`]'s labels are drawn from, in
2221/// their order, and whether that order ranks them - pandas'
2222/// `CategoricalIndex.categories` / `.ordered`.
2223#[derive(Debug, Clone, PartialEq, Eq)]
2224pub struct IndexCategories {
2225    pub categories: Vec<IndexLabel>,
2226    pub ordered: bool,
2227}
2228
2229/// A dtype an [`Index`] is declared with where its labels alone read
2230/// another: pandas' `Index([1, 2], dtype=object)` holds the ints 1 and 2
2231/// under the object dtype (they became the strings '1' and '2';
2232/// br-frankenpandas-i20vm); an empty index keeps the dtype it was taken
2233/// from (`iloc[:0]` of an int64 index is int64, it read as object; dwyud);
2234/// a DatetimeIndex field (`.year`) is numpy's int32 (it was int64; pqjzo).
2235#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2236#[serde(rename_all = "snake_case")]
2237pub enum DeclaredDtype {
2238    Object,
2239    Int64,
2240    Int32,
2241    Float64,
2242    Bool,
2243    Datetime64,
2244    Timedelta64,
2245}
2246
2247impl DeclaredDtype {
2248    /// pandas' name of the dtype.
2249    #[must_use]
2250    pub const fn name(self) -> &'static str {
2251        match self {
2252            Self::Object => "object",
2253            Self::Int64 => "int64",
2254            Self::Int32 => "int32",
2255            Self::Float64 => "float64",
2256            Self::Bool => "bool",
2257            Self::Datetime64 => "datetime64[ns]",
2258            Self::Timedelta64 => "timedelta64[ns]",
2259        }
2260    }
2261
2262    /// The declared dtype pandas' name reads as, None for another.
2263    #[must_use]
2264    pub fn of_name(name: &str) -> Option<Self> {
2265        Some(match name {
2266            "object" => Self::Object,
2267            "int64" => Self::Int64,
2268            "int32" => Self::Int32,
2269            "float64" => Self::Float64,
2270            "bool" => Self::Bool,
2271            "datetime64[ns]" => Self::Datetime64,
2272            "timedelta64[ns]" => Self::Timedelta64,
2273            _ => return None,
2274        })
2275    }
2276}
2277
2278/// The derived layout, with the row `MultiIndex` levels listed only when an
2279/// index carries them: a flat index prints exactly as before they existed.
2280impl fmt::Debug for Index {
2281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2282        let mut out = f.debug_struct("Index");
2283        out.field("labels", &self.labels)
2284            .field("name", &self.name)
2285            .field("label_identity", &self.label_identity)
2286            .field("duplicate_cache", &self.duplicate_cache)
2287            .field("sort_order_cache", &self.sort_order_cache)
2288            .field(
2289                "semantic_fingerprint_cache",
2290                &self.semantic_fingerprint_cache,
2291            );
2292        if let Some(levels) = &self.row_multiindex {
2293            out.field("row_multiindex", levels);
2294        }
2295        if let Some(tz) = &self.tz {
2296            out.field("tz", tz);
2297        }
2298        if let Some(freq) = &self.freq {
2299            out.field("freq", freq);
2300        }
2301        if let Some(range) = &self.range {
2302            out.field("range", range);
2303        }
2304        if let Some(declared) = &self.declared {
2305            out.field("declared", declared);
2306        }
2307        if let Some(categories) = &self.categories {
2308            out.field("categories", categories);
2309        }
2310        out.finish()
2311    }
2312}
2313
2314/// Serde for the shared `Arc` behind [`Index`]'s row `MultiIndex` levels:
2315/// serialized as the plain `MultiIndex` (the workspace builds serde without
2316/// its `rc` feature).
2317mod row_multiindex_serde {
2318    use serde::{Deserialize, Deserializer, Serialize, Serializer};
2319
2320    use super::{Arc, MultiIndex};
2321
2322    #[allow(
2323        clippy::ref_option,
2324        reason = "serde's `with` contract passes the field by reference"
2325    )]
2326    pub fn serialize<S: Serializer>(
2327        levels: &Option<Arc<MultiIndex>>,
2328        serializer: S,
2329    ) -> Result<S::Ok, S::Error> {
2330        levels.as_deref().serialize(serializer)
2331    }
2332
2333    pub fn deserialize<'de, D: Deserializer<'de>>(
2334        deserializer: D,
2335    ) -> Result<Option<Arc<MultiIndex>>, D::Error> {
2336        Ok(Option::<MultiIndex>::deserialize(deserializer)?.map(Arc::new))
2337    }
2338}
2339
2340/// Equal labels in the same zone: pandas' `equals` is False between an aware
2341/// index and a naive one, or two zones, over the same instants.
2342impl PartialEq for Index {
2343    fn eq(&self, other: &Self) -> bool {
2344        self.tz == other.tz && self.labels_equal(other)
2345    }
2346}
2347
2348impl Eq for Index {}
2349
2350fn detect_duplicates(labels: &[IndexLabel]) -> bool {
2351    let mut seen = FxHashMap::<&IndexLabel, ()>::default();
2352    for label in labels {
2353        if seen.insert(label, ()).is_some() {
2354            return true;
2355        }
2356    }
2357    false
2358}
2359
2360fn ordered_label_identity_pair(left: u64, right: u64) -> (u64, u64) {
2361    if left <= right {
2362        (left, right)
2363    } else {
2364        (right, left)
2365    }
2366}
2367
2368fn fixed_width_label_memory_usage(len: usize, width: usize) -> usize {
2369    len.saturating_mul(width)
2370}
2371
2372fn repeat_output_capacity(len: usize, repeats: usize) -> usize {
2373    len.checked_mul(repeats)
2374        .expect("index repeat output length overflow")
2375}
2376
2377fn combined_output_capacity(left: usize, right: usize) -> usize {
2378    left.checked_add(right)
2379        .expect("index combined output length overflow")
2380}
2381
2382fn int64_drop_values(labels_to_drop: &[IndexLabel]) -> Vec<i64> {
2383    labels_to_drop
2384        .iter()
2385        .filter_map(|label| match label {
2386            IndexLabel::Int64(value) => Some(*value),
2387            _ => None,
2388        })
2389        .collect()
2390}
2391
2392fn is_non_decreasing_i64(values: &[i64]) -> bool {
2393    values.windows(2).all(|window| window[0] <= window[1])
2394}
2395
2396fn drop_sorted_i64_values(values: &[i64], mut drop_values: Vec<i64>) -> Vec<i64> {
2397    drop_values.sort_unstable();
2398    drop_values.dedup();
2399
2400    let mut kept = Vec::with_capacity(values.len());
2401    let mut drop_index = 0usize;
2402    for &value in values {
2403        while drop_index < drop_values.len() && drop_values[drop_index] < value {
2404            drop_index += 1;
2405        }
2406        if drop_index < drop_values.len() && drop_values[drop_index] == value {
2407            continue;
2408        }
2409        kept.push(value);
2410    }
2411    kept
2412}
2413
2414fn insert_output_capacity(len: usize) -> usize {
2415    len.checked_add(1)
2416        .expect("index insert output length overflow")
2417}
2418
2419fn aggregate_output_capacity(lengths: impl IntoIterator<Item = usize>) -> usize {
2420    lengths
2421        .into_iter()
2422        .try_fold(0usize, |total, len| total.checked_add(len))
2423        .expect("index aggregate output length overflow")
2424}
2425
2426fn checked_cartesian_product_len(
2427    lengths: impl IntoIterator<Item = usize>,
2428) -> Result<usize, IndexError> {
2429    lengths.into_iter().try_fold(1usize, |total, len| {
2430        total.checked_mul(len).ok_or_else(|| {
2431            IndexError::InvalidArgument("MultiIndex product cardinality overflow".to_owned())
2432        })
2433    })
2434}
2435
2436fn saturating_usize_sum(values: impl IntoIterator<Item = usize>) -> usize {
2437    values.into_iter().fold(0usize, usize::saturating_add)
2438}
2439
2440impl Index {
2441    #[must_use]
2442    pub fn new(labels: Vec<IndexLabel>) -> Self {
2443        Self {
2444            labels: IndexLabels::new(labels),
2445            name: None,
2446            label_identity: next_index_label_identity(),
2447            duplicate_cache: OnceLock::new(),
2448            sort_order_cache: OnceLock::new(),
2449            monotonic_cache: Default::default(),
2450            semantic_fingerprint_cache: OnceLock::new(),
2451            row_multiindex: None,
2452            tz: None,
2453            freq: None,
2454            range: None,
2455            declared: None,
2456            categories: None,
2457        }
2458    }
2459
2460    fn labels_equal(&self, other: &Self) -> bool {
2461        if self.label_identity == other.label_identity {
2462            return true;
2463        }
2464
2465        let key = ordered_label_identity_pair(self.label_identity, other.label_identity);
2466        let cache = INDEX_LABEL_EQUALITY_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
2467        if let Some(equal) = cache
2468            .lock()
2469            .expect("index label equality cache poisoned")
2470            .get(&key)
2471            .copied()
2472        {
2473            return equal;
2474        }
2475
2476        let equal = self.labels == other.labels;
2477        let mut guard = cache.lock().expect("index label equality cache poisoned");
2478        if guard.len() >= INDEX_LABEL_EQUALITY_CACHE_MAX {
2479            guard.clear();
2480        }
2481        guard.insert(key, equal);
2482        equal
2483    }
2484
2485    /// Construct an index whose caller has already proven all labels unique.
2486    ///
2487    /// This preserves the public `Index::new` surface while letting alignment
2488    /// builders carry their uniqueness proof into the runtime duplicate cache.
2489    #[must_use]
2490    #[doc(hidden)]
2491    pub fn new_known_unique(labels: Vec<IndexLabel>) -> Self {
2492        debug_assert!(!detect_duplicates(&labels));
2493        let index = Self::new(labels);
2494        let _ = index.duplicate_cache.set(false);
2495        index
2496    }
2497
2498    /// Construct an index whose labels are the dense unit range
2499    /// `start..start+len`, without allocating the label vector until a caller
2500    /// asks for label materialization.
2501    #[must_use]
2502    #[doc(hidden)]
2503    pub fn new_known_unique_int64_unit_range(start: i64, len: usize) -> Self {
2504        let labels = IndexLabels::new_int64_unit_range(start, len)
2505            .expect("validated Int64 unit range bounds");
2506        let index = Self {
2507            labels,
2508            name: None,
2509            label_identity: next_index_label_identity(),
2510            duplicate_cache: OnceLock::new(),
2511            sort_order_cache: OnceLock::new(),
2512            monotonic_cache: Default::default(),
2513            semantic_fingerprint_cache: OnceLock::new(),
2514            row_multiindex: None,
2515            tz: None,
2516            freq: None,
2517            range: None,
2518            declared: None,
2519            categories: None,
2520        };
2521        let _ = index.duplicate_cache.set(false);
2522        let _ = index.sort_order_cache.set(SortOrder::AscendingInt64);
2523        index
2524    }
2525
2526    /// pandas' default index over `len` rows: the RangeIndex `range(0, len)`
2527    /// a concat with `ignore_index`, a merge or a reader builds (they came
2528    /// back as a plain Index of 0..len).
2529    #[must_use]
2530    pub fn default_range(len: usize) -> Self {
2531        let span = i64::try_from(len).ok().map(|stop| (0, stop, 1));
2532        Self::new_known_unique_int64_unit_range(0, len).with_range_span(span)
2533    }
2534
2535    /// Construct an index whose labels are the affine Int64 sequence
2536    /// `start + i * step`, without allocating the label vector until a caller
2537    /// asks for label materialization.
2538    #[must_use]
2539    #[doc(hidden)]
2540    pub fn new_known_unique_int64_affine_range(start: i64, step: i64, len: usize) -> Option<Self> {
2541        let labels = IndexLabels::new_int64_affine(start, step, len)?;
2542        let index = Self {
2543            labels,
2544            name: None,
2545            label_identity: next_index_label_identity(),
2546            duplicate_cache: OnceLock::new(),
2547            sort_order_cache: OnceLock::new(),
2548            monotonic_cache: Default::default(),
2549            semantic_fingerprint_cache: OnceLock::new(),
2550            row_multiindex: None,
2551            tz: None,
2552            freq: None,
2553            range: None,
2554            declared: None,
2555            categories: None,
2556        };
2557        let _ = index.duplicate_cache.set(false);
2558        if len <= 1 || step > 0 {
2559            let _ = index.sort_order_cache.set(SortOrder::AscendingInt64);
2560        }
2561        Some(index)
2562    }
2563
2564    fn new_int64_two_affine_runs(
2565        first: Int64AffineLabels,
2566        second: Int64AffineLabels,
2567    ) -> Option<Self> {
2568        let labels = IndexLabels::new_int64_two_affine(first, second)?;
2569        Some(Self {
2570            labels,
2571            name: None,
2572            label_identity: next_index_label_identity(),
2573            duplicate_cache: OnceLock::new(),
2574            sort_order_cache: OnceLock::new(),
2575            monotonic_cache: Default::default(),
2576            semantic_fingerprint_cache: OnceLock::new(),
2577            row_multiindex: None,
2578            tz: None,
2579            freq: None,
2580            range: None,
2581            declared: None,
2582            categories: None,
2583        })
2584    }
2585
2586    fn new_known_unique_int64_two_affine_runs(
2587        first: Int64AffineLabels,
2588        second: Int64AffineLabels,
2589    ) -> Option<Self> {
2590        let index = Self::new_int64_two_affine_runs(first, second)?;
2591        let _ = index.duplicate_cache.set(false);
2592        Some(index)
2593    }
2594
2595    #[must_use]
2596    pub fn from_i64(values: Vec<i64>) -> Self {
2597        Self::from_i64_values(values)
2598    }
2599
2600    /// Construct an index over Int64 labels backed by a contiguous `Vec<i64>`
2601    /// (br-frankenpandas-dxqpm). Label materialization into `IndexLabel`s is
2602    /// deferred until a caller asks for `labels()`; clones of the index share
2603    /// the typed backing instead of deep-copying the enum vector.
2604    #[must_use]
2605    #[doc(hidden)]
2606    pub fn from_i64_values(values: Vec<i64>) -> Self {
2607        Self {
2608            labels: IndexLabels::new_int64_values(Arc::new(values)),
2609            name: None,
2610            label_identity: next_index_label_identity(),
2611            duplicate_cache: OnceLock::new(),
2612            sort_order_cache: OnceLock::new(),
2613            monotonic_cache: Default::default(),
2614            semantic_fingerprint_cache: OnceLock::new(),
2615            row_multiindex: None,
2616            tz: None,
2617            freq: None,
2618            range: None,
2619            declared: None,
2620            categories: None,
2621        }
2622    }
2623
2624    /// Construct an Int64-labelled index as a strided view over an existing
2625    /// typed backing. Unlike affine ranges, the source values may be duplicated
2626    /// or unsorted, so uniqueness and sort caches are intentionally not seeded.
2627    #[must_use]
2628    #[doc(hidden)]
2629    pub fn from_i64_strided_values(
2630        values: Arc<Vec<i64>>,
2631        start: usize,
2632        step: usize,
2633        len: usize,
2634    ) -> Option<Self> {
2635        Some(Self {
2636            labels: IndexLabels::new_int64_strided(values, start, step, len)?,
2637            name: None,
2638            label_identity: next_index_label_identity(),
2639            duplicate_cache: OnceLock::new(),
2640            sort_order_cache: OnceLock::new(),
2641            monotonic_cache: Default::default(),
2642            semantic_fingerprint_cache: OnceLock::new(),
2643            row_multiindex: None,
2644            tz: None,
2645            freq: None,
2646            range: None,
2647            declared: None,
2648            categories: None,
2649        })
2650    }
2651
2652    /// Construct an index over Utf8 labels backed by a contiguous byte buffer +
2653    /// offsets (br-frankenpandas-nbspq). Label materialization into
2654    /// `IndexLabel::Utf8` is deferred until `labels()` is asked for; clones share
2655    /// the `Arc` backing. Caller guarantees `bytes` is valid UTF-8 and
2656    /// `offsets` holds `n+1` ascending entries ending at `bytes.len()`.
2657    #[must_use]
2658    #[doc(hidden)]
2659    pub fn from_utf8_contiguous(bytes: Arc<[u8]>, offsets: Arc<[usize]>) -> Self {
2660        Self {
2661            labels: IndexLabels::new_utf8_contiguous(bytes, offsets),
2662            name: None,
2663            label_identity: next_index_label_identity(),
2664            duplicate_cache: OnceLock::new(),
2665            sort_order_cache: OnceLock::new(),
2666            monotonic_cache: Default::default(),
2667            semantic_fingerprint_cache: OnceLock::new(),
2668            row_multiindex: None,
2669            tz: None,
2670            freq: None,
2671            range: None,
2672            declared: None,
2673            categories: None,
2674        }
2675    }
2676
2677    /// Raw `i64` view of an all-Int64 label vector, computing and caching it
2678    /// on first request. `None` means at least one label is not Int64.
2679    #[must_use]
2680    #[doc(hidden)]
2681    pub fn int64_label_values(&self) -> Option<Arc<Vec<i64>>> {
2682        self.labels.int64_view()
2683    }
2684
2685    /// The cached `i64` label view if already computed (never computes).
2686    /// Outer `None` = not yet computed; `Some(None)` = known non-Int64.
2687    #[must_use]
2688    #[doc(hidden)]
2689    pub fn cached_int64_label_values(&self) -> Option<Option<Arc<Vec<i64>>>> {
2690        self.labels.cached_int64_view()
2691    }
2692
2693    /// Whether the labels are ints held by a typed backing (a range, an
2694    /// int64 buffer): every one an Int64, none missing - known without
2695    /// materializing them. False says nothing about the labels.
2696    #[must_use]
2697    #[doc(hidden)]
2698    pub fn has_int64_backing(&self) -> bool {
2699        self.labels.has_lazy_int64_backing()
2700    }
2701
2702    /// The kinds of label this index holds, worked out once per label
2703    /// identity: typed ints and a datetime range answer without a scan, any
2704    /// other labels after one pass, kept as the equality of two indexes is
2705    /// (br-frankenpandas-nmna9: every `.index` rescanned a million labels to
2706    /// pick its class, and DatetimeIndex::from_index again to check it).
2707    #[must_use]
2708    pub fn label_kinds(&self) -> LabelKinds {
2709        if self.labels.is_empty() {
2710            return LabelKinds::default();
2711        }
2712        if self.labels.has_lazy_int64_backing() {
2713            return LabelKinds::INT64;
2714        }
2715        if self.labels.datetime64_affine_range().is_some() {
2716            return LabelKinds::DATETIME64;
2717        }
2718        let cache = INDEX_LABEL_KINDS_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
2719        if let Some(kinds) = cache
2720            .lock()
2721            .expect("index label kinds cache poisoned")
2722            .get(&self.label_identity)
2723            .copied()
2724        {
2725            return kinds;
2726        }
2727        let kinds = self
2728            .labels
2729            .iter()
2730            .fold(LabelKinds::default(), |kinds, label| {
2731                kinds.union(LabelKinds::of(label))
2732            });
2733        self.remember_label_kinds(kinds);
2734        kinds
2735    }
2736
2737    /// Keeps `kinds` as the label kinds of this label identity, for
2738    /// [`Self::label_kinds`]: its own pass, or another that read every label
2739    /// (a datetime ascent, br-frankenpandas-pirog).
2740    fn remember_label_kinds(&self, kinds: LabelKinds) {
2741        let cache = INDEX_LABEL_KINDS_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
2742        let mut guard = cache.lock().expect("index label kinds cache poisoned");
2743        if guard.len() >= INDEX_LABEL_KINDS_CACHE_MAX {
2744            guard.clear();
2745        }
2746        guard.insert(self.label_identity, kinds);
2747    }
2748
2749    #[must_use]
2750    pub fn from_utf8(values: Vec<String>) -> Self {
2751        Self::new(values.into_iter().map(IndexLabel::from).collect())
2752    }
2753
2754    #[must_use]
2755    pub fn from_timedelta64(nanos: Vec<i64>) -> Self {
2756        Self::new(nanos.into_iter().map(IndexLabel::Timedelta64).collect())
2757            .declared_if_empty(DeclaredDtype::Timedelta64)
2758    }
2759
2760    #[must_use]
2761    #[doc(hidden)]
2762    pub fn from_datetime64_affine_range(start: i64, step: i64, len: usize) -> Option<Self> {
2763        let labels = IndexLabels::new_datetime64_affine(start, step, len)?;
2764        let index = Self {
2765            labels,
2766            name: None,
2767            label_identity: next_index_label_identity(),
2768            duplicate_cache: OnceLock::new(),
2769            sort_order_cache: OnceLock::new(),
2770            monotonic_cache: Default::default(),
2771            semantic_fingerprint_cache: OnceLock::new(),
2772            row_multiindex: None,
2773            tz: None,
2774            freq: None,
2775            range: None,
2776            declared: None,
2777            categories: None,
2778        };
2779        let _ = index.duplicate_cache.set(false);
2780        if len <= 1 || step > 0 {
2781            let _ = index.sort_order_cache.set(SortOrder::AscendingDatetime64);
2782        }
2783        Some(index.declared_if_empty(DeclaredDtype::Datetime64))
2784    }
2785
2786    #[must_use]
2787    pub fn from_datetime64(nanos: Vec<i64>) -> Self {
2788        Self::new(nanos.into_iter().map(IndexLabel::Datetime64).collect())
2789            .declared_if_empty(DeclaredDtype::Datetime64)
2790    }
2791
2792    /// No labels show a type, so an empty index built as `dtype` declares
2793    /// it (an empty date_range under a Series was an object index;
2794    /// br-frankenpandas-ce86r).
2795    fn declared_if_empty(self, dtype: DeclaredDtype) -> Self {
2796        if self.is_empty() {
2797            self.with_declared_dtype(Some(dtype))
2798        } else {
2799            self
2800        }
2801    }
2802
2803    /// The `(first, step, len)` of a date_range's lazy datetime labels -
2804    /// label `k` is `Datetime64(first + k * step)` - None for any other
2805    /// labels (br-frankenpandas-so0mr).
2806    #[must_use]
2807    #[doc(hidden)]
2808    pub fn datetime64_affine_labels(&self) -> Option<(i64, i64, usize)> {
2809        self.labels
2810            .datetime64_affine_range()
2811            .map(|range| (range.start, range.step, range.len))
2812    }
2813
2814    #[must_use]
2815    pub fn len(&self) -> usize {
2816        self.labels.len()
2817    }
2818
2819    #[must_use]
2820    pub fn is_empty(&self) -> bool {
2821        self.labels.is_empty()
2822    }
2823
2824    #[must_use]
2825    pub fn labels(&self) -> &[IndexLabel] {
2826        self.labels.as_slice()
2827    }
2828
2829    #[must_use]
2830    #[doc(hidden)]
2831    pub fn int64_unit_range_labels(&self) -> Option<(i64, usize)> {
2832        self.labels
2833            .int64_unit_range()
2834            .map(|range| (range.start, range.len))
2835    }
2836
2837    #[must_use]
2838    pub fn semantic_labels_fingerprint_with<F>(&self, compute: F) -> String
2839    where
2840        F: FnOnce(&[IndexLabel]) -> String,
2841    {
2842        self.semantic_fingerprint_cache
2843            .get_or_init(|| compute(self.labels()))
2844            .clone()
2845    }
2846
2847    /// Return the index name (matches `pd.Index.name`): its text, and its
2848    /// typed label when it is not a string ([`LabelName`]).
2849    #[must_use]
2850    pub fn name(&self) -> Option<&LabelName> {
2851        self.name.as_ref()
2852    }
2853
2854    /// Return a new index with the given name (matches `pd.Index.set_names`).
2855    /// A [`LabelName`] keeps its typed label; text is a string name.
2856    #[must_use]
2857    pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
2858        let mut idx = self.clone();
2859        idx.name = name.map(Into::into);
2860        idx
2861    }
2862
2863    /// Alias for `set_names` — set the index name, returning a new `Index`.
2864    #[must_use]
2865    pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
2866        self.set_names(Some(name))
2867    }
2868
2869    /// Return a list of index names.
2870    ///
2871    /// Matches `pd.Index.names`. For a flat (non-MultiIndex) index this returns
2872    /// a single-element list with the current name (or `None`).
2873    #[must_use]
2874    pub fn names(&self) -> Vec<Option<String>> {
2875        vec![self.name.clone().map(String::from)]
2876    }
2877
2878    /// Set names from a list.
2879    ///
2880    /// Matches `pd.Index.set_names([name])`. For flat index only the first
2881    /// element is used. Panics if the list is empty.
2882    #[must_use]
2883    pub fn set_names_list(&self, names: &[Option<&str>]) -> Self {
2884        assert!(
2885            !names.is_empty(),
2886            "set_names_list requires at least one name"
2887        );
2888        self.set_names(names[0])
2889    }
2890
2891    /// Return the index as-is (flat index identity).
2892    ///
2893    /// Matches `pd.Index.to_flat_index()`. For a non-MultiIndex this is a
2894    /// no-op that returns a clone. For a MultiIndex it would convert tuples
2895    /// to flat labels; attached row `MultiIndex` levels are dropped, leaving
2896    /// the flat labels alone.
2897    #[must_use]
2898    pub fn to_flat_index(&self) -> Self {
2899        let mut flat = self.clone();
2900        flat.row_multiindex = None;
2901        flat
2902    }
2903
2904    /// Return a new index named `name` (`None` clears it); a
2905    /// [`LabelName`] keeps its typed label.
2906    #[must_use]
2907    pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
2908        self.set_names(name)
2909    }
2910
2911    /// An index of `labels` taken from this one (a subset, a reordering, a
2912    /// repeat): this index's name, and its zone while the labels are all
2913    /// datetimes. `Index::new(labels)` plus the name dropped the zone, so a
2914    /// tz-aware index came back as naive UTC labels (fvsao.60).
2915    #[must_use]
2916    pub fn relabeled(&self, labels: Vec<IndexLabel>) -> Self {
2917        self.propagate_name(Self::new(labels))
2918    }
2919
2920    /// Internal: propagate this index's name onto a newly created index.
2921    fn propagate_name(&self, mut other: Self) -> Self {
2922        other.name.clone_from(&self.name);
2923        if self.tz.is_some() && other.holds_only_datetimes() {
2924            other.tz.clone_from(&self.tz);
2925        }
2926        if let Some(categories) = &self.categories
2927            && other.labels_within(categories)
2928        {
2929            other.categories = Some(Arc::clone(categories));
2930        }
2931        other.with_dtype_of(self)
2932    }
2933
2934    /// Whether every label (a missing one aside) is one of `categories`.
2935    fn labels_within(&self, categories: &IndexCategories) -> bool {
2936        let known: std::collections::HashSet<&IndexLabel> = categories.categories.iter().collect();
2937        self.labels()
2938            .iter()
2939            .all(|label| label.is_missing() || known.contains(label))
2940    }
2941
2942    /// pandas' `CategoricalIndex` metadata of these labels, None for an
2943    /// index that is not categorical.
2944    #[must_use]
2945    pub fn categories(&self) -> Option<&IndexCategories> {
2946        self.categories.as_deref()
2947    }
2948
2949    /// These labels as a categorical index drawn from `categories` (None:
2950    /// not categorical). A label outside the categories is an error, as a
2951    /// CategoricalIndex cannot hold one.
2952    pub fn with_categories(
2953        mut self,
2954        categories: Option<IndexCategories>,
2955    ) -> Result<Self, IndexError> {
2956        if let Some(categories) = &categories
2957            && !self.labels_within(categories)
2958        {
2959            return Err(IndexError::InvalidArgument(
2960                "a categorical index's labels must be among its categories".to_owned(),
2961            ));
2962        }
2963        self.categories = categories.map(Arc::new);
2964        Ok(self)
2965    }
2966
2967    /// These labels - selected, sliced or computed from `source`'s - under
2968    /// the dtype pandas gives them: `source`'s declared object dtype (it
2969    /// holds any labels), its int32 while they are ints, and for no label
2970    /// at all `source`'s dtype, as pandas' empty slice or selection keeps it
2971    /// (br-frankenpandas-i20vm / pqjzo / dwyud). A dtype these labels are
2972    /// already declared with stays.
2973    #[must_use]
2974    pub fn with_dtype_of(mut self, source: &Self) -> Self {
2975        if self.declared.is_none() {
2976            self.declared = match source.declared {
2977                Some(DeclaredDtype::Object) => Some(DeclaredDtype::Object),
2978                Some(DeclaredDtype::Int32) if self.is_integer() => Some(DeclaredDtype::Int32),
2979                declared if self.is_empty() => {
2980                    declared.or_else(|| DeclaredDtype::of_name(source.dtype()))
2981                }
2982                _ => None,
2983            };
2984        }
2985        self
2986    }
2987
2988    /// These labels under `declared` (see [`DeclaredDtype`]); None their
2989    /// own dtype.
2990    #[must_use]
2991    pub fn with_declared_dtype(mut self, declared: Option<DeclaredDtype>) -> Self {
2992        self.declared = declared;
2993        self
2994    }
2995
2996    /// The dtype these labels are declared with, if any.
2997    #[must_use]
2998    pub fn declared_dtype(&self) -> Option<DeclaredDtype> {
2999        self.declared
3000    }
3001
3002    /// Whether every label is a datetime (NaT included) - what a time zone
3003    /// can describe.
3004    fn holds_only_datetimes(&self) -> bool {
3005        // A date_range's lazy range is datetimes without its labels made
3006        // (br-frankenpandas-so0mr).
3007        if self.labels.datetime64_affine_range().is_some() {
3008            return true;
3009        }
3010        self.labels().iter().all(|label| {
3011            matches!(
3012                label,
3013                IndexLabel::Datetime64(_) | IndexLabel::Null(fp_types::NullKind::NaT)
3014            )
3015        })
3016    }
3017
3018    /// The time zone of these datetime labels (pandas `DatetimeIndex.tz`),
3019    /// None for a naive index.
3020    #[must_use]
3021    pub fn tz(&self) -> Option<&str> {
3022        self.tz.as_deref()
3023    }
3024
3025    /// These labels shown in `tz` (None: naive). The labels are UTC
3026    /// nanoseconds either way; a zone attaches only to an index of datetimes.
3027    pub fn with_tz(mut self, tz: Option<&str>) -> Result<Self, IndexError> {
3028        if let Some(zone) = tz {
3029            fp_types::tz_validate(zone)?;
3030            if !self.holds_only_datetimes() {
3031                return Err(IndexError::InvalidArgument(format!(
3032                    "a time zone ('{zone}') describes datetime labels only"
3033                )));
3034            }
3035        }
3036        self.tz = tz.map(str::to_owned);
3037        Ok(self)
3038    }
3039
3040    /// pandas' `DatetimeIndex.freq` of these labels as its freqstr, None
3041    /// when none is set (see the field).
3042    #[must_use]
3043    pub fn freq(&self) -> Option<&str> {
3044        self.freq.as_deref()
3045    }
3046
3047    /// These labels with `freq` (a pandas freqstr) set or cleared. The
3048    /// caller vouches that the labels follow it.
3049    #[must_use]
3050    pub fn with_freq(mut self, freq: Option<String>) -> Self {
3051        self.freq = freq;
3052        self
3053    }
3054
3055    /// The `range(start, stop, step)` these labels are as a pandas
3056    /// RangeIndex (see the field), while the labels still hold exactly that
3057    /// range (its length, first and last label).
3058    #[must_use]
3059    pub fn range_span(&self) -> Option<(i64, i64, i64)> {
3060        let (start, stop, step) = self.range?;
3061        let len = RangeIndex::new(start, stop, step).ok()?.len();
3062        if len != self.len() {
3063            return None;
3064        }
3065        if len == 0 {
3066            return Some((start, stop, step));
3067        }
3068        let last =
3069            i64::try_from(i128::from(start) + i128::from(step) * i128::try_from(len - 1).ok()?)
3070                .ok()?;
3071        let holds = if let Some(affine) = self.labels.int64_affine_range() {
3072            affine.start == start && (len == 1 || affine.step == step)
3073        } else {
3074            let labels = self.labels();
3075            labels.first() == Some(&IndexLabel::Int64(start))
3076                && labels.last() == Some(&IndexLabel::Int64(last))
3077        };
3078        holds.then_some((start, stop, step))
3079    }
3080
3081    /// These labels marked as the pandas RangeIndex `span` (or unmarked);
3082    /// [`Self::range_span`] answers only while the labels hold it.
3083    #[must_use]
3084    pub fn with_range_span(mut self, span: Option<(i64, i64, i64)>) -> Self {
3085        self.range = span;
3086        self
3087    }
3088
3089    /// In place, [`Self::with_range_span`].
3090    pub fn set_range_span(&mut self, span: Option<(i64, i64, i64)>) {
3091        self.range = span;
3092    }
3093
3094    /// The `range(start, stop, step)` Int64 labels in one constant nonzero
3095    /// step (or none) are, the stop one step past the last label.
3096    #[must_use]
3097    pub fn int64_range_span(&self) -> Option<(i64, i64, i64)> {
3098        let (start, step) = self.int64_range_step()?;
3099        let stop = step.checked_mul(i64::try_from(self.len()).ok()?)?;
3100        Some((start, start.checked_add(stop)?, step))
3101    }
3102
3103    /// The RangeIndex that positions `start..stop` by `step` (as Python's
3104    /// `slice.indices(len)` resolves a slice) of this RangeIndex are, as
3105    /// Python slices a range: `range(4)[1::2]` is `range(1, 4, 2)`.
3106    #[must_use]
3107    pub fn sliced_range_span(&self, start: i64, stop: i64, step: i64) -> Option<(i64, i64, i64)> {
3108        let (first, _, by) = self.range_span()?;
3109        Some((
3110            first.checked_add(start.checked_mul(by)?)?,
3111            first.checked_add(stop.checked_mul(by)?)?,
3112            by.checked_mul(step)?,
3113        ))
3114    }
3115
3116    /// The (start, step) of Int64 labels in one constant nonzero step, as a
3117    /// RangeIndex holds them ((0, 1) for no labels, the label and 1 for one).
3118    #[must_use]
3119    pub fn int64_range_step(&self) -> Option<(i64, i64)> {
3120        // A lazy affine backing answers without materializing its labels.
3121        if let Some(affine) = self.labels.int64_affine_range() {
3122            let step = if affine.len > 1 { affine.step } else { 1 };
3123            return (step != 0).then_some((affine.start, step));
3124        }
3125        let labels = self.labels();
3126        let value = |label: &IndexLabel| match label {
3127            IndexLabel::Int64(value) => Some(*value),
3128            _ => None,
3129        };
3130        let Some(first) = labels.first() else {
3131            return Some((0, 1));
3132        };
3133        let start = value(first)?;
3134        let Some(second) = labels.get(1) else {
3135            return Some((start, 1));
3136        };
3137        let step = value(second)?.checked_sub(start)?;
3138        if step == 0 {
3139            return None;
3140        }
3141        let mut expected = start;
3142        for label in labels {
3143            if value(label)? != expected {
3144                return None;
3145            }
3146            expected = expected.checked_add(step).unwrap_or(expected);
3147        }
3148        Some((start, step))
3149    }
3150
3151    /// Internal: if both indexes share the same name, return it; otherwise None.
3152    /// Matches pandas behavior for binary set operations.
3153    fn shared_name(&self, other: &Self) -> Option<LabelName> {
3154        if self.name == other.name {
3155            self.name.clone()
3156        } else {
3157            None
3158        }
3159    }
3160
3161    #[must_use]
3162    pub fn has_duplicates(&self) -> bool {
3163        if self.labels.int64_affine_range().is_some() {
3164            return false;
3165        }
3166        *self.duplicate_cache.get_or_init(|| {
3167            // Every `SortOrder::Ascending*` variant is STRICTLY ascending
3168            // (`detect_sort_order` rejects equal neighbours with `a < b`), so a
3169            // recognized sort order proves uniqueness with zero hashing
3170            // (br-frankenpandas-idxdup). `sort_order()` is a single linear pass
3171            // (itself cached and reused by the binary-search backends), far
3172            // cheaper than the FxHashMap insert-per-label below; only genuinely
3173            // unsorted indexes fall through to it.
3174            if !matches!(self.sort_order(), SortOrder::Unsorted) {
3175                return false;
3176            }
3177            // Typed all-Int64 fast path: inline `i64` duplicate detection with
3178            // early exit instead of the pointer-keyed `FxHashMap<&IndexLabel>`.
3179            if let Some(vals) = self.labels.int64_view() {
3180                return Self::has_duplicates_i64(&vals);
3181            }
3182            detect_duplicates(self.labels())
3183        })
3184    }
3185
3186    /// Whether all index labels are unique.
3187    ///
3188    /// Matches `pd.Index.is_unique`.
3189    #[must_use]
3190    pub fn is_unique(&self) -> bool {
3191        !self.has_duplicates()
3192    }
3193
3194    /// Get the position (integer location) of a label.
3195    ///
3196    /// ⚠️ ONE position. `pd.Index.get_loc` returns THREE different types depending
3197    /// on the index, and this collapses all of them to the first-or-some match.
3198    /// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18):
3199    /// ```text
3200    ///   Index([10,20,30]).get_loc(20)     -> 1                        int
3201    ///   Index([10,20,20,30]).get_loc(20)  -> slice(1, 3)              the whole run
3202    ///   Index([20,10,20]).get_loc(20)     -> array([True,False,True]) a mask
3203    ///   Index([10,20]).get_loc(99)        -> KeyError
3204    /// ```
3205    /// So on a duplicate-bearing index this answers a strictly weaker question than
3206    /// pandas does. Use [`Self::get_loc_all`] when the index may hold duplicates;
3207    /// it returns the position SET, which is what all three pandas shapes encode.
3208    ///
3209    /// ⚠️ And on a SORTED duplicate run this is not even guaranteed to be the FIRST
3210    /// match: `position` reaches `binary_search`, which may land on any element of
3211    /// the run.
3212    #[must_use]
3213    pub fn get_loc(&self, label: &IndexLabel) -> Option<usize> {
3214        self.position(label)
3215    }
3216
3217    /// Every position at which `label` occurs, in index order.
3218    ///
3219    /// The duplicate-safe counterpart to [`Self::get_loc`]. pandas expresses this
3220    /// answer in three different return types — an int, a slice over the run, or a
3221    /// boolean mask — and all three encode the same position SET, which is what this
3222    /// returns. MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18):
3223    /// ```text
3224    ///   [10,20,30]      key 20  -> [1]        (pandas: 1)
3225    ///   [10,20,20,30]   key 20  -> [1, 2]     (pandas: slice(1, 3))
3226    ///   [20,10,20]      key 20  -> [0, 2]     (pandas: [True, False, True])
3227    ///   [10,20]         key 99  -> []         (pandas: KeyError)
3228    ///   [1.0,NaN,2.0,NaN] key NaN -> [1, 3]   (pandas: [False,True,False,True])
3229    /// ```
3230    /// A MISSING key is an empty Vec rather than an error, matching this crate's
3231    /// `Option`-returning `get_loc` rather than pandas' `KeyError`.
3232    ///
3233    /// NaN matches NaN because `OrderedF64` compares on a canonical bit pattern, so
3234    /// a NaN label is findable — as it is in pandas — even though `f64::NAN != f64::NAN`.
3235    ///
3236    /// ⚠️ O(n) BY CONSTRUCTION, and deliberately not routed through `position`'s
3237    /// optimized lookups: the affine-range, binary-search and cached-hash paths all
3238    /// answer with a SINGLE position and cannot enumerate a duplicate run. A faster
3239    /// implementation would need a label -> positions multimap, which nothing here
3240    /// builds today.
3241    #[must_use]
3242    pub fn get_loc_all(&self, label: &IndexLabel) -> Vec<usize> {
3243        self.labels()
3244            .iter()
3245            .enumerate()
3246            .filter(|(_, candidate)| *candidate == label)
3247            .map(|(position, _)| position)
3248            .collect()
3249    }
3250
3251    /// AG-13: Lazily detect and cache the sort order of this index.
3252    #[must_use]
3253    fn sort_order(&self) -> SortOrder {
3254        if self
3255            .labels
3256            .int64_affine_range()
3257            .is_some_and(|range| range.len <= 1 || range.step > 0)
3258        {
3259            return SortOrder::AscendingInt64;
3260        }
3261        *self.sort_order_cache.get_or_init(|| {
3262            if let Some(values) = self.labels.int64_view() {
3263                if values.len() <= 1 || values.windows(2).all(|pair| pair[0] < pair[1]) {
3264                    SortOrder::AscendingInt64
3265                } else {
3266                    SortOrder::Unsorted
3267                }
3268            } else if let Some(range) = self.labels.datetime64_affine_range() {
3269                if range.len <= 1 || range.step > 0 {
3270                    SortOrder::AscendingDatetime64
3271                } else {
3272                    SortOrder::Unsorted
3273                }
3274            } else {
3275                detect_sort_order(self.labels())
3276            }
3277        })
3278    }
3279
3280    /// Returns `true` if this index is sorted (strictly ascending, no duplicates).
3281    #[must_use]
3282    pub fn is_sorted(&self) -> bool {
3283        !matches!(self.sort_order(), SortOrder::Unsorted)
3284    }
3285
3286    /// AG-13: Adaptive position lookup.
3287    ///
3288    /// For sorted `Int64` or `Utf8` indexes, uses binary search (O(log n)).
3289    /// For unsorted indexes, falls back to linear scan (O(n)).
3290    #[must_use]
3291    pub fn position(&self, needle: &IndexLabel) -> Option<usize> {
3292        // An integral float key is the int it equals: the int paths below
3293        // match Int64 keys, and every other path compares by value
3294        // (br-frankenpandas-l5sed).
3295        let as_int;
3296        let needle = match (needle, needle.exact_int()) {
3297            (IndexLabel::Float64(_), Some(int)) => {
3298                as_int = IndexLabel::Int64(int);
3299                &as_int
3300            }
3301            _ => needle,
3302        };
3303        if let (Some(range), IndexLabel::Int64(target)) = (self.labels.int64_affine_range(), needle)
3304        {
3305            return range.position(*target);
3306        }
3307        if let (Some(range), IndexLabel::Datetime64(target)) =
3308            (self.labels.datetime64_affine_range(), needle)
3309        {
3310            return range.position(*target);
3311        }
3312        if self.labels.has_lazy_int64_backing() {
3313            let IndexLabel::Int64(target) = needle else {
3314                return None;
3315            };
3316            let values = self.labels.int64_view()?;
3317            return if matches!(self.sort_order(), SortOrder::AscendingInt64) {
3318                values.binary_search(target).ok()
3319            } else {
3320                int64_position_lookup_cached(self.label_identity, &values)
3321                    .get(target)
3322                    .copied()
3323            };
3324        }
3325        match self.sort_order() {
3326            SortOrder::AscendingInt64 => {
3327                if let IndexLabel::Int64(target) = needle {
3328                    self.labels
3329                        .binary_search_by(|label| {
3330                            if let IndexLabel::Int64(v) = label {
3331                                v.cmp(target)
3332                            } else {
3333                                std::cmp::Ordering::Less
3334                            }
3335                        })
3336                        .ok()
3337                } else {
3338                    None // Type mismatch: no Int64 label can match a Utf8 needle
3339                }
3340            }
3341            SortOrder::AscendingUtf8 => {
3342                if let IndexLabel::Utf8(target) = needle {
3343                    self.labels
3344                        .binary_search_by(|label| {
3345                            if let IndexLabel::Utf8(v) = label {
3346                                v.as_str().cmp(target.as_str())
3347                            } else {
3348                                std::cmp::Ordering::Less
3349                            }
3350                        })
3351                        .ok()
3352                } else {
3353                    None
3354                }
3355            }
3356            SortOrder::AscendingTimedelta64 => {
3357                if let IndexLabel::Timedelta64(target) = needle {
3358                    self.labels
3359                        .binary_search_by(|label| {
3360                            if let IndexLabel::Timedelta64(v) = label {
3361                                v.cmp(target)
3362                            } else {
3363                                std::cmp::Ordering::Less
3364                            }
3365                        })
3366                        .ok()
3367                } else {
3368                    None
3369                }
3370            }
3371            SortOrder::AscendingDatetime64 => {
3372                if let IndexLabel::Datetime64(target) = needle {
3373                    self.labels
3374                        .binary_search_by(|label| {
3375                            if let IndexLabel::Datetime64(v) = label {
3376                                v.cmp(target)
3377                            } else {
3378                                std::cmp::Ordering::Less
3379                            }
3380                        })
3381                        .ok()
3382                } else {
3383                    None
3384                }
3385            }
3386            SortOrder::Unsorted => self.labels.iter().position(|label| label == needle),
3387        }
3388    }
3389
3390    #[must_use]
3391    pub fn position_map_first(&self) -> HashMap<IndexLabel, usize> {
3392        let mut positions = HashMap::with_capacity(self.labels.len());
3393        for (idx, label) in self.labels.iter().enumerate() {
3394            positions.entry(label.clone()).or_insert(idx);
3395        }
3396        positions
3397    }
3398
3399    fn position_map_first_ref(&self) -> FxHashMap<&IndexLabel, usize> {
3400        let mut positions =
3401            FxHashMap::with_capacity_and_hasher(self.labels.len(), Default::default());
3402        for (idx, label) in self.labels.iter().enumerate() {
3403            positions.entry(label).or_insert(idx);
3404        }
3405        positions
3406    }
3407
3408    /// First-occurrence position of every `target` value within `haystack`,
3409    /// over raw `i64` keys. Bit-identical to the `FxHashMap<&IndexLabel>` probe
3410    /// (`position_map_first_ref` + `map.get`) for all-Int64 indexes — same
3411    /// first-occurrence semantics — but the keys are INLINE `i64` rather than
3412    /// pointers into the 32-byte `IndexLabel` enum vector, so each probe costs
3413    /// one cache miss instead of two (hashtable slot + pointer-chase into the
3414    /// label vector). A bounded value span uses a hash-free direct-address
3415    /// table; otherwise an inline-key `FxHashMap<i64, usize>`.
3416    fn get_indexer_i64(haystack: &[i64], target: &[i64]) -> Vec<Option<usize>> {
3417        // Dense direct-address gate (mirrors the groupby/value-counts dense
3418        // histogram cap): bounded span, ≤ 2^26 slots and ≤ 16× the key count.
3419        if !haystack.is_empty() {
3420            let mut min = haystack[0];
3421            let mut max = haystack[0];
3422            for &v in haystack {
3423                if v < min {
3424                    min = v;
3425                } else if v > max {
3426                    max = v;
3427                }
3428            }
3429            let span = (max as i128 - min as i128 + 1) as u128;
3430            if span <= (1u128 << 26) && span <= (haystack.len() as u128).saturating_mul(16) {
3431                let span = span as usize;
3432                let mut table = vec![usize::MAX; span];
3433                for (idx, &v) in haystack.iter().enumerate() {
3434                    let slot = (v as i128 - min as i128) as usize;
3435                    if table[slot] == usize::MAX {
3436                        table[slot] = idx;
3437                    }
3438                }
3439                return target
3440                    .iter()
3441                    .map(|&v| {
3442                        if v < min || v > max {
3443                            return None;
3444                        }
3445                        let slot = (v as i128 - min as i128) as usize;
3446                        let pos = table[slot];
3447                        (pos != usize::MAX).then_some(pos)
3448                    })
3449                    .collect();
3450            }
3451        }
3452
3453        let mut map: FxHashMap<i64, usize> =
3454            FxHashMap::with_capacity_and_hasher(haystack.len(), Default::default());
3455        for (idx, &v) in haystack.iter().enumerate() {
3456            map.entry(v).or_insert(idx);
3457        }
3458        target.iter().map(|&v| map.get(&v).copied()).collect()
3459    }
3460
3461    fn get_indexer_non_unique_sorted_dense_i64(
3462        source: &[i64],
3463        targets: &[i64],
3464    ) -> Option<(Vec<isize>, Vec<usize>)> {
3465        if !is_non_decreasing_i64(source) {
3466            return None;
3467        }
3468        let (min, span) = Self::i64_dense_span(source)?;
3469        let mut starts = vec![usize::MAX; span];
3470        let mut ends = vec![0usize; span];
3471        for (position, &label) in source.iter().enumerate() {
3472            let slot = (label as i128 - min as i128) as usize;
3473            if starts[slot] == usize::MAX {
3474                starts[slot] = position;
3475            }
3476            ends[slot] = position + 1;
3477        }
3478
3479        let mut indexer = Vec::with_capacity(targets.len());
3480        let mut missing = Vec::new();
3481        let span = span as i128;
3482        for (target_position, &label) in targets.iter().enumerate() {
3483            let offset = label as i128 - min as i128;
3484            if offset < 0 || offset >= span {
3485                indexer.push(-1);
3486                missing.push(target_position);
3487                continue;
3488            }
3489            let slot = offset as usize;
3490            let start = starts[slot];
3491            if start == usize::MAX {
3492                indexer.push(-1);
3493                missing.push(target_position);
3494                continue;
3495            }
3496            indexer.extend(
3497                (start..ends[slot]).map(|position| isize::try_from(position).unwrap_or(isize::MAX)),
3498            );
3499        }
3500        Some((indexer, missing))
3501    }
3502
3503    /// `(min, span)` of an `i64` slice when the span is dense enough for a
3504    /// direct-address bitset (≤ 2^26 slots and ≤ 16× the element count),
3505    /// else `None` (caller uses an inline-key hash set).
3506    fn i64_dense_span(vals: &[i64]) -> Option<(i64, usize)> {
3507        let first = *vals.first()?;
3508        let mut min = first;
3509        let mut max = first;
3510        for &v in vals {
3511            if v < min {
3512                min = v;
3513            } else if v > max {
3514                max = v;
3515            }
3516        }
3517        let span = (max as i128 - min as i128 + 1) as u128;
3518        if span <= (1u128 << 26) && span <= (vals.len() as u128).saturating_mul(16) {
3519            Some((min, span as usize))
3520        } else {
3521            None
3522        }
3523    }
3524
3525    /// Self-ordered, first-occurrence-deduplicated membership filter over raw
3526    /// `i64` keys: keep each `a` value whose presence in `b` equals
3527    /// `keep_present` (`true` ⇒ intersection, `false` ⇒ difference). Bit-
3528    /// identical to the `FxHashMap<&IndexLabel>` filter
3529    /// (`other.position_map_first_ref()` membership + a `seen` dedup) for
3530    /// all-Int64 indexes, but membership and dedup use INLINE `i64` keys —
3531    /// a dense bitset when the value span is bounded (the membership test then
3532    /// fits in L2: 1 bit/slot vs the 16-byte pointer-keyed map entry that also
3533    /// chases into the 32-byte enum vector), else an inline-key `FxHashSet<i64>`.
3534    /// Extract the raw ns vector when EVERY label is the requested temporal
3535    /// variant (`Datetime64` when `datetime`, else `Timedelta64`); `None` on the
3536    /// first mismatch OR an empty input (so a degenerate empty set-op keeps the
3537    /// generic fallback's dtype). Lets the temporal index reuse the i64 kernels
3538    /// (`membership_filter_i64` / `union_i64`) — Datetime64/Timedelta64 are
3539    /// ns-backed but `int64_view()` only matches `IndexLabel::Int64`, so without
3540    /// this they fall to the pointer-key `FxHashMap<&IndexLabel>` path.
3541    fn all_temporal_ns(labels: &[IndexLabel], datetime: bool) -> Option<Vec<i64>> {
3542        if labels.is_empty() {
3543            return None;
3544        }
3545        let mut out = Vec::with_capacity(labels.len());
3546        for label in labels {
3547            match (datetime, label) {
3548                (true, IndexLabel::Datetime64(ns)) | (false, IndexLabel::Timedelta64(ns)) => {
3549                    out.push(*ns);
3550                }
3551                _ => return None,
3552            }
3553        }
3554        Some(out)
3555    }
3556
3557    /// Like [`Self::all_temporal_ns`] but returns `None` if ANY label is NaT (the
3558    /// temporal missing sentinel). The dedup family (nunique / unique /
3559    /// duplicated / drop_duplicates) has per-op NaT semantics (dropna-exclude vs
3560    /// keep-one vs treat-as-value) that the generic fallback already encodes, so
3561    /// a NaT-bearing temporal index bails to it; a no-NaT index reuses the i64
3562    /// kernels, where a present timestamp behaves exactly like any other i64.
3563    fn temporal_ns_present(&self, datetime: bool) -> Option<Vec<i64>> {
3564        let labels = self.labels();
3565        if labels.is_empty() {
3566            return None;
3567        }
3568        let mut out = Vec::with_capacity(labels.len());
3569        for label in labels {
3570            match (datetime, label) {
3571                (true, IndexLabel::Datetime64(ns)) | (false, IndexLabel::Timedelta64(ns)) => {
3572                    if label.is_missing() {
3573                        return None;
3574                    }
3575                    out.push(*ns);
3576                }
3577                _ => return None,
3578            }
3579        }
3580        Some(out)
3581    }
3582
3583    fn membership_filter_i64(a: &[i64], b: &[i64], keep_present: bool) -> Vec<i64> {
3584        let mut out: Vec<i64> = Vec::new();
3585        if a.is_empty() {
3586            return out;
3587        }
3588        // `b` empty ⇒ nothing is present: intersection is empty, difference is
3589        // all of `a` (deduplicated, self order).
3590        if b.is_empty() && keep_present {
3591            return out;
3592        }
3593
3594        // Membership of `b`.
3595        let b_dense = Self::i64_dense_span(b);
3596        let (mut b_bits, mut b_hash) = (Vec::<u64>::new(), FxHashSet::<i64>::default());
3597        if let Some((bmin, bspan)) = b_dense {
3598            b_bits = vec![0u64; bspan.div_ceil(64)];
3599            for &v in b {
3600                let s = (v - bmin) as usize;
3601                b_bits[s >> 6] |= 1u64 << (s & 63);
3602            }
3603        } else {
3604            b_hash.reserve(b.len());
3605            for &v in b {
3606                b_hash.insert(v);
3607            }
3608        }
3609
3610        // First-occurrence dedup over the kept `a` values.
3611        let a_dense = Self::i64_dense_span(a);
3612        let mut seen_bits = Vec::<u64>::new();
3613        let mut seen_hash = FxHashSet::<i64>::default();
3614        if let Some((_, aspan)) = a_dense {
3615            seen_bits = vec![0u64; aspan.div_ceil(64)];
3616        }
3617
3618        for &v in a {
3619            let in_b = match b_dense {
3620                Some((bmin, bspan)) => {
3621                    let off = v as i128 - bmin as i128;
3622                    off >= 0 && (off as u128) < bspan as u128 && {
3623                        let s = off as usize;
3624                        (b_bits[s >> 6] >> (s & 63)) & 1 == 1
3625                    }
3626                }
3627                None => b_hash.contains(&v),
3628            };
3629            if in_b != keep_present {
3630                continue;
3631            }
3632            let fresh = match a_dense {
3633                Some((amin, _)) => {
3634                    let s = (v - amin) as usize;
3635                    let (w, bit) = (s >> 6, 1u64 << (s & 63));
3636                    let f = seen_bits[w] & bit == 0;
3637                    if f {
3638                        seen_bits[w] |= bit;
3639                    }
3640                    f
3641                }
3642                None => seen_hash.insert(v),
3643            };
3644            if fresh {
3645                out.push(v);
3646            }
3647        }
3648        out
3649    }
3650
3651    /// Multiset union over raw `i64` keys, matching `Index.union(sort=False)`:
3652    /// labels keep their first-seen order across `a` then `b`, while each label
3653    /// is emitted the maximum of its multiplicities in either input.
3654    fn union_i64(a: &[i64], b: &[i64]) -> Vec<i64> {
3655        // pandas preserves the left index's physical order when the right
3656        // operand is unique. Grouping the left counts by first-seen key would
3657        // turn `[3, 1, 3, 2].union([2, 4, 1], sort=False)` into
3658        // `[3, 3, 1, 2, 4]` instead of pandas' `[3, 1, 3, 2, 4]`.
3659        if !Self::has_duplicates_i64(b) {
3660            let mut out = a.to_vec();
3661            let mut seen = FxHashSet::<i64>::default();
3662            seen.reserve(combined_output_capacity(a.len(), b.len()));
3663            seen.extend(a.iter().copied());
3664            for &value in b {
3665                if seen.insert(value) {
3666                    out.push(value);
3667                }
3668            }
3669            return out;
3670        }
3671
3672        let mut counts = FxHashMap::<i64, (usize, usize)>::default();
3673        counts.reserve(combined_output_capacity(a.len(), b.len()));
3674        let mut order = Vec::with_capacity(combined_output_capacity(a.len(), b.len()));
3675
3676        for &value in a {
3677            let entry = counts.entry(value).or_insert((0, 0));
3678            if entry.0 == 0 && entry.1 == 0 {
3679                order.push(value);
3680            }
3681            entry.0 += 1;
3682        }
3683        for &value in b {
3684            let entry = counts.entry(value).or_insert((0, 0));
3685            if entry.0 == 0 && entry.1 == 0 {
3686                order.push(value);
3687            }
3688            entry.1 += 1;
3689        }
3690
3691        let mut out = Vec::with_capacity(combined_output_capacity(a.len(), b.len()));
3692        for value in order {
3693            let (left_count, right_count) = counts[&value];
3694            out.extend(std::iter::repeat_n(value, left_count.max(right_count)));
3695        }
3696        out
3697    }
3698
3699    /// Membership of each `haystack` value within `needles`, over raw `i64`
3700    /// keys (dense bitset when the needle span is bounded, else inline-key
3701    /// `FxHashSet<i64>`). Bit-identical to the `FxHashMap<&IndexLabel>`
3702    /// `set.contains_key` probe for all-Int64 inputs.
3703    fn isin_i64(haystack: &[i64], needles: &[i64]) -> Vec<bool> {
3704        if needles.is_empty() {
3705            return vec![false; haystack.len()];
3706        }
3707        match Self::i64_dense_span(needles) {
3708            Some((min, span)) => {
3709                let mut bits = vec![0u64; span.div_ceil(64)];
3710                for &v in needles {
3711                    let s = (v - min) as usize;
3712                    bits[s >> 6] |= 1u64 << (s & 63);
3713                }
3714                haystack
3715                    .iter()
3716                    .map(|&v| {
3717                        let off = v as i128 - min as i128;
3718                        off >= 0
3719                            && (off as u128) < span as u128
3720                            && (bits[(off as usize) >> 6] >> ((off as usize) & 63)) & 1 == 1
3721                    })
3722                    .collect()
3723            }
3724            None => {
3725                let set: FxHashSet<i64> = needles.iter().copied().collect();
3726                haystack.iter().map(|&v| set.contains(&v)).collect()
3727            }
3728        }
3729    }
3730
3731    /// Factorize raw `i64` keys: first-occurrence integer codes + the unique
3732    /// values in first-occurrence order. Bit-identical to the
3733    /// `FxHashMap<IndexLabel, isize>` path for all-Int64 indexes (which never
3734    /// have a missing label, so no `-1` codes), with inline `i64` keys — a dense
3735    /// direct-address code table when the value span is bounded, else an
3736    /// inline-key `FxHashMap<i64, isize>`.
3737    fn factorize_i64(vals: &[i64]) -> (Vec<isize>, Vec<i64>) {
3738        let mut codes = Vec::with_capacity(vals.len());
3739        let mut uniques = Vec::<i64>::new();
3740        match Self::i64_dense_span(vals) {
3741            Some((min, span)) => {
3742                // `-1` marks an unseen slot; assigned codes are always `>= 0`.
3743                let mut table = vec![-1isize; span];
3744                for &v in vals {
3745                    let s = (v - min) as usize;
3746                    let mut code = table[s];
3747                    if code == -1 {
3748                        code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
3749                        table[s] = code;
3750                        uniques.push(v);
3751                    }
3752                    codes.push(code);
3753                }
3754            }
3755            None => {
3756                let mut positions: FxHashMap<i64, isize> =
3757                    FxHashMap::with_capacity_and_hasher(vals.len(), Default::default());
3758                for &v in vals {
3759                    if let Some(&code) = positions.get(&v) {
3760                        codes.push(code);
3761                    } else {
3762                        let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
3763                        positions.insert(v, code);
3764                        uniques.push(v);
3765                        codes.push(code);
3766                    }
3767                }
3768            }
3769        }
3770        (codes, uniques)
3771    }
3772
3773    /// Stable ascending argsort over raw Int64 labels. Equivalent to sorting
3774    /// positions by `IndexLabel::Int64(value).cmp(...)`, but avoids enum
3775    /// materialization/comparison for indexes that already carry typed Int64
3776    /// backing. `sort_by_key` is stable, so duplicate labels keep their
3777    /// original order just like the generic `IndexLabel` comparator path.
3778    fn argsort_i64(vals: &[i64]) -> Vec<usize> {
3779        let mut indices: Vec<usize> = (0..vals.len()).collect();
3780        indices.sort_by_key(|&idx| vals[idx]);
3781        indices
3782    }
3783
3784    fn argsort_int64_affine(range: Int64AffineLabels) -> Vec<usize> {
3785        if range.len <= 1 || range.step > 0 {
3786            (0..range.len).collect()
3787        } else {
3788            (0..range.len).rev().collect()
3789        }
3790    }
3791
3792    /// Whether `vals` contains any duplicate, over raw `i64` keys with an
3793    /// early exit. Bit-identical to `detect_duplicates` for all-Int64 indexes,
3794    /// with inline keys (dense bitset when bounded, else `FxHashSet<i64>`).
3795    fn has_duplicates_i64(vals: &[i64]) -> bool {
3796        match Self::i64_dense_span(vals) {
3797            Some((min, span)) => {
3798                let mut bits = vec![0u64; span.div_ceil(64)];
3799                for &v in vals {
3800                    let s = (v - min) as usize;
3801                    let (w, bit) = (s >> 6, 1u64 << (s & 63));
3802                    if bits[w] & bit != 0 {
3803                        return true;
3804                    }
3805                    bits[w] |= bit;
3806                }
3807                false
3808            }
3809            None => {
3810                let mut seen: FxHashSet<i64> =
3811                    FxHashSet::with_capacity_and_hasher(vals.len(), Default::default());
3812                for &v in vals {
3813                    if !seen.insert(v) {
3814                        return true;
3815                    }
3816                }
3817                false
3818            }
3819        }
3820    }
3821
3822    /// First-occurrence-deduplicated unique values over raw `i64` keys, in
3823    /// input order. Bit-identical to the `FxHashMap<&IndexLabel>` first-seen
3824    /// filter for all-Int64 indexes, with inline `i64` dedup keys (dense bitset
3825    /// when bounded, else `FxHashSet<i64>`).
3826    fn unique_i64(vals: &[i64]) -> Vec<i64> {
3827        let mut out: Vec<i64> = Vec::new();
3828        let dense = Self::i64_dense_span(vals);
3829        let mut seen_bits = Vec::<u64>::new();
3830        let mut seen_hash = FxHashSet::<i64>::default();
3831        if let Some((_, span)) = dense {
3832            seen_bits = vec![0u64; span.div_ceil(64)];
3833        } else {
3834            seen_hash.reserve(vals.len());
3835        }
3836        for &v in vals {
3837            let fresh = match dense {
3838                Some((min, _)) => {
3839                    let s = (v - min) as usize;
3840                    let (w, bit) = (s >> 6, 1u64 << (s & 63));
3841                    let f = seen_bits[w] & bit == 0;
3842                    if f {
3843                        seen_bits[w] |= bit;
3844                    }
3845                    f
3846                }
3847                None => seen_hash.insert(v),
3848            };
3849            if fresh {
3850                out.push(v);
3851            }
3852        }
3853        out
3854    }
3855
3856    /// Count distinct raw `i64` labels without constructing owned
3857    /// `IndexLabel::Int64` uniques. Int64 labels are never missing, so this is
3858    /// valid for both `dropna` modes.
3859    fn nunique_i64(vals: &[i64]) -> usize {
3860        let dense = Self::i64_dense_span(vals);
3861        match dense {
3862            Some((min, span)) => {
3863                let mut seen_bits = vec![0u64; span.div_ceil(64)];
3864                let mut count = 0usize;
3865                for &v in vals {
3866                    let s = (v - min) as usize;
3867                    let (w, bit) = (s >> 6, 1u64 << (s & 63));
3868                    if seen_bits[w] & bit == 0 {
3869                        seen_bits[w] |= bit;
3870                        count += 1;
3871                    }
3872                }
3873                count
3874            }
3875            None => {
3876                let mut seen =
3877                    FxHashSet::<i64>::with_capacity_and_hasher(vals.len(), Default::default());
3878                for &v in vals {
3879                    seen.insert(v);
3880                }
3881                seen.len()
3882            }
3883        }
3884    }
3885
3886    /// `duplicated` mask over raw `i64` keys — bit-identical to the
3887    /// `FxHashMap<&IndexLabel>` path for all-Int64 indexes, with inline `i64`
3888    /// keys (dense bitsets when the value span is bounded, else hash sets).
3889    /// Every label's canonical float bits spread
3890    /// ([`fp_types::spread_float_bits`]) as an i64 key when every label is a
3891    /// Float64: bijective, so equal keys are exactly equal labels (-0.0 as
3892    /// 0.0, NaN as NaN), for the i64 duplicate masks. None for any other
3893    /// label (br-frankenpandas-bss5q.3).
3894    fn float_label_keys(&self) -> Option<Vec<i64>> {
3895        self.labels
3896            .iter()
3897            .map(|label| match label {
3898                IndexLabel::Float64(value) => {
3899                    Some(fp_types::spread_float_bits(value.canonical_bits()) as i64)
3900                }
3901                _ => None,
3902            })
3903            .collect()
3904    }
3905
3906    fn duplicated_i64(vals: &[i64], keep: DuplicateKeep) -> Vec<bool> {
3907        let n = vals.len();
3908        let mut result = vec![false; n];
3909        let dense = Self::i64_dense_span(vals);
3910        match keep {
3911            DuplicateKeep::First | DuplicateKeep::Last => {
3912                let mut seen_bits = Vec::<u64>::new();
3913                let mut seen_hash = FxHashSet::<i64>::default();
3914                if let Some((_, span)) = dense {
3915                    seen_bits = vec![0u64; span.div_ceil(64)];
3916                } else {
3917                    seen_hash.reserve(n);
3918                }
3919                let mut mark = |i: usize| {
3920                    let v = vals[i];
3921                    let fresh = match dense {
3922                        Some((min, _)) => {
3923                            let s = (v - min) as usize;
3924                            let (w, bit) = (s >> 6, 1u64 << (s & 63));
3925                            let f = seen_bits[w] & bit == 0;
3926                            if f {
3927                                seen_bits[w] |= bit;
3928                            }
3929                            f
3930                        }
3931                        None => seen_hash.insert(v),
3932                    };
3933                    if !fresh {
3934                        result[i] = true;
3935                    }
3936                };
3937                if matches!(keep, DuplicateKeep::First) {
3938                    for i in 0..n {
3939                        mark(i);
3940                    }
3941                } else {
3942                    for i in (0..n).rev() {
3943                        mark(i);
3944                    }
3945                }
3946            }
3947            DuplicateKeep::None => {
3948                // Two-bitset (seen / seen-again) ⇒ `result[i] = count > 1`.
3949                match dense {
3950                    Some((min, span)) => {
3951                        let words = span.div_ceil(64);
3952                        let mut seen = vec![0u64; words];
3953                        let mut dup = vec![0u64; words];
3954                        for &v in vals {
3955                            let s = (v - min) as usize;
3956                            let (w, bit) = (s >> 6, 1u64 << (s & 63));
3957                            if seen[w] & bit == 0 {
3958                                seen[w] |= bit;
3959                            } else {
3960                                dup[w] |= bit;
3961                            }
3962                        }
3963                        for (i, &v) in vals.iter().enumerate() {
3964                            let s = (v - min) as usize;
3965                            result[i] = (dup[s >> 6] >> (s & 63)) & 1 == 1;
3966                        }
3967                    }
3968                    None => {
3969                        let mut counts: FxHashMap<i64, u32> =
3970                            FxHashMap::with_capacity_and_hasher(n, Default::default());
3971                        for &v in vals {
3972                            *counts.entry(v).or_insert(0) += 1;
3973                        }
3974                        for (i, &v) in vals.iter().enumerate() {
3975                            result[i] = counts[&v] > 1;
3976                        }
3977                    }
3978                }
3979            }
3980        }
3981        result
3982    }
3983
3984    // ── Pandas Index Model: lookup and membership ──────────────────────
3985
3986    #[must_use]
3987    pub fn contains(&self, label: &IndexLabel) -> bool {
3988        self.position(label).is_some()
3989    }
3990
3991    #[must_use]
3992    pub fn get_indexer(&self, target: &Index) -> Vec<Option<usize>> {
3993        // An affine Int64 source can answer every lookup from its arithmetic
3994        // witness.  Keep the target typed as well: materializing the source to
3995        // an `Arc<Vec<i64>>` solely to reject a miss-heavy target made this
3996        // otherwise O(m) operation pay an avoidable O(n) allocation and scan.
3997        if let Some(source) = self.labels.int64_affine_range() {
3998            return target.labels.affine_int64_indexer(source);
3999        }
4000        // When `self` is strictly ascending (any SortOrder::Ascending* ⟹
4001        // globally IndexLabel::Ord-sorted and unique) we can resolve target
4002        // positions without building the O(n) FxHashMap of `self`
4003        // (br-frankenpandas-idxdup):
4004        //   * target also sorted  ⇒ one two-pointer merge, O(n+m), no hashing;
4005        //   * target unsorted     ⇒ binary-search each label, O(m log n).
4006        // Both yield the same first-occurrence position the hash path returns
4007        // (uniqueness makes "first" the only one); unsorted `self` keeps the
4008        // hash path so a per-label scan never degrades to O(n·m).
4009        if !matches!(self.sort_order(), SortOrder::Unsorted) {
4010            if let (Some(labels), Some(targets)) =
4011                (self.labels.int64_view(), target.labels.int64_view())
4012            {
4013                if !matches!(target.sort_order(), SortOrder::Unsorted) {
4014                    let mut out = Vec::with_capacity(targets.len());
4015                    let mut i = 0usize;
4016                    for &target in targets.iter() {
4017                        while i < labels.len() && labels[i] < target {
4018                            i += 1;
4019                        }
4020                        if i < labels.len() && labels[i] == target {
4021                            out.push(Some(i));
4022                        } else {
4023                            out.push(None);
4024                        }
4025                    }
4026                    return out;
4027                }
4028                return targets
4029                    .iter()
4030                    .map(|target| labels.binary_search(target).ok())
4031                    .collect();
4032            }
4033            let labels = self.labels();
4034            let targets = target.labels();
4035            if !matches!(target.sort_order(), SortOrder::Unsorted) {
4036                let mut out = Vec::with_capacity(targets.len());
4037                let mut i = 0usize;
4038                for label in targets {
4039                    while i < labels.len() && labels[i] < *label {
4040                        i += 1;
4041                    }
4042                    if i < labels.len() && labels[i] == *label {
4043                        out.push(Some(i));
4044                    } else {
4045                        out.push(None);
4046                    }
4047                }
4048                return out;
4049            }
4050            return targets.iter().map(|label| self.position(label)).collect();
4051        }
4052        // Typed all-Int64 fast path: probe over raw `i64` keys (inline, one
4053        // cache miss per lookup) instead of the `FxHashMap<&IndexLabel>` whose
4054        // pointer keys force a second cache miss chasing into the 32-byte enum
4055        // label vector — the dominant cost of unsorted Int64 get_indexer
4056        // (~14× slower than pandas' inline-key khash). Bit-identical: same
4057        // first-occurrence position per target label.
4058        if let (Some(self_i64), Some(target_i64)) =
4059            (self.labels.int64_view(), target.labels.int64_view())
4060        {
4061            // Unsorted UNIQUE Int64 self: reuse the identity-cached i64->pos
4062            // map so repeated reindex/align/join don't rebuild it every call
4063            // (pandas caches its int64 engine). Bit-identical first-occurrence;
4064            // a duplicate self returns None and keeps the per-call builder.
4065            if let Some(resolved) = self.unsorted_unique_int64_positions(target.labels()) {
4066                return resolved;
4067            }
4068            return Self::get_indexer_i64(&self_i64, &target_i64);
4069        }
4070        // Unsorted UNIQUE non-Int64 self: route through the identity-cached
4071        // position lookups (the loc batch resolvers) so repeated
4072        // reindex/align/join against the same index don't rebuild the
4073        // pointer-key `FxHashMap<&IndexLabel, usize>` each call — pandas caches
4074        // its index engine for exactly this repeated-alignment pattern.
4075        // Bit-identical: get_indexer self is unique, so first-occurrence ==
4076        // only-occurrence == `position_map_first_ref().get()`; a duplicate or
4077        // non-Utf8/non-Datetime self returns `None` from the resolvers and
4078        // falls through to the unchanged map path.
4079        if let Some(resolved) = self.unique_utf8_positions(target.labels()) {
4080            return resolved;
4081        }
4082        if let Some(resolved) = self.unique_datetime64_positions(target.labels()) {
4083            return resolved;
4084        }
4085        if let Some(resolved) = self.unique_timedelta64_positions(target.labels()) {
4086            return resolved;
4087        }
4088        let map = self.position_map_first_ref();
4089        target
4090            .labels
4091            .iter()
4092            .map(|label| map.get(label).copied())
4093            .collect()
4094    }
4095
4096    /// Resolve a list-like label selector against a strictly ascending all-Int64
4097    /// index without building the duplicate-expansion map.
4098    ///
4099    /// `SortOrder::AscendingInt64` is strict, so the index is unique and each
4100    /// requested label can yield at most one position. Missing requested
4101    /// labels, or ones equal to no int (an integral Float64 is its int), are
4102    /// represented as `None`; callers preserve their own
4103    /// fail-closed error surface. Returns `None` only when this index is not a
4104    /// sorted unique Int64 index and the duplicate-aware fallback must run.
4105    #[must_use]
4106    #[doc(hidden)]
4107    pub fn sorted_unique_int64_positions(
4108        &self,
4109        labels: &[IndexLabel],
4110    ) -> Option<Vec<Option<usize>>> {
4111        if !matches!(self.sort_order(), SortOrder::AscendingInt64) {
4112            return None;
4113        }
4114        let values = self.labels.int64_view()?;
4115        // An integral Float64 selector is the int it equals (l5sed).
4116        Some(
4117            labels
4118                .iter()
4119                .map(|label| {
4120                    label
4121                        .exact_int()
4122                        .and_then(|value| values.binary_search(&value).ok())
4123                })
4124                .collect(),
4125        )
4126    }
4127
4128    /// Resolve a list-like selector against an UNSORTED unique all-Int64 index
4129    /// using a first-occurrence `i64 -> position` hashtable cached by the
4130    /// index's runtime label identity, instead of rebuilding the per-call
4131    /// pointer-key `FxHashMap<&IndexLabel, Vec<usize>>` over the whole index.
4132    ///
4133    /// Returns `None` (so the caller keeps its duplicate-aware fallback) when
4134    /// the index is strictly-ascending Int64 (use
4135    /// [`Self::sorted_unique_int64_positions`]), has duplicate labels (pandas
4136    /// returns every match, which needs the multimap), or is not all-Int64.
4137    /// The index is unique here, so each requested label yields at most one
4138    /// position; missing selectors, or ones equal to no int (an integral
4139    /// Float64 is its int), map to `None` and callers preserve their own
4140    /// fail-closed error surface.
4141    /// Each of `targets`' position in these unique int labels (a typed
4142    /// backing's), through the lookup kept per label identity - built once
4143    /// for this index, as pandas keeps its engine - None for labels that are
4144    /// not unique ints held typed (br-frankenpandas-mcq15).
4145    #[must_use]
4146    #[doc(hidden)]
4147    pub fn unique_int64_positions_of(&self, targets: &[i64]) -> Option<Vec<Option<usize>>> {
4148        if !self.labels.has_lazy_int64_backing() || self.has_duplicates() {
4149            return None;
4150        }
4151        let values = self.labels.int64_view()?;
4152        let lookup = int64_position_lookup_cached(self.label_identity, &values);
4153        Some(
4154            targets
4155                .iter()
4156                .map(|value| lookup.get(value).copied())
4157                .collect(),
4158        )
4159    }
4160
4161    #[must_use]
4162    #[doc(hidden)]
4163    pub fn unsorted_unique_int64_positions(
4164        &self,
4165        labels: &[IndexLabel],
4166    ) -> Option<Vec<Option<usize>>> {
4167        if matches!(self.sort_order(), SortOrder::AscendingInt64) {
4168            return None;
4169        }
4170        if self.has_duplicates() {
4171            return None;
4172        }
4173        let values = self.labels.int64_view()?;
4174        let lookup = int64_position_lookup_cached(self.label_identity, &values);
4175        // An integral Float64 selector is the int it equals (l5sed).
4176        Some(
4177            labels
4178                .iter()
4179                .map(|label| {
4180                    label
4181                        .exact_int()
4182                        .and_then(|value| lookup.get(&value).copied())
4183                })
4184                .collect(),
4185        )
4186    }
4187
4188    /// Resolve a list-like selector against a unique all-Utf8 index using a
4189    /// first-occurrence `String -> position` hashtable cached by the index's
4190    /// runtime label identity, instead of rebuilding the per-call pointer-key
4191    /// `FxHashMap<&IndexLabel, Vec<usize>>` over the whole index.
4192    ///
4193    /// Returns `None` (caller keeps its duplicate-aware fallback) when the index
4194    /// has duplicate labels (pandas returns every match) or is not entirely
4195    /// Utf8. The index is unique here, so each requested label yields at most
4196    /// one position; missing or non-Utf8 selectors map to `None` and callers
4197    /// preserve their own fail-closed error surface.
4198    #[must_use]
4199    #[doc(hidden)]
4200    pub fn unique_utf8_positions(&self, labels: &[IndexLabel]) -> Option<Vec<Option<usize>>> {
4201        if self.has_duplicates() {
4202            return None;
4203        }
4204        let lookup = utf8_position_lookup_cached(self.label_identity, self.labels())?;
4205        Some(
4206            labels
4207                .iter()
4208                .map(|label| match label {
4209                    IndexLabel::Utf8(value) => lookup.get(value.as_str()).copied(),
4210                    _ => None,
4211                })
4212                .collect(),
4213        )
4214    }
4215
4216    /// Resolve a list-like selector against a unique all-Datetime64 index using
4217    /// a first-occurrence ns->position hashtable cached by the index's runtime
4218    /// label identity, instead of rebuilding the per-call pointer-key
4219    /// `FxHashMap<&IndexLabel, Vec<usize>>`. This is the time-series `loc[[ts]]`
4220    /// fast path.
4221    ///
4222    /// Returns `None` (caller keeps its duplicate-aware fallback) when the index
4223    /// has duplicate labels or is not entirely Datetime64. The index is unique
4224    /// here, so each requested label yields at most one position; missing or
4225    /// non-Datetime64 selectors map to `None` and callers preserve their own
4226    /// fail-closed error surface.
4227    #[must_use]
4228    #[doc(hidden)]
4229    pub fn unique_datetime64_positions(&self, labels: &[IndexLabel]) -> Option<Vec<Option<usize>>> {
4230        if self.has_duplicates() {
4231            return None;
4232        }
4233        let lookup = datetime64_position_lookup_cached(self.label_identity, self.labels())?;
4234        Some(
4235            labels
4236                .iter()
4237                .map(|label| match label {
4238                    IndexLabel::Datetime64(ns) => lookup.get(ns).copied(),
4239                    _ => None,
4240                })
4241                .collect(),
4242        )
4243    }
4244
4245    /// Resolve a list-like selector against a unique all-Timedelta64 index using
4246    /// a first-occurrence ns->position hashtable cached by the index's runtime
4247    /// label identity — the `loc[[td]]` fast path for a TimedeltaIndex. Exact
4248    /// sibling of [`Self::unique_datetime64_positions`] (the deferred mirror of
4249    /// the Datetime64 batch resolver). Returns `None` (caller keeps its
4250    /// duplicate-aware pointer-key fallback) when the index has duplicates or is
4251    /// not entirely Timedelta64; the index is unique here, so each requested
4252    /// label yields at most one position and a missing/non-Timedelta64 selector
4253    /// maps to `None`.
4254    #[must_use]
4255    #[doc(hidden)]
4256    pub fn unique_timedelta64_positions(
4257        &self,
4258        labels: &[IndexLabel],
4259    ) -> Option<Vec<Option<usize>>> {
4260        if self.has_duplicates() {
4261            return None;
4262        }
4263        let lookup = timedelta64_position_lookup_cached(self.label_identity, self.labels())?;
4264        Some(
4265            labels
4266                .iter()
4267                .map(|label| match label {
4268                    IndexLabel::Timedelta64(ns) => lookup.get(ns).copied(),
4269                    _ => None,
4270                })
4271                .collect(),
4272        )
4273    }
4274
4275    #[must_use]
4276    pub fn isin(&self, values: &[IndexLabel]) -> Vec<bool> {
4277        // Typed all-Int64 fast path: probe over raw `i64` keys. An all-Int64
4278        // index matches the needles that equal an int - an Int64, or an
4279        // integral Float64 (labels compare numbers by value; l5sed) - so the
4280        // others are dropped without changing membership, bit-identical to
4281        // the pointer-keyed `FxHashMap` probe but without the per-label
4282        // enum-pointer cache miss.
4283        if let Some(self_i64) = self.labels.int64_view() {
4284            let needles: Vec<i64> = values.iter().filter_map(IndexLabel::exact_int).collect();
4285            return Self::isin_i64(&self_i64, &needles);
4286        }
4287        let set: FxHashMap<&IndexLabel, ()> = values.iter().map(|v| (v, ())).collect();
4288        self.labels.iter().map(|l| set.contains_key(l)).collect()
4289    }
4290
4291    // ── Pandas Index Model: deduplication ──────────────────────────────
4292
4293    #[must_use]
4294    pub fn is_monotonic_increasing(&self) -> bool {
4295        *self.monotonic_cache[0].get_or_init(|| self.labels_ascend())
4296    }
4297
4298    fn labels_ascend(&self) -> bool {
4299        if let Some(answer) = self
4300            .labels
4301            .held()
4302            .and_then(held_datetimes_monotonic::<true>)
4303        {
4304            // An ascent read every label as a datetime, none NaT: those are
4305            // the label kinds, kept for the next asker (a resampler's axis
4306            // check scanned them again on a fresh index).
4307            if answer && !self.labels.is_empty() {
4308                self.remember_label_kinds(LabelKinds::DATETIME64);
4309            }
4310            return answer;
4311        }
4312        if self.labels.has_datetime64_nat() {
4313            return false;
4314        }
4315        if self.labels.len() <= 1 {
4316            return true;
4317        }
4318        // Affine Int64 backings (RangeIndex / unit / affine) are monotonic by
4319        // construction: ascending iff the step is non-negative. O(1), no
4320        // IndexLabel materialization (br-frankenpandas-k9tlb vein).
4321        if let Some(affine) = self.labels.int64_affine_range() {
4322            return affine.step >= 0;
4323        }
4324        // Datetime64 affine backings carry the same validated `(start, step,
4325        // len)` witness. IndexLabel::Datetime64 ordering compares the raw
4326        // nanoseconds, so the step sign is exactly the former label-window
4327        // result without materializing any labels. Keep NaT-bearing ranges on
4328        // the existing fallback because i64::MIN is the reserved NaT sentinel.
4329        if let Some(affine) = self.labels.datetime64_affine_range()
4330            && affine.position(i64::MIN).is_none()
4331        {
4332            return affine.step >= 0;
4333        }
4334        // Typed non-affine Int64: scan the i64 view instead of the wider
4335        // IndexLabel window, so we never materialize the label vector. All-Int64
4336        // backings carry no missing labels and IndexLabel::Int64 Ord matches i64
4337        // Ord, so this is bit-identical to the fallback.
4338        if let Some(values) = self.labels.int64_view() {
4339            return values.windows(2).all(|pair| pair[0] <= pair[1]);
4340        }
4341        for pair in self.labels.windows(2) {
4342            if pair[0] > pair[1] {
4343                return false;
4344            }
4345        }
4346        true
4347    }
4348
4349    /// Alias for is_monotonic_increasing.
4350    #[must_use]
4351    pub fn is_monotonic(&self) -> bool {
4352        self.is_monotonic_increasing()
4353    }
4354
4355    #[must_use]
4356    pub fn is_monotonic_decreasing(&self) -> bool {
4357        *self.monotonic_cache[1].get_or_init(|| self.labels_descend())
4358    }
4359
4360    fn labels_descend(&self) -> bool {
4361        if let Some(answer) = self
4362            .labels
4363            .held()
4364            .and_then(held_datetimes_monotonic::<false>)
4365        {
4366            return answer;
4367        }
4368        if self.labels.has_datetime64_nat() {
4369            return false;
4370        }
4371        if self.labels.len() <= 1 {
4372            return true;
4373        }
4374        // Affine Int64 backings are monotonic by construction: descending iff the
4375        // step is non-positive. O(1), no IndexLabel materialization
4376        // (br-frankenpandas-k9tlb vein).
4377        if let Some(affine) = self.labels.int64_affine_range() {
4378            return affine.step <= 0;
4379        }
4380        if let Some(affine) = self.labels.datetime64_affine_range()
4381            && affine.position(i64::MIN).is_none()
4382        {
4383            return affine.step <= 0;
4384        }
4385        // Typed non-affine Int64: scan the i64 view (no label materialization),
4386        // bit-identical to the IndexLabel fallback for all-Int64 backings.
4387        if let Some(values) = self.labels.int64_view() {
4388            return values.windows(2).all(|pair| pair[0] >= pair[1]);
4389        }
4390        for pair in self.labels.windows(2) {
4391            if pair[0] < pair[1] {
4392                return false;
4393            }
4394        }
4395        true
4396    }
4397
4398    #[must_use]
4399    pub fn unique(&self) -> Self {
4400        // A strictly-ascending index (every recognized SortOrder) is already
4401        // all-unique in first-seen order, so unique() is an identity — return an
4402        // O(1) Arc-sharing clone instead of hashing every label and rebuilding
4403        // the vector (br-frankenpandas-idxdup dedup family).
4404        if !matches!(self.sort_order(), SortOrder::Unsorted) {
4405            return self.clone();
4406        }
4407        // Typed all-Int64 fast path: inline `i64` first-occurrence dedup instead
4408        // of the pointer-keyed `FxHashMap<&IndexLabel>`. Bit-identical order.
4409        if let Some(vals) = self.labels.int64_view() {
4410            return self.propagate_name(Self::from_i64_values(Self::unique_i64(&vals)));
4411        }
4412        // Datetime64 / Timedelta64 (no NaT): inline-i64 first-occurrence dedup via
4413        // unique_i64, rebuilt with the temporal dtype (unique over a DatetimeIndex
4414        // was 0.49x pandas). NaT bails to the pointer-key path (which keeps the
4415        // one NaT). Bit-identical: same first-occurrence ns order and dtype.
4416        if let Some(ns) = self.temporal_ns_present(true) {
4417            return self.propagate_name(Self::from_datetime64(Self::unique_i64(&ns)));
4418        }
4419        if let Some(ns) = self.temporal_ns_present(false) {
4420            return self.propagate_name(Self::from_timedelta64(Self::unique_i64(&ns)));
4421        }
4422        // Float64 labels: the first of each through the i64 mask over their
4423        // keys ([`Self::float_label_keys`]).
4424        if let Some(keys) = self.float_label_keys() {
4425            let repeats = Self::duplicated_i64(&keys, DuplicateKeep::First);
4426            let labels: Vec<IndexLabel> = self
4427                .labels
4428                .iter()
4429                .zip(repeats)
4430                .filter(|(_, repeat)| !repeat)
4431                .map(|(label, _)| label.clone())
4432                .collect();
4433            return self.propagate_name(Self::new(labels));
4434        }
4435        let mut seen = FxHashMap::<&IndexLabel, ()>::default();
4436        let labels: Vec<IndexLabel> = self
4437            .labels
4438            .iter()
4439            .filter(|l| seen.insert(l, ()).is_none())
4440            .cloned()
4441            .collect();
4442        self.propagate_name(Self::new(labels))
4443    }
4444
4445    #[must_use]
4446    pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
4447        let mut result = vec![false; self.labels.len()];
4448        // Strictly-ascending => no duplicates under any keep mode; skip hashing.
4449        if !matches!(self.sort_order(), SortOrder::Unsorted) {
4450            return result;
4451        }
4452        // Typed all-Int64 fast path: inline `i64` keys (dense bitsets when the
4453        // value span is bounded) instead of the pointer-keyed
4454        // `FxHashMap<&IndexLabel>`. Bit-identical mask per keep mode.
4455        if let Some(vals) = self.labels.int64_view() {
4456            return Self::duplicated_i64(&vals, keep);
4457        }
4458        // Datetime64 / Timedelta64 (no NaT): inline-i64 duplicate mask via
4459        // duplicated_i64 instead of the pointer-key FxHashMap (duplicated over a
4460        // DatetimeIndex was 0.66x pandas). NaT bails to the per-keep fallback.
4461        // Bit-identical: present timestamps mask exactly like any i64.
4462        if let Some(ns) = self
4463            .temporal_ns_present(true)
4464            .or_else(|| self.temporal_ns_present(false))
4465        {
4466            return Self::duplicated_i64(&ns, keep);
4467        }
4468        // Float64 labels through the i64 mask over their keys
4469        // ([`Self::float_label_keys`]): the label map was 0.54x pandas.
4470        if let Some(keys) = self.float_label_keys() {
4471            return Self::duplicated_i64(&keys, keep);
4472        }
4473        match keep {
4474            DuplicateKeep::First => {
4475                let mut seen = FxHashMap::<&IndexLabel, ()>::default();
4476                for (i, label) in self.labels.iter().enumerate() {
4477                    if seen.insert(label, ()).is_some() {
4478                        result[i] = true;
4479                    }
4480                }
4481            }
4482            DuplicateKeep::Last => {
4483                let mut seen = FxHashMap::<&IndexLabel, ()>::default();
4484                for (i, label) in self.labels.iter().enumerate().rev() {
4485                    if seen.insert(label, ()).is_some() {
4486                        result[i] = true;
4487                    }
4488                }
4489            }
4490            DuplicateKeep::None => {
4491                let mut counts = FxHashMap::<&IndexLabel, usize>::default();
4492                for label in &self.labels {
4493                    *counts.entry(label).or_insert(0) += 1;
4494                }
4495                for (i, label) in self.labels.iter().enumerate() {
4496                    if counts[label] > 1 {
4497                        result[i] = true;
4498                    }
4499                }
4500            }
4501        }
4502        result
4503    }
4504
4505    #[must_use]
4506    pub fn drop_duplicates(&self) -> Self {
4507        self.drop_duplicates_keep(DuplicateKeep::First)
4508    }
4509
4510    /// Drop duplicated labels with explicit keep behavior.
4511    ///
4512    /// Matches `pd.Index.drop_duplicates(keep=...)`.
4513    #[must_use]
4514    pub fn drop_duplicates_keep(&self, keep: DuplicateKeep) -> Self {
4515        // Strictly-ascending => nothing is dropped; O(1) Arc-sharing clone.
4516        if !matches!(self.sort_order(), SortOrder::Unsorted) {
4517            return self.clone();
4518        }
4519        if let Some(values) = self.labels.int64_view() {
4520            let duplicated = Self::duplicated_i64(&values, keep);
4521            let labels = values
4522                .iter()
4523                .copied()
4524                .zip(duplicated)
4525                .filter_map(|(value, is_duplicated)| (!is_duplicated).then_some(value))
4526                .collect();
4527            return self.propagate_name(Self::from_i64_values(labels));
4528        }
4529        // Datetime64 / Timedelta64 (no NaT): inline-i64 keep-mask filter, rebuilt
4530        // with the temporal dtype (drop_duplicates over a DatetimeIndex was 0.69x
4531        // pandas). NaT bails to the generic path. Bit-identical: same kept
4532        // first/last occurrences in self order.
4533        for datetime in [true, false] {
4534            if let Some(values) = self.temporal_ns_present(datetime) {
4535                let duplicated = Self::duplicated_i64(&values, keep);
4536                let labels: Vec<i64> = values
4537                    .iter()
4538                    .copied()
4539                    .zip(duplicated)
4540                    .filter_map(|(value, is_duplicated)| (!is_duplicated).then_some(value))
4541                    .collect();
4542                let result = if datetime {
4543                    Self::from_datetime64(labels)
4544                } else {
4545                    Self::from_timedelta64(labels)
4546                };
4547                return self.propagate_name(result);
4548            }
4549        }
4550        let duplicated = self.duplicated(keep);
4551        let labels = self
4552            .labels
4553            .iter()
4554            .zip(duplicated)
4555            .filter(|(_, is_duplicated)| !is_duplicated)
4556            .map(|(label, _)| label.clone())
4557            .collect();
4558        self.propagate_name(Self::new(labels))
4559    }
4560
4561    // ── Pandas Index Model: set operations ─────────────────────────────
4562
4563    #[must_use]
4564    pub fn intersection(&self, other: &Self) -> Self {
4565        // Both strictly ascending (every SortOrder::Ascending* is globally
4566        // IndexLabel::Ord-sorted and unique) => a two-pointer merge yields the
4567        // same self-ordered, deduplicated intersection without building either
4568        // FxHashMap (br-frankenpandas-idxdup set ops).
4569        if let Some(labels) = self.sorted_merge_set_op_i64(other, SetMergeKind::Intersection) {
4570            let mut result = Self::from_i64_values(labels);
4571            result.name = self.shared_name(other);
4572            result.tz = joined_tz(self, other);
4573            return result;
4574        }
4575        if let Some(labels) = self.sorted_merge_set_op(other, SetMergeKind::Intersection) {
4576            let mut result = Self::new(labels);
4577            result.name = self.shared_name(other);
4578            result.tz = joined_tz(self, other);
4579            return result;
4580        }
4581        // Typed all-Int64 fast path: inline `i64` membership + dedup instead of
4582        // the pointer-keyed `FxHashMap<&IndexLabel>` (whose probes chase into
4583        // the enum vector — ~9× slower than pandas at 1M). Bit-identical:
4584        // self-order, first-occurrence dedup, same matched labels.
4585        if let (Some(a_i64), Some(b_i64)) = (self.labels.int64_view(), other.labels.int64_view()) {
4586            let mut result =
4587                Self::from_i64_values(Self::membership_filter_i64(&a_i64, &b_i64, true));
4588            result.name = self.shared_name(other);
4589            result.tz = joined_tz(self, other);
4590            return result;
4591        }
4592        // Datetime64 / Timedelta64 i64-keyed intersection (unsorted temporal
4593        // indexes miss the sorted-merge path and int64_view's Int64-only gate, so
4594        // they fell to the pointer-key FxHashMap — intersection over an UNSORTED
4595        // DatetimeIndex was 0.37x pandas). Reuse membership_filter_i64 over the ns
4596        // and rebuild the temporal dtype. Bit-identical: same self-order
4597        // first-occurrence kept-present labels, inline i64 keys.
4598        if let (Some(a_ns), Some(b_ns)) = (
4599            Self::all_temporal_ns(self.labels(), true),
4600            Self::all_temporal_ns(other.labels(), true),
4601        ) {
4602            let mut result = Self::from_datetime64(Self::membership_filter_i64(&a_ns, &b_ns, true));
4603            result.name = self.shared_name(other);
4604            result.tz = joined_tz(self, other);
4605            return result;
4606        }
4607        if let (Some(a_ns), Some(b_ns)) = (
4608            Self::all_temporal_ns(self.labels(), false),
4609            Self::all_temporal_ns(other.labels(), false),
4610        ) {
4611            let mut result =
4612                Self::from_timedelta64(Self::membership_filter_i64(&a_ns, &b_ns, true));
4613            result.name = self.shared_name(other);
4614            result.tz = joined_tz(self, other);
4615            return result;
4616        }
4617        // Typed all-Utf8 fast path (Utf8 sibling of membership_filter_i64): both
4618        // sides are pure `IndexLabel::Utf8` (no Null), so hash `&str` directly
4619        // (skipping the FxHashMap<&IndexLabel> enum load) AND dedup via a "matched"
4620        // flag stored IN the other-map, eliminating the separate `seen` set — one
4621        // hash map instead of two (~40% fewer string-hash probes). Bit-identical to
4622        // the generic path: same self-order, first-occurrence dedup (a self label
4623        // present in other emits once, then its map flag suppresses repeats), same
4624        // matched labels. The all-Utf8 gate (no Null) is what makes skipping the
4625        // `&IndexLabel` keys safe — the generic path would otherwise also match a
4626        // Null self label against a Null in other.
4627        let self_labels = self.labels();
4628        let other_labels = other.labels();
4629        if self_labels.iter().all(|l| matches!(l, IndexLabel::Utf8(_)))
4630            && other_labels
4631                .iter()
4632                .all(|l| matches!(l, IndexLabel::Utf8(_)))
4633        {
4634            let mut b_matched: FxHashMap<&str, bool> = FxHashMap::default();
4635            b_matched.reserve(other_labels.len());
4636            for label in other_labels {
4637                if let IndexLabel::Utf8(s) = label {
4638                    b_matched.entry(s.as_str()).or_insert(false);
4639                }
4640            }
4641            let mut labels: Vec<IndexLabel> = Vec::new();
4642            for label in self_labels {
4643                if let IndexLabel::Utf8(s) = label
4644                    && let Some(matched) = b_matched.get_mut(s.as_str())
4645                    && !*matched
4646                {
4647                    *matched = true;
4648                    labels.push(label.clone());
4649                }
4650            }
4651            let mut result = Self::new(labels);
4652            result.name = self.shared_name(other);
4653            result.tz = joined_tz(self, other);
4654            return result;
4655        }
4656        let other_set = other.position_map_first_ref();
4657        let mut seen = FxHashMap::<&IndexLabel, ()>::default();
4658        let labels: Vec<IndexLabel> = self
4659            .labels
4660            .iter()
4661            .filter(|l| other_set.contains_key(l) && seen.insert(l, ()).is_none())
4662            .cloned()
4663            .collect();
4664        let mut result = Self::new(labels);
4665        result.name = self.shared_name(other);
4666        result.tz = joined_tz(self, other);
4667        result
4668    }
4669
4670    /// Hash-free two-pointer set merge for two strictly-ascending (hence
4671    /// `IndexLabel::Ord`-sorted and unique) indexes; returns `None` when either
4672    /// side is unsorted so the caller keeps its FxHashMap path. Emits labels in
4673    /// `self`'s order, which equals the sorted order on the fast path — exactly
4674    /// what the hash path's `self`-iteration-order filter produces.
4675    fn sorted_merge_set_op_i64(&self, other: &Self, kind: SetMergeKind) -> Option<Vec<i64>> {
4676        if !matches!(self.sort_order(), SortOrder::AscendingInt64)
4677            || !matches!(other.sort_order(), SortOrder::AscendingInt64)
4678        {
4679            return None;
4680        }
4681        let a = self.labels.int64_view()?;
4682        let b = other.labels.int64_view()?;
4683        let mut labels = Vec::with_capacity(a.len().min(b.len()));
4684        let (mut i, mut j) = (0usize, 0usize);
4685        while i < a.len() {
4686            if j >= b.len() {
4687                if kind == SetMergeKind::Difference {
4688                    labels.extend_from_slice(&a[i..]);
4689                }
4690                break;
4691            }
4692            match a[i].cmp(&b[j]) {
4693                std::cmp::Ordering::Less => {
4694                    if kind == SetMergeKind::Difference {
4695                        labels.push(a[i]);
4696                    }
4697                    i += 1;
4698                }
4699                std::cmp::Ordering::Greater => j += 1,
4700                std::cmp::Ordering::Equal => {
4701                    if kind == SetMergeKind::Intersection {
4702                        labels.push(a[i]);
4703                    }
4704                    i += 1;
4705                    j += 1;
4706                }
4707            }
4708        }
4709        Some(labels)
4710    }
4711
4712    fn sorted_merge_set_op(&self, other: &Self, kind: SetMergeKind) -> Option<Vec<IndexLabel>> {
4713        if matches!(self.sort_order(), SortOrder::Unsorted)
4714            || matches!(other.sort_order(), SortOrder::Unsorted)
4715        {
4716            return None;
4717        }
4718        let a = self.labels();
4719        let b = other.labels();
4720        let mut labels = Vec::with_capacity(a.len().min(b.len()));
4721        let (mut i, mut j) = (0usize, 0usize);
4722        while i < a.len() {
4723            if j >= b.len() {
4724                if kind == SetMergeKind::Difference {
4725                    labels.extend_from_slice(&a[i..]);
4726                }
4727                break;
4728            }
4729            match a[i].cmp(&b[j]) {
4730                std::cmp::Ordering::Less => {
4731                    if kind == SetMergeKind::Difference {
4732                        labels.push(a[i].clone());
4733                    }
4734                    i += 1;
4735                }
4736                std::cmp::Ordering::Greater => j += 1,
4737                std::cmp::Ordering::Equal => {
4738                    if kind == SetMergeKind::Intersection {
4739                        labels.push(a[i].clone());
4740                    }
4741                    i += 1;
4742                    j += 1;
4743                }
4744            }
4745        }
4746        Some(labels)
4747    }
4748
4749    #[must_use]
4750    pub fn union_with(&self, other: &Self) -> Self {
4751        // Typed all-Int64 fast path: inline `i64` multiplicity accounting instead
4752        // of enum-keyed maps. It retains pandas' first-seen label ordering while
4753        // preserving each label's maximum count across the two inputs.
4754        if let (Some(a_i64), Some(b_i64)) = (self.labels.int64_view(), other.labels.int64_view()) {
4755            let mut result = Self::from_i64_values(Self::union_i64(&a_i64, &b_i64));
4756            result.name = self.shared_name(other);
4757            result.tz = joined_tz(self, other);
4758            return result;
4759        }
4760        let self_labels = self.labels();
4761        let other_labels = other.labels();
4762        // Datetime64 / Timedelta64 are ns-backed, so reuse the typed i64 multiset
4763        // union and rebuild the matching temporal dtype. Empty inputs return None
4764        // so the degenerate empty-union dtype stays the generic fallback's.
4765        let temporal_ns = |labels: &[IndexLabel], datetime: bool| -> Option<Vec<i64>> {
4766            if labels.is_empty() {
4767                return None;
4768            }
4769            let mut out = Vec::with_capacity(labels.len());
4770            for label in labels {
4771                match (datetime, label) {
4772                    (true, IndexLabel::Datetime64(ns)) | (false, IndexLabel::Timedelta64(ns)) => {
4773                        out.push(*ns);
4774                    }
4775                    _ => return None,
4776                }
4777            }
4778            Some(out)
4779        };
4780        if let (Some(a_ns), Some(b_ns)) = (
4781            temporal_ns(self_labels, true),
4782            temporal_ns(other_labels, true),
4783        ) {
4784            let mut result = Self::from_datetime64(Self::union_i64(&a_ns, &b_ns));
4785            result.name = self.shared_name(other);
4786            result.tz = joined_tz(self, other);
4787            return result;
4788        }
4789        if let (Some(a_ns), Some(b_ns)) = (
4790            temporal_ns(self_labels, false),
4791            temporal_ns(other_labels, false),
4792        ) {
4793            let mut result = Self::from_timedelta64(Self::union_i64(&a_ns, &b_ns));
4794            result.name = self.shared_name(other);
4795            result.tz = joined_tz(self, other);
4796            return result;
4797        }
4798        if other.is_unique() {
4799            let mut labels = self_labels.to_vec();
4800            let mut seen = FxHashSet::<&IndexLabel>::default();
4801            seen.reserve(combined_output_capacity(
4802                self_labels.len(),
4803                other_labels.len(),
4804            ));
4805            seen.extend(self_labels.iter());
4806            for label in other_labels {
4807                if seen.insert(label) {
4808                    labels.push(label.clone());
4809                }
4810            }
4811            let mut result = Self::new(labels);
4812            result.name = self.shared_name(other);
4813            result.tz = joined_tz(self, other);
4814            return result;
4815        }
4816        let mut counts = FxHashMap::<&IndexLabel, (usize, usize)>::default();
4817        counts.reserve(combined_output_capacity(
4818            self.labels.len(),
4819            other.labels.len(),
4820        ));
4821        let mut order = Vec::with_capacity(combined_output_capacity(
4822            self.labels.len(),
4823            other.labels.len(),
4824        ));
4825        for label in &self.labels {
4826            let entry = counts.entry(label).or_insert((0, 0));
4827            if entry.0 == 0 && entry.1 == 0 {
4828                order.push(label);
4829            }
4830            entry.0 += 1;
4831        }
4832        for label in &other.labels {
4833            let entry = counts.entry(label).or_insert((0, 0));
4834            if entry.0 == 0 && entry.1 == 0 {
4835                order.push(label);
4836            }
4837            entry.1 += 1;
4838        }
4839        let mut labels = Vec::with_capacity(combined_output_capacity(
4840            self.labels.len(),
4841            other.labels.len(),
4842        ));
4843        for label in order {
4844            let (left_count, right_count) = counts[label];
4845            labels.extend(std::iter::repeat_n(
4846                label.clone(),
4847                left_count.max(right_count),
4848            ));
4849        }
4850        let mut result = Self::new(labels);
4851        result.name = self.shared_name(other);
4852        result.tz = joined_tz(self, other);
4853        result
4854    }
4855
4856    #[must_use]
4857    pub fn difference(&self, other: &Self) -> Self {
4858        // Two-pointer merge when both sides are strictly ascending (see
4859        // intersection / sorted_merge_set_op).
4860        if let Some(labels) = self.sorted_merge_set_op_i64(other, SetMergeKind::Difference) {
4861            return self.propagate_name(Self::from_i64_values(labels));
4862        }
4863        if let Some(labels) = self.sorted_merge_set_op(other, SetMergeKind::Difference) {
4864            return self.propagate_name(Self::new(labels));
4865        }
4866        // Typed all-Int64 fast path: inline `i64` membership (keep absent) +
4867        // dedup instead of the pointer-keyed `FxHashMap<&IndexLabel>`.
4868        // Bit-identical: self-order, first-occurrence dedup, labels not in other.
4869        if let (Some(a_i64), Some(b_i64)) = (self.labels.int64_view(), other.labels.int64_view()) {
4870            return self.propagate_name(Self::from_i64_values(Self::membership_filter_i64(
4871                &a_i64, &b_i64, false,
4872            )));
4873        }
4874        // Datetime64 / Timedelta64 i64-keyed difference (unsorted temporal indexes
4875        // miss sorted-merge + the Int64-only int64_view, so they hit the
4876        // pointer-key map — difference over an UNSORTED DatetimeIndex was 0.57x
4877        // pandas). Reuse membership_filter_i64(keep_present=false). Bit-identical:
4878        // self-order, labels not in other, first-occurrence dedup, inline i64 keys.
4879        if let (Some(a_ns), Some(b_ns)) = (
4880            Self::all_temporal_ns(self.labels(), true),
4881            Self::all_temporal_ns(other.labels(), true),
4882        ) {
4883            return self.propagate_name(Self::from_datetime64(Self::membership_filter_i64(
4884                &a_ns, &b_ns, false,
4885            )));
4886        }
4887        if let (Some(a_ns), Some(b_ns)) = (
4888            Self::all_temporal_ns(self.labels(), false),
4889            Self::all_temporal_ns(other.labels(), false),
4890        ) {
4891            return self.propagate_name(Self::from_timedelta64(Self::membership_filter_i64(
4892                &a_ns, &b_ns, false,
4893            )));
4894        }
4895        // Typed all-Utf8 fast path: ONE FxHashMap<&str,()> seeded with other's
4896        // labels doubles as membership AND self-dedup — `insert(s).is_none()` is
4897        // true only when s is neither in other nor already emitted, so there is no
4898        // separate `seen` set (one map instead of two). Bit-identical: self-order,
4899        // labels not in other, first-occurrence dedup. The all-Utf8 gate (no Null)
4900        // makes &str keys safe.
4901        let self_labels = self.labels();
4902        let other_labels = other.labels();
4903        if self_labels.iter().all(|l| matches!(l, IndexLabel::Utf8(_)))
4904            && other_labels
4905                .iter()
4906                .all(|l| matches!(l, IndexLabel::Utf8(_)))
4907        {
4908            let mut set: FxHashMap<&str, ()> = FxHashMap::default();
4909            set.reserve(other_labels.len());
4910            for label in other_labels {
4911                if let IndexLabel::Utf8(s) = label {
4912                    set.insert(s.as_str(), ());
4913                }
4914            }
4915            let mut labels: Vec<IndexLabel> = Vec::new();
4916            for label in self_labels {
4917                if let IndexLabel::Utf8(s) = label
4918                    && set.insert(s.as_str(), ()).is_none()
4919                {
4920                    labels.push(label.clone());
4921                }
4922            }
4923            return self.propagate_name(Self::new(labels));
4924        }
4925        let other_set = other.position_map_first_ref();
4926        let mut seen = FxHashMap::<&IndexLabel, ()>::default();
4927        let labels: Vec<IndexLabel> = self
4928            .labels
4929            .iter()
4930            .filter(|l| !other_set.contains_key(l) && seen.insert(l, ()).is_none())
4931            .cloned()
4932            .collect();
4933        self.propagate_name(Self::new(labels))
4934    }
4935
4936    #[must_use]
4937    pub fn symmetric_difference(&self, other: &Self) -> Self {
4938        // Typed all-Int64 fast path: the two halves (self-not-in-other,
4939        // other-not-in-self) are disjoint by construction, so the original
4940        // shared `seen` only ever dedups WITHIN a half — exactly what two
4941        // independent `membership_filter_i64(.., keep_present=false)` calls do,
4942        // with inline `i64` keys instead of the pointer-keyed `FxHashMap`.
4943        if let (Some(a_i64), Some(b_i64)) = (self.labels.int64_view(), other.labels.int64_view()) {
4944            let mut labels = Self::membership_filter_i64(&a_i64, &b_i64, false);
4945            labels.extend(Self::membership_filter_i64(&b_i64, &a_i64, false));
4946            let mut result = Self::from_i64_values(labels);
4947            result.name = self.shared_name(other);
4948            result.tz = joined_tz(self, other);
4949            return result;
4950        }
4951        // Datetime64 / Timedelta64 i64-keyed symmetric_difference (unsorted
4952        // temporal indexes hit the pointer-key map — symdiff over an UNSORTED
4953        // DatetimeIndex was 0.48x pandas). The two halves are disjoint, so two
4954        // independent membership_filter_i64(keep_present=false) calls reproduce
4955        // the shared-`seen` within-half dedup. Bit-identical: self-not-in-other
4956        // then other-not-in-self, inline i64 keys.
4957        if let (Some(a_ns), Some(b_ns)) = (
4958            Self::all_temporal_ns(self.labels(), true),
4959            Self::all_temporal_ns(other.labels(), true),
4960        ) {
4961            let mut labels = Self::membership_filter_i64(&a_ns, &b_ns, false);
4962            labels.extend(Self::membership_filter_i64(&b_ns, &a_ns, false));
4963            let mut result = Self::from_datetime64(labels);
4964            result.name = self.shared_name(other);
4965            result.tz = joined_tz(self, other);
4966            return result;
4967        }
4968        if let (Some(a_ns), Some(b_ns)) = (
4969            Self::all_temporal_ns(self.labels(), false),
4970            Self::all_temporal_ns(other.labels(), false),
4971        ) {
4972            let mut labels = Self::membership_filter_i64(&a_ns, &b_ns, false);
4973            labels.extend(Self::membership_filter_i64(&b_ns, &a_ns, false));
4974            let mut result = Self::from_timedelta64(labels);
4975            result.name = self.shared_name(other);
4976            result.tz = joined_tz(self, other);
4977            return result;
4978        }
4979        // Typed all-Utf8 fast path: the two halves are disjoint, so the shared
4980        // `seen` only ever dedups WITHIN a half. Build self_set/other_set as
4981        // FxHashMap<&str,()> and let each membership map ALSO carry its half's
4982        // dedup: for the self-half, `other_set.insert(s).is_none()` is true only
4983        // when s is not in other and not yet emitted; symmetrically for the
4984        // other-half via self_set. Drops the separate `seen` map (3 maps -> 2) and
4985        // hashes &str. Bit-identical: self-then-other order, label not in the
4986        // opposite side, first-occurrence dedup within each half.
4987        let self_labels = self.labels();
4988        let other_labels = other.labels();
4989        if self_labels.iter().all(|l| matches!(l, IndexLabel::Utf8(_)))
4990            && other_labels
4991                .iter()
4992                .all(|l| matches!(l, IndexLabel::Utf8(_)))
4993        {
4994            let mut self_set: FxHashMap<&str, ()> = FxHashMap::default();
4995            self_set.reserve(self_labels.len());
4996            for label in self_labels {
4997                if let IndexLabel::Utf8(s) = label {
4998                    self_set.insert(s.as_str(), ());
4999                }
5000            }
5001            let mut other_set: FxHashMap<&str, ()> = FxHashMap::default();
5002            other_set.reserve(other_labels.len());
5003            for label in other_labels {
5004                if let IndexLabel::Utf8(s) = label {
5005                    other_set.insert(s.as_str(), ());
5006                }
5007            }
5008            let mut labels: Vec<IndexLabel> = Vec::new();
5009            for label in self_labels {
5010                if let IndexLabel::Utf8(s) = label
5011                    && other_set.insert(s.as_str(), ()).is_none()
5012                {
5013                    labels.push(label.clone());
5014                }
5015            }
5016            for label in other_labels {
5017                if let IndexLabel::Utf8(s) = label
5018                    && self_set.insert(s.as_str(), ()).is_none()
5019                {
5020                    labels.push(label.clone());
5021                }
5022            }
5023            let mut result = Self::new(labels);
5024            result.name = self.shared_name(other);
5025            result.tz = joined_tz(self, other);
5026            return result;
5027        }
5028        let self_set = self.position_map_first_ref();
5029        let other_set = other.position_map_first_ref();
5030        let mut seen = FxHashMap::<&IndexLabel, ()>::default();
5031        let mut labels = Vec::new();
5032        for label in &self.labels {
5033            if !other_set.contains_key(label) && seen.insert(label, ()).is_none() {
5034                labels.push(label.clone());
5035            }
5036        }
5037        for label in &other.labels {
5038            if !self_set.contains_key(label) && seen.insert(label, ()).is_none() {
5039                labels.push(label.clone());
5040            }
5041        }
5042        let mut result = Self::new(labels);
5043        result.name = self.shared_name(other);
5044        result.tz = joined_tz(self, other);
5045        result
5046    }
5047
5048    // ── Pandas Index Model: ordering and slicing ───────────────────────
5049
5050    #[must_use]
5051    pub fn argsort(&self) -> Vec<usize> {
5052        if let Some(range) = self.labels.int64_affine_range() {
5053            return Self::argsort_int64_affine(range);
5054        }
5055        if let Some(vals) = self.labels.int64_view() {
5056            return Self::argsort_i64(&vals);
5057        }
5058        // Datetime64 / Timedelta64: radix/stable-key argsort over the raw ns
5059        // instead of the comparison sort that derefs into the IndexLabel vector
5060        // per compare (argsort over a DatetimeIndex was 0.57x pandas). Bit-
5061        // identical: IndexLabel derives Ord so Datetime64/Timedelta64 order by
5062        // their inner i64 (NaT == i64::MIN sorts first in BOTH paths), and both
5063        // argsort_i64 (sort_by_key) and the fallback (sort_by) are STABLE, so
5064        // duplicate-timestamp ties keep input order identically.
5065        if let Some(ns) = Self::all_temporal_ns(self.labels(), true)
5066            .or_else(|| Self::all_temporal_ns(self.labels(), false))
5067        {
5068            return Self::argsort_i64(&ns);
5069        }
5070        let mut indices: Vec<usize> = (0..self.labels.len()).collect();
5071        indices.sort_by(|&a, &b| self.labels[a].cmp(&self.labels[b]));
5072        indices
5073    }
5074
5075    #[must_use]
5076    pub fn sort_values(&self) -> Self {
5077        if let Some(range) = self.labels.int64_affine_range() {
5078            if range.len <= 1 || range.step > 0 {
5079                return self.clone();
5080            }
5081            if let Ok(last_offset) = i64::try_from(range.len - 1)
5082                && let Some(delta) = range.step.checked_mul(last_offset)
5083                && let Some(start) = range.start.checked_add(delta)
5084                && let Some(step) = range.step.checked_neg()
5085                && let Some(sorted) =
5086                    Self::new_known_unique_int64_affine_range(start, step, range.len)
5087            {
5088                return self.propagate_name(sorted);
5089            }
5090        }
5091        if let Some(vals) = self.labels.int64_view() {
5092            let order = Self::argsort_i64(&vals);
5093            let sorted = order.iter().map(|&idx| vals[idx]).collect();
5094            return self.propagate_name(Self::from_i64_values(sorted));
5095        }
5096        // Datetime64 / Timedelta64: stable i64 argsort + gather, rebuilt with the
5097        // temporal dtype (sort_values over a DatetimeIndex was 0.58x pandas).
5098        // Bit-identical to the comparison-sort fallback (see argsort).
5099        if let Some(ns) = Self::all_temporal_ns(self.labels(), true) {
5100            let order = Self::argsort_i64(&ns);
5101            let sorted = order.iter().map(|&idx| ns[idx]).collect();
5102            return self.propagate_name(Self::from_datetime64(sorted));
5103        }
5104        if let Some(ns) = Self::all_temporal_ns(self.labels(), false) {
5105            let order = Self::argsort_i64(&ns);
5106            let sorted = order.iter().map(|&idx| ns[idx]).collect();
5107            return self.propagate_name(Self::from_timedelta64(sorted));
5108        }
5109        let order = self.argsort();
5110        self.propagate_name(Self::new(
5111            order.iter().map(|&i| self.labels[i].clone()).collect(),
5112        ))
5113    }
5114
5115    /// Select labels by position, carrying the row `MultiIndex` levels (taken at
5116    /// the same positions) when the index has them.
5117    #[must_use]
5118    pub fn take(&self, indices: &[usize]) -> Self {
5119        let mut taken = self.take_labels(indices);
5120        // A run of consecutive positions is a slice: it keeps the freq, as
5121        // pandas' getitem keeps it for a slice or a mask selecting a run
5122        // (pandas' take keeps a steady step too: see `take_freq`).
5123        if !indices.is_empty() && indices.windows(2).all(|pair| pair[1] == pair[0] + 1) {
5124            taken.freq.clone_from(&self.freq);
5125        }
5126        match self
5127            .row_multiindex
5128            .as_deref()
5129            .map(|levels| levels.take(indices))
5130        {
5131            Some(Ok(levels)) => taken.attach_row_multiindex(levels),
5132            _ => taken,
5133        }
5134    }
5135
5136    fn take_labels(&self, indices: &[usize]) -> Self {
5137        // Affine-in, affine-out fast path (br-frankenpandas, BlackThrush): when the
5138        // backing is an Int64 affine range AND the requested positions are
5139        // themselves arithmetic (constant stride), the gathered labels are
5140        // `start + step*pos` evaluated at an arithmetic position sequence — which
5141        // is again an affine range with `label_step = step * position_step`. A
5142        // single O(len) stride-verification pass (no `Vec<i64>` materialization,
5143        // no per-element gather + index rebuild — the dominant cost in the
5144        // `affine_index_take` hot loop, ~1.5x slower than pandas' numpy gather)
5145        // yields a lazy affine index in O(1). Mirrors `RangeIndex::take_
5146        // arithmetic_positions`. Bit-transparent: produces the identical labels in
5147        // the identical order as the materialize-then-rebuild path below; out-of-
5148        // bounds or non-arithmetic positions return `None` and fall through to it.
5149        if let Some(idx) = self.take_affine_positions(indices) {
5150            return idx;
5151        }
5152        if let Some(values) = self.labels.take_i64_values(indices) {
5153            return self.propagate_name(Self::from_i64_values(values));
5154        }
5155        self.propagate_name(Self::new(
5156            indices.iter().map(|&i| self.labels[i].clone()).collect(),
5157        ))
5158    }
5159
5160    /// Lazy affine result for an affine-backed index taken at arithmetic
5161    /// positions. Returns `None` (caller falls back to the materializing path)
5162    /// when the backing is not an Int64 affine range, the positions are not a
5163    /// constant-stride sequence, any position is out of bounds, or the resulting
5164    /// affine parameters overflow `i64`.
5165    fn take_affine_positions(&self, positions: &[usize]) -> Option<Self> {
5166        let affine = self.labels.int64_affine_range()?;
5167        let len = affine.len;
5168        let value_at = |p: usize| -> Option<i64> {
5169            let offset = i64::try_from(p).ok()?;
5170            affine
5171                .step
5172                .checked_mul(offset)
5173                .and_then(|delta| affine.start.checked_add(delta))
5174        };
5175        let result = match positions {
5176            [] => Index::new_known_unique_int64_affine_range(affine.start, affine.step, 0)?,
5177            &[p] => {
5178                if p >= len {
5179                    return None;
5180                }
5181                Index::new_known_unique_int64_affine_range(value_at(p)?, affine.step, 1)?
5182            }
5183            &[first, second, ..] => {
5184                if first >= len {
5185                    return None;
5186                }
5187                // `i64` (not `i128`) stride arithmetic: every position is a valid
5188                // index `< len <= isize::MAX`, so the difference of any two fits
5189                // `i64` without overflow — and the `i64` windows scan autovectorizes
5190                // where the `i128` form could not (the hot loop of this fast path).
5191                let position_step = second as i64 - first as i64;
5192                if position_step == 0 {
5193                    return None;
5194                }
5195                // Single pass: verify the constant position stride. Because the
5196                // sequence is monotone with that stride, all positions lie in
5197                // `[min(first,last), max(first,last)]`, so a single endpoint
5198                // bounds check below suffices.
5199                if !positions
5200                    .windows(2)
5201                    .all(|w| w[1] as i64 - w[0] as i64 == position_step)
5202                {
5203                    return None;
5204                }
5205                let last = *positions.last().expect("non-empty by match arm");
5206                if first.max(last) >= len {
5207                    return None;
5208                }
5209                let label_step = affine.step.checked_mul(position_step)?;
5210                let first_label = value_at(first)?;
5211                Index::new_known_unique_int64_affine_range(
5212                    first_label,
5213                    label_step,
5214                    positions.len(),
5215                )?
5216            }
5217        };
5218        Some(self.propagate_name(result))
5219    }
5220
5221    #[must_use]
5222    pub fn slice(&self, start: usize, len: usize) -> Self {
5223        let mut sliced = self.propagate_name(Self {
5224            labels: self.labels.slice(start, len),
5225            name: None,
5226            label_identity: next_index_label_identity(),
5227            duplicate_cache: OnceLock::new(),
5228            sort_order_cache: OnceLock::new(),
5229            monotonic_cache: Default::default(),
5230            semantic_fingerprint_cache: OnceLock::new(),
5231            row_multiindex: None,
5232            tz: None,
5233            freq: None,
5234            range: None,
5235            declared: None,
5236            categories: None,
5237        });
5238        sliced.freq.clone_from(&self.freq);
5239        // A slice of a RangeIndex is one (pandas).
5240        if self.range.is_some() {
5241            let first = start.min(self.len());
5242            sliced.range = i64::try_from(first).ok().and_then(|first| {
5243                let stop = first.checked_add(i64::try_from(sliced.len()).ok()?)?;
5244                self.sliced_range_span(first, stop, 1)
5245            });
5246        }
5247        let Some(levels) = self.row_multiindex.as_deref() else {
5248            return sliced;
5249        };
5250        let positions: Vec<usize> = (start..start.saturating_add(sliced.len())).collect();
5251        match levels.take(&positions) {
5252            Ok(levels) => sliced.attach_row_multiindex(levels),
5253            Err(_) => sliced,
5254        }
5255    }
5256
5257    /// Attach the levels of the row `MultiIndex` whose flattened labels this
5258    /// index holds, one level tuple per label, in label order. The caller
5259    /// vouches that label `i` is the flat form of tuple `i`; the heights must
5260    /// match.
5261    pub fn with_row_multiindex(self, levels: MultiIndex) -> Result<Self, IndexError> {
5262        if levels.len() != self.len() {
5263            return Err(IndexError::LengthMismatch {
5264                expected: self.len(),
5265                actual: levels.len(),
5266                context: "row MultiIndex height vs index length".to_owned(),
5267            });
5268        }
5269        Ok(self.attach_row_multiindex(levels))
5270    }
5271
5272    fn attach_row_multiindex(mut self, levels: MultiIndex) -> Self {
5273        self.row_multiindex = Some(Arc::new(levels));
5274        self
5275    }
5276
5277    /// The row `MultiIndex` levels these flat labels stand for, when attached
5278    /// (see [`Self::with_row_multiindex`]).
5279    #[must_use]
5280    pub fn row_multiindex(&self) -> Option<&MultiIndex> {
5281        self.row_multiindex.as_deref()
5282    }
5283
5284    #[must_use]
5285    pub fn from_range(start: i64, stop: i64, step: i64) -> Self {
5286        let len = if step > 0 {
5287            if start >= stop {
5288                Some(0_i128)
5289            } else {
5290                let distance = stop as i128 - start as i128;
5291                let step = step as i128;
5292                Some((distance + step - 1) / step)
5293            }
5294        } else if step < 0 {
5295            if start <= stop {
5296                Some(0_i128)
5297            } else {
5298                let distance = start as i128 - stop as i128;
5299                let step = -(step as i128);
5300                Some((distance + step - 1) / step)
5301            }
5302        } else {
5303            Some(0_i128)
5304        };
5305        if let Some(len) = len.and_then(|value| usize::try_from(value).ok())
5306            && let Some(mut index) = Self::new_known_unique_int64_affine_range(start, step, len)
5307        {
5308            // Known to be a range: marked without reading the lazy labels.
5309            index.range = (step != 0).then_some((start, stop, step));
5310            return index;
5311        }
5312
5313        let mut labels = Vec::new();
5314        let mut val = start;
5315        if step > 0 {
5316            while val < stop {
5317                labels.push(IndexLabel::Int64(val));
5318                val += step;
5319            }
5320        } else if step < 0 {
5321            while val > stop {
5322                labels.push(IndexLabel::Int64(val));
5323                val += step;
5324            }
5325        }
5326        Self::new(labels).with_range_span((step != 0).then_some((start, stop, step)))
5327    }
5328
5329    // ── Pandas Index Model: aggregation ──────────────────────────────
5330
5331    /// Minimum label.
5332    ///
5333    /// Matches `pd.Index.min()`.
5334    #[must_use]
5335    pub fn min(&self) -> Option<IndexLabel> {
5336        // Affine Int64 ranges have their minimum at a known endpoint; return an
5337        // owned scalar without forcing the lazy label vector.
5338        if let Some(affine) = self.labels.int64_affine_range() {
5339            if affine.len == 0 {
5340                return None;
5341            }
5342            let position = if affine.step >= 0 { 0 } else { affine.len - 1 };
5343            return Some(IndexLabel::Int64(affine.value_at(position)));
5344        }
5345        // Datetime64 affine ranges have the same validated endpoint witness.
5346        // Derived IndexLabel ordering compares their raw nanoseconds, including
5347        // the reserved i64::MIN NaT sentinel, so the minimum is exactly the
5348        // first endpoint when ascending and the last when descending.
5349        if let Some(affine) = self.labels.datetime64_affine_range() {
5350            if affine.len == 0 {
5351                return None;
5352            }
5353            let position = if affine.step >= 0 { 0 } else { affine.len - 1 };
5354            return Some(IndexLabel::Datetime64(affine.value_at(position)));
5355        }
5356        // Lazy typed/strided Int64: scan raw i64 values and return the same
5357        // scalar the IndexLabel fallback would have yielded, without materializing.
5358        if self.labels.has_lazy_int64_backing()
5359            && let Some(values) = self.labels.int64_view()
5360        {
5361            return values.iter().copied().min().map(IndexLabel::Int64);
5362        }
5363        self.labels.iter().min().cloned()
5364    }
5365
5366    /// Maximum label.
5367    ///
5368    /// Matches `pd.Index.max()`.
5369    #[must_use]
5370    pub fn max(&self) -> Option<IndexLabel> {
5371        // Affine Int64 ranges have their maximum at the opposite endpoint from
5372        // min(); no IndexLabel materialization needed.
5373        if let Some(affine) = self.labels.int64_affine_range() {
5374            if affine.len == 0 {
5375                return None;
5376            }
5377            let position = if affine.step >= 0 { affine.len - 1 } else { 0 };
5378            return Some(IndexLabel::Int64(affine.value_at(position)));
5379        }
5380        // Datetime64 affine ranges carry the same validated endpoint witness.
5381        // IndexLabel ordering compares raw nanoseconds, including the reserved
5382        // i64::MIN NaT sentinel, so the opposite endpoint from min() is exact.
5383        if let Some(affine) = self.labels.datetime64_affine_range() {
5384            if affine.len == 0 {
5385                return None;
5386            }
5387            let position = if affine.step >= 0 { affine.len - 1 } else { 0 };
5388            return Some(IndexLabel::Datetime64(affine.value_at(position)));
5389        }
5390        // Lazy typed/strided Int64: scan raw i64 values and return an owned
5391        // scalar, preserving fallback ordering semantics for all-Int64 labels.
5392        if self.labels.has_lazy_int64_backing()
5393            && let Some(values) = self.labels.int64_view()
5394        {
5395            return values.iter().copied().max().map(IndexLabel::Int64);
5396        }
5397        self.labels.iter().max().cloned()
5398    }
5399
5400    /// Position of the minimum label.
5401    ///
5402    /// Matches `pd.Index.argmin()`.
5403    #[must_use]
5404    pub fn argmin(&self) -> Option<usize> {
5405        // Affine Int64 (RangeIndex / unit / affine): the minimum sits at a known
5406        // end — index 0 when ascending (step >= 0), len-1 when descending. O(1),
5407        // no IndexLabel materialization (br-frankenpandas-ikbh9 vein).
5408        if let Some(affine) = self.labels.int64_affine_range() {
5409            return (affine.len > 0).then(|| if affine.step >= 0 { 0 } else { affine.len - 1 });
5410        }
5411        // A validated Datetime64 affine range is unique for len > 1, and its
5412        // raw-nanosecond ordering is the same ordering used by IndexLabel.
5413        // Therefore the minimum position is the corresponding endpoint even
5414        // when that endpoint is the reserved i64::MIN NaT sentinel.
5415        if let Some(affine) = self.labels.datetime64_affine_range() {
5416            return (affine.len > 0).then(|| if affine.step >= 0 { 0 } else { affine.len - 1 });
5417        }
5418        // Lazy typed/strided Int64: scan the i64 view with the identical min_by
5419        // (last-of-equal) tie-break — bit-identical, no label vector. Guarded by
5420        // has_lazy_int64_backing so already-materialized indexes keep the label
5421        // iter and avoid an extra i64 allocation (matches any()/all()).
5422        if self.labels.has_lazy_int64_backing()
5423            && let Some(values) = self.labels.int64_view()
5424        {
5425            return values
5426                .iter()
5427                .enumerate()
5428                .min_by(|(_, a), (_, b)| a.cmp(b))
5429                .map(|(i, _)| i);
5430        }
5431        self.labels
5432            .iter()
5433            .enumerate()
5434            .min_by(|(_, a), (_, b)| a.cmp(b))
5435            .map(|(i, _)| i)
5436    }
5437
5438    /// Position of the maximum label.
5439    ///
5440    /// Matches `pd.Index.argmax()`.
5441    #[must_use]
5442    pub fn argmax(&self) -> Option<usize> {
5443        // Affine Int64: the maximum sits at a known end — index len-1 when
5444        // ascending (step >= 0), 0 when descending. O(1), no materialization
5445        // (br-frankenpandas-ikbh9 vein).
5446        if let Some(affine) = self.labels.int64_affine_range() {
5447            return (affine.len > 0).then(|| if affine.step >= 0 { affine.len - 1 } else { 0 });
5448        }
5449        // A validated Datetime64 affine range is unique for len > 1 and uses
5450        // raw nanosecond ordering, so its maximum is the same endpoint without
5451        // materializing one IndexLabel per row. Singleton and empty ranges keep
5452        // the former tie/empty behavior.
5453        if let Some(affine) = self.labels.datetime64_affine_range() {
5454            return (affine.len > 0).then(|| if affine.step >= 0 { affine.len - 1 } else { 0 });
5455        }
5456        // Lazy typed/strided Int64: scan the i64 view with the identical max_by
5457        // (last-of-equal) tie-break — bit-identical, no label vector.
5458        if self.labels.has_lazy_int64_backing()
5459            && let Some(values) = self.labels.int64_view()
5460        {
5461            return values
5462                .iter()
5463                .enumerate()
5464                .max_by(|(_, a), (_, b)| a.cmp(b))
5465                .map(|(i, _)| i);
5466        }
5467        self.labels
5468            .iter()
5469            .enumerate()
5470            .max_by(|(_, a), (_, b)| a.cmp(b))
5471            .map(|(i, _)| i)
5472    }
5473
5474    /// Number of unique labels.
5475    ///
5476    /// Matches `pd.Index.nunique()`.
5477    #[must_use]
5478    pub fn nunique(&self) -> usize {
5479        self.nunique_with_dropna(true)
5480    }
5481
5482    /// Number of unique labels with explicit missing-value control.
5483    ///
5484    /// Matches `pd.Index.nunique(dropna=...)`.
5485    #[must_use]
5486    pub fn nunique_with_dropna(&self, dropna: bool) -> usize {
5487        // Affine Int64 (RangeIndex / unit / affine) is strictly monotonic, so all
5488        // `len` labels are distinct, and an Int64 backing carries no missing
5489        // labels — nunique == len for either dropna setting, with no IndexLabel
5490        // materialization (br-frankenpandas-a55d8 vein).
5491        if let Some(affine) = self.labels.int64_affine_range() {
5492            return affine.len;
5493        }
5494        // A validated affine Datetime64 backing has no repeated raw nanosecond
5495        // values. It can contain the reserved NaT sentinel at most once, so the
5496        // witness gives the exact dropna-aware count without materializing the
5497        // IndexLabel vector or allocating a temporary nanosecond buffer.
5498        if let Some(affine) = self.labels.datetime64_affine_range() {
5499            return affine.len - usize::from(dropna && affine.position(i64::MIN).is_some());
5500        }
5501        if let Some(values) = self.labels.int64_view() {
5502            return Self::nunique_i64(&values);
5503        }
5504        // Datetime64 / Timedelta64 (no NaT): reuse nunique_i64 over the ns instead
5505        // of the pointer-key FxHashMap (nunique over a DatetimeIndex was 0.52x
5506        // pandas). NaT-bearing temporal indexes bail so the dropna fallback below
5507        // keeps its missing semantics. Bit-identical: distinct present timestamps.
5508        if let Some(ns) = self
5509            .temporal_ns_present(true)
5510            .or_else(|| self.temporal_ns_present(false))
5511        {
5512            return Self::nunique_i64(&ns);
5513        }
5514        self.unique()
5515            .labels
5516            .iter()
5517            .filter(|label| !dropna || !label.is_missing())
5518            .count()
5519    }
5520
5521    // ── Pandas Index Model: transformation ───────────────────────────
5522
5523    /// Apply a function to each label, producing a new Index.
5524    ///
5525    /// Matches `pd.Index.map(func)`.
5526    #[must_use]
5527    pub fn map<F>(&self, func: F) -> Self
5528    where
5529        F: Fn(&IndexLabel) -> IndexLabel,
5530    {
5531        self.propagate_name(Self::new(self.labels.iter().map(&func).collect()))
5532    }
5533
5534    /// Rename the index (create a copy with transformed labels).
5535    ///
5536    /// Matches `pd.Index.rename(name)` / `pd.Index.set_names(name)`.
5537    /// Applies a function to each label.
5538    #[must_use]
5539    pub fn rename<F>(&self, func: F) -> Self
5540    where
5541        F: Fn(&IndexLabel) -> IndexLabel,
5542    {
5543        self.map(func)
5544    }
5545
5546    /// Drop specific labels from the index.
5547    ///
5548    /// Matches `pd.Index.drop(labels)`.
5549    #[must_use]
5550    pub fn drop_labels(&self, labels_to_drop: &[IndexLabel]) -> Self {
5551        if let Some(values) = self.labels.int64_view() {
5552            let drop_values = int64_drop_values(labels_to_drop);
5553            let kept = if drop_values.is_empty() {
5554                values.as_ref().clone()
5555            } else if is_non_decreasing_i64(values.as_slice()) {
5556                drop_sorted_i64_values(values.as_slice(), drop_values)
5557            } else {
5558                let drop_set: FxHashSet<i64> = drop_values.into_iter().collect();
5559                values
5560                    .iter()
5561                    .copied()
5562                    .filter(|value| !drop_set.contains(value))
5563                    .collect()
5564            };
5565            return self.propagate_name(Self::from_i64_values(kept));
5566        }
5567        let kept = if labels_to_drop.len() < 8 {
5568            self.labels
5569                .iter()
5570                .filter(|label| !labels_to_drop.contains(label))
5571                .cloned()
5572                .collect()
5573        } else {
5574            let drop_set: FxHashSet<&IndexLabel> = labels_to_drop.iter().collect();
5575            self.labels
5576                .iter()
5577                .filter(|label| !drop_set.contains(label))
5578                .cloned()
5579                .collect()
5580        };
5581        self.propagate_name(Self::new(kept))
5582    }
5583
5584    /// Convert all labels to Int64 (if possible) or Utf8.
5585    ///
5586    /// Matches `pd.Index.astype(dtype)`. Returns a new Index with labels
5587    /// converted to the target type representation.
5588    #[must_use]
5589    pub fn astype_int(&self) -> Self {
5590        if self.labels.has_lazy_int64_backing()
5591            && let Some(values) = self.labels.int64_view()
5592        {
5593            return self.propagate_name(Self::from_i64_values(values.as_ref().clone()));
5594        }
5595        self.propagate_name(Self::new(
5596            self.labels
5597                .iter()
5598                .map(|l| match l {
5599                    IndexLabel::Int64(_) => l.clone(),
5600                    IndexLabel::Float64(v) => IndexLabel::Int64(v.0 as i64),
5601                    IndexLabel::Bool(b) => IndexLabel::Int64(i64::from(*b)),
5602                    IndexLabel::Utf8(s) => s
5603                        .parse::<i64>()
5604                        .map_or_else(|_| l.clone(), IndexLabel::Int64),
5605                    IndexLabel::Timedelta64(ns) => IndexLabel::Int64(*ns),
5606                    IndexLabel::Datetime64(ns) => IndexLabel::Int64(*ns),
5607                    // A period is its ordinal (NaT's too), as pandas'.
5608                    IndexLabel::Period(period) => IndexLabel::Int64(period.ordinal),
5609                    // Missing labels, objects and intervals have no integer
5610                    // form; preserved like unparseable strings (pandas
5611                    // astype(int) raises on them — callers reject before
5612                    // reaching here).
5613                    IndexLabel::Object(_) | IndexLabel::Interval(_) | IndexLabel::Null(_) => {
5614                        l.clone()
5615                    }
5616                })
5617                .collect(),
5618        ))
5619    }
5620
5621    /// Convert labels to Float64 (`pd.Index.astype('float64')`): integers and
5622    /// bools widen, numeric strings parse, a missing label becomes NaN;
5623    /// datetimes, timedeltas and non-numeric strings are pandas' TypeError /
5624    /// ValueError, reported as `InvalidArgument`. (fvsao.4)
5625    pub fn astype_float(&self) -> Result<Self, IndexError> {
5626        let labels = self
5627            .labels
5628            .iter()
5629            .map(|label| {
5630                let value = match label {
5631                    IndexLabel::Int64(v) => *v as f64,
5632                    IndexLabel::Float64(v) => v.0,
5633                    IndexLabel::Bool(b) => f64::from(u8::from(*b)),
5634                    IndexLabel::Utf8(s) => s.parse::<f64>().map_err(|_| {
5635                        IndexError::InvalidArgument(format!(
5636                            "could not convert string to float: '{s}'"
5637                        ))
5638                    })?,
5639                    IndexLabel::Null(_) => f64::NAN,
5640                    IndexLabel::Timedelta64(_) | IndexLabel::Datetime64(_) => {
5641                        return Err(IndexError::InvalidArgument(
5642                            "Cannot cast a datetime-like Index to dtype float64".to_owned(),
5643                        ));
5644                    }
5645                    IndexLabel::Period(_) => {
5646                        return Err(IndexError::InvalidArgument(
5647                            "Cannot cast PeriodIndex to dtype float64".to_owned(),
5648                        ));
5649                    }
5650                    IndexLabel::Interval(_) => {
5651                        return Err(IndexError::InvalidArgument(
5652                            "Cannot cast IntervalIndex to dtype float64".to_owned(),
5653                        ));
5654                    }
5655                    IndexLabel::Object(object) => {
5656                        return Err(IndexError::InvalidArgument(format!(
5657                            "float() argument must be a string or a real number, not {}",
5658                            object.repr()
5659                        )));
5660                    }
5661                };
5662                Ok(IndexLabel::Float64(OrderedF64(value)))
5663            })
5664            .collect::<Result<Vec<_>, IndexError>>()?;
5665        Ok(self.propagate_name(Self::new(labels)))
5666    }
5667
5668    /// Convert labels to bool (`pd.Index.astype(bool)`): nonzero numbers and
5669    /// non-empty strings are true; missing and datetime-like labels are
5670    /// refused. (fvsao.4)
5671    pub fn astype_bool(&self) -> Result<Self, IndexError> {
5672        let labels = self
5673            .labels
5674            .iter()
5675            .map(|label| {
5676                let flag = match label {
5677                    IndexLabel::Int64(v) => *v != 0,
5678                    IndexLabel::Float64(v) => v.0 != 0.0,
5679                    IndexLabel::Bool(b) => *b,
5680                    IndexLabel::Utf8(s) => !s.is_empty(),
5681                    IndexLabel::Object(_) => index_label_is_truthy(label),
5682                    // NaT is false, a period true (pandas').
5683                    IndexLabel::Period(period) => !period.is_nat(),
5684                    IndexLabel::Null(_)
5685                    | IndexLabel::Timedelta64(_)
5686                    | IndexLabel::Datetime64(_)
5687                    | IndexLabel::Interval(_) => {
5688                        return Err(IndexError::InvalidArgument(format!(
5689                            "cannot cast index label {label:?} to bool"
5690                        )));
5691                    }
5692                };
5693                Ok(IndexLabel::Bool(flag))
5694            })
5695            .collect::<Result<Vec<_>, IndexError>>()?;
5696        Ok(self.propagate_name(Self::new(labels)))
5697    }
5698
5699    /// Convert all labels to Utf8 strings.
5700    ///
5701    /// Matches `pd.Index.astype(str)`.
5702    #[must_use]
5703    pub fn astype_str(&self) -> Self {
5704        if self.labels.has_lazy_int64_backing()
5705            && let Some(values) = self.labels.int64_view()
5706        {
5707            return self.propagate_name(Self::new(
5708                values
5709                    .iter()
5710                    .map(|value| IndexLabel::Utf8(value.to_string()))
5711                    .collect(),
5712            ));
5713        }
5714        self.propagate_name(Self::new(
5715            self.labels
5716                .iter()
5717                .map(|l| match l {
5718                    IndexLabel::Int64(v) => IndexLabel::Utf8(v.to_string()),
5719                    IndexLabel::Float64(v) => IndexLabel::Utf8(if v.0.is_nan() {
5720                        "nan".to_owned()
5721                    } else {
5722                        let t = format!("{}", v.0);
5723                        if t.contains('.') || t.contains('e') || t.contains("inf") {
5724                            t
5725                        } else {
5726                            format!("{t}.0")
5727                        }
5728                    }),
5729                    IndexLabel::Bool(b) => {
5730                        IndexLabel::Utf8(if *b { "True" } else { "False" }.to_owned())
5731                    }
5732                    IndexLabel::Utf8(_) => l.clone(),
5733                    IndexLabel::Timedelta64(ns) => IndexLabel::Utf8(Timedelta::format(*ns)),
5734                    IndexLabel::Datetime64(ns) => IndexLabel::Utf8(format_datetime_ns(*ns)),
5735                    IndexLabel::Object(object) => IndexLabel::Utf8(object.to_string()),
5736                    // A period's calendar text, NaT's 'NaT'.
5737                    IndexLabel::Period(period) => IndexLabel::Utf8(period.to_string()),
5738                    // An interval's str ('(0, 1]').
5739                    IndexLabel::Interval(interval) => IndexLabel::Utf8(interval.to_string()),
5740                    // astype(str) uses Python str() forms: str(None)=='None',
5741                    // str(nan)=='nan' (LOWERCASE, unlike the repr surface),
5742                    // str(NaT)=='NaT'. Verified pandas 2.2.3.
5743                    IndexLabel::Null(kind) => IndexLabel::Utf8(
5744                        match kind {
5745                            fp_types::NullKind::Null => "None",
5746                            fp_types::NullKind::NaN => "nan",
5747                            fp_types::NullKind::NaT => "NaT",
5748                        }
5749                        .to_owned(),
5750                    ),
5751                })
5752                .collect(),
5753        ))
5754    }
5755
5756    /// Convert labels to a pandas dtype string.
5757    ///
5758    /// Matches `pd.Index.astype(dtype)` for the generic dtype names this crate
5759    /// can represent directly.
5760    pub fn astype(&self, dtype: &str) -> Result<Self, IndexError> {
5761        let (out, declared) = match dtype {
5762            "int" | "int64" => (self.astype_int(), DeclaredDtype::Int64),
5763            "float" | "float64" => (self.astype_float()?, DeclaredDtype::Float64),
5764            "bool" => (self.astype_bool()?, DeclaredDtype::Bool),
5765            "str" | "string" | "object" => (self.astype_str(), DeclaredDtype::Object),
5766            "datetime64[ns]" => {
5767                ensure_index_kind(self, LabelKinds::DATETIME64, "DatetimeIndex")?;
5768                (self.clone(), DeclaredDtype::Datetime64)
5769            }
5770            "timedelta64[ns]" => {
5771                ensure_index_kind(self, LabelKinds::TIMEDELTA64, "TimedeltaIndex")?;
5772                (self.clone(), DeclaredDtype::Timedelta64)
5773            }
5774            other => {
5775                return Err(IndexError::InvalidArgument(format!(
5776                    "unsupported Index.astype dtype {other:?}"
5777                )));
5778            }
5779        };
5780        // No labels show a type: an empty index is the dtype asked for
5781        // (Index([], dtype='int64') is int64, it was object;
5782        // br-frankenpandas-ce86r).
5783        Ok(if out.is_empty() {
5784            out.with_declared_dtype(Some(declared))
5785        } else {
5786            out
5787        })
5788    }
5789
5790    /// Equality check against another Index.
5791    ///
5792    /// Matches `pd.Index.equals(other)`. Returns true iff `other` has
5793    /// the same labels in the same order, in the same time zone (pandas:
5794    /// the same instants in two zones, or aware against naive, differ in
5795    /// dtype and are not equal). Names are ignored (use `identical` for a
5796    /// name-sensitive check).
5797    #[must_use]
5798    pub fn equals(&self, other: &Self) -> bool {
5799        self == other
5800    }
5801
5802    /// Strict equality including name.
5803    ///
5804    /// Matches `pd.Index.identical(other)`. Requires the same labels in
5805    /// the same order AND the same name (and zone).
5806    #[must_use]
5807    pub fn identical(&self, other: &Self) -> bool {
5808        self == other && self.name == other.name
5809    }
5810
5811    /// Typed `value_counts_raw` over raw `i64` keys: first-seen (value, count)
5812    /// pairs, then the same stable count sort. Bit-identical to the
5813    /// `FxHashMap<IndexLabel,usize>` path for all-Int64 indexes (which have no
5814    /// missing labels, so `dropna` is a no-op): a dense direct-address histogram
5815    /// when the value span is bounded, else an inline-key `FxHashMap<i64,usize>`.
5816    fn value_counts_raw_i64(
5817        vals: &[i64],
5818        sort: bool,
5819        ascending: bool,
5820    ) -> (Vec<(IndexLabel, usize)>, usize) {
5821        let total = vals.len();
5822        let mut seen: Vec<i64> = Vec::new();
5823        let mut pairs: Vec<(IndexLabel, usize)> = match Self::i64_dense_span(vals) {
5824            Some((min, span)) => {
5825                let mut counts = vec![0usize; span];
5826                for &v in vals {
5827                    let s = (v - min) as usize;
5828                    if counts[s] == 0 {
5829                        seen.push(v);
5830                    }
5831                    counts[s] += 1;
5832                }
5833                seen.iter()
5834                    .map(|&v| (IndexLabel::Int64(v), counts[(v - min) as usize]))
5835                    .collect()
5836            }
5837            None => {
5838                let mut counts: FxHashMap<i64, usize> =
5839                    FxHashMap::with_capacity_and_hasher(vals.len(), Default::default());
5840                for &v in vals {
5841                    let c = counts.entry(v).or_insert(0);
5842                    if *c == 0 {
5843                        seen.push(v);
5844                    }
5845                    *c += 1;
5846                }
5847                seen.iter()
5848                    .map(|&v| (IndexLabel::Int64(v), counts[&v]))
5849                    .collect()
5850            }
5851        };
5852        if sort {
5853            if ascending {
5854                pairs.sort_by_key(|entry| entry.1);
5855            } else {
5856                pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
5857            }
5858        }
5859        (pairs, total)
5860    }
5861
5862    fn value_counts_raw(
5863        &self,
5864        sort: bool,
5865        ascending: bool,
5866        dropna: bool,
5867    ) -> (Vec<(IndexLabel, usize)>, usize) {
5868        // Typed all-Int64 fast path: inline `i64` histogram instead of the
5869        // cloned-key, double-hashed `FxHashMap<IndexLabel,usize>`. Int64 labels
5870        // are never missing, so `dropna` changes nothing — bit-identical pairs.
5871        if let Some(vals) = self.labels.int64_view() {
5872            return Self::value_counts_raw_i64(&vals, sort, ascending);
5873        }
5874        // Datetime64 / Timedelta64 (no NaT): reuse the i64 histogram and relabel
5875        // the Int64 pairs to the temporal dtype instead of the cloned-key
5876        // FxHashMap<IndexLabel> (value_counts over a DatetimeIndex was 0.58x
5877        // pandas). NaT bails so the dropna fallback keeps its semantics.
5878        // Bit-identical: value_counts_raw_i64 yields the same first-seen-then-sort
5879        // (value, count) order; only the label variant changes (1:1 with the ns).
5880        for datetime in [true, false] {
5881            if let Some(ns) = self.temporal_ns_present(datetime) {
5882                let (pairs, total) = Self::value_counts_raw_i64(&ns, sort, ascending);
5883                let make: fn(i64) -> IndexLabel = if datetime {
5884                    IndexLabel::Datetime64
5885                } else {
5886                    IndexLabel::Timedelta64
5887                };
5888                let pairs = pairs
5889                    .into_iter()
5890                    .map(|(label, count)| match label {
5891                        IndexLabel::Int64(v) => (make(v), count),
5892                        other => (other, count),
5893                    })
5894                    .collect();
5895                return (pairs, total);
5896            }
5897        }
5898        // Typed all-Utf8 fast path: tally `&str` keys (ONE `entry` hash per label,
5899        // and NO per-label `String` clone — the generic path below clones every
5900        // label twice into an `FxHashMap<IndexLabel>` key) — making value_counts a
5901        // LOSS vs pandas. Both sides pure Utf8 (no Null), so `dropna` is moot
5902        // (total == len). Bit-identical: same first-seen order, same per-label
5903        // counts, same `sort_by_key` (stable, so first-seen breaks ties). Allocates
5904        // a String only once per DISTINCT label when building the final pairs.
5905        if self
5906            .labels()
5907            .iter()
5908            .all(|l| matches!(l, IndexLabel::Utf8(_)))
5909        {
5910            let labels = self.labels();
5911            let mut seen_order: Vec<&str> = Vec::new();
5912            let mut counts: FxHashMap<&str, usize> = FxHashMap::default();
5913            for label in labels {
5914                if let IndexLabel::Utf8(s) = label {
5915                    let e = counts.entry(s.as_str()).or_insert(0);
5916                    if *e == 0 {
5917                        seen_order.push(s.as_str());
5918                    }
5919                    *e += 1;
5920                }
5921            }
5922            let total = labels.len();
5923            let mut pairs: Vec<(IndexLabel, usize)> = seen_order
5924                .into_iter()
5925                .map(|s| (IndexLabel::Utf8(s.to_owned()), counts[s]))
5926                .collect();
5927            if sort {
5928                if ascending {
5929                    pairs.sort_by_key(|entry| entry.1);
5930                } else {
5931                    pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
5932                }
5933            }
5934            return (pairs, total);
5935        }
5936        let mut seen_order: Vec<IndexLabel> = Vec::new();
5937        let mut counts: FxHashMap<IndexLabel, usize> = FxHashMap::default();
5938        let mut total = 0usize;
5939        for label in &self.labels {
5940            if dropna && label.is_missing() {
5941                continue;
5942            }
5943            total += 1;
5944            if !counts.contains_key(label) {
5945                seen_order.push(label.clone());
5946            }
5947            *counts.entry(label.clone()).or_insert(0) += 1;
5948        }
5949        let mut pairs: Vec<(IndexLabel, usize)> = seen_order
5950            .into_iter()
5951            .map(|label| {
5952                let count = counts[&label];
5953                (label, count)
5954            })
5955            .collect();
5956        if sort {
5957            if ascending {
5958                pairs.sort_by_key(|entry| entry.1);
5959            } else {
5960                pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
5961            }
5962        }
5963        (pairs, total)
5964    }
5965
5966    /// Count occurrences of each distinct label.
5967    ///
5968    /// Matches `pd.Index.value_counts()` default behavior. Missing labels are
5969    /// dropped, counts are sorted descending, and first-seen order breaks ties.
5970    #[must_use]
5971    pub fn value_counts(&self) -> Vec<(IndexLabel, usize)> {
5972        self.value_counts_raw(true, false, true).0
5973    }
5974
5975    /// Count occurrences of each distinct label with pandas-style options.
5976    ///
5977    /// Matches `pd.Index.value_counts(normalize, sort, ascending, dropna)`.
5978    /// Returns `Scalar::Int64` counts unless `normalize=true`, in which case
5979    /// the values are `Scalar::Float64` fractions.
5980    #[must_use]
5981    pub fn value_counts_with_options(
5982        &self,
5983        normalize: bool,
5984        sort: bool,
5985        ascending: bool,
5986        dropna: bool,
5987    ) -> Vec<(IndexLabel, Scalar)> {
5988        let (pairs, total) = self.value_counts_raw(sort, ascending, dropna);
5989        if normalize {
5990            let denom = total as f64;
5991            return pairs
5992                .into_iter()
5993                .map(|(label, count)| (label, Scalar::Float64(count as f64 / denom)))
5994                .collect();
5995        }
5996
5997        pairs
5998            .into_iter()
5999            .map(|(label, count)| (label, Scalar::Int64(count as i64)))
6000            .collect()
6001    }
6002
6003    /// Shift the labels by `periods` positions, filling vacated slots
6004    /// with `fill`.
6005    ///
6006    /// ⚠️ THIS IS NOT `pd.Index.shift`, and the claim that used to be here cited a
6007    /// signature pandas does not have. It said "Matches `pd.Index.shift(periods,
6008    /// fill_value=...)` for the positional form". MEASURED, live pandas 2.2.3
6009    /// (CrimsonPine 2026-08-19):
6010    /// ```text
6011    ///   inspect.signature(pd.Index.shift) -> (self, periods=1, freq=None)
6012    ///       there is NO fill_value parameter, and no positional form at all
6013    ///   pd.Index([10,20,30]).shift(1)
6014    ///       -> NotImplementedError: This method is only implemented for
6015    ///          DatetimeIndex, PeriodIndex and TimedeltaIndex
6016    ///   pd.date_range('2024-01-01', periods=3, freq='D').shift(1)
6017    ///       -> ['2024-01-02','2024-01-03','2024-01-04']
6018    ///          labels move FORWARD IN TIME by one freq unit; length preserved;
6019    ///          nothing is filled and nothing falls off the end
6020    ///   pd.DatetimeIndex([...]).shift(1)   with no inferable freq
6021    ///       -> NullFrequencyError: Cannot shift with no freq
6022    /// ```
6023    /// So pandas' `Index.shift` is a TEMPORAL relabel available only on datetime-like
6024    /// indexes, whereas this is a POSITIONAL shift that vacates slots and fills them —
6025    /// the semantics of `pd.Series.shift`, applied to labels. The two share a name and
6026    /// nothing else.
6027    ///
6028    /// Kept as a FrankenPandas operation (its behaviour is pinned by
6029    /// `index_shift_positive_pads_left` / `_negative_pads_right` / `_zero_is_clone`);
6030    /// only the false parity claim is removed. Positive periods shift right, negative
6031    /// shift left.
6032    #[must_use]
6033    pub fn shift(&self, periods: i64, fill: IndexLabel) -> Self {
6034        let len = self.labels.len();
6035        if len == 0 || periods == 0 {
6036            return self.clone();
6037        }
6038        let abs = periods.unsigned_abs() as usize;
6039        if let Some(values) = self.labels.int64_view()
6040            && let IndexLabel::Int64(fill_value) = &fill
6041        {
6042            let mut out: Vec<i64> = Vec::with_capacity(len);
6043            if abs >= len {
6044                out.resize(len, *fill_value);
6045            } else if periods > 0 {
6046                out.resize(abs, *fill_value);
6047                out.extend_from_slice(&values[..len - abs]);
6048            } else {
6049                out.extend_from_slice(&values[abs..]);
6050                out.resize(len, *fill_value);
6051            }
6052            return self.propagate_name(Self::from_i64_values(out));
6053        }
6054        let mut out: Vec<IndexLabel> = Vec::with_capacity(len);
6055        if abs >= len {
6056            for _ in 0..len {
6057                out.push(fill.clone());
6058            }
6059        } else if periods > 0 {
6060            for _ in 0..abs {
6061                out.push(fill.clone());
6062            }
6063            out.extend_from_slice(&self.labels[..len - abs]);
6064        } else {
6065            out.extend_from_slice(&self.labels[abs..]);
6066            for _ in 0..abs {
6067                out.push(fill.clone());
6068            }
6069        }
6070        self.propagate_name(Self::new(out))
6071    }
6072
6073    /// Nearest-preceding-or-equal label lookup.
6074    ///
6075    /// Matches `pd.Index.asof(label)` for monotonic-increasing indexes: returns the
6076    /// largest label `<= key`, or `None` when the key precedes every entry.
6077    ///
6078    /// ⚠️ THE NON-MONOTONIC CLAIM THAT USED TO BE HERE WAS WRONG IN BOTH HALVES. It
6079    /// said pandas "emits a warning in the non-monotonic case but still does a linear
6080    /// scan — we match that behavior". MEASURED, live pandas 2.2.3 (CrimsonPine
6081    /// 2026-08-19), on `pd.Index([30, 10, 20])`:
6082    /// ```text
6083    ///   .asof(25) -> ValueError: index must be monotonic increasing or decreasing
6084    ///   .asof(5)  -> ValueError (same)
6085    ///   .asof(35) -> ValueError (same)
6086    /// ```
6087    /// pandas REFUSES; it does not warn and scan. And this function does not scan
6088    /// either — the loop below BREAKS at the first label greater than the key, which
6089    /// is correct only on sorted input. So on `[30, 10, 20]` it stops at 30 and
6090    /// returns `None`, silently answering "nothing precedes 25" for an index that
6091    /// contains 20.
6092    ///
6093    /// ⚠️ DOCUMENTED DIVERGENCE, not a fix: matching pandas means RAISING on a
6094    /// non-monotonic index, and this returns `Option` rather than `Result`, so the
6095    /// change is a signature decision rather than a repair. Callers must sort first;
6096    /// `is_sorted()` answers the precondition. Pinned by
6097    /// `asof_on_a_non_monotonic_index_is_a_documented_divergence`.
6098    #[must_use]
6099    pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
6100        if let (Some(range), IndexLabel::Int64(needle)) = (self.labels.int64_affine_range(), key) {
6101            if range.len == 0 {
6102                return None;
6103            }
6104            if range.len == 1 {
6105                return (range.start <= *needle).then_some(IndexLabel::Int64(range.start));
6106            }
6107            if range.step > 0 {
6108                let delta = i128::from(*needle) - i128::from(range.start);
6109                if delta < 0 {
6110                    return None;
6111                }
6112                let position = usize::try_from(delta / i128::from(range.step))
6113                    .unwrap_or(range.len - 1)
6114                    .min(range.len - 1);
6115                return Some(IndexLabel::Int64(range.value_at(position)));
6116            }
6117        }
6118        if self.labels.has_lazy_int64_backing()
6119            && let IndexLabel::Int64(needle) = key
6120            && let Some(values) = self.labels.int64_view()
6121        {
6122            let mut best = None;
6123            for &value in values.iter() {
6124                if value <= *needle {
6125                    best = Some(value);
6126                } else {
6127                    break;
6128                }
6129            }
6130            return best.map(IndexLabel::Int64);
6131        }
6132        let mut best: Option<&IndexLabel> = None;
6133        for label in &self.labels {
6134            if label.is_missing() {
6135                continue;
6136            }
6137            if label.cmp(key).is_le() {
6138                best = Some(label);
6139            } else {
6140                break;
6141            }
6142        }
6143        best.cloned()
6144    }
6145
6146    /// Position where `value` would be inserted to keep the index
6147    /// sorted ascending.
6148    ///
6149    /// Matches `pd.Index.searchsorted(value, side)`. `side` is
6150    /// `"left"` (first valid insertion) or `"right"` (last). Returns
6151    /// an error for unknown sides or missing needles.
6152    pub fn searchsorted(&self, value: &IndexLabel, side: &str) -> Result<usize, IndexError> {
6153        if side != "left" && side != "right" {
6154            return Err(IndexError::InvalidArgument(format!(
6155                "searchsorted: side must be 'left' or 'right', got {side:?}"
6156            )));
6157        }
6158        if value.is_missing() {
6159            return Err(IndexError::InvalidArgument(
6160                "searchsorted: needle cannot be missing".to_owned(),
6161            ));
6162        }
6163        if let Some(range) = self.labels.int64_affine_range()
6164            && let IndexLabel::Int64(needle) = value
6165        {
6166            if range.len == 0 {
6167                return Ok(0);
6168            }
6169            if range.len == 1 {
6170                let go_right = range.start < *needle || (range.start == *needle && side == "right");
6171                return Ok(usize::from(go_right));
6172            }
6173            if range.step > 0 {
6174                if *needle < range.start {
6175                    return Ok(0);
6176                }
6177                let delta = i128::from(*needle) - i128::from(range.start);
6178                let step = i128::from(range.step);
6179                let mut position = delta / step;
6180                if side == "right" || delta % step != 0 {
6181                    position += 1;
6182                }
6183                return Ok(usize::try_from(position)
6184                    .unwrap_or(range.len)
6185                    .min(range.len));
6186            }
6187        }
6188        if self.labels.has_lazy_int64_backing()
6189            && let IndexLabel::Int64(needle) = value
6190            && let Some(values) = self.labels.int64_view()
6191        {
6192            let mut lo = 0usize;
6193            let mut hi = values.len();
6194            while lo < hi {
6195                let mid = lo + (hi - lo) / 2;
6196                let go_right = values[mid] < *needle || (values[mid] == *needle && side == "right");
6197                if go_right {
6198                    lo = mid + 1;
6199                } else {
6200                    hi = mid;
6201                }
6202            }
6203            return Ok(lo);
6204        }
6205        let mut lo = 0usize;
6206        let mut hi = self.labels.len();
6207        while lo < hi {
6208            let mid = lo + (hi - lo) / 2;
6209            let cmp = if self.labels[mid].is_missing() {
6210                std::cmp::Ordering::Greater
6211            } else {
6212                self.labels[mid].cmp(value)
6213            };
6214            use std::cmp::Ordering;
6215            let go_right = matches!(
6216                (cmp, side),
6217                (Ordering::Less, _) | (Ordering::Equal, "right")
6218            );
6219            if go_right {
6220                lo = mid + 1;
6221            } else {
6222                hi = mid;
6223            }
6224        }
6225        Ok(lo)
6226    }
6227
6228    /// Approximate memory footprint (bytes) occupied by the labels.
6229    ///
6230    /// Matches `pd.Index.memory_usage(deep=...)`. `deep=false` uses
6231    /// a fixed per-label width (8 bytes for Int64/Timedelta64/
6232    /// Datetime64, pointer-size for Utf8); `deep=true` additionally
6233    /// accounts for each Utf8 string's byte length.
6234    #[must_use]
6235    pub fn memory_usage(&self, deep: bool) -> usize {
6236        if self.labels.has_lazy_int64_backing() {
6237            return fixed_width_label_memory_usage(self.labels.len(), 8);
6238        }
6239        self.labels.iter().fold(0usize, |total, label| {
6240            total.saturating_add(match label {
6241                IndexLabel::Int64(_)
6242                | IndexLabel::Float64(_)
6243                | IndexLabel::Timedelta64(_)
6244                | IndexLabel::Datetime64(_)
6245                | IndexLabel::Object(_)
6246                | IndexLabel::Period(_)
6247                | IndexLabel::Interval(_)
6248                | IndexLabel::Null(_) => 8,
6249                IndexLabel::Bool(_) => 1,
6250                IndexLabel::Utf8(s) => {
6251                    if deep {
6252                        std::mem::size_of::<String>().saturating_add(s.len())
6253                    } else {
6254                        std::mem::size_of::<String>()
6255                    }
6256                }
6257            })
6258        })
6259    }
6260
6261    /// Number of levels in this index.
6262    ///
6263    /// Matches `pd.Index.nlevels`. Always 1 for the flat Index type;
6264    /// MultiIndex already overrides this. Provided so callers can
6265    /// write level-agnostic code that works on either kind.
6266    #[must_use]
6267    pub fn nlevels(&self) -> usize {
6268        1
6269    }
6270
6271    /// Materialize labels into an owned `Vec<IndexLabel>`.
6272    ///
6273    /// Matches `pd.Index.to_list()`. Convenience helper for callers
6274    /// that need ownership without manually cloning via `labels()`.
6275    #[must_use]
6276    pub fn to_list(&self) -> Vec<IndexLabel> {
6277        self.labels.to_owned_labels()
6278    }
6279
6280    /// Stringify each label using its `Display` impl.
6281    ///
6282    /// Matches `pd.Index.format()` / `pd.Index.astype(str).tolist()`.
6283    /// Result is a `Vec<String>` in index order.
6284    #[must_use]
6285    pub fn format(&self) -> Vec<String> {
6286        if self.labels.has_lazy_int64_backing()
6287            && let Some(values) = self.labels.int64_view()
6288        {
6289            return values.iter().map(ToString::to_string).collect();
6290        }
6291        self.labels.iter().map(IndexLabel::to_string).collect()
6292    }
6293
6294    /// Replace labels at positions where `cond` is true with `value`.
6295    ///
6296    /// Matches `pd.Index.putmask(cond, value)`. A shorter `cond`
6297    /// leaves trailing labels unchanged (pandas-style lenient
6298    /// alignment); a longer `cond` is silently truncated. The name
6299    /// is preserved. It is [`Self::where_cond`] of the other labels, so an
6300    /// int index given a NaN or a float turns float64 as there (it kept
6301    /// int64 beside the NaN; br-frankenpandas-oq1df).
6302    #[must_use]
6303    pub fn putmask(&self, cond: &[bool], value: &IndexLabel) -> Self {
6304        let kept: Vec<bool> = (0..self.len())
6305            .map(|i| !cond.get(i).copied().unwrap_or(false))
6306            .collect();
6307        self.where_cond(&kept, value)
6308    }
6309
6310    /// Whether any label coerces to true.
6311    ///
6312    /// Matches `pd.Index.any()`. Non-zero integers, non-empty strings,
6313    /// and non-NaT timedeltas count as truthy. Missing labels are
6314    /// treated as falsy. Empty index returns false.
6315    #[must_use]
6316    pub fn any(&self) -> bool {
6317        if self.labels.has_lazy_int64_backing()
6318            && let Some(values) = self.labels.int64_view()
6319        {
6320            return values.iter().any(|&value| value != 0);
6321        }
6322        self.labels.iter().any(index_label_is_truthy)
6323    }
6324
6325    /// Whether all labels coerce to true.
6326    ///
6327    /// Matches `pd.Index.all()`. Empty index returns true (pandas
6328    /// convention: vacuously true). Missing labels count as falsy.
6329    #[must_use]
6330    pub fn all(&self) -> bool {
6331        if self.labels.has_lazy_int64_backing()
6332            && let Some(values) = self.labels.int64_view()
6333        {
6334            return values.iter().all(|&value| value != 0);
6335        }
6336        self.labels.iter().all(index_label_is_truthy)
6337    }
6338
6339    /// Drop missing labels, preserving order.
6340    ///
6341    /// Matches `pd.Index.dropna()`. Labels whose `is_missing()` returns
6342    /// true are removed. The name (if any) is preserved.
6343    #[must_use]
6344    pub fn dropna(&self) -> Self {
6345        if self.labels.has_lazy_int64_backing() {
6346            return self.clone();
6347        }
6348        self.propagate_name(Self::new(
6349            self.labels
6350                .iter()
6351                .filter(|label| !label.is_missing())
6352                .cloned()
6353                .collect(),
6354        ))
6355    }
6356
6357    /// Insert a new label at the given position.
6358    ///
6359    /// Matches `pd.Index.insert(loc, item)`. `loc` is an ordinal position
6360    /// where the new label is inserted; positions equal to `len()` append
6361    /// to the end. Out-of-bounds positions return an `OutOfBounds` error.
6362    pub fn insert(&self, loc: usize, item: IndexLabel) -> Result<Self, IndexError> {
6363        if loc > self.labels.len() {
6364            return Err(IndexError::OutOfBounds {
6365                position: loc,
6366                length: self.labels.len(),
6367            });
6368        }
6369        if let Some(values) = self.labels.int64_view()
6370            && let IndexLabel::Int64(value) = &item
6371        {
6372            let mut out = Vec::with_capacity(insert_output_capacity(values.len()));
6373            let (head, tail) = values.split_at(loc);
6374            out.extend_from_slice(head);
6375            out.push(*value);
6376            out.extend_from_slice(tail);
6377            return Ok(self.propagate_name(Self::from_i64_values(out)));
6378        }
6379        let mut labels = self.labels().to_vec();
6380        labels.insert(loc, item);
6381        Ok(self.propagate_name(Self::new(labels)))
6382    }
6383
6384    /// Delete the label at the given position.
6385    ///
6386    /// Matches `pd.Index.delete(loc)`. Returns an `OutOfBounds` error
6387    /// for positions outside `0..len()`.
6388    pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
6389        if loc >= self.labels.len() {
6390            return Err(IndexError::OutOfBounds {
6391                position: loc,
6392                length: self.labels.len(),
6393            });
6394        }
6395        if let Some(values) = self.labels.int64_view() {
6396            let mut out = Vec::with_capacity(values.len() - 1);
6397            let (head, deleted_and_tail) = values.split_at(loc);
6398            let (_, tail) = deleted_and_tail.split_at(1);
6399            out.extend_from_slice(head);
6400            out.extend_from_slice(tail);
6401            return Ok(self.propagate_name(Self::from_i64_values(out)));
6402        }
6403        let mut labels = self.labels().to_vec();
6404        labels.remove(loc);
6405        Ok(self.propagate_name(Self::new(labels)))
6406    }
6407
6408    /// Append another index to the end of this one.
6409    ///
6410    /// Matches `pd.Index.append(other)`. The returned index contains
6411    /// `self.labels` followed by `other.labels`. Name is preserved from
6412    /// `self`; a time zone only when both share it.
6413    #[must_use]
6414    pub fn append(&self, other: &Self) -> Self {
6415        if let (Some(left), Some(right)) = (self.labels.int64_view(), other.labels.int64_view()) {
6416            let mut values = Vec::with_capacity(combined_output_capacity(left.len(), right.len()));
6417            values.extend_from_slice(left.as_slice());
6418            values.extend_from_slice(right.as_slice());
6419            return self.propagate_name(Self::from_i64_values(values));
6420        }
6421        let mut labels = self.labels().to_vec();
6422        labels.extend(other.labels.iter().cloned());
6423        let mut appended = self.propagate_name(Self::new(labels));
6424        if self.tz != other.tz {
6425            appended.tz = None;
6426        }
6427        appended
6428    }
6429
6430    /// Repeat each label `repeats` times.
6431    ///
6432    /// Matches `pd.Index.repeat(repeats)`. `repeats=0` yields an empty
6433    /// index; `repeats=1` is a no-op clone. Name is preserved.
6434    #[must_use]
6435    pub fn repeat(&self, repeats: usize) -> Self {
6436        if repeats == 0 {
6437            if self.labels.int64_view().is_some() {
6438                return self.propagate_name(Self::from_i64_values(Vec::new()));
6439            }
6440            return self.propagate_name(Self::new(Vec::new()));
6441        }
6442        if repeats == 1 {
6443            return self.clone();
6444        }
6445        if let Some(values) = self.labels.int64_view() {
6446            let mut out = Vec::with_capacity(repeat_output_capacity(values.len(), repeats));
6447            for &value in values.iter() {
6448                for _ in 0..repeats {
6449                    out.push(value);
6450                }
6451            }
6452            return self.propagate_name(Self::from_i64_values(out));
6453        }
6454        let mut out = Vec::with_capacity(repeat_output_capacity(self.labels.len(), repeats));
6455        for label in &self.labels {
6456            for _ in 0..repeats {
6457                out.push(label.clone());
6458            }
6459        }
6460        self.propagate_name(Self::new(out))
6461    }
6462
6463    /// Fill missing labels with the provided scalar.
6464    ///
6465    /// Matches `pd.Index.fillna(value)`.
6466    #[must_use]
6467    pub fn fillna(&self, value: &IndexLabel) -> Self {
6468        if self.labels.has_lazy_int64_backing() {
6469            return self.clone();
6470        }
6471        self.propagate_name(Self::new(
6472            self.labels
6473                .iter()
6474                .map(|label| {
6475                    if label.is_missing() {
6476                        value.clone()
6477                    } else {
6478                        label.clone()
6479                    }
6480                })
6481                .collect(),
6482        ))
6483    }
6484
6485    /// Matches `pd.Index.isna()`.
6486    #[must_use]
6487    pub fn isna(&self) -> Vec<bool> {
6488        if self.labels.has_lazy_int64_backing() {
6489            return vec![false; self.labels.len()];
6490        }
6491        self.labels.iter().map(IndexLabel::is_missing).collect()
6492    }
6493
6494    /// Matches `pd.Index.notna()`.
6495    #[must_use]
6496    pub fn notna(&self) -> Vec<bool> {
6497        if self.labels.has_lazy_int64_backing() {
6498            return vec![true; self.labels.len()];
6499        }
6500        self.labels
6501            .iter()
6502            .map(|label| !label.is_missing())
6503            .collect()
6504    }
6505
6506    /// Where: replace labels at false positions with a fill value.
6507    ///
6508    /// Matches `pd.Index.where(cond, other)`.
6509    #[must_use]
6510    pub fn where_cond(&self, cond: &[bool], other: &IndexLabel) -> Self {
6511        if let Some(values) = self.labels.int64_view()
6512            && let IndexLabel::Int64(replacement) = other
6513        {
6514            let new_labels: Vec<i64> = values
6515                .iter()
6516                .enumerate()
6517                .map(|(i, &label)| {
6518                    if cond.get(i).copied().unwrap_or(false) {
6519                        label
6520                    } else {
6521                        *replacement
6522                    }
6523                })
6524                .collect();
6525            return self.propagate_name(Self::from_i64_values(new_labels));
6526        }
6527        // An int index given a NaN or a float in place of a label is float64,
6528        // as pandas' (the ints stayed beside the NaN: an int64 index holding
6529        // NaN; br-frankenpandas-oq1df).
6530        let replaced = (0..self.len()).any(|i| !cond.get(i).copied().unwrap_or(false));
6531        let widened = replaced
6532            && matches!(
6533                other,
6534                IndexLabel::Float64(_) | IndexLabel::Null(fp_types::NullKind::NaN)
6535            )
6536            && self
6537                .labels
6538                .iter()
6539                .all(|label| matches!(label, IndexLabel::Int64(_)));
6540        self.propagate_name(Self::new(
6541            self.labels
6542                .iter()
6543                .enumerate()
6544                .map(|(i, l)| {
6545                    if !cond.get(i).copied().unwrap_or(false) {
6546                        other.clone()
6547                    } else if let (true, IndexLabel::Int64(value)) = (widened, l) {
6548                        #[allow(clippy::cast_precision_loss)] // pandas' int64 -> float64
6549                        let value = *value as f64;
6550                        IndexLabel::Float64(OrderedF64(value))
6551                    } else {
6552                        l.clone()
6553                    }
6554                })
6555                .collect(),
6556        ))
6557    }
6558
6559    /// Alias for `union_with`, matching `pd.Index.union`.
6560    #[must_use]
6561    pub fn union(&self, other: &Self) -> Self {
6562        self.union_with(other)
6563    }
6564
6565    /// Alias for `sort_values`, matching `pd.Index.sort`.
6566    #[must_use]
6567    pub fn sort(&self) -> Self {
6568        self.sort_values()
6569    }
6570
6571    /// Sort labels and return the positional indexer used for the sort.
6572    ///
6573    /// Matches the flat-index shape of `pd.Index.sortlevel()`.
6574    #[must_use]
6575    pub fn sortlevel(&self) -> (Self, Vec<usize>) {
6576        let order = self.argsort();
6577        (self.take(&order), order)
6578    }
6579
6580    /// Alias for `drop_labels`, matching `pd.Index.drop`.
6581    #[must_use]
6582    pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Self {
6583        self.drop_labels(labels_to_drop)
6584    }
6585
6586    /// Clone this index, matching `pd.Index.copy`.
6587    #[must_use]
6588    pub fn copy(&self) -> Self {
6589        self.clone()
6590    }
6591
6592    /// Alias for `where_cond`, matching `pd.Index.where`.
6593    #[must_use]
6594    pub fn where_(&self, cond: &[bool], other: &IndexLabel) -> Self {
6595        self.where_cond(cond, other)
6596    }
6597
6598    /// Alias for `to_list`, matching `pd.Index.tolist`.
6599    #[must_use]
6600    pub fn tolist(&self) -> Vec<IndexLabel> {
6601        self.to_list()
6602    }
6603
6604    /// Object-array-shaped materialization, matching `pd.Index.to_numpy`.
6605    #[must_use]
6606    pub fn to_numpy(&self) -> Vec<IndexLabel> {
6607        self.to_list()
6608    }
6609
6610    /// Alias for `to_numpy`, matching `pd.Index.array`.
6611    #[must_use]
6612    pub fn array(&self) -> Vec<IndexLabel> {
6613        self.to_numpy()
6614    }
6615
6616    /// Alias for `to_numpy`, matching `pd.Index.values`.
6617    #[must_use]
6618    pub fn values(&self) -> Vec<IndexLabel> {
6619        self.to_numpy()
6620    }
6621
6622    /// Alias for `to_numpy`, matching `pd.Index.ravel`.
6623    #[must_use]
6624    pub fn ravel(&self) -> Vec<IndexLabel> {
6625        self.to_numpy()
6626    }
6627
6628    /// Return a shallow clone view, matching `pd.Index.view` for this
6629    /// immutable Rust representation.
6630    #[must_use]
6631    pub fn view(&self) -> Self {
6632        self.clone()
6633    }
6634
6635    /// Flat-index transpose is identity, matching `pd.Index.transpose`.
6636    #[must_use]
6637    pub fn transpose(&self) -> Self {
6638        self.clone()
6639    }
6640
6641    /// Alias for `transpose`, matching `pd.Index.T`.
6642    #[allow(non_snake_case)]
6643    #[must_use]
6644    pub fn T(&self) -> Self {
6645        self.transpose()
6646    }
6647
6648    /// One-column row materialization, matching the flat-index shape of
6649    /// `pd.Index.to_frame(index=False)`.
6650    #[must_use]
6651    pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
6652        if let Some(values) = self.labels.int64_view() {
6653            return values
6654                .iter()
6655                .map(|&value| vec![IndexLabel::Int64(value)])
6656                .collect();
6657        }
6658        self.labels
6659            .iter()
6660            .map(|label| vec![label.clone()])
6661            .collect()
6662    }
6663
6664    /// Series-shaped materialization using the index labels as both index and
6665    /// values until `fp-frame` owns the richer return type.
6666    #[must_use]
6667    pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
6668        if let Some(values) = self.labels.int64_view() {
6669            return values
6670                .iter()
6671                .map(|&value| {
6672                    let label = IndexLabel::Int64(value);
6673                    (label.clone(), label)
6674                })
6675                .collect();
6676        }
6677        self.labels
6678            .iter()
6679            .map(|label| (label.clone(), label.clone()))
6680            .collect()
6681    }
6682
6683    /// Pandas dtype string for this flat index.
6684    #[must_use]
6685    pub fn dtype(&self) -> &'static str {
6686        if let Some(declared) = self.declared {
6687            return declared.name();
6688        }
6689        // A range is int64 when it holds no label too (an empty one was
6690        // object; br-frankenpandas-7bope).
6691        if self.range.is_some() {
6692            return "int64";
6693        }
6694        match self.inferred_type() {
6695            "integer" => "int64",
6696            "floating" => "float64",
6697            "boolean" => "bool",
6698            "string" => "object",
6699            "timedelta64" => "timedelta64[ns]",
6700            "datetime64" => "datetime64[ns]",
6701            "empty" | "mixed" => "object",
6702            _ => "object",
6703        }
6704    }
6705
6706    /// One-element dtype list, matching the `.dtypes` accessor shape used by
6707    /// pandas containers.
6708    #[must_use]
6709    pub fn dtypes(&self) -> Vec<&'static str> {
6710        vec![self.dtype()]
6711    }
6712
6713    /// Infer object labels without changing the current typed representation.
6714    #[must_use]
6715    pub fn infer_objects(&self) -> Self {
6716        self.clone()
6717    }
6718
6719    /// Whether this index's dtype can hold integer labels.
6720    #[must_use]
6721    pub fn holds_integer(&self) -> bool {
6722        self.is_integer()
6723    }
6724
6725    /// Pandas-style inferred-type string for the label values.
6726    #[must_use]
6727    pub fn inferred_type(&self) -> &'static str {
6728        if self.labels.is_empty() {
6729            return "empty";
6730        }
6731        if self.labels.has_lazy_int64_backing() {
6732            return "integer";
6733        }
6734        let mut non_missing = self.labels.iter().filter(|label| !label.is_missing());
6735        let Some(first) = non_missing.next() else {
6736            // Every label is missing: pandas infers NaN floating (NaN beside
6737            // None too), NaT an instant and None alone mixed - an all-NaN
6738            // index is float64 (it was object; br-frankenpandas-mzes1).
6739            let all = |kind: fn(&IndexLabel) -> bool| self.labels.iter().all(kind);
6740            return if all(|label| {
6741                matches!(
6742                    label,
6743                    IndexLabel::Datetime64(_) | IndexLabel::Null(fp_types::NullKind::NaT)
6744                )
6745            }) {
6746                "datetime64"
6747            } else if all(|label| matches!(label, IndexLabel::Timedelta64(_))) {
6748                "timedelta64"
6749            } else if all(|label| matches!(label, IndexLabel::Period(_))) {
6750                // A PeriodIndex of NaT alone is still one (45fzr).
6751                "period"
6752            } else if self.labels.iter().any(|label| {
6753                matches!(
6754                    label,
6755                    IndexLabel::Float64(_) | IndexLabel::Null(fp_types::NullKind::NaN)
6756                )
6757            }) && all(|label| {
6758                matches!(
6759                    label,
6760                    IndexLabel::Float64(_)
6761                        | IndexLabel::Null(fp_types::NullKind::NaN | fp_types::NullKind::Null)
6762                )
6763            }) {
6764                "floating"
6765            } else {
6766                "mixed"
6767            };
6768        };
6769        let same_kind = |label: &IndexLabel| {
6770            matches!(
6771                (first, label),
6772                (IndexLabel::Int64(_), IndexLabel::Int64(_))
6773                    | (IndexLabel::Float64(_), IndexLabel::Float64(_))
6774                    | (IndexLabel::Bool(_), IndexLabel::Bool(_))
6775                    | (IndexLabel::Utf8(_), IndexLabel::Utf8(_))
6776                    | (IndexLabel::Timedelta64(_), IndexLabel::Timedelta64(_))
6777                    | (IndexLabel::Datetime64(_), IndexLabel::Datetime64(_))
6778            ) || matches!(
6779                (first, label),
6780                (IndexLabel::Period(a), IndexLabel::Period(b)) if a.freq == b.freq
6781            ) || matches!(
6782                (first, label),
6783                (IndexLabel::Interval(_), IndexLabel::Interval(_))
6784            )
6785        };
6786        if !non_missing.all(same_kind) {
6787            return "mixed";
6788        }
6789        // pandas infers with skipna=False: a missing label beside bools or
6790        // strings is a kind of its own (an object Index; `[True, None]` read
6791        // bool), where NaN is a float and NaT an instant.
6792        let beside_missing = |kind| {
6793            if self.labels.iter().any(IndexLabel::is_missing) {
6794                "mixed"
6795            } else {
6796                kind
6797            }
6798        };
6799        match first {
6800            IndexLabel::Int64(_) => "integer",
6801            IndexLabel::Float64(_) => "floating",
6802            IndexLabel::Bool(_) => beside_missing("boolean"),
6803            IndexLabel::Utf8(_) => beside_missing("string"),
6804            IndexLabel::Timedelta64(_) => "timedelta64",
6805            IndexLabel::Datetime64(_) => "datetime64",
6806            // Periods of one freq (a NaT beside them too); another freq
6807            // among them was mixed above.
6808            IndexLabel::Period(_) => "period",
6809            IndexLabel::Interval(_) => "interval",
6810            // The core cannot read an object's kind (pandas says "date" for
6811            // datetime.date labels); and unreachable for Null: `first` comes
6812            // from the non-missing iterator and every Null label is_missing.
6813            IndexLabel::Object(_) | IndexLabel::Null(_) => "mixed",
6814        }
6815    }
6816
6817    /// Whether this index contains missing labels, matching `pd.Index.hasnans`.
6818    #[must_use]
6819    pub fn hasnans(&self) -> bool {
6820        if self.labels.has_lazy_int64_backing() {
6821            return false;
6822        }
6823        self.labels.iter().any(IndexLabel::is_missing)
6824    }
6825
6826    /// Number of dimensions, matching `pd.Index.ndim`.
6827    #[must_use]
6828    pub fn ndim(&self) -> usize {
6829        1
6830    }
6831
6832    /// One-dimensional shape, matching `pd.Index.shape`.
6833    #[must_use]
6834    pub fn shape(&self) -> (usize,) {
6835        (self.len(),)
6836    }
6837
6838    /// Number of entries, matching `pd.Index.size`.
6839    #[must_use]
6840    pub fn size(&self) -> usize {
6841        self.len()
6842    }
6843
6844    /// Shallow byte footprint, matching `pd.Index.nbytes`.
6845    #[must_use]
6846    pub fn nbytes(&self) -> usize {
6847        self.memory_usage(false)
6848    }
6849
6850    /// Alias for `is_empty`, matching the pandas `.empty` property.
6851    #[must_use]
6852    pub fn empty(&self) -> bool {
6853        self.is_empty()
6854    }
6855
6856    /// Return the single contained label.
6857    ///
6858    /// Matches `pd.Index.item()`, which rejects indexes with length other than
6859    /// one.
6860    pub fn item(&self) -> Result<IndexLabel, IndexError> {
6861        if self.len() == 1 {
6862            if self.labels.has_lazy_int64_backing()
6863                && let Some(values) = self.labels.int64_view()
6864                && let Some(&value) = values.first()
6865            {
6866                return Ok(IndexLabel::Int64(value));
6867            }
6868            Ok(self.labels[0].clone())
6869        } else {
6870            Err(IndexError::InvalidArgument(format!(
6871                "item requires exactly one label, got {}",
6872                self.len()
6873            )))
6874        }
6875    }
6876
6877    /// Identity check, matching `pd.Index.is_`.
6878    #[must_use]
6879    pub fn is_(&self, other: &Self) -> bool {
6880        std::ptr::eq(self, other)
6881    }
6882
6883    /// Whether all non-missing labels are booleans.
6884    #[must_use]
6885    pub fn is_boolean(&self) -> bool {
6886        false
6887    }
6888
6889    /// Whether this generic index is categorical.
6890    #[must_use]
6891    pub fn is_categorical(&self) -> bool {
6892        false
6893    }
6894
6895    /// Whether all non-missing labels are floating-point.
6896    #[must_use]
6897    pub fn is_floating(&self) -> bool {
6898        false
6899    }
6900
6901    /// Whether all non-missing labels are Int64 labels.
6902    #[must_use]
6903    pub fn is_integer(&self) -> bool {
6904        if self.labels.has_lazy_int64_backing() {
6905            return !self.labels.is_empty();
6906        }
6907        !self.labels.is_empty()
6908            && self
6909                .labels
6910                .iter()
6911                .filter(|label| !label.is_missing())
6912                .all(|label| matches!(label, IndexLabel::Int64(_)))
6913    }
6914
6915    /// Whether this generic index is interval-typed.
6916    #[must_use]
6917    pub fn is_interval(&self) -> bool {
6918        false
6919    }
6920
6921    /// Whether all non-missing labels are numeric.
6922    #[must_use]
6923    pub fn is_numeric(&self) -> bool {
6924        self.is_integer()
6925    }
6926
6927    /// Whether this index is object-backed.
6928    #[must_use]
6929    pub fn is_object(&self) -> bool {
6930        matches!(self.dtype(), "object")
6931    }
6932
6933    /// Alias for `isna`, matching `pd.Index.isnull`.
6934    #[must_use]
6935    pub fn isnull(&self) -> Vec<bool> {
6936        self.isna()
6937    }
6938
6939    /// Alias for `notna`, matching `pd.Index.notnull`.
6940    #[must_use]
6941    pub fn notnull(&self) -> Vec<bool> {
6942        self.notna()
6943    }
6944
6945    /// Factorize labels into integer codes and unique labels.
6946    ///
6947    /// Missing labels receive code `-1`; non-missing labels preserve first-seen
6948    /// order in the returned uniques index.
6949    #[must_use]
6950    pub fn factorize(&self) -> (Vec<isize>, Self) {
6951        // Typed all-Int64 fast path: inline `i64` codes (dense code table when
6952        // the value span is bounded) instead of the cloned-key
6953        // `FxHashMap<IndexLabel, isize>`. Int64 labels are never missing, so the
6954        // generic `-1` missing branch never fires — bit-identical codes/uniques.
6955        if let Some(vals) = self.labels.int64_view() {
6956            let (codes, uniques) = Self::factorize_i64(&vals);
6957            // Build the uniques over the typed Int64 backing — defers the
6958            // per-label `IndexLabel` materialization the `Vec<IndexLabel>` form
6959            // would force (the dominant tail at high cardinality).
6960            return (codes, self.propagate_name(Self::from_i64(uniques)));
6961        }
6962        let mut positions = FxHashMap::<IndexLabel, isize>::default();
6963        let mut uniques = Vec::<IndexLabel>::new();
6964        let mut codes = Vec::with_capacity(self.labels.len());
6965        for label in &self.labels {
6966            if label.is_missing() {
6967                codes.push(-1);
6968            } else if let Some(code) = positions.get(label) {
6969                codes.push(*code);
6970            } else {
6971                let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
6972                positions.insert(label.clone(), code);
6973                uniques.push(label.clone());
6974                codes.push(code);
6975            }
6976        }
6977        (codes, self.propagate_name(Self::new(uniques)))
6978    }
6979
6980    /// Positional indexer that EXPANDS duplicate matches, matching
6981    /// `pd.Index.get_indexer_for`.
6982    ///
6983    /// ⚠️ This was an alias for [`Self::get_indexer`], and pandas defines the two as
6984    /// DIFFERENT precisely when the source has duplicates — that is the whole reason
6985    /// `get_indexer_for` exists. pandas' rule is: `get_indexer` when the index is
6986    /// unique, otherwise `get_indexer_non_unique(target)[0]`, so the result can be
6987    /// LONGER than `target`.
6988    ///
6989    /// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18), index `[10, 20, 20, 30]`:
6990    /// ```text
6991    ///   target [20, 99, 10]
6992    ///   get_indexer_for -> [1, 2, -1, 0]     FOUR entries for a THREE-entry target
6993    ///   get_indexer     -> InvalidIndexError: Reindexing only valid with uniquely
6994    ///                      valued Index objects
6995    /// ```
6996    /// The duplicate 20 contributes both of its positions. A `-1` (missing) becomes
6997    /// `None` here, keeping this crate's `Option` spelling.
6998    ///
6999    /// The sibling [`MultiIndex::get_indexer`] already models this correctly — it
7000    /// REFUSES a duplicate-bearing source and documents that callers wanting
7001    /// expansion should use `get_indexer_for` or `get_indexer_non_unique`. The flat
7002    /// index simply had not been given the same treatment.
7003    ///
7004    /// ⚠️ [`Self::get_indexer`] still does NOT refuse a duplicate source the way
7005    /// pandas does; it answers with the first match per target. Changing that is a
7006    /// signature question (it returns a `Vec`, not a `Result`) and is left alone
7007    /// here so this stays a behaviour fix on one method.
7008    #[must_use]
7009    pub fn get_indexer_for(&self, target: &Self) -> Vec<Option<usize>> {
7010        if self.has_duplicates() {
7011            return self
7012                .get_indexer_non_unique(target)
7013                .0
7014                .into_iter()
7015                .map(|position| usize::try_from(position).ok())
7016                .collect();
7017        }
7018        self.get_indexer(target)
7019    }
7020
7021    /// Expand duplicate matches while indexing a target index.
7022    ///
7023    /// Matches `pd.Index.get_indexer_non_unique(target)` shape: every matching
7024    /// source position is emitted for each target label, and missing target
7025    /// ordinal positions are returned separately.
7026    #[must_use]
7027    pub fn get_indexer_non_unique(&self, target: &Self) -> (Vec<isize>, Vec<usize>) {
7028        if let (Some(source), Some(targets)) =
7029            (self.labels.int64_view(), target.labels.int64_view())
7030        {
7031            if let Some(result) = Self::get_indexer_non_unique_sorted_dense_i64(&source, &targets) {
7032                return result;
7033            }
7034
7035            let mut positions = FxHashMap::<i64, Vec<usize>>::default();
7036            for (position, &label) in source.iter().enumerate() {
7037                positions.entry(label).or_default().push(position);
7038            }
7039
7040            let mut indexer = Vec::with_capacity(targets.len());
7041            let mut missing = Vec::new();
7042            for (target_position, &label) in targets.iter().enumerate() {
7043                if let Some(source_positions) = positions.get(&label) {
7044                    indexer.extend(
7045                        source_positions
7046                            .iter()
7047                            .map(|position| isize::try_from(*position).unwrap_or(isize::MAX)),
7048                    );
7049                } else {
7050                    indexer.push(-1);
7051                    missing.push(target_position);
7052                }
7053            }
7054            return (indexer, missing);
7055        }
7056
7057        // Typed all-Utf8 fast path: key the source position map on `&str` instead
7058        // of cloning every source `IndexLabel` (a String alloc per source row).
7059        // Gate BOTH sides pure Utf8 (no Null) so every target label is a `&str`
7060        // lookup (no skipped emissions). Bit-identical: same per-key source-order
7061        // position lists, same target-order indexer, same missing list.
7062        let self_labels = self.labels();
7063        let target_labels = target.labels();
7064        if self_labels.iter().all(|l| matches!(l, IndexLabel::Utf8(_)))
7065            && target_labels
7066                .iter()
7067                .all(|l| matches!(l, IndexLabel::Utf8(_)))
7068        {
7069            let mut positions = FxHashMap::<&str, Vec<usize>>::default();
7070            for (position, label) in self_labels.iter().enumerate() {
7071                if let IndexLabel::Utf8(s) = label {
7072                    positions.entry(s.as_str()).or_default().push(position);
7073                }
7074            }
7075            let mut indexer = Vec::new();
7076            let mut missing = Vec::new();
7077            for (target_position, label) in target_labels.iter().enumerate() {
7078                if let IndexLabel::Utf8(s) = label {
7079                    if let Some(source_positions) = positions.get(s.as_str()) {
7080                        indexer.extend(
7081                            source_positions
7082                                .iter()
7083                                .map(|position| isize::try_from(*position).unwrap_or(isize::MAX)),
7084                        );
7085                    } else {
7086                        indexer.push(-1);
7087                        missing.push(target_position);
7088                    }
7089                }
7090            }
7091            return (indexer, missing);
7092        }
7093        let mut positions = FxHashMap::<IndexLabel, Vec<usize>>::default();
7094        for (position, label) in self.labels.iter().enumerate() {
7095            positions.entry(label.clone()).or_default().push(position);
7096        }
7097
7098        let mut indexer = Vec::new();
7099        let mut missing = Vec::new();
7100        for (target_position, label) in target.labels.iter().enumerate() {
7101            if let Some(source_positions) = positions.get(label) {
7102                indexer.extend(
7103                    source_positions
7104                        .iter()
7105                        .map(|position| isize::try_from(*position).unwrap_or(isize::MAX)),
7106                );
7107            } else {
7108                indexer.push(-1);
7109                missing.push(target_position);
7110            }
7111        }
7112        (indexer, missing)
7113    }
7114
7115    /// Get labels for a level. Flat indexes only accept level 0.
7116    pub fn get_level_values(&self, level: usize) -> Result<Self, IndexError> {
7117        if level == 0 {
7118            Ok(self.clone())
7119        } else {
7120            Err(IndexError::OutOfBounds {
7121                position: level,
7122                length: 1,
7123            })
7124        }
7125    }
7126
7127    /// Bound for a label slice, matching `pd.Index.get_slice_bound(label,
7128    /// side)`: over an increasing index where the label sorts; else the
7129    /// label's own position (one past it for the right side; a run of equal
7130    /// labels bounds by its ends), else where it sorts in a decreasing index.
7131    /// A label an unsorted index does not hold is pandas' KeyError of it
7132    /// ([`IndexError::LabelNotFound`]), one it holds apart from one run
7133    /// pandas' non-unique KeyError. It was a bare searchsorted, wrong on a
7134    /// decreasing or unsorted index (br-frankenpandas-h1kl9).
7135    pub fn get_slice_bound(&self, label: &IndexLabel, side: &str) -> Result<usize, IndexError> {
7136        let left = match side {
7137            "left" => true,
7138            "right" => false,
7139            other => {
7140                return Err(IndexError::InvalidArgument(format!(
7141                    "Invalid value for side kwarg, must be either 'left' or 'right': {other}"
7142                )));
7143            }
7144        };
7145        if self.is_monotonic_increasing() {
7146            return self.searchsorted(label, side);
7147        }
7148        let labels = self.labels();
7149        let matches: Vec<usize> = labels
7150            .iter()
7151            .enumerate()
7152            .filter(|(_, candidate)| *candidate == label)
7153            .map(|(position, _)| position)
7154            .collect();
7155        if let (Some(&first), Some(&last)) = (matches.first(), matches.last()) {
7156            // Ascending positions are one run exactly when they span their
7157            // count.
7158            if last - first + 1 != matches.len() {
7159                let shown = match label {
7160                    IndexLabel::Utf8(text) => format!("'{text}'"),
7161                    other => other.to_string(),
7162                };
7163                return Err(IndexError::KeyError(format!(
7164                    "Cannot get {side} slice bound for non-unique label: {shown}"
7165                )));
7166            }
7167            return Ok(if left { first } else { last + 1 });
7168        }
7169        if self.is_monotonic_decreasing() && !label.is_missing() {
7170            // The labels above the label (left) or not below it (right).
7171            return Ok(labels
7172                .iter()
7173                .filter(|candidate| {
7174                    if left {
7175                        *candidate > label
7176                    } else {
7177                        *candidate >= label
7178                    }
7179                })
7180                .count());
7181        }
7182        Err(IndexError::LabelNotFound(label.clone()))
7183    }
7184
7185    /// Return `(start, stop)` bounds for a label slice, as pandas'
7186    /// `Index.slice_locs(start, end)`: each bound's [`Self::get_slice_bound`],
7187    /// stop exclusive and not raised to the start (a stop before the start
7188    /// slices nothing; it was clamped to the start).
7189    pub fn slice_locs(
7190        &self,
7191        start: Option<&IndexLabel>,
7192        end: Option<&IndexLabel>,
7193    ) -> Result<(usize, usize), IndexError> {
7194        let start = match start {
7195            Some(label) => self.get_slice_bound(label, "left")?,
7196            None => 0,
7197        };
7198        let end = match end {
7199            Some(label) => self.get_slice_bound(label, "right")?,
7200            None => self.len(),
7201        };
7202        Ok((start, end))
7203    }
7204
7205    /// Alias for `slice_locs`, matching `pd.Index.slice_indexer`.
7206    pub fn slice_indexer(
7207        &self,
7208        start: Option<&IndexLabel>,
7209        end: Option<&IndexLabel>,
7210    ) -> Result<(usize, usize), IndexError> {
7211        self.slice_locs(start, end)
7212    }
7213
7214    /// Reindex to a target index, returning the target and source positions.
7215    #[must_use]
7216    pub fn reindex(&self, target: &Self) -> (Self, Vec<Option<usize>>) {
7217        (target.clone(), self.get_indexer(target))
7218    }
7219
7220    /// Flat-index `droplevel` is invalid because it would remove the only
7221    /// level.
7222    pub fn droplevel(&self, level: usize) -> Result<Self, IndexError> {
7223        if level == 0 {
7224            Err(IndexError::InvalidArgument(
7225                "cannot remove the only level from a flat Index".to_owned(),
7226            ))
7227        } else {
7228            Err(IndexError::OutOfBounds {
7229                position: level,
7230                length: 1,
7231            })
7232        }
7233    }
7234
7235    /// Round Float64 labels to `decimals` places, halves to even as numpy's
7236    /// `around` (which pandas' `Index.round` uses) does; a negative
7237    /// `decimals` rounds to tens, hundreds, ... and then changes Int64 labels
7238    /// too. Other labels are unchanged. This used to return the index
7239    /// unchanged, float labels included
7240    /// (br-frankenpandas-rc0923-epic-python-honest-dropin-fvsao.5).
7241    #[must_use]
7242    pub fn round(&self, decimals: i32) -> Self {
7243        let labels = self
7244            .labels()
7245            .iter()
7246            .map(|label| match label {
7247                IndexLabel::Float64(f) => {
7248                    IndexLabel::Float64(OrderedF64(round_half_even(f.0, decimals)))
7249                }
7250                IndexLabel::Int64(i) if decimals < 0 => {
7251                    IndexLabel::Int64(round_half_even(*i as f64, decimals) as i64)
7252                }
7253                other => other.clone(),
7254            })
7255            .collect();
7256        Self::new(labels).rename_index(self.name())
7257    }
7258
7259    /// String accessor for Utf8 labels, matching `pd.Index.str`.
7260    #[must_use]
7261    pub fn r#str(&self) -> IndexStringAccessor<'_> {
7262        IndexStringAccessor::borrowed(self)
7263    }
7264
7265    /// Group label positions by label value, matching `pd.Index.groupby`.
7266    #[must_use]
7267    pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
7268        let mut groups = HashMap::<IndexLabel, Vec<usize>>::new();
7269        if self.labels.has_lazy_int64_backing()
7270            && let Some(values) = self.labels.int64_view()
7271        {
7272            for (position, &value) in values.iter().enumerate() {
7273                groups
7274                    .entry(IndexLabel::Int64(value))
7275                    .or_default()
7276                    .push(position);
7277            }
7278            return groups;
7279        }
7280        for (position, label) in self.labels.iter().enumerate() {
7281            groups.entry(label.clone()).or_default().push(position);
7282        }
7283        groups
7284    }
7285
7286    /// Join two flat indexes using pandas-style join modes.
7287    pub fn join(&self, other: &Self, how: &str) -> Result<Self, IndexError> {
7288        match how {
7289            "left" => Ok(self.clone()),
7290            "right" => Ok(other.clone()),
7291            "inner" => Ok(self.intersection(other)),
7292            "outer" => Ok(self.union_with(other)),
7293            other => Err(IndexError::InvalidArgument(format!(
7294                "join: how must be 'left', 'right', 'inner', or 'outer', got {other:?}"
7295            ))),
7296        }
7297    }
7298
7299    /// Locate nearest preceding-or-equal positions for each target label.
7300    ///
7301    /// Matches `pd.Index.asof_locs(where, mask)` for monotonic flat indexes.
7302    #[must_use]
7303    pub fn asof_locs(&self, where_index: &Self, mask: Option<&[bool]>) -> Vec<Option<usize>> {
7304        if self.labels.has_lazy_int64_backing()
7305            && where_index.labels.has_lazy_int64_backing()
7306            && let (Some(source), Some(keys)) =
7307                (self.labels.int64_view(), where_index.labels.int64_view())
7308        {
7309            if mask.is_none() {
7310                if source.windows(2).all(|pair| pair[0] <= pair[1])
7311                    && keys.windows(2).all(|pair| pair[0] <= pair[1])
7312                {
7313                    let mut out = Vec::with_capacity(keys.len());
7314                    let mut source_pos = 0usize;
7315                    for &key in keys.iter() {
7316                        while source_pos < source.len() && source[source_pos] <= key {
7317                            source_pos += 1;
7318                        }
7319                        out.push(source_pos.checked_sub(1));
7320                    }
7321                    return out;
7322                }
7323                return keys
7324                    .iter()
7325                    .map(|&key| {
7326                        let mut lo = 0usize;
7327                        let mut hi = source.len();
7328                        while lo < hi {
7329                            let mid = lo + (hi - lo) / 2;
7330                            if source[mid] <= key {
7331                                lo = mid + 1;
7332                            } else {
7333                                hi = mid;
7334                            }
7335                        }
7336                        lo.checked_sub(1)
7337                    })
7338                    .collect();
7339            }
7340            return keys
7341                .iter()
7342                .map(|&key| {
7343                    let mut best = None;
7344                    for (position, &label) in source.iter().enumerate() {
7345                        if mask
7346                            .and_then(|values| values.get(position))
7347                            .is_some_and(|include| !include)
7348                        {
7349                            continue;
7350                        }
7351                        if label <= key {
7352                            best = Some(position);
7353                        } else {
7354                            break;
7355                        }
7356                    }
7357                    best
7358                })
7359                .collect();
7360        }
7361        where_index
7362            .labels
7363            .iter()
7364            .map(|key| {
7365                let mut best = None;
7366                for (position, label) in self.labels.iter().enumerate() {
7367                    if mask
7368                        .and_then(|values| values.get(position))
7369                        .is_some_and(|include| !include)
7370                    {
7371                        continue;
7372                    }
7373                    if label.is_missing() {
7374                        continue;
7375                    }
7376                    if label.cmp(key).is_le() {
7377                        best = Some(position);
7378                    } else {
7379                        break;
7380                    }
7381                }
7382                best
7383            })
7384            .collect()
7385    }
7386
7387    /// Positional first differences for comparable scalar index labels.
7388    ///
7389    /// Int64 and Timedelta64 labels produce same-kind differences. Datetime64
7390    /// labels produce Timedelta64 deltas. Unsupported label combinations and
7391    /// overflow return `None` for that position.
7392    #[must_use]
7393    pub fn diff(&self, periods: usize) -> Vec<Option<IndexLabel>> {
7394        if periods == 0 {
7395            if let Some(values) = self.labels.int64_view() {
7396                return values.iter().map(|_| Some(IndexLabel::Int64(0))).collect();
7397            }
7398            return self
7399                .labels
7400                .iter()
7401                .map(|label| match label {
7402                    IndexLabel::Int64(_) => Some(IndexLabel::Int64(0)),
7403                    IndexLabel::Timedelta64(current) if *current != Timedelta::NAT => {
7404                        Some(IndexLabel::Timedelta64(0))
7405                    }
7406                    IndexLabel::Datetime64(current) if *current != i64::MIN => {
7407                        Some(IndexLabel::Timedelta64(0))
7408                    }
7409                    _ => None,
7410                })
7411                .collect();
7412        }
7413        if let Some(values) = self.labels.int64_view() {
7414            let leading = periods.min(values.len());
7415            let mut out = Vec::with_capacity(values.len());
7416            out.extend(std::iter::repeat_n(None, leading));
7417            if periods >= values.len() {
7418                return out;
7419            }
7420            for (&current, &previous) in values[periods..]
7421                .iter()
7422                .zip(&values[..values.len() - periods])
7423            {
7424                out.push(current.checked_sub(previous).map(IndexLabel::Int64));
7425            }
7426            return out;
7427        }
7428        let mut out = vec![None; self.len()];
7429        for (position, slot) in out.iter_mut().enumerate().skip(periods) {
7430            *slot = match (&self.labels[position], &self.labels[position - periods]) {
7431                (IndexLabel::Int64(current), IndexLabel::Int64(previous)) => {
7432                    current.checked_sub(*previous).map(IndexLabel::Int64)
7433                }
7434                (IndexLabel::Timedelta64(current), IndexLabel::Timedelta64(previous))
7435                    if *current != Timedelta::NAT && *previous != Timedelta::NAT =>
7436                {
7437                    current.checked_sub(*previous).map(IndexLabel::Timedelta64)
7438                }
7439                (IndexLabel::Datetime64(current), IndexLabel::Datetime64(previous))
7440                    if *current != i64::MIN && *previous != i64::MIN =>
7441                {
7442                    current.checked_sub(*previous).map(IndexLabel::Timedelta64)
7443                }
7444                _ => None,
7445            };
7446        }
7447        out
7448    }
7449}
7450
7451#[derive(Debug, Clone)]
7452pub struct IndexStringAccessor<'a> {
7453    index: Cow<'a, Index>,
7454}
7455
7456impl<'a> IndexStringAccessor<'a> {
7457    fn borrowed(index: &'a Index) -> Self {
7458        Self {
7459            index: Cow::Borrowed(index),
7460        }
7461    }
7462
7463    fn owned(index: Index) -> Self {
7464        Self {
7465            index: Cow::Owned(index),
7466        }
7467    }
7468
7469    fn map_utf8<T>(&self, func: impl Fn(&str) -> T) -> Vec<Option<T>> {
7470        self.index
7471            .labels()
7472            .iter()
7473            .map(|label| match label {
7474                IndexLabel::Utf8(value) => Some(func(value)),
7475                IndexLabel::Int64(_)
7476                | IndexLabel::Float64(_)
7477                | IndexLabel::Bool(_)
7478                | IndexLabel::Timedelta64(_)
7479                | IndexLabel::Datetime64(_)
7480                | IndexLabel::Object(_)
7481                | IndexLabel::Period(_)
7482                | IndexLabel::Interval(_)
7483                | IndexLabel::Null(_) => None,
7484            })
7485            .collect()
7486    }
7487
7488    /// Lowercase string labels.
7489    #[must_use]
7490    pub fn lower(&self) -> Vec<Option<String>> {
7491        self.map_utf8(str::to_lowercase)
7492    }
7493
7494    /// Uppercase string labels.
7495    #[must_use]
7496    pub fn upper(&self) -> Vec<Option<String>> {
7497        self.map_utf8(str::to_uppercase)
7498    }
7499
7500    /// Substring membership for string labels.
7501    #[must_use]
7502    pub fn contains(&self, needle: &str) -> Vec<Option<bool>> {
7503        self.map_utf8(|value| value.contains(needle))
7504    }
7505
7506    /// String length for string labels.
7507    #[must_use]
7508    pub fn len(&self) -> Vec<Option<usize>> {
7509        self.map_utf8(str::len)
7510    }
7511
7512    /// String emptiness for string labels.
7513    #[must_use]
7514    pub fn is_empty(&self) -> Vec<Option<bool>> {
7515        self.map_utf8(str::is_empty)
7516    }
7517}
7518
7519fn datetime_from_nanos(nanos: i64) -> Option<chrono::DateTime<chrono::Utc>> {
7520    if nanos == i64::MIN {
7521        return None;
7522    }
7523    let secs = nanos.div_euclid(1_000_000_000);
7524    let subsec_nanos = nanos.rem_euclid(1_000_000_000) as u32;
7525    chrono::DateTime::from_timestamp(secs, subsec_nanos)
7526}
7527
7528fn datetime_to_period_error(message: impl Into<String>) -> IndexError {
7529    IndexError::InvalidArgument(format!(
7530        "DatetimeIndex to_period failed: {}",
7531        message.into()
7532    ))
7533}
7534
7535/// The weekly ordinal of `date` for weeks ending on `freq`'s weekday:
7536/// whole weeks since the Monday 1969-12-22, the week start moved `shift`
7537/// days later for an anchor other than Sunday (W-MON weeks start Tuesday).
7538fn date_to_weekly_period_ordinal(
7539    date: chrono::NaiveDate,
7540    freq: PeriodFreq,
7541) -> Result<i64, IndexError> {
7542    let base = period_epoch_date(1969, 12, 22)?;
7543    Ok((date.signed_duration_since(base).num_days() - freq.week_start_shift()).div_euclid(7))
7544}
7545
7546/// `date`'s month count since 1970-01 on `freq`'s fiscal calendar: a fiscal
7547/// year ending in June starts in July, so July 2023 counts as the first
7548/// month of fiscal 2024 (Period('2023-07-01', 'Y-JUN') is '2024').
7549fn fiscal_month_ordinal(date: chrono::NaiveDate, freq: PeriodFreq) -> Result<i64, IndexError> {
7550    (i64::from(date.year()) - 1970)
7551        .checked_mul(12)
7552        .and_then(|base| base.checked_add(i64::from(date.month() - 1)))
7553        .and_then(|months| months.checked_add(freq.fiscal_month_shift()))
7554        .ok_or_else(|| datetime_to_period_error("fiscal month ordinal overflow"))
7555}
7556
7557fn business_period_anchor_date(date: chrono::NaiveDate) -> Result<chrono::NaiveDate, IndexError> {
7558    match date.weekday().num_days_from_monday() {
7559        5 => period_add_days(date, 2),
7560        6 => period_add_days(date, 1),
7561        _ => Ok(date),
7562    }
7563}
7564
7565fn date_to_business_period_ordinal(date: chrono::NaiveDate) -> Result<i64, IndexError> {
7566    let adjusted = business_period_anchor_date(date)?;
7567    let days = adjusted
7568        .signed_duration_since(period_epoch_date(1970, 1, 1)?)
7569        .num_days();
7570    let rem_ordinal = match days.rem_euclid(7) {
7571        0 => 0,
7572        1 => 1,
7573        4 => 2,
7574        5 => 3,
7575        6 => 4,
7576        _ => {
7577            return Err(datetime_to_period_error(
7578                "business period anchor did not land on a business day",
7579            ));
7580        }
7581    };
7582    days.div_euclid(7)
7583        .checked_mul(5)
7584        .and_then(|base| base.checked_add(rem_ordinal))
7585        .ok_or_else(|| datetime_to_period_error("business ordinal overflow"))
7586}
7587
7588fn business_period_end_anchor_date(
7589    date: chrono::NaiveDate,
7590) -> Result<chrono::NaiveDate, IndexError> {
7591    match date.weekday().num_days_from_monday() {
7592        5 => period_add_days(date, -1),
7593        6 => period_add_days(date, -2),
7594        _ => Ok(date),
7595    }
7596}
7597
7598fn datetime_period_ordinal(nanos: i64, freq: PeriodFreq) -> Result<i64, IndexError> {
7599    let dt = datetime_from_nanos(nanos).ok_or_else(|| {
7600        datetime_to_period_error(format!("invalid or NaT datetime nanos {nanos}"))
7601    })?;
7602    let date = dt.date_naive();
7603    let year_offset = i64::from(date.year()) - 1970;
7604    match freq {
7605        // Fiscal years / quarters: the month count on the fiscal calendar,
7606        // twelve (three) to a period (Q-JAN puts 2024-03 in 2025Q1).
7607        PeriodFreq::Annual(_) => {
7608            fiscal_month_ordinal(date, freq).map(|months| months.div_euclid(12))
7609        }
7610        PeriodFreq::Quarterly(_) => {
7611            fiscal_month_ordinal(date, freq).map(|months| months.div_euclid(3))
7612        }
7613        PeriodFreq::Monthly => year_offset
7614            .checked_mul(12)
7615            .and_then(|base| base.checked_add(i64::from(date.month() - 1)))
7616            .ok_or_else(|| datetime_to_period_error("monthly ordinal overflow")),
7617        PeriodFreq::Daily => {
7618            let epoch = chrono::NaiveDate::from_ymd_opt(1970, 1, 1)
7619                .ok_or_else(|| datetime_to_period_error("invalid epoch boundary"))?;
7620            Ok(date.signed_duration_since(epoch).num_days())
7621        }
7622        PeriodFreq::Hourly => Ok(nanos.div_euclid(Timedelta::NANOS_PER_HOUR)),
7623        PeriodFreq::Minutely => Ok(nanos.div_euclid(Timedelta::NANOS_PER_MIN)),
7624        PeriodFreq::Secondly => Ok(nanos.div_euclid(Timedelta::NANOS_PER_SEC)),
7625        // MEASURED, live pandas 2.2.3: the ordinal is simply the unit count since
7626        // the epoch, FLOORED -- Timestamp('1969-12-31 23:59:59.999').to_period('ms')
7627        // has ordinal -1, and '...999000001' at 'ns' has -999999. div_euclid is
7628        // that floor; plain `/` would truncate toward zero and be wrong pre-epoch.
7629        PeriodFreq::Milliseconds => Ok(nanos.div_euclid(Timedelta::NANOS_PER_MILLI)),
7630        PeriodFreq::Microseconds => Ok(nanos.div_euclid(Timedelta::NANOS_PER_MICRO)),
7631        // Storage is already nanoseconds, so this is the identity.
7632        PeriodFreq::Nanoseconds => Ok(nanos),
7633        PeriodFreq::Weekly(_) => date_to_weekly_period_ordinal(date, freq),
7634        PeriodFreq::Business => date_to_business_period_ordinal(date),
7635        _ => Err(datetime_to_period_error("unsupported period frequency")),
7636    }
7637}
7638
7639fn datetime_period_ordinal_at_boundary(
7640    nanos: i64,
7641    freq: PeriodFreq,
7642    boundary: PeriodBoundary,
7643) -> Result<i64, IndexError> {
7644    if freq == PeriodFreq::Business && matches!(boundary, PeriodBoundary::End) {
7645        let dt = datetime_from_nanos(nanos).ok_or_else(|| {
7646            datetime_to_period_error(format!("invalid or NaT datetime nanos {nanos}"))
7647        })?;
7648        return date_to_business_period_ordinal(business_period_end_anchor_date(dt.date_naive())?);
7649    }
7650    datetime_period_ordinal(nanos, freq)
7651}
7652
7653/// The period of `freq` holding the wall-clock instant `nanos`, as pandas'
7654/// `Timestamp.to_period(freq)` (a NaT or out-of-range instant is an error).
7655pub fn datetime_nanos_to_period(nanos: i64, freq: PeriodFreq) -> Result<Period, IndexError> {
7656    datetime_period_ordinal(nanos, freq).map(|ordinal| Period::new(ordinal, freq))
7657}
7658
7659fn map_datetime_labels<T, F>(labels: &[IndexLabel], func: F) -> Vec<Option<T>>
7660where
7661    F: Fn(chrono::DateTime<chrono::Utc>) -> T,
7662{
7663    labels
7664        .iter()
7665        .map(|label| match label {
7666            IndexLabel::Datetime64(nanos) => datetime_from_nanos(*nanos).map(&func),
7667            IndexLabel::Int64(_)
7668            | IndexLabel::Float64(_)
7669            | IndexLabel::Bool(_)
7670            | IndexLabel::Utf8(_)
7671            | IndexLabel::Timedelta64(_)
7672            | IndexLabel::Object(_)
7673            | IndexLabel::Period(_)
7674            | IndexLabel::Interval(_)
7675            | IndexLabel::Null(_) => None,
7676        })
7677        .collect()
7678}
7679
7680fn time_to_nanos(time: chrono::NaiveTime) -> i64 {
7681    use chrono::Timelike;
7682    i64::from(time.num_seconds_from_midnight()) * 1_000_000_000 + i64::from(time.nanosecond())
7683}
7684
7685fn parse_time_of_day_nanos(time: &str, context: &str) -> Result<i64, IndexError> {
7686    let trimmed = time.trim();
7687    for format in ["%H:%M:%S%.f", "%H:%M:%S", "%H:%M"] {
7688        if let Ok(parsed) = chrono::NaiveTime::parse_from_str(trimmed, format) {
7689            return Ok(time_to_nanos(parsed));
7690        }
7691    }
7692    Err(IndexError::InvalidArgument(format!(
7693        "{context}: invalid time {time:?}; expected HH:MM, HH:MM:SS, or fractional seconds"
7694    )))
7695}
7696
7697fn datetime_label_time_nanos(label: &IndexLabel) -> Option<i64> {
7698    match label {
7699        IndexLabel::Datetime64(nanos) => {
7700            datetime_from_nanos(*nanos).map(|dt| time_to_nanos(dt.time()))
7701        }
7702        IndexLabel::Int64(_)
7703        | IndexLabel::Float64(_)
7704        | IndexLabel::Bool(_)
7705        | IndexLabel::Utf8(_)
7706        | IndexLabel::Timedelta64(_)
7707        | IndexLabel::Object(_)
7708        | IndexLabel::Period(_)
7709        | IndexLabel::Interval(_)
7710        | IndexLabel::Null(_) => None,
7711    }
7712}
7713
7714fn time_nanos_in_between(
7715    time: i64,
7716    start: i64,
7717    end: i64,
7718    include_start: bool,
7719    include_end: bool,
7720) -> bool {
7721    let after_start = if include_start {
7722        time >= start
7723    } else {
7724        time > start
7725    };
7726    let before_end = if include_end { time <= end } else { time < end };
7727    if start <= end {
7728        after_start && before_end
7729    } else {
7730        after_start || before_end
7731    }
7732}
7733
7734fn map_timedelta_labels<T, F>(labels: &[IndexLabel], func: F) -> Vec<Option<T>>
7735where
7736    F: Fn(i64) -> T,
7737{
7738    labels
7739        .iter()
7740        .map(|label| match label {
7741            IndexLabel::Timedelta64(nanos) if *nanos != Timedelta::NAT => Some(func(*nanos)),
7742            IndexLabel::Int64(_)
7743            | IndexLabel::Float64(_)
7744            | IndexLabel::Bool(_)
7745            | IndexLabel::Utf8(_)
7746            | IndexLabel::Timedelta64(_)
7747            | IndexLabel::Datetime64(_)
7748            | IndexLabel::Object(_)
7749            | IndexLabel::Period(_)
7750            | IndexLabel::Interval(_)
7751            | IndexLabel::Null(_) => None,
7752        })
7753        .collect()
7754}
7755
7756fn timedelta_components_for_index(nanos: i64) -> TimedeltaComponents {
7757    let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7758    let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7759
7760    let hours = rem / Timedelta::NANOS_PER_HOUR;
7761    let rem = rem % Timedelta::NANOS_PER_HOUR;
7762    let minutes = rem / Timedelta::NANOS_PER_MIN;
7763    let rem = rem % Timedelta::NANOS_PER_MIN;
7764    let seconds = rem / Timedelta::NANOS_PER_SEC;
7765    let rem = rem % Timedelta::NANOS_PER_SEC;
7766    let milliseconds = rem / Timedelta::NANOS_PER_MILLI;
7767    let rem = rem % Timedelta::NANOS_PER_MILLI;
7768    let microseconds = rem / Timedelta::NANOS_PER_MICRO;
7769    let nanoseconds = rem % Timedelta::NANOS_PER_MICRO;
7770
7771    TimedeltaComponents {
7772        days,
7773        hours,
7774        minutes,
7775        seconds,
7776        milliseconds,
7777        microseconds,
7778        nanoseconds,
7779    }
7780}
7781
7782#[derive(Clone, Copy)]
7783enum TemporalRoundMode {
7784    Floor,
7785    Ceil,
7786    Round,
7787}
7788
7789#[derive(Clone, Copy)]
7790enum PeriodBoundary {
7791    Start,
7792    End,
7793}
7794
7795fn parse_fixed_temporal_freq(freq: &str, context: &str) -> Result<i64, IndexError> {
7796    let trimmed = freq.trim();
7797    let unit_nanos = Timedelta::unit_to_nanos(trimmed)
7798        .or_else(|| Timedelta::parse(trimmed).ok())
7799        .ok_or_else(|| {
7800            IndexError::InvalidArgument(format!("{context}: invalid frequency {freq:?}"))
7801        })?;
7802    if unit_nanos <= 0 {
7803        return Err(IndexError::InvalidArgument(format!(
7804            "{context}: frequency must be positive, got {freq:?}"
7805        )));
7806    }
7807    Ok(unit_nanos)
7808}
7809
7810fn round_nanos_to_unit(nanos: i64, unit_nanos: i64, mode: TemporalRoundMode) -> i64 {
7811    match mode {
7812        TemporalRoundMode::Floor => nanos.div_euclid(unit_nanos).saturating_mul(unit_nanos),
7813        TemporalRoundMode::Ceil => {
7814            let rem = nanos.rem_euclid(unit_nanos);
7815            if rem == 0 {
7816                nanos
7817            } else {
7818                nanos.saturating_add(unit_nanos - rem)
7819            }
7820        }
7821        TemporalRoundMode::Round => {
7822            let floor = nanos.div_euclid(unit_nanos);
7823            let rem = nanos.rem_euclid(unit_nanos);
7824            if rem == 0 {
7825                return nanos;
7826            }
7827            let twice_rem = i128::from(rem) * 2;
7828            let unit = i128::from(unit_nanos);
7829            let chosen = if twice_rem < unit {
7830                floor
7831            } else if twice_rem > unit {
7832                floor.saturating_add(1)
7833            } else if floor % 2 == 0 {
7834                floor
7835            } else {
7836                floor.saturating_add(1)
7837            };
7838            chosen.saturating_mul(unit_nanos)
7839        }
7840    }
7841}
7842
7843fn positional_diff<T>(
7844    len: usize,
7845    periods: i64,
7846    mut diff_at: impl FnMut(usize, usize) -> Option<T>,
7847) -> Vec<Option<T>> {
7848    let mut out = (0..len).map(|_| None).collect::<Vec<_>>();
7849    if periods == 0 {
7850        for (position, slot) in out.iter_mut().enumerate() {
7851            *slot = diff_at(position, position);
7852        }
7853        return out;
7854    }
7855    let Ok(offset) = usize::try_from(periods.unsigned_abs()) else {
7856        return out;
7857    };
7858    if offset >= len {
7859        return out;
7860    }
7861    if periods > 0 {
7862        for (position, slot) in out.iter_mut().enumerate().skip(offset) {
7863            *slot = diff_at(position, position - offset);
7864        }
7865    } else {
7866        for (position, slot) in out.iter_mut().enumerate().take(len - offset) {
7867            *slot = diff_at(position, position + offset);
7868        }
7869    }
7870    out
7871}
7872
7873fn optional_diffs_to_timedelta_index(
7874    values: Vec<Option<i64>>,
7875    name: Option<&LabelName>,
7876) -> TimedeltaIndex {
7877    let mut out = TimedeltaIndex::new(
7878        values
7879            .into_iter()
7880            .map(|value| value.unwrap_or(Timedelta::NAT))
7881            .collect(),
7882    );
7883    if let Some(name) = name {
7884        out = out.set_name(name);
7885    }
7886    out
7887}
7888
7889fn period_timestamp_error(message: impl Into<String>) -> IndexError {
7890    IndexError::InvalidArgument(format!(
7891        "PeriodIndex timestamp conversion failed: {}",
7892        message.into()
7893    ))
7894}
7895
7896fn period_date_error(err: DateRangeError) -> IndexError {
7897    period_timestamp_error(err.to_string())
7898}
7899
7900fn period_date_to_nanos(date: chrono::NaiveDate) -> Result<i64, IndexError> {
7901    date_to_midnight_nanos(date).map_err(period_date_error)
7902}
7903
7904fn period_checked_add_nanos(nanos: i64, delta: i64) -> Result<i64, IndexError> {
7905    nanos
7906        .checked_add(delta)
7907        .ok_or_else(|| period_timestamp_error("nanosecond timestamp overflow"))
7908}
7909
7910fn period_month_start(month_ordinal: i64) -> Result<chrono::NaiveDate, IndexError> {
7911    let year = 1970_i64
7912        .checked_add(month_ordinal.div_euclid(12))
7913        .ok_or_else(|| period_timestamp_error("year overflow"))?;
7914    let year = i32::try_from(year).map_err(|_| period_timestamp_error("year out of range"))?;
7915    let month = u32::try_from(month_ordinal.rem_euclid(12) + 1)
7916        .map_err(|_| period_timestamp_error("month out of range"))?;
7917    chrono::NaiveDate::from_ymd_opt(year, month, 1)
7918        .ok_or_else(|| period_timestamp_error("invalid month boundary"))
7919}
7920
7921fn period_epoch_date(year: i32, month: u32, day: u32) -> Result<chrono::NaiveDate, IndexError> {
7922    chrono::NaiveDate::from_ymd_opt(year, month, day)
7923        .ok_or_else(|| period_timestamp_error("invalid epoch boundary"))
7924}
7925
7926fn period_add_days(date: chrono::NaiveDate, days: i64) -> Result<chrono::NaiveDate, IndexError> {
7927    let delta = chrono::Duration::try_days(days)
7928        .ok_or_else(|| period_timestamp_error("day offset overflow"))?;
7929    date.checked_add_signed(delta)
7930        .ok_or_else(|| period_timestamp_error("date overflow"))
7931}
7932
7933fn period_business_date(ordinal: i64) -> Result<chrono::NaiveDate, IndexError> {
7934    let week = ordinal.div_euclid(5);
7935    let day_offset = match ordinal.rem_euclid(5) {
7936        0 => 0,
7937        1 => 1,
7938        2 => 4,
7939        3 => 5,
7940        4 => 6,
7941        _ => {
7942            return Err(period_timestamp_error(
7943                "business-day remainder out of range",
7944            ));
7945        }
7946    };
7947    let calendar_days = week
7948        .checked_mul(7)
7949        .and_then(|days| days.checked_add(day_offset))
7950        .ok_or_else(|| period_timestamp_error("business-day ordinal overflow"))?;
7951    period_add_days(period_epoch_date(1970, 1, 1)?, calendar_days)
7952}
7953
7954/// The instant (epoch nanoseconds) a period starts at, pandas'
7955/// `Period.start_time`: fp-frame reads a period label there where a
7956/// datetime label's own instant is read (45fzr). NaT and an ordinal past
7957/// the calendar are errors.
7958pub fn period_start_nanos(period: Period) -> Result<i64, IndexError> {
7959    match period.freq {
7960        // A fiscal year / quarter starts the shift's months before its
7961        // calendar counterpart: Y-JUN 2024 (ordinal 54) starts 2023-07-01.
7962        PeriodFreq::Annual(_) | PeriodFreq::Quarterly(_) => {
7963            let months = if matches!(period.freq, PeriodFreq::Annual(_)) {
7964                12
7965            } else {
7966                3
7967            };
7968            let month_ordinal = period
7969                .ordinal
7970                .checked_mul(months)
7971                .and_then(|month| month.checked_sub(period.freq.fiscal_month_shift()))
7972                .ok_or_else(|| period_timestamp_error("fiscal ordinal overflow"))?;
7973            period_date_to_nanos(period_month_start(month_ordinal)?)
7974        }
7975        PeriodFreq::Monthly => period_date_to_nanos(period_month_start(period.ordinal)?),
7976        PeriodFreq::Weekly(_) => {
7977            let base = period_epoch_date(1969, 12, 22)?;
7978            let days = period
7979                .ordinal
7980                .checked_mul(7)
7981                .and_then(|days| days.checked_add(period.freq.week_start_shift()))
7982                .ok_or_else(|| period_timestamp_error("weekly ordinal overflow"))?;
7983            period_date_to_nanos(period_add_days(base, days)?)
7984        }
7985        PeriodFreq::Daily => {
7986            let base = period_epoch_date(1970, 1, 1)?;
7987            period_date_to_nanos(period_add_days(base, period.ordinal)?)
7988        }
7989        PeriodFreq::Business => period_date_to_nanos(period_business_date(period.ordinal)?),
7990        PeriodFreq::Hourly => period
7991            .ordinal
7992            .checked_mul(Timedelta::NANOS_PER_HOUR)
7993            .ok_or_else(|| period_timestamp_error("hourly ordinal overflow")),
7994        PeriodFreq::Minutely => period
7995            .ordinal
7996            .checked_mul(Timedelta::NANOS_PER_MIN)
7997            .ok_or_else(|| period_timestamp_error("minutely ordinal overflow")),
7998        PeriodFreq::Secondly => period
7999            .ordinal
8000            .checked_mul(Timedelta::NANOS_PER_SEC)
8001            .ok_or_else(|| period_timestamp_error("secondly ordinal overflow")),
8002        PeriodFreq::Milliseconds => period
8003            .ordinal
8004            .checked_mul(Timedelta::NANOS_PER_MILLI)
8005            .ok_or_else(|| period_timestamp_error("millisecond ordinal overflow")),
8006        PeriodFreq::Microseconds => period
8007            .ordinal
8008            .checked_mul(Timedelta::NANOS_PER_MICRO)
8009            .ok_or_else(|| period_timestamp_error("microsecond ordinal overflow")),
8010        // Identity, and therefore the one arm that cannot overflow -- which also
8011        // makes period_end_nanos (next_start - 1ns) collapse to the start, the
8012        // correct end for a period one nanosecond wide.
8013        PeriodFreq::Nanoseconds => Ok(period.ordinal),
8014        _ => Err(period_timestamp_error("unsupported period frequency")),
8015    }
8016}
8017
8018fn period_next_start_nanos(period: Period) -> Result<i64, IndexError> {
8019    let next = Period {
8020        ordinal: period
8021            .ordinal
8022            .checked_add(1)
8023            .ok_or_else(|| period_timestamp_error("period ordinal overflow"))?,
8024        freq: period.freq,
8025    };
8026    period_start_nanos(next)
8027}
8028
8029fn period_end_nanos(period: Period) -> Result<i64, IndexError> {
8030    period_checked_add_nanos(period_next_start_nanos(period)?, -1)
8031}
8032
8033fn period_boundary_nanos(period: Period, boundary: PeriodBoundary) -> Result<i64, IndexError> {
8034    // A NaT period's boundary is NaT (pandas' start_time / end_time /
8035    // to_timestamp of NaT; every field read through it raised).
8036    if period.ordinal == i64::MIN {
8037        return Ok(i64::MIN);
8038    }
8039    match boundary {
8040        PeriodBoundary::Start => period_start_nanos(period),
8041        PeriodBoundary::End => period_end_nanos(period),
8042    }
8043}
8044
8045fn parse_period_boundary_how(how: &str, context: &str) -> Result<PeriodBoundary, IndexError> {
8046    match how.trim().to_ascii_lowercase().as_str() {
8047        "" | "e" | "end" | "finish" => Ok(PeriodBoundary::End),
8048        "s" | "start" | "begin" | "b" => Ok(PeriodBoundary::Start),
8049        other => Err(IndexError::InvalidArgument(format!(
8050            "{context} how must be 'start' or 'end', got {other:?}"
8051        ))),
8052    }
8053}
8054
8055fn period_qyear(period: Period) -> Result<i32, IndexError> {
8056    // pandas' field of a NaT period is -1.
8057    if period.ordinal == i64::MIN {
8058        return Ok(-1);
8059    }
8060    // A quarter's qyear is the fiscal year its ordinal counts: Q-JAN's
8061    // 2025Q1 ends 2024-04-30 and its qyear is 2025.
8062    if matches!(period.freq, PeriodFreq::Quarterly(_)) {
8063        return i32::try_from(1970 + period.ordinal.div_euclid(4))
8064            .map_err(|_| period_timestamp_error("qyear out of range"));
8065    }
8066    let end_nanos = period_end_nanos(period)?;
8067    datetime_nanos_to_date(end_nanos)
8068        .map(|date| date.year())
8069        .map_err(period_date_error)
8070}
8071
8072#[derive(Debug, Clone, Copy)]
8073pub struct PeriodFields<'a> {
8074    pub year: &'a [i32],
8075    pub quarter: Option<&'a [u32]>,
8076    pub month: Option<&'a [u32]>,
8077    pub day: Option<&'a [u32]>,
8078    pub hour: Option<&'a [u32]>,
8079    pub minute: Option<&'a [u32]>,
8080    pub second: Option<&'a [u32]>,
8081    pub freq: Option<PeriodFreq>,
8082}
8083
8084impl<'a> PeriodFields<'a> {
8085    #[must_use]
8086    pub const fn new(year: &'a [i32]) -> Self {
8087        Self {
8088            year,
8089            quarter: None,
8090            month: None,
8091            day: None,
8092            hour: None,
8093            minute: None,
8094            second: None,
8095            freq: None,
8096        }
8097    }
8098}
8099
8100fn period_fields_error(message: impl Into<String>) -> IndexError {
8101    IndexError::InvalidArgument(format!(
8102        "PeriodIndex.from_fields failed: {}",
8103        message.into()
8104    ))
8105}
8106
8107fn period_fields_freq(fields: &PeriodFields<'_>) -> Result<PeriodFreq, IndexError> {
8108    let freq = fields
8109        .freq
8110        .or_else(|| fields.quarter.map(|_| PeriodFreq::QUARTERLY))
8111        .ok_or_else(|| {
8112            period_fields_error("freq is required unless quarter fields imply quarterly periods")
8113        })?;
8114    if fields.quarter.is_some() && !matches!(freq, PeriodFreq::Quarterly(_)) {
8115        return Err(period_fields_error(
8116            "quarter fields require quarterly frequency",
8117        ));
8118    }
8119    Ok(freq)
8120}
8121
8122fn validate_period_field_len(
8123    name: &str,
8124    values: Option<&[u32]>,
8125    expected: usize,
8126) -> Result<(), IndexError> {
8127    if values.is_some_and(|items| items.len() != expected) {
8128        return Err(period_fields_error(format!(
8129            "Mismatched Period array lengths for {name}"
8130        )));
8131    }
8132    Ok(())
8133}
8134
8135fn validate_period_fields(fields: &PeriodFields<'_>) -> Result<(), IndexError> {
8136    let expected = fields.year.len();
8137    validate_period_field_len("quarter", fields.quarter, expected)?;
8138    validate_period_field_len("month", fields.month, expected)?;
8139    validate_period_field_len("day", fields.day, expected)?;
8140    validate_period_field_len("hour", fields.hour, expected)?;
8141    validate_period_field_len("minute", fields.minute, expected)?;
8142    validate_period_field_len("second", fields.second, expected)
8143}
8144
8145fn period_field_value(values: Option<&[u32]>, position: usize, default: u32) -> u32 {
8146    values
8147        .and_then(|items| items.get(position).copied())
8148        .unwrap_or(default)
8149}
8150
8151fn required_period_field(
8152    values: Option<&[u32]>,
8153    name: &str,
8154    position: usize,
8155) -> Result<u32, IndexError> {
8156    values
8157        .and_then(|items| items.get(position).copied())
8158        .ok_or_else(|| period_fields_error(format!("{name} fields are required")))
8159}
8160
8161/// The period a fiscal `year` and `quarter` name under `freq` (pandas'
8162/// quarter_to_myear): the ordinal counts fiscal quarters, so Q-JAN's 2024
8163/// quarter 1 is 2024Q1 whatever calendar months it spans (2023-02..04).
8164fn fiscal_quarter_period(year: i32, quarter: u32, freq: PeriodFreq) -> Result<Period, IndexError> {
8165    if !(1..=4).contains(&quarter) {
8166        return Err(period_fields_error(format!(
8167            "quarter must be in 1..=4, got {quarter}"
8168        )));
8169    }
8170    let ordinal = (i64::from(year) - 1970) * 4 + i64::from(quarter) - 1;
8171    Ok(Period::new(ordinal, freq))
8172}
8173
8174fn period_from_fields_at(
8175    fields: &PeriodFields<'_>,
8176    freq: PeriodFreq,
8177    position: usize,
8178) -> Result<Period, IndexError> {
8179    let year = fields
8180        .year
8181        .get(position)
8182        .copied()
8183        .ok_or_else(|| period_fields_error("year fields are required"))?;
8184    let month = if matches!(freq, PeriodFreq::Quarterly(_)) {
8185        if let Some(quarters) = fields.quarter {
8186            let quarter = quarters
8187                .get(position)
8188                .copied()
8189                .ok_or_else(|| period_fields_error("quarter fields are required"))?;
8190            return fiscal_quarter_period(year, quarter, freq);
8191        } else {
8192            required_period_field(fields.month, "month", position)?
8193        }
8194    } else {
8195        if fields.quarter.is_some() && fields.month.is_none() {
8196            return Err(period_fields_error(
8197                "quarter fields require quarterly frequency unless month is also supplied",
8198            ));
8199        }
8200        required_period_field(fields.month, "month", position)?
8201    };
8202    let day = if matches!(
8203        freq,
8204        PeriodFreq::Annual(_) | PeriodFreq::Quarterly(_) | PeriodFreq::Monthly
8205    ) {
8206        1
8207    } else {
8208        period_field_value(fields.day, position, 1)
8209    };
8210    let hour = if matches!(
8211        freq,
8212        PeriodFreq::Hourly
8213            | PeriodFreq::Minutely
8214            | PeriodFreq::Secondly
8215            | PeriodFreq::Milliseconds
8216            | PeriodFreq::Microseconds
8217            | PeriodFreq::Nanoseconds
8218    ) {
8219        period_field_value(fields.hour, position, 0)
8220    } else {
8221        0
8222    };
8223    let minute = if matches!(
8224        freq,
8225        PeriodFreq::Minutely
8226            | PeriodFreq::Secondly
8227            | PeriodFreq::Milliseconds
8228            | PeriodFreq::Microseconds
8229            | PeriodFreq::Nanoseconds
8230    ) {
8231        period_field_value(fields.minute, position, 0)
8232    } else {
8233        0
8234    };
8235    let second = if matches!(
8236        freq,
8237        PeriodFreq::Secondly
8238            | PeriodFreq::Milliseconds
8239            | PeriodFreq::Microseconds
8240            | PeriodFreq::Nanoseconds
8241    ) {
8242        period_field_value(fields.second, position, 0)
8243    } else {
8244        0
8245    };
8246    let date = chrono::NaiveDate::from_ymd_opt(year, month, day)
8247        .ok_or_else(|| period_fields_error("invalid year/month/day combination"))?;
8248    let time = chrono::NaiveTime::from_hms_opt(hour, minute, second)
8249        .ok_or_else(|| period_fields_error("invalid hour/minute/second combination"))?;
8250    let nanos = date_and_time_to_nanos(date, time_to_nanos(time)).map_err(period_date_error)?;
8251    datetime_period_ordinal(nanos, freq).map(|ordinal| Period::new(ordinal, freq))
8252}
8253
8254fn ensure_index_kind(index: &Index, kinds: LabelKinds, kind: &str) -> Result<(), IndexError> {
8255    if index.label_kinds().within(kinds) {
8256        Ok(())
8257    } else {
8258        Err(IndexError::InvalidArgument(format!(
8259            "{kind} requires homogeneous {kind} labels"
8260        )))
8261    }
8262}
8263
8264const FREQ_MONTH_CODES: [&str; 12] = [
8265    "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
8266];
8267const FREQ_WEEKDAY_CODES: [&str; 7] = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];
8268
8269/// A freqstr from a count and a rule code, as pandas writes it: the count
8270/// only when it is not 1 ('D', '2D', '-1D').
8271fn freq_with_count(n: i64, rule: &str) -> String {
8272    if n == 1 {
8273        rule.to_owned()
8274    } else {
8275        format!("{n}{rule}")
8276    }
8277}
8278
8279/// A freqstr's count and rule code ('2D' -> (2, "D"), '-1D' -> (-1, "D"),
8280/// 'W-SUN' -> (1, "W-SUN")).
8281#[must_use]
8282pub fn split_freq_count(freqstr: &str) -> Option<(i64, &str)> {
8283    let body = freqstr
8284        .char_indices()
8285        .find(|&(i, c)| !(c.is_ascii_digit() || (i == 0 && matches!(c, '-' | '+'))))
8286        .map_or(freqstr.len(), |(i, _)| i);
8287    let (count, rule) = freqstr.split_at(body);
8288    let n = match count {
8289        "" | "+" => 1,
8290        "-" => -1,
8291        digits => digits.parse().ok()?,
8292    };
8293    (!rule.is_empty()).then_some((n, rule))
8294}
8295
8296/// pandas' freqstr for a frequency alias - what `date_range(freq=alias)
8297/// .freqstr` reports ('W' -> 'W-SUN', '12H' -> '12h', 'M' -> 'ME', 'Q' ->
8298/// 'QE-DEC', 'T' -> 'min', '1D' -> 'D') - or None for an alias this does
8299/// not know.
8300#[must_use]
8301pub fn canonical_freq(alias: &str) -> Option<String> {
8302    let (n, rule) = split_freq_count(alias.trim())?;
8303    let (base, suffix) = match rule.split_once('-') {
8304        Some((base, suffix)) => (base, Some(suffix.to_ascii_uppercase())),
8305        None => (rule, None),
8306    };
8307    let month = |default: &str| -> Option<String> {
8308        let code = suffix.clone().unwrap_or_else(|| default.to_owned());
8309        FREQ_MONTH_CODES.contains(&code.as_str()).then_some(code)
8310    };
8311    let semimonth_day = || -> Option<i64> {
8312        let day = suffix
8313            .as_deref()
8314            .map_or(Some(15), |text| text.parse().ok())?;
8315        (2..=27).contains(&day).then_some(day)
8316    };
8317    let plain = |code: &str| suffix.is_none().then(|| code.to_owned());
8318    let canonical = match base {
8319        "D" | "d" => plain("D")?,
8320        "h" | "H" => plain("h")?,
8321        "min" | "T" => plain("min")?,
8322        "s" | "S" => plain("s")?,
8323        "ms" | "L" => plain("ms")?,
8324        "us" | "U" => plain("us")?,
8325        "ns" | "N" => plain("ns")?,
8326        "B" => plain("B")?,
8327        "M" | "ME" => plain("ME")?,
8328        "MS" => plain("MS")?,
8329        "BM" | "BME" => plain("BME")?,
8330        "BMS" => plain("BMS")?,
8331        "W" => {
8332            let day = suffix.clone().unwrap_or_else(|| "SUN".to_owned());
8333            if !FREQ_WEEKDAY_CODES.contains(&day.as_str()) {
8334                return None;
8335            }
8336            format!("W-{day}")
8337        }
8338        "SM" | "SME" => format!("SME-{}", semimonth_day()?),
8339        "SMS" => format!("SMS-{}", semimonth_day()?),
8340        "Q" | "QE" => format!("QE-{}", month("DEC")?),
8341        "QS" => format!("QS-{}", month("JAN")?),
8342        "Y" | "A" | "YE" => format!("YE-{}", month("DEC")?),
8343        "YS" | "AS" => format!("YS-{}", month("JAN")?),
8344        _ => return None,
8345    };
8346    Some(freq_with_count(n, &canonical))
8347}
8348
8349/// A freqstr with its count multiplied by `factor` - the freq of a slice
8350/// with that step ('D' x 2 -> '2D', 'D' x -1 -> '-1D'); None for a zero
8351/// factor.
8352#[must_use]
8353pub fn scale_freq(freqstr: &str, factor: i64) -> Option<String> {
8354    if factor == 0 {
8355        return None;
8356    }
8357    let (n, rule) = split_freq_count(freqstr)?;
8358    Some(freq_with_count(n.checked_mul(factor)?, rule))
8359}
8360
8361/// pandas' tick units, coarsest first: the rule code, its length in
8362/// nanoseconds and the resolution a tick's Timedelta holds it at (seconds
8363/// for a day down to a second).
8364const TICK_UNITS: [(&str, i64, i64); 7] = [
8365    ("D", 86_400_000_000_000, 1_000_000_000),
8366    ("h", 3_600_000_000_000, 1_000_000_000),
8367    ("min", 60_000_000_000, 1_000_000_000),
8368    ("s", 1_000_000_000, 1_000_000_000),
8369    ("ms", 1_000_000, 1_000_000),
8370    ("us", 1_000, 1_000),
8371    ("ns", 1, 1),
8372];
8373
8374/// A tick freqstr's count and unit (its place in [`TICK_UNITS`]).
8375fn tick_count(freqstr: &str) -> Option<(i64, usize)> {
8376    let (n, rule) = split_freq_count(freqstr)?;
8377    let unit = TICK_UNITS.iter().position(|(code, _, _)| *code == rule)?;
8378    Some((n, unit))
8379}
8380
8381/// The tick freqstr of a duration, pandas' `delta_to_tick`: whole days in
8382/// days, other whole seconds in hours, minutes or seconds, else in milli-,
8383/// micro- or nanoseconds ('0D' for none).
8384fn duration_tick(nanos: i64) -> String {
8385    const SECOND: i64 = 1_000_000_000;
8386    let (n, rule) = if nanos % SECOND == 0 {
8387        let seconds = nanos / SECOND;
8388        if seconds % 86_400 == 0 {
8389            (seconds / 86_400, "D")
8390        } else if seconds % 3_600 == 0 {
8391            (seconds / 3_600, "h")
8392        } else if seconds % 60 == 0 {
8393            (seconds / 60, "min")
8394        } else {
8395            (seconds, "s")
8396        }
8397    } else if nanos % 1_000_000 == 0 {
8398        (nanos / 1_000_000, "ms")
8399    } else if nanos % 1_000 == 0 {
8400        (nanos / 1_000, "us")
8401    } else {
8402        (nanos, "ns")
8403    };
8404    freq_with_count(n, rule)
8405}
8406
8407/// The freq of a TimedeltaIndex multiplied by a float, pandas' `Tick *
8408/// factor`: the same unit when the product is whole (truncated), else the
8409/// next finer unit's count times it ('D' x 1.5 -> '36h'). None for a freq
8410/// that is not a tick or a product that is zero or not finite (pandas
8411/// drops that freq); Err past nanoseconds, pandas' ValueError.
8412pub fn multiply_tick_freq(freqstr: &str, factor: f64) -> Result<Option<String>, String> {
8413    let Some((mut n, mut unit)) = tick_count(freqstr) else {
8414        return Ok(None);
8415    };
8416    loop {
8417        let product = factor * n as f64;
8418        if !product.is_finite() {
8419            return Ok(None);
8420        }
8421        // pandas: np.isclose(n % 1, 0), then int(n).
8422        if product.rem_euclid(1.0) <= 1e-8 {
8423            let count = product.trunc() as i64;
8424            return Ok((count != 0).then(|| freq_with_count(count, TICK_UNITS[unit].0)));
8425        }
8426        let Some(&(_, finer, _)) = TICK_UNITS.get(unit + 1) else {
8427            return Err("Could not convert to integer offset at any resolution".to_owned());
8428        };
8429        n = n
8430            .checked_mul(TICK_UNITS[unit].1 / finer)
8431            .ok_or_else(|| "Could not convert to integer offset at any resolution".to_owned())?;
8432        unit += 1;
8433    }
8434}
8435
8436/// The freq of a TimedeltaIndex divided by a number, pandas' `Tick /
8437/// divisor`: the tick's Timedelta at its own resolution divided and
8438/// truncated there, as a tick again ('D' / 7 -> '12342s', 'D' / 2 ->
8439/// '12h'). None for a freq that is not a tick, a quotient that is not
8440/// finite, or one that truncates a nonzero freq to nothing (pandas drops
8441/// that freq).
8442#[must_use]
8443pub fn divide_tick_freq(freqstr: &str, divisor: f64) -> Option<String> {
8444    let (n, unit) = tick_count(freqstr)?;
8445    let (_, length, resolution) = TICK_UNITS[unit];
8446    let held = n.checked_mul(length / resolution)?;
8447    let quotient = held as f64 / divisor;
8448    if !quotient.is_finite() {
8449        return None;
8450    }
8451    let nanos = (quotient.trunc() as i64).checked_mul(resolution)?;
8452    (nanos != 0 || n == 0).then(|| duration_tick(nanos))
8453}
8454
8455/// The freq a `take` of `positions` keeps: pandas reads positions in one
8456/// constant nonzero step as a slice (`maybe_indices_to_slice`), so the freq
8457/// scales by the step ([0, 2] of 'h' is '2h'); any other take has none.
8458/// pandas' take-based selections (iloc / take with positions, between_time,
8459/// at_time) keep it so; its getitem with positions (Series.sort_values, loc)
8460/// does not.
8461#[must_use]
8462pub fn take_freq(freq: Option<String>, positions: &[usize]) -> Option<String> {
8463    let freq = freq?;
8464    let step = match positions {
8465        // No positions is an empty slice to pandas (`s.iloc[[]]` keeps 'D';
8466        // br-frankenpandas-0l1nu).
8467        [] => return Some(freq),
8468        [_] => 1,
8469        [first, second, ..] => i64::try_from(*second).ok()? - i64::try_from(*first).ok()?,
8470    };
8471    let steady = positions.windows(2).all(|pair| {
8472        i64::try_from(pair[1])
8473            .ok()
8474            .zip(i64::try_from(pair[0]).ok())
8475            .is_some_and(|(next, current)| next - current == step)
8476    });
8477    if step == 0 || !steady {
8478        return None;
8479    }
8480    scale_freq(&freq, step)
8481}
8482
8483/// pandas' month-position check: whether every date is a calendar ('ce') or
8484/// business ('be') month end, a calendar ('cs') or business ('bs') month
8485/// start, in that order of preference.
8486fn freq_month_position(stamps: &[Timestamp]) -> Option<&'static str> {
8487    let (mut calendar_end, mut business_end) = (true, true);
8488    let (mut calendar_start, mut business_start) = (true, true);
8489    for stamp in stamps {
8490        let day = stamp.day()?;
8491        let weekday = stamp.dayofweek()?;
8492        let month_days = stamp.days_in_month()?;
8493        calendar_start &= day == 1;
8494        business_start &= day == 1 || (day <= 3 && weekday == 0);
8495        let at_end = day == month_days;
8496        calendar_end &= at_end;
8497        business_end &= at_end || (month_days - day < 3 && weekday == 4);
8498    }
8499    if calendar_end {
8500        Some("ce")
8501    } else if business_end {
8502        Some("be")
8503    } else if calendar_start {
8504        Some("cs")
8505    } else if business_start {
8506        Some("bs")
8507    } else {
8508        None
8509    }
8510}
8511
8512/// The sorted distinct consecutive differences of `values`.
8513fn freq_unique_deltas(values: &[i64]) -> Vec<i64> {
8514    let mut deltas: Vec<i64> = values.windows(2).map(|pair| pair[1] - pair[0]).collect();
8515    deltas.sort_unstable();
8516    deltas.dedup();
8517    deltas
8518}
8519
8520/// pandas' frequency inference (`inferred_freq`): `wall` is each label's
8521/// wall clock (a calendar rule reads it) and `instants` the UTC instants (a
8522/// sub-day step reads them, as a DST change moves the wall clock). Needs
8523/// three or more strictly monotonic labels. A day multiple tries the annual,
8524/// quarterly and monthly rules (the dates' month position: YS / YE / QS /
8525/// QE / MS / ME and their business forms), then 'D' or `W-<day>` for a
8526/// single step, then business days ('B'); a sub-day step is its tick
8527/// ('h', 'min', 's', 'ms', 'us', 'ns') with a count. None otherwise.
8528#[must_use]
8529pub fn infer_datetime_freq(wall: &[i64], instants: &[i64]) -> Option<String> {
8530    const DAY: i64 = 86_400_000_000_000;
8531    if wall.len() < 3 || wall.len() != instants.len() {
8532        return None;
8533    }
8534    let increasing = wall.windows(2).all(|pair| pair[1] > pair[0]);
8535    let decreasing = wall.windows(2).all(|pair| pair[1] < pair[0]);
8536    if !(increasing || decreasing) {
8537        return None;
8538    }
8539    let deltas = freq_unique_deltas(wall);
8540    if deltas[0] % DAY == 0 {
8541        let stamps: Vec<Timestamp> = wall
8542            .iter()
8543            .map(|&nanos| Timestamp::from_nanos(nanos))
8544            .collect();
8545        let years: Vec<i64> = stamps.iter().map(Timestamp::year).collect::<Option<_>>()?;
8546        let months: Vec<i64> = stamps.iter().map(Timestamp::month).collect::<Option<_>>()?;
8547        let month_ordinals: Vec<i64> = years
8548            .iter()
8549            .zip(&months)
8550            .map(|(year, month)| year * 12 + month)
8551            .collect();
8552        let ydiffs = freq_unique_deltas(&years);
8553        let mdiffs = freq_unique_deltas(&month_ordinals);
8554        let position = freq_month_position(&stamps);
8555        let first_month = usize::try_from(months[0] - 1).ok()?;
8556        if ydiffs.len() == 1 && months.iter().all(|&month| month == months[0]) {
8557            let rule = match position {
8558                Some("cs") => Some("YS"),
8559                Some("bs") => Some("BYS"),
8560                Some("ce") => Some("YE"),
8561                Some("be") => Some("BYE"),
8562                _ => None,
8563            };
8564            if let Some(rule) = rule {
8565                let code = FREQ_MONTH_CODES.get(first_month)?;
8566                return Some(freq_with_count(ydiffs[0], &format!("{rule}-{code}")));
8567            }
8568        }
8569        if mdiffs.len() == 1 && mdiffs[0] % 3 == 0 {
8570            let rule = match position {
8571                Some("cs") => Some("QS"),
8572                Some("bs") => Some("BQS"),
8573                Some("ce") => Some("QE"),
8574                Some("be") => Some("BQE"),
8575                _ => None,
8576            };
8577            if let Some(rule) = rule {
8578                // pandas names the quarter by (month % 3): 0 -> DEC, 2 -> NOV,
8579                // 1 -> OCT (so a January-April-July run is 'QS-OCT').
8580                let code = match months[0] % 3 {
8581                    0 => "DEC",
8582                    2 => "NOV",
8583                    _ => "OCT",
8584                };
8585                return Some(freq_with_count(mdiffs[0] / 3, &format!("{rule}-{code}")));
8586            }
8587        }
8588        if mdiffs.len() == 1 {
8589            let rule = match position {
8590                Some("cs") => Some("MS"),
8591                Some("bs") => Some("BMS"),
8592                Some("ce") => Some("ME"),
8593                Some("be") => Some("BME"),
8594                _ => None,
8595            };
8596            if let Some(rule) = rule {
8597                return Some(freq_with_count(mdiffs[0], rule));
8598            }
8599        }
8600        if deltas.len() == 1 {
8601            let days = deltas[0] / DAY;
8602            if days % 7 == 0 {
8603                let weekday = usize::try_from(stamps[0].dayofweek()?).ok()?;
8604                let code = FREQ_WEEKDAY_CODES.get(weekday)?;
8605                return Some(freq_with_count(days / 7, &format!("W-{code}")));
8606            }
8607            return Some(freq_with_count(days, "D"));
8608        }
8609        // Business days: one-day steps, and three-day ones only from a
8610        // Friday to a Monday.
8611        if deltas == [DAY, 3 * DAY] {
8612            let mut weekday = stamps[0].dayofweek()?;
8613            let business = wall.windows(2).all(|pair| {
8614                let shift = (pair[1] - pair[0]) / DAY;
8615                weekday = (weekday + shift).rem_euclid(7);
8616                (weekday == 0 && shift == 3) || ((1..=4).contains(&weekday) && shift == 1)
8617            });
8618            if business {
8619                return Some("B".to_owned());
8620            }
8621        }
8622        return None;
8623    }
8624    let steps = freq_unique_deltas(instants);
8625    let [step] = steps.as_slice() else {
8626        return None;
8627    };
8628    [
8629        (3_600_000_000_000, "h"),
8630        (60_000_000_000, "min"),
8631        (1_000_000_000, "s"),
8632        (1_000_000, "ms"),
8633        (1_000, "us"),
8634        (1, "ns"),
8635    ]
8636    .into_iter()
8637    .find(|(unit, _)| step % unit == 0)
8638    .map(|(unit, rule)| freq_with_count(step / unit, rule))
8639}
8640
8641/// Public pandas-style datetime index wrapper.
8642///
8643/// The canonical storage remains [`Index`] with `Datetime64` labels so existing
8644/// DataFrame/Series alignment code keeps one representation. This wrapper adds
8645/// the type-level public surface pandas users expect (`DatetimeIndex`) and a
8646/// small first slice of datetime accessors.
8647#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8648pub struct DatetimeIndex {
8649    index: Index,
8650}
8651
8652impl DatetimeIndex {
8653    #[must_use]
8654    pub fn new(nanos: Vec<i64>) -> Self {
8655        Self {
8656            index: Index::from_datetime64(nanos),
8657        }
8658    }
8659
8660    pub fn from_index(index: Index) -> Result<Self, IndexError> {
8661        if index.labels.datetime64_affine_range().is_none() {
8662            ensure_index_kind(&index, LabelKinds::DATETIME64, "DatetimeIndex")?;
8663        }
8664        Ok(Self { index })
8665    }
8666
8667    #[must_use]
8668    pub fn as_index(&self) -> &Index {
8669        &self.index
8670    }
8671
8672    #[must_use]
8673    pub fn into_index(self) -> Index {
8674        self.index
8675    }
8676
8677    #[must_use]
8678    pub fn len(&self) -> usize {
8679        self.index.len()
8680    }
8681
8682    #[must_use]
8683    pub fn is_empty(&self) -> bool {
8684        self.index.is_empty()
8685    }
8686
8687    #[must_use]
8688    pub fn name(&self) -> Option<&LabelName> {
8689        self.index.name()
8690    }
8691
8692    #[must_use]
8693    pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
8694        Self {
8695            index: self.index.set_name(name),
8696        }
8697    }
8698
8699    #[must_use]
8700    pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
8701        Self {
8702            index: self.index.set_names(name),
8703        }
8704    }
8705
8706    #[must_use]
8707    pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
8708        self.set_names(name)
8709    }
8710
8711    #[must_use]
8712    pub fn names(&self) -> Vec<Option<String>> {
8713        self.index.names()
8714    }
8715
8716    #[must_use]
8717    pub fn copy(&self) -> Self {
8718        self.clone()
8719    }
8720
8721    #[must_use]
8722    pub fn shape(&self) -> (usize,) {
8723        self.index.shape()
8724    }
8725
8726    #[must_use]
8727    pub fn size(&self) -> usize {
8728        self.index.size()
8729    }
8730
8731    #[must_use]
8732    pub fn empty(&self) -> bool {
8733        self.index.empty()
8734    }
8735
8736    #[must_use]
8737    pub fn dtype(&self) -> &'static str {
8738        "datetime64[ns]"
8739    }
8740
8741    #[must_use]
8742    pub fn dtypes(&self) -> Vec<&'static str> {
8743        vec![self.dtype()]
8744    }
8745
8746    #[must_use]
8747    pub fn memory_usage(&self, deep: bool) -> usize {
8748        self.index.memory_usage(deep)
8749    }
8750
8751    #[must_use]
8752    pub fn nbytes(&self) -> usize {
8753        self.index.nbytes()
8754    }
8755
8756    #[must_use]
8757    pub fn hasnans(&self) -> bool {
8758        self.index.hasnans()
8759    }
8760
8761    #[must_use]
8762    pub fn isna(&self) -> Vec<bool> {
8763        self.index.isna()
8764    }
8765
8766    #[must_use]
8767    pub fn notna(&self) -> Vec<bool> {
8768        self.index.notna()
8769    }
8770
8771    #[must_use]
8772    pub fn is_unique(&self) -> bool {
8773        self.index.is_unique()
8774    }
8775
8776    #[must_use]
8777    pub fn has_duplicates(&self) -> bool {
8778        self.index.has_duplicates()
8779    }
8780
8781    #[must_use]
8782    pub fn is_monotonic_increasing(&self) -> bool {
8783        self.index.is_monotonic_increasing()
8784    }
8785
8786    #[must_use]
8787    pub fn is_monotonic(&self) -> bool {
8788        self.index.is_monotonic()
8789    }
8790
8791    #[must_use]
8792    pub fn is_monotonic_decreasing(&self) -> bool {
8793        self.index.is_monotonic_decreasing()
8794    }
8795
8796    #[must_use]
8797    pub fn nunique(&self) -> usize {
8798        self.index.nunique()
8799    }
8800
8801    #[must_use]
8802    pub fn nunique_with_dropna(&self, dropna: bool) -> usize {
8803        self.index.nunique_with_dropna(dropna)
8804    }
8805
8806    #[must_use]
8807    pub fn ndim(&self) -> usize {
8808        self.index.ndim()
8809    }
8810
8811    pub fn item(&self) -> Result<Option<i64>, IndexError> {
8812        match self.index.item()? {
8813            IndexLabel::Datetime64(nanos) if nanos != i64::MIN => Ok(Some(nanos)),
8814            IndexLabel::Datetime64(_) => Ok(None),
8815            label => Err(IndexError::InvalidArgument(format!(
8816                "DatetimeIndex item must be datetime64, got {label}"
8817            ))),
8818        }
8819    }
8820
8821    #[must_use]
8822    pub fn is_(&self, other: &Self) -> bool {
8823        std::ptr::eq(self, other)
8824    }
8825
8826    #[must_use]
8827    pub fn equals(&self, other: &Self) -> bool {
8828        self.index.equals(&other.index)
8829    }
8830
8831    #[must_use]
8832    pub fn identical(&self, other: &Self) -> bool {
8833        self.index.identical(&other.index)
8834    }
8835
8836    #[must_use]
8837    pub fn holds_integer(&self) -> bool {
8838        false
8839    }
8840
8841    #[must_use]
8842    pub fn inferred_type(&self) -> &'static str {
8843        "datetime64"
8844    }
8845
8846    #[must_use]
8847    pub fn is_boolean(&self) -> bool {
8848        false
8849    }
8850
8851    #[must_use]
8852    pub fn is_categorical(&self) -> bool {
8853        false
8854    }
8855
8856    #[must_use]
8857    pub fn is_floating(&self) -> bool {
8858        false
8859    }
8860
8861    #[must_use]
8862    pub fn is_integer(&self) -> bool {
8863        false
8864    }
8865
8866    #[must_use]
8867    pub fn is_interval(&self) -> bool {
8868        false
8869    }
8870
8871    #[must_use]
8872    pub fn is_numeric(&self) -> bool {
8873        false
8874    }
8875
8876    #[must_use]
8877    pub fn is_object(&self) -> bool {
8878        false
8879    }
8880
8881    #[must_use]
8882    pub fn nanos(&self) -> Vec<Option<i64>> {
8883        self.index
8884            .labels()
8885            .iter()
8886            .map(|label| match label {
8887                IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => Some(*nanos),
8888                IndexLabel::Int64(_)
8889                | IndexLabel::Float64(_)
8890                | IndexLabel::Bool(_)
8891                | IndexLabel::Utf8(_)
8892                | IndexLabel::Timedelta64(_)
8893                | IndexLabel::Datetime64(_)
8894                | IndexLabel::Object(_)
8895                | IndexLabel::Period(_)
8896                | IndexLabel::Interval(_)
8897                | IndexLabel::Null(_) => None,
8898            })
8899            .collect()
8900    }
8901
8902    #[must_use]
8903    pub fn values(&self) -> Vec<Option<i64>> {
8904        self.nanos()
8905    }
8906
8907    #[must_use]
8908    pub fn to_list(&self) -> Vec<Option<i64>> {
8909        self.nanos()
8910    }
8911
8912    #[must_use]
8913    pub fn tolist(&self) -> Vec<Option<i64>> {
8914        self.to_list()
8915    }
8916
8917    #[must_use]
8918    pub fn to_numpy(&self) -> Vec<Option<i64>> {
8919        self.nanos()
8920    }
8921
8922    #[must_use]
8923    pub fn array(&self) -> Vec<Option<i64>> {
8924        self.nanos()
8925    }
8926
8927    /// Underlying nanoseconds-since-epoch, matching `pd.DatetimeIndex.asi8`.
8928    /// NAT is preserved as `i64::MIN` to match the on-disk sentinel.
8929    #[must_use]
8930    pub fn asi8(&self) -> Vec<i64> {
8931        // A date_range's lazy range, its labels not made (br-frankenpandas-so0mr).
8932        if let Some(range) = self.index.labels.datetime64_affine_range() {
8933            return range.materialize_i64();
8934        }
8935        self.index
8936            .labels()
8937            .iter()
8938            .map(|label| match label {
8939                IndexLabel::Datetime64(nanos) => *nanos,
8940                IndexLabel::Int64(_)
8941                | IndexLabel::Float64(_)
8942                | IndexLabel::Bool(_)
8943                | IndexLabel::Utf8(_)
8944                | IndexLabel::Timedelta64(_)
8945                | IndexLabel::Object(_)
8946                | IndexLabel::Period(_)
8947                | IndexLabel::Interval(_)
8948                | IndexLabel::Null(_) => i64::MIN,
8949            })
8950            .collect()
8951    }
8952
8953    /// The one element of [`Self::asi8`] at `pos` (`None` past the end),
8954    /// without building the rest: reading element by element through `asi8()`
8955    /// made iterating a DatetimeIndex quadratic (br-frankenpandas-tumiz).
8956    #[must_use]
8957    pub fn asi8_at(&self, pos: usize) -> Option<i64> {
8958        if pos >= self.index.len() {
8959            return None;
8960        }
8961        if let Some(range) = self.index.labels.datetime64_affine_range() {
8962            return Some(range.value_at(pos));
8963        }
8964        Some(match self.index.labels().get(pos)? {
8965            IndexLabel::Datetime64(nanos) => *nanos,
8966            _ => i64::MIN,
8967        })
8968    }
8969
8970    /// Convert datetime labels to period ordinals at the requested frequency,
8971    /// matching `pd.DatetimeIndex.to_period(freq)` for supported fixed
8972    /// calendar frequencies.
8973    pub fn to_period(&self, freq: &str) -> Result<PeriodIndex, IndexError> {
8974        let period_freq = PeriodFreq::parse(freq).ok_or_else(|| {
8975            IndexError::InvalidArgument(format!("to_period: unsupported frequency '{freq}'"))
8976        })?;
8977        let periods = self
8978            .wall_labels()
8979            .iter()
8980            .map(|label| match label {
8981                IndexLabel::Datetime64(nanos) => datetime_nanos_to_period(*nanos, period_freq),
8982                other => Err(IndexError::InvalidArgument(format!(
8983                    "to_period requires DatetimeIndex labels, got {other:?}"
8984                ))),
8985            })
8986            .collect::<Result<Vec<_>, _>>()?;
8987        let mut out = PeriodIndex::new(periods);
8988        if let Some(name) = self.name() {
8989            out = out.set_name(name);
8990        }
8991        Ok(out)
8992    }
8993
8994    /// Format each timestamp as Python's strftime does, matching
8995    /// `pd.DatetimeIndex.strftime(format)` (see [`fp_types::strftime_python`];
8996    /// chrono's formatter printed `%f` with nine digits and panicked on an
8997    /// unknown directive). A tz-aware instant formats its wall clock, `%z` /
8998    /// `%Z` its zone's offset and abbreviation then. NAT propagates as `None`.
8999    #[must_use]
9000    pub fn strftime(&self, format: &str) -> Vec<Option<String>> {
9001        let zone = self.index.tz();
9002        self.index
9003            .labels()
9004            .iter()
9005            .map(|label| match label {
9006                IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => {
9007                    Some(fp_types::strftime_in_zone(*nanos, format, zone))
9008                }
9009                _ => None,
9010            })
9011            .collect()
9012    }
9013
9014    /// Position of the maximum label, matching `pd.DatetimeIndex.argmax()`.
9015    /// Pandas returns the *first* tied position and skips NAT entries; this
9016    /// method walks the labels itself to match that ordering exactly. Empty
9017    /// indexes (or all-NAT indexes) raise pandas-style `ValueError` mirrored
9018    /// as [`IndexError::InvalidArgument`].
9019    pub fn argmax(&self) -> Result<usize, IndexError> {
9020        let labels = self.index.labels();
9021        let mut best: Option<usize> = None;
9022        for (i, label) in labels.iter().enumerate() {
9023            let nanos = match label {
9024                IndexLabel::Datetime64(n) if *n != i64::MIN => *n,
9025                _ => continue,
9026            };
9027            best = Some(match best {
9028                Some(b) => match labels[b] {
9029                    IndexLabel::Datetime64(prev) if nanos > prev => i,
9030                    _ => b,
9031                },
9032                None => i,
9033            });
9034        }
9035        best.ok_or_else(|| {
9036            IndexError::InvalidArgument("attempt to get argmax of an empty sequence".to_owned())
9037        })
9038    }
9039
9040    /// Position of the minimum label, matching `pd.DatetimeIndex.argmin()`.
9041    /// Returns the first-tied position and skips NAT to match pandas semantics.
9042    pub fn argmin(&self) -> Result<usize, IndexError> {
9043        let labels = self.index.labels();
9044        let mut best: Option<usize> = None;
9045        for (i, label) in labels.iter().enumerate() {
9046            let nanos = match label {
9047                IndexLabel::Datetime64(n) if *n != i64::MIN => *n,
9048                _ => continue,
9049            };
9050            best = Some(match best {
9051                Some(b) => match labels[b] {
9052                    IndexLabel::Datetime64(prev) if nanos < prev => i,
9053                    _ => b,
9054                },
9055                None => i,
9056            });
9057        }
9058        best.ok_or_else(|| {
9059            IndexError::InvalidArgument("attempt to get argmin of an empty sequence".to_owned())
9060        })
9061    }
9062
9063    /// Positions that would sort the labels ascending, matching
9064    /// `pd.DatetimeIndex.argsort()`.
9065    #[must_use]
9066    pub fn argsort(&self) -> Vec<usize> {
9067        self.index.argsort()
9068    }
9069
9070    /// First-seen unique labels, matching `pd.DatetimeIndex.unique()`.
9071    /// Returns a new DatetimeIndex; one with no repeats is itself, freq kept.
9072    pub fn unique(&self) -> Result<Self, IndexError> {
9073        if !self.index.has_duplicates() {
9074            return Ok(self.clone());
9075        }
9076        Self::from_index(self.index.unique())
9077    }
9078
9079    /// Identity-stable factorization, matching `pd.DatetimeIndex.factorize()`.
9080    /// Returns `(codes, uniques)` where `uniques` is rebuilt as DatetimeIndex.
9081    pub fn factorize(&self) -> Result<(Vec<isize>, Self), IndexError> {
9082        let (codes, uniques) = self.index.factorize();
9083        Ok((codes, Self::from_index(uniques)?))
9084    }
9085
9086    /// Value counts, matching `pd.DatetimeIndex.value_counts()`.
9087    #[must_use]
9088    pub fn value_counts(&self) -> Vec<(IndexLabel, usize)> {
9089        self.index.value_counts()
9090    }
9091
9092    /// Duplicate mask per position, matching `pd.DatetimeIndex.duplicated(keep)`.
9093    #[must_use]
9094    pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
9095        self.index.duplicated(keep)
9096    }
9097
9098    /// Drop duplicate labels, matching `pd.DatetimeIndex.drop_duplicates()`.
9099    pub fn drop_duplicates(&self) -> Result<Self, IndexError> {
9100        Self::from_index(self.index.drop_duplicates())
9101    }
9102
9103    /// Pick labels at the given positions, matching `pd.DatetimeIndex.take()`.
9104    /// Out-of-bounds positions raise [`IndexError::OutOfBounds`].
9105    pub fn take(&self, positions: &[usize]) -> Result<Self, IndexError> {
9106        let labels = self.index.labels();
9107        for &p in positions {
9108            if p >= labels.len() {
9109                return Err(IndexError::OutOfBounds {
9110                    position: p,
9111                    length: labels.len(),
9112                });
9113            }
9114        }
9115        let nanos: Vec<i64> = positions
9116            .iter()
9117            .map(|&p| match labels[p] {
9118                IndexLabel::Datetime64(n) => n,
9119                _ => i64::MIN,
9120            })
9121            .collect();
9122        let freq = take_freq(self.freq(), positions);
9123        Ok(self.with_instants(nanos).with_freq(freq))
9124    }
9125
9126    /// Repeat each label `repeats` times, matching `pd.DatetimeIndex.repeat()`.
9127    #[must_use]
9128    pub fn repeat(&self, repeats: usize) -> Self {
9129        let mut out = Vec::with_capacity(repeat_output_capacity(self.len(), repeats));
9130        for label in self.index.labels() {
9131            if let IndexLabel::Datetime64(n) = label {
9132                for _ in 0..repeats {
9133                    out.push(*n);
9134                }
9135            }
9136        }
9137        self.with_instants(out)
9138    }
9139
9140    /// Per-position membership mask, matching `pd.DatetimeIndex.isin(values)`.
9141    /// `values` is interpreted as a slice of nanoseconds-since-epoch; pass
9142    /// `i64::MIN` to test for NAT.
9143    #[must_use]
9144    pub fn isin(&self, values: &[i64]) -> Vec<bool> {
9145        let needle: FxHashSet<i64> = values.iter().copied().collect();
9146        self.index
9147            .labels()
9148            .iter()
9149            .map(|label| match label {
9150                IndexLabel::Datetime64(n) => needle.contains(n),
9151                _ => false,
9152            })
9153            .collect()
9154    }
9155
9156    /// Concatenate with another DatetimeIndex, matching
9157    /// `pd.DatetimeIndex.append(other)`. The index name is preserved when
9158    /// both operands share it; otherwise pandas drops the name.
9159    #[must_use]
9160    pub fn append(&self, other: &Self) -> Self {
9161        let mut nanos: Vec<i64> = self
9162            .index
9163            .labels()
9164            .iter()
9165            .filter_map(|label| match label {
9166                IndexLabel::Datetime64(n) => Some(*n),
9167                _ => None,
9168            })
9169            .collect();
9170        nanos.extend(other.index.labels().iter().filter_map(|label| match label {
9171            IndexLabel::Datetime64(n) => Some(*n),
9172            _ => None,
9173        }));
9174        let mut out = Self::new(nanos);
9175        if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
9176            out = out.set_name(name);
9177        }
9178        // A zone only when both share it (pandas gives an object Index
9179        // of the two zones' Timestamps otherwise).
9180        if self.index.tz == other.index.tz {
9181            out.index.tz.clone_from(&self.index.tz);
9182        }
9183        out
9184    }
9185
9186    /// Minimum non-NAT label, matching `pd.DatetimeIndex.min()`.
9187    /// Returns `None` for empty or all-NAT inputs to mirror pandas' NaT.
9188    #[must_use]
9189    pub fn min(&self) -> Option<i64> {
9190        self.index
9191            .labels()
9192            .iter()
9193            .filter_map(|label| match label {
9194                IndexLabel::Datetime64(n) if *n != i64::MIN => Some(*n),
9195                _ => None,
9196            })
9197            .min()
9198    }
9199
9200    /// Shift each label by `periods` units of `freq_nanos`, matching
9201    /// `pd.DatetimeIndex.shift(periods, freq)` once `freq` has been
9202    /// resolved to a nanosecond duration. NAT propagates as NAT;
9203    /// arithmetic overflow saturates.
9204    #[must_use]
9205    pub fn shift(&self, periods: i64, freq_nanos: i64) -> Self {
9206        let delta = periods.saturating_mul(freq_nanos);
9207        let nanos: Vec<i64> = self
9208            .index
9209            .labels()
9210            .iter()
9211            .map(|label| match label {
9212                IndexLabel::Datetime64(n) if *n != i64::MIN => n.saturating_add(delta),
9213                _ => i64::MIN,
9214            })
9215            .collect();
9216        // Every label moves by the same span, so the freq holds (pandas).
9217        self.with_instants(nanos).with_freq(self.freq())
9218    }
9219
9220    /// Positional first differences, matching `pd.DatetimeIndex.diff()`.
9221    /// Datetime deltas materialize as a TimedeltaIndex; NAT inputs propagate
9222    /// to NAT outputs, and signed `periods` follows pandas' forward/backward
9223    /// lookup direction.
9224    #[must_use]
9225    pub fn diff(&self, periods: i64) -> TimedeltaIndex {
9226        let labels = self.index.labels();
9227        optional_diffs_to_timedelta_index(
9228            positional_diff(labels.len(), periods, |current, previous| {
9229                match (&labels[current], &labels[previous]) {
9230                    (
9231                        IndexLabel::Datetime64(current_nanos),
9232                        IndexLabel::Datetime64(previous_nanos),
9233                    ) if *current_nanos != i64::MIN && *previous_nanos != i64::MIN => {
9234                        current_nanos.checked_sub(*previous_nanos)
9235                    }
9236                    _ => None,
9237                }
9238            }),
9239            self.name(),
9240        )
9241    }
9242
9243    /// Rounding reads the wall clock: a tz-aware index rounds its wall
9244    /// times and places them back in its zone, as pandas.
9245    fn round_fixed_freq(&self, freq: &str, mode: TemporalRoundMode) -> Result<Self, IndexError> {
9246        let unit_nanos = parse_fixed_temporal_freq(freq, "DatetimeIndex rounding")?;
9247        let nanos: Vec<i64> = self
9248            .wall_labels()
9249            .iter()
9250            .map(|label| match label {
9251                IndexLabel::Datetime64(n) if *n != i64::MIN => {
9252                    round_nanos_to_unit(*n, unit_nanos, mode)
9253                }
9254                _ => i64::MIN,
9255            })
9256            .collect();
9257        let mut out = Self::new(nanos);
9258        if let Some(name) = self.name() {
9259            out = out.set_name(name);
9260        }
9261        self.rezoned(out)
9262    }
9263
9264    /// Round timestamps down to a fixed pandas frequency.
9265    pub fn floor(&self, freq: &str) -> Result<Self, IndexError> {
9266        self.round_fixed_freq(freq, TemporalRoundMode::Floor)
9267    }
9268
9269    /// Round timestamps up to a fixed pandas frequency.
9270    pub fn ceil(&self, freq: &str) -> Result<Self, IndexError> {
9271        self.round_fixed_freq(freq, TemporalRoundMode::Ceil)
9272    }
9273
9274    /// Round timestamps to the nearest fixed pandas frequency, using half-even ties.
9275    pub fn round(&self, freq: &str) -> Result<Self, IndexError> {
9276        self.round_fixed_freq(freq, TemporalRoundMode::Round)
9277    }
9278
9279    /// Validate the frequency and return a clone, matching pandas DatetimeIndex.snap.
9280    pub fn snap(&self, freq: &str) -> Result<Self, IndexError> {
9281        parse_fixed_temporal_freq(freq, "DatetimeIndex.snap")?;
9282        Ok(self.clone())
9283    }
9284
9285    /// Average non-NAT label as nanoseconds-since-epoch, matching
9286    /// `pd.DatetimeIndex.mean()`. Empty / all-NAT returns `None`.
9287    /// Sum is computed in `i128` to avoid overflow.
9288    #[must_use]
9289    pub fn mean(&self) -> Option<i64> {
9290        let mut total: i128 = 0;
9291        let mut count: i128 = 0;
9292        for label in self.index.labels() {
9293            if let IndexLabel::Datetime64(n) = label
9294                && *n != i64::MIN
9295            {
9296                total += i128::from(*n);
9297                count += 1;
9298            }
9299        }
9300        if count == 0 {
9301            return None;
9302        }
9303        i64::try_from(total / count).ok()
9304    }
9305
9306    /// Sample variance over non-NAT labels in nanoseconds-squared,
9307    /// matching `pd.DatetimeIndex.var(ddof=1)`. Returns `None` for
9308    /// fewer than two non-NAT entries.
9309    #[must_use]
9310    pub fn var(&self) -> Option<f64> {
9311        let nanos: Vec<f64> = self
9312            .index
9313            .labels()
9314            .iter()
9315            .filter_map(|label| match label {
9316                IndexLabel::Datetime64(n) if *n != i64::MIN => Some(*n as f64),
9317                _ => None,
9318            })
9319            .collect();
9320        if nanos.len() < 2 {
9321            return None;
9322        }
9323        let mean = nanos.iter().sum::<f64>() / nanos.len() as f64;
9324        Some(nanos.iter().map(|n| (n - mean).powi(2)).sum::<f64>() / (nanos.len() as f64 - 1.0))
9325    }
9326
9327    /// Sample standard deviation of non-NAT labels in nanoseconds,
9328    /// matching `pd.DatetimeIndex.std(ddof=1)`. Returns `None` for
9329    /// fewer than two non-NAT entries.
9330    #[must_use]
9331    pub fn std(&self) -> Option<i64> {
9332        let nanos: Vec<f64> = self
9333            .index
9334            .labels()
9335            .iter()
9336            .filter_map(|label| match label {
9337                IndexLabel::Datetime64(n) if *n != i64::MIN => Some(*n as f64),
9338                _ => None,
9339            })
9340            .collect();
9341        if nanos.len() < 2 {
9342            return None;
9343        }
9344        let mean = nanos.iter().sum::<f64>() / nanos.len() as f64;
9345        let var =
9346            nanos.iter().map(|n| (n - mean).powi(2)).sum::<f64>() / (nanos.len() as f64 - 1.0);
9347        Some(var.sqrt() as i64)
9348    }
9349
9350    /// Median non-NAT label. Empty returns None. For an even-length non-NAT
9351    /// subset, returns the average of the two middle values.
9352    ///
9353    /// ⚠️ `pd.DatetimeIndex.median()` does NOT exist (measured 2.2.3:
9354    /// `AttributeError`). Its sibling `mean()` DOES -- do not infer one from
9355    /// the other. FP superset; the pandas spelling is `idx.to_series().median()`.
9356    #[must_use]
9357    pub fn median(&self) -> Option<i64> {
9358        let mut nanos: Vec<i64> = self
9359            .index
9360            .labels()
9361            .iter()
9362            .filter_map(|label| match label {
9363                IndexLabel::Datetime64(n) if *n != i64::MIN => Some(*n),
9364                _ => None,
9365            })
9366            .collect();
9367        if nanos.is_empty() {
9368            return None;
9369        }
9370        nanos.sort_unstable();
9371        let mid = nanos.len() / 2;
9372        if nanos.len() % 2 == 1 {
9373            Some(nanos[mid])
9374        } else {
9375            let total = i128::from(nanos[mid - 1]) + i128::from(nanos[mid]);
9376            i64::try_from(total / 2).ok()
9377        }
9378    }
9379
9380    /// Maximum non-NAT label, matching `pd.DatetimeIndex.max()`.
9381    #[must_use]
9382    pub fn max(&self) -> Option<i64> {
9383        self.index
9384            .labels()
9385            .iter()
9386            .filter_map(|label| match label {
9387                IndexLabel::Datetime64(n) if *n != i64::MIN => Some(*n),
9388                _ => None,
9389            })
9390            .max()
9391    }
9392
9393    /// Labels present in both indexes, matching
9394    /// `pd.DatetimeIndex.intersection(other)`. Preserves first-seen order
9395    /// from `self`.
9396    #[must_use]
9397    pub fn intersection(&self, other: &Self) -> Self {
9398        let other_set: FxHashSet<i64> = other
9399            .index
9400            .labels()
9401            .iter()
9402            .filter_map(|label| match label {
9403                IndexLabel::Datetime64(n) => Some(*n),
9404                _ => None,
9405            })
9406            .collect();
9407        let mut seen = FxHashSet::<i64>::default();
9408        let nanos: Vec<i64> = self
9409            .index
9410            .labels()
9411            .iter()
9412            .filter_map(|label| match label {
9413                IndexLabel::Datetime64(n) if other_set.contains(n) && seen.insert(*n) => Some(*n),
9414                _ => None,
9415            })
9416            .collect();
9417        // pandas infers the freq of the shared labels.
9418        let shared = self.with_joined_instants(other, nanos);
9419        let freq = shared.inferred_freq();
9420        shared.with_freq(freq)
9421    }
9422
9423    /// `pd.DatetimeIndex.union(other)` (pandas' default `sort=None`); see
9424    /// [`Self::union_sorted`].
9425    #[must_use]
9426    pub fn union(&self, other: &Self) -> Self {
9427        self.union_sorted(other, None)
9428    }
9429
9430    /// `pd.DatetimeIndex.union(other, sort=)`: the labels of both, each
9431    /// once, sorted (pandas' default `sort=None` returns this index itself
9432    /// when `other` is empty or equal, and `other` when this one is empty;
9433    /// `sort=False` keeps first-seen order - it never sorted, so
9434    /// `[03, 01] | [02]` came back `[03, 01, 02]`). The result carries its
9435    /// inferred freq, as pandas'.
9436    #[must_use]
9437    pub fn union_sorted(&self, other: &Self, sort: Option<bool>) -> Self {
9438        if sort.is_none() {
9439            if other.is_empty() || self.index == other.index {
9440                return self.clone();
9441            }
9442            if self.is_empty() {
9443                return other.clone();
9444            }
9445        }
9446        let mut seen = FxHashSet::<i64>::default();
9447        let mut nanos: Vec<i64> = Vec::new();
9448        for label in self
9449            .index
9450            .labels()
9451            .iter()
9452            .chain(other.index.labels().iter())
9453        {
9454            if let IndexLabel::Datetime64(n) = label
9455                && seen.insert(*n)
9456            {
9457                nanos.push(*n);
9458            }
9459        }
9460        if sort != Some(false) {
9461            nanos.sort_unstable();
9462        }
9463        let joined = self.with_joined_instants(other, nanos);
9464        let freq = joined.inferred_freq();
9465        joined.with_freq(freq)
9466    }
9467
9468    /// Labels in self not in other, matching
9469    /// `pd.DatetimeIndex.difference(other)`.
9470    #[must_use]
9471    pub fn difference(&self, other: &Self) -> Self {
9472        let other_set: FxHashSet<i64> = other
9473            .index
9474            .labels()
9475            .iter()
9476            .filter_map(|label| match label {
9477                IndexLabel::Datetime64(n) => Some(*n),
9478                _ => None,
9479            })
9480            .collect();
9481        let mut seen = FxHashSet::<i64>::default();
9482        let nanos: Vec<i64> = self
9483            .index
9484            .labels()
9485            .iter()
9486            .filter_map(|label| match label {
9487                IndexLabel::Datetime64(n) if !other_set.contains(n) && seen.insert(*n) => Some(*n),
9488                _ => None,
9489            })
9490            .collect();
9491        // Per br-frankenpandas-6r1lq: difference is asymmetric — pandas
9492        // always preserves self.name (unlike union/intersection which use
9493        // shared_name).
9494        let mut out = self.with_instants(nanos);
9495        out.index.tz = joined_tz(&self.index, &other.index);
9496        out
9497    }
9498
9499    /// Labels in either but not both, matching
9500    /// `pd.DatetimeIndex.symmetric_difference(other)`.
9501    #[must_use]
9502    pub fn symmetric_difference(&self, other: &Self) -> Self {
9503        let self_set: FxHashSet<i64> = self
9504            .index
9505            .labels()
9506            .iter()
9507            .filter_map(|label| match label {
9508                IndexLabel::Datetime64(n) => Some(*n),
9509                _ => None,
9510            })
9511            .collect();
9512        let other_set: FxHashSet<i64> = other
9513            .index
9514            .labels()
9515            .iter()
9516            .filter_map(|label| match label {
9517                IndexLabel::Datetime64(n) => Some(*n),
9518                _ => None,
9519            })
9520            .collect();
9521        let mut seen = FxHashSet::<i64>::default();
9522        let mut nanos: Vec<i64> = Vec::new();
9523        for label in self.index.labels() {
9524            if let IndexLabel::Datetime64(n) = label
9525                && !other_set.contains(n)
9526                && seen.insert(*n)
9527            {
9528                nanos.push(*n);
9529            }
9530        }
9531        for label in other.index.labels() {
9532            if let IndexLabel::Datetime64(n) = label
9533                && !self_set.contains(n)
9534                && seen.insert(*n)
9535            {
9536                nanos.push(*n);
9537            }
9538        }
9539        self.with_joined_instants(other, nanos)
9540    }
9541
9542    /// Sort labels ascending, matching `pd.DatetimeIndex.sort_values()`.
9543    /// NAT sorts first because the underlying sentinel is `i64::MIN`,
9544    /// matching pandas' `na_position='first'` default for datetime indexes.
9545    #[must_use]
9546    pub fn sort_values(&self) -> Self {
9547        let mut nanos: Vec<i64> = self
9548            .index
9549            .labels()
9550            .iter()
9551            .filter_map(|label| match label {
9552                IndexLabel::Datetime64(n) => Some(*n),
9553                _ => None,
9554            })
9555            .collect();
9556        nanos.sort_unstable();
9557        self.with_instants(nanos)
9558    }
9559
9560    /// Alias for `sort_values`, matching `pd.DatetimeIndex.sort()`.
9561    #[must_use]
9562    pub fn sort(&self) -> Self {
9563        self.sort_values()
9564    }
9565
9566    /// Remove the label at the given position, matching
9567    /// `pd.DatetimeIndex.delete(loc)`.
9568    pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
9569        let labels = self.index.labels();
9570        if loc >= labels.len() {
9571            return Err(IndexError::OutOfBounds {
9572                position: loc,
9573                length: labels.len(),
9574            });
9575        }
9576        let nanos: Vec<i64> = labels
9577            .iter()
9578            .enumerate()
9579            .filter(|(i, _)| *i != loc)
9580            .filter_map(|(_, label)| match label {
9581                IndexLabel::Datetime64(n) => Some(*n),
9582                _ => None,
9583            })
9584            .collect();
9585        Ok(self.with_instants(nanos))
9586    }
9587
9588    /// Replace positions where `cond` is `false` with `other`, matching
9589    /// `pd.DatetimeIndex.where(cond, other)`. Pass `i64::MIN` to insert
9590    /// NAT.
9591    pub fn r#where(&self, cond: &[bool], other: i64) -> Result<Self, IndexError> {
9592        let labels = self.index.labels();
9593        if cond.len() != labels.len() {
9594            return Err(IndexError::LengthMismatch {
9595                expected: labels.len(),
9596                actual: cond.len(),
9597                context: "where: cond length must match index length".to_owned(),
9598            });
9599        }
9600        let nanos: Vec<i64> = labels
9601            .iter()
9602            .zip(cond.iter())
9603            .map(|(label, &keep)| {
9604                if keep {
9605                    match label {
9606                        IndexLabel::Datetime64(n) => *n,
9607                        _ => i64::MIN,
9608                    }
9609                } else {
9610                    other
9611                }
9612            })
9613            .collect();
9614        Ok(self.with_instants(nanos))
9615    }
9616
9617    /// Replace positions where `mask` is `true` with `value`, matching
9618    /// `pd.DatetimeIndex.putmask(mask, value)`. The complement of `where`.
9619    pub fn putmask(&self, mask: &[bool], value: i64) -> Result<Self, IndexError> {
9620        let labels = self.index.labels();
9621        if mask.len() != labels.len() {
9622            return Err(IndexError::LengthMismatch {
9623                expected: labels.len(),
9624                actual: mask.len(),
9625                context: "putmask: mask length must match index length".to_owned(),
9626            });
9627        }
9628        let nanos: Vec<i64> = labels
9629            .iter()
9630            .zip(mask.iter())
9631            .map(|(label, &replace)| {
9632                if replace {
9633                    value
9634                } else {
9635                    match label {
9636                        IndexLabel::Datetime64(n) => *n,
9637                        _ => i64::MIN,
9638                    }
9639                }
9640            })
9641            .collect();
9642        Ok(self.with_instants(nanos))
9643    }
9644
9645    /// Binary-search insertion position, matching
9646    /// `pd.DatetimeIndex.searchsorted(value, side)`. The needle is the
9647    /// nanoseconds-since-epoch value to locate; pandas behavior on NAT
9648    /// needles is to raise, mirrored as
9649    /// [`IndexError::InvalidArgument("searchsorted: needle cannot be missing")`].
9650    pub fn searchsorted(&self, value: i64, side: &str) -> Result<usize, IndexError> {
9651        self.index
9652            .searchsorted(&IndexLabel::Datetime64(value), side)
9653    }
9654
9655    /// Convert each label to a `chrono::DateTime<Utc>`, matching
9656    /// `pd.DatetimeIndex.to_pydatetime()`. NAT propagates as `None`.
9657    #[must_use]
9658    pub fn to_pydatetime(&self) -> Vec<Option<chrono::DateTime<chrono::Utc>>> {
9659        self.index
9660            .labels()
9661            .iter()
9662            .map(|label| match label {
9663                IndexLabel::Datetime64(nanos) => datetime_from_nanos(*nanos),
9664                _ => None,
9665            })
9666            .collect()
9667    }
9668
9669    /// Insert `value` at position `loc`, matching
9670    /// `pd.DatetimeIndex.insert(loc, value)`. `loc == len()` appends;
9671    /// `loc > len()` raises [`IndexError::OutOfBounds`].
9672    pub fn insert(&self, loc: usize, value: i64) -> Result<Self, IndexError> {
9673        let labels = self.index.labels();
9674        if loc > labels.len() {
9675            return Err(IndexError::OutOfBounds {
9676                position: loc,
9677                length: labels.len(),
9678            });
9679        }
9680        let mut nanos: Vec<i64> = labels
9681            .iter()
9682            .filter_map(|label| match label {
9683                IndexLabel::Datetime64(n) => Some(*n),
9684                _ => None,
9685            })
9686            .collect();
9687        nanos.insert(loc, value);
9688        Ok(self.with_instants(nanos))
9689    }
9690
9691    /// Stringify each label, matching `pd.DatetimeIndex.format()`.
9692    /// Non-NAT labels render as the chrono RFC3339 timestamp (a tz-aware
9693    /// index's on its wall clock with the zone's offset); NAT renders as
9694    /// the `NaT` literal pandas uses.
9695    #[must_use]
9696    pub fn format(&self) -> Vec<String> {
9697        let zone = self.index.tz();
9698        self.index
9699            .labels()
9700            .iter()
9701            .map(|label| match label {
9702                IndexLabel::Datetime64(nanos) => match datetime_from_nanos(*nanos) {
9703                    Some(dt) => {
9704                        let offset = zone
9705                            .and_then(|zone| fp_types::tz_offset_seconds(zone, *nanos).ok())
9706                            .and_then(chrono::FixedOffset::east_opt);
9707                        match offset {
9708                            Some(offset) => dt.with_timezone(&offset).to_rfc3339(),
9709                            None => dt.to_rfc3339(),
9710                        }
9711                    }
9712                    None => "NaT".to_owned(),
9713                },
9714                _ => "NaT".to_owned(),
9715            })
9716            .collect()
9717    }
9718
9719    /// Replace NAT positions with `value`, matching
9720    /// `pd.DatetimeIndex.fillna(value)`. Preserves the index name.
9721    #[must_use]
9722    pub fn fillna(&self, value: i64) -> Self {
9723        let nanos: Vec<i64> = self
9724            .index
9725            .labels()
9726            .iter()
9727            .map(|label| match label {
9728                IndexLabel::Datetime64(n) if *n != i64::MIN => *n,
9729                _ => value,
9730            })
9731            .collect();
9732        self.with_instants(nanos)
9733    }
9734
9735    /// Alias for [`isna`](Self::isna), matching `pd.DatetimeIndex.isnull()`.
9736    #[must_use]
9737    pub fn isnull(&self) -> Vec<bool> {
9738        self.isna()
9739    }
9740
9741    /// Alias for [`notna`](Self::notna), matching `pd.DatetimeIndex.notnull()`.
9742    #[must_use]
9743    pub fn notnull(&self) -> Vec<bool> {
9744        self.notna()
9745    }
9746
9747    /// Calendar date part of each label, matching `pd.DatetimeIndex.date`.
9748    #[must_use]
9749    pub fn date(&self) -> Vec<Option<chrono::NaiveDate>> {
9750        map_datetime_labels(&self.wall_labels(), |dt| dt.date_naive())
9751    }
9752
9753    /// Within-day clock time of each label, matching
9754    /// `pd.DatetimeIndex.time`.
9755    #[must_use]
9756    pub fn time(&self) -> Vec<Option<chrono::NaiveTime>> {
9757        map_datetime_labels(&self.wall_labels(), |dt| dt.time())
9758    }
9759
9760    /// Time component preserving timezone semantics, matching
9761    /// `pd.DatetimeIndex.timetz`. FrankenPandas currently stores
9762    /// timezone-naive UTC nanoseconds, so this matches [`Self::time`].
9763    #[must_use]
9764    pub fn timetz(&self) -> Vec<Option<chrono::NaiveTime>> {
9765        self.time()
9766    }
9767
9768    /// Convert each label to its Julian Date, matching
9769    /// `pd.DatetimeIndex.to_julian_date()`. The formula is
9770    /// `JD = unix_seconds / 86400 + 2440587.5` and the result is
9771    /// computed in f64; NAT propagates as `None`.
9772    #[must_use]
9773    pub fn to_julian_date(&self) -> Vec<Option<f64>> {
9774        const SECONDS_PER_DAY: f64 = 86_400.0;
9775        const UNIX_EPOCH_JD: f64 = 2_440_587.5;
9776        self.index
9777            .labels()
9778            .iter()
9779            .map(|label| match label {
9780                IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => {
9781                    let secs = (*nanos as f64) / 1_000_000_000.0;
9782                    Some(secs / SECONDS_PER_DAY + UNIX_EPOCH_JD)
9783                }
9784                _ => None,
9785            })
9786            .collect()
9787    }
9788
9789    /// pandas' `DatetimeIndex.tz_localize(tz)`: a naive index's wall-clock
9790    /// times placed in `tz` (a wall time a DST change skips or repeats is an
9791    /// error, pandas' default `ambiguous` / `nonexistent='raise'`), or an
9792    /// aware index's wall clock kept without its zone (`None`). Localizing
9793    /// an aware index to a zone is pandas' TypeError.
9794    pub fn tz_localize(&self, tz: Option<&str>) -> Result<Self, IndexError> {
9795        match (tz, self.index.tz()) {
9796            (Some(_), Some(_)) => Err(IndexError::TimeZoneMismatch(
9797                "Already tz-aware, use tz_convert to convert.".to_owned(),
9798            )),
9799            (None, None) => Ok(self.clone()),
9800            (None, Some(_)) => Ok(self.wall_index()),
9801            (Some(zone), None) => {
9802                let nanos = self
9803                    .index
9804                    .labels()
9805                    .iter()
9806                    .map(|label| match label {
9807                        IndexLabel::Datetime64(nanos) => {
9808                            fp_types::tz_wall_to_utc_nanos(zone, *nanos)
9809                        }
9810                        _ => Ok(i64::MIN),
9811                    })
9812                    .collect::<Result<Vec<_>, _>>()?;
9813                let localized = Self::new(nanos).rename_index(self.name());
9814                // pandas keeps the freq only for UTC, where no wall time moves.
9815                let freq = self.index.freq.clone().filter(|_| zone == "UTC");
9816                Ok(Self {
9817                    index: localized.index.with_tz(Some(zone))?.with_freq(freq),
9818                })
9819            }
9820        }
9821    }
9822
9823    /// pandas' `DatetimeIndex.tz_convert(tz)`: the same instants shown in
9824    /// `tz` (`None`: UTC, naive). Converting a naive index is pandas'
9825    /// TypeError.
9826    pub fn tz_convert(&self, tz: Option<&str>) -> Result<Self, IndexError> {
9827        if self.index.tz().is_none() {
9828            return Err(IndexError::TimeZoneMismatch(
9829                "Cannot convert tz-naive timestamps, use tz_localize to localize".to_owned(),
9830            ));
9831        }
9832        Ok(Self {
9833            index: self.index.clone().with_tz(tz)?,
9834        })
9835    }
9836
9837    /// These instants (UTC nanoseconds) shown in `tz` - no conversion: the
9838    /// constructor for an aware index from its instants (`tz_localize`
9839    /// takes wall times, `tz_convert` changes an aware index's zone).
9840    pub fn with_tz(self, tz: Option<&str>) -> Result<Self, IndexError> {
9841        Ok(Self {
9842            index: self.index.with_tz(tz)?,
9843        })
9844    }
9845
9846    /// `nanos` - instants taken, sorted, filtered or moved by a duration from
9847    /// this index's - as an index with its name and zone.
9848    fn with_instants(&self, nanos: Vec<i64>) -> Self {
9849        let mut out = Self::new(nanos).rename_index(self.name());
9850        out.index.tz.clone_from(&self.index.tz);
9851        out
9852    }
9853
9854    /// `nanos` from a set operation of this index with `other`: pandas keeps
9855    /// a shared name and zone (two zones meet in UTC).
9856    fn with_joined_instants(&self, other: &Self, nanos: Vec<i64>) -> Self {
9857        let mut out = Self::new(nanos);
9858        if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
9859            out = out.set_name(name);
9860        }
9861        out.index.tz = joined_tz(&self.index, &other.index);
9862        out
9863    }
9864
9865    /// The labels as the wall clock shows them: a tz-aware index's UTC
9866    /// instants moved into its zone, which every calendar field reads (a
9867    /// naive index's labels as they are).
9868    fn wall_labels(&self) -> Cow<'_, [IndexLabel]> {
9869        let Some(zone) = self.index.tz() else {
9870            return Cow::Borrowed(self.index.labels());
9871        };
9872        Cow::Owned(
9873            self.index
9874                .labels()
9875                .iter()
9876                .map(|label| match label {
9877                    IndexLabel::Datetime64(nanos) => IndexLabel::Datetime64(
9878                        fp_types::tz_utc_to_wall_nanos(zone, *nanos).unwrap_or(*nanos),
9879                    ),
9880                    other => other.clone(),
9881                })
9882                .collect(),
9883        )
9884    }
9885
9886    /// The wall-clock times as a naive index (`tz_localize(None)`), the
9887    /// name kept.
9888    fn wall_index(&self) -> Self {
9889        Self {
9890            index: Index::new(self.wall_labels().into_owned()).rename_index(self.name()),
9891        }
9892    }
9893
9894    /// Naive wall-clock times computed from this index placed back in its
9895    /// zone (a naive index's as they are), as pandas re-localizes a
9896    /// rounded or normalized aware index.
9897    fn rezoned(&self, wall: Self) -> Result<Self, IndexError> {
9898        match self.index.tz() {
9899            Some(zone) => wall.tz_localize(Some(zone)),
9900            None => Ok(wall),
9901        }
9902    }
9903
9904    /// Timezone name, matching `pd.DatetimeIndex.tz` (None when naive).
9905    #[must_use]
9906    pub fn tz(&self) -> Option<String> {
9907        self.index.tz().map(str::to_owned)
9908    }
9909
9910    /// Alias for [`tz`](Self::tz), matching `pd.DatetimeIndex.tzinfo`.
9911    #[must_use]
9912    pub fn tzinfo(&self) -> Option<String> {
9913        self.tz()
9914    }
9915
9916    /// The frequency this index was built with, as its freqstr - pandas'
9917    /// `DatetimeIndex.freq` / `freqstr` ('D', '12h', 'W-SUN', 'ME'); None
9918    /// when it has none (it was always None).
9919    #[must_use]
9920    pub fn freq(&self) -> Option<String> {
9921        self.index.freq().map(str::to_owned)
9922    }
9923
9924    /// Alias of [`Self::freq`], matching `pd.DatetimeIndex.freqstr`.
9925    #[must_use]
9926    pub fn freqstr(&self) -> Option<String> {
9927        self.freq()
9928    }
9929
9930    /// This index with `freq` (a freqstr) set or cleared; the caller vouches
9931    /// that the labels follow it.
9932    #[must_use]
9933    pub fn with_freq(self, freq: Option<String>) -> Self {
9934        Self {
9935            index: self.index.with_freq(freq),
9936        }
9937    }
9938
9939    /// pandas' `DatetimeIndex.inferred_freq`: the frequency the labels
9940    /// follow, read from their wall clock (see [`infer_datetime_freq`]);
9941    /// None for fewer than three labels, NaT, repeats or an irregular run
9942    /// (it was always None).
9943    #[must_use]
9944    pub fn inferred_freq(&self) -> Option<String> {
9945        let mut wall = Vec::with_capacity(self.len());
9946        for label in self.wall_labels().iter() {
9947            match label {
9948                IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => wall.push(*nanos),
9949                _ => return None,
9950            }
9951        }
9952        let instants: Vec<i64> = self
9953            .index
9954            .labels()
9955            .iter()
9956            .filter_map(|label| match label {
9957                IndexLabel::Datetime64(nanos) => Some(*nanos),
9958                _ => None,
9959            })
9960            .collect();
9961        infer_datetime_freq(&wall, &instants)
9962    }
9963
9964    /// Cast to a different storage resolution, matching
9965    /// `pd.DatetimeIndex.as_unit(unit)`. FrankenPandas's storage is fixed
9966    /// at nanoseconds so only `"ns"` is supported as a no-op clone; other
9967    /// units reject with a typed compatibility error.
9968    pub fn as_unit(&self, unit: &str) -> Result<Self, IndexError> {
9969        match unit {
9970            "ns" => Ok(self.clone()),
9971            other => Err(IndexError::InvalidArgument(format!(
9972                "as_unit: only 'ns' is supported by FrankenPandas's Datetime64 storage; got {other:?}"
9973            ))),
9974        }
9975    }
9976
9977    /// Storage resolution unit, matching `pd.DatetimeIndex.unit`. Always
9978    /// `"ns"` because FrankenPandas stores Datetime64 as nanoseconds.
9979    #[must_use]
9980    pub fn unit(&self) -> &'static str {
9981        "ns"
9982    }
9983
9984    /// Resolution string, matching `pd.DatetimeIndex.resolution`. Always
9985    /// `"nanosecond"` because the underlying storage is fixed at ns.
9986    #[must_use]
9987    pub fn resolution(&self) -> &'static str {
9988        "nanosecond"
9989    }
9990
9991    /// First position of `value`, matching `pd.DatetimeIndex.get_loc(value)`.
9992    /// Pandas raises KeyError for missing values; this surface mirrors
9993    /// that with [`IndexError::InvalidArgument`].
9994    pub fn get_loc(&self, value: i64) -> Result<usize, IndexError> {
9995        // Delegate to Index::position, which binary-searches a monotonic
9996        // (AscendingDatetime64) index in O(log n) instead of the O(n) linear
9997        // scan, and falls back to the same first-match linear scan when unsorted
9998        // (br-frankenpandas-idxdup). Bit-identical: a Datetime64(value) needle
9999        // matches exactly the labels this scan accepted.
10000        self.index
10001            .position(&IndexLabel::Datetime64(value))
10002            .ok_or_else(|| {
10003                IndexError::InvalidArgument(format!("get_loc: {value} not in DatetimeIndex"))
10004            })
10005    }
10006
10007    /// Set the index name, matching `pd.DatetimeIndex.rename(name)`.
10008    /// Alias for set_name.
10009    #[must_use]
10010    pub fn rename(&self, name: &str) -> Self {
10011        self.set_name(name)
10012    }
10013
10014    /// Reindex against `target`, matching
10015    /// `pd.DatetimeIndex.reindex(target)`. Returns
10016    /// `(target.clone(), indexer)` where indexer is the per-target
10017    /// position from get_indexer (with -1 for missing).
10018    #[must_use]
10019    pub fn reindex(&self, target: &Self) -> (Self, Vec<isize>) {
10020        let labels: Vec<i64> = target
10021            .index
10022            .labels()
10023            .iter()
10024            .filter_map(|label| match label {
10025                IndexLabel::Datetime64(n) => Some(*n),
10026                _ => None,
10027            })
10028            .collect();
10029        let indexer = self.get_indexer(&labels);
10030        (target.clone(), indexer)
10031    }
10032
10033    /// Locate every position matching each target, matching
10034    /// `pd.DatetimeIndex.get_indexer_non_unique(targets)`. Returns
10035    /// `(positions, missing)` where `positions` lists every source
10036    /// position matching any target (in target order) and `missing`
10037    /// lists target ordinals that had no match.
10038    #[must_use]
10039    pub fn get_indexer_non_unique(&self, targets: &[i64]) -> (Vec<isize>, Vec<usize>) {
10040        let labels = self.index.labels();
10041        let mut by_value = FxHashMap::<i64, Vec<usize>>::default();
10042        for (i, label) in labels.iter().enumerate() {
10043            if let IndexLabel::Datetime64(n) = label {
10044                by_value.entry(*n).or_default().push(i);
10045            }
10046        }
10047        let mut positions = Vec::<isize>::new();
10048        let mut missing = Vec::<usize>::new();
10049        for (idx, target) in targets.iter().enumerate() {
10050            if let Some(matches) = by_value.get(target) {
10051                positions.extend(
10052                    matches
10053                        .iter()
10054                        .map(|p| isize::try_from(*p).unwrap_or(isize::MAX)),
10055                );
10056            } else {
10057                positions.push(-1);
10058                missing.push(idx);
10059            }
10060        }
10061        (positions, missing)
10062    }
10063
10064    /// Alias for [`get_indexer`](Self::get_indexer), matching
10065    /// `pd.DatetimeIndex.get_indexer_for(targets)`.
10066    #[must_use]
10067    pub fn get_indexer_for(&self, targets: &[i64]) -> Vec<isize> {
10068        self.get_indexer(targets)
10069    }
10070
10071    /// Locate each label in `targets`, matching
10072    /// `pd.DatetimeIndex.get_indexer(targets)`. Returns `Vec<isize>` where
10073    /// `-1` means "missing".
10074    #[must_use]
10075    pub fn get_indexer(&self, targets: &[i64]) -> Vec<isize> {
10076        let labels = self.index.labels();
10077        let mut positions = FxHashMap::<i64, isize>::default();
10078        for (i, label) in labels.iter().enumerate() {
10079            if let IndexLabel::Datetime64(n) = label {
10080                positions
10081                    .entry(*n)
10082                    .or_insert_with(|| isize::try_from(i).unwrap_or(isize::MAX));
10083            }
10084        }
10085        targets
10086            .iter()
10087            .map(|n| positions.get(n).copied().unwrap_or(-1))
10088            .collect()
10089    }
10090
10091    /// Position of the slice boundary for `label` and `side`, matching
10092    /// `pd.DatetimeIndex.get_slice_bound(label, side)`. Mirrors
10093    /// `searchsorted(label, side)`.
10094    pub fn get_slice_bound(&self, label: i64, side: &str) -> Result<usize, IndexError> {
10095        self.searchsorted(label, side)
10096    }
10097
10098    /// Half-open positional range for a label slice, matching
10099    /// `pd.DatetimeIndex.slice_indexer(start, end)`. Wraps slice_locs
10100    /// in a `std::ops::Range<usize>`.
10101    pub fn slice_indexer(
10102        &self,
10103        start: i64,
10104        end: i64,
10105    ) -> Result<std::ops::Range<usize>, IndexError> {
10106        let (left, right) = self.slice_locs(start, end)?;
10107        Ok(left..right)
10108    }
10109
10110    /// Find positions of `[start, end]` for a label slice, matching
10111    /// `pd.DatetimeIndex.slice_locs(start, end)`. Requires the index to
10112    /// be monotonically increasing; non-monotonic input rejects.
10113    pub fn slice_locs(&self, start: i64, end: i64) -> Result<(usize, usize), IndexError> {
10114        if !self.is_monotonic_increasing() {
10115            return Err(IndexError::InvalidArgument(
10116                "slice_locs requires a monotonic increasing DatetimeIndex".to_owned(),
10117            ));
10118        }
10119        let left = self.searchsorted(start, "left")?;
10120        let right = self.searchsorted(end, "right")?;
10121        Ok((left, right))
10122    }
10123
10124    /// Convert to a flat [`Index`], matching
10125    /// `pd.DatetimeIndex.to_flat_index()`. Clone-as-Index because the
10126    /// underlying storage is already a flat Index of Datetime64 labels.
10127    #[must_use]
10128    pub fn to_flat_index(&self) -> Index {
10129        self.index.clone()
10130    }
10131
10132    /// String accessor for the flat datetime labels.
10133    #[must_use]
10134    pub fn r#str(&self) -> IndexStringAccessor<'_> {
10135        IndexStringAccessor::owned(self.to_flat_index())
10136    }
10137
10138    /// One-column row materialization, matching `pd.DatetimeIndex.to_frame(index=False)`.
10139    #[must_use]
10140    pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
10141        self.to_flat_index().to_frame()
10142    }
10143
10144    /// Series-shaped materialization using datetime labels as both index and values.
10145    #[must_use]
10146    pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
10147        self.to_flat_index().to_series()
10148    }
10149
10150    /// Whether any datetime label coerces to true.
10151    #[must_use]
10152    pub fn any(&self) -> bool {
10153        self.to_flat_index().any()
10154    }
10155
10156    /// Whether all datetime labels coerce to true.
10157    #[must_use]
10158    pub fn all(&self) -> bool {
10159        self.to_flat_index().all()
10160    }
10161
10162    /// Get labels for a level. DatetimeIndex is flat and only accepts level 0.
10163    pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
10164        self.to_flat_index().get_level_values(level)
10165    }
10166
10167    /// Drop a level. DatetimeIndex is flat, so removing its only level is invalid.
10168    pub fn droplevel(&self, level: usize) -> Result<Index, IndexError> {
10169        self.to_flat_index().droplevel(level)
10170    }
10171
10172    /// Group equal datetime labels into position buckets.
10173    #[must_use]
10174    pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
10175        self.to_flat_index().groupby()
10176    }
10177
10178    /// Apply a function to each datetime label, returning a flat Index.
10179    #[must_use]
10180    pub fn map<F>(&self, func: F) -> Index
10181    where
10182        F: Fn(&IndexLabel) -> IndexLabel,
10183    {
10184        self.to_flat_index().map(func)
10185    }
10186
10187    /// Cast datetime labels to a pandas dtype string, returning a flat Index.
10188    pub fn astype(&self, dtype: &str) -> Result<Index, IndexError> {
10189        self.to_flat_index().astype(dtype)
10190    }
10191
10192    /// Nearest preceding-or-equal datetime label lookup.
10193    #[must_use]
10194    pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
10195        self.to_flat_index().asof(key)
10196    }
10197
10198    /// Locate nearest preceding-or-equal datetime positions for each target label.
10199    #[must_use]
10200    pub fn asof_locs(&self, where_index: &Index, mask: Option<&[bool]>) -> Vec<Option<usize>> {
10201        self.to_flat_index().asof_locs(where_index, mask)
10202    }
10203
10204    /// Drop datetime labels, returning a flat Index.
10205    #[must_use]
10206    pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Index {
10207        self.to_flat_index().drop(labels_to_drop)
10208    }
10209
10210    /// Join datetime labels with another flat Index.
10211    pub fn join(&self, other: &Index, how: &str) -> Result<Index, IndexError> {
10212        self.to_flat_index().join(other, how)
10213    }
10214
10215    /// Sort datetime labels and return the positional sorter.
10216    #[must_use]
10217    pub fn sortlevel(&self) -> (Index, Vec<usize>) {
10218        self.to_flat_index().sortlevel()
10219    }
10220
10221    /// Returns a clone, matching `pd.DatetimeIndex.view()`. FrankenPandas
10222    /// owns its label storage so view materializes a fresh clone instead
10223    /// of an aliasing reference.
10224    #[must_use]
10225    pub fn view(&self) -> Self {
10226        self.clone()
10227    }
10228
10229    /// Identity transpose for a 1D index, matching
10230    /// `pd.DatetimeIndex.transpose()`.
10231    #[must_use]
10232    pub fn transpose(&self) -> Self {
10233        self.clone()
10234    }
10235
10236    /// Alias for `transpose`, matching `pd.DatetimeIndex.T`.
10237    #[allow(non_snake_case)]
10238    #[must_use]
10239    pub fn T(&self) -> Self {
10240        self.transpose()
10241    }
10242
10243    /// Flatten labels to nanoseconds-since-epoch with NAT preserved,
10244    /// matching `pd.DatetimeIndex.ravel()`.
10245    #[must_use]
10246    pub fn ravel(&self) -> Vec<Option<i64>> {
10247        self.values()
10248    }
10249
10250    /// Number of levels in this Index, matching `pd.DatetimeIndex.nlevels`.
10251    /// Always `1` because DatetimeIndex is a single-level index.
10252    #[must_use]
10253    pub fn nlevels(&self) -> usize {
10254        1
10255    }
10256
10257    /// Identity dtype-reinference for typed indexes, matching
10258    /// `pd.DatetimeIndex.infer_objects()`.
10259    #[must_use]
10260    pub fn infer_objects(&self) -> Self {
10261        self.clone()
10262    }
10263
10264    /// Drop NAT labels, matching `pd.DatetimeIndex.dropna()`. Non-datetime
10265    /// labels (which the wrapper rejects on construction) and `i64::MIN`
10266    /// sentinels are removed; surviving labels keep their order.
10267    pub fn dropna(&self) -> Self {
10268        let surviving: Vec<i64> = self
10269            .index
10270            .labels()
10271            .iter()
10272            .filter_map(|label| match label {
10273                IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => Some(*nanos),
10274                _ => None,
10275            })
10276            .collect();
10277        self.with_instants(surviving)
10278    }
10279
10280    #[must_use]
10281    pub fn year(&self) -> Vec<Option<i32>> {
10282        use chrono::Datelike;
10283        map_datetime_labels(&self.wall_labels(), |dt| dt.year())
10284    }
10285
10286    #[must_use]
10287    pub fn month(&self) -> Vec<Option<u32>> {
10288        use chrono::Datelike;
10289        map_datetime_labels(&self.wall_labels(), |dt| dt.month())
10290    }
10291
10292    #[must_use]
10293    pub fn day(&self) -> Vec<Option<u32>> {
10294        use chrono::Datelike;
10295        map_datetime_labels(&self.wall_labels(), |dt| dt.day())
10296    }
10297
10298    /// Hour of day per label (0..=23), matching `pd.DatetimeIndex.hour`.
10299    #[must_use]
10300    pub fn hour(&self) -> Vec<Option<u32>> {
10301        use chrono::Timelike;
10302        map_datetime_labels(&self.wall_labels(), |dt| dt.hour())
10303    }
10304
10305    /// Minute of hour per label (0..=59), matching `pd.DatetimeIndex.minute`.
10306    #[must_use]
10307    pub fn minute(&self) -> Vec<Option<u32>> {
10308        use chrono::Timelike;
10309        map_datetime_labels(&self.wall_labels(), |dt| dt.minute())
10310    }
10311
10312    /// Second of minute per label (0..=59), matching `pd.DatetimeIndex.second`.
10313    #[must_use]
10314    pub fn second(&self) -> Vec<Option<u32>> {
10315        use chrono::Timelike;
10316        map_datetime_labels(&self.wall_labels(), |dt| dt.second())
10317    }
10318
10319    /// Microsecond component (0..=999_999), matching `pd.DatetimeIndex.microsecond`.
10320    /// Computed from the within-second nanosecond bucket: `nanos / 1_000`.
10321    #[must_use]
10322    pub fn microsecond(&self) -> Vec<Option<u32>> {
10323        use chrono::Timelike;
10324        map_datetime_labels(&self.wall_labels(), |dt| dt.nanosecond() / 1_000)
10325    }
10326
10327    /// Nanosecond component (0..=999), matching `pd.DatetimeIndex.nanosecond`.
10328    /// Computed from the within-second nanosecond bucket: `nanos % 1_000`.
10329    #[must_use]
10330    pub fn nanosecond(&self) -> Vec<Option<u32>> {
10331        use chrono::Timelike;
10332        map_datetime_labels(&self.wall_labels(), |dt| dt.nanosecond() % 1_000)
10333    }
10334
10335    /// Integer positions whose clock time equals `time`, matching
10336    /// `pd.DatetimeIndex.indexer_at_time(time)`.
10337    pub fn indexer_at_time(&self, time: &str) -> Result<Vec<usize>, IndexError> {
10338        let target = parse_time_of_day_nanos(time, "DatetimeIndex.indexer_at_time")?;
10339        Ok(self
10340            .wall_labels()
10341            .iter()
10342            .enumerate()
10343            .filter_map(|(position, label)| {
10344                (datetime_label_time_nanos(label) == Some(target)).then_some(position)
10345            })
10346            .collect())
10347    }
10348
10349    /// Integer positions whose clock time falls between `start_time` and
10350    /// `end_time`, matching `pd.DatetimeIndex.indexer_between_time`.
10351    /// Ranges that cross midnight use pandas' wrap-around semantics.
10352    pub fn indexer_between_time(
10353        &self,
10354        start_time: &str,
10355        end_time: &str,
10356        include_start: bool,
10357        include_end: bool,
10358    ) -> Result<Vec<usize>, IndexError> {
10359        let start =
10360            parse_time_of_day_nanos(start_time, "DatetimeIndex.indexer_between_time start_time")?;
10361        let end = parse_time_of_day_nanos(end_time, "DatetimeIndex.indexer_between_time end_time")?;
10362        Ok(self
10363            .wall_labels()
10364            .iter()
10365            .enumerate()
10366            .filter_map(|(position, label)| {
10367                datetime_label_time_nanos(label)
10368                    .filter(|time| {
10369                        time_nanos_in_between(*time, start, end, include_start, include_end)
10370                    })
10371                    .map(|_| position)
10372            })
10373            .collect())
10374    }
10375
10376    /// ISO 8601 week-of-year (1..=53).
10377    ///
10378    /// ⚠️ NOT DEPRECATED -- REMOVED. `pd.DatetimeIndex.week` raises
10379    /// `AttributeError` on pandas 2.2.3 (measured), as does `.weekofyear`; both
10380    /// went in pandas 2.0. The pandas replacement is [`isocalendar`](Self::isocalendar),
10381    /// below. FP keeps this as a SUPERSET for pandas 1.x callers, not as parity.
10382    ///
10383    /// ⚠️ Do NOT generalize the removal to PeriodIndex: `pd.PeriodIndex.week`
10384    /// and `.weekofyear` both SURVIVE on 2.2.3, so the PeriodIndex docs in this
10385    /// file are correct as written.
10386    #[must_use]
10387    pub fn week(&self) -> Vec<Option<u32>> {
10388        use chrono::Datelike;
10389        map_datetime_labels(&self.wall_labels(), |dt| dt.iso_week().week())
10390    }
10391
10392    /// ISO calendar `(year, week, weekday)` triples, matching
10393    /// `pd.DatetimeIndex.isocalendar()`. Weekday uses pandas' Monday=1
10394    /// through Sunday=7 convention.
10395    #[must_use]
10396    pub fn isocalendar(&self) -> Vec<Option<(i32, u32, u32)>> {
10397        use chrono::Datelike;
10398        map_datetime_labels(&self.wall_labels(), |dt| {
10399            let iso = dt.iso_week();
10400            (iso.year(), iso.week(), dt.weekday().number_from_monday())
10401        })
10402    }
10403
10404    /// Alias for [`week`](Self::week).
10405    ///
10406    /// ⚠️ `pd.DatetimeIndex.weekofyear` was REMOVED in pandas 2.0 (measured:
10407    /// `AttributeError` on 2.2.3). Superset, not parity -- see [`week`](Self::week).
10408    #[must_use]
10409    pub fn weekofyear(&self) -> Vec<Option<u32>> {
10410        self.week()
10411    }
10412
10413    /// Day of year (1..=366), matching `pd.DatetimeIndex.dayofyear`.
10414    #[must_use]
10415    pub fn dayofyear(&self) -> Vec<Option<u32>> {
10416        use chrono::Datelike;
10417        map_datetime_labels(&self.wall_labels(), |dt| dt.ordinal())
10418    }
10419
10420    /// Alias for [`dayofyear`](Self::dayofyear), matching `pd.DatetimeIndex.day_of_year`.
10421    #[must_use]
10422    pub fn day_of_year(&self) -> Vec<Option<u32>> {
10423        self.dayofyear()
10424    }
10425
10426    /// Weekday number (Monday=0..Sunday=6), matching
10427    /// `pd.DatetimeIndex.dayofweek`.
10428    #[must_use]
10429    pub fn dayofweek(&self) -> Vec<Option<u32>> {
10430        use chrono::Datelike;
10431        map_datetime_labels(&self.wall_labels(), |dt| {
10432            dt.weekday().num_days_from_monday()
10433        })
10434    }
10435
10436    /// Alias for [`dayofweek`](Self::dayofweek), matching `pd.DatetimeIndex.day_of_week`.
10437    #[must_use]
10438    pub fn day_of_week(&self) -> Vec<Option<u32>> {
10439        self.dayofweek()
10440    }
10441
10442    /// Alias for [`dayofweek`](Self::dayofweek), matching `pd.DatetimeIndex.weekday`.
10443    #[must_use]
10444    pub fn weekday(&self) -> Vec<Option<u32>> {
10445        self.dayofweek()
10446    }
10447
10448    /// Calendar quarter (1..=4), matching `pd.DatetimeIndex.quarter`.
10449    #[must_use]
10450    pub fn quarter(&self) -> Vec<Option<u32>> {
10451        use chrono::Datelike;
10452        map_datetime_labels(&self.wall_labels(), |dt| (dt.month() - 1) / 3 + 1)
10453    }
10454
10455    /// Whether the year is a leap year, matching
10456    /// `pd.DatetimeIndex.is_leap_year`.
10457    #[must_use]
10458    pub fn is_leap_year(&self) -> Vec<Option<bool>> {
10459        use chrono::Datelike;
10460        map_datetime_labels(&self.wall_labels(), |dt| {
10461            chrono::NaiveDate::from_ymd_opt(dt.year(), 1, 1).is_some_and(|d| d.leap_year())
10462        })
10463    }
10464
10465    /// Number of days in the calendar month of each label,
10466    /// matching `pd.DatetimeIndex.days_in_month`.
10467    #[must_use]
10468    pub fn days_in_month(&self) -> Vec<Option<u32>> {
10469        use chrono::Datelike;
10470        map_datetime_labels(&self.wall_labels(), |dt| {
10471            days_in_calendar_month(dt.year(), dt.month())
10472        })
10473    }
10474
10475    /// Alias for [`days_in_month`](Self::days_in_month), matching `pd.DatetimeIndex.daysinmonth`.
10476    #[must_use]
10477    pub fn daysinmonth(&self) -> Vec<Option<u32>> {
10478        self.days_in_month()
10479    }
10480
10481    /// Whether the day is the first of the month, matching
10482    /// `pd.DatetimeIndex.is_month_start`.
10483    #[must_use]
10484    pub fn is_month_start(&self) -> Vec<Option<bool>> {
10485        use chrono::Datelike;
10486        map_datetime_labels(&self.wall_labels(), |dt| dt.day() == 1)
10487    }
10488
10489    /// Whether the day is the last of the month, matching
10490    /// `pd.DatetimeIndex.is_month_end`.
10491    #[must_use]
10492    pub fn is_month_end(&self) -> Vec<Option<bool>> {
10493        use chrono::Datelike;
10494        map_datetime_labels(&self.wall_labels(), |dt| {
10495            dt.day() == days_in_calendar_month(dt.year(), dt.month())
10496        })
10497    }
10498
10499    /// Whether the timestamp is the first day of a quarter, matching
10500    /// `pd.DatetimeIndex.is_quarter_start`. Quarter starts: Jan/Apr/Jul/Oct day 1.
10501    #[must_use]
10502    pub fn is_quarter_start(&self) -> Vec<Option<bool>> {
10503        use chrono::Datelike;
10504        map_datetime_labels(&self.wall_labels(), |dt| {
10505            matches!(dt.month(), 1 | 4 | 7 | 10) && dt.day() == 1
10506        })
10507    }
10508
10509    /// Whether the timestamp is the last day of a quarter, matching
10510    /// `pd.DatetimeIndex.is_quarter_end`. Quarter ends: Mar/Jun/Sep/Dec last day.
10511    #[must_use]
10512    pub fn is_quarter_end(&self) -> Vec<Option<bool>> {
10513        use chrono::Datelike;
10514        map_datetime_labels(&self.wall_labels(), |dt| {
10515            matches!(dt.month(), 3 | 6 | 9 | 12)
10516                && dt.day() == days_in_calendar_month(dt.year(), dt.month())
10517        })
10518    }
10519
10520    /// Whether the timestamp is January 1, matching
10521    /// `pd.DatetimeIndex.is_year_start`.
10522    #[must_use]
10523    pub fn is_year_start(&self) -> Vec<Option<bool>> {
10524        use chrono::Datelike;
10525        map_datetime_labels(&self.wall_labels(), |dt| dt.month() == 1 && dt.day() == 1)
10526    }
10527
10528    /// Whether the timestamp is December 31, matching
10529    /// `pd.DatetimeIndex.is_year_end`.
10530    #[must_use]
10531    pub fn is_year_end(&self) -> Vec<Option<bool>> {
10532        use chrono::Datelike;
10533        map_datetime_labels(&self.wall_labels(), |dt| dt.month() == 12 && dt.day() == 31)
10534    }
10535
10536    /// Full English month name, matching `pd.DatetimeIndex.month_name()`.
10537    #[must_use]
10538    pub fn month_name(&self) -> Vec<Option<String>> {
10539        use chrono::Datelike;
10540        map_datetime_labels(&self.wall_labels(), |dt| {
10541            month_name_english(dt.month()).to_owned()
10542        })
10543    }
10544
10545    /// Full English weekday name, matching `pd.DatetimeIndex.day_name()`.
10546    #[must_use]
10547    pub fn day_name(&self) -> Vec<Option<String>> {
10548        use chrono::Datelike;
10549        map_datetime_labels(&self.wall_labels(), |dt| {
10550            weekday_name_english(dt.weekday()).to_owned()
10551        })
10552    }
10553
10554    /// Truncate every timestamp to its wall-clock midnight, matching
10555    /// `pd.DatetimeIndex.normalize()`: a tz-aware index's midnights are back
10556    /// in its zone (a midnight a DST change skips is an error, as pandas).
10557    /// NAT labels propagate.
10558    pub fn normalize(&self) -> Result<Self, IndexError> {
10559        let nanos: Vec<i64> = self
10560            .wall_labels()
10561            .iter()
10562            .map(|label| match label {
10563                IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => {
10564                    let secs_per_day: i64 = 86_400;
10565                    let nanos_per_day: i64 = secs_per_day * 1_000_000_000;
10566                    nanos.div_euclid(nanos_per_day) * nanos_per_day
10567                }
10568                _ => i64::MIN,
10569            })
10570            .collect();
10571        let mut normalized = Self::new(nanos);
10572        if let Some(name) = self.name() {
10573            normalized = normalized.set_name(name);
10574        }
10575        // pandas infers the freq of the midnights (then localizes, which
10576        // keeps it only in UTC).
10577        let freq = normalized.inferred_freq();
10578        self.rezoned(normalized.with_freq(freq))
10579    }
10580
10581    /// Whether every label is at its wall-clock midnight (NAT counts as
10582    /// normalized), matching `pd.DatetimeIndex.is_normalized`.
10583    #[must_use]
10584    pub fn is_normalized(&self) -> bool {
10585        let nanos_per_day: i64 = 86_400 * 1_000_000_000;
10586        self.wall_labels().iter().all(|label| match label {
10587            IndexLabel::Datetime64(nanos) => {
10588                *nanos == i64::MIN || nanos.rem_euclid(nanos_per_day) == 0
10589            }
10590            _ => true,
10591        })
10592    }
10593}
10594
10595fn month_name_english(month: u32) -> &'static str {
10596    match month {
10597        1 => "January",
10598        2 => "February",
10599        3 => "March",
10600        4 => "April",
10601        5 => "May",
10602        6 => "June",
10603        7 => "July",
10604        8 => "August",
10605        9 => "September",
10606        10 => "October",
10607        11 => "November",
10608        12 => "December",
10609        _ => "",
10610    }
10611}
10612
10613fn weekday_name_english(weekday: chrono::Weekday) -> &'static str {
10614    match weekday {
10615        chrono::Weekday::Mon => "Monday",
10616        chrono::Weekday::Tue => "Tuesday",
10617        chrono::Weekday::Wed => "Wednesday",
10618        chrono::Weekday::Thu => "Thursday",
10619        chrono::Weekday::Fri => "Friday",
10620        chrono::Weekday::Sat => "Saturday",
10621        chrono::Weekday::Sun => "Sunday",
10622    }
10623}
10624
10625fn days_in_calendar_month(year: i32, month: u32) -> u32 {
10626    let next_month = if month == 12 { 1 } else { month + 1 };
10627    let next_year = if month == 12 { year + 1 } else { year };
10628    let first_of_next = chrono::NaiveDate::from_ymd_opt(next_year, next_month, 1);
10629    let first_of_this = chrono::NaiveDate::from_ymd_opt(year, month, 1);
10630    match (first_of_next, first_of_this) {
10631        (Some(next), Some(this)) => (next - this).num_days() as u32,
10632        _ => 0,
10633    }
10634}
10635
10636/// Public pandas-style timedelta index wrapper.
10637#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
10638pub struct TimedeltaIndex {
10639    index: Index,
10640}
10641
10642impl TimedeltaIndex {
10643    #[must_use]
10644    pub fn new(nanos: Vec<i64>) -> Self {
10645        Self {
10646            index: Index::from_timedelta64(nanos),
10647        }
10648    }
10649
10650    pub fn from_index(index: Index) -> Result<Self, IndexError> {
10651        ensure_index_kind(&index, LabelKinds::TIMEDELTA64, "TimedeltaIndex")?;
10652        Ok(Self { index })
10653    }
10654
10655    #[must_use]
10656    pub fn as_index(&self) -> &Index {
10657        &self.index
10658    }
10659
10660    #[must_use]
10661    pub fn into_index(self) -> Index {
10662        self.index
10663    }
10664
10665    #[must_use]
10666    pub fn len(&self) -> usize {
10667        self.index.len()
10668    }
10669
10670    #[must_use]
10671    pub fn is_empty(&self) -> bool {
10672        self.index.is_empty()
10673    }
10674
10675    #[must_use]
10676    pub fn name(&self) -> Option<&LabelName> {
10677        self.index.name()
10678    }
10679
10680    #[must_use]
10681    pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
10682        Self {
10683            index: self.index.set_name(name),
10684        }
10685    }
10686
10687    #[must_use]
10688    pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
10689        Self {
10690            index: self.index.set_names(name),
10691        }
10692    }
10693
10694    #[must_use]
10695    pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
10696        self.set_names(name)
10697    }
10698
10699    #[must_use]
10700    pub fn names(&self) -> Vec<Option<String>> {
10701        self.index.names()
10702    }
10703
10704    #[must_use]
10705    pub fn copy(&self) -> Self {
10706        self.clone()
10707    }
10708
10709    #[must_use]
10710    pub fn shape(&self) -> (usize,) {
10711        self.index.shape()
10712    }
10713
10714    #[must_use]
10715    pub fn size(&self) -> usize {
10716        self.index.size()
10717    }
10718
10719    #[must_use]
10720    pub fn empty(&self) -> bool {
10721        self.index.empty()
10722    }
10723
10724    #[must_use]
10725    pub fn dtype(&self) -> &'static str {
10726        "timedelta64[ns]"
10727    }
10728
10729    #[must_use]
10730    pub fn dtypes(&self) -> Vec<&'static str> {
10731        vec![self.dtype()]
10732    }
10733
10734    #[must_use]
10735    pub fn memory_usage(&self, deep: bool) -> usize {
10736        self.index.memory_usage(deep)
10737    }
10738
10739    #[must_use]
10740    pub fn nbytes(&self) -> usize {
10741        self.index.nbytes()
10742    }
10743
10744    #[must_use]
10745    pub fn hasnans(&self) -> bool {
10746        self.index.hasnans()
10747    }
10748
10749    #[must_use]
10750    pub fn isna(&self) -> Vec<bool> {
10751        self.index.isna()
10752    }
10753
10754    #[must_use]
10755    pub fn notna(&self) -> Vec<bool> {
10756        self.index.notna()
10757    }
10758
10759    #[must_use]
10760    pub fn is_unique(&self) -> bool {
10761        self.index.is_unique()
10762    }
10763
10764    #[must_use]
10765    pub fn has_duplicates(&self) -> bool {
10766        self.index.has_duplicates()
10767    }
10768
10769    #[must_use]
10770    pub fn is_monotonic_increasing(&self) -> bool {
10771        self.index.is_monotonic_increasing()
10772    }
10773
10774    #[must_use]
10775    pub fn is_monotonic(&self) -> bool {
10776        self.index.is_monotonic()
10777    }
10778
10779    #[must_use]
10780    pub fn is_monotonic_decreasing(&self) -> bool {
10781        self.index.is_monotonic_decreasing()
10782    }
10783
10784    #[must_use]
10785    pub fn nunique(&self) -> usize {
10786        self.index.nunique()
10787    }
10788
10789    #[must_use]
10790    pub fn nunique_with_dropna(&self, dropna: bool) -> usize {
10791        self.index.nunique_with_dropna(dropna)
10792    }
10793
10794    #[must_use]
10795    pub fn ndim(&self) -> usize {
10796        self.index.ndim()
10797    }
10798
10799    pub fn item(&self) -> Result<Option<i64>, IndexError> {
10800        match self.index.item()? {
10801            IndexLabel::Timedelta64(nanos) if nanos != Timedelta::NAT => Ok(Some(nanos)),
10802            IndexLabel::Timedelta64(_) => Ok(None),
10803            label => Err(IndexError::InvalidArgument(format!(
10804                "TimedeltaIndex item must be timedelta64, got {label}"
10805            ))),
10806        }
10807    }
10808
10809    #[must_use]
10810    pub fn is_(&self, other: &Self) -> bool {
10811        std::ptr::eq(self, other)
10812    }
10813
10814    #[must_use]
10815    pub fn equals(&self, other: &Self) -> bool {
10816        self.index.equals(&other.index)
10817    }
10818
10819    #[must_use]
10820    pub fn identical(&self, other: &Self) -> bool {
10821        self.index.identical(&other.index)
10822    }
10823
10824    #[must_use]
10825    pub fn holds_integer(&self) -> bool {
10826        false
10827    }
10828
10829    #[must_use]
10830    pub fn inferred_type(&self) -> &'static str {
10831        "timedelta64"
10832    }
10833
10834    #[must_use]
10835    pub fn is_boolean(&self) -> bool {
10836        false
10837    }
10838
10839    #[must_use]
10840    pub fn is_categorical(&self) -> bool {
10841        false
10842    }
10843
10844    #[must_use]
10845    pub fn is_floating(&self) -> bool {
10846        false
10847    }
10848
10849    #[must_use]
10850    pub fn is_integer(&self) -> bool {
10851        false
10852    }
10853
10854    #[must_use]
10855    pub fn is_interval(&self) -> bool {
10856        false
10857    }
10858
10859    #[must_use]
10860    pub fn is_numeric(&self) -> bool {
10861        false
10862    }
10863
10864    #[must_use]
10865    pub fn is_object(&self) -> bool {
10866        false
10867    }
10868
10869    #[must_use]
10870    pub fn nanos(&self) -> Vec<Option<i64>> {
10871        map_timedelta_labels(self.index.labels(), |nanos| nanos)
10872    }
10873
10874    #[must_use]
10875    pub fn values(&self) -> Vec<Option<i64>> {
10876        self.nanos()
10877    }
10878
10879    #[must_use]
10880    pub fn to_list(&self) -> Vec<Option<i64>> {
10881        self.nanos()
10882    }
10883
10884    #[must_use]
10885    pub fn tolist(&self) -> Vec<Option<i64>> {
10886        self.to_list()
10887    }
10888
10889    #[must_use]
10890    pub fn to_numpy(&self) -> Vec<Option<i64>> {
10891        self.nanos()
10892    }
10893
10894    #[must_use]
10895    pub fn array(&self) -> Vec<Option<i64>> {
10896        self.nanos()
10897    }
10898
10899    #[must_use]
10900    pub fn days(&self) -> Vec<Option<i64>> {
10901        map_timedelta_labels(self.index.labels(), |nanos| {
10902            nanos.div_euclid(Timedelta::NANOS_PER_DAY)
10903        })
10904    }
10905
10906    #[must_use]
10907    pub fn seconds(&self) -> Vec<Option<i64>> {
10908        map_timedelta_labels(self.index.labels(), |nanos| {
10909            nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC
10910        })
10911    }
10912
10913    #[must_use]
10914    pub fn total_seconds(&self) -> Vec<Option<f64>> {
10915        map_timedelta_labels(self.index.labels(), Timedelta::total_seconds)
10916    }
10917
10918    /// Calendar-style component rows, matching `pd.TimedeltaIndex.components`.
10919    /// NAT propagates as `None`.
10920    #[must_use]
10921    pub fn components(&self) -> Vec<Option<TimedeltaComponents>> {
10922        map_timedelta_labels(self.index.labels(), timedelta_components_for_index)
10923    }
10924
10925    /// Underlying nanosecond duration, matching `pd.TimedeltaIndex.asi8`.
10926    /// `Timedelta::NAT` is preserved at the sentinel value.
10927    #[must_use]
10928    pub fn asi8(&self) -> Vec<i64> {
10929        self.index
10930            .labels()
10931            .iter()
10932            .map(|label| match label {
10933                IndexLabel::Timedelta64(nanos) => *nanos,
10934                IndexLabel::Int64(_)
10935                | IndexLabel::Float64(_)
10936                | IndexLabel::Bool(_)
10937                | IndexLabel::Utf8(_)
10938                | IndexLabel::Datetime64(_)
10939                | IndexLabel::Object(_)
10940                | IndexLabel::Period(_)
10941                | IndexLabel::Interval(_)
10942                | IndexLabel::Null(_) => Timedelta::NAT,
10943            })
10944            .collect()
10945    }
10946
10947    /// Microseconds-within-second component (0..=999_999), matching
10948    /// `pd.TimedeltaIndex.microseconds`.
10949    #[must_use]
10950    pub fn microseconds(&self) -> Vec<Option<i64>> {
10951        map_timedelta_labels(self.index.labels(), |nanos| {
10952            nanos.rem_euclid(Timedelta::NANOS_PER_SEC) / 1_000
10953        })
10954    }
10955
10956    /// Nanoseconds-within-microsecond component (0..=999), matching
10957    /// `pd.TimedeltaIndex.nanoseconds`.
10958    #[must_use]
10959    pub fn nanoseconds(&self) -> Vec<Option<i64>> {
10960        map_timedelta_labels(self.index.labels(), |nanos| nanos.rem_euclid(1_000))
10961    }
10962
10963    /// Position of the maximum label, matching `pd.TimedeltaIndex.argmax()`.
10964    /// Skips NAT and returns the first-tied position to match pandas
10965    /// `skipna=True` default.
10966    pub fn argmax(&self) -> Result<usize, IndexError> {
10967        let labels = self.index.labels();
10968        let mut best: Option<usize> = None;
10969        for (i, label) in labels.iter().enumerate() {
10970            let nanos = match label {
10971                IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => *n,
10972                _ => continue,
10973            };
10974            best = Some(match best {
10975                Some(b) => match labels[b] {
10976                    IndexLabel::Timedelta64(prev) if nanos > prev => i,
10977                    _ => b,
10978                },
10979                None => i,
10980            });
10981        }
10982        best.ok_or_else(|| {
10983            IndexError::InvalidArgument("attempt to get argmax of an empty sequence".to_owned())
10984        })
10985    }
10986
10987    /// Position of the minimum label, matching `pd.TimedeltaIndex.argmin()`.
10988    pub fn argmin(&self) -> Result<usize, IndexError> {
10989        let labels = self.index.labels();
10990        let mut best: Option<usize> = None;
10991        for (i, label) in labels.iter().enumerate() {
10992            let nanos = match label {
10993                IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => *n,
10994                _ => continue,
10995            };
10996            best = Some(match best {
10997                Some(b) => match labels[b] {
10998                    IndexLabel::Timedelta64(prev) if nanos < prev => i,
10999                    _ => b,
11000                },
11001                None => i,
11002            });
11003        }
11004        best.ok_or_else(|| {
11005            IndexError::InvalidArgument("attempt to get argmin of an empty sequence".to_owned())
11006        })
11007    }
11008
11009    /// Positions that would sort the labels ascending, matching
11010    /// `pd.TimedeltaIndex.argsort()`.
11011    #[must_use]
11012    pub fn argsort(&self) -> Vec<usize> {
11013        self.index.argsort()
11014    }
11015
11016    /// First-seen unique labels, matching `pd.TimedeltaIndex.unique()`.
11017    pub fn unique(&self) -> Result<Self, IndexError> {
11018        Self::from_index(self.index.unique())
11019    }
11020
11021    /// Factorization, matching `pd.TimedeltaIndex.factorize()`. NAT inputs
11022    /// receive `-1` codes; uniques excludes NAT.
11023    pub fn factorize(&self) -> Result<(Vec<isize>, Self), IndexError> {
11024        let (codes, uniques) = self.index.factorize();
11025        Ok((codes, Self::from_index(uniques)?))
11026    }
11027
11028    /// Value counts, matching `pd.TimedeltaIndex.value_counts()`. NAT is
11029    /// dropped by default to match pandas.
11030    #[must_use]
11031    pub fn value_counts(&self) -> Vec<(IndexLabel, usize)> {
11032        self.index.value_counts()
11033    }
11034
11035    /// Duplicate mask per position, matching
11036    /// `pd.TimedeltaIndex.duplicated(keep)`.
11037    #[must_use]
11038    pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
11039        self.index.duplicated(keep)
11040    }
11041
11042    /// Drop duplicate labels, matching `pd.TimedeltaIndex.drop_duplicates()`.
11043    pub fn drop_duplicates(&self) -> Result<Self, IndexError> {
11044        Self::from_index(self.index.drop_duplicates())
11045    }
11046
11047    /// Replace positions where `cond` is `false` with `other`, matching
11048    /// `pd.TimedeltaIndex.where(cond, other)`. Pass `Timedelta::NAT` to
11049    /// insert NAT.
11050    pub fn r#where(&self, cond: &[bool], other: i64) -> Result<Self, IndexError> {
11051        let labels = self.index.labels();
11052        if cond.len() != labels.len() {
11053            return Err(IndexError::LengthMismatch {
11054                expected: labels.len(),
11055                actual: cond.len(),
11056                context: "where: cond length must match index length".to_owned(),
11057            });
11058        }
11059        let nanos: Vec<i64> = labels
11060            .iter()
11061            .zip(cond.iter())
11062            .map(|(label, &keep)| {
11063                if keep {
11064                    match label {
11065                        IndexLabel::Timedelta64(n) => *n,
11066                        _ => Timedelta::NAT,
11067                    }
11068                } else {
11069                    other
11070                }
11071            })
11072            .collect();
11073        let mut out = Self::new(nanos);
11074        if let Some(name) = self.name() {
11075            out = out.set_name(name);
11076        }
11077        Ok(out)
11078    }
11079
11080    /// Replace positions where `mask` is `true` with `value`, matching
11081    /// `pd.TimedeltaIndex.putmask(mask, value)`.
11082    pub fn putmask(&self, mask: &[bool], value: i64) -> Result<Self, IndexError> {
11083        let labels = self.index.labels();
11084        if mask.len() != labels.len() {
11085            return Err(IndexError::LengthMismatch {
11086                expected: labels.len(),
11087                actual: mask.len(),
11088                context: "putmask: mask length must match index length".to_owned(),
11089            });
11090        }
11091        let nanos: Vec<i64> = labels
11092            .iter()
11093            .zip(mask.iter())
11094            .map(|(label, &replace)| {
11095                if replace {
11096                    value
11097                } else {
11098                    match label {
11099                        IndexLabel::Timedelta64(n) => *n,
11100                        _ => Timedelta::NAT,
11101                    }
11102                }
11103            })
11104            .collect();
11105        let mut out = Self::new(nanos);
11106        if let Some(name) = self.name() {
11107            out = out.set_name(name);
11108        }
11109        Ok(out)
11110    }
11111
11112    /// Binary-search insertion position, matching
11113    /// `pd.TimedeltaIndex.searchsorted(value, side)`. The needle is a
11114    /// nanosecond duration; NAT needles raise.
11115    pub fn searchsorted(&self, value: i64, side: &str) -> Result<usize, IndexError> {
11116        self.index
11117            .searchsorted(&IndexLabel::Timedelta64(value), side)
11118    }
11119
11120    /// Insert `value` at position `loc`, matching
11121    /// `pd.TimedeltaIndex.insert(loc, value)`. `loc == len()` appends;
11122    /// `loc > len()` raises [`IndexError::OutOfBounds`].
11123    pub fn insert(&self, loc: usize, value: i64) -> Result<Self, IndexError> {
11124        let labels = self.index.labels();
11125        if loc > labels.len() {
11126            return Err(IndexError::OutOfBounds {
11127                position: loc,
11128                length: labels.len(),
11129            });
11130        }
11131        let mut nanos: Vec<i64> = labels
11132            .iter()
11133            .filter_map(|label| match label {
11134                IndexLabel::Timedelta64(n) => Some(*n),
11135                _ => None,
11136            })
11137            .collect();
11138        nanos.insert(loc, value);
11139        let mut out = Self::new(nanos);
11140        if let Some(name) = self.name() {
11141            out = out.set_name(name);
11142        }
11143        Ok(out)
11144    }
11145
11146    /// Stringify each label, matching `pd.TimedeltaIndex.format()`.
11147    /// Non-NAT labels render as a signed nanosecond integer; NAT renders
11148    /// as the `NaT` literal.
11149    #[must_use]
11150    pub fn format(&self) -> Vec<String> {
11151        self.index
11152            .labels()
11153            .iter()
11154            .map(|label| match label {
11155                IndexLabel::Timedelta64(nanos) if *nanos != Timedelta::NAT => nanos.to_string(),
11156                _ => "NaT".to_owned(),
11157            })
11158            .collect()
11159    }
11160
11161    /// Replace NAT positions with `value`, matching
11162    /// `pd.TimedeltaIndex.fillna(value)`. Preserves the index name.
11163    #[must_use]
11164    pub fn fillna(&self, value: i64) -> Self {
11165        let nanos: Vec<i64> = self
11166            .index
11167            .labels()
11168            .iter()
11169            .map(|label| match label {
11170                IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => *n,
11171                _ => value,
11172            })
11173            .collect();
11174        let mut out = Self::new(nanos);
11175        if let Some(name) = self.name() {
11176            out = out.set_name(name);
11177        }
11178        out
11179    }
11180
11181    /// Alias for [`isna`](Self::isna), matching `pd.TimedeltaIndex.isnull()`.
11182    #[must_use]
11183    pub fn isnull(&self) -> Vec<bool> {
11184        self.isna()
11185    }
11186
11187    /// Alias for [`notna`](Self::notna), matching `pd.TimedeltaIndex.notnull()`.
11188    #[must_use]
11189    pub fn notnull(&self) -> Vec<bool> {
11190        self.notna()
11191    }
11192
11193    /// Convert each label to a `chrono::Duration`, matching
11194    /// `pd.TimedeltaIndex.to_pytimedelta()`. NAT propagates as `None`.
11195    #[must_use]
11196    pub fn to_pytimedelta(&self) -> Vec<Option<chrono::Duration>> {
11197        self.index
11198            .labels()
11199            .iter()
11200            .map(|label| match label {
11201                IndexLabel::Timedelta64(nanos) if *nanos != Timedelta::NAT => {
11202                    Some(chrono::Duration::nanoseconds(*nanos))
11203                }
11204                _ => None,
11205            })
11206            .collect()
11207    }
11208
11209    /// The frequency this index was built with, as its freqstr - pandas'
11210    /// `TimedeltaIndex.freq` / `freqstr` ('h', '30min', 'D'); None when it
11211    /// has none (it was always None).
11212    #[must_use]
11213    pub fn freq(&self) -> Option<String> {
11214        self.index.freq().map(str::to_owned)
11215    }
11216
11217    /// Alias of [`Self::freq`], matching `pd.TimedeltaIndex.freqstr`.
11218    #[must_use]
11219    pub fn freqstr(&self) -> Option<String> {
11220        self.freq()
11221    }
11222
11223    /// This index with `freq` (a freqstr) set or cleared; the caller vouches
11224    /// that the labels follow it.
11225    #[must_use]
11226    pub fn with_freq(self, freq: Option<String>) -> Self {
11227        Self {
11228            index: self.index.with_freq(freq),
11229        }
11230    }
11231
11232    /// pandas' `TimedeltaIndex.inferred_freq`: the tick every step is (a
11233    /// count of D / h / min / s / ms / us / ns, negative for a decreasing
11234    /// run); None for fewer than three durations, NaT, repeats or an uneven
11235    /// step (it was always None).
11236    #[must_use]
11237    pub fn inferred_freq(&self) -> Option<String> {
11238        let nanos: Vec<i64> = self
11239            .index
11240            .labels()
11241            .iter()
11242            .map(|label| match label {
11243                IndexLabel::Timedelta64(nanos) if *nanos != i64::MIN => Some(*nanos),
11244                _ => None,
11245            })
11246            .collect::<Option<_>>()?;
11247        if nanos.len() < 3 {
11248            return None;
11249        }
11250        let steps = freq_unique_deltas(&nanos);
11251        let [step] = steps.as_slice() else {
11252            return None;
11253        };
11254        if *step == 0 {
11255            return None;
11256        }
11257        // pandas' daily rule reads a whole-week step as weekly, naming the
11258        // weekday the first duration falls on as an instant after the epoch
11259        // (7 days -> 1970-01-08, a Thursday: 'W-THU').
11260        const WEEK: i64 = 7 * 86_400_000_000_000;
11261        if step % WEEK == 0 {
11262            let weekday = Timestamp::from_nanos(nanos[0]).dayofweek()?;
11263            let code = FREQ_WEEKDAY_CODES.get(usize::try_from(weekday).ok()?)?;
11264            return Some(freq_with_count(step / WEEK, &format!("W-{code}")));
11265        }
11266        [
11267            (86_400_000_000_000, "D"),
11268            (3_600_000_000_000, "h"),
11269            (60_000_000_000, "min"),
11270            (1_000_000_000, "s"),
11271            (1_000_000, "ms"),
11272            (1_000, "us"),
11273            (1, "ns"),
11274        ]
11275        .into_iter()
11276        .find(|(unit, _)| step % unit == 0)
11277        .map(|(unit, rule)| freq_with_count(step / unit, rule))
11278    }
11279
11280    /// Cast to a different storage resolution, matching
11281    /// `pd.TimedeltaIndex.as_unit(unit)`. Only `"ns"` is supported.
11282    pub fn as_unit(&self, unit: &str) -> Result<Self, IndexError> {
11283        match unit {
11284            "ns" => Ok(self.clone()),
11285            other => Err(IndexError::InvalidArgument(format!(
11286                "as_unit: only 'ns' is supported by FrankenPandas's Timedelta64 storage; got {other:?}"
11287            ))),
11288        }
11289    }
11290
11291    /// Storage resolution unit, matching `pd.TimedeltaIndex.unit`. Always
11292    /// `"ns"`.
11293    #[must_use]
11294    pub fn unit(&self) -> &'static str {
11295        "ns"
11296    }
11297
11298    /// Resolution string. Always `"nanosecond"`.
11299    ///
11300    /// ⚠️ TWO ways this is not parity. (a) `pd.TimedeltaIndex.resolution` does
11301    /// NOT exist (measured 2.2.3: `AttributeError`) even though
11302    /// `pd.DatetimeIndex.resolution` DOES. (b) Where pandas has a `resolution`,
11303    /// it describes the DATA, not the storage unit: `resolution` on a
11304    /// `DatetimeIndex` of day-aligned labels returns `'day'`. The fixed
11305    /// `"nanosecond"` here answers a different question, and the class-level
11306    /// `pd.Timedelta.resolution` is a `Timedelta` of 1ns, not a string.
11307    #[must_use]
11308    pub fn resolution(&self) -> &'static str {
11309        "nanosecond"
11310    }
11311
11312    /// First position of `value`, matching `pd.TimedeltaIndex.get_loc(value)`.
11313    pub fn get_loc(&self, value: i64) -> Result<usize, IndexError> {
11314        // Binary-search a monotonic (AscendingTimedelta64) index via
11315        // Index::position; same first-match linear fallback when unsorted
11316        // (br-frankenpandas-idxdup).
11317        self.index
11318            .position(&IndexLabel::Timedelta64(value))
11319            .ok_or_else(|| {
11320                IndexError::InvalidArgument(format!("get_loc: {value} not in TimedeltaIndex"))
11321            })
11322    }
11323
11324    /// Set the index name, matching `pd.TimedeltaIndex.rename(name)`.
11325    #[must_use]
11326    pub fn rename(&self, name: &str) -> Self {
11327        self.set_name(name)
11328    }
11329
11330    /// Reindex against `target`, matching
11331    /// `pd.TimedeltaIndex.reindex(target)`.
11332    #[must_use]
11333    pub fn reindex(&self, target: &Self) -> (Self, Vec<isize>) {
11334        let labels: Vec<i64> = target
11335            .index
11336            .labels()
11337            .iter()
11338            .filter_map(|label| match label {
11339                IndexLabel::Timedelta64(n) => Some(*n),
11340                _ => None,
11341            })
11342            .collect();
11343        let indexer = self.get_indexer(&labels);
11344        (target.clone(), indexer)
11345    }
11346
11347    /// Locate every position matching each target, matching
11348    /// `pd.TimedeltaIndex.get_indexer_non_unique(targets)`.
11349    #[must_use]
11350    pub fn get_indexer_non_unique(&self, targets: &[i64]) -> (Vec<isize>, Vec<usize>) {
11351        let labels = self.index.labels();
11352        let mut by_value = FxHashMap::<i64, Vec<usize>>::default();
11353        for (i, label) in labels.iter().enumerate() {
11354            if let IndexLabel::Timedelta64(n) = label {
11355                by_value.entry(*n).or_default().push(i);
11356            }
11357        }
11358        let mut positions = Vec::<isize>::new();
11359        let mut missing = Vec::<usize>::new();
11360        for (idx, target) in targets.iter().enumerate() {
11361            if let Some(matches) = by_value.get(target) {
11362                positions.extend(
11363                    matches
11364                        .iter()
11365                        .map(|p| isize::try_from(*p).unwrap_or(isize::MAX)),
11366                );
11367            } else {
11368                positions.push(-1);
11369                missing.push(idx);
11370            }
11371        }
11372        (positions, missing)
11373    }
11374
11375    /// Alias for [`get_indexer`](Self::get_indexer), matching
11376    /// `pd.TimedeltaIndex.get_indexer_for(targets)`.
11377    #[must_use]
11378    pub fn get_indexer_for(&self, targets: &[i64]) -> Vec<isize> {
11379        self.get_indexer(targets)
11380    }
11381
11382    /// Locate each label in `targets`, matching
11383    /// `pd.TimedeltaIndex.get_indexer(targets)`.
11384    #[must_use]
11385    pub fn get_indexer(&self, targets: &[i64]) -> Vec<isize> {
11386        let labels = self.index.labels();
11387        let mut positions = FxHashMap::<i64, isize>::default();
11388        for (i, label) in labels.iter().enumerate() {
11389            if let IndexLabel::Timedelta64(n) = label {
11390                positions
11391                    .entry(*n)
11392                    .or_insert_with(|| isize::try_from(i).unwrap_or(isize::MAX));
11393            }
11394        }
11395        targets
11396            .iter()
11397            .map(|n| positions.get(n).copied().unwrap_or(-1))
11398            .collect()
11399    }
11400
11401    /// Position of the slice boundary for `label` and `side`, matching
11402    /// `pd.TimedeltaIndex.get_slice_bound(label, side)`. Mirrors
11403    /// `searchsorted(label, side)`.
11404    pub fn get_slice_bound(&self, label: i64, side: &str) -> Result<usize, IndexError> {
11405        self.searchsorted(label, side)
11406    }
11407
11408    /// Half-open positional range for a label slice, matching
11409    /// `pd.TimedeltaIndex.slice_indexer(start, end)`.
11410    pub fn slice_indexer(
11411        &self,
11412        start: i64,
11413        end: i64,
11414    ) -> Result<std::ops::Range<usize>, IndexError> {
11415        let (left, right) = self.slice_locs(start, end)?;
11416        Ok(left..right)
11417    }
11418
11419    /// Find positions of `[start, end]` for a label slice, matching
11420    /// `pd.TimedeltaIndex.slice_locs(start, end)`. Requires the index to
11421    /// be monotonically increasing.
11422    pub fn slice_locs(&self, start: i64, end: i64) -> Result<(usize, usize), IndexError> {
11423        if !self.is_monotonic_increasing() {
11424            return Err(IndexError::InvalidArgument(
11425                "slice_locs requires a monotonic increasing TimedeltaIndex".to_owned(),
11426            ));
11427        }
11428        let left = self.searchsorted(start, "left")?;
11429        let right = self.searchsorted(end, "right")?;
11430        Ok((left, right))
11431    }
11432
11433    /// Convert to a flat [`Index`], matching
11434    /// `pd.TimedeltaIndex.to_flat_index()`.
11435    #[must_use]
11436    pub fn to_flat_index(&self) -> Index {
11437        self.index.clone()
11438    }
11439
11440    /// String accessor for the flat timedelta labels.
11441    #[must_use]
11442    pub fn r#str(&self) -> IndexStringAccessor<'_> {
11443        IndexStringAccessor::owned(self.to_flat_index())
11444    }
11445
11446    /// One-column row materialization, matching `pd.TimedeltaIndex.to_frame(index=False)`.
11447    #[must_use]
11448    pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
11449        self.to_flat_index().to_frame()
11450    }
11451
11452    /// Series-shaped materialization using timedelta labels as both index and values.
11453    #[must_use]
11454    pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
11455        self.to_flat_index().to_series()
11456    }
11457
11458    /// Whether any timedelta label coerces to true.
11459    #[must_use]
11460    pub fn any(&self) -> bool {
11461        self.to_flat_index().any()
11462    }
11463
11464    /// Whether all timedelta labels coerce to true.
11465    #[must_use]
11466    pub fn all(&self) -> bool {
11467        self.to_flat_index().all()
11468    }
11469
11470    /// Get labels for a level. TimedeltaIndex is flat and only accepts level 0.
11471    pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
11472        self.to_flat_index().get_level_values(level)
11473    }
11474
11475    /// Drop a level. TimedeltaIndex is flat, so removing its only level is invalid.
11476    pub fn droplevel(&self, level: usize) -> Result<Index, IndexError> {
11477        self.to_flat_index().droplevel(level)
11478    }
11479
11480    /// Group equal timedelta labels into position buckets.
11481    #[must_use]
11482    pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
11483        self.to_flat_index().groupby()
11484    }
11485
11486    /// Apply a function to each timedelta label, returning a flat Index.
11487    #[must_use]
11488    pub fn map<F>(&self, func: F) -> Index
11489    where
11490        F: Fn(&IndexLabel) -> IndexLabel,
11491    {
11492        self.to_flat_index().map(func)
11493    }
11494
11495    /// Cast timedelta labels to a pandas dtype string, returning a flat Index.
11496    pub fn astype(&self, dtype: &str) -> Result<Index, IndexError> {
11497        self.to_flat_index().astype(dtype)
11498    }
11499
11500    /// Nearest preceding-or-equal timedelta label lookup.
11501    #[must_use]
11502    pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
11503        self.to_flat_index().asof(key)
11504    }
11505
11506    /// Locate nearest preceding-or-equal timedelta positions for each target label.
11507    #[must_use]
11508    pub fn asof_locs(&self, where_index: &Index, mask: Option<&[bool]>) -> Vec<Option<usize>> {
11509        self.to_flat_index().asof_locs(where_index, mask)
11510    }
11511
11512    /// Drop timedelta labels, returning a flat Index.
11513    #[must_use]
11514    pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Index {
11515        self.to_flat_index().drop(labels_to_drop)
11516    }
11517
11518    /// Join timedelta labels with another flat Index.
11519    pub fn join(&self, other: &Index, how: &str) -> Result<Index, IndexError> {
11520        self.to_flat_index().join(other, how)
11521    }
11522
11523    /// Sort timedelta labels and return the positional sorter.
11524    #[must_use]
11525    pub fn sortlevel(&self) -> (Index, Vec<usize>) {
11526        self.to_flat_index().sortlevel()
11527    }
11528
11529    /// Returns a clone, matching `pd.TimedeltaIndex.view()`.
11530    #[must_use]
11531    pub fn view(&self) -> Self {
11532        self.clone()
11533    }
11534
11535    /// Identity transpose for a 1D index, matching
11536    /// `pd.TimedeltaIndex.transpose()`.
11537    #[must_use]
11538    pub fn transpose(&self) -> Self {
11539        self.clone()
11540    }
11541
11542    /// Alias for `transpose`, matching `pd.TimedeltaIndex.T`.
11543    #[allow(non_snake_case)]
11544    #[must_use]
11545    pub fn T(&self) -> Self {
11546        self.transpose()
11547    }
11548
11549    /// Flatten labels to nanosecond durations with NAT preserved,
11550    /// matching `pd.TimedeltaIndex.ravel()`.
11551    #[must_use]
11552    pub fn ravel(&self) -> Vec<Option<i64>> {
11553        self.values()
11554    }
11555
11556    /// Number of levels, matching `pd.TimedeltaIndex.nlevels`. Always `1`.
11557    #[must_use]
11558    pub fn nlevels(&self) -> usize {
11559        1
11560    }
11561
11562    /// Identity dtype-reinference for typed indexes, matching
11563    /// `pd.TimedeltaIndex.infer_objects()`.
11564    #[must_use]
11565    pub fn infer_objects(&self) -> Self {
11566        self.clone()
11567    }
11568
11569    /// Drop NAT labels, matching `pd.TimedeltaIndex.dropna()`.
11570    pub fn dropna(&self) -> Self {
11571        let surviving: Vec<i64> = self
11572            .index
11573            .labels()
11574            .iter()
11575            .filter_map(|label| match label {
11576                IndexLabel::Timedelta64(nanos) if *nanos != Timedelta::NAT => Some(*nanos),
11577                _ => None,
11578            })
11579            .collect();
11580        let mut filtered = Self::new(surviving);
11581        if let Some(name) = self.name() {
11582            filtered = filtered.set_name(name);
11583        }
11584        filtered
11585    }
11586
11587    /// Pick labels at the given positions, matching
11588    /// `pd.TimedeltaIndex.take()`. Out-of-bounds positions raise
11589    /// [`IndexError::OutOfBounds`].
11590    pub fn take(&self, positions: &[usize]) -> Result<Self, IndexError> {
11591        let labels = self.index.labels();
11592        for &p in positions {
11593            if p >= labels.len() {
11594                return Err(IndexError::OutOfBounds {
11595                    position: p,
11596                    length: labels.len(),
11597                });
11598            }
11599        }
11600        let nanos: Vec<i64> = positions
11601            .iter()
11602            .map(|&p| match labels[p] {
11603                IndexLabel::Timedelta64(n) => n,
11604                _ => Timedelta::NAT,
11605            })
11606            .collect();
11607        let mut out = Self::new(nanos);
11608        if let Some(name) = self.name() {
11609            out = out.set_name(name);
11610        }
11611        Ok(out.with_freq(take_freq(self.freq(), positions)))
11612    }
11613
11614    /// Repeat each label `repeats` times, matching
11615    /// `pd.TimedeltaIndex.repeat()`.
11616    #[must_use]
11617    pub fn repeat(&self, repeats: usize) -> Self {
11618        let mut out = Vec::with_capacity(repeat_output_capacity(self.len(), repeats));
11619        for label in self.index.labels() {
11620            if let IndexLabel::Timedelta64(n) = label {
11621                for _ in 0..repeats {
11622                    out.push(*n);
11623                }
11624            }
11625        }
11626        let mut result = Self::new(out);
11627        if let Some(name) = self.name() {
11628            result = result.set_name(name);
11629        }
11630        result
11631    }
11632
11633    /// Per-position membership mask, matching
11634    /// `pd.TimedeltaIndex.isin(values)`. `values` is interpreted as a slice
11635    /// of nanosecond durations; pass `Timedelta::NAT` to test for NAT.
11636    #[must_use]
11637    pub fn isin(&self, values: &[i64]) -> Vec<bool> {
11638        let needle: FxHashSet<i64> = values.iter().copied().collect();
11639        self.index
11640            .labels()
11641            .iter()
11642            .map(|label| match label {
11643                IndexLabel::Timedelta64(n) => needle.contains(n),
11644                _ => false,
11645            })
11646            .collect()
11647    }
11648
11649    /// Concatenate with another TimedeltaIndex, matching
11650    /// `pd.TimedeltaIndex.append(other)`. Preserves the index name when both
11651    /// operands share it; otherwise pandas drops the name.
11652    #[must_use]
11653    pub fn append(&self, other: &Self) -> Self {
11654        let mut nanos: Vec<i64> = self
11655            .index
11656            .labels()
11657            .iter()
11658            .filter_map(|label| match label {
11659                IndexLabel::Timedelta64(n) => Some(*n),
11660                _ => None,
11661            })
11662            .collect();
11663        nanos.extend(other.index.labels().iter().filter_map(|label| match label {
11664            IndexLabel::Timedelta64(n) => Some(*n),
11665            _ => None,
11666        }));
11667        let mut out = Self::new(nanos);
11668        if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
11669            out = out.set_name(name);
11670        }
11671        out
11672    }
11673
11674    /// Minimum non-NAT label, matching `pd.TimedeltaIndex.min()`.
11675    #[must_use]
11676    pub fn min(&self) -> Option<i64> {
11677        self.index
11678            .labels()
11679            .iter()
11680            .filter_map(|label| match label {
11681                IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => Some(*n),
11682                _ => None,
11683            })
11684            .min()
11685    }
11686
11687    /// Shift each label by `periods` units of `freq_nanos`, matching
11688    /// `pd.TimedeltaIndex.shift(periods, freq)`. NAT propagates as NAT.
11689    #[must_use]
11690    pub fn shift(&self, periods: i64, freq_nanos: i64) -> Self {
11691        let delta = periods.saturating_mul(freq_nanos);
11692        let nanos: Vec<i64> = self
11693            .index
11694            .labels()
11695            .iter()
11696            .map(|label| match label {
11697                IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => n.saturating_add(delta),
11698                _ => Timedelta::NAT,
11699            })
11700            .collect();
11701        let mut out = Self::new(nanos);
11702        if let Some(name) = self.name() {
11703            out = out.set_name(name);
11704        }
11705        out
11706    }
11707
11708    /// Positional first differences, matching `pd.TimedeltaIndex.diff()`.
11709    /// NAT inputs propagate and signed `periods` follows pandas' lookup
11710    /// direction.
11711    #[must_use]
11712    pub fn diff(&self, periods: i64) -> Self {
11713        let labels = self.index.labels();
11714        optional_diffs_to_timedelta_index(
11715            positional_diff(labels.len(), periods, |current, previous| {
11716                match (&labels[current], &labels[previous]) {
11717                    (
11718                        IndexLabel::Timedelta64(current_nanos),
11719                        IndexLabel::Timedelta64(previous_nanos),
11720                    ) if *current_nanos != Timedelta::NAT && *previous_nanos != Timedelta::NAT => {
11721                        current_nanos.checked_sub(*previous_nanos)
11722                    }
11723                    _ => None,
11724                }
11725            }),
11726            self.name(),
11727        )
11728    }
11729
11730    fn round_fixed_freq(&self, freq: &str, mode: TemporalRoundMode) -> Result<Self, IndexError> {
11731        let unit_nanos = parse_fixed_temporal_freq(freq, "TimedeltaIndex rounding")?;
11732        let nanos: Vec<i64> = self
11733            .index
11734            .labels()
11735            .iter()
11736            .map(|label| match label {
11737                IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => {
11738                    round_nanos_to_unit(*n, unit_nanos, mode)
11739                }
11740                _ => Timedelta::NAT,
11741            })
11742            .collect();
11743        let mut out = Self::new(nanos);
11744        if let Some(name) = self.name() {
11745            out = out.set_name(name);
11746        }
11747        Ok(out)
11748    }
11749
11750    /// Round timedeltas down to a fixed pandas frequency.
11751    pub fn floor(&self, freq: &str) -> Result<Self, IndexError> {
11752        self.round_fixed_freq(freq, TemporalRoundMode::Floor)
11753    }
11754
11755    /// Round timedeltas up to a fixed pandas frequency.
11756    pub fn ceil(&self, freq: &str) -> Result<Self, IndexError> {
11757        self.round_fixed_freq(freq, TemporalRoundMode::Ceil)
11758    }
11759
11760    /// Round timedeltas to the nearest fixed pandas frequency, using half-even ties.
11761    pub fn round(&self, freq: &str) -> Result<Self, IndexError> {
11762        self.round_fixed_freq(freq, TemporalRoundMode::Round)
11763    }
11764
11765    /// Average non-NAT label as nanosecond duration, matching
11766    /// `pd.TimedeltaIndex.mean()`. Empty / all-NAT returns `None`.
11767    #[must_use]
11768    pub fn mean(&self) -> Option<i64> {
11769        let mut total: i128 = 0;
11770        let mut count: i128 = 0;
11771        for label in self.index.labels() {
11772            if let IndexLabel::Timedelta64(n) = label
11773                && *n != Timedelta::NAT
11774            {
11775                total += i128::from(*n);
11776                count += 1;
11777            }
11778        }
11779        if count == 0 {
11780            return None;
11781        }
11782        i64::try_from(total / count).ok()
11783    }
11784
11785    /// Sum of non-NAT labels as nanosecond duration, matching
11786    /// `pd.TimedeltaIndex.sum()`. Returns `Some(0)` for empty inputs to
11787    /// match pandas. Sum is computed in `i128` to avoid overflow before
11788    /// narrowing back to `i64`.
11789    #[must_use]
11790    pub fn sum(&self) -> Option<i64> {
11791        let mut total: i128 = 0;
11792        for label in self.index.labels() {
11793            if let IndexLabel::Timedelta64(n) = label
11794                && *n != Timedelta::NAT
11795            {
11796                total += i128::from(*n);
11797            }
11798        }
11799        i64::try_from(total).ok()
11800    }
11801
11802    /// Sample variance over non-NAT labels in nanoseconds-squared,
11803    /// matching `pd.TimedeltaIndex.var(ddof=1)`. Returns `None` for
11804    /// fewer than two non-NAT entries.
11805    #[must_use]
11806    pub fn var(&self) -> Option<f64> {
11807        let nanos: Vec<f64> = self
11808            .index
11809            .labels()
11810            .iter()
11811            .filter_map(|label| match label {
11812                IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => Some(*n as f64),
11813                _ => None,
11814            })
11815            .collect();
11816        if nanos.len() < 2 {
11817            return None;
11818        }
11819        let mean = nanos.iter().sum::<f64>() / nanos.len() as f64;
11820        Some(nanos.iter().map(|n| (n - mean).powi(2)).sum::<f64>() / (nanos.len() as f64 - 1.0))
11821    }
11822
11823    /// Sample standard deviation of non-NAT labels in nanoseconds,
11824    /// matching `pd.TimedeltaIndex.std(ddof=1)`. Returns `None` for
11825    /// fewer than two non-NAT entries.
11826    #[must_use]
11827    pub fn std(&self) -> Option<i64> {
11828        let nanos: Vec<f64> = self
11829            .index
11830            .labels()
11831            .iter()
11832            .filter_map(|label| match label {
11833                IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => Some(*n as f64),
11834                _ => None,
11835            })
11836            .collect();
11837        if nanos.len() < 2 {
11838            return None;
11839        }
11840        let mean = nanos.iter().sum::<f64>() / nanos.len() as f64;
11841        let var =
11842            nanos.iter().map(|n| (n - mean).powi(2)).sum::<f64>() / (nanos.len() as f64 - 1.0);
11843        Some(var.sqrt() as i64)
11844    }
11845
11846    /// Median non-NAT label, matching `pd.TimedeltaIndex.median()`.
11847    #[must_use]
11848    pub fn median(&self) -> Option<i64> {
11849        let mut nanos: Vec<i64> = self
11850            .index
11851            .labels()
11852            .iter()
11853            .filter_map(|label| match label {
11854                IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => Some(*n),
11855                _ => None,
11856            })
11857            .collect();
11858        if nanos.is_empty() {
11859            return None;
11860        }
11861        nanos.sort_unstable();
11862        let mid = nanos.len() / 2;
11863        if nanos.len() % 2 == 1 {
11864            Some(nanos[mid])
11865        } else {
11866            let total = i128::from(nanos[mid - 1]) + i128::from(nanos[mid]);
11867            i64::try_from(total / 2).ok()
11868        }
11869    }
11870
11871    /// Maximum non-NAT label, matching `pd.TimedeltaIndex.max()`.
11872    #[must_use]
11873    pub fn max(&self) -> Option<i64> {
11874        self.index
11875            .labels()
11876            .iter()
11877            .filter_map(|label| match label {
11878                IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => Some(*n),
11879                _ => None,
11880            })
11881            .max()
11882    }
11883
11884    /// Labels present in both indexes, matching
11885    /// `pd.TimedeltaIndex.intersection(other)`.
11886    #[must_use]
11887    pub fn intersection(&self, other: &Self) -> Self {
11888        let other_set: FxHashSet<i64> = other
11889            .index
11890            .labels()
11891            .iter()
11892            .filter_map(|label| match label {
11893                IndexLabel::Timedelta64(n) => Some(*n),
11894                _ => None,
11895            })
11896            .collect();
11897        let mut seen = FxHashSet::<i64>::default();
11898        let nanos: Vec<i64> = self
11899            .index
11900            .labels()
11901            .iter()
11902            .filter_map(|label| match label {
11903                IndexLabel::Timedelta64(n) if other_set.contains(n) && seen.insert(*n) => Some(*n),
11904                _ => None,
11905            })
11906            .collect();
11907        let mut out = Self::new(nanos);
11908        if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
11909            out = out.set_name(name);
11910        }
11911        out
11912    }
11913
11914    /// Labels from self followed by labels from other not already present,
11915    /// matching `pd.TimedeltaIndex.union(other)`.
11916    #[must_use]
11917    pub fn union(&self, other: &Self) -> Self {
11918        let mut seen = FxHashSet::<i64>::default();
11919        let mut nanos: Vec<i64> = Vec::new();
11920        for label in self
11921            .index
11922            .labels()
11923            .iter()
11924            .chain(other.index.labels().iter())
11925        {
11926            if let IndexLabel::Timedelta64(n) = label
11927                && seen.insert(*n)
11928            {
11929                nanos.push(*n);
11930            }
11931        }
11932        let mut out = Self::new(nanos);
11933        if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
11934            out = out.set_name(name);
11935        }
11936        out
11937    }
11938
11939    /// Labels in self not in other, matching
11940    /// `pd.TimedeltaIndex.difference(other)`.
11941    #[must_use]
11942    pub fn difference(&self, other: &Self) -> Self {
11943        let other_set: FxHashSet<i64> = other
11944            .index
11945            .labels()
11946            .iter()
11947            .filter_map(|label| match label {
11948                IndexLabel::Timedelta64(n) => Some(*n),
11949                _ => None,
11950            })
11951            .collect();
11952        let mut seen = FxHashSet::<i64>::default();
11953        let nanos: Vec<i64> = self
11954            .index
11955            .labels()
11956            .iter()
11957            .filter_map(|label| match label {
11958                IndexLabel::Timedelta64(n) if !other_set.contains(n) && seen.insert(*n) => Some(*n),
11959                _ => None,
11960            })
11961            .collect();
11962        let mut out = Self::new(nanos);
11963        // Per br-frankenpandas-6r1lq: difference preserves self.name only
11964        // (asymmetric op).
11965        if let Some(name) = self.name() {
11966            out = out.set_name(name);
11967        }
11968        out
11969    }
11970
11971    /// Labels in either but not both, matching
11972    /// `pd.TimedeltaIndex.symmetric_difference(other)`.
11973    #[must_use]
11974    pub fn symmetric_difference(&self, other: &Self) -> Self {
11975        let self_set: FxHashSet<i64> = self
11976            .index
11977            .labels()
11978            .iter()
11979            .filter_map(|label| match label {
11980                IndexLabel::Timedelta64(n) => Some(*n),
11981                _ => None,
11982            })
11983            .collect();
11984        let other_set: FxHashSet<i64> = other
11985            .index
11986            .labels()
11987            .iter()
11988            .filter_map(|label| match label {
11989                IndexLabel::Timedelta64(n) => Some(*n),
11990                _ => None,
11991            })
11992            .collect();
11993        let mut seen = FxHashSet::<i64>::default();
11994        let mut nanos: Vec<i64> = Vec::new();
11995        for label in self.index.labels() {
11996            if let IndexLabel::Timedelta64(n) = label
11997                && !other_set.contains(n)
11998                && seen.insert(*n)
11999            {
12000                nanos.push(*n);
12001            }
12002        }
12003        for label in other.index.labels() {
12004            if let IndexLabel::Timedelta64(n) = label
12005                && !self_set.contains(n)
12006                && seen.insert(*n)
12007            {
12008                nanos.push(*n);
12009            }
12010        }
12011        let mut out = Self::new(nanos);
12012        if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
12013            out = out.set_name(name);
12014        }
12015        out
12016    }
12017
12018    /// Sort labels ascending, matching `pd.TimedeltaIndex.sort_values()`.
12019    /// NAT sorts first (Timedelta::NAT sentinel) to match pandas
12020    /// `na_position='first'` default.
12021    #[must_use]
12022    pub fn sort_values(&self) -> Self {
12023        let mut nanos: Vec<i64> = self
12024            .index
12025            .labels()
12026            .iter()
12027            .filter_map(|label| match label {
12028                IndexLabel::Timedelta64(n) => Some(*n),
12029                _ => None,
12030            })
12031            .collect();
12032        nanos.sort_unstable();
12033        let mut out = Self::new(nanos);
12034        if let Some(name) = self.name() {
12035            out = out.set_name(name);
12036        }
12037        out
12038    }
12039
12040    /// Alias for `sort_values`, matching `pd.TimedeltaIndex.sort()`.
12041    #[must_use]
12042    pub fn sort(&self) -> Self {
12043        self.sort_values()
12044    }
12045
12046    /// Remove the label at the given position, matching
12047    /// `pd.TimedeltaIndex.delete(loc)`.
12048    pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
12049        let labels = self.index.labels();
12050        if loc >= labels.len() {
12051            return Err(IndexError::OutOfBounds {
12052                position: loc,
12053                length: labels.len(),
12054            });
12055        }
12056        let nanos: Vec<i64> = labels
12057            .iter()
12058            .enumerate()
12059            .filter(|(i, _)| *i != loc)
12060            .filter_map(|(_, label)| match label {
12061                IndexLabel::Timedelta64(n) => Some(*n),
12062                _ => None,
12063            })
12064            .collect();
12065        let mut out = Self::new(nanos);
12066        if let Some(name) = self.name() {
12067            out = out.set_name(name);
12068        }
12069        Ok(out)
12070    }
12071}
12072
12073/// Public pandas-style period index wrapper.
12074///
12075/// `Period` already lives in `fp-types`; this wrapper gives callers a typed
12076/// index container while DataFrame integration can still materialize through
12077/// string labels until a dedicated Period `IndexLabel` variant lands.
12078#[derive(Debug, Clone, Serialize, Deserialize)]
12079pub struct PeriodIndex {
12080    values: Vec<Period>,
12081    name: Option<LabelName>,
12082    /// The freq the index was built at, which an empty one has no period to
12083    /// show (period_range(periods=0) was period[unknown];
12084    /// br-frankenpandas-ce86r). A non-empty index's is its periods'.
12085    #[serde(default)]
12086    built_freq: Option<PeriodFreq>,
12087}
12088
12089/// Equal periods, name and freq - the periods' own, or for empty indexes
12090/// the freq each was built at - whichever constructor made them.
12091impl PartialEq for PeriodIndex {
12092    fn eq(&self, other: &Self) -> bool {
12093        self.values == other.values && self.name == other.name && self.freq() == other.freq()
12094    }
12095}
12096
12097impl Eq for PeriodIndex {}
12098
12099impl PeriodIndex {
12100    #[must_use]
12101    pub fn new(values: Vec<Period>) -> Self {
12102        Self {
12103            values,
12104            name: None,
12105            built_freq: None,
12106        }
12107    }
12108
12109    /// Construct a PeriodIndex from raw ordinal values and a frequency,
12110    /// matching `pd.PeriodIndex.from_ordinals(ordinals, freq)`.
12111    #[must_use]
12112    pub fn from_ordinals(ordinals: &[i64], freq: PeriodFreq) -> Self {
12113        let values: Vec<Period> = ordinals
12114            .iter()
12115            .map(|&ordinal| Period::new(ordinal, freq))
12116            .collect();
12117        Self {
12118            values,
12119            name: None,
12120            built_freq: Some(freq),
12121        }
12122    }
12123
12124    pub fn from_fields(fields: PeriodFields<'_>) -> Result<Self, IndexError> {
12125        validate_period_fields(&fields)?;
12126        let freq = period_fields_freq(&fields)?;
12127        let values = (0..fields.year.len())
12128            .map(|position| period_from_fields_at(&fields, freq, position))
12129            .collect::<Result<Vec<_>, _>>()?;
12130        Ok(Self {
12131            values,
12132            name: None,
12133            built_freq: Some(freq),
12134        })
12135    }
12136
12137    #[must_use]
12138    pub fn from_range(start: Period, periods: usize) -> Self {
12139        Self {
12140            values: fp_types::period_range(start, periods),
12141            name: None,
12142            built_freq: Some(start.freq),
12143        }
12144    }
12145
12146    #[must_use]
12147    pub fn values(&self) -> &[Period] {
12148        &self.values
12149    }
12150
12151    #[must_use]
12152    pub fn len(&self) -> usize {
12153        self.values.len()
12154    }
12155
12156    #[must_use]
12157    pub fn is_empty(&self) -> bool {
12158        self.values.is_empty()
12159    }
12160
12161    #[must_use]
12162    pub fn name(&self) -> Option<&LabelName> {
12163        self.name.as_ref()
12164    }
12165
12166    #[must_use]
12167    pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
12168        let mut out = self.clone();
12169        out.name = Some(name.into());
12170        out
12171    }
12172
12173    #[must_use]
12174    pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
12175        let mut out = self.clone();
12176        out.name = name.map(Into::into);
12177        out
12178    }
12179
12180    #[must_use]
12181    pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
12182        self.set_names(name)
12183    }
12184
12185    #[must_use]
12186    pub fn names(&self) -> Vec<Option<String>> {
12187        vec![self.name.clone().map(String::from)]
12188    }
12189
12190    #[must_use]
12191    pub fn copy(&self) -> Self {
12192        self.clone()
12193    }
12194
12195    #[must_use]
12196    pub fn shape(&self) -> (usize,) {
12197        (self.len(),)
12198    }
12199
12200    #[must_use]
12201    pub fn size(&self) -> usize {
12202        self.len()
12203    }
12204
12205    #[must_use]
12206    pub fn empty(&self) -> bool {
12207        self.is_empty()
12208    }
12209
12210    #[must_use]
12211    pub fn dtype(&self) -> String {
12212        self.freq().map_or_else(
12213            || "period[unknown]".to_owned(),
12214            |freq| format!("period[{freq}]"),
12215        )
12216    }
12217
12218    #[must_use]
12219    pub fn dtypes(&self) -> Vec<String> {
12220        vec![self.dtype()]
12221    }
12222
12223    /// Whether any period label is missing (NaT, [`Period::is_nat`]; this
12224    /// was always false, br-frankenpandas-u6p7i).
12225    #[must_use]
12226    pub fn hasnans(&self) -> bool {
12227        self.values.iter().any(Period::is_nat)
12228    }
12229
12230    /// Missing-value mask, matching `pd.PeriodIndex.isna()`.
12231    #[must_use]
12232    pub fn isna(&self) -> Vec<bool> {
12233        self.values.iter().map(Period::is_nat).collect()
12234    }
12235
12236    /// Alias for [`isna`](Self::isna), matching `pd.PeriodIndex.isnull()`.
12237    #[must_use]
12238    pub fn isnull(&self) -> Vec<bool> {
12239        self.isna()
12240    }
12241
12242    /// Non-missing mask, matching `pd.PeriodIndex.notna()`.
12243    #[must_use]
12244    pub fn notna(&self) -> Vec<bool> {
12245        self.values.iter().map(|period| !period.is_nat()).collect()
12246    }
12247
12248    /// Alias for [`notna`](Self::notna), matching `pd.PeriodIndex.notnull()`.
12249    #[must_use]
12250    pub fn notnull(&self) -> Vec<bool> {
12251        self.notna()
12252    }
12253
12254    /// Drop missing labels, matching `pd.PeriodIndex.dropna()`.
12255    ///
12256    /// With no native Period NaT sentinel, this is a name-preserving clone.
12257    #[must_use]
12258    pub fn dropna(&self) -> Self {
12259        self.clone()
12260    }
12261
12262    #[must_use]
12263    pub fn memory_usage(&self, deep: bool) -> usize {
12264        let name_bytes = if deep {
12265            self.name.as_ref().map_or(0, |name| name.len())
12266        } else {
12267            0
12268        };
12269        fixed_width_label_memory_usage(self.values.len(), std::mem::size_of::<Period>())
12270            .saturating_add(name_bytes)
12271    }
12272
12273    #[must_use]
12274    pub fn nbytes(&self) -> usize {
12275        self.memory_usage(false)
12276    }
12277
12278    fn compare_periods(left: &Period, right: &Period) -> std::cmp::Ordering {
12279        left.cmp_same_freq(right).unwrap_or_else(|| {
12280            left.freq
12281                .cmp(&right.freq)
12282                .then(left.ordinal.cmp(&right.ordinal))
12283        })
12284    }
12285
12286    #[must_use]
12287    pub fn is_unique(&self) -> bool {
12288        let mut direction = std::cmp::Ordering::Equal;
12289        for pair in self.values.windows(2) {
12290            let ordering = Self::compare_periods(&pair[0], &pair[1]);
12291            if ordering.is_eq() {
12292                return false;
12293            }
12294            if direction.is_eq() {
12295                direction = ordering;
12296            } else if ordering != direction {
12297                let unique: FxHashSet<&Period> = self.values.iter().collect();
12298                return unique.len() == self.values.len();
12299            }
12300        }
12301        true
12302    }
12303
12304    #[must_use]
12305    pub fn has_duplicates(&self) -> bool {
12306        !self.is_unique()
12307    }
12308
12309    #[must_use]
12310    pub fn is_monotonic_increasing(&self) -> bool {
12311        self.values
12312            .windows(2)
12313            .all(|window| Self::compare_periods(&window[0], &window[1]).is_le())
12314    }
12315
12316    #[must_use]
12317    pub fn is_monotonic(&self) -> bool {
12318        self.is_monotonic_increasing()
12319    }
12320
12321    #[must_use]
12322    pub fn is_monotonic_decreasing(&self) -> bool {
12323        self.values
12324            .windows(2)
12325            .all(|window| Self::compare_periods(&window[0], &window[1]).is_ge())
12326    }
12327
12328    #[must_use]
12329    pub fn nunique(&self) -> usize {
12330        self.values.iter().collect::<FxHashSet<_>>().len()
12331    }
12332
12333    #[must_use]
12334    pub fn ndim(&self) -> usize {
12335        1
12336    }
12337
12338    pub fn item(&self) -> Result<Period, IndexError> {
12339        if self.values.len() == 1 {
12340            Ok(self.values[0])
12341        } else {
12342            Err(IndexError::InvalidArgument(format!(
12343                "item requires exactly one label, got {}",
12344                self.values.len()
12345            )))
12346        }
12347    }
12348
12349    #[must_use]
12350    pub fn is_(&self, other: &Self) -> bool {
12351        std::ptr::eq(self, other)
12352    }
12353
12354    #[must_use]
12355    pub fn equals(&self, other: &Self) -> bool {
12356        self.values == other.values
12357    }
12358
12359    #[must_use]
12360    pub fn identical(&self, other: &Self) -> bool {
12361        self.equals(other) && self.name == other.name
12362    }
12363
12364    #[must_use]
12365    pub fn holds_integer(&self) -> bool {
12366        false
12367    }
12368
12369    #[must_use]
12370    pub fn inferred_type(&self) -> &'static str {
12371        "period"
12372    }
12373
12374    #[must_use]
12375    pub fn is_boolean(&self) -> bool {
12376        false
12377    }
12378
12379    #[must_use]
12380    pub fn is_categorical(&self) -> bool {
12381        false
12382    }
12383
12384    #[must_use]
12385    pub fn is_floating(&self) -> bool {
12386        false
12387    }
12388
12389    #[must_use]
12390    pub fn is_integer(&self) -> bool {
12391        false
12392    }
12393
12394    #[must_use]
12395    pub fn is_interval(&self) -> bool {
12396        false
12397    }
12398
12399    #[must_use]
12400    pub fn is_numeric(&self) -> bool {
12401        false
12402    }
12403
12404    #[must_use]
12405    pub fn is_object(&self) -> bool {
12406        false
12407    }
12408
12409    #[must_use]
12410    pub fn freq(&self) -> Option<PeriodFreq> {
12411        self.values
12412            .first()
12413            .map(|period| period.freq)
12414            .or(self.built_freq)
12415    }
12416
12417    /// Raw period ordinals, matching `pd.PeriodIndex.asi8`.
12418    #[must_use]
12419    pub fn asi8(&self) -> Vec<i64> {
12420        self.values.iter().map(|period| period.ordinal).collect()
12421    }
12422
12423    #[must_use]
12424    pub fn to_list(&self) -> Vec<Period> {
12425        self.values.clone()
12426    }
12427
12428    #[must_use]
12429    pub fn tolist(&self) -> Vec<Period> {
12430        self.to_list()
12431    }
12432
12433    #[must_use]
12434    pub fn to_numpy(&self) -> Vec<Period> {
12435        self.values.clone()
12436    }
12437
12438    #[must_use]
12439    pub fn array(&self) -> Vec<Period> {
12440        self.values.clone()
12441    }
12442
12443    #[must_use]
12444    pub fn to_index(&self) -> Index {
12445        // Period labels, so a Series / DataFrame on this index keeps it (it
12446        // was their text; 45fzr).
12447        Index::new(
12448            self.values
12449                .iter()
12450                .copied()
12451                .map(IndexLabel::Period)
12452                .collect(),
12453        )
12454        .set_names(self.name.clone())
12455    }
12456
12457    /// The PeriodIndex `index` holds: its labels periods of one freq (NaT
12458    /// among them), or None for any other label (45fzr).
12459    #[must_use]
12460    pub fn from_index(index: &Index) -> Option<Self> {
12461        let mut freq = None;
12462        let values = index
12463            .labels()
12464            .iter()
12465            .map(|label| match label {
12466                IndexLabel::Period(period) if freq.is_none_or(|freq| freq == period.freq) => {
12467                    freq = Some(period.freq);
12468                    Some(*period)
12469                }
12470                _ => None,
12471            })
12472            .collect::<Option<Vec<_>>>()?;
12473        Some(Self {
12474            values,
12475            name: index.name().cloned(),
12476            built_freq: freq,
12477        })
12478    }
12479
12480    /// First-seen unique periods, matching `pd.PeriodIndex.unique()`.
12481    /// Preserves the index name.
12482    #[must_use]
12483    pub fn unique(&self) -> Self {
12484        let mut seen = FxHashSet::<&Period>::default();
12485        let mut uniques = Vec::<Period>::new();
12486        for period in &self.values {
12487            if seen.insert(period) {
12488                uniques.push(*period);
12489            }
12490        }
12491        Self {
12492            values: uniques,
12493            name: self.name.clone(),
12494            built_freq: self.built_freq,
12495        }
12496    }
12497
12498    /// Per-position duplicate mask, matching
12499    /// `pd.PeriodIndex.duplicated(keep)`.
12500    #[must_use]
12501    pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
12502        let mut result = vec![false; self.values.len()];
12503        match keep {
12504            DuplicateKeep::First => {
12505                let mut seen = FxHashSet::<&Period>::default();
12506                for (i, period) in self.values.iter().enumerate() {
12507                    if !seen.insert(period) {
12508                        result[i] = true;
12509                    }
12510                }
12511            }
12512            DuplicateKeep::Last => {
12513                let mut seen = FxHashSet::<&Period>::default();
12514                for (i, period) in self.values.iter().enumerate().rev() {
12515                    if !seen.insert(period) {
12516                        result[i] = true;
12517                    }
12518                }
12519            }
12520            DuplicateKeep::None => {
12521                let mut counts = FxHashMap::<&Period, usize>::default();
12522                for period in &self.values {
12523                    *counts.entry(period).or_insert(0) += 1;
12524                }
12525                for (i, period) in self.values.iter().enumerate() {
12526                    if counts.get(period).copied().unwrap_or(0) > 1 {
12527                        result[i] = true;
12528                    }
12529                }
12530            }
12531        }
12532        result
12533    }
12534
12535    /// Drop duplicate periods (keep first), matching
12536    /// `pd.PeriodIndex.drop_duplicates()`.
12537    #[must_use]
12538    pub fn drop_duplicates(&self) -> Self {
12539        self.unique()
12540    }
12541
12542    /// Value counts, matching `pd.PeriodIndex.value_counts()`. Pandas
12543    /// sorts descending by count.
12544    #[must_use]
12545    pub fn value_counts(&self) -> Vec<(Period, usize)> {
12546        let mut order = Vec::<&Period>::new();
12547        let mut counts = FxHashMap::<&Period, usize>::default();
12548        for period in &self.values {
12549            let entry = counts.entry(period).or_insert_with(|| {
12550                order.push(period);
12551                0
12552            });
12553            *entry += 1;
12554        }
12555        let mut pairs: Vec<(Period, usize)> = order.iter().map(|p| (**p, counts[*p])).collect();
12556        pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
12557        pairs
12558    }
12559
12560    /// Pick periods at the given positions, matching
12561    /// `pd.PeriodIndex.take()`. Out-of-bounds positions raise
12562    /// [`IndexError::OutOfBounds`].
12563    pub fn take(&self, positions: &[usize]) -> Result<Self, IndexError> {
12564        for &p in positions {
12565            if p >= self.values.len() {
12566                return Err(IndexError::OutOfBounds {
12567                    position: p,
12568                    length: self.values.len(),
12569                });
12570            }
12571        }
12572        let taken: Vec<Period> = positions.iter().map(|&p| self.values[p]).collect();
12573        Ok(Self {
12574            values: taken,
12575            name: self.name.clone(),
12576            built_freq: self.freq(),
12577        })
12578    }
12579
12580    /// Repeat each period `repeats` times, matching
12581    /// `pd.PeriodIndex.repeat()`.
12582    #[must_use]
12583    pub fn repeat(&self, repeats: usize) -> Self {
12584        let mut out = Vec::with_capacity(repeat_output_capacity(self.values.len(), repeats));
12585        for &period in &self.values {
12586            for _ in 0..repeats {
12587                out.push(period);
12588            }
12589        }
12590        Self {
12591            values: out,
12592            name: self.name.clone(),
12593            built_freq: self.freq(),
12594        }
12595    }
12596
12597    /// Positional first differences in period-frequency units.
12598    ///
12599    /// Pandas returns frequency offset objects for `PeriodIndex.diff()`. The
12600    /// Rust surface exposes the same semantic payload as ordinal deltas while
12601    /// preserving null slots for positions without a comparison partner or
12602    /// mixed-frequency pairs.
12603    #[must_use]
12604    pub fn diff(&self, periods: i64) -> Vec<Option<i64>> {
12605        positional_diff(self.values.len(), periods, |current, previous| {
12606            self.values[current].diff(&self.values[previous])
12607        })
12608    }
12609
12610    /// Convert periods to a new frequency using pandas' default end boundary.
12611    ///
12612    /// Matches `pd.PeriodIndex.asfreq(freq)` for supported target frequencies.
12613    pub fn asfreq(&self, freq: &str) -> Result<Self, IndexError> {
12614        self.asfreq_with_how(freq, "end")
12615    }
12616
12617    /// Convert periods to a new frequency at the requested boundary.
12618    ///
12619    /// Supported `how` values mirror pandas' common aliases:
12620    /// `start` / `s` / `begin` and `end` / `e` / `finish`.
12621    pub fn asfreq_with_how(&self, freq: &str, how: &str) -> Result<Self, IndexError> {
12622        let target_freq = PeriodFreq::parse(freq).ok_or_else(|| {
12623            IndexError::InvalidArgument(format!("asfreq: unsupported frequency '{freq}'"))
12624        })?;
12625        let boundary = parse_period_boundary_how(how, "asfreq")?;
12626        let values = self
12627            .values
12628            .iter()
12629            .copied()
12630            .map(|period| {
12631                // NaT stays NaT at the new frequency.
12632                if period.ordinal == i64::MIN {
12633                    return Ok(Period::new(i64::MIN, target_freq));
12634                }
12635                let nanos = period_boundary_nanos(period, boundary)?;
12636                datetime_period_ordinal_at_boundary(nanos, target_freq, boundary)
12637                    .map(|ordinal| Period::new(ordinal, target_freq))
12638            })
12639            .collect::<Result<Vec<_>, _>>()?;
12640        Ok(Self {
12641            values,
12642            name: self.name.clone(),
12643            built_freq: Some(target_freq),
12644        })
12645    }
12646
12647    fn to_timestamp_boundary(&self, boundary: PeriodBoundary) -> Result<DatetimeIndex, IndexError> {
12648        let nanos = self
12649            .values
12650            .iter()
12651            .copied()
12652            .map(|period| period_boundary_nanos(period, boundary))
12653            .collect::<Result<Vec<_>, _>>()?;
12654        let mut out = DatetimeIndex::new(nanos);
12655        if let Some(name) = self.name() {
12656            out = out.set_name(name);
12657        }
12658        Ok(out)
12659    }
12660
12661    /// Timestamp at each period's start boundary.
12662    ///
12663    /// Matches `pd.PeriodIndex.start_time`.
12664    pub fn start_time(&self) -> Result<DatetimeIndex, IndexError> {
12665        self.to_timestamp_boundary(PeriodBoundary::Start)
12666    }
12667
12668    /// Timestamp at each period's inclusive end boundary.
12669    ///
12670    /// Matches `pd.PeriodIndex.end_time`.
12671    pub fn end_time(&self) -> Result<DatetimeIndex, IndexError> {
12672        self.to_timestamp_boundary(PeriodBoundary::End)
12673    }
12674
12675    /// Convert periods to timestamp labels at the requested boundary.
12676    ///
12677    /// Supported `how` values mirror pandas' common aliases:
12678    /// `start` / `s` / `begin` and `end` / `e` / `finish`.
12679    pub fn to_timestamp(&self, how: &str) -> Result<DatetimeIndex, IndexError> {
12680        match how.trim().to_ascii_lowercase().as_str() {
12681            "" | "s" | "start" | "begin" | "b" => self.start_time(),
12682            "e" | "end" | "finish" => self.end_time(),
12683            other => Err(IndexError::InvalidArgument(format!(
12684                "to_timestamp how must be 'start' or 'end', got {other:?}"
12685            ))),
12686        }
12687    }
12688
12689    /// Fiscal year for each period's ending boundary.
12690    ///
12691    /// For the currently supported unanchored frequencies this is the
12692    /// calendar year of `end_time`, matching pandas' `PeriodIndex.qyear`.
12693    pub fn qyear(&self) -> Result<Vec<i32>, IndexError> {
12694        self.values
12695            .iter()
12696            .copied()
12697            .map(period_qyear)
12698            .collect::<Result<Vec<_>, _>>()
12699    }
12700
12701    // ── Per br-frankenpandas-qigpe: date-part accessors (19 methods) ──
12702
12703    /// The instant each period's fields read, as pandas' `get_date_info`
12704    /// reads them: the period's END date at midnight - a month's day is its
12705    /// last (31), a quarter's month its third, a week's year that of its
12706    /// Sunday - and a sub-daily period its own start (the hour it is). NaT
12707    /// stays NaT. The fields read the start (day 1, month 1 of a quarter).
12708    fn field_instants(&self) -> Result<DatetimeIndex, IndexError> {
12709        const DAY: i64 = 86_400_000_000_000;
12710        let nanos = self
12711            .values
12712            .iter()
12713            .map(|&period| {
12714                if period.ordinal == i64::MIN {
12715                    return Ok(i64::MIN);
12716                }
12717                match period.freq {
12718                    PeriodFreq::Hourly
12719                    | PeriodFreq::Minutely
12720                    | PeriodFreq::Secondly
12721                    | PeriodFreq::Milliseconds
12722                    | PeriodFreq::Microseconds
12723                    | PeriodFreq::Nanoseconds => period_start_nanos(period),
12724                    _ => period_end_nanos(period).map(|end| end - end.rem_euclid(DAY)),
12725                }
12726            })
12727            .collect::<Result<Vec<_>, _>>()?;
12728        Ok(DatetimeIndex::new(nanos))
12729    }
12730
12731    /// Year component for each period, matching `pd.PeriodIndex.year`.
12732    pub fn year(&self) -> Result<Vec<Option<i32>>, IndexError> {
12733        Ok(self.field_instants()?.year())
12734    }
12735
12736    /// Month component (1-12), matching `pd.PeriodIndex.month`.
12737    pub fn month(&self) -> Result<Vec<Option<u32>>, IndexError> {
12738        Ok(self.field_instants()?.month())
12739    }
12740
12741    /// Day of month (1-31), matching `pd.PeriodIndex.day`.
12742    pub fn day(&self) -> Result<Vec<Option<u32>>, IndexError> {
12743        Ok(self.field_instants()?.day())
12744    }
12745
12746    /// Hour (0-23), matching `pd.PeriodIndex.hour`.
12747    pub fn hour(&self) -> Result<Vec<Option<u32>>, IndexError> {
12748        Ok(self.field_instants()?.hour())
12749    }
12750
12751    /// Minute (0-59), matching `pd.PeriodIndex.minute`.
12752    pub fn minute(&self) -> Result<Vec<Option<u32>>, IndexError> {
12753        Ok(self.field_instants()?.minute())
12754    }
12755
12756    /// Second (0-59), matching `pd.PeriodIndex.second`.
12757    pub fn second(&self) -> Result<Vec<Option<u32>>, IndexError> {
12758        Ok(self.field_instants()?.second())
12759    }
12760
12761    /// Quarter (1-4), matching `pd.PeriodIndex.quarter`: a quarterly
12762    /// period's fiscal quarter (Q-JAN's 2025Q1 is quarter 1 though it ends
12763    /// in April), any other the calendar quarter of its end date.
12764    pub fn quarter(&self) -> Result<Vec<Option<u32>>, IndexError> {
12765        let calendar = self.field_instants()?.quarter();
12766        Ok(self
12767            .values
12768            .iter()
12769            .zip(calendar)
12770            .map(|(period, calendar)| match period.freq {
12771                PeriodFreq::Quarterly(_) if period.ordinal != i64::MIN => {
12772                    u32::try_from(period.ordinal.rem_euclid(4) + 1).ok()
12773                }
12774                _ => calendar,
12775            })
12776            .collect())
12777    }
12778
12779    /// Day of week (0=Monday, 6=Sunday), matching `pd.PeriodIndex.weekday`.
12780    pub fn weekday(&self) -> Result<Vec<Option<u32>>, IndexError> {
12781        Ok(self.field_instants()?.weekday())
12782    }
12783
12784    /// Day of week (0=Monday, 6=Sunday), alias for weekday.
12785    /// Matches `pd.PeriodIndex.dayofweek`.
12786    pub fn dayofweek(&self) -> Result<Vec<Option<u32>>, IndexError> {
12787        self.weekday()
12788    }
12789
12790    /// Day of week (0=Monday, 6=Sunday), alias for weekday.
12791    /// Matches `pd.PeriodIndex.day_of_week`.
12792    pub fn day_of_week(&self) -> Result<Vec<Option<u32>>, IndexError> {
12793        self.weekday()
12794    }
12795
12796    /// Day of year (1-366), matching `pd.PeriodIndex.dayofyear`.
12797    pub fn dayofyear(&self) -> Result<Vec<Option<u32>>, IndexError> {
12798        Ok(self.field_instants()?.dayofyear())
12799    }
12800
12801    /// Day of year (1-366), alias for dayofyear.
12802    /// Matches `pd.PeriodIndex.day_of_year`.
12803    pub fn day_of_year(&self) -> Result<Vec<Option<u32>>, IndexError> {
12804        self.dayofyear()
12805    }
12806
12807    /// Days in month (28-31), matching `pd.PeriodIndex.days_in_month`.
12808    pub fn days_in_month(&self) -> Result<Vec<Option<u32>>, IndexError> {
12809        Ok(self.field_instants()?.daysinmonth())
12810    }
12811
12812    /// Days in month (28-31), alias for days_in_month.
12813    /// Matches `pd.PeriodIndex.daysinmonth`.
12814    pub fn daysinmonth(&self) -> Result<Vec<Option<u32>>, IndexError> {
12815        self.days_in_month()
12816    }
12817
12818    /// ISO week number (1-53), matching `pd.PeriodIndex.week`.
12819    pub fn week(&self) -> Result<Vec<Option<u32>>, IndexError> {
12820        Ok(self.field_instants()?.week())
12821    }
12822
12823    /// ISO week number (1-53), alias for week.
12824    /// Matches `pd.PeriodIndex.weekofyear`.
12825    pub fn weekofyear(&self) -> Result<Vec<Option<u32>>, IndexError> {
12826        self.week()
12827    }
12828
12829    /// Whether year is a leap year, matching `pd.PeriodIndex.is_leap_year`.
12830    pub fn is_leap_year(&self) -> Result<Vec<Option<bool>>, IndexError> {
12831        Ok(self.field_instants()?.is_leap_year())
12832    }
12833
12834    /// Frequency resolution string, matching `pd.PeriodIndex.resolution`.
12835    ///
12836    /// `None` for an empty index, and also for the two frequencies whose pandas
12837    /// offsets have no resolution to report -- see [`PeriodFreq::resolution`].
12838    #[must_use]
12839    pub fn resolution(&self) -> Option<&'static str> {
12840        self.values.first().and_then(|p| p.freq.resolution())
12841    }
12842
12843    /// Format each period as a string with strftime, matching `pd.PeriodIndex.strftime`.
12844    pub fn strftime(&self, fmt: &str) -> Result<Vec<Option<String>>, IndexError> {
12845        Ok(self.field_instants()?.strftime(fmt))
12846    }
12847
12848    fn ensure_homogeneous_freq(&self) -> Result<Option<PeriodFreq>, IndexError> {
12849        let mut iter = self.values.iter();
12850        let Some(first) = iter.next() else {
12851            return Ok(None);
12852        };
12853        for period in iter {
12854            if period.freq != first.freq {
12855                return Err(IndexError::InvalidArgument(format!(
12856                    "PeriodIndex has mixed frequencies: {:?} and {:?}",
12857                    first.freq, period.freq
12858                )));
12859            }
12860        }
12861        Ok(Some(first.freq))
12862    }
12863
12864    fn ensure_compatible_freq(&self, other: &Self) -> Result<(), IndexError> {
12865        if let (Some(left), Some(right)) = (self.values.first(), other.values.first())
12866            && left.freq != right.freq
12867        {
12868            return Err(IndexError::InvalidArgument(format!(
12869                "set operation: incompatible frequencies {:?} vs {:?}",
12870                left.freq, right.freq
12871            )));
12872        }
12873        self.ensure_homogeneous_freq()?;
12874        other.ensure_homogeneous_freq()?;
12875        Ok(())
12876    }
12877
12878    /// Periods present in both, matching
12879    /// `pd.PeriodIndex.intersection(other)`. Mixed-freq rejects.
12880    pub fn intersection(&self, other: &Self) -> Result<Self, IndexError> {
12881        self.ensure_compatible_freq(other)?;
12882        let other_set: FxHashSet<&Period> = other.values.iter().collect();
12883        let mut seen = FxHashSet::<&Period>::default();
12884        let values: Vec<Period> = self
12885            .values
12886            .iter()
12887            .filter(|p| other_set.contains(p) && seen.insert(p))
12888            .copied()
12889            .collect();
12890        Ok(Self {
12891            values,
12892            name: if self.name == other.name {
12893                self.name.clone()
12894            } else {
12895                None
12896            },
12897            built_freq: self.freq(),
12898        })
12899    }
12900
12901    /// Self periods then other periods not seen, matching
12902    /// `pd.PeriodIndex.union(other)`. Mixed-freq rejects.
12903    pub fn union(&self, other: &Self) -> Result<Self, IndexError> {
12904        self.ensure_compatible_freq(other)?;
12905        let mut seen = FxHashSet::<Period>::default();
12906        let values: Vec<Period> = self
12907            .values
12908            .iter()
12909            .chain(other.values.iter())
12910            .filter(|p| seen.insert(**p))
12911            .copied()
12912            .collect();
12913        Ok(Self {
12914            values,
12915            name: if self.name == other.name {
12916                self.name.clone()
12917            } else {
12918                None
12919            },
12920            built_freq: self.freq(),
12921        })
12922    }
12923
12924    /// Self periods not in other, matching
12925    /// `pd.PeriodIndex.difference(other)`. Mixed-freq rejects.
12926    pub fn difference(&self, other: &Self) -> Result<Self, IndexError> {
12927        self.ensure_compatible_freq(other)?;
12928        let other_set: FxHashSet<&Period> = other.values.iter().collect();
12929        let mut seen = FxHashSet::<&Period>::default();
12930        let values: Vec<Period> = self
12931            .values
12932            .iter()
12933            .filter(|p| !other_set.contains(p) && seen.insert(p))
12934            .copied()
12935            .collect();
12936        Ok(Self {
12937            values,
12938            name: if self.name == other.name {
12939                self.name.clone()
12940            } else {
12941                None
12942            },
12943            built_freq: self.freq(),
12944        })
12945    }
12946
12947    /// Periods in either but not both, matching
12948    /// `pd.PeriodIndex.symmetric_difference(other)`. Mixed-freq rejects.
12949    pub fn symmetric_difference(&self, other: &Self) -> Result<Self, IndexError> {
12950        self.ensure_compatible_freq(other)?;
12951        let self_set: FxHashSet<&Period> = self.values.iter().collect();
12952        let other_set: FxHashSet<&Period> = other.values.iter().collect();
12953        let mut seen = FxHashSet::<Period>::default();
12954        let mut values = Vec::<Period>::new();
12955        for p in &self.values {
12956            if !other_set.contains(p) && seen.insert(*p) {
12957                values.push(*p);
12958            }
12959        }
12960        for p in &other.values {
12961            if !self_set.contains(p) && seen.insert(*p) {
12962                values.push(*p);
12963            }
12964        }
12965        Ok(Self {
12966            values,
12967            name: if self.name == other.name {
12968                self.name.clone()
12969            } else {
12970                None
12971            },
12972            built_freq: self.freq(),
12973        })
12974    }
12975
12976    /// Sort periods by ordinal ascending, matching
12977    /// `pd.PeriodIndex.sort_values()`. Mixed-frequency rejects.
12978    pub fn sort_values(&self) -> Result<Self, IndexError> {
12979        self.ensure_homogeneous_freq()?;
12980        let mut periods = self.values.clone();
12981        periods.sort_by_key(|period| period.ordinal);
12982        Ok(Self {
12983            values: periods,
12984            name: self.name.clone(),
12985            built_freq: self.freq(),
12986        })
12987    }
12988
12989    /// Alias for `sort_values`, matching `pd.PeriodIndex.sort()`.
12990    pub fn sort(&self) -> Result<Self, IndexError> {
12991        self.sort_values()
12992    }
12993
12994    /// Position of the maximum ordinal, matching
12995    /// `pd.PeriodIndex.argmax()`. Mixed-freq input rejects; empty
12996    /// raises pandas-style "attempt to get argmax of an empty
12997    /// sequence".
12998    pub fn argmax(&self) -> Result<usize, IndexError> {
12999        self.ensure_homogeneous_freq()?;
13000        if self.values.is_empty() {
13001            return Err(IndexError::InvalidArgument(
13002                "attempt to get argmax of an empty sequence".to_owned(),
13003            ));
13004        }
13005        let mut best = 0;
13006        for (i, period) in self.values.iter().enumerate().skip(1) {
13007            if period.ordinal > self.values[best].ordinal {
13008                best = i;
13009            }
13010        }
13011        Ok(best)
13012    }
13013
13014    /// Position of the minimum ordinal, matching
13015    /// `pd.PeriodIndex.argmin()`. Mixed-freq input rejects; empty
13016    /// raises pandas-style "attempt to get argmin of an empty
13017    /// sequence".
13018    pub fn argmin(&self) -> Result<usize, IndexError> {
13019        self.ensure_homogeneous_freq()?;
13020        if self.values.is_empty() {
13021            return Err(IndexError::InvalidArgument(
13022                "attempt to get argmin of an empty sequence".to_owned(),
13023            ));
13024        }
13025        let mut best = 0;
13026        for (i, period) in self.values.iter().enumerate().skip(1) {
13027            if period.ordinal < self.values[best].ordinal {
13028                best = i;
13029            }
13030        }
13031        Ok(best)
13032    }
13033
13034    /// Positions that would sort the index by ordinal ascending,
13035    /// matching `pd.PeriodIndex.argsort()`. Mixed-freq input rejects.
13036    pub fn argsort(&self) -> Result<Vec<usize>, IndexError> {
13037        self.ensure_homogeneous_freq()?;
13038        let mut positions: Vec<usize> = (0..self.values.len()).collect();
13039        positions.sort_by_key(|&i| self.values[i].ordinal);
13040        Ok(positions)
13041    }
13042
13043    /// Period with the mean ordinal, matching `pd.PeriodIndex.mean()`.
13044    /// Mixed-frequency input rejects.
13045    pub fn mean(&self) -> Result<Option<Period>, IndexError> {
13046        let freq = match self.ensure_homogeneous_freq()? {
13047            Some(f) => f,
13048            None => return Ok(None),
13049        };
13050        let total: i128 = self.values.iter().map(|p| i128::from(p.ordinal)).sum();
13051        let count = self.values.len() as i128;
13052        let avg = i64::try_from(total / count)
13053            .map_err(|_| IndexError::InvalidArgument("mean: ordinal overflow".to_owned()))?;
13054        Ok(Some(Period::new(avg, freq)))
13055    }
13056
13057    /// Period with the median ordinal.
13058    ///
13059    /// ⚠️ `pd.PeriodIndex.median()` does NOT exist (measured 2.2.3:
13060    /// `AttributeError`). FP superset, not parity.
13061    /// For an even-length subset, returns the period at floor(median) of
13062    /// the two middle ordinals.
13063    pub fn median(&self) -> Result<Option<Period>, IndexError> {
13064        let freq = match self.ensure_homogeneous_freq()? {
13065            Some(f) => f,
13066            None => return Ok(None),
13067        };
13068        let mut ordinals: Vec<i64> = self.values.iter().map(|p| p.ordinal).collect();
13069        ordinals.sort_unstable();
13070        let mid = ordinals.len() / 2;
13071        let median = if ordinals.len() % 2 == 1 {
13072            ordinals[mid]
13073        } else {
13074            let total = i128::from(ordinals[mid - 1]) + i128::from(ordinals[mid]);
13075            i64::try_from(total / 2)
13076                .map_err(|_| IndexError::InvalidArgument("median: ordinal overflow".to_owned()))?
13077        };
13078        Ok(Some(Period::new(median, freq)))
13079    }
13080
13081    /// Period with the smallest ordinal, matching `pd.PeriodIndex.min()`.
13082    /// Mixed-frequency input rejects because pandas requires same-freq
13083    /// comparisons; empty returns `Ok(None)` to mirror the pandas NaT result.
13084    pub fn min(&self) -> Result<Option<Period>, IndexError> {
13085        self.ensure_homogeneous_freq()?;
13086        Ok(self
13087            .values
13088            .iter()
13089            .copied()
13090            .min_by_key(|period| period.ordinal))
13091    }
13092
13093    /// Period with the largest ordinal, matching `pd.PeriodIndex.max()`.
13094    pub fn max(&self) -> Result<Option<Period>, IndexError> {
13095        self.ensure_homogeneous_freq()?;
13096        Ok(self
13097            .values
13098            .iter()
13099            .copied()
13100            .max_by_key(|period| period.ordinal))
13101    }
13102
13103    /// Binary-search insertion position, matching
13104    /// `pd.PeriodIndex.searchsorted(value, side)`. Mixed-frequency lookups
13105    /// reject because pandas requires same-freq comparisons. side must be
13106    /// `"left"` or `"right"`.
13107    pub fn searchsorted(&self, value: Period, side: &str) -> Result<usize, IndexError> {
13108        if side != "left" && side != "right" {
13109            return Err(IndexError::InvalidArgument(format!(
13110                "searchsorted: side must be 'left' or 'right', got {side:?}"
13111            )));
13112        }
13113        if let Some(first) = self.values.first()
13114            && first.freq != value.freq
13115        {
13116            return Err(IndexError::InvalidArgument(format!(
13117                "searchsorted: needle frequency {:?} does not match index frequency {:?}",
13118                value.freq, first.freq
13119            )));
13120        }
13121        let mut lo = 0usize;
13122        let mut hi = self.values.len();
13123        while lo < hi {
13124            let mid = lo + (hi - lo) / 2;
13125            let cmp = self.values[mid].ordinal.cmp(&value.ordinal);
13126            use std::cmp::Ordering;
13127            let go_right = matches!(
13128                (cmp, side),
13129                (Ordering::Less, _) | (Ordering::Equal, "right")
13130            );
13131            if go_right {
13132                lo = mid + 1;
13133            } else {
13134                hi = mid;
13135            }
13136        }
13137        Ok(lo)
13138    }
13139
13140    /// Half-open positional range for a period slice, matching
13141    /// `pd.PeriodIndex.slice_indexer(start, end)`.
13142    pub fn slice_indexer(
13143        &self,
13144        start: Period,
13145        end: Period,
13146    ) -> Result<std::ops::Range<usize>, IndexError> {
13147        let (left, right) = self.slice_locs(start, end)?;
13148        Ok(left..right)
13149    }
13150
13151    /// Find positions of `[start, end]` for a period slice, matching
13152    /// `pd.PeriodIndex.slice_locs(start, end)`. Requires the index to
13153    /// be sorted ascending and the start/end periods to share its
13154    /// frequency.
13155    pub fn slice_locs(&self, start: Period, end: Period) -> Result<(usize, usize), IndexError> {
13156        if !self.is_monotonic_increasing() {
13157            return Err(IndexError::InvalidArgument(
13158                "slice_locs requires a monotonic increasing PeriodIndex".to_owned(),
13159            ));
13160        }
13161        let left = self.searchsorted(start, "left")?;
13162        let right = self.searchsorted(end, "right")?;
13163        Ok((left, right))
13164    }
13165
13166    /// First position of `period`, matching
13167    /// `pd.PeriodIndex.get_loc(period)`.
13168    pub fn get_loc(&self, period: Period) -> Result<usize, IndexError> {
13169        self.values
13170            .iter()
13171            .position(|p| *p == period)
13172            .ok_or_else(|| {
13173                IndexError::InvalidArgument(format!("get_loc: period {period} not in PeriodIndex"))
13174            })
13175    }
13176
13177    /// Set the index name, matching `pd.PeriodIndex.rename(name)`.
13178    #[must_use]
13179    pub fn rename(&self, name: &str) -> Self {
13180        self.set_name(name)
13181    }
13182
13183    /// Reindex against `target`, matching
13184    /// `pd.PeriodIndex.reindex(target)`.
13185    #[must_use]
13186    pub fn reindex(&self, target: &Self) -> (Self, Vec<isize>) {
13187        let indexer = self.get_indexer(target.values());
13188        (target.clone(), indexer)
13189    }
13190
13191    /// Locate every position matching each target, matching
13192    /// `pd.PeriodIndex.get_indexer_non_unique(targets)`.
13193    #[must_use]
13194    pub fn get_indexer_non_unique(&self, targets: &[Period]) -> (Vec<isize>, Vec<usize>) {
13195        let mut by_value = FxHashMap::<Period, Vec<usize>>::default();
13196        for (i, period) in self.values.iter().enumerate() {
13197            by_value.entry(*period).or_default().push(i);
13198        }
13199        let mut positions = Vec::<isize>::new();
13200        let mut missing = Vec::<usize>::new();
13201        for (idx, target) in targets.iter().enumerate() {
13202            if let Some(matches) = by_value.get(target) {
13203                positions.extend(
13204                    matches
13205                        .iter()
13206                        .map(|p| isize::try_from(*p).unwrap_or(isize::MAX)),
13207                );
13208            } else {
13209                positions.push(-1);
13210                missing.push(idx);
13211            }
13212        }
13213        (positions, missing)
13214    }
13215
13216    /// Alias for [`get_indexer`](Self::get_indexer), matching
13217    /// `pd.PeriodIndex.get_indexer_for(targets)`.
13218    #[must_use]
13219    pub fn get_indexer_for(&self, targets: &[Period]) -> Vec<isize> {
13220        self.get_indexer(targets)
13221    }
13222
13223    /// Locate each target period in the index, matching
13224    /// `pd.PeriodIndex.get_indexer(targets)`. Returns `Vec<isize>`
13225    /// where `-1` means "missing".
13226    #[must_use]
13227    pub fn get_indexer(&self, targets: &[Period]) -> Vec<isize> {
13228        let mut positions = FxHashMap::<Period, isize>::default();
13229        for (i, period) in self.values.iter().enumerate() {
13230            positions
13231                .entry(*period)
13232                .or_insert_with(|| isize::try_from(i).unwrap_or(isize::MAX));
13233        }
13234        targets
13235            .iter()
13236            .map(|p| positions.get(p).copied().unwrap_or(-1))
13237            .collect()
13238    }
13239
13240    /// Replace positions where `cond` is `false` with `other`, matching
13241    /// `pd.PeriodIndex.where(cond, other)`. The replacement period must
13242    /// share the index frequency.
13243    pub fn r#where(&self, cond: &[bool], other: Period) -> Result<Self, IndexError> {
13244        if cond.len() != self.values.len() {
13245            return Err(IndexError::LengthMismatch {
13246                expected: self.values.len(),
13247                actual: cond.len(),
13248                context: "where: cond length must match index length".to_owned(),
13249            });
13250        }
13251        if let Some(first) = self.values.first()
13252            && first.freq != other.freq
13253        {
13254            return Err(IndexError::InvalidArgument(format!(
13255                "where: replacement frequency {:?} does not match index frequency {:?}",
13256                other.freq, first.freq
13257            )));
13258        }
13259        let values: Vec<Period> = self
13260            .values
13261            .iter()
13262            .zip(cond.iter())
13263            .map(|(period, &keep)| if keep { *period } else { other })
13264            .collect();
13265        Ok(Self {
13266            values,
13267            name: self.name.clone(),
13268            built_freq: self.freq(),
13269        })
13270    }
13271
13272    /// Replace positions where `mask` is `true` with `value`, matching
13273    /// `pd.PeriodIndex.putmask(mask, value)`.
13274    pub fn putmask(&self, mask: &[bool], value: Period) -> Result<Self, IndexError> {
13275        if mask.len() != self.values.len() {
13276            return Err(IndexError::LengthMismatch {
13277                expected: self.values.len(),
13278                actual: mask.len(),
13279                context: "putmask: mask length must match index length".to_owned(),
13280            });
13281        }
13282        if let Some(first) = self.values.first()
13283            && first.freq != value.freq
13284        {
13285            return Err(IndexError::InvalidArgument(format!(
13286                "putmask: replacement frequency {:?} does not match index frequency {:?}",
13287                value.freq, first.freq
13288            )));
13289        }
13290        let values: Vec<Period> = self
13291            .values
13292            .iter()
13293            .zip(mask.iter())
13294            .map(|(period, &replace)| if replace { value } else { *period })
13295            .collect();
13296        Ok(Self {
13297            values,
13298            name: self.name.clone(),
13299            built_freq: self.freq(),
13300        })
13301    }
13302
13303    /// Insert `period` at position `loc`, matching
13304    /// `pd.PeriodIndex.insert(loc, period)`.
13305    pub fn insert(&self, loc: usize, period: Period) -> Result<Self, IndexError> {
13306        if loc > self.values.len() {
13307            return Err(IndexError::OutOfBounds {
13308                position: loc,
13309                length: self.values.len(),
13310            });
13311        }
13312        let mut periods = self.values.clone();
13313        periods.insert(loc, period);
13314        Ok(Self {
13315            values: periods,
13316            name: self.name.clone(),
13317            built_freq: self.freq(),
13318        })
13319    }
13320
13321    /// Shift each period by `n` units of its own frequency, matching
13322    /// `pd.PeriodIndex.shift(periods)`. Mixed-frequency input rejects
13323    /// via the existing ensure_homogeneous_freq guard.
13324    pub fn shift(&self, n: i64) -> Result<Self, IndexError> {
13325        self.ensure_homogeneous_freq()?;
13326        let values: Vec<Period> = self.values.iter().map(|p| p.shift(n)).collect();
13327        Ok(Self {
13328            values,
13329            name: self.name.clone(),
13330            built_freq: self.freq(),
13331        })
13332    }
13333
13334    /// Period labels are already discrete; pandas PeriodIndex.round returns a clone.
13335    #[must_use]
13336    pub fn round(&self, _freq: &str) -> Self {
13337        self.clone()
13338    }
13339
13340    /// Whether period ordinals form a contiguous run, matching
13341    /// `pd.PeriodIndex.is_full`. Empty and single-element indexes are
13342    /// trivially full. Mixed-frequency input returns `false` because the
13343    /// concept is undefined.
13344    #[must_use]
13345    pub fn is_full(&self) -> bool {
13346        if self.values.len() <= 1 {
13347            return true;
13348        }
13349        // Mixed-freq: not full.
13350        let first_freq = self.values[0].freq;
13351        if self.values.iter().any(|p| p.freq != first_freq) {
13352            return false;
13353        }
13354        let mut sorted: Vec<i64> = self.values.iter().map(|p| p.ordinal).collect();
13355        sorted.sort_unstable();
13356        sorted.windows(2).all(|w| w[1] - w[0] == 1)
13357    }
13358
13359    /// Stringify each period via Display, matching `pd.PeriodIndex.format()`.
13360    #[must_use]
13361    pub fn format(&self) -> Vec<String> {
13362        self.values.iter().map(Period::to_string).collect()
13363    }
13364
13365    /// Frequency alias, matching `pd.PeriodIndex.freqstr`. Returns `None`
13366    /// for an empty index; otherwise the Display form of the freq.
13367    #[must_use]
13368    pub fn freqstr(&self) -> Option<String> {
13369        self.freq().map(|f| f.to_string())
13370    }
13371
13372    /// Inferred frequency.
13373    ///
13374    /// ⚠️ `pd.PeriodIndex.inferred_freq` does NOT exist (measured 2.2.3:
13375    /// `AttributeError`), so the behaviour once described here as pandas' was
13376    /// never observed from pandas. `DatetimeIndex`/`TimedeltaIndex` DO have
13377    /// `inferred_freq`; on a PeriodIndex the freq is carried by `.freq`, which
13378    /// is mandatory, so there is nothing to infer. FP returns the freq when all
13379    /// periods share it, otherwise `None`. Mixed
13380    /// frequency is detected via `ensure_homogeneous_freq` (the same guard
13381    /// used by min/max).
13382    #[must_use]
13383    pub fn inferred_freq(&self) -> Option<String> {
13384        match self.ensure_homogeneous_freq() {
13385            Ok(Some(freq)) => Some(freq.to_string()),
13386            Ok(None) | Err(_) => None,
13387        }
13388    }
13389
13390    /// Convert to a flat [`Index`] of period strings, matching
13391    /// `pd.PeriodIndex.to_flat_index()`.
13392    #[must_use]
13393    pub fn to_flat_index(&self) -> Index {
13394        self.to_index()
13395    }
13396
13397    /// String accessor for rendered period labels.
13398    #[must_use]
13399    pub fn r#str(&self) -> IndexStringAccessor<'_> {
13400        IndexStringAccessor::owned(self.to_flat_index())
13401    }
13402
13403    /// One-column row materialization, matching `pd.PeriodIndex.to_frame(index=False)`.
13404    #[must_use]
13405    pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
13406        self.to_flat_index().to_frame()
13407    }
13408
13409    /// Series-shaped materialization using period labels as both index and values.
13410    #[must_use]
13411    pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
13412        self.to_flat_index().to_series()
13413    }
13414
13415    /// Whether any period label coerces to true: the flat index's answer, a
13416    /// NaT being missing there (pandas raises TypeError for either; 45fzr).
13417    #[must_use]
13418    pub fn any(&self) -> bool {
13419        self.to_flat_index().any()
13420    }
13421
13422    /// Whether all period labels coerce to true.
13423    #[must_use]
13424    pub fn all(&self) -> bool {
13425        self.to_flat_index().all()
13426    }
13427
13428    /// Get labels for a level. PeriodIndex is flat and only accepts level 0.
13429    pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
13430        self.to_flat_index().get_level_values(level)
13431    }
13432
13433    /// Drop a level. PeriodIndex is flat, so removing its only level is invalid.
13434    pub fn droplevel(&self, level: usize) -> Result<Index, IndexError> {
13435        self.to_flat_index().droplevel(level)
13436    }
13437
13438    /// Group equal period labels into position buckets.
13439    #[must_use]
13440    pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
13441        self.to_flat_index().groupby()
13442    }
13443
13444    /// Apply a function to each period label, returning a flat Index.
13445    #[must_use]
13446    pub fn map<F>(&self, func: F) -> Index
13447    where
13448        F: Fn(&IndexLabel) -> IndexLabel,
13449    {
13450        self.to_flat_index().map(func)
13451    }
13452
13453    /// Cast period labels to a pandas dtype string, returning a flat Index.
13454    pub fn astype(&self, dtype: &str) -> Result<Index, IndexError> {
13455        match dtype {
13456            "int" | "int64" => Ok(Index::from_i64(
13457                self.values.iter().map(|period| period.ordinal).collect(),
13458            )
13459            .set_names(self.name())),
13460            "datetime64[ns]" => Ok(Index::from_datetime64(
13461                self.values
13462                    .iter()
13463                    .copied()
13464                    .map(period_start_nanos)
13465                    .collect::<Result<Vec<_>, _>>()?,
13466            )
13467            .set_names(self.name())),
13468            _ => self.to_flat_index().astype(dtype),
13469        }
13470    }
13471
13472    /// Nearest preceding-or-equal period label lookup.
13473    #[must_use]
13474    pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
13475        self.to_flat_index().asof(key)
13476    }
13477
13478    /// Locate nearest preceding-or-equal period positions for each target label.
13479    #[must_use]
13480    pub fn asof_locs(&self, where_index: &Index, mask: Option<&[bool]>) -> Vec<Option<usize>> {
13481        self.to_flat_index().asof_locs(where_index, mask)
13482    }
13483
13484    /// Drop period labels, returning a flat Index.
13485    #[must_use]
13486    pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Index {
13487        self.to_flat_index().drop(labels_to_drop)
13488    }
13489
13490    /// Join period labels with another flat Index.
13491    pub fn join(&self, other: &Index, how: &str) -> Result<Index, IndexError> {
13492        self.to_flat_index().join(other, how)
13493    }
13494
13495    /// Sort period labels and return the positional sorter.
13496    #[must_use]
13497    pub fn sortlevel(&self) -> (Index, Vec<usize>) {
13498        self.to_flat_index().sortlevel()
13499    }
13500
13501    /// Returns a clone, matching `pd.PeriodIndex.view()`.
13502    #[must_use]
13503    pub fn view(&self) -> Self {
13504        self.clone()
13505    }
13506
13507    /// Identity transpose for a 1D index, matching
13508    /// `pd.PeriodIndex.transpose()`.
13509    #[must_use]
13510    pub fn transpose(&self) -> Self {
13511        self.clone()
13512    }
13513
13514    /// Alias for `transpose`, matching `pd.PeriodIndex.T`.
13515    #[allow(non_snake_case)]
13516    #[must_use]
13517    pub fn T(&self) -> Self {
13518        self.transpose()
13519    }
13520
13521    /// Flatten periods to a `Vec<Period>`, matching
13522    /// `pd.PeriodIndex.ravel()`.
13523    #[must_use]
13524    pub fn ravel(&self) -> Vec<Period> {
13525        self.values.clone()
13526    }
13527
13528    /// Number of levels, matching `pd.PeriodIndex.nlevels`. Always `1`.
13529    #[must_use]
13530    pub fn nlevels(&self) -> usize {
13531        1
13532    }
13533
13534    /// Identity dtype-reinference for typed indexes, matching
13535    /// `pd.PeriodIndex.infer_objects()`.
13536    #[must_use]
13537    pub fn infer_objects(&self) -> Self {
13538        self.clone()
13539    }
13540
13541    /// Per-position membership mask, matching `pd.PeriodIndex.isin(values)`.
13542    #[must_use]
13543    pub fn isin(&self, values: &[Period]) -> Vec<bool> {
13544        let needle: FxHashSet<Period> = values.iter().copied().collect();
13545        self.values.iter().map(|p| needle.contains(p)).collect()
13546    }
13547
13548    /// Concatenate with another PeriodIndex, matching
13549    /// `pd.PeriodIndex.append(other)`. Preserves the index name when both
13550    /// operands share it; otherwise the name is dropped.
13551    #[must_use]
13552    pub fn append(&self, other: &Self) -> Self {
13553        let mut periods = self.values.clone();
13554        periods.extend_from_slice(&other.values);
13555        let name = if self.name == other.name {
13556            self.name.clone()
13557        } else {
13558            None
13559        };
13560        Self {
13561            values: periods,
13562            name,
13563            built_freq: self.freq(),
13564        }
13565    }
13566
13567    /// Remove the period at the given position, matching
13568    /// `pd.PeriodIndex.delete(loc)`.
13569    pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
13570        if loc >= self.values.len() {
13571            return Err(IndexError::OutOfBounds {
13572                position: loc,
13573                length: self.values.len(),
13574            });
13575        }
13576        let mut periods = self.values.clone();
13577        periods.remove(loc);
13578        Ok(Self {
13579            values: periods,
13580            name: self.name.clone(),
13581            built_freq: self.freq(),
13582        })
13583    }
13584
13585    /// Factorize, matching `pd.PeriodIndex.factorize()`. Returns
13586    /// `(codes, uniques)` with isize codes — Period currently has no
13587    /// missing-value sentinel so all codes are non-negative.
13588    #[must_use]
13589    pub fn factorize(&self) -> (Vec<isize>, Self) {
13590        let mut positions = FxHashMap::<&Period, isize>::default();
13591        let mut uniques = Vec::<Period>::new();
13592        let mut codes = Vec::with_capacity(self.values.len());
13593        for period in &self.values {
13594            if let Some(code) = positions.get(period) {
13595                codes.push(*code);
13596            } else {
13597                let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
13598                positions.insert(period, code);
13599                uniques.push(*period);
13600                codes.push(code);
13601            }
13602        }
13603        (
13604            codes,
13605            Self {
13606                values: uniques,
13607                name: self.name.clone(),
13608                built_freq: self.freq(),
13609            },
13610        )
13611    }
13612}
13613
13614/// Public pandas-style range index wrapper.
13615#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13616pub struct RangeIndex {
13617    start: i64,
13618    stop: i64,
13619    step: i64,
13620    name: Option<LabelName>,
13621}
13622
13623/// Borrowed, lazily evaluated Int64 values of a [`RangeIndex`].
13624///
13625/// A `RangeIndex` is an affine sequence, so typed consumers can read its values
13626/// without first allocating an owned buffer.  Use [`Self::to_vec`] only when an
13627/// owned list is actually required by the receiving API.
13628#[derive(Clone, Copy, Debug)]
13629pub struct RangeIndexValues<'a> {
13630    index: &'a RangeIndex,
13631}
13632
13633impl RangeIndexValues<'_> {
13634    #[must_use]
13635    pub fn len(&self) -> usize {
13636        self.index.len()
13637    }
13638
13639    #[must_use]
13640    pub fn is_empty(&self) -> bool {
13641        self.index.is_empty()
13642    }
13643
13644    #[must_use]
13645    pub fn get(&self, position: usize) -> Option<i64> {
13646        (position < self.len()).then(|| self.index.value_at(position))
13647    }
13648
13649    #[must_use]
13650    pub fn iter(&self) -> RangeValuesIter {
13651        let len = self.len();
13652        // br-frankenpandas-3gsa7 made this view zero-boxing; it is still
13653        // 0.112x against pandas at 100k because `RangeIndex::value_at` pays
13654        // i128 arithmetic PER ELEMENT — an i128 multiply (no SIMD form on
13655        // x86-64), an i128 add, and a checked narrow back to i64. The proof
13656        // that none of that is needed already existed one function below as
13657        // `i64_position_arithmetic_is_safe`, which establishes ONCE that
13658        // `start + step * (len - 1)` fits in i64. Values are monotone in
13659        // `position` for either sign of `step`, so every intermediate is
13660        // bracketed by `start` and that endpoint and cannot overflow.
13661        // Hoisting the check turns the body into pure i64 affine arithmetic.
13662        RangeValuesIter {
13663            start: self.index.start,
13664            step: self.index.step,
13665            head: 0,
13666            tail: len,
13667            i64_safe: self.index.i64_position_arithmetic_is_safe(len).is_some(),
13668        }
13669    }
13670
13671    #[must_use]
13672    pub fn to_vec(&self) -> Vec<i64> {
13673        self.iter().collect()
13674    }
13675}
13676
13677/// Affine iterator over a [`RangeIndex`]'s values.
13678///
13679/// `i64_safe` is decided once at construction. It is NOT a correctness switch:
13680/// both arms yield identical values, and the i128 arm remains a complete
13681/// implementation for ranges whose endpoint genuinely does not fit in i64.
13682/// Its only purpose is to let `fold`/`rfold` run a branch-free i64 loop that
13683/// LLVM can strength-reduce to repeated addition and vectorize.
13684#[derive(Clone, Copy, Debug)]
13685pub struct RangeValuesIter {
13686    start: i64,
13687    step: i64,
13688    head: usize,
13689    tail: usize,
13690    i64_safe: bool,
13691}
13692
13693impl RangeValuesIter {
13694    #[inline]
13695    fn value_at(&self, position: usize) -> i64 {
13696        if self.i64_safe {
13697            self.start
13698                .wrapping_add(self.step.wrapping_mul(position as i64))
13699        } else {
13700            let value = i128::from(self.start) + (position as i128) * i128::from(self.step);
13701            i64::try_from(value).expect("validated RangeIndex value bounds")
13702        }
13703    }
13704}
13705
13706impl Iterator for RangeValuesIter {
13707    type Item = i64;
13708
13709    #[inline]
13710    fn next(&mut self) -> Option<i64> {
13711        if self.head >= self.tail {
13712            return None;
13713        }
13714        let value = self.value_at(self.head);
13715        self.head += 1;
13716        Some(value)
13717    }
13718
13719    #[inline]
13720    fn size_hint(&self) -> (usize, Option<usize>) {
13721        let remaining = self.tail - self.head;
13722        (remaining, Some(remaining))
13723    }
13724
13725    /// Overridden so the `i64_safe` branch is tested ONCE per fold rather than
13726    /// once per element. This is the whole lever: the default `fold` routes
13727    /// through `next()`, which keeps the test inside the loop and blocks
13728    /// vectorisation.
13729    #[inline]
13730    fn fold<B, F>(self, init: B, mut f: F) -> B
13731    where
13732        F: FnMut(B, i64) -> B,
13733    {
13734        let mut acc = init;
13735        if self.i64_safe {
13736            let mut value = self
13737                .start
13738                .wrapping_add(self.step.wrapping_mul(self.head as i64));
13739            for _ in self.head..self.tail {
13740                acc = f(acc, value);
13741                value = value.wrapping_add(self.step);
13742            }
13743        } else {
13744            for position in self.head..self.tail {
13745                acc = f(acc, self.value_at(position));
13746            }
13747        }
13748        acc
13749    }
13750}
13751
13752impl DoubleEndedIterator for RangeValuesIter {
13753    #[inline]
13754    fn next_back(&mut self) -> Option<i64> {
13755        if self.head >= self.tail {
13756            return None;
13757        }
13758        self.tail -= 1;
13759        Some(self.value_at(self.tail))
13760    }
13761
13762    #[inline]
13763    fn rfold<B, F>(self, init: B, mut f: F) -> B
13764    where
13765        F: FnMut(B, i64) -> B,
13766    {
13767        let mut acc = init;
13768        if self.i64_safe && self.tail > self.head {
13769            let mut value = self
13770                .start
13771                .wrapping_add(self.step.wrapping_mul((self.tail - 1) as i64));
13772            for _ in self.head..self.tail {
13773                acc = f(acc, value);
13774                value = value.wrapping_sub(self.step);
13775            }
13776        } else {
13777            for position in (self.head..self.tail).rev() {
13778                acc = f(acc, self.value_at(position));
13779            }
13780        }
13781        acc
13782    }
13783}
13784
13785impl ExactSizeIterator for RangeValuesIter {
13786    #[inline]
13787    fn len(&self) -> usize {
13788        self.tail - self.head
13789    }
13790}
13791
13792impl std::iter::FusedIterator for RangeValuesIter {}
13793
13794impl RangeIndex {
13795    pub fn new(start: i64, stop: i64, step: i64) -> Result<Self, IndexError> {
13796        if step == 0 {
13797            return Err(IndexError::InvalidArgument(
13798                "RangeIndex step must be non-zero".to_owned(),
13799            ));
13800        }
13801        Ok(Self {
13802            start,
13803            stop,
13804            step,
13805            name: None,
13806        })
13807    }
13808
13809    pub fn from_len(len: usize) -> Result<Self, IndexError> {
13810        let stop = i64::try_from(len).map_err(|_| {
13811            IndexError::InvalidArgument("RangeIndex length exceeds i64 range".to_owned())
13812        })?;
13813        Self::new(0, stop, 1)
13814    }
13815
13816    #[must_use]
13817    pub const fn start(&self) -> i64 {
13818        self.start
13819    }
13820
13821    #[must_use]
13822    pub const fn stop(&self) -> i64 {
13823        self.stop
13824    }
13825
13826    #[must_use]
13827    pub const fn step(&self) -> i64 {
13828        self.step
13829    }
13830
13831    #[must_use]
13832    pub fn len(&self) -> usize {
13833        let start = i128::from(self.start);
13834        let stop = i128::from(self.stop);
13835        let step = i128::from(self.step);
13836        let len = if step > 0 {
13837            if start >= stop {
13838                0
13839            } else {
13840                (stop - start + step - 1) / step
13841            }
13842        } else if start <= stop {
13843            0
13844        } else {
13845            let positive_step = -step;
13846            (start - stop + positive_step - 1) / positive_step
13847        };
13848        usize::try_from(len).unwrap_or(usize::MAX)
13849    }
13850
13851    #[must_use]
13852    pub fn is_empty(&self) -> bool {
13853        self.len() == 0
13854    }
13855
13856    #[must_use]
13857    pub fn name(&self) -> Option<&LabelName> {
13858        self.name.as_ref()
13859    }
13860
13861    #[must_use]
13862    pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
13863        let mut out = self.clone();
13864        out.name = Some(name.into());
13865        out
13866    }
13867
13868    #[must_use]
13869    pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
13870        let mut out = self.clone();
13871        out.name = name.map(Into::into);
13872        out
13873    }
13874
13875    #[must_use]
13876    pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
13877        self.set_names(name)
13878    }
13879
13880    #[must_use]
13881    pub fn names(&self) -> Vec<Option<String>> {
13882        vec![self.name.clone().map(String::from)]
13883    }
13884
13885    #[must_use]
13886    pub fn copy(&self) -> Self {
13887        self.clone()
13888    }
13889
13890    #[must_use]
13891    pub fn shape(&self) -> (usize,) {
13892        (self.len(),)
13893    }
13894
13895    #[must_use]
13896    pub fn size(&self) -> usize {
13897        self.len()
13898    }
13899
13900    #[must_use]
13901    pub fn empty(&self) -> bool {
13902        self.is_empty()
13903    }
13904
13905    #[must_use]
13906    pub fn dtype(&self) -> &'static str {
13907        "int64"
13908    }
13909
13910    #[must_use]
13911    pub fn dtypes(&self) -> Vec<&'static str> {
13912        vec![self.dtype()]
13913    }
13914
13915    #[must_use]
13916    pub fn memory_usage(&self, _deep: bool) -> usize {
13917        self.len().saturating_mul(std::mem::size_of::<i64>())
13918    }
13919
13920    #[must_use]
13921    pub fn nbytes(&self) -> usize {
13922        self.memory_usage(false)
13923    }
13924
13925    #[must_use]
13926    pub fn is_unique(&self) -> bool {
13927        true
13928    }
13929
13930    #[must_use]
13931    pub fn has_duplicates(&self) -> bool {
13932        false
13933    }
13934
13935    #[must_use]
13936    pub fn is_monotonic_increasing(&self) -> bool {
13937        self.len() <= 1 || self.step > 0
13938    }
13939
13940    #[must_use]
13941    pub fn is_monotonic(&self) -> bool {
13942        self.is_monotonic_increasing()
13943    }
13944
13945    #[must_use]
13946    pub fn is_monotonic_decreasing(&self) -> bool {
13947        self.len() <= 1 || self.step < 0
13948    }
13949
13950    #[must_use]
13951    pub fn nunique(&self) -> usize {
13952        self.len()
13953    }
13954
13955    #[must_use]
13956    pub fn ndim(&self) -> usize {
13957        1
13958    }
13959
13960    pub fn item(&self) -> Result<i64, IndexError> {
13961        if self.len() == 1 {
13962            Ok(self.start)
13963        } else {
13964            Err(IndexError::InvalidArgument(format!(
13965                "item requires exactly one label, got {}",
13966                self.len()
13967            )))
13968        }
13969    }
13970
13971    #[must_use]
13972    pub fn is_(&self, other: &Self) -> bool {
13973        std::ptr::eq(self, other)
13974    }
13975
13976    #[must_use]
13977    pub fn equals(&self, other: &Self) -> bool {
13978        let len = self.len();
13979        if len != other.len() {
13980            return false;
13981        }
13982        match len {
13983            0 => true,
13984            1 => self.start == other.start,
13985            _ => self.start == other.start && self.step == other.step,
13986        }
13987    }
13988
13989    #[must_use]
13990    pub fn identical(&self, other: &Self) -> bool {
13991        self.equals(other) && self.name == other.name
13992    }
13993
13994    #[must_use]
13995    pub fn holds_integer(&self) -> bool {
13996        true
13997    }
13998
13999    #[must_use]
14000    pub fn inferred_type(&self) -> &'static str {
14001        if self.is_empty() { "empty" } else { "integer" }
14002    }
14003
14004    #[must_use]
14005    pub fn is_boolean(&self) -> bool {
14006        false
14007    }
14008
14009    #[must_use]
14010    pub fn is_categorical(&self) -> bool {
14011        false
14012    }
14013
14014    #[must_use]
14015    pub fn is_floating(&self) -> bool {
14016        false
14017    }
14018
14019    #[must_use]
14020    pub fn is_integer(&self) -> bool {
14021        true
14022    }
14023
14024    #[must_use]
14025    pub fn is_interval(&self) -> bool {
14026        false
14027    }
14028
14029    #[must_use]
14030    pub fn is_numeric(&self) -> bool {
14031        true
14032    }
14033
14034    #[must_use]
14035    pub fn is_object(&self) -> bool {
14036        false
14037    }
14038
14039    #[must_use]
14040    pub fn to_index(&self) -> Index {
14041        Index::from_range(self.start, self.stop, self.step).set_names(self.name.as_deref())
14042    }
14043
14044    #[must_use]
14045    pub fn values(&self) -> RangeIndexValues<'_> {
14046        RangeIndexValues { index: self }
14047    }
14048
14049    fn value_at(&self, position: usize) -> i64 {
14050        let value = i128::from(self.start) + (position as i128) * i128::from(self.step);
14051        i64::try_from(value).expect("validated RangeIndex value bounds")
14052    }
14053
14054    fn i64_position_arithmetic_is_safe(&self, len: usize) -> Option<()> {
14055        if len == 0 {
14056            return Some(());
14057        }
14058        let last_position = i64::try_from(len.checked_sub(1)?).ok()?;
14059        let span = self.step.checked_mul(last_position)?;
14060        self.start.checked_add(span)?;
14061        Some(())
14062    }
14063
14064    fn fast_i64_values_at_positions(&self, positions: &[usize], len: usize) -> Option<Vec<i64>> {
14065        self.i64_position_arithmetic_is_safe(len)?;
14066        let mut labels = Vec::with_capacity(positions.len());
14067        for &position in positions {
14068            if position >= len {
14069                return None;
14070            }
14071            let position = i64::try_from(position).expect("prevalidated RangeIndex position");
14072            labels.push(self.start + self.step * position);
14073        }
14074        Some(labels)
14075    }
14076
14077    fn fast_i64_repeat_values(&self, len: usize, repeats: usize) -> Option<Vec<i64>> {
14078        self.i64_position_arithmetic_is_safe(len)?;
14079        let mut labels = Vec::with_capacity(repeat_output_capacity(len, repeats));
14080        let mut value = self.start;
14081        for position in 0..len {
14082            match repeats {
14083                0 => {}
14084                1 => labels.push(value),
14085                2 => {
14086                    labels.push(value);
14087                    labels.push(value);
14088                }
14089                _ => {
14090                    for _ in 0..repeats {
14091                        labels.push(value);
14092                    }
14093                }
14094            }
14095            if position + 1 < len {
14096                value += self.step;
14097            }
14098        }
14099        Some(labels)
14100    }
14101
14102    fn push_i64_position_range(
14103        &self,
14104        len: usize,
14105        start: usize,
14106        end: usize,
14107        labels: &mut Vec<i64>,
14108    ) -> Option<()> {
14109        if start > end || end > len {
14110            return None;
14111        }
14112        self.i64_position_arithmetic_is_safe(len)?;
14113        if start == end {
14114            return Some(());
14115        }
14116        let start_position = i64::try_from(start).ok()?;
14117        let span = self.step.checked_mul(start_position)?;
14118        let mut value = self.start.checked_add(span)?;
14119        for position in start..end {
14120            labels.push(value);
14121            if position + 1 < end {
14122                value += self.step;
14123            }
14124        }
14125        Some(())
14126    }
14127
14128    fn i64_position_affine_run(
14129        &self,
14130        len: usize,
14131        start: usize,
14132        end: usize,
14133    ) -> Option<Int64AffineLabels> {
14134        if start > end || end > len {
14135            return None;
14136        }
14137        self.i64_position_arithmetic_is_safe(len)?;
14138        let run_len = end - start;
14139        let start_value = if run_len == 0 {
14140            self.start
14141        } else {
14142            let start_position = i64::try_from(start).ok()?;
14143            let span = self.step.checked_mul(start_position)?;
14144            self.start.checked_add(span)?
14145        };
14146        Int64AffineLabels::new(start_value, self.step, run_len)
14147    }
14148
14149    fn fast_i64_insert_values(&self, len: usize, loc: usize, value: i64) -> Option<Vec<i64>> {
14150        let mut labels = Vec::with_capacity(insert_output_capacity(len));
14151        self.push_i64_position_range(len, 0, loc, &mut labels)?;
14152        labels.push(value);
14153        self.push_i64_position_range(len, loc, len, &mut labels)?;
14154        Some(labels)
14155    }
14156
14157    fn fast_i64_append_index(&self, other: &Self, len: usize, other_len: usize) -> Option<Index> {
14158        let first = self.i64_position_affine_run(len, 0, len)?;
14159        let second = other.i64_position_affine_run(other_len, 0, other_len)?;
14160        Index::new_int64_two_affine_runs(first, second)
14161    }
14162
14163    fn fast_i64_append_values(
14164        &self,
14165        other: &Self,
14166        len: usize,
14167        other_len: usize,
14168    ) -> Option<Vec<i64>> {
14169        let mut labels = Vec::with_capacity(combined_output_capacity(len, other_len));
14170        self.push_i64_position_range(len, 0, len, &mut labels)?;
14171        other.push_i64_position_range(other_len, 0, other_len, &mut labels)?;
14172        Some(labels)
14173    }
14174
14175    fn fast_i64_delete_index(&self, len: usize, loc: usize) -> Option<Index> {
14176        let first = self.i64_position_affine_run(len, 0, loc)?;
14177        let second = self.i64_position_affine_run(len, loc + 1, len)?;
14178        Index::new_known_unique_int64_two_affine_runs(first, second)
14179    }
14180
14181    fn fast_i64_delete_values(&self, len: usize, loc: usize) -> Option<Vec<i64>> {
14182        let mut labels = Vec::with_capacity(len.saturating_sub(1));
14183        self.push_i64_position_range(len, 0, loc, &mut labels)?;
14184        self.push_i64_position_range(len, loc + 1, len, &mut labels)?;
14185        Some(labels)
14186    }
14187
14188    fn take_arithmetic_positions(&self, positions: &[usize], len: usize) -> Option<Index> {
14189        // Single O(len) pass: verify constant position stride AND in-bounds. The
14190        // result of an affine RangeIndex taken at an arithmetic position sequence
14191        // is again affine (`label_step = step * position_step`), so this returns a
14192        // lazy affine index in O(1) without the separate bounds-check loop + the
14193        // per-element `value_at` gather the materializing fall-back pays — the
14194        // dominant cost in the `range_index_take` hot loop. Any out-of-bounds or
14195        // non-arithmetic positions return `None`, falling through to the
14196        // materializing path which reports the precise out-of-bounds error.
14197        let mut index = match positions {
14198            [] => Index::new_known_unique_int64_affine_range(self.start, self.step, 0)?,
14199            &[position] => {
14200                if position >= len {
14201                    return None;
14202                }
14203                let first_label = self.value_at(position);
14204                Index::new_known_unique_int64_affine_range(first_label, self.step, 1)?
14205            }
14206            &[first, second, ..] => {
14207                if first >= len {
14208                    return None;
14209                }
14210                // `i64` (not `i128`) stride arithmetic: positions are valid indices
14211                // `< len <= isize::MAX`, so pairwise differences fit `i64`; the
14212                // `i64` windows scan autovectorizes where the `i128` form could not.
14213                let position_step = second as i64 - first as i64;
14214                if position_step == 0 {
14215                    return None;
14216                }
14217                if !positions
14218                    .windows(2)
14219                    .all(|w| w[1] as i64 - w[0] as i64 == position_step)
14220                {
14221                    return None;
14222                }
14223                let last = *positions.last().expect("non-empty by match arm");
14224                // Monotone sequence ⇒ all positions lie within `[min, max]`; a
14225                // single endpoint bounds check covers the whole range.
14226                if first.max(last) >= len {
14227                    return None;
14228                }
14229                let label_step = self.step.checked_mul(position_step)?;
14230                let first_label = self.value_at(first);
14231                Index::new_known_unique_int64_affine_range(
14232                    first_label,
14233                    label_step,
14234                    positions.len(),
14235                )?
14236            }
14237        };
14238
14239        if let Some(name) = self.name() {
14240            index = index.set_name(name);
14241        }
14242        Some(index)
14243    }
14244
14245    fn affine_span_index(
14246        &self,
14247        first_position: usize,
14248        len: usize,
14249        name: Option<&LabelName>,
14250    ) -> Option<Index> {
14251        let start = if len == 0 {
14252            self.start
14253        } else {
14254            self.value_at(first_position)
14255        };
14256        let mut index = Index::new_known_unique_int64_affine_range(start, self.step, len)?;
14257        if let Some(name) = name {
14258            index = index.set_name(name);
14259        }
14260        Some(index)
14261    }
14262
14263    fn matching_step_offset(&self, other: &Self) -> Option<i128> {
14264        if self.step == 0 || self.step != other.step {
14265            return None;
14266        }
14267        let delta = i128::from(other.start) - i128::from(self.start);
14268        let step = i128::from(self.step);
14269        (delta % step == 0).then_some(delta / step)
14270    }
14271
14272    fn same_lattice_overlap_positions(&self, other: &Self) -> Option<Option<(usize, usize)>> {
14273        let self_len = self.len();
14274        let other_len = other.len();
14275        if self_len == 0 || other_len == 0 {
14276            return Some(None);
14277        }
14278        let other_start = self.matching_step_offset(other)?;
14279        let other_end = other_start.checked_add(other_len as i128 - 1)?;
14280        let first = other_start.max(0);
14281        let last = other_end.min(self_len as i128 - 1);
14282        if first > last {
14283            return Some(None);
14284        }
14285        Some(Some((
14286            usize::try_from(first).ok()?,
14287            usize::try_from(last).ok()?,
14288        )))
14289    }
14290
14291    fn single_difference_span_positions(&self, other: &Self) -> Option<Option<(usize, usize)>> {
14292        let self_len = self.len();
14293        match self.same_lattice_overlap_positions(other)? {
14294            None => Some((self_len > 0).then_some((0, self_len))),
14295            Some((first, last)) => {
14296                if first == 0 && last + 1 == self_len {
14297                    Some(None)
14298                } else if first == 0 {
14299                    Some(Some((last + 1, self_len - last - 1)))
14300                } else if last + 1 == self_len {
14301                    Some(Some((0, first)))
14302                } else {
14303                    None
14304                }
14305            }
14306        }
14307    }
14308
14309    fn position_of_value(&self, value: i64) -> Option<usize> {
14310        self.position_of_value_with_len(value, self.len())
14311    }
14312
14313    fn position_of_value_with_len(&self, value: i64, len: usize) -> Option<usize> {
14314        self.position_of_value_with_len_and_bounds(value, len, self.position_bounds_for_len(len))
14315    }
14316
14317    fn position_of_value_with_len_and_bounds(
14318        &self,
14319        value: i64,
14320        len: usize,
14321        bounds: Option<(i64, i64)>,
14322    ) -> Option<usize> {
14323        if self.step == 0 {
14324            return None;
14325        }
14326        if len == 0 {
14327            return None;
14328        }
14329        if let Some((lower, upper)) = bounds {
14330            if value < lower || value > upper {
14331                return None;
14332            }
14333            if let Some(offset) = value.checked_sub(self.start)
14334                && let Some(0) = offset.checked_rem(self.step)
14335                && let Some(position) = offset.checked_div(self.step)
14336                && position >= 0
14337            {
14338                let position = position as usize;
14339                if position < len {
14340                    return Some(position);
14341                }
14342            }
14343            return None;
14344        }
14345        let offset = i128::from(value) - i128::from(self.start);
14346        let step = i128::from(self.step);
14347        if offset % step != 0 {
14348            return None;
14349        }
14350        let position = offset / step;
14351        (position >= 0 && position < len as i128).then_some(position as usize)
14352    }
14353
14354    fn position_bounds_for_len(&self, len: usize) -> Option<(i64, i64)> {
14355        self.first_last_for_len(len)
14356            .map(|(first, last)| (first.min(last), first.max(last)))
14357    }
14358
14359    fn first_last_for_len(&self, len: usize) -> Option<(i64, i64)> {
14360        if len == 0 {
14361            return None;
14362        }
14363        let last_offset = len - 1;
14364        let last = i128::from(self.start) + (last_offset as i128) * i128::from(self.step);
14365        let last = i64::try_from(last).ok()?;
14366        Some((self.start, last))
14367    }
14368
14369    fn range_target_indexer(&self, target: &Self, source_len: usize) -> Option<Vec<isize>> {
14370        let target_len = target.len();
14371        if target_len == 0 {
14372            return Some(Vec::new());
14373        }
14374        if source_len == 0 {
14375            return Some(vec![-1; target_len]);
14376        }
14377
14378        let source_step = i128::from(self.step);
14379        let target_step = i128::from(target.step);
14380        let first_offset = i128::from(target.start) - i128::from(self.start);
14381        if target_step % source_step != 0 {
14382            return None;
14383        }
14384        if first_offset % source_step != 0 {
14385            return Some(vec![-1; target_len]);
14386        }
14387
14388        let mut source_position = first_offset / source_step;
14389        let source_position_step = target_step / source_step;
14390        let source_len = source_len as i128;
14391        let mut indexer = Vec::with_capacity(target_len);
14392        for _ in 0..target_len {
14393            if (0..source_len).contains(&source_position) {
14394                indexer.push(source_position as isize);
14395            } else {
14396                indexer.push(-1);
14397            }
14398            source_position += source_position_step;
14399        }
14400        Some(indexer)
14401    }
14402
14403    fn contains_value(&self, value: i64) -> bool {
14404        self.position_of_value(value).is_some()
14405    }
14406
14407    /// Positional first differences for RangeIndex values.
14408    #[must_use]
14409    pub fn diff(&self, periods: i64) -> Vec<Option<i64>> {
14410        let len = self.len();
14411        if len == 0 {
14412            return Vec::new();
14413        }
14414        if periods == 0 {
14415            return vec![Some(0); len];
14416        }
14417        let Ok(offset) = usize::try_from(periods.unsigned_abs()) else {
14418            return vec![None; len];
14419        };
14420        if offset >= len {
14421            return vec![None; len];
14422        }
14423
14424        let diff = i128::from(self.step) * i128::from(periods);
14425        let diff = i64::try_from(diff).ok();
14426        let mut out = vec![None; len];
14427        if periods > 0 {
14428            out[offset..].fill(diff);
14429        } else {
14430            out[..len - offset].fill(diff);
14431        }
14432        out
14433    }
14434
14435    #[must_use]
14436    pub fn to_list(&self) -> Vec<i64> {
14437        self.values().to_vec()
14438    }
14439
14440    #[must_use]
14441    pub fn tolist(&self) -> Vec<i64> {
14442        self.values().to_vec()
14443    }
14444
14445    #[must_use]
14446    pub fn to_numpy(&self) -> Vec<i64> {
14447        self.values().to_vec()
14448    }
14449
14450    #[must_use]
14451    pub fn array(&self) -> Vec<i64> {
14452        self.values().to_vec()
14453    }
14454
14455    /// Position of the maximum value, matching `pd.RangeIndex.argmax()`.
14456    ///
14457    /// `step > 0` makes the last position the maximum; `step < 0` makes
14458    /// position 0 the maximum. Empty ranges raise the same
14459    /// `attempt to get argmax of an empty sequence` error pandas surfaces.
14460    pub fn argmax(&self) -> Result<usize, IndexError> {
14461        if self.is_empty() {
14462            return Err(IndexError::InvalidArgument(
14463                "attempt to get argmax of an empty sequence".to_owned(),
14464            ));
14465        }
14466        if self.step > 0 {
14467            Ok(self.len() - 1)
14468        } else {
14469            Ok(0)
14470        }
14471    }
14472
14473    /// Position of the minimum value, matching `pd.RangeIndex.argmin()`.
14474    pub fn argmin(&self) -> Result<usize, IndexError> {
14475        if self.is_empty() {
14476            return Err(IndexError::InvalidArgument(
14477                "attempt to get argmin of an empty sequence".to_owned(),
14478            ));
14479        }
14480        if self.step > 0 {
14481            Ok(0)
14482        } else {
14483            Ok(self.len() - 1)
14484        }
14485    }
14486
14487    /// Positions that would sort the index ascending, matching
14488    /// `pd.RangeIndex.argsort()`.
14489    #[must_use]
14490    pub fn argsort(&self) -> Vec<usize> {
14491        let len = self.len();
14492        if self.step >= 0 {
14493            (0..len).collect()
14494        } else {
14495            (0..len).rev().collect()
14496        }
14497    }
14498
14499    /// RangeIndex enforces uniqueness, so every position is reported as a
14500    /// non-duplicate, matching `pd.RangeIndex.duplicated(keep=...)`.
14501    #[must_use]
14502    pub fn duplicated(&self, _keep: DuplicateKeep) -> Vec<bool> {
14503        vec![false; self.len()]
14504    }
14505
14506    /// Drop duplicates, matching `pd.RangeIndex.drop_duplicates()`.
14507    /// Returns a clone because RangeIndex never has duplicates.
14508    #[must_use]
14509    pub fn drop_duplicates(&self) -> Self {
14510        self.clone()
14511    }
14512
14513    /// Per-position missingness mask, matching `pd.RangeIndex.isna()`.
14514    /// Always all-false because RangeIndex is int64-typed.
14515    #[must_use]
14516    pub fn isna(&self) -> Vec<bool> {
14517        vec![false; self.len()]
14518    }
14519
14520    /// Alias for [`isna`](Self::isna), matching `pd.RangeIndex.isnull()`.
14521    #[must_use]
14522    pub fn isnull(&self) -> Vec<bool> {
14523        self.isna()
14524    }
14525
14526    /// Per-position non-missing mask, matching `pd.RangeIndex.notna()`.
14527    #[must_use]
14528    pub fn notna(&self) -> Vec<bool> {
14529        vec![true; self.len()]
14530    }
14531
14532    /// Alias for [`notna`](Self::notna), matching `pd.RangeIndex.notnull()`.
14533    #[must_use]
14534    pub fn notnull(&self) -> Vec<bool> {
14535        self.notna()
14536    }
14537
14538    /// Whether any position is missing, matching `pd.RangeIndex.hasnans`.
14539    #[must_use]
14540    pub fn hasnans(&self) -> bool {
14541        false
14542    }
14543
14544    /// Drop missing positions, matching `pd.RangeIndex.dropna()`.
14545    /// Returns a clone because RangeIndex cannot hold missing values.
14546    #[must_use]
14547    pub fn dropna(&self) -> Self {
14548        self.clone()
14549    }
14550
14551    /// Fill missing positions, matching `pd.RangeIndex.fillna(value)`.
14552    /// Returns a clone — RangeIndex has no missing positions to fill.
14553    #[must_use]
14554    pub fn fillna(&self, _value: i64) -> Self {
14555        self.clone()
14556    }
14557
14558    /// Stringify each value, matching `pd.RangeIndex.format()`.
14559    #[must_use]
14560    pub fn format(&self) -> Vec<String> {
14561        (0..self.len())
14562            .map(|position| self.value_at(position).to_string())
14563            .collect()
14564    }
14565
14566    /// Identity factorization, matching `pd.RangeIndex.factorize()`.
14567    /// Codes are [0..len) because every value is unique; uniques is a
14568    /// clone of `self`.
14569    #[must_use]
14570    pub fn factorize(&self) -> (Vec<usize>, Self) {
14571        ((0..self.len()).collect(), self.clone())
14572    }
14573
14574    /// Pick values at the given positions, matching
14575    /// `pd.RangeIndex.take()`. Out-of-bounds positions raise
14576    /// [`IndexError::OutOfBounds`].
14577    pub fn take(&self, positions: &[usize]) -> Result<Index, IndexError> {
14578        let len = self.len();
14579        // Fast path first: a single pass verifies stride + bounds and returns a
14580        // lazy affine index. Only when positions are non-arithmetic (or out of
14581        // bounds) do we run the explicit bounds-check loop + materialize below.
14582        if let Some(idx) = self.take_arithmetic_positions(positions, len) {
14583            return Ok(idx);
14584        }
14585        let labels = if let Some(labels) = self.fast_i64_values_at_positions(positions, len) {
14586            labels
14587        } else {
14588            for &p in positions {
14589                if p >= len {
14590                    return Err(IndexError::OutOfBounds {
14591                        position: p,
14592                        length: len,
14593                    });
14594                }
14595            }
14596            positions.iter().map(|&p| self.value_at(p)).collect()
14597        };
14598        let mut idx = Index::from_i64_values(labels);
14599        if let Some(name) = self.name() {
14600            idx = idx.set_name(name);
14601        }
14602        Ok(idx)
14603    }
14604
14605    /// Repeat each value `repeats` times, matching `pd.RangeIndex.repeat()`.
14606    /// Returns a flat [`Index`] because the result is generally not a
14607    /// contiguous range.
14608    #[must_use]
14609    pub fn repeat(&self, repeats: usize) -> Index {
14610        let len = self.len();
14611        let labels = if repeats == 0 {
14612            Vec::new()
14613        } else if let Some(labels) = self.fast_i64_repeat_values(len, repeats) {
14614            labels
14615        } else {
14616            let mut labels = Vec::with_capacity(repeat_output_capacity(len, repeats));
14617            for position in 0..len {
14618                let value = self.value_at(position);
14619                for _ in 0..repeats {
14620                    labels.push(value);
14621                }
14622            }
14623            labels
14624        };
14625        let mut idx = Index::from_i64_values(labels);
14626        if let Some(name) = self.name() {
14627            idx = idx.set_name(name);
14628        }
14629        idx
14630    }
14631
14632    /// First and last value as (start, last), or None if empty. Used to
14633    /// power closed-form reductions that don't materialize the full vector.
14634    fn first_last(&self) -> Option<(i64, i64)> {
14635        let len = self.len();
14636        if len == 0 {
14637            return None;
14638        }
14639        let last_offset = len - 1;
14640        let last = i128::from(self.start) + (last_offset as i128) * i128::from(self.step);
14641        let last = i64::try_from(last).ok()?;
14642        Some((self.start, last))
14643    }
14644
14645    /// Sort values ascending, matching `pd.RangeIndex.sort_values()`.
14646    /// Ascending or zero step returns a clone; descending step rebuilds
14647    /// an ascending RangeIndex starting from min with positive step.
14648    /// Empty returns clone of self.
14649    #[must_use]
14650    pub fn sort_values(&self) -> Self {
14651        if self.len() <= 1 || self.step >= 0 {
14652            return self.clone();
14653        }
14654        let len = self.len();
14655        let last = self.start + (len as i64 - 1) * self.step;
14656        let new_step = -self.step;
14657        let new_stop = last + (len as i64) * new_step;
14658        Self {
14659            start: last,
14660            stop: new_stop,
14661            step: new_step,
14662            name: self.name.clone(),
14663        }
14664    }
14665
14666    /// Alias for `sort_values`, matching `pd.RangeIndex.sort()`.
14667    #[must_use]
14668    pub fn sort(&self) -> Self {
14669        self.sort_values()
14670    }
14671
14672    /// Smallest value in the range, matching `pd.RangeIndex.min()`. Closed
14673    /// form on (start, step, len). Empty returns None.
14674    #[must_use]
14675    pub fn min(&self) -> Option<i64> {
14676        let (first, last) = self.first_last()?;
14677        Some(first.min(last))
14678    }
14679
14680    /// Largest value in the range, matching `pd.RangeIndex.max()`.
14681    #[must_use]
14682    pub fn max(&self) -> Option<i64> {
14683        let (first, last) = self.first_last()?;
14684        Some(first.max(last))
14685    }
14686
14687    /// Return whether `value` is present in this RangeIndex, matching `value in pd.RangeIndex`.
14688    #[must_use]
14689    pub fn contains(&self, value: i64) -> bool {
14690        self.contains_value(value)
14691    }
14692
14693    /// Bound for a value slice, matching `pd.RangeIndex.get_slice_bound(value, side)`.
14694    pub fn get_slice_bound(&self, value: i64, side: &str) -> Result<usize, IndexError> {
14695        self.searchsorted(value, side)
14696    }
14697
14698    /// Create a RangeIndex matching `pd.RangeIndex.from_range`.
14699    pub fn from_range(start: i64, stop: i64, step: i64) -> Result<Self, IndexError> {
14700        Self::new(start, stop, step)
14701    }
14702
14703    /// Return unique values, matching `pd.RangeIndex.unique()`.
14704    #[must_use]
14705    pub fn unique(&self) -> Self {
14706        self.clone()
14707    }
14708
14709    /// Median value. Returns `None` for an empty range; for an even-length
14710    /// range, returns the average of the two middle values as f64.
14711    ///
14712    /// ⚠️ NOT A PARITY SURFACE: pandas `Index` exposes no numeric reductions
14713    /// (measured 2.2.3: `sum`/`prod`/`mean`/`median`/`std`/`var` all raise
14714    /// `AttributeError`; only `min`/`max`/`argmin`/`argmax` exist). See
14715    /// [`sum`](Self::sum).
14716    #[must_use]
14717    pub fn median(&self) -> Option<f64> {
14718        let len = self.len();
14719        if len == 0 {
14720            return None;
14721        }
14722        let mid = len / 2;
14723        if len % 2 == 1 {
14724            Some(self.value_at(mid) as f64)
14725        } else {
14726            Some((self.value_at(mid - 1) as f64 + self.value_at(mid) as f64) / 2.0)
14727        }
14728    }
14729
14730    /// Sample variance (ddof=1). Returns `None` for fewer than two values.
14731    ///
14732    /// ⚠️ NOT A PARITY SURFACE: pandas `Index` exposes no numeric reductions
14733    /// (measured 2.2.3: `sum`/`prod`/`mean`/`median`/`std`/`var` all raise
14734    /// `AttributeError`; only `min`/`max`/`argmin`/`argmax` exist). See
14735    /// [`sum`](Self::sum).
14736    #[must_use]
14737    pub fn var(&self) -> Option<f64> {
14738        let len = self.len();
14739        if len < 2 {
14740            return None;
14741        }
14742        let n = len as f64;
14743        let step = self.step as f64;
14744        Some(step * step * n * (n + 1.0) / 12.0)
14745    }
14746
14747    /// Sample standard deviation (ddof=1).
14748    ///
14749    /// ⚠️ NOT A PARITY SURFACE: pandas `Index` exposes no numeric reductions
14750    /// (measured 2.2.3: `sum`/`prod`/`mean`/`median`/`std`/`var` all raise
14751    /// `AttributeError`; only `min`/`max`/`argmin`/`argmax` exist). See
14752    /// [`sum`](Self::sum).
14753    #[must_use]
14754    pub fn std(&self) -> Option<f64> {
14755        self.var().map(f64::sqrt)
14756    }
14757
14758    /// Product of all values. Empty returns 1; saturating to i64 on overflow.
14759    ///
14760    /// ⚠️ NOT A PARITY SURFACE: pandas `Index` exposes no numeric reductions
14761    /// (measured 2.2.3: `sum`/`prod`/`mean`/`median`/`std`/`var` all raise
14762    /// `AttributeError`; only `min`/`max`/`argmin`/`argmax` exist). See
14763    /// [`sum`](Self::sum).
14764    #[must_use]
14765    pub fn prod(&self) -> i64 {
14766        if self
14767            .first_last()
14768            .is_some_and(|(first, last)| first > 0 && last > 0)
14769        {
14770            let mut total: i128 = 1;
14771            for position in 0..self.len() {
14772                total *= i128::from(self.value_at(position));
14773                if total > i128::from(i64::MAX) {
14774                    return i64::MAX;
14775                }
14776            }
14777            return total as i64;
14778        }
14779
14780        let mut total: i128 = 1;
14781        for position in 0..self.len() {
14782            let v = self.value_at(position);
14783            total = total.saturating_mul(i128::from(v));
14784        }
14785        i64::try_from(total).unwrap_or(if total > 0 { i64::MAX } else { i64::MIN })
14786    }
14787
14788    /// Sum of all values. Closed form via arithmetic-progression:
14789    /// `n * (first + last) / 2` when `n*(first+last)` is even; falls back to a
14790    /// precise i128 path otherwise.
14791    ///
14792    /// ⚠️ NOT A PARITY SURFACE: pandas `Index` has NO numeric reductions.
14793    /// Measured on 2.2.3, `pd.RangeIndex(5).sum()` raises `AttributeError`, as
14794    /// do `prod`/`mean`/`median`/`std`/`var`; only `min`/`max`/`argmin`/`argmax`
14795    /// exist on an Index. The pandas spelling is `idx.to_series().sum()`. These
14796    /// six methods are an FP SUPERSET -- do not cite them as parity evidence.
14797    #[must_use]
14798    pub fn sum(&self) -> i64 {
14799        let len = self.len();
14800        if len == 0 {
14801            return 0;
14802        }
14803        let Some((first, last)) = self.first_last() else {
14804            return 0;
14805        };
14806        let n = len as i128;
14807        let total = (i128::from(first) + i128::from(last)) * n / 2;
14808        i64::try_from(total).unwrap_or(if total > 0 { i64::MAX } else { i64::MIN })
14809    }
14810
14811    /// Mean of all values. Returns `None` for an empty range.
14812    ///
14813    /// ⚠️ NOT A PARITY SURFACE: pandas `Index` exposes no numeric reductions
14814    /// (measured 2.2.3: `sum`/`prod`/`mean`/`median`/`std`/`var` all raise
14815    /// `AttributeError`; only `min`/`max`/`argmin`/`argmax` exist). See
14816    /// [`sum`](Self::sum).
14817    #[must_use]
14818    pub fn mean(&self) -> Option<f64> {
14819        let len = self.len();
14820        if len == 0 {
14821            return None;
14822        }
14823        let (first, last) = self.first_last()?;
14824        Some((i128::from(first) + i128::from(last)) as f64 / 2.0)
14825    }
14826
14827    /// Binary-search insertion position, matching
14828    /// `pd.RangeIndex.searchsorted(value, side)`. Restricted to
14829    /// ascending ranges (`step > 0`) because searchsorted assumes a
14830    /// monotonically-increasing input; negative-step ranges raise.
14831    pub fn searchsorted(&self, value: i64, side: &str) -> Result<usize, IndexError> {
14832        if side != "left" && side != "right" {
14833            return Err(IndexError::InvalidArgument(format!(
14834                "searchsorted: side must be 'left' or 'right', got {side:?}"
14835            )));
14836        }
14837        if self.step < 0 {
14838            return Err(IndexError::InvalidArgument(
14839                "searchsorted requires a monotonically-increasing RangeIndex".to_owned(),
14840            ));
14841        }
14842        let len = self.len();
14843        if len == 0 {
14844            return Ok(0);
14845        }
14846        let start = i128::from(self.start);
14847        let value = i128::from(value);
14848        if value < start {
14849            return Ok(0);
14850        }
14851        let step = i128::from(self.step);
14852        let offset = value - start;
14853        let base = offset / step;
14854        let rem = offset % step;
14855        let insertion = if rem == 0 {
14856            base + i128::from(side == "right")
14857        } else {
14858            base + 1
14859        };
14860        let len_i128 = len as i128;
14861        Ok(if insertion >= len_i128 {
14862            len
14863        } else {
14864            insertion as usize
14865        })
14866    }
14867
14868    /// Convert to a flat [`Index`] of i64 labels, matching
14869    /// `pd.RangeIndex.to_flat_index()`.
14870    #[must_use]
14871    pub fn to_flat_index(&self) -> Index {
14872        let mut idx = Index::from_range(self.start, self.stop, self.step);
14873        if let Some(name) = self.name() {
14874            idx = idx.set_name(name);
14875        }
14876        idx
14877    }
14878
14879    /// String accessor for the flat integer labels.
14880    #[must_use]
14881    pub fn r#str(&self) -> IndexStringAccessor<'_> {
14882        IndexStringAccessor::owned(self.to_flat_index())
14883    }
14884
14885    /// One-column row materialization, matching `pd.RangeIndex.to_frame(index=False)`.
14886    #[must_use]
14887    pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
14888        (0..self.len())
14889            .map(|position| vec![IndexLabel::Int64(self.value_at(position))])
14890            .collect()
14891    }
14892
14893    /// Series-shaped materialization using range labels as both index and values.
14894    #[must_use]
14895    pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
14896        (0..self.len())
14897            .map(|position| {
14898                let label = IndexLabel::Int64(self.value_at(position));
14899                (label.clone(), label)
14900            })
14901            .collect()
14902    }
14903
14904    /// Whether any range label coerces to true.
14905    #[must_use]
14906    pub fn any(&self) -> bool {
14907        let len = self.len();
14908        len != 0 && (len != 1 || self.start != 0)
14909    }
14910
14911    /// Whether all range labels coerce to true.
14912    #[must_use]
14913    pub fn all(&self) -> bool {
14914        !self.contains_value(0)
14915    }
14916
14917    /// Get labels for a level. RangeIndex is flat and only accepts level 0.
14918    pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
14919        if level == 0 {
14920            Ok(self.to_flat_index())
14921        } else {
14922            Err(IndexError::OutOfBounds {
14923                position: level,
14924                length: 1,
14925            })
14926        }
14927    }
14928
14929    /// Drop a level. RangeIndex is flat, so removing its only level is invalid.
14930    pub fn droplevel(&self, level: usize) -> Result<Index, IndexError> {
14931        if level == 0 {
14932            Err(IndexError::InvalidArgument(
14933                "cannot remove the only level from a flat Index".to_owned(),
14934            ))
14935        } else {
14936            Err(IndexError::OutOfBounds {
14937                position: level,
14938                length: 1,
14939            })
14940        }
14941    }
14942
14943    /// Group equal range labels into position buckets.
14944    #[must_use]
14945    pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
14946        let mut groups = HashMap::with_capacity(self.len());
14947        for position in 0..self.len() {
14948            groups.insert(IndexLabel::Int64(self.value_at(position)), vec![position]);
14949        }
14950        groups
14951    }
14952
14953    /// Apply a function to each range label, returning a flat Index.
14954    #[must_use]
14955    pub fn map<F>(&self, func: F) -> Index
14956    where
14957        F: Fn(&IndexLabel) -> IndexLabel,
14958    {
14959        let labels = (0..self.len())
14960            .map(|position| func(&IndexLabel::Int64(self.value_at(position))))
14961            .collect();
14962        let mut out = Index::new(labels);
14963        if let Some(name) = self.name() {
14964            out = out.set_name(name);
14965        }
14966        out
14967    }
14968
14969    /// Cast range labels to a pandas dtype string, returning a flat Index.
14970    pub fn astype(&self, dtype: &str) -> Result<Index, IndexError> {
14971        match dtype {
14972            "int" | "int64" => Ok(self.to_flat_index()),
14973            "str" | "string" | "object" => {
14974                let labels = (0..self.len())
14975                    .map(|position| IndexLabel::Utf8(self.value_at(position).to_string()))
14976                    .collect();
14977                let mut out = Index::new(labels);
14978                if let Some(name) = self.name() {
14979                    out = out.set_name(name);
14980                }
14981                Ok(out)
14982            }
14983            "datetime64[ns]" => {
14984                if self.is_empty() {
14985                    Ok(self.to_flat_index())
14986                } else {
14987                    Err(IndexError::InvalidArgument(
14988                        "DatetimeIndex requires homogeneous DatetimeIndex labels".to_owned(),
14989                    ))
14990                }
14991            }
14992            "timedelta64[ns]" => {
14993                if self.is_empty() {
14994                    Ok(self.to_flat_index())
14995                } else {
14996                    Err(IndexError::InvalidArgument(
14997                        "TimedeltaIndex requires homogeneous TimedeltaIndex labels".to_owned(),
14998                    ))
14999                }
15000            }
15001            other => Err(IndexError::InvalidArgument(format!(
15002                "unsupported Index.astype dtype {other:?}"
15003            ))),
15004        }
15005    }
15006
15007    /// Nearest preceding-or-equal range label lookup.
15008    #[must_use]
15009    pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
15010        if let IndexLabel::Int64(needle) = key
15011            && self.step > 0
15012        {
15013            let position = self.searchsorted(*needle, "right").ok()?.checked_sub(1)?;
15014            return Some(IndexLabel::Int64(self.value_at(position)));
15015        }
15016        let mut best = None;
15017        for position in 0..self.len() {
15018            let label = IndexLabel::Int64(self.value_at(position));
15019            if label.cmp(key).is_le() {
15020                best = Some(label);
15021            } else {
15022                break;
15023            }
15024        }
15025        best
15026    }
15027
15028    /// Locate nearest preceding-or-equal range positions for each target label.
15029    #[must_use]
15030    pub fn asof_locs(&self, where_index: &Index, mask: Option<&[bool]>) -> Vec<Option<usize>> {
15031        if let Some(keys) = where_index.labels.int64_view() {
15032            if mask.is_none() {
15033                if self.step > 0 && keys.windows(2).all(|pair| pair[0] <= pair[1]) {
15034                    let len = self.len();
15035                    let mut next_position = 0usize;
15036                    let mut best = None;
15037                    let mut positions = Vec::with_capacity(keys.len());
15038                    for &key in keys.iter() {
15039                        while next_position < len && self.value_at(next_position) <= key {
15040                            best = Some(next_position);
15041                            next_position += 1;
15042                        }
15043                        positions.push(best);
15044                    }
15045                    return positions;
15046                }
15047                return keys
15048                    .iter()
15049                    .map(|&key| {
15050                        let mut lo = 0usize;
15051                        let mut hi = self.len();
15052                        while lo < hi {
15053                            let mid = lo + (hi - lo) / 2;
15054                            if self.value_at(mid) <= key {
15055                                lo = mid + 1;
15056                            } else {
15057                                hi = mid;
15058                            }
15059                        }
15060                        lo.checked_sub(1)
15061                    })
15062                    .collect();
15063            }
15064            return keys
15065                .iter()
15066                .map(|&key| {
15067                    let mut best = None;
15068                    for position in 0..self.len() {
15069                        if mask
15070                            .and_then(|values| values.get(position))
15071                            .is_some_and(|include| !include)
15072                        {
15073                            continue;
15074                        }
15075                        if self.value_at(position) <= key {
15076                            best = Some(position);
15077                        } else {
15078                            break;
15079                        }
15080                    }
15081                    best
15082                })
15083                .collect();
15084        }
15085        where_index
15086            .labels
15087            .iter()
15088            .map(|key| {
15089                let mut best = None;
15090                for position in 0..self.len() {
15091                    if mask
15092                        .and_then(|values| values.get(position))
15093                        .is_some_and(|include| !include)
15094                    {
15095                        continue;
15096                    }
15097                    let label = IndexLabel::Int64(self.value_at(position));
15098                    if label.cmp(key).is_le() {
15099                        best = Some(position);
15100                    } else {
15101                        break;
15102                    }
15103                }
15104                best
15105            })
15106            .collect()
15107    }
15108
15109    /// Drop range labels, returning a flat Index.
15110    #[must_use]
15111    pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Index {
15112        let len = self.len();
15113        let mut drop_positions = vec![false; len];
15114        for label in labels_to_drop {
15115            if let IndexLabel::Int64(value) = label
15116                && let Some(position) = self.position_of_value(*value)
15117            {
15118                drop_positions[position] = true;
15119            }
15120        }
15121        let labels = (0..len)
15122            .filter_map(|position| (!drop_positions[position]).then_some(self.value_at(position)))
15123            .collect();
15124        let mut out = Index::from_i64_values(labels);
15125        if let Some(name) = self.name() {
15126            out = out.set_name(name);
15127        }
15128        out
15129    }
15130
15131    fn apply_join_name(&self, other: &Index, mut out: Index) -> Index {
15132        if self.name() == other.name()
15133            && let Some(name) = self.name()
15134        {
15135            out = out.set_name(name);
15136        }
15137        out
15138    }
15139
15140    fn matching_step_i64_slice_offset(&self, other: &[i64]) -> Option<i128> {
15141        let &first = other.first()?;
15142        let step = i128::from(self.step);
15143        for (position, &value) in other.iter().enumerate() {
15144            let expected = i128::from(first) + (position as i128) * step;
15145            if i128::from(value) != expected {
15146                return None;
15147            }
15148        }
15149        let offset = i128::from(first) - i128::from(self.start);
15150        if offset % step != 0 {
15151            return None;
15152        }
15153        Some(offset / step)
15154    }
15155
15156    fn same_lattice_i64_slice_overlap_positions(
15157        &self,
15158        other: &[i64],
15159    ) -> Option<Option<(usize, usize)>> {
15160        if self.is_empty() || other.is_empty() {
15161            return Some(None);
15162        }
15163        let other_start = self.matching_step_i64_slice_offset(other)?;
15164        let other_last = other_start.checked_add(other.len() as i128 - 1)?;
15165        let first = other_start.max(0);
15166        let last = other_last.min(self.len() as i128 - 1);
15167        if first > last {
15168            return Some(None);
15169        }
15170        Some(Some((
15171            usize::try_from(first).ok()?,
15172            usize::try_from(last).ok()?,
15173        )))
15174    }
15175
15176    fn join_outer_i64_affine_slice(&self, other: &[i64]) -> Option<Index> {
15177        let self_len = self.len();
15178        if other.is_empty() {
15179            return self.affine_span_index(0, self_len, None);
15180        }
15181        if self_len == 0 {
15182            self.matching_step_i64_slice_offset(other)?;
15183            return Index::new_known_unique_int64_affine_range(other[0], self.step, other.len());
15184        }
15185        let other_start = self.matching_step_i64_slice_offset(other)?;
15186        if other_start < 0 || other_start > self_len as i128 {
15187            return None;
15188        }
15189        let other_last = other_start.checked_add(other.len() as i128 - 1)?;
15190        let joined_len = (self_len as i128).max(other_last + 1);
15191        self.affine_span_index(0, usize::try_from(joined_len).ok()?, None)
15192    }
15193
15194    fn join_inner_i64(&self, other: &[i64]) -> Index {
15195        if let Some(overlap) = self.same_lattice_i64_slice_overlap_positions(other) {
15196            let (first, len) = match overlap {
15197                Some((first, last)) => (first, last - first + 1),
15198                None => (0, 0),
15199            };
15200            if let Some(index) = self.affine_span_index(first, len, None) {
15201                return index;
15202            }
15203        }
15204
15205        let mut labels = Vec::new();
15206        if other.is_empty() || self.is_empty() {
15207            return Index::from_i64_values(labels);
15208        }
15209
15210        if let Some((min, span)) = Index::i64_dense_span(other) {
15211            let mut bits = vec![0u64; span.div_ceil(64)];
15212            for &value in other {
15213                let slot = (value as i128 - min as i128) as usize;
15214                bits[slot >> 6] |= 1u64 << (slot & 63);
15215            }
15216            for position in 0..self.len() {
15217                let value = self.value_at(position);
15218                let offset = value as i128 - min as i128;
15219                if offset >= 0 && (offset as usize) < span {
15220                    let slot = offset as usize;
15221                    if (bits[slot >> 6] >> (slot & 63)) & 1 == 1 {
15222                        labels.push(value);
15223                    }
15224                }
15225            }
15226        } else {
15227            let mut other_set = FxHashSet::<i64>::default();
15228            other_set.reserve(other.len());
15229            for &value in other {
15230                other_set.insert(value);
15231            }
15232            for position in 0..self.len() {
15233                let value = self.value_at(position);
15234                if other_set.contains(&value) {
15235                    labels.push(value);
15236                }
15237            }
15238        }
15239
15240        Index::from_i64_values(labels)
15241    }
15242
15243    fn join_outer_i64(&self, other: &[i64]) -> Index {
15244        if let Some(index) = self.join_outer_i64_affine_slice(other) {
15245            return index;
15246        }
15247
15248        let mut labels = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
15249        for position in 0..self.len() {
15250            labels.push(self.value_at(position));
15251        }
15252        if other.is_empty() {
15253            return Index::from_i64_values(labels);
15254        }
15255
15256        // A duplicate-bearing right index uses the same first-key grouping as
15257        // `Index::union_with`. The range itself is unique, but emitting its
15258        // complete physical order and appending surplus right duplicates would
15259        // place a second `6` after `3`, unlike the flat-index oracle.
15260        if Index::has_duplicates_i64(other) {
15261            let mut counts = FxHashMap::<i64, (usize, usize)>::default();
15262            counts.reserve(combined_output_capacity(self.len(), other.len()));
15263            let mut order = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
15264            for position in 0..self.len() {
15265                let value = self.value_at(position);
15266                let entry = counts.entry(value).or_insert((0, 0));
15267                if entry.0 == 0 && entry.1 == 0 {
15268                    order.push(value);
15269                }
15270                entry.0 += 1;
15271            }
15272            for &value in other {
15273                let entry = counts.entry(value).or_insert((0, 0));
15274                if entry.0 == 0 && entry.1 == 0 {
15275                    order.push(value);
15276                }
15277                entry.1 += 1;
15278            }
15279            let mut grouped = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
15280            for value in order {
15281                let (left_count, right_count) = counts[&value];
15282                grouped.extend(std::iter::repeat_n(value, left_count.max(right_count)));
15283            }
15284            return Index::from_i64_values(grouped);
15285        }
15286
15287        if let Some((min, span)) = Index::i64_dense_span(other) {
15288            let mut seen = vec![0u64; span.div_ceil(64)];
15289            for &value in other {
15290                if self.contains_value(value) {
15291                    continue;
15292                }
15293                let slot = (value as i128 - min as i128) as usize;
15294                let bit = 1u64 << (slot & 63);
15295                let word = slot >> 6;
15296                if seen[word] & bit == 0 {
15297                    labels.push(value);
15298                    seen[word] |= bit;
15299                }
15300            }
15301        } else {
15302            let mut seen = FxHashSet::<i64>::default();
15303            seen.reserve(other.len());
15304            for &value in other {
15305                if !self.contains_value(value) && seen.insert(value) {
15306                    labels.push(value);
15307                }
15308            }
15309        }
15310
15311        Index::from_i64_values(labels)
15312    }
15313
15314    /// Join range labels with another flat Index.
15315    pub fn join(&self, other: &Index, how: &str) -> Result<Index, IndexError> {
15316        match how {
15317            "left" => Ok(self.to_flat_index()),
15318            "right" => Ok(other.clone()),
15319            "inner" => {
15320                if let Some(other_values) = other.labels.int64_view() {
15321                    let out = self.join_inner_i64(&other_values);
15322                    return Ok(self.apply_join_name(other, out));
15323                }
15324                self.to_flat_index().join(other, how)
15325            }
15326            "outer" => {
15327                if let Some(other_values) = other.labels.int64_view() {
15328                    let out = self.join_outer_i64(&other_values);
15329                    return Ok(self.apply_join_name(other, out));
15330                }
15331                self.to_flat_index().join(other, how)
15332            }
15333            other => Err(IndexError::InvalidArgument(format!(
15334                "join: how must be 'left', 'right', 'inner', or 'outer', got {other:?}"
15335            ))),
15336        }
15337    }
15338
15339    /// Sort range labels and return the positional sorter.
15340    #[must_use]
15341    pub fn sortlevel(&self) -> (Index, Vec<usize>) {
15342        let order = self.argsort();
15343        let labels = order
15344            .iter()
15345            .map(|&position| self.value_at(position))
15346            .collect();
15347        let mut out = Index::from_i64_values(labels);
15348        if let Some(name) = self.name() {
15349            out = out.set_name(name);
15350        }
15351        (out, order)
15352    }
15353
15354    /// Returns a clone, matching `pd.RangeIndex.view()`.
15355    #[must_use]
15356    pub fn view(&self) -> Self {
15357        self.clone()
15358    }
15359
15360    /// Identity transpose for a 1D index, matching
15361    /// `pd.RangeIndex.transpose()`.
15362    #[must_use]
15363    pub fn transpose(&self) -> Self {
15364        self.clone()
15365    }
15366
15367    /// Alias for `transpose`, matching `pd.RangeIndex.T`.
15368    #[allow(non_snake_case)]
15369    #[must_use]
15370    pub fn T(&self) -> Self {
15371        self.transpose()
15372    }
15373
15374    /// Flatten the range to a `Vec<i64>`, matching `pd.RangeIndex.ravel()`.
15375    #[must_use]
15376    pub fn ravel(&self) -> Vec<i64> {
15377        self.values().to_vec()
15378    }
15379
15380    /// Number of levels, matching `pd.RangeIndex.nlevels`. Always `1`.
15381    #[must_use]
15382    pub fn nlevels(&self) -> usize {
15383        1
15384    }
15385
15386    /// Identity dtype-reinference, matching `pd.RangeIndex.infer_objects()`.
15387    #[must_use]
15388    pub fn infer_objects(&self) -> Self {
15389        self.clone()
15390    }
15391
15392    /// Per-position membership mask, matching `pd.RangeIndex.isin(values)`.
15393    #[must_use]
15394    pub fn isin(&self, values: &[i64]) -> Vec<bool> {
15395        let mut mask = vec![false; self.len()];
15396        for &value in values {
15397            if let Some(position) = self.position_of_value(value) {
15398                mask[position] = true;
15399            }
15400        }
15401        mask
15402    }
15403
15404    /// Half-open positional range for a value slice, matching
15405    /// `pd.RangeIndex.slice_indexer(start, end)`.
15406    pub fn slice_indexer(
15407        &self,
15408        start: i64,
15409        end: i64,
15410    ) -> Result<std::ops::Range<usize>, IndexError> {
15411        let (left, right) = self.slice_locs(start, end)?;
15412        Ok(left..right)
15413    }
15414
15415    /// Find positions of `[start, end]` for a value slice, matching
15416    /// `pd.RangeIndex.slice_locs(start, end)`. Requires the range to
15417    /// be ascending (`step > 0`).
15418    pub fn slice_locs(&self, start: i64, end: i64) -> Result<(usize, usize), IndexError> {
15419        if self.step < 0 {
15420            return Err(IndexError::InvalidArgument(
15421                "slice_locs requires a monotonic increasing RangeIndex".to_owned(),
15422            ));
15423        }
15424        let left = self.searchsorted(start, "left")?;
15425        let right = self.searchsorted(end, "right")?;
15426        Ok((left, right))
15427    }
15428
15429    /// First position of `value`, matching `pd.RangeIndex.get_loc(value)`.
15430    /// Closed-form on (start, step, len).
15431    pub fn get_loc(&self, value: i64) -> Result<usize, IndexError> {
15432        if self.step == 0 {
15433            return Err(IndexError::InvalidArgument(
15434                "get_loc: zero-step RangeIndex is invalid".to_owned(),
15435            ));
15436        }
15437        self.position_of_value(value).ok_or_else(|| {
15438            IndexError::InvalidArgument(format!("get_loc: {value} not in RangeIndex"))
15439        })
15440    }
15441
15442    /// Set the index name, matching `pd.RangeIndex.rename(name)`.
15443    #[must_use]
15444    pub fn rename(&self, name: &str) -> Self {
15445        self.set_name(name)
15446    }
15447
15448    /// Reindex against `target`, matching `pd.RangeIndex.reindex(target)`.
15449    /// Returns `(target.clone(), indexer)`.
15450    #[must_use]
15451    pub fn reindex(&self, target: &Self) -> (Self, Vec<isize>) {
15452        let source_len = self.len();
15453        if let Some(indexer) = self.range_target_indexer(target, source_len) {
15454            return (target.clone(), indexer);
15455        }
15456        let bounds = self.position_bounds_for_len(source_len);
15457        let indexer = (0..target.len())
15458            .map(|position| {
15459                match self.position_of_value_with_len_and_bounds(
15460                    target.value_at(position),
15461                    source_len,
15462                    bounds,
15463                ) {
15464                    Some(position) => position as isize,
15465                    None => -1,
15466                }
15467            })
15468            .collect();
15469        (target.clone(), indexer)
15470    }
15471
15472    /// Locate every position matching each target, matching
15473    /// `pd.RangeIndex.get_indexer_non_unique(targets)`. RangeIndex is
15474    /// always unique so each target either matches one position or
15475    /// none.
15476    #[must_use]
15477    pub fn get_indexer_non_unique(&self, targets: &[i64]) -> (Vec<isize>, Vec<usize>) {
15478        let source_len = self.len();
15479        let bounds = self.position_bounds_for_len(source_len);
15480        let mut positions = Vec::<isize>::with_capacity(targets.len());
15481        let mut missing = Vec::<usize>::new();
15482        for (idx, target) in targets.iter().enumerate() {
15483            match self.position_of_value_with_len_and_bounds(*target, source_len, bounds) {
15484                Some(position) => positions.push(position as isize),
15485                None => {
15486                    positions.push(-1);
15487                    missing.push(idx);
15488                }
15489            }
15490        }
15491        (positions, missing)
15492    }
15493
15494    /// Alias for [`get_indexer`](Self::get_indexer), matching
15495    /// `pd.RangeIndex.get_indexer_for(targets)`.
15496    #[must_use]
15497    pub fn get_indexer_for(&self, targets: &[i64]) -> Vec<isize> {
15498        self.get_indexer(targets)
15499    }
15500
15501    /// Locate each target value, matching
15502    /// `pd.RangeIndex.get_indexer(targets)`. Closed-form per target.
15503    #[must_use]
15504    pub fn get_indexer(&self, targets: &[i64]) -> Vec<isize> {
15505        let source_len = self.len();
15506        let bounds = self.position_bounds_for_len(source_len);
15507        let mut positions = Vec::with_capacity(targets.len());
15508        for &value in targets {
15509            positions.push(
15510                match self.position_of_value_with_len_and_bounds(value, source_len, bounds) {
15511                    Some(position) => position as isize,
15512                    None => -1,
15513                },
15514            );
15515        }
15516        positions
15517    }
15518
15519    /// Replace positions where `cond` is `false` with `other`, matching
15520    /// `pd.RangeIndex.where(cond, other)`. Returns flat Index because
15521    /// the result is generally not a contiguous range.
15522    pub fn r#where(&self, cond: &[bool], other: i64) -> Result<Index, IndexError> {
15523        let len = self.len();
15524        if cond.len() != len {
15525            return Err(IndexError::LengthMismatch {
15526                expected: len,
15527                actual: cond.len(),
15528                context: "where: cond length must match index length".to_owned(),
15529            });
15530        }
15531        let labels: Vec<i64> = cond
15532            .iter()
15533            .enumerate()
15534            .map(
15535                |(position, &keep)| {
15536                    if keep { self.value_at(position) } else { other }
15537                },
15538            )
15539            .collect();
15540        let mut out = Index::from_i64_values(labels);
15541        if let Some(name) = self.name() {
15542            out = out.set_name(name);
15543        }
15544        Ok(out)
15545    }
15546
15547    /// Replace positions where `mask` is `true` with `value`, matching
15548    /// `pd.RangeIndex.putmask(mask, value)`.
15549    pub fn putmask(&self, mask: &[bool], value: i64) -> Result<Index, IndexError> {
15550        let len = self.len();
15551        if mask.len() != len {
15552            return Err(IndexError::LengthMismatch {
15553                expected: len,
15554                actual: mask.len(),
15555                context: "putmask: mask length must match index length".to_owned(),
15556            });
15557        }
15558        let labels: Vec<i64> = mask
15559            .iter()
15560            .enumerate()
15561            .map(|(position, &replace)| {
15562                if replace {
15563                    value
15564                } else {
15565                    self.value_at(position)
15566                }
15567            })
15568            .collect();
15569        let mut out = Index::from_i64_values(labels);
15570        if let Some(name) = self.name() {
15571            out = out.set_name(name);
15572        }
15573        Ok(out)
15574    }
15575
15576    /// Returns an ascending-ordered `RangeIndex` covering the same value set
15577    /// (name preserved). pandas set operations
15578    /// (union/intersection/difference/symmetric_difference) return results
15579    /// sorted ascending under the default `sort=None`, so descending ranges
15580    /// (`step < 0`) are normalized to their ascending equivalent before the
15581    /// set-op logic runs. Ascending or empty ranges are returned unchanged.
15582    /// Falls back to an unchanged clone in the (unrepresentable) case where the
15583    /// ascending `stop` would overflow `i64`.
15584    fn ascending_normalized(&self) -> RangeIndex {
15585        let len = self.len();
15586        if self.step >= 0 || len == 0 {
15587            return self.clone();
15588        }
15589        // Descending: the smallest value is the last element and the step
15590        // magnitude is the ascending step. The ascending range runs
15591        // [last, self.start] inclusive, i.e. stop = self.start + 1.
15592        let last = self.value_at(len - 1);
15593        let asc_step = self.step.wrapping_neg();
15594        match self.start.checked_add(1) {
15595            Some(stop) if asc_step > 0 => RangeIndex {
15596                start: last,
15597                stop,
15598                step: asc_step,
15599                name: self.name.clone(),
15600            },
15601            _ => self.clone(),
15602        }
15603    }
15604
15605    /// Values present in both ranges, matching
15606    /// `pd.RangeIndex.intersection(other)`. Returns flat Index because the
15607    /// result may not be a contiguous range. NB: pandas uses `sort=False` for
15608    /// intersection (unlike union/difference/symmetric_difference, which default
15609    /// to `sort=None`). Its result is ascending EXCEPT when BOTH operands are
15610    /// descending (`step < 0`), where it is descending. (Verified against pandas
15611    /// 2.2.3 over 150k random pairs.) The self-order scan below already yields
15612    /// descending order over a descending range, so both-descending goes through
15613    /// the operands as-is; every other case is routed through ascending-
15614    /// normalized operands so the fast paths and fallback produce ascending.
15615    #[must_use]
15616    pub fn intersection(&self, other: &Self) -> Index {
15617        if self.step < 0 && other.step < 0 {
15618            self.intersection_selforder(other)
15619        } else {
15620            self.ascending_normalized()
15621                .intersection_selforder(&other.ascending_normalized())
15622        }
15623    }
15624
15625    fn intersection_selforder(&self, other: &Self) -> Index {
15626        let shared_name = self.name().filter(|_| self.name() == other.name());
15627        if let Some(overlap) = self.same_lattice_overlap_positions(other) {
15628            let (first, len) = match overlap {
15629                Some((first, last)) => (first, last - first + 1),
15630                None => (0, 0),
15631            };
15632            if let Some(index) = self.affine_span_index(first, len, shared_name) {
15633                return index;
15634            }
15635        }
15636        let mut labels = Vec::with_capacity(self.len().min(other.len()));
15637        for position in 0..self.len() {
15638            let value = self.value_at(position);
15639            if other.contains_value(value) {
15640                labels.push(value);
15641            }
15642        }
15643        let mut idx = Index::from_i64_values(labels);
15644        if let Some(name) = shared_name {
15645            idx = idx.set_name(name);
15646        }
15647        idx
15648    }
15649
15650    /// True when the two ranges enumerate the same value sequence (order
15651    /// included), i.e. `pd.Index.equals`. Used to detect the union passthrough
15652    /// case where pandas returns `self` unchanged rather than sorting.
15653    fn range_values_equal(&self, other: &Self) -> bool {
15654        let len = self.len();
15655        len == other.len()
15656            && (len == 0
15657                || (self.value_at(0) == other.value_at(0) && (len == 1 || self.step == other.step)))
15658    }
15659
15660    /// Union of the two ranges, matching `pd.RangeIndex.union(other)`. pandas
15661    /// (`sort=None`) returns the result sorted ascending EXCEPT when an operand
15662    /// is empty or the two are value-equal, where it passes the surviving
15663    /// operand through unchanged (order preserved). fp's existing fast paths
15664    /// already reproduce those passthrough cases, so only the both-non-empty,
15665    /// non-equal case is normalized to ascending.
15666    #[must_use]
15667    pub fn union(&self, other: &Self) -> Index {
15668        if self.is_empty() || other.is_empty() || self.range_values_equal(other) {
15669            return self.union_ascending(other);
15670        }
15671        self.ascending_normalized()
15672            .union_ascending(&other.ascending_normalized())
15673    }
15674
15675    fn union_ascending(&self, other: &Self) -> Index {
15676        let shared_name = self.name().filter(|_| self.name() == other.name());
15677        let self_len = self.len();
15678        let other_len = other.len();
15679        if self_len == 0 {
15680            if let Some(index) = other.affine_span_index(0, other_len, shared_name) {
15681                return index;
15682            }
15683        } else if other_len == 0 {
15684            if let Some(index) = self.affine_span_index(0, self_len, shared_name) {
15685                return index;
15686            }
15687        } else if let Some(other_start) = self.matching_step_offset(other)
15688            && let Some(other_end) = other_start.checked_add(other_len as i128 - 1)
15689            && other_start >= 0
15690            && other_start <= self_len as i128
15691        {
15692            let last = (self_len as i128 - 1).max(other_end);
15693            if let Ok(len) = usize::try_from(last + 1)
15694                && let Some(index) = self.affine_span_index(0, len, shared_name)
15695            {
15696                return index;
15697            }
15698        }
15699        let mut labels = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
15700        for position in 0..self.len() {
15701            labels.push(self.value_at(position));
15702        }
15703        for position in 0..other.len() {
15704            let value = other.value_at(position);
15705            if !self.contains_value(value) {
15706                labels.push(value);
15707            }
15708        }
15709        // pandas sorts the union result ascending; both operands are already
15710        // ascending here (normalized), so a sort produces the pandas order for
15711        // the non-aligned case where the two lattices interleave.
15712        labels.sort_unstable();
15713        let mut idx = Index::from_i64_values(labels);
15714        if let Some(name) = shared_name {
15715            idx = idx.set_name(name);
15716        }
15717        idx
15718    }
15719
15720    /// Self values not in other, matching `pd.RangeIndex.difference(other)`.
15721    /// pandas (`sort=None`) sorts the result ascending EXCEPT when `other` is
15722    /// empty, where it returns `self` unchanged; both-empty / equal operands
15723    /// yield an empty result. Only the both-non-empty, non-equal case is
15724    /// normalized to ascending.
15725    #[must_use]
15726    pub fn difference(&self, other: &Self) -> Index {
15727        if self.is_empty() || other.is_empty() || self.range_values_equal(other) {
15728            return self.difference_ascending(other);
15729        }
15730        self.ascending_normalized()
15731            .difference_ascending(&other.ascending_normalized())
15732    }
15733
15734    fn difference_ascending(&self, other: &Self) -> Index {
15735        // Per br-frankenpandas-6r1lq: difference preserves self.name (not
15736        // shared_name like union/intersection).
15737        if let Some(span) = self.single_difference_span_positions(other) {
15738            let (first, len) = span.unwrap_or((0, 0));
15739            if let Some(index) = self.affine_span_index(first, len, self.name()) {
15740                return index;
15741            }
15742        }
15743        let mut labels = Vec::with_capacity(self.len());
15744        for position in 0..self.len() {
15745            let value = self.value_at(position);
15746            if !other.contains_value(value) {
15747                labels.push(value);
15748            }
15749        }
15750        let mut idx = Index::from_i64_values(labels);
15751        if let Some(name) = self.name() {
15752            idx = idx.set_name(name);
15753        }
15754        idx
15755    }
15756
15757    /// Values in either but not both, matching
15758    /// `pd.RangeIndex.symmetric_difference(other)`. pandas (`sort=None`) sorts
15759    /// the result ascending EXCEPT when an operand is empty, where it returns
15760    /// the surviving operand unchanged; equal operands yield an empty result.
15761    /// Only the both-non-empty, non-equal case is normalized to ascending.
15762    #[must_use]
15763    pub fn symmetric_difference(&self, other: &Self) -> Index {
15764        if self.is_empty() || other.is_empty() || self.range_values_equal(other) {
15765            return self.symmetric_difference_ascending(other);
15766        }
15767        self.ascending_normalized()
15768            .symmetric_difference_ascending(&other.ascending_normalized())
15769    }
15770
15771    fn symmetric_difference_ascending(&self, other: &Self) -> Index {
15772        let shared_name = self.name().filter(|_| self.name() == other.name());
15773        if let (Some(left_span), Some(right_span)) = (
15774            self.single_difference_span_positions(other),
15775            other.single_difference_span_positions(self),
15776        ) {
15777            match (left_span, right_span) {
15778                (None, None) => {
15779                    if let Some(index) = self.affine_span_index(0, 0, shared_name) {
15780                        return index;
15781                    }
15782                }
15783                (Some((first, len)), None) => {
15784                    if let Some(index) = self.affine_span_index(first, len, shared_name) {
15785                        return index;
15786                    }
15787                }
15788                (None, Some((first, len))) => {
15789                    if let Some(index) = other.affine_span_index(first, len, shared_name) {
15790                        return index;
15791                    }
15792                }
15793                (Some((left_first, left_len)), Some((right_first, right_len))) => {
15794                    if left_len == 0 {
15795                        if let Some(index) =
15796                            other.affine_span_index(right_first, right_len, shared_name)
15797                        {
15798                            return index;
15799                        }
15800                    } else if right_len == 0 {
15801                        if let Some(index) =
15802                            self.affine_span_index(left_first, left_len, shared_name)
15803                        {
15804                            return index;
15805                        }
15806                    } else {
15807                        let left_last = self.value_at(left_first + left_len - 1);
15808                        let right_start = other.value_at(right_first);
15809                        if left_last
15810                            .checked_add(self.step)
15811                            .is_some_and(|next| next == right_start)
15812                            && let Some(len) = left_len.checked_add(right_len)
15813                            && let Some(index) =
15814                                self.affine_span_index(left_first, len, shared_name)
15815                        {
15816                            return index;
15817                        }
15818                        // Only emit [left ++ right] directly when the left run
15819                        // is entirely below the right run, so the concatenation
15820                        // is ascending (pandas sorts the result). Otherwise fall
15821                        // through to the sorted fallback below.
15822                        if left_last < right_start
15823                            && let (Some(left_run), Some(right_run)) = (
15824                                Int64AffineLabels::new(
15825                                    self.value_at(left_first),
15826                                    self.step,
15827                                    left_len,
15828                                ),
15829                                Int64AffineLabels::new(
15830                                    other.value_at(right_first),
15831                                    other.step,
15832                                    right_len,
15833                                ),
15834                            )
15835                            && let Some(mut index) =
15836                                Index::new_known_unique_int64_two_affine_runs(left_run, right_run)
15837                        {
15838                            if let Some(name) = shared_name {
15839                                index = index.set_name(name);
15840                            }
15841                            return index;
15842                        }
15843                    }
15844                }
15845            }
15846        }
15847        let mut labels = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
15848        for position in 0..self.len() {
15849            let value = self.value_at(position);
15850            if !other.contains_value(value) {
15851                labels.push(value);
15852            }
15853        }
15854        for position in 0..other.len() {
15855            let value = other.value_at(position);
15856            if !self.contains_value(value) {
15857                labels.push(value);
15858            }
15859        }
15860        // pandas sorts the symmetric-difference result ascending; the two
15861        // single-value runs above are each ascending (operands normalized) but
15862        // interleave when neither range sits wholly below the other, so sort.
15863        labels.sort_unstable();
15864        let mut idx = Index::from_i64_values(labels);
15865        if let Some(name) = shared_name {
15866            idx = idx.set_name(name);
15867        }
15868        idx
15869    }
15870
15871    /// Insert `value` at position `loc`, matching
15872    /// `pd.RangeIndex.insert(loc, value)`. Returns a flat [`Index`]
15873    /// because the result is generally not a contiguous range.
15874    pub fn insert(&self, loc: usize, value: i64) -> Result<Index, IndexError> {
15875        let len = self.len();
15876        if loc > len {
15877            return Err(IndexError::OutOfBounds {
15878                position: loc,
15879                length: len,
15880            });
15881        }
15882        let labels = if let Some(labels) = self.fast_i64_insert_values(len, loc, value) {
15883            labels
15884        } else {
15885            let mut labels = Vec::with_capacity(insert_output_capacity(len));
15886            for position in 0..loc {
15887                labels.push(self.value_at(position));
15888            }
15889            labels.push(value);
15890            for position in loc..len {
15891                labels.push(self.value_at(position));
15892            }
15893            labels
15894        };
15895        let mut out = Index::from_i64_values(labels);
15896        if let Some(name) = self.name() {
15897            out = out.set_name(name);
15898        }
15899        Ok(out)
15900    }
15901
15902    /// Concatenate with another RangeIndex, matching
15903    /// `pd.RangeIndex.append(other)`. Returns a flat [`Index`] because the
15904    /// resulting values are generally not a contiguous range; preserves
15905    /// the index name when both operands share it.
15906    #[must_use]
15907    pub fn append(&self, other: &Self) -> Index {
15908        let len = self.len();
15909        let other_len = other.len();
15910        if let Some(index) = self.fast_i64_append_index(other, len, other_len) {
15911            let mut out = index;
15912            if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
15913                out = out.set_name(name);
15914            }
15915            return out;
15916        }
15917        let labels = if let Some(labels) = self.fast_i64_append_values(other, len, other_len) {
15918            labels
15919        } else {
15920            let mut labels = Vec::with_capacity(combined_output_capacity(len, other_len));
15921            for position in 0..len {
15922                labels.push(self.value_at(position));
15923            }
15924            for position in 0..other_len {
15925                labels.push(other.value_at(position));
15926            }
15927            labels
15928        };
15929        let mut out = Index::from_i64_values(labels);
15930        if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
15931            out = out.set_name(name);
15932        }
15933        out
15934    }
15935
15936    /// Remove the value at the given position, matching
15937    /// `pd.RangeIndex.delete(loc)`. Returns a flat [`Index`] because the
15938    /// residual values may no longer form a contiguous range.
15939    pub fn delete(&self, loc: usize) -> Result<Index, IndexError> {
15940        let len = self.len();
15941        if loc >= len {
15942            return Err(IndexError::OutOfBounds {
15943                position: loc,
15944                length: len,
15945            });
15946        }
15947        if let Some(index) = self.fast_i64_delete_index(len, loc) {
15948            let mut out = index;
15949            if let Some(name) = self.name() {
15950                out = out.set_name(name);
15951            }
15952            return Ok(out);
15953        }
15954        let labels = if let Some(labels) = self.fast_i64_delete_values(len, loc) {
15955            labels
15956        } else {
15957            let mut labels = Vec::with_capacity(len.saturating_sub(1));
15958            for position in 0..len {
15959                if position != loc {
15960                    labels.push(self.value_at(position));
15961                }
15962            }
15963            labels
15964        };
15965        let mut out = Index::from_i64_values(labels);
15966        if let Some(name) = self.name() {
15967            out = out.set_name(name);
15968        }
15969        Ok(out)
15970    }
15971}
15972
15973/// Public pandas-style categorical index wrapper: typed labels (text,
15974/// numbers, dates, intervals, ...) drawn from typed categories, a missing
15975/// label (NaN) holding no category. They were text only
15976/// (br-frankenpandas-lztvp).
15977#[derive(Clone, Serialize, Deserialize)]
15978pub struct CategoricalIndex {
15979    labels: Vec<IndexLabel>,
15980    categories: Vec<IndexLabel>,
15981    ordered: bool,
15982    name: Option<LabelName>,
15983    #[serde(default, skip_serializing_if = "Option::is_none")]
15984    category_codes: Option<Vec<usize>>,
15985}
15986
15987impl std::fmt::Debug for CategoricalIndex {
15988    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15989        f.debug_struct("CategoricalIndex")
15990            .field("labels", &self.labels)
15991            .field("categories", &self.categories)
15992            .field("ordered", &self.ordered)
15993            .field("name", &self.name)
15994            .finish()
15995    }
15996}
15997
15998impl PartialEq for CategoricalIndex {
15999    fn eq(&self, other: &Self) -> bool {
16000        self.labels == other.labels
16001            && self.categories == other.categories
16002            && self.ordered == other.ordered
16003            && self.name == other.name
16004    }
16005}
16006
16007impl Eq for CategoricalIndex {}
16008
16009fn mark_category_rank(seen_ranks: &mut [u64], rank: usize) -> bool {
16010    let word = rank >> 6;
16011    let bit = 1u64 << (rank & 63);
16012    let is_new = seen_ranks[word] & bit == 0;
16013    if is_new {
16014        seen_ranks[word] |= bit;
16015    }
16016    is_new
16017}
16018
16019impl CategoricalIndex {
16020    fn category_codes_for(labels: &[IndexLabel], categories: &[IndexLabel]) -> Option<Vec<usize>> {
16021        let map = {
16022            let mut map: FxHashMap<&IndexLabel, usize> = FxHashMap::default();
16023            for (i, cat) in categories.iter().enumerate() {
16024                map.entry(cat).or_insert(i);
16025            }
16026            map
16027        };
16028        let mut codes = Vec::with_capacity(labels.len());
16029        for label in labels {
16030            codes.push(map.get(label).copied()?);
16031        }
16032        Some(codes)
16033    }
16034
16035    /// A label as the index holds it: any missing one is NaN.
16036    fn held(label: IndexLabel) -> IndexLabel {
16037        if label.is_missing() {
16038            IndexLabel::Null(fp_types::NullKind::NaN)
16039        } else {
16040            label
16041        }
16042    }
16043
16044    fn from_parts(
16045        labels: Vec<IndexLabel>,
16046        categories: Vec<IndexLabel>,
16047        ordered: bool,
16048        name: Option<LabelName>,
16049    ) -> Self {
16050        let category_codes = Self::category_codes_for(&labels, &categories);
16051        Self {
16052            labels,
16053            categories,
16054            ordered,
16055            name,
16056            category_codes,
16057        }
16058    }
16059
16060    /// The index of `labels`, its categories the distinct non-missing ones
16061    /// in first-seen order; a missing label is NaN.
16062    #[must_use]
16063    pub fn from_values<L: Into<IndexLabel>>(labels: Vec<L>, ordered: bool) -> Self {
16064        // First-seen dedup in O(n): a side hash set tracks membership while the
16065        // categories Vec preserves insertion order, replacing the O(n·k)
16066        // `categories.contains` linear rescan per label.
16067        let labels: Vec<IndexLabel> = labels
16068            .into_iter()
16069            .map(|label| Self::held(label.into()))
16070            .collect();
16071        let mut categories = Vec::<IndexLabel>::new();
16072        let mut ranks = FxHashMap::<&IndexLabel, usize>::default();
16073        let mut category_codes = Vec::<usize>::with_capacity(labels.len());
16074        for label in &labels {
16075            if label.is_missing() {
16076                continue;
16077            }
16078            let rank = if let Some(rank) = ranks.get(label).copied() {
16079                rank
16080            } else {
16081                let rank = categories.len();
16082                ranks.insert(label, rank);
16083                categories.push(label.clone());
16084                rank
16085            };
16086            category_codes.push(rank);
16087        }
16088        drop(ranks);
16089        let complete = category_codes.len() == labels.len();
16090        Self {
16091            labels,
16092            categories,
16093            ordered,
16094            name: None,
16095            category_codes: complete.then_some(category_codes),
16096        }
16097    }
16098
16099    /// The index of `labels` over `categories`, as pandas' constructor: a
16100    /// label outside the categories (or missing) is NaN - it was refused.
16101    /// Repeated or missing categories are pandas' errors.
16102    pub fn with_categories<L: Into<IndexLabel>, C: Into<IndexLabel>>(
16103        labels: Vec<L>,
16104        categories: Vec<C>,
16105        ordered: bool,
16106    ) -> Result<Self, IndexError> {
16107        let categories: Vec<IndexLabel> = categories.into_iter().map(Into::into).collect();
16108        if categories.iter().any(IndexLabel::is_missing) {
16109            return Err(IndexError::InvalidArgument(
16110                "Categorical categories cannot be null".to_owned(),
16111            ));
16112        }
16113        // O(n+k) membership: hash the category set once, then place each
16114        // label in original order.
16115        let mut category_map = FxHashMap::<&IndexLabel, usize>::default();
16116        let mut unique = true;
16117        for (rank, category) in categories.iter().enumerate() {
16118            unique &= category_map.insert(category, rank).is_none();
16119        }
16120        if !unique {
16121            return Err(IndexError::InvalidArgument(
16122                "Categorical categories must be unique".to_owned(),
16123            ));
16124        }
16125        let mut category_codes = Vec::<usize>::with_capacity(labels.len());
16126        let mut complete = true;
16127        let labels: Vec<IndexLabel> = labels
16128            .into_iter()
16129            .map(|label| {
16130                let label = label.into();
16131                match category_map.get(&label).copied() {
16132                    Some(rank) => {
16133                        category_codes.push(rank);
16134                        label
16135                    }
16136                    None => {
16137                        complete = false;
16138                        IndexLabel::Null(fp_types::NullKind::NaN)
16139                    }
16140                }
16141            })
16142            .collect();
16143        drop(category_map);
16144        Ok(Self {
16145            labels,
16146            categories,
16147            ordered,
16148            name: None,
16149            category_codes: complete.then_some(category_codes),
16150        })
16151    }
16152
16153    #[must_use]
16154    pub fn labels(&self) -> &[IndexLabel] {
16155        &self.labels
16156    }
16157
16158    #[must_use]
16159    pub fn categories(&self) -> &[IndexLabel] {
16160        &self.categories
16161    }
16162
16163    #[must_use]
16164    pub fn ordered(&self) -> bool {
16165        self.ordered
16166    }
16167
16168    #[must_use]
16169    pub fn len(&self) -> usize {
16170        self.labels.len()
16171    }
16172
16173    #[must_use]
16174    pub fn is_empty(&self) -> bool {
16175        self.labels.is_empty()
16176    }
16177
16178    #[must_use]
16179    pub fn name(&self) -> Option<&LabelName> {
16180        self.name.as_ref()
16181    }
16182
16183    #[must_use]
16184    pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
16185        let mut out = self.clone();
16186        out.name = Some(name.into());
16187        out
16188    }
16189
16190    #[must_use]
16191    pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
16192        let mut out = self.clone();
16193        out.name = name.map(Into::into);
16194        out
16195    }
16196
16197    #[must_use]
16198    pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
16199        self.set_names(name)
16200    }
16201
16202    #[must_use]
16203    pub fn names(&self) -> Vec<Option<String>> {
16204        vec![self.name.clone().map(String::from)]
16205    }
16206
16207    #[must_use]
16208    pub fn copy(&self) -> Self {
16209        self.clone()
16210    }
16211
16212    #[must_use]
16213    pub fn shape(&self) -> (usize,) {
16214        (self.len(),)
16215    }
16216
16217    #[must_use]
16218    pub fn size(&self) -> usize {
16219        self.len()
16220    }
16221
16222    #[must_use]
16223    pub fn empty(&self) -> bool {
16224        self.is_empty()
16225    }
16226
16227    #[must_use]
16228    pub fn dtype(&self) -> &'static str {
16229        "category"
16230    }
16231
16232    #[must_use]
16233    pub fn dtypes(&self) -> Vec<&'static str> {
16234        vec![self.dtype()]
16235    }
16236
16237    #[must_use]
16238    pub fn memory_usage(&self, deep: bool) -> usize {
16239        let fixed = fixed_width_label_memory_usage(
16240            self.labels.len().saturating_add(self.categories.len()),
16241            std::mem::size_of::<String>(),
16242        );
16243        if deep {
16244            let text_len = |label: &IndexLabel| match label {
16245                IndexLabel::Utf8(text) => text.len(),
16246                _ => 0,
16247            };
16248            fixed
16249                .saturating_add(saturating_usize_sum(self.labels.iter().map(text_len)))
16250                .saturating_add(saturating_usize_sum(self.categories.iter().map(text_len)))
16251                .saturating_add(self.name.as_ref().map_or(0, |name| name.len()))
16252        } else {
16253            fixed
16254        }
16255    }
16256
16257    #[must_use]
16258    pub fn nbytes(&self) -> usize {
16259        self.memory_usage(false)
16260    }
16261
16262    /// Which labels are missing (it was all false: no label could be).
16263    #[must_use]
16264    pub fn isna(&self) -> Vec<bool> {
16265        self.labels.iter().map(IndexLabel::is_missing).collect()
16266    }
16267
16268    #[must_use]
16269    pub fn notna(&self) -> Vec<bool> {
16270        self.labels
16271            .iter()
16272            .map(|label| !label.is_missing())
16273            .collect()
16274    }
16275
16276    /// Categorical labels cannot be differenced without converting to a
16277    /// numeric or datetime dtype, matching pandas' fail-closed behavior.
16278    pub fn diff(&self, _periods: i64) -> Result<Vec<Option<i64>>, IndexError> {
16279        Err(IndexError::InvalidArgument(
16280            "Categorical has no 'diff' method; convert to a suitable dtype before calling diff"
16281                .to_owned(),
16282        ))
16283    }
16284
16285    #[must_use]
16286    pub fn is_unique(&self) -> bool {
16287        if self.labels.len() <= 1 {
16288            return true;
16289        }
16290        if let Some(codes) = &self.category_codes {
16291            return self.labels_are_unique_by_category_codes(codes);
16292        }
16293        if self.category_rank_unique_scan_is_bounded() {
16294            return self.labels_are_unique_by_category_rank();
16295        }
16296        self.labels_are_unique_by_hash()
16297    }
16298
16299    #[must_use]
16300    pub fn has_duplicates(&self) -> bool {
16301        !self.is_unique()
16302    }
16303
16304    #[must_use]
16305    pub fn is_monotonic_increasing(&self) -> bool {
16306        if let Some(codes) = &self.category_codes {
16307            return self.category_codes_are_monotonic_increasing(codes);
16308        }
16309        self.category_ranks_are_monotonic(|prev, next| prev <= next)
16310    }
16311
16312    #[must_use]
16313    pub fn is_monotonic(&self) -> bool {
16314        self.is_monotonic_increasing()
16315    }
16316
16317    #[must_use]
16318    pub fn is_monotonic_decreasing(&self) -> bool {
16319        if let Some(codes) = &self.category_codes {
16320            return self.category_codes_are_monotonic_decreasing(codes);
16321        }
16322        self.category_ranks_are_monotonic(|prev, next| prev >= next)
16323    }
16324
16325    /// The distinct non-missing labels, as pandas' `nunique()` (dropna).
16326    #[must_use]
16327    pub fn nunique(&self) -> usize {
16328        self.distinct_count()
16329            .saturating_sub(usize::from(self.labels.iter().any(IndexLabel::is_missing)))
16330    }
16331
16332    /// The distinct labels, a missing one (all are NaN) counted once.
16333    fn distinct_count(&self) -> usize {
16334        if self.labels.len() <= 1 {
16335            return self.labels.len();
16336        }
16337        if let Some(codes) = &self.category_codes {
16338            return self.unique_label_count_by_category_codes(codes);
16339        }
16340        if self.category_rank_unique_scan_is_bounded() {
16341            return self.unique_label_count_by_category_rank();
16342        }
16343        self.unique_label_count_by_hash()
16344    }
16345
16346    #[must_use]
16347    pub fn ndim(&self) -> usize {
16348        1
16349    }
16350
16351    pub fn item(&self) -> Result<IndexLabel, IndexError> {
16352        if self.labels.len() == 1 {
16353            Ok(self.labels[0].clone())
16354        } else {
16355            Err(IndexError::InvalidArgument(format!(
16356                "item requires exactly one label, got {}",
16357                self.labels.len()
16358            )))
16359        }
16360    }
16361
16362    #[must_use]
16363    pub fn is_(&self, other: &Self) -> bool {
16364        std::ptr::eq(self, other)
16365    }
16366
16367    #[must_use]
16368    pub fn equals(&self, other: &Self) -> bool {
16369        self.labels == other.labels
16370            && self.categories == other.categories
16371            && self.ordered == other.ordered
16372    }
16373
16374    #[must_use]
16375    pub fn identical(&self, other: &Self) -> bool {
16376        self.equals(other) && self.name == other.name
16377    }
16378
16379    #[must_use]
16380    pub fn holds_integer(&self) -> bool {
16381        false
16382    }
16383
16384    #[must_use]
16385    pub fn inferred_type(&self) -> &'static str {
16386        "categorical"
16387    }
16388
16389    #[must_use]
16390    pub fn is_boolean(&self) -> bool {
16391        false
16392    }
16393
16394    #[must_use]
16395    pub fn is_categorical(&self) -> bool {
16396        true
16397    }
16398
16399    #[must_use]
16400    pub fn is_floating(&self) -> bool {
16401        false
16402    }
16403
16404    #[must_use]
16405    pub fn is_integer(&self) -> bool {
16406        false
16407    }
16408
16409    #[must_use]
16410    pub fn is_interval(&self) -> bool {
16411        false
16412    }
16413
16414    #[must_use]
16415    pub fn is_numeric(&self) -> bool {
16416        false
16417    }
16418
16419    #[must_use]
16420    pub fn is_object(&self) -> bool {
16421        false
16422    }
16423
16424    /// First-occurrence category index for each category name, matching the
16425    /// semantics of `categories.iter().position(...)` but built once in O(k).
16426    /// `or_insert` keeps the first index if `categories` somehow has dupes.
16427    fn category_index_map(&self) -> FxHashMap<&IndexLabel, usize> {
16428        let mut map: FxHashMap<&IndexLabel, usize> = FxHashMap::default();
16429        for (i, cat) in self.categories.iter().enumerate() {
16430            map.entry(cat).or_insert(i);
16431        }
16432        map
16433    }
16434
16435    fn category_rank_unique_scan_is_bounded(&self) -> bool {
16436        // Category-rank scans pay O(category_count) metadata work before the
16437        // label pass. Keep this stricter than dense integer span heuristics so
16438        // sparse category universes fall back to the O(label_count) hash path.
16439        self.categories.len() <= self.labels.len().saturating_mul(8)
16440    }
16441
16442    fn labels_are_unique_by_hash(&self) -> bool {
16443        let mut seen: FxHashSet<&IndexLabel> = FxHashSet::default();
16444        for label in &self.labels {
16445            if !seen.insert(label) {
16446                return false;
16447            }
16448        }
16449        true
16450    }
16451
16452    fn unique_label_count_by_hash(&self) -> usize {
16453        self.labels.iter().collect::<FxHashSet<_>>().len()
16454    }
16455
16456    fn labels_are_unique_by_category_rank(&self) -> bool {
16457        let map = self.category_index_map();
16458        let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
16459        let mut invalid_seen: FxHashSet<&IndexLabel> = FxHashSet::default();
16460        for label in &self.labels {
16461            if let Some(rank) = map.get(label).copied() {
16462                if !mark_category_rank(&mut seen_ranks, rank) {
16463                    return false;
16464                }
16465            } else if !invalid_seen.insert(label) {
16466                return false;
16467            }
16468        }
16469        true
16470    }
16471
16472    fn labels_are_unique_by_category_codes(&self, category_codes: &[usize]) -> bool {
16473        if category_codes.len() != self.labels.len() {
16474            return self.labels_are_unique_by_category_rank();
16475        }
16476        let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
16477        for &rank in category_codes {
16478            let Some(_) = self.categories.get(rank) else {
16479                return self.labels_are_unique_by_category_rank();
16480            };
16481            if !mark_category_rank(&mut seen_ranks, rank) {
16482                return false;
16483            }
16484        }
16485        true
16486    }
16487
16488    fn unique_label_count_by_category_rank(&self) -> usize {
16489        let map = self.category_index_map();
16490        let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
16491        let mut invalid_seen: FxHashSet<&IndexLabel> = FxHashSet::default();
16492        let mut unique = 0usize;
16493        for label in &self.labels {
16494            if let Some(rank) = map.get(label).copied() {
16495                if mark_category_rank(&mut seen_ranks, rank) {
16496                    unique += 1;
16497                }
16498            } else if invalid_seen.insert(label) {
16499                unique += 1;
16500            }
16501        }
16502        unique
16503    }
16504
16505    fn unique_label_count_by_category_codes(&self, category_codes: &[usize]) -> usize {
16506        if category_codes.len() != self.labels.len() {
16507            return self.unique_label_count_by_category_rank();
16508        }
16509        let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
16510        let mut unique = 0usize;
16511        for &rank in category_codes {
16512            let Some(_) = self.categories.get(rank) else {
16513                return self.unique_label_count_by_category_rank();
16514            };
16515            if mark_category_rank(&mut seen_ranks, rank) {
16516                unique += 1;
16517            }
16518        }
16519        unique
16520    }
16521
16522    fn unique_labels_by_hash(&self) -> Vec<IndexLabel> {
16523        let mut seen = FxHashSet::<&IndexLabel>::default();
16524        let mut uniques = Vec::<IndexLabel>::new();
16525        for label in &self.labels {
16526            if seen.insert(label) {
16527                uniques.push(label.clone());
16528            }
16529        }
16530        uniques
16531    }
16532
16533    fn unique_labels_by_category_rank(&self) -> Vec<IndexLabel> {
16534        let map = self.category_index_map();
16535        let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
16536        let mut invalid_seen: FxHashSet<&IndexLabel> = FxHashSet::default();
16537        let mut uniques =
16538            Vec::<IndexLabel>::with_capacity(self.labels.len().min(self.categories.len()));
16539        for label in &self.labels {
16540            if let Some(rank) = map.get(label).copied() {
16541                if mark_category_rank(&mut seen_ranks, rank) {
16542                    uniques.push(label.clone());
16543                }
16544            } else if invalid_seen.insert(label) {
16545                uniques.push(label.clone());
16546            }
16547        }
16548        uniques
16549    }
16550
16551    fn unique_by_category_codes(&self, category_codes: &[usize]) -> Self {
16552        if category_codes.len() != self.labels.len() {
16553            return Self::from_parts(
16554                self.unique_labels_by_category_rank(),
16555                self.categories.clone(),
16556                self.ordered,
16557                self.name.clone(),
16558            );
16559        }
16560        let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
16561        let mut unique_labels =
16562            Vec::<IndexLabel>::with_capacity(self.labels.len().min(self.categories.len()));
16563        let mut unique_category_codes =
16564            Vec::<usize>::with_capacity(self.labels.len().min(self.categories.len()));
16565        for &rank in category_codes {
16566            let Some(category) = self.categories.get(rank) else {
16567                return Self::from_parts(
16568                    self.unique_labels_by_category_rank(),
16569                    self.categories.clone(),
16570                    self.ordered,
16571                    self.name.clone(),
16572                );
16573            };
16574            if mark_category_rank(&mut seen_ranks, rank) {
16575                unique_labels.push(category.clone());
16576                unique_category_codes.push(rank);
16577            }
16578        }
16579        Self {
16580            labels: unique_labels,
16581            categories: self.categories.clone(),
16582            ordered: self.ordered,
16583            name: self.name.clone(),
16584            category_codes: Some(unique_category_codes),
16585        }
16586    }
16587
16588    fn value_counts_by_hash(&self) -> Vec<(IndexLabel, usize)> {
16589        let mut order = Vec::<&IndexLabel>::new();
16590        let mut counts = FxHashMap::<&IndexLabel, usize>::default();
16591        for label in &self.labels {
16592            let entry = counts.entry(label).or_insert_with(|| {
16593                order.push(label);
16594                0
16595            });
16596            *entry += 1;
16597        }
16598        let mut pairs: Vec<(IndexLabel, usize)> = order
16599            .iter()
16600            .map(|label| ((*label).clone(), counts[label]))
16601            .collect();
16602        pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
16603        pairs
16604    }
16605
16606    fn value_counts_by_category_rank(&self) -> Vec<(IndexLabel, usize)> {
16607        let map = self.category_index_map();
16608        let mut counts = vec![0usize; self.categories.len()];
16609        let mut invalid_counts = FxHashMap::<&IndexLabel, usize>::default();
16610        let mut order = Vec::<&IndexLabel>::new();
16611        for label in &self.labels {
16612            if let Some(rank) = map.get(label).copied() {
16613                if counts[rank] == 0 {
16614                    order.push(label);
16615                }
16616                counts[rank] += 1;
16617            } else {
16618                let entry = invalid_counts.entry(label).or_insert_with(|| {
16619                    order.push(label);
16620                    0
16621                });
16622                *entry += 1;
16623            }
16624        }
16625        let mut pairs = Vec::with_capacity(order.len());
16626        for label in order {
16627            if let Some(rank) = map.get(label).copied() {
16628                pairs.push((self.categories[rank].clone(), counts[rank]));
16629            } else {
16630                pairs.push((label.to_owned(), invalid_counts[label]));
16631            }
16632        }
16633        pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
16634        pairs
16635    }
16636
16637    fn value_counts_by_category_codes(&self, category_codes: &[usize]) -> Vec<(IndexLabel, usize)> {
16638        if category_codes.len() != self.labels.len() {
16639            return self.value_counts_by_category_rank();
16640        }
16641        let mut counts = vec![0usize; self.categories.len()];
16642        let mut order = Vec::<usize>::with_capacity(self.categories.len().min(self.labels.len()));
16643        for &rank in category_codes {
16644            let Some(count) = counts.get_mut(rank) else {
16645                return self.value_counts_by_category_rank();
16646            };
16647            if *count == 0 {
16648                order.push(rank);
16649            }
16650            *count += 1;
16651        }
16652        let mut pairs: Vec<(IndexLabel, usize)> = order
16653            .into_iter()
16654            .map(|rank| (self.categories[rank].clone(), counts[rank]))
16655            .collect();
16656        pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
16657        pairs
16658    }
16659
16660    fn factorize_by_hash(&self) -> (Vec<isize>, Self) {
16661        let mut positions = FxHashMap::<&IndexLabel, isize>::default();
16662        let mut uniques = Vec::<IndexLabel>::new();
16663        let mut codes = Vec::with_capacity(self.labels.len());
16664        for label in &self.labels {
16665            if let Some(code) = positions.get(label) {
16666                codes.push(*code);
16667            } else {
16668                let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
16669                positions.insert(label, code);
16670                uniques.push(label.clone());
16671                codes.push(code);
16672            }
16673        }
16674        let unique_index = Self::from_parts(
16675            uniques,
16676            self.categories.clone(),
16677            self.ordered,
16678            self.name.clone(),
16679        );
16680        (codes, unique_index)
16681    }
16682
16683    fn factorize_by_category_codes(&self, category_codes: &[usize]) -> (Vec<isize>, Self) {
16684        if category_codes.len() != self.labels.len() {
16685            return self.factorize_by_category_rank();
16686        }
16687        let mut rank_codes = vec![-1isize; self.categories.len()];
16688        let mut unique_labels = Vec::<IndexLabel>::new();
16689        let mut unique_category_codes = Vec::<usize>::new();
16690        let mut codes = Vec::with_capacity(category_codes.len());
16691        for &rank in category_codes {
16692            let Some(category) = self.categories.get(rank) else {
16693                return self.factorize_by_category_rank();
16694            };
16695            let mut code = rank_codes[rank];
16696            if code < 0 {
16697                code = isize::try_from(unique_labels.len()).unwrap_or(isize::MAX);
16698                rank_codes[rank] = code;
16699                unique_labels.push(category.clone());
16700                unique_category_codes.push(rank);
16701            }
16702            codes.push(code);
16703        }
16704        let unique_index = Self {
16705            labels: unique_labels,
16706            categories: self.categories.clone(),
16707            ordered: self.ordered,
16708            name: self.name.clone(),
16709            category_codes: Some(unique_category_codes),
16710        };
16711        (codes, unique_index)
16712    }
16713
16714    fn factorize_by_category_rank(&self) -> (Vec<isize>, Self) {
16715        let map = self.category_index_map();
16716        let mut rank_codes = vec![-1isize; self.categories.len()];
16717        let mut invalid_codes = FxHashMap::<&IndexLabel, isize>::default();
16718        let mut uniques = Vec::<IndexLabel>::new();
16719        let mut codes = Vec::with_capacity(self.labels.len());
16720        for label in &self.labels {
16721            if let Some(rank) = map.get(label).copied() {
16722                let mut code = rank_codes[rank];
16723                if code < 0 {
16724                    code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
16725                    rank_codes[rank] = code;
16726                    uniques.push(label.clone());
16727                }
16728                codes.push(code);
16729            } else if let Some(code) = invalid_codes.get(label) {
16730                codes.push(*code);
16731            } else {
16732                let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
16733                invalid_codes.insert(label, code);
16734                uniques.push(label.clone());
16735                codes.push(code);
16736            }
16737        }
16738        let unique_index = Self::from_parts(
16739            uniques,
16740            self.categories.clone(),
16741            self.ordered,
16742            self.name.clone(),
16743        );
16744        (codes, unique_index)
16745    }
16746
16747    fn duplicated_by_hash(&self, keep: DuplicateKeep) -> Vec<bool> {
16748        let n = self.labels.len();
16749        let mut result = vec![false; n];
16750        match keep {
16751            DuplicateKeep::First | DuplicateKeep::Last => {
16752                let mut seen: FxHashSet<&IndexLabel> =
16753                    FxHashSet::with_capacity_and_hasher(n, Default::default());
16754                let mut mark = |i: usize| {
16755                    if !seen.insert(&self.labels[i]) {
16756                        result[i] = true;
16757                    }
16758                };
16759                if matches!(keep, DuplicateKeep::First) {
16760                    for i in 0..n {
16761                        mark(i);
16762                    }
16763                } else {
16764                    for i in (0..n).rev() {
16765                        mark(i);
16766                    }
16767                }
16768            }
16769            DuplicateKeep::None => {
16770                let mut counts: FxHashMap<&IndexLabel, u32> =
16771                    FxHashMap::with_capacity_and_hasher(n, Default::default());
16772                for label in &self.labels {
16773                    *counts.entry(label).or_insert(0) += 1;
16774                }
16775                for (i, label) in self.labels.iter().enumerate() {
16776                    result[i] = counts[label] > 1;
16777                }
16778            }
16779        }
16780        result
16781    }
16782
16783    fn duplicated_by_category_rank(&self, keep: DuplicateKeep) -> Vec<bool> {
16784        let n = self.labels.len();
16785        let map = self.category_index_map();
16786        let mut result = vec![false; n];
16787        match keep {
16788            DuplicateKeep::First | DuplicateKeep::Last => {
16789                let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
16790                let mut invalid_seen: FxHashSet<&IndexLabel> = FxHashSet::default();
16791                let mut mark = |i: usize| {
16792                    let label = &self.labels[i];
16793                    let fresh = if let Some(rank) = map.get(label).copied() {
16794                        mark_category_rank(&mut seen_ranks, rank)
16795                    } else {
16796                        invalid_seen.insert(label)
16797                    };
16798                    if !fresh {
16799                        result[i] = true;
16800                    }
16801                };
16802                if matches!(keep, DuplicateKeep::First) {
16803                    for i in 0..n {
16804                        mark(i);
16805                    }
16806                } else {
16807                    for i in (0..n).rev() {
16808                        mark(i);
16809                    }
16810                }
16811            }
16812            DuplicateKeep::None => {
16813                let words = self.categories.len().div_ceil(64);
16814                let mut seen_ranks = vec![0u64; words];
16815                let mut duplicate_ranks = vec![0u64; words];
16816                let mut invalid_seen: FxHashSet<&IndexLabel> = FxHashSet::default();
16817                let mut invalid_duplicates: FxHashSet<&IndexLabel> = FxHashSet::default();
16818                for label in &self.labels {
16819                    if let Some(rank) = map.get(label).copied() {
16820                        let word = rank >> 6;
16821                        let bit = 1u64 << (rank & 63);
16822                        if seen_ranks[word] & bit == 0 {
16823                            seen_ranks[word] |= bit;
16824                        } else {
16825                            duplicate_ranks[word] |= bit;
16826                        }
16827                    } else if !invalid_seen.insert(label) {
16828                        invalid_duplicates.insert(label);
16829                    }
16830                }
16831                for (i, label) in self.labels.iter().enumerate() {
16832                    result[i] = if let Some(rank) = map.get(label).copied() {
16833                        let word = rank >> 6;
16834                        let bit = 1u64 << (rank & 63);
16835                        duplicate_ranks[word] & bit != 0
16836                    } else {
16837                        invalid_duplicates.contains(label)
16838                    };
16839                }
16840            }
16841        }
16842        result
16843    }
16844
16845    fn duplicated_by_category_codes(
16846        &self,
16847        category_codes: &[usize],
16848        keep: DuplicateKeep,
16849    ) -> Vec<bool> {
16850        if category_codes.len() != self.labels.len() {
16851            return self.duplicated_by_category_rank(keep);
16852        }
16853        let n = category_codes.len();
16854        let mut result = vec![false; n];
16855        match keep {
16856            DuplicateKeep::First | DuplicateKeep::Last => {
16857                let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
16858                let mut mark = |i: usize| {
16859                    let rank = category_codes[i];
16860                    let Some(_) = self.categories.get(rank) else {
16861                        result = self.duplicated_by_category_rank(keep);
16862                        return false;
16863                    };
16864                    if !mark_category_rank(&mut seen_ranks, rank) {
16865                        result[i] = true;
16866                    }
16867                    true
16868                };
16869                if matches!(keep, DuplicateKeep::First) {
16870                    for i in 0..n {
16871                        if !mark(i) {
16872                            return result;
16873                        }
16874                    }
16875                } else {
16876                    for i in (0..n).rev() {
16877                        if !mark(i) {
16878                            return result;
16879                        }
16880                    }
16881                }
16882            }
16883            DuplicateKeep::None => {
16884                let words = self.categories.len().div_ceil(64);
16885                let mut seen_ranks = vec![0u64; words];
16886                let mut duplicate_ranks = vec![0u64; words];
16887                for &rank in category_codes {
16888                    let Some(_) = self.categories.get(rank) else {
16889                        return self.duplicated_by_category_rank(keep);
16890                    };
16891                    let word = rank >> 6;
16892                    let bit = 1u64 << (rank & 63);
16893                    if seen_ranks[word] & bit == 0 {
16894                        seen_ranks[word] |= bit;
16895                    } else {
16896                        duplicate_ranks[word] |= bit;
16897                    }
16898                }
16899                for (i, &rank) in category_codes.iter().enumerate() {
16900                    let word = rank >> 6;
16901                    let bit = 1u64 << (rank & 63);
16902                    result[i] = duplicate_ranks[word] & bit != 0;
16903                }
16904            }
16905        }
16906        result
16907    }
16908
16909    fn category_ranks_are_monotonic(
16910        &self,
16911        mut ordered: impl FnMut(Option<usize>, Option<usize>) -> bool,
16912    ) -> bool {
16913        let map = self.category_index_map();
16914        let mut ranks = self.labels.iter().map(|label| map.get(label).copied());
16915        let Some(mut previous) = ranks.next() else {
16916            return true;
16917        };
16918        for rank in ranks {
16919            if !ordered(previous, rank) {
16920                return false;
16921            }
16922            previous = rank;
16923        }
16924        true
16925    }
16926
16927    fn category_codes_are_monotonic_increasing(&self, category_codes: &[usize]) -> bool {
16928        if category_codes.len() != self.labels.len() {
16929            return self.category_ranks_are_monotonic(|prev, next| prev <= next);
16930        }
16931        let Some((&first, rest)) = category_codes.split_first() else {
16932            return true;
16933        };
16934        if first >= self.categories.len() {
16935            return self.category_ranks_are_monotonic(|prev, next| prev <= next);
16936        }
16937        let mut previous = first;
16938        for &rank in rest {
16939            if rank >= self.categories.len() {
16940                return self.category_ranks_are_monotonic(|prev, next| prev <= next);
16941            }
16942            if previous > rank {
16943                return false;
16944            }
16945            previous = rank;
16946        }
16947        true
16948    }
16949
16950    fn category_codes_are_monotonic_decreasing(&self, category_codes: &[usize]) -> bool {
16951        if category_codes.len() != self.labels.len() {
16952            return self.category_ranks_are_monotonic(|prev, next| prev >= next);
16953        }
16954        let Some((&first, rest)) = category_codes.split_first() else {
16955            return true;
16956        };
16957        if first >= self.categories.len() {
16958            return self.category_ranks_are_monotonic(|prev, next| prev >= next);
16959        }
16960        let mut previous = first;
16961        for &rank in rest {
16962            if rank >= self.categories.len() {
16963                return self.category_ranks_are_monotonic(|prev, next| prev >= next);
16964            }
16965            if previous < rank {
16966                return false;
16967            }
16968            previous = rank;
16969        }
16970        true
16971    }
16972
16973    #[must_use]
16974    pub fn codes(&self) -> Vec<Option<usize>> {
16975        if let Some(codes) = &self.category_codes {
16976            return codes.iter().copied().map(Some).collect();
16977        }
16978        // O(n+k): hash category->index once instead of a linear
16979        // `categories.position` scan per label. First-occurrence index
16980        // preserved, so output is bit-identical.
16981        let map = self.category_index_map();
16982        self.labels
16983            .iter()
16984            .map(|label| map.get(label).copied())
16985            .collect()
16986    }
16987
16988    #[must_use]
16989    pub fn values(&self) -> Vec<IndexLabel> {
16990        self.labels.clone()
16991    }
16992
16993    #[must_use]
16994    pub fn to_list(&self) -> Vec<IndexLabel> {
16995        self.labels.clone()
16996    }
16997
16998    #[must_use]
16999    pub fn tolist(&self) -> Vec<IndexLabel> {
17000        self.to_list()
17001    }
17002
17003    #[must_use]
17004    pub fn to_numpy(&self) -> Vec<IndexLabel> {
17005        self.labels.clone()
17006    }
17007
17008    #[must_use]
17009    pub fn array(&self) -> Vec<IndexLabel> {
17010        self.labels.clone()
17011    }
17012
17013    /// The labels as a plain Index (of their own kind: text, numbers,
17014    /// intervals, ...).
17015    #[must_use]
17016    pub fn to_index(&self) -> Index {
17017        Index::new(self.labels.clone()).set_names(self.name.as_deref())
17018    }
17019
17020    /// Stringify each label, matching `pd.CategoricalIndex.format()`.
17021    #[must_use]
17022    pub fn format(&self) -> Vec<String> {
17023        self.labels.iter().map(ToString::to_string).collect()
17024    }
17025
17026    /// Whether `value` may be placed in this index: a category, or missing.
17027    fn placeable(&self, value: &IndexLabel, op: &str) -> Result<IndexLabel, IndexError> {
17028        if value.is_missing() {
17029            return Ok(IndexLabel::Null(fp_types::NullKind::NaN));
17030        }
17031        if !self.categories.contains(value) {
17032            return Err(IndexError::InvalidArgument(format!(
17033                "{op}: replacement {value:?} is not a category"
17034            )));
17035        }
17036        Ok(value.clone())
17037    }
17038
17039    /// Replace positions where `cond` is `false` with `other`, matching
17040    /// `pd.CategoricalIndex.where(cond, other)`. `other` must be a
17041    /// category, or missing (pandas' default).
17042    pub fn r#where(&self, cond: &[bool], other: &IndexLabel) -> Result<Self, IndexError> {
17043        if cond.len() != self.labels.len() {
17044            return Err(IndexError::LengthMismatch {
17045                expected: self.labels.len(),
17046                actual: cond.len(),
17047                context: "where: cond length must match index length".to_owned(),
17048            });
17049        }
17050        let other = self.placeable(other, "where")?;
17051        let labels: Vec<IndexLabel> = self
17052            .labels
17053            .iter()
17054            .zip(cond.iter())
17055            .map(
17056                |(label, &keep)| {
17057                    if keep { label.clone() } else { other.clone() }
17058                },
17059            )
17060            .collect();
17061        Ok(Self::from_parts(
17062            labels,
17063            self.categories.clone(),
17064            self.ordered,
17065            self.name.clone(),
17066        ))
17067    }
17068
17069    /// Replace positions where `mask` is `true` with `value`, matching
17070    /// `pd.CategoricalIndex.putmask(mask, value)`.
17071    pub fn putmask(&self, mask: &[bool], value: &IndexLabel) -> Result<Self, IndexError> {
17072        if mask.len() != self.labels.len() {
17073            return Err(IndexError::LengthMismatch {
17074                expected: self.labels.len(),
17075                actual: mask.len(),
17076                context: "putmask: mask length must match index length".to_owned(),
17077            });
17078        }
17079        let value = self.placeable(value, "putmask")?;
17080        let labels: Vec<IndexLabel> = self
17081            .labels
17082            .iter()
17083            .zip(mask.iter())
17084            .map(|(label, &replace)| {
17085                if replace {
17086                    value.clone()
17087                } else {
17088                    label.clone()
17089                }
17090            })
17091            .collect();
17092        Ok(Self::from_parts(
17093            labels,
17094            self.categories.clone(),
17095            self.ordered,
17096            self.name.clone(),
17097        ))
17098    }
17099
17100    /// Alias for [`isna`](Self::isna), matching `pd.CategoricalIndex.isnull()`.
17101    #[must_use]
17102    pub fn isnull(&self) -> Vec<bool> {
17103        self.isna()
17104    }
17105
17106    /// Alias for [`notna`](Self::notna), matching `pd.CategoricalIndex.notnull()`.
17107    #[must_use]
17108    pub fn notnull(&self) -> Vec<bool> {
17109        self.notna()
17110    }
17111
17112    /// Whether any label is missing, matching `pd.CategoricalIndex.hasnans`
17113    /// (it was always false: no label could be missing).
17114    #[must_use]
17115    pub fn hasnans(&self) -> bool {
17116        self.labels.iter().any(IndexLabel::is_missing)
17117    }
17118
17119    /// Drop missing positions, matching `pd.CategoricalIndex.dropna()`.
17120    #[must_use]
17121    pub fn dropna(&self) -> Self {
17122        Self::from_parts(
17123            self.labels
17124                .iter()
17125                .filter(|label| !label.is_missing())
17126                .cloned()
17127                .collect(),
17128            self.categories.clone(),
17129            self.ordered,
17130            self.name.clone(),
17131        )
17132    }
17133
17134    /// Fill missing positions with `value`, matching
17135    /// `pd.CategoricalIndex.fillna(value)`: with nothing missing the index is
17136    /// unchanged; otherwise `value` must be a category (it was ignored).
17137    pub fn fillna(&self, value: &IndexLabel) -> Result<Self, IndexError> {
17138        if !self.hasnans() {
17139            return Ok(self.clone());
17140        }
17141        let value = self.placeable(value, "fillna")?;
17142        Ok(Self::from_parts(
17143            self.labels
17144                .iter()
17145                .map(|label| {
17146                    if label.is_missing() {
17147                        value.clone()
17148                    } else {
17149                        label.clone()
17150                    }
17151                })
17152                .collect(),
17153            self.categories.clone(),
17154            self.ordered,
17155            self.name.clone(),
17156        ))
17157    }
17158
17159    /// Mark the categorical as ordered, matching
17160    /// `pd.CategoricalIndex.as_ordered()`.
17161    #[must_use]
17162    pub fn as_ordered(&self) -> Self {
17163        let mut out = self.clone();
17164        out.ordered = true;
17165        out
17166    }
17167
17168    /// Mark the categorical as unordered, matching
17169    /// `pd.CategoricalIndex.as_unordered()`.
17170    #[must_use]
17171    pub fn as_unordered(&self) -> Self {
17172        let mut out = self.clone();
17173        out.ordered = false;
17174        out
17175    }
17176
17177    /// Extend the categories list with new entries, matching
17178    /// `pd.CategoricalIndex.add_categories(new)`. Rejects when any new
17179    /// category is already present.
17180    pub fn add_categories<L: Into<IndexLabel>>(&self, new: Vec<L>) -> Result<Self, IndexError> {
17181        let new: Vec<IndexLabel> = new.into_iter().map(Into::into).collect();
17182        // O(k_existing + k_new): hash the existing categories once instead of a
17183        // linear `categories.contains` scan per new entry. First clashing entry
17184        // (in `new` order) is still the one reported.
17185        let existing: FxHashSet<&IndexLabel> = self.categories.iter().collect();
17186        for cat in &new {
17187            if existing.contains(cat) {
17188                return Err(IndexError::InvalidArgument(format!(
17189                    "add_categories: {cat:?} is already a category"
17190                )));
17191            }
17192        }
17193        let mut categories = self.categories.clone();
17194        categories.extend(new);
17195        Ok(Self::from_parts(
17196            self.labels.clone(),
17197            categories,
17198            self.ordered,
17199            self.name.clone(),
17200        ))
17201    }
17202
17203    /// Drop categories from the list, matching
17204    /// `pd.CategoricalIndex.remove_categories(removals)`: each must be a
17205    /// category, and a label of a removed one becomes NaN (it was refused,
17206    /// no label could be missing; lztvp).
17207    pub fn remove_categories(&self, removals: &[IndexLabel]) -> Result<Self, IndexError> {
17208        let category_set: FxHashSet<&IndexLabel> = self.categories.iter().collect();
17209        for cat in removals {
17210            if !category_set.contains(cat) {
17211                return Err(IndexError::InvalidArgument(format!(
17212                    "remove_categories: {cat:?} is not a category"
17213                )));
17214            }
17215        }
17216        let removals_set: FxHashSet<&IndexLabel> = removals.iter().collect();
17217        let categories: Vec<IndexLabel> = self
17218            .categories
17219            .iter()
17220            .filter(|cat| !removals_set.contains(cat))
17221            .cloned()
17222            .collect();
17223        Ok(self.recategorized(categories, self.ordered))
17224    }
17225
17226    /// This index over `categories`: a label no longer among them is NaN,
17227    /// as pandas' `set_categories` / `remove_categories`.
17228    fn recategorized(&self, categories: Vec<IndexLabel>, ordered: bool) -> Self {
17229        let kept: FxHashSet<&IndexLabel> = categories.iter().collect();
17230        let labels: Vec<IndexLabel> = self
17231            .labels
17232            .iter()
17233            .map(|label| {
17234                if kept.contains(label) {
17235                    label.clone()
17236                } else {
17237                    IndexLabel::Null(fp_types::NullKind::NaN)
17238                }
17239            })
17240            .collect();
17241        drop(kept);
17242        Self::from_parts(labels, categories, ordered, self.name.clone())
17243    }
17244
17245    /// Narrow categories to the set of labels actually present, matching
17246    /// `pd.CategoricalIndex.remove_unused_categories()`.
17247    #[must_use]
17248    pub fn remove_unused_categories(&self) -> Self {
17249        let used: FxHashSet<&IndexLabel> = self.labels.iter().collect();
17250        let categories: Vec<IndexLabel> = self
17251            .categories
17252            .iter()
17253            .filter(|cat| used.contains(cat))
17254            .cloned()
17255            .collect();
17256        Self::from_parts(
17257            self.labels.clone(),
17258            categories,
17259            self.ordered,
17260            self.name.clone(),
17261        )
17262    }
17263
17264    /// Replace the categories list, matching
17265    /// `pd.CategoricalIndex.set_categories(new_categories)`: a label not
17266    /// among the new categories becomes NaN (it was refused; lztvp).
17267    pub fn set_categories<L: Into<IndexLabel>>(
17268        &self,
17269        new_categories: Vec<L>,
17270    ) -> Result<Self, IndexError> {
17271        let new_categories: Vec<IndexLabel> = new_categories.into_iter().map(Into::into).collect();
17272        let mut seen = FxHashSet::<&IndexLabel>::default();
17273        if !new_categories.iter().all(|cat| seen.insert(cat)) {
17274            return Err(IndexError::InvalidArgument(
17275                "Categorical categories must be unique".to_owned(),
17276            ));
17277        }
17278        drop(seen);
17279        Ok(self.recategorized(new_categories, self.ordered))
17280    }
17281
17282    /// Rename categories pos-by-pos, matching
17283    /// `pd.CategoricalIndex.rename_categories(new)`. Rejects when the
17284    /// new list has a different length; a missing label stays missing.
17285    pub fn rename_categories<L: Into<IndexLabel>>(&self, new: Vec<L>) -> Result<Self, IndexError> {
17286        let new: Vec<IndexLabel> = new.into_iter().map(Into::into).collect();
17287        if new.len() != self.categories.len() {
17288            return Err(IndexError::InvalidArgument(format!(
17289                "rename_categories: expected {} new names, got {}",
17290                self.categories.len(),
17291                new.len()
17292            )));
17293        }
17294        let mapping: FxHashMap<&IndexLabel, &IndexLabel> =
17295            self.categories.iter().zip(new.iter()).collect();
17296        let labels: Vec<IndexLabel> = self
17297            .labels
17298            .iter()
17299            .map(|label| {
17300                mapping
17301                    .get(label)
17302                    .map_or_else(|| label.clone(), |to| (*to).clone())
17303            })
17304            .collect();
17305        drop(mapping);
17306        Ok(Self::from_parts(
17307            labels,
17308            new,
17309            self.ordered,
17310            self.name.clone(),
17311        ))
17312    }
17313
17314    /// Reorder the categories list, matching
17315    /// `pd.CategoricalIndex.reorder_categories(new, ordered)`. Rejects
17316    /// when the new list is not a permutation of the existing categories.
17317    pub fn reorder_categories<L: Into<IndexLabel>>(
17318        &self,
17319        new: Vec<L>,
17320        ordered: bool,
17321    ) -> Result<Self, IndexError> {
17322        let new: Vec<IndexLabel> = new.into_iter().map(Into::into).collect();
17323        if new.len() != self.categories.len() {
17324            return Err(IndexError::InvalidArgument(format!(
17325                "reorder_categories: expected {} categories, got {}",
17326                self.categories.len(),
17327                new.len()
17328            )));
17329        }
17330        let existing: FxHashSet<&IndexLabel> = self.categories.iter().collect();
17331        for cat in &new {
17332            if !existing.contains(cat) {
17333                return Err(IndexError::InvalidArgument(format!(
17334                    "reorder_categories: {cat:?} is not an existing category"
17335                )));
17336            }
17337        }
17338        let new_set: FxHashSet<&IndexLabel> = new.iter().collect();
17339        if new_set.len() != new.len() {
17340            return Err(IndexError::InvalidArgument(
17341                "reorder_categories: new categories contain duplicates".to_owned(),
17342            ));
17343        }
17344        Ok(Self::from_parts(
17345            self.labels.clone(),
17346            new,
17347            ordered,
17348            self.name.clone(),
17349        ))
17350    }
17351
17352    /// Convert to a flat [`Index`] of utf8 labels, matching
17353    /// `pd.CategoricalIndex.to_flat_index()`.
17354    #[must_use]
17355    pub fn to_flat_index(&self) -> Index {
17356        self.to_index()
17357    }
17358
17359    /// String accessor for categorical string labels.
17360    #[must_use]
17361    pub fn r#str(&self) -> IndexStringAccessor<'_> {
17362        IndexStringAccessor::owned(self.to_flat_index())
17363    }
17364
17365    /// One-column row materialization, matching `pd.CategoricalIndex.to_frame(index=False)`.
17366    #[must_use]
17367    pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
17368        self.to_flat_index().to_frame()
17369    }
17370
17371    /// Series-shaped materialization using category labels as both index and values.
17372    #[must_use]
17373    pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
17374        self.to_flat_index().to_series()
17375    }
17376
17377    /// Whether any category label coerces to true.
17378    #[must_use]
17379    pub fn any(&self) -> bool {
17380        self.to_flat_index().any()
17381    }
17382
17383    /// Whether all category labels coerce to true.
17384    #[must_use]
17385    pub fn all(&self) -> bool {
17386        self.to_flat_index().all()
17387    }
17388
17389    /// Get labels for a level. CategoricalIndex is flat and only accepts level 0.
17390    pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
17391        self.to_flat_index().get_level_values(level)
17392    }
17393
17394    /// Drop a level. CategoricalIndex is flat, so removing its only level is invalid.
17395    pub fn droplevel(&self, level: usize) -> Result<Index, IndexError> {
17396        self.to_flat_index().droplevel(level)
17397    }
17398
17399    /// Group equal category labels into position buckets.
17400    #[must_use]
17401    pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
17402        self.to_flat_index().groupby()
17403    }
17404
17405    /// Apply a function to each category label, returning a flat Index.
17406    #[must_use]
17407    pub fn map<F>(&self, func: F) -> Index
17408    where
17409        F: Fn(&IndexLabel) -> IndexLabel,
17410    {
17411        self.to_flat_index().map(func)
17412    }
17413
17414    /// Cast category labels to a pandas dtype string, returning a flat Index.
17415    pub fn astype(&self, dtype: &str) -> Result<Index, IndexError> {
17416        self.to_flat_index().astype(dtype)
17417    }
17418
17419    /// Nearest preceding-or-equal category label lookup.
17420    #[must_use]
17421    pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
17422        self.to_flat_index().asof(key)
17423    }
17424
17425    /// Locate nearest preceding-or-equal category positions for each target label.
17426    #[must_use]
17427    pub fn asof_locs(&self, where_index: &Index, mask: Option<&[bool]>) -> Vec<Option<usize>> {
17428        self.to_flat_index().asof_locs(where_index, mask)
17429    }
17430
17431    /// Drop category labels, returning a flat Index.
17432    #[must_use]
17433    pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Index {
17434        self.to_flat_index().drop(labels_to_drop)
17435    }
17436
17437    /// Join category labels with another flat Index.
17438    pub fn join(&self, other: &Index, how: &str) -> Result<Index, IndexError> {
17439        self.to_flat_index().join(other, how)
17440    }
17441
17442    /// Sort category labels and return the positional sorter.
17443    #[must_use]
17444    pub fn sortlevel(&self) -> (Index, Vec<usize>) {
17445        self.to_flat_index().sortlevel()
17446    }
17447
17448    /// Set the index name, matching `pd.CategoricalIndex.rename(name)`.
17449    #[must_use]
17450    pub fn rename(&self, name: &str) -> Self {
17451        self.set_name(name)
17452    }
17453
17454    /// Returns a clone, matching `pd.CategoricalIndex.view()`.
17455    #[must_use]
17456    pub fn view(&self) -> Self {
17457        self.clone()
17458    }
17459
17460    /// Identity transpose for a 1D index, matching
17461    /// `pd.CategoricalIndex.transpose()`.
17462    #[must_use]
17463    pub fn transpose(&self) -> Self {
17464        self.clone()
17465    }
17466
17467    /// Alias for `transpose`, matching `pd.CategoricalIndex.T`.
17468    #[allow(non_snake_case)]
17469    #[must_use]
17470    pub fn T(&self) -> Self {
17471        self.transpose()
17472    }
17473
17474    /// Flatten the labels, matching `pd.CategoricalIndex.ravel()`.
17475    #[must_use]
17476    pub fn ravel(&self) -> Vec<IndexLabel> {
17477        self.labels.clone()
17478    }
17479
17480    /// Number of levels, matching `pd.CategoricalIndex.nlevels`. Always `1`.
17481    #[must_use]
17482    pub fn nlevels(&self) -> usize {
17483        1
17484    }
17485
17486    /// Identity dtype-reinference, matching
17487    /// `pd.CategoricalIndex.infer_objects()`.
17488    #[must_use]
17489    pub fn infer_objects(&self) -> Self {
17490        self.clone()
17491    }
17492
17493    /// Binary-search insertion position, matching
17494    /// `pd.CategoricalIndex.searchsorted(value, side)`. Forwarded through
17495    /// the labels' flat Index.
17496    pub fn searchsorted(&self, value: &IndexLabel, side: &str) -> Result<usize, IndexError> {
17497        self.to_index().searchsorted(value, side)
17498    }
17499
17500    /// Find positions of `[start, end]` for a label slice, matching
17501    /// `pd.CategoricalIndex.slice_locs(start, end)`. Requires labels to
17502    /// be sorted (so the searchsorted result lines up with the slice
17503    /// boundary).
17504    pub fn slice_locs(
17505        &self,
17506        start: &IndexLabel,
17507        end: &IndexLabel,
17508    ) -> Result<(usize, usize), IndexError> {
17509        let labels_sorted = self.labels.windows(2).all(|w| w[0] <= w[1]);
17510        if !labels_sorted {
17511            return Err(IndexError::InvalidArgument(
17512                "slice_locs requires a CategoricalIndex with labels sorted lexicographically"
17513                    .to_owned(),
17514            ));
17515        }
17516        let left = self.searchsorted(start, "left")?;
17517        let right = self.searchsorted(end, "right")?;
17518        Ok((left, right))
17519    }
17520
17521    /// Half-open positional range for a label slice, matching
17522    /// `pd.CategoricalIndex.slice_indexer(start, end)`.
17523    pub fn slice_indexer(
17524        &self,
17525        start: &IndexLabel,
17526        end: &IndexLabel,
17527    ) -> Result<std::ops::Range<usize>, IndexError> {
17528        let (l, r) = self.slice_locs(start, end)?;
17529        Ok(l..r)
17530    }
17531
17532    fn set_op_via_string<F>(&self, other: &Self, op: F) -> Self
17533    where
17534        F: FnOnce(Vec<&IndexLabel>, Vec<&IndexLabel>) -> Vec<IndexLabel>,
17535    {
17536        let labels = op(self.labels.iter().collect(), other.labels.iter().collect());
17537        // Dedup the union of categories with a seen-set instead of an O(k)
17538        // `Vec::contains` per label (O(n·k) for high-cardinality categoricals).
17539        // `seen` borrows self.categories + labels (both stable) — never the
17540        // growing `categories` Vec — so a label is pushed iff it is neither an
17541        // existing category nor already pushed this pass: identical first-seen
17542        // order and dedup to the linear scan.
17543        let mut categories: Vec<IndexLabel> = self.categories.clone();
17544        let mut seen: FxHashSet<&IndexLabel> = self.categories.iter().collect();
17545        for label in &labels {
17546            if !label.is_missing() && seen.insert(label) {
17547                categories.push(label.clone());
17548            }
17549        }
17550        Self::from_parts(
17551            labels,
17552            categories,
17553            self.ordered,
17554            if self.name == other.name {
17555                self.name.clone()
17556            } else {
17557                None
17558            },
17559        )
17560    }
17561
17562    /// Labels in both indexes (first-seen order from self), matching
17563    /// `pd.CategoricalIndex.intersection(other)`.
17564    #[must_use]
17565    pub fn intersection(&self, other: &Self) -> Self {
17566        self.set_op_via_string(other, |left, right| {
17567            let right_set: FxHashSet<&&IndexLabel> = right.iter().collect();
17568            let mut seen = FxHashSet::<&IndexLabel>::default();
17569            left.into_iter()
17570                .filter(|label| right_set.contains(label) && seen.insert(label))
17571                .cloned()
17572                .collect()
17573        })
17574    }
17575
17576    /// Self labels then other labels not seen, matching
17577    /// `pd.CategoricalIndex.union(other)`.
17578    #[must_use]
17579    pub fn union(&self, other: &Self) -> Self {
17580        self.set_op_via_string(other, |left, right| {
17581            let mut seen = FxHashSet::<&IndexLabel>::default();
17582            left.into_iter()
17583                .chain(right)
17584                .filter(|label| seen.insert(label))
17585                .cloned()
17586                .collect()
17587        })
17588    }
17589
17590    /// Labels in either but not both, matching
17591    /// `pd.CategoricalIndex.symmetric_difference(other)`.
17592    #[must_use]
17593    pub fn symmetric_difference(&self, other: &Self) -> Self {
17594        self.set_op_via_string(other, |left, right| {
17595            let left_set: FxHashSet<&&IndexLabel> = left.iter().collect();
17596            let right_set: FxHashSet<&&IndexLabel> = right.iter().collect();
17597            let mut seen = FxHashSet::<&IndexLabel>::default();
17598            let mut out = Vec::<IndexLabel>::new();
17599            for label in &left {
17600                if !right_set.contains(label) && seen.insert(*label) {
17601                    out.push((*label).clone());
17602                }
17603            }
17604            for label in &right {
17605                if !left_set.contains(label) && seen.insert(*label) {
17606                    out.push((*label).clone());
17607                }
17608            }
17609            out
17610        })
17611    }
17612
17613    /// Self labels not in other, matching
17614    /// `pd.CategoricalIndex.difference(other)`.
17615    #[must_use]
17616    pub fn difference(&self, other: &Self) -> Self {
17617        // Per br-frankenpandas-6r1lq: difference preserves self.name (not
17618        // shared_name like set_op_via_string applies for union/intersection).
17619        let mut out = self.set_op_via_string(other, |left, right| {
17620            let right_set: FxHashSet<&&IndexLabel> = right.iter().collect();
17621            let mut seen = FxHashSet::<&IndexLabel>::default();
17622            left.into_iter()
17623                .filter(|label| !right_set.contains(label) && seen.insert(label))
17624                .cloned()
17625                .collect()
17626        });
17627        out.name = self.name.clone();
17628        out
17629    }
17630
17631    /// Sort labels ascending, matching `pd.CategoricalIndex.sort_values()`.
17632    /// `ordered=true` sorts by category position; `ordered=false` sorts
17633    /// lexicographically. Categories list and ordered flag are preserved.
17634    #[must_use]
17635    pub fn sort_values(&self) -> Self {
17636        let positions = self.argsort();
17637        let labels: Vec<IndexLabel> = positions.iter().map(|&p| self.labels[p].clone()).collect();
17638        Self::from_parts(
17639            labels,
17640            self.categories.clone(),
17641            self.ordered,
17642            self.name.clone(),
17643        )
17644    }
17645
17646    /// Alias for `sort_values`, matching `pd.CategoricalIndex.sort()`.
17647    #[must_use]
17648    pub fn sort(&self) -> Self {
17649        self.sort_values()
17650    }
17651
17652    /// Positions that would sort labels ascending, matching
17653    /// `pd.CategoricalIndex.argsort()`.
17654    ///
17655    /// pandas sorts a Categorical by its **category codes** — the position of
17656    /// each label within `categories` — for both ordered and unordered
17657    /// categoricals (`Categorical._values_for_argsort` returns `self.codes`),
17658    /// NOT lexicographically by the label text. So categories `[b, a, c]` sort
17659    /// before-`a` because `b` has code 0. The sort is stable, so equal-code
17660    /// ties keep their original order; a missing label (no code) sorts last,
17661    /// as pandas' na_position='last'.
17662    #[must_use]
17663    pub fn argsort(&self) -> Vec<usize> {
17664        let map = self.category_index_map();
17665        let mut positions: Vec<usize> = (0..self.labels.len()).collect();
17666        positions.sort_by_key(|&i| map.get(&self.labels[i]).copied().unwrap_or(usize::MAX));
17667        positions
17668    }
17669
17670    /// Concatenate with another CategoricalIndex, matching
17671    /// `pd.CategoricalIndex.append(other)`. Categories merge
17672    /// (other-only categories are appended) and the index name is
17673    /// preserved when both operands share it.
17674    #[must_use]
17675    pub fn append(&self, other: &Self) -> Self {
17676        let mut labels = self.labels.clone();
17677        labels.extend_from_slice(&other.labels);
17678        // Union categories with a seen-set, not O(k) `Vec::contains` per entry
17679        // (see set_op_via_string). `seen` borrows self/other categories, never
17680        // the growing `categories` Vec; identical first-seen order + dedup.
17681        let mut categories = self.categories.clone();
17682        let mut seen: FxHashSet<&IndexLabel> = self.categories.iter().collect();
17683        for cat in &other.categories {
17684            if seen.insert(cat) {
17685                categories.push(cat.clone());
17686            }
17687        }
17688        let name = if self.name == other.name {
17689            self.name.clone()
17690        } else {
17691            None
17692        };
17693        Self::from_parts(labels, categories, self.ordered && other.ordered, name)
17694    }
17695
17696    /// Remove the label at the given position, matching
17697    /// `pd.CategoricalIndex.delete(loc)`. OOB raises.
17698    pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
17699        if loc >= self.labels.len() {
17700            return Err(IndexError::OutOfBounds {
17701                position: loc,
17702                length: self.labels.len(),
17703            });
17704        }
17705        let mut labels = self.labels.clone();
17706        labels.remove(loc);
17707        Ok(Self::from_parts(
17708            labels,
17709            self.categories.clone(),
17710            self.ordered,
17711            self.name.clone(),
17712        ))
17713    }
17714
17715    /// Insert `value` at position `loc`, matching
17716    /// `pd.CategoricalIndex.insert(loc, value)`. The value must be a
17717    /// category or missing; OOB and not-a-category raise.
17718    pub fn insert(&self, loc: usize, value: &IndexLabel) -> Result<Self, IndexError> {
17719        if loc > self.labels.len() {
17720            return Err(IndexError::OutOfBounds {
17721                position: loc,
17722                length: self.labels.len(),
17723            });
17724        }
17725        let value = self.placeable(value, "insert")?;
17726        let mut labels = self.labels.clone();
17727        labels.insert(loc, value);
17728        Ok(Self::from_parts(
17729            labels,
17730            self.categories.clone(),
17731            self.ordered,
17732            self.name.clone(),
17733        ))
17734    }
17735
17736    /// Repeat each label `repeats` times, matching
17737    /// `pd.CategoricalIndex.repeat(repeats)`.
17738    #[must_use]
17739    pub fn repeat(&self, repeats: usize) -> Self {
17740        let mut labels = Vec::with_capacity(repeat_output_capacity(self.labels.len(), repeats));
17741        for label in &self.labels {
17742            for _ in 0..repeats {
17743                labels.push(label.clone());
17744            }
17745        }
17746        Self::from_parts(
17747            labels,
17748            self.categories.clone(),
17749            self.ordered,
17750            self.name.clone(),
17751        )
17752    }
17753
17754    /// Pick labels at the given positions, matching
17755    /// `pd.CategoricalIndex.take(positions)`. Out-of-bounds positions
17756    /// raise [`IndexError::OutOfBounds`].
17757    pub fn take(&self, positions: &[usize]) -> Result<Self, IndexError> {
17758        for &p in positions {
17759            if p >= self.labels.len() {
17760                return Err(IndexError::OutOfBounds {
17761                    position: p,
17762                    length: self.labels.len(),
17763                });
17764            }
17765        }
17766        let labels: Vec<IndexLabel> = positions.iter().map(|&p| self.labels[p].clone()).collect();
17767        Ok(Self::from_parts(
17768            labels,
17769            self.categories.clone(),
17770            self.ordered,
17771            self.name.clone(),
17772        ))
17773    }
17774
17775    /// Per-position membership mask, matching
17776    /// `pd.CategoricalIndex.isin(values)`.
17777    #[must_use]
17778    pub fn isin(&self, values: &[IndexLabel]) -> Vec<bool> {
17779        let needle: FxHashSet<&IndexLabel> = values.iter().collect();
17780        self.labels.iter().map(|l| needle.contains(l)).collect()
17781    }
17782
17783    /// Locate every position matching each target, matching
17784    /// `pd.CategoricalIndex.get_indexer_non_unique(targets)`.
17785    #[must_use]
17786    pub fn get_indexer_non_unique(&self, targets: &[IndexLabel]) -> (Vec<isize>, Vec<usize>) {
17787        let mut by_value = FxHashMap::<&IndexLabel, Vec<usize>>::default();
17788        for (i, label) in self.labels.iter().enumerate() {
17789            by_value.entry(label).or_default().push(i);
17790        }
17791        let mut positions = Vec::<isize>::new();
17792        let mut missing = Vec::<usize>::new();
17793        for (idx, target) in targets.iter().enumerate() {
17794            if let Some(matches) = by_value.get(target) {
17795                positions.extend(
17796                    matches
17797                        .iter()
17798                        .map(|p| isize::try_from(*p).unwrap_or(isize::MAX)),
17799                );
17800            } else {
17801                positions.push(-1);
17802                missing.push(idx);
17803            }
17804        }
17805        (positions, missing)
17806    }
17807
17808    /// Locate each label in `targets`, matching
17809    /// `pd.CategoricalIndex.get_indexer(targets)`.
17810    #[must_use]
17811    pub fn get_indexer(&self, targets: &[IndexLabel]) -> Vec<isize> {
17812        let mut positions = FxHashMap::<&IndexLabel, isize>::default();
17813        for (i, label) in self.labels.iter().enumerate() {
17814            positions
17815                .entry(label)
17816                .or_insert_with(|| isize::try_from(i).unwrap_or(isize::MAX));
17817        }
17818        targets
17819            .iter()
17820            .map(|t| positions.get(t).copied().unwrap_or(-1))
17821            .collect()
17822    }
17823
17824    /// Alias for [`get_indexer`](Self::get_indexer), matching
17825    /// `pd.CategoricalIndex.get_indexer_for(targets)`.
17826    #[must_use]
17827    pub fn get_indexer_for(&self, targets: &[IndexLabel]) -> Vec<isize> {
17828        self.get_indexer(targets)
17829    }
17830
17831    /// First position of `value`, matching
17832    /// `pd.CategoricalIndex.get_loc(value)`.
17833    pub fn get_loc(&self, value: &IndexLabel) -> Result<usize, IndexError> {
17834        self.labels.iter().position(|l| l == value).ok_or_else(|| {
17835            IndexError::InvalidArgument(format!("get_loc: {value:?} not in CategoricalIndex"))
17836        })
17837    }
17838
17839    /// Position of the maximum label, matching
17840    /// `pd.CategoricalIndex.argmax()`. ordered=true uses category
17841    /// position; unordered uses lexicographic ordering. Empty raises
17842    /// pandas-style "attempt to get argmax of an empty sequence".
17843    pub fn argmax(&self) -> Result<usize, IndexError> {
17844        if self.labels.is_empty() {
17845            return Err(IndexError::InvalidArgument(
17846                "attempt to get argmax of an empty sequence".to_owned(),
17847            ));
17848        }
17849        self.extreme_position(true).ok_or_else(|| {
17850            IndexError::InvalidArgument("attempt to get argmax of an empty sequence".to_owned())
17851        })
17852    }
17853
17854    /// The position of the first largest (`largest`) or smallest label,
17855    /// missing labels skipped: by category position when ordered, by the
17856    /// labels themselves otherwise. None when no label is present.
17857    fn extreme_position(&self, largest: bool) -> Option<usize> {
17858        let map = self.category_index_map();
17859        let mut best: Option<usize> = None;
17860        for (i, label) in self.labels.iter().enumerate() {
17861            if label.is_missing() {
17862                continue;
17863            }
17864            let better = best.is_none_or(|at| {
17865                let current = &self.labels[at];
17866                let order = if self.ordered {
17867                    map.get(label).cmp(&map.get(current))
17868                } else {
17869                    label.cmp(current)
17870                };
17871                if largest {
17872                    order.is_gt()
17873                } else {
17874                    order.is_lt()
17875                }
17876            });
17877            if better {
17878                best = Some(i);
17879            }
17880        }
17881        best
17882    }
17883
17884    /// Position of the minimum label, matching
17885    /// `pd.CategoricalIndex.argmin()`. Same ordering rules as argmax.
17886    pub fn argmin(&self) -> Result<usize, IndexError> {
17887        if self.labels.is_empty() {
17888            return Err(IndexError::InvalidArgument(
17889                "attempt to get argmin of an empty sequence".to_owned(),
17890            ));
17891        }
17892        self.extreme_position(false).ok_or_else(|| {
17893            IndexError::InvalidArgument("attempt to get argmin of an empty sequence".to_owned())
17894        })
17895    }
17896
17897    /// Smallest label in category order when ordered, by the labels
17898    /// themselves when unordered, matching `pd.CategoricalIndex.min()`
17899    /// (missing labels skipped). None when no label is present.
17900    #[must_use]
17901    pub fn min(&self) -> Option<&IndexLabel> {
17902        self.extreme_position(false).map(|at| &self.labels[at])
17903    }
17904
17905    /// Largest label, matching `pd.CategoricalIndex.max()`.
17906    #[must_use]
17907    pub fn max(&self) -> Option<&IndexLabel> {
17908        self.extreme_position(true).map(|at| &self.labels[at])
17909    }
17910
17911    /// First-seen unique labels, matching `pd.CategoricalIndex.unique()`.
17912    /// Categories are preserved (not narrowed to seen labels) and the
17913    /// ordered flag rolls through. The result keeps the index name.
17914    #[must_use]
17915    pub fn unique(&self) -> Self {
17916        if let Some(codes) = &self.category_codes
17917            && self.category_rank_unique_scan_is_bounded()
17918        {
17919            return self.unique_by_category_codes(codes);
17920        }
17921        let labels = if self.category_rank_unique_scan_is_bounded() {
17922            self.unique_labels_by_category_rank()
17923        } else {
17924            self.unique_labels_by_hash()
17925        };
17926        Self::from_parts(
17927            labels,
17928            self.categories.clone(),
17929            self.ordered,
17930            self.name.clone(),
17931        )
17932    }
17933
17934    /// Per-position duplicate mask, matching
17935    /// `pd.CategoricalIndex.duplicated(keep)`.
17936    #[must_use]
17937    pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
17938        if let Some(codes) = &self.category_codes {
17939            if self.category_rank_unique_scan_is_bounded() {
17940                return self.duplicated_by_category_codes(codes, keep);
17941            }
17942            return self.duplicated_by_hash(keep);
17943        }
17944        if self.category_rank_unique_scan_is_bounded() {
17945            return self.duplicated_by_category_rank(keep);
17946        }
17947        self.duplicated_by_hash(keep)
17948    }
17949
17950    /// Drop duplicate labels (keep first), matching
17951    /// `pd.CategoricalIndex.drop_duplicates()`. Categories and ordered
17952    /// flag are preserved.
17953    #[must_use]
17954    pub fn drop_duplicates(&self) -> Self {
17955        self.unique()
17956    }
17957
17958    /// Value counts, matching `pd.CategoricalIndex.value_counts()`: the
17959    /// present labels' counts, missing ones left out (dropna).
17960    #[must_use]
17961    pub fn value_counts(&self) -> Vec<(IndexLabel, usize)> {
17962        let mut pairs = if let Some(codes) = &self.category_codes {
17963            self.value_counts_by_category_codes(codes)
17964        } else if self.category_rank_unique_scan_is_bounded() {
17965            self.value_counts_by_category_rank()
17966        } else {
17967            self.value_counts_by_hash()
17968        };
17969        pairs.retain(|(label, _)| !label.is_missing());
17970        pairs
17971    }
17972
17973    /// Factorize, matching `pd.CategoricalIndex.factorize()`. Returns
17974    /// `(codes, uniques)` where `uniques` is a CategoricalIndex with
17975    /// the same categories list; a missing label's code is -1, and it is
17976    /// no unique.
17977    #[must_use]
17978    pub fn factorize(&self) -> (Vec<isize>, Self) {
17979        let (mut codes, mut uniques) = if let Some(codes) = &self.category_codes {
17980            self.factorize_by_category_codes(codes)
17981        } else if self.category_rank_unique_scan_is_bounded() {
17982            self.factorize_by_category_rank()
17983        } else {
17984            self.factorize_by_hash()
17985        };
17986        if let Some(missing) = uniques.labels.iter().position(IndexLabel::is_missing) {
17987            let missing = isize::try_from(missing).unwrap_or(isize::MAX);
17988            for code in &mut codes {
17989                if *code == missing {
17990                    *code = -1;
17991                } else if *code > missing {
17992                    *code -= 1;
17993                }
17994            }
17995            uniques = uniques.dropna();
17996        }
17997        (codes, uniques)
17998    }
17999}
18000
18001// ── IntervalIndex ──────────────────────────────────────────────────────────
18002
18003/// An index of `Interval` objects (`pd.IntervalIndex`).
18004///
18005/// An immutable index of half-open, closed, or open intervals.
18006/// Backed by float64 endpoints with configurable closed semantics.
18007#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18008pub struct IntervalIndex {
18009    values: Vec<Interval>,
18010    closed: IntervalClosed,
18011    name: Option<LabelName>,
18012}
18013
18014impl IntervalIndex {
18015    /// Construct a new `IntervalIndex` from a vector of `Interval`s.
18016    #[must_use]
18017    pub fn new(values: Vec<Interval>) -> Self {
18018        let closed = values.first().map_or(IntervalClosed::Right, |iv| iv.closed);
18019        Self {
18020            values,
18021            closed,
18022            name: None,
18023        }
18024    }
18025
18026    /// Construct a new `IntervalIndex` with explicit closed policy and name.
18027    #[must_use]
18028    pub fn new_with_options(
18029        values: Vec<Interval>,
18030        closed: IntervalClosed,
18031        name: Option<String>,
18032    ) -> Self {
18033        Self {
18034            values,
18035            closed,
18036            name: name.map(LabelName::from),
18037        }
18038    }
18039
18040    /// Construct an `IntervalIndex` from endpoint breaks (`pd.IntervalIndex.from_breaks`).
18041    ///
18042    /// # Errors
18043    /// Returns `IndexError::InvalidArgument` if breaks has fewer than 2 elements.
18044    pub fn from_breaks(breaks: &[f64], closed: IntervalClosed) -> Result<Self, IndexError> {
18045        if breaks.len() < 2 {
18046            return Err(IndexError::InvalidArgument(
18047                "breaks must have at least 2 elements".to_string(),
18048            ));
18049        }
18050        let mut values = Vec::with_capacity(breaks.len() - 1);
18051        for i in 0..(breaks.len() - 1) {
18052            values.push(Interval::new(breaks[i], breaks[i + 1], closed));
18053        }
18054        Ok(Self {
18055            values,
18056            closed,
18057            name: None,
18058        })
18059    }
18060
18061    /// Construct an `IntervalIndex` from (left, right) tuples (`pd.IntervalIndex.from_tuples`).
18062    #[must_use]
18063    pub fn from_tuples(tuples: &[(f64, f64)], closed: IntervalClosed) -> Self {
18064        let mut values = Vec::with_capacity(tuples.len());
18065        for &(left, right) in tuples {
18066            values.push(Interval::new(left, right, closed));
18067        }
18068        Self {
18069            values,
18070            closed,
18071            name: None,
18072        }
18073    }
18074
18075    /// Construct an `IntervalIndex` from separate left and right arrays (`pd.IntervalIndex.from_arrays`).
18076    ///
18077    /// # Errors
18078    /// Returns `IndexError::LengthMismatch` if left and right arrays have different lengths.
18079    pub fn from_arrays(
18080        left: &[f64],
18081        right: &[f64],
18082        closed: IntervalClosed,
18083    ) -> Result<Self, IndexError> {
18084        if left.len() != right.len() {
18085            return Err(IndexError::LengthMismatch {
18086                expected: left.len(),
18087                actual: right.len(),
18088                context: "IntervalIndex.from_arrays left and right arrays must have equal length"
18089                    .to_string(),
18090            });
18091        }
18092        let mut values = Vec::with_capacity(left.len());
18093        for (&l, &r) in left.iter().zip(right.iter()) {
18094            values.push(Interval::new(l, r, closed));
18095        }
18096        Ok(Self {
18097            values,
18098            closed,
18099            name: None,
18100        })
18101    }
18102
18103    /// Construct an `IntervalIndex` from a range specification (`pd.interval_range`).
18104    ///
18105    /// # Errors
18106    /// Returns `IndexError::InvalidArgument` if parameters are invalid.
18107    pub fn from_range(
18108        start: Option<f64>,
18109        end: Option<f64>,
18110        periods: Option<usize>,
18111        freq: Option<f64>,
18112        closed: Option<IntervalClosed>,
18113    ) -> Result<Self, IndexError> {
18114        let closed_val = closed.unwrap_or(IntervalClosed::Right);
18115        let values = interval_range(start, end, periods, freq, closed)
18116            .map_err(|e| IndexError::InvalidArgument(e.to_string()))?;
18117        Ok(Self {
18118            values,
18119            closed: closed_val,
18120            name: None,
18121        })
18122    }
18123
18124    #[must_use]
18125    pub fn values(&self) -> &[Interval] {
18126        &self.values
18127    }
18128
18129    #[must_use]
18130    pub fn len(&self) -> usize {
18131        self.values.len()
18132    }
18133
18134    #[must_use]
18135    pub fn is_empty(&self) -> bool {
18136        self.values.is_empty()
18137    }
18138
18139    #[must_use]
18140    pub fn closed(&self) -> IntervalClosed {
18141        self.closed
18142    }
18143
18144    #[must_use]
18145    pub fn name(&self) -> Option<&LabelName> {
18146        self.name.as_ref()
18147    }
18148
18149    #[must_use]
18150    pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
18151        let mut out = self.clone();
18152        out.name = Some(name.into());
18153        out
18154    }
18155
18156    #[must_use]
18157    pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
18158        let mut out = self.clone();
18159        out.name = name.map(Into::into);
18160        out
18161    }
18162
18163    #[must_use]
18164    pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
18165        self.set_names(name)
18166    }
18167
18168    #[must_use]
18169    pub fn names(&self) -> Vec<Option<String>> {
18170        vec![self.name.clone().map(String::from)]
18171    }
18172
18173    #[must_use]
18174    pub fn copy(&self) -> Self {
18175        self.clone()
18176    }
18177
18178    #[must_use]
18179    pub fn shape(&self) -> (usize,) {
18180        (self.len(),)
18181    }
18182
18183    #[must_use]
18184    pub fn size(&self) -> usize {
18185        self.len()
18186    }
18187
18188    #[must_use]
18189    pub fn empty(&self) -> bool {
18190        self.is_empty()
18191    }
18192
18193    #[must_use]
18194    pub fn dtype(&self) -> String {
18195        format!("interval[float64, {}]", self.closed)
18196    }
18197
18198    #[must_use]
18199    pub fn dtypes(&self) -> Vec<String> {
18200        vec![self.dtype()]
18201    }
18202
18203    #[must_use]
18204    pub fn hasnans(&self) -> bool {
18205        false
18206    }
18207
18208    #[must_use]
18209    pub fn isna(&self) -> Vec<bool> {
18210        vec![false; self.len()]
18211    }
18212
18213    #[must_use]
18214    pub fn isnull(&self) -> Vec<bool> {
18215        self.isna()
18216    }
18217
18218    #[must_use]
18219    pub fn notna(&self) -> Vec<bool> {
18220        vec![true; self.len()]
18221    }
18222
18223    #[must_use]
18224    pub fn notnull(&self) -> Vec<bool> {
18225        self.notna()
18226    }
18227
18228    #[must_use]
18229    pub fn dropna(&self) -> Self {
18230        self.clone()
18231    }
18232
18233    /// Return an `Index` containing the left endpoints of each interval.
18234    #[must_use]
18235    pub fn left(&self) -> Index {
18236        let labels = self
18237            .values
18238            .iter()
18239            .map(|iv| IndexLabel::Float64(OrderedF64(iv.left)))
18240            .collect();
18241        Index::new(labels)
18242    }
18243
18244    /// Return an `Index` containing the right endpoints of each interval.
18245    #[must_use]
18246    pub fn right(&self) -> Index {
18247        let labels = self
18248            .values
18249            .iter()
18250            .map(|iv| IndexLabel::Float64(OrderedF64(iv.right)))
18251            .collect();
18252        Index::new(labels)
18253    }
18254
18255    /// Return an `Index` containing the midpoint `(left + right) / 2` of each interval.
18256    #[must_use]
18257    pub fn mid(&self) -> Index {
18258        let labels = self
18259            .values
18260            .iter()
18261            .map(|iv| IndexLabel::Float64(OrderedF64(iv.mid())))
18262            .collect();
18263        Index::new(labels)
18264    }
18265
18266    /// Return an `Index` containing the length `right - left` of each interval.
18267    #[must_use]
18268    pub fn length(&self) -> Index {
18269        let labels = self
18270            .values
18271            .iter()
18272            .map(|iv| IndexLabel::Float64(OrderedF64(iv.length())))
18273            .collect();
18274        Index::new(labels)
18275    }
18276
18277    /// True if any two intervals in the index overlap.
18278    #[must_use]
18279    pub fn is_overlapping(&self) -> bool {
18280        let len = self.values.len();
18281        if len < 2 {
18282            return false;
18283        }
18284        for i in 0..len {
18285            for j in (i + 1)..len {
18286                if self.values[i].overlaps(&self.values[j]) {
18287                    return true;
18288                }
18289            }
18290        }
18291        false
18292    }
18293
18294    /// Check if each interval overlaps with the given interval.
18295    #[must_use]
18296    pub fn overlaps(&self, other: &Interval) -> Vec<bool> {
18297        self.values.iter().map(|iv| iv.overlaps(other)).collect()
18298    }
18299
18300    /// Check if each interval contains the given scalar point.
18301    #[must_use]
18302    pub fn contains(&self, point: f64) -> Vec<bool> {
18303        self.values.iter().map(|iv| iv.contains(point)).collect()
18304    }
18305
18306    /// Return the integer position of the interval containing the query scalar point.
18307    ///
18308    /// # Errors
18309    /// Returns `IndexError::InvalidArgument` if no interval contains `point`, or if
18310    /// multiple overlapping intervals contain `point`.
18311    pub fn get_loc(&self, point: f64) -> Result<usize, IndexError> {
18312        let mut found = None;
18313        for (i, iv) in self.values.iter().enumerate() {
18314            if iv.contains(point) {
18315                if found.is_some() {
18316                    return Err(IndexError::InvalidArgument(format!(
18317                        "point {point} overlaps multiple intervals"
18318                    )));
18319                }
18320                found = Some(i);
18321            }
18322        }
18323        found.ok_or_else(|| {
18324            IndexError::InvalidArgument(format!("point {point} not found in IntervalIndex"))
18325        })
18326    }
18327
18328    /// Return the integer position of an exact matching `Interval`.
18329    ///
18330    /// # Errors
18331    /// Returns `IndexError::InvalidArgument` if target interval is not in the index.
18332    pub fn get_loc_interval(&self, target: &Interval) -> Result<usize, IndexError> {
18333        self.values
18334            .iter()
18335            .position(|iv| {
18336                OrderedF64(iv.left) == OrderedF64(target.left)
18337                    && OrderedF64(iv.right) == OrderedF64(target.right)
18338                    && iv.closed == target.closed
18339            })
18340            .ok_or_else(|| {
18341                IndexError::InvalidArgument(format!(
18342                    "interval {target:?} not found in IntervalIndex"
18343                ))
18344            })
18345    }
18346
18347    /// Compute positional indexer for target points.
18348    #[must_use]
18349    pub fn get_indexer(&self, target: &[f64]) -> Vec<Option<usize>> {
18350        target.iter().map(|&pt| self.get_loc(pt).ok()).collect()
18351    }
18352
18353    /// Return a new `IntervalIndex` with specified `closed` semantics.
18354    #[must_use]
18355    pub fn set_closed(&self, closed: IntervalClosed) -> Self {
18356        let values = self
18357            .values
18358            .iter()
18359            .map(|iv| Interval::new(iv.left, iv.right, closed))
18360            .collect();
18361        Self {
18362            values,
18363            closed,
18364            name: self.name.clone(),
18365        }
18366    }
18367
18368    /// Convert to a standard `Index` with string representations.
18369    #[must_use]
18370    pub fn to_index(&self) -> Index {
18371        let labels = self
18372            .values
18373            .iter()
18374            .map(|iv| IndexLabel::Utf8(format!("{iv}")))
18375            .collect();
18376        let mut idx = Index::new(labels);
18377        if let Some(name) = &self.name {
18378            idx = idx.set_name(name);
18379        }
18380        idx
18381    }
18382
18383    #[must_use]
18384    pub fn is_unique(&self) -> bool {
18385        let len = self.values.len();
18386        if len < 2 {
18387            return true;
18388        }
18389        for i in 0..len {
18390            for j in (i + 1)..len {
18391                if OrderedF64(self.values[i].left) == OrderedF64(self.values[j].left)
18392                    && OrderedF64(self.values[i].right) == OrderedF64(self.values[j].right)
18393                    && self.values[i].closed == self.values[j].closed
18394                {
18395                    return false;
18396                }
18397            }
18398        }
18399        true
18400    }
18401
18402    #[must_use]
18403    pub fn is_monotonic_increasing(&self) -> bool {
18404        if self.values.len() < 2 {
18405            return true;
18406        }
18407        for w in self.values.windows(2) {
18408            let left_cmp = OrderedF64(w[0].left).cmp(&OrderedF64(w[1].left));
18409            if left_cmp.is_gt() {
18410                return false;
18411            }
18412            if left_cmp.is_eq() && OrderedF64(w[0].right).cmp(&OrderedF64(w[1].right)).is_gt() {
18413                return false;
18414            }
18415        }
18416        true
18417    }
18418
18419    #[must_use]
18420    pub fn is_monotonic_decreasing(&self) -> bool {
18421        if self.values.len() < 2 {
18422            return true;
18423        }
18424        for w in self.values.windows(2) {
18425            let left_cmp = OrderedF64(w[0].left).cmp(&OrderedF64(w[1].left));
18426            if left_cmp.is_lt() {
18427                return false;
18428            }
18429            if left_cmp.is_eq() && OrderedF64(w[0].right).cmp(&OrderedF64(w[1].right)).is_lt() {
18430                return false;
18431            }
18432        }
18433        true
18434    }
18435
18436    /// Get interval at integer position (supports negative indexing).
18437    ///
18438    /// # Errors
18439    /// Returns `IndexError::OutOfBounds` if `idx` is out of range.
18440    pub fn get_item(&self, idx: isize) -> Result<Interval, IndexError> {
18441        let len = self.values.len() as isize;
18442        let pos = if idx < 0 { idx + len } else { idx };
18443        if pos < 0 || pos >= len {
18444            return Err(IndexError::OutOfBounds {
18445                position: if idx < 0 {
18446                    idx.unsigned_abs()
18447                } else {
18448                    idx as usize
18449                },
18450                length: self.values.len(),
18451            });
18452        }
18453        Ok(self.values[pos as usize])
18454    }
18455
18456    #[must_use]
18457    pub fn slice(&self, start: usize, end: usize) -> Self {
18458        let end = end.min(self.values.len());
18459        let start = start.min(end);
18460        Self {
18461            values: self.values[start..end].to_vec(),
18462            closed: self.closed,
18463            name: self.name.clone(),
18464        }
18465    }
18466
18467    #[must_use]
18468    pub fn head(&self, n: usize) -> Self {
18469        self.slice(0, n)
18470    }
18471
18472    #[must_use]
18473    pub fn tail(&self, n: usize) -> Self {
18474        let len = self.values.len();
18475        let start = len.saturating_sub(n);
18476        self.slice(start, len)
18477    }
18478
18479    /// Take values at indices.
18480    ///
18481    /// # Errors
18482    /// Returns `IndexError::OutOfBounds` if any index is out of bounds.
18483    pub fn take(&self, indices: &[usize]) -> Result<Self, IndexError> {
18484        let mut values = Vec::with_capacity(indices.len());
18485        for &idx in indices {
18486            if idx >= self.values.len() {
18487                return Err(IndexError::OutOfBounds {
18488                    position: idx,
18489                    length: self.values.len(),
18490                });
18491            }
18492            values.push(self.values[idx]);
18493        }
18494        Ok(Self {
18495            values,
18496            closed: self.closed,
18497            name: self.name.clone(),
18498        })
18499    }
18500
18501    /// Check whether intervals are closed on the left endpoint (`pd.IntervalIndex.closed_left`).
18502    #[must_use]
18503    pub fn closed_left(&self) -> bool {
18504        self.closed.left_closed()
18505    }
18506
18507    /// Check whether intervals are closed on the right endpoint (`pd.IntervalIndex.closed_right`).
18508    #[must_use]
18509    pub fn closed_right(&self) -> bool {
18510        self.closed.right_closed()
18511    }
18512
18513    /// Check whether intervals are open on the left endpoint (`pd.IntervalIndex.open_left`).
18514    #[must_use]
18515    pub fn open_left(&self) -> bool {
18516        !self.closed.left_closed()
18517    }
18518
18519    /// Check whether intervals are open on the right endpoint (`pd.IntervalIndex.open_right`).
18520    #[must_use]
18521    pub fn open_right(&self) -> bool {
18522        !self.closed.right_closed()
18523    }
18524
18525    /// Return a boolean whether the IntervalIndex is non-overlapping and monotonic (`pd.IntervalIndex.is_non_overlapping_monotonic`).
18526    #[must_use]
18527    pub fn is_non_overlapping_monotonic(&self) -> bool {
18528        (self.is_monotonic_increasing() || self.is_monotonic_decreasing()) && !self.is_overlapping()
18529    }
18530
18531    /// Return intervals as a vector of (left, right) tuples (`pd.IntervalIndex.to_tuples`).
18532    #[must_use]
18533    pub fn to_tuples(&self) -> Vec<(f64, f64)> {
18534        self.values.iter().map(|iv| (iv.left, iv.right)).collect()
18535    }
18536
18537    /// Return intervals as a vector of `Interval` values.
18538    #[must_use]
18539    pub fn to_list(&self) -> Vec<Interval> {
18540        self.values.clone()
18541    }
18542
18543    /// Alias for `to_list`.
18544    #[must_use]
18545    pub fn tolist(&self) -> Vec<Interval> {
18546        self.to_list()
18547    }
18548}
18549
18550impl From<IntervalIndex> for Index {
18551    fn from(ii: IntervalIndex) -> Self {
18552        ii.to_index()
18553    }
18554}
18555
18556impl From<&IntervalIndex> for Index {
18557    fn from(ii: &IntervalIndex) -> Self {
18558        ii.to_index()
18559    }
18560}
18561
18562#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18563pub struct AlignmentPlan {
18564    pub union_index: Index,
18565    pub left_positions: Vec<Option<usize>>,
18566    pub right_positions: Vec<Option<usize>>,
18567}
18568
18569#[derive(Debug, Error, Clone, PartialEq, Eq)]
18570#[non_exhaustive]
18571pub enum IndexError {
18572    #[error("alignment vectors must have equal lengths")]
18573    InvalidAlignmentVectors,
18574    #[error("position {position} out of bounds for length {length}")]
18575    OutOfBounds { position: usize, length: usize },
18576    #[error("length mismatch: expected {expected}, got {actual} ({context})")]
18577    LengthMismatch {
18578        expected: usize,
18579        actual: usize,
18580        context: String,
18581    },
18582    #[error("invalid argument: {0}")]
18583    InvalidArgument(String),
18584    /// A label the index does not hold where it must: pandas'
18585    /// `KeyError(label)`.
18586    #[error("{0}")]
18587    LabelNotFound(IndexLabel),
18588    /// pandas' `KeyError(message)`.
18589    #[error("{0}")]
18590    KeyError(String),
18591    /// An unknown zone, or a wall time a DST change skips or repeats.
18592    #[error(transparent)]
18593    TimeZone(#[from] fp_types::TimeZoneError),
18594    /// Mixing tz-aware and tz-naive datetimes where pandas refuses to
18595    /// (localizing an aware index, converting a naive one, joining the two):
18596    /// pandas' `TypeError`.
18597    #[error("{0}")]
18598    TimeZoneMismatch(String),
18599}
18600
18601/// Alignment mode for index-level join semantics.
18602#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18603pub enum AlignMode {
18604    /// Only labels present in both indexes.
18605    Inner,
18606    /// All left labels; right fills with None for missing.
18607    Left,
18608    /// All right labels; left fills with None for missing.
18609    Right,
18610    /// All labels from both indexes (union). Default for arithmetic.
18611    Outer,
18612}
18613
18614fn index_position_groups(index: &Index) -> FxHashMap<IndexLabel, Vec<usize>> {
18615    let mut groups: FxHashMap<IndexLabel, Vec<usize>> = FxHashMap::default();
18616    for (pos, label) in index.labels().iter().enumerate() {
18617        groups.entry(label.clone()).or_default().push(pos);
18618    }
18619    groups
18620}
18621
18622fn align_non_unique(left: &Index, right: &Index, mode: AlignMode) -> AlignmentPlan {
18623    let left_groups = index_position_groups(left);
18624    let right_groups = index_position_groups(right);
18625
18626    let mut out_labels = Vec::new();
18627    let mut left_positions = Vec::new();
18628    let mut right_positions = Vec::new();
18629
18630    match mode {
18631        AlignMode::Inner => {
18632            for (left_pos, label) in left.labels().iter().enumerate() {
18633                if let Some(right_hits) = right_groups.get(label) {
18634                    for &right_pos in right_hits {
18635                        out_labels.push(label.clone());
18636                        left_positions.push(Some(left_pos));
18637                        right_positions.push(Some(right_pos));
18638                    }
18639                }
18640            }
18641        }
18642        AlignMode::Left => {
18643            for (left_pos, label) in left.labels().iter().enumerate() {
18644                match right_groups.get(label) {
18645                    Some(right_hits) if !right_hits.is_empty() => {
18646                        for &right_pos in right_hits {
18647                            out_labels.push(label.clone());
18648                            left_positions.push(Some(left_pos));
18649                            right_positions.push(Some(right_pos));
18650                        }
18651                    }
18652                    _ => {
18653                        out_labels.push(label.clone());
18654                        left_positions.push(Some(left_pos));
18655                        right_positions.push(None);
18656                    }
18657                }
18658            }
18659        }
18660        AlignMode::Right => {
18661            for (right_pos, label) in right.labels().iter().enumerate() {
18662                match left_groups.get(label) {
18663                    Some(left_hits) if !left_hits.is_empty() => {
18664                        for &left_pos in left_hits {
18665                            out_labels.push(label.clone());
18666                            left_positions.push(Some(left_pos));
18667                            right_positions.push(Some(right_pos));
18668                        }
18669                    }
18670                    _ => {
18671                        out_labels.push(label.clone());
18672                        left_positions.push(None);
18673                        right_positions.push(Some(right_pos));
18674                    }
18675                }
18676            }
18677        }
18678        AlignMode::Outer => {
18679            for (left_pos, label) in left.labels().iter().enumerate() {
18680                match right_groups.get(label) {
18681                    Some(right_hits) if !right_hits.is_empty() => {
18682                        for &right_pos in right_hits {
18683                            out_labels.push(label.clone());
18684                            left_positions.push(Some(left_pos));
18685                            right_positions.push(Some(right_pos));
18686                        }
18687                    }
18688                    _ => {
18689                        out_labels.push(label.clone());
18690                        left_positions.push(Some(left_pos));
18691                        right_positions.push(None);
18692                    }
18693                }
18694            }
18695
18696            for (right_pos, label) in right.labels().iter().enumerate() {
18697                if !left_groups.contains_key(label) {
18698                    out_labels.push(label.clone());
18699                    left_positions.push(None);
18700                    right_positions.push(Some(right_pos));
18701                }
18702            }
18703        }
18704    }
18705
18706    let mut union_index = Index::new(out_labels);
18707    match mode {
18708        AlignMode::Left => {
18709            union_index.name = left.name.clone();
18710            union_index.tz.clone_from(&left.tz);
18711        }
18712        AlignMode::Right => {
18713            union_index.name = right.name.clone();
18714            union_index.tz.clone_from(&right.tz);
18715        }
18716        AlignMode::Inner | AlignMode::Outer => union_index.tz = joined_tz(left, right),
18717    }
18718
18719    AlignmentPlan {
18720        union_index,
18721        left_positions,
18722        right_positions,
18723    }
18724}
18725
18726/// The zone of an index joining two aware indexes, as pandas: a shared zone
18727/// is kept and two different zones meet in UTC (the labels are instants
18728/// either way). None when either side is naive - joining an aware index with
18729/// a naive one is pandas' TypeError, which [`check_tz_compatible`] reports.
18730#[must_use]
18731pub fn joined_tz(left: &Index, right: &Index) -> Option<String> {
18732    match (left.tz(), right.tz()) {
18733        (Some(l), Some(r)) if l == r => Some(l.to_owned()),
18734        (Some(_), Some(_)) => Some("UTC".to_owned()),
18735        _ => None,
18736    }
18737}
18738
18739/// pandas refuses to join a tz-aware datetime index with a tz-naive one
18740/// ("Cannot join tz-naive with tz-aware DatetimeIndex"); callers that align
18741/// two indexes check this first.
18742pub fn check_tz_compatible(left: &Index, right: &Index) -> Result<(), IndexError> {
18743    if left.tz().is_some() != right.tz().is_some()
18744        && left.holds_only_datetimes()
18745        && right.holds_only_datetimes()
18746        && !left.is_empty()
18747        && !right.is_empty()
18748    {
18749        return Err(IndexError::TimeZoneMismatch(
18750            "Cannot join tz-naive with tz-aware DatetimeIndex".to_owned(),
18751        ));
18752    }
18753    Ok(())
18754}
18755
18756/// Align two indexes using the specified join mode.
18757///
18758/// Returns an `AlignmentPlan` whose `union_index` contains the output index
18759/// (which may be an intersection, left-only, right-only, or union depending on mode).
18760pub fn align(left: &Index, right: &Index, mode: AlignMode) -> AlignmentPlan {
18761    if left.has_duplicates() || right.has_duplicates() {
18762        return align_non_unique(left, right, mode);
18763    }
18764
18765    match mode {
18766        AlignMode::Inner => align_inner(left, right),
18767        AlignMode::Left => align_left(left, right),
18768        AlignMode::Right => {
18769            let plan = align_left(right, left);
18770            AlignmentPlan {
18771                union_index: plan.union_index,
18772                left_positions: plan.right_positions,
18773                right_positions: plan.left_positions,
18774            }
18775        }
18776        AlignMode::Outer => align_union(left, right),
18777    }
18778}
18779
18780/// Inner alignment: only labels present in both indexes.
18781///
18782/// For non-unique labels, emits cartesian matches preserving left order.
18783pub fn align_inner(left: &Index, right: &Index) -> AlignmentPlan {
18784    if left.has_duplicates() || right.has_duplicates() {
18785        return align_non_unique(left, right, AlignMode::Inner);
18786    }
18787
18788    // Typed all-Int64 fast path: inline `i64` right-position map instead of the
18789    // pointer-keyed `FxHashMap<&IndexLabel>`. Bit-identical: left-order matches
18790    // present in right, with their (left, right) positions.
18791    if let (Some(left_vals), Some(right_vals)) =
18792        (left.labels.int64_view(), right.labels.int64_view())
18793    {
18794        let mut right_pos: FxHashMap<i64, usize> =
18795            FxHashMap::with_capacity_and_hasher(right_vals.len(), Default::default());
18796        for (i, &v) in right_vals.iter().enumerate() {
18797            right_pos.entry(v).or_insert(i);
18798        }
18799        let mut out_vals = Vec::new();
18800        let mut left_positions = Vec::new();
18801        let mut right_positions = Vec::new();
18802        for (left_pos, &v) in left_vals.iter().enumerate() {
18803            if let Some(&rp) = right_pos.get(&v) {
18804                out_vals.push(v);
18805                left_positions.push(Some(left_pos));
18806                right_positions.push(Some(rp));
18807            }
18808        }
18809        let shared_name = if left.name() == right.name() {
18810            left.name().cloned()
18811        } else {
18812            None
18813        };
18814        let mut union_index = Index::from_i64(out_vals);
18815        union_index.name = shared_name;
18816        return AlignmentPlan {
18817            union_index,
18818            left_positions,
18819            right_positions,
18820        };
18821    }
18822
18823    let right_map = right.position_map_first_ref();
18824
18825    let mut output_labels = Vec::new();
18826    let mut left_positions = Vec::new();
18827    let mut right_positions = Vec::new();
18828
18829    for (left_pos, label) in left.labels.iter().enumerate() {
18830        if let Some(&right_pos) = right_map.get(label) {
18831            output_labels.push(label.clone());
18832            left_positions.push(Some(left_pos));
18833            right_positions.push(Some(right_pos));
18834        }
18835    }
18836
18837    // Per br-frankenpandas-m2i5n: pandas inner alignment preserves the
18838    // shared index name (preserved when both operands agree, None when
18839    // they differ). Mirrors align_non_unique handling.
18840    let shared_name = if left.name() == right.name() {
18841        left.name().cloned()
18842    } else {
18843        None
18844    };
18845    let mut union_index = Index::new(output_labels);
18846    union_index.name = shared_name;
18847    union_index.tz = joined_tz(left, right);
18848    AlignmentPlan {
18849        union_index,
18850        left_positions,
18851        right_positions,
18852    }
18853}
18854
18855/// Left alignment: all left labels preserved, right fills with None for missing.
18856pub fn align_left(left: &Index, right: &Index) -> AlignmentPlan {
18857    if left.has_duplicates() || right.has_duplicates() {
18858        return align_non_unique(left, right, AlignMode::Left);
18859    }
18860
18861    // Typed all-Int64 fast path: inline `i64` right-position map instead of the
18862    // pointer-keyed `FxHashMap<&IndexLabel>`. The union is `left` unchanged, and
18863    // `left_positions` is the identity `0..n` — only `right_positions` needs a
18864    // lookup. Bit-identical.
18865    if let (Some(left_vals), Some(right_vals)) =
18866        (left.labels.int64_view(), right.labels.int64_view())
18867    {
18868        let mut right_pos: FxHashMap<i64, usize> =
18869            FxHashMap::with_capacity_and_hasher(right_vals.len(), Default::default());
18870        for (i, &v) in right_vals.iter().enumerate() {
18871            right_pos.entry(v).or_insert(i);
18872        }
18873        let n = left_vals.len();
18874        let left_positions: Vec<Option<usize>> = (0..n).map(Some).collect();
18875        let right_positions: Vec<Option<usize>> = left_vals
18876            .iter()
18877            .map(|v| right_pos.get(v).copied())
18878            .collect();
18879        return AlignmentPlan {
18880            union_index: left.clone(),
18881            left_positions,
18882            right_positions,
18883        };
18884    }
18885
18886    let right_map = right.position_map_first_ref();
18887
18888    let mut left_positions = Vec::with_capacity(left.len());
18889    let mut right_positions = Vec::with_capacity(left.len());
18890
18891    for (left_pos, label) in left.labels.iter().enumerate() {
18892        left_positions.push(Some(left_pos));
18893        right_positions.push(right_map.get(label).copied());
18894    }
18895
18896    AlignmentPlan {
18897        union_index: left.clone(),
18898        left_positions,
18899        right_positions,
18900    }
18901}
18902
18903/// Typed all-Int64 union alignment over raw `i64` keys (both inputs unique, per
18904/// the `align_union` `has_duplicates` guard). Produces the SAME union order as
18905/// the generic path — left labels in order, then right-only labels in right
18906/// order — and the same per-side position vectors, but with INLINE `i64` map
18907/// keys instead of `FxHashMap<&IndexLabel>` pointers into the enum vector (two
18908/// position maps + two position lookups per union label, each otherwise paying
18909/// a pointer-chase cache miss). Returns `(union_values, left_positions,
18910/// right_positions)`.
18911#[allow(clippy::type_complexity)]
18912fn align_union_i64(
18913    left_vals: &[i64],
18914    right_vals: &[i64],
18915) -> (Vec<i64>, Vec<Option<usize>>, Vec<Option<usize>>) {
18916    // `left` is unique, so its labels occupy union positions `0..n` in order:
18917    // `left_positions[i] = Some(i)` there and `None` for the right-only tail —
18918    // no map lookup needed. A membership SET of `left` filters the right tail;
18919    // a `right` position MAP serves `right_positions`.
18920    let mut left_set: FxHashSet<i64> =
18921        FxHashSet::with_capacity_and_hasher(left_vals.len(), Default::default());
18922    for &v in left_vals {
18923        left_set.insert(v);
18924    }
18925    let mut right_pos: FxHashMap<i64, usize> =
18926        FxHashMap::with_capacity_and_hasher(right_vals.len(), Default::default());
18927    for (i, &v) in right_vals.iter().enumerate() {
18928        right_pos.entry(v).or_insert(i);
18929    }
18930
18931    let mut union_vals =
18932        Vec::with_capacity(combined_output_capacity(left_vals.len(), right_vals.len()));
18933    union_vals.extend_from_slice(left_vals);
18934    for &v in right_vals {
18935        if !left_set.contains(&v) {
18936            union_vals.push(v);
18937        }
18938    }
18939
18940    let n = left_vals.len();
18941    let mut left_positions = Vec::with_capacity(union_vals.len());
18942    left_positions.extend((0..n).map(Some));
18943    left_positions.extend(std::iter::repeat_n(None, union_vals.len() - n));
18944    let right_positions = union_vals
18945        .iter()
18946        .map(|v| right_pos.get(v).copied())
18947        .collect();
18948    (union_vals, left_positions, right_positions)
18949}
18950
18951pub fn align_union(left: &Index, right: &Index) -> AlignmentPlan {
18952    if left.has_duplicates() || right.has_duplicates() {
18953        return align_non_unique(left, right, AlignMode::Outer);
18954    }
18955
18956    // Typed all-Int64 fast path: inline `i64` position maps instead of the
18957    // pointer-keyed `FxHashMap<&IndexLabel>`. Bit-identical union order and
18958    // position vectors; the union index keeps the typed Int64 backing.
18959    if let (Some(left_vals), Some(right_vals)) =
18960        (left.labels.int64_view(), right.labels.int64_view())
18961    {
18962        let (union_vals, left_positions, right_positions) =
18963            align_union_i64(&left_vals, &right_vals);
18964        let shared_name = if left.name() == right.name() {
18965            left.name().cloned()
18966        } else {
18967            None
18968        };
18969        let mut union_index = Index::from_i64(union_vals);
18970        union_index.name = shared_name;
18971        return AlignmentPlan {
18972            union_index,
18973            left_positions,
18974            right_positions,
18975        };
18976    }
18977
18978    let left_positions_map = left.position_map_first_ref();
18979    let right_positions_map = right.position_map_first_ref();
18980
18981    let mut union_labels = Vec::with_capacity(combined_output_capacity(
18982        left.labels.len(),
18983        right.labels.len(),
18984    ));
18985    union_labels.extend(left.labels.iter().cloned());
18986    for label in &right.labels {
18987        if !left_positions_map.contains_key(&label) {
18988            union_labels.push(label.clone());
18989        }
18990    }
18991
18992    let left_positions = union_labels
18993        .iter()
18994        .map(|label| left_positions_map.get(&label).copied())
18995        .collect();
18996
18997    let right_positions = union_labels
18998        .iter()
18999        .map(|label| right_positions_map.get(&label).copied())
19000        .collect();
19001
19002    // Per br-frankenpandas-r4k11: pandas outer alignment preserves the
19003    // shared index name. Mirrors align_inner / align_non_unique handling.
19004    let shared_name = if left.name() == right.name() {
19005        left.name().cloned()
19006    } else {
19007        None
19008    };
19009    let mut union_index = Index::new(union_labels);
19010    union_index.name = shared_name;
19011    union_index.tz = joined_tz(left, right);
19012    AlignmentPlan {
19013        union_index,
19014        left_positions,
19015        right_positions,
19016    }
19017}
19018
19019pub fn validate_alignment_plan(plan: &AlignmentPlan) -> Result<(), IndexError> {
19020    if plan.left_positions.len() != plan.right_positions.len()
19021        || plan.left_positions.len() != plan.union_index.len()
19022    {
19023        return Err(IndexError::InvalidAlignmentVectors);
19024    }
19025
19026    Ok(())
19027}
19028
19029// ── AG-11: Leapfrog Triejoin for Multi-Way Index Alignment ─────────────
19030
19031/// Result of multi-way alignment: a union index plus per-input position vectors.
19032#[derive(Debug, Clone, PartialEq, Eq)]
19033pub struct MultiAlignmentPlan {
19034    pub union_index: Index,
19035    pub positions: Vec<Vec<Option<usize>>>,
19036}
19037
19038/// K-way merge union of multiple sorted iterators.
19039///
19040/// Produces a sorted, deduplicated index containing all labels from all inputs.
19041/// Each input is sorted internally before merging. Uses a min-heap for O(N log K)
19042/// performance where N = total labels and K = number of indexes.
19043pub fn leapfrog_union(indexes: &[&Index]) -> Index {
19044    if indexes.is_empty() {
19045        return Index::new(Vec::new());
19046    }
19047    if indexes.len() == 1 {
19048        return indexes[0].unique().sort_values();
19049    }
19050
19051    // Sort and dedup each input
19052    let sorted: Vec<Vec<&IndexLabel>> = indexes
19053        .iter()
19054        .map(|idx| {
19055            let mut labels: Vec<&IndexLabel> = idx.labels().iter().collect();
19056            labels.sort();
19057            labels.dedup();
19058            labels
19059        })
19060        .collect();
19061
19062    // Initialize min-heap: (label, iter_index, position_in_iter)
19063    let mut heap = std::collections::BinaryHeap::new();
19064    for (i, iter) in sorted.iter().enumerate() {
19065        if !iter.is_empty() {
19066            heap.push(std::cmp::Reverse((iter[0].clone(), i, 0_usize)));
19067        }
19068    }
19069
19070    let total = aggregate_output_capacity(sorted.iter().map(Vec::len));
19071    let mut result = Vec::with_capacity(total);
19072
19073    while let Some(std::cmp::Reverse((label, iter_idx, pos))) = heap.pop() {
19074        // Deduplicate: only push if different from last
19075        if result.last() != Some(&label) {
19076            result.push(label);
19077        }
19078
19079        let next_pos = pos + 1;
19080        if next_pos < sorted[iter_idx].len() {
19081            heap.push(std::cmp::Reverse((
19082                sorted[iter_idx][next_pos].clone(),
19083                iter_idx,
19084                next_pos,
19085            )));
19086        }
19087    }
19088
19089    Index::new(result)
19090}
19091
19092/// Leapfrog intersection: labels present in ALL input indexes.
19093///
19094/// Classic leapfrog algorithm on sorted iterators. For each position,
19095/// advance the smallest iterator to seek the maximum. When all iterators
19096/// agree, emit the label.
19097pub fn leapfrog_intersection(indexes: &[&Index]) -> Index {
19098    if indexes.is_empty() {
19099        return Index::new(Vec::new());
19100    }
19101    if indexes.len() == 1 {
19102        return indexes[0].unique().sort_values();
19103    }
19104
19105    // Sort and dedup each input
19106    let sorted: Vec<Vec<&IndexLabel>> = indexes
19107        .iter()
19108        .map(|idx| {
19109            let mut labels: Vec<&IndexLabel> = idx.labels().iter().collect();
19110            labels.sort();
19111            labels.dedup();
19112            labels
19113        })
19114        .collect();
19115
19116    // Cursors into each sorted iterator
19117    let k = sorted.len();
19118    let mut cursors: Vec<usize> = vec![0; k];
19119    let mut result = Vec::new();
19120
19121    'outer: loop {
19122        // Check if any iterator is exhausted
19123        for i in 0..k {
19124            if cursors[i] >= sorted[i].len() {
19125                break 'outer;
19126            }
19127        }
19128
19129        // Find the max label across all cursors
19130        let mut max_label = sorted[0][cursors[0]];
19131        for i in 1..k {
19132            if sorted[i][cursors[i]] > max_label {
19133                max_label = sorted[i][cursors[i]];
19134            }
19135        }
19136
19137        // Advance all cursors to at least max_label
19138        let mut all_equal = true;
19139        for i in 0..k {
19140            // Binary search for max_label in sorted[i] starting from cursors[i]
19141            let remaining = &sorted[i][cursors[i]..];
19142            match remaining.binary_search(&max_label) {
19143                Ok(offset) => {
19144                    cursors[i] += offset;
19145                }
19146                Err(offset) => {
19147                    cursors[i] += offset;
19148                    all_equal = false;
19149                }
19150            }
19151            if cursors[i] >= sorted[i].len() {
19152                break 'outer;
19153            }
19154        }
19155
19156        if all_equal {
19157            // All iterators point to the same label
19158            result.push(max_label.clone());
19159            for cursor in &mut cursors {
19160                *cursor += 1;
19161            }
19162        }
19163        // If not all equal, the loop continues with updated cursors
19164    }
19165
19166    Index::new(result)
19167}
19168
19169/// Multi-way alignment: union all indexes, then compute position vectors.
19170///
19171/// This is the AGM-bound-optimal replacement for iterative pairwise `align_union`.
19172/// For N indexes, produces a single sorted union index and N position vectors
19173/// mapping each union label to its original position in each input.
19174pub fn multi_way_align(indexes: &[&Index]) -> MultiAlignmentPlan {
19175    if indexes.is_empty() {
19176        return MultiAlignmentPlan {
19177            union_index: Index::new(Vec::new()),
19178            positions: Vec::new(),
19179        };
19180    }
19181
19182    // Preserve pandas-style union ordering: start with the first index's labels,
19183    // then append unseen labels from subsequent indexes in encounter order.
19184    // This matches iterative align_union(sort=False) semantics while avoiding
19185    // the O(N*K) pairwise alignment cascade.
19186    // Borrow labels into the membership set (no clone per label) and clone only
19187    // the first-seen ones into the output. The prior version cloned EVERY label
19188    // into an owned HashSet<IndexLabel> (even duplicates) — clone-bound. Borrowed
19189    // keys + FxHashSet leave only the unique-label output clones. The borrow is
19190    // valid: every &IndexLabel comes from `indexes`, which outlives this scan.
19191    let aggregate_capacity =
19192        aggregate_output_capacity(indexes.iter().map(|idx| idx.labels().len()));
19193    let mut seen: FxHashSet<&IndexLabel> =
19194        FxHashSet::with_capacity_and_hasher(aggregate_capacity, Default::default());
19195    let mut union_labels: Vec<IndexLabel> = Vec::with_capacity(aggregate_capacity);
19196    for idx in indexes {
19197        for label in idx.labels() {
19198            if seen.insert(label) {
19199                union_labels.push(label.clone());
19200            }
19201        }
19202    }
19203    // Per br-frankenpandas-nrhjq: pandas multi-index union sets name to
19204    // the shared name across all inputs (= None if any differ).
19205    let first_name = indexes.first().and_then(|idx| idx.name()).cloned();
19206    let shared_name = if indexes.iter().all(|idx| idx.name() == first_name.as_ref()) {
19207        first_name
19208    } else {
19209        None
19210    };
19211    let mut union = Index::new(union_labels);
19212    union.name = shared_name;
19213
19214    // Build position maps for each input
19215    let maps: Vec<FxHashMap<&IndexLabel, usize>> = indexes
19216        .iter()
19217        .map(|idx| idx.position_map_first_ref())
19218        .collect();
19219
19220    let positions: Vec<Vec<Option<usize>>> = maps
19221        .iter()
19222        .map(|map| {
19223            union
19224                .labels
19225                .iter()
19226                .map(|label| map.get(label).copied())
19227                .collect()
19228        })
19229        .collect();
19230
19231    MultiAlignmentPlan {
19232        union_index: union,
19233        positions,
19234    }
19235}
19236
19237// ── TimedeltaIndex helpers ──────────────────────────────────────────────
19238
19239/// Error for timedelta_range parameter combinations.
19240#[derive(Debug, Clone, Error)]
19241pub enum TimedeltaRangeError {
19242    #[error("must specify at least two of start, end, periods")]
19243    InsufficientParams,
19244    #[error("must specify no more than two of start, end, periods")]
19245    TooManyParams,
19246    /// A zero step goes nowhere (pandas' ZeroDivisionError). A negative one
19247    /// steps backwards and a range stepping away from `end` is empty, as
19248    /// pandas' (they were refused; br-frankenpandas-tzxpk).
19249    #[error("freq must be non-zero")]
19250    ZeroFreq,
19251}
19252
19253/// Create a TimedeltaIndex with evenly spaced values.
19254///
19255/// Analogous to `pd.timedelta_range()`. Must specify exactly two of:
19256/// start, end, periods. Frequency defaults to 1 day (86_400_000_000_000 ns).
19257///
19258/// # Examples
19259/// ```
19260/// use fp_index::timedelta_range;
19261/// use fp_types::Timedelta;
19262///
19263/// let idx = timedelta_range(
19264///     Some(Timedelta::NANOS_PER_DAY),
19265///     None,
19266///     Some(3),
19267///     Timedelta::NANOS_PER_DAY,
19268///     None,
19269/// ).unwrap();
19270/// assert_eq!(idx.len(), 3);
19271/// ```
19272pub fn timedelta_range(
19273    start: Option<i64>,
19274    end: Option<i64>,
19275    periods: Option<usize>,
19276    freq: i64,
19277    name: Option<&str>,
19278) -> Result<Index, TimedeltaRangeError> {
19279    if freq == 0 {
19280        return Err(TimedeltaRangeError::ZeroFreq);
19281    }
19282
19283    let (start_ns, count) = match (start, end, periods) {
19284        (Some(s), Some(e), None) => {
19285            // A step away from `end` reaches nothing (empty, as pandas').
19286            let n = if (freq > 0 && e < s) || (freq < 0 && e > s) {
19287                0
19288            } else {
19289                ((e - s) / freq + 1) as usize
19290            };
19291            (s, n)
19292        }
19293        (Some(s), None, Some(p)) => (s, p),
19294        (None, Some(e), Some(p)) => {
19295            let s = e - (p.saturating_sub(1) as i64) * freq;
19296            (s, p)
19297        }
19298        (Some(_), Some(_), Some(_)) => return Err(TimedeltaRangeError::TooManyParams),
19299        _ => return Err(TimedeltaRangeError::InsufficientParams),
19300    };
19301
19302    let nanos: Vec<i64> = (0..count).map(|i| start_ns + (i as i64) * freq).collect();
19303    let mut idx = Index::from_timedelta64(nanos);
19304    if let Some(n) = name {
19305        idx = idx.set_name(n);
19306    }
19307    Ok(idx)
19308}
19309
19310// ── DatetimeIndex helpers ───────────────────────────────────────────────
19311
19312/// Error for date_range parameter combinations.
19313#[derive(Debug, Clone, Error)]
19314pub enum DateRangeError {
19315    #[error("must specify at least two of start, end, periods")]
19316    InsufficientParams,
19317    #[error("need at least 3 dates to infer frequency")]
19318    InsufficientDates,
19319    #[error("must specify no more than two of start, end, periods")]
19320    TooManyParams,
19321    #[error("freq must be positive")]
19322    NonPositiveFreq,
19323    #[error("cannot compute range: end < start with positive freq")]
19324    InvalidRange,
19325    #[error("invalid datetime string: {0}")]
19326    ParseError(String),
19327}
19328
19329/// Parse an ISO 8601 datetime string to nanoseconds since epoch.
19330fn parse_datetime_to_nanos(s: &str) -> Result<i64, DateRangeError> {
19331    use chrono::NaiveDateTime;
19332
19333    let trimmed = s.trim();
19334
19335    // Try full datetime format
19336    if let Ok(dt) = NaiveDateTime::parse_from_str(trimmed, "%Y-%m-%d %H:%M:%S") {
19337        return datetime_to_nanos(dt);
19338    }
19339    if let Ok(dt) = NaiveDateTime::parse_from_str(trimmed, "%Y-%m-%dT%H:%M:%S") {
19340        return datetime_to_nanos(dt);
19341    }
19342
19343    // Try date-only format (midnight)
19344    if let Ok(date) = chrono::NaiveDate::parse_from_str(trimmed, "%Y-%m-%d") {
19345        let dt = date
19346            .and_hms_opt(0, 0, 0)
19347            .ok_or(DateRangeError::InvalidRange)?;
19348        return datetime_to_nanos(dt);
19349    }
19350
19351    Err(DateRangeError::ParseError(trimmed.to_owned()))
19352}
19353
19354fn datetime_to_nanos(dt: chrono::NaiveDateTime) -> Result<i64, DateRangeError> {
19355    dt.and_utc()
19356        .timestamp_nanos_opt()
19357        .ok_or(DateRangeError::InvalidRange)
19358}
19359
19360fn datetime_nanos_to_date(nanos: i64) -> Result<chrono::NaiveDate, DateRangeError> {
19361    let (date, _) = split_datetime_nanos(nanos)?;
19362    Ok(date)
19363}
19364
19365fn split_datetime_nanos(nanos: i64) -> Result<(chrono::NaiveDate, i64), DateRangeError> {
19366    let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
19367    let time_nanos = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
19368    let epoch = chrono::NaiveDate::from_ymd_opt(1970, 1, 1).ok_or(DateRangeError::InvalidRange)?;
19369    let date = epoch
19370        .checked_add_signed(chrono::Duration::days(days))
19371        .ok_or(DateRangeError::InvalidRange)?;
19372    Ok((date, time_nanos))
19373}
19374
19375fn date_to_midnight_nanos(date: chrono::NaiveDate) -> Result<i64, DateRangeError> {
19376    let dt = date
19377        .and_hms_opt(0, 0, 0)
19378        .ok_or(DateRangeError::InvalidRange)?;
19379    dt.and_utc()
19380        .timestamp_nanos_opt()
19381        .ok_or(DateRangeError::InvalidRange)
19382}
19383
19384fn date_and_time_to_nanos(date: chrono::NaiveDate, time_nanos: i64) -> Result<i64, DateRangeError> {
19385    date_to_midnight_nanos(date)?
19386        .checked_add(time_nanos)
19387        .ok_or(DateRangeError::InvalidRange)
19388}
19389
19390fn checked_day_step(
19391    date: chrono::NaiveDate,
19392    days: i64,
19393) -> Result<chrono::NaiveDate, DateRangeError> {
19394    date.checked_add_signed(chrono::Duration::days(days))
19395        .ok_or(DateRangeError::InvalidRange)
19396}
19397
19398fn is_business_day(date: chrono::NaiveDate) -> bool {
19399    use chrono::{Datelike, Weekday};
19400
19401    !matches!(date.weekday(), Weekday::Sat | Weekday::Sun)
19402}
19403
19404fn next_business_day(mut date: chrono::NaiveDate) -> Result<chrono::NaiveDate, DateRangeError> {
19405    while !is_business_day(date) {
19406        date = checked_day_step(date, 1)?;
19407    }
19408    Ok(date)
19409}
19410
19411fn previous_business_day(mut date: chrono::NaiveDate) -> Result<chrono::NaiveDate, DateRangeError> {
19412    while !is_business_day(date) {
19413        date = checked_day_step(date, -1)?;
19414    }
19415    Ok(date)
19416}
19417
19418fn collect_business_days_from_start(
19419    start: chrono::NaiveDate,
19420    periods: usize,
19421) -> Result<Vec<i64>, DateRangeError> {
19422    let mut values = Vec::with_capacity(periods);
19423    let mut date = next_business_day(start)?;
19424    while values.len() < periods {
19425        values.push(date_to_midnight_nanos(date)?);
19426        date = next_business_day(checked_day_step(date, 1)?)?;
19427    }
19428    Ok(values)
19429}
19430
19431fn collect_business_days_through_end(
19432    end: chrono::NaiveDate,
19433    periods: usize,
19434) -> Result<Vec<i64>, DateRangeError> {
19435    let mut values = Vec::with_capacity(periods);
19436    let mut date = previous_business_day(end)?;
19437    while values.len() < periods {
19438        values.push(date_to_midnight_nanos(date)?);
19439        date = previous_business_day(checked_day_step(date, -1)?)?;
19440    }
19441    values.reverse();
19442    Ok(values)
19443}
19444
19445fn collect_business_days_between(
19446    start: chrono::NaiveDate,
19447    end: chrono::NaiveDate,
19448) -> Result<Vec<i64>, DateRangeError> {
19449    if end < start {
19450        return Err(DateRangeError::InvalidRange);
19451    }
19452
19453    let mut values = Vec::new();
19454    let mut date = next_business_day(start)?;
19455    while date <= end {
19456        values.push(date_to_midnight_nanos(date)?);
19457        date = next_business_day(checked_day_step(date, 1)?)?;
19458    }
19459    Ok(values)
19460}
19461
19462/// A small subset of pandas `pandas.tseries.offsets` date offsets.
19463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19464pub enum DateOffset {
19465    Day(i32),
19466    BusinessDay(i32),
19467    MonthEnd(i32),
19468}
19469
19470/// Apply a date offset to a timestamp string and return nanoseconds since epoch.
19471///
19472/// This mirrors `pd.Timestamp(timestamp) + pd.offsets.<Offset>(n)` for the
19473/// supported offsets.
19474pub fn apply_date_offset(timestamp: &str, offset: DateOffset) -> Result<i64, DateRangeError> {
19475    let nanos = parse_datetime_to_nanos(timestamp)?;
19476    apply_date_offset_to_nanos(nanos, offset)
19477}
19478
19479/// Apply a date offset to a nanosecond timestamp.
19480pub fn apply_date_offset_to_nanos(nanos: i64, offset: DateOffset) -> Result<i64, DateRangeError> {
19481    match offset {
19482        DateOffset::Day(days) => nanos
19483            .checked_add(
19484                i64::from(days)
19485                    .checked_mul(Timedelta::NANOS_PER_DAY)
19486                    .ok_or(DateRangeError::InvalidRange)?,
19487            )
19488            .ok_or(DateRangeError::InvalidRange),
19489        DateOffset::BusinessDay(days) => {
19490            let (date, time_nanos) = split_datetime_nanos(nanos)?;
19491            let shifted = apply_business_day_offset(date, days)?;
19492            date_and_time_to_nanos(shifted, time_nanos)
19493        }
19494        DateOffset::MonthEnd(months) => {
19495            let (date, time_nanos) = split_datetime_nanos(nanos)?;
19496            let shifted = apply_month_end_offset(date, months)?;
19497            date_and_time_to_nanos(shifted, time_nanos)
19498        }
19499    }
19500}
19501
19502fn apply_business_day_offset(
19503    date: chrono::NaiveDate,
19504    days: i32,
19505) -> Result<chrono::NaiveDate, DateRangeError> {
19506    if days == 0 {
19507        return next_business_day(date);
19508    }
19509
19510    let mut shifted = date;
19511    if days > 0 {
19512        for _ in 0..days.unsigned_abs() {
19513            shifted = next_business_day(checked_day_step(shifted, 1)?)?;
19514        }
19515    } else {
19516        for _ in 0..days.unsigned_abs() {
19517            shifted = previous_business_day(checked_day_step(shifted, -1)?)?;
19518        }
19519    }
19520    Ok(shifted)
19521}
19522
19523fn last_day_of_month(year: i32, month: u32) -> Result<chrono::NaiveDate, DateRangeError> {
19524    let (next_year, next_month) = if month == 12 {
19525        (year.checked_add(1).ok_or(DateRangeError::InvalidRange)?, 1)
19526    } else {
19527        (year, month + 1)
19528    };
19529    let first_next_month = chrono::NaiveDate::from_ymd_opt(next_year, next_month, 1)
19530        .ok_or(DateRangeError::InvalidRange)?;
19531    checked_day_step(first_next_month, -1)
19532}
19533
19534fn add_months_to_month_end(
19535    date: chrono::NaiveDate,
19536    months: i32,
19537) -> Result<chrono::NaiveDate, DateRangeError> {
19538    use chrono::Datelike;
19539
19540    let month_index = i64::from(date.year())
19541        .checked_mul(12)
19542        .and_then(|value| value.checked_add(i64::from(date.month()) - 1))
19543        .and_then(|value| value.checked_add(i64::from(months)))
19544        .ok_or(DateRangeError::InvalidRange)?;
19545    let year =
19546        i32::try_from(month_index.div_euclid(12)).map_err(|_| DateRangeError::InvalidRange)?;
19547    let month =
19548        u32::try_from(month_index.rem_euclid(12) + 1).map_err(|_| DateRangeError::InvalidRange)?;
19549    last_day_of_month(year, month)
19550}
19551
19552fn month_ordinal(date: chrono::NaiveDate) -> i64 {
19553    use chrono::Datelike;
19554
19555    i64::from(date.year()) * 12 + i64::from(date.month()) - 1
19556}
19557
19558fn apply_month_end_offset(
19559    date: chrono::NaiveDate,
19560    months: i32,
19561) -> Result<chrono::NaiveDate, DateRangeError> {
19562    use chrono::Datelike;
19563
19564    let current_month_end = last_day_of_month(date.year(), date.month())?;
19565    if months == 0 {
19566        return if date == current_month_end {
19567            Ok(date)
19568        } else {
19569            Ok(current_month_end)
19570        };
19571    }
19572
19573    let month_steps = if months > 0 && date != current_month_end {
19574        months - 1
19575    } else {
19576        months
19577    };
19578    add_months_to_month_end(current_month_end, month_steps)
19579}
19580
19581/// pandas' month aliases (`MONTH_ALIASES`), January first.
19582const MONTH_ALIASES: [&str; 12] = [
19583    "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
19584];
19585
19586/// pandas' weekday aliases (`int_to_weekday`), Monday first.
19587const WEEKDAY_ALIASES: [&str; 7] = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];
19588
19589/// pandas' `_maybe_add_count`: the alias, its count in front unless 1.
19590fn with_count(base: &str, count: i64) -> String {
19591    if count == 1 {
19592        base.to_owned()
19593    } else {
19594        format!("{count}{base}")
19595    }
19596}
19597
19598/// pandas' `unique_deltas`: the distinct differences of consecutive values,
19599/// ascending.
19600fn unique_deltas(values: &[i64]) -> Vec<i64> {
19601    let mut deltas: Vec<i64> = values.windows(2).map(|pair| pair[1] - pair[0]).collect();
19602    deltas.sort_unstable();
19603    deltas.dedup();
19604    deltas
19605}
19606
19607/// A fixed step under a day as pandas names it: whole hours, minutes,
19608/// seconds, milli-, microseconds, else nanoseconds, with its count.
19609fn fixed_frequency_name(step: i64) -> Option<String> {
19610    if step == 0 {
19611        return None;
19612    }
19613    for (unit, suffix) in [
19614        (Timedelta::NANOS_PER_HOUR, "h"),
19615        (Timedelta::NANOS_PER_MIN, "min"),
19616        (Timedelta::NANOS_PER_SEC, "s"),
19617        (Timedelta::NANOS_PER_MILLI, "ms"),
19618        (Timedelta::NANOS_PER_MICRO, "us"),
19619    ] {
19620        if step % unit == 0 {
19621            return Some(with_count(suffix, step / unit));
19622        }
19623    }
19624    Some(with_count("ns", step))
19625}
19626
19627/// pandas' `month_position_check`: whether every date is its month's
19628/// calendar end (`ce`), business end (`be`, a Friday within the last three
19629/// days), calendar start (`cs`) or business start (`bs`, a Monday within the
19630/// first three), asked in that order.
19631fn month_position(dates: &[chrono::NaiveDate]) -> Option<&'static str> {
19632    use chrono::Datelike;
19633
19634    let (mut calendar_start, mut business_start) = (true, true);
19635    let (mut calendar_end, mut business_end) = (true, true);
19636    for date in dates {
19637        let (day, weekday) = (date.day(), date.weekday().num_days_from_monday());
19638        let last = last_day_of_month(date.year(), date.month()).ok()?.day();
19639        calendar_start &= day == 1;
19640        business_start &= day == 1 || (day <= 3 && weekday == 0);
19641        calendar_end &= day == last;
19642        business_end &= day == last || (last - day < 3 && weekday == 4);
19643    }
19644    if calendar_end {
19645        Some("ce")
19646    } else if business_end {
19647        Some("be")
19648    } else if calendar_start {
19649        Some("cs")
19650    } else if business_start {
19651        Some("bs")
19652    } else {
19653        None
19654    }
19655}
19656
19657/// pandas' `_infer_daily_rule`, for steps of whole days: an annual, then a
19658/// quarterly, then a monthly rule when every date sits at the same position
19659/// in its month, else a fixed step (`D`, or `W-<weekday>` for whole weeks),
19660/// business days, a week of the month. `deltas` are [`unique_deltas`].
19661fn infer_daily_rule(dates: &[chrono::NaiveDate], deltas: &[i64]) -> Option<String> {
19662    use chrono::Datelike;
19663
19664    let first = dates[0];
19665    let position = month_position(dates);
19666    let years: Vec<i64> = dates.iter().map(|date| i64::from(date.year())).collect();
19667    let ydiffs = unique_deltas(&years);
19668    if ydiffs.len() == 1
19669        && dates.iter().all(|date| date.month() == first.month())
19670        && let Some(rule) = position.and_then(|position| match position {
19671            "cs" => Some("YS"),
19672            "bs" => Some("BYS"),
19673            "ce" => Some("YE"),
19674            "be" => Some("BYE"),
19675            _ => None,
19676        })
19677    {
19678        let month = MONTH_ALIASES[first.month0() as usize];
19679        return Some(with_count(&format!("{rule}-{month}"), ydiffs[0]));
19680    }
19681    let months: Vec<i64> = dates.iter().map(|date| month_ordinal(*date)).collect();
19682    let mdiffs = unique_deltas(&months);
19683    if mdiffs.len() == 1 {
19684        let quarterly = position.and_then(|position| match position {
19685            "cs" => Some("QS"),
19686            "bs" => Some("BQS"),
19687            "ce" => Some("QE"),
19688            "be" => Some("BQE"),
19689            _ => None,
19690        });
19691        if mdiffs[0] % 3 == 0
19692            && let Some(rule) = quarterly
19693        {
19694            // pandas anchors a quarter on the month its first date's month
19695            // shares a remainder with: 0 -> DEC, 2 -> NOV, 1 -> OCT.
19696            let anchor = match first.month() % 3 {
19697                0 => "DEC",
19698                2 => "NOV",
19699                _ => "OCT",
19700            };
19701            return Some(with_count(&format!("{rule}-{anchor}"), mdiffs[0] / 3));
19702        }
19703        if let Some(rule) = position.and_then(|position| match position {
19704            "cs" => Some("MS"),
19705            "bs" => Some("BMS"),
19706            "ce" => Some("ME"),
19707            "be" => Some("BME"),
19708            _ => None,
19709        }) {
19710            return Some(with_count(rule, mdiffs[0]));
19711        }
19712    }
19713    let weekday = first.weekday().num_days_from_monday();
19714    if let [delta] = deltas {
19715        let days = delta / Timedelta::NANOS_PER_DAY;
19716        return Some(if days.rem_euclid(7) == 0 {
19717            with_count(
19718                &format!("W-{}", WEEKDAY_ALIASES[weekday as usize]),
19719                days / 7,
19720            )
19721        } else {
19722            with_count("D", days)
19723        });
19724    }
19725    // Business days: steps of one day, three across a weekend, landing on
19726    // Monday after three and Tuesday..Friday after one.
19727    if deltas == [Timedelta::NANOS_PER_DAY, 3 * Timedelta::NANOS_PER_DAY] {
19728        let mut on = i64::from(weekday);
19729        let business = dates.windows(2).all(|pair| {
19730            let shift = (pair[1] - pair[0]).num_days();
19731            on = (on + shift).rem_euclid(7);
19732            (on == 0 && shift == 3) || ((1..=4).contains(&on) && shift == 1)
19733        });
19734        if business {
19735            return Some("B".to_owned());
19736        }
19737    }
19738    // A week of the month: one weekday, one of the first four weeks.
19739    if dates.iter().all(|date| date.weekday() == first.weekday()) {
19740        let mut weeks: Vec<u32> = dates
19741            .iter()
19742            .map(|date| (date.day() - 1) / 7)
19743            .filter(|week| *week < 4)
19744            .collect();
19745        weeks.sort_unstable();
19746        weeks.dedup();
19747        if let [week] = weeks[..] {
19748            return Some(format!(
19749                "WOM-{}{}",
19750                week + 1,
19751                WEEKDAY_ALIASES[weekday as usize]
19752            ));
19753        }
19754    }
19755    None
19756}
19757
19758/// Infer a pandas-style frequency string from a DatetimeIndex.
19759///
19760/// Returns `Ok(None)` for irregular or duplicate timestamp sequences. Returns
19761/// an error for the pandas-compatible "fewer than 3 dates" case.
19762pub fn infer_freq(index: &Index) -> Result<Option<String>, DateRangeError> {
19763    if let Some(range) = index.labels.datetime64_affine_range() {
19764        if range.position(i64::MIN).is_some() {
19765            return Ok(None);
19766        }
19767        if range.len < 3 {
19768            return Err(DateRangeError::InsufficientDates);
19769        }
19770        // A step of whole days is pandas' daily rule, which reads the dates
19771        // (annual / weekly anchors) - from the range's arithmetic, its labels
19772        // left unbuilt; a shorter one is its unit.
19773        if range.step % Timedelta::NANOS_PER_DAY != 0 {
19774            return Ok(fixed_frequency_name(range.step));
19775        }
19776        let mut values = Vec::with_capacity(range.len);
19777        let mut value = range.start;
19778        for _ in 0..range.len {
19779            values.push(value);
19780            value = value.wrapping_add(range.step);
19781        }
19782        return infer_freq_from_nanos(&values);
19783    }
19784
19785    let mut values = Vec::with_capacity(index.len());
19786    for label in index.labels() {
19787        match label {
19788            IndexLabel::Datetime64(value) if *value != i64::MIN => values.push(*value),
19789            IndexLabel::Datetime64(_) => return Ok(None),
19790            _ => {
19791                return Err(DateRangeError::ParseError(
19792                    "expected datetime64 index".to_owned(),
19793                ));
19794            }
19795        }
19796    }
19797    infer_freq_from_nanos(&values)
19798}
19799
19800/// Infer a pandas-style frequency string from timestamp strings.
19801pub fn infer_freq_from_timestamps(timestamps: &[&str]) -> Result<Option<String>, DateRangeError> {
19802    let values: Vec<i64> = timestamps
19803        .iter()
19804        .map(|timestamp| parse_datetime_to_nanos(timestamp))
19805        .collect::<Result<_, _>>()?;
19806    infer_freq_from_nanos(&values)
19807}
19808
19809/// Infer a pandas-style frequency string from nanosecond timestamps, as
19810/// pandas' `_FrequencyInferer.get_freq` does: None unless strictly
19811/// increasing or decreasing; when the smallest step is whole days, its daily
19812/// rule ([`infer_daily_rule`]: YS-JAN, QE-DEC, MS, W-MON, B, WOM-3FRI...);
19813/// business hours (`bh`) for steps of 1 / 17 / 65 hours; else one fixed step
19814/// in its unit (`15min`, `-1h`), None for several.
19815pub fn infer_freq_from_nanos(values: &[i64]) -> Result<Option<String>, DateRangeError> {
19816    if values.len() < 3 {
19817        return Err(DateRangeError::InsufficientDates);
19818    }
19819    let increasing = values.windows(2).all(|pair| pair[1] > pair[0]);
19820    if !increasing && !values.windows(2).all(|pair| pair[1] < pair[0]) {
19821        return Ok(None);
19822    }
19823    let deltas = unique_deltas(values);
19824    if deltas[0] % Timedelta::NANOS_PER_DAY == 0 {
19825        let dates: Vec<chrono::NaiveDate> = values
19826            .iter()
19827            .map(|value| split_datetime_nanos(*value).map(|(date, _)| date))
19828            .collect::<Result<_, _>>()?;
19829        return Ok(infer_daily_rule(&dates, &deltas));
19830    }
19831    let hour = Timedelta::NANOS_PER_HOUR;
19832    if deltas.iter().all(|delta| delta % hour == 0) {
19833        let hours: Vec<i64> = deltas.iter().map(|delta| delta / hour).collect();
19834        if matches!(hours.as_slice(), [1, 17] | [1, 65] | [1, 17, 65]) {
19835            return Ok(Some("bh".to_owned()));
19836        }
19837    }
19838    Ok(match deltas.as_slice() {
19839        [step] => fixed_frequency_name(*step),
19840        _ => None,
19841    })
19842}
19843
19844/// Create a DatetimeIndex with evenly spaced values.
19845///
19846/// Analogous to `pd.date_range()`. Must specify exactly two of:
19847/// start, end, periods. Frequency defaults to 1 day.
19848///
19849/// # Examples
19850/// ```
19851/// use fp_index::date_range;
19852/// use fp_types::Timedelta;
19853///
19854/// let idx = date_range(
19855///     Some("2024-01-01"),
19856///     None,
19857///     Some(3),
19858///     Timedelta::NANOS_PER_DAY,
19859///     None,
19860/// ).unwrap();
19861/// assert_eq!(idx.len(), 3);
19862/// ```
19863pub fn date_range(
19864    start: Option<&str>,
19865    end: Option<&str>,
19866    periods: Option<usize>,
19867    freq: i64,
19868    name: Option<&str>,
19869) -> Result<Index, DateRangeError> {
19870    if freq <= 0 {
19871        return Err(DateRangeError::NonPositiveFreq);
19872    }
19873
19874    let start_ns = start.map(parse_datetime_to_nanos).transpose()?;
19875    let end_ns = end.map(parse_datetime_to_nanos).transpose()?;
19876
19877    let (start_val, count) = match (start_ns, end_ns, periods) {
19878        (Some(s), Some(e), None) => {
19879            if e < s {
19880                return Err(DateRangeError::InvalidRange);
19881            }
19882            let span = e.checked_sub(s).ok_or(DateRangeError::InvalidRange)?;
19883            let n = (span / freq + 1) as usize;
19884            (s, n)
19885        }
19886        (Some(s), None, Some(p)) => (s, p),
19887        (None, Some(e), Some(p)) => {
19888            let offset = checked_date_range_offset(p.saturating_sub(1), freq)?;
19889            let s = e.checked_sub(offset).ok_or(DateRangeError::InvalidRange)?;
19890            (s, p)
19891        }
19892        (Some(_), Some(_), Some(_)) => return Err(DateRangeError::TooManyParams),
19893        _ => return Err(DateRangeError::InsufficientParams),
19894    };
19895
19896    let last_offset = checked_date_range_offset(count.saturating_sub(1), freq)?;
19897    start_val
19898        .checked_add(last_offset)
19899        .ok_or(DateRangeError::InvalidRange)?;
19900
19901    let mut idx = Index::from_datetime64_affine_range(start_val, freq, count)
19902        .ok_or(DateRangeError::InvalidRange)?;
19903    if let Some(n) = name {
19904        idx = idx.set_name(n);
19905    }
19906    Ok(idx)
19907}
19908
19909fn checked_date_range_offset(steps: usize, freq: i64) -> Result<i64, DateRangeError> {
19910    let steps = i64::try_from(steps).map_err(|_| DateRangeError::InvalidRange)?;
19911    steps.checked_mul(freq).ok_or(DateRangeError::InvalidRange)
19912}
19913
19914/// Create a DatetimeIndex with default weekday-only business-day values.
19915///
19916/// Analogous to `pd.bdate_range(..., freq="B")` for the default Monday-Friday
19917/// calendar. Exactly two of start, end, and periods must be specified.
19918pub fn bdate_range(
19919    start: Option<&str>,
19920    end: Option<&str>,
19921    periods: Option<usize>,
19922    name: Option<&str>,
19923) -> Result<Index, DateRangeError> {
19924    let start_date = start
19925        .map(parse_datetime_to_nanos)
19926        .transpose()?
19927        .map(datetime_nanos_to_date)
19928        .transpose()?;
19929    let end_date = end
19930        .map(parse_datetime_to_nanos)
19931        .transpose()?
19932        .map(datetime_nanos_to_date)
19933        .transpose()?;
19934
19935    let nanos = match (start_date, end_date, periods) {
19936        (Some(start), Some(end), None) => collect_business_days_between(start, end)?,
19937        (Some(start), None, Some(periods)) => collect_business_days_from_start(start, periods)?,
19938        (None, Some(end), Some(periods)) => collect_business_days_through_end(end, periods)?,
19939        (Some(_), Some(_), Some(_)) => return Err(DateRangeError::TooManyParams),
19940        _ => return Err(DateRangeError::InsufficientParams),
19941    };
19942
19943    let mut idx = Index::from_datetime64(nanos);
19944    if let Some(n) = name {
19945        idx = idx.set_name(n);
19946    }
19947    Ok(idx)
19948}
19949
19950// ── MultiIndex ──────────────────────────────────────────────────────────
19951
19952/// Slicing specification for index and MultiIndex selections, matching `pd.IndexSlice`.
19953#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
19954pub struct IndexSlice<T = IndexLabel> {
19955    pub start: Option<T>,
19956    pub stop: Option<T>,
19957    pub step: Option<isize>,
19958}
19959
19960impl<T> IndexSlice<T> {
19961    /// Create a new `IndexSlice` with explicit start, stop, and step.
19962    #[must_use]
19963    pub const fn new(start: Option<T>, stop: Option<T>, step: Option<isize>) -> Self {
19964        Self { start, stop, step }
19965    }
19966
19967    /// Match a full slice `[:]`.
19968    #[must_use]
19969    pub const fn all() -> Self {
19970        Self {
19971            start: None,
19972            stop: None,
19973            step: None,
19974        }
19975    }
19976
19977    /// Create an `IndexSlice` from start and stop bounds.
19978    #[must_use]
19979    pub const fn from_bounds(start: Option<T>, stop: Option<T>) -> Self {
19980        Self {
19981            start,
19982            stop,
19983            step: None,
19984        }
19985    }
19986
19987    /// Create an `IndexSlice` with only a start bound `[start:]`.
19988    #[must_use]
19989    pub const fn from_start(start: T) -> Self {
19990        Self {
19991            start: Some(start),
19992            stop: None,
19993            step: None,
19994        }
19995    }
19996
19997    /// Create an `IndexSlice` with only a stop bound `[:stop]`.
19998    #[must_use]
19999    pub const fn from_stop(stop: T) -> Self {
20000        Self {
20001            start: None,
20002            stop: Some(stop),
20003            step: None,
20004        }
20005    }
20006}
20007
20008/// A hierarchical (multi-level) index for DataFrames and Series.
20009///
20010/// Stores multiple levels of labels as separate vectors (columnar layout),
20011/// analogous to pandas `pd.MultiIndex`. Each row position has one label
20012/// per level. The combination of labels across all levels forms the
20013/// composite key for that row.
20014///
20015/// This type exists alongside `Index` and can be converted to/from it.
20016/// Full DataFrame integration is a future step.
20017#[derive(Debug, Clone, Serialize, Deserialize)]
20018pub struct MultiIndex {
20019    /// One `Vec<IndexLabel>` per level, all the same length (= nrows).
20020    levels: Vec<Vec<IndexLabel>>,
20021    /// Optional name for each level, typed: set_index([0, 1]) names them the
20022    /// integers 0 and 1 (fvsao.64).
20023    names: Vec<Option<LabelName>>,
20024    /// Per-level first-seen identity codes, used by duplicate/unique kernels.
20025    #[serde(skip)]
20026    identity_codes: Option<Vec<Vec<u32>>>,
20027    /// A missing label is a value of its level - pandas' groupby
20028    /// (dropna=False) keys, NaN inside `levels` - rather than pandas' code
20029    /// -1 (set_index, from_arrays): an unstack sorts it with the values
20030    /// (last) instead of first. Only [`Self::with_missing_as_level`] sets it.
20031    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
20032    missing_is_a_level: bool,
20033}
20034
20035/// Typed position plan for an outer alignment of two unique MultiIndexes.
20036///
20037/// Each vector is indexed by `union_index` row and names the corresponding
20038/// source row, or `None` when that side has no matching tuple.
20039#[derive(Debug, Clone, PartialEq)]
20040pub struct MultiIndexOuterAlignment {
20041    pub union_index: MultiIndex,
20042    pub left_positions: Vec<Option<usize>>,
20043    pub right_positions: Vec<Option<usize>>,
20044}
20045
20046type Utf8LevelPair<'a> = (&'a [IndexLabel], &'a [IndexLabel]);
20047type Utf8LevelPairs<'a> = (Utf8LevelPair<'a>, Utf8LevelPair<'a>);
20048
20049struct CompactIdentityCodeLayout<'a> {
20050    level0: &'a [u32],
20051    level1: &'a [u32],
20052    level1_cardinality: usize,
20053    slot_count: usize,
20054}
20055
20056impl CompactIdentityCodeLayout<'_> {
20057    #[inline]
20058    fn slot(&self, row: usize) -> usize {
20059        self.level0[row] as usize * self.level1_cardinality + self.level1[row] as usize
20060    }
20061}
20062
20063fn multi_index_codes_memory_usage(nlevels: usize, len: usize) -> usize {
20064    nlevels
20065        .saturating_mul(len)
20066        .saturating_mul(std::mem::size_of::<isize>())
20067}
20068
20069fn build_multi_index_identity_codes(levels: &[Vec<IndexLabel>]) -> Option<Vec<Vec<u32>>> {
20070    if levels.len() != 2 {
20071        return None;
20072    }
20073    let len = levels.first().map_or(0, Vec::len);
20074    if len == 0 || levels[1].len() != len {
20075        return None;
20076    }
20077    let slot_cap = len.saturating_mul(8).max(1024);
20078
20079    let mut level0_positions =
20080        FxHashMap::<&IndexLabel, u32>::with_capacity_and_hasher(len, Default::default());
20081    let mut level0_codes = Vec::with_capacity(len);
20082    for label in &levels[0] {
20083        if let Some(&code) = level0_positions.get(label) {
20084            level0_codes.push(code);
20085        } else {
20086            let code = u32::try_from(level0_positions.len()).ok()?;
20087            level0_positions.insert(label, code);
20088            level0_codes.push(code);
20089        }
20090    }
20091    let level0_cardinality = level0_positions.len();
20092    if level0_cardinality > slot_cap {
20093        return None;
20094    }
20095
20096    let mut level1_positions =
20097        FxHashMap::<&IndexLabel, u32>::with_capacity_and_hasher(len, Default::default());
20098    let mut level1_codes = Vec::with_capacity(len);
20099    for label in &levels[1] {
20100        if let Some(&code) = level1_positions.get(label) {
20101            level1_codes.push(code);
20102        } else {
20103            let next_cardinality = level1_positions.len().checked_add(1)?;
20104            let slot_count = level0_cardinality.checked_mul(next_cardinality)?;
20105            if slot_count > slot_cap {
20106                return None;
20107            }
20108            let code = u32::try_from(level1_positions.len()).ok()?;
20109            level1_positions.insert(label, code);
20110            level1_codes.push(code);
20111        }
20112    }
20113    Some(vec![level0_codes, level1_codes])
20114}
20115
20116impl PartialEq for MultiIndex {
20117    fn eq(&self, other: &Self) -> bool {
20118        self.levels == other.levels && self.names == other.names
20119    }
20120}
20121
20122impl MultiIndex {
20123    fn from_levels_and_names(levels: Vec<Vec<IndexLabel>>, names: Vec<Option<LabelName>>) -> Self {
20124        let identity_codes = build_multi_index_identity_codes(&levels);
20125        Self {
20126            levels,
20127            names,
20128            identity_codes,
20129            missing_is_a_level: false,
20130        }
20131    }
20132
20133    /// These levels with a missing label read as a value of its level (see
20134    /// the field): a groupby result's keys under dropna=False.
20135    #[must_use]
20136    pub fn with_missing_as_level(mut self, missing_is_a_level: bool) -> Self {
20137        self.missing_is_a_level = missing_is_a_level;
20138        self
20139    }
20140
20141    /// Whether a missing label is a value of its level (see the field).
20142    #[must_use]
20143    pub fn missing_is_a_level(&self) -> bool {
20144        self.missing_is_a_level
20145    }
20146
20147    fn compact_two_level_identity_layout(&self) -> Option<CompactIdentityCodeLayout<'_>> {
20148        let codes = self.identity_codes.as_ref()?;
20149        if codes.len() != 2 || codes[0].len() != self.len() || codes[1].len() != self.len() {
20150            return None;
20151        }
20152        let level0_cardinality = codes[0]
20153            .iter()
20154            .copied()
20155            .max()
20156            .map_or(0usize, |code| code as usize + 1);
20157        let level1_cardinality = codes[1]
20158            .iter()
20159            .copied()
20160            .max()
20161            .map_or(0usize, |code| code as usize + 1);
20162        let slot_count = level0_cardinality.checked_mul(level1_cardinality)?;
20163        if slot_count == 0 {
20164            return None;
20165        }
20166        if slot_count > self.len().saturating_mul(8).max(1024) {
20167            return None;
20168        }
20169        Some(CompactIdentityCodeLayout {
20170            level0: &codes[0],
20171            level1: &codes[1],
20172            level1_cardinality,
20173            slot_count,
20174        })
20175    }
20176
20177    /// Number of levels in this MultiIndex.
20178    #[must_use]
20179    pub fn nlevels(&self) -> usize {
20180        self.levels.len()
20181    }
20182
20183    /// Number of rows (entries) in this MultiIndex.
20184    #[must_use]
20185    pub fn len(&self) -> usize {
20186        self.levels.first().map_or(0, Vec::len)
20187    }
20188
20189    /// Whether this MultiIndex has zero entries.
20190    #[must_use]
20191    pub fn is_empty(&self) -> bool {
20192        self.len() == 0
20193    }
20194
20195    /// Compare two rows lexicographically across all levels.
20196    ///
20197    /// Private helper for sortedness predicates. Returns `Ordering::Equal`
20198    /// only when every level value matches exactly.
20199    fn row_cmp(&self, a: usize, b: usize) -> std::cmp::Ordering {
20200        for level in 0..self.nlevels() {
20201            let ord = self.levels[level][a].cmp(&self.levels[level][b]);
20202            if ord != std::cmp::Ordering::Equal {
20203                return ord;
20204            }
20205        }
20206        std::cmp::Ordering::Equal
20207    }
20208
20209    /// Whether this MultiIndex is sorted in lexicographic (row-major) order.
20210    ///
20211    /// Matches `pd.MultiIndex.is_monotonic_increasing`. Row `i` must be less
20212    /// than or equal to row `i+1` under level-by-level comparison. Empty or
20213    /// single-row indexes return `true` (trivially sorted).
20214    ///
20215    /// Per br-frankenpandas-w4uu: pandas `df.loc['A':'B']` on a MultiIndex
20216    /// raises `KeyError: MultiIndex slicing requires the index to be
20217    /// lexsorted` when this predicate is false. fp-frame's range-slice
20218    /// callers should gate on this before delegating to `slice_locs`.
20219    #[must_use]
20220    pub fn is_monotonic_increasing(&self) -> bool {
20221        if self.len() <= 1 {
20222            return true;
20223        }
20224        (0..self.len() - 1).all(|i| self.row_cmp(i, i + 1) != std::cmp::Ordering::Greater)
20225    }
20226
20227    /// Whether this MultiIndex is sorted in strictly descending order.
20228    ///
20229    /// Matches `pd.MultiIndex.is_monotonic_decreasing`. Row `i` must be
20230    /// greater than or equal to row `i+1`. Empty / single-row: `true`.
20231    #[must_use]
20232    pub fn is_monotonic_decreasing(&self) -> bool {
20233        if self.len() <= 1 {
20234            return true;
20235        }
20236        (0..self.len() - 1).all(|i| self.row_cmp(i, i + 1) != std::cmp::Ordering::Less)
20237    }
20238
20239    /// Alias for `is_monotonic_increasing`.
20240    ///
20241    /// ⚠️ REMOVED, not deprecated: `pd.MultiIndex.is_lexsorted` raises
20242    /// `AttributeError` on 2.2.3 (deprecated in 1.x, dropped in 2.0). Kept as a
20243    /// convenience alias for migrated code -- an FP superset, not parity.
20244    #[must_use]
20245    pub fn is_lexsorted(&self) -> bool {
20246        self.is_monotonic_increasing()
20247    }
20248
20249    /// Level names, typed ([`LabelName`]).
20250    #[must_use]
20251    pub fn names(&self) -> &[Option<LabelName>] {
20252        &self.names
20253    }
20254
20255    /// Scalar index name, matching `pd.MultiIndex.name`.
20256    #[must_use]
20257    pub const fn name(&self) -> Option<&LabelName> {
20258        None
20259    }
20260
20261    /// Number of entries, matching `pd.MultiIndex.size`.
20262    #[must_use]
20263    pub fn size(&self) -> usize {
20264        self.len()
20265    }
20266
20267    /// Shape of this one-dimensional index, matching `pd.MultiIndex.shape`.
20268    #[must_use]
20269    pub fn shape(&self) -> (usize,) {
20270        (self.len(),)
20271    }
20272
20273    /// Number of dimensions, matching `pd.MultiIndex.ndim`.
20274    #[must_use]
20275    pub fn ndim(&self) -> usize {
20276        1
20277    }
20278
20279    /// Alias for `is_empty`, matching the pandas `.empty` property.
20280    #[must_use]
20281    pub fn empty(&self) -> bool {
20282        self.is_empty()
20283    }
20284
20285    fn shift_unsupported_error() -> IndexError {
20286        IndexError::InvalidArgument(
20287            "This method is only implemented for DatetimeIndex, PeriodIndex and TimedeltaIndex; Got type MultiIndex"
20288                .to_owned(),
20289        )
20290    }
20291
20292    /// Unsupported temporal shift, matching `pd.MultiIndex.shift(...)`.
20293    pub fn shift(&self, _periods: i64, _freq: Option<&str>) -> Result<Self, IndexError> {
20294        Err(Self::shift_unsupported_error())
20295    }
20296
20297    fn astype_categorical_error() -> IndexError {
20298        IndexError::InvalidArgument(
20299            "> 1 ndim Categorical are not supported at this time".to_owned(),
20300        )
20301    }
20302
20303    fn astype_unsupported_dtype_error(dtype: &str) -> IndexError {
20304        IndexError::InvalidArgument(format!(
20305            "Setting a MultiIndex dtype to anything other than object is not supported; got {dtype}"
20306        ))
20307    }
20308
20309    /// Cast labels to a different dtype, matching `pd.MultiIndex.astype(...)`.
20310    ///
20311    /// Pandas only supports the object dtype on MultiIndex; categorical raises
20312    /// `NotImplementedError` and any other dtype raises `TypeError`. Object
20313    /// returns a clone of the index.
20314    pub fn astype(&self, dtype: &str) -> Result<Self, IndexError> {
20315        match dtype {
20316            "object" | "O" => Ok(self.clone()),
20317            "category" => Err(Self::astype_categorical_error()),
20318            other => Err(Self::astype_unsupported_dtype_error(other)),
20319        }
20320    }
20321
20322    fn diff_unsupported_error() -> IndexError {
20323        IndexError::InvalidArgument(
20324            "cannot perform __sub__ with this index type: MultiIndex".to_owned(),
20325        )
20326    }
20327
20328    /// Unsupported positional differencing, matching `pd.MultiIndex.diff(...)`.
20329    ///
20330    /// Pandas defines `Index.diff` as `self - self.shift(periods)` and raises
20331    /// `TypeError` because tuple-valued levels do not support subtraction.
20332    pub fn diff(&self, _periods: i64) -> Result<Self, IndexError> {
20333        Err(Self::diff_unsupported_error())
20334    }
20335
20336    /// Numeric rounding, matching `pd.MultiIndex.round(...)`, which is a NO-OP
20337    /// returning an equal copy.
20338    ///
20339    /// ⚠️ THIS USED TO REFUSE, on the reasoning that "pandas applies `np.around`
20340    /// to the underlying values; tuple-valued MultiIndex labels do not support
20341    /// `rint`". That conflates two different calls. MEASURED, live pandas 2.2.3:
20342    ///
20343    /// ```text
20344    /// mi = pd.MultiIndex.from_tuples([(1.567, "a"), (2.345, "b")])
20345    /// mi.round(0) / round(2) / round(-1)  -> [(1.567, 'a'), (2.345, 'b')]  unchanged
20346    /// mi.round(2).equals(mi)              -> True   (a copy, not the same object)
20347    /// np.around(mi, 2)                    -> TypeError: can't multiply sequence
20348    ///                                        by non-int of type 'float'
20349    /// ```
20350    ///
20351    /// So `np.around(index)` does raise — but `Index.round()` never reaches it for
20352    /// a MultiIndex, and the float level value is NOT rounded either. The old
20353    /// error text was numpy's `rint` message, which is not even what numpy emits
20354    /// on this input.
20355    ///
20356    /// `decimals` is accepted and ignored, exactly as pandas does.
20357    pub fn round(&self, _decimals: i32) -> Result<Self, IndexError> {
20358        Ok(self.clone())
20359    }
20360
20361    fn string_accessor_error() -> IndexError {
20362        IndexError::InvalidArgument(
20363            "Can only use .str accessor with Index, not MultiIndex".to_owned(),
20364        )
20365    }
20366
20367    /// Unsupported string accessor.
20368    ///
20369    /// Refusing IS the parity behaviour: `pd.MultiIndex.str` raises
20370    /// `AttributeError` on 2.2.3 (a plain string-valued `pd.Index` DOES carry
20371    /// `.str`; a MultiIndex does not). The wording before cited the attribute as
20372    /// though it existed.
20373    pub fn r#str(&self) -> Result<(), IndexError> {
20374        Err(Self::string_accessor_error())
20375    }
20376
20377    fn asof_comparison_type_name(&self) -> &'static str {
20378        match self.levels.first().and_then(|level| level.first()) {
20379            Some(IndexLabel::Int64(_)) => "int",
20380            Some(IndexLabel::Float64(_)) => "float",
20381            Some(IndexLabel::Bool(_)) => "bool",
20382            Some(IndexLabel::Utf8(_)) => "str",
20383            Some(IndexLabel::Timedelta64(_)) => "Timedelta",
20384            Some(IndexLabel::Datetime64(_)) => "Timestamp",
20385            Some(IndexLabel::Null(fp_types::NullKind::Null)) => "NoneType",
20386            Some(IndexLabel::Null(fp_types::NullKind::NaN)) => "float",
20387            Some(IndexLabel::Null(fp_types::NullKind::NaT)) => "NaTType",
20388            Some(IndexLabel::Period(_)) => "Period",
20389            Some(IndexLabel::Interval(_)) => "Interval",
20390            Some(IndexLabel::Object(_)) | None => "object",
20391        }
20392    }
20393
20394    fn asof_unsupported_error(&self) -> IndexError {
20395        IndexError::InvalidArgument(format!(
20396            "'<' not supported between instances of 'tuple' and '{}'",
20397            self.asof_comparison_type_name()
20398        ))
20399    }
20400
20401    /// Unsupported nearest-key lookup, matching `pd.MultiIndex.asof(...)`.
20402    pub fn asof(&self, _key: &[IndexLabel]) -> Result<Option<Vec<IndexLabel>>, IndexError> {
20403        if self.is_empty() {
20404            return Ok(None);
20405        }
20406        Err(self.asof_unsupported_error())
20407    }
20408
20409    fn asof_locs_no_mask_error() -> IndexError {
20410        IndexError::InvalidArgument("object too deep for desired array".to_owned())
20411    }
20412
20413    fn asof_locs_empty_mask_error() -> IndexError {
20414        IndexError::InvalidArgument("attempt to get argmax of an empty sequence".to_owned())
20415    }
20416
20417    fn asof_locs_empty_take_error() -> IndexError {
20418        IndexError::InvalidArgument("cannot do a non-empty take from an empty axes.".to_owned())
20419    }
20420
20421    fn asof_locs_mask_length_error(expected: usize, actual: usize) -> IndexError {
20422        IndexError::InvalidArgument(format!(
20423            "boolean index did not match indexed array along axis 0; size of axis is {expected} but size of corresponding boolean axis is {actual}"
20424        ))
20425    }
20426
20427    fn asof_locs_broadcast_error(where_len: usize) -> IndexError {
20428        IndexError::InvalidArgument(format!(
20429            "operands could not be broadcast together with shapes ({where_len},) (2,)"
20430        ))
20431    }
20432
20433    /// Unsupported nearest-position lookup, matching `pd.MultiIndex.asof_locs(...)`.
20434    pub fn asof_locs(
20435        &self,
20436        where_index: &Self,
20437        mask: Option<&[bool]>,
20438    ) -> Result<Vec<Option<usize>>, IndexError> {
20439        let Some(mask) = mask else {
20440            return Err(Self::asof_locs_no_mask_error());
20441        };
20442        if mask.len() != self.len() {
20443            return Err(Self::asof_locs_mask_length_error(self.len(), mask.len()));
20444        }
20445        if mask.is_empty() && self.is_empty() && where_index.is_empty() {
20446            return Err(Self::asof_locs_empty_mask_error());
20447        }
20448        if mask.iter().all(|include| !*include) && !where_index.is_empty() {
20449            return Err(Self::asof_locs_empty_take_error());
20450        }
20451        Err(Self::asof_locs_broadcast_error(where_index.len()))
20452    }
20453
20454    /// Set the names for all levels.
20455    #[must_use]
20456    pub fn set_names(mut self, names: Vec<Option<LabelName>>) -> Self {
20457        // Pad or truncate to match nlevels.
20458        self.names = names;
20459        self.names.resize(self.nlevels(), None);
20460        self
20461    }
20462
20463    /// Rename all MultiIndex levels, matching `pd.MultiIndex.rename(names)`.
20464    ///
20465    /// Unlike [`Self::set_names`], pandas rename requires one name per level
20466    /// and returns a renamed clone without mutating the source index.
20467    pub fn rename(&self, names: Vec<Option<LabelName>>) -> Result<Self, IndexError> {
20468        if names.len() != self.nlevels() {
20469            return Err(IndexError::LengthMismatch {
20470                expected: self.nlevels(),
20471                actual: names.len(),
20472                context: "MultiIndex.rename names length".to_owned(),
20473            });
20474        }
20475        Ok(Self::from_levels_and_names(self.levels.clone(), names))
20476    }
20477
20478    /// Rename one MultiIndex level, matching `pd.MultiIndex.rename(name, level=...)`.
20479    pub fn rename_level(&self, name: Option<LabelName>, level: usize) -> Result<Self, IndexError> {
20480        if level >= self.nlevels() {
20481            return Err(IndexError::OutOfBounds {
20482                position: level,
20483                length: self.nlevels(),
20484            });
20485        }
20486        let mut names = self.names.clone();
20487        names[level] = name;
20488        Ok(Self::from_levels_and_names(self.levels.clone(), names))
20489    }
20490
20491    fn shared_names(&self, other: &Self) -> Vec<Option<LabelName>> {
20492        self.names
20493            .iter()
20494            .zip(&other.names)
20495            .map(
20496                |(left, right)| {
20497                    if left == right { left.clone() } else { None }
20498                },
20499            )
20500            .collect()
20501    }
20502
20503    fn ensure_same_nlevels(&self, other: &Self) -> Result<(), IndexError> {
20504        if self.nlevels() != other.nlevels() {
20505            return Err(IndexError::LengthMismatch {
20506                expected: self.nlevels(),
20507                actual: other.nlevels(),
20508                context: "MultiIndex level count mismatch".to_owned(),
20509            });
20510        }
20511        Ok(())
20512    }
20513
20514    /// Build the AACE outer-alignment witness without materializing composite
20515    /// `Vec<IndexLabel>` tuples when the per-level codes fit in a `u64`.
20516    ///
20517    /// Outer alignment is only position-preserving for unique composite labels;
20518    /// duplicate tuples retain pandas' duplicate-aware expansion surface and
20519    /// are rejected here rather than silently choosing a first occurrence.
20520    pub fn outer_align(&self, other: &Self) -> Result<MultiIndexOuterAlignment, IndexError> {
20521        self.ensure_same_nlevels(other)?;
20522        if self.has_duplicates() || other.has_duplicates() {
20523            return Err(IndexError::InvalidArgument(
20524                "outer_align requires uniquely valued MultiIndexes".to_owned(),
20525            ));
20526        }
20527
20528        if let Some((left_keys, right_keys)) = self.factorize_packed_keys(other) {
20529            let mut union_levels: Vec<Vec<IndexLabel>> = self
20530                .levels
20531                .iter()
20532                .map(|_| Vec::with_capacity(self.len().saturating_add(other.len())))
20533                .collect();
20534            let mut union_positions =
20535                FxHashMap::<u64, usize>::with_capacity_and_hasher(self.len(), Default::default());
20536            let mut left_positions = Vec::with_capacity(self.len().saturating_add(other.len()));
20537            let mut right_positions = Vec::with_capacity(self.len().saturating_add(other.len()));
20538
20539            for (row, &key) in left_keys.iter().enumerate() {
20540                union_positions.insert(key, left_positions.len());
20541                for (out, level) in union_levels.iter_mut().zip(&self.levels) {
20542                    out.push(level[row].clone());
20543                }
20544                left_positions.push(Some(row));
20545                right_positions.push(None);
20546            }
20547            for (row, &key) in right_keys.iter().enumerate() {
20548                if let Some(&union_row) = union_positions.get(&key) {
20549                    right_positions[union_row] = Some(row);
20550                } else {
20551                    union_positions.insert(key, left_positions.len());
20552                    for (out, level) in union_levels.iter_mut().zip(&other.levels) {
20553                        out.push(level[row].clone());
20554                    }
20555                    left_positions.push(None);
20556                    right_positions.push(Some(row));
20557                }
20558            }
20559
20560            return Ok(MultiIndexOuterAlignment {
20561                union_index: Self::from_levels_and_names(union_levels, self.shared_names(other)),
20562                left_positions,
20563                right_positions,
20564            });
20565        }
20566
20567        let union_index = self.union(other)?;
20568        Ok(MultiIndexOuterAlignment {
20569            left_positions: self
20570                .get_indexer(&union_index)?
20571                .into_iter()
20572                .map(|position| usize::try_from(position).ok())
20573                .collect(),
20574            right_positions: other
20575                .get_indexer(&union_index)?
20576                .into_iter()
20577                .map(|position| usize::try_from(position).ok())
20578                .collect(),
20579            union_index,
20580        })
20581    }
20582
20583    fn tuple_at(&self, row: usize) -> Vec<IndexLabel> {
20584        self.levels.iter().map(|level| level[row].clone()).collect()
20585    }
20586
20587    fn take_existing_positions(&self, positions: &[usize]) -> Self {
20588        let levels = self
20589            .levels
20590            .iter()
20591            .map(|level| {
20592                positions
20593                    .iter()
20594                    .map(|&position| level[position].clone())
20595                    .collect()
20596            })
20597            .collect();
20598        Self::from_levels_and_names(levels, self.names.clone())
20599            .with_missing_as_level(self.missing_is_a_level)
20600    }
20601
20602    fn missing_label_for_level(&self, level_idx: usize) -> IndexLabel {
20603        self.levels[level_idx]
20604            .iter()
20605            .find(|label| label.is_missing())
20606            .cloned()
20607            .unwrap_or(IndexLabel::Datetime64(i64::MIN))
20608    }
20609
20610    fn from_tuples_with_names(
20611        tuples: Vec<Vec<IndexLabel>>,
20612        names: Vec<Option<LabelName>>,
20613    ) -> Result<Self, IndexError> {
20614        Ok(Self::from_tuples(tuples)?.set_names(names))
20615    }
20616
20617    /// A level's catalog as pandas factorizes it (sorted, its `safe_sort`):
20618    /// the distinct non-missing labels, numbers (bools, ints, floats) by
20619    /// value first, then strings, then any other kind in its own order.
20620    fn level_catalog(level: &[IndexLabel]) -> Vec<IndexLabel> {
20621        fn number(label: &IndexLabel) -> Option<f64> {
20622            match label {
20623                IndexLabel::Bool(value) => Some(f64::from(u8::from(*value))),
20624                #[allow(clippy::cast_precision_loss)] // only ordering int vs float
20625                IndexLabel::Int64(value) => Some(*value as f64),
20626                IndexLabel::Float64(value) => Some(value.0),
20627                _ => None,
20628            }
20629        }
20630        fn kind(label: &IndexLabel) -> u8 {
20631            match label {
20632                IndexLabel::Bool(_) | IndexLabel::Int64(_) | IndexLabel::Float64(_) => 0,
20633                IndexLabel::Utf8(_) => 1,
20634                _ => 2,
20635            }
20636        }
20637        let mut seen = FxHashMap::<&IndexLabel, ()>::default();
20638        let mut catalog: Vec<IndexLabel> = level
20639            .iter()
20640            .filter(|label| !label.is_missing() && seen.insert(label, ()).is_none())
20641            .cloned()
20642            .collect();
20643        catalog.sort_by(|a, b| match (a, b) {
20644            (IndexLabel::Int64(x), IndexLabel::Int64(y)) => x.cmp(y),
20645            _ => match (number(a), number(b)) {
20646                (Some(x), Some(y)) => x.total_cmp(&y).then_with(|| a.cmp(b)),
20647                _ => kind(a).cmp(&kind(b)).then_with(|| a.cmp(b)),
20648            },
20649        });
20650        catalog
20651    }
20652
20653    /// Unique labels for each level, sorted as pandas factorizes them
20654    /// (br-frankenpandas-98f6w: they kept first-seen order).
20655    ///
20656    /// Matches `pd.MultiIndex.levels`. Missing labels are excluded from the
20657    /// level catalog and receive `-1` in `codes()`.
20658    #[must_use]
20659    pub fn levels(&self) -> Vec<Index> {
20660        self.levels
20661            .iter()
20662            .enumerate()
20663            .map(|(level_idx, level)| {
20664                let mut index = Index::new(Self::level_catalog(level));
20665                if let Some(name) = self.names.get(level_idx).and_then(|name| name.as_ref()) {
20666                    index = index.set_name(name);
20667                }
20668                index
20669            })
20670            .collect()
20671    }
20672
20673    /// Integer level codes for each row, matching `pd.MultiIndex.codes`.
20674    ///
20675    /// Missing labels receive code `-1`; all other labels are encoded by their
20676    /// position in the corresponding (sorted) `levels()` entry.
20677    #[must_use]
20678    pub fn codes(&self) -> Vec<Vec<isize>> {
20679        self.levels
20680            .iter()
20681            .map(|level| {
20682                let positions: FxHashMap<IndexLabel, isize> = Self::level_catalog(level)
20683                    .into_iter()
20684                    .enumerate()
20685                    .map(|(code, label)| (label, isize::try_from(code).unwrap_or(isize::MAX)))
20686                    .collect();
20687                level
20688                    .iter()
20689                    .map(|label| {
20690                        if label.is_missing() {
20691                            -1
20692                        } else {
20693                            positions.get(label).copied().unwrap_or(-1)
20694                        }
20695                    })
20696                    .collect()
20697            })
20698            .collect()
20699    }
20700
20701    /// Cardinality of each level, matching `pd.MultiIndex.levshape`.
20702    #[must_use]
20703    pub fn levshape(&self) -> Vec<usize> {
20704        self.levels().iter().map(Index::len).collect()
20705    }
20706
20707    /// Materialize every composite key as an owned tuple.
20708    ///
20709    /// Matches `pd.MultiIndex.to_list()` / `tolist()`.
20710    #[must_use]
20711    pub fn to_list(&self) -> Vec<Vec<IndexLabel>> {
20712        (0..self.len()).map(|row| self.tuple_at(row)).collect()
20713    }
20714
20715    /// Alias for `to_list`, matching `pd.MultiIndex.tolist()`.
20716    #[must_use]
20717    pub fn tolist(&self) -> Vec<Vec<IndexLabel>> {
20718        self.to_list()
20719    }
20720
20721    /// Object-array-shaped materialization, matching `pd.MultiIndex.to_numpy`.
20722    #[must_use]
20723    pub fn to_numpy(&self) -> Vec<Vec<IndexLabel>> {
20724        self.to_list()
20725    }
20726
20727    /// Alias for `to_numpy`, matching `pd.MultiIndex.values`.
20728    #[must_use]
20729    pub fn values(&self) -> Vec<Vec<IndexLabel>> {
20730        self.to_numpy()
20731    }
20732
20733    /// Alias for `to_numpy`, matching `pd.MultiIndex.array`.
20734    #[must_use]
20735    pub fn array(&self) -> Vec<Vec<IndexLabel>> {
20736        self.to_numpy()
20737    }
20738
20739    /// Alias for `to_numpy`, matching `pd.MultiIndex.ravel()`.
20740    #[must_use]
20741    pub fn ravel(&self) -> Vec<Vec<IndexLabel>> {
20742        self.to_numpy()
20743    }
20744
20745    /// Return a shallow clone view, matching `pd.MultiIndex.view`.
20746    #[must_use]
20747    pub fn view(&self) -> Self {
20748        self.clone()
20749    }
20750
20751    /// MultiIndex transpose is identity, matching `pd.MultiIndex.transpose`.
20752    #[must_use]
20753    pub fn transpose(&self) -> Self {
20754        self.clone()
20755    }
20756
20757    /// Alias for `transpose`, matching `pd.MultiIndex.T`.
20758    #[allow(non_snake_case)]
20759    #[must_use]
20760    pub fn T(&self) -> Self {
20761        self.transpose()
20762    }
20763
20764    /// Row materialization for `pd.MultiIndex.to_frame(index=False)`.
20765    ///
20766    /// `fp-frame` owns the richer DataFrame return type; the index crate keeps
20767    /// the level-by-level row payload that callers can lift into a frame.
20768    #[must_use]
20769    pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
20770        self.to_list()
20771    }
20772
20773    /// Series-shaped materialization using tuple keys as both index and value.
20774    ///
20775    /// This mirrors `pd.MultiIndex.to_series()` at the payload level while
20776    /// avoiding a dependency from `fp-index` back into `fp-frame`.
20777    #[must_use]
20778    pub fn to_series(&self) -> Vec<(Vec<IndexLabel>, Vec<IndexLabel>)> {
20779        self.to_list()
20780            .into_iter()
20781            .map(|tuple| (tuple.clone(), tuple))
20782            .collect()
20783    }
20784
20785    /// Stringify each tuple in row order, matching `pd.MultiIndex.format()`.
20786    #[must_use]
20787    pub fn format(&self) -> Vec<String> {
20788        self.to_list()
20789            .into_iter()
20790            .map(|tuple| {
20791                let parts: Vec<String> = tuple.into_iter().map(|label| label.to_string()).collect();
20792                format!("({})", parts.join(", "))
20793            })
20794            .collect()
20795    }
20796
20797    /// Approximate memory footprint of all level labels and codes.
20798    ///
20799    /// `deep=false` counts fixed-width labels and `String` headers; `deep=true`
20800    /// additionally counts string bytes, mirroring `Index::memory_usage`.
20801    #[must_use]
20802    pub fn memory_usage(&self, deep: bool) -> usize {
20803        let level_bytes = self.levels.iter().flatten().fold(0usize, |total, label| {
20804            total.saturating_add(match label {
20805                IndexLabel::Int64(_)
20806                | IndexLabel::Float64(_)
20807                | IndexLabel::Timedelta64(_)
20808                | IndexLabel::Datetime64(_)
20809                | IndexLabel::Object(_)
20810                | IndexLabel::Period(_)
20811                | IndexLabel::Interval(_)
20812                | IndexLabel::Null(_) => 8,
20813                IndexLabel::Bool(_) => 1,
20814                IndexLabel::Utf8(value) => {
20815                    if deep {
20816                        std::mem::size_of::<String>().saturating_add(value.len())
20817                    } else {
20818                        std::mem::size_of::<String>()
20819                    }
20820                }
20821            })
20822        });
20823        level_bytes.saturating_add(multi_index_codes_memory_usage(self.nlevels(), self.len()))
20824    }
20825
20826    /// Shallow memory footprint, matching `pd.MultiIndex.nbytes`.
20827    #[must_use]
20828    pub fn nbytes(&self) -> usize {
20829        self.memory_usage(false)
20830    }
20831
20832    /// Pandas dtype string for MultiIndex itself.
20833    #[must_use]
20834    pub fn dtype(&self) -> &'static str {
20835        "object"
20836    }
20837
20838    /// Dtype string for each level, matching `pd.MultiIndex.dtypes`.
20839    #[must_use]
20840    pub fn dtypes(&self) -> Vec<&'static str> {
20841        self.levels
20842            .iter()
20843            .map(|level| Index::new(level.clone()).dtype())
20844            .collect()
20845    }
20846
20847    /// Pandas-style inferred type for MultiIndex values.
20848    #[must_use]
20849    pub fn inferred_type(&self) -> &'static str {
20850        "mixed"
20851    }
20852
20853    /// Infer object labels without changing this typed representation.
20854    #[must_use]
20855    pub fn infer_objects(&self) -> Self {
20856        self.clone()
20857    }
20858
20859    /// Whether this MultiIndex can hold integer labels as scalar keys.
20860    #[must_use]
20861    pub fn holds_integer(&self) -> bool {
20862        false
20863    }
20864
20865    /// Return the sole tuple, matching `pd.MultiIndex.item()`.
20866    pub fn item(&self) -> Result<Vec<IndexLabel>, IndexError> {
20867        if self.len() == 1 {
20868            Ok(self.tuple_at(0))
20869        } else {
20870            Err(IndexError::InvalidArgument(format!(
20871                "item requires exactly one tuple, got {}",
20872                self.len()
20873            )))
20874        }
20875    }
20876
20877    /// Return a shallow copy, matching `pd.MultiIndex.copy()`.
20878    #[must_use]
20879    pub fn copy(&self) -> Self {
20880        self.clone()
20881    }
20882
20883    fn multi_index_isna_error() -> IndexError {
20884        IndexError::InvalidArgument("isna is not defined for MultiIndex".to_owned())
20885    }
20886
20887    /// Unsupported missing-label check, matching `pd.MultiIndex.hasnans`.
20888    pub fn hasnans(&self) -> Result<bool, IndexError> {
20889        Err(Self::multi_index_isna_error())
20890    }
20891
20892    /// Unsupported missing-label mask, matching `pd.MultiIndex.isna()`.
20893    pub fn isna(&self) -> Result<Vec<bool>, IndexError> {
20894        Err(Self::multi_index_isna_error())
20895    }
20896
20897    /// Alias for `isna`, matching `pd.MultiIndex.isnull`.
20898    pub fn isnull(&self) -> Result<Vec<bool>, IndexError> {
20899        Err(Self::multi_index_isna_error())
20900    }
20901
20902    /// Unsupported inverse missing-label mask, matching `pd.MultiIndex.notna()`.
20903    pub fn notna(&self) -> Result<Vec<bool>, IndexError> {
20904        Err(Self::multi_index_isna_error())
20905    }
20906
20907    /// Alias for `notna`, matching `pd.MultiIndex.notnull`.
20908    pub fn notnull(&self) -> Result<Vec<bool>, IndexError> {
20909        Err(Self::multi_index_isna_error())
20910    }
20911
20912    /// Replace missing labels in every level with one scalar label.
20913    #[must_use]
20914    pub fn fillna(&self, value: &IndexLabel) -> Self {
20915        let levels = self
20916            .levels
20917            .iter()
20918            .map(|level| {
20919                level
20920                    .iter()
20921                    .map(|label| {
20922                        if label.is_missing() {
20923                            value.clone()
20924                        } else {
20925                            label.clone()
20926                        }
20927                    })
20928                    .collect()
20929            })
20930            .collect();
20931        Self::from_levels_and_names(levels, self.names.clone())
20932    }
20933
20934    /// Replace missing labels with one replacement per level.
20935    pub fn fillna_tuple(&self, values: &[IndexLabel]) -> Result<Self, IndexError> {
20936        if values.len() != self.nlevels() {
20937            return Err(IndexError::LengthMismatch {
20938                expected: self.nlevels(),
20939                actual: values.len(),
20940                context: "fillna_tuple replacement arity mismatch".to_owned(),
20941            });
20942        }
20943        let levels = self
20944            .levels
20945            .iter()
20946            .enumerate()
20947            .map(|(level_idx, level)| {
20948                level
20949                    .iter()
20950                    .map(|label| {
20951                        if label.is_missing() {
20952                            values[level_idx].clone()
20953                        } else {
20954                            label.clone()
20955                        }
20956                    })
20957                    .collect()
20958            })
20959            .collect();
20960        Ok(Self::from_levels_and_names(levels, self.names.clone()))
20961    }
20962
20963    /// Replace tuples where `cond` is true with `value`.
20964    pub fn putmask(&self, cond: &[bool], value: Vec<IndexLabel>) -> Result<Self, IndexError> {
20965        if cond.len() != self.len() {
20966            return Err(IndexError::LengthMismatch {
20967                expected: self.len(),
20968                actual: cond.len(),
20969                context: "putmask condition length mismatch".to_owned(),
20970            });
20971        }
20972        if value.len() != self.nlevels() {
20973            return Err(IndexError::LengthMismatch {
20974                expected: self.nlevels(),
20975                actual: value.len(),
20976                context: "putmask tuple arity mismatch".to_owned(),
20977            });
20978        }
20979        let tuples = (0..self.len())
20980            .map(|row| {
20981                if cond[row] {
20982                    value.clone()
20983                } else {
20984                    self.tuple_at(row)
20985                }
20986            })
20987            .collect();
20988        Self::from_tuples_with_names(tuples, self.names.clone())
20989    }
20990
20991    /// Keep original tuples where `cond` is true, otherwise use `other`.
20992    pub fn r#where(&self, cond: &[bool], other: Vec<IndexLabel>) -> Result<Self, IndexError> {
20993        if cond.len() != self.len() {
20994            return Err(IndexError::LengthMismatch {
20995                expected: self.len(),
20996                actual: cond.len(),
20997                context: "where condition length mismatch".to_owned(),
20998            });
20999        }
21000        if other.len() != self.nlevels() {
21001            return Err(IndexError::LengthMismatch {
21002                expected: self.nlevels(),
21003                actual: other.len(),
21004                context: "where tuple arity mismatch".to_owned(),
21005            });
21006        }
21007        let tuples = (0..self.len())
21008            .map(|row| {
21009                if cond[row] {
21010                    self.tuple_at(row)
21011                } else {
21012                    other.clone()
21013                }
21014            })
21015            .collect();
21016        Self::from_tuples_with_names(tuples, self.names.clone())
21017    }
21018
21019    /// Map each composite tuple through a caller-supplied function.
21020    pub fn map<T, F>(&self, mut mapper: F) -> Vec<T>
21021    where
21022        F: FnMut(&[IndexLabel]) -> T,
21023    {
21024        (0..self.len())
21025            .map(|row| {
21026                let tuple = self.tuple_at(row);
21027                mapper(&tuple)
21028            })
21029            .collect()
21030    }
21031
21032    /// Rebuild row labels using replacement level catalogs and current codes.
21033    pub fn set_levels(&self, new_levels: Vec<Vec<IndexLabel>>) -> Result<Self, IndexError> {
21034        if new_levels.len() != self.nlevels() {
21035            return Err(IndexError::LengthMismatch {
21036                expected: self.nlevels(),
21037                actual: new_levels.len(),
21038                context: "set_levels level count mismatch".to_owned(),
21039            });
21040        }
21041        let codes = self.codes();
21042        let mut levels = Vec::with_capacity(self.nlevels());
21043        for (level_idx, level_codes) in codes.into_iter().enumerate() {
21044            let mut level = Vec::with_capacity(self.len());
21045            for code in level_codes {
21046                if code == -1 {
21047                    level.push(self.missing_label_for_level(level_idx));
21048                    continue;
21049                }
21050                if code < -1 {
21051                    return Err(IndexError::InvalidArgument(format!(
21052                        "negative code {code} at level {level_idx}"
21053                    )));
21054                }
21055                let position = usize::try_from(code).map_err(|_| {
21056                    IndexError::InvalidArgument(format!("invalid code {code} at level {level_idx}"))
21057                })?;
21058                let label = new_levels[level_idx]
21059                    .get(position)
21060                    .ok_or(IndexError::OutOfBounds {
21061                        position,
21062                        length: new_levels[level_idx].len(),
21063                    })?;
21064                level.push(label.clone());
21065            }
21066            levels.push(level);
21067        }
21068        Ok(Self::from_levels_and_names(levels, self.names.clone()))
21069    }
21070
21071    /// Rebuild row labels using replacement codes and current level catalogs.
21072    pub fn set_codes(&self, codes: Vec<Vec<isize>>) -> Result<Self, IndexError> {
21073        if codes.len() != self.nlevels() {
21074            return Err(IndexError::LengthMismatch {
21075                expected: self.nlevels(),
21076                actual: codes.len(),
21077                context: "set_codes level count mismatch".to_owned(),
21078            });
21079        }
21080        let catalogs = self.levels();
21081        let mut levels = Vec::with_capacity(self.nlevels());
21082        for (level_idx, level_codes) in codes.into_iter().enumerate() {
21083            if level_codes.len() != self.len() {
21084                return Err(IndexError::LengthMismatch {
21085                    expected: self.len(),
21086                    actual: level_codes.len(),
21087                    context: format!("set_codes level {level_idx} length mismatch"),
21088                });
21089            }
21090            let labels = catalogs[level_idx].labels();
21091            let mut level = Vec::with_capacity(self.len());
21092            for code in level_codes {
21093                if code == -1 {
21094                    level.push(self.missing_label_for_level(level_idx));
21095                    continue;
21096                }
21097                if code < -1 {
21098                    return Err(IndexError::InvalidArgument(format!(
21099                        "negative code {code} at level {level_idx}"
21100                    )));
21101                }
21102                let position = usize::try_from(code).map_err(|_| {
21103                    IndexError::InvalidArgument(format!("invalid code {code} at level {level_idx}"))
21104                })?;
21105                let label = labels.get(position).ok_or(IndexError::OutOfBounds {
21106                    position,
21107                    length: labels.len(),
21108                })?;
21109                level.push(label.clone());
21110            }
21111            levels.push(level);
21112        }
21113        Ok(Self::from_levels_and_names(levels, self.names.clone()))
21114    }
21115
21116    /// Drop unused level labels. This representation stores row labels directly,
21117    /// so there is no separate unused catalog to prune.
21118    #[must_use]
21119    pub fn remove_unused_levels(&self) -> Self {
21120        self.clone()
21121    }
21122
21123    /// Identity check, matching `pd.MultiIndex.is_`.
21124    #[must_use]
21125    pub fn is_(&self, other: &Self) -> bool {
21126        std::ptr::eq(self, other)
21127    }
21128
21129    /// Whether this MultiIndex is boolean-typed.
21130    #[must_use]
21131    pub fn is_boolean(&self) -> bool {
21132        false
21133    }
21134
21135    /// Whether this MultiIndex is categorical-typed.
21136    #[must_use]
21137    pub fn is_categorical(&self) -> bool {
21138        false
21139    }
21140
21141    /// Whether this MultiIndex is floating-typed.
21142    #[must_use]
21143    pub fn is_floating(&self) -> bool {
21144        false
21145    }
21146
21147    /// Whether this MultiIndex is integer-typed.
21148    #[must_use]
21149    pub fn is_integer(&self) -> bool {
21150        false
21151    }
21152
21153    /// Whether this MultiIndex is interval-typed.
21154    #[must_use]
21155    pub fn is_interval(&self) -> bool {
21156        false
21157    }
21158
21159    /// Whether this MultiIndex is numeric-typed.
21160    #[must_use]
21161    pub fn is_numeric(&self) -> bool {
21162        false
21163    }
21164
21165    /// Whether this MultiIndex is object-backed.
21166    #[must_use]
21167    pub fn is_object(&self) -> bool {
21168        true
21169    }
21170
21171    /// Compare row tuples only, matching `pd.MultiIndex.equals`.
21172    #[must_use]
21173    pub fn equals(&self, other: &Self) -> bool {
21174        self.levels == other.levels
21175    }
21176
21177    /// Compare row tuples and level names, matching `pd.MultiIndex.identical`.
21178    #[must_use]
21179    pub fn identical(&self, other: &Self) -> bool {
21180        self.equals(other) && self.names == other.names
21181    }
21182
21183    /// Compare unique level catalogs, matching `pd.MultiIndex.equal_levels`.
21184    #[must_use]
21185    pub fn equal_levels(&self, other: &Self) -> bool {
21186        self.levels() == other.levels()
21187    }
21188
21189    /// Get the labels for a specific level.
21190    ///
21191    /// Matches `pd.MultiIndex.get_level_values(level)`.
21192    pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
21193        if level >= self.levels.len() {
21194            return Err(IndexError::OutOfBounds {
21195                position: level,
21196                length: self.levels.len(),
21197            });
21198        }
21199        let mut idx = Index::new(self.levels[level].clone());
21200        if let Some(name) = self.names.get(level).and_then(|n| n.as_ref()) {
21201            idx = idx.set_name(name);
21202        }
21203        Ok(idx)
21204    }
21205
21206    /// Get the tuple of labels at a specific position.
21207    pub fn get_tuple(&self, position: usize) -> Option<Vec<&IndexLabel>> {
21208        if position >= self.len() {
21209            return None;
21210        }
21211        Some(self.levels.iter().map(|level| &level[position]).collect())
21212    }
21213
21214    /// Select rows by positional index.
21215    pub fn take(&self, positions: &[usize]) -> Result<Self, IndexError> {
21216        for &position in positions {
21217            if position >= self.len() {
21218                return Err(IndexError::OutOfBounds {
21219                    position,
21220                    length: self.len(),
21221                });
21222            }
21223        }
21224
21225        let mut levels = Vec::with_capacity(self.nlevels());
21226        for level in &self.levels {
21227            let selected = positions
21228                .iter()
21229                .map(|&position| level[position].clone())
21230                .collect();
21231            levels.push(selected);
21232        }
21233
21234        // Rows of the same levels: a missing label stays what it was.
21235        Ok(Self::from_levels_and_names(levels, self.names.clone())
21236            .with_missing_as_level(self.missing_is_a_level))
21237    }
21238
21239    /// Delete the tuple at a positional location.
21240    ///
21241    /// Matches `pd.MultiIndex.delete(loc)`.
21242    pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
21243        if loc >= self.len() {
21244            return Err(IndexError::OutOfBounds {
21245                position: loc,
21246                length: self.len(),
21247            });
21248        }
21249        let positions: Vec<usize> = (0..self.len()).filter(|&row| row != loc).collect();
21250        Ok(self.take_existing_positions(&positions))
21251    }
21252
21253    /// Insert a tuple at a positional location.
21254    ///
21255    /// Matches `pd.MultiIndex.insert(loc, item)`. Inserting into an empty
21256    /// zero-level MultiIndex adopts the tuple arity as the new level count.
21257    pub fn insert(&self, loc: usize, item: Vec<IndexLabel>) -> Result<Self, IndexError> {
21258        if loc > self.len() {
21259            return Err(IndexError::OutOfBounds {
21260                position: loc,
21261                length: self.len(),
21262            });
21263        }
21264        if self.nlevels() == 0 {
21265            if loc != 0 {
21266                return Err(IndexError::OutOfBounds {
21267                    position: loc,
21268                    length: 0,
21269                });
21270            }
21271            return Self::from_tuples(vec![item]);
21272        }
21273        if item.len() != self.nlevels() {
21274            return Err(IndexError::LengthMismatch {
21275                expected: self.nlevels(),
21276                actual: item.len(),
21277                context: "insert tuple arity mismatch".to_owned(),
21278            });
21279        }
21280
21281        let mut levels = self.levels.clone();
21282        for (level_idx, label) in item.into_iter().enumerate() {
21283            levels[level_idx].insert(loc, label);
21284        }
21285        Ok(Self::from_levels_and_names(levels, self.names.clone()))
21286    }
21287
21288    /// Drop every occurrence of the provided tuples.
21289    ///
21290    /// Matches `pd.MultiIndex.drop(labels)` with the default fail-closed
21291    /// behavior for missing labels.
21292    pub fn drop(&self, labels_to_drop: &[Vec<IndexLabel>]) -> Result<Self, IndexError> {
21293        for label in labels_to_drop {
21294            self.validate_key_arity(label, false)?;
21295        }
21296        // Reuse one key buffer across rows instead of materializing every row
21297        // tuple via to_list() (which allocates a Vec per row). `found` stores
21298        // references into `labels_to_drop` (stable across iterations) — obtained
21299        // from drop_set.get() — so the reused buffer never escapes. FxHashSet
21300        // replaces the std SipHash set. Bit-identical: same retained positions
21301        // and same missing-key detection (value-based membership).
21302        let drop_set: FxHashSet<&Vec<IndexLabel>> = labels_to_drop.iter().collect();
21303        let mut found: FxHashSet<&Vec<IndexLabel>> = FxHashSet::default();
21304        let mut positions = Vec::new();
21305        let mut key: Vec<IndexLabel> = Vec::with_capacity(self.nlevels());
21306        for row in 0..self.len() {
21307            key.clear();
21308            key.extend(self.levels.iter().map(|level| level[row].clone()));
21309            if let Some(matched) = drop_set.get(&key) {
21310                found.insert(*matched);
21311            } else {
21312                positions.push(row);
21313            }
21314        }
21315        if let Some(missing) = labels_to_drop.iter().find(|label| !found.contains(label)) {
21316            return Err(IndexError::InvalidArgument(format!(
21317                "tuple key not found: {:?}",
21318                missing
21319            )));
21320        }
21321        Ok(self.take_existing_positions(&positions))
21322    }
21323
21324    fn validate_key_arity(
21325        &self,
21326        key: &[IndexLabel],
21327        allow_partial: bool,
21328    ) -> Result<(), IndexError> {
21329        let nlevels = self.nlevels();
21330        if key.is_empty() {
21331            return Err(IndexError::InvalidArgument(
21332                "MultiIndex key must contain at least one level".to_owned(),
21333            ));
21334        }
21335        if (!allow_partial && key.len() != nlevels) || (allow_partial && key.len() > nlevels) {
21336            return Err(IndexError::InvalidArgument(format!(
21337                "wrong tuple arity: expected {}{}, got {}",
21338                if allow_partial { "1.." } else { "" },
21339                nlevels,
21340                key.len()
21341            )));
21342        }
21343        Ok(())
21344    }
21345
21346    fn row_matches_prefix(&self, row: usize, key: &[IndexLabel]) -> bool {
21347        key.iter()
21348            .enumerate()
21349            .all(|(level, expected)| &self.levels[level][row] == expected)
21350    }
21351
21352    fn row_prefix_cmp(&self, row: usize, key: &[IndexLabel]) -> std::cmp::Ordering {
21353        for (level, expected) in key.iter().enumerate() {
21354            let ord = self.levels[level][row].cmp(expected);
21355            if ord != std::cmp::Ordering::Equal {
21356                return ord;
21357            }
21358        }
21359        std::cmp::Ordering::Equal
21360    }
21361
21362    /// Return matching row positions for an exact tuple key.
21363    pub fn get_loc_tuple(&self, key: &[IndexLabel]) -> Result<Vec<usize>, IndexError> {
21364        self.validate_key_arity(key, false)?;
21365        let positions: Vec<usize> = (0..self.len())
21366            .filter(|&row| self.row_matches_prefix(row, key))
21367            .collect();
21368        if positions.is_empty() {
21369            return Err(IndexError::InvalidArgument(format!(
21370                "tuple key not found: {:?}",
21371                key
21372            )));
21373        }
21374        Ok(positions)
21375    }
21376
21377    /// Return row positions for an exact tuple, partial-prefix tuple, or a single level key.
21378    ///
21379    /// `level=None` treats `key` as an exact tuple when it has full arity, or a
21380    /// prefix tuple when shorter than `nlevels()`. `level=Some(n)` treats
21381    /// `key` as a single label lookup on that level.
21382    pub fn get_loc(
21383        &self,
21384        key: &[IndexLabel],
21385        level: Option<usize>,
21386    ) -> Result<Vec<usize>, IndexError> {
21387        if let Some(level) = level {
21388            if level >= self.nlevels() {
21389                return Err(IndexError::OutOfBounds {
21390                    position: level,
21391                    length: self.nlevels(),
21392                });
21393            }
21394            if key.len() != 1 {
21395                return Err(IndexError::InvalidArgument(format!(
21396                    "level lookup expects exactly one label, got {}",
21397                    key.len()
21398                )));
21399            }
21400            let positions: Vec<usize> = self.levels[level]
21401                .iter()
21402                .enumerate()
21403                .filter_map(|(row, label)| if label == &key[0] { Some(row) } else { None })
21404                .collect();
21405            if positions.is_empty() {
21406                return Err(IndexError::InvalidArgument(format!(
21407                    "level key not found at level {level}: {:?}",
21408                    key[0]
21409                )));
21410            }
21411            return Ok(positions);
21412        }
21413
21414        self.validate_key_arity(key, true)?;
21415        let positions: Vec<usize> = (0..self.len())
21416            .filter(|&row| self.row_matches_prefix(row, key))
21417            .collect();
21418        if positions.is_empty() {
21419            return Err(IndexError::InvalidArgument(format!(
21420                "tuple key not found: {:?}",
21421                key
21422            )));
21423        }
21424        Ok(positions)
21425    }
21426
21427    /// Return row positions for a list-like exact or partial-prefix selector.
21428    ///
21429    /// Matches the list-label subset of `pd.MultiIndex.get_locs(seq)`.
21430    pub fn get_locs(&self, key: &[IndexLabel]) -> Result<Vec<usize>, IndexError> {
21431        if key.is_empty() {
21432            return Ok(Vec::new());
21433        }
21434        self.get_loc(key, None)
21435    }
21436
21437    /// pandas-style partial tuple lookup returning matching positions and the remaining index.
21438    pub fn get_loc_level(
21439        &self,
21440        key: &[IndexLabel],
21441    ) -> Result<(Vec<usize>, Option<MultiIndexOrIndex>), IndexError> {
21442        let positions = self.get_loc(key, None)?;
21443        if key.len() == self.nlevels() {
21444            return Ok((positions, None));
21445        }
21446
21447        let mut remaining = MultiIndexOrIndex::Multi(self.take(&positions)?);
21448        for _ in 0..key.len() {
21449            remaining = match remaining {
21450                MultiIndexOrIndex::Multi(mi) => mi.droplevel(0)?,
21451                MultiIndexOrIndex::Index(_) => {
21452                    return Err(IndexError::InvalidArgument(
21453                        "cannot drop more levels than remain".to_owned(),
21454                    ));
21455                }
21456            };
21457        }
21458
21459        Ok((positions, Some(remaining)))
21460    }
21461
21462    /// Return `(start, stop)` bounds for a lexicographic tuple slice.
21463    ///
21464    /// The returned `stop` is exclusive, matching pandas `slice_locs`.
21465    pub fn slice_locs(
21466        &self,
21467        start: Option<&[IndexLabel]>,
21468        end: Option<&[IndexLabel]>,
21469    ) -> Result<(usize, usize), IndexError> {
21470        if let Some(start) = start {
21471            self.validate_key_arity(start, true)?;
21472        }
21473        if let Some(end) = end {
21474            self.validate_key_arity(end, true)?;
21475        }
21476
21477        let start_pos = match start {
21478            Some(start_key) => (0..self.len())
21479                .find(|&row| self.row_prefix_cmp(row, start_key) != std::cmp::Ordering::Less)
21480                .unwrap_or(self.len()),
21481            None => 0,
21482        };
21483        let end_pos = match end {
21484            Some(end_key) => (0..self.len())
21485                .rfind(|&row| self.row_prefix_cmp(row, end_key) != std::cmp::Ordering::Greater)
21486                .map_or(0, |row| row + 1),
21487            None => self.len(),
21488        };
21489
21490        if end_pos < start_pos {
21491            return Ok((start_pos, start_pos));
21492        }
21493        Ok((start_pos, end_pos))
21494    }
21495
21496    /// Bound for a tuple slice, matching `pd.MultiIndex.get_slice_bound`.
21497    pub fn get_slice_bound(&self, label: &[IndexLabel], side: &str) -> Result<usize, IndexError> {
21498        match side {
21499            "left" => Ok(self.slice_locs(Some(label), Some(label))?.0),
21500            "right" => Ok(self.slice_locs(Some(label), Some(label))?.1),
21501            other => Err(IndexError::InvalidArgument(format!(
21502                "get_slice_bound: side must be 'left' or 'right', got {other:?}"
21503            ))),
21504        }
21505    }
21506
21507    /// Alias for `slice_locs`, matching `pd.MultiIndex.slice_indexer`.
21508    pub fn slice_indexer(
21509        &self,
21510        start: Option<&[IndexLabel]>,
21511        end: Option<&[IndexLabel]>,
21512    ) -> Result<(usize, usize), IndexError> {
21513        self.slice_locs(start, end)
21514    }
21515
21516    /// Return a label-bounded range, matching `pd.MultiIndex.truncate`.
21517    ///
21518    /// Bounds are interpreted as partial or full tuple prefixes and are
21519    /// inclusive on both sides. Open-ended bounds retain the corresponding
21520    /// leading or trailing rows.
21521    pub fn truncate(
21522        &self,
21523        before: Option<&[IndexLabel]>,
21524        after: Option<&[IndexLabel]>,
21525    ) -> Result<Self, IndexError> {
21526        let (start, stop) = self.slice_locs(before, after)?;
21527        let positions: Vec<usize> = (start..stop).collect();
21528        Ok(self.take_existing_positions(&positions))
21529    }
21530
21531    /// Insertion positions for target tuples, matching `pd.MultiIndex.searchsorted`.
21532    ///
21533    /// `side` is `"left"` for the first valid insertion position or `"right"`
21534    /// for the position after an equal run. Like pandas, callers are expected
21535    /// to use this on lexicographically sorted indexes.
21536    pub fn searchsorted(&self, target: &Self, side: &str) -> Result<Vec<usize>, IndexError> {
21537        if side != "left" && side != "right" {
21538            return Err(IndexError::InvalidArgument(format!(
21539                "searchsorted: side must be 'left' or 'right', got {side:?}"
21540            )));
21541        }
21542
21543        Ok((0..target.len())
21544            .map(|target_row| {
21545                let needle = target.tuple_at(target_row);
21546                let mut lo = 0_usize;
21547                let mut hi = self.len();
21548                while lo < hi {
21549                    let mid = lo + (hi - lo) / 2;
21550                    let cmp = self.tuple_at(mid).cmp(&needle);
21551                    use std::cmp::Ordering;
21552                    let go_right = matches!(
21553                        (cmp, side),
21554                        (Ordering::Less, _) | (Ordering::Equal, "right")
21555                    );
21556                    if go_right {
21557                        lo = mid + 1;
21558                    } else {
21559                        hi = mid;
21560                    }
21561                }
21562                lo
21563            })
21564            .collect())
21565    }
21566
21567    /// Compute a non-unique indexer against another MultiIndex.
21568    ///
21569    /// Matches `pd.MultiIndex.get_indexer_non_unique(target)` by expanding
21570    /// every matching source position for each target tuple in target order.
21571    /// Missing target tuples contribute a single `-1` entry and their target
21572    /// position is recorded in the returned `missing` vector.
21573    #[must_use]
21574    /// Dictionary-encode every level of `self` and `target` into integer codes
21575    /// (consistent across both) and pack each row's tuple into one mixed-radix
21576    /// `u64` key (br-frankenpandas-mipack). Lets get_indexer hash an integer per
21577    /// row instead of allocating a `Vec<IndexLabel>` (and cloning Utf8 Strings)
21578    /// per row. Returns `None` when there are no levels, the level counts
21579    /// differ, or the combined code space overflows `u64` (caller keeps the
21580    /// `Vec<IndexLabel>`-key path). Bijective on tuple identity, so the source
21581    /// map and target lookups match exactly the same rows.
21582    /// Pack each row's tuple into one mixed-radix `u64` whose ascending order
21583    /// equals the lexicographic `row_cmp` order (br-frankenpandas-misort): per
21584    /// level, distinct values are ranked by `IndexLabel::Ord` and the rank codes
21585    /// are packed most-significant-first. So sorting these `u64` keys reproduces
21586    /// the level-by-level tuple sort while comparing integers instead of
21587    /// (Utf8) tuples. Returns `None` when there are no levels or the combined
21588    /// code space overflows `u64` (caller keeps the tuple-comparison sort).
21589    fn sorted_packed_keys(&self) -> Option<Vec<u64>> {
21590        let nlev = self.nlevels();
21591        if nlev == 0 {
21592            return None;
21593        }
21594        let n = self.len();
21595        let mut keys = vec![0u64; n];
21596        let mut combined: u128 = 1;
21597        for level in 0..nlev {
21598            let col = &self.levels[level];
21599            // Dedup to DISTINCT values first (O(n) hash), then sort only those
21600            // (O(d log d)); sorting all n refs would cost as much as the tuple
21601            // sort we are replacing.
21602            let mut sorted: Vec<&IndexLabel> =
21603                col.iter().collect::<FxHashSet<_>>().into_iter().collect();
21604            sorted.sort_unstable();
21605            let radix = sorted.len() as u64;
21606            let mut rank: FxHashMap<&IndexLabel, u64> =
21607                FxHashMap::with_capacity_and_hasher(sorted.len(), Default::default());
21608            for (r, value) in sorted.iter().enumerate() {
21609                rank.insert(*value, r as u64);
21610            }
21611            for (dst, value) in keys.iter_mut().zip(col.iter()) {
21612                *dst = dst.checked_mul(radix)?.checked_add(rank[value])?;
21613            }
21614            combined = combined.checked_mul(radix as u128)?;
21615            if combined > u64::MAX as u128 {
21616                return None;
21617            }
21618        }
21619        Some(keys)
21620    }
21621
21622    /// Pack each row's tuple into one mixed-radix `u64` using FIRST-SEEN per-level
21623    /// codes (br-frankenpandas-midedup). Unlike [`Self::sorted_packed_keys`] this
21624    /// skips the per-level distinct sort — dedup only needs the keys to be a
21625    /// bijection on tuple identity, not lexicographically ordered. Lets
21626    /// duplicated/unique/drop_duplicates hash one integer per row instead of
21627    /// allocating (and Utf8-cloning) a `Vec<IndexLabel>` per row. `None` when
21628    /// there are no levels or the combined code space overflows `u64`.
21629    fn identity_packed_keys(&self) -> Option<Vec<u64>> {
21630        let nlev = self.nlevels();
21631        if nlev == 0 {
21632            return None;
21633        }
21634        let n = self.len();
21635        let mut keys = vec![0u64; n];
21636        let mut combined: u128 = 1;
21637        for level in 0..nlev {
21638            let col = &self.levels[level];
21639            let mut code: FxHashMap<&IndexLabel, u64> =
21640                FxHashMap::with_capacity_and_hasher(col.len(), Default::default());
21641            let mut next = 0u64;
21642            let codes: Vec<u64> = col
21643                .iter()
21644                .map(|value| {
21645                    *code.entry(value).or_insert_with(|| {
21646                        let c = next;
21647                        next += 1;
21648                        c
21649                    })
21650                })
21651                .collect();
21652            let radix = next;
21653            for (dst, &c) in keys.iter_mut().zip(&codes) {
21654                *dst = dst.checked_mul(radix)?.checked_add(c)?;
21655            }
21656            combined = combined.checked_mul(radix as u128)?;
21657            if combined > u64::MAX as u128 {
21658                return None;
21659            }
21660        }
21661        Some(keys)
21662    }
21663
21664    fn factorize_packed_keys(&self, target: &Self) -> Option<(Vec<u64>, Vec<u64>)> {
21665        let nlev = self.nlevels();
21666        if nlev == 0 || nlev != target.nlevels() {
21667            return None;
21668        }
21669        let n = self.len();
21670        let m = target.len();
21671        let mut src = vec![0u64; n];
21672        let mut tgt = vec![0u64; m];
21673        let mut combined: u128 = 1;
21674        for level in 0..nlev {
21675            let mut codes: FxHashMap<&IndexLabel, u64> = FxHashMap::default();
21676            let mut next = 0u64;
21677            // Source first so its codes are dense and lookups stay consistent;
21678            // target-only values get fresh codes that no source key can match.
21679            let s_level = &self.levels[level];
21680            let t_level = &target.levels[level];
21681            let s_codes: Vec<u64> = (0..n)
21682                .map(|row| {
21683                    *codes.entry(&s_level[row]).or_insert_with(|| {
21684                        let c = next;
21685                        next += 1;
21686                        c
21687                    })
21688                })
21689                .collect();
21690            let t_codes: Vec<u64> = (0..m)
21691                .map(|row| {
21692                    *codes.entry(&t_level[row]).or_insert_with(|| {
21693                        let c = next;
21694                        next += 1;
21695                        c
21696                    })
21697                })
21698                .collect();
21699            // Mixed-radix: shift existing partial keys up by this level's radix
21700            // (= its distinct-value count) and add the new codes.
21701            let radix = next;
21702            for (dst, &c) in src.iter_mut().zip(&s_codes) {
21703                *dst = dst.checked_mul(radix)?.checked_add(c)?;
21704            }
21705            for (dst, &c) in tgt.iter_mut().zip(&t_codes) {
21706                *dst = dst.checked_mul(radix)?.checked_add(c)?;
21707            }
21708            combined = combined.checked_mul(radix as u128)?;
21709            if combined > u64::MAX as u128 {
21710                return None;
21711            }
21712        }
21713        Some((src, tgt))
21714    }
21715
21716    fn two_utf8_levels(&self) -> Option<Utf8LevelPair<'_>> {
21717        if self.nlevels() != 2 {
21718            return None;
21719        }
21720        let self_l0 = self.levels[0].as_slice();
21721        let self_l1 = self.levels[1].as_slice();
21722        if [self_l0, self_l1].into_iter().all(|level| {
21723            level
21724                .iter()
21725                .all(|label| matches!(label, IndexLabel::Utf8(_)))
21726        }) {
21727            Some((self_l0, self_l1))
21728        } else {
21729            None
21730        }
21731    }
21732
21733    fn two_utf8_level_slices<'a>(&'a self, target: &'a Self) -> Option<Utf8LevelPairs<'a>> {
21734        if let (Some(self_levels), Some(target_levels)) =
21735            (self.two_utf8_levels(), target.two_utf8_levels())
21736        {
21737            Some((self_levels, target_levels))
21738        } else {
21739            None
21740        }
21741    }
21742
21743    #[inline]
21744    fn utf8_pair_at<'a>(levels: Utf8LevelPair<'a>, row: usize) -> (&'a str, &'a str) {
21745        let IndexLabel::Utf8(left) = &levels.0[row] else {
21746            unreachable!("two_utf8_level_slices pre-validates all labels")
21747        };
21748        let IndexLabel::Utf8(right) = &levels.1[row] else {
21749            unreachable!("two_utf8_level_slices pre-validates all labels")
21750        };
21751        (left.as_str(), right.as_str())
21752    }
21753
21754    fn two_utf8_result_from_pairs(pairs: Vec<(&str, &str)>, names: Vec<Option<LabelName>>) -> Self {
21755        let mut left = Vec::with_capacity(pairs.len());
21756        let mut right = Vec::with_capacity(pairs.len());
21757        for (l, r) in pairs {
21758            left.push(IndexLabel::Utf8(l.to_owned()));
21759            right.push(IndexLabel::Utf8(r.to_owned()));
21760        }
21761        Self::from_levels_and_names(vec![left, right], names)
21762    }
21763
21764    pub fn get_indexer_non_unique(&self, target: &Self) -> (Vec<isize>, Vec<usize>) {
21765        if self.nlevels() != target.nlevels() {
21766            return (vec![-1; target.len()], (0..target.len()).collect());
21767        }
21768
21769        if let Some((src_keys, tgt_keys)) = self.factorize_packed_keys(target) {
21770            let mut positions = FxHashMap::<u64, Vec<usize>>::with_capacity_and_hasher(
21771                self.len(),
21772                Default::default(),
21773            );
21774            for (row, &key) in src_keys.iter().enumerate() {
21775                positions.entry(key).or_default().push(row);
21776            }
21777            let mut indexer = Vec::new();
21778            let mut missing = Vec::new();
21779            for (target_row, &key) in tgt_keys.iter().enumerate() {
21780                if let Some(matches) = positions.get(&key) {
21781                    indexer.extend(matches.iter().map(|&pos| pos as isize));
21782                } else {
21783                    indexer.push(-1);
21784                    missing.push(target_row);
21785                }
21786            }
21787            return (indexer, missing);
21788        }
21789
21790        let mut positions = FxHashMap::<Vec<IndexLabel>, Vec<usize>>::with_capacity_and_hasher(
21791            self.len(),
21792            Default::default(),
21793        );
21794        for row in 0..self.len() {
21795            let key: Vec<IndexLabel> = self.levels.iter().map(|level| level[row].clone()).collect();
21796            positions.entry(key).or_default().push(row);
21797        }
21798
21799        let mut indexer = Vec::new();
21800        let mut missing = Vec::new();
21801        for target_row in 0..target.len() {
21802            let key: Vec<IndexLabel> = target
21803                .levels
21804                .iter()
21805                .map(|level| level[target_row].clone())
21806                .collect();
21807            if let Some(matches) = positions.get(&key) {
21808                indexer.extend(matches.iter().map(|&pos| pos as isize));
21809            } else {
21810                indexer.push(-1);
21811                missing.push(target_row);
21812            }
21813        }
21814
21815        (indexer, missing)
21816    }
21817
21818    /// Compute a positional indexer against another MultiIndex.
21819    ///
21820    /// Matches `pd.MultiIndex.get_indexer(target)` for unique source indexes:
21821    /// each target tuple maps to its first source position, and missing target
21822    /// tuples map to `-1`. Duplicate source tuples are rejected because pandas
21823    /// treats reindexing from a non-unique index as invalid; callers that want
21824    /// duplicate expansion should use [`Self::get_indexer_for`] or
21825    /// [`Self::get_indexer_non_unique`].
21826    pub fn get_indexer(&self, target: &Self) -> Result<Vec<isize>, IndexError> {
21827        if self.has_duplicates() {
21828            return Err(IndexError::InvalidArgument(
21829                "get_indexer requires a uniquely valued MultiIndex".to_owned(),
21830            ));
21831        }
21832        if self.nlevels() != target.nlevels() {
21833            return Ok(vec![-1; target.len()]);
21834        }
21835
21836        if let Some((src_keys, tgt_keys)) = self.factorize_packed_keys(target) {
21837            let mut positions =
21838                FxHashMap::<u64, isize>::with_capacity_and_hasher(self.len(), Default::default());
21839            for (row, &key) in src_keys.iter().enumerate() {
21840                positions
21841                    .entry(key)
21842                    .or_insert(isize::try_from(row).unwrap_or(isize::MAX));
21843            }
21844            return Ok(tgt_keys
21845                .iter()
21846                .map(|key| positions.get(key).copied().unwrap_or(-1))
21847                .collect());
21848        }
21849
21850        let mut positions = FxHashMap::<Vec<IndexLabel>, isize>::with_capacity_and_hasher(
21851            self.len(),
21852            Default::default(),
21853        );
21854        for row in 0..self.len() {
21855            positions
21856                .entry(self.tuple_at(row))
21857                .or_insert(isize::try_from(row).unwrap_or(isize::MAX));
21858        }
21859
21860        Ok((0..target.len())
21861            .map(|target_row| {
21862                let key = target.tuple_at(target_row);
21863                positions.get(&key).copied().unwrap_or(-1)
21864            })
21865            .collect())
21866    }
21867
21868    /// Compute a positional indexer, expanding duplicate source matches.
21869    ///
21870    /// Matches `pd.MultiIndex.get_indexer_for(target)`: unique source indexes
21871    /// use the compact one-position-per-target form, while non-unique source
21872    /// indexes expand every matching source position for each target tuple.
21873    pub fn get_indexer_for(&self, target: &Self) -> Result<Vec<isize>, IndexError> {
21874        if self.has_duplicates() {
21875            Ok(self.get_indexer_non_unique(target).0)
21876        } else {
21877            self.get_indexer(target)
21878        }
21879    }
21880
21881    /// Reindex to a target MultiIndex, returning the target and source positions.
21882    ///
21883    /// Matches `pd.MultiIndex.reindex(target)` for unique source indexes:
21884    /// the returned index is the requested target, and the indexer maps each
21885    /// target tuple to its source position or `-1` for missing tuples.
21886    pub fn reindex(&self, target: &Self) -> Result<(Self, Vec<isize>), IndexError> {
21887        Ok((target.clone(), self.get_indexer(target)?))
21888    }
21889
21890    /// Per-row flag for duplicated composite tuples.
21891    ///
21892    /// Matches `pd.MultiIndex.duplicated(keep='first'|'last'|False)`.
21893    /// - `DuplicateKeep::First` marks all but the first occurrence of each
21894    ///   tuple as duplicated (pandas default).
21895    /// - `DuplicateKeep::Last` marks all but the last occurrence.
21896    /// - `DuplicateKeep::None` marks every occurrence of any tuple that
21897    ///   appears more than once.
21898    #[must_use]
21899    pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
21900        let len = self.len();
21901        let mut out = vec![false; len];
21902        if len == 0 {
21903            return out;
21904        }
21905        if let Some(layout) = self.compact_two_level_identity_layout() {
21906            match keep {
21907                DuplicateKeep::First => {
21908                    let mut seen = vec![0_u8; layout.slot_count];
21909                    for (row, slot) in out.iter_mut().enumerate() {
21910                        let key = layout.slot(row);
21911                        if seen[key] == 0 {
21912                            seen[key] = 1;
21913                        } else {
21914                            *slot = true;
21915                        }
21916                    }
21917                }
21918                DuplicateKeep::Last => {
21919                    let mut seen = vec![0_u8; layout.slot_count];
21920                    for row in (0..len).rev() {
21921                        let key = layout.slot(row);
21922                        if seen[key] == 0 {
21923                            seen[key] = 1;
21924                        } else {
21925                            out[row] = true;
21926                        }
21927                    }
21928                }
21929                DuplicateKeep::None => {
21930                    let mut counts = vec![0_usize; layout.slot_count];
21931                    for row in 0..len {
21932                        counts[layout.slot(row)] += 1;
21933                    }
21934                    for (row, slot) in out.iter_mut().enumerate() {
21935                        if counts[layout.slot(row)] > 1 {
21936                            *slot = true;
21937                        }
21938                    }
21939                }
21940            }
21941            return out;
21942        }
21943        // Materialize each row's composite key exactly once per pass. The prior
21944        // version built BOTH a counts and a first_seen map for every keep mode
21945        // (incl. a key.clone()) and then rebuilt the key again in the keep-mode
21946        // loop — 3-4 Vec<IndexLabel> allocations per row. Each mode now does the
21947        // minimal work; output is positional so marking order is irrelevant.
21948        // Packed-key fast path (br-frankenpandas-midedup): one u64 per row keyed
21949        // on tuple identity, so dedup hashes integers instead of allocating (and
21950        // Utf8-cloning) a Vec<IndexLabel> per row. Bijective on identity ⇒ the
21951        // dup mask is identical to the Vec-key path.
21952        if let Some(keys) = self.identity_packed_keys() {
21953            match keep {
21954                DuplicateKeep::First => {
21955                    let mut seen: FxHashSet<u64> =
21956                        FxHashSet::with_capacity_and_hasher(len, Default::default());
21957                    for (row, slot) in out.iter_mut().enumerate() {
21958                        if !seen.insert(keys[row]) {
21959                            *slot = true;
21960                        }
21961                    }
21962                }
21963                DuplicateKeep::Last => {
21964                    let mut seen: FxHashSet<u64> =
21965                        FxHashSet::with_capacity_and_hasher(len, Default::default());
21966                    for row in (0..len).rev() {
21967                        if !seen.insert(keys[row]) {
21968                            out[row] = true;
21969                        }
21970                    }
21971                }
21972                DuplicateKeep::None => {
21973                    let mut counts: FxHashMap<u64, usize> =
21974                        FxHashMap::with_capacity_and_hasher(len, Default::default());
21975                    for &key in &keys {
21976                        *counts.entry(key).or_insert(0) += 1;
21977                    }
21978                    for (row, slot) in out.iter_mut().enumerate() {
21979                        if counts[&keys[row]] > 1 {
21980                            *slot = true;
21981                        }
21982                    }
21983                }
21984            }
21985            return out;
21986        }
21987
21988        let key_at = |row: usize| -> Vec<IndexLabel> {
21989            self.levels.iter().map(|level| level[row].clone()).collect()
21990        };
21991        match keep {
21992            DuplicateKeep::First => {
21993                // First occurrence kept; a key already seen earlier is a dup.
21994                let mut seen: FxHashSet<Vec<IndexLabel>> =
21995                    FxHashSet::with_capacity_and_hasher(len, Default::default());
21996                for (row, slot) in out.iter_mut().enumerate() {
21997                    if !seen.insert(key_at(row)) {
21998                        *slot = true;
21999                    }
22000                }
22001            }
22002            DuplicateKeep::Last => {
22003                // Last occurrence kept; scanning in reverse, the first key seen
22004                // in reverse is the last forward occurrence (kept = false).
22005                let mut seen: FxHashSet<Vec<IndexLabel>> =
22006                    FxHashSet::with_capacity_and_hasher(len, Default::default());
22007                for row in (0..len).rev() {
22008                    if !seen.insert(key_at(row)) {
22009                        out[row] = true;
22010                    }
22011                }
22012            }
22013            DuplicateKeep::None => {
22014                // Every occurrence of a key with count > 1 is a dup.
22015                let mut counts: FxHashMap<Vec<IndexLabel>, usize> =
22016                    FxHashMap::with_capacity_and_hasher(len, Default::default());
22017                for row in 0..len {
22018                    *counts.entry(key_at(row)).or_insert(0) += 1;
22019                }
22020                for (row, slot) in out.iter_mut().enumerate() {
22021                    if counts[&key_at(row)] > 1 {
22022                        *slot = true;
22023                    }
22024                }
22025            }
22026        }
22027        out
22028    }
22029
22030    /// Whether all composite tuples are unique.
22031    ///
22032    /// Matches `pd.MultiIndex.is_unique`.
22033    #[must_use]
22034    pub fn is_unique(&self) -> bool {
22035        let len = self.len();
22036        if len <= 1 {
22037            return true;
22038        }
22039        if let Some(layout) = self.compact_two_level_identity_layout() {
22040            let mut seen = vec![0_u8; layout.slot_count];
22041            for row in 0..len {
22042                let key = layout.slot(row);
22043                if seen[key] != 0 {
22044                    return false;
22045                }
22046                seen[key] = 1;
22047            }
22048            return true;
22049        }
22050        if let Some(keys) = self.identity_packed_keys() {
22051            let mut seen: FxHashSet<u64> =
22052                FxHashSet::with_capacity_and_hasher(len, Default::default());
22053            return keys.into_iter().all(|key| seen.insert(key));
22054        }
22055
22056        let mut seen: FxHashSet<Vec<IndexLabel>> =
22057            FxHashSet::with_capacity_and_hasher(len, Default::default());
22058        (0..len).all(|row| seen.insert(self.tuple_at(row)))
22059    }
22060
22061    /// Whether any composite tuple appears more than once.
22062    ///
22063    /// Matches `pd.MultiIndex.has_duplicates`.
22064    #[must_use]
22065    pub fn has_duplicates(&self) -> bool {
22066        !self.is_unique()
22067    }
22068
22069    /// Drop duplicated tuples with pandas' default `keep='first'`.
22070    #[must_use]
22071    pub fn drop_duplicates(&self) -> Self {
22072        self.drop_duplicates_keep(DuplicateKeep::First)
22073    }
22074
22075    /// Drop duplicated tuples with explicit keep behavior.
22076    #[must_use]
22077    pub fn drop_duplicates_keep(&self, keep: DuplicateKeep) -> Self {
22078        if keep == DuplicateKeep::First
22079            && let Some(layout) = self.compact_two_level_identity_layout()
22080        {
22081            let mut seen = vec![0_u8; layout.slot_count];
22082            let mut positions = Vec::with_capacity(layout.slot_count.min(self.len()));
22083            for row in 0..self.len() {
22084                let key = layout.slot(row);
22085                if seen[key] == 0 {
22086                    seen[key] = 1;
22087                    positions.push(row);
22088                }
22089            }
22090            return self.take_existing_positions(&positions);
22091        }
22092        let duplicated = self.duplicated(keep);
22093        let positions: Vec<usize> = duplicated
22094            .iter()
22095            .enumerate()
22096            .filter_map(|(position, is_duplicated)| (!is_duplicated).then_some(position))
22097            .collect();
22098        self.take_existing_positions(&positions)
22099    }
22100
22101    /// Unique tuples, preserving first-seen order.
22102    #[must_use]
22103    pub fn unique(&self) -> Self {
22104        self.drop_duplicates_keep(DuplicateKeep::First)
22105    }
22106
22107    /// Number of unique tuples.
22108    #[must_use]
22109    pub fn nunique(&self) -> usize {
22110        let len = self.len();
22111        if len == 0 {
22112            return 0;
22113        }
22114        if let Some(layout) = self.compact_two_level_identity_layout() {
22115            let mut seen = vec![0_u8; layout.slot_count];
22116            let mut count = 0usize;
22117            for row in 0..len {
22118                let key = layout.slot(row);
22119                if seen[key] == 0 {
22120                    seen[key] = 1;
22121                    count += 1;
22122                }
22123            }
22124            return count;
22125        }
22126        if let Some(keys) = self.identity_packed_keys() {
22127            let mut seen: FxHashSet<u64> =
22128                FxHashSet::with_capacity_and_hasher(len, Default::default());
22129            for key in keys {
22130                seen.insert(key);
22131            }
22132            return seen.len();
22133        }
22134        let mut seen: FxHashSet<Vec<IndexLabel>> =
22135            FxHashSet::with_capacity_and_hasher(len, Default::default());
22136        for row in 0..len {
22137            seen.insert(self.tuple_at(row));
22138        }
22139        seen.len()
22140    }
22141
22142    /// Unsupported boolean reduction, matching `pd.MultiIndex.all()`.
22143    pub fn all(&self) -> Result<bool, IndexError> {
22144        Err(IndexError::InvalidArgument(
22145            "cannot perform all with this index type: MultiIndex".to_owned(),
22146        ))
22147    }
22148
22149    /// Unsupported boolean reduction, matching `pd.MultiIndex.any()`.
22150    pub fn any(&self) -> Result<bool, IndexError> {
22151        Err(IndexError::InvalidArgument(
22152            "cannot perform any with this index type: MultiIndex".to_owned(),
22153        ))
22154    }
22155
22156    /// Factorize tuples into integer codes and unique tuples.
22157    ///
22158    /// Missing labels remain part of the composite tuple identity, matching
22159    /// pandas' MultiIndex-level factorization behavior.
22160    #[must_use]
22161    pub fn factorize(&self) -> (Vec<isize>, Self) {
22162        let mut positions: FxHashMap<Vec<IndexLabel>, isize> =
22163            FxHashMap::with_capacity_and_hasher(self.len(), Default::default());
22164        let mut uniques = Vec::<Vec<IndexLabel>>::new();
22165        let mut codes = Vec::with_capacity(self.len());
22166        for tuple in self.to_list() {
22167            if let Some(code) = positions.get(&tuple) {
22168                codes.push(*code);
22169            } else {
22170                let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
22171                positions.insert(tuple.clone(), code);
22172                uniques.push(tuple);
22173                codes.push(code);
22174            }
22175        }
22176        let mut levels: Vec<Vec<IndexLabel>> = (0..self.nlevels())
22177            .map(|_| Vec::with_capacity(uniques.len()))
22178            .collect();
22179        for tuple in uniques {
22180            for (level_idx, label) in tuple.into_iter().enumerate() {
22181                levels[level_idx].push(label);
22182            }
22183        }
22184        let unique_index = Self::from_levels_and_names(levels, self.names.clone());
22185        (codes, unique_index)
22186    }
22187
22188    /// Count unique tuple occurrences, sorted by count descending then tuple.
22189    #[must_use]
22190    pub fn value_counts(&self) -> Vec<(Vec<IndexLabel>, usize)> {
22191        if let Some(layout) = self.compact_two_level_identity_layout() {
22192            let mut counts = vec![0usize; layout.slot_count];
22193            let mut first_rows = vec![usize::MAX; layout.slot_count];
22194            let mut unique_count = 0usize;
22195            for row in 0..self.len() {
22196                let slot = layout.slot(row);
22197                if counts[slot] == 0 {
22198                    first_rows[slot] = row;
22199                    unique_count += 1;
22200                }
22201                counts[slot] += 1;
22202            }
22203            let mut pairs = Vec::with_capacity(unique_count);
22204            for (slot, count) in counts.into_iter().enumerate() {
22205                if count != 0 {
22206                    pairs.push((self.tuple_at(first_rows[slot]), count));
22207                }
22208            }
22209            pairs.sort_by(|(left_tuple, left_count), (right_tuple, right_count)| {
22210                right_count
22211                    .cmp(left_count)
22212                    .then_with(|| left_tuple.cmp(right_tuple))
22213            });
22214            return pairs;
22215        }
22216        let mut counts: FxHashMap<Vec<IndexLabel>, usize> =
22217            FxHashMap::with_capacity_and_hasher(self.len(), Default::default());
22218        for tuple in self.to_list() {
22219            *counts.entry(tuple).or_insert(0) += 1;
22220        }
22221        let mut pairs: Vec<(Vec<IndexLabel>, usize)> = counts.into_iter().collect();
22222        pairs.sort_by(|(left_tuple, left_count), (right_tuple, right_count)| {
22223            right_count
22224                .cmp(left_count)
22225                .then_with(|| left_tuple.cmp(right_tuple))
22226        });
22227        pairs
22228    }
22229
22230    /// Positional sorter for lexicographic tuple order.
22231    #[must_use]
22232    pub fn argsort(&self) -> Vec<usize> {
22233        let mut order: Vec<usize> = (0..self.len()).collect();
22234        // Packed-key fast path: sort on one u64 per row (ascending u64 order ==
22235        // lexicographic row_cmp order) instead of comparing (Utf8) tuples. The
22236        // `.then(left.cmp(right))` original-position tiebreak is preserved, so
22237        // the permutation is identical to the tuple-comparison sort.
22238        if let Some(keys) = self.sorted_packed_keys() {
22239            order.sort_by(|&left, &right| {
22240                keys[left].cmp(&keys[right]).then_with(|| left.cmp(&right))
22241            });
22242            return order;
22243        }
22244        order.sort_by(|&left, &right| self.row_cmp(left, right).then_with(|| left.cmp(&right)));
22245        order
22246    }
22247
22248    /// Sort tuples lexicographically, matching `pd.MultiIndex.sort_values()`.
22249    #[must_use]
22250    pub fn sort_values(&self) -> Self {
22251        self.take_existing_positions(&self.argsort())
22252    }
22253
22254    /// Alias for `sort_values`, matching `pd.MultiIndex.sort`.
22255    #[must_use]
22256    pub fn sort(&self) -> Self {
22257        self.sort_values()
22258    }
22259
22260    /// Sort tuples and return the positional indexer used for the sort.
22261    #[must_use]
22262    pub fn sortlevel(&self) -> (Self, Vec<usize>) {
22263        let order = self.argsort();
22264        (self.take_existing_positions(&order), order)
22265    }
22266
22267    /// Lexicographic minimum tuple.
22268    #[must_use]
22269    pub fn min(&self) -> Option<Vec<IndexLabel>> {
22270        self.argsort()
22271            .first()
22272            .map(|&position| self.tuple_at(position))
22273    }
22274
22275    /// Lexicographic maximum tuple.
22276    #[must_use]
22277    pub fn max(&self) -> Option<Vec<IndexLabel>> {
22278        self.argsort()
22279            .last()
22280            .map(|&position| self.tuple_at(position))
22281    }
22282
22283    /// Position of the maximum tuple.
22284    #[must_use]
22285    pub fn argmax(&self) -> Option<usize> {
22286        self.argsort().last().copied()
22287    }
22288
22289    /// Position of the minimum tuple.
22290    #[must_use]
22291    pub fn argmin(&self) -> Option<usize> {
22292        self.argsort().first().copied()
22293    }
22294
22295    /// Append another MultiIndex to this one.
22296    ///
22297    /// Matches `pd.MultiIndex.append(other)` for equal-level indexes.
22298    pub fn append(&self, other: &Self) -> Result<Self, IndexError> {
22299        self.ensure_same_nlevels(other)?;
22300        let mut levels = Vec::with_capacity(self.nlevels());
22301        for level_idx in 0..self.nlevels() {
22302            let mut level = self.levels[level_idx].clone();
22303            level.extend(other.levels[level_idx].iter().cloned());
22304            levels.push(level);
22305        }
22306        Ok(Self::from_levels_and_names(
22307            levels,
22308            self.shared_names(other),
22309        ))
22310    }
22311
22312    /// Repeat each tuple `repeats` times, matching `pd.MultiIndex.repeat`.
22313    #[must_use]
22314    pub fn repeat(&self, repeats: usize) -> Self {
22315        if repeats == 1 {
22316            return self.clone();
22317        }
22318        let mut levels = Vec::with_capacity(self.nlevels());
22319        for level in &self.levels {
22320            let mut repeated = Vec::with_capacity(repeat_output_capacity(level.len(), repeats));
22321            for label in level {
22322                for _ in 0..repeats {
22323                    repeated.push(label.clone());
22324                }
22325            }
22326            levels.push(repeated);
22327        }
22328        Self::from_levels_and_names(levels, self.names.clone())
22329    }
22330
22331    /// Drop tuples containing any missing level label.
22332    ///
22333    /// Matches `pd.MultiIndex.dropna(how='any')`, which is pandas' default.
22334    #[must_use]
22335    pub fn dropna(&self) -> Self {
22336        self.dropna_any()
22337    }
22338
22339    /// Drop tuples containing any missing level label.
22340    #[must_use]
22341    pub fn dropna_any(&self) -> Self {
22342        let positions: Vec<usize> = (0..self.len())
22343            .filter(|&row| self.levels.iter().all(|level| !level[row].is_missing()))
22344            .collect();
22345        self.take_existing_positions(&positions)
22346    }
22347
22348    /// Drop tuples whose level labels are all missing.
22349    #[must_use]
22350    pub fn dropna_all(&self) -> Self {
22351        let positions: Vec<usize> = (0..self.len())
22352            .filter(|&row| !self.levels.iter().all(|level| level[row].is_missing()))
22353            .collect();
22354        self.take_existing_positions(&positions)
22355    }
22356
22357    /// Tuple intersection preserving left order and de-duplicating results.
22358    pub fn intersection(&self, other: &Self) -> Result<Self, IndexError> {
22359        self.ensure_same_nlevels(other)?;
22360        if let Some((self_levels, other_levels)) = self.two_utf8_level_slices(other) {
22361            let mut other_set = FxHashSet::<(&str, &str)>::default();
22362            for row in 0..other.len() {
22363                other_set.insert(Self::utf8_pair_at(other_levels, row));
22364            }
22365            let mut seen = FxHashSet::<(&str, &str)>::default();
22366            let mut pairs = Vec::new();
22367            for row in 0..self.len() {
22368                let key = Self::utf8_pair_at(self_levels, row);
22369                if other_set.contains(&key) && seen.insert(key) {
22370                    pairs.push(key);
22371                    if seen.len() == other_set.len() {
22372                        break;
22373                    }
22374                }
22375            }
22376            return Ok(Self::two_utf8_result_from_pairs(
22377                pairs,
22378                self.shared_names(other),
22379            ));
22380        }
22381        // Packed-key fast path (br-frankenpandas-misetop): identity-coded u64 per
22382        // row instead of to_list() (per-row Vec<IndexLabel> + Utf8 clone) and a
22383        // SipHash HashMap<Vec<IndexLabel>>. Keep self rows whose key is in other,
22384        // deduped first-seen, then gather those positions. Bijective on tuple
22385        // identity ⇒ same kept rows, same order.
22386        if let Some((self_keys, other_keys)) = self.factorize_packed_keys(other) {
22387            let other_set: FxHashSet<u64> = other_keys.into_iter().collect();
22388            let mut seen: FxHashSet<u64> =
22389                FxHashSet::with_capacity_and_hasher(self_keys.len(), Default::default());
22390            let positions: Vec<usize> = self_keys
22391                .iter()
22392                .enumerate()
22393                .filter_map(|(i, &k)| (other_set.contains(&k) && seen.insert(k)).then_some(i))
22394                .collect();
22395            return Ok(self
22396                .take_existing_positions(&positions)
22397                .set_names(self.shared_names(other)));
22398        }
22399        let other_keys: FxHashSet<Vec<IndexLabel>> = other.to_list().into_iter().collect();
22400        let mut seen =
22401            FxHashSet::<Vec<IndexLabel>>::with_capacity_and_hasher(self.len(), Default::default());
22402        let tuples = self
22403            .to_list()
22404            .into_iter()
22405            .filter(|tuple| other_keys.contains(tuple) && seen.insert(tuple.clone()))
22406            .collect();
22407        Self::from_tuples_with_names(tuples, self.shared_names(other))
22408    }
22409
22410    /// Tuple union preserving first-seen order from `self` then `other`.
22411    pub fn union(&self, other: &Self) -> Result<Self, IndexError> {
22412        self.ensure_same_nlevels(other)?;
22413        if let Some((self_levels, other_levels)) = self.two_utf8_level_slices(other) {
22414            let mut seen = FxHashSet::<(&str, &str)>::default();
22415            let mut pairs = Vec::new();
22416            for (levels, len) in [(self_levels, self.len()), (other_levels, other.len())] {
22417                for row in 0..len {
22418                    let key = Self::utf8_pair_at(levels, row);
22419                    if seen.insert(key) {
22420                        pairs.push(key);
22421                    }
22422                }
22423            }
22424            return Ok(Self::two_utf8_result_from_pairs(
22425                pairs,
22426                self.shared_names(other),
22427            ));
22428        }
22429        // General typed composite path: pack the dictionary-coded level columns
22430        // into one key and gather rows column-by-column.  This preserves the
22431        // left-first outer-union order without allocating a `Vec<IndexLabel>`
22432        // tuple (or cloning its labels merely to hash it) for every row.
22433        if let Some((self_keys, other_keys)) = self.factorize_packed_keys(other) {
22434            let mut seen: FxHashSet<u64> = FxHashSet::with_capacity_and_hasher(
22435                self.len().saturating_add(other.len()),
22436                Default::default(),
22437            );
22438            let mut levels: Vec<Vec<IndexLabel>> = self
22439                .levels
22440                .iter()
22441                .map(|_| Vec::with_capacity(self.len().saturating_add(other.len())))
22442                .collect();
22443            for (keys, source) in [(&self_keys, self), (&other_keys, other)] {
22444                for (row, &key) in keys.iter().enumerate() {
22445                    if seen.insert(key) {
22446                        for (out, level) in levels.iter_mut().zip(&source.levels) {
22447                            out.push(level[row].clone());
22448                        }
22449                    }
22450                }
22451            }
22452            return Ok(Self::from_levels_and_names(
22453                levels,
22454                self.shared_names(other),
22455            ));
22456        }
22457        let mut seen = FxHashSet::<Vec<IndexLabel>>::with_capacity_and_hasher(
22458            combined_output_capacity(self.len(), other.len()),
22459            Default::default(),
22460        );
22461        let mut tuples = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
22462        for tuple in self.to_list().into_iter().chain(other.to_list()) {
22463            if seen.insert(tuple.clone()) {
22464                tuples.push(tuple);
22465            }
22466        }
22467        Self::from_tuples_with_names(tuples, self.shared_names(other))
22468    }
22469
22470    /// Alias for `union`, matching the flat `Index::union_with` naming.
22471    pub fn union_with(&self, other: &Self) -> Result<Self, IndexError> {
22472        self.union(other)
22473    }
22474
22475    /// Tuple difference preserving left order and de-duplicating results.
22476    pub fn difference(&self, other: &Self) -> Result<Self, IndexError> {
22477        self.ensure_same_nlevels(other)?;
22478        if let Some((self_levels, other_levels)) = self.two_utf8_level_slices(other) {
22479            let mut other_set = FxHashSet::<(&str, &str)>::default();
22480            for row in 0..other.len() {
22481                other_set.insert(Self::utf8_pair_at(other_levels, row));
22482            }
22483            let mut seen = FxHashSet::<(&str, &str)>::default();
22484            let mut pairs = Vec::new();
22485            for row in 0..self.len() {
22486                let key = Self::utf8_pair_at(self_levels, row);
22487                if !other_set.contains(&key) && seen.insert(key) {
22488                    pairs.push(key);
22489                }
22490            }
22491            return Ok(Self::two_utf8_result_from_pairs(
22492                pairs,
22493                self.shared_names(other),
22494            ));
22495        }
22496        // Packed-key fast path (br-frankenpandas-misetop): keep self rows whose
22497        // key is NOT in other, deduped first-seen. See intersection.
22498        if let Some((self_keys, other_keys)) = self.factorize_packed_keys(other) {
22499            let other_set: FxHashSet<u64> = other_keys.into_iter().collect();
22500            let mut seen: FxHashSet<u64> =
22501                FxHashSet::with_capacity_and_hasher(self_keys.len(), Default::default());
22502            let positions: Vec<usize> = self_keys
22503                .iter()
22504                .enumerate()
22505                .filter_map(|(i, &k)| (!other_set.contains(&k) && seen.insert(k)).then_some(i))
22506                .collect();
22507            return Ok(self
22508                .take_existing_positions(&positions)
22509                .set_names(self.shared_names(other)));
22510        }
22511        let other_keys: FxHashSet<Vec<IndexLabel>> = other.to_list().into_iter().collect();
22512        let mut seen =
22513            FxHashSet::<Vec<IndexLabel>>::with_capacity_and_hasher(self.len(), Default::default());
22514        let tuples = self
22515            .to_list()
22516            .into_iter()
22517            .filter(|tuple| !other_keys.contains(tuple) && seen.insert(tuple.clone()))
22518            .collect();
22519        Self::from_tuples_with_names(tuples, self.shared_names(other))
22520    }
22521
22522    /// Tuple symmetric difference preserving first-seen order.
22523    pub fn symmetric_difference(&self, other: &Self) -> Result<Self, IndexError> {
22524        self.ensure_same_nlevels(other)?;
22525        if let Some((self_levels, other_levels)) = self.two_utf8_level_slices(other) {
22526            let mut self_set = FxHashSet::<(&str, &str)>::default();
22527            for row in 0..self.len() {
22528                self_set.insert(Self::utf8_pair_at(self_levels, row));
22529            }
22530            let mut other_set = FxHashSet::<(&str, &str)>::default();
22531            for row in 0..other.len() {
22532                other_set.insert(Self::utf8_pair_at(other_levels, row));
22533            }
22534            let mut seen = FxHashSet::<(&str, &str)>::default();
22535            let mut pairs = Vec::new();
22536            for row in 0..self.len() {
22537                let key = Self::utf8_pair_at(self_levels, row);
22538                if !other_set.contains(&key) && seen.insert(key) {
22539                    pairs.push(key);
22540                }
22541            }
22542            for row in 0..other.len() {
22543                let key = Self::utf8_pair_at(other_levels, row);
22544                if !self_set.contains(&key) && seen.insert(key) {
22545                    pairs.push(key);
22546                }
22547            }
22548            return Ok(Self::two_utf8_result_from_pairs(
22549                pairs,
22550                self.shared_names(other),
22551            ));
22552        }
22553        let self_keys: FxHashSet<Vec<IndexLabel>> = self.to_list().into_iter().collect();
22554        let other_keys: FxHashSet<Vec<IndexLabel>> = other.to_list().into_iter().collect();
22555        let mut seen = FxHashSet::<Vec<IndexLabel>>::with_capacity_and_hasher(
22556            combined_output_capacity(self.len(), other.len()),
22557            Default::default(),
22558        );
22559        let mut tuples = Vec::new();
22560        for tuple in self.to_list() {
22561            if !other_keys.contains(&tuple) && seen.insert(tuple.clone()) {
22562                tuples.push(tuple);
22563            }
22564        }
22565        for tuple in other.to_list() {
22566            if !self_keys.contains(&tuple) && seen.insert(tuple.clone()) {
22567                tuples.push(tuple);
22568            }
22569        }
22570        Self::from_tuples_with_names(tuples, self.shared_names(other))
22571    }
22572
22573    /// Group tuple positions by composite key, matching `pd.MultiIndex.groupby`.
22574    #[must_use]
22575    pub fn groupby(&self) -> HashMap<Vec<IndexLabel>, Vec<usize>> {
22576        let mut groups = HashMap::<Vec<IndexLabel>, Vec<usize>>::new();
22577        for row in 0..self.len() {
22578            groups.entry(self.tuple_at(row)).or_default().push(row);
22579        }
22580        groups
22581    }
22582
22583    /// Join two MultiIndexes using pandas-style join modes.
22584    pub fn join(&self, other: &Self, how: &str) -> Result<Self, IndexError> {
22585        match how {
22586            "left" => Ok(self.clone()),
22587            "right" => Ok(other.clone()),
22588            "inner" => self.intersection(other),
22589            "outer" => self.union(other),
22590            other => Err(IndexError::InvalidArgument(format!(
22591                "join: how must be 'left', 'right', 'inner', or 'outer', got {other:?}"
22592            ))),
22593        }
22594    }
22595
22596    /// Per-row membership test against a set of tuples.
22597    ///
22598    /// Matches `pd.MultiIndex.isin(values)`. Each entry in the returned
22599    /// bool vector is `true` iff that row's composite tuple appears in
22600    /// `values`. Tuples whose length does not match the MultiIndex's
22601    /// number of levels never match (silently contribute `false`),
22602    /// matching pandas' lenient behavior.
22603    #[must_use]
22604    pub fn isin(&self, values: &[Vec<IndexLabel>]) -> Vec<bool> {
22605        let nlevels = self.nlevels();
22606        let lookup: FxHashSet<&Vec<IndexLabel>> =
22607            values.iter().filter(|v| v.len() == nlevels).collect();
22608        if lookup.is_empty() {
22609            return vec![false; self.len()];
22610        }
22611        // Reuse one key buffer across rows: clear + extend refills the composite
22612        // lookup key in place, so membership is tested without allocating a fresh
22613        // Vec<IndexLabel> per row. Result is identical (value-based membership,
22614        // positional bool output).
22615        let mut key: Vec<IndexLabel> = Vec::with_capacity(nlevels);
22616        let mut out = Vec::with_capacity(self.len());
22617        for row in 0..self.len() {
22618            key.clear();
22619            key.extend(self.levels.iter().map(|level| level[row].clone()));
22620            out.push(lookup.contains(&key));
22621        }
22622        out
22623    }
22624
22625    /// Per-row membership test against values for a single level.
22626    ///
22627    /// Matches `pd.MultiIndex.isin(values, level=...)`. Returns `true`
22628    /// for positions whose label at `level` is in `values`. Returns an
22629    /// `OutOfBounds` error when `level` exceeds `nlevels()`.
22630    pub fn isin_level(&self, values: &[IndexLabel], level: usize) -> Result<Vec<bool>, IndexError> {
22631        if level >= self.nlevels() {
22632            return Err(IndexError::OutOfBounds {
22633                position: level,
22634                length: self.nlevels(),
22635            });
22636        }
22637        let lookup: FxHashSet<&IndexLabel> = values.iter().collect();
22638        Ok(self.levels[level]
22639            .iter()
22640            .map(|label| lookup.contains(label))
22641            .collect())
22642    }
22643
22644    /// Construct a MultiIndex from tuples of labels.
22645    ///
22646    /// Matches `pd.MultiIndex.from_tuples(tuples)`.
22647    /// Each inner Vec represents one row's labels across all levels.
22648    pub fn from_tuples(tuples: Vec<Vec<IndexLabel>>) -> Result<Self, IndexError> {
22649        if tuples.is_empty() {
22650            return Ok(Self::from_levels_and_names(Vec::new(), Vec::new()));
22651        }
22652
22653        let nlevels = tuples[0].len();
22654        for (i, t) in tuples.iter().enumerate() {
22655            if t.len() != nlevels {
22656                return Err(IndexError::LengthMismatch {
22657                    expected: nlevels,
22658                    actual: t.len(),
22659                    context: format!("tuple at position {i} has wrong number of levels"),
22660                });
22661            }
22662        }
22663
22664        let mut levels: Vec<Vec<IndexLabel>> = (0..nlevels)
22665            .map(|_| Vec::with_capacity(tuples.len()))
22666            .collect();
22667        for tuple in &tuples {
22668            for (level_idx, label) in tuple.iter().enumerate() {
22669                levels[level_idx].push(label.clone());
22670            }
22671        }
22672
22673        Ok(Self::from_levels_and_names(levels, vec![None; nlevels]))
22674    }
22675
22676    /// Construct a MultiIndex from parallel arrays (one per level).
22677    ///
22678    /// Matches `pd.MultiIndex.from_arrays(arrays)`.
22679    pub fn from_arrays(arrays: Vec<Vec<IndexLabel>>) -> Result<Self, IndexError> {
22680        if arrays.is_empty() {
22681            return Ok(Self::from_levels_and_names(Vec::new(), Vec::new()));
22682        }
22683
22684        let expected_len = arrays[0].len();
22685        for (i, arr) in arrays.iter().enumerate() {
22686            if arr.len() != expected_len {
22687                return Err(IndexError::LengthMismatch {
22688                    expected: expected_len,
22689                    actual: arr.len(),
22690                    context: format!("level {i} array length mismatch"),
22691                });
22692            }
22693        }
22694
22695        let nlevels = arrays.len();
22696        Ok(Self::from_levels_and_names(arrays, vec![None; nlevels]))
22697    }
22698
22699    /// Construct a MultiIndex from frame-like columns.
22700    ///
22701    /// Matches `pd.MultiIndex.from_frame(frame)` at the payload level:
22702    /// each input entry is one frame column, with the optional column name
22703    /// becoming the corresponding level name.
22704    pub fn from_frame(columns: Vec<(Option<String>, Vec<IndexLabel>)>) -> Result<Self, IndexError> {
22705        if columns.is_empty() {
22706            return Ok(Self::from_levels_and_names(Vec::new(), Vec::new()));
22707        }
22708
22709        let expected_len = columns[0].1.len();
22710        for (column_idx, (_, values)) in columns.iter().enumerate() {
22711            if values.len() != expected_len {
22712                return Err(IndexError::LengthMismatch {
22713                    expected: expected_len,
22714                    actual: values.len(),
22715                    context: format!("from_frame column {column_idx} length mismatch"),
22716                });
22717            }
22718        }
22719
22720        let mut names = Vec::with_capacity(columns.len());
22721        let mut levels = Vec::with_capacity(columns.len());
22722        for (name, values) in columns {
22723            names.push(name.map(LabelName::from));
22724            levels.push(values);
22725        }
22726
22727        Ok(Self::from_levels_and_names(levels, names))
22728    }
22729
22730    /// Construct a MultiIndex from the Cartesian product of iterables.
22731    ///
22732    /// Matches `pd.MultiIndex.from_product(iterables)`.
22733    pub fn from_product(iterables: Vec<Vec<IndexLabel>>) -> Result<Self, IndexError> {
22734        if iterables.is_empty() {
22735            return Ok(Self::from_levels_and_names(Vec::new(), Vec::new()));
22736        }
22737
22738        // Compute total size of the Cartesian product.
22739        let total = checked_cartesian_product_len(iterables.iter().map(Vec::len))?;
22740        if total == 0 {
22741            let nlevels = iterables.len();
22742            return Ok(Self::from_levels_and_names(
22743                (0..nlevels).map(|_| Vec::new()).collect(),
22744                vec![None; nlevels],
22745            ));
22746        }
22747
22748        let nlevels = iterables.len();
22749        let mut levels: Vec<Vec<IndexLabel>> =
22750            (0..nlevels).map(|_| Vec::with_capacity(total)).collect();
22751
22752        // Generate Cartesian product: for each position, compute which
22753        // element from each level by dividing position by the product of
22754        // all subsequent level lengths.
22755        for pos in 0..total {
22756            let mut remaining = pos;
22757            for (level_idx, iterable) in iterables.iter().enumerate().rev() {
22758                let idx_in_level = remaining % iterable.len();
22759                remaining /= iterable.len();
22760                levels[level_idx].push(iterable[idx_in_level].clone());
22761            }
22762        }
22763
22764        Ok(Self::from_levels_and_names(levels, vec![None; nlevels]))
22765    }
22766
22767    /// Flatten this MultiIndex into a single-level Index by joining
22768    /// level labels with a separator.
22769    ///
22770    /// Matches `pd.MultiIndex.to_flat_index()` (approximately).
22771    #[must_use]
22772    pub fn to_flat_index(&self, sep: &str) -> Index {
22773        use std::fmt::Write as _;
22774        let n = self.len();
22775        // Contiguous-Utf8 flat index (br-frankenpandas-flatidx-contig): the old form
22776        // built n separate `IndexLabel::Utf8(String)` — one heap allocation per row —
22777        // then `Index::new(Vec<IndexLabel>)`. This is the reshape MultiIndex floor hit
22778        // by wide_to_long / stack / unstack / set_index_multi, and it is built eagerly
22779        // even though the row MultiIndex is stored alongside. Instead write ALL n
22780        // composite labels into ONE growing String buffer, recording byte offsets, and
22781        // hand the buffer + offsets to the lazy contiguous-Utf8 Index backing (nbspq):
22782        // one big allocation instead of n small ones, no per-row IndexLabel box, no
22783        // per-row `Vec<String>` + `join`. Semantically identical — the backing
22784        // materializes the same `IndexLabel::Utf8` labels on demand (same bytes:
22785        // `write!("{}", level[i])` == `level[i].to_string()`, `sep` between levels ==
22786        // `parts.join(sep)`), so labels(), lookups, and duplicate detection are unchanged.
22787        // The n composite-label bytes are independent per row and the assembly is
22788        // CPU-bound (per-row `write!` formatting + `push_str`, not raw bandwidth), so
22789        // build it in PARALLEL — each worker fills its own local byte buffer + relative
22790        // offsets for a contiguous row range, then the chunks are concatenated in row
22791        // order with offsets shifted by the running byte base. Bit-identical to the
22792        // serial build. This is the reshape MultiIndex floor hit by wide_to_long / stack
22793        // / unstack / set_index_multi; CPU-bound per-thread-buffer parallelism scales
22794        // even on a loaded box (no shared-allocator/bandwidth contention).
22795        let levels = &self.levels;
22796        // The per-level `write!(buf, "{}", level[i])` above was the LAST piece of
22797        // `core::fmt` left inside this already-parallel, already-contiguous build:
22798        // an `IndexLabel` Display + `Formatter::pad` dispatch per LEVEL per ROW,
22799        // and this loop does no other work. Dispatch straight off the variant
22800        // instead. BIT-IDENTICAL by construction against `impl Display for
22801        // IndexLabel`: `Int64(v) => write!(f, "{v}")` is plain decimal, which is
22802        // exactly `push_i64_decimal`; `Utf8(v) => write!(f, "{v}")` is exactly the
22803        // string's bytes. Every other variant (Float64 "%.1f"-style ".0" fixup,
22804        // Bool "True"/"False", Null, temporal) keeps the verbatim Display path
22805        // through a REUSED scratch String, which also drops that variant's per-row
22806        // allocation. Same bytes, same offsets, same order.
22807        let build = |lo: usize, hi: usize| -> (Vec<u8>, Vec<usize>) {
22808            let mut buf: Vec<u8> = Vec::new();
22809            let mut offs: Vec<usize> = Vec::with_capacity(hi - lo);
22810            let mut scratch = String::new();
22811            for i in lo..hi {
22812                for (li, level) in levels.iter().enumerate() {
22813                    if li > 0 {
22814                        buf.extend_from_slice(sep.as_bytes());
22815                    }
22816                    match &level[i] {
22817                        IndexLabel::Int64(v) => push_i64_decimal(&mut buf, *v),
22818                        IndexLabel::Utf8(s) => buf.extend_from_slice(s.as_bytes()),
22819                        other => {
22820                            scratch.clear();
22821                            let _ = write!(scratch, "{other}");
22822                            buf.extend_from_slice(scratch.as_bytes());
22823                        }
22824                    }
22825                }
22826                offs.push(buf.len());
22827            }
22828            (buf, offs)
22829        };
22830        const FLATIDX_PAR_MIN_ROWS: usize = 50_000;
22831        const FLATIDX_PAR_MIN_PER_WORKER: usize = 16_384;
22832        let workers = if n >= FLATIDX_PAR_MIN_ROWS {
22833            cached_available_parallelism()
22834                .min(16)
22835                .min(n / FLATIDX_PAR_MIN_PER_WORKER)
22836                .max(1)
22837        } else {
22838            1
22839        };
22840        let (bytes, offsets): (Vec<u8>, Vec<usize>) = if workers >= 2 {
22841            let chunk = n.div_ceil(workers);
22842            let build = &build;
22843            let parts: Vec<(Vec<u8>, Vec<usize>)> = std::thread::scope(|scope| {
22844                let mut handles = Vec::with_capacity(workers);
22845                let mut start = 0;
22846                while start < n {
22847                    let end = (start + chunk).min(n);
22848                    handles.push(scope.spawn(move || build(start, end)));
22849                    start = end;
22850                }
22851                handles
22852                    .into_iter()
22853                    .map(|h| h.join().expect("to_flat_index thread"))
22854                    .collect()
22855            });
22856            let total: usize = parts.iter().map(|(b, _)| b.len()).sum();
22857            let mut bytes = Vec::with_capacity(total);
22858            let mut offsets = Vec::with_capacity(n + 1);
22859            offsets.push(0);
22860            let mut base = 0usize;
22861            for (b, offs) in &parts {
22862                for &o in offs {
22863                    offsets.push(base + o);
22864                }
22865                base += b.len();
22866                bytes.extend_from_slice(b);
22867            }
22868            (bytes, offsets)
22869        } else {
22870            let (b, offs) = build(0, n);
22871            let mut offsets = Vec::with_capacity(n + 1);
22872            offsets.push(0);
22873            offsets.extend_from_slice(&offs);
22874            (b, offsets)
22875        };
22876        Index::from_utf8_contiguous(Arc::from(bytes), Arc::from(offsets))
22877    }
22878
22879    /// **Bench-only ORIG reference.** Byte-for-byte the `to_flat_index` body as it
22880    /// stood before the `core::fmt` removal (`write!(buf, "{}", level[i])` per level
22881    /// per row), including the identical parallel/serial split and gates, so an A/B
22882    /// isolates EXACTLY the formatting change and nothing else. Compiled only under
22883    /// `cfg(test)`, so the shipped binary is unaffected. Kept in-tree (rather than
22884    /// stashed or diffed against another build) because `rch exec` picks its worker
22885    /// non-deterministically and the ORIG/CAND ratio is NOT worker-invariant: both
22886    /// arms must live in ONE binary and alternate inside ONE invocation.
22887    #[cfg(test)]
22888    #[must_use]
22889    pub(crate) fn to_flat_index_ref_write_fmt(&self, sep: &str) -> Index {
22890        use std::fmt::Write as _;
22891        let n = self.len();
22892        let levels = &self.levels;
22893        let build = |lo: usize, hi: usize| -> (Vec<u8>, Vec<usize>) {
22894            let mut buf = String::new();
22895            let mut offs: Vec<usize> = Vec::with_capacity(hi - lo);
22896            for i in lo..hi {
22897                for (li, level) in levels.iter().enumerate() {
22898                    if li > 0 {
22899                        buf.push_str(sep);
22900                    }
22901                    let _ = write!(buf, "{}", level[i]);
22902                }
22903                offs.push(buf.len());
22904            }
22905            (buf.into_bytes(), offs)
22906        };
22907        const FLATIDX_PAR_MIN_ROWS: usize = 50_000;
22908        const FLATIDX_PAR_MIN_PER_WORKER: usize = 16_384;
22909        let workers = if n >= FLATIDX_PAR_MIN_ROWS {
22910            cached_available_parallelism()
22911                .min(16)
22912                .min(n / FLATIDX_PAR_MIN_PER_WORKER)
22913                .max(1)
22914        } else {
22915            1
22916        };
22917        let (bytes, offsets): (Vec<u8>, Vec<usize>) = if workers >= 2 {
22918            let chunk = n.div_ceil(workers);
22919            let build = &build;
22920            let parts: Vec<(Vec<u8>, Vec<usize>)> = std::thread::scope(|scope| {
22921                let mut handles = Vec::with_capacity(workers);
22922                let mut start = 0;
22923                while start < n {
22924                    let end = (start + chunk).min(n);
22925                    handles.push(scope.spawn(move || build(start, end)));
22926                    start = end;
22927                }
22928                handles
22929                    .into_iter()
22930                    .map(|h| h.join().expect("to_flat_index ref thread"))
22931                    .collect()
22932            });
22933            let total: usize = parts.iter().map(|(b, _)| b.len()).sum();
22934            let mut bytes = Vec::with_capacity(total);
22935            let mut offsets = Vec::with_capacity(n + 1);
22936            offsets.push(0);
22937            let mut base = 0usize;
22938            for (b, offs) in &parts {
22939                for &o in offs {
22940                    offsets.push(base + o);
22941                }
22942                base += b.len();
22943                bytes.extend_from_slice(b);
22944            }
22945            (bytes, offsets)
22946        } else {
22947            let (b, offs) = build(0, n);
22948            let mut offsets = Vec::with_capacity(n + 1);
22949            offsets.push(0);
22950            offsets.extend_from_slice(&offs);
22951            (b, offsets)
22952        };
22953        Index::from_utf8_contiguous(Arc::from(bytes), Arc::from(offsets))
22954    }
22955
22956    /// Drop a level from this MultiIndex, returning a new MultiIndex
22957    /// (or an Index if only one level remains).
22958    ///
22959    /// Matches `pd.MultiIndex.droplevel(level)`.
22960    pub fn droplevel(&self, level: usize) -> Result<MultiIndexOrIndex, IndexError> {
22961        if level >= self.nlevels() {
22962            return Err(IndexError::OutOfBounds {
22963                position: level,
22964                length: self.nlevels(),
22965            });
22966        }
22967        if self.nlevels() <= 1 {
22968            return Err(IndexError::OutOfBounds {
22969                position: level,
22970                length: self.nlevels(),
22971            });
22972        }
22973
22974        let mut new_levels = self.levels.clone();
22975        new_levels.remove(level);
22976        let mut new_names = self.names.clone();
22977        new_names.remove(level);
22978
22979        if new_levels.len() == 1 {
22980            let mut idx = Index::new(new_levels.into_iter().next().unwrap());
22981            if let Some(ref name) = new_names[0] {
22982                idx = idx.set_name(name);
22983            }
22984            Ok(MultiIndexOrIndex::Index(idx))
22985        } else {
22986            Ok(MultiIndexOrIndex::Multi(Self::from_levels_and_names(
22987                new_levels, new_names,
22988            )))
22989        }
22990    }
22991
22992    /// Swap two levels.
22993    ///
22994    /// Matches `pd.MultiIndex.swaplevel(i, j)`.
22995    pub fn swaplevel(&self, i: usize, j: usize) -> Result<Self, IndexError> {
22996        if i >= self.nlevels() || j >= self.nlevels() {
22997            return Err(IndexError::OutOfBounds {
22998                position: i.max(j),
22999                length: self.nlevels(),
23000            });
23001        }
23002        let mut new_levels = self.levels.clone();
23003        let mut new_names = self.names.clone();
23004        new_levels.swap(i, j);
23005        new_names.swap(i, j);
23006        Ok(Self::from_levels_and_names(new_levels, new_names))
23007    }
23008
23009    /// Reorder levels according to the given order.
23010    ///
23011    /// Matches `pd.MultiIndex.reorder_levels(order)`.
23012    /// `order` is a slice of level indices specifying the new order.
23013    /// Must contain each level index exactly once.
23014    pub fn reorder_levels(&self, order: &[usize]) -> Result<Self, IndexError> {
23015        if order.len() != self.nlevels() {
23016            return Err(IndexError::LengthMismatch {
23017                expected: self.nlevels(),
23018                actual: order.len(),
23019                context: "reorder_levels: order length must match nlevels".into(),
23020            });
23021        }
23022
23023        // Validate all indices are in range and unique.
23024        let mut seen = vec![false; self.nlevels()];
23025        for &idx in order {
23026            if idx >= self.nlevels() {
23027                return Err(IndexError::OutOfBounds {
23028                    position: idx,
23029                    length: self.nlevels(),
23030                });
23031            }
23032            if seen[idx] {
23033                return Err(IndexError::LengthMismatch {
23034                    expected: self.nlevels(),
23035                    actual: order.len(),
23036                    context: format!("reorder_levels: duplicate level index {idx}"),
23037                });
23038            }
23039            seen[idx] = true;
23040        }
23041
23042        let new_levels: Vec<Vec<IndexLabel>> =
23043            order.iter().map(|&idx| self.levels[idx].clone()).collect();
23044        let new_names: Vec<Option<LabelName>> =
23045            order.iter().map(|&idx| self.names[idx].clone()).collect();
23046
23047        Ok(Self::from_levels_and_names(new_levels, new_names))
23048    }
23049}
23050
23051/// Result of `MultiIndex::droplevel` — either a MultiIndex (if 2+ levels remain)
23052/// or a plain Index (if reduced to 1 level).
23053#[allow(clippy::large_enum_variant)]
23054#[derive(Debug, Clone, PartialEq)]
23055pub enum MultiIndexOrIndex {
23056    Multi(MultiIndex),
23057    Index(Index),
23058}
23059
23060#[cfg(test)]
23061mod tests {
23062    use std::sync::Arc;
23063
23064    use fp_types::{Period, PeriodFreq, Scalar, Timedelta};
23065
23066    use crate::{Int64TwoAffineLabels, LabelKinds, OrderedF64};
23067
23068    #[test]
23069    fn index_categories_ride_selection_and_refuse_outsiders_cld41() {
23070        let text = |values: &[&str]| -> Vec<IndexLabel> {
23071            values
23072                .iter()
23073                .map(|value| IndexLabel::Utf8((*value).to_owned()))
23074                .collect()
23075        };
23076        let categories = super::IndexCategories {
23077            categories: text(&["y", "x", "z"]),
23078            ordered: true,
23079        };
23080        let index = Index::new(text(&["x", "y", "x"]))
23081            .with_categories(Some(categories.clone()))
23082            .expect("labels among the categories");
23083        assert_eq!(index.categories(), Some(&categories));
23084        // A selection of the labels keeps them (take, slice, clone).
23085        assert_eq!(index.take(&[2, 0]).categories(), Some(&categories));
23086        assert_eq!(index.slice(1, 2).categories(), Some(&categories));
23087        assert_eq!(index.clone().categories(), Some(&categories));
23088        // Equality ignores them, as the zone-free label comparison does.
23089        assert_eq!(index, Index::new(text(&["x", "y", "x"])));
23090        // NEGATIVE: a label outside the categories is refused, and a plain
23091        // index has none.
23092        assert!(
23093            Index::new(text(&["x", "w"]))
23094                .with_categories(Some(categories))
23095                .is_err()
23096        );
23097        assert!(Index::new(text(&["x"])).categories().is_none());
23098    }
23099
23100    #[test]
23101    fn interval_labels_compare_hash_and_print_like_pandas_c27hq() {
23102        use std::collections::HashSet;
23103
23104        use fp_types::{Interval, IntervalClosed};
23105        let right = |left: f64, right: f64| Interval::new(left, right, IntervalClosed::Right);
23106        let a = IndexLabel::Interval(right(0.0, 1.0));
23107        let b = IndexLabel::Interval(right(1.0, 2.0));
23108        // An interval is a present label, equal to itself whatever the
23109        // endpoints' type, printed as pandas prints it.
23110        assert!(!a.is_missing());
23111        assert_eq!(
23112            a,
23113            IndexLabel::Interval(right(0.0, 1.0).with_int_endpoints())
23114        );
23115        assert_eq!(b.to_string(), "(1.0, 2.0]");
23116        // Ordered by left then right endpoint, before missing labels.
23117        let mut labels = vec![
23118            IndexLabel::Null(fp_types::NullKind::NaN),
23119            b.clone(),
23120            IndexLabel::Interval(right(0.0, 2.0)),
23121            a.clone(),
23122        ];
23123        labels.sort();
23124        assert_eq!(
23125            labels,
23126            vec![
23127                a.clone(),
23128                IndexLabel::Interval(right(0.0, 2.0)),
23129                b.clone(),
23130                IndexLabel::Null(fp_types::NullKind::NaN),
23131            ]
23132        );
23133        // Equal intervals hash alike (-0.0 is 0.0), so an index finds them.
23134        let set: HashSet<IndexLabel> = [a.clone(), IndexLabel::Interval(right(-0.0, 1.0))]
23135            .into_iter()
23136            .collect();
23137        assert_eq!(set.len(), 1);
23138        let index = Index::new(vec![b.clone(), a.clone()]);
23139        assert_eq!(index.position(&a), Some(1));
23140        // NEGATIVE: the closed side is part of the label, and an interval is
23141        // not its text.
23142        assert_ne!(
23143            a,
23144            IndexLabel::Interval(Interval::new(0.0, 1.0, IntervalClosed::Left))
23145        );
23146        assert_ne!(a, IndexLabel::Utf8("(0.0, 1.0]".to_owned()));
23147    }
23148
23149    #[test]
23150    fn slice_bounds_read_decreasing_and_unsorted_like_pandas_h1kl9() {
23151        let int = IndexLabel::Int64;
23152        let float = |value: f64| IndexLabel::Float64(OrderedF64(value));
23153        // A decreasing index: a held label bounds by its position, one
23154        // between labels by the count above (left) or not below (right).
23155        let decreasing = Index::from_i64(vec![4, 3, 2, 1]);
23156        assert_eq!(
23157            decreasing.slice_locs(Some(&int(2)), Some(&int(3))),
23158            Ok((2, 2))
23159        );
23160        assert_eq!(
23161            decreasing.slice_locs(Some(&float(2.5)), Some(&float(1.5))),
23162            Ok((2, 3))
23163        );
23164        // A stop before the start is kept (pandas slices nothing with it).
23165        assert_eq!(
23166            decreasing.slice_locs(Some(&int(0)), Some(&int(5))),
23167            Ok((4, 0))
23168        );
23169        // An unsorted index finds a held label; one it cannot place, or one
23170        // held apart from one run, is pandas' KeyError.
23171        let unsorted = Index::from_i64(vec![3, 1, 2]);
23172        assert_eq!(
23173            unsorted.slice_locs(Some(&int(1)), Some(&int(2))),
23174            Ok((1, 3))
23175        );
23176        assert_eq!(
23177            unsorted.get_slice_bound(&int(5), "left"),
23178            Err(IndexError::LabelNotFound(int(5)))
23179        );
23180        assert_eq!(
23181            Index::from_i64(vec![1, 2, 1]).get_slice_bound(&int(1), "left"),
23182            Err(IndexError::KeyError(
23183                "Cannot get left slice bound for non-unique label: 1".to_owned()
23184            ))
23185        );
23186        // NEGATIVE: an increasing index keeps its searchsorted bounds, a run
23187        // of equal labels bounding by its ends, and an unknown side is an
23188        // error.
23189        let increasing = Index::from_i64(vec![1, 2, 2, 3]);
23190        assert_eq!(
23191            increasing.slice_locs(Some(&int(2)), Some(&int(2))),
23192            Ok((1, 3))
23193        );
23194        assert_eq!(increasing.get_slice_bound(&float(2.5), "right"), Ok(3));
23195        assert!(increasing.get_slice_bound(&int(2), "middle").is_err());
23196    }
23197
23198    #[test]
23199    fn unsorted_unique_int64_positions_gating_and_resolution() {
23200        // Unsorted unique Int64 ⇒ resolves via the cached hashtable.
23201        let idx = Index::new(vec![
23202            IndexLabel::Int64(4),
23203            IndexLabel::Int64(0),
23204            IndexLabel::Int64(6),
23205            IndexLabel::Int64(2),
23206        ]);
23207        let got = idx
23208            .unsorted_unique_int64_positions(&[
23209                IndexLabel::Int64(6),
23210                IndexLabel::Int64(4),
23211                IndexLabel::Int64(99),
23212            ])
23213            .expect("unsorted unique Int64 index should resolve");
23214        assert_eq!(got, vec![Some(2), Some(0), None]);
23215
23216        // Sorted-ascending Int64 ⇒ None (binary-search path owns it).
23217        let sorted = Index::new(vec![
23218            IndexLabel::Int64(0),
23219            IndexLabel::Int64(2),
23220            IndexLabel::Int64(4),
23221        ]);
23222        assert!(
23223            sorted
23224                .unsorted_unique_int64_positions(&[IndexLabel::Int64(2)])
23225                .is_none()
23226        );
23227
23228        // Duplicate labels ⇒ None (multimap semantics required).
23229        let dup = Index::new(vec![
23230            IndexLabel::Int64(5),
23231            IndexLabel::Int64(1),
23232            IndexLabel::Int64(5),
23233        ]);
23234        assert!(
23235            dup.unsorted_unique_int64_positions(&[IndexLabel::Int64(5)])
23236                .is_none()
23237        );
23238    }
23239
23240    #[test]
23241    fn get_indexer_unsorted_unique_utf8_matches_map_path() {
23242        // Unsorted unique Utf8 self now routes through the cached resolver; the
23243        // result must equal first-occurrence positions (None for absent).
23244        let idx = Index::new(vec![
23245            IndexLabel::Utf8("beta".to_owned()),
23246            IndexLabel::Utf8("alpha".to_owned()),
23247            IndexLabel::Utf8("gamma".to_owned()),
23248        ]);
23249        let target = Index::new(vec![
23250            IndexLabel::Utf8("gamma".to_owned()),
23251            IndexLabel::Utf8("alpha".to_owned()),
23252            IndexLabel::Utf8("missing".to_owned()),
23253            IndexLabel::Utf8("beta".to_owned()),
23254        ]);
23255        assert_eq!(
23256            idx.get_indexer(&target),
23257            vec![Some(2), Some(1), None, Some(0)]
23258        );
23259
23260        // Duplicate self keeps first-occurrence semantics via the map fallback.
23261        let dup = Index::new(vec![
23262            IndexLabel::Utf8("x".to_owned()),
23263            IndexLabel::Utf8("y".to_owned()),
23264            IndexLabel::Utf8("x".to_owned()),
23265        ]);
23266        let t2 = Index::new(vec![IndexLabel::Utf8("x".to_owned())]);
23267        assert_eq!(dup.get_indexer(&t2), vec![Some(0)]);
23268    }
23269
23270    use super::{
23271        CategoricalIndex, DateOffset, DateRangeError, DatetimeIndex, Index, IndexError, IndexLabel,
23272        Int64AffineLabels, MultiIndex, PeriodFields, PeriodIndex, RangeIndex, TimedeltaIndex,
23273        TimedeltaRangeError, align_union, apply_date_offset, bdate_range, date_range, infer_freq,
23274        infer_freq_from_timestamps, timedelta_range, validate_alignment_plan,
23275    };
23276
23277    fn int64_labels(index: &Index) -> Vec<i64> {
23278        index
23279            .labels()
23280            .iter()
23281            .filter_map(|label| match label {
23282                IndexLabel::Int64(value) => Some(*value),
23283                _ => None,
23284            })
23285            .collect()
23286    }
23287
23288    /// Regression lock for br-frankenpandas-i3t8. `Index` must stay
23289    /// `Send + Sync` so `DataFrame` can be wrapped in `Arc` and shared
23290    /// across reader threads. A future refactor that reintroduces
23291    /// `std::cell::OnceCell` (or any `!Sync` interior-mutability primitive)
23292    /// breaks this test at compile time.
23293    #[test]
23294    fn index_is_send_and_sync() {
23295        fn assert_send_sync<T: Send + Sync>() {}
23296        assert_send_sync::<Index>();
23297        assert_send_sync::<MultiIndex>();
23298    }
23299
23300    #[test]
23301    fn bdate_range_rolls_weekend_start_forward() {
23302        let idx = bdate_range(Some("2024-01-06"), None, Some(3), None).unwrap();
23303        assert_eq!(
23304            idx.labels(),
23305            &[
23306                IndexLabel::Datetime64(1_704_672_000_000_000_000),
23307                IndexLabel::Datetime64(1_704_758_400_000_000_000),
23308                IndexLabel::Datetime64(1_704_844_800_000_000_000),
23309            ]
23310        );
23311    }
23312
23313    #[test]
23314    fn bdate_range_rolls_weekend_end_backward_and_preserves_name() {
23315        let idx = bdate_range(None, Some("2024-01-07"), Some(3), Some("biz")).unwrap();
23316        assert_eq!(
23317            idx.labels(),
23318            &[
23319                IndexLabel::Datetime64(1_704_240_000_000_000_000),
23320                IndexLabel::Datetime64(1_704_326_400_000_000_000),
23321                IndexLabel::Datetime64(1_704_412_800_000_000_000),
23322            ]
23323        );
23324        assert_eq!(idx.name().map(|n| n.as_str()), Some("biz"));
23325    }
23326
23327    #[test]
23328    fn timedelta_range_rejects_over_specified_parameters() {
23329        let err = timedelta_range(
23330            Some(Timedelta::NANOS_PER_DAY),
23331            Some(3 * Timedelta::NANOS_PER_DAY),
23332            Some(2),
23333            Timedelta::NANOS_PER_DAY,
23334            None,
23335        )
23336        .expect_err("start + end + periods with explicit freq must fail closed");
23337        assert!(matches!(err, TimedeltaRangeError::TooManyParams));
23338    }
23339
23340    #[test]
23341    fn timedelta_range_steps_backwards_and_away_is_empty_tzxpk() {
23342        let day = Timedelta::NANOS_PER_DAY;
23343        let labels = |idx: Index| idx.labels().to_vec();
23344        // pandas: timedelta_range('5D', periods=3, freq='-1D') is 5, 4, 3 days.
23345        assert_eq!(
23346            labels(timedelta_range(Some(5 * day), None, Some(3), -day, None).unwrap()),
23347            [5, 4, 3].map(|d| IndexLabel::Timedelta64(d * day))
23348        );
23349        // ... from end: '-1D' ending at 1 day is 3, 2, 1 days.
23350        assert_eq!(
23351            labels(timedelta_range(None, Some(day), Some(3), -day, None).unwrap()),
23352            [3, 2, 1].map(|d| IndexLabel::Timedelta64(d * day))
23353        );
23354        // Stepping away from `end` is empty, either sign.
23355        assert!(
23356            timedelta_range(Some(day), Some(5 * day), None, -day, None)
23357                .unwrap()
23358                .is_empty()
23359        );
23360        assert!(
23361            timedelta_range(Some(5 * day), Some(day), None, day, None)
23362                .unwrap()
23363                .is_empty()
23364        );
23365        // NEGATIVE: a zero step is refused.
23366        assert!(matches!(
23367            timedelta_range(Some(day), None, Some(2), 0, None),
23368            Err(TimedeltaRangeError::ZeroFreq)
23369        ));
23370    }
23371
23372    #[test]
23373    fn date_range_rejects_over_specified_parameters() {
23374        let err = date_range(
23375            Some("2020-01-01"),
23376            Some("2020-01-03"),
23377            Some(2),
23378            Timedelta::NANOS_PER_DAY,
23379            None,
23380        )
23381        .expect_err("start + end + periods with explicit freq must fail closed");
23382        assert!(matches!(err, DateRangeError::TooManyParams));
23383    }
23384
23385    #[test]
23386    fn date_range_keeps_validated_labels_lazy_until_observed() {
23387        let index = date_range(
23388            Some("2024-01-01"),
23389            None,
23390            Some(3),
23391            Timedelta::NANOS_PER_DAY,
23392            Some("timestamp"),
23393        )
23394        .unwrap();
23395        assert_eq!(
23396            index.labels.datetime64_affine_range(),
23397            Some(Int64AffineLabels {
23398                start: 1_704_067_200_000_000_000,
23399                step: Timedelta::NANOS_PER_DAY,
23400                len: 3,
23401            })
23402        );
23403        assert!(index.labels.materialized.get().is_none());
23404        assert_eq!(index.name().map(|n| n.as_str()), Some("timestamp"));
23405        assert_eq!(
23406            index.labels(),
23407            &[
23408                IndexLabel::Datetime64(1_704_067_200_000_000_000),
23409                IndexLabel::Datetime64(1_704_153_600_000_000_000),
23410                IndexLabel::Datetime64(1_704_240_000_000_000_000),
23411            ]
23412        );
23413    }
23414
23415    #[test]
23416    fn datetime_index_of_an_affine_range_keeps_it_lazy_so0mr() {
23417        // A DatetimeIndex over a date_range's lazy range, zoned, answers its
23418        // instants without making its labels (br-frankenpandas-so0mr).
23419        let (start, step) = (1_704_067_200_000_000_000, 60 * Timedelta::NANOS_PER_SEC);
23420        let expected: Vec<i64> = (0..4).map(|k| start + k * step).collect();
23421        let affine = Index::from_datetime64_affine_range(start, step, 4).unwrap();
23422        let dti = DatetimeIndex::from_index(affine)
23423            .and_then(|dti| dti.with_tz(Some("UTC")))
23424            .unwrap();
23425        assert_eq!(dti.asi8(), expected);
23426        assert!(dti.as_index().labels.materialized.get().is_none());
23427        assert_eq!(dti.tz().as_deref(), Some("UTC"));
23428        assert_eq!(
23429            DatetimeIndex::from_index(Index::from_datetime64(expected.clone()))
23430                .unwrap()
23431                .asi8(),
23432            expected
23433        );
23434        // Negative: an index of other labels is still refused.
23435        let ints = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Int64(2)]);
23436        assert!(DatetimeIndex::from_index(ints).is_err());
23437        // Labels a clone makes are the original's too (a Series resampled
23438        // made them again every call).
23439        let original = Index::from_datetime64_affine_range(start, step, 4).unwrap();
23440        let clone = original.clone();
23441        assert!(original.labels.materialized.get().is_none());
23442        assert_eq!(clone.labels().len(), 4);
23443        assert!(original.labels.materialized.get().is_some());
23444        assert_eq!(original.labels(), clone.labels());
23445    }
23446
23447    #[test]
23448    fn datetime_index_reads_one_stamp_at_a_position_tumiz() {
23449        // asi8_at is asi8()[pos] without the rest - a lazy range answers
23450        // from its arithmetic, labels unmade (br-frankenpandas-tumiz).
23451        let (start, step) = (1_704_067_200_000_000_000, -3_600 * Timedelta::NANOS_PER_SEC);
23452        let lazy =
23453            DatetimeIndex::from_index(Index::from_datetime64_affine_range(start, step, 5).unwrap())
23454                .unwrap();
23455        let listed = DatetimeIndex::new(vec![start, i64::MIN, start - 7]);
23456        for dti in [&lazy, &listed] {
23457            let all = dti.asi8();
23458            let each: Vec<i64> = (0..all.len()).filter_map(|pos| dti.asi8_at(pos)).collect();
23459            assert_eq!(each, all);
23460            // NEGATIVE: past the end is None, not a stamp.
23461            assert_eq!(dti.asi8_at(all.len()), None);
23462        }
23463        assert!(lazy.as_index().labels.materialized.get().is_none());
23464    }
23465
23466    #[test]
23467    fn date_range_affine_matches_eager_labels_for_each_parameter_form() {
23468        let expected = |start: i64, step: i64, len: usize| {
23469            (0..len)
23470                .map(|offset| {
23471                    IndexLabel::Datetime64(
23472                        start + i64::try_from(offset).expect("small test offset fits i64") * step,
23473                    )
23474                })
23475                .collect::<Vec<_>>()
23476        };
23477        let start = 1_704_067_200_000_000_000;
23478
23479        let start_end = date_range(
23480            Some("2024-01-01"),
23481            Some("2024-01-06"),
23482            None,
23483            2 * Timedelta::NANOS_PER_DAY,
23484            None,
23485        )
23486        .unwrap();
23487        assert_eq!(
23488            start_end.labels(),
23489            expected(start, 2 * Timedelta::NANOS_PER_DAY, 3)
23490        );
23491
23492        let end_periods = date_range(
23493            None,
23494            Some("2024-01-01 02:00:00"),
23495            Some(3),
23496            Timedelta::NANOS_PER_HOUR,
23497            None,
23498        )
23499        .unwrap();
23500        assert_eq!(
23501            end_periods.labels(),
23502            expected(start, Timedelta::NANOS_PER_HOUR, 3)
23503        );
23504
23505        let empty = date_range(
23506            Some("2024-01-01"),
23507            None,
23508            Some(0),
23509            Timedelta::NANOS_PER_DAY,
23510            Some("empty"),
23511        )
23512        .unwrap();
23513        assert!(empty.is_empty());
23514        assert_eq!(empty.name().map(|n| n.as_str()), Some("empty"));
23515    }
23516
23517    #[test]
23518    fn date_range_rejects_generated_timestamp_overflow() {
23519        let err = date_range(
23520            Some("2262-04-11 23:47:16"),
23521            None,
23522            Some(3),
23523            Timedelta::NANOS_PER_SEC,
23524            None,
23525        )
23526        .expect_err("overflow past i64::MAX nanos must fail closed");
23527        assert!(matches!(err, DateRangeError::InvalidRange));
23528    }
23529
23530    #[test]
23531    fn date_range_rejects_backfilled_timestamp_underflow() {
23532        let err = date_range(
23533            None,
23534            Some("1677-09-21 00:12:44"),
23535            Some(3),
23536            Timedelta::NANOS_PER_SEC,
23537            None,
23538        )
23539        .expect_err("underflow before i64::MIN nanos must fail closed");
23540        assert!(matches!(err, DateRangeError::InvalidRange));
23541    }
23542
23543    #[test]
23544    fn date_range_rejects_out_of_bounds_timestamp_parse() {
23545        let err = date_range(
23546            Some("2263-01-01"),
23547            None,
23548            Some(1),
23549            Timedelta::NANOS_PER_DAY,
23550            None,
23551        )
23552        .expect_err("out-of-bounds timestamps must not be coerced to i64::MIN");
23553        assert!(matches!(err, DateRangeError::InvalidRange));
23554    }
23555
23556    #[test]
23557    fn date_offset_business_day_skips_weekend() {
23558        let nanos = apply_date_offset("2024-01-05", DateOffset::BusinessDay(1)).unwrap();
23559        assert_eq!(nanos, 1_704_672_000_000_000_000);
23560    }
23561
23562    #[test]
23563    fn date_offset_month_end_handles_leap_year() {
23564        let nanos = apply_date_offset("2024-02-10", DateOffset::MonthEnd(1)).unwrap();
23565        assert_eq!(nanos, 1_709_164_800_000_000_000);
23566    }
23567
23568    #[test]
23569    fn index_label_numbers_compare_by_value_l5sed() {
23570        use std::hash::{BuildHasher, RandomState};
23571        let hashes = RandomState::new();
23572        let int = IndexLabel::Int64;
23573        let float = |value: f64| IndexLabel::Float64(OrderedF64(value));
23574        // An int and the float it equals are one label, hashed alike.
23575        assert_eq!(int(2), float(2.0));
23576        assert_eq!(hashes.hash_one(int(2)), hashes.hash_one(float(2.0)));
23577        assert_eq!(int(0), float(-0.0));
23578        assert_eq!(hashes.hash_one(int(0)), hashes.hash_one(float(-0.0)));
23579        assert_eq!(int(2).cmp(&float(2.0)), std::cmp::Ordering::Equal);
23580        // Numbers order by value, beside each other; NaN after them.
23581        let mut labels = vec![
23582            IndexLabel::Utf8("a".into()),
23583            int(2),
23584            float(f64::NAN),
23585            float(1.5),
23586            int(1),
23587        ];
23588        labels.sort();
23589        assert_eq!(
23590            labels,
23591            vec![
23592                int(1),
23593                float(1.5),
23594                int(2),
23595                float(f64::NAN),
23596                IndexLabel::Utf8("a".into())
23597            ]
23598        );
23599        // Exact at the edges: 2^53 + 1 is no float, 2^63 no int.
23600        let big = (1_i64 << 53) + 1;
23601        assert_ne!(int(big), float(9_007_199_254_740_992.0));
23602        assert!(int(big) > float(9_007_199_254_740_992.0));
23603        assert_ne!(int(i64::MAX), float(9_223_372_036_854_775_808.0));
23604        assert!(int(i64::MAX) < float(9_223_372_036_854_775_808.0));
23605        assert_eq!(int(i64::MIN), float(-9_223_372_036_854_775_808.0));
23606        // Lookups over an int index find an integral float key.
23607        let index = Index::new(vec![int(1), int(2)]);
23608        assert_eq!(index.position(&float(2.0)), Some(1));
23609        assert_eq!(index.isin(&[float(1.0)]), vec![true, false]);
23610        let targets = Index::new(vec![float(2.0), float(3.0)]);
23611        assert_eq!(index.get_indexer(&targets), vec![Some(1), None]);
23612        assert!(index.equals(&Index::new(vec![float(1.0), float(2.0)])));
23613        // NEGATIVE: a fraction, text, a bool, a duration and a missing value
23614        // equal no int.
23615        assert_ne!(int(1), float(1.5));
23616        assert_eq!(index.position(&float(1.5)), None);
23617        assert_ne!(int(1), IndexLabel::Utf8("1".into()));
23618        assert_ne!(int(1), IndexLabel::Bool(true));
23619        assert_ne!(int(1), IndexLabel::Timedelta64(1));
23620        assert_ne!(int(1), IndexLabel::Null(fp_types::NullKind::NaN));
23621        assert_eq!(index.position(&IndexLabel::Utf8("2".into())), None);
23622    }
23623
23624    #[test]
23625    fn declared_dtype_holds_and_carries_as_pandas_i20vm() {
23626        use crate::DeclaredDtype;
23627        let ints = || Index::new(vec![IndexLabel::Int64(1), IndexLabel::Int64(2)]);
23628        // An object index of ints: its dtype object, its labels ints.
23629        let object = ints().with_declared_dtype(Some(DeclaredDtype::Object));
23630        assert_eq!(object.dtype(), "object");
23631        assert_eq!(object.labels()[0], IndexLabel::Int64(1));
23632        assert_eq!(object.take(&[1]).dtype(), "object");
23633        assert_eq!(object.slice(0, 1).dtype(), "object");
23634        // Equality ignores it, as pandas' equals.
23635        assert_eq!(object, ints());
23636        // No row keeps the source's dtype (dwyud).
23637        assert_eq!(ints().take(&[]).dtype(), "int64");
23638        assert_eq!(ints().slice(0, 0).dtype(), "int64");
23639        let floats = Index::new(vec![IndexLabel::Float64(OrderedF64(1.5))]);
23640        assert_eq!(floats.slice(0, 0).dtype(), "float64");
23641        // int32 while the labels are ints (pqjzo).
23642        let int32 = ints().with_declared_dtype(Some(DeclaredDtype::Int32));
23643        assert_eq!(int32.take(&[0]).dtype(), "int32");
23644        let halves = Index::new(vec![IndexLabel::Float64(OrderedF64(0.5))]);
23645        assert_eq!(halves.with_dtype_of(&int32).dtype(), "float64");
23646        // NEGATIVE: labels of their own read their own dtype.
23647        assert_eq!(ints().take(&[0]).dtype(), "int64");
23648        assert_eq!(object.with_declared_dtype(None).dtype(), "int64");
23649    }
23650
23651    #[test]
23652    fn empty_indexes_keep_the_dtype_they_are_built_as_ce86r() {
23653        // No labels show a type: an empty index cast to (or built as) a
23654        // dtype reports it, as pandas (they were object).
23655        let empty = crate::Index::new(Vec::new());
23656        for (dtype, expected) in [
23657            ("int64", "int64"),
23658            ("float64", "float64"),
23659            ("bool", "bool"),
23660            ("str", "object"),
23661            ("datetime64[ns]", "datetime64[ns]"),
23662            ("timedelta64[ns]", "timedelta64[ns]"),
23663        ] {
23664            assert_eq!(empty.astype(dtype).unwrap().dtype(), expected, "{dtype}");
23665        }
23666        assert_eq!(
23667            crate::Index::from_datetime64(Vec::new()).dtype(),
23668            "datetime64[ns]"
23669        );
23670        assert_eq!(
23671            crate::Index::from_timedelta64(Vec::new()).dtype(),
23672            "timedelta64[ns]"
23673        );
23674        // NEGATIVE: labels still decide a non-empty index's dtype, and an
23675        // empty one with no dtype asked for is object.
23676        let ints = crate::Index::new(vec![IndexLabel::Int64(1), IndexLabel::Int64(2)]);
23677        assert_eq!(ints.astype("float64").unwrap().dtype(), "float64");
23678        assert_eq!(empty.dtype(), "object");
23679        assert_eq!(
23680            crate::Index::from_datetime64(vec![5]).declared_dtype(),
23681            None
23682        );
23683    }
23684
23685    #[test]
23686    fn an_empty_period_range_keeps_its_freq_ce86r() {
23687        let start = Period::new(648, PeriodFreq::Monthly);
23688        let none = crate::PeriodIndex::from_range(start, 0);
23689        assert_eq!(none.freq(), Some(PeriodFreq::Monthly));
23690        assert_eq!(none.unique().freq(), Some(PeriodFreq::Monthly));
23691        // Periods' own freq still decides, and equality follows the freq:
23692        // the same periods from either constructor are equal, empty
23693        // indexes of two freqs are not.
23694        let three = crate::PeriodIndex::from_range(start, 3);
23695        assert_eq!(three, crate::PeriodIndex::new(three.values().to_vec()));
23696        assert_ne!(
23697            none,
23698            crate::PeriodIndex::from_range(Period::new(19_000, PeriodFreq::Daily), 0)
23699        );
23700        assert_eq!(crate::PeriodIndex::new(Vec::new()).freq(), None);
23701    }
23702
23703    #[test]
23704    fn take_freq_keeps_it_for_an_empty_take_0l1nu() {
23705        // pandas reads no positions as an empty slice (s.iloc[[]] keeps 'D'),
23706        // one or a steady step as a slice scaled by it, anything else as none.
23707        let daily = || Some("D".to_owned());
23708        assert_eq!(crate::take_freq(daily(), &[]).as_deref(), Some("D"));
23709        assert_eq!(crate::take_freq(daily(), &[3]).as_deref(), Some("D"));
23710        assert_eq!(
23711            crate::take_freq(daily(), &[4, 2, 0]).as_deref(),
23712            Some("-2D")
23713        );
23714        assert_eq!(crate::take_freq(daily(), &[0, 1, 3]), None);
23715        assert_eq!(crate::take_freq(None, &[]), None);
23716    }
23717
23718    #[test]
23719    fn infer_freq_detects_fixed_and_calendar_offsets() {
23720        assert_eq!(
23721            infer_freq_from_timestamps(&["2024-01-01", "2024-01-03", "2024-01-05"]).unwrap(),
23722            Some("2D".to_owned())
23723        );
23724        assert_eq!(
23725            infer_freq_from_timestamps(&[
23726                "2024-01-01",
23727                "2024-01-02",
23728                "2024-01-03",
23729                "2024-01-04",
23730                "2024-01-05",
23731                "2024-01-08",
23732                "2024-01-09",
23733            ])
23734            .unwrap(),
23735            Some("B".to_owned())
23736        );
23737        assert_eq!(
23738            infer_freq_from_timestamps(&["2024-01-31", "2024-02-29", "2024-03-31"]).unwrap(),
23739            Some("ME".to_owned())
23740        );
23741    }
23742
23743    #[test]
23744    fn infer_freq_returns_none_for_irregular_or_duplicate_values() {
23745        assert_eq!(
23746            infer_freq_from_timestamps(&["2024-01-01", "2024-01-02", "2024-01-04"]).unwrap(),
23747            None
23748        );
23749        assert_eq!(
23750            infer_freq_from_timestamps(&["2024-01-01", "2024-01-02", "2024-01-02"]).unwrap(),
23751            None
23752        );
23753    }
23754
23755    #[test]
23756    fn infer_freq_uses_datetime_affine_witness_without_materializing_8xtj5() {
23757        let cases = [
23758            (0, 1, 0),
23759            (0, 0, 1),
23760            (0, Timedelta::NANOS_PER_SEC, 2),
23761            (0, Timedelta::NANOS_PER_DAY, 3),
23762            (17, 2 * Timedelta::NANOS_PER_SEC, 100),
23763            (0, -Timedelta::NANOS_PER_SEC, 3),
23764            (i64::MIN, 1, 1),
23765            (i64::MIN, 1, 3),
23766        ];
23767
23768        for (start, step, len) in cases {
23769            let affine = Index::from_datetime64_affine_range(start, step, len)
23770                .expect("valid affine test range");
23771            let eager_values = (0..len)
23772                .map(|offset| start + i64::try_from(offset).expect("small test offset") * step)
23773                .collect();
23774            let eager = Index::from_datetime64(eager_values);
23775            let affine_result = infer_freq(&affine);
23776            let eager_result = infer_freq(&eager);
23777            assert_eq!(
23778                format!("{affine_result:?}"),
23779                format!("{eager_result:?}"),
23780                "affine inference must preserve eager semantics for start={start}, step={step}, len={len}",
23781            );
23782            assert!(
23783                affine.labels.materialized.get().is_none(),
23784                "frequency inference must not materialize affine labels",
23785            );
23786        }
23787    }
23788
23789    #[test]
23790    fn union_alignment_preserves_left_then_right_unseen_order() {
23791        let left = Index::new(vec![1_i64.into(), 2_i64.into(), 4_i64.into()]);
23792        let right = Index::new(vec![2_i64.into(), 3_i64.into(), 4_i64.into()]);
23793
23794        let plan = align_union(&left, &right);
23795        assert_eq!(
23796            plan.union_index.labels(),
23797            &[
23798                IndexLabel::Int64(1),
23799                IndexLabel::Int64(2),
23800                IndexLabel::Int64(4),
23801                IndexLabel::Int64(3),
23802            ]
23803        );
23804        assert_eq!(plan.left_positions, vec![Some(0), Some(1), Some(2), None]);
23805        assert_eq!(plan.right_positions, vec![None, Some(0), Some(2), Some(1)]);
23806        validate_alignment_plan(&plan).expect("plan must be valid");
23807    }
23808
23809    #[test]
23810    fn duplicate_detection_matches_index_surface() {
23811        let index = Index::new(vec!["a".into(), "a".into(), "b".into()]);
23812        assert!(index.has_duplicates());
23813    }
23814
23815    #[test]
23816    fn has_duplicates_sort_fast_path_matches_hashmap_idxdup() {
23817        // The strict-ascending fast path in has_duplicates must agree with the
23818        // FxHashMap detect_duplicates for every shape: sorted-unique (fast path
23819        // returns false), sorted-with-dups (not strictly ascending -> Unsorted
23820        // -> hashmap), unsorted-unique, unsorted-dups, descending, single,
23821        // empty, and Utf8.
23822        let cases: Vec<Vec<IndexLabel>> = vec![
23823            vec![],
23824            vec![5_i64.into()],
23825            vec![1_i64.into(), 2_i64.into(), 3_i64.into()], // sorted unique
23826            vec![1_i64.into(), 5_i64.into(), 9_i64.into()], // sorted unique, gapped
23827            vec![1_i64.into(), 2_i64.into(), 2_i64.into()], // sorted with dup
23828            vec![3_i64.into(), 1_i64.into(), 2_i64.into()], // unsorted unique
23829            vec![3_i64.into(), 1_i64.into(), 3_i64.into()], // unsorted dup
23830            vec![9_i64.into(), 5_i64.into(), 1_i64.into()], // descending unique
23831            vec!["a".into(), "b".into(), "c".into()],       // sorted utf8 unique
23832            vec!["a".into(), "a".into(), "b".into()],       // utf8 dup
23833            vec!["c".into(), "a".into(), "b".into()],       // unsorted utf8 unique
23834        ];
23835        for labels in cases {
23836            let expected = super::detect_duplicates(&labels);
23837            let got = Index::new(labels.clone()).has_duplicates();
23838            assert_eq!(got, expected, "mismatch for {labels:?}");
23839        }
23840    }
23841
23842    #[test]
23843    fn dedup_family_sort_fast_path_matches_reference_idxdup() {
23844        // unique / duplicated / drop_duplicates strict-ascending fast paths must
23845        // equal an independent first-seen reference for every shape.
23846        let cases: Vec<Vec<IndexLabel>> = vec![
23847            vec![],
23848            vec![7_i64.into()],
23849            vec![1_i64.into(), 2_i64.into(), 3_i64.into()], // sorted unique
23850            vec![1_i64.into(), 2_i64.into(), 2_i64.into(), 4_i64.into()], // sorted dup
23851            vec![3_i64.into(), 1_i64.into(), 3_i64.into(), 2_i64.into()], // unsorted dup
23852            vec![9_i64.into(), 5_i64.into(), 1_i64.into()], // descending
23853            vec!["a".into(), "b".into(), "c".into()],       // sorted utf8
23854            vec!["b".into(), "a".into(), "b".into()],       // unsorted utf8 dup
23855        ];
23856        for labels in cases {
23857            let idx = Index::new(labels.clone());
23858
23859            let mut seen = std::collections::HashSet::new();
23860            let ref_unique: Vec<IndexLabel> = labels
23861                .iter()
23862                .filter(|l| seen.insert((*l).clone()))
23863                .cloned()
23864                .collect();
23865            assert_eq!(
23866                idx.unique().labels(),
23867                ref_unique.as_slice(),
23868                "unique {labels:?}"
23869            );
23870
23871            let mut seen_f = std::collections::HashSet::new();
23872            let ref_dup_first: Vec<bool> =
23873                labels.iter().map(|l| !seen_f.insert(l.clone())).collect();
23874            assert_eq!(
23875                idx.duplicated(DuplicateKeep::First),
23876                ref_dup_first,
23877                "duplicated(First) {labels:?}"
23878            );
23879
23880            assert_eq!(
23881                idx.drop_duplicates().labels(),
23882                ref_unique.as_slice(),
23883                "drop_duplicates {labels:?}"
23884            );
23885        }
23886    }
23887
23888    #[test]
23889    fn typed_int64_unique_preserves_typed_backing_codb() {
23890        let index = Index::from_i64_values(vec![3, 1, 3, 2, 1]).set_name("row");
23891        assert!(index.labels.materialized.get().is_none());
23892
23893        let unique = index.unique();
23894
23895        assert_eq!(unique.name().map(|n| n.as_str()), Some("row"));
23896        assert_eq!(unique.labels.int64_view().unwrap().as_slice(), &[3, 1, 2]);
23897        assert!(index.labels.materialized.get().is_none());
23898        assert!(
23899            unique.labels.materialized.get().is_none(),
23900            "typed Int64 unique should preserve typed output backing"
23901        );
23902
23903        let materialized = Index::new(vec![
23904            IndexLabel::Int64(3),
23905            IndexLabel::Int64(1),
23906            IndexLabel::Int64(3),
23907            IndexLabel::Int64(2),
23908            IndexLabel::Int64(1),
23909        ])
23910        .set_name("row");
23911        assert_eq!(unique.labels(), materialized.unique().labels());
23912    }
23913
23914    #[test]
23915    fn typed_int64_drop_duplicates_preserves_typed_backing_codb() {
23916        let index = Index::from_i64_values(vec![9, 9, 4, 9, 4, 2]).set_name("axis");
23917        assert!(index.labels.materialized.get().is_none());
23918
23919        let dropped = index.drop_duplicates();
23920
23921        assert_eq!(dropped.name().map(|n| n.as_str()), Some("axis"));
23922        assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[9, 4, 2]);
23923        assert!(index.labels.materialized.get().is_none());
23924        assert!(
23925            dropped.labels.materialized.get().is_none(),
23926            "drop_duplicates delegates to unique and should keep typed backing"
23927        );
23928    }
23929
23930    #[test]
23931    fn typed_int64_drop_duplicates_keep_modes_preserve_typed_backing_codb() {
23932        let index = Index::from_i64_values(vec![9, 9, 4, 9, 4, 2]).set_name("axis");
23933        assert!(index.labels.materialized.get().is_none());
23934
23935        let keep_last = index.drop_duplicates_keep(DuplicateKeep::Last);
23936        let keep_none = index.drop_duplicates_keep(DuplicateKeep::None);
23937
23938        assert_eq!(keep_last.name().map(|n| n.as_str()), Some("axis"));
23939        assert_eq!(
23940            keep_last.labels.int64_view().unwrap().as_slice(),
23941            &[9, 4, 2]
23942        );
23943        assert_eq!(keep_none.name().map(|n| n.as_str()), Some("axis"));
23944        assert_eq!(keep_none.labels.int64_view().unwrap().as_slice(), &[2]);
23945        assert!(
23946            index.labels.materialized.get().is_none(),
23947            "keep modes should not materialize the source Int64 labels"
23948        );
23949        assert!(
23950            keep_last.labels.materialized.get().is_none(),
23951            "keep=last should keep typed output backing"
23952        );
23953        assert!(
23954            keep_none.labels.materialized.get().is_none(),
23955            "keep=false should keep typed output backing"
23956        );
23957
23958        let materialized = Index::new(vec![
23959            IndexLabel::Int64(9),
23960            IndexLabel::Int64(9),
23961            IndexLabel::Int64(4),
23962            IndexLabel::Int64(9),
23963            IndexLabel::Int64(4),
23964            IndexLabel::Int64(2),
23965        ])
23966        .set_name("axis");
23967        assert_eq!(
23968            keep_last.labels(),
23969            materialized
23970                .drop_duplicates_keep(DuplicateKeep::Last)
23971                .labels()
23972        );
23973        assert_eq!(
23974            keep_none.labels(),
23975            materialized
23976                .drop_duplicates_keep(DuplicateKeep::None)
23977                .labels()
23978        );
23979    }
23980
23981    #[test]
23982    fn sorted_merge_set_ops_match_reference_idxdup() {
23983        // intersection / difference must equal the self-ordered, deduped
23984        // FxHashMap reference whether the two-pointer fast path fires (both
23985        // strictly ascending) or the hash path runs (any side unsorted).
23986        let s = |v: &[i64]| v.iter().map(|x| IndexLabel::Int64(*x)).collect::<Vec<_>>();
23987        let pairs: Vec<(Vec<IndexLabel>, Vec<IndexLabel>)> = vec![
23988            (s(&[1, 2, 3, 5]), s(&[2, 3, 4])), // both sorted, overlap
23989            (s(&[1, 2, 3]), s(&[4, 5, 6])),    // both sorted, disjoint
23990            (s(&[1, 2, 3]), s(&[1, 2, 3])),    // identical
23991            (s(&[1, 2, 3]), vec![]),           // empty other
23992            (vec![], s(&[1, 2, 3])),           // empty self
23993            (s(&[3, 1, 2]), s(&[2, 3])),       // self unsorted -> hash path
23994            (s(&[1, 2, 3]), s(&[3, 1])),       // other unsorted -> hash path
23995            (
23996                vec!["a".into(), "c".into(), "e".into()],
23997                vec!["b".into(), "c".into()],
23998            ), // utf8 sorted
23999            (
24000                vec![1_i64.into(), 2_i64.into()],
24001                vec!["a".into(), "b".into()],
24002            ), // mixed-type sorted, disjoint by Ord variant
24003        ];
24004        for (a, b) in pairs {
24005            let ia = Index::new(a.clone());
24006            let ib = Index::new(b.clone());
24007            let bset: std::collections::HashSet<IndexLabel> = b.iter().cloned().collect();
24008
24009            let mut seen = std::collections::HashSet::new();
24010            let ref_inter: Vec<IndexLabel> = a
24011                .iter()
24012                .filter(|l| bset.contains(*l) && seen.insert((*l).clone()))
24013                .cloned()
24014                .collect();
24015            assert_eq!(
24016                ia.intersection(&ib).labels(),
24017                ref_inter.as_slice(),
24018                "intersection {a:?} ∩ {b:?}"
24019            );
24020
24021            let mut seen_d = std::collections::HashSet::new();
24022            let ref_diff: Vec<IndexLabel> = a
24023                .iter()
24024                .filter(|l| !bset.contains(*l) && seen_d.insert((*l).clone()))
24025                .cloned()
24026                .collect();
24027            assert_eq!(
24028                ia.difference(&ib).labels(),
24029                ref_diff.as_slice(),
24030                "difference {a:?} \\ {b:?}"
24031            );
24032        }
24033    }
24034
24035    #[test]
24036    fn sorted_int64_set_ops_keep_typed_backing_without_materializing_v7m2q() {
24037        let left = Index::from_i64_values(vec![1, 3, 5, 9]).set_name("axis");
24038        let right = Index::from_i64_values(vec![0, 3, 4, 9, 10]).set_name("axis");
24039        assert!(left.labels.materialized.get().is_none());
24040        assert!(right.labels.materialized.get().is_none());
24041
24042        let intersection = left.intersection(&right);
24043        let difference = left.difference(&right);
24044        assert_eq!(intersection.name().map(|n| n.as_str()), Some("axis"));
24045        assert_eq!(difference.name().map(|n| n.as_str()), Some("axis"));
24046        assert_eq!(
24047            intersection.labels.int64_view().unwrap().as_slice(),
24048            &[3, 9]
24049        );
24050        assert_eq!(difference.labels.int64_view().unwrap().as_slice(), &[1, 5]);
24051        assert!(
24052            left.labels.materialized.get().is_none(),
24053            "sorted Int64 set ops should not materialize the left input"
24054        );
24055        assert!(
24056            right.labels.materialized.get().is_none(),
24057            "sorted Int64 set ops should not materialize the right input"
24058        );
24059        assert!(
24060            intersection.labels.materialized.get().is_none(),
24061            "intersection should keep typed Int64 output backing"
24062        );
24063        assert!(
24064            difference.labels.materialized.get().is_none(),
24065            "difference should keep typed Int64 output backing"
24066        );
24067    }
24068
24069    #[test]
24070    fn datetime_timedelta_get_loc_binary_search_matches_linear_idxdup() {
24071        // get_loc now binary-searches a monotonic typed index; the result must
24072        // equal a linear first-match reference for both sorted (binary path) and
24073        // unsorted (linear path) value vectors.
24074        for nanos in [
24075            vec![10_i64, 20, 30, 40, 50], // sorted -> AscendingDatetime64/Timedelta64
24076            vec![30_i64, 10, 50, 20, 40], // unsorted -> linear fallback
24077        ] {
24078            let dt = DatetimeIndex::new(nanos.clone());
24079            let td = TimedeltaIndex::new(nanos.clone());
24080            for q in [10_i64, 20, 30, 40, 50, 0, 99] {
24081                let expected = nanos.iter().position(|n| *n == q);
24082                assert_eq!(
24083                    dt.get_loc(q).ok(),
24084                    expected,
24085                    "datetime nanos={nanos:?} q={q}"
24086                );
24087                assert_eq!(
24088                    td.get_loc(q).ok(),
24089                    expected,
24090                    "timedelta nanos={nanos:?} q={q}"
24091                );
24092            }
24093        }
24094    }
24095
24096    #[test]
24097    fn get_indexer_sorted_fast_path_matches_reference_idxdup() {
24098        // get_indexer's sorted merge / binary-search fast paths and the
24099        // FxHashMap fallback must all equal a first-occurrence reference.
24100        let s = |v: &[i64]| v.iter().map(|x| IndexLabel::Int64(*x)).collect::<Vec<_>>();
24101        let cases: Vec<(Vec<IndexLabel>, Vec<IndexLabel>)> = vec![
24102            (s(&[1, 2, 3, 4, 5]), s(&[2, 4, 6])),    // both sorted
24103            (s(&[1, 2, 3, 4, 5]), s(&[5, 1, 3, 9])), // self sorted, target unsorted
24104            (s(&[3, 1, 5, 2]), s(&[1, 2, 3])),       // self unsorted -> hash path
24105            (s(&[1, 2, 3]), vec![]),                 // empty target
24106            (vec![], s(&[1, 2])),                    // empty self
24107            (
24108                vec!["a".into(), "c".into(), "e".into()],
24109                vec!["c".into(), "z".into(), "a".into()],
24110            ), // utf8, target unsorted
24111            (s(&[1, 2, 3]), vec!["a".into()]),       // mixed type sorted, no match
24112        ];
24113        for (a, b) in cases {
24114            let ia = Index::new(a.clone());
24115            let ib = Index::new(b.clone());
24116            let ref_out: Vec<Option<usize>> =
24117                b.iter().map(|t| a.iter().position(|x| x == t)).collect();
24118            assert_eq!(ia.get_indexer(&ib), ref_out, "get_indexer {a:?} -> {b:?}");
24119        }
24120    }
24121
24122    /// br-frankenpandas: `RangeValuesIter` carries an i64 fast arm and an i128
24123    /// fallback, plus overridden `fold`/`rfold` that must agree with the
24124    /// element-at-a-time `next`/`next_back` they bypass. Every combination is
24125    /// checked against an independent i128 reference, including a range whose
24126    /// endpoint does NOT fit in i64 so the fallback is genuinely exercised —
24127    /// otherwise this test would pass while only ever running one arm.
24128    #[test]
24129    fn range_values_iter_arms_and_folds_all_agree() {
24130        let cases: [(i64, i64, i64); 9] = [
24131            (0, 20, 2),
24132            (1, 7, 3),
24133            (5, 5, 1),
24134            (10, 0, -2),
24135            (-9, 9, 4),
24136            (0, 1, 1),
24137            (i64::MIN, i64::MIN + 10, 1),
24138            (i64::MAX - 10, i64::MAX, 1),
24139            (0, i64::MAX, i64::MAX / 2),
24140        ];
24141        let mut saw_fast = false;
24142        for (start, stop, step) in cases {
24143            let range = RangeIndex::new(start, stop, step).expect("valid range");
24144            let values = range.values();
24145            let len = values.len();
24146
24147            // The i128 fallback cannot be reached through a normally-sized
24148            // RangeIndex: the last value is always strictly inside `stop`, so
24149            // it fits in i64 by construction, and the only ranges that select
24150            // the fallback are longer than i64::MAX and cannot be iterated in
24151            // a test. So drive the SAME parameters through a forced-slow
24152            // iterator and require the two arms to agree element for element.
24153            // Without this the fallback would be dead code under test.
24154            let slow = crate::RangeValuesIter {
24155                start,
24156                step,
24157                head: 0,
24158                tail: len,
24159                i64_safe: false,
24160            };
24161            assert!(!slow.i64_safe);
24162            assert_eq!(
24163                slow.collect::<Vec<_>>(),
24164                values.iter().collect::<Vec<_>>(),
24165                "i128 arm disagrees with i64 arm {start},{stop},{step}"
24166            );
24167            assert_eq!(
24168                slow.fold(0_i128, |acc, v| acc + i128::from(v)),
24169                values.iter().fold(0_i128, |acc, v| acc + i128::from(v)),
24170                "i128 fold disagrees with i64 fold {start},{stop},{step}"
24171            );
24172            assert_eq!(
24173                slow.rfold(0_i128, |acc, v| acc + i128::from(v)),
24174                values.iter().rfold(0_i128, |acc, v| acc + i128::from(v)),
24175                "i128 rfold disagrees with i64 rfold {start},{stop},{step}"
24176            );
24177
24178            let reference: Vec<i64> = (0..len)
24179                .map(|position| {
24180                    let v = i128::from(start) + (position as i128) * i128::from(step);
24181                    i64::try_from(v).expect("reference fits")
24182                })
24183                .collect();
24184
24185            assert!(
24186                values.iter().i64_safe,
24187                "a normally-sized range must select the i64 arm {start},{stop},{step}"
24188            );
24189            saw_fast = true;
24190
24191            assert_eq!(
24192                values.iter().collect::<Vec<_>>(),
24193                reference,
24194                "next {start},{stop},{step}"
24195            );
24196            assert_eq!(values.to_vec(), reference, "to_vec {start},{stop},{step}");
24197
24198            let mut reversed: Vec<i64> = values.iter().rev().collect();
24199            reversed.reverse();
24200            assert_eq!(reversed, reference, "next_back {start},{stop},{step}");
24201
24202            let want: i128 = reference.iter().map(|&v| i128::from(v)).sum();
24203            let folded = values.iter().fold(0_i128, |acc, v| acc + i128::from(v));
24204            let rfolded = values.iter().rfold(0_i128, |acc, v| acc + i128::from(v));
24205            assert_eq!(folded, want, "fold {start},{stop},{step}");
24206            assert_eq!(rfolded, want, "rfold {start},{stop},{step}");
24207
24208            assert_eq!(
24209                values.iter().len(),
24210                len,
24211                "ExactSizeIterator {start},{stop},{step}"
24212            );
24213
24214            // A partially consumed iterator must fold the REMAINDER, which is
24215            // where a fast arm that recomputes from `start` would silently
24216            // disagree with `next`.
24217            if len >= 3 {
24218                let mut partial = values.iter();
24219                partial.next();
24220                partial.next_back();
24221                assert_eq!(
24222                    partial.fold(0_i128, |acc, v| acc + i128::from(v)),
24223                    reference[1..len - 1]
24224                        .iter()
24225                        .map(|&v| i128::from(v))
24226                        .sum::<i128>(),
24227                    "partial fold {start},{stop},{step}"
24228                );
24229            }
24230        }
24231        assert!(saw_fast, "no case exercised the i64 fast arm");
24232
24233        // And the selector itself must still be able to say NO: a range longer
24234        // than i64::MAX positions cannot do i64 position arithmetic. Checked
24235        // without iterating it.
24236        let huge = RangeIndex::new(i64::MIN, i64::MAX, 1).expect("valid range");
24237        assert!(
24238            !huge.values().iter().i64_safe,
24239            "a range longer than i64::MAX must fall back to the i128 arm"
24240        );
24241    }
24242
24243    #[test]
24244    fn known_unique_constructor_seeds_duplicate_cache() {
24245        let index = Index::new_known_unique(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
24246        assert_eq!(index.duplicate_cache.get(), Some(&false));
24247        assert!(!index.has_duplicates());
24248    }
24249
24250    #[test]
24251    fn index_equality_ignores_duplicate_cache_state() {
24252        let index_with_cache = Index::new(vec!["a".into(), "a".into(), "b".into()]);
24253        assert!(index_with_cache.has_duplicates());
24254
24255        let fresh_index = Index::new(vec!["a".into(), "a".into(), "b".into()]);
24256        assert_eq!(index_with_cache, fresh_index);
24257    }
24258
24259    #[test]
24260    fn index_label_identity_cache_preserves_equality_contracts() {
24261        let base = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
24262        let clone = base.clone();
24263        assert_eq!(base.label_identity, clone.label_identity);
24264        assert_eq!(base, clone);
24265
24266        let renamed = clone.rename_index(Some("rows"));
24267        assert_eq!(base.label_identity, renamed.label_identity);
24268        assert!(base.equals(&renamed));
24269        assert!(!base.identical(&renamed));
24270
24271        let independent_equal = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
24272        assert_ne!(base.label_identity, independent_equal.label_identity);
24273        assert_eq!(base, independent_equal);
24274
24275        let different = Index::new(vec![1_i64.into(), 2_i64.into(), 4_i64.into()]);
24276        assert_ne!(base, different);
24277        assert!(!base.equals(&different));
24278    }
24279
24280    #[test]
24281    fn label_kinds_equal_a_pass_over_the_labels_nmna9() {
24282        // label_kinds - kept by label identity, answered without a scan for
24283        // typed ints and a datetime range - equals a fold over the labels,
24284        // and the typed index constructors check through it
24285        // (br-frankenpandas-nmna9).
24286        let pass = |index: &Index| {
24287            index
24288                .labels()
24289                .iter()
24290                .fold(LabelKinds::default(), |kinds, label| {
24291                    kinds.union(LabelKinds::of(label))
24292                })
24293        };
24294        let null = |kind| IndexLabel::Null(kind);
24295        let cases = [
24296            Index::new(vec![1_i64.into(), 2_i64.into()]),
24297            Index::from_i64_values(vec![5, 3, 9]),
24298            Index::from_range(0, 10, 2),
24299            Index::new(vec![
24300                "a".into(),
24301                null(fp_types::NullKind::NaN),
24302                IndexLabel::Bool(true),
24303            ]),
24304            Index::from_datetime64(vec![0, 10, 20]),
24305            Index::new(vec![
24306                IndexLabel::Datetime64(3),
24307                null(fp_types::NullKind::NaT),
24308            ]),
24309            Index::new(vec![
24310                IndexLabel::Timedelta64(7),
24311                null(fp_types::NullKind::Null),
24312            ]),
24313            Index::new(Vec::new()),
24314        ];
24315        for index in cases {
24316            assert_eq!(index.label_kinds(), pass(&index), "{index:?}");
24317            assert_eq!(index.clone().label_kinds(), pass(&index), "{index:?}");
24318        }
24319        assert!(DatetimeIndex::from_index(Index::from_datetime64(vec![0, 10, 20])).is_ok());
24320        assert!(TimedeltaIndex::from_index(Index::new(vec![IndexLabel::Timedelta64(1)])).is_ok());
24321        // NEGATIVE: another kind beside them refuses, and labels made from
24322        // ones already seen are a new identity with their own kinds.
24323        assert!(
24324            DatetimeIndex::from_index(Index::new(vec![IndexLabel::Datetime64(1), 2_i64.into()]))
24325                .is_err()
24326        );
24327        assert!(
24328            TimedeltaIndex::from_index(Index::new(vec![
24329                IndexLabel::Timedelta64(1),
24330                null(fp_types::NullKind::NaT),
24331            ]))
24332            .is_err()
24333        );
24334        let ints = Index::new(vec![1_i64.into(), 2_i64.into()]);
24335        assert_eq!(ints.label_kinds(), LabelKinds::INT64);
24336        let mut labels = ints.labels().to_vec();
24337        labels.push(IndexLabel::Bool(true));
24338        assert_eq!(
24339            Index::new(labels).label_kinds(),
24340            LabelKinds::INT64.union(LabelKinds::BOOL)
24341        );
24342    }
24343
24344    #[test]
24345    fn row_multiindex_levels_ride_with_their_flat_labels_4qg5w9() {
24346        let utf8 = |s: &str| IndexLabel::Utf8(s.to_owned());
24347        let levels = MultiIndex::from_arrays(vec![
24348            vec![utf8("y"), utf8("x"), utf8("x")],
24349            vec![1_i64.into(), 1_i64.into(), 2_i64.into()],
24350        ])
24351        .expect("levels")
24352        .set_names(vec![Some("k".into()), Some("j".into())]);
24353        let flat = Index::new(vec![utf8("y|1"), utf8("x|1"), utf8("x|2")]);
24354        let index = flat
24355            .clone()
24356            .with_row_multiindex(levels.clone())
24357            .expect("heights match");
24358        assert_eq!(index.row_multiindex(), Some(&levels));
24359        assert_eq!(index, flat, "the levels do not change label equality");
24360        assert_eq!(index.clone().row_multiindex(), Some(&levels));
24361
24362        // take and slice carry the levels at the same positions.
24363        let taken = index.take(&[2, 0]);
24364        assert_eq!(taken.labels(), &[utf8("x|2"), utf8("y|1")]);
24365        let taken_levels = taken.row_multiindex().expect("take carries the levels");
24366        assert_eq!(
24367            taken_levels.get_tuple(0),
24368            Some(vec![&utf8("x"), &2_i64.into()])
24369        );
24370        assert_eq!(
24371            taken_levels.get_tuple(1),
24372            Some(vec![&utf8("y"), &1_i64.into()])
24373        );
24374        assert_eq!(taken_levels.names(), levels.names());
24375        let sliced = index.slice(1, 2);
24376        assert_eq!(sliced.labels(), &[utf8("x|1"), utf8("x|2")]);
24377        let sliced_levels = sliced.row_multiindex().expect("slice carries the levels");
24378        assert_eq!(sliced_levels.len(), 2);
24379        assert_eq!(
24380            sliced_levels.get_tuple(0),
24381            Some(vec![&utf8("x"), &1_i64.into()])
24382        );
24383
24384        // NEGATIVE: labels built any other way are flat, never mislabelled.
24385        let sorted = index.sort_values();
24386        assert_eq!(sorted.labels(), &[utf8("x|1"), utf8("x|2"), utf8("y|1")]);
24387        assert!(sorted.row_multiindex().is_none());
24388        assert!(index.to_flat_index().row_multiindex().is_none());
24389        assert!(matches!(
24390            flat.with_row_multiindex(levels.take(&[0]).expect("take")),
24391            Err(IndexError::LengthMismatch {
24392                expected: 3,
24393                actual: 1,
24394                ..
24395            })
24396        ));
24397    }
24398
24399    #[test]
24400    fn semantic_fingerprint_cache_reuses_label_result() {
24401        let index = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
24402        let calls = std::cell::Cell::new(0);
24403
24404        let first = index.semantic_labels_fingerprint_with(|labels| {
24405            calls.set(calls.get() + 1);
24406            format!("labels:{}", labels.len())
24407        });
24408        let second = index.semantic_labels_fingerprint_with(|_| {
24409            calls.set(calls.get() + 1);
24410            "changed".to_owned()
24411        });
24412
24413        assert_eq!(first, "labels:3");
24414        assert_eq!(second, "labels:3");
24415        assert_eq!(calls.get(), 1);
24416    }
24417
24418    #[test]
24419    fn int64_unit_range_index_preserves_materialized_surface() {
24420        let index = Index::new_known_unique_int64_unit_range(-2, 4).rename_index(Some("idx"));
24421        let reference = Index::new(vec![
24422            IndexLabel::Int64(-2),
24423            IndexLabel::Int64(-1),
24424            IndexLabel::Int64(0),
24425            IndexLabel::Int64(1),
24426        ])
24427        .rename_index(Some("idx"));
24428
24429        assert_eq!(index.len(), 4);
24430        assert!(!index.has_duplicates());
24431        assert!(index.is_sorted());
24432        assert_eq!(index.position(&IndexLabel::Int64(0)), Some(2));
24433        assert_eq!(index.position(&IndexLabel::Int64(2)), None);
24434        assert_eq!(index.labels(), reference.labels());
24435        assert_eq!(index, reference);
24436    }
24437
24438    #[test]
24439    fn int64_affine_range_index_preserves_materialized_surface() {
24440        let index = Index::new_known_unique_int64_affine_range(3, 2, 4)
24441            .unwrap()
24442            .rename_index(Some("idx"));
24443        let reference = Index::new(vec![
24444            IndexLabel::Int64(3),
24445            IndexLabel::Int64(5),
24446            IndexLabel::Int64(7),
24447            IndexLabel::Int64(9),
24448        ])
24449        .rename_index(Some("idx"));
24450
24451        assert_eq!(index.len(), 4);
24452        assert!(!index.has_duplicates());
24453        assert!(index.is_sorted());
24454        assert_eq!(index.position(&IndexLabel::Int64(7)), Some(2));
24455        assert_eq!(index.position(&IndexLabel::Int64(8)), None);
24456        assert_eq!(index.labels(), reference.labels());
24457        let values = index.int64_label_values().unwrap();
24458        assert_eq!(values.as_slice(), &[3, 5, 7, 9]);
24459        assert_eq!(index, reference);
24460
24461        let singleton = Index::new_known_unique_int64_affine_range(i64::MAX, 1, 1).unwrap();
24462        assert_eq!(singleton.labels(), &[IndexLabel::Int64(i64::MAX)]);
24463    }
24464
24465    #[test]
24466    fn int64_strided_index_preserves_duplicate_and_unsorted_semantics() {
24467        let duplicate =
24468            Index::from_i64_strided_values(Arc::new(vec![10, 99, 10, 99, 20]), 0, 2, 3).unwrap();
24469        assert_eq!(
24470            duplicate.labels(),
24471            &[
24472                IndexLabel::Int64(10),
24473                IndexLabel::Int64(10),
24474                IndexLabel::Int64(20),
24475            ]
24476        );
24477        assert!(duplicate.has_duplicates());
24478        assert!(!duplicate.is_sorted());
24479        assert_eq!(duplicate.position(&IndexLabel::Int64(20)), Some(2));
24480
24481        let unsorted =
24482            Index::from_i64_strided_values(Arc::new(vec![30, 99, 10, 99, 20]), 0, 2, 3).unwrap();
24483        assert_eq!(int64_labels(&unsorted), vec![30, 10, 20]);
24484        assert!(!unsorted.has_duplicates());
24485        assert!(!unsorted.is_sorted());
24486        assert_eq!(unsorted.position(&IndexLabel::Int64(10)), Some(1));
24487    }
24488
24489    #[test]
24490    fn index_variant_wrappers_expose_public_type_surface() {
24491        let range = RangeIndex::new(1, 7, 2).unwrap().set_name("row");
24492        assert_eq!(range.values().to_vec(), vec![1, 3, 5]);
24493        assert_eq!(range.to_list(), range.values().to_vec());
24494        assert_eq!(range.tolist(), range.values().to_vec());
24495        assert_eq!(range.to_numpy(), range.values().to_vec());
24496        assert_eq!(range.array(), range.values().to_vec());
24497        assert_eq!(range.len(), 3);
24498        assert_eq!(range.size(), 3);
24499        assert_eq!(range.shape(), (3,));
24500        assert!(!range.empty());
24501        assert_eq!(range.dtype(), "int64");
24502        assert_eq!(range.dtypes(), vec!["int64"]);
24503        assert_eq!(range.names(), vec![Some("row".to_owned())]);
24504        assert_eq!(range.copy(), range);
24505        assert_eq!(range.rename_index(None::<&str>).name(), None);
24506        assert_eq!(range.nbytes(), 3 * std::mem::size_of::<i64>());
24507        assert_eq!(range.to_index().name().map(|n| n.as_str()), Some("row"));
24508        assert!(RangeIndex::new(0, 5, 0).is_err());
24509
24510        let dt = DatetimeIndex::new(vec![1_706_918_400_000_000_000, i64::MIN]).set_name("when");
24511        assert_eq!(dt.year(), vec![Some(2024), None]);
24512        assert_eq!(dt.month(), vec![Some(2), None]);
24513        assert_eq!(dt.day(), vec![Some(3), None]);
24514        assert_eq!(dt.values(), vec![Some(1_706_918_400_000_000_000), None]);
24515        assert_eq!(dt.to_list(), dt.values());
24516        assert_eq!(dt.tolist(), dt.values());
24517        assert_eq!(dt.to_numpy(), dt.values());
24518        assert_eq!(dt.array(), dt.values());
24519        assert_eq!(dt.size(), 2);
24520        assert_eq!(dt.shape(), (2,));
24521        assert!(!dt.empty());
24522        assert_eq!(dt.dtype(), "datetime64[ns]");
24523        assert_eq!(dt.dtypes(), vec!["datetime64[ns]"]);
24524        assert_eq!(dt.names(), vec![Some("when".to_owned())]);
24525        assert_eq!(dt.copy(), dt);
24526        assert!(dt.hasnans());
24527        assert_eq!(dt.isna(), vec![false, true]);
24528        assert_eq!(dt.notna(), vec![true, false]);
24529        assert!(dt.nbytes() <= dt.memory_usage(true));
24530        assert!(DatetimeIndex::from_index(Index::from_i64(vec![1])).is_err());
24531
24532        let td = TimedeltaIndex::new(vec![90_061_000_000_000, Timedelta::NAT]).set_name("delta");
24533        assert_eq!(td.days(), vec![Some(1), None]);
24534        assert_eq!(td.seconds(), vec![Some(3661), None]);
24535        assert_eq!(td.total_seconds(), vec![Some(90061.0), None]);
24536        assert_eq!(td.values(), vec![Some(90_061_000_000_000), None]);
24537        assert_eq!(td.to_list(), td.values());
24538        assert_eq!(td.tolist(), td.values());
24539        assert_eq!(td.to_numpy(), td.values());
24540        assert_eq!(td.array(), td.values());
24541        assert_eq!(td.size(), 2);
24542        assert_eq!(td.shape(), (2,));
24543        assert!(!td.empty());
24544        assert_eq!(td.dtype(), "timedelta64[ns]");
24545        assert_eq!(td.dtypes(), vec!["timedelta64[ns]"]);
24546        assert_eq!(td.names(), vec![Some("delta".to_owned())]);
24547        assert_eq!(td.copy(), td);
24548        assert!(td.hasnans());
24549        assert_eq!(td.isna(), vec![false, true]);
24550        assert_eq!(td.notna(), vec![true, false]);
24551
24552        let period =
24553            PeriodIndex::from_range(Period::new(10, PeriodFreq::Monthly), 3).set_name("period");
24554        assert_eq!(period.freq(), Some(PeriodFreq::Monthly));
24555        assert_eq!(
24556            period.values(),
24557            &[
24558                Period::new(10, PeriodFreq::Monthly),
24559                Period::new(11, PeriodFreq::Monthly),
24560                Period::new(12, PeriodFreq::Monthly),
24561            ]
24562        );
24563        assert_eq!(period.to_list(), period.values());
24564        assert_eq!(period.tolist(), period.values());
24565        assert_eq!(period.to_numpy(), period.values());
24566        assert_eq!(period.array(), period.values());
24567        assert_eq!(period.size(), 3);
24568        assert_eq!(period.shape(), (3,));
24569        assert!(!period.empty());
24570        assert_eq!(period.dtype(), "period[M]");
24571        assert_eq!(period.dtypes(), vec!["period[M]".to_owned()]);
24572        assert_eq!(period.names(), vec![Some("period".to_owned())]);
24573        assert_eq!(period.copy(), period);
24574        assert_eq!(period.rename_index(None::<&str>).name(), None);
24575        assert!(period.nbytes() <= period.memory_usage(true));
24576        assert_eq!(period.to_index().name().map(|n| n.as_str()), Some("period"));
24577
24578        let period_width = std::mem::size_of::<Period>();
24579        assert_eq!(period.nbytes(), 3 * period_width);
24580        assert_eq!(period.memory_usage(true), 3 * period_width + "period".len());
24581        assert_eq!(
24582            super::fixed_width_label_memory_usage(usize::MAX, period_width),
24583            usize::MAX
24584        );
24585
24586        let categorical = CategoricalIndex::from_values(
24587            vec!["low".to_owned(), "high".to_owned(), "low".to_owned()],
24588            true,
24589        )
24590        .set_name("priority");
24591        assert_eq!(
24592            categorical.categories(),
24593            &[IndexLabel::from("low"), IndexLabel::from("high")]
24594        );
24595        assert_eq!(categorical.codes(), vec![Some(0), Some(1), Some(0)]);
24596        assert!(categorical.ordered());
24597        assert_eq!(
24598            categorical.values(),
24599            vec![
24600                IndexLabel::from("low"),
24601                IndexLabel::from("high"),
24602                IndexLabel::from("low")
24603            ]
24604        );
24605        assert_eq!(categorical.to_list(), categorical.values());
24606        assert_eq!(categorical.tolist(), categorical.values());
24607        assert_eq!(categorical.to_numpy(), categorical.values());
24608        assert_eq!(categorical.array(), categorical.values());
24609        assert_eq!(categorical.size(), 3);
24610        assert_eq!(categorical.shape(), (3,));
24611        assert!(!categorical.empty());
24612        assert_eq!(categorical.dtype(), "category");
24613        assert_eq!(categorical.dtypes(), vec!["category"]);
24614        assert_eq!(categorical.names(), vec![Some("priority".to_owned())]);
24615        assert_eq!(categorical.copy(), categorical);
24616        assert_eq!(categorical.isna(), vec![false, false, false]);
24617        assert_eq!(categorical.notna(), vec![true, true, true]);
24618        assert!(categorical.nbytes() <= categorical.memory_usage(true));
24619        assert_eq!(
24620            categorical.to_index().name().map(|n| n.as_str()),
24621            Some("priority")
24622        );
24623        // A label outside the categories is NaN, as pandas' constructor.
24624        let outside = CategoricalIndex::with_categories(
24625            vec!["missing".to_owned()],
24626            vec!["known".to_owned()],
24627            false,
24628        )
24629        .expect("a label outside the categories is NaN");
24630        assert_eq!(
24631            outside.labels(),
24632            &[IndexLabel::Null(fp_types::NullKind::NaN)]
24633        );
24634        assert_eq!(outside.isna(), vec![true]);
24635        assert_eq!(outside.categories(), &[IndexLabel::from("known")]);
24636        // Repeated categories still reject.
24637        assert!(
24638            CategoricalIndex::with_categories(
24639                vec!["known".to_owned()],
24640                vec!["known".to_owned(), "known".to_owned()],
24641                false,
24642            )
24643            .is_err()
24644        );
24645    }
24646
24647    #[test]
24648    fn categorical_index_memory_usage_saturates_uza04180() -> Result<(), super::IndexError> {
24649        let categorical = CategoricalIndex::from_values(
24650            vec!["low".to_owned(), "high".to_owned(), "low".to_owned()],
24651            true,
24652        )
24653        .set_name("priority");
24654        let fixed = 5 * std::mem::size_of::<String>();
24655
24656        assert_eq!(categorical.nbytes(), fixed);
24657        assert_eq!(categorical.memory_usage(false), fixed);
24658        assert_eq!(
24659            categorical.memory_usage(true),
24660            fixed + "lowhighlow".len() + "lowhigh".len() + "priority".len()
24661        );
24662        assert_eq!(super::saturating_usize_sum([usize::MAX, 1]), usize::MAX);
24663        Ok(())
24664    }
24665
24666    #[test]
24667    fn typed_index_str_accessors_forward_flat_labels_e7ms9() -> Result<(), super::IndexError> {
24668        let flat = Index::new(vec!["Alpha".into(), 1_i64.into(), "".into()]);
24669        assert_eq!(
24670            flat.r#str().lower(),
24671            vec![Some("alpha".to_owned()), None, Some(String::new())]
24672        );
24673
24674        let range = RangeIndex::new(1, 4, 1)?;
24675        assert_eq!(range.r#str().len(), vec![None, None, None]);
24676
24677        let dt = DatetimeIndex::new(vec![1_704_067_200_000_000_000]);
24678        assert_eq!(dt.r#str().upper(), vec![None]);
24679
24680        let td = TimedeltaIndex::new(vec![90_061_000_000_000]);
24681        assert_eq!(td.r#str().contains("day"), vec![None]);
24682
24683        // TEST-CHANGE (45fzr): period labels are periods now, not text, so
24684        // the str accessor reads them as the instants and durations above
24685        // do (pandas raises AttributeError for PeriodIndex.str).
24686        let period = PeriodIndex::from_range(Period::new(10, PeriodFreq::Monthly), 2);
24687        assert_eq!(period.r#str().lower(), vec![None, None]);
24688
24689        let categorical = CategoricalIndex::from_values(
24690            vec!["Low".to_owned(), "HIGH".to_owned(), String::new()],
24691            false,
24692        );
24693        assert_eq!(
24694            categorical.r#str().lower(),
24695            vec![
24696                Some("low".to_owned()),
24697                Some("high".to_owned()),
24698                Some(String::new())
24699            ]
24700        );
24701        Ok(())
24702    }
24703
24704    #[test]
24705    fn period_index_from_fields_builds_period_ordinals_th1fd() -> Result<(), super::IndexError> {
24706        let years = [2020, 2021];
24707        let months = [1, 2];
24708        let monthly = PeriodIndex::from_fields(PeriodFields {
24709            month: Some(&months),
24710            freq: Some(PeriodFreq::Monthly),
24711            ..PeriodFields::new(&years)
24712        })?;
24713        assert_eq!(
24714            monthly.values(),
24715            &[
24716                Period::new(600, PeriodFreq::Monthly),
24717                Period::new(613, PeriodFreq::Monthly)
24718            ]
24719        );
24720
24721        let quarter_years = [2020];
24722        let quarters = [2];
24723        let quarterly = PeriodIndex::from_fields(PeriodFields {
24724            quarter: Some(&quarters),
24725            ..PeriodFields::new(&quarter_years)
24726        })?;
24727        assert_eq!(
24728            quarterly.values(),
24729            &[Period::new(201, PeriodFreq::QUARTERLY)]
24730        );
24731
24732        let single_year = [2020];
24733        let single_month = [1];
24734        let weekly = PeriodIndex::from_fields(PeriodFields {
24735            month: Some(&single_month),
24736            freq: Some(PeriodFreq::WEEKLY),
24737            ..PeriodFields::new(&single_year)
24738        })?;
24739        assert_eq!(weekly.values(), &[Period::new(2_610, PeriodFreq::WEEKLY)]);
24740
24741        let weekend_day = [4];
24742        let business = PeriodIndex::from_fields(PeriodFields {
24743            month: Some(&single_month),
24744            day: Some(&weekend_day),
24745            freq: Some(PeriodFreq::Business),
24746            ..PeriodFields::new(&single_year)
24747        })?;
24748        assert_eq!(
24749            business.values(),
24750            &[Period::new(13_047, PeriodFreq::Business)]
24751        );
24752
24753        let days = [2];
24754        let hours = [3];
24755        let minutes = [4];
24756        let seconds = [5];
24757        let secondly = PeriodIndex::from_fields(PeriodFields {
24758            month: Some(&single_month),
24759            day: Some(&days),
24760            hour: Some(&hours),
24761            minute: Some(&minutes),
24762            second: Some(&seconds),
24763            freq: Some(PeriodFreq::Secondly),
24764            ..PeriodFields::new(&single_year)
24765        })?;
24766        let expected_date = chrono::NaiveDate::from_ymd_opt(2020, 1, 2)
24767            .ok_or_else(|| super::IndexError::InvalidArgument("invalid test date".to_owned()))?;
24768        let expected_time = chrono::NaiveTime::from_hms_opt(3, 4, 5)
24769            .ok_or_else(|| super::IndexError::InvalidArgument("invalid test time".to_owned()))?;
24770        let expected_nanos =
24771            super::date_and_time_to_nanos(expected_date, super::time_to_nanos(expected_time))
24772                .map_err(super::period_date_error)?;
24773        assert_eq!(
24774            secondly.values(),
24775            &[Period::new(
24776                super::datetime_period_ordinal(expected_nanos, PeriodFreq::Secondly)?,
24777                PeriodFreq::Secondly
24778            )]
24779        );
24780
24781        assert!(
24782            PeriodIndex::from_fields(PeriodFields {
24783                month: Some(&months),
24784                freq: Some(PeriodFreq::Monthly),
24785                ..PeriodFields::new(&single_year)
24786            })
24787            .is_err()
24788        );
24789        let invalid_month = [13];
24790        assert!(
24791            PeriodIndex::from_fields(PeriodFields {
24792                month: Some(&invalid_month),
24793                freq: Some(PeriodFreq::Monthly),
24794                ..PeriodFields::new(&single_year)
24795            })
24796            .is_err()
24797        );
24798        let invalid_day = [99];
24799        assert_eq!(
24800            PeriodIndex::from_fields(PeriodFields {
24801                month: Some(&single_month),
24802                day: Some(&invalid_day),
24803                freq: Some(PeriodFreq::Monthly),
24804                ..PeriodFields::new(&single_year)
24805            })?
24806            .values(),
24807            &[Period::new(600, PeriodFreq::Monthly)]
24808        );
24809        assert!(
24810            PeriodIndex::from_fields(PeriodFields {
24811                quarter: Some(&quarters),
24812                month: Some(&single_month),
24813                freq: Some(PeriodFreq::Monthly),
24814                ..PeriodFields::new(&single_year)
24815            })
24816            .is_err()
24817        );
24818        Ok(())
24819    }
24820
24821    #[test]
24822    fn index_variant_wrappers_expose_identity_and_type_surface() {
24823        let range = RangeIndex::new(1, 7, 2).unwrap().set_name("row");
24824        assert!(range.is_(&range));
24825        assert!(range.equals(&range.copy()));
24826        assert!(range.identical(&range.copy()));
24827        assert!(!range.identical(&range.rename_index(None::<&str>)));
24828        assert!(range.is_unique());
24829        assert!(!range.has_duplicates());
24830        assert!(range.is_monotonic_increasing());
24831        assert!(!range.is_monotonic_decreasing());
24832        assert_eq!(range.nunique(), 3);
24833        assert_eq!(range.ndim(), 1);
24834        assert_eq!(RangeIndex::new(4, 5, 1).unwrap().item().unwrap(), 4);
24835        assert!(range.item().is_err());
24836        assert!(range.holds_integer());
24837        assert_eq!(range.inferred_type(), "integer");
24838        assert!(range.is_integer());
24839        assert!(range.is_numeric());
24840        assert!(!range.is_boolean());
24841        assert!(!range.is_categorical());
24842        assert!(!range.is_floating());
24843        assert!(!range.is_interval());
24844        assert!(!range.is_object());
24845
24846        let dt = DatetimeIndex::new(vec![1_706_918_400_000_000_000, i64::MIN]).set_name("when");
24847        assert!(dt.is_(&dt));
24848        assert!(dt.equals(&dt.copy()));
24849        assert!(dt.identical(&dt.copy()));
24850        assert!(!dt.identical(&dt.rename_index(None::<&str>)));
24851        assert!(dt.is_unique());
24852        assert!(!dt.has_duplicates());
24853        assert_eq!(dt.nunique(), 1);
24854        assert_eq!(dt.nunique_with_dropna(false), 2);
24855        assert_eq!(dt.ndim(), 1);
24856        assert_eq!(
24857            DatetimeIndex::new(vec![1_706_918_400_000_000_000])
24858                .item()
24859                .unwrap(),
24860            Some(1_706_918_400_000_000_000)
24861        );
24862        assert_eq!(DatetimeIndex::new(vec![i64::MIN]).item().unwrap(), None);
24863        assert_eq!(dt.inferred_type(), "datetime64");
24864        assert!(!dt.holds_integer());
24865        assert!(!dt.is_integer());
24866        assert!(!dt.is_numeric());
24867        assert!(!dt.is_boolean());
24868        assert!(!dt.is_categorical());
24869        assert!(!dt.is_floating());
24870        assert!(!dt.is_interval());
24871        assert!(!dt.is_object());
24872        assert!(DatetimeIndex::new(vec![1, 2]).is_monotonic_increasing());
24873        assert!(DatetimeIndex::new(vec![2, 1]).is_monotonic_decreasing());
24874
24875        let td = TimedeltaIndex::new(vec![1, Timedelta::NAT]).set_name("delta");
24876        assert!(td.is_(&td));
24877        assert!(td.equals(&td.copy()));
24878        assert!(td.identical(&td.copy()));
24879        assert!(!td.identical(&td.rename_index(None::<&str>)));
24880        assert!(td.is_unique());
24881        assert_eq!(td.nunique(), 1);
24882        assert_eq!(td.nunique_with_dropna(false), 2);
24883        assert_eq!(td.ndim(), 1);
24884        assert_eq!(TimedeltaIndex::new(vec![7]).item().unwrap(), Some(7));
24885        assert_eq!(
24886            TimedeltaIndex::new(vec![Timedelta::NAT]).item().unwrap(),
24887            None
24888        );
24889        assert_eq!(td.inferred_type(), "timedelta64");
24890        assert!(!td.holds_integer());
24891        assert!(!td.is_integer());
24892        assert!(!td.is_numeric());
24893        assert!(!td.is_boolean());
24894        assert!(!td.is_categorical());
24895        assert!(!td.is_floating());
24896        assert!(!td.is_interval());
24897        assert!(!td.is_object());
24898        assert!(TimedeltaIndex::new(vec![1, 2]).is_monotonic_increasing());
24899        assert!(TimedeltaIndex::new(vec![2, 1]).is_monotonic_decreasing());
24900
24901        let period =
24902            PeriodIndex::from_range(Period::new(10, PeriodFreq::Monthly), 3).set_name("period");
24903        assert!(period.is_(&period));
24904        assert!(period.equals(&period.copy()));
24905        assert!(period.identical(&period.copy()));
24906        assert!(!period.identical(&period.rename_index(None::<&str>)));
24907        assert!(period.is_unique());
24908        assert!(!period.has_duplicates());
24909        assert!(period.is_monotonic_increasing());
24910        assert!(!period.is_monotonic_decreasing());
24911        assert_eq!(period.nunique(), 3);
24912        assert_eq!(period.ndim(), 1);
24913        assert_eq!(
24914            PeriodIndex::new(vec![Period::new(42, PeriodFreq::Daily)])
24915                .item()
24916                .unwrap(),
24917            Period::new(42, PeriodFreq::Daily)
24918        );
24919        assert_eq!(period.inferred_type(), "period");
24920        assert!(!period.holds_integer());
24921        assert!(!period.is_integer());
24922        assert!(!period.is_numeric());
24923        assert!(!period.is_boolean());
24924        assert!(!period.is_categorical());
24925        assert!(!period.is_floating());
24926        assert!(!period.is_interval());
24927        assert!(!period.is_object());
24928
24929        let categorical = CategoricalIndex::from_values(
24930            vec!["low".to_owned(), "high".to_owned(), "low".to_owned()],
24931            true,
24932        )
24933        .set_name("priority");
24934        assert!(categorical.is_(&categorical));
24935        assert!(categorical.equals(&categorical.copy()));
24936        assert!(categorical.identical(&categorical.copy()));
24937        assert!(!categorical.identical(&categorical.rename_index(None::<&str>)));
24938        assert!(!categorical.is_unique());
24939        assert!(categorical.has_duplicates());
24940        assert_eq!(categorical.nunique(), 2);
24941        assert_eq!(categorical.ndim(), 1);
24942        assert_eq!(
24943            CategoricalIndex::from_values(vec!["high".to_owned()], true)
24944                .item()
24945                .unwrap(),
24946            IndexLabel::from("high")
24947        );
24948        assert_eq!(categorical.inferred_type(), "categorical");
24949        assert!(!categorical.holds_integer());
24950        assert!(!categorical.is_integer());
24951        assert!(!categorical.is_numeric());
24952        assert!(!categorical.is_boolean());
24953        assert!(categorical.is_categorical());
24954        assert!(!categorical.is_floating());
24955        assert!(!categorical.is_interval());
24956        assert!(!categorical.is_object());
24957        assert!(!categorical.is_monotonic_increasing());
24958        assert!(!categorical.is_monotonic_decreasing());
24959        assert!(
24960            CategoricalIndex::from_values(vec!["low".to_owned(), "high".to_owned()], true)
24961                .is_monotonic_increasing()
24962        );
24963    }
24964
24965    // === AG-13: Adaptive Index Backend Tests ===
24966
24967    #[test]
24968    fn sorted_int64_index_detected() {
24969        let index = Index::from_i64(vec![1, 2, 3, 4, 5]);
24970        assert!(index.is_sorted());
24971    }
24972
24973    #[test]
24974    fn unsorted_int64_index_detected() {
24975        let index = Index::from_i64(vec![3, 1, 2]);
24976        assert!(!index.is_sorted());
24977    }
24978
24979    #[test]
24980    fn sorted_utf8_index_detected() {
24981        let index = Index::from_utf8(vec!["a".into(), "b".into(), "c".into()]);
24982        assert!(index.is_sorted());
24983    }
24984
24985    #[test]
24986    fn unsorted_utf8_index_detected() {
24987        let index = Index::from_utf8(vec!["c".into(), "a".into(), "b".into()]);
24988        assert!(!index.is_sorted());
24989    }
24990
24991    #[test]
24992    fn duplicate_int64_is_not_sorted() {
24993        let index = Index::from_i64(vec![1, 2, 2, 3]);
24994        assert!(!index.is_sorted());
24995    }
24996
24997    #[test]
24998    fn empty_index_is_sorted() {
24999        let index = Index::new(vec![]);
25000        assert!(index.is_sorted());
25001    }
25002
25003    #[test]
25004    fn single_element_is_sorted() {
25005        let index = Index::from_i64(vec![42]);
25006        assert!(index.is_sorted());
25007    }
25008
25009    #[test]
25010    fn binary_search_position_sorted_int64() {
25011        let index = Index::from_i64(vec![10, 20, 30, 40, 50]);
25012        assert_eq!(index.position(&IndexLabel::Int64(10)), Some(0));
25013        assert_eq!(index.position(&IndexLabel::Int64(30)), Some(2));
25014        assert_eq!(index.position(&IndexLabel::Int64(50)), Some(4));
25015        assert_eq!(index.position(&IndexLabel::Int64(25)), None);
25016        assert_eq!(index.position(&IndexLabel::Int64(0)), None);
25017        assert_eq!(index.position(&IndexLabel::Int64(100)), None);
25018    }
25019
25020    #[test]
25021    fn binary_search_position_sorted_utf8() {
25022        let index = Index::from_utf8(vec!["apple".into(), "banana".into(), "cherry".into()]);
25023        assert_eq!(index.position(&IndexLabel::Utf8("apple".into())), Some(0));
25024        assert_eq!(index.position(&IndexLabel::Utf8("banana".into())), Some(1));
25025        assert_eq!(index.position(&IndexLabel::Utf8("cherry".into())), Some(2));
25026        assert_eq!(index.position(&IndexLabel::Utf8("date".into())), None);
25027    }
25028
25029    #[test]
25030    fn type_mismatch_returns_none() {
25031        let int_index = Index::from_i64(vec![1, 2, 3]);
25032        // Looking for a Utf8 needle in an Int64 index
25033        assert_eq!(int_index.position(&IndexLabel::Utf8("1".into())), None);
25034
25035        let utf8_index = Index::from_utf8(vec!["a".into(), "b".into()]);
25036        // Looking for an Int64 needle in a Utf8 index
25037        assert_eq!(utf8_index.position(&IndexLabel::Int64(1)), None);
25038    }
25039
25040    #[test]
25041    fn linear_fallback_for_unsorted_index() {
25042        let index = Index::from_i64(vec![30, 10, 20]);
25043        assert!(!index.is_sorted());
25044        assert_eq!(index.position(&IndexLabel::Int64(30)), Some(0));
25045        assert_eq!(index.position(&IndexLabel::Int64(10)), Some(1));
25046        assert_eq!(index.position(&IndexLabel::Int64(20)), Some(2));
25047        assert_eq!(index.position(&IndexLabel::Int64(99)), None);
25048    }
25049
25050    #[test]
25051    fn binary_search_large_sorted_index() {
25052        // Verify binary search works correctly on a large sorted index.
25053        let labels: Vec<i64> = (0..10_000).collect();
25054        let index = Index::from_i64(labels);
25055        assert!(index.is_sorted());
25056
25057        // Check first, middle, last, and missing positions.
25058        assert_eq!(index.position(&IndexLabel::Int64(0)), Some(0));
25059        assert_eq!(index.position(&IndexLabel::Int64(5000)), Some(5000));
25060        assert_eq!(index.position(&IndexLabel::Int64(9999)), Some(9999));
25061        assert_eq!(index.position(&IndexLabel::Int64(10_000)), None);
25062        assert_eq!(index.position(&IndexLabel::Int64(-1)), None);
25063    }
25064
25065    #[test]
25066    fn sort_detection_is_cached() {
25067        let index = Index::from_i64(vec![1, 2, 3]);
25068        // First call computes and caches.
25069        assert!(index.is_sorted());
25070        // Second call should return same result from cache.
25071        assert!(index.is_sorted());
25072    }
25073
25074    #[test]
25075    fn mixed_label_types_are_unsorted() {
25076        let index = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Utf8("a".into())]);
25077        assert!(!index.is_sorted());
25078    }
25079
25080    #[test]
25081    fn position_consistent_sorted_vs_unsorted() {
25082        // Verify that for a sorted index, binary search gives the same
25083        // results as a linear scan would.
25084        let sorted = Index::from_i64(vec![5, 10, 15, 20, 25]);
25085        assert!(sorted.is_sorted());
25086
25087        for &target in &[5, 10, 15, 20, 25, 0, 12, 30] {
25088            let needle = IndexLabel::Int64(target);
25089            let expected = sorted.labels().iter().position(|l| l == &needle);
25090            assert_eq!(
25091                sorted.position(&needle),
25092                expected,
25093                "mismatch for target={target}"
25094            );
25095        }
25096    }
25097
25098    // === bd-2gi.15: Alignment mode tests ===
25099
25100    use super::{AlignMode, align, align_inner, align_left};
25101
25102    #[test]
25103    fn align_inner_keeps_only_overlapping_labels() {
25104        let left = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
25105        let right = Index::new(vec![2_i64.into(), 3_i64.into(), 4_i64.into()]);
25106
25107        let plan = align_inner(&left, &right);
25108        assert_eq!(
25109            plan.union_index.labels(),
25110            &[IndexLabel::Int64(2), IndexLabel::Int64(3)]
25111        );
25112        assert_eq!(plan.left_positions, vec![Some(1), Some(2)]);
25113        assert_eq!(plan.right_positions, vec![Some(0), Some(1)]);
25114        validate_alignment_plan(&plan).expect("valid");
25115    }
25116
25117    #[test]
25118    fn align_inner_disjoint_yields_empty() {
25119        let left = Index::new(vec![1_i64.into(), 2_i64.into()]);
25120        let right = Index::new(vec![3_i64.into(), 4_i64.into()]);
25121
25122        let plan = align_inner(&left, &right);
25123        assert!(plan.union_index.is_empty());
25124        assert!(plan.left_positions.is_empty());
25125        assert!(plan.right_positions.is_empty());
25126    }
25127
25128    #[test]
25129    fn align_left_preserves_all_left_labels() {
25130        let left = Index::new(vec!["a".into(), "b".into(), "c".into()]);
25131        let right = Index::new(vec!["b".into(), "d".into()]);
25132
25133        let plan = align_left(&left, &right);
25134        assert_eq!(
25135            plan.union_index.labels(),
25136            &["a".into(), "b".into(), "c".into()]
25137        );
25138        assert_eq!(plan.left_positions, vec![Some(0), Some(1), Some(2)]);
25139        assert_eq!(plan.right_positions, vec![None, Some(0), None]);
25140        validate_alignment_plan(&plan).expect("valid");
25141    }
25142
25143    #[test]
25144    fn align_right_preserves_all_right_labels() {
25145        let left = Index::new(vec!["a".into(), "b".into()]);
25146        let right = Index::new(vec!["b".into(), "c".into(), "d".into()]);
25147
25148        let plan = align(&left, &right, AlignMode::Right);
25149        assert_eq!(
25150            plan.union_index.labels(),
25151            &["b".into(), "c".into(), "d".into()]
25152        );
25153        // Left has "b" at position 1.
25154        assert_eq!(plan.left_positions, vec![Some(1), None, None]);
25155        assert_eq!(plan.right_positions, vec![Some(0), Some(1), Some(2)]);
25156    }
25157
25158    #[test]
25159    fn align_mode_outer_matches_union() {
25160        let left = Index::new(vec![1_i64.into(), 2_i64.into()]);
25161        let right = Index::new(vec![2_i64.into(), 3_i64.into()]);
25162
25163        let plan_outer = align(&left, &right, AlignMode::Outer);
25164        let plan_union = align_union(&left, &right);
25165        assert_eq!(plan_outer, plan_union);
25166    }
25167
25168    #[test]
25169    fn align_inner_duplicate_labels_cartesian() {
25170        let left = Index::new(vec!["a".into(), "b".into(), "a".into()]);
25171        let right = Index::new(vec!["a".into(), "a".into(), "c".into()]);
25172
25173        let plan = align_inner(&left, &right);
25174        assert_eq!(
25175            plan.union_index.labels(),
25176            &["a".into(), "a".into(), "a".into(), "a".into()]
25177        );
25178        assert_eq!(
25179            plan.left_positions,
25180            vec![Some(0), Some(0), Some(2), Some(2)]
25181        );
25182        assert_eq!(
25183            plan.right_positions,
25184            vec![Some(0), Some(1), Some(0), Some(1)]
25185        );
25186        validate_alignment_plan(&plan).expect("valid");
25187    }
25188
25189    #[test]
25190    fn align_left_duplicate_labels_expand_right_matches() {
25191        let left = Index::new(vec!["a".into(), "b".into(), "a".into()]);
25192        let right = Index::new(vec!["a".into(), "a".into(), "c".into()]);
25193
25194        let plan = align_left(&left, &right);
25195        assert_eq!(
25196            plan.union_index.labels(),
25197            &["a".into(), "a".into(), "b".into(), "a".into(), "a".into()]
25198        );
25199        assert_eq!(
25200            plan.left_positions,
25201            vec![Some(0), Some(0), Some(1), Some(2), Some(2)]
25202        );
25203        assert_eq!(
25204            plan.right_positions,
25205            vec![Some(0), Some(1), None, Some(0), Some(1)]
25206        );
25207        validate_alignment_plan(&plan).expect("valid");
25208    }
25209
25210    #[test]
25211    fn align_right_duplicate_labels_expand_left_matches() {
25212        let left = Index::new(vec!["a".into(), "b".into(), "a".into()]);
25213        let right = Index::new(vec!["a".into(), "a".into(), "c".into()]);
25214
25215        let plan = align(&left, &right, AlignMode::Right);
25216        assert_eq!(
25217            plan.union_index.labels(),
25218            &["a".into(), "a".into(), "a".into(), "a".into(), "c".into()]
25219        );
25220        assert_eq!(
25221            plan.left_positions,
25222            vec![Some(0), Some(2), Some(0), Some(2), None]
25223        );
25224        assert_eq!(
25225            plan.right_positions,
25226            vec![Some(0), Some(0), Some(1), Some(1), Some(2)]
25227        );
25228        validate_alignment_plan(&plan).expect("valid");
25229    }
25230
25231    #[test]
25232    fn align_outer_duplicate_labels_preserves_left_order_and_right_only() {
25233        let left = Index::new(vec!["a".into(), "b".into(), "a".into()]);
25234        let right = Index::new(vec!["a".into(), "a".into(), "c".into()]);
25235
25236        let plan = align_union(&left, &right);
25237        assert_eq!(
25238            plan.union_index.labels(),
25239            &[
25240                "a".into(),
25241                "a".into(),
25242                "b".into(),
25243                "a".into(),
25244                "a".into(),
25245                "c".into()
25246            ]
25247        );
25248        assert_eq!(
25249            plan.left_positions,
25250            vec![Some(0), Some(0), Some(1), Some(2), Some(2), None]
25251        );
25252        assert_eq!(
25253            plan.right_positions,
25254            vec![Some(0), Some(1), None, Some(0), Some(1), Some(2)]
25255        );
25256        validate_alignment_plan(&plan).expect("valid");
25257    }
25258
25259    #[test]
25260    fn align_inner_identical_indexes() {
25261        let left = Index::new(vec!["x".into(), "y".into()]);
25262        let right = Index::new(vec!["x".into(), "y".into()]);
25263
25264        let plan = align_inner(&left, &right);
25265        assert_eq!(plan.union_index.labels(), &["x".into(), "y".into()]);
25266        assert_eq!(plan.left_positions, vec![Some(0), Some(1)]);
25267        assert_eq!(plan.right_positions, vec![Some(0), Some(1)]);
25268    }
25269
25270    #[test]
25271    fn align_left_identical_indexes() {
25272        let left = Index::new(vec![1_i64.into(), 2_i64.into()]);
25273        let right = Index::new(vec![1_i64.into(), 2_i64.into()]);
25274
25275        let plan = align_left(&left, &right);
25276        assert_eq!(plan.union_index.labels(), left.labels());
25277        assert_eq!(plan.left_positions, vec![Some(0), Some(1)]);
25278        assert_eq!(plan.right_positions, vec![Some(0), Some(1)]);
25279    }
25280
25281    #[test]
25282    fn align_inner_empty_input() {
25283        let left = Index::new(Vec::new());
25284        let right = Index::new(vec![1_i64.into()]);
25285
25286        let plan = align_inner(&left, &right);
25287        assert!(plan.union_index.is_empty());
25288    }
25289
25290    #[test]
25291    fn align_left_empty_left() {
25292        let left = Index::new(Vec::new());
25293        let right = Index::new(vec![1_i64.into()]);
25294
25295        let plan = align_left(&left, &right);
25296        assert!(plan.union_index.is_empty());
25297    }
25298
25299    // === bd-2gi.13: Index model and indexer semantics ===
25300
25301    use super::DuplicateKeep;
25302
25303    #[test]
25304    fn contains_finds_existing_label() {
25305        let index = Index::from_i64(vec![10, 20, 30]);
25306        assert!(index.contains(&IndexLabel::Int64(20)));
25307        assert!(!index.contains(&IndexLabel::Int64(99)));
25308    }
25309
25310    #[test]
25311    fn get_indexer_bulk_lookup() {
25312        let index = Index::new(vec!["a".into(), "b".into(), "c".into()]);
25313        let target = Index::new(vec!["c".into(), "a".into(), "z".into()]);
25314        assert_eq!(index.get_indexer(&target), vec![Some(2), Some(0), None]);
25315    }
25316
25317    #[test]
25318    fn isin_membership_mask() {
25319        let index = Index::from_i64(vec![1, 2, 3, 4, 5]);
25320        let values = vec![IndexLabel::Int64(2), IndexLabel::Int64(4)];
25321        assert_eq!(index.isin(&values), vec![false, true, false, true, false]);
25322    }
25323
25324    #[test]
25325    fn unique_preserves_first_seen_order() {
25326        let index = Index::new(vec![
25327            "b".into(),
25328            "a".into(),
25329            "b".into(),
25330            "c".into(),
25331            "a".into(),
25332        ]);
25333        let uniq = index.unique();
25334        assert_eq!(uniq.labels(), &["b".into(), "a".into(), "c".into()]);
25335    }
25336
25337    #[test]
25338    fn duplicated_keep_first() {
25339        let index = Index::from_i64(vec![1, 2, 1, 3, 2]);
25340        assert_eq!(
25341            index.duplicated(DuplicateKeep::First),
25342            vec![false, false, true, false, true]
25343        );
25344    }
25345
25346    #[test]
25347    fn duplicated_keep_last() {
25348        let index = Index::from_i64(vec![1, 2, 1, 3, 2]);
25349        assert_eq!(
25350            index.duplicated(DuplicateKeep::Last),
25351            vec![true, true, false, false, false]
25352        );
25353    }
25354
25355    #[test]
25356    fn duplicated_keep_none_marks_all() {
25357        let index = Index::from_i64(vec![1, 2, 1, 3, 2]);
25358        assert_eq!(
25359            index.duplicated(DuplicateKeep::None),
25360            vec![true, true, true, false, true]
25361        );
25362    }
25363
25364    #[test]
25365    fn drop_duplicates_equals_unique() {
25366        let index = Index::from_i64(vec![3, 1, 3, 2, 1]);
25367        assert_eq!(index.drop_duplicates(), index.unique());
25368    }
25369
25370    #[test]
25371    fn index_drop_duplicates_keep_last() {
25372        let index = Index::new(vec![
25373            "llama".into(),
25374            "cow".into(),
25375            "llama".into(),
25376            "beetle".into(),
25377            "llama".into(),
25378            "hippo".into(),
25379        ])
25380        .set_names(Some("animals"));
25381
25382        let deduped = index.drop_duplicates_keep(DuplicateKeep::Last);
25383
25384        assert_eq!(
25385            deduped.labels(),
25386            &[
25387                IndexLabel::from("cow"),
25388                IndexLabel::from("beetle"),
25389                IndexLabel::from("llama"),
25390                IndexLabel::from("hippo"),
25391            ]
25392        );
25393        assert_eq!(deduped.name().map(|n| n.as_str()), Some("animals"));
25394    }
25395
25396    #[test]
25397    fn index_drop_duplicates_keep_none_discards_all_duplicates() {
25398        let index = Index::new(vec![
25399            "llama".into(),
25400            "cow".into(),
25401            "llama".into(),
25402            "beetle".into(),
25403            "llama".into(),
25404            "hippo".into(),
25405        ]);
25406
25407        let deduped = index.drop_duplicates_keep(DuplicateKeep::None);
25408
25409        assert_eq!(
25410            deduped.labels(),
25411            &[
25412                IndexLabel::from("cow"),
25413                IndexLabel::from("beetle"),
25414                IndexLabel::from("hippo"),
25415            ]
25416        );
25417    }
25418
25419    #[test]
25420    fn intersection_preserves_left_order() {
25421        let left = Index::new(vec!["c".into(), "a".into(), "b".into()]);
25422        let right = Index::new(vec!["b".into(), "d".into(), "a".into()]);
25423        let result = left.intersection(&right);
25424        assert_eq!(result.labels(), &["a".into(), "b".into()]);
25425    }
25426
25427    #[test]
25428    fn intersection_deduplicates() {
25429        let left = Index::from_i64(vec![1, 1, 2]);
25430        let right = Index::from_i64(vec![1, 2, 2]);
25431        let result = left.intersection(&right);
25432        assert_eq!(
25433            result.labels(),
25434            &[IndexLabel::Int64(1), IndexLabel::Int64(2)]
25435        );
25436    }
25437
25438    #[test]
25439    fn union_with_combines_unique_labels() {
25440        let left = Index::from_i64(vec![1, 2, 3]);
25441        let right = Index::from_i64(vec![2, 4, 3]);
25442        let result = left.union_with(&right);
25443        assert_eq!(
25444            result.labels(),
25445            &[
25446                IndexLabel::Int64(1),
25447                IndexLabel::Int64(2),
25448                IndexLabel::Int64(3),
25449                IndexLabel::Int64(4),
25450            ]
25451        );
25452    }
25453
25454    #[test]
25455    fn union_with_preserves_maximum_duplicate_multiplicity_lerb2() {
25456        // pandas 2.2.3: Index([3, 1, 2, 1]).union(Index([2, 4, 2]),
25457        // sort=False) -> [3, 1, 1, 2, 2, 4]. The output is neither a
25458        // deduplicated set nor a concatenation: labels are first-seen ordered,
25459        // then repeated by the larger input multiplicity.
25460        let left = Index::from_i64_values(vec![3, 1, 2, 1]);
25461        let right = Index::from_i64_values(vec![2, 4, 2]);
25462        let result = left.union_with(&right);
25463        assert_eq!(
25464            result.labels.int64_view().unwrap().as_slice(),
25465            &[3, 1, 1, 2, 2, 4]
25466        );
25467        assert_ne!(
25468            result.labels.int64_view().unwrap().as_slice(),
25469            &[3, 1, 2, 1, 2, 4, 2],
25470            "negative: union must not concatenate the duplicate-bearing inputs"
25471        );
25472    }
25473
25474    #[test]
25475    fn union_with_preserves_utf8_duplicate_multiplicity_lerb2() {
25476        let left = Index::new(vec!["b".into(), "a".into(), "b".into()]);
25477        let right = Index::new(vec!["a".into(), "a".into(), "c".into()]);
25478        assert_eq!(
25479            left.union_with(&right).labels(),
25480            &[
25481                IndexLabel::Utf8("b".to_owned()),
25482                IndexLabel::Utf8("b".to_owned()),
25483                IndexLabel::Utf8("a".to_owned()),
25484                IndexLabel::Utf8("a".to_owned()),
25485                IndexLabel::Utf8("c".to_owned()),
25486            ]
25487        );
25488    }
25489
25490    #[test]
25491    fn difference_removes_other_labels() {
25492        let left = Index::from_i64(vec![1, 2, 3, 4]);
25493        let right = Index::from_i64(vec![2, 4]);
25494        let result = left.difference(&right);
25495        assert_eq!(
25496            result.labels(),
25497            &[IndexLabel::Int64(1), IndexLabel::Int64(3)]
25498        );
25499    }
25500
25501    #[test]
25502    fn difference_preserves_self_name_even_when_other_differs_6r1lq() {
25503        // Per br-frankenpandas-6r1lq: difference is asymmetric — pandas
25504        // preserves self.name regardless of whether other has the same name.
25505        let left = Index::from_i64(vec![1, 2, 3]).set_name("left_axis");
25506        let right = Index::from_i64(vec![2, 3, 4]).set_name("right_axis");
25507        let result = left.difference(&right);
25508        assert_eq!(result.name().map(|n| n.as_str()), Some("left_axis"));
25509    }
25510
25511    #[test]
25512    fn symmetric_difference_xor() {
25513        let left = Index::from_i64(vec![1, 2, 3]);
25514        let right = Index::from_i64(vec![2, 3, 4]);
25515        let result = left.symmetric_difference(&right);
25516        assert_eq!(
25517            result.labels(),
25518            &[IndexLabel::Int64(1), IndexLabel::Int64(4)]
25519        );
25520    }
25521
25522    #[test]
25523    fn argsort_returns_sorting_indices() {
25524        let index = Index::from_i64(vec![30, 10, 20]);
25525        assert_eq!(index.argsort(), vec![1, 2, 0]);
25526    }
25527
25528    /// `get_loc_all` returns the position SET that pandas encodes three ways.
25529    ///
25530    /// br-frankenpandas-lerb2. `pd.Index.get_loc` returns an int, a slice, or a
25531    /// boolean mask depending on whether the index is unique and monotonic; all
25532    /// three describe the same set of positions, and `get_loc` here can only ever
25533    /// answer with one of them.
25534    ///
25535    /// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18):
25536    /// ```text
25537    ///   [10,20,30]        get_loc(20)  -> 1                           => [1]
25538    ///   [10,20,20,30]     get_loc(20)  -> slice(1, 3)                 => [1, 2]
25539    ///   [20,10,20]        get_loc(20)  -> array([True,False,True])    => [0, 2]
25540    ///   [10,20]           get_loc(99)  -> KeyError                    => []
25541    ///   [1.0,NaN,2.0,NaN] get_loc(NaN) -> array([F,True,F,True])      => [1, 3]
25542    /// ```
25543    #[test]
25544    fn get_loc_all_returns_every_position_lerb2() {
25545        assert_eq!(
25546            Index::from_i64(vec![10, 20, 30]).get_loc_all(&IndexLabel::Int64(20)),
25547            vec![1]
25548        );
25549        // ⚠️ The duplicate rows are the point: `get_loc` collapses each of these to a
25550        // single position, which is why they need their own accessor.
25551        assert_eq!(
25552            Index::from_i64(vec![10, 20, 20, 30]).get_loc_all(&IndexLabel::Int64(20)),
25553            vec![1, 2]
25554        );
25555        assert_eq!(
25556            Index::from_i64(vec![20, 10, 20]).get_loc_all(&IndexLabel::Int64(20)),
25557            vec![0, 2]
25558        );
25559        // Missing is EMPTY, not an error — this crate's get_loc returns Option, so
25560        // an absent key is not exceptional here the way pandas' KeyError is.
25561        assert!(
25562            Index::from_i64(vec![10, 20])
25563                .get_loc_all(&IndexLabel::Int64(99))
25564                .is_empty()
25565        );
25566        // ⚠️ NaN is findable, because OrderedF64 compares on a canonical bit pattern.
25567        // A derived PartialEq over raw f64 would make this row return [] instead.
25568        let floats = Index::new(vec![
25569            IndexLabel::Float64(OrderedF64(1.0)),
25570            IndexLabel::Float64(OrderedF64(f64::NAN)),
25571            IndexLabel::Float64(OrderedF64(2.0)),
25572            IndexLabel::Float64(OrderedF64(f64::NAN)),
25573        ]);
25574        assert_eq!(
25575            floats.get_loc_all(&IndexLabel::Float64(OrderedF64(f64::NAN))),
25576            vec![1, 3]
25577        );
25578    }
25579
25580    /// `asof` on a NON-MONOTONIC index: FrankenPandas answers, pandas refuses.
25581    ///
25582    /// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-19), `pd.Index([30,10,20])`:
25583    /// every `.asof(k)` raises `ValueError: index must be monotonic increasing or
25584    /// decreasing`. FrankenPandas returns `None` instead, because the scan breaks at
25585    /// the first label greater than the key — it stops at 30 and never reaches the 20
25586    /// that actually precedes 25.
25587    ///
25588    /// ⚠️ THIS PINS FrankenPandas' ANSWER, NOT pandas'. It exists so the divergence is
25589    /// visible and deliberate rather than discovered later: matching pandas means
25590    /// raising, and `asof` returns `Option`, not `Result`. If that signature ever
25591    /// changes, this test should change with it — do not read it as parity evidence.
25592    #[test]
25593    fn asof_on_a_non_monotonic_index_is_a_documented_divergence() {
25594        let unsorted = Index::from_i64(vec![30, 10, 20]);
25595        assert!(
25596            !unsorted.is_sorted(),
25597            "precondition: the index is non-monotonic"
25598        );
25599
25600        // pandas: ValueError. Here: None, because the scan stops at 30.
25601        assert_eq!(unsorted.asof(&IndexLabel::Int64(25)), None);
25602        assert_eq!(unsorted.asof(&IndexLabel::Int64(5)), None);
25603
25604        // ⚠️ And the answer is not merely "conservative": 20 DOES precede 25 and is
25605        // present in the index. Sorting first is what makes the lookup meaningful.
25606        let sorted = unsorted.sort_values();
25607        assert_eq!(
25608            sorted.asof(&IndexLabel::Int64(25)),
25609            Some(IndexLabel::Int64(20)),
25610            "after sorting, the preceding label is found"
25611        );
25612    }
25613
25614    #[test]
25615    fn int64_argsort_is_stable_and_keeps_typed_backing_6ubrp() {
25616        let index = Index::from_i64_values(vec![3, 1, 2, 1, 3]);
25617        assert!(index.labels.materialized.get().is_none());
25618        assert_eq!(index.argsort(), vec![1, 3, 2, 0, 4]);
25619        assert!(
25620            index.labels.materialized.get().is_none(),
25621            "typed Int64 argsort should not materialize IndexLabel values"
25622        );
25623    }
25624
25625    #[test]
25626    fn descending_int64_affine_argsort_does_not_materialize_6ubrp() {
25627        let index = Index::new_known_unique_int64_affine_range(10, -2, 4).unwrap();
25628        assert!(index.labels.materialized.get().is_none());
25629        assert_eq!(index.argsort(), vec![3, 2, 1, 0]);
25630        assert!(
25631            index.labels.materialized.get().is_none(),
25632            "affine Int64 argsort should not materialize IndexLabel values"
25633        );
25634    }
25635
25636    #[test]
25637    fn sort_values_produces_sorted_index() {
25638        let index = Index::new(vec!["c".into(), "a".into(), "b".into()]);
25639        let sorted = index.sort_values();
25640        assert_eq!(sorted.labels(), &["a".into(), "b".into(), "c".into()]);
25641    }
25642
25643    #[test]
25644    fn int64_sort_values_preserves_name_and_stable_duplicates_6ubrp() {
25645        let index = Index::from_i64_values(vec![3, 1, 2, 1, 3]).set_name("rows");
25646        let sorted = index.sort_values();
25647        assert_eq!(sorted.name().map(|n| n.as_str()), Some("rows"));
25648        assert_eq!(
25649            sorted.labels(),
25650            &[
25651                IndexLabel::Int64(1),
25652                IndexLabel::Int64(1),
25653                IndexLabel::Int64(2),
25654                IndexLabel::Int64(3),
25655                IndexLabel::Int64(3),
25656            ]
25657        );
25658    }
25659
25660    #[test]
25661    fn descending_int64_affine_sort_values_reuses_affine_backing_6ubrp() {
25662        let index = Index::new_known_unique_int64_affine_range(10, -2, 4)
25663            .unwrap()
25664            .set_name("axis");
25665        let sorted = index.sort_values();
25666        assert_eq!(sorted.name().map(|n| n.as_str()), Some("axis"));
25667        assert_eq!(
25668            sorted.labels.int64_affine_range(),
25669            Some(Int64AffineLabels {
25670                start: 4,
25671                step: 2,
25672                len: 4
25673            })
25674        );
25675        assert!(
25676            sorted.labels.materialized.get().is_none(),
25677            "descending affine sort_values should keep affine Int64 backing"
25678        );
25679        assert_eq!(
25680            sorted.labels(),
25681            &[
25682                IndexLabel::Int64(4),
25683                IndexLabel::Int64(6),
25684                IndexLabel::Int64(8),
25685                IndexLabel::Int64(10),
25686            ]
25687        );
25688    }
25689
25690    #[test]
25691    fn take_selects_by_position() {
25692        let index = Index::from_i64(vec![10, 20, 30, 40, 50]);
25693        let taken = index.take(&[4, 0, 2]);
25694        assert_eq!(
25695            taken.labels(),
25696            &[
25697                IndexLabel::Int64(50),
25698                IndexLabel::Int64(10),
25699                IndexLabel::Int64(30),
25700            ]
25701        );
25702    }
25703
25704    #[test]
25705    fn int64_take_preserves_typed_backing_without_materializing_vbmsv() {
25706        let index = Index::from_i64_values(vec![10, 20, 30, 40]).set_name("rows");
25707        assert!(index.labels.materialized.get().is_none());
25708
25709        let taken = index.take(&[2, 0, 2]);
25710
25711        assert_eq!(taken.name().map(|n| n.as_str()), Some("rows"));
25712        assert_eq!(taken.labels.int64_view().unwrap().as_slice(), &[30, 10, 30]);
25713        assert!(index.labels.materialized.get().is_none());
25714        assert!(
25715            taken.labels.materialized.get().is_none(),
25716            "typed Int64 take should keep typed output backing"
25717        );
25718    }
25719
25720    #[test]
25721    fn affine_int64_take_gathers_raw_values_without_materializing_vbmsv() {
25722        let index = Index::new_known_unique_int64_affine_range(5, 3, 4)
25723            .unwrap()
25724            .set_name("axis");
25725        assert!(index.labels.materialized.get().is_none());
25726
25727        let taken = index.take(&[3, 1]);
25728
25729        assert_eq!(taken.name().map(|n| n.as_str()), Some("axis"));
25730        assert_eq!(taken.labels.int64_view().unwrap().as_slice(), &[14, 8]);
25731        assert!(index.labels.materialized.get().is_none());
25732        assert!(
25733            taken.labels.materialized.get().is_none(),
25734            "affine Int64 take should gather into typed output backing"
25735        );
25736    }
25737
25738    #[test]
25739    fn slice_extracts_subrange() {
25740        let index = Index::from_i64(vec![10, 20, 30, 40, 50]);
25741        let sliced = index.slice(1, 3);
25742        assert_eq!(
25743            sliced.labels(),
25744            &[
25745                IndexLabel::Int64(20),
25746                IndexLabel::Int64(30),
25747                IndexLabel::Int64(40),
25748            ]
25749        );
25750    }
25751
25752    #[test]
25753    fn slice_of_materialized_index_keeps_shared_label_view() {
25754        let index = Index::new(vec![
25755            IndexLabel::Utf8("a".into()),
25756            IndexLabel::Utf8("b".into()),
25757            IndexLabel::Utf8("c".into()),
25758            IndexLabel::Utf8("d".into()),
25759        ]);
25760        let sliced = index.slice(1, 2);
25761
25762        assert!(sliced.labels.materialized_slice.is_some());
25763        assert!(sliced.labels.materialized.get().is_none());
25764        assert_eq!(
25765            sliced.labels(),
25766            &[IndexLabel::Utf8("b".into()), IndexLabel::Utf8("c".into()),]
25767        );
25768    }
25769
25770    #[test]
25771    fn slice_clamps_to_bounds() {
25772        let index = Index::from_i64(vec![1, 2, 3]);
25773        let sliced = index.slice(1, 100);
25774        assert_eq!(
25775            sliced.labels(),
25776            &[IndexLabel::Int64(2), IndexLabel::Int64(3)]
25777        );
25778    }
25779
25780    #[test]
25781    fn from_range_basic() {
25782        let index = Index::from_range(0, 5, 1);
25783        assert_eq!(
25784            index.labels.int64_affine_range(),
25785            Some(Int64AffineLabels {
25786                start: 0,
25787                step: 1,
25788                len: 5
25789            })
25790        );
25791        assert!(
25792            index.labels.materialized.get().is_none(),
25793            "from_range should keep unit Int64 range labels lazy"
25794        );
25795        assert_eq!(
25796            index.labels(),
25797            &[
25798                IndexLabel::Int64(0),
25799                IndexLabel::Int64(1),
25800                IndexLabel::Int64(2),
25801                IndexLabel::Int64(3),
25802                IndexLabel::Int64(4),
25803            ]
25804        );
25805    }
25806
25807    #[test]
25808    fn from_range_step_2() {
25809        let index = Index::from_range(0, 10, 3);
25810        assert_eq!(
25811            index.labels.int64_affine_range(),
25812            Some(Int64AffineLabels {
25813                start: 0,
25814                step: 3,
25815                len: 4
25816            })
25817        );
25818        assert!(
25819            index.labels.materialized.get().is_none(),
25820            "from_range should keep strided Int64 labels lazy"
25821        );
25822        assert_eq!(
25823            index.labels(),
25824            &[
25825                IndexLabel::Int64(0),
25826                IndexLabel::Int64(3),
25827                IndexLabel::Int64(6),
25828                IndexLabel::Int64(9),
25829            ]
25830        );
25831    }
25832
25833    #[test]
25834    fn from_range_negative_step() {
25835        let index = Index::from_range(5, 0, -2);
25836        assert_eq!(
25837            index.labels.int64_affine_range(),
25838            Some(Int64AffineLabels {
25839                start: 5,
25840                step: -2,
25841                len: 3
25842            })
25843        );
25844        assert!(
25845            index.labels.materialized.get().is_none(),
25846            "from_range should keep descending Int64 labels lazy"
25847        );
25848        assert_eq!(
25849            index.labels(),
25850            &[
25851                IndexLabel::Int64(5),
25852                IndexLabel::Int64(3),
25853                IndexLabel::Int64(1),
25854            ]
25855        );
25856    }
25857
25858    #[test]
25859    fn from_range_empty_when_step_zero() {
25860        let index = Index::from_range(0, 5, 0);
25861        assert_eq!(
25862            index.labels.int64_affine_range(),
25863            Some(Int64AffineLabels {
25864                start: 0,
25865                step: 0,
25866                len: 0
25867            })
25868        );
25869        assert!(
25870            index.labels.materialized.get().is_none(),
25871            "from_range step=0 should keep empty Int64 labels lazy"
25872        );
25873        assert!(index.is_empty());
25874    }
25875
25876    #[test]
25877    fn set_ops_empty_inputs() {
25878        let empty = Index::new(Vec::new());
25879        let non_empty = Index::from_i64(vec![1, 2]);
25880        assert!(empty.intersection(&non_empty).is_empty());
25881        assert_eq!(empty.union_with(&non_empty), non_empty);
25882        assert!(empty.difference(&non_empty).is_empty());
25883        assert_eq!(empty.symmetric_difference(&non_empty), non_empty);
25884    }
25885
25886    #[test]
25887    fn int64_set_ops_match_pandas_reference_c6wel() {
25888        fn labels_i64(index: &Index) -> Vec<i64> {
25889            let mut out = Vec::with_capacity(index.len());
25890            for label in index.labels() {
25891                if let IndexLabel::Int64(value) = label {
25892                    out.push(*value);
25893                } else {
25894                    out.push(i64::MIN);
25895                }
25896            }
25897            out
25898        }
25899
25900        fn intersection_ref(a: &[i64], b: &[i64]) -> Vec<i64> {
25901            let bset: std::collections::BTreeSet<i64> = b.iter().copied().collect();
25902            let mut seen = std::collections::BTreeSet::new();
25903            let mut out = Vec::new();
25904            for &value in a {
25905                if bset.contains(&value) && seen.insert(value) {
25906                    out.push(value);
25907                }
25908            }
25909            out
25910        }
25911
25912        fn union_ref(a: &[i64], b: &[i64]) -> Vec<i64> {
25913            let b_unique = b
25914                .iter()
25915                .copied()
25916                .collect::<std::collections::BTreeSet<_>>()
25917                .len()
25918                == b.len();
25919            if b_unique {
25920                let mut out = a.to_vec();
25921                let mut seen = a.iter().copied().collect::<std::collections::BTreeSet<_>>();
25922                for &value in b {
25923                    if seen.insert(value) {
25924                        out.push(value);
25925                    }
25926                }
25927                return out;
25928            }
25929            let mut counts = std::collections::BTreeMap::<i64, (usize, usize)>::new();
25930            let mut order = Vec::new();
25931            for &value in a {
25932                let entry = counts.entry(value).or_insert((0, 0));
25933                if entry.0 == 0 && entry.1 == 0 {
25934                    order.push(value);
25935                }
25936                entry.0 += 1;
25937            }
25938            for &value in b {
25939                let entry = counts.entry(value).or_insert((0, 0));
25940                if entry.0 == 0 && entry.1 == 0 {
25941                    order.push(value);
25942                }
25943                entry.1 += 1;
25944            }
25945            let mut out = Vec::with_capacity(super::combined_output_capacity(a.len(), b.len()));
25946            for value in order {
25947                let (left_count, right_count) = counts[&value];
25948                out.extend(std::iter::repeat_n(value, left_count.max(right_count)));
25949            }
25950            out
25951        }
25952
25953        fn difference_ref(a: &[i64], b: &[i64]) -> Vec<i64> {
25954            let bset: std::collections::BTreeSet<i64> = b.iter().copied().collect();
25955            let mut seen = std::collections::BTreeSet::new();
25956            let mut out = Vec::new();
25957            for &value in a {
25958                if !bset.contains(&value) && seen.insert(value) {
25959                    out.push(value);
25960                }
25961            }
25962            out
25963        }
25964
25965        fn symmetric_difference_ref(a: &[i64], b: &[i64]) -> Vec<i64> {
25966            let aset: std::collections::BTreeSet<i64> = a.iter().copied().collect();
25967            let bset: std::collections::BTreeSet<i64> = b.iter().copied().collect();
25968            let mut seen = std::collections::BTreeSet::new();
25969            let mut out = Vec::new();
25970            for &value in a {
25971                if !bset.contains(&value) && seen.insert(value) {
25972                    out.push(value);
25973                }
25974            }
25975            for &value in b {
25976                if !aset.contains(&value) && seen.insert(value) {
25977                    out.push(value);
25978                }
25979            }
25980            out
25981        }
25982
25983        let mut state: u64 = 0xc6e1_f157_e700_0001;
25984        let mut next = || {
25985            state = state
25986                .wrapping_mul(6_364_136_223_846_793_005)
25987                .wrapping_add(1_442_695_040_888_963_407);
25988            u32::try_from(state >> 33).unwrap_or(0)
25989        };
25990        let values = |len: usize, next: &mut dyn FnMut() -> u32| {
25991            let mut vals: Vec<i64> = (0..len).map(|_| i64::from(next() % 11) - 5).collect();
25992            match next() % 5 {
25993                0 => vals.sort_unstable(),
25994                1 => vals.sort_unstable_by(|a, b| b.cmp(a)),
25995                2 if vals.len() > 1 => {
25996                    let shift = usize::try_from(next()).unwrap_or(0) % vals.len();
25997                    vals.rotate_left(shift);
25998                }
25999                _ => {}
26000            }
26001            vals
26002        };
26003
26004        for iter in 0..2500u32 {
26005            let a = values(usize::try_from(next() % 15).unwrap_or(0), &mut next);
26006            let b = values(usize::try_from(next() % 15).unwrap_or(0), &mut next);
26007            let ia = Index::from_i64_values(a.clone());
26008            let ib = Index::from_i64_values(b.clone());
26009
26010            assert_eq!(
26011                labels_i64(&ia.intersection(&ib)),
26012                intersection_ref(&a, &b),
26013                "intersection iter={iter} a={a:?} b={b:?}"
26014            );
26015            assert_eq!(
26016                labels_i64(&ia.union_with(&ib)),
26017                union_ref(&a, &b),
26018                "union iter={iter} a={a:?} b={b:?}"
26019            );
26020            assert_eq!(
26021                labels_i64(&ia.difference(&ib)),
26022                difference_ref(&a, &b),
26023                "difference iter={iter} a={a:?} b={b:?}"
26024            );
26025            assert_eq!(
26026                labels_i64(&ia.symmetric_difference(&ib)),
26027                symmetric_difference_ref(&a, &b),
26028                "symmetric_difference iter={iter} a={a:?} b={b:?}"
26029            );
26030        }
26031    }
26032
26033    #[test]
26034    fn unsorted_int64_set_ops_keep_typed_backing_without_materializing_m8x4p() {
26035        let left = Index::from_i64_values(vec![3, 1, 3, 2]).set_name("axis");
26036        let right = Index::from_i64_values(vec![2, 4, 1]).set_name("axis");
26037        assert!(left.labels.materialized.get().is_none());
26038        assert!(right.labels.materialized.get().is_none());
26039
26040        let intersection = left.intersection(&right);
26041        let union = left.union_with(&right);
26042        let difference = left.difference(&right);
26043        let symmetric = left.symmetric_difference(&right);
26044
26045        assert_eq!(intersection.name().map(|n| n.as_str()), Some("axis"));
26046        assert_eq!(union.name().map(|n| n.as_str()), Some("axis"));
26047        assert_eq!(difference.name().map(|n| n.as_str()), Some("axis"));
26048        assert_eq!(symmetric.name().map(|n| n.as_str()), Some("axis"));
26049        assert_eq!(
26050            intersection.labels.int64_view().unwrap().as_slice(),
26051            &[1, 2]
26052        );
26053        assert_eq!(
26054            union.labels.int64_view().unwrap().as_slice(),
26055            &[3, 1, 3, 2, 4],
26056            "pandas preserves the duplicate left occurrence when the right index is unique"
26057        );
26058        assert_ne!(
26059            union.labels.int64_view().unwrap().as_slice(),
26060            &[3, 3, 1, 2, 4],
26061            "negative: grouping left duplicates by label is not pandas union ordering"
26062        );
26063        assert_eq!(difference.labels.int64_view().unwrap().as_slice(), &[3]);
26064        assert_eq!(symmetric.labels.int64_view().unwrap().as_slice(), &[3, 4]);
26065        assert!(
26066            left.labels.materialized.get().is_none(),
26067            "hash Int64 set ops should not materialize the left input"
26068        );
26069        assert!(
26070            right.labels.materialized.get().is_none(),
26071            "hash Int64 set ops should not materialize the right input"
26072        );
26073        for output in [&intersection, &union, &difference, &symmetric] {
26074            assert!(
26075                output.labels.materialized.get().is_none(),
26076                "Int64 set op output should stay typed"
26077            );
26078        }
26079    }
26080
26081    // === AG-11: Leapfrog Triejoin Tests ===
26082
26083    use super::{leapfrog_intersection, leapfrog_union, multi_way_align};
26084
26085    #[test]
26086    fn leapfrog_union_three_indexes() {
26087        let a = Index::from_i64(vec![1, 3, 5]);
26088        let b = Index::from_i64(vec![2, 3, 6]);
26089        let c = Index::from_i64(vec![4, 5, 6]);
26090        let result = leapfrog_union(&[&a, &b, &c]);
26091        assert_eq!(
26092            result.labels(),
26093            &[
26094                IndexLabel::Int64(1),
26095                IndexLabel::Int64(2),
26096                IndexLabel::Int64(3),
26097                IndexLabel::Int64(4),
26098                IndexLabel::Int64(5),
26099                IndexLabel::Int64(6),
26100            ]
26101        );
26102    }
26103
26104    #[test]
26105    fn leapfrog_union_deduplicates() {
26106        let a = Index::from_i64(vec![1, 1, 2]);
26107        let b = Index::from_i64(vec![2, 2, 3]);
26108        let result = leapfrog_union(&[&a, &b]);
26109        assert_eq!(
26110            result.labels(),
26111            &[
26112                IndexLabel::Int64(1),
26113                IndexLabel::Int64(2),
26114                IndexLabel::Int64(3),
26115            ]
26116        );
26117    }
26118
26119    #[test]
26120    fn leapfrog_union_single_index() {
26121        let a = Index::from_i64(vec![3, 1, 2]);
26122        let result = leapfrog_union(&[&a]);
26123        assert_eq!(
26124            result.labels(),
26125            &[
26126                IndexLabel::Int64(1),
26127                IndexLabel::Int64(2),
26128                IndexLabel::Int64(3),
26129            ]
26130        );
26131    }
26132
26133    #[test]
26134    fn leapfrog_union_empty() {
26135        let result = leapfrog_union(&[]);
26136        assert!(result.is_empty());
26137    }
26138
26139    #[test]
26140    fn leapfrog_union_with_empty_input() {
26141        let a = Index::from_i64(vec![1, 2]);
26142        let b = Index::new(Vec::new());
26143        let result = leapfrog_union(&[&a, &b]);
26144        assert_eq!(
26145            result.labels(),
26146            &[IndexLabel::Int64(1), IndexLabel::Int64(2)]
26147        );
26148    }
26149
26150    #[test]
26151    fn leapfrog_intersection_three_indexes() {
26152        let a = Index::from_i64(vec![1, 2, 3, 4, 5]);
26153        let b = Index::from_i64(vec![2, 3, 5, 7]);
26154        let c = Index::from_i64(vec![3, 5, 8]);
26155        let result = leapfrog_intersection(&[&a, &b, &c]);
26156        assert_eq!(
26157            result.labels(),
26158            &[IndexLabel::Int64(3), IndexLabel::Int64(5)]
26159        );
26160    }
26161
26162    #[test]
26163    fn leapfrog_intersection_disjoint() {
26164        let a = Index::from_i64(vec![1, 2]);
26165        let b = Index::from_i64(vec![3, 4]);
26166        let result = leapfrog_intersection(&[&a, &b]);
26167        assert!(result.is_empty());
26168    }
26169
26170    #[test]
26171    fn leapfrog_intersection_identical() {
26172        let a = Index::from_i64(vec![1, 2, 3]);
26173        let b = Index::from_i64(vec![1, 2, 3]);
26174        let result = leapfrog_intersection(&[&a, &b]);
26175        assert_eq!(
26176            result.labels(),
26177            &[
26178                IndexLabel::Int64(1),
26179                IndexLabel::Int64(2),
26180                IndexLabel::Int64(3),
26181            ]
26182        );
26183    }
26184
26185    #[test]
26186    fn leapfrog_intersection_with_unsorted_input() {
26187        let a = Index::from_i64(vec![5, 3, 1, 4, 2]);
26188        let b = Index::from_i64(vec![4, 2, 6, 1]);
26189        let result = leapfrog_intersection(&[&a, &b]);
26190        assert_eq!(
26191            result.labels(),
26192            &[
26193                IndexLabel::Int64(1),
26194                IndexLabel::Int64(2),
26195                IndexLabel::Int64(4),
26196            ]
26197        );
26198    }
26199
26200    #[test]
26201    fn leapfrog_intersection_empty_input() {
26202        let a = Index::from_i64(vec![1, 2, 3]);
26203        let b = Index::new(Vec::new());
26204        let result = leapfrog_intersection(&[&a, &b]);
26205        assert!(result.is_empty());
26206    }
26207
26208    #[test]
26209    fn multi_way_align_three_indexes() {
26210        let a = Index::from_i64(vec![1, 3]);
26211        let b = Index::from_i64(vec![2, 3]);
26212        let c = Index::from_i64(vec![1, 2]);
26213        assert_eq!(
26214            super::aggregate_output_capacity([a.len(), b.len(), c.len()]),
26215            6
26216        );
26217        let plan = multi_way_align(&[&a, &b, &c]);
26218        assert_eq!(
26219            plan.union_index.labels(),
26220            &[
26221                IndexLabel::Int64(1),
26222                IndexLabel::Int64(3),
26223                IndexLabel::Int64(2),
26224            ]
26225        );
26226        assert_eq!(plan.positions.len(), 3);
26227        // a has 1 at pos 0, 3 at pos 1, no 2
26228        assert_eq!(plan.positions[0], vec![Some(0), Some(1), None]);
26229        // b has no 1, 3 at pos 1, 2 at pos 0
26230        assert_eq!(plan.positions[1], vec![None, Some(1), Some(0)]);
26231        // c has 1 at pos 0, no 3, 2 at pos 1
26232        assert_eq!(plan.positions[2], vec![Some(0), None, Some(1)]);
26233    }
26234
26235    #[test]
26236    fn multi_way_align_deduplicates_repeated_labels_uza04186() {
26237        let a = Index::from_i64(vec![1, 1, 3]);
26238        let b = Index::from_i64(vec![3, 2, 2]);
26239
26240        let plan = multi_way_align(&[&a, &b]);
26241
26242        assert_eq!(
26243            plan.union_index.labels(),
26244            &[
26245                IndexLabel::Int64(1),
26246                IndexLabel::Int64(3),
26247                IndexLabel::Int64(2)
26248            ]
26249        );
26250        assert_eq!(plan.positions[0], vec![Some(0), Some(2), None]);
26251        assert_eq!(plan.positions[1], vec![None, Some(0), Some(1)]);
26252    }
26253
26254    #[test]
26255    fn multi_way_align_empty() {
26256        let plan = multi_way_align(&[]);
26257        assert!(plan.union_index.is_empty());
26258        assert!(plan.positions.is_empty());
26259    }
26260
26261    #[test]
26262    fn multi_way_align_isomorphic_with_pairwise() {
26263        // AG-11 contract: multi-way union produces same label set as
26264        // iterative pairwise union (associativity + commutativity).
26265        let a = Index::from_i64(vec![1, 4, 7]);
26266        let b = Index::from_i64(vec![2, 4, 8]);
26267        let c = Index::from_i64(vec![3, 7, 8]);
26268
26269        let multi = leapfrog_union(&[&a, &b, &c]);
26270
26271        // Iterative pairwise
26272        let ab = a.union_with(&b);
26273        let abc = ab.union_with(&c);
26274        let pairwise = abc.sort_values();
26275
26276        assert_eq!(multi.labels(), pairwise.labels());
26277    }
26278
26279    #[test]
26280    fn leapfrog_union_utf8_labels() {
26281        let a = Index::new(vec!["c".into(), "a".into()]);
26282        let b = Index::new(vec!["b".into(), "d".into()]);
26283        let result = leapfrog_union(&[&a, &b]);
26284        assert_eq!(
26285            result.labels(),
26286            &["a".into(), "b".into(), "c".into(), "d".into()]
26287        );
26288    }
26289
26290    #[test]
26291    fn leapfrog_large_multi_way() {
26292        // 5 indexes, each 1000 labels, overlapping ranges
26293        let indexes: Vec<Index> = (0..5)
26294            .map(|i| {
26295                let start = i * 200;
26296                let end = start + 1000;
26297                Index::from_i64((start..end).collect())
26298            })
26299            .collect();
26300        let refs: Vec<&Index> = indexes.iter().collect();
26301
26302        let union = leapfrog_union(&refs);
26303        // Range is 0..1800 (0-999, 200-1199, 400-1399, 600-1599, 800-1799)
26304        assert_eq!(union.len(), 1800);
26305
26306        let intersection = leapfrog_intersection(&refs);
26307        // Intersection is 800..999 (all 5 overlap)
26308        assert_eq!(intersection.len(), 200);
26309    }
26310
26311    // === AG-11-T: Full test plan (bd-2t5e.17) ===
26312
26313    #[test]
26314    fn ag11t_two_sorted_identical() {
26315        let a = Index::from_i64(vec![1, 2, 3]);
26316        let b = Index::from_i64(vec![1, 2, 3]);
26317        let result = leapfrog_union(&[&a, &b]);
26318        assert_eq!(
26319            result.labels(),
26320            &[
26321                IndexLabel::Int64(1),
26322                IndexLabel::Int64(2),
26323                IndexLabel::Int64(3)
26324            ]
26325        );
26326        let plan = multi_way_align(&[&a, &b]);
26327        // Both map to identity positions
26328        assert_eq!(plan.positions[0], vec![Some(0), Some(1), Some(2)]);
26329        assert_eq!(plan.positions[1], vec![Some(0), Some(1), Some(2)]);
26330        eprintln!("[AG-11-T] two_sorted_identical | in=[3,3] out=3 | PASS");
26331    }
26332
26333    #[test]
26334    fn ag11t_two_sorted_disjoint() {
26335        let a = Index::from_i64(vec![1, 2, 3]);
26336        let b = Index::from_i64(vec![4, 5, 6]);
26337        let result = leapfrog_union(&[&a, &b]);
26338        assert_eq!(result.len(), 6);
26339        assert_eq!(result.labels()[0], IndexLabel::Int64(1));
26340        assert_eq!(result.labels()[5], IndexLabel::Int64(6));
26341        eprintln!("[AG-11-T] two_sorted_disjoint | in=[3,3] out=6 | PASS");
26342    }
26343
26344    #[test]
26345    fn ag11t_two_sorted_overlapping_with_positions() {
26346        let a = Index::from_i64(vec![1, 3, 5]);
26347        let b = Index::from_i64(vec![2, 3, 4]);
26348        let plan = multi_way_align(&[&a, &b]);
26349        assert_eq!(
26350            plan.union_index.labels(),
26351            &[
26352                IndexLabel::Int64(1),
26353                IndexLabel::Int64(3),
26354                IndexLabel::Int64(5),
26355                IndexLabel::Int64(2),
26356                IndexLabel::Int64(4),
26357            ]
26358        );
26359        assert_eq!(
26360            plan.positions[0],
26361            vec![Some(0), Some(1), Some(2), None, None]
26362        );
26363        assert_eq!(
26364            plan.positions[1],
26365            vec![None, Some(1), None, Some(0), Some(2)]
26366        );
26367        eprintln!("[AG-11-T] two_sorted_overlapping | in=[3,3] out=5 | PASS");
26368    }
26369
26370    #[test]
26371    fn ag11t_five_way_union_vs_pairwise() {
26372        let indexes: Vec<Index> = (0..5)
26373            .map(|i| Index::from_i64(vec![i * 10, i * 10 + 1, i * 10 + 2]))
26374            .collect();
26375        let refs: Vec<&Index> = indexes.iter().collect();
26376
26377        let leapfrog = leapfrog_union(&refs);
26378
26379        // Iterative pairwise
26380        let mut pairwise = indexes[0].clone();
26381        for idx in &indexes[1..] {
26382            pairwise = pairwise.union_with(idx);
26383        }
26384        let pairwise = pairwise.sort_values();
26385
26386        assert_eq!(leapfrog.labels(), pairwise.labels());
26387        eprintln!(
26388            "[AG-11-T] five_way_union_vs_pairwise | in=[3x5] out={} | PASS",
26389            leapfrog.len()
26390        );
26391    }
26392
26393    #[test]
26394    fn ag11t_single_element_indexes() {
26395        let indexes: Vec<Index> = (0..10).map(|i| Index::from_i64(vec![i])).collect();
26396        let refs: Vec<&Index> = indexes.iter().collect();
26397        let result = leapfrog_union(&refs);
26398        assert_eq!(result.len(), 10);
26399        for (i, label) in result.labels().iter().enumerate() {
26400            assert_eq!(*label, IndexLabel::Int64(i as i64));
26401        }
26402        eprintln!("[AG-11-T] single_element_indexes | in=[1x10] out=10 | PASS");
26403    }
26404
26405    #[test]
26406    fn ag11t_all_same_labels() {
26407        let base = Index::from_i64(vec![1, 2, 3]);
26408        let refs: Vec<&Index> = (0..5).map(|_| &base).collect();
26409        let plan = multi_way_align(&refs);
26410        assert_eq!(
26411            plan.union_index.labels(),
26412            &[
26413                IndexLabel::Int64(1),
26414                IndexLabel::Int64(2),
26415                IndexLabel::Int64(3)
26416            ]
26417        );
26418        // All 5 inputs should have identity positions
26419        for pos_vec in &plan.positions {
26420            assert_eq!(*pos_vec, vec![Some(0), Some(1), Some(2)]);
26421        }
26422        eprintln!("[AG-11-T] all_same_labels | in=[3x5] out=3 | PASS");
26423    }
26424
26425    #[test]
26426    fn ag11t_iso_associativity() {
26427        let a = Index::from_i64(vec![1, 4, 7, 10]);
26428        let b = Index::from_i64(vec![2, 4, 8, 10]);
26429        let c = Index::from_i64(vec![3, 7, 8, 10]);
26430
26431        let leapfrog_result = leapfrog_union(&[&a, &b, &c]);
26432
26433        // union(A, union(B, C))
26434        let bc = b.union_with(&c).sort_values();
26435        let a_bc = a.union_with(&bc).sort_values();
26436
26437        // union(union(A, B), C)
26438        let ab = a.union_with(&b).sort_values();
26439        let ab_c = ab.union_with(&c).sort_values();
26440
26441        assert_eq!(leapfrog_result.labels(), a_bc.labels());
26442        assert_eq!(leapfrog_result.labels(), ab_c.labels());
26443        eprintln!("[AG-11-T] iso_associativity | verified | PASS");
26444    }
26445
26446    #[test]
26447    fn ag11t_iso_commutativity() {
26448        let a = Index::from_i64(vec![1, 5, 9]);
26449        let b = Index::from_i64(vec![2, 5, 8]);
26450        let c = Index::from_i64(vec![3, 5, 7]);
26451
26452        let abc = leapfrog_union(&[&a, &b, &c]);
26453        let cab = leapfrog_union(&[&c, &a, &b]);
26454        let bca = leapfrog_union(&[&b, &c, &a]);
26455
26456        // All orderings produce same sorted output
26457        assert_eq!(abc.labels(), cab.labels());
26458        assert_eq!(abc.labels(), bca.labels());
26459        eprintln!("[AG-11-T] iso_commutativity | verified | PASS");
26460    }
26461
26462    // ── Index: min/max/argmin/argmax ──
26463
26464    #[test]
26465    fn index_min_max_int() {
26466        let idx = Index::new(vec![3_i64.into(), 1_i64.into(), 2_i64.into()]);
26467        assert_eq!(idx.min(), Some(IndexLabel::Int64(1)));
26468        assert_eq!(idx.max(), Some(IndexLabel::Int64(3)));
26469        assert_eq!(idx.argmin(), Some(1));
26470        assert_eq!(idx.argmax(), Some(0));
26471    }
26472
26473    #[test]
26474    fn index_min_max_utf8() {
26475        let idx = Index::new(vec!["c".into(), "a".into(), "b".into()]);
26476        assert_eq!(idx.min(), Some(IndexLabel::Utf8("a".into())));
26477        assert_eq!(idx.max(), Some(IndexLabel::Utf8("c".into())));
26478        assert_eq!(idx.argmin(), Some(1));
26479        assert_eq!(idx.argmax(), Some(0));
26480    }
26481
26482    #[test]
26483    fn index_min_max_empty() {
26484        let idx = Index::new(vec![]);
26485        assert_eq!(idx.min(), None);
26486        assert_eq!(idx.max(), None);
26487        assert_eq!(idx.argmin(), None);
26488        assert_eq!(idx.argmax(), None);
26489    }
26490
26491    #[test]
26492    fn index_nunique() {
26493        let idx = Index::new(vec![1_i64.into(), 2_i64.into(), 1_i64.into()]);
26494        assert_eq!(idx.nunique(), 2);
26495    }
26496
26497    #[test]
26498    fn typed_int64_nunique_counts_without_label_materialization_codb() {
26499        let index = Index::from_i64_values(vec![3, 1, 3, 2, 1, 4]).set_name("row");
26500        assert!(index.labels.materialized.get().is_none());
26501
26502        assert_eq!(index.nunique(), 4);
26503        assert_eq!(index.nunique_with_dropna(false), 4);
26504        assert!(
26505            index.labels.materialized.get().is_none(),
26506            "typed Int64 nunique should count raw values without materializing labels"
26507        );
26508
26509        let materialized = Index::new(vec![
26510            IndexLabel::Int64(3),
26511            IndexLabel::Int64(1),
26512            IndexLabel::Int64(3),
26513            IndexLabel::Int64(2),
26514            IndexLabel::Int64(1),
26515            IndexLabel::Int64(4),
26516        ]);
26517        assert_eq!(index.nunique(), materialized.nunique());
26518        assert_eq!(
26519            index.nunique_with_dropna(false),
26520            materialized.nunique_with_dropna(false)
26521        );
26522    }
26523
26524    #[test]
26525    fn sparse_int64_nunique_counts_without_label_materialization_codb() {
26526        let index = Index::from_i64_values(vec![0, 1_000_000, -500_000, 0, 1_000_000]);
26527        assert!(index.labels.materialized.get().is_none());
26528
26529        assert_eq!(index.nunique(), 3);
26530        assert_eq!(index.nunique_with_dropna(false), 3);
26531        assert!(
26532            index.labels.materialized.get().is_none(),
26533            "wide-span Int64 nunique should use raw hash keys without materializing labels"
26534        );
26535    }
26536
26537    #[test]
26538    fn index_nunique_dropna_false_counts_timedelta_nat_once() {
26539        let idx = Index::from_timedelta64(vec![Timedelta::NAT, Timedelta::NAT, 5]);
26540        assert_eq!(idx.nunique(), 1);
26541        assert_eq!(idx.nunique_with_dropna(false), 2);
26542    }
26543
26544    #[test]
26545    fn index_nunique_dropna_false_counts_datetime_nat_once() {
26546        let idx = Index::new(vec![
26547            IndexLabel::Datetime64(i64::MIN),
26548            IndexLabel::Datetime64(i64::MIN),
26549            IndexLabel::Datetime64(1_700_000_000_000_000_000),
26550        ]);
26551        assert_eq!(idx.nunique(), 1);
26552        assert_eq!(idx.nunique_with_dropna(false), 2);
26553    }
26554
26555    // ── Index: map/rename/drop/astype ──
26556
26557    #[test]
26558    fn index_map() {
26559        let idx = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
26560        let mapped = idx.map(|l| match l {
26561            IndexLabel::Int64(v) => IndexLabel::Int64(v * 10),
26562            other => other.clone(),
26563        });
26564        assert_eq!(mapped.labels()[0], IndexLabel::Int64(10));
26565        assert_eq!(mapped.labels()[2], IndexLabel::Int64(30));
26566    }
26567
26568    #[test]
26569    fn index_drop_labels() {
26570        let idx = Index::new(vec!["a".into(), "b".into(), "c".into()]);
26571        let dropped = idx.drop_labels(&["b".into()]);
26572        assert_eq!(dropped.len(), 2);
26573        assert_eq!(dropped.labels()[0], IndexLabel::Utf8("a".into()));
26574        assert_eq!(dropped.labels()[1], IndexLabel::Utf8("c".into()));
26575    }
26576
26577    #[test]
26578    fn float_index_dedups_through_spread_keys_bss5q3() {
26579        // br-frankenpandas-bss5q.3: a float index's duplicated / unique /
26580        // drop_duplicates run through the i64 masks over its spread canonical
26581        // bits - -0.0 one label with 0.0, every NaN one label, each keep
26582        // mode as pandas answers it. NEGATIVE: a Float64 beside an Int64
26583        // label gives no float keys (the label map answers).
26584        let float = |value: f64| IndexLabel::Float64(OrderedF64(value));
26585        let index = crate::Index::new(vec![
26586            float(3.0),
26587            float(-0.0),
26588            float(f64::NAN),
26589            float(0.0),
26590            float(3.0),
26591            float(f64::NAN),
26592            float(1024.0),
26593        ]);
26594        assert_eq!(
26595            index.duplicated(crate::DuplicateKeep::First),
26596            vec![false, false, false, true, true, true, false]
26597        );
26598        assert_eq!(
26599            index.duplicated(crate::DuplicateKeep::Last),
26600            vec![true, true, true, false, false, false, false]
26601        );
26602        assert_eq!(
26603            index.duplicated(crate::DuplicateKeep::None),
26604            vec![true, true, true, true, true, true, false]
26605        );
26606        let unique = index.unique();
26607        assert_eq!(unique.len(), 4);
26608        assert_eq!(unique.labels()[1], float(-0.0));
26609        assert_eq!(
26610            index.drop_duplicates_keep(crate::DuplicateKeep::None).len(),
26611            1
26612        );
26613        let mixed = crate::Index::new(vec![float(1.0), IndexLabel::Int64(1)]);
26614        assert!(mixed.float_label_keys().is_none());
26615    }
26616
26617    #[test]
26618    fn generic_drop_labels_hash_preserves_mixed_identity_arboe() {
26619        let labels = vec![
26620            IndexLabel::Utf8("duplicate".into()),
26621            IndexLabel::Int64(7),
26622            IndexLabel::Float64(OrderedF64(f64::NAN)),
26623            IndexLabel::Float64(OrderedF64(-0.0)),
26624            IndexLabel::Float64(OrderedF64(0.0)),
26625            IndexLabel::Bool(true),
26626            IndexLabel::Datetime64(i64::MIN),
26627            IndexLabel::Timedelta64(Timedelta::NAT),
26628            IndexLabel::Null(fp_types::NullKind::Null),
26629            IndexLabel::Utf8("duplicate".into()),
26630            IndexLabel::Utf8("keep".into()),
26631        ];
26632        let drops = vec![
26633            IndexLabel::Utf8("duplicate".into()),
26634            IndexLabel::Float64(OrderedF64(f64::from_bits(0x7ff8_0000_0000_0001))),
26635            IndexLabel::Float64(OrderedF64(0.0)),
26636            IndexLabel::Datetime64(i64::MIN),
26637            IndexLabel::Null(fp_types::NullKind::NaN),
26638            IndexLabel::Utf8("absent".into()),
26639            IndexLabel::Int64(999),
26640            IndexLabel::Bool(false),
26641            IndexLabel::Timedelta64(123),
26642        ];
26643        let expected = labels
26644            .iter()
26645            .filter(|label| !drops.contains(label))
26646            .cloned()
26647            .collect::<Vec<_>>();
26648
26649        let dropped = Index::new(labels).set_name("mixed").drop_labels(&drops);
26650
26651        assert_eq!(dropped.labels(), expected.as_slice());
26652        assert_eq!(dropped.name().map(|n| n.as_str()), Some("mixed"));
26653    }
26654
26655    #[test]
26656    #[ignore = "foreground profile-first A/B"]
26657    fn generic_drop_labels_hash_profile_arboe() {
26658        use std::{hint::black_box, time::Instant};
26659
26660        fn former(input: &Index, drops: &[IndexLabel]) -> Index {
26661            let kept = input
26662                .labels
26663                .iter()
26664                .filter(|label| !drops.contains(label))
26665                .cloned()
26666                .collect();
26667            input.propagate_name(Index::new(kept))
26668        }
26669
26670        fn candidate(input: &Index, drops: &[IndexLabel]) -> Index {
26671            input.drop_labels(drops)
26672        }
26673
26674        fn elapsed(
26675            input: &Index,
26676            drops: &[IndexLabel],
26677            dropper: fn(&Index, &[IndexLabel]) -> Index,
26678        ) -> u128 {
26679            let started = Instant::now();
26680            let output = dropper(black_box(input), black_box(drops));
26681            black_box(&output);
26682            let elapsed = started.elapsed().as_nanos();
26683            black_box(output);
26684            elapsed
26685        }
26686
26687        fn samples(input: &Index, drops: &[IndexLabel]) -> (Vec<u128>, Vec<u128>) {
26688            const SAMPLES: usize = 12;
26689            for _ in 0..2 {
26690                black_box(elapsed(input, drops, former));
26691                black_box(elapsed(input, drops, candidate));
26692            }
26693            let mut former_ns = Vec::with_capacity(SAMPLES);
26694            let mut candidate_ns = Vec::with_capacity(SAMPLES);
26695            for sample in 0..SAMPLES {
26696                if sample % 2 == 0 {
26697                    former_ns.push(elapsed(input, drops, former));
26698                    candidate_ns.push(elapsed(input, drops, candidate));
26699                } else {
26700                    candidate_ns.push(elapsed(input, drops, candidate));
26701                    former_ns.push(elapsed(input, drops, former));
26702                }
26703            }
26704            (former_ns, candidate_ns)
26705        }
26706
26707        fn percentile(samples: &[u128], percent: usize) -> u128 {
26708            let mut sorted = samples.to_vec();
26709            sorted.sort_unstable();
26710            let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
26711            sorted[rank]
26712        }
26713
26714        let parity_input = vec![
26715            IndexLabel::Utf8("a".into()),
26716            IndexLabel::Int64(7),
26717            IndexLabel::Float64(OrderedF64(f64::NAN)),
26718            IndexLabel::Float64(OrderedF64(-0.0)),
26719            IndexLabel::Float64(OrderedF64(0.0)),
26720            IndexLabel::Bool(true),
26721            IndexLabel::Datetime64(i64::MIN),
26722            IndexLabel::Timedelta64(Timedelta::NAT),
26723            IndexLabel::Null(fp_types::NullKind::Null),
26724            IndexLabel::Utf8("a".into()),
26725        ];
26726        let parity_drops = vec![
26727            IndexLabel::Utf8("a".into()),
26728            IndexLabel::Float64(OrderedF64(f64::from_bits(0x7ff8_0000_0000_0001))),
26729            IndexLabel::Float64(OrderedF64(0.0)),
26730            IndexLabel::Datetime64(i64::MIN),
26731            IndexLabel::Null(fp_types::NullKind::NaN),
26732            IndexLabel::Utf8("absent".into()),
26733            IndexLabel::Int64(999),
26734            IndexLabel::Bool(false),
26735            IndexLabel::Timedelta64(123),
26736        ];
26737        let parity_input = Index::new(parity_input).set_name("mixed");
26738        let expected = former(&parity_input, &parity_drops);
26739        let actual = candidate(&parity_input, &parity_drops);
26740        assert_eq!(actual.labels(), expected.labels());
26741        assert_eq!(actual.name(), expected.name());
26742
26743        const ROWS: usize = 16_384;
26744        const DROP_COUNT: usize = 4_096;
26745        let input = Index::new(
26746            (0..ROWS)
26747                .map(|index| IndexLabel::Utf8(format!("key-{:08}", index % (ROWS / 2))))
26748                .collect::<Vec<_>>(),
26749        )
26750        .set_name("bench");
26751        let large_drops = (0..DROP_COUNT)
26752            .map(|index| IndexLabel::Utf8(format!("key-{:08}", index * 2)))
26753            .collect::<Vec<_>>();
26754        let small_drops = large_drops[..4].to_vec();
26755        let large_expected = former(&input, &large_drops);
26756        let large_actual = candidate(&input, &large_drops);
26757        assert_eq!(large_actual.labels(), large_expected.labels());
26758        assert_eq!(large_actual.name(), large_expected.name());
26759        let small_expected = former(&input, &small_drops);
26760        let small_actual = candidate(&input, &small_drops);
26761        assert_eq!(small_actual.labels(), small_expected.labels());
26762        assert_eq!(small_actual.name(), small_expected.name());
26763
26764        let (large_former, large_candidate) = samples(&input, &large_drops);
26765        let (small_former, small_candidate) = samples(&input, &small_drops);
26766        let large_former_p50 = percentile(&large_former, 50);
26767        let large_former_p95 = percentile(&large_former, 95);
26768        let large_former_p99 = percentile(&large_former, 99);
26769        let large_candidate_p50 = percentile(&large_candidate, 50);
26770        let large_candidate_p95 = percentile(&large_candidate, 95);
26771        let large_candidate_p99 = percentile(&large_candidate, 99);
26772        let small_former_p50 = percentile(&small_former, 50);
26773        let small_candidate_p50 = percentile(&small_candidate, 50);
26774        println!(
26775            "GENERIC_DROP_HASH rows={ROWS} drops={DROP_COUNT} former_p50_ns={large_former_p50} candidate_p50_ns={large_candidate_p50} speedup_p50={:.6} former_p95_ns={large_former_p95} candidate_p95_ns={large_candidate_p95} speedup_p95={:.6} former_p99_ns={large_former_p99} candidate_p99_ns={large_candidate_p99} speedup_p99={:.6} small_drops=4 small_former_p50_ns={small_former_p50} small_candidate_p50_ns={small_candidate_p50} small_speedup_p50={:.6} former_samples={large_former:?} candidate_samples={large_candidate:?} small_former_samples={small_former:?} small_candidate_samples={small_candidate:?}",
26776            large_former_p50 as f64 / large_candidate_p50 as f64,
26777            large_former_p95 as f64 / large_candidate_p95 as f64,
26778            large_former_p99 as f64 / large_candidate_p99 as f64,
26779            small_former_p50 as f64 / small_candidate_p50 as f64,
26780        );
26781    }
26782
26783    #[test]
26784    fn int64_drop_labels_preserves_typed_backing_codb() {
26785        let index = Index::from_i64_values(vec![1, 2, 1, 3, 4]).set_name("row");
26786        assert!(index.labels.materialized.get().is_none());
26787
26788        let dropped = index.drop_labels(&[IndexLabel::Int64(1), IndexLabel::Utf8("1".into())]);
26789
26790        assert_eq!(dropped.name().map(|n| n.as_str()), Some("row"));
26791        assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[2, 3, 4]);
26792        assert!(index.labels.materialized.get().is_none());
26793        assert!(
26794            dropped.labels.materialized.get().is_none(),
26795            "typed Int64 drop_labels should keep typed output backing"
26796        );
26797
26798        let materialized = Index::new(vec![
26799            IndexLabel::Int64(1),
26800            IndexLabel::Int64(2),
26801            IndexLabel::Int64(1),
26802            IndexLabel::Int64(3),
26803            IndexLabel::Int64(4),
26804        ]);
26805        assert_eq!(
26806            dropped.labels(),
26807            materialized
26808                .drop_labels(&[IndexLabel::Int64(1), IndexLabel::Utf8("1".into())])
26809                .labels()
26810        );
26811    }
26812
26813    #[test]
26814    fn sorted_int64_drop_labels_preserves_typed_backing_codb() {
26815        let index = Index::from_i64_values(vec![0, 1, 1, 2, 3, 4, 5, 6]).set_name("row");
26816        assert!(index.labels.materialized.get().is_none());
26817
26818        let dropped = index.drop_labels(&[
26819            IndexLabel::Int64(4),
26820            IndexLabel::Int64(1),
26821            IndexLabel::Int64(100),
26822            IndexLabel::Utf8("2".into()),
26823        ]);
26824
26825        assert_eq!(dropped.name().map(|n| n.as_str()), Some("row"));
26826        assert_eq!(
26827            dropped.labels.int64_view().unwrap().as_slice(),
26828            &[0, 2, 3, 5, 6]
26829        );
26830        assert!(index.labels.materialized.get().is_none());
26831        assert!(
26832            dropped.labels.materialized.get().is_none(),
26833            "sorted Int64 drop_labels should keep typed output backing"
26834        );
26835    }
26836
26837    #[test]
26838    fn affine_int64_drop_labels_preserves_typed_backing_codb() {
26839        let index = Index::new_known_unique_int64_affine_range(10, -2, 5)
26840            .unwrap()
26841            .set_name("axis");
26842        assert!(index.labels.materialized.get().is_none());
26843
26844        let dropped = index.drop_labels(&[IndexLabel::Int64(8), IndexLabel::Int64(2)]);
26845
26846        assert_eq!(dropped.name().map(|n| n.as_str()), Some("axis"));
26847        assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[10, 6, 4]);
26848        assert!(index.labels.materialized.get().is_none());
26849        assert!(
26850            dropped.labels.materialized.get().is_none(),
26851            "affine Int64 drop_labels should gather raw values into typed output"
26852        );
26853    }
26854
26855    #[test]
26856    fn index_astype_str() {
26857        let idx = Index::new(vec![1_i64.into(), 2_i64.into()]);
26858        let str_idx = idx.astype_str();
26859        assert_eq!(str_idx.labels()[0], IndexLabel::Utf8("1".into()));
26860        assert_eq!(str_idx.labels()[1], IndexLabel::Utf8("2".into()));
26861    }
26862
26863    #[test]
26864    fn typed_int64_astype_str_avoids_source_materialization_codb() {
26865        let index = Index::from_i64_values(vec![7, -5, 0]).set_name("row");
26866        assert!(index.labels.materialized.get().is_none());
26867
26868        let str_idx = index.astype_str();
26869
26870        assert_eq!(str_idx.name().map(|n| n.as_str()), Some("row"));
26871        assert_eq!(
26872            str_idx.labels(),
26873            &[
26874                IndexLabel::Utf8("7".into()),
26875                IndexLabel::Utf8("-5".into()),
26876                IndexLabel::Utf8("0".into()),
26877            ]
26878        );
26879        assert!(
26880            index.labels.materialized.get().is_none(),
26881            "astype_str should stringify raw Int64 values without materializing source labels"
26882        );
26883
26884        let materialized = Index::new(vec![
26885            IndexLabel::Int64(7),
26886            IndexLabel::Int64(-5),
26887            IndexLabel::Int64(0),
26888        ])
26889        .set_name("row");
26890        assert_eq!(str_idx.labels(), materialized.astype_str().labels());
26891    }
26892
26893    #[test]
26894    fn affine_int64_astype_str_avoids_source_materialization_codb() {
26895        let index = Index::new_known_unique_int64_affine_range(4, -3, 3)
26896            .unwrap()
26897            .set_name("axis");
26898        assert!(index.labels.materialized.get().is_none());
26899
26900        let str_idx = index.astype_str();
26901
26902        assert_eq!(str_idx.name().map(|n| n.as_str()), Some("axis"));
26903        assert_eq!(
26904            str_idx.labels(),
26905            &[
26906                IndexLabel::Utf8("4".into()),
26907                IndexLabel::Utf8("1".into()),
26908                IndexLabel::Utf8("-2".into()),
26909            ]
26910        );
26911        assert!(
26912            index.labels.materialized.get().is_none(),
26913            "affine astype_str should not materialize source labels"
26914        );
26915    }
26916
26917    #[test]
26918    fn index_astype_int() {
26919        let idx = Index::new(vec![
26920            IndexLabel::Utf8("10".into()),
26921            IndexLabel::Utf8("20".into()),
26922        ]);
26923        let int_idx = idx.astype_int();
26924        assert_eq!(int_idx.labels()[0], IndexLabel::Int64(10));
26925        assert_eq!(int_idx.labels()[1], IndexLabel::Int64(20));
26926    }
26927
26928    /// pandas 2.2.3: Index([1, 2]).astype('float64') -> Index([1.0, 2.0],
26929    /// dtype='float64'); astype(bool) -> [True, False] for [3, 0]; a
26930    /// non-numeric string refuses the float cast. Index.astype used to accept
26931    /// only int/str (and the binding ignored the dtype altogether). (fvsao.4)
26932    #[test]
26933    fn index_astype_float_and_bool_fvsao4() {
26934        let ints = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Int64(2)]).set_name("n");
26935        let floats = ints.astype("float64").expect("float cast");
26936        assert_eq!(
26937            floats.labels(),
26938            &[
26939                IndexLabel::Float64(OrderedF64(1.0)),
26940                IndexLabel::Float64(OrderedF64(2.0))
26941            ]
26942        );
26943        assert_eq!(floats.dtype(), "float64");
26944        assert_eq!(floats.name().map(|n| n.as_str()), Some("n"));
26945        let flags = Index::new(vec![IndexLabel::Int64(3), IndexLabel::Int64(0)])
26946            .astype("bool")
26947            .expect("bool cast");
26948        assert_eq!(
26949            flags.labels(),
26950            &[IndexLabel::Bool(true), IndexLabel::Bool(false)]
26951        );
26952        assert_eq!(flags.dtype(), "bool");
26953        assert!(
26954            Index::new(vec![IndexLabel::Utf8("x".into())])
26955                .astype("float64")
26956                .is_err()
26957        );
26958        assert!(
26959            Index::new(vec![IndexLabel::Datetime64(0)])
26960                .astype("float64")
26961                .is_err()
26962        );
26963    }
26964
26965    #[test]
26966    fn typed_int64_astype_int_avoids_label_materialization_ntqtf() {
26967        let index = Index::from_i64_values(vec![7, 5, 7]).set_name("rows");
26968        assert!(index.labels.materialized.get().is_none());
26969
26970        let cast = index.astype_int();
26971
26972        assert_eq!(cast.name().map(|n| n.as_str()), Some("rows"));
26973        assert_eq!(cast.labels.int64_view().unwrap().as_slice(), &[7, 5, 7]);
26974        assert!(index.labels.materialized.get().is_none());
26975        assert!(
26976            cast.labels.materialized.get().is_none(),
26977            "already-Int64 astype_int should keep typed output backing"
26978        );
26979    }
26980
26981    #[test]
26982    fn affine_int64_astype_int_avoids_label_materialization_ntqtf() {
26983        let index = Index::new_known_unique_int64_affine_range(2, 4, 3)
26984            .unwrap()
26985            .set_name("axis");
26986        assert!(index.labels.materialized.get().is_none());
26987
26988        let cast = index.astype_int();
26989
26990        assert_eq!(cast.name().map(|n| n.as_str()), Some("axis"));
26991        assert_eq!(cast.labels.int64_view().unwrap().as_slice(), &[2, 6, 10]);
26992        assert!(index.labels.materialized.get().is_none());
26993        assert!(
26994            cast.labels.materialized.get().is_none(),
26995            "affine Int64 astype_int should keep typed output backing"
26996        );
26997    }
26998
26999    #[test]
27000    fn index_isna_notna() {
27001        let idx = Index::new(vec![1_i64.into(), 2_i64.into()]);
27002        assert_eq!(idx.isna(), vec![false, false]);
27003        assert_eq!(idx.notna(), vec![true, true]);
27004    }
27005
27006    #[test]
27007    fn typed_int64_missing_helpers_avoid_label_materialization_zyoot() {
27008        let index = Index::from_i64_values(vec![1, 0, -4]).set_name("rows");
27009        assert!(index.labels.materialized.get().is_none());
27010
27011        assert_eq!(index.isna(), vec![false, false, false]);
27012        assert_eq!(index.notna(), vec![true, true, true]);
27013        assert!(
27014            index.labels.materialized.get().is_none(),
27015            "isna/notna should not materialize typed Int64 labels"
27016        );
27017
27018        let dropped = index.dropna();
27019        assert_eq!(dropped.name().map(|n| n.as_str()), Some("rows"));
27020        assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[1, 0, -4]);
27021        assert!(index.labels.materialized.get().is_none());
27022        assert!(
27023            dropped.labels.materialized.get().is_none(),
27024            "dropna should preserve typed Int64 backing"
27025        );
27026
27027        let filled = index.fillna(&IndexLabel::Utf8("missing".into()));
27028        assert_eq!(filled.name().map(|n| n.as_str()), Some("rows"));
27029        assert_eq!(filled.labels.int64_view().unwrap().as_slice(), &[1, 0, -4]);
27030        assert!(index.labels.materialized.get().is_none());
27031        assert!(
27032            filled.labels.materialized.get().is_none(),
27033            "fillna should preserve typed Int64 backing when there are no missing labels"
27034        );
27035    }
27036
27037    #[test]
27038    fn affine_int64_missing_helpers_avoid_label_materialization_zyoot() {
27039        let index = Index::new_known_unique_int64_affine_range(4, -2, 3)
27040            .unwrap()
27041            .set_name("axis");
27042        assert!(index.labels.materialized.get().is_none());
27043
27044        assert_eq!(index.isna(), vec![false, false, false]);
27045        assert_eq!(index.notna(), vec![true, true, true]);
27046        assert!(index.labels.materialized.get().is_none());
27047
27048        let dropped = index.dropna();
27049        assert_eq!(dropped.name().map(|n| n.as_str()), Some("axis"));
27050        assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[4, 2, 0]);
27051        assert!(index.labels.materialized.get().is_none());
27052        assert!(
27053            dropped.labels.materialized.get().is_none(),
27054            "dropna should preserve affine Int64 backing"
27055        );
27056
27057        let empty = Index::new_known_unique_int64_affine_range(0, 0, 0).unwrap();
27058        assert_eq!(empty.isna(), Vec::<bool>::new());
27059        assert_eq!(empty.notna(), Vec::<bool>::new());
27060        let filled_empty = empty.fillna(&IndexLabel::Int64(99));
27061        assert!(filled_empty.labels.int64_view().unwrap().is_empty());
27062        assert!(empty.labels.materialized.get().is_none());
27063        assert!(filled_empty.labels.materialized.get().is_none());
27064    }
27065
27066    #[test]
27067    fn int64_hasnans_avoids_label_materialization_99qun() {
27068        let typed = Index::from_i64_values(vec![7, 0, -3]);
27069        assert!(typed.labels.materialized.get().is_none());
27070        assert!(!typed.hasnans());
27071        assert!(
27072            typed.labels.materialized.get().is_none(),
27073            "hasnans should not materialize typed Int64 labels"
27074        );
27075
27076        let affine = Index::new_known_unique_int64_affine_range(9, -3, 4).unwrap();
27077        assert!(affine.labels.materialized.get().is_none());
27078        assert!(!affine.hasnans());
27079        assert!(
27080            affine.labels.materialized.get().is_none(),
27081            "hasnans should not materialize affine Int64 labels"
27082        );
27083    }
27084
27085    #[test]
27086    fn index_isna_notna_detects_datetimelike_nat() {
27087        let datetime_idx = Index::new(vec![
27088            IndexLabel::Datetime64(i64::MIN),
27089            IndexLabel::Datetime64(1_700_000_000_000_000_000),
27090        ]);
27091        assert_eq!(datetime_idx.isna(), vec![true, false]);
27092        assert_eq!(datetime_idx.notna(), vec![false, true]);
27093
27094        let timedelta_idx = Index::from_timedelta64(vec![Timedelta::NAT, 5]);
27095        assert_eq!(timedelta_idx.isna(), vec![true, false]);
27096        assert_eq!(timedelta_idx.notna(), vec![false, true]);
27097    }
27098
27099    #[test]
27100    fn index_fillna_replaces_datetime_nat_and_preserves_name() {
27101        let idx = Index::new(vec![
27102            IndexLabel::Datetime64(i64::MIN),
27103            IndexLabel::Datetime64(1_700_000_000_000_000_000),
27104            IndexLabel::Datetime64(i64::MIN),
27105        ])
27106        .set_name("when");
27107
27108        let filled = idx.fillna(&IndexLabel::Datetime64(1_800_000_000_000_000_000));
27109
27110        assert_eq!(
27111            filled.labels(),
27112            &[
27113                IndexLabel::Datetime64(1_800_000_000_000_000_000),
27114                IndexLabel::Datetime64(1_700_000_000_000_000_000),
27115                IndexLabel::Datetime64(1_800_000_000_000_000_000),
27116            ]
27117        );
27118        assert_eq!(filled.name().map(|n| n.as_str()), Some("when"));
27119    }
27120
27121    #[test]
27122    fn index_fillna_replaces_timedelta_nat() {
27123        let idx = Index::from_timedelta64(vec![Timedelta::NAT, 5, Timedelta::NAT]);
27124
27125        let filled = idx.fillna(&IndexLabel::Timedelta64(42));
27126
27127        assert_eq!(
27128            filled.labels(),
27129            &[
27130                IndexLabel::Timedelta64(42),
27131                IndexLabel::Timedelta64(5),
27132                IndexLabel::Timedelta64(42),
27133            ]
27134        );
27135    }
27136
27137    #[test]
27138    fn index_dropna_removes_missing_and_preserves_name() {
27139        let idx =
27140            Index::from_timedelta64(vec![1, Timedelta::NAT, 3, Timedelta::NAT, 5]).set_name("t");
27141        let dropped = idx.dropna();
27142        assert_eq!(
27143            dropped.labels(),
27144            &[
27145                IndexLabel::Timedelta64(1),
27146                IndexLabel::Timedelta64(3),
27147                IndexLabel::Timedelta64(5),
27148            ]
27149        );
27150        assert_eq!(dropped.name().map(|n| n.as_str()), Some("t"));
27151    }
27152
27153    #[test]
27154    fn index_dropna_all_present_is_noop() {
27155        let idx = Index::from_i64(vec![1, 2, 3]);
27156        let dropped = idx.dropna();
27157        assert_eq!(
27158            dropped.labels(),
27159            &[
27160                IndexLabel::Int64(1),
27161                IndexLabel::Int64(2),
27162                IndexLabel::Int64(3),
27163            ]
27164        );
27165    }
27166
27167    #[test]
27168    fn index_insert_at_middle_position() {
27169        let idx = Index::from_i64(vec![1, 3, 4]);
27170        let result = idx.insert(1, IndexLabel::Int64(2)).unwrap();
27171        assert_eq!(
27172            result.labels(),
27173            &[
27174                IndexLabel::Int64(1),
27175                IndexLabel::Int64(2),
27176                IndexLabel::Int64(3),
27177                IndexLabel::Int64(4),
27178            ]
27179        );
27180    }
27181
27182    #[test]
27183    fn index_insert_at_end_appends() {
27184        let idx = Index::from_i64(vec![1, 2]);
27185        let result = idx.insert(2, IndexLabel::Int64(3)).unwrap();
27186        assert_eq!(
27187            result.labels(),
27188            &[
27189                IndexLabel::Int64(1),
27190                IndexLabel::Int64(2),
27191                IndexLabel::Int64(3),
27192            ]
27193        );
27194    }
27195
27196    #[test]
27197    fn typed_int64_insert_avoids_label_materialization_uza04152() {
27198        let index = Index::from_i64_values(vec![10, 20, 30]).set_name("rows");
27199        assert!(index.labels.materialized.get().is_none());
27200
27201        let result = index.insert(1, IndexLabel::Int64(15)).unwrap();
27202
27203        assert_eq!(result.name().map(|n| n.as_str()), Some("rows"));
27204        assert_eq!(
27205            result.labels.int64_view().unwrap().as_slice(),
27206            &[10, 15, 20, 30]
27207        );
27208        assert!(index.labels.materialized.get().is_none());
27209        assert!(
27210            result.labels.materialized.get().is_none(),
27211            "typed Int64 insert should keep typed output backing"
27212        );
27213    }
27214
27215    #[test]
27216    fn affine_int64_insert_avoids_label_materialization_uza04152() {
27217        let index = Index::new_known_unique_int64_affine_range(2, 3, 3)
27218            .unwrap()
27219            .set_name("axis");
27220        assert!(index.labels.materialized.get().is_none());
27221
27222        let result = index.insert(2, IndexLabel::Int64(7)).unwrap();
27223
27224        assert_eq!(result.name().map(|n| n.as_str()), Some("axis"));
27225        assert_eq!(
27226            result.labels.int64_view().unwrap().as_slice(),
27227            &[2, 5, 7, 8]
27228        );
27229        assert!(index.labels.materialized.get().is_none());
27230        assert!(
27231            result.labels.materialized.get().is_none(),
27232            "affine Int64 insert should rebuild typed output without materializing labels"
27233        );
27234    }
27235
27236    #[test]
27237    fn index_insert_past_end_errors() {
27238        let idx = Index::from_i64(vec![1, 2]);
27239        let err = idx.insert(5, IndexLabel::Int64(9)).unwrap_err();
27240        assert!(matches!(err, crate::IndexError::OutOfBounds { .. }));
27241    }
27242
27243    #[test]
27244    fn index_delete_removes_position() {
27245        let idx = Index::from_i64(vec![10, 20, 30]).set_name("k");
27246        let result = idx.delete(1).unwrap();
27247        assert_eq!(
27248            result.labels(),
27249            &[IndexLabel::Int64(10), IndexLabel::Int64(30)]
27250        );
27251        assert_eq!(result.name().map(|n| n.as_str()), Some("k"));
27252    }
27253
27254    #[test]
27255    fn typed_int64_delete_avoids_label_materialization_uza04150() {
27256        let index = Index::from_i64_values(vec![10, 20, 30, 40]).set_name("rows");
27257        assert!(index.labels.materialized.get().is_none());
27258
27259        let result = index.delete(2).unwrap();
27260
27261        assert_eq!(result.name().map(|n| n.as_str()), Some("rows"));
27262        assert_eq!(
27263            result.labels.int64_view().unwrap().as_slice(),
27264            &[10, 20, 40]
27265        );
27266        assert!(index.labels.materialized.get().is_none());
27267        assert!(
27268            result.labels.materialized.get().is_none(),
27269            "typed Int64 delete should keep typed output backing"
27270        );
27271    }
27272
27273    #[test]
27274    fn affine_int64_delete_avoids_label_materialization_uza04150() {
27275        let index = Index::new_known_unique_int64_affine_range(2, 3, 4)
27276            .unwrap()
27277            .set_name("axis");
27278        assert!(index.labels.materialized.get().is_none());
27279
27280        let result = index.delete(1).unwrap();
27281
27282        assert_eq!(result.name().map(|n| n.as_str()), Some("axis"));
27283        assert_eq!(result.labels.int64_view().unwrap().as_slice(), &[2, 8, 11]);
27284        assert!(index.labels.materialized.get().is_none());
27285        assert!(
27286            result.labels.materialized.get().is_none(),
27287            "affine Int64 delete should rebuild typed output without materializing labels"
27288        );
27289    }
27290
27291    #[test]
27292    fn index_delete_out_of_bounds_errors() {
27293        let idx = Index::from_i64(vec![1]);
27294        let err = idx.delete(1).unwrap_err();
27295        assert!(matches!(err, crate::IndexError::OutOfBounds { .. }));
27296    }
27297
27298    #[test]
27299    fn index_append_concatenates() {
27300        let a = Index::from_i64(vec![1, 2]).set_name("left");
27301        let b = Index::from_i64(vec![3, 4]);
27302        let result = a.append(&b);
27303        assert_eq!(
27304            result.labels(),
27305            &[
27306                IndexLabel::Int64(1),
27307                IndexLabel::Int64(2),
27308                IndexLabel::Int64(3),
27309                IndexLabel::Int64(4),
27310            ]
27311        );
27312        assert_eq!(result.name().map(|n| n.as_str()), Some("left"));
27313    }
27314
27315    #[test]
27316    fn index_append_empty_is_noop() {
27317        let a = Index::from_i64(vec![1, 2]);
27318        let empty = Index::new(Vec::new());
27319        let result = a.append(&empty);
27320        assert_eq!(result.labels(), a.labels());
27321    }
27322
27323    #[test]
27324    fn int64_append_preserves_typed_backing_codb() {
27325        let left = Index::from_i64_values(vec![1, 2, 3]).set_name("row");
27326        let right = Index::from_i64_values(vec![4, 5]);
27327        assert!(left.labels.materialized.get().is_none());
27328        assert!(right.labels.materialized.get().is_none());
27329
27330        let appended = left.append(&right);
27331
27332        assert_eq!(appended.name().map(|n| n.as_str()), Some("row"));
27333        assert_eq!(
27334            appended.labels.int64_view().unwrap().as_slice(),
27335            &[1, 2, 3, 4, 5]
27336        );
27337        assert!(left.labels.materialized.get().is_none());
27338        assert!(right.labels.materialized.get().is_none());
27339        assert!(
27340            appended.labels.materialized.get().is_none(),
27341            "Int64 append should keep typed output backing"
27342        );
27343    }
27344
27345    #[test]
27346    fn affine_int64_append_preserves_typed_backing_codb() {
27347        let left = Index::new_known_unique_int64_affine_range(10, -2, 3)
27348            .unwrap()
27349            .set_name("axis");
27350        let right = Index::new_known_unique_int64_affine_range(1, 3, 3).unwrap();
27351        assert!(left.labels.materialized.get().is_none());
27352        assert!(right.labels.materialized.get().is_none());
27353
27354        let appended = left.append(&right);
27355
27356        assert_eq!(appended.name().map(|n| n.as_str()), Some("axis"));
27357        assert_eq!(
27358            appended.labels.int64_view().unwrap().as_slice(),
27359            &[10, 8, 6, 1, 4, 7]
27360        );
27361        assert!(left.labels.materialized.get().is_none());
27362        assert!(right.labels.materialized.get().is_none());
27363        assert!(
27364            appended.labels.materialized.get().is_none(),
27365            "affine Int64 append should gather raw values into typed output"
27366        );
27367    }
27368
27369    #[test]
27370    fn index_repeat_duplicates_each_label() {
27371        let idx = Index::from_i64(vec![1, 2, 3]).set_name("k");
27372        let result = idx.repeat(2);
27373        assert_eq!(
27374            result.labels(),
27375            &[
27376                IndexLabel::Int64(1),
27377                IndexLabel::Int64(1),
27378                IndexLabel::Int64(2),
27379                IndexLabel::Int64(2),
27380                IndexLabel::Int64(3),
27381                IndexLabel::Int64(3),
27382            ]
27383        );
27384        assert_eq!(result.name().map(|n| n.as_str()), Some("k"));
27385    }
27386
27387    #[test]
27388    fn index_repeat_zero_yields_empty() {
27389        let idx = Index::from_i64(vec![1, 2, 3]);
27390        let result = idx.repeat(0);
27391        assert!(result.labels().is_empty());
27392    }
27393
27394    #[test]
27395    fn index_repeat_one_is_clone() {
27396        let idx = Index::from_i64(vec![1, 2]);
27397        let result = idx.repeat(1);
27398        assert_eq!(result.labels(), idx.labels());
27399    }
27400
27401    #[test]
27402    fn int64_repeat_preserves_typed_backing_codb() {
27403        let index = Index::from_i64_values(vec![2, 4, 6]).set_name("row");
27404        assert!(index.labels.materialized.get().is_none());
27405
27406        let repeated = index.repeat(3);
27407
27408        assert_eq!(repeated.name().map(|n| n.as_str()), Some("row"));
27409        assert_eq!(
27410            repeated.labels.int64_view().unwrap().as_slice(),
27411            &[2, 2, 2, 4, 4, 4, 6, 6, 6]
27412        );
27413        assert!(index.labels.materialized.get().is_none());
27414        assert!(
27415            repeated.labels.materialized.get().is_none(),
27416            "typed Int64 repeat should keep typed output backing"
27417        );
27418    }
27419
27420    #[test]
27421    fn affine_int64_repeat_zero_preserves_empty_typed_backing_codb() {
27422        let index = Index::new_known_unique_int64_affine_range(3, 5, 4)
27423            .unwrap()
27424            .set_name("axis");
27425        assert!(index.labels.materialized.get().is_none());
27426
27427        let repeated = index.repeat(0);
27428
27429        assert_eq!(repeated.name().map(|n| n.as_str()), Some("axis"));
27430        assert!(repeated.labels.int64_view().unwrap().is_empty());
27431        assert!(index.labels.materialized.get().is_none());
27432        assert!(
27433            repeated.labels.materialized.get().is_none(),
27434            "zero-repeat Int64 output should stay typed-empty"
27435        );
27436    }
27437
27438    #[test]
27439    fn index_equals_same_labels_ignores_name() {
27440        let a = Index::from_i64(vec![1, 2, 3]).set_name("x");
27441        let b = Index::from_i64(vec![1, 2, 3]).set_name("y");
27442        assert!(a.equals(&b));
27443    }
27444
27445    #[test]
27446    fn index_equals_differing_labels_false() {
27447        let a = Index::from_i64(vec![1, 2, 3]);
27448        let b = Index::from_i64(vec![1, 2]);
27449        assert!(!a.equals(&b));
27450    }
27451
27452    #[test]
27453    fn index_identical_requires_matching_name() {
27454        let a = Index::from_i64(vec![1, 2]).set_name("x");
27455        let b = Index::from_i64(vec![1, 2]).set_name("y");
27456        assert!(a.equals(&b));
27457        assert!(!a.identical(&b));
27458        let c = Index::from_i64(vec![1, 2]).set_name("x");
27459        assert!(a.identical(&c));
27460    }
27461
27462    #[test]
27463    fn index_value_counts_sorts_by_descending_count() {
27464        let idx = Index::new(vec![
27465            "a".into(),
27466            "b".into(),
27467            "a".into(),
27468            "c".into(),
27469            "a".into(),
27470            "b".into(),
27471        ]);
27472        let counts = idx.value_counts();
27473        assert_eq!(counts[0].0, IndexLabel::Utf8("a".into()));
27474        assert_eq!(counts[0].1, 3);
27475        assert_eq!(counts[1].0, IndexLabel::Utf8("b".into()));
27476        assert_eq!(counts[1].1, 2);
27477        assert_eq!(counts[2].0, IndexLabel::Utf8("c".into()));
27478        assert_eq!(counts[2].1, 1);
27479    }
27480
27481    #[test]
27482    fn index_value_counts_empty() {
27483        let idx = Index::new(Vec::<IndexLabel>::new());
27484        assert!(idx.value_counts().is_empty());
27485    }
27486
27487    #[test]
27488    fn index_value_counts_drops_missing_by_default() {
27489        let idx = Index::new(vec![
27490            IndexLabel::Datetime64(i64::MIN),
27491            IndexLabel::Utf8("a".into()),
27492            IndexLabel::Utf8("a".into()),
27493            IndexLabel::Datetime64(i64::MIN),
27494        ]);
27495
27496        let counts = idx.value_counts();
27497        assert_eq!(counts, vec![(IndexLabel::Utf8("a".into()), 2)]);
27498    }
27499
27500    #[test]
27501    fn index_value_counts_with_options_preserves_first_seen_order_when_unsorted() {
27502        let idx = Index::new(vec![
27503            IndexLabel::Datetime64(i64::MIN),
27504            IndexLabel::Utf8("b".into()),
27505            IndexLabel::Utf8("a".into()),
27506            IndexLabel::Utf8("b".into()),
27507        ]);
27508
27509        let counts = idx.value_counts_with_options(false, false, false, false);
27510        assert_eq!(
27511            counts,
27512            vec![
27513                (IndexLabel::Datetime64(i64::MIN), Scalar::Int64(1)),
27514                (IndexLabel::Utf8("b".into()), Scalar::Int64(2)),
27515                (IndexLabel::Utf8("a".into()), Scalar::Int64(1)),
27516            ]
27517        );
27518    }
27519
27520    #[test]
27521    fn index_value_counts_with_options_normalize_excludes_missing_from_denominator() {
27522        let idx = Index::new(vec![
27523            IndexLabel::Int64(1),
27524            IndexLabel::Int64(1),
27525            IndexLabel::Int64(2),
27526            IndexLabel::Datetime64(i64::MIN),
27527        ]);
27528
27529        let counts = idx.value_counts_with_options(true, true, false, true);
27530        assert!(matches!(
27531            counts.as_slice(),
27532            [
27533                (IndexLabel::Int64(1), Scalar::Float64(_)),
27534                (IndexLabel::Int64(2), Scalar::Float64(_))
27535            ]
27536        ));
27537        let [
27538            (IndexLabel::Int64(1), Scalar::Float64(first)),
27539            (IndexLabel::Int64(2), Scalar::Float64(second)),
27540        ] = counts.as_slice()
27541        else {
27542            return;
27543        };
27544        assert!((first - (2.0 / 3.0)).abs() < 1e-12);
27545        assert!((second - (1.0 / 3.0)).abs() < 1e-12);
27546    }
27547
27548    #[test]
27549    fn index_shift_positive_pads_left() {
27550        let idx = Index::from_i64(vec![1, 2, 3, 4]).set_name("k");
27551        let shifted = idx.shift(2, IndexLabel::Int64(-1));
27552        assert_eq!(
27553            shifted.labels(),
27554            &[
27555                IndexLabel::Int64(-1),
27556                IndexLabel::Int64(-1),
27557                IndexLabel::Int64(1),
27558                IndexLabel::Int64(2),
27559            ]
27560        );
27561        assert_eq!(shifted.name().map(|n| n.as_str()), Some("k"));
27562    }
27563
27564    #[test]
27565    fn index_shift_negative_pads_right() {
27566        let idx = Index::from_i64(vec![1, 2, 3, 4]);
27567        let shifted = idx.shift(-1, IndexLabel::Int64(0));
27568        assert_eq!(
27569            shifted.labels(),
27570            &[
27571                IndexLabel::Int64(2),
27572                IndexLabel::Int64(3),
27573                IndexLabel::Int64(4),
27574                IndexLabel::Int64(0),
27575            ]
27576        );
27577    }
27578
27579    #[test]
27580    fn index_shift_zero_is_clone() {
27581        let idx = Index::from_i64(vec![1, 2, 3]);
27582        let shifted = idx.shift(0, IndexLabel::Int64(-1));
27583        assert_eq!(shifted.labels(), idx.labels());
27584    }
27585
27586    #[test]
27587    fn index_shift_larger_than_len_fills_all() {
27588        let idx = Index::from_i64(vec![1, 2, 3]);
27589        let shifted = idx.shift(10, IndexLabel::Int64(-1));
27590        assert_eq!(
27591            shifted.labels(),
27592            &[
27593                IndexLabel::Int64(-1),
27594                IndexLabel::Int64(-1),
27595                IndexLabel::Int64(-1),
27596            ]
27597        );
27598    }
27599
27600    #[test]
27601    fn typed_int64_shift_preserves_typed_backing_codb() {
27602        let index = Index::from_i64_values(vec![1, 2, 3, 4]).set_name("k");
27603        assert!(index.labels.materialized.get().is_none());
27604
27605        let shifted = index.shift(2, IndexLabel::Int64(-1));
27606
27607        assert_eq!(shifted.name().map(|n| n.as_str()), Some("k"));
27608        assert_eq!(
27609            shifted.labels.int64_view().unwrap().as_slice(),
27610            &[-1, -1, 1, 2]
27611        );
27612        assert!(index.labels.materialized.get().is_none());
27613        assert!(
27614            shifted.labels.materialized.get().is_none(),
27615            "typed Int64 shift should keep typed output backing"
27616        );
27617
27618        let materialized = Index::new(vec![
27619            IndexLabel::Int64(1),
27620            IndexLabel::Int64(2),
27621            IndexLabel::Int64(3),
27622            IndexLabel::Int64(4),
27623        ])
27624        .set_name("k");
27625        assert_eq!(
27626            shifted.labels(),
27627            materialized.shift(2, IndexLabel::Int64(-1)).labels()
27628        );
27629
27630        let filled = index.shift(10, IndexLabel::Int64(0));
27631        assert_eq!(
27632            filled.labels.int64_view().unwrap().as_slice(),
27633            &[0, 0, 0, 0]
27634        );
27635        assert!(index.labels.materialized.get().is_none());
27636    }
27637
27638    #[test]
27639    fn affine_int64_shift_preserves_typed_backing_codb() {
27640        let index = Index::new_known_unique_int64_affine_range(10, -2, 4)
27641            .unwrap()
27642            .set_name("axis");
27643        assert!(index.labels.materialized.get().is_none());
27644
27645        let shifted = index.shift(-1, IndexLabel::Int64(99));
27646
27647        assert_eq!(shifted.name().map(|n| n.as_str()), Some("axis"));
27648        assert_eq!(
27649            shifted.labels.int64_view().unwrap().as_slice(),
27650            &[8, 6, 4, 99]
27651        );
27652        assert!(index.labels.materialized.get().is_none());
27653        assert!(
27654            shifted.labels.materialized.get().is_none(),
27655            "affine Int64 shift should gather raw values into typed output"
27656        );
27657    }
27658
27659    #[test]
27660    fn index_any_all_basic() {
27661        let idx = Index::from_i64(vec![0, 0, 1]);
27662        assert!(idx.any());
27663        assert!(!idx.all());
27664
27665        let all_nonzero = Index::from_i64(vec![1, 2, 3]);
27666        assert!(all_nonzero.all());
27667        assert!(all_nonzero.any());
27668
27669        let all_zero = Index::from_i64(vec![0, 0]);
27670        assert!(!all_zero.any());
27671        assert!(!all_zero.all());
27672    }
27673
27674    #[test]
27675    fn typed_int64_any_all_avoid_label_materialization_c1ikv() {
27676        let mixed = Index::from_i64_values(vec![0, 3, 0]);
27677        assert!(mixed.labels.materialized.get().is_none());
27678        assert!(mixed.any());
27679        assert!(!mixed.all());
27680        assert!(
27681            mixed.labels.materialized.get().is_none(),
27682            "any/all should read typed Int64 values without materializing labels"
27683        );
27684
27685        let all_nonzero = Index::from_i64_values(vec![-2, 1, 5]);
27686        assert!(all_nonzero.labels.materialized.get().is_none());
27687        assert!(all_nonzero.any());
27688        assert!(all_nonzero.all());
27689        assert!(all_nonzero.labels.materialized.get().is_none());
27690    }
27691
27692    #[test]
27693    fn affine_int64_any_all_avoid_label_materialization_c1ikv() {
27694        let zeros = Index::new_known_unique_int64_affine_range(0, 0, 0).unwrap();
27695        assert!(zeros.labels.materialized.get().is_none());
27696        assert!(!zeros.any());
27697        assert!(zeros.all());
27698        assert!(zeros.labels.materialized.get().is_none());
27699
27700        let values = Index::new_known_unique_int64_affine_range(2, 2, 3).unwrap();
27701        assert!(values.labels.materialized.get().is_none());
27702        assert!(values.any());
27703        assert!(values.all());
27704        assert!(values.labels.materialized.get().is_none());
27705    }
27706
27707    #[test]
27708    fn index_all_empty_is_true() {
27709        let idx = Index::new(Vec::<IndexLabel>::new());
27710        assert!(idx.all());
27711        assert!(!idx.any());
27712    }
27713
27714    #[test]
27715    fn index_any_string_nonempty_truthy() {
27716        let idx = Index::new(vec!["".into(), "".into(), "x".into()]);
27717        assert!(idx.any());
27718        assert!(!idx.all());
27719    }
27720
27721    #[test]
27722    fn index_to_list_returns_owned_labels() {
27723        let idx = Index::from_i64(vec![1, 2, 3]);
27724        assert_eq!(
27725            idx.to_list(),
27726            vec![
27727                IndexLabel::Int64(1),
27728                IndexLabel::Int64(2),
27729                IndexLabel::Int64(3),
27730            ]
27731        );
27732    }
27733
27734    #[test]
27735    fn index_format_stringifies_labels() {
27736        let idx = Index::new(vec![
27737            IndexLabel::Int64(10),
27738            IndexLabel::Utf8("abc".into()),
27739            IndexLabel::Int64(-5),
27740        ]);
27741        assert_eq!(idx.format(), vec!["10", "abc", "-5"]);
27742    }
27743
27744    #[test]
27745    fn typed_int64_format_avoids_label_materialization_ye9dl() {
27746        let index = Index::from_i64_values(vec![10, -5, 0]);
27747        assert!(index.labels.materialized.get().is_none());
27748
27749        assert_eq!(index.format(), vec!["10", "-5", "0"]);
27750        assert!(
27751            index.labels.materialized.get().is_none(),
27752            "format should read typed Int64 values without materializing labels"
27753        );
27754    }
27755
27756    #[test]
27757    fn affine_int64_format_avoids_label_materialization_ye9dl() {
27758        let index = Index::new_known_unique_int64_affine_range(10, -3, 4).unwrap();
27759        assert!(index.labels.materialized.get().is_none());
27760
27761        assert_eq!(index.format(), vec!["10", "7", "4", "1"]);
27762        assert!(
27763            index.labels.materialized.get().is_none(),
27764            "format should read affine Int64 values without materializing labels"
27765        );
27766    }
27767
27768    #[test]
27769    fn index_putmask_replaces_true_positions() {
27770        let idx = Index::from_i64(vec![1, 2, 3, 4]).set_name("k");
27771        let cond = vec![false, true, false, true];
27772        let replaced = idx.putmask(&cond, &IndexLabel::Int64(0));
27773        assert_eq!(
27774            replaced.labels(),
27775            &[
27776                IndexLabel::Int64(1),
27777                IndexLabel::Int64(0),
27778                IndexLabel::Int64(3),
27779                IndexLabel::Int64(0),
27780            ]
27781        );
27782        assert_eq!(replaced.name().map(|n| n.as_str()), Some("k"));
27783    }
27784
27785    #[test]
27786    fn index_putmask_short_cond_leaves_tail_unchanged() {
27787        let idx = Index::from_i64(vec![1, 2, 3, 4]);
27788        // cond shorter than index — trailing positions keep original
27789        // labels (matches pandas lenient alignment).
27790        let cond = vec![true];
27791        let replaced = idx.putmask(&cond, &IndexLabel::Int64(-1));
27792        assert_eq!(
27793            replaced.labels(),
27794            &[
27795                IndexLabel::Int64(-1),
27796                IndexLabel::Int64(2),
27797                IndexLabel::Int64(3),
27798                IndexLabel::Int64(4),
27799            ]
27800        );
27801    }
27802
27803    #[test]
27804    fn index_putmask_empty_cond_is_noop() {
27805        let idx = Index::from_i64(vec![1, 2]);
27806        let replaced = idx.putmask(&[], &IndexLabel::Int64(0));
27807        assert_eq!(replaced.labels(), idx.labels());
27808    }
27809
27810    #[test]
27811    fn int64_putmask_avoids_label_materialization_codb() {
27812        let index = Index::from_i64_values(vec![1, 2, 3, 4]).set_name("row");
27813        assert!(index.labels.materialized.get().is_none());
27814
27815        let replaced = index.putmask(&[false, true, false, true], &IndexLabel::Int64(9));
27816
27817        assert_eq!(replaced.name().map(|n| n.as_str()), Some("row"));
27818        assert_eq!(
27819            replaced.labels.int64_view().unwrap().as_slice(),
27820            &[1, 9, 3, 9]
27821        );
27822        assert!(index.labels.materialized.get().is_none());
27823        assert!(
27824            replaced.labels.materialized.get().is_none(),
27825            "typed Int64 putmask should keep typed output backing"
27826        );
27827
27828        let materialized = Index::new(vec![
27829            IndexLabel::Int64(1),
27830            IndexLabel::Int64(2),
27831            IndexLabel::Int64(3),
27832            IndexLabel::Int64(4),
27833        ]);
27834        assert_eq!(
27835            replaced.labels(),
27836            materialized
27837                .putmask(&[false, true, false, true], &IndexLabel::Int64(9))
27838                .labels()
27839        );
27840    }
27841
27842    #[test]
27843    fn affine_int64_putmask_avoids_label_materialization_codb() {
27844        let index = Index::new_known_unique_int64_affine_range(10, -2, 4)
27845            .unwrap()
27846            .set_name("axis");
27847        assert!(index.labels.materialized.get().is_none());
27848
27849        let replaced = index.putmask(&[true, false, true], &IndexLabel::Int64(5));
27850
27851        assert_eq!(replaced.name().map(|n| n.as_str()), Some("axis"));
27852        assert_eq!(
27853            replaced.labels.int64_view().unwrap().as_slice(),
27854            &[5, 8, 5, 4]
27855        );
27856        assert!(index.labels.materialized.get().is_none());
27857        assert!(
27858            replaced.labels.materialized.get().is_none(),
27859            "affine Int64 putmask should gather raw values into typed output"
27860        );
27861    }
27862
27863    #[test]
27864    fn index_asof_finds_largest_not_exceeding() {
27865        let idx = Index::from_i64(vec![1, 3, 5, 7]);
27866        assert_eq!(idx.asof(&IndexLabel::Int64(4)), Some(IndexLabel::Int64(3)));
27867        assert_eq!(idx.asof(&IndexLabel::Int64(5)), Some(IndexLabel::Int64(5)));
27868        assert_eq!(idx.asof(&IndexLabel::Int64(7)), Some(IndexLabel::Int64(7)));
27869        assert_eq!(
27870            idx.asof(&IndexLabel::Int64(100)),
27871            Some(IndexLabel::Int64(7))
27872        );
27873    }
27874
27875    #[test]
27876    fn index_asof_before_first_returns_none() {
27877        let idx = Index::from_i64(vec![5, 10]);
27878        assert_eq!(idx.asof(&IndexLabel::Int64(0)), None);
27879    }
27880
27881    #[test]
27882    fn int64_asof_avoids_label_materialization_1851g() {
27883        let typed = Index::from_i64_values(vec![1, 3, 5, 7]);
27884        assert!(typed.labels.materialized.get().is_none());
27885        assert_eq!(
27886            typed.asof(&IndexLabel::Int64(4)),
27887            Some(IndexLabel::Int64(3))
27888        );
27889        assert_eq!(typed.asof(&IndexLabel::Int64(0)), None);
27890        assert_eq!(
27891            typed.asof(&IndexLabel::Int64(7)),
27892            Some(IndexLabel::Int64(7))
27893        );
27894        assert!(
27895            typed.labels.materialized.get().is_none(),
27896            "asof should not materialize typed Int64 labels"
27897        );
27898
27899        let affine = Index::new_known_unique_int64_affine_range(1, 2, 4).unwrap();
27900        assert!(affine.labels.materialized.get().is_none());
27901        assert!(affine.cached_int64_label_values().is_none());
27902        assert_eq!(
27903            affine.asof(&IndexLabel::Int64(6)),
27904            Some(IndexLabel::Int64(5))
27905        );
27906        assert_eq!(
27907            affine.asof(&IndexLabel::Int64(100)),
27908            Some(IndexLabel::Int64(7))
27909        );
27910        assert!(
27911            affine.labels.materialized.get().is_none(),
27912            "asof should not materialize affine Int64 labels"
27913        );
27914        assert!(
27915            affine.cached_int64_label_values().is_none(),
27916            "asof should not materialize the affine raw i64 view"
27917        );
27918
27919        let extreme = Index::new_known_unique_int64_affine_range(i64::MIN, i64::MAX, 2).unwrap();
27920        assert_eq!(
27921            extreme.asof(&IndexLabel::Int64(i64::MAX)),
27922            Some(IndexLabel::Int64(-1))
27923        );
27924        assert!(extreme.cached_int64_label_values().is_none());
27925
27926        let singleton = Index::new_known_unique_int64_affine_range(7, i64::MIN, 1).unwrap();
27927        assert_eq!(singleton.asof(&IndexLabel::Int64(6)), None);
27928        assert_eq!(
27929            singleton.asof(&IndexLabel::Int64(7)),
27930            Some(IndexLabel::Int64(7))
27931        );
27932        assert!(singleton.cached_int64_label_values().is_none());
27933
27934        let empty = Index::new_known_unique_int64_affine_range(0, 0, 0).unwrap();
27935        assert_eq!(empty.asof(&IndexLabel::Int64(0)), None);
27936        assert!(empty.cached_int64_label_values().is_none());
27937    }
27938
27939    #[test]
27940    fn int64_asof_locs_avoids_label_materialization_4jr8s() {
27941        let source = Index::from_i64_values(vec![1, 3, 5, 7]);
27942        let probes = Index::from_i64_values(vec![0, 4, 7, 10]);
27943        assert!(source.labels.materialized.get().is_none());
27944        assert!(probes.labels.materialized.get().is_none());
27945        assert_eq!(
27946            source.asof_locs(&probes, None),
27947            vec![None, Some(1), Some(3), Some(3)]
27948        );
27949        assert_eq!(
27950            source.asof_locs(&probes, Some(&[true, false, true, true])),
27951            vec![None, Some(0), Some(3), Some(3)]
27952        );
27953        assert!(
27954            source.labels.materialized.get().is_none(),
27955            "asof_locs should not materialize source Int64 labels"
27956        );
27957        assert!(
27958            probes.labels.materialized.get().is_none(),
27959            "asof_locs should not materialize probe Int64 labels"
27960        );
27961    }
27962
27963    #[test]
27964    fn int64_asof_locs_no_mask_uses_right_bound_without_materializing_lx6k2() {
27965        let source = Index::from_i64_values(vec![1, 3, 3, 8]);
27966        let probes = Index::from_i64_values(vec![0, 3, 4, 9]);
27967        assert_eq!(
27968            source.asof_locs(&probes, None),
27969            vec![None, Some(2), Some(2), Some(3)]
27970        );
27971        assert!(
27972            source.labels.materialized.get().is_none(),
27973            "no-mask asof_locs should keep duplicate Int64 source labels raw"
27974        );
27975        assert!(
27976            probes.labels.materialized.get().is_none(),
27977            "no-mask asof_locs should keep duplicate Int64 probe labels raw"
27978        );
27979    }
27980
27981    #[test]
27982    fn index_searchsorted_left_right() {
27983        let idx = Index::from_i64(vec![1, 2, 2, 5]);
27984        assert_eq!(idx.searchsorted(&IndexLabel::Int64(2), "left").unwrap(), 1);
27985        assert_eq!(idx.searchsorted(&IndexLabel::Int64(2), "right").unwrap(), 3);
27986        assert_eq!(idx.searchsorted(&IndexLabel::Int64(0), "left").unwrap(), 0);
27987        assert_eq!(idx.searchsorted(&IndexLabel::Int64(6), "left").unwrap(), 4);
27988    }
27989
27990    #[test]
27991    fn int64_searchsorted_avoids_label_materialization_ymhb6() {
27992        let typed = Index::from_i64_values(vec![1, 2, 2, 5]);
27993        assert!(typed.labels.materialized.get().is_none());
27994        assert_eq!(
27995            typed.searchsorted(&IndexLabel::Int64(2), "left").unwrap(),
27996            1
27997        );
27998        assert_eq!(
27999            typed.searchsorted(&IndexLabel::Int64(2), "right").unwrap(),
28000            3
28001        );
28002        assert_eq!(
28003            typed.searchsorted(&IndexLabel::Int64(0), "left").unwrap(),
28004            0
28005        );
28006        assert_eq!(
28007            typed.searchsorted(&IndexLabel::Int64(6), "left").unwrap(),
28008            4
28009        );
28010        assert!(
28011            typed.labels.materialized.get().is_none(),
28012            "searchsorted should not materialize typed Int64 labels"
28013        );
28014
28015        let affine = Index::new_known_unique_int64_affine_range(1, 2, 4).unwrap();
28016        assert!(affine.labels.materialized.get().is_none());
28017        assert_eq!(
28018            affine.searchsorted(&IndexLabel::Int64(4), "left").unwrap(),
28019            2
28020        );
28021        assert_eq!(
28022            affine.searchsorted(&IndexLabel::Int64(5), "left").unwrap(),
28023            2
28024        );
28025        assert_eq!(
28026            affine.searchsorted(&IndexLabel::Int64(5), "right").unwrap(),
28027            3
28028        );
28029        assert!(
28030            affine.labels.materialized.get().is_none(),
28031            "searchsorted should not materialize affine Int64 labels"
28032        );
28033    }
28034
28035    #[test]
28036    fn index_searchsorted_rejects_invalid_side() {
28037        let idx = Index::from_i64(vec![1]);
28038        assert!(idx.searchsorted(&IndexLabel::Int64(0), "middle").is_err());
28039    }
28040
28041    #[test]
28042    fn index_memory_usage_counts_fixed_width() {
28043        let idx = Index::from_i64(vec![1, 2, 3]);
28044        let shallow = idx.memory_usage(false);
28045        assert_eq!(shallow, 24); // 3 * 8
28046        // deep is identical for fixed-width types.
28047        assert_eq!(idx.memory_usage(true), 24);
28048    }
28049
28050    #[test]
28051    fn int64_memory_usage_avoids_label_materialization_bqfj0() {
28052        let typed = Index::from_i64_values(vec![1, 2, 3, 4]);
28053        assert!(typed.labels.materialized.get().is_none());
28054        assert_eq!(typed.memory_usage(false), 32);
28055        assert_eq!(typed.memory_usage(true), 32);
28056        assert_eq!(typed.nbytes(), 32);
28057        assert!(
28058            typed.labels.materialized.get().is_none(),
28059            "memory_usage should not materialize typed Int64 labels"
28060        );
28061
28062        let affine = Index::new_known_unique_int64_affine_range(10, -2, 5).unwrap();
28063        assert!(affine.labels.materialized.get().is_none());
28064        assert_eq!(affine.memory_usage(false), 40);
28065        assert_eq!(affine.memory_usage(true), 40);
28066        assert_eq!(affine.nbytes(), 40);
28067        assert!(
28068            affine.labels.materialized.get().is_none(),
28069            "memory_usage should not materialize affine Int64 labels"
28070        );
28071
28072        let empty = Index::from_i64_values(Vec::new());
28073        assert!(empty.labels.materialized.get().is_none());
28074        assert_eq!(empty.memory_usage(false), 0);
28075        assert_eq!(empty.memory_usage(true), 0);
28076        assert_eq!(empty.nbytes(), 0);
28077        assert!(empty.labels.materialized.get().is_none());
28078    }
28079
28080    #[test]
28081    fn index_memory_usage_saturates_fixed_width_bytes_uza04179() {
28082        assert_eq!(super::fixed_width_label_memory_usage(4, 8), 32);
28083        assert_eq!(
28084            super::fixed_width_label_memory_usage(usize::MAX, 8),
28085            usize::MAX
28086        );
28087        assert_eq!(
28088            super::fixed_width_label_memory_usage(8, usize::MAX),
28089            usize::MAX
28090        );
28091    }
28092
28093    #[test]
28094    fn index_memory_usage_deep_counts_utf8_bytes() {
28095        let idx = Index::new(vec![
28096            IndexLabel::Utf8("hi".into()),
28097            IndexLabel::Utf8("world".into()),
28098        ]);
28099        let shallow = idx.memory_usage(false);
28100        let deep = idx.memory_usage(true);
28101        // deep - shallow == sum of string byte lengths
28102        assert_eq!(deep - shallow, 7);
28103    }
28104
28105    #[test]
28106    fn index_nlevels_flat_index_is_one() {
28107        let idx = Index::from_i64(vec![1, 2]);
28108        assert_eq!(idx.nlevels(), 1);
28109    }
28110
28111    #[test]
28112    fn index_where_cond() {
28113        let idx = Index::new(vec!["a".into(), "b".into(), "c".into()]);
28114        let cond = vec![true, false, true];
28115        let result = idx.where_cond(&cond, &"X".into());
28116        assert_eq!(result.labels()[0], IndexLabel::Utf8("a".into()));
28117        assert_eq!(result.labels()[1], IndexLabel::Utf8("X".into()));
28118        assert_eq!(result.labels()[2], IndexLabel::Utf8("c".into()));
28119    }
28120
28121    #[test]
28122    fn int_index_where_nan_is_float_oq1df() {
28123        let nan = IndexLabel::Null(fp_types::NullKind::NaN);
28124        let idx = Index::from_i64(vec![1, 2, 3]);
28125        let result = idx.where_cond(&[false, true, true], &nan);
28126        assert_eq!(
28127            result.labels(),
28128            &[
28129                nan.clone(),
28130                IndexLabel::Float64(OrderedF64(2.0)),
28131                IndexLabel::Float64(OrderedF64(3.0)),
28132            ]
28133        );
28134        let result = idx.where_cond(&[true, false, true], &IndexLabel::Float64(OrderedF64(0.5)));
28135        assert_eq!(result.labels()[0], IndexLabel::Float64(OrderedF64(1.0)));
28136        // Nothing replaced, or an int in place of a label: still ints.
28137        let kept = idx.where_cond(&[true, true, true], &nan);
28138        assert_eq!(kept.labels()[0], IndexLabel::Int64(1));
28139        let ints = idx.where_cond(&[false, true, true], &IndexLabel::Int64(0));
28140        assert_eq!(ints.labels()[0], IndexLabel::Int64(0));
28141        assert_eq!(ints.labels()[1], IndexLabel::Int64(2));
28142    }
28143
28144    #[test]
28145    fn index_a31qh_conversion_aliases_materialize_labels() {
28146        let idx = Index::new(vec!["a".into(), "b".into()]).set_name("key");
28147        let labels = vec![IndexLabel::from("a"), IndexLabel::from("b")];
28148
28149        assert_eq!(idx.tolist(), labels);
28150        assert_eq!(idx.to_numpy(), labels);
28151        assert_eq!(idx.array(), labels);
28152        assert_eq!(idx.values(), labels);
28153        assert_eq!(idx.ravel(), labels);
28154        assert_eq!(idx.view(), idx);
28155        assert_eq!(idx.transpose(), idx);
28156        assert_eq!(idx.T(), idx);
28157        assert_eq!(
28158            idx.to_frame(),
28159            vec![vec![IndexLabel::from("a")], vec![IndexLabel::from("b")]]
28160        );
28161        assert_eq!(
28162            idx.to_series(),
28163            vec![
28164                (IndexLabel::from("a"), IndexLabel::from("a")),
28165                (IndexLabel::from("b"), IndexLabel::from("b")),
28166            ]
28167        );
28168    }
28169
28170    #[test]
28171    fn int64_frame_series_views_avoid_source_materialization_codb() {
28172        let index = Index::from_i64_values(vec![7, -1, 7]).set_name("row");
28173        assert!(index.labels.materialized.get().is_none());
28174
28175        assert_eq!(
28176            index.to_frame(),
28177            vec![
28178                vec![IndexLabel::Int64(7)],
28179                vec![IndexLabel::Int64(-1)],
28180                vec![IndexLabel::Int64(7)],
28181            ]
28182        );
28183        assert!(
28184            index.labels.materialized.get().is_none(),
28185            "to_frame should build owned rows from raw Int64 values"
28186        );
28187
28188        assert_eq!(
28189            index.to_series(),
28190            vec![
28191                (IndexLabel::Int64(7), IndexLabel::Int64(7)),
28192                (IndexLabel::Int64(-1), IndexLabel::Int64(-1)),
28193                (IndexLabel::Int64(7), IndexLabel::Int64(7)),
28194            ]
28195        );
28196        assert!(
28197            index.labels.materialized.get().is_none(),
28198            "to_series should build owned pairs from raw Int64 values"
28199        );
28200
28201        let materialized = Index::new(vec![
28202            IndexLabel::Int64(7),
28203            IndexLabel::Int64(-1),
28204            IndexLabel::Int64(7),
28205        ]);
28206        assert_eq!(index.to_frame(), materialized.to_frame());
28207        assert_eq!(index.to_series(), materialized.to_series());
28208
28209        let affine = Index::new_known_unique_int64_affine_range(4, 3, 3).unwrap();
28210        assert!(affine.labels.materialized.get().is_none());
28211        assert_eq!(
28212            affine.to_frame(),
28213            vec![
28214                vec![IndexLabel::Int64(4)],
28215                vec![IndexLabel::Int64(7)],
28216                vec![IndexLabel::Int64(10)],
28217            ]
28218        );
28219        assert!(affine.labels.materialized.get().is_none());
28220    }
28221
28222    #[test]
28223    fn int64_list_aliases_avoid_source_materialization_codb() {
28224        let index = Index::from_i64_values(vec![4, 0, -2]).set_name("row");
28225        let expected = vec![
28226            IndexLabel::Int64(4),
28227            IndexLabel::Int64(0),
28228            IndexLabel::Int64(-2),
28229        ];
28230        assert!(index.labels.materialized.get().is_none());
28231
28232        assert_eq!(index.to_list(), expected);
28233        assert_eq!(index.tolist(), expected);
28234        assert_eq!(index.to_numpy(), expected);
28235        assert_eq!(index.array(), expected);
28236        assert_eq!(index.values(), expected);
28237        assert_eq!(index.ravel(), expected);
28238        assert!(
28239            index.labels.materialized.get().is_none(),
28240            "to_list aliases should materialize owned labels without caching source labels"
28241        );
28242
28243        let materialized = Index::new(expected);
28244        assert_eq!(index.to_list(), materialized.to_list());
28245        assert_eq!(index.to_numpy(), materialized.to_numpy());
28246
28247        let affine = Index::new_known_unique_int64_affine_range(2, 3, 4).unwrap();
28248        let expected_affine = vec![
28249            IndexLabel::Int64(2),
28250            IndexLabel::Int64(5),
28251            IndexLabel::Int64(8),
28252            IndexLabel::Int64(11),
28253        ];
28254        assert!(affine.labels.materialized.get().is_none());
28255        assert!(affine.cached_int64_label_values().is_none());
28256        assert_eq!(affine.to_list(), expected_affine);
28257        assert_eq!(affine.values(), expected_affine);
28258        assert_eq!(affine.ravel(), expected_affine);
28259        assert!(
28260            affine.labels.materialized.get().is_none(),
28261            "affine to_list aliases should not cache IndexLabel labels"
28262        );
28263        assert!(
28264            affine.cached_int64_label_values().is_none(),
28265            "affine to_list aliases should not build the intermediate i64 view"
28266        );
28267    }
28268
28269    #[test]
28270    fn index_a31qh_dtype_metadata_and_type_checks() {
28271        let ints = Index::from_i64(vec![1, 2, 3]);
28272        assert_eq!(ints.dtype(), "int64");
28273        assert_eq!(ints.dtypes(), vec!["int64"]);
28274        assert_eq!(ints.inferred_type(), "integer");
28275        assert!(ints.holds_integer());
28276        assert!(ints.is_integer());
28277        assert!(ints.is_numeric());
28278        assert!(!ints.is_object());
28279        assert_eq!(ints.ndim(), 1);
28280        assert_eq!(ints.shape(), (3,));
28281        assert_eq!(ints.size(), 3);
28282        assert_eq!(ints.nbytes(), ints.memory_usage(false));
28283        assert!(!ints.empty());
28284        assert_eq!(
28285            Index::from_i64(vec![42]).item().unwrap(),
28286            IndexLabel::Int64(42)
28287        );
28288        assert!(ints.item().is_err());
28289
28290        let mixed = Index::new(vec![
28291            IndexLabel::Int64(1),
28292            IndexLabel::Utf8("x".into()),
28293            IndexLabel::Datetime64(i64::MIN),
28294        ]);
28295        assert_eq!(mixed.dtype(), "object");
28296        assert_eq!(mixed.inferred_type(), "mixed");
28297        assert!(mixed.is_object());
28298        assert!(mixed.hasnans());
28299        assert_eq!(mixed.isnull(), mixed.isna());
28300        assert_eq!(mixed.notnull(), mixed.notna());
28301        assert!(!mixed.is_boolean());
28302        assert!(!mixed.is_categorical());
28303        assert!(!mixed.is_floating());
28304        assert!(!mixed.is_interval());
28305        assert_eq!(mixed.infer_objects(), mixed);
28306        assert!(ints.is_(&ints));
28307        assert!(!ints.is_(&Index::from_i64(vec![1, 2, 3])));
28308    }
28309
28310    #[test]
28311    fn a_missing_label_beside_bools_or_strings_is_mixed() {
28312        use fp_types::NullKind;
28313        // pd.Index([True, None]) / ['a', np.nan]: inferred 'mixed', object.
28314        for labels in [
28315            vec![IndexLabel::Bool(true), IndexLabel::Null(NullKind::Null)],
28316            vec![
28317                IndexLabel::Utf8("a".into()),
28318                IndexLabel::Null(NullKind::NaN),
28319            ],
28320        ] {
28321            let index = Index::new(labels);
28322            assert_eq!(index.inferred_type(), "mixed");
28323            assert_eq!(index.dtype(), "object");
28324        }
28325        // NEGATIVE: NaN is a float and NaT an instant; and every label present.
28326        let floats = Index::new(vec![
28327            IndexLabel::Float64(OrderedF64(1.5)),
28328            IndexLabel::Null(NullKind::NaN),
28329        ]);
28330        assert_eq!(floats.inferred_type(), "floating");
28331        let instants = Index::new(vec![
28332            IndexLabel::Datetime64(0),
28333            IndexLabel::Null(NullKind::NaT),
28334        ]);
28335        assert_eq!(instants.inferred_type(), "datetime64");
28336        let bools = Index::new(vec![IndexLabel::Bool(true), IndexLabel::Bool(false)]);
28337        assert_eq!(bools.dtype(), "bool");
28338        let texts = Index::new(vec![IndexLabel::Utf8("a".into())]);
28339        assert_eq!(texts.inferred_type(), "string");
28340    }
28341
28342    #[test]
28343    fn an_index_of_missing_labels_alone_is_typed_by_them_mzes1() {
28344        use fp_types::NullKind;
28345        // pd.Index([nan, nan]) / [nan, None]: float64 (it was object);
28346        // [NaT, NaT]: datetime64[ns].
28347        for labels in [
28348            vec![
28349                IndexLabel::Null(NullKind::NaN),
28350                IndexLabel::Null(NullKind::NaN),
28351            ],
28352            vec![
28353                IndexLabel::Null(NullKind::NaN),
28354                IndexLabel::Null(NullKind::Null),
28355            ],
28356        ] {
28357            let index = Index::new(labels);
28358            assert_eq!(index.inferred_type(), "floating");
28359            assert_eq!(index.dtype(), "float64");
28360        }
28361        let nats = Index::new(vec![IndexLabel::Null(NullKind::NaT); 2]);
28362        assert_eq!(nats.dtype(), "datetime64[ns]");
28363        // NEGATIVE: None alone stays object ('mixed'), and no labels 'empty'.
28364        let nones = Index::new(vec![IndexLabel::Null(NullKind::Null); 2]);
28365        assert_eq!(nones.inferred_type(), "mixed");
28366        assert_eq!(nones.dtype(), "object");
28367        assert_eq!(Index::new(Vec::new()).inferred_type(), "empty");
28368    }
28369
28370    #[test]
28371    fn period_labels_make_a_period_index_45fzr() {
28372        use fp_types::{Period, PeriodFreq};
28373        // Ordinal 648 is 2024-01 monthly (54 years of 12 months).
28374        let jan = Period::new(648, PeriodFreq::Monthly);
28375        let feb = Period::new(649, PeriodFreq::Monthly);
28376        let nat = Period::new(i64::MIN, PeriodFreq::Monthly);
28377        let index = Index::new(vec![
28378            IndexLabel::Period(feb),
28379            IndexLabel::Period(jan),
28380            IndexLabel::Period(nat),
28381        ]);
28382        assert_eq!(index.labels()[0].to_string(), "2024-02");
28383        assert_eq!(index.labels()[2].to_string(), "NaT");
28384        assert!(index.labels()[2].is_missing());
28385        assert!(!index.labels()[0].is_missing());
28386        assert_eq!(index.inferred_type(), "period");
28387        assert!(IndexLabel::Period(jan) < IndexLabel::Period(feb));
28388        // A PeriodIndex and its labels round-trip.
28389        let periods = PeriodIndex::from_index(&index).expect("periods of one freq");
28390        assert_eq!(periods.freqstr().as_deref(), Some("M"));
28391        assert_eq!(periods.to_index().labels(), index.labels());
28392        // NEGATIVE: text that reads as periods is no PeriodIndex, nor are
28393        // periods of two freqs (an object index there, as pandas').
28394        assert!(PeriodIndex::from_index(&Index::from_utf8(vec!["2024-01".to_owned()])).is_none());
28395        let mixed = Index::new(vec![
28396            IndexLabel::Period(jan),
28397            IndexLabel::Period(Period::new(0, PeriodFreq::Daily)),
28398        ]);
28399        assert!(PeriodIndex::from_index(&mixed).is_none());
28400        assert_eq!(mixed.inferred_type(), "mixed");
28401    }
28402
28403    #[test]
28404    fn int64_item_avoids_label_materialization_0633o() {
28405        let typed = Index::from_i64_values(vec![42]);
28406        assert!(typed.labels.materialized.get().is_none());
28407        assert_eq!(typed.item().unwrap(), IndexLabel::Int64(42));
28408        assert!(
28409            typed.labels.materialized.get().is_none(),
28410            "item should not materialize typed Int64 labels"
28411        );
28412
28413        let affine = Index::new_known_unique_int64_affine_range(9, 3, 1).unwrap();
28414        assert!(affine.labels.materialized.get().is_none());
28415        assert_eq!(affine.item().unwrap(), IndexLabel::Int64(9));
28416        assert!(
28417            affine.labels.materialized.get().is_none(),
28418            "item should not materialize affine Int64 labels"
28419        );
28420    }
28421
28422    #[test]
28423    fn int64_dtype_predicates_avoid_label_materialization_gzi1i() {
28424        let typed = Index::from_i64_values(vec![4, 0, -2]);
28425        assert!(typed.labels.materialized.get().is_none());
28426        assert_eq!(typed.inferred_type(), "integer");
28427        assert_eq!(typed.dtype(), "int64");
28428        assert_eq!(typed.dtypes(), vec!["int64"]);
28429        assert!(typed.holds_integer());
28430        assert!(typed.is_integer());
28431        assert!(typed.is_numeric());
28432        assert!(!typed.is_object());
28433        assert!(
28434            typed.labels.materialized.get().is_none(),
28435            "dtype predicates should not materialize typed Int64 labels"
28436        );
28437
28438        let affine = Index::new_known_unique_int64_affine_range(12, -4, 4).unwrap();
28439        assert!(affine.labels.materialized.get().is_none());
28440        assert_eq!(affine.inferred_type(), "integer");
28441        assert_eq!(affine.dtype(), "int64");
28442        assert!(affine.is_integer());
28443        assert!(affine.is_numeric());
28444        assert!(!affine.is_object());
28445        assert!(
28446            affine.labels.materialized.get().is_none(),
28447            "dtype predicates should not materialize affine Int64 labels"
28448        );
28449
28450        let empty = Index::from_i64_values(Vec::new());
28451        assert!(empty.labels.materialized.get().is_none());
28452        assert_eq!(empty.inferred_type(), "empty");
28453        assert_eq!(empty.dtype(), "object");
28454        assert!(!empty.is_integer());
28455        assert!(!empty.is_numeric());
28456        assert!(empty.is_object());
28457        assert!(empty.labels.materialized.get().is_none());
28458    }
28459
28460    #[test]
28461    fn int64_monotonic_predicates_avoid_label_materialization_k9tlb() {
28462        // Ascending affine range: O(1) via step sign, no materialization.
28463        let asc = Index::new_known_unique_int64_affine_range(0, 2, 4).unwrap();
28464        assert!(asc.labels.materialized.get().is_none());
28465        assert!(asc.is_monotonic_increasing());
28466        assert!(asc.is_monotonic());
28467        assert!(!asc.is_monotonic_decreasing());
28468        assert!(
28469            asc.labels.materialized.get().is_none(),
28470            "affine monotonic predicates must not materialize labels"
28471        );
28472
28473        // Descending affine range.
28474        let desc = Index::new_known_unique_int64_affine_range(12, -4, 4).unwrap();
28475        assert!(desc.labels.materialized.get().is_none());
28476        assert!(!desc.is_monotonic_increasing());
28477        assert!(desc.is_monotonic_decreasing());
28478        assert!(desc.labels.materialized.get().is_none());
28479
28480        // Typed non-affine Int64 that is neither ascending nor descending:
28481        // scans the i64 view, still no label vector.
28482        let unsorted = Index::from_i64_values(vec![4, 0, 7]);
28483        assert!(unsorted.labels.materialized.get().is_none());
28484        assert!(!unsorted.is_monotonic_increasing());
28485        assert!(!unsorted.is_monotonic_decreasing());
28486        assert!(
28487            unsorted.labels.materialized.get().is_none(),
28488            "typed Int64 monotonic predicates must not materialize labels"
28489        );
28490
28491        let sorted = Index::from_i64_values(vec![-2, 0, 0, 4]);
28492        assert!(sorted.is_monotonic_increasing());
28493        assert!(!sorted.is_monotonic_decreasing());
28494        assert!(sorted.labels.materialized.get().is_none());
28495
28496        let sorted_desc = Index::from_i64_values(vec![4, 0, 0, -2]);
28497        assert!(!sorted_desc.is_monotonic_increasing());
28498        assert!(sorted_desc.is_monotonic_decreasing());
28499
28500        // Single element / empty are trivially monotonic both ways.
28501        let one = Index::from_i64_values(vec![7]);
28502        assert!(one.is_monotonic_increasing() && one.is_monotonic_decreasing());
28503        let empty = Index::from_i64_values(Vec::new());
28504        assert!(empty.is_monotonic_increasing() && empty.is_monotonic_decreasing());
28505
28506        // Bit-identical to the object-label fallback path.
28507        let obj = Index::new(vec![
28508            IndexLabel::Int64(1),
28509            IndexLabel::Int64(3),
28510            IndexLabel::Int64(3),
28511            IndexLabel::Int64(9),
28512        ]);
28513        assert_eq!(
28514            obj.is_monotonic_increasing(),
28515            Index::from_i64_values(vec![1, 3, 3, 9]).is_monotonic_increasing()
28516        );
28517        assert_eq!(
28518            obj.is_monotonic_decreasing(),
28519            Index::from_i64_values(vec![1, 3, 3, 9]).is_monotonic_decreasing()
28520        );
28521    }
28522
28523    #[test]
28524    fn datetime64_affine_monotonic_predicates_match_eager_oracle_jrlto() {
28525        let cases = [
28526            ("ascending", 0, 2, 4),
28527            ("descending", 12, -4, 4),
28528            ("near_max", i64::MAX, -1, 3),
28529            ("singleton", 7, 0, 1),
28530            ("empty", 0, 0, 0),
28531        ];
28532
28533        for (name, start, step, len) in cases {
28534            let affine = Index::from_datetime64_affine_range(start, step, len)
28535                .expect("valid Datetime64 affine range");
28536            let eager_values = (0..len)
28537                .map(|offset| {
28538                    let offset = i64::try_from(offset).expect("test offset fits i64");
28539                    start
28540                        .checked_add(step.checked_mul(offset).expect("test span fits i64"))
28541                        .expect("test endpoint fits i64")
28542                })
28543                .collect();
28544            let eager = Index::from_datetime64(eager_values);
28545
28546            assert!(
28547                affine.labels.materialized.get().is_none(),
28548                "{name}: affine labels must begin lazy",
28549            );
28550            assert_eq!(
28551                affine.is_monotonic_increasing(),
28552                eager.is_monotonic_increasing(),
28553                "{name}: increasing predicate must match eager labels",
28554            );
28555            assert_eq!(
28556                affine.is_monotonic_decreasing(),
28557                eager.is_monotonic_decreasing(),
28558                "{name}: decreasing predicate must match eager labels",
28559            );
28560            assert_eq!(
28561                affine.is_monotonic(),
28562                eager.is_monotonic(),
28563                "{name}: monotonic alias must match eager labels",
28564            );
28565            assert!(
28566                affine.labels.materialized.get().is_none(),
28567                "{name}: affine monotonic predicates must not materialize labels",
28568            );
28569            assert!(
28570                affine.labels.int64_typed.get().is_none(),
28571                "{name}: affine monotonic predicates must not probe the Int64 view",
28572            );
28573        }
28574
28575        // NaT-bearing affine ranges must reject monotonicity without
28576        // materializing their labels.
28577        for (name, start, step) in [("nat_start", i64::MIN, 1), ("nat_end", i64::MIN + 2, -1)] {
28578            let affine = Index::from_datetime64_affine_range(start, step, 3)
28579                .expect("valid NaT-bearing Datetime64 affine range");
28580            let eager_values = (0..3).map(|offset| start + step * offset).collect();
28581            let eager = Index::from_datetime64(eager_values);
28582
28583            assert_eq!(
28584                affine.is_monotonic_increasing(),
28585                eager.is_monotonic_increasing(),
28586                "{name}: increasing predicate must retain the eager fallback",
28587            );
28588            assert_eq!(
28589                affine.is_monotonic_decreasing(),
28590                eager.is_monotonic_decreasing(),
28591                "{name}: decreasing predicate must retain the eager fallback",
28592            );
28593            assert!(
28594                affine.labels.materialized.get().is_none(),
28595                "{name}: NaT detection must keep affine labels lazy",
28596            );
28597        }
28598    }
28599
28600    #[test]
28601    fn datetime64_nat_is_not_monotonic_x6i5k() {
28602        // pandas 2.2.3 reports both predicates false for a DatetimeIndex with
28603        // NaT at every position, including the singleton case.
28604        for (name, values) in [
28605            ("nat_start", vec![i64::MIN, 1, 2]),
28606            ("nat_middle", vec![1, i64::MIN, 2]),
28607            ("nat_end", vec![1, 2, i64::MIN]),
28608            ("reverse", vec![2, 1, i64::MIN]),
28609            ("singleton_nat", vec![i64::MIN]),
28610        ] {
28611            let index = Index::from_datetime64(values);
28612
28613            assert!(
28614                !index.is_monotonic_increasing(),
28615                "{name}: NaT-bearing DatetimeIndex must not be increasing",
28616            );
28617            assert!(
28618                !index.is_monotonic_decreasing(),
28619                "{name}: NaT-bearing DatetimeIndex must not be decreasing",
28620            );
28621            assert!(
28622                !index.is_monotonic(),
28623                "{name}: monotonic alias must preserve increasing semantics",
28624            );
28625        }
28626    }
28627
28628    #[test]
28629    fn held_datetime_monotonic_flags_in_one_pass_pirog() {
28630        // br-frankenpandas-pirog: held datetime labels answer both flags in
28631        // one pass, as pandas' DatetimeIndex: equal neighbours keep an
28632        // ascent, a descending pair breaks it, NaT anywhere breaks both.
28633        // NEGATIVE: datetimes followed by a text label leave the pass at the
28634        // text, and the generic label order answers, as before - it ranks
28635        // text below a datetime, so an ascent into text is no ascent (pandas
28636        // False too: a Timestamp and a str do not compare).
28637        for (name, stamps, increasing, decreasing) in [
28638            ("equal neighbours", vec![1, 1, 2], true, false),
28639            ("all equal", vec![5, 5, 5], true, true),
28640            ("descending pair", vec![1, 3, 2], false, false),
28641            ("descending", vec![3, 2, 2], false, true),
28642            ("NaT first", vec![i64::MIN, 1, 2], false, false),
28643            ("NaT last of a descent", vec![2, 1, i64::MIN], false, false),
28644            ("empty", vec![], true, true),
28645        ] {
28646            let index = Index::from_datetime64(stamps);
28647            assert_eq!(
28648                (
28649                    index.is_monotonic_increasing(),
28650                    index.is_monotonic_decreasing()
28651                ),
28652                (increasing, decreasing),
28653                "{name}"
28654            );
28655        }
28656        let mixed = Index::new(vec![
28657            IndexLabel::Datetime64(1),
28658            IndexLabel::Datetime64(2),
28659            IndexLabel::Utf8("a".to_owned()),
28660        ]);
28661        assert!(!mixed.is_monotonic_increasing());
28662        assert!(!mixed.is_monotonic_decreasing());
28663        // The flags are remembered, shared by clones (a clone asked first
28664        // answers the original); an index taken from a remembered one
28665        // answers its own order.
28666        let ascending = Index::from_datetime64(vec![1, 2, 3]);
28667        assert!(ascending.clone().is_monotonic_increasing());
28668        assert_eq!(ascending.monotonic_cache[0].get(), Some(&true));
28669        assert!(ascending.is_monotonic_increasing());
28670        let reversed = ascending.take(&[2, 1, 0]);
28671        assert!(!reversed.is_monotonic_increasing());
28672        assert!(reversed.is_monotonic_decreasing());
28673        // An ascent read every label: the label kinds are kept from it (no
28674        // second pass for a resampler's axis check). NEGATIVE: the mixed
28675        // index's pass stopped at the text, so its kinds are its own.
28676        let fresh = Index::from_datetime64(vec![4, 5, 6]);
28677        assert!(fresh.is_monotonic_increasing());
28678        let kept = crate::INDEX_LABEL_KINDS_CACHE
28679            .get()
28680            .and_then(|cache| cache.lock().ok()?.get(&fresh.label_identity).copied());
28681        assert_eq!(kept, Some(crate::LabelKinds::DATETIME64));
28682        assert_eq!(fresh.label_kinds(), crate::LabelKinds::DATETIME64);
28683        assert!(mixed.label_kinds().intersects(crate::LabelKinds::UTF8));
28684    }
28685
28686    #[test]
28687    fn datetime64_affine_nunique_matches_eager_oracle_uls13() {
28688        let cases = [
28689            ("empty", 0, 0, 0),
28690            ("singleton", 7, 0, 1),
28691            ("singleton_nat", i64::MIN, 0, 1),
28692            ("ascending", 0, 2, 4),
28693            ("nat_start", i64::MIN, 1, 4),
28694            ("nat_end", i64::MIN + 3, -1, 4),
28695            ("near_max", i64::MAX, -1, 3),
28696        ];
28697
28698        for (name, start, step, len) in cases {
28699            let affine = Index::from_datetime64_affine_range(start, step, len)
28700                .expect("valid Datetime64 affine range");
28701            let eager_values = (0..len)
28702                .map(|offset| {
28703                    let offset = i64::try_from(offset).expect("test offset fits i64");
28704                    start
28705                        .checked_add(step.checked_mul(offset).expect("test span fits i64"))
28706                        .expect("test endpoint fits i64")
28707                })
28708                .collect();
28709            let eager = Index::from_datetime64(eager_values);
28710
28711            for dropna in [true, false] {
28712                assert_eq!(
28713                    affine.nunique_with_dropna(dropna),
28714                    eager.nunique_with_dropna(dropna),
28715                    "{name}: dropna={dropna}",
28716                );
28717            }
28718            assert!(
28719                affine.labels.materialized.get().is_none(),
28720                "{name}: affine nunique must not materialize labels",
28721            );
28722            assert!(
28723                affine.labels.int64_typed.get().is_none(),
28724                "{name}: affine nunique must not probe the Int64 view",
28725            );
28726        }
28727    }
28728
28729    fn datetime64_nunique_former_body_uls13(index: &Index, dropna: bool) -> usize {
28730        if let Some(affine) = index.labels.int64_affine_range() {
28731            return affine.len;
28732        }
28733        if let Some(values) = index.labels.int64_view() {
28734            return Index::nunique_i64(&values);
28735        }
28736        if let Some(ns) = index
28737            .temporal_ns_present(true)
28738            .or_else(|| index.temporal_ns_present(false))
28739        {
28740            return Index::nunique_i64(&ns);
28741        }
28742        index
28743            .unique()
28744            .labels
28745            .iter()
28746            .filter(|label| !dropna || !label.is_missing())
28747            .count()
28748    }
28749
28750    fn median_nanos_uls13(samples: &mut [u128]) -> u128 {
28751        samples.sort_unstable();
28752        samples[samples.len() / 2]
28753    }
28754
28755    fn measure_nunique_nanos_uls13(f: impl FnOnce() -> usize) -> u128 {
28756        let start = std::time::Instant::now();
28757        std::hint::black_box(f());
28758        start.elapsed().as_nanos()
28759    }
28760
28761    #[test]
28762    #[ignore = "perf A/B; run with --ignored --nocapture"]
28763    fn datetime64_affine_nunique_ab_uls13() {
28764        const LEN: usize = 1_000_000;
28765        const SAMPLES: usize = 15;
28766        let reference_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
28767        let reference_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
28768        let candidate_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
28769        let candidate_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
28770
28771        assert_eq!(
28772            datetime64_nunique_former_body_uls13(&reference_a, true),
28773            candidate_a.nunique(),
28774        );
28775        assert!(candidate_a.labels.materialized.get().is_none());
28776        for _ in 0..3 {
28777            std::hint::black_box(datetime64_nunique_former_body_uls13(&reference_a, true));
28778            std::hint::black_box(datetime64_nunique_former_body_uls13(&reference_b, true));
28779            std::hint::black_box(candidate_a.nunique());
28780            std::hint::black_box(candidate_b.nunique());
28781        }
28782
28783        let mut former_a = Vec::with_capacity(SAMPLES);
28784        let mut former_b = Vec::with_capacity(SAMPLES);
28785        let mut witness_a = Vec::with_capacity(SAMPLES);
28786        let mut witness_b = Vec::with_capacity(SAMPLES);
28787        for sample in 0..SAMPLES {
28788            if sample % 2 == 0 {
28789                former_a.push(measure_nunique_nanos_uls13(|| {
28790                    datetime64_nunique_former_body_uls13(&reference_a, true)
28791                }));
28792                witness_a.push(measure_nunique_nanos_uls13(|| candidate_a.nunique()));
28793                witness_b.push(measure_nunique_nanos_uls13(|| candidate_b.nunique()));
28794                former_b.push(measure_nunique_nanos_uls13(|| {
28795                    datetime64_nunique_former_body_uls13(&reference_b, true)
28796                }));
28797            } else {
28798                former_b.push(measure_nunique_nanos_uls13(|| {
28799                    datetime64_nunique_former_body_uls13(&reference_b, true)
28800                }));
28801                witness_b.push(measure_nunique_nanos_uls13(|| candidate_b.nunique()));
28802                witness_a.push(measure_nunique_nanos_uls13(|| candidate_a.nunique()));
28803                former_a.push(measure_nunique_nanos_uls13(|| {
28804                    datetime64_nunique_former_body_uls13(&reference_a, true)
28805                }));
28806            }
28807        }
28808
28809        let former_a_p50 = median_nanos_uls13(&mut former_a);
28810        let former_b_p50 = median_nanos_uls13(&mut former_b);
28811        let witness_a_p50 = median_nanos_uls13(&mut witness_a);
28812        let witness_b_p50 = median_nanos_uls13(&mut witness_b);
28813        let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
28814        let witness_mean = (witness_a_p50 + witness_b_p50) as f64 / 2.0;
28815
28816        println!("affine Datetime64 nunique, len={LEN}, samples={SAMPLES}");
28817        println!("former body p50 A/B: {former_a_p50} / {former_b_p50} ns");
28818        println!("affine witness p50 A/B: {witness_a_p50} / {witness_b_p50} ns");
28819        println!(
28820            "former/witness p50 ratio: {:.3}x",
28821            former_mean / witness_mean
28822        );
28823        assert!(candidate_a.labels.materialized.get().is_none());
28824        assert!(candidate_b.labels.materialized.get().is_none());
28825    }
28826
28827    #[test]
28828    fn datetime64_affine_min_matches_eager_oracle_hi31t() {
28829        let cases = [
28830            ("empty", 0, 0, 0),
28831            ("singleton", 7, 0, 1),
28832            ("singleton_nat", i64::MIN, 0, 1),
28833            ("ascending", 0, 2, 4),
28834            ("descending", 12, -4, 4),
28835            ("nat_start", i64::MIN, 1, 4),
28836            ("nat_end", i64::MIN + 3, -1, 4),
28837            ("near_max", i64::MAX, -1, 3),
28838        ];
28839
28840        for (name, start, step, len) in cases {
28841            let affine = Index::from_datetime64_affine_range(start, step, len)
28842                .expect("valid Datetime64 affine range");
28843            let eager_values = (0..len)
28844                .map(|offset| {
28845                    let offset = i64::try_from(offset).expect("test offset fits i64");
28846                    start
28847                        .checked_add(step.checked_mul(offset).expect("test span fits i64"))
28848                        .expect("test endpoint fits i64")
28849                })
28850                .collect();
28851            let eager = Index::from_datetime64(eager_values);
28852
28853            assert_eq!(affine.min(), eager.min(), "{name}");
28854            assert!(
28855                affine.labels.materialized.get().is_none(),
28856                "{name}: affine min must not materialize labels",
28857            );
28858            assert!(
28859                affine.labels.int64_typed.get().is_none(),
28860                "{name}: affine min must not probe the Int64 view",
28861            );
28862        }
28863    }
28864
28865    fn datetime64_min_former_body_hi31t(index: &Index) -> Option<IndexLabel> {
28866        if let Some(affine) = index.labels.int64_affine_range() {
28867            if affine.len == 0 {
28868                return None;
28869            }
28870            let position = if affine.step >= 0 { 0 } else { affine.len - 1 };
28871            return Some(IndexLabel::Int64(affine.value_at(position)));
28872        }
28873        if index.labels.has_lazy_int64_backing()
28874            && let Some(values) = index.labels.int64_view()
28875        {
28876            return values.iter().copied().min().map(IndexLabel::Int64);
28877        }
28878        index.labels.iter().min().cloned()
28879    }
28880
28881    fn median_nanos_hi31t(samples: &mut [u128]) -> u128 {
28882        samples.sort_unstable();
28883        samples[samples.len() / 2]
28884    }
28885
28886    fn measure_min_nanos_hi31t<T>(f: impl FnOnce() -> T) -> u128 {
28887        let start = std::time::Instant::now();
28888        std::hint::black_box(f());
28889        start.elapsed().as_nanos()
28890    }
28891
28892    #[test]
28893    #[ignore = "perf A/B; run with --ignored --nocapture"]
28894    fn datetime64_affine_min_ab_hi31t() {
28895        const LEN: usize = 1_000_000;
28896        const SAMPLES: usize = 15;
28897        let reference_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
28898        let reference_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
28899        let candidate_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
28900        let candidate_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
28901
28902        assert_eq!(
28903            datetime64_min_former_body_hi31t(&reference_a),
28904            candidate_a.min(),
28905        );
28906        assert!(candidate_a.labels.materialized.get().is_none());
28907        for _ in 0..3 {
28908            std::hint::black_box(datetime64_min_former_body_hi31t(&reference_a));
28909            std::hint::black_box(datetime64_min_former_body_hi31t(&reference_b));
28910            std::hint::black_box(candidate_a.min());
28911            std::hint::black_box(candidate_b.min());
28912        }
28913
28914        let mut former_a = Vec::with_capacity(SAMPLES);
28915        let mut former_b = Vec::with_capacity(SAMPLES);
28916        let mut witness_a = Vec::with_capacity(SAMPLES);
28917        let mut witness_b = Vec::with_capacity(SAMPLES);
28918        for sample in 0..SAMPLES {
28919            if sample % 2 == 0 {
28920                former_a.push(measure_min_nanos_hi31t(|| {
28921                    datetime64_min_former_body_hi31t(&reference_a)
28922                }));
28923                witness_a.push(measure_min_nanos_hi31t(|| candidate_a.min()));
28924                witness_b.push(measure_min_nanos_hi31t(|| candidate_b.min()));
28925                former_b.push(measure_min_nanos_hi31t(|| {
28926                    datetime64_min_former_body_hi31t(&reference_b)
28927                }));
28928            } else {
28929                former_b.push(measure_min_nanos_hi31t(|| {
28930                    datetime64_min_former_body_hi31t(&reference_b)
28931                }));
28932                witness_b.push(measure_min_nanos_hi31t(|| candidate_b.min()));
28933                witness_a.push(measure_min_nanos_hi31t(|| candidate_a.min()));
28934                former_a.push(measure_min_nanos_hi31t(|| {
28935                    datetime64_min_former_body_hi31t(&reference_a)
28936                }));
28937            }
28938        }
28939
28940        let former_a_p50 = median_nanos_hi31t(&mut former_a);
28941        let former_b_p50 = median_nanos_hi31t(&mut former_b);
28942        let witness_a_p50 = median_nanos_hi31t(&mut witness_a);
28943        let witness_b_p50 = median_nanos_hi31t(&mut witness_b);
28944        let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
28945        let witness_mean = (witness_a_p50 + witness_b_p50) as f64 / 2.0;
28946
28947        println!("affine Datetime64 min, len={LEN}, samples={SAMPLES}");
28948        println!("former body p50 A/B: {former_a_p50} / {former_b_p50} ns");
28949        println!("affine witness p50 A/B: {witness_a_p50} / {witness_b_p50} ns");
28950        println!(
28951            "former/witness p50 ratio: {:.3}x",
28952            former_mean / witness_mean
28953        );
28954        assert!(candidate_a.labels.materialized.get().is_none());
28955        assert!(candidate_b.labels.materialized.get().is_none());
28956    }
28957
28958    #[test]
28959    fn datetime64_affine_max_matches_eager_oracle_nsexq() {
28960        let cases = [
28961            ("empty", 0, 0, 0),
28962            ("singleton", 7, 0, 1),
28963            ("singleton_nat", i64::MIN, 0, 1),
28964            ("ascending", 0, 2, 4),
28965            ("descending", 12, -4, 4),
28966            ("nat_start", i64::MIN, 1, 4),
28967            ("nat_end", i64::MIN + 3, -1, 4),
28968            ("near_max", i64::MAX, -1, 3),
28969        ];
28970
28971        for (name, start, step, len) in cases {
28972            let affine = Index::from_datetime64_affine_range(start, step, len)
28973                .expect("valid Datetime64 affine range");
28974            let eager_values = (0..len)
28975                .map(|offset| {
28976                    let offset = i64::try_from(offset).expect("test offset fits i64");
28977                    start
28978                        .checked_add(step.checked_mul(offset).expect("test span fits i64"))
28979                        .expect("test endpoint fits i64")
28980                })
28981                .collect();
28982            let eager = Index::from_datetime64(eager_values);
28983
28984            assert_eq!(affine.max(), eager.max(), "{name}");
28985            assert!(
28986                affine.labels.materialized.get().is_none(),
28987                "{name}: affine max must not materialize labels",
28988            );
28989            assert!(
28990                affine.labels.int64_typed.get().is_none(),
28991                "{name}: affine max must not probe the Int64 view",
28992            );
28993        }
28994    }
28995
28996    fn datetime64_max_former_body_nsexq(index: &Index) -> Option<IndexLabel> {
28997        if let Some(affine) = index.labels.int64_affine_range() {
28998            if affine.len == 0 {
28999                return None;
29000            }
29001            let position = if affine.step >= 0 { affine.len - 1 } else { 0 };
29002            return Some(IndexLabel::Int64(affine.value_at(position)));
29003        }
29004        if index.labels.has_lazy_int64_backing()
29005            && let Some(values) = index.labels.int64_view()
29006        {
29007            return values.iter().copied().max().map(IndexLabel::Int64);
29008        }
29009        index.labels.iter().max().cloned()
29010    }
29011
29012    fn median_nanos_nsexq(samples: &mut [u128]) -> u128 {
29013        samples.sort_unstable();
29014        samples[samples.len() / 2]
29015    }
29016
29017    fn measure_max_nanos_nsexq<T>(f: impl FnOnce() -> T) -> u128 {
29018        let start = std::time::Instant::now();
29019        std::hint::black_box(f());
29020        start.elapsed().as_nanos()
29021    }
29022
29023    #[test]
29024    #[ignore = "perf A/B; run with --ignored --nocapture"]
29025    fn datetime64_affine_max_ab_nsexq() {
29026        const LEN: usize = 1_000_000;
29027        const SAMPLES: usize = 15;
29028        let reference_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29029        let reference_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29030        let candidate_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29031        let candidate_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29032
29033        assert_eq!(
29034            datetime64_max_former_body_nsexq(&reference_a),
29035            candidate_a.max(),
29036        );
29037        assert!(candidate_a.labels.materialized.get().is_none());
29038        for _ in 0..3 {
29039            std::hint::black_box(datetime64_max_former_body_nsexq(&reference_a));
29040            std::hint::black_box(datetime64_max_former_body_nsexq(&reference_b));
29041            std::hint::black_box(candidate_a.max());
29042            std::hint::black_box(candidate_b.max());
29043        }
29044
29045        let mut former_a = Vec::with_capacity(SAMPLES);
29046        let mut former_b = Vec::with_capacity(SAMPLES);
29047        let mut witness_a = Vec::with_capacity(SAMPLES);
29048        let mut witness_b = Vec::with_capacity(SAMPLES);
29049        for sample in 0..SAMPLES {
29050            if sample % 2 == 0 {
29051                former_a.push(measure_max_nanos_nsexq(|| {
29052                    datetime64_max_former_body_nsexq(&reference_a)
29053                }));
29054                witness_a.push(measure_max_nanos_nsexq(|| candidate_a.max()));
29055                witness_b.push(measure_max_nanos_nsexq(|| candidate_b.max()));
29056                former_b.push(measure_max_nanos_nsexq(|| {
29057                    datetime64_max_former_body_nsexq(&reference_b)
29058                }));
29059            } else {
29060                former_b.push(measure_max_nanos_nsexq(|| {
29061                    datetime64_max_former_body_nsexq(&reference_b)
29062                }));
29063                witness_b.push(measure_max_nanos_nsexq(|| candidate_b.max()));
29064                witness_a.push(measure_max_nanos_nsexq(|| candidate_a.max()));
29065                former_a.push(measure_max_nanos_nsexq(|| {
29066                    datetime64_max_former_body_nsexq(&reference_a)
29067                }));
29068            }
29069        }
29070
29071        let former_a_p50 = median_nanos_nsexq(&mut former_a);
29072        let former_b_p50 = median_nanos_nsexq(&mut former_b);
29073        let witness_a_p50 = median_nanos_nsexq(&mut witness_a);
29074        let witness_b_p50 = median_nanos_nsexq(&mut witness_b);
29075        let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
29076        let witness_mean = (witness_a_p50 + witness_b_p50) as f64 / 2.0;
29077
29078        println!("affine Datetime64 max, len={LEN}, samples={SAMPLES}");
29079        println!("former body p50 A/B: {former_a_p50} / {former_b_p50} ns");
29080        println!("affine witness p50 A/B: {witness_a_p50} / {witness_b_p50} ns");
29081        println!(
29082            "former/witness p50 ratio: {:.3}x",
29083            former_mean / witness_mean
29084        );
29085        assert!(candidate_a.labels.materialized.get().is_none());
29086        assert!(candidate_b.labels.materialized.get().is_none());
29087    }
29088
29089    #[test]
29090    fn datetime64_affine_argmin_matches_eager_oracle_wxjca() {
29091        let cases = [
29092            ("empty", 0, 0, 0),
29093            ("singleton", 7, 0, 1),
29094            ("singleton_nat", i64::MIN, 0, 1),
29095            ("ascending", 0, 2, 4),
29096            ("descending", 12, -4, 4),
29097            ("nat_start", i64::MIN, 1, 4),
29098            ("nat_end", i64::MIN + 3, -1, 4),
29099            ("near_max", i64::MAX, -1, 3),
29100        ];
29101
29102        for (name, start, step, len) in cases {
29103            let affine = Index::from_datetime64_affine_range(start, step, len)
29104                .expect("valid Datetime64 affine range");
29105            let eager_values = (0..len)
29106                .map(|offset| {
29107                    let offset = i64::try_from(offset).expect("test offset fits i64");
29108                    start
29109                        .checked_add(step.checked_mul(offset).expect("test span fits i64"))
29110                        .expect("test endpoint fits i64")
29111                })
29112                .collect();
29113            let eager = Index::from_datetime64(eager_values);
29114
29115            assert_eq!(affine.argmin(), eager.argmin(), "{name}");
29116            assert!(
29117                affine.labels.materialized.get().is_none(),
29118                "{name}: affine argmin must not materialize labels",
29119            );
29120            assert!(
29121                affine.labels.int64_typed.get().is_none(),
29122                "{name}: affine argmin must not probe the Int64 view",
29123            );
29124        }
29125    }
29126
29127    fn datetime64_argmin_former_body_wxjca(index: &Index) -> Option<usize> {
29128        if let Some(affine) = index.labels.int64_affine_range() {
29129            return (affine.len > 0).then(|| if affine.step >= 0 { 0 } else { affine.len - 1 });
29130        }
29131        if index.labels.has_lazy_int64_backing()
29132            && let Some(values) = index.labels.int64_view()
29133        {
29134            return values
29135                .iter()
29136                .enumerate()
29137                .min_by(|(_, a), (_, b)| a.cmp(b))
29138                .map(|(i, _)| i);
29139        }
29140        index
29141            .labels
29142            .iter()
29143            .enumerate()
29144            .min_by(|(_, a), (_, b)| a.cmp(b))
29145            .map(|(i, _)| i)
29146    }
29147
29148    fn median_nanos_wxjca(samples: &mut [u128]) -> u128 {
29149        samples.sort_unstable();
29150        samples[samples.len() / 2]
29151    }
29152
29153    fn measure_argmin_nanos_wxjca<T>(f: impl FnOnce() -> T) -> u128 {
29154        let start = std::time::Instant::now();
29155        std::hint::black_box(f());
29156        start.elapsed().as_nanos()
29157    }
29158
29159    #[test]
29160    #[ignore = "perf A/B; run with --ignored --nocapture"]
29161    fn datetime64_affine_argmin_ab_wxjca() {
29162        const LEN: usize = 1_000_000;
29163        const SAMPLES: usize = 15;
29164        let reference_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29165        let reference_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29166        let candidate_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29167        let candidate_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29168
29169        assert_eq!(
29170            datetime64_argmin_former_body_wxjca(&reference_a),
29171            candidate_a.argmin(),
29172        );
29173        assert!(candidate_a.labels.materialized.get().is_none());
29174        for _ in 0..3 {
29175            std::hint::black_box(datetime64_argmin_former_body_wxjca(&reference_a));
29176            std::hint::black_box(datetime64_argmin_former_body_wxjca(&reference_b));
29177            std::hint::black_box(candidate_a.argmin());
29178            std::hint::black_box(candidate_b.argmin());
29179        }
29180
29181        let mut former_a = Vec::with_capacity(SAMPLES);
29182        let mut former_b = Vec::with_capacity(SAMPLES);
29183        let mut witness_a = Vec::with_capacity(SAMPLES);
29184        let mut witness_b = Vec::with_capacity(SAMPLES);
29185        for sample in 0..SAMPLES {
29186            if sample % 2 == 0 {
29187                former_a.push(measure_argmin_nanos_wxjca(|| {
29188                    datetime64_argmin_former_body_wxjca(&reference_a)
29189                }));
29190                witness_a.push(measure_argmin_nanos_wxjca(|| candidate_a.argmin()));
29191                witness_b.push(measure_argmin_nanos_wxjca(|| candidate_b.argmin()));
29192                former_b.push(measure_argmin_nanos_wxjca(|| {
29193                    datetime64_argmin_former_body_wxjca(&reference_b)
29194                }));
29195            } else {
29196                former_b.push(measure_argmin_nanos_wxjca(|| {
29197                    datetime64_argmin_former_body_wxjca(&reference_b)
29198                }));
29199                witness_b.push(measure_argmin_nanos_wxjca(|| candidate_b.argmin()));
29200                witness_a.push(measure_argmin_nanos_wxjca(|| candidate_a.argmin()));
29201                former_a.push(measure_argmin_nanos_wxjca(|| {
29202                    datetime64_argmin_former_body_wxjca(&reference_a)
29203                }));
29204            }
29205        }
29206
29207        let former_a_p50 = median_nanos_wxjca(&mut former_a);
29208        let former_b_p50 = median_nanos_wxjca(&mut former_b);
29209        let witness_a_p50 = median_nanos_wxjca(&mut witness_a);
29210        let witness_b_p50 = median_nanos_wxjca(&mut witness_b);
29211        let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
29212        let witness_mean = (witness_a_p50 + witness_b_p50) as f64 / 2.0;
29213
29214        println!("affine Datetime64 argmin, len={LEN}, samples={SAMPLES}");
29215        println!("former body p50 A/B: {former_a_p50} / {former_b_p50} ns");
29216        println!("affine witness p50 A/B: {witness_a_p50} / {witness_b_p50} ns");
29217        println!(
29218            "former/witness p50 ratio: {:.3}x",
29219            former_mean / witness_mean
29220        );
29221        assert!(candidate_a.labels.materialized.get().is_none());
29222        assert!(candidate_b.labels.materialized.get().is_none());
29223    }
29224
29225    #[test]
29226    fn datetime64_affine_argmax_matches_eager_oracle_h453b() {
29227        let cases = [
29228            ("empty", 0, 0, 0),
29229            ("singleton", 7, 0, 1),
29230            ("singleton_nat", i64::MIN, 0, 1),
29231            ("ascending", 0, 2, 4),
29232            ("descending", 12, -4, 4),
29233            ("nat_start", i64::MIN, 1, 4),
29234            ("nat_end", i64::MIN + 3, -1, 4),
29235            ("near_max", i64::MAX, -1, 3),
29236        ];
29237
29238        for (name, start, step, len) in cases {
29239            let affine = Index::from_datetime64_affine_range(start, step, len)
29240                .expect("valid Datetime64 affine range");
29241            let eager_values = (0..len)
29242                .map(|offset| {
29243                    let offset = i64::try_from(offset).expect("test offset fits i64");
29244                    start
29245                        .checked_add(step.checked_mul(offset).expect("test span fits i64"))
29246                        .expect("test endpoint fits i64")
29247                })
29248                .collect();
29249            let eager = Index::from_datetime64(eager_values);
29250
29251            assert_eq!(affine.argmax(), eager.argmax(), "{name}");
29252            assert!(
29253                affine.labels.materialized.get().is_none(),
29254                "{name}: affine argmax must not materialize labels",
29255            );
29256            assert!(
29257                affine.labels.int64_typed.get().is_none(),
29258                "{name}: affine argmax must not probe the Int64 view",
29259            );
29260        }
29261    }
29262
29263    fn datetime64_argmax_former_body_h453b(index: &Index) -> Option<usize> {
29264        if let Some(affine) = index.labels.int64_affine_range() {
29265            return (affine.len > 0).then(|| if affine.step >= 0 { affine.len - 1 } else { 0 });
29266        }
29267        if index.labels.has_lazy_int64_backing()
29268            && let Some(values) = index.labels.int64_view()
29269        {
29270            return values
29271                .iter()
29272                .enumerate()
29273                .max_by(|(_, a), (_, b)| a.cmp(b))
29274                .map(|(i, _)| i);
29275        }
29276        index
29277            .labels
29278            .iter()
29279            .enumerate()
29280            .max_by(|(_, a), (_, b)| a.cmp(b))
29281            .map(|(i, _)| i)
29282    }
29283
29284    #[test]
29285    #[ignore = "perf A/B; run with --ignored --nocapture"]
29286    fn datetime64_affine_argmax_profile_h453b() {
29287        const LEN: usize = 250_000;
29288        const SAMPLES: usize = 10;
29289        let former_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29290        let former_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29291        let witness_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29292        let witness_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
29293
29294        assert_eq!(
29295            datetime64_argmax_former_body_h453b(&former_a),
29296            witness_a.argmax(),
29297        );
29298        for _ in 0..3 {
29299            std::hint::black_box(datetime64_argmax_former_body_h453b(&former_a));
29300            std::hint::black_box(witness_a.argmax());
29301            std::hint::black_box(witness_b.argmax());
29302            std::hint::black_box(datetime64_argmax_former_body_h453b(&former_b));
29303        }
29304
29305        let measure = |f: &dyn Fn() -> Option<usize>| {
29306            let started = std::time::Instant::now();
29307            std::hint::black_box(f());
29308            started.elapsed().as_nanos()
29309        };
29310        let mut former_a_ns = Vec::with_capacity(SAMPLES);
29311        let mut former_b_ns = Vec::with_capacity(SAMPLES);
29312        let mut witness_a_ns = Vec::with_capacity(SAMPLES);
29313        let mut witness_b_ns = Vec::with_capacity(SAMPLES);
29314        for sample in 0..SAMPLES {
29315            if sample % 2 == 0 {
29316                former_a_ns.push(measure(&|| datetime64_argmax_former_body_h453b(&former_a)));
29317                witness_a_ns.push(measure(&|| witness_a.argmax()));
29318                witness_b_ns.push(measure(&|| witness_b.argmax()));
29319                former_b_ns.push(measure(&|| datetime64_argmax_former_body_h453b(&former_b)));
29320            } else {
29321                former_b_ns.push(measure(&|| datetime64_argmax_former_body_h453b(&former_b)));
29322                witness_b_ns.push(measure(&|| witness_b.argmax()));
29323                witness_a_ns.push(measure(&|| witness_a.argmax()));
29324                former_a_ns.push(measure(&|| datetime64_argmax_former_body_h453b(&former_a)));
29325            }
29326        }
29327
29328        for samples in [
29329            &mut former_a_ns,
29330            &mut former_b_ns,
29331            &mut witness_a_ns,
29332            &mut witness_b_ns,
29333        ] {
29334            samples.sort_unstable();
29335        }
29336        let middle = SAMPLES / 2;
29337        let former_a_p50 = former_a_ns[middle];
29338        let former_b_p50 = former_b_ns[middle];
29339        let witness_a_p50 = witness_a_ns[middle];
29340        let witness_b_p50 = witness_b_ns[middle];
29341        let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
29342        let witness_mean = (witness_a_p50 + witness_b_p50) as f64 / 2.0;
29343        println!("affine Datetime64 argmax, len={LEN}, samples={SAMPLES}");
29344        println!("former body p50 A/B: {former_a_p50} / {former_b_p50} ns");
29345        println!("affine witness p50 A/B: {witness_a_p50} / {witness_b_p50} ns");
29346        println!(
29347            "former/witness p50 ratio: {:.3}x",
29348            former_mean / witness_mean
29349        );
29350    }
29351
29352    #[test]
29353    fn int64_argminmax_avoid_label_materialization_ikbh9() {
29354        // Ascending affine [0,2,4,6]: argmin=0, argmax=len-1. O(1), no materialization.
29355        let asc = Index::new_known_unique_int64_affine_range(0, 2, 4).unwrap();
29356        assert!(asc.labels.materialized.get().is_none());
29357        assert_eq!(asc.argmin(), Some(0));
29358        assert_eq!(asc.argmax(), Some(3));
29359        assert!(
29360            asc.labels.materialized.get().is_none(),
29361            "affine argmin/argmax must not materialize labels"
29362        );
29363
29364        // Descending affine [12,8,4,0]: argmin at the end, argmax at the front.
29365        let desc = Index::new_known_unique_int64_affine_range(12, -4, 4).unwrap();
29366        assert!(desc.labels.materialized.get().is_none());
29367        assert_eq!(desc.argmin(), Some(3));
29368        assert_eq!(desc.argmax(), Some(0));
29369        assert!(desc.labels.materialized.get().is_none());
29370
29371        // Typed Int64 with ties. Rust's min_by returns the FIRST of equal
29372        // minima, max_by the LAST of equal maxima — the i64-view fast path must
29373        // match exactly. [3,1,1,2] -> min 1 first at idx 1; max 3 unique at idx 0.
29374        let tied = Index::from_i64_values(vec![3, 1, 1, 2]);
29375        assert!(tied.labels.materialized.get().is_none());
29376        assert_eq!(tied.argmin(), Some(1));
29377        assert_eq!(tied.argmax(), Some(0));
29378        assert!(
29379            tied.labels.materialized.get().is_none(),
29380            "typed Int64 argmin/argmax must not materialize labels"
29381        );
29382
29383        // Bit-identical to the object-label path (which also has ties).
29384        let obj = Index::new(vec![
29385            IndexLabel::Int64(3),
29386            IndexLabel::Int64(1),
29387            IndexLabel::Int64(1),
29388            IndexLabel::Int64(2),
29389        ]);
29390        assert_eq!(obj.argmin(), tied.argmin());
29391        assert_eq!(obj.argmax(), tied.argmax());
29392
29393        // Tied maxima: [5,2,5,1] -> max 5 at idx 0,2 -> max_by last = 2; min 1 at idx 3.
29394        let tied_max = Index::from_i64_values(vec![5, 2, 5, 1]);
29395        assert_eq!(tied_max.argmax(), Some(2));
29396        assert_eq!(tied_max.argmin(), Some(3));
29397
29398        // Single element and empty.
29399        assert_eq!(Index::from_i64_values(vec![7]).argmin(), Some(0));
29400        assert_eq!(Index::from_i64_values(vec![7]).argmax(), Some(0));
29401        assert_eq!(Index::from_i64_values(Vec::new()).argmin(), None);
29402        assert_eq!(Index::from_i64_values(Vec::new()).argmax(), None);
29403    }
29404
29405    #[test]
29406    fn int64_minmax_avoid_label_materialization_uza04151() {
29407        // Ascending affine [0,2,4,6]: min/max are closed-form endpoints.
29408        let asc = Index::new_known_unique_int64_affine_range(0, 2, 4).unwrap();
29409        assert!(asc.labels.materialized.get().is_none());
29410        assert_eq!(asc.min(), Some(IndexLabel::Int64(0)));
29411        assert_eq!(asc.max(), Some(IndexLabel::Int64(6)));
29412        assert!(
29413            asc.labels.materialized.get().is_none(),
29414            "affine min/max must not materialize labels"
29415        );
29416
29417        // Descending affine [12,8,4,0]: min/max swap endpoints.
29418        let desc = Index::new_known_unique_int64_affine_range(12, -4, 4).unwrap();
29419        assert!(desc.labels.materialized.get().is_none());
29420        assert_eq!(desc.min(), Some(IndexLabel::Int64(0)));
29421        assert_eq!(desc.max(), Some(IndexLabel::Int64(12)));
29422        assert!(desc.labels.materialized.get().is_none());
29423
29424        // Lazy typed Int64 scans the raw i64 view, preserving scalar results.
29425        let typed = Index::from_i64_values(vec![5, 2, 5, 1]);
29426        assert!(typed.labels.materialized.get().is_none());
29427        assert_eq!(typed.min(), Some(IndexLabel::Int64(1)));
29428        assert_eq!(typed.max(), Some(IndexLabel::Int64(5)));
29429        assert!(
29430            typed.labels.materialized.get().is_none(),
29431            "typed Int64 min/max must not materialize labels"
29432        );
29433
29434        let obj = Index::new(vec![
29435            IndexLabel::Int64(5),
29436            IndexLabel::Int64(2),
29437            IndexLabel::Int64(5),
29438            IndexLabel::Int64(1),
29439        ]);
29440        assert_eq!(obj.min(), typed.min());
29441        assert_eq!(obj.max(), typed.max());
29442
29443        assert_eq!(Index::from_i64_values(Vec::new()).min(), None);
29444        assert_eq!(Index::from_i64_values(Vec::new()).max(), None);
29445    }
29446
29447    #[test]
29448    fn int64_nunique_avoid_label_materialization_a55d8() {
29449        // Affine range: nunique == len for either dropna, no materialization.
29450        let asc = Index::new_known_unique_int64_affine_range(0, 2, 5).unwrap();
29451        assert!(asc.labels.materialized.get().is_none());
29452        assert_eq!(asc.nunique(), 5);
29453        assert_eq!(asc.nunique_with_dropna(false), 5);
29454        assert!(
29455            asc.labels.materialized.get().is_none(),
29456            "affine nunique must not materialize labels"
29457        );
29458
29459        // Descending affine and unit range behave the same.
29460        let desc = Index::new_known_unique_int64_affine_range(20, -5, 4).unwrap();
29461        assert_eq!(desc.nunique(), 4);
29462        assert!(desc.labels.materialized.get().is_none());
29463
29464        // Equivalence vs the object-label path (with a duplicate).
29465        let obj = Index::new(vec![
29466            IndexLabel::Int64(1),
29467            IndexLabel::Int64(1),
29468            IndexLabel::Int64(2),
29469        ]);
29470        assert_eq!(obj.nunique(), 2);
29471    }
29472
29473    #[test]
29474    fn sorted_int64_get_indexer_avoids_label_materialization_codb() {
29475        let source = Index::from_i64_values(vec![1, 3, 5, 9]).set_name("n");
29476        let sorted_target = Index::from_i64_values(vec![0, 3, 3, 6, 9]);
29477        let unsorted_target = Index::from_i64_values(vec![9, 1, 4, 5]);
29478        assert!(source.labels.materialized.get().is_none());
29479        assert!(sorted_target.labels.materialized.get().is_none());
29480        assert!(unsorted_target.labels.materialized.get().is_none());
29481
29482        let sorted_actual = source.get_indexer(&sorted_target);
29483        let unsorted_actual = source.get_indexer(&unsorted_target);
29484
29485        assert_eq!(sorted_actual, vec![None, Some(1), Some(1), None, Some(3)]);
29486        assert_eq!(unsorted_actual, vec![Some(3), Some(0), None, Some(2)]);
29487        assert!(
29488            source.labels.materialized.get().is_none(),
29489            "sorted Int64 source should stay on raw backing"
29490        );
29491        assert!(
29492            sorted_target.labels.materialized.get().is_none(),
29493            "sorted Int64 target should stay on raw backing"
29494        );
29495        assert!(
29496            unsorted_target.labels.materialized.get().is_none(),
29497            "unsorted Int64 target should stay on raw backing"
29498        );
29499
29500        let materialized_source = Index::new(vec![
29501            IndexLabel::Int64(1),
29502            IndexLabel::Int64(3),
29503            IndexLabel::Int64(5),
29504            IndexLabel::Int64(9),
29505        ]);
29506        let materialized_sorted_target = Index::new(vec![
29507            IndexLabel::Int64(0),
29508            IndexLabel::Int64(3),
29509            IndexLabel::Int64(3),
29510            IndexLabel::Int64(6),
29511            IndexLabel::Int64(9),
29512        ]);
29513        let materialized_unsorted_target = Index::new(vec![
29514            IndexLabel::Int64(9),
29515            IndexLabel::Int64(1),
29516            IndexLabel::Int64(4),
29517            IndexLabel::Int64(5),
29518        ]);
29519        assert_eq!(
29520            sorted_actual,
29521            materialized_source.get_indexer(&materialized_sorted_target)
29522        );
29523        assert_eq!(
29524            unsorted_actual,
29525            materialized_source.get_indexer(&materialized_unsorted_target)
29526        );
29527    }
29528
29529    #[test]
29530    fn int64_position_avoids_label_materialization_codb() {
29531        let sorted = Index::from_i64_values(vec![1, 3, 5, 9]);
29532        let unsorted = Index::from_i64_values(vec![5, 1, 5, 3]);
29533        assert!(sorted.labels.materialized.get().is_none());
29534        assert!(unsorted.labels.materialized.get().is_none());
29535
29536        assert_eq!(sorted.position(&IndexLabel::Int64(5)), Some(2));
29537        assert_eq!(sorted.get_loc(&IndexLabel::Int64(7)), None);
29538        assert!(!sorted.contains(&IndexLabel::Utf8("5".to_owned())));
29539        assert_eq!(unsorted.position(&IndexLabel::Int64(5)), Some(0));
29540        assert_eq!(unsorted.position(&IndexLabel::Int64(3)), Some(3));
29541
29542        assert!(
29543            sorted.labels.materialized.get().is_none(),
29544            "sorted Int64 position should stay on raw backing"
29545        );
29546        assert!(
29547            unsorted.labels.materialized.get().is_none(),
29548            "unsorted Int64 position should stay on raw backing"
29549        );
29550
29551        let materialized_sorted = Index::new(vec![
29552            IndexLabel::Int64(1),
29553            IndexLabel::Int64(3),
29554            IndexLabel::Int64(5),
29555            IndexLabel::Int64(9),
29556        ]);
29557        let materialized_unsorted = Index::new(vec![
29558            IndexLabel::Int64(5),
29559            IndexLabel::Int64(1),
29560            IndexLabel::Int64(5),
29561            IndexLabel::Int64(3),
29562        ]);
29563        assert_eq!(
29564            sorted.position(&IndexLabel::Int64(5)),
29565            materialized_sorted.position(&IndexLabel::Int64(5))
29566        );
29567        assert_eq!(
29568            unsorted.position(&IndexLabel::Int64(5)),
29569            materialized_unsorted.position(&IndexLabel::Int64(5))
29570        );
29571    }
29572
29573    #[test]
29574    fn int64_index_mutation_fast_paths_match_materialized_2bgtq() {
29575        // Differential harness (br-frankenpandas-2bgtq): insert (uza04.152),
29576        // delete (uza04.150), groupby (xk18v) and take on lazy Int64 indexes must
29577        // produce the same result as the materialized fallback. Deterministic
29578        // seeded LCG — no rand crate, no mocks.
29579        let mut state: u64 = 0x84242_u64.wrapping_mul(0x9e37_79b9);
29580        let mut next = || {
29581            state = state
29582                .wrapping_mul(6_364_136_223_846_793_005)
29583                .wrapping_add(1_442_695_040_888_963_407);
29584            (state >> 33) as u32
29585        };
29586
29587        for iter in 0..2500u32 {
29588            let len = (next() % 11) as usize;
29589            let mut vals: Vec<i64> = (0..len).map(|_| (next() % 9) as i64 - 4).collect();
29590            if next() % 3 == 0 {
29591                vals.sort_unstable();
29592            }
29593            let lazy = Index::from_i64_values(vals.clone());
29594            let mat = Index::new(
29595                vals.iter()
29596                    .copied()
29597                    .map(IndexLabel::Int64)
29598                    .collect::<Vec<_>>(),
29599            );
29600            let ctx = format!("iter={iter} vals={vals:?}");
29601
29602            // groupby (xk18v): label -> positions map must match exactly.
29603            assert_eq!(lazy.groupby(), mat.groupby(), "groupby {ctx}");
29604
29605            // insert (uza04.152) at a random valid loc with an Int64 item and,
29606            // occasionally, a non-Int64 item to exercise the dtype transition.
29607            let loc = (next() as usize) % (len + 1);
29608            let item = if next() % 4 == 0 {
29609                IndexLabel::Utf8(format!("s{}", next() % 3))
29610            } else {
29611                IndexLabel::Int64((next() % 11) as i64 - 5)
29612            };
29613            let li = lazy.insert(loc, item.clone());
29614            let mi = mat.insert(loc, item.clone());
29615            assert_eq!(li.is_ok(), mi.is_ok(), "insert ok {ctx} loc={loc}");
29616            if let (Ok(a), Ok(b)) = (&li, &mi) {
29617                assert_eq!(
29618                    a.labels(),
29619                    b.labels(),
29620                    "insert labels {ctx} loc={loc} item={item:?}"
29621                );
29622            }
29623
29624            // delete (uza04.150) at a random valid loc.
29625            if len > 0 {
29626                let dloc = (next() as usize) % len;
29627                let ld = lazy.delete(dloc);
29628                let md = mat.delete(dloc);
29629                assert_eq!(ld.is_ok(), md.is_ok(), "delete ok {ctx} dloc={dloc}");
29630                if let (Ok(a), Ok(b)) = (&ld, &md) {
29631                    assert_eq!(a.labels(), b.labels(), "delete labels {ctx} dloc={dloc}");
29632                }
29633
29634                // take with random in-range positions (possibly repeated / reordered).
29635                let k = (next() % 6) as usize;
29636                let positions: Vec<usize> = (0..k).map(|_| (next() as usize) % len).collect();
29637                assert_eq!(
29638                    lazy.take(&positions).labels(),
29639                    mat.take(&positions).labels(),
29640                    "take {ctx} positions={positions:?}"
29641                );
29642            }
29643        }
29644    }
29645
29646    #[test]
29647    fn int64_affine_lookup_fast_paths_match_materialized_q70pn() {
29648        // Differential harness (br-frankenpandas-q70pn): affine Int64 lookup fast
29649        // paths (searchsorted arithmetic lngwv, asof 1851g/4jr8s, affine get_loc/
29650        // position) must agree with the materialized binary-search/linear fallback
29651        // for every query. Deterministic seeded LCG — no rand crate, no mocks.
29652        let mut state: u64 = 0x2545_f491_4f6c_dd1d;
29653        let mut next = || {
29654            state = state
29655                .wrapping_mul(6_364_136_223_846_793_005)
29656                .wrapping_add(1_442_695_040_888_963_407);
29657            (state >> 33) as u32
29658        };
29659
29660        for iter in 0..2000u32 {
29661            // Ascending affine range (step > 0) so searchsorted/asof are valid.
29662            let len = (next() % 9) as usize + 1;
29663            let start = (next() % 11) as i64 - 5;
29664            let step = (next() % 4) as i64 + 1; // 1..=4
29665            let Some(affine) = Index::new_known_unique_int64_affine_range(start, step, len) else {
29666                continue;
29667            };
29668            let vals: Vec<i64> = (0..len as i64).map(|i| start + step * i).collect();
29669            let mat = Index::new(
29670                vals.iter()
29671                    .copied()
29672                    .map(IndexLabel::Int64)
29673                    .collect::<Vec<_>>(),
29674            );
29675
29676            // Query span: below min, exact elements, between elements, above max.
29677            let lo = start - 2;
29678            let hi = start + step * (len as i64 - 1) + 2;
29679            for q in lo..=hi {
29680                let label = IndexLabel::Int64(q);
29681                let ctx = format!("iter={iter} start={start} step={step} len={len} q={q}");
29682
29683                assert_eq!(affine.get_loc(&label), mat.get_loc(&label), "get_loc {ctx}");
29684                assert_eq!(
29685                    affine.position(&label),
29686                    mat.position(&label),
29687                    "position {ctx}"
29688                );
29689                assert_eq!(affine.asof(&label), mat.asof(&label), "asof {ctx}");
29690                for side in ["left", "right"] {
29691                    assert_eq!(
29692                        affine.searchsorted(&label, side).unwrap(),
29693                        mat.searchsorted(&label, side).unwrap(),
29694                        "searchsorted side={side} {ctx}"
29695                    );
29696                }
29697            }
29698
29699            // get_indexer over a small mixed target (present + absent keys).
29700            let targ_vals: Vec<i64> = (0..4).map(|_| (next() % 14) as i64 - 6).collect();
29701            let target = Index::new(
29702                targ_vals
29703                    .iter()
29704                    .copied()
29705                    .map(IndexLabel::Int64)
29706                    .collect::<Vec<_>>(),
29707            );
29708            assert_eq!(
29709                affine.get_indexer(&target),
29710                mat.get_indexer(&target),
29711                "get_indexer iter={iter} targ={targ_vals:?}"
29712            );
29713        }
29714    }
29715
29716    #[test]
29717    fn affine_get_indexer_probes_typed_targets_without_materializing_3gsa7() {
29718        let source = Index::new_known_unique_int64_affine_range(10, 2, 5).unwrap();
29719        let targets = Index::from_i64_values(vec![10, 11, 16, 99, 12]);
29720
29721        assert_eq!(
29722            source.get_indexer(&targets),
29723            vec![Some(0), None, Some(3), None, Some(1)]
29724        );
29725        assert!(
29726            source.cached_int64_label_values().is_none(),
29727            "affine source lookup must not materialize an i64 label vector"
29728        );
29729        assert!(
29730            targets.labels.materialized.get().is_none(),
29731            "typed target lookup must not box values into IndexLabel"
29732        );
29733
29734        let all_miss = Index::new_known_unique_int64_affine_range(11, 2, 5).unwrap();
29735        assert_eq!(source.get_indexer(&all_miss), vec![None; 5]);
29736        assert!(all_miss.cached_int64_label_values().is_none());
29737
29738        let descending = Index::new_known_unique_int64_affine_range(18, -2, 5).unwrap();
29739        assert_eq!(
29740            descending.get_indexer(&targets),
29741            vec![Some(4), None, Some(1), None, Some(3)]
29742        );
29743        assert!(descending.cached_int64_label_values().is_none());
29744
29745        // Planted negative: a non-Int64 target cannot match an affine Int64
29746        // source and must not be treated as a numerically compatible label.
29747        let non_int64 = Index::new(vec![IndexLabel::Utf8("10".to_owned())]);
29748        assert_eq!(source.get_indexer(&non_int64), vec![None]);
29749    }
29750
29751    #[test]
29752    fn affine_index_searchsorted_avoids_materialization_lngwv() {
29753        let affine = Index::new_known_unique_int64_affine_range(1, 2, 4).unwrap();
29754        for (needle, left, right) in [(0, 0, 0), (1, 0, 1), (2, 1, 1), (7, 3, 4), (8, 4, 4)] {
29755            let needle = IndexLabel::Int64(needle);
29756            assert_eq!(affine.searchsorted(&needle, "left").unwrap(), left);
29757            assert_eq!(affine.searchsorted(&needle, "right").unwrap(), right);
29758        }
29759        assert!(
29760            affine.cached_int64_label_values().is_none(),
29761            "affine searchsorted should not materialize the raw i64 view"
29762        );
29763
29764        let extreme = Index::new_known_unique_int64_affine_range(i64::MIN, i64::MAX, 2).unwrap();
29765        for (needle, left, right) in [
29766            (i64::MIN, 0, 1),
29767            (i64::MIN + 1, 1, 1),
29768            (-1, 1, 2),
29769            (i64::MAX, 2, 2),
29770        ] {
29771            let needle = IndexLabel::Int64(needle);
29772            assert_eq!(extreme.searchsorted(&needle, "left").unwrap(), left);
29773            assert_eq!(extreme.searchsorted(&needle, "right").unwrap(), right);
29774        }
29775        assert!(extreme.cached_int64_label_values().is_none());
29776
29777        let singleton = Index::new_known_unique_int64_affine_range(7, i64::MIN, 1).unwrap();
29778        for (needle, left, right) in [(6, 0, 0), (7, 0, 1), (8, 1, 1)] {
29779            let needle = IndexLabel::Int64(needle);
29780            assert_eq!(singleton.searchsorted(&needle, "left").unwrap(), left);
29781            assert_eq!(singleton.searchsorted(&needle, "right").unwrap(), right);
29782        }
29783        assert!(singleton.cached_int64_label_values().is_none());
29784
29785        let empty = Index::new_known_unique_int64_affine_range(0, 0, 0).unwrap();
29786        assert_eq!(
29787            empty
29788                .searchsorted(&IndexLabel::Int64(i64::MAX), "right")
29789                .unwrap(),
29790            0
29791        );
29792        assert!(empty.cached_int64_label_values().is_none());
29793    }
29794
29795    #[test]
29796    fn affine_take_arithmetic_positions_match_materialized_blackthrush() {
29797        // Differential harness (BlackThrush): the affine-in/affine-out `take`
29798        // fast paths (`Index::take_affine_positions` + `RangeIndex::take_
29799        // arithmetic_positions`) must produce the identical labels, in the
29800        // identical order, as a materialized gather — for arithmetic position
29801        // sequences (the fast path) AND non-arithmetic ones (the fallback).
29802        // Deterministic seeded LCG, no rand crate, no mocks.
29803        let mut state: u64 = 0x9e37_79b9_7f4a_7c15;
29804        let mut next = || {
29805            state = state
29806                .wrapping_mul(6_364_136_223_846_793_005)
29807                .wrapping_add(1_442_695_040_888_963_407);
29808            (state >> 33) as u32
29809        };
29810
29811        for iter in 0..3000u32 {
29812            let len = (next() % 40) as usize + 1;
29813            let start = (next() % 21) as i64 - 10;
29814            let step = (next() % 7) as i64 - 3; // -3..=3 (incl. 0)
29815            let Some(affine) = Index::new_known_unique_int64_affine_range(start, step, len) else {
29816                continue;
29817            };
29818            let vals: Vec<i64> = (0..len as i64)
29819                .map(|i| start.checked_add(step.checked_mul(i).unwrap()).unwrap())
29820                .collect();
29821            let mat = Index::new(
29822                vals.iter()
29823                    .copied()
29824                    .map(IndexLabel::Int64)
29825                    .collect::<Vec<_>>(),
29826            );
29827
29828            // RangeIndex equivalent (positive step only; RangeIndex requires it).
29829            let range = if step > 0 {
29830                RangeIndex::new(start, start + step * len as i64, step).ok()
29831            } else {
29832                None
29833            };
29834
29835            // Build a position sequence: arithmetic (constant stride) most of the
29836            // time, occasionally non-arithmetic, occasionally empty/single.
29837            let mode = next() % 5;
29838            let positions: Vec<usize> = match mode {
29839                0 => Vec::new(),
29840                1 => vec![(next() as usize) % len],
29841                2 | 3 => {
29842                    // arithmetic in-bounds: pick pstart, pstep, count s.t. all < len.
29843                    let count = (next() % 8) as usize + 2;
29844                    let pstep = (next() % 3) as usize + 1;
29845                    let max_start = len.saturating_sub(1 + pstep * (count - 1));
29846                    if max_start == 0 && len <= pstep * (count - 1) {
29847                        continue;
29848                    }
29849                    let pstart = (next() as usize) % (max_start + 1);
29850                    (0..count).map(|k| pstart + pstep * k).collect()
29851                }
29852                _ => {
29853                    // arbitrary (likely non-arithmetic) in-bounds positions.
29854                    let count = (next() % 6) as usize + 1;
29855                    (0..count).map(|_| (next() as usize) % len).collect()
29856                }
29857            };
29858
29859            let ctx = format!("iter={iter} start={start} step={step} len={len} pos={positions:?}");
29860            let oracle: Vec<IndexLabel> = positions
29861                .iter()
29862                .map(|&p| IndexLabel::Int64(vals[p]))
29863                .collect();
29864
29865            assert_eq!(
29866                affine.take(&positions).labels(),
29867                oracle,
29868                "affine take {ctx}"
29869            );
29870            assert_eq!(
29871                mat.take(&positions).labels(),
29872                oracle,
29873                "materialized take {ctx}"
29874            );
29875
29876            if let Some(range) = &range {
29877                let got = range.take(&positions).expect("range take in-bounds");
29878                assert_eq!(got.labels(), oracle, "range take {ctx}");
29879            }
29880        }
29881    }
29882
29883    #[test]
29884    fn arithmetic_take_stays_lazy_and_range_reports_oob_3gsa7() {
29885        let affine = Index::new_known_unique_int64_affine_range(10, 3, 10).unwrap();
29886        let taken = affine.take(&[1, 3, 5]);
29887        assert_eq!(
29888            taken.labels.int64_affine_range(),
29889            Some(Int64AffineLabels {
29890                start: 13,
29891                step: 6,
29892                len: 3,
29893            })
29894        );
29895        assert!(
29896            taken.cached_int64_label_values().is_none(),
29897            "arithmetic Index::take must retain its affine witness without raw-label materialization"
29898        );
29899
29900        let range = RangeIndex::new(10, 40, 3).unwrap();
29901        let range_taken = range.take(&[1, 3, 5]).unwrap();
29902        assert_eq!(
29903            range_taken.labels.int64_affine_range(),
29904            taken.labels.int64_affine_range()
29905        );
29906        assert!(
29907            range_taken.cached_int64_label_values().is_none(),
29908            "arithmetic RangeIndex::take must retain its affine witness without raw-label materialization"
29909        );
29910
29911        let error = range.take(&[1, 3, 10]).unwrap_err();
29912        assert!(matches!(
29913            error,
29914            super::IndexError::OutOfBounds {
29915                position: 10,
29916                length: 10,
29917            }
29918        ));
29919    }
29920
29921    #[test]
29922    fn int64_index_sort_values_monotonic_bbx5s() {
29923        // Property (br-frankenpandas-bbx5s): sort_values yields a monotonic-increasing
29924        // index equal to the sorted label multiset. Seeded LCG, no mocks.
29925        let mut st: u64 = 0x4e57_0b1c_2d3e_4f53;
29926        let mut next = || {
29927            st = st
29928                .wrapping_mul(6_364_136_223_846_793_005)
29929                .wrapping_add(1_442_695_040_888_963_407);
29930            (st >> 33) as u32
29931        };
29932        for iter in 0..800u32 {
29933            let n = (next() % 12) as usize + 1;
29934            let labels: Vec<i64> = (0..n).map(|_| (next() % 8) as i64).collect(); // dups
29935            let idx = Index::new(
29936                labels
29937                    .iter()
29938                    .copied()
29939                    .map(IndexLabel::Int64)
29940                    .collect::<Vec<_>>(),
29941            );
29942            let sorted = idx.sort_values();
29943            assert!(
29944                sorted.is_monotonic_increasing(),
29945                "monotonic iter={iter} labels={labels:?}"
29946            );
29947            let got: Vec<i64> = sorted
29948                .labels()
29949                .iter()
29950                .map(|l| match l {
29951                    IndexLabel::Int64(k) => *k,
29952                    _ => i64::MIN,
29953                })
29954                .collect();
29955            let mut exp = labels.clone();
29956            exp.sort_unstable();
29957            assert_eq!(got, exp, "sorted multiset iter={iter}");
29958        }
29959    }
29960
29961    #[test]
29962    fn int64_get_indexer_non_unique_ohq9e() {
29963        use std::collections::HashMap;
29964        // Differential (br-frankenpandas-ohq9e): get_indexer_non_unique on a
29965        // non-unique source. Per target label: all source positions concatenated
29966        // (source order), else -1 + record missing target pos. Seeded LCG, no mocks.
29967        let mut st: u64 = 0x4e57_0b1c_2d3e_4f52;
29968        let mut next = || {
29969            st = st
29970                .wrapping_mul(6_364_136_223_846_793_005)
29971                .wrapping_add(1_442_695_040_888_963_407);
29972            (st >> 33) as u32
29973        };
29974        for iter in 0..800u32 {
29975            let sn = (next() % 10) as usize + 1;
29976            let source: Vec<i64> = (0..sn).map(|_| (next() % 4) as i64).collect(); // dups
29977            let tn = (next() % 6) as usize + 1;
29978            let target: Vec<i64> = (0..tn).map(|_| (next() % 6) as i64).collect(); // some absent
29979            let src_idx = Index::new(
29980                source
29981                    .iter()
29982                    .copied()
29983                    .map(IndexLabel::Int64)
29984                    .collect::<Vec<_>>(),
29985            );
29986            let tgt_idx = Index::new(
29987                target
29988                    .iter()
29989                    .copied()
29990                    .map(IndexLabel::Int64)
29991                    .collect::<Vec<_>>(),
29992            );
29993            let (indexer, missing) = src_idx.get_indexer_non_unique(&tgt_idx);
29994
29995            // Oracle.
29996            let mut positions: HashMap<i64, Vec<usize>> = HashMap::new();
29997            for (p, &l) in source.iter().enumerate() {
29998                positions.entry(l).or_default().push(p);
29999            }
30000            let mut exp_idx: Vec<isize> = Vec::new();
30001            let mut exp_missing: Vec<usize> = Vec::new();
30002            for (tp, &l) in target.iter().enumerate() {
30003                if let Some(ps) = positions.get(&l) {
30004                    exp_idx.extend(ps.iter().map(|&p| p as isize));
30005                } else {
30006                    exp_idx.push(-1);
30007                    exp_missing.push(tp);
30008                }
30009            }
30010            assert_eq!(
30011                indexer, exp_idx,
30012                "indexer iter={iter} src={source:?} tgt={target:?}"
30013            );
30014            assert_eq!(missing, exp_missing, "missing iter={iter}");
30015        }
30016    }
30017
30018    #[test]
30019    fn int64_index_append_concat_qveej() {
30020        // Differential (br-frankenpandas-qveej): append concatenates labels in order
30021        // with no dedup (npbx4 was union/dedup). Seeded LCG, no mocks.
30022        let mut s: u64 = 0xa99e_0d1c_2b3e_4f50;
30023        let mut next = || {
30024            s = s
30025                .wrapping_mul(6_364_136_223_846_793_005)
30026                .wrapping_add(1_442_695_040_888_963_407);
30027            (s >> 33) as u32
30028        };
30029        let to_vec = |idx: &Index| -> Vec<i64> {
30030            idx.labels()
30031                .iter()
30032                .map(|l| match l {
30033                    IndexLabel::Int64(k) => *k,
30034                    _ => i64::MIN,
30035                })
30036                .collect()
30037        };
30038        for iter in 0..1000u32 {
30039            let na = (next() % 6) as usize;
30040            let nb = (next() % 6) as usize;
30041            let a: Vec<i64> = (0..na).map(|_| (next() % 6) as i64).collect();
30042            let b: Vec<i64> = (0..nb).map(|_| (next() % 6) as i64).collect();
30043            let ia = Index::new(a.iter().copied().map(IndexLabel::Int64).collect::<Vec<_>>());
30044            let ib = Index::new(b.iter().copied().map(IndexLabel::Int64).collect::<Vec<_>>());
30045            let app = ia.append(&ib);
30046            let mut exp = a.clone();
30047            exp.extend_from_slice(&b);
30048            assert_eq!(to_vec(&app), exp, "append iter={iter} a={a:?} b={b:?}");
30049        }
30050    }
30051
30052    #[test]
30053    fn int64_index_get_indexer_nonaffine_miaf7() {
30054        use std::collections::HashMap;
30055
30056        // Differential (br-frankenpandas-miaf7): get_indexer on a non-monotonic
30057        // unique Int64 index == position map, -1 for absent. Seeded LCG, no mocks.
30058        let mut state: u64 = 0x9e3a_71b5_c2d4_06f1;
30059        let mut next = || {
30060            state = state
30061                .wrapping_mul(6_364_136_223_846_793_005)
30062                .wrapping_add(1_442_695_040_888_963_407);
30063            (state >> 33) as u32
30064        };
30065        for iter in 0..1500u32 {
30066            let n = (next() % 10) as usize + 1;
30067            // Shuffled distinct labels 0..n.
30068            let mut labels: Vec<i64> = (0..n as i64).collect();
30069            for i in (1..n).rev() {
30070                let j = (next() as usize) % (i + 1);
30071                labels.swap(i, j);
30072            }
30073            let ix = Index::new(
30074                labels
30075                    .iter()
30076                    .copied()
30077                    .map(IndexLabel::Int64)
30078                    .collect::<Vec<_>>(),
30079            );
30080            let pos: HashMap<i64, usize> =
30081                labels.iter().enumerate().map(|(p, &v)| (v, p)).collect();
30082
30083            // Targets mix present (0..n) and absent (n..n+3, -1).
30084            let q = (next() % 8) as usize + 1;
30085            let targets: Vec<i64> = (0..q)
30086                .map(|_| (next() % (n as u32 + 4)) as i64 - 1)
30087                .collect();
30088            let target_ix = Index::new(
30089                targets
30090                    .iter()
30091                    .copied()
30092                    .map(IndexLabel::Int64)
30093                    .collect::<Vec<_>>(),
30094            );
30095            let got = ix.get_indexer(&target_ix);
30096            assert_eq!(got.len(), targets.len(), "len iter={iter}");
30097            for i in 0..targets.len() {
30098                let exp = pos.get(&targets[i]).copied();
30099                assert_eq!(
30100                    got[i], exp,
30101                    "get_indexer iter={iter} target={} labels={labels:?}",
30102                    targets[i]
30103                );
30104            }
30105        }
30106    }
30107
30108    #[test]
30109    fn int64_index_set_ops_match_set_oracle_npbx4() {
30110        use std::collections::BTreeSet;
30111
30112        // Differential vs BTreeSet oracle (br-frankenpandas-npbx4): union /
30113        // intersection / difference / symmetric_difference produce exactly the
30114        // expected label set, with no duplicates. Order-independent (membership).
30115        // Deterministic seeded LCG — no rand crate, no mocks.
30116        let mut state: u64 = 0x5e70_b1c2_d3e4_f506;
30117        let mut next = || {
30118            state = state
30119                .wrapping_mul(6_364_136_223_846_793_005)
30120                .wrapping_add(1_442_695_040_888_963_407);
30121            (state >> 33) as u32
30122        };
30123        let mk = |vals: &[i64]| {
30124            Index::new(
30125                vals.iter()
30126                    .copied()
30127                    .map(IndexLabel::Int64)
30128                    .collect::<Vec<_>>(),
30129            )
30130        };
30131        let to_set = |idx: &Index| -> BTreeSet<i64> {
30132            idx.labels()
30133                .iter()
30134                .map(|l| match l {
30135                    IndexLabel::Int64(k) => *k,
30136                    _ => i64::MIN,
30137                })
30138                .collect()
30139        };
30140        for iter in 0..1500u32 {
30141            // Distinct unique label subsets of 0..10.
30142            let a: Vec<i64> = (0..10i64).filter(|_| next() % 2 == 0).collect();
30143            let b: Vec<i64> = (0..10i64).filter(|_| next() % 2 == 0).collect();
30144            let ia = mk(&a);
30145            let ib = mk(&b);
30146            let aset: BTreeSet<i64> = a.iter().copied().collect();
30147            let bset: BTreeSet<i64> = b.iter().copied().collect();
30148            let ctx = format!("iter={iter} a={a:?} b={b:?}");
30149
30150            let inter = ia.intersection(&ib);
30151            let exp: BTreeSet<i64> = aset.intersection(&bset).copied().collect();
30152            assert_eq!(to_set(&inter), exp, "intersection {ctx}");
30153            assert_eq!(inter.len(), exp.len(), "intersection dedup {ctx}");
30154
30155            let uni = ia.union(&ib);
30156            let exp: BTreeSet<i64> = aset.union(&bset).copied().collect();
30157            assert_eq!(to_set(&uni), exp, "union {ctx}");
30158            assert_eq!(uni.len(), exp.len(), "union dedup {ctx}");
30159
30160            let diff = ia.difference(&ib);
30161            let exp: BTreeSet<i64> = aset.difference(&bset).copied().collect();
30162            assert_eq!(to_set(&diff), exp, "difference {ctx}");
30163            assert_eq!(diff.len(), exp.len(), "difference dedup {ctx}");
30164
30165            let sym = ia.symmetric_difference(&ib);
30166            let exp: BTreeSet<i64> = aset.symmetric_difference(&bset).copied().collect();
30167            assert_eq!(to_set(&sym), exp, "symdiff {ctx}");
30168            assert_eq!(sym.len(), exp.len(), "symdiff dedup {ctx}");
30169        }
30170    }
30171
30172    #[test]
30173    fn int64_index_fast_paths_match_materialized_fallback_yfyb9() {
30174        // Differential harness (br-frankenpandas-yfyb9): every Int64 fast path on
30175        // Index (min/max, argmin/argmax, is_monotonic_*, nunique, is_unique,
30176        // has_duplicates, hasnans, dtype predicates) must agree between a LAZY
30177        // representation (from_i64_values / affine constructor => fast path) and a
30178        // MATERIALIZED one (Index::new of IndexLabel::Int64 => fallback path) of
30179        // the SAME values. Deterministic seeded LCG — no rand crate, no mocks.
30180        let mut state: u64 = 0xd1b5_4a32_d192_ed03;
30181        let mut next = || {
30182            state = state
30183                .wrapping_mul(6_364_136_223_846_793_005)
30184                .wrapping_add(1_442_695_040_888_963_407);
30185            (state >> 33) as u32
30186        };
30187
30188        let materialized = |vals: &[i64]| {
30189            Index::new(
30190                vals.iter()
30191                    .copied()
30192                    .map(IndexLabel::Int64)
30193                    .collect::<Vec<_>>(),
30194            )
30195        };
30196        let assert_agree = |lazy: &Index, mat: &Index, ctx: &str| {
30197            assert_eq!(lazy.len(), mat.len(), "len {ctx}");
30198            assert_eq!(lazy.min(), mat.min(), "min {ctx}");
30199            assert_eq!(lazy.max(), mat.max(), "max {ctx}");
30200            assert_eq!(lazy.argmin(), mat.argmin(), "argmin {ctx}");
30201            assert_eq!(lazy.argmax(), mat.argmax(), "argmax {ctx}");
30202            assert_eq!(
30203                lazy.is_monotonic_increasing(),
30204                mat.is_monotonic_increasing(),
30205                "mono_inc {ctx}"
30206            );
30207            assert_eq!(
30208                lazy.is_monotonic_decreasing(),
30209                mat.is_monotonic_decreasing(),
30210                "mono_dec {ctx}"
30211            );
30212            assert_eq!(lazy.nunique(), mat.nunique(), "nunique {ctx}");
30213            assert_eq!(lazy.is_unique(), mat.is_unique(), "is_unique {ctx}");
30214            assert_eq!(
30215                lazy.has_duplicates(),
30216                mat.has_duplicates(),
30217                "has_duplicates {ctx}"
30218            );
30219            assert_eq!(lazy.hasnans(), mat.hasnans(), "hasnans {ctx}");
30220            assert_eq!(
30221                lazy.inferred_type(),
30222                mat.inferred_type(),
30223                "inferred_type {ctx}"
30224            );
30225            assert_eq!(lazy.dtype(), mat.dtype(), "dtype {ctx}");
30226            assert_eq!(lazy.is_integer(), mat.is_integer(), "is_integer {ctx}");
30227            assert_eq!(lazy.is_numeric(), mat.is_numeric(), "is_numeric {ctx}");
30228        };
30229
30230        // Typed Int64 (from_i64_values, fast path) vs materialized fallback.
30231        for iter in 0..2500u32 {
30232            let len = (next() % 13) as usize;
30233            let force_sorted = next() % 3 == 0;
30234            let mut vals: Vec<i64> = (0..len).map(|_| (next() % 9) as i64 - 4).collect();
30235            if force_sorted {
30236                vals.sort_unstable();
30237            }
30238            let lazy = Index::from_i64_values(vals.clone());
30239            let mat = materialized(&vals);
30240            assert_agree(&lazy, &mat, &format!("typed iter={iter} vals={vals:?}"));
30241        }
30242
30243        // Affine Int64 ranges (fast path) vs materialized fallback.
30244        for iter in 0..1500u32 {
30245            let len = (next() % 10) as usize;
30246            let start = (next() % 13) as i64 - 6;
30247            // Non-zero step for len > 1 (affine constructor requires it).
30248            let step = {
30249                let s = (next() % 7) as i64 - 3;
30250                if s == 0 { 1 } else { s }
30251            };
30252            let Some(lazy) = Index::new_known_unique_int64_affine_range(start, step, len) else {
30253                continue;
30254            };
30255            let vals: Vec<i64> = (0..len as i64).map(|i| start + step * i).collect();
30256            let mat = materialized(&vals);
30257            assert_agree(
30258                &lazy,
30259                &mat,
30260                &format!("affine iter={iter} start={start} step={step} len={len}"),
30261            );
30262        }
30263    }
30264
30265    #[test]
30266    fn index_a31qh_factorize_reindex_and_non_unique_indexer() {
30267        let idx = Index::new(vec![
30268            IndexLabel::Utf8("a".into()),
30269            IndexLabel::Utf8("b".into()),
30270            IndexLabel::Utf8("a".into()),
30271            IndexLabel::Datetime64(i64::MIN),
30272        ])
30273        .set_name("letters");
30274
30275        let (codes, uniques) = idx.factorize();
30276        assert_eq!(codes, vec![0, 1, 0, -1]);
30277        assert_eq!(
30278            uniques.labels(),
30279            &[IndexLabel::from("a"), IndexLabel::from("b")]
30280        );
30281        assert_eq!(uniques.name().map(|n| n.as_str()), Some("letters"));
30282
30283        let target = Index::new(vec![
30284            IndexLabel::Utf8("a".into()),
30285            IndexLabel::Utf8("z".into()),
30286            IndexLabel::Utf8("b".into()),
30287        ]);
30288        // ⚠️ RE-PINNED (br-frankenpandas-lerb2): this asserted [Some(0), None,
30289        // Some(1)] — one entry per target, first match only — which is
30290        // `get_indexer`'s answer, not `get_indexer_for`'s. `idx` HAS duplicates, and
30291        // the very next assertion shows both positions of "a" at 0 and 2.
30292        // pandas' rule is get_indexer when unique, else get_indexer_non_unique()[0],
30293        // so the result may be LONGER than the target. MEASURED, live pandas 2.2.3,
30294        // index [10,20,20,30] with target [20,99,10]: get_indexer_for -> [1,2,-1,0],
30295        // four entries for a three-entry target.
30296        assert_eq!(
30297            idx.get_indexer_for(&target),
30298            vec![Some(0), Some(2), None, Some(1)]
30299        );
30300        assert_eq!(
30301            idx.get_indexer_non_unique(&target),
30302            (vec![0, 2, -1, 1], vec![1])
30303        );
30304
30305        let (reindexed, positions) = idx.reindex(&target);
30306        assert_eq!(reindexed, target);
30307        assert_eq!(positions, vec![Some(0), None, Some(1)]);
30308    }
30309
30310    #[test]
30311    fn int64_get_indexer_non_unique_avoids_label_materialization_codb() {
30312        let source = Index::from_i64_values(vec![4, 2, 4, 7, 2]).set_name("source");
30313        let target = Index::from_i64_values(vec![2, 5, 4, 2]);
30314        assert!(source.labels.materialized.get().is_none());
30315        assert!(target.labels.materialized.get().is_none());
30316
30317        let actual = source.get_indexer_non_unique(&target);
30318
30319        assert_eq!(actual, (vec![1, 4, -1, 0, 2, 1, 4], vec![1]));
30320        assert!(
30321            source.labels.materialized.get().is_none(),
30322            "raw Int64 source positions should not materialize labels"
30323        );
30324        assert!(
30325            target.labels.materialized.get().is_none(),
30326            "raw Int64 targets should not materialize labels"
30327        );
30328
30329        let materialized_source = Index::new(vec![
30330            IndexLabel::Int64(4),
30331            IndexLabel::Int64(2),
30332            IndexLabel::Int64(4),
30333            IndexLabel::Int64(7),
30334            IndexLabel::Int64(2),
30335        ]);
30336        let materialized_target = Index::new(vec![
30337            IndexLabel::Int64(2),
30338            IndexLabel::Int64(5),
30339            IndexLabel::Int64(4),
30340            IndexLabel::Int64(2),
30341        ]);
30342        assert_eq!(
30343            actual,
30344            materialized_source.get_indexer_non_unique(&materialized_target)
30345        );
30346    }
30347
30348    #[test]
30349    fn sorted_int64_get_indexer_non_unique_dense_runs_codb() {
30350        let source = Index::from_i64_values(vec![1, 1, 2, 2, 2, 4, 4, 6]).set_name("source");
30351        let target = Index::from_i64_values(vec![2, 3, 1, 6, 4, 0]);
30352        assert!(source.labels.materialized.get().is_none());
30353        assert!(target.labels.materialized.get().is_none());
30354
30355        let actual = source.get_indexer_non_unique(&target);
30356
30357        assert_eq!(actual, (vec![2, 3, 4, -1, 0, 1, 7, 5, 6, -1], vec![1, 5]));
30358        assert!(
30359            source.labels.materialized.get().is_none(),
30360            "sorted dense Int64 source should stay on raw backing"
30361        );
30362        assert!(
30363            target.labels.materialized.get().is_none(),
30364            "sorted dense Int64 targets should stay on raw backing"
30365        );
30366
30367        let materialized_source = Index::new(vec![
30368            IndexLabel::Int64(1),
30369            IndexLabel::Int64(1),
30370            IndexLabel::Int64(2),
30371            IndexLabel::Int64(2),
30372            IndexLabel::Int64(2),
30373            IndexLabel::Int64(4),
30374            IndexLabel::Int64(4),
30375            IndexLabel::Int64(6),
30376        ]);
30377        let materialized_target = Index::new(vec![
30378            IndexLabel::Int64(2),
30379            IndexLabel::Int64(3),
30380            IndexLabel::Int64(1),
30381            IndexLabel::Int64(6),
30382            IndexLabel::Int64(4),
30383            IndexLabel::Int64(0),
30384        ]);
30385        assert_eq!(
30386            actual,
30387            materialized_source.get_indexer_non_unique(&materialized_target)
30388        );
30389    }
30390
30391    #[test]
30392    fn index_a31qh_set_sort_slice_and_level_aliases() {
30393        let idx = Index::from_i64(vec![3, 1, 2]).set_name("n");
30394        let sorted = idx.sort();
30395        assert_eq!(
30396            sorted.labels(),
30397            &[
30398                IndexLabel::Int64(1),
30399                IndexLabel::Int64(2),
30400                IndexLabel::Int64(3),
30401            ]
30402        );
30403        let (sortlevel, order) = idx.sortlevel();
30404        assert_eq!(sortlevel, sorted);
30405        assert_eq!(order, vec![1, 2, 0]);
30406
30407        let other = Index::from_i64(vec![2, 4]);
30408        assert_eq!(idx.union(&other), idx.union_with(&other));
30409        assert_eq!(
30410            idx.drop(&[IndexLabel::Int64(1)]),
30411            idx.drop_labels(&[IndexLabel::Int64(1)])
30412        );
30413        assert_eq!(idx.copy(), idx);
30414        assert_eq!(
30415            idx.where_(&[true, false, true], &IndexLabel::Int64(0))
30416                .labels()[1],
30417            IndexLabel::Int64(0)
30418        );
30419        assert_eq!(idx.get_level_values(0).unwrap(), idx);
30420        assert!(idx.get_level_values(1).is_err());
30421        assert!(idx.droplevel(0).is_err());
30422
30423        let sorted_lookup = Index::from_i64(vec![1, 2, 2, 4]);
30424        assert_eq!(
30425            sorted_lookup
30426                .get_slice_bound(&IndexLabel::Int64(2), "left")
30427                .unwrap(),
30428            1
30429        );
30430        assert_eq!(
30431            sorted_lookup
30432                .slice_locs(Some(&IndexLabel::Int64(2)), Some(&IndexLabel::Int64(4)))
30433                .unwrap(),
30434            (1, 4)
30435        );
30436        assert_eq!(
30437            sorted_lookup
30438                .slice_indexer(Some(&IndexLabel::Int64(2)), Some(&IndexLabel::Int64(2)))
30439                .unwrap(),
30440            (1, 3)
30441        );
30442    }
30443
30444    #[test]
30445    fn index_a31qh_astype_str_groupby_join_asof_and_diff() {
30446        let idx = Index::new(vec![
30447            IndexLabel::Utf8("Alpha".into()),
30448            IndexLabel::Utf8("beta".into()),
30449            IndexLabel::Int64(7),
30450        ]);
30451        assert_eq!(
30452            idx.r#str().lower(),
30453            vec![Some("alpha".to_owned()), Some("beta".to_owned()), None]
30454        );
30455        assert_eq!(
30456            idx.r#str().upper(),
30457            vec![Some("ALPHA".to_owned()), Some("BETA".to_owned()), None]
30458        );
30459        assert_eq!(
30460            idx.r#str().contains("ta"),
30461            vec![Some(false), Some(true), None]
30462        );
30463        assert_eq!(idx.r#str().len(), vec![Some(5), Some(4), None]);
30464        assert_eq!(idx.r#str().is_empty(), vec![Some(false), Some(false), None]);
30465        assert!(idx.astype("object").is_ok());
30466        assert!(idx.astype("float64").is_err());
30467
30468        let grouped = Index::new(vec!["a".into(), "b".into(), "a".into()]).groupby();
30469        assert_eq!(grouped[&IndexLabel::from("a")], vec![0, 2]);
30470        assert_eq!(grouped[&IndexLabel::from("b")], vec![1]);
30471
30472        let left = Index::from_i64(vec![1, 2, 3]);
30473        let right = Index::from_i64(vec![2, 4]);
30474        assert_eq!(
30475            left.join(&right, "inner").unwrap(),
30476            left.intersection(&right)
30477        );
30478        assert_eq!(left.join(&right, "outer").unwrap(), left.union_with(&right));
30479        assert_eq!(left.join(&right, "left").unwrap(), left);
30480        assert_eq!(left.join(&right, "right").unwrap(), right);
30481        assert!(left.join(&right, "sideways").is_err());
30482
30483        let sorted = Index::from_i64(vec![1, 3, 5, 7]);
30484        let probes = Index::from_i64(vec![0, 3, 4, 8]);
30485        assert_eq!(
30486            sorted.asof_locs(&probes, None),
30487            vec![None, Some(1), Some(1), Some(3)]
30488        );
30489        assert_eq!(
30490            sorted.asof_locs(&probes, Some(&[true, false, true, true])),
30491            vec![None, Some(0), Some(0), Some(3)]
30492        );
30493
30494        assert_eq!(
30495            sorted.diff(1),
30496            vec![
30497                None,
30498                Some(IndexLabel::Int64(2)),
30499                Some(IndexLabel::Int64(2)),
30500                Some(IndexLabel::Int64(2)),
30501            ]
30502        );
30503        let datetimes = Index::from_datetime64(vec![10, 25]);
30504        assert_eq!(
30505            datetimes.diff(1),
30506            vec![None, Some(IndexLabel::Timedelta64(15))]
30507        );
30508    }
30509
30510    #[test]
30511    fn int64_diff_avoids_label_materialization_codb() {
30512        let index = Index::from_i64_values(vec![10, 13, 20, i64::MIN]).set_name("n");
30513        assert!(index.labels.materialized.get().is_none());
30514
30515        let actual = index.diff(2);
30516
30517        assert_eq!(actual, vec![None, None, Some(IndexLabel::Int64(10)), None,]);
30518        assert_eq!(index.diff(99), vec![None, None, None, None]);
30519        assert_eq!(
30520            index.diff(0),
30521            vec![
30522                Some(IndexLabel::Int64(0)),
30523                Some(IndexLabel::Int64(0)),
30524                Some(IndexLabel::Int64(0)),
30525                Some(IndexLabel::Int64(0)),
30526            ]
30527        );
30528        assert!(
30529            index.labels.materialized.get().is_none(),
30530            "raw Int64 diff should not materialize source labels"
30531        );
30532
30533        let materialized = Index::new(vec![
30534            IndexLabel::Int64(10),
30535            IndexLabel::Int64(13),
30536            IndexLabel::Int64(20),
30537            IndexLabel::Int64(i64::MIN),
30538        ])
30539        .set_name("n");
30540        assert_eq!(actual, materialized.diff(2));
30541    }
30542
30543    #[test]
30544    fn int64_groupby_avoids_label_materialization_xk18v() {
30545        let idx = Index::from_i64_values(vec![2, 1, 2, 3, 1]);
30546        assert!(idx.labels.materialized.get().is_none());
30547        let grouped = idx.groupby();
30548        assert_eq!(grouped[&IndexLabel::Int64(1)], vec![1, 4]);
30549        assert_eq!(grouped[&IndexLabel::Int64(2)], vec![0, 2]);
30550        assert_eq!(grouped[&IndexLabel::Int64(3)], vec![3]);
30551        assert!(
30552            idx.labels.materialized.get().is_none(),
30553            "groupby should not materialize source Int64 labels"
30554        );
30555    }
30556
30557    // ── Index name tests ────────────────────────────────────────────
30558
30559    #[test]
30560    fn index_name_default_none() {
30561        let idx = Index::new(vec![1_i64.into(), 2_i64.into()]);
30562        assert_eq!(idx.name(), None);
30563    }
30564
30565    #[test]
30566    fn index_set_name() {
30567        let idx = Index::new(vec![1_i64.into(), 2_i64.into()]);
30568        let named = idx.set_name("year");
30569        assert_eq!(named.name().map(|n| n.as_str()), Some("year"));
30570        assert_eq!(named.labels(), idx.labels());
30571    }
30572
30573    #[test]
30574    fn index_names_keep_their_type_fvsao64() {
30575        use super::LabelName;
30576        let zero = LabelName::typed(IndexLabel::Int64(0));
30577        let named = Index::new(vec![1_i64.into()]).set_name(zero.clone());
30578        assert_eq!(
30579            named.name().map(LabelName::label),
30580            Some(IndexLabel::Int64(0))
30581        );
30582        // A name handed on keeps its label (relabel, rename by name, union
30583        // of two indexes named alike).
30584        assert_eq!(named.relabeled(vec![2_i64.into()]).name(), Some(&zero));
30585        assert_eq!(
30586            Index::new(vec![3_i64.into()])
30587                .rename_index(named.name())
30588                .name(),
30589            Some(&zero)
30590        );
30591        assert_eq!(named.union(&named.clone()).name(), Some(&zero));
30592        // NEGATIVE: the integer 0 and the string '0' are different names - a
30593        // union of indexes named each is unnamed, as pandas' - and text
30594        // names a string.
30595        let text = Index::new(vec![4_i64.into()]).set_name("0");
30596        assert_eq!(
30597            text.name().map(LabelName::label),
30598            Some(IndexLabel::Utf8("0".to_owned()))
30599        );
30600        assert_eq!(named.union(&text).name(), None);
30601        assert_eq!(named.names(), vec![Some("0".to_owned())]);
30602    }
30603
30604    #[test]
30605    fn multiindex_level_names_keep_their_type_fvsao64() {
30606        use super::LabelName;
30607        let zero = LabelName::typed(IndexLabel::Int64(0));
30608        let multi = super::MultiIndex::from_arrays(vec![
30609            vec![1_i64.into(), 2_i64.into()],
30610            vec!["x".into(), "y".into()],
30611        ])
30612        .unwrap()
30613        .set_names(vec![Some(zero.clone()), Some("b".into())]);
30614        let label = |name: &Option<LabelName>| name.as_ref().map(LabelName::label);
30615        assert_eq!(label(&multi.names()[0]), Some(IndexLabel::Int64(0)));
30616        // A level taken out keeps its typed name; a renamed level takes the
30617        // new one.
30618        assert_eq!(multi.get_level_values(0).unwrap().name(), Some(&zero));
30619        let seven = Some(LabelName::typed(IndexLabel::Int64(7)));
30620        let renamed = multi.rename_level(seven, 1).unwrap();
30621        assert_eq!(label(&renamed.names()[1]), Some(IndexLabel::Int64(7)));
30622        // NEGATIVE: a string level name is the string ('0' is not 0).
30623        let text = multi.clone().set_names(vec![Some("0".into()), None]);
30624        assert_eq!(
30625            label(&text.names()[0]),
30626            Some(IndexLabel::Utf8("0".to_owned()))
30627        );
30628        assert_ne!(text.names()[0], multi.names()[0]);
30629    }
30630
30631    #[test]
30632    fn index_set_names_some_and_none() {
30633        let idx = Index::new(vec!["a".into(), "b".into()]);
30634        let named = idx.set_names(Some("letters"));
30635        assert_eq!(named.name().map(|n| n.as_str()), Some("letters"));
30636        let cleared = named.set_names(None::<&str>);
30637        assert_eq!(cleared.name(), None);
30638    }
30639
30640    #[test]
30641    fn index_name_propagates_through_unique() {
30642        let idx = Index::new(vec![1_i64.into(), 1_i64.into(), 2_i64.into()]).set_name("id");
30643        let u = idx.unique();
30644        assert_eq!(u.name().map(|n| n.as_str()), Some("id"));
30645        assert_eq!(u.len(), 2);
30646    }
30647
30648    #[test]
30649    fn index_name_propagates_through_sort_values() {
30650        let idx = Index::new(vec![3_i64.into(), 1_i64.into(), 2_i64.into()]).set_name("val");
30651        let sorted = idx.sort_values();
30652        assert_eq!(sorted.name().map(|n| n.as_str()), Some("val"));
30653    }
30654
30655    #[test]
30656    fn index_name_propagates_through_take_and_slice() {
30657        let idx = Index::new(vec!["a".into(), "b".into(), "c".into()]).set_name("letter");
30658        assert_eq!(idx.take(&[0, 2]).name().map(|n| n.as_str()), Some("letter"));
30659        assert_eq!(idx.slice(1, 2).name().map(|n| n.as_str()), Some("letter"));
30660    }
30661
30662    #[test]
30663    fn index_name_propagates_through_map() {
30664        let idx = Index::new(vec![1_i64.into(), 2_i64.into()]).set_name("x");
30665        let mapped = idx.map(|l| match l {
30666            IndexLabel::Int64(v) => IndexLabel::Int64(v * 10),
30667            other => other.clone(),
30668        });
30669        assert_eq!(mapped.name().map(|n| n.as_str()), Some("x"));
30670    }
30671
30672    #[test]
30673    fn index_name_propagates_through_drop_labels() {
30674        let idx = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]).set_name("num");
30675        let dropped = idx.drop_labels(&[2_i64.into()]);
30676        assert_eq!(dropped.name().map(|n| n.as_str()), Some("num"));
30677        assert_eq!(dropped.len(), 2);
30678    }
30679
30680    #[test]
30681    fn index_name_propagates_through_astype() {
30682        let idx = Index::new(vec![1_i64.into(), 2_i64.into()]).set_name("n");
30683        assert_eq!(idx.astype_str().name().map(|n| n.as_str()), Some("n"));
30684        let idx2 = Index::new(vec!["1".into(), "2".into()]).set_name("s");
30685        assert_eq!(idx2.astype_int().name().map(|n| n.as_str()), Some("s"));
30686    }
30687
30688    #[test]
30689    fn index_name_shared_for_intersection() {
30690        let a = Index::new(vec![1_i64.into(), 2_i64.into()]).set_name("x");
30691        let b = Index::new(vec![2_i64.into(), 3_i64.into()]).set_name("x");
30692        assert_eq!(a.intersection(&b).name().map(|n| n.as_str()), Some("x"));
30693
30694        let c = Index::new(vec![2_i64.into(), 3_i64.into()]).set_name("y");
30695        assert_eq!(a.intersection(&c).name(), None);
30696    }
30697
30698    #[test]
30699    fn index_name_shared_for_union() {
30700        let a = Index::new(vec![1_i64.into()]).set_name("k");
30701        let b = Index::new(vec![2_i64.into()]).set_name("k");
30702        assert_eq!(a.union_with(&b).name().map(|n| n.as_str()), Some("k"));
30703
30704        let c = Index::new(vec![2_i64.into()]);
30705        assert_eq!(a.union_with(&c).name(), None);
30706    }
30707
30708    #[test]
30709    fn index_name_propagates_through_where_cond() {
30710        let idx = Index::new(vec!["a".into(), "b".into()]).set_name("col");
30711        let result = idx.where_cond(&[true, false], &"Z".into());
30712        assert_eq!(result.name().map(|n| n.as_str()), Some("col"));
30713    }
30714
30715    #[test]
30716    fn int64_where_cond_avoids_label_materialization_codb() {
30717        let index = Index::from_i64_values(vec![4, 5, 6, 7]).set_name("row");
30718        assert!(index.labels.materialized.get().is_none());
30719
30720        let replaced = index.where_cond(&[true, false, true], &IndexLabel::Int64(-1));
30721
30722        assert_eq!(replaced.name().map(|n| n.as_str()), Some("row"));
30723        assert_eq!(
30724            replaced.labels.int64_view().unwrap().as_slice(),
30725            &[4, -1, 6, -1]
30726        );
30727        assert!(index.labels.materialized.get().is_none());
30728        assert!(
30729            replaced.labels.materialized.get().is_none(),
30730            "typed Int64 where should keep typed output backing"
30731        );
30732
30733        let materialized = Index::new(vec![
30734            IndexLabel::Int64(4),
30735            IndexLabel::Int64(5),
30736            IndexLabel::Int64(6),
30737            IndexLabel::Int64(7),
30738        ]);
30739        assert_eq!(
30740            replaced.labels(),
30741            materialized
30742                .where_cond(&[true, false, true], &IndexLabel::Int64(-1))
30743                .labels()
30744        );
30745    }
30746
30747    #[test]
30748    fn affine_int64_where_cond_avoids_label_materialization_codb() {
30749        let index = Index::new_known_unique_int64_affine_range(2, 3, 4)
30750            .unwrap()
30751            .set_name("axis");
30752        assert!(index.labels.materialized.get().is_none());
30753
30754        let replaced = index.where_cond(&[false, true, true, false], &IndexLabel::Int64(0));
30755
30756        assert_eq!(replaced.name().map(|n| n.as_str()), Some("axis"));
30757        assert_eq!(
30758            replaced.labels.int64_view().unwrap().as_slice(),
30759            &[0, 5, 8, 0]
30760        );
30761        assert!(index.labels.materialized.get().is_none());
30762        assert!(
30763            replaced.labels.materialized.get().is_none(),
30764            "affine Int64 where should gather raw values into typed output"
30765        );
30766    }
30767
30768    #[test]
30769    fn index_rename_index() {
30770        let idx = Index::new(vec![1_i64.into()]);
30771        let named = idx.rename_index(Some("foo"));
30772        assert_eq!(named.name().map(|n| n.as_str()), Some("foo"));
30773        let cleared = named.rename_index(None::<&str>);
30774        assert_eq!(cleared.name(), None);
30775    }
30776
30777    #[test]
30778    fn index_equality_ignores_name() {
30779        let a = Index::new(vec![1_i64.into(), 2_i64.into()]).set_name("a");
30780        let b = Index::new(vec![1_i64.into(), 2_i64.into()]).set_name("b");
30781        assert_eq!(a, b);
30782    }
30783
30784    #[test]
30785    fn index_names_property() {
30786        let idx = Index::new(vec![1_i64.into()]);
30787        assert_eq!(idx.names(), vec![None]);
30788        let named = idx.set_name("x");
30789        assert_eq!(named.names(), vec![Some("x".to_string())]);
30790    }
30791
30792    #[test]
30793    fn index_set_names_list() {
30794        let idx = Index::new(vec![1_i64.into()]);
30795        let named = idx.set_names_list(&[Some("foo")]);
30796        assert_eq!(named.name().map(|n| n.as_str()), Some("foo"));
30797        let cleared = named.set_names_list(&[None]);
30798        assert_eq!(cleared.name(), None);
30799    }
30800
30801    #[test]
30802    fn index_to_flat_index() {
30803        let idx = Index::new(vec!["a".into(), "b".into()]).set_name("x");
30804        let flat = idx.to_flat_index();
30805        assert_eq!(flat, idx);
30806        assert_eq!(flat.name().map(|n| n.as_str()), Some("x"));
30807    }
30808
30809    // ── MultiIndex tests ──
30810
30811    #[test]
30812    fn multi_index_from_tuples() {
30813        let mi = MultiIndex::from_tuples(vec![
30814            vec!["a".into(), 1_i64.into()],
30815            vec!["a".into(), 2_i64.into()],
30816            vec!["b".into(), 1_i64.into()],
30817        ])
30818        .unwrap();
30819
30820        assert_eq!(mi.nlevels(), 2);
30821        assert_eq!(mi.len(), 3);
30822        assert!(!mi.is_empty());
30823    }
30824
30825    #[test]
30826    fn multi_index_from_tuples_ragged_errors() {
30827        let err = MultiIndex::from_tuples(vec![
30828            vec!["a".into(), 1_i64.into()],
30829            vec!["b".into()], // wrong number of levels
30830        ]);
30831        assert!(err.is_err());
30832    }
30833
30834    #[test]
30835    fn multi_index_from_arrays() {
30836        let mi = MultiIndex::from_arrays(vec![
30837            vec!["a".into(), "a".into(), "b".into()],
30838            vec![1_i64.into(), 2_i64.into(), 1_i64.into()],
30839        ])
30840        .unwrap();
30841
30842        assert_eq!(mi.nlevels(), 2);
30843        assert_eq!(mi.len(), 3);
30844    }
30845
30846    #[test]
30847    fn multi_index_from_arrays_length_mismatch_errors() {
30848        let err = MultiIndex::from_arrays(vec![
30849            vec!["a".into(), "b".into()],
30850            vec![1_i64.into()], // wrong length
30851        ]);
30852        assert!(err.is_err());
30853    }
30854
30855    #[test]
30856    fn multi_index_from_frame_preserves_column_names_a1dv9() {
30857        let mi = MultiIndex::from_frame(vec![
30858            (
30859                Some("letter".into()),
30860                vec!["a".into(), "b".into(), "b".into()],
30861            ),
30862            (
30863                Some("number".into()),
30864                vec![1_i64.into(), 1_i64.into(), 2_i64.into()],
30865            ),
30866        ])
30867        .unwrap();
30868
30869        assert_eq!(mi.names(), &[Some("letter".into()), Some("number".into())]);
30870        assert_eq!(
30871            mi.to_list(),
30872            vec![
30873                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
30874                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
30875                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
30876            ]
30877        );
30878
30879        let empty = MultiIndex::from_frame(Vec::new()).unwrap();
30880        assert!(empty.is_empty());
30881        assert_eq!(empty.nlevels(), 0);
30882    }
30883
30884    #[test]
30885    fn multi_index_from_frame_rejects_length_mismatch_a1dv9() {
30886        let err = MultiIndex::from_frame(vec![
30887            (Some("letter".into()), vec!["a".into(), "b".into()]),
30888            (Some("number".into()), vec![1_i64.into()]),
30889        ])
30890        .unwrap_err();
30891
30892        assert!(matches!(
30893            err,
30894            super::IndexError::LengthMismatch {
30895                expected: 2,
30896                actual: 1,
30897                ..
30898            }
30899        ));
30900    }
30901
30902    #[test]
30903    fn multi_index_from_product() {
30904        let mi = MultiIndex::from_product(vec![
30905            vec!["a".into(), "b".into()],
30906            vec![1_i64.into(), 2_i64.into(), 3_i64.into()],
30907        ])
30908        .unwrap();
30909
30910        assert_eq!(mi.nlevels(), 2);
30911        assert_eq!(mi.len(), 6); // 2 * 3
30912    }
30913
30914    #[test]
30915    fn multi_index_product_cardinality_rejects_overflow_uza04184() {
30916        assert_eq!(super::checked_cartesian_product_len([2, 3, 4]).unwrap(), 24);
30917        assert_eq!(
30918            super::checked_cartesian_product_len([usize::MAX, 0]).unwrap(),
30919            0
30920        );
30921        let err = super::checked_cartesian_product_len([usize::MAX, 2]).unwrap_err();
30922        assert!(matches!(
30923            err,
30924            super::IndexError::InvalidArgument(message)
30925                if message == "MultiIndex product cardinality overflow"
30926        ));
30927    }
30928
30929    #[test]
30930    fn multi_index_from_product_values() {
30931        let mi = MultiIndex::from_product(vec![
30932            vec!["x".into(), "y".into()],
30933            vec![1_i64.into(), 2_i64.into()],
30934        ])
30935        .unwrap();
30936
30937        // Should produce: (x,1), (x,2), (y,1), (y,2)
30938        assert_eq!(
30939            mi.get_tuple(0).unwrap(),
30940            vec![&IndexLabel::Utf8("x".into()), &IndexLabel::Int64(1)]
30941        );
30942        assert_eq!(
30943            mi.get_tuple(1).unwrap(),
30944            vec![&IndexLabel::Utf8("x".into()), &IndexLabel::Int64(2)]
30945        );
30946        assert_eq!(
30947            mi.get_tuple(2).unwrap(),
30948            vec![&IndexLabel::Utf8("y".into()), &IndexLabel::Int64(1)]
30949        );
30950        assert_eq!(
30951            mi.get_tuple(3).unwrap(),
30952            vec![&IndexLabel::Utf8("y".into()), &IndexLabel::Int64(2)]
30953        );
30954    }
30955
30956    #[test]
30957    fn multi_index_get_level_values() {
30958        let mi = MultiIndex::from_tuples(vec![
30959            vec!["a".into(), 1_i64.into()],
30960            vec!["b".into(), 2_i64.into()],
30961        ])
30962        .unwrap()
30963        .set_names(vec![Some("letter".into()), Some("number".into())]);
30964
30965        let level0 = mi.get_level_values(0).unwrap();
30966        assert_eq!(
30967            level0.labels(),
30968            &[IndexLabel::Utf8("a".into()), IndexLabel::Utf8("b".into())]
30969        );
30970        assert_eq!(level0.name().map(|n| n.as_str()), Some("letter"));
30971
30972        let level1 = mi.get_level_values(1).unwrap();
30973        assert_eq!(
30974            level1.labels(),
30975            &[IndexLabel::Int64(1), IndexLabel::Int64(2)]
30976        );
30977        assert_eq!(level1.name().map(|n| n.as_str()), Some("number"));
30978    }
30979
30980    #[test]
30981    fn multi_index_get_level_values_out_of_bounds() {
30982        let mi = MultiIndex::from_tuples(vec![vec!["a".into()]]).unwrap();
30983        assert!(mi.get_level_values(1).is_err());
30984    }
30985
30986    #[test]
30987    fn multi_index_metadata_shape_and_tuple_materialization() {
30988        let mi = MultiIndex::from_tuples(vec![
30989            vec!["a".into(), 1_i64.into()],
30990            vec!["a".into(), 2_i64.into()],
30991            vec!["b".into(), 1_i64.into()],
30992        ])
30993        .unwrap()
30994        .set_names(vec![Some("letter".into()), Some("number".into())]);
30995
30996        let tuples = vec![
30997            vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
30998            vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
30999            vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
31000        ];
31001        assert_eq!(mi.name(), None);
31002        assert_eq!(mi.names(), &[Some("letter".into()), Some("number".into())]);
31003        assert_eq!(mi.size(), 3);
31004        assert_eq!(mi.shape(), (3,));
31005        assert_eq!(mi.ndim(), 1);
31006        assert!(!mi.empty());
31007        assert_eq!(mi.to_list(), tuples);
31008        assert_eq!(mi.tolist(), mi.to_list());
31009        assert_eq!(mi.to_numpy(), mi.to_list());
31010        assert_eq!(mi.values(), mi.to_list());
31011        assert_eq!(mi.array(), mi.to_list());
31012        assert_eq!(mi.ravel(), mi.to_list());
31013        assert_eq!(mi.format(), vec!["(a, 1)", "(a, 2)", "(b, 1)"]);
31014        assert_eq!(mi.view(), mi);
31015        assert_eq!(mi.transpose(), mi);
31016        assert_eq!(mi.T(), mi);
31017        assert_eq!(mi.to_frame(), tuples);
31018        assert_eq!(
31019            mi.to_series(),
31020            tuples
31021                .iter()
31022                .cloned()
31023                .map(|tuple| (tuple.clone(), tuple))
31024                .collect::<Vec<_>>()
31025        );
31026    }
31027
31028    #[test]
31029    fn multi_index_levels_codes_and_levshape_exclude_missing_labels() {
31030        let mi = MultiIndex::from_tuples(vec![
31031            vec!["a".into(), 1_i64.into()],
31032            vec![IndexLabel::Datetime64(i64::MIN), 2_i64.into()],
31033            vec!["a".into(), 1_i64.into()],
31034        ])
31035        .unwrap()
31036        .set_names(vec![Some("letter".into()), Some("number".into())]);
31037
31038        let levels = mi.levels();
31039        assert_eq!(levels[0].labels(), &[IndexLabel::Utf8("a".into())]);
31040        assert_eq!(levels[0].name().map(|n| n.as_str()), Some("letter"));
31041        assert_eq!(
31042            levels[1].labels(),
31043            &[IndexLabel::Int64(1), IndexLabel::Int64(2)]
31044        );
31045        assert_eq!(levels[1].name().map(|n| n.as_str()), Some("number"));
31046        assert_eq!(mi.codes(), vec![vec![0, -1, 0], vec![0, 1, 0]]);
31047        assert_eq!(mi.levshape(), vec![1, 2]);
31048        assert!(mi.memory_usage(false) <= mi.memory_usage(true));
31049        assert_eq!(mi.nbytes(), mi.memory_usage(false));
31050    }
31051
31052    /// levels / codes are pandas' sorted catalog - numbers by value before
31053    /// strings - whatever order the labels first appear in, and set_codes /
31054    /// set_levels read them the same way (98f6w: first-seen order).
31055    #[test]
31056    fn multi_index_levels_are_sorted_as_pandas_factorizes_98f6w() {
31057        let mi = MultiIndex::from_tuples(vec![
31058            vec!["s".into(), "b".into()],
31059            vec!["n".into(), 2_i64.into()],
31060            vec!["s".into(), 1_i64.into()],
31061            vec![IndexLabel::Null(fp_types::NullKind::NaN), 1_i64.into()],
31062        ])
31063        .unwrap();
31064        let levels = mi.levels();
31065        assert_eq!(
31066            levels[0].labels(),
31067            &["n".into(), "s".into()] as &[IndexLabel]
31068        );
31069        assert_eq!(
31070            levels[1].labels(),
31071            &[1_i64.into(), 2_i64.into(), "b".into()] as &[IndexLabel]
31072        );
31073        assert_eq!(mi.codes(), vec![vec![1, 0, 1, -1], vec![2, 1, 0, 0]]);
31074        // The codes read against the levels give back every tuple.
31075        let again = mi.set_codes(mi.codes()).unwrap();
31076        for row in 0..mi.len() {
31077            assert_eq!(again.get_tuple(row), mi.get_tuple(row));
31078        }
31079        // set_levels replaces the sorted catalog: 'n' -> 'N', 's' -> 'S'.
31080        let relabelled = mi
31081            .set_levels(vec![
31082                vec!["N".into(), "S".into()],
31083                vec![1_i64.into(), 2_i64.into(), "b".into()],
31084            ])
31085            .unwrap();
31086        assert_eq!(relabelled.get_tuple(0).unwrap()[0], &IndexLabel::from("S"));
31087        assert_eq!(relabelled.get_tuple(1).unwrap()[0], &IndexLabel::from("N"));
31088        // NEGATIVE: an already sorted level keeps its order and codes.
31089        let sorted = MultiIndex::from_tuples(vec![
31090            vec!["a".into(), 1_i64.into()],
31091            vec!["b".into(), 2_i64.into()],
31092        ])
31093        .unwrap();
31094        assert_eq!(sorted.codes(), vec![vec![0, 1], vec![0, 1]]);
31095    }
31096
31097    #[test]
31098    fn multi_index_memory_usage_saturates_code_bytes_uza04178() {
31099        assert_eq!(
31100            super::multi_index_codes_memory_usage(2, 3),
31101            6 * std::mem::size_of::<isize>()
31102        );
31103        assert_eq!(
31104            super::multi_index_codes_memory_usage(usize::MAX, 2),
31105            usize::MAX
31106        );
31107        assert_eq!(
31108            super::multi_index_codes_memory_usage(2, usize::MAX),
31109            usize::MAX
31110        );
31111    }
31112
31113    #[test]
31114    fn multi_index_dtype_type_checks_and_item_match_object_index_shape() {
31115        let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])
31116            .unwrap()
31117            .set_names(vec![Some("letter".into()), Some("number".into())]);
31118
31119        assert_eq!(mi.dtype(), "object");
31120        assert_eq!(mi.dtypes(), vec!["object", "int64"]);
31121        assert_eq!(mi.inferred_type(), "mixed");
31122        assert_eq!(mi.infer_objects(), mi);
31123        assert!(!mi.holds_integer());
31124        assert!(!mi.is_boolean());
31125        assert!(!mi.is_categorical());
31126        assert!(!mi.is_floating());
31127        assert!(!mi.is_integer());
31128        assert!(!mi.is_interval());
31129        assert!(!mi.is_numeric());
31130        assert!(mi.is_object());
31131        assert!(mi.is_(&mi));
31132        assert_eq!(
31133            mi.item().unwrap(),
31134            vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)]
31135        );
31136
31137        let multi = mi.repeat(2);
31138        assert!(multi.item().is_err());
31139    }
31140
31141    #[test]
31142    fn multi_index_missing_masks_fillna_putmask_where_and_map() {
31143        let mi = MultiIndex::from_tuples(vec![
31144            vec!["a".into(), 1_i64.into()],
31145            vec![IndexLabel::Datetime64(i64::MIN), 2_i64.into()],
31146            vec!["b".into(), IndexLabel::Timedelta64(Timedelta::NAT)],
31147            vec!["c".into(), 3_i64.into()],
31148        ])
31149        .unwrap()
31150        .set_names(vec![Some("letter".into()), Some("number".into())]);
31151
31152        let missing_mask_errors = [
31153            mi.hasnans().unwrap_err(),
31154            mi.isna().unwrap_err(),
31155            mi.isnull().unwrap_err(),
31156            mi.notna().unwrap_err(),
31157            mi.notnull().unwrap_err(),
31158        ];
31159        for err in missing_mask_errors {
31160            assert!(matches!(
31161                err,
31162                super::IndexError::InvalidArgument(message)
31163                    if message == "isna is not defined for MultiIndex"
31164            ));
31165        }
31166        assert_eq!(mi.copy(), mi);
31167        assert_eq!(mi.remove_unused_levels(), mi);
31168
31169        let scalar_filled = mi.fillna(&IndexLabel::Utf8("missing".into()));
31170        assert_eq!(
31171            scalar_filled.to_list(),
31172            vec![
31173                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
31174                vec![IndexLabel::Utf8("missing".into()), IndexLabel::Int64(2)],
31175                vec![
31176                    IndexLabel::Utf8("b".into()),
31177                    IndexLabel::Utf8("missing".into())
31178                ],
31179                vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
31180            ]
31181        );
31182
31183        let tuple_filled = mi
31184            .fillna_tuple(&[IndexLabel::Utf8("z".into()), IndexLabel::Int64(0)])
31185            .unwrap();
31186        assert_eq!(
31187            tuple_filled.to_list(),
31188            vec![
31189                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
31190                vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(2)],
31191                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(0)],
31192                vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
31193            ]
31194        );
31195        assert!(
31196            mi.fillna_tuple(&[IndexLabel::Utf8("short".into())])
31197                .is_err()
31198        );
31199
31200        let masked = mi
31201            .putmask(
31202                &[false, true, false, true],
31203                vec![IndexLabel::Utf8("x".into()), IndexLabel::Int64(9)],
31204            )
31205            .unwrap();
31206        assert_eq!(
31207            masked.to_list(),
31208            vec![
31209                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
31210                vec![IndexLabel::Utf8("x".into()), IndexLabel::Int64(9)],
31211                vec![
31212                    IndexLabel::Utf8("b".into()),
31213                    IndexLabel::Timedelta64(Timedelta::NAT)
31214                ],
31215                vec![IndexLabel::Utf8("x".into()), IndexLabel::Int64(9)],
31216            ]
31217        );
31218        assert!(
31219            mi.putmask(&[true], vec![IndexLabel::Utf8("x".into())])
31220                .is_err()
31221        );
31222
31223        let where_result = mi
31224            .r#where(
31225                &[true, false, true, false],
31226                vec![IndexLabel::Utf8("fallback".into()), IndexLabel::Int64(5)],
31227            )
31228            .unwrap();
31229        assert_eq!(
31230            where_result.to_list(),
31231            vec![
31232                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
31233                vec![IndexLabel::Utf8("fallback".into()), IndexLabel::Int64(5)],
31234                vec![
31235                    IndexLabel::Utf8("b".into()),
31236                    IndexLabel::Timedelta64(Timedelta::NAT)
31237                ],
31238                vec![IndexLabel::Utf8("fallback".into()), IndexLabel::Int64(5)],
31239            ]
31240        );
31241
31242        let rendered = mi.map(|tuple| {
31243            tuple
31244                .iter()
31245                .map(ToString::to_string)
31246                .collect::<Vec<_>>()
31247                .join("|")
31248        });
31249        assert_eq!(rendered[0], "a|1");
31250        assert_eq!(rendered[3], "c|3");
31251    }
31252
31253    #[test]
31254    fn multi_index_set_levels_and_set_codes_rebuild_from_pandas_catalogs() {
31255        let mi = MultiIndex::from_tuples(vec![
31256            vec!["a".into(), 1_i64.into()],
31257            vec!["b".into(), 2_i64.into()],
31258            vec!["a".into(), 1_i64.into()],
31259        ])
31260        .unwrap()
31261        .set_names(vec![Some("letter".into()), Some("number".into())]);
31262
31263        let relabeled = mi
31264            .set_levels(vec![
31265                vec![IndexLabel::Utf8("x".into()), IndexLabel::Utf8("y".into())],
31266                vec![IndexLabel::Int64(10), IndexLabel::Int64(20)],
31267            ])
31268            .unwrap();
31269        assert_eq!(
31270            relabeled.to_list(),
31271            vec![
31272                vec![IndexLabel::Utf8("x".into()), IndexLabel::Int64(10)],
31273                vec![IndexLabel::Utf8("y".into()), IndexLabel::Int64(20)],
31274                vec![IndexLabel::Utf8("x".into()), IndexLabel::Int64(10)],
31275            ]
31276        );
31277        assert_eq!(relabeled.names(), mi.names());
31278        assert!(
31279            mi.set_levels(vec![vec![IndexLabel::Utf8("only".into())]])
31280                .is_err()
31281        );
31282        assert!(
31283            mi.set_levels(vec![
31284                vec![IndexLabel::Utf8("x".into())],
31285                vec![IndexLabel::Int64(10), IndexLabel::Int64(20)],
31286            ])
31287            .is_err()
31288        );
31289
31290        let recoded = mi.set_codes(vec![vec![1, 0, 1], vec![1, -1, 0]]).unwrap();
31291        assert_eq!(
31292            recoded.to_list(),
31293            vec![
31294                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
31295                vec![
31296                    IndexLabel::Utf8("a".into()),
31297                    IndexLabel::Datetime64(i64::MIN)
31298                ],
31299                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
31300            ]
31301        );
31302        assert_eq!(recoded.names(), mi.names());
31303        assert!(mi.set_codes(vec![vec![0, 1, 0]]).is_err());
31304        assert!(mi.set_codes(vec![vec![0, 1], vec![0, 1, 0]]).is_err());
31305        assert!(mi.set_codes(vec![vec![0, 1, 0], vec![0, 99, 0]]).is_err());
31306    }
31307
31308    #[test]
31309    fn multi_index_equals_identical_and_equal_levels_match_pandas_names() {
31310        let left = MultiIndex::from_tuples(vec![
31311            vec!["a".into(), 1_i64.into()],
31312            vec!["b".into(), 2_i64.into()],
31313        ])
31314        .unwrap()
31315        .set_names(vec![Some("letter".into()), Some("number".into())]);
31316        let renamed = left
31317            .clone()
31318            .set_names(vec![Some("letter".into()), Some("other".into())]);
31319        let reordered = MultiIndex::from_tuples(vec![
31320            vec!["b".into(), 2_i64.into()],
31321            vec!["a".into(), 1_i64.into()],
31322        ])
31323        .unwrap()
31324        .set_names(vec![Some("letter".into()), Some("number".into())]);
31325
31326        assert!(left.equals(&renamed));
31327        assert!(!left.identical(&renamed));
31328        assert!(left.equal_levels(&renamed));
31329        assert!(!left.equals(&reordered));
31330        // TEST-CHANGE (98f6w): this asserted the reordered rows' levels
31331        // differ; pandas 2.2.3 sorts each level, so they are equal
31332        // (pd.MultiIndex.from_tuples([('a', 1), ('b', 2)]).equal_levels(
31333        // pd.MultiIndex.from_tuples([('b', 2), ('a', 1)])) is True).
31334        assert!(left.equal_levels(&reordered));
31335        // NEGATIVE: a level holding another value differs.
31336        let other_value = MultiIndex::from_tuples(vec![
31337            vec!["a".into(), 1_i64.into()],
31338            vec!["c".into(), 2_i64.into()],
31339        ])
31340        .unwrap();
31341        assert!(!left.equal_levels(&other_value));
31342    }
31343
31344    #[test]
31345    fn multi_index_to_flat_index() {
31346        let mi = MultiIndex::from_tuples(vec![
31347            vec!["a".into(), 1_i64.into()],
31348            vec!["b".into(), 2_i64.into()],
31349        ])
31350        .unwrap();
31351
31352        let flat = mi.to_flat_index("_");
31353        assert_eq!(flat.labels()[0], IndexLabel::Utf8("a_1".into()));
31354        assert_eq!(flat.labels()[1], IndexLabel::Utf8("b_2".into()));
31355    }
31356
31357    #[test]
31358    fn multi_index_droplevel() {
31359        let mi = MultiIndex::from_tuples(vec![
31360            vec!["a".into(), 1_i64.into(), "x".into()],
31361            vec!["b".into(), 2_i64.into(), "y".into()],
31362        ])
31363        .unwrap()
31364        .set_names(vec![
31365            Some("l0".into()),
31366            Some("l1".into()),
31367            Some("l2".into()),
31368        ]);
31369
31370        // Drop middle level -> 2 levels remain -> MultiIndex
31371        let result = mi.droplevel(1).unwrap();
31372        assert!(
31373            matches!(&result, super::MultiIndexOrIndex::Multi(_)),
31374            "expected MultiIndex after dropping from 3 levels"
31375        );
31376        if let super::MultiIndexOrIndex::Multi(mi2) = result {
31377            assert_eq!(mi2.nlevels(), 2);
31378            assert_eq!(mi2.names(), &[Some("l0".into()), Some("l2".into())]);
31379        }
31380    }
31381
31382    #[test]
31383    fn multi_index_droplevel_to_index() {
31384        let mi = MultiIndex::from_tuples(vec![
31385            vec!["a".into(), 1_i64.into()],
31386            vec!["b".into(), 2_i64.into()],
31387        ])
31388        .unwrap()
31389        .set_names(vec![Some("letter".into()), Some("number".into())]);
31390
31391        // Drop one level from 2 -> 1 level -> plain Index
31392        let result = mi.droplevel(0).unwrap();
31393        assert!(
31394            matches!(&result, super::MultiIndexOrIndex::Index(_)),
31395            "expected Index after dropping from 2 levels"
31396        );
31397        if let super::MultiIndexOrIndex::Index(idx) = result {
31398            assert_eq!(idx.labels(), &[IndexLabel::Int64(1), IndexLabel::Int64(2)]);
31399            assert_eq!(idx.name().map(|n| n.as_str()), Some("number"));
31400        }
31401    }
31402
31403    #[test]
31404    fn multi_index_swaplevel() {
31405        let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])
31406            .unwrap()
31407            .set_names(vec![Some("first".into()), Some("second".into())]);
31408
31409        let swapped = mi.swaplevel(0, 1).unwrap();
31410        assert_eq!(
31411            swapped.names(),
31412            &[Some("second".into()), Some("first".into())]
31413        );
31414        assert_eq!(
31415            swapped.get_tuple(0).unwrap(),
31416            vec![&IndexLabel::Int64(1), &IndexLabel::Utf8("a".into())]
31417        );
31418    }
31419
31420    #[test]
31421    fn multi_index_empty() {
31422        let mi = MultiIndex::from_tuples(vec![]).unwrap();
31423        assert_eq!(mi.nlevels(), 0);
31424        assert_eq!(mi.len(), 0);
31425        assert!(mi.is_empty());
31426    }
31427
31428    #[test]
31429    fn multi_index_get_tuple_out_of_bounds() {
31430        let mi = MultiIndex::from_tuples(vec![vec!["a".into()]]).unwrap();
31431        assert!(mi.get_tuple(1).is_none());
31432    }
31433
31434    #[test]
31435    fn multi_index_get_loc_tuple_exact_and_duplicates() {
31436        let mi = MultiIndex::from_arrays(vec![
31437            vec!["east".into(), "east".into(), "west".into(), "east".into()],
31438            vec!["A".into(), "B".into(), "A".into(), "A".into()],
31439        ])
31440        .unwrap();
31441
31442        let positions = mi
31443            .get_loc_tuple(&[
31444                IndexLabel::Utf8("east".into()),
31445                IndexLabel::Utf8("A".into()),
31446            ])
31447            .unwrap();
31448        assert_eq!(positions, vec![0, 3]);
31449    }
31450
31451    #[test]
31452    fn multi_index_get_loc_level_prefix_returns_remaining_index() {
31453        let mi = MultiIndex::from_arrays(vec![
31454            vec!["east".into(), "east".into(), "west".into()],
31455            vec!["A".into(), "B".into(), "A".into()],
31456        ])
31457        .unwrap()
31458        .set_names(vec![Some("region".into()), Some("product".into())]);
31459
31460        let (positions, remaining) = mi
31461            .get_loc_level(&[IndexLabel::Utf8("east".into())])
31462            .unwrap();
31463        assert_eq!(positions, vec![0, 1]);
31464        assert!(matches!(
31465            &remaining,
31466            Some(super::MultiIndexOrIndex::Index(index))
31467                if index.labels()
31468                    == [IndexLabel::Utf8("A".into()), IndexLabel::Utf8("B".into())]
31469                    && index.name().is_some_and(|name| name == "product")
31470        ));
31471    }
31472
31473    #[test]
31474    fn multi_index_groupby_join_groups_duplicate_tuples_d89fe3() {
31475        let mi = MultiIndex::from_tuples(vec![
31476            vec!["a".into(), 1_i64.into()],
31477            vec!["b".into(), 2_i64.into()],
31478            vec!["a".into(), 1_i64.into()],
31479        ])
31480        .unwrap();
31481
31482        let groups = mi.groupby();
31483        assert_eq!(
31484            groups[&vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)]],
31485            vec![0, 2]
31486        );
31487        assert_eq!(
31488            groups[&vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)]],
31489            vec![1]
31490        );
31491    }
31492
31493    #[test]
31494    fn multi_index_groupby_join_modes_d89fe3() {
31495        let left = MultiIndex::from_tuples(vec![
31496            vec!["a".into(), 1_i64.into()],
31497            vec!["b".into(), 2_i64.into()],
31498            vec!["c".into(), 3_i64.into()],
31499        ])
31500        .unwrap();
31501        let right = MultiIndex::from_tuples(vec![
31502            vec!["b".into(), 2_i64.into()],
31503            vec!["d".into(), 4_i64.into()],
31504        ])
31505        .unwrap();
31506
31507        assert_eq!(left.join(&right, "left").unwrap(), left);
31508        assert_eq!(left.join(&right, "right").unwrap(), right);
31509        assert_eq!(
31510            left.join(&right, "inner").unwrap().to_list(),
31511            vec![vec!["b".into(), 2_i64.into()]]
31512        );
31513        assert_eq!(
31514            left.join(&right, "outer").unwrap().to_list(),
31515            vec![
31516                vec!["a".into(), 1_i64.into()],
31517                vec!["b".into(), 2_i64.into()],
31518                vec!["c".into(), 3_i64.into()],
31519                vec!["d".into(), 4_i64.into()]
31520            ]
31521        );
31522    }
31523
31524    #[test]
31525    fn multi_index_groupby_join_rejects_bad_mode_and_level_mismatch_d89fe3() {
31526        let left = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
31527        let right = MultiIndex::from_tuples(vec![vec!["a".into()]]).unwrap();
31528
31529        assert!(left.join(&right, "sideways").is_err());
31530        assert!(left.join(&right, "inner").is_err());
31531        assert!(left.join(&right, "outer").is_err());
31532    }
31533
31534    #[test]
31535    fn multi_index_slice_locs_uses_lexicographic_bounds() {
31536        let mi = MultiIndex::from_arrays(vec![
31537            vec!["east".into(), "east".into(), "west".into(), "west".into()],
31538            vec![1_i64.into(), 2_i64.into(), 1_i64.into(), 2_i64.into()],
31539        ])
31540        .unwrap();
31541
31542        let (start, stop) = mi
31543            .slice_locs(
31544                Some(&[IndexLabel::Utf8("east".into()), IndexLabel::Int64(2)]),
31545                Some(&[IndexLabel::Utf8("west".into()), IndexLabel::Int64(1)]),
31546            )
31547            .unwrap();
31548        assert_eq!((start, stop), (1, 3));
31549    }
31550
31551    #[test]
31552    fn multi_index_slice_bound_partial_prefixes_d89fe2() {
31553        let mi = MultiIndex::from_arrays(vec![
31554            vec!["east".into(), "east".into(), "west".into(), "west".into()],
31555            vec![1_i64.into(), 2_i64.into(), 1_i64.into(), 2_i64.into()],
31556        ])
31557        .unwrap();
31558
31559        let east = [IndexLabel::Utf8("east".into())];
31560        assert_eq!(mi.get_slice_bound(&east, "left").unwrap(), 0);
31561        assert_eq!(mi.get_slice_bound(&east, "right").unwrap(), 2);
31562
31563        let west = [IndexLabel::Utf8("west".into())];
31564        assert_eq!(mi.slice_indexer(Some(&west), None).unwrap(), (2, 4));
31565        assert_eq!(mi.slice_indexer(None, Some(&east)).unwrap(), (0, 2));
31566    }
31567
31568    #[test]
31569    fn multi_index_slice_bound_full_tuple_and_missing_insert_d89fe2() {
31570        let mi = MultiIndex::from_arrays(vec![
31571            vec!["east".into(), "east".into(), "west".into(), "west".into()],
31572            vec![1_i64.into(), 2_i64.into(), 1_i64.into(), 2_i64.into()],
31573        ])
31574        .unwrap();
31575
31576        let exact = [IndexLabel::Utf8("east".into()), IndexLabel::Int64(2)];
31577        assert_eq!(mi.get_slice_bound(&exact, "left").unwrap(), 1);
31578        assert_eq!(mi.get_slice_bound(&exact, "right").unwrap(), 2);
31579
31580        let missing_insert = [IndexLabel::Utf8("east".into()), IndexLabel::Int64(3)];
31581        assert_eq!(mi.get_slice_bound(&missing_insert, "left").unwrap(), 2);
31582        assert_eq!(mi.get_slice_bound(&missing_insert, "right").unwrap(), 2);
31583    }
31584
31585    #[test]
31586    fn multi_index_slice_bound_rejects_invalid_side_d89fe2() {
31587        let mi = MultiIndex::from_tuples(vec![vec![IndexLabel::Utf8("east".into())]]).unwrap();
31588        let key = [IndexLabel::Utf8("east".into())];
31589
31590        assert!(mi.get_slice_bound(&key, "middle").is_err());
31591    }
31592
31593    #[test]
31594    fn multi_index_truncate_uses_prefix_bounds_d89fe11() -> Result<(), super::IndexError> {
31595        let mi = MultiIndex::from_tuples(vec![
31596            vec!["a".into(), 1_i64.into()],
31597            vec!["a".into(), 3_i64.into()],
31598            vec!["b".into(), 1_i64.into()],
31599            vec!["c".into(), 1_i64.into()],
31600        ])?
31601        .set_names(vec![Some("letter".into()), Some("number".into())]);
31602
31603        let bounded = mi.truncate(
31604            Some(&[IndexLabel::Utf8("a".into())]),
31605            Some(&[IndexLabel::Utf8("b".into())]),
31606        )?;
31607        assert_eq!(
31608            bounded.to_list(),
31609            vec![
31610                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
31611                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(3)],
31612                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
31613            ]
31614        );
31615        assert_eq!(bounded.names(), mi.names());
31616
31617        let tail = mi.truncate(Some(&[IndexLabel::Utf8("b".into())]), None)?;
31618        assert_eq!(
31619            tail.to_list(),
31620            vec![
31621                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
31622                vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(1)],
31623            ]
31624        );
31625
31626        let clipped = mi.truncate(None, Some(&[IndexLabel::Utf8("aa".into())]))?;
31627        assert_eq!(
31628            clipped.to_list(),
31629            vec![
31630                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
31631                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(3)],
31632            ]
31633        );
31634
31635        let empty = mi.truncate(Some(&[IndexLabel::Utf8("d".into())]), None)?;
31636        assert!(empty.is_empty());
31637        assert_eq!(empty.names(), mi.names());
31638
31639        Ok(())
31640    }
31641
31642    #[test]
31643    fn multi_index_get_locs_prefix_and_exact_selectors_d89fe10() -> Result<(), super::IndexError> {
31644        let mi = MultiIndex::from_tuples(vec![
31645            vec!["a".into(), 1_i64.into()],
31646            vec!["a".into(), 2_i64.into()],
31647            vec!["b".into(), 1_i64.into()],
31648            vec!["b".into(), 2_i64.into()],
31649        ])?;
31650
31651        assert_eq!(mi.get_locs(&[IndexLabel::Utf8("a".into())])?, vec![0, 1]);
31652        assert_eq!(
31653            mi.get_locs(&[IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)])?,
31654            vec![0]
31655        );
31656        assert_eq!(mi.get_locs(&[])?, Vec::<usize>::new());
31657
31658        Ok(())
31659    }
31660
31661    #[test]
31662    fn multi_index_get_locs_rejects_missing_and_overlong_keys_d89fe10()
31663    -> Result<(), super::IndexError> {
31664        let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
31665
31666        assert!(mi.get_locs(&[IndexLabel::Utf8("z".into())]).is_err());
31667        assert!(
31668            mi.get_locs(&[
31669                IndexLabel::Utf8("a".into()),
31670                IndexLabel::Int64(1),
31671                IndexLabel::Utf8("extra".into()),
31672            ])
31673            .is_err()
31674        );
31675
31676        Ok(())
31677    }
31678
31679    #[test]
31680    fn multi_index_get_indexer_non_unique_expands_duplicate_matches() {
31681        let source = MultiIndex::from_tuples(vec![
31682            vec!["a".into(), 1_i64.into()],
31683            vec!["a".into(), 2_i64.into()],
31684            vec!["b".into(), 1_i64.into()],
31685            vec!["a".into(), 1_i64.into()],
31686        ])
31687        .unwrap();
31688        let target = MultiIndex::from_tuples(vec![
31689            vec!["a".into(), 1_i64.into()],
31690            vec!["z".into(), 9_i64.into()],
31691            vec!["a".into(), 2_i64.into()],
31692            vec!["a".into(), 1_i64.into()],
31693        ])
31694        .unwrap();
31695
31696        let (indexer, missing) = source.get_indexer_non_unique(&target);
31697        assert_eq!(indexer, vec![0, 3, -1, 1, 0, 3]);
31698        assert_eq!(missing, vec![1]);
31699    }
31700
31701    #[test]
31702    fn multi_index_setop_packed_matches_reference_misetop() {
31703        // intersection/difference packed path must equal an independent
31704        // tuple-set reference (mixed Utf8+Int64 levels, duplicate self rows,
31705        // partial overlap, disjoint, and empty other).
31706        let mk = |spec: &[(&str, i64)]| {
31707            MultiIndex::from_tuples(
31708                spec.iter()
31709                    .map(|(s, i)| vec![IndexLabel::Utf8((*s).to_string()), IndexLabel::Int64(*i)])
31710                    .collect::<Vec<_>>(),
31711            )
31712            .unwrap()
31713        };
31714        type TupleSpec = Vec<(&'static str, i64)>;
31715        type SetopCase = (TupleSpec, TupleSpec);
31716
31717        let cases: Vec<SetopCase> = vec![
31718            (
31719                vec![("a", 1), ("b", 2), ("a", 1), ("c", 3), ("b", 2)],
31720                vec![("b", 2), ("c", 3), ("z", 9)],
31721            ),
31722            (vec![("a", 1), ("b", 2)], vec![("x", 7), ("y", 8)]),
31723            (vec![("a", 1), ("a", 1), ("b", 2)], vec![("a", 1)]),
31724        ];
31725        for (sa, sb) in cases {
31726            let a = mk(&sa);
31727            let b = mk(&sb);
31728            let bset: std::collections::HashSet<Vec<IndexLabel>> =
31729                b.to_list().into_iter().collect();
31730
31731            let mut seen = std::collections::HashSet::new();
31732            let ref_inter: Vec<Vec<IndexLabel>> = a
31733                .to_list()
31734                .into_iter()
31735                .filter(|t| bset.contains(t) && seen.insert(t.clone()))
31736                .collect();
31737            assert_eq!(
31738                a.intersection(&b).unwrap().to_list(),
31739                ref_inter,
31740                "inter {sa:?}"
31741            );
31742
31743            let mut seen_d = std::collections::HashSet::new();
31744            let ref_diff: Vec<Vec<IndexLabel>> = a
31745                .to_list()
31746                .into_iter()
31747                .filter(|t| !bset.contains(t) && seen_d.insert(t.clone()))
31748                .collect();
31749            assert_eq!(a.difference(&b).unwrap().to_list(), ref_diff, "diff {sa:?}");
31750        }
31751    }
31752
31753    #[test]
31754    fn multi_index_two_utf8_setops_preserve_order_and_names_codb188() {
31755        let left = MultiIndex::from_arrays(vec![
31756            vec![
31757                "a".into(),
31758                "b".into(),
31759                "a".into(),
31760                "c".into(),
31761                "d".into(),
31762                "b".into(),
31763            ],
31764            vec![
31765                "x".into(),
31766                "y".into(),
31767                "x".into(),
31768                "z".into(),
31769                "w".into(),
31770                "y".into(),
31771            ],
31772        ])
31773        .unwrap()
31774        .set_names(vec![Some("L0".into()), Some("L1".into())]);
31775        let right = MultiIndex::from_arrays(vec![
31776            vec!["b".into(), "c".into(), "e".into(), "b".into()],
31777            vec!["y".into(), "z".into(), "q".into(), "y".into()],
31778        ])
31779        .unwrap()
31780        .set_names(vec![Some("L0".into()), Some("other".into())]);
31781
31782        assert_eq!(
31783            left.intersection(&right).unwrap().to_list(),
31784            vec![
31785                vec![IndexLabel::Utf8("b".into()), IndexLabel::Utf8("y".into())],
31786                vec![IndexLabel::Utf8("c".into()), IndexLabel::Utf8("z".into())],
31787            ]
31788        );
31789        assert_eq!(
31790            left.difference(&right).unwrap().to_list(),
31791            vec![
31792                vec![IndexLabel::Utf8("a".into()), IndexLabel::Utf8("x".into())],
31793                vec![IndexLabel::Utf8("d".into()), IndexLabel::Utf8("w".into())],
31794            ]
31795        );
31796        assert_eq!(
31797            left.union(&right).unwrap().to_list(),
31798            vec![
31799                vec![IndexLabel::Utf8("a".into()), IndexLabel::Utf8("x".into())],
31800                vec![IndexLabel::Utf8("b".into()), IndexLabel::Utf8("y".into())],
31801                vec![IndexLabel::Utf8("c".into()), IndexLabel::Utf8("z".into())],
31802                vec![IndexLabel::Utf8("d".into()), IndexLabel::Utf8("w".into())],
31803                vec![IndexLabel::Utf8("e".into()), IndexLabel::Utf8("q".into())],
31804            ]
31805        );
31806        assert_eq!(
31807            left.symmetric_difference(&right).unwrap().to_list(),
31808            vec![
31809                vec![IndexLabel::Utf8("a".into()), IndexLabel::Utf8("x".into())],
31810                vec![IndexLabel::Utf8("d".into()), IndexLabel::Utf8("w".into())],
31811                vec![IndexLabel::Utf8("e".into()), IndexLabel::Utf8("q".into())],
31812            ]
31813        );
31814        assert_eq!(
31815            left.intersection(&right).unwrap().names(),
31816            vec![Some("L0".into()), None]
31817        );
31818    }
31819
31820    #[test]
31821    fn multi_index_two_level_dedup_counts_identity_codes_codb2tc1q() {
31822        let mi = MultiIndex::from_arrays(vec![
31823            vec![
31824                "a".into(),
31825                "b".into(),
31826                "a".into(),
31827                "c".into(),
31828                "b".into(),
31829                "d".into(),
31830            ],
31831            vec![
31832                "x".into(),
31833                "y".into(),
31834                "x".into(),
31835                "z".into(),
31836                "y".into(),
31837                "w".into(),
31838            ],
31839        ])
31840        .unwrap()
31841        .set_names(vec![Some("L0".into()), Some("L1".into())]);
31842
31843        assert_eq!(mi.nunique(), 4);
31844        assert_eq!(
31845            mi.duplicated(DuplicateKeep::First),
31846            vec![false, false, true, false, true, false]
31847        );
31848        assert_eq!(
31849            mi.duplicated(DuplicateKeep::Last),
31850            vec![true, true, false, false, false, false]
31851        );
31852        assert_eq!(
31853            mi.duplicated(DuplicateKeep::None),
31854            vec![true, true, true, false, true, false]
31855        );
31856        let unique = mi.unique();
31857        assert_eq!(
31858            unique.to_list(),
31859            vec![
31860                vec![IndexLabel::Utf8("a".into()), IndexLabel::Utf8("x".into())],
31861                vec![IndexLabel::Utf8("b".into()), IndexLabel::Utf8("y".into())],
31862                vec![IndexLabel::Utf8("c".into()), IndexLabel::Utf8("z".into())],
31863                vec![IndexLabel::Utf8("d".into()), IndexLabel::Utf8("w".into())],
31864            ]
31865        );
31866        assert_eq!(unique.names(), mi.names());
31867    }
31868
31869    #[test]
31870    fn multi_index_setop_generic_fallback_preserves_order_codb() {
31871        // Force the generic Vec<IndexLabel> tuple-key path: 65 levels with
31872        // multiple distinct values make mixed-radix u64 packing overflow.
31873        let mk = |row_keys: &[i64]| {
31874            let mut levels = Vec::with_capacity(65);
31875            for level in 0..65 {
31876                let column = row_keys
31877                    .iter()
31878                    .map(|key| IndexLabel::Utf8(format!("level-{level}:key-{key}")))
31879                    .collect();
31880                levels.push(column);
31881            }
31882            MultiIndex::from_arrays(levels).unwrap()
31883        };
31884
31885        let left = mk(&[0, 1, 0, 2]);
31886        let right = mk(&[1, 3, 2, 1]);
31887
31888        assert_eq!(
31889            left.intersection(&right).unwrap().to_list(),
31890            mk(&[1, 2]).to_list()
31891        );
31892        assert_eq!(
31893            left.union(&right).unwrap().to_list(),
31894            mk(&[0, 1, 2, 3]).to_list()
31895        );
31896        assert_eq!(
31897            left.difference(&right).unwrap().to_list(),
31898            mk(&[0]).to_list()
31899        );
31900        assert_eq!(
31901            left.symmetric_difference(&right).unwrap().to_list(),
31902            mk(&[0, 3]).to_list()
31903        );
31904    }
31905
31906    #[test]
31907    fn multi_index_duplicated_packed_matches_vec_reference_midedup() {
31908        // The identity-packed-key duplicated path must equal an independent
31909        // Vec<IndexLabel>-key reference for all keep modes (mixed Utf8+Int64
31910        // levels with duplicate tuples).
31911        let n = 400usize;
31912        let mut state: u64 = 0x9e37_79b9_7f4a_7c15;
31913        let mut l0 = Vec::with_capacity(n);
31914        let mut l1 = Vec::with_capacity(n);
31915        for _ in 0..n {
31916            state = state
31917                .wrapping_mul(6364136223846793005)
31918                .wrapping_add(1442695040888963407);
31919            l0.push(IndexLabel::Utf8(format!("g{}", (state >> 40) % 6)));
31920            state = state
31921                .wrapping_mul(6364136223846793005)
31922                .wrapping_add(1442695040888963407);
31923            l1.push(IndexLabel::Int64(((state >> 40) % 5) as i64));
31924        }
31925        let mi = MultiIndex::from_arrays(vec![l0, l1]).unwrap();
31926        let rows = mi.to_list();
31927
31928        for keep in [
31929            DuplicateKeep::First,
31930            DuplicateKeep::Last,
31931            DuplicateKeep::None,
31932        ] {
31933            let mut want = vec![false; n];
31934            match keep {
31935                DuplicateKeep::First => {
31936                    let mut seen = std::collections::HashSet::new();
31937                    for (r, w) in want.iter_mut().enumerate() {
31938                        if !seen.insert(rows[r].clone()) {
31939                            *w = true;
31940                        }
31941                    }
31942                }
31943                DuplicateKeep::Last => {
31944                    let mut seen = std::collections::HashSet::new();
31945                    for r in (0..n).rev() {
31946                        if !seen.insert(rows[r].clone()) {
31947                            want[r] = true;
31948                        }
31949                    }
31950                }
31951                DuplicateKeep::None => {
31952                    let mut counts: std::collections::HashMap<Vec<IndexLabel>, usize> =
31953                        Default::default();
31954                    for r in &rows {
31955                        *counts.entry(r.clone()).or_insert(0) += 1;
31956                    }
31957                    for (r, w) in want.iter_mut().enumerate() {
31958                        if counts[&rows[r]] > 1 {
31959                            *w = true;
31960                        }
31961                    }
31962                }
31963            }
31964            assert_eq!(mi.duplicated(keep), want, "duplicated {keep:?}");
31965        }
31966        // drop_duplicates/unique derive from duplicated(First).
31967        let mut seen = std::collections::HashSet::new();
31968        let kept: Vec<Vec<IndexLabel>> = rows
31969            .iter()
31970            .filter(|r| seen.insert((*r).clone()))
31971            .cloned()
31972            .collect();
31973        assert_eq!(mi.unique().to_list(), kept);
31974        assert_eq!(mi.nunique(), kept.len());
31975    }
31976
31977    #[test]
31978    fn multi_index_argsort_packed_matches_tuple_sort_misort() {
31979        // The sorted-packed-key argsort must equal the level-by-level tuple
31980        // comparison sort (stable, original-position tiebreak) for mixed
31981        // Utf8+Int64 levels with duplicate tuples and shuffled order.
31982        let n = 600usize;
31983        let mut state: u64 = 0x1234_5678_9abc_def1;
31984        let mut l0 = Vec::with_capacity(n);
31985        let mut l1 = Vec::with_capacity(n);
31986        for _ in 0..n {
31987            state = state
31988                .wrapping_mul(6364136223846793005)
31989                .wrapping_add(1442695040888963407);
31990            let a = (state >> 33) % 7; // low cardinality -> duplicate tuples
31991            state = state
31992                .wrapping_mul(6364136223846793005)
31993                .wrapping_add(1442695040888963407);
31994            let b = (state >> 33) % 5;
31995            l0.push(IndexLabel::Utf8(format!("g{a}")));
31996            l1.push(IndexLabel::Int64(b as i64));
31997        }
31998        let mi = MultiIndex::from_arrays(vec![l0, l1]).unwrap();
31999
32000        // Independent reference: stable sort by lexicographic tuple, ties by pos.
32001        let rows = mi.to_list();
32002        let mut want: Vec<usize> = (0..n).collect();
32003        want.sort_by(|&a, &b| rows[a].cmp(&rows[b]).then(a.cmp(&b)));
32004
32005        assert_eq!(mi.argsort(), want, "argsort");
32006        assert_eq!(
32007            mi.sort_values().to_list(),
32008            mi.take_existing_positions(&want).to_list()
32009        );
32010        // min/max derive from argsort and must match the reference ends.
32011        assert_eq!(mi.min(), Some(rows[want[0]].clone()));
32012        assert_eq!(mi.max(), Some(rows[want[n - 1]].clone()));
32013    }
32014
32015    #[test]
32016    fn multi_index_get_indexer_packed_matches_vec_reference_mipack() {
32017        // The packed-u64-key path must equal an independent Vec<IndexLabel>-key
32018        // reference (mixed Utf8+Int64 levels, duplicate source, target-only
32019        // values exercising fresh per-level codes and the mixed-radix packing).
32020        let mk = |spec: &[(&str, i64)]| {
32021            MultiIndex::from_tuples(
32022                spec.iter()
32023                    .map(|(s, i)| vec![IndexLabel::Utf8((*s).to_string()), IndexLabel::Int64(*i)])
32024                    .collect::<Vec<_>>(),
32025            )
32026            .unwrap()
32027        };
32028        let source = mk(&[("a", 1), ("a", 2), ("b", 1), ("a", 1), ("c", 5), ("b", 2)]);
32029        let target = mk(&[
32030            ("b", 1),
32031            ("z", 9),
32032            ("a", 1),
32033            ("a", 2),
32034            ("c", 5),
32035            ("q", 0),
32036            ("b", 2),
32037        ]);
32038        let src_rows = source.to_list();
32039        let tgt_rows = target.to_list();
32040
32041        let mut pos: std::collections::HashMap<Vec<IndexLabel>, Vec<usize>> = Default::default();
32042        for (r, key) in src_rows.iter().enumerate() {
32043            pos.entry(key.clone()).or_default().push(r);
32044        }
32045        let mut ref_ix = Vec::new();
32046        let mut ref_miss = Vec::new();
32047        for (tr, key) in tgt_rows.iter().enumerate() {
32048            if let Some(m) = pos.get(key) {
32049                ref_ix.extend(m.iter().map(|&p| p as isize));
32050            } else {
32051                ref_ix.push(-1);
32052                ref_miss.push(tr);
32053            }
32054        }
32055        let (ix, miss) = source.get_indexer_non_unique(&target);
32056        assert_eq!(ix, ref_ix, "non_unique indexer");
32057        assert_eq!(miss, ref_miss, "non_unique missing");
32058
32059        let usrc = mk(&[("a", 1), ("a", 2), ("b", 1), ("c", 5), ("b", 2)]);
32060        let urows = usrc.to_list();
32061        let mut upos: std::collections::HashMap<Vec<IndexLabel>, isize> = Default::default();
32062        for (r, key) in urows.iter().enumerate() {
32063            upos.entry(key.clone()).or_insert(r as isize);
32064        }
32065        let ref_u: Vec<isize> = tgt_rows
32066            .iter()
32067            .map(|k| upos.get(k).copied().unwrap_or(-1))
32068            .collect();
32069        assert_eq!(usrc.get_indexer(&target).unwrap(), ref_u, "unique indexer");
32070    }
32071
32072    #[test]
32073    fn multi_index_get_indexer_unique_maps_hits_and_missing_d89fe1() -> Result<(), super::IndexError>
32074    {
32075        let source = MultiIndex::from_tuples(vec![
32076            vec!["a".into(), 1_i64.into()],
32077            vec!["b".into(), 2_i64.into()],
32078            vec!["c".into(), 3_i64.into()],
32079        ])?;
32080        let target = MultiIndex::from_tuples(vec![
32081            vec!["b".into(), 2_i64.into()],
32082            vec!["z".into(), 9_i64.into()],
32083            vec!["a".into(), 1_i64.into()],
32084        ])?;
32085
32086        assert_eq!(source.get_indexer(&target)?, vec![1, -1, 0]);
32087        assert_eq!(source.get_indexer_for(&target)?, vec![1, -1, 0]);
32088
32089        Ok(())
32090    }
32091
32092    #[test]
32093    fn multi_index_typed_outer_align_preserves_columns_and_rejects_duplicate_tuple_3gsa7()
32094    -> Result<(), super::IndexError> {
32095        let left = MultiIndex::from_tuples(vec![
32096            vec!["a".into(), 1_i64.into()],
32097            vec!["a".into(), 2_i64.into()],
32098            vec!["b".into(), 1_i64.into()],
32099        ])?;
32100        let right = MultiIndex::from_tuples(vec![
32101            vec!["a".into(), 2_i64.into()],
32102            vec!["c".into(), 3_i64.into()],
32103        ])?;
32104
32105        let plan = left.outer_align(&right)?;
32106        assert_eq!(
32107            plan.union_index.to_list(),
32108            vec![
32109                vec!["a".into(), 1_i64.into()],
32110                vec!["a".into(), 2_i64.into()],
32111                vec!["b".into(), 1_i64.into()],
32112                vec!["c".into(), 3_i64.into()],
32113            ]
32114        );
32115        assert_eq!(plan.left_positions, vec![Some(0), Some(1), Some(2), None]);
32116        assert_eq!(plan.right_positions, vec![None, Some(0), None, Some(1)]);
32117        assert_eq!(plan.union_index, left.union(&right)?);
32118
32119        // A repeated value in one level is valid when the complete tuples are
32120        // unique; a duplicate tuple is not valid for this unique-only witness.
32121        let duplicate_tuple = MultiIndex::from_tuples(vec![
32122            vec!["a".into(), 1_i64.into()],
32123            vec!["a".into(), 1_i64.into()],
32124        ])?;
32125        let error = duplicate_tuple.outer_align(&right).unwrap_err();
32126        assert!(matches!(
32127            error,
32128            super::IndexError::InvalidArgument(message)
32129                if message == "outer_align requires uniquely valued MultiIndexes"
32130        ));
32131
32132        Ok(())
32133    }
32134
32135    #[test]
32136    fn multi_index_get_indexer_rejects_duplicate_source_d89fe1() -> Result<(), super::IndexError> {
32137        let source = MultiIndex::from_tuples(vec![
32138            vec!["a".into(), 1_i64.into()],
32139            vec!["a".into(), 1_i64.into()],
32140            vec!["b".into(), 2_i64.into()],
32141        ])?;
32142        let target = MultiIndex::from_tuples(vec![
32143            vec!["a".into(), 1_i64.into()],
32144            vec!["b".into(), 2_i64.into()],
32145        ])?;
32146
32147        let err = match source.get_indexer(&target) {
32148            Ok(indexer) => {
32149                return Err(super::IndexError::InvalidArgument(format!(
32150                    "duplicate source index unexpectedly returned {indexer:?}"
32151                )));
32152            }
32153            Err(err) => err,
32154        };
32155        assert!(matches!(
32156            err,
32157            super::IndexError::InvalidArgument(message)
32158                if message == "get_indexer requires a uniquely valued MultiIndex"
32159        ));
32160        assert_eq!(source.get_indexer_for(&target)?, vec![0, 1, 2]);
32161
32162        Ok(())
32163    }
32164
32165    #[test]
32166    fn multi_index_get_indexer_level_mismatch_marks_missing_d89fe1() -> Result<(), super::IndexError>
32167    {
32168        let source = MultiIndex::from_tuples(vec![
32169            vec!["a".into(), 1_i64.into()],
32170            vec!["b".into(), 2_i64.into()],
32171        ])?;
32172        let target = MultiIndex::from_tuples(vec![vec!["a".into()], vec!["b".into()]])?;
32173
32174        assert_eq!(source.get_indexer(&target)?, vec![-1, -1]);
32175        assert_eq!(source.get_indexer_for(&target)?, vec![-1, -1]);
32176
32177        Ok(())
32178    }
32179
32180    #[test]
32181    fn multi_index_reindex_maps_target_hits_and_missing_d89fe4() -> Result<(), super::IndexError> {
32182        let source = MultiIndex::from_tuples(vec![
32183            vec!["a".into(), 1_i64.into()],
32184            vec!["b".into(), 2_i64.into()],
32185            vec!["c".into(), 3_i64.into()],
32186        ])?;
32187        let target = MultiIndex::from_tuples(vec![
32188            vec!["b".into(), 2_i64.into()],
32189            vec!["z".into(), 9_i64.into()],
32190            vec!["a".into(), 1_i64.into()],
32191        ])?
32192        .set_names(vec![Some("letter".into()), Some("number".into())]);
32193
32194        let (reindexed, indexer) = source.reindex(&target)?;
32195        assert_eq!(reindexed, target);
32196        assert_eq!(indexer, vec![1, -1, 0]);
32197
32198        Ok(())
32199    }
32200
32201    #[test]
32202    fn multi_index_reindex_rejects_duplicate_source_d89fe4() -> Result<(), super::IndexError> {
32203        let source = MultiIndex::from_tuples(vec![
32204            vec!["a".into(), 1_i64.into()],
32205            vec!["a".into(), 1_i64.into()],
32206        ])?;
32207        let target = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
32208
32209        assert!(source.reindex(&target).is_err());
32210
32211        Ok(())
32212    }
32213
32214    #[test]
32215    fn multi_index_reindex_level_mismatch_marks_missing_d89fe4() -> Result<(), super::IndexError> {
32216        let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
32217        let target = MultiIndex::from_tuples(vec![vec!["a".into()]])?;
32218
32219        let (reindexed, indexer) = source.reindex(&target)?;
32220        assert_eq!(reindexed, target);
32221        assert_eq!(indexer, vec![-1]);
32222
32223        Ok(())
32224    }
32225
32226    #[test]
32227    fn multi_index_rename_replaces_all_names_d89fe5() -> Result<(), super::IndexError> {
32228        let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?
32229            .set_names(vec![Some("old0".into()), Some("old1".into())]);
32230
32231        let renamed = source.rename(vec![Some("new0".into()), Some("new1".into())])?;
32232
32233        assert_eq!(renamed.names(), &[Some("new0".into()), Some("new1".into())]);
32234        assert_eq!(source.names(), &[Some("old0".into()), Some("old1".into())]);
32235        assert_eq!(renamed.to_list(), source.to_list());
32236
32237        Ok(())
32238    }
32239
32240    #[test]
32241    fn multi_index_rename_level_replaces_one_name_d89fe5() -> Result<(), super::IndexError> {
32242        let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?
32243            .set_names(vec![Some("old0".into()), Some("old1".into())]);
32244
32245        let renamed = source.rename_level(Some("new1".into()), 1)?;
32246
32247        assert_eq!(renamed.names(), &[Some("old0".into()), Some("new1".into())]);
32248        assert_eq!(source.names(), &[Some("old0".into()), Some("old1".into())]);
32249
32250        Ok(())
32251    }
32252
32253    #[test]
32254    fn multi_index_rename_rejects_wrong_name_count_d89fe5() -> Result<(), super::IndexError> {
32255        let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
32256
32257        let err = source.rename(vec![Some("only".into())]).unwrap_err();
32258
32259        assert!(matches!(
32260            err,
32261            super::IndexError::LengthMismatch {
32262                expected: 2,
32263                actual: 1,
32264                ..
32265            }
32266        ));
32267
32268        Ok(())
32269    }
32270
32271    #[test]
32272    fn multi_index_rename_level_rejects_out_of_bounds_d89fe5() -> Result<(), super::IndexError> {
32273        let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
32274
32275        let err = source.rename_level(Some("missing".into()), 2).unwrap_err();
32276
32277        assert!(matches!(
32278            err,
32279            super::IndexError::OutOfBounds {
32280                position: 2,
32281                length: 2
32282            }
32283        ));
32284
32285        Ok(())
32286    }
32287
32288    #[test]
32289    fn multi_index_searchsorted_left_and_right_d89fe6() -> Result<(), super::IndexError> {
32290        let source = MultiIndex::from_tuples(vec![
32291            vec!["a".into(), 1_i64.into()],
32292            vec!["a".into(), 3_i64.into()],
32293            vec!["b".into(), 2_i64.into()],
32294            vec!["b".into(), 2_i64.into()],
32295        ])?;
32296        let target = MultiIndex::from_tuples(vec![
32297            vec!["a".into(), 0_i64.into()],
32298            vec!["a".into(), 1_i64.into()],
32299            vec!["a".into(), 2_i64.into()],
32300            vec!["a".into(), 3_i64.into()],
32301            vec!["b".into(), 2_i64.into()],
32302            vec!["c".into(), 0_i64.into()],
32303        ])?;
32304
32305        assert_eq!(
32306            source.searchsorted(&target, "left")?,
32307            vec![0, 0, 1, 1, 2, 4]
32308        );
32309        assert_eq!(
32310            source.searchsorted(&target, "right")?,
32311            vec![0, 1, 1, 2, 4, 4]
32312        );
32313
32314        Ok(())
32315    }
32316
32317    #[test]
32318    fn multi_index_searchsorted_empty_target_d89fe6() -> Result<(), super::IndexError> {
32319        let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
32320        let target = MultiIndex::from_tuples(Vec::new())?;
32321
32322        assert_eq!(source.searchsorted(&target, "left")?, Vec::<usize>::new());
32323
32324        Ok(())
32325    }
32326
32327    #[test]
32328    fn multi_index_searchsorted_rejects_invalid_side_d89fe6() -> Result<(), super::IndexError> {
32329        let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
32330        let target = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
32331
32332        let err = source.searchsorted(&target, "middle").unwrap_err();
32333
32334        assert!(matches!(
32335            err,
32336            super::IndexError::InvalidArgument(message)
32337                if message == "searchsorted: side must be 'left' or 'right', got \"middle\""
32338        ));
32339
32340        Ok(())
32341    }
32342
32343    #[test]
32344    fn multi_index_get_indexer_non_unique_level_mismatch_marks_all_missing() {
32345        let source = MultiIndex::from_tuples(vec![
32346            vec!["a".into(), 1_i64.into()],
32347            vec!["b".into(), 2_i64.into()],
32348        ])
32349        .unwrap();
32350        let target = MultiIndex::from_tuples(vec![vec!["a".into()], vec!["b".into()]]).unwrap();
32351
32352        let (indexer, missing) = source.get_indexer_non_unique(&target);
32353        assert_eq!(indexer, vec![-1, -1]);
32354        assert_eq!(missing, vec![0, 1]);
32355    }
32356
32357    #[test]
32358    fn multi_index_isin_tuple_membership() {
32359        let mi = MultiIndex::from_tuples(vec![
32360            vec!["a".into(), 1_i64.into()],
32361            vec!["b".into(), 2_i64.into()],
32362            vec!["a".into(), 3_i64.into()],
32363        ])
32364        .unwrap();
32365        let needles: Vec<Vec<IndexLabel>> = vec![
32366            vec!["a".into(), 1_i64.into()],
32367            vec!["b".into(), 2_i64.into()],
32368        ];
32369        assert_eq!(mi.isin(&needles), vec![true, true, false]);
32370    }
32371
32372    #[test]
32373    fn multi_index_isin_ignores_mismatched_tuple_length() {
32374        let mi = MultiIndex::from_tuples(vec![
32375            vec!["a".into(), 1_i64.into()],
32376            vec!["b".into(), 2_i64.into()],
32377        ])
32378        .unwrap();
32379        // Wrong-arity tuple contributes no matches.
32380        let needles: Vec<Vec<IndexLabel>> = vec![vec!["a".into()]];
32381        assert_eq!(mi.isin(&needles), vec![false, false]);
32382    }
32383
32384    #[test]
32385    fn multi_index_isin_empty_values_yields_all_false() {
32386        let mi = MultiIndex::from_tuples(vec![
32387            vec!["a".into(), 1_i64.into()],
32388            vec!["b".into(), 2_i64.into()],
32389        ])
32390        .unwrap();
32391        let needles: Vec<Vec<IndexLabel>> = Vec::new();
32392        assert_eq!(mi.isin(&needles), vec![false, false]);
32393    }
32394
32395    #[test]
32396    fn multi_index_isin_level_filters_by_level() {
32397        let mi = MultiIndex::from_tuples(vec![
32398            vec!["a".into(), 1_i64.into()],
32399            vec!["b".into(), 2_i64.into()],
32400            vec!["a".into(), 3_i64.into()],
32401        ])
32402        .unwrap();
32403        let level0 = mi.isin_level(&["a".into()], 0).unwrap();
32404        assert_eq!(level0, vec![true, false, true]);
32405        let level1 = mi.isin_level(&[2_i64.into(), 3_i64.into()], 1).unwrap();
32406        assert_eq!(level1, vec![false, true, true]);
32407    }
32408
32409    #[test]
32410    fn multi_index_isin_level_out_of_bounds_errors() {
32411        let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
32412        let err = mi.isin_level(&["a".into()], 5).unwrap_err();
32413        assert!(matches!(err, crate::IndexError::OutOfBounds { .. }));
32414    }
32415
32416    #[test]
32417    fn multi_index_isin_empty_index_yields_empty() {
32418        let mi = MultiIndex::from_tuples(Vec::new()).unwrap();
32419        let needles: Vec<Vec<IndexLabel>> = vec![vec!["a".into(), 1_i64.into()]];
32420        assert_eq!(mi.isin(&needles), Vec::<bool>::new());
32421    }
32422
32423    #[test]
32424    fn multi_index_duplicated_keep_first_default() {
32425        let mi = MultiIndex::from_tuples(vec![
32426            vec!["a".into(), 1_i64.into()],
32427            vec!["b".into(), 2_i64.into()],
32428            vec!["a".into(), 1_i64.into()],
32429            vec!["c".into(), 3_i64.into()],
32430        ])
32431        .unwrap();
32432        let dup = mi.duplicated(DuplicateKeep::First);
32433        assert_eq!(dup, vec![false, false, true, false]);
32434    }
32435
32436    #[test]
32437    fn multi_index_duplicated_keep_last_marks_earlier_occurrences() {
32438        let mi = MultiIndex::from_tuples(vec![
32439            vec!["a".into(), 1_i64.into()],
32440            vec!["a".into(), 1_i64.into()],
32441            vec!["b".into(), 2_i64.into()],
32442        ])
32443        .unwrap();
32444        let dup = mi.duplicated(DuplicateKeep::Last);
32445        assert_eq!(dup, vec![true, false, false]);
32446    }
32447
32448    #[test]
32449    fn multi_index_duplicated_keep_none_marks_all_repeats() {
32450        let mi = MultiIndex::from_tuples(vec![
32451            vec!["a".into(), 1_i64.into()],
32452            vec!["b".into(), 2_i64.into()],
32453            vec!["a".into(), 1_i64.into()],
32454            vec!["c".into(), 3_i64.into()],
32455        ])
32456        .unwrap();
32457        let dup = mi.duplicated(DuplicateKeep::None);
32458        assert_eq!(dup, vec![true, false, true, false]);
32459    }
32460
32461    #[test]
32462    fn multi_index_is_unique_true_and_false() {
32463        let unique = MultiIndex::from_tuples(vec![
32464            vec!["a".into(), 1_i64.into()],
32465            vec!["b".into(), 2_i64.into()],
32466        ])
32467        .unwrap();
32468        assert!(unique.is_unique());
32469        assert!(!unique.has_duplicates());
32470
32471        let duped = MultiIndex::from_tuples(vec![
32472            vec!["a".into(), 1_i64.into()],
32473            vec!["a".into(), 1_i64.into()],
32474        ])
32475        .unwrap();
32476        assert!(!duped.is_unique());
32477        assert!(duped.has_duplicates());
32478    }
32479
32480    fn multi_index_is_unique_former_haoam(index: &MultiIndex) -> bool {
32481        !index
32482            .duplicated(DuplicateKeep::First)
32483            .iter()
32484            .any(|&duplicated| duplicated)
32485    }
32486
32487    #[test]
32488    fn multi_index_is_unique_short_circuit_matches_former_haoam() {
32489        let compact_unique = MultiIndex::from_arrays(vec![
32490            vec![0_i64.into(), 1_i64.into(), 0_i64.into(), 1_i64.into()],
32491            vec![0_i64.into(), 0_i64.into(), 1_i64.into(), 1_i64.into()],
32492        ])
32493        .unwrap();
32494        let compact_duplicate = MultiIndex::from_arrays(vec![
32495            vec![0_i64.into(), 0_i64.into(), 1_i64.into()],
32496            vec![1_i64.into(), 1_i64.into(), 0_i64.into()],
32497        ])
32498        .unwrap();
32499        let packed_unique = MultiIndex::from_arrays(vec![
32500            vec![0_i64.into(), 1_i64.into(), 0_i64.into()],
32501            vec![0_i64.into(), 0_i64.into(), 1_i64.into()],
32502            vec![1_i64.into(), 1_i64.into(), 0_i64.into()],
32503        ])
32504        .unwrap();
32505        let packed_duplicate = MultiIndex::from_arrays(vec![
32506            vec![0_i64.into(), 1_i64.into(), 0_i64.into()],
32507            vec![0_i64.into(), 1_i64.into(), 0_i64.into()],
32508            vec![1_i64.into(), 0_i64.into(), 1_i64.into()],
32509        ])
32510        .unwrap();
32511
32512        let generic = |keys: &[i64]| {
32513            let levels = (0..65)
32514                .map(|level| {
32515                    keys.iter()
32516                        .map(|key| IndexLabel::Utf8(format!("level-{level}:key-{key}")))
32517                        .collect()
32518                })
32519                .collect();
32520            MultiIndex::from_arrays(levels).unwrap()
32521        };
32522        let generic_unique = generic(&[0, 1, 2]);
32523        let generic_duplicate = generic(&[0, 1, 0]);
32524        let empty = MultiIndex::from_arrays(vec![Vec::new(), Vec::new()]).unwrap();
32525        let singleton = MultiIndex::from_tuples(vec![vec![0_i64.into(), "x".into()]]).unwrap();
32526
32527        for index in [
32528            &empty,
32529            &singleton,
32530            &compact_unique,
32531            &compact_duplicate,
32532            &packed_unique,
32533            &packed_duplicate,
32534            &generic_unique,
32535            &generic_duplicate,
32536        ] {
32537            let former = multi_index_is_unique_former_haoam(index);
32538            assert_eq!(index.is_unique(), former);
32539            assert_eq!(index.has_duplicates(), !former);
32540        }
32541    }
32542
32543    #[test]
32544    #[ignore = "foreground release A/B for br-frankenpandas-haoam"]
32545    fn multi_index_is_unique_short_circuit_ab_haoam() {
32546        const ITEMS: usize = 131_072;
32547        const SAMPLES: usize = 10;
32548        const CALLS: usize = 4;
32549
32550        let make_index = |duplicate_first: bool| {
32551            let mut level0 = Vec::with_capacity(ITEMS);
32552            let mut level1 = Vec::with_capacity(ITEMS);
32553            for row in 0..ITEMS {
32554                let key = if duplicate_first && row < 2 {
32555                    0
32556                } else if duplicate_first {
32557                    row - 1
32558                } else {
32559                    row
32560                };
32561                level0.push(IndexLabel::Int64((key % 512) as i64));
32562                level1.push(IndexLabel::Int64((key / 512) as i64));
32563            }
32564            MultiIndex::from_arrays(vec![level0, level1]).unwrap()
32565        };
32566        let early_duplicate = make_index(true);
32567        let all_unique = make_index(false);
32568
32569        for index in [&early_duplicate, &all_unique] {
32570            assert_eq!(index.is_unique(), multi_index_is_unique_former_haoam(index));
32571            std::hint::black_box(multi_index_is_unique_former_haoam(index));
32572            std::hint::black_box(index.is_unique());
32573        }
32574
32575        let measure = |index: &MultiIndex, former: bool| {
32576            let start = std::time::Instant::now();
32577            for _ in 0..CALLS {
32578                let unique = if former {
32579                    multi_index_is_unique_former_haoam(index)
32580                } else {
32581                    index.is_unique()
32582                };
32583                std::hint::black_box(unique);
32584            }
32585            start.elapsed().as_nanos()
32586        };
32587        let mut early_former = Vec::with_capacity(SAMPLES);
32588        let mut early_candidate = Vec::with_capacity(SAMPLES);
32589        let mut unique_former = Vec::with_capacity(SAMPLES);
32590        let mut unique_candidate = Vec::with_capacity(SAMPLES);
32591        for sample in 0..SAMPLES {
32592            if sample % 2 == 0 {
32593                early_former.push(measure(&early_duplicate, true));
32594                early_candidate.push(measure(&early_duplicate, false));
32595                unique_candidate.push(measure(&all_unique, false));
32596                unique_former.push(measure(&all_unique, true));
32597            } else {
32598                early_candidate.push(measure(&early_duplicate, false));
32599                early_former.push(measure(&early_duplicate, true));
32600                unique_former.push(measure(&all_unique, true));
32601                unique_candidate.push(measure(&all_unique, false));
32602            }
32603        }
32604        early_former.sort_unstable();
32605        early_candidate.sort_unstable();
32606        unique_former.sort_unstable();
32607        unique_candidate.sort_unstable();
32608        let middle = SAMPLES / 2;
32609        println!(
32610            "multi_index_is_unique_short_circuit_ab items={ITEMS} calls={CALLS} samples={SAMPLES} early_former_p50_ns={} early_candidate_p50_ns={} early_speedup={:.6}x unique_former_p50_ns={} unique_candidate_p50_ns={} unique_speedup={:.6}x\nearly_former_samples_ns={early_former:?}\nearly_candidate_samples_ns={early_candidate:?}\nunique_former_samples_ns={unique_former:?}\nunique_candidate_samples_ns={unique_candidate:?}",
32611            early_former[middle],
32612            early_candidate[middle],
32613            early_former[middle] as f64 / early_candidate[middle] as f64,
32614            unique_former[middle],
32615            unique_candidate[middle],
32616            unique_former[middle] as f64 / unique_candidate[middle] as f64,
32617        );
32618    }
32619
32620    #[test]
32621    fn multi_index_duplicated_empty_yields_empty() {
32622        let mi = MultiIndex::from_tuples(Vec::new()).unwrap();
32623        assert_eq!(mi.duplicated(DuplicateKeep::First), Vec::<bool>::new());
32624        assert!(mi.is_unique());
32625    }
32626
32627    #[test]
32628    fn multi_index_all_any_reject_bool_reduction_d89fe7() -> Result<(), super::IndexError> {
32629        let non_empty = MultiIndex::from_tuples(vec![
32630            vec!["a".into(), 1_i64.into()],
32631            vec!["b".into(), 2_i64.into()],
32632        ])?;
32633        let empty = MultiIndex::from_arrays(vec![Vec::new(), Vec::new()])?;
32634
32635        let cases = [
32636            (
32637                non_empty.all().unwrap_err(),
32638                "cannot perform all with this index type: MultiIndex",
32639            ),
32640            (
32641                non_empty.any().unwrap_err(),
32642                "cannot perform any with this index type: MultiIndex",
32643            ),
32644            (
32645                empty.all().unwrap_err(),
32646                "cannot perform all with this index type: MultiIndex",
32647            ),
32648            (
32649                empty.any().unwrap_err(),
32650                "cannot perform any with this index type: MultiIndex",
32651            ),
32652        ];
32653
32654        for (err, expected) in cases {
32655            assert!(matches!(
32656                err,
32657                super::IndexError::InvalidArgument(message) if message == expected
32658            ));
32659        }
32660
32661        Ok(())
32662    }
32663
32664    #[test]
32665    fn multi_index_shift_rejects_temporal_shift_d89fe9() -> Result<(), super::IndexError> {
32666        let mi = MultiIndex::from_tuples(vec![
32667            vec!["a".into(), 1_i64.into()],
32668            vec!["b".into(), 2_i64.into()],
32669        ])?;
32670        let expected = "This method is only implemented for DatetimeIndex, PeriodIndex and TimedeltaIndex; Got type MultiIndex";
32671
32672        for err in [
32673            mi.shift(1, None).unwrap_err(),
32674            mi.shift(0, None).unwrap_err(),
32675            mi.shift(1, Some("D")).unwrap_err(),
32676        ] {
32677            assert!(matches!(
32678                err,
32679                super::IndexError::InvalidArgument(message) if message == expected
32680            ));
32681        }
32682
32683        Ok(())
32684    }
32685
32686    #[test]
32687    fn multi_index_str_rejects_string_accessor_d89fe12() -> Result<(), super::IndexError> {
32688        let mi = MultiIndex::from_tuples(vec![
32689            vec!["a".into(), 1_i64.into()],
32690            vec!["b".into(), 2_i64.into()],
32691        ])?;
32692
32693        let err = mi.r#str().unwrap_err();
32694
32695        assert!(matches!(
32696            err,
32697            super::IndexError::InvalidArgument(message)
32698                if message == "Can only use .str accessor with Index, not MultiIndex"
32699        ));
32700
32701        Ok(())
32702    }
32703
32704    #[test]
32705    fn multi_index_astype_object_clones_other_dtypes_reject_c2x17() -> Result<(), super::IndexError>
32706    {
32707        let mi = MultiIndex::from_tuples(vec![
32708            vec!["a".into(), 1_i64.into()],
32709            vec!["b".into(), 2_i64.into()],
32710        ])?;
32711
32712        for dtype in ["object", "O"] {
32713            let cloned = mi.astype(dtype)?;
32714            assert!(cloned.equals(&mi));
32715            assert_eq!(cloned.nlevels(), mi.nlevels());
32716            assert_eq!(cloned.len(), mi.len());
32717        }
32718
32719        let cat_err = mi.astype("category").unwrap_err();
32720        assert!(matches!(
32721            cat_err,
32722            super::IndexError::InvalidArgument(message)
32723                if message == "> 1 ndim Categorical are not supported at this time"
32724        ));
32725
32726        for dtype in ["int64", "float64", "datetime64[ns]"] {
32727            let err = mi.astype(dtype).unwrap_err();
32728            let expected = format!(
32729                "Setting a MultiIndex dtype to anything other than object is not supported; got {dtype}"
32730            );
32731            assert!(matches!(
32732                err,
32733                super::IndexError::InvalidArgument(message) if message == expected
32734            ));
32735        }
32736
32737        Ok(())
32738    }
32739
32740    #[test]
32741    fn multi_index_diff_rejects_tuple_subtraction_c2x17() -> Result<(), super::IndexError> {
32742        let mi = MultiIndex::from_tuples(vec![
32743            vec!["a".into(), 1_i64.into()],
32744            vec!["b".into(), 2_i64.into()],
32745            vec!["c".into(), 3_i64.into()],
32746        ])?;
32747        let expected = "cannot perform __sub__ with this index type: MultiIndex";
32748
32749        for periods in [-1_i64, 0, 1, 2] {
32750            let err = mi.diff(periods).unwrap_err();
32751            assert!(matches!(
32752                err,
32753                super::IndexError::InvalidArgument(message) if message == expected
32754            ));
32755        }
32756
32757        Ok(())
32758    }
32759
32760    /// `MultiIndex.round` is a NO-OP in pandas, not a refusal.
32761    ///
32762    /// ⚠️ THIS TEST USED TO ASSERT THE OPPOSITE, pinning the numpy `rint` error
32763    /// text. The refusal and this assertion both rested on the reasoning that
32764    /// pandas applies `np.around` to tuple labels. It does not. MEASURED, live
32765    /// pandas 2.2.3:
32766    ///
32767    /// ```text
32768    /// mi = pd.MultiIndex.from_tuples([(1.567, "a"), (2.345, "b")])
32769    /// mi.round(0) / round(2) / round(-1) -> [(1.567, 'a'), (2.345, 'b')]
32770    /// mi.round(2).equals(mi)             -> True
32771    /// np.around(mi, 2)                   -> TypeError (a DIFFERENT call, and a
32772    ///                                       different message from the one that
32773    ///                                       was pinned here)
32774    /// ```
32775    ///
32776    /// Found by the error-only-stub classifier added to
32777    /// scripts/validate_api_coverage_drift.py: it flagged ten MultiIndex methods
32778    /// whose whole body is `Err(...)`, and probing all ten against pandas showed
32779    /// NINE are correct refusals (pandas raises too, and for `all`/`any` with the
32780    /// same wording) while `round` alone was wrong.
32781    #[test]
32782    fn multi_index_round_is_a_no_op_matching_pandas_c2x17() -> Result<(), super::IndexError> {
32783        let mi = MultiIndex::from_tuples(vec![
32784            vec!["a".into(), 1_i64.into()],
32785            vec!["b".into(), 2_i64.into()],
32786        ])?;
32787
32788        for decimals in [-1_i32, 0, 1, 4] {
32789            let rounded = mi.round(decimals)?;
32790            assert_eq!(
32791                rounded.values(),
32792                mi.values(),
32793                "round({decimals}) must leave a MultiIndex unchanged"
32794            );
32795        }
32796
32797        // Float levels are NOT rounded either — the no-op is total, which is the
32798        // half a "rounding is unsupported here" reading would still get wrong.
32799        let floats = MultiIndex::from_tuples(vec![
32800            vec![
32801                super::IndexLabel::Float64(super::OrderedF64(1.567)),
32802                "a".into(),
32803            ],
32804            vec![
32805                super::IndexLabel::Float64(super::OrderedF64(2.345)),
32806                "b".into(),
32807            ],
32808        ])?;
32809        assert_eq!(floats.round(2)?.values(), floats.values());
32810
32811        Ok(())
32812    }
32813
32814    #[test]
32815    fn range_index_argmax_argmin_handles_step_direction_mrchb() {
32816        let asc = super::RangeIndex::new(0, 5, 1).unwrap();
32817        assert_eq!(asc.argmax().unwrap(), 4);
32818        assert_eq!(asc.argmin().unwrap(), 0);
32819
32820        let desc = super::RangeIndex::new(10, 0, -2).unwrap();
32821        assert_eq!(desc.argmax().unwrap(), 0);
32822        assert_eq!(desc.argmin().unwrap(), desc.len() - 1);
32823
32824        let big_step = super::RangeIndex::new(1, 100, 7).unwrap();
32825        assert_eq!(big_step.argmax().unwrap(), big_step.len() - 1);
32826        assert_eq!(big_step.argmin().unwrap(), 0);
32827    }
32828
32829    #[test]
32830    fn range_index_argmax_argmin_reject_empty_mrchb() {
32831        let empty = super::RangeIndex::new(5, 5, 1).unwrap();
32832        assert!(empty.is_empty());
32833        let max_err = empty.argmax().unwrap_err();
32834        assert!(matches!(
32835            max_err,
32836            super::IndexError::InvalidArgument(ref message)
32837                if message == "attempt to get argmax of an empty sequence"
32838        ));
32839        let min_err = empty.argmin().unwrap_err();
32840        assert!(matches!(
32841            min_err,
32842            super::IndexError::InvalidArgument(ref message)
32843                if message == "attempt to get argmin of an empty sequence"
32844        ));
32845    }
32846
32847    #[test]
32848    fn range_index_argsort_orientation_matches_step_sign_mrchb() {
32849        let asc = super::RangeIndex::new(0, 5, 1).unwrap();
32850        assert_eq!(asc.argsort(), vec![0, 1, 2, 3, 4]);
32851
32852        let desc = super::RangeIndex::new(10, 0, -2).unwrap();
32853        assert_eq!(desc.argsort(), vec![4, 3, 2, 1, 0]);
32854
32855        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
32856        assert_eq!(empty.argsort(), Vec::<usize>::new());
32857    }
32858
32859    #[test]
32860    fn datetime_index_time_of_day_accessors_match_pandas_znejf() {
32861        // 2024-01-01T12:34:56.789012345Z
32862        // secs = 1704112496, subsec_nanos = 789_012_345
32863        // total nanos = 1_704_112_496_000_000_000 + 789_012_345
32864        //             = 1_704_112_496_789_012_345
32865        let total: i64 = 1_704_112_496 * 1_000_000_000 + 789_012_345;
32866        let dt = super::DatetimeIndex::new(vec![total, i64::MIN, 0]);
32867
32868        assert_eq!(dt.hour(), vec![Some(12), None, Some(0)]);
32869        assert_eq!(dt.minute(), vec![Some(34), None, Some(0)]);
32870        assert_eq!(dt.second(), vec![Some(56), None, Some(0)]);
32871        assert_eq!(dt.microsecond(), vec![Some(789_012), None, Some(0)]);
32872        assert_eq!(dt.nanosecond(), vec![Some(345), None, Some(0)]);
32873    }
32874
32875    #[test]
32876    fn datetime_index_time_of_day_indexers_match_pandas_bwzmn() -> Result<(), super::IndexError> {
32877        let hour = fp_types::Timedelta::NANOS_PER_HOUR;
32878        let minute = fp_types::Timedelta::NANOS_PER_MIN;
32879        let day = fp_types::Timedelta::NANOS_PER_DAY;
32880        let dt = super::DatetimeIndex::new(vec![
32881            9 * hour,
32882            12 * hour + 30 * minute,
32883            i64::MIN,
32884            23 * hour + 30 * minute,
32885            day + 30 * minute,
32886        ]);
32887
32888        assert_eq!(dt.indexer_at_time("12:30")?, vec![1]);
32889        assert_eq!(dt.indexer_at_time("12:30:00.000000000")?, vec![1]);
32890        assert_eq!(dt.indexer_at_time("00:30:00")?, vec![4]);
32891        assert!(dt.indexer_at_time("not-a-time").is_err());
32892
32893        assert_eq!(
32894            dt.indexer_between_time("08:00", "13:00", true, true)?,
32895            vec![0, 1]
32896        );
32897        assert_eq!(
32898            dt.indexer_between_time("09:00", "13:00", false, true)?,
32899            vec![1]
32900        );
32901        assert_eq!(
32902            dt.indexer_between_time("23:00", "01:00", true, true)?,
32903            vec![3, 4]
32904        );
32905        assert_eq!(
32906            dt.indexer_between_time("23:30", "00:30", false, false)?,
32907            Vec::<usize>::new()
32908        );
32909        assert!(
32910            dt.indexer_between_time("09:00", "not-a-time", true, true)
32911                .is_err()
32912        );
32913        Ok(())
32914    }
32915
32916    #[test]
32917    fn datetime_index_week_weekofyear_match_pandas_e8xhb() {
32918        const NS: i64 = 1_000_000_000;
32919        // 2024-01-01 (Monday) is in ISO week 1 of 2024.
32920        let jan_01 = 1_704_067_200_i64 * NS;
32921        // 2024-12-30 (Monday) is in ISO week 1 of 2025 (yes: pandas/ chrono
32922        // both report this as week 1).
32923        let dec_30 = 1_735_516_800_i64 * NS;
32924        let dt = super::DatetimeIndex::new(vec![jan_01, dec_30, i64::MIN]);
32925
32926        let weeks = dt.week();
32927        assert_eq!(weeks[0], Some(1));
32928        assert_eq!(weeks[1], Some(1));
32929        assert_eq!(weeks[2], None);
32930
32931        // weekofyear is an alias.
32932        assert_eq!(dt.weekofyear(), weeks);
32933        assert_eq!(
32934            dt.isocalendar(),
32935            vec![Some((2024, 1, 1)), Some((2025, 1, 1)), None]
32936        );
32937    }
32938
32939    #[test]
32940    fn datetime_index_day_of_x_and_quarter_match_pandas_k860x() {
32941        // 2024-01-15T00:00:00Z (a Monday).
32942        let mon: i64 = 1_705_276_800 * 1_000_000_000;
32943        // 2024-01-21T00:00:00Z (a Sunday).
32944        let sun: i64 = 1_705_795_200 * 1_000_000_000;
32945        // 2024-04-30T00:00:00Z (Apr -> 30 days; Q2).
32946        let apr30: i64 = 1_714_435_200 * 1_000_000_000;
32947        let dt = super::DatetimeIndex::new(vec![mon, sun, apr30, i64::MIN]);
32948
32949        // 2024 is a leap year. Jan 15 = ordinal 15. Jan 21 = ordinal 21.
32950        // Apr 30 = 31+29+31+30 = 121.
32951        assert_eq!(dt.dayofyear(), vec![Some(15), Some(21), Some(121), None]);
32952        assert_eq!(dt.day_of_year(), dt.dayofyear());
32953
32954        // Mon=0, Sun=6. Apr 30 2024 was a Tuesday → 1.
32955        assert_eq!(dt.dayofweek(), vec![Some(0), Some(6), Some(1), None]);
32956        assert_eq!(dt.day_of_week(), dt.dayofweek());
32957        assert_eq!(dt.weekday(), dt.dayofweek());
32958
32959        // Q1 / Q1 / Q2.
32960        assert_eq!(dt.quarter(), vec![Some(1), Some(1), Some(2), None]);
32961
32962        // 2024 is a leap year.
32963        assert_eq!(
32964            dt.is_leap_year(),
32965            vec![Some(true), Some(true), Some(true), None]
32966        );
32967
32968        // Jan -> 31, Apr -> 30.
32969        assert_eq!(dt.days_in_month(), vec![Some(31), Some(31), Some(30), None]);
32970        assert_eq!(dt.daysinmonth(), dt.days_in_month());
32971    }
32972
32973    #[test]
32974    fn datetime_index_boundary_accessors_match_pandas_qy7yd() {
32975        // 2024 is a leap year. Each entry is the 00:00:00Z second-of-epoch
32976        // multiplied by 1_000_000_000.
32977        const NS: i64 = 1_000_000_000;
32978        let jan_01 = 1_704_067_200_i64 * NS; // year/quarter/month start
32979        let jan_31 = 1_706_659_200_i64 * NS; // month end (Jan)
32980        let feb_29 = 1_709_164_800_i64 * NS; // leap-month end
32981        let mar_31 = 1_711_843_200_i64 * NS; // quarter/month end (Q1)
32982        let apr_01 = 1_711_929_600_i64 * NS; // quarter/month start (Q2)
32983        let dec_31 = 1_735_603_200_i64 * NS; // year/quarter/month end
32984        let nat = i64::MIN;
32985
32986        let dt =
32987            super::DatetimeIndex::new(vec![jan_01, jan_31, feb_29, mar_31, apr_01, dec_31, nat]);
32988
32989        // is_year_start: only Jan 1.
32990        assert_eq!(
32991            dt.is_year_start(),
32992            vec![
32993                Some(true),
32994                Some(false),
32995                Some(false),
32996                Some(false),
32997                Some(false),
32998                Some(false),
32999                None
33000            ]
33001        );
33002        // is_year_end: only Dec 31.
33003        assert_eq!(
33004            dt.is_year_end(),
33005            vec![
33006                Some(false),
33007                Some(false),
33008                Some(false),
33009                Some(false),
33010                Some(false),
33011                Some(true),
33012                None
33013            ]
33014        );
33015        // is_quarter_start: Jan 1, Apr 1.
33016        assert_eq!(
33017            dt.is_quarter_start(),
33018            vec![
33019                Some(true),
33020                Some(false),
33021                Some(false),
33022                Some(false),
33023                Some(true),
33024                Some(false),
33025                None
33026            ]
33027        );
33028        // is_quarter_end: Mar 31, Dec 31.
33029        assert_eq!(
33030            dt.is_quarter_end(),
33031            vec![
33032                Some(false),
33033                Some(false),
33034                Some(false),
33035                Some(true),
33036                Some(false),
33037                Some(true),
33038                None
33039            ]
33040        );
33041        // is_month_start: Jan 1, Apr 1.
33042        assert_eq!(
33043            dt.is_month_start(),
33044            vec![
33045                Some(true),
33046                Some(false),
33047                Some(false),
33048                Some(false),
33049                Some(true),
33050                Some(false),
33051                None
33052            ]
33053        );
33054        // is_month_end: Jan 31, Feb 29 (leap), Mar 31, Dec 31.
33055        assert_eq!(
33056            dt.is_month_end(),
33057            vec![
33058                Some(false),
33059                Some(true),
33060                Some(true),
33061                Some(true),
33062                Some(false),
33063                Some(true),
33064                None
33065            ]
33066        );
33067    }
33068
33069    #[test]
33070    fn index_variants_insert_match_pandas_veabb() -> Result<(), super::IndexError> {
33071        const NS: i64 = 1_000_000_000;
33072        let a = 1_704_067_200_i64 * NS;
33073        let b = 1_705_276_800_i64 * NS;
33074        let c = 1_706_140_800_i64 * NS;
33075        let dt = super::DatetimeIndex::new(vec![a, c]).set_name("ts");
33076
33077        // Middle insertion.
33078        let middle = dt.insert(1, b)?;
33079        assert_eq!(middle.values(), vec![Some(a), Some(b), Some(c)]);
33080        assert_eq!(middle.name().map(|n| n.as_str()), Some("ts"));
33081
33082        // End insertion (loc == len()).
33083        let end = dt.insert(dt.len(), b)?;
33084        assert_eq!(end.values(), vec![Some(a), Some(c), Some(b)]);
33085
33086        // OOB.
33087        assert!(matches!(
33088            dt.insert(99, b).unwrap_err(),
33089            super::IndexError::OutOfBounds {
33090                position: 99,
33091                length: 2
33092            }
33093        ));
33094
33095        let td = super::TimedeltaIndex::new(vec![100_i64, 300]).set_name("d");
33096        let td_inserted = td.insert(1, 200)?;
33097        assert_eq!(td_inserted.values(), vec![Some(100), Some(200), Some(300)]);
33098        assert_eq!(td_inserted.name().map(|n| n.as_str()), Some("d"));
33099
33100        use fp_types::{Period, PeriodFreq};
33101        let p1 = Period::new(10, PeriodFreq::Monthly);
33102        let p2 = Period::new(11, PeriodFreq::Monthly);
33103        let p3 = Period::new(12, PeriodFreq::Monthly);
33104        let pi = super::PeriodIndex::new(vec![p1, p3]).set_name("p");
33105        let pi_inserted = pi.insert(1, p2)?;
33106        assert_eq!(pi_inserted.values(), &[p1, p2, p3]);
33107
33108        let r = super::RangeIndex::new(0, 3, 1).unwrap();
33109        let r_inserted = r.insert(1, 99)?;
33110        let labels = int64_labels(&r_inserted);
33111        assert_eq!(labels, vec![0, 99, 1, 2]);
33112        Ok(())
33113    }
33114
33115    #[test]
33116    fn index_variants_format_match_pandas_n31q2() {
33117        const NS: i64 = 1_000_000_000;
33118        let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS, i64::MIN]);
33119        let dt_fmt = dt.format();
33120        assert!(dt_fmt[0].starts_with("2024-01-01"));
33121        assert_eq!(dt_fmt[1], "NaT");
33122
33123        let td = super::TimedeltaIndex::new(vec![1_000_000_i64, fp_types::Timedelta::NAT]);
33124        let td_fmt = td.format();
33125        assert_eq!(td_fmt[0], "1000000");
33126        assert_eq!(td_fmt[1], "NaT");
33127
33128        use fp_types::{Period, PeriodFreq};
33129        let pi = super::PeriodIndex::new(vec![Period::new(10, PeriodFreq::Monthly)]);
33130        let pi_fmt = pi.format();
33131        assert!(!pi_fmt[0].is_empty());
33132
33133        let cat = super::CategoricalIndex::from_values(vec!["a".to_owned(), "b".to_owned()], false);
33134        assert_eq!(cat.format(), vec!["a".to_owned(), "b".to_owned()]);
33135    }
33136
33137    #[test]
33138    fn datetime_timedelta_fillna_isnull_match_pandas_az3t9() {
33139        const NS: i64 = 1_000_000_000;
33140        let unix = 1_704_067_200_i64 * NS;
33141        let dt = super::DatetimeIndex::new(vec![unix, i64::MIN, 0]).set_name("ts");
33142
33143        let filled = dt.fillna(unix);
33144        // NAT is replaced; existing values are preserved.
33145        assert_eq!(filled.values(), vec![Some(unix), Some(unix), Some(0)]);
33146        assert_eq!(filled.name().map(|n| n.as_str()), Some("ts"));
33147
33148        let iso = dt.isnull();
33149        assert_eq!(iso, dt.isna());
33150        let nio = dt.notnull();
33151        assert_eq!(nio, dt.notna());
33152
33153        let nat = fp_types::Timedelta::NAT;
33154        let td = super::TimedeltaIndex::new(vec![100_i64, nat, 0]).set_name("d");
33155        let td_filled = td.fillna(99);
33156        assert_eq!(td_filled.values(), vec![Some(100), Some(99), Some(0)]);
33157        assert_eq!(td_filled.name().map(|n| n.as_str()), Some("d"));
33158        assert_eq!(td.isnull(), td.isna());
33159        assert_eq!(td.notnull(), td.notna());
33160    }
33161
33162    #[test]
33163    fn datetime_index_date_and_time_accessors_match_pandas_66pll() {
33164        const NS: i64 = 1_000_000_000;
33165        // 2024-01-15T12:34:56.789012345Z (computed in br-teeck).
33166        let total: i64 = 1_705_322_096_i64 * NS + 789_012_345;
33167        let dt = super::DatetimeIndex::new(vec![total, i64::MIN, 0]);
33168
33169        let dates = dt.date();
33170        assert_eq!(
33171            dates[0],
33172            Some(chrono::NaiveDate::from_ymd_opt(2024, 1, 15).unwrap())
33173        );
33174        assert_eq!(dates[1], None);
33175        assert_eq!(
33176            dates[2],
33177            Some(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
33178        );
33179
33180        let times = dt.time();
33181        assert_eq!(
33182            times[0],
33183            chrono::NaiveTime::from_hms_nano_opt(12, 34, 56, 789_012_345)
33184        );
33185        assert_eq!(times[1], None);
33186        assert_eq!(times[2], chrono::NaiveTime::from_hms_nano_opt(0, 0, 0, 0));
33187        assert_eq!(dt.timetz(), times);
33188    }
33189
33190    #[test]
33191    fn datetime_index_to_pydatetime_and_julian_match_pandas_dww6m() {
33192        const NS: i64 = 1_000_000_000;
33193        // 2024-01-01T00:00:00Z
33194        let unix = 1_704_067_200_i64;
33195        let total = unix * NS;
33196        let dt = super::DatetimeIndex::new(vec![total, i64::MIN]);
33197
33198        let pydt = dt.to_pydatetime();
33199        let first = pydt[0].expect("non-NAT label decodes");
33200        assert_eq!(first.timestamp(), unix);
33201        assert_eq!(pydt[1], None);
33202
33203        let julian = dt.to_julian_date();
33204        // JD for 2024-01-01T00:00:00Z = 2_460_310.5.
33205        let expected = (unix as f64) / 86_400.0 + 2_440_587.5;
33206        let observed = julian[0].expect("non-NAT label decodes");
33207        assert!((observed - expected).abs() < 1e-9);
33208        assert_eq!(julian[1], None);
33209    }
33210
33211    #[test]
33212    fn timedelta_index_to_pytimedelta_match_pandas_dww6m() {
33213        let one_day_nanos = fp_types::Timedelta::NANOS_PER_DAY;
33214        let td = super::TimedeltaIndex::new(vec![one_day_nanos, fp_types::Timedelta::NAT]);
33215        let durations = td.to_pytimedelta();
33216        let one_day = durations[0].expect("non-NAT label decodes");
33217        assert_eq!(one_day.num_seconds(), 86_400);
33218        assert_eq!(durations[1], None);
33219    }
33220
33221    #[test]
33222    fn relabeled_keeps_the_name_and_the_zone_of_datetime_labels_fvsao_60() {
33223        let instants = |ns: &[i64]| ns.iter().map(|&v| IndexLabel::Datetime64(v)).collect();
33224        let aware = Index::new(instants(&[30, 10, 20]))
33225            .set_names(Some("when"))
33226            .with_tz(Some("US/Eastern"))
33227            .unwrap();
33228        // A subset / reordering of the labels keeps both (Index::new plus
33229        // the name dropped the zone).
33230        let taken = aware.relabeled(instants(&[20, 30]));
33231        assert_eq!(taken.name().map(|n| n.as_str()), Some("when"));
33232        assert_eq!(taken.tz(), Some("US/Eastern"));
33233        // NEGATIVES: labels that are not all datetimes keep the name only;
33234        // a naive index invents no zone.
33235        let text = aware.relabeled(vec![IndexLabel::Utf8("a".to_owned())]);
33236        assert_eq!(
33237            (text.name().map(|n| n.as_str()), text.tz()),
33238            (Some("when"), None)
33239        );
33240        let naive = Index::new(instants(&[1])).relabeled(instants(&[1]));
33241        assert_eq!(naive.tz(), None);
33242    }
33243
33244    #[test]
33245    fn datetime_index_tz_localize_tz_convert_match_pandas_qm31w() {
33246        use fp_types::TimeZoneError;
33247        const NS: i64 = 1_000_000_000;
33248        const HOUR: i64 = 3_600 * NS;
33249        // Wall 2024-01-01 09:00 and 2024-07-01 09:00 (naive).
33250        let jan = 1_704_067_200_i64 * NS + 9 * HOUR;
33251        let jul = 1_719_792_000_i64 * NS + 9 * HOUR;
33252        let dt = super::DatetimeIndex::new(vec![jan, jul, i64::MIN]).set_name("ts");
33253        assert_eq!(dt.tz(), None);
33254
33255        // pandas: New York is EST (-5h) in January and EDT (-4h) in July;
33256        // the labels become UTC instants, the fields keep the wall clock.
33257        let ny = dt.tz_localize(Some("US/Eastern")).expect("localize");
33258        assert_eq!(ny.tz().as_deref(), Some("US/Eastern"));
33259        assert_eq!(ny.name().map(|n| n.as_str()), Some("ts"));
33260        assert_eq!(
33261            ny.values(),
33262            vec![Some(jan + 5 * HOUR), Some(jul + 4 * HOUR), None]
33263        );
33264        assert_eq!(ny.hour(), vec![Some(9), Some(9), None]);
33265        // pandas' equals: the same instants in another zone (or naive) differ.
33266        let same_instants_naive = ny.tz_convert(None).expect("naive UTC");
33267        assert!(!ny.equals(&same_instants_naive));
33268        assert!(!ny.equals(&ny.tz_convert(Some("UTC")).expect("UTC")));
33269        assert!(ny.equals(&ny.clone()));
33270
33271        // tz_convert keeps the instants and moves the wall clock.
33272        let tokyo = ny.tz_convert(Some("Asia/Tokyo")).expect("convert");
33273        assert_eq!(tokyo.values(), ny.values());
33274        assert_eq!(tokyo.hour(), vec![Some(23), Some(22), None]);
33275        assert_eq!(tokyo.day(), vec![Some(1), Some(1), None]);
33276        // tz_convert(None) is UTC, naive; tz_localize(None) keeps the wall.
33277        let utc_naive = ny.tz_convert(None).expect("to naive UTC");
33278        assert_eq!(utc_naive.tz(), None);
33279        assert_eq!(utc_naive.values(), ny.values());
33280        assert!(ny.tz_localize(None).expect("drop zone").equals(&dt));
33281        // A take keeps the zone; normalize is the wall-clock midnight.
33282        assert_eq!(
33283            ny.take(&[1]).expect("take").tz().as_deref(),
33284            Some("US/Eastern")
33285        );
33286        let midnights = ny.normalize().expect("normalize");
33287        assert_eq!(midnights.tz().as_deref(), Some("US/Eastern"));
33288        assert_eq!(midnights.hour(), vec![Some(0), Some(0), None]);
33289        assert_eq!(
33290            midnights.values(),
33291            vec![
33292                Some(jan - 9 * HOUR + 5 * HOUR),
33293                Some(jul - 9 * HOUR + 4 * HOUR),
33294                None
33295            ]
33296        );
33297
33298        // NEGATIVES (pandas' errors): localizing an aware index, converting a
33299        // naive one, a wall time a DST change skips, an unknown zone.
33300        assert!(matches!(
33301            ny.tz_localize(Some("UTC")),
33302            Err(super::IndexError::TimeZoneMismatch(ref m)) if m.contains("Already tz-aware")
33303        ));
33304        assert!(matches!(
33305            dt.tz_convert(Some("UTC")),
33306            Err(super::IndexError::TimeZoneMismatch(ref m)) if m.contains("tz-naive")
33307        ));
33308        let skipped = 1_710_028_800_i64 * NS + 2 * HOUR + 30 * 60 * NS; // 2024-03-10 02:30
33309        assert_eq!(
33310            super::DatetimeIndex::new(vec![skipped]).tz_localize(Some("US/Eastern")),
33311            Err(super::IndexError::TimeZone(TimeZoneError::NonExistent(
33312                "2024-03-10 02:30:00".to_owned()
33313            )))
33314        );
33315        assert!(matches!(
33316            dt.tz_localize(Some("Mars/Base")),
33317            Err(super::IndexError::TimeZone(TimeZoneError::Unknown(_)))
33318        ));
33319    }
33320
33321    #[test]
33322    fn datetime_timedelta_as_unit_match_pandas_70mbe() {
33323        let dt = super::DatetimeIndex::new(vec![]);
33324        assert!(dt.as_unit("ns").is_ok());
33325        let bad = dt.as_unit("us").unwrap_err();
33326        assert!(matches!(
33327            bad,
33328            super::IndexError::InvalidArgument(ref msg) if msg.contains("as_unit")
33329        ));
33330
33331        let td = super::TimedeltaIndex::new(vec![]);
33332        assert!(td.as_unit("ns").is_ok());
33333        assert!(td.as_unit("ms").is_err());
33334    }
33335
33336    #[test]
33337    fn datetime_timedelta_unit_resolution_match_pandas_c50rv() {
33338        let dt = super::DatetimeIndex::new(vec![]);
33339        assert_eq!(dt.unit(), "ns");
33340        assert_eq!(dt.resolution(), "nanosecond");
33341
33342        let td = super::TimedeltaIndex::new(vec![]);
33343        assert_eq!(td.unit(), "ns");
33344        assert_eq!(td.resolution(), "nanosecond");
33345    }
33346
33347    #[test]
33348    fn datetime_timedelta_tz_freq_accessors_return_none_ze7et() {
33349        const NS: i64 = 1_000_000_000;
33350        let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS]);
33351        assert_eq!(dt.tz(), None);
33352        assert_eq!(dt.tzinfo(), None);
33353        assert_eq!(dt.freq(), None);
33354        assert_eq!(dt.freqstr(), None);
33355        assert_eq!(dt.inferred_freq(), None);
33356
33357        let td = super::TimedeltaIndex::new(vec![100_i64]);
33358        assert_eq!(td.freq(), None);
33359        assert_eq!(td.freqstr(), None);
33360        assert_eq!(td.inferred_freq(), None);
33361    }
33362
33363    #[test]
33364    fn period_index_freqstr_inferred_freq_match_pandas_ze7et() {
33365        use fp_types::{Period, PeriodFreq};
33366        let pi = super::PeriodIndex::new(vec![
33367            Period::new(10, PeriodFreq::Monthly),
33368            Period::new(11, PeriodFreq::Monthly),
33369        ]);
33370        let s = pi.freqstr().expect("homogeneous index has a freqstr");
33371        assert!(!s.is_empty());
33372        let inferred = pi.inferred_freq().expect("homogeneous freq is inferable");
33373        assert_eq!(inferred, s);
33374
33375        // Mixed-frequency index: inferred_freq returns None.
33376        let mixed = super::PeriodIndex::new(vec![
33377            Period::new(10, PeriodFreq::Monthly),
33378            Period::new(10, PeriodFreq::ANNUAL),
33379        ]);
33380        assert_eq!(mixed.inferred_freq(), None);
33381
33382        // Empty index: freqstr is None.
33383        let empty = super::PeriodIndex::new(Vec::new());
33384        assert_eq!(empty.freqstr(), None);
33385        assert_eq!(empty.inferred_freq(), None);
33386    }
33387
33388    #[test]
33389    fn range_index_where_putmask_match_pandas_jw1kw() -> Result<(), super::IndexError> {
33390        let r = super::RangeIndex::new(0, 5, 1).unwrap().set_name("r");
33391
33392        let masked = r.r#where(&[true, false, true, false, true], 99)?;
33393        assert_eq!(int64_labels(&masked), vec![0, 99, 2, 99, 4]);
33394        assert_eq!(masked.name().map(|n| n.as_str()), Some("r"));
33395
33396        let put = r.putmask(&[false, true, false, true, false], 99)?;
33397        assert_eq!(int64_labels(&put), vec![0, 99, 2, 99, 4]);
33398
33399        // Length mismatch.
33400        assert!(matches!(
33401            r.r#where(&[true, false], 0).unwrap_err(),
33402            super::IndexError::LengthMismatch { .. }
33403        ));
33404        assert!(matches!(
33405            r.putmask(&[true; 7], 0).unwrap_err(),
33406            super::IndexError::LengthMismatch { .. }
33407        ));
33408        Ok(())
33409    }
33410
33411    #[test]
33412    fn range_index_set_ops_match_pandas_tz40f() {
33413        let left = super::RangeIndex::new(0, 5, 1).unwrap().set_name("r");
33414        let right = super::RangeIndex::new(3, 8, 1).unwrap().set_name("r");
33415
33416        let inter = left.intersection(&right);
33417        assert_eq!(int64_labels(&inter), vec![3, 4]);
33418        assert_eq!(inter.name().map(|n| n.as_str()), Some("r"));
33419
33420        let union = left.union(&right);
33421        assert_eq!(int64_labels(&union), vec![0, 1, 2, 3, 4, 5, 6, 7]);
33422
33423        let diff = left.difference(&right);
33424        assert_eq!(int64_labels(&diff), vec![0, 1, 2]);
33425
33426        let sym = left.symmetric_difference(&right);
33427        assert_eq!(int64_labels(&sym), vec![0, 1, 2, 5, 6, 7]);
33428
33429        // Mismatched names drop the name.
33430        let other_name = super::RangeIndex::new(3, 6, 1).unwrap().set_name("other");
33431        assert_eq!(left.union(&other_name).name(), None);
33432    }
33433
33434    #[test]
33435    fn period_range_slice_indexer_match_pandas_18kvv() -> Result<(), super::IndexError> {
33436        use fp_types::{Period, PeriodFreq};
33437        let pi = super::PeriodIndex::new(vec![
33438            Period::new(10, PeriodFreq::Monthly),
33439            Period::new(11, PeriodFreq::Monthly),
33440            Period::new(12, PeriodFreq::Monthly),
33441        ]);
33442        assert_eq!(
33443            pi.slice_indexer(
33444                Period::new(11, PeriodFreq::Monthly),
33445                Period::new(12, PeriodFreq::Monthly)
33446            )?,
33447            1..3
33448        );
33449
33450        let r = super::RangeIndex::new(0, 10, 2).unwrap();
33451        assert_eq!(r.slice_indexer(2, 6)?, 1..4);
33452        Ok(())
33453    }
33454
33455    #[test]
33456    fn period_range_slice_locs_match_pandas_fdga0() -> Result<(), super::IndexError> {
33457        use fp_types::{Period, PeriodFreq};
33458        let p1 = Period::new(10, PeriodFreq::Monthly);
33459        let p2 = Period::new(11, PeriodFreq::Monthly);
33460        let p3 = Period::new(12, PeriodFreq::Monthly);
33461        let p4 = Period::new(13, PeriodFreq::Monthly);
33462        let pi = super::PeriodIndex::new(vec![p1, p2, p3, p4]);
33463        assert_eq!(pi.slice_locs(p2, p3)?, (1, 3));
33464        assert_eq!(pi.slice_locs(p1, p4)?, (0, 4));
33465        // Non-monotonic rejects.
33466        let unsorted = super::PeriodIndex::new(vec![p3, p1, p2]);
33467        assert!(unsorted.slice_locs(p1, p3).is_err());
33468
33469        let r = super::RangeIndex::new(0, 10, 2).unwrap();
33470        // Values 0,2,4,6,8.
33471        assert_eq!(r.slice_locs(2, 6)?, (1, 4));
33472        assert_eq!(r.slice_locs(0, 8)?, (0, 5));
33473
33474        // Descending rejects.
33475        let desc = super::RangeIndex::new(10, 0, -2).unwrap();
33476        assert!(desc.slice_locs(2, 6).is_err());
33477        Ok(())
33478    }
33479
33480    #[test]
33481    fn typed_index_variants_rename_alias_match_pandas_i8t6n() {
33482        let dt = super::DatetimeIndex::new(vec![]);
33483        assert_eq!(dt.rename("ts").name().map(|n| n.as_str()), Some("ts"));
33484
33485        let td = super::TimedeltaIndex::new(vec![]);
33486        assert_eq!(td.rename("d").name().map(|n| n.as_str()), Some("d"));
33487
33488        use fp_types::PeriodFreq;
33489        let pi = super::PeriodIndex::new(vec![]);
33490        assert_eq!(pi.rename("p").name().map(|n| n.as_str()), Some("p"));
33491        let _ = PeriodFreq::Monthly; // suppress unused-import warning when no other test in scope
33492
33493        let r = super::RangeIndex::new(0, 0, 1).unwrap();
33494        assert_eq!(r.rename("r").name().map(|n| n.as_str()), Some("r"));
33495
33496        let cat = super::CategoricalIndex::from_values(vec!["a".to_owned()], false);
33497        assert_eq!(cat.rename("c").name().map(|n| n.as_str()), Some("c"));
33498    }
33499
33500    #[test]
33501    fn typed_index_variants_reindex_match_pandas_qm3nq() {
33502        const NS: i64 = 1_000_000_000;
33503        let a = 1_704_067_200_i64 * NS;
33504        let b = 1_705_276_800_i64 * NS;
33505        let dt = super::DatetimeIndex::new(vec![a, b]);
33506        let target = super::DatetimeIndex::new(vec![b, a, 0]);
33507        let (out, indexer) = dt.reindex(&target);
33508        assert_eq!(out.values(), target.values());
33509        assert_eq!(indexer, vec![1, 0, -1]);
33510
33511        let td = super::TimedeltaIndex::new(vec![100_i64, 200]);
33512        let td_target = super::TimedeltaIndex::new(vec![200_i64, 999]);
33513        let (_, td_indexer) = td.reindex(&td_target);
33514        assert_eq!(td_indexer, vec![1, -1]);
33515
33516        use fp_types::{Period, PeriodFreq};
33517        let p1 = Period::new(10, PeriodFreq::Monthly);
33518        let p2 = Period::new(11, PeriodFreq::Monthly);
33519        let pi = super::PeriodIndex::new(vec![p1, p2]);
33520        let pi_target = super::PeriodIndex::new(vec![p2, Period::new(99, PeriodFreq::Monthly)]);
33521        let (_, pi_indexer) = pi.reindex(&pi_target);
33522        assert_eq!(pi_indexer, vec![1, -1]);
33523
33524        let r = super::RangeIndex::new(0, 5, 1).unwrap();
33525        let r_target = super::RangeIndex::new(2, 6, 1).unwrap();
33526        let (_, r_indexer) = r.reindex(&r_target);
33527        assert_eq!(r_indexer, vec![2, 3, 4, -1]);
33528
33529        let descending_target = super::RangeIndex::new(6, -3, -3)
33530            .unwrap()
33531            .set_name("target");
33532        let (reindexed, descending_indexer) = r.reindex(&descending_target);
33533        assert!(reindexed.identical(&descending_target));
33534        assert_eq!(descending_indexer, vec![-1, 3, 0]);
33535    }
33536
33537    #[test]
33538    fn period_range_categorical_get_indexer_non_unique_match_pandas_z9sna()
33539    -> Result<(), super::IndexError> {
33540        use fp_types::{Period, PeriodFreq};
33541        let p1 = Period::new(10, PeriodFreq::Monthly);
33542        let p2 = Period::new(11, PeriodFreq::Monthly);
33543        // PeriodIndex with duplicate p1.
33544        let pi = super::PeriodIndex::new(vec![p1, p2, p1]);
33545        let (positions, missing) =
33546            pi.get_indexer_non_unique(&[p1, Period::new(99, PeriodFreq::Monthly)]);
33547        assert_eq!(positions, vec![0, 2, -1]);
33548        assert_eq!(missing, vec![1]);
33549
33550        // RangeIndex (always unique).
33551        let r = super::RangeIndex::new(0, 5, 1).unwrap();
33552        let (positions, missing) = r.get_indexer_non_unique(&[2, 99]);
33553        assert_eq!(positions, vec![2, -1]);
33554        assert_eq!(missing, vec![1]);
33555
33556        // CategoricalIndex with duplicate "a".
33557        let cat = super::CategoricalIndex::from_values(
33558            vec!["a".to_owned(), "b".to_owned(), "a".to_owned()],
33559            false,
33560        );
33561        let (positions, missing) =
33562            cat.get_indexer_non_unique(&[IndexLabel::from("a"), IndexLabel::from("z")]);
33563        assert_eq!(positions, vec![0, 2, -1]);
33564        assert_eq!(missing, vec![1]);
33565
33566        // Categorical get_indexer also works.
33567        let mapped = cat.get_indexer(&[IndexLabel::from("b"), IndexLabel::from("z")]);
33568        assert_eq!(mapped, vec![1, -1]);
33569        // get_indexer_for is an alias.
33570        assert_eq!(
33571            cat.get_indexer_for(&[IndexLabel::from("a")]),
33572            cat.get_indexer(&[IndexLabel::from("a")])
33573        );
33574        Ok(())
33575    }
33576
33577    #[test]
33578    fn typed_index_variants_get_indexer_for_aliases_match_pandas_lf1jy()
33579    -> Result<(), super::IndexError> {
33580        const NS: i64 = 1_000_000_000;
33581        let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS]);
33582        assert_eq!(
33583            dt.get_indexer_for(&[1_704_067_200_i64 * NS, 0]),
33584            dt.get_indexer(&[1_704_067_200_i64 * NS, 0])
33585        );
33586
33587        let td = super::TimedeltaIndex::new(vec![100_i64, 200]);
33588        assert_eq!(td.get_indexer_for(&[200, 999]), td.get_indexer(&[200, 999]));
33589
33590        use fp_types::{Period, PeriodFreq};
33591        let pi = super::PeriodIndex::new(vec![Period::new(10, PeriodFreq::Monthly)]);
33592        let target = vec![Period::new(10, PeriodFreq::Monthly)];
33593        assert_eq!(pi.get_indexer_for(&target), pi.get_indexer(&target));
33594
33595        let r = super::RangeIndex::new(0, 5, 1).unwrap();
33596        assert_eq!(r.get_indexer_for(&[2, 99]), r.get_indexer(&[2, 99]));
33597        Ok(())
33598    }
33599
33600    #[test]
33601    fn period_range_get_loc_get_indexer_match_pandas_e7psu() -> Result<(), super::IndexError> {
33602        use fp_types::{Period, PeriodFreq};
33603        let p1 = Period::new(10, PeriodFreq::Monthly);
33604        let p2 = Period::new(11, PeriodFreq::Monthly);
33605        let p3 = Period::new(12, PeriodFreq::Monthly);
33606        let pi = super::PeriodIndex::new(vec![p1, p2, p3]);
33607        assert_eq!(pi.get_loc(p2)?, 1);
33608        assert!(pi.get_loc(Period::new(99, PeriodFreq::Monthly)).is_err());
33609        assert_eq!(
33610            pi.get_indexer(&[p3, p1, Period::new(99, PeriodFreq::Monthly)]),
33611            vec![2, 0, -1]
33612        );
33613
33614        // RangeIndex with step=2: 0, 2, 4, 6, 8.
33615        let r = super::RangeIndex::new(0, 10, 2).unwrap();
33616        assert_eq!(r.get_loc(0)?, 0);
33617        assert_eq!(r.get_loc(8)?, 4);
33618        assert!(r.get_loc(7).is_err()); // not in step
33619        assert!(r.get_loc(99).is_err()); // out of range
33620        assert_eq!(r.get_indexer(&[4, 7, 0, 99]), vec![2, -1, 0, -1]);
33621
33622        // Negative step: 10, 8, 6, 4, 2.
33623        let desc = super::RangeIndex::new(10, 0, -2).unwrap();
33624        assert_eq!(desc.get_loc(10)?, 0);
33625        assert_eq!(desc.get_loc(2)?, 4);
33626        assert!(desc.get_loc(7).is_err());
33627        Ok(())
33628    }
33629
33630    #[test]
33631    fn range_index_vectorized_indexers_match_get_loc_29u49() {
33632        let source = super::RangeIndex::new(10, 0, -2).unwrap();
33633
33634        let targets = [10, 7, 2, 0, 6];
33635        assert_eq!(source.get_indexer(&targets), vec![0, -1, 4, -1, 2]);
33636        let (positions, missing) = source.get_indexer_non_unique(&targets);
33637        assert_eq!(positions, vec![0, -1, 4, -1, 2]);
33638        assert_eq!(missing, vec![1, 3]);
33639
33640        let target_index = super::RangeIndex::new(12, -2, -4).unwrap();
33641        let (reindexed, indexer) = source.reindex(&target_index);
33642        assert!(reindexed.identical(&target_index));
33643        assert_eq!(indexer, vec![-1, 1, 3, -1]);
33644
33645        let missing_error = source.get_loc(7).unwrap_err();
33646        assert!(matches!(
33647            missing_error,
33648            super::IndexError::InvalidArgument(ref msg)
33649                if msg == "get_loc: 7 not in RangeIndex"
33650        ));
33651    }
33652
33653    #[test]
33654    fn range_index_reindex_uses_arithmetic_lattice_fast_path_codb159() {
33655        let source = super::RangeIndex::new(0, 10, 2).unwrap();
33656
33657        let all_miss_target = super::RangeIndex::new(1, 11, 2).unwrap();
33658        let (reindexed, indexer) = source.reindex(&all_miss_target);
33659        assert!(reindexed.identical(&all_miss_target));
33660        assert_eq!(indexer, vec![-1, -1, -1, -1, -1]);
33661
33662        let aligned_target = super::RangeIndex::new(4, 12, 2).unwrap();
33663        let (reindexed, indexer) = source.reindex(&aligned_target);
33664        assert!(reindexed.identical(&aligned_target));
33665        assert_eq!(indexer, vec![2, 3, 4, -1]);
33666
33667        let descending_source = super::RangeIndex::new(10, 0, -2).unwrap();
33668        let descending_target = super::RangeIndex::new(8, -4, -4).unwrap();
33669        let (reindexed, indexer) = descending_source.reindex(&descending_target);
33670        assert!(reindexed.identical(&descending_target));
33671        assert_eq!(indexer, vec![1, 3, -1]);
33672
33673        let partial_lattice_target = super::RangeIndex::new(0, 10, 2).unwrap();
33674        let wide_step_source = super::RangeIndex::new(0, 12, 4).unwrap();
33675        let (reindexed, indexer) = wide_step_source.reindex(&partial_lattice_target);
33676        assert!(reindexed.identical(&partial_lattice_target));
33677        assert_eq!(indexer, vec![0, -1, 1, -1, 2]);
33678    }
33679
33680    #[test]
33681    fn range_index_bulk_indexers_reuse_source_len_without_extreme_overflow_codb159() {
33682        let source = super::RangeIndex::new(i64::MIN, i64::MIN + 10, 2).unwrap();
33683        assert_eq!(
33684            source.get_indexer(&[i64::MIN, i64::MIN + 8, i64::MAX]),
33685            vec![0, 4, -1]
33686        );
33687
33688        let (positions, missing) =
33689            source.get_indexer_non_unique(&[i64::MIN, i64::MIN + 1, i64::MIN + 8, i64::MAX]);
33690        assert_eq!(positions, vec![0, -1, 4, -1]);
33691        assert_eq!(missing, vec![1, 3]);
33692    }
33693
33694    #[test]
33695    fn range_index_get_loc_uses_wide_arithmetic_uza04172() -> Result<(), super::IndexError> {
33696        let asc = super::RangeIndex::new(i64::MIN, i64::MIN + 10, 2).unwrap();
33697        assert_eq!(asc.get_loc(i64::MIN)?, 0);
33698        assert_eq!(asc.get_loc(i64::MIN + 8)?, 4);
33699        let asc_missing = asc.get_loc(i64::MAX).unwrap_err();
33700        assert!(matches!(
33701            asc_missing,
33702            super::IndexError::InvalidArgument(ref msg)
33703                if msg == &format!("get_loc: {} not in RangeIndex", i64::MAX)
33704        ));
33705
33706        let desc = super::RangeIndex::new(i64::MAX, i64::MAX - 10, -2).unwrap();
33707        assert_eq!(desc.get_loc(i64::MAX)?, 0);
33708        assert_eq!(desc.get_loc(i64::MAX - 8)?, 4);
33709        let desc_missing = desc.get_loc(i64::MIN).unwrap_err();
33710        assert!(matches!(
33711            desc_missing,
33712            super::IndexError::InvalidArgument(ref msg)
33713                if msg == &format!("get_loc: {} not in RangeIndex", i64::MIN)
33714        ));
33715        Ok(())
33716    }
33717
33718    #[test]
33719    fn period_index_where_putmask_match_pandas_so9oh() -> Result<(), super::IndexError> {
33720        use fp_types::{Period, PeriodFreq};
33721        let p1 = Period::new(10, PeriodFreq::Monthly);
33722        let p2 = Period::new(11, PeriodFreq::Monthly);
33723        let p3 = Period::new(12, PeriodFreq::Monthly);
33724        let pi = super::PeriodIndex::new(vec![p1, p2, p3]).set_name("p");
33725
33726        // where: keep position 0 and 2.
33727        let masked = pi.r#where(&[true, false, true], p1)?;
33728        assert_eq!(masked.values(), &[p1, p1, p3]);
33729        assert_eq!(masked.name().map(|n| n.as_str()), Some("p"));
33730
33731        // putmask: replace masked positions.
33732        let put = pi.putmask(&[false, true, false], p1)?;
33733        assert_eq!(put.values(), &[p1, p1, p3]);
33734
33735        // Length mismatch.
33736        let bad_len = pi.r#where(&[true, false], p1).unwrap_err();
33737        assert!(matches!(bad_len, super::IndexError::LengthMismatch { .. }));
33738
33739        // Mismatched freq replacement rejects.
33740        let mismatch = Period::new(10, PeriodFreq::ANNUAL);
33741        assert!(pi.r#where(&[true, false, true], mismatch).is_err());
33742        assert!(pi.putmask(&[false, true, false], mismatch).is_err());
33743        Ok(())
33744    }
33745
33746    #[test]
33747    fn categorical_index_where_putmask_match_pandas_so9oh() -> Result<(), super::IndexError> {
33748        let cat = super::CategoricalIndex::with_categories(
33749            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
33750            vec![
33751                "a".to_owned(),
33752                "b".to_owned(),
33753                "c".to_owned(),
33754                "d".to_owned(),
33755            ],
33756            false,
33757        )?;
33758
33759        let masked = cat.r#where(&[true, false, true], &IndexLabel::from("d"))?;
33760        assert_eq!(
33761            masked.labels(),
33762            vec![
33763                IndexLabel::from("a"),
33764                IndexLabel::from("d"),
33765                IndexLabel::from("c")
33766            ]
33767            .as_slice()
33768        );
33769
33770        let put = cat.putmask(&[false, true, true], &IndexLabel::from("d"))?;
33771        assert_eq!(
33772            put.labels(),
33773            vec![
33774                IndexLabel::from("a"),
33775                IndexLabel::from("d"),
33776                IndexLabel::from("d")
33777            ]
33778            .as_slice()
33779        );
33780
33781        // Replacement that's not a category rejects.
33782        assert!(
33783            cat.r#where(&[true, false, true], &IndexLabel::from("zzz"))
33784                .is_err()
33785        );
33786
33787        // Length mismatch.
33788        assert!(cat.putmask(&[true; 5], &IndexLabel::from("a")).is_err());
33789        Ok(())
33790    }
33791
33792    #[test]
33793    fn period_index_set_ops_match_pandas_8042v() -> Result<(), super::IndexError> {
33794        use fp_types::{Period, PeriodFreq};
33795        let p1 = Period::new(10, PeriodFreq::Monthly);
33796        let p2 = Period::new(11, PeriodFreq::Monthly);
33797        let p3 = Period::new(12, PeriodFreq::Monthly);
33798        let p4 = Period::new(13, PeriodFreq::Monthly);
33799        let left = super::PeriodIndex::new(vec![p1, p2, p3]).set_name("p");
33800        let right = super::PeriodIndex::new(vec![p2, p3, p4]).set_name("p");
33801
33802        assert_eq!(left.intersection(&right)?.values(), &[p2, p3]);
33803        assert_eq!(left.union(&right)?.values(), &[p1, p2, p3, p4]);
33804        assert_eq!(left.difference(&right)?.values(), &[p1]);
33805        assert_eq!(left.symmetric_difference(&right)?.values(), &[p1, p4]);
33806
33807        // Mismatched freq rejects.
33808        let mismatch = super::PeriodIndex::new(vec![Period::new(10, PeriodFreq::ANNUAL)]);
33809        assert!(left.intersection(&mismatch).is_err());
33810        assert!(left.union(&mismatch).is_err());
33811        assert!(left.difference(&mismatch).is_err());
33812        assert!(left.symmetric_difference(&mismatch).is_err());
33813
33814        // Mismatched names drop the name.
33815        let other_name = super::PeriodIndex::new(vec![p2]).set_name("other");
33816        assert_eq!(left.union(&other_name)?.name(), None);
33817        Ok(())
33818    }
33819
33820    #[test]
33821    fn period_categorical_sort_values_match_pandas_482qd() -> Result<(), super::IndexError> {
33822        use fp_types::{Period, PeriodFreq};
33823        let p1 = Period::new(10, PeriodFreq::Monthly);
33824        let p2 = Period::new(11, PeriodFreq::Monthly);
33825        let p3 = Period::new(12, PeriodFreq::Monthly);
33826        let pi = super::PeriodIndex::new(vec![p3, p1, p2]).set_name("p");
33827        let sorted = pi.sort_values()?;
33828        let sorted_alias = pi.sort()?;
33829        assert_eq!(sorted.values(), &[p1, p2, p3]);
33830        assert_eq!(sorted_alias.values(), sorted.values());
33831        assert_eq!(sorted.name().map(|n| n.as_str()), Some("p"));
33832        assert_eq!(sorted_alias.name().map(|n| n.as_str()), Some("p"));
33833
33834        let mixed = super::PeriodIndex::new(vec![
33835            Period::new(10, PeriodFreq::Monthly),
33836            Period::new(10, PeriodFreq::ANNUAL),
33837        ]);
33838        assert!(mixed.sort_values().is_err());
33839        assert!(mixed.sort().is_err());
33840
33841        // CategoricalIndex with ordered=true uses category position.
33842        let cat = super::CategoricalIndex::with_categories(
33843            vec![
33844                "b".to_owned(),
33845                "a".to_owned(),
33846                "c".to_owned(),
33847                "a".to_owned(),
33848            ],
33849            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
33850            true,
33851        )?;
33852        let cat_sorted = cat.sort_values();
33853        let cat_sorted_alias = cat.sort();
33854        assert_eq!(
33855            cat_sorted.labels(),
33856            vec![
33857                IndexLabel::from("a"),
33858                IndexLabel::from("a"),
33859                IndexLabel::from("b"),
33860                IndexLabel::from("c")
33861            ]
33862            .as_slice()
33863        );
33864        assert_eq!(cat_sorted_alias.labels(), cat_sorted.labels());
33865
33866        Ok(())
33867    }
33868
33869    #[test]
33870    fn categorical_sort_values_by_category_code_not_lexicographic() {
33871        // Non-lexicographic category order: codes b=0, a=1, c=2. pandas
33872        // sort_values orders by code -> b, a, a, c (NOT lexicographic a,a,b,c).
33873        // The old `to_index().argsort()` text sort returned a,a,b,c, which
33874        // diverges from pandas; the existing 482qd test used lexicographic
33875        // categories so it could not catch this.
33876        let cat = super::CategoricalIndex::with_categories(
33877            vec![
33878                "a".to_owned(),
33879                "c".to_owned(),
33880                "b".to_owned(),
33881                "a".to_owned(),
33882            ],
33883            vec!["b".to_owned(), "a".to_owned(), "c".to_owned()],
33884            true,
33885        )
33886        .unwrap();
33887        // labels [a,c,b,a] -> codes [1,2,0,1]; stable argsort by code:
33888        // code0 -> pos2 (b); code1 -> pos0 (a), pos3 (a); code2 -> pos1 (c).
33889        assert_eq!(cat.argsort(), vec![2, 0, 3, 1]);
33890        assert_eq!(
33891            cat.sort_values().labels(),
33892            [
33893                IndexLabel::from("b"),
33894                IndexLabel::from("a"),
33895                IndexLabel::from("a"),
33896                IndexLabel::from("c")
33897            ]
33898            .as_slice()
33899        );
33900
33901        // Unordered categoricals also sort by category code in pandas.
33902        let cat_u = super::CategoricalIndex::with_categories(
33903            vec!["a".to_owned(), "b".to_owned()],
33904            vec!["b".to_owned(), "a".to_owned()],
33905            false,
33906        )
33907        .unwrap();
33908        // codes a=1, b=0 -> sorted by code: b, a.
33909        assert_eq!(
33910            cat_u.sort_values().labels(),
33911            [IndexLabel::from("b"), IndexLabel::from("a")].as_slice()
33912        );
33913    }
33914
33915    #[test]
33916    fn period_index_from_ordinals_match_pandas_baenb() {
33917        use fp_types::PeriodFreq;
33918        let pi = super::PeriodIndex::from_ordinals(&[10, 11, 12], PeriodFreq::Monthly);
33919        assert_eq!(pi.values().len(), 3);
33920        assert_eq!(pi.values()[0].ordinal, 10);
33921        assert_eq!(pi.values()[2].ordinal, 12);
33922        assert_eq!(pi.asi8(), vec![10, 11, 12]);
33923        for period in pi.values() {
33924            assert_eq!(period.freq, PeriodFreq::Monthly);
33925        }
33926
33927        let empty = super::PeriodIndex::from_ordinals(&[], PeriodFreq::ANNUAL);
33928        assert!(empty.is_empty());
33929        assert!(empty.asi8().is_empty());
33930    }
33931
33932    #[test]
33933    fn period_fields_read_the_end_date_and_nat_is_missing() -> Result<(), super::IndexError> {
33934        use fp_types::PeriodFreq;
33935        // pd.PeriodIndex(['2024-01', NaT, '2023-02'], freq='M'): a month's
33936        // day is its last; a NaT period's fields are missing (the binding's
33937        // -1), its boundaries NaT, its asfreq NaT.
33938        let months = super::PeriodIndex::from_ordinals(&[648, i64::MIN, 637], PeriodFreq::Monthly);
33939        assert_eq!(months.day()?, vec![Some(31), None, Some(28)]);
33940        assert_eq!(months.dayofyear()?, vec![Some(31), None, Some(59)]);
33941        assert_eq!(months.week()?, vec![Some(5), None, Some(9)]);
33942        assert_eq!(months.qyear()?, vec![2024, -1, 2023]);
33943        assert_eq!(
33944            months.start_time()?.as_index().labels()[1],
33945            super::IndexLabel::Datetime64(i64::MIN)
33946        );
33947        let days = months.asfreq("D")?;
33948        assert_eq!(days.values()[1].ordinal, i64::MIN);
33949        assert_eq!(days.values()[1].freq, PeriodFreq::Daily);
33950        // A quarter's month is its third; an hour's hour is itself.
33951        let quarters = super::PeriodIndex::from_ordinals(&[216], PeriodFreq::QUARTERLY);
33952        assert_eq!(quarters.month()?, vec![Some(3)]);
33953        let hours = super::PeriodIndex::from_ordinals(&[473_374], PeriodFreq::Hourly);
33954        assert_eq!(hours.hour()?, vec![Some(22)]);
33955        // NEGATIVE: a month's year and month are those of its start too.
33956        assert_eq!(months.year()?, vec![Some(2024), None, Some(2023)]);
33957        assert_eq!(months.month()?, vec![Some(1), None, Some(2)]);
33958        Ok(())
33959    }
33960
33961    /// Anchored frequencies on pandas' fiscal axes, live pandas 2.2.3:
33962    /// 2024-03-01 is Y-JUN '2024' (ordinal 54, from 2023-07-01), Q-JAN
33963    /// '2025Q1' (220, from 2024-02-01; quarter 1, qyear 2025, year 2024),
33964    /// Q-NOV '2024Q2' (217), W-MON ordinal 2827 from 2024-02-27, W-SAT 2826
33965    /// from 2024-02-25; 1969-12-31 at Q-JAN is 1970Q4 (3)
33966    /// (br-frankenpandas-39h5n).
33967    #[test]
33968    fn anchored_periods_follow_the_fiscal_calendar_39h5n() -> Result<(), super::IndexError> {
33969        use fp_types::PeriodFreq;
33970        const DAY: i64 = 86_400_000_000_000;
33971        let march_first = 19_783 * DAY;
33972        let cases = [
33973            (PeriodFreq::Annual(6), 54, 19_539),
33974            (PeriodFreq::Quarterly(1), 220, 19_754),
33975            (PeriodFreq::Quarterly(11), 217, 19_783),
33976            (PeriodFreq::Weekly(0), 2827, 19_780),
33977            (PeriodFreq::Weekly(5), 2826, 19_778),
33978            (PeriodFreq::QUARTERLY, 216, 19_723),
33979        ];
33980        for (freq, ordinal, start_day) in cases {
33981            let period = super::datetime_nanos_to_period(march_first, freq)?;
33982            assert_eq!(period.ordinal, ordinal, "{freq:?}");
33983            assert_eq!(
33984                super::period_start_nanos(period)?,
33985                start_day * DAY,
33986                "{freq:?}"
33987            );
33988        }
33989        let pre_epoch = super::datetime_nanos_to_period(-DAY, PeriodFreq::Quarterly(1))?;
33990        assert_eq!(pre_epoch.ordinal, 3);
33991        let quarters =
33992            super::PeriodIndex::from_ordinals(&[220, i64::MIN], PeriodFreq::Quarterly(1));
33993        assert_eq!(quarters.quarter()?, vec![Some(1), None]);
33994        assert_eq!(quarters.qyear()?, vec![2025, -1]);
33995        assert_eq!(quarters.year()?, vec![Some(2024), None]);
33996        assert_eq!(quarters.month()?, vec![Some(4), None]);
33997        // NEGATIVE: a fiscal year's quarter is its end date's calendar one.
33998        let years = super::PeriodIndex::from_ordinals(&[54], PeriodFreq::Annual(6));
33999        assert_eq!(years.quarter()?, vec![Some(2)]);
34000        Ok(())
34001    }
34002
34003    #[test]
34004    fn period_index_astype_datetime_and_int_match_pandas() -> Result<(), super::IndexError> {
34005        use fp_types::PeriodFreq;
34006
34007        let pi = super::PeriodIndex::from_ordinals(&[600, 601], PeriodFreq::Monthly).set_name("p");
34008
34009        let as_int = pi.astype("int64")?;
34010        assert_eq!(
34011            as_int.labels(),
34012            &[IndexLabel::Int64(600), IndexLabel::Int64(601)]
34013        );
34014        assert_eq!(as_int.name().map(|n| n.as_str()), Some("p"));
34015
34016        let as_datetime = pi.astype("datetime64[ns]")?;
34017        assert_eq!(
34018            as_datetime.labels(),
34019            &[
34020                IndexLabel::Datetime64(1_577_836_800_000_000_000),
34021                IndexLabel::Datetime64(1_580_515_200_000_000_000),
34022            ]
34023        );
34024        assert_eq!(as_datetime.name().map(|n| n.as_str()), Some("p"));
34025
34026        Ok(())
34027    }
34028
34029    #[test]
34030    fn period_index_missing_value_accessors_are_all_present() {
34031        use fp_types::PeriodFreq;
34032        let pi = super::PeriodIndex::from_ordinals(&[10, 11, 12], PeriodFreq::Monthly)
34033            .set_name("periods");
34034        assert!(!pi.hasnans());
34035        assert_eq!(pi.isna(), vec![false, false, false]);
34036        assert_eq!(pi.isnull(), pi.isna());
34037        assert_eq!(pi.notna(), vec![true, true, true]);
34038        assert_eq!(pi.notnull(), pi.notna());
34039        let dropped = pi.dropna();
34040        assert_eq!(dropped.values(), pi.values());
34041        assert_eq!(dropped.name().map(|n| n.as_str()), Some("periods"));
34042    }
34043
34044    #[test]
34045    fn period_index_mean_median_match_pandas_3rsrc() -> Result<(), super::IndexError> {
34046        use fp_types::{Period, PeriodFreq};
34047        let p1 = Period::new(10, PeriodFreq::Monthly);
34048        let p2 = Period::new(20, PeriodFreq::Monthly);
34049        let p3 = Period::new(30, PeriodFreq::Monthly);
34050        let pi = super::PeriodIndex::new(vec![p1, p2, p3]);
34051        assert_eq!(pi.mean()?.unwrap().ordinal, 20);
34052        assert_eq!(pi.median()?.unwrap().ordinal, 20);
34053
34054        let empty = super::PeriodIndex::new(Vec::new());
34055        assert_eq!(empty.mean()?, None);
34056        assert_eq!(empty.median()?, None);
34057
34058        let mixed = super::PeriodIndex::new(vec![p1, Period::new(10, PeriodFreq::ANNUAL)]);
34059        assert!(mixed.mean().is_err());
34060        assert!(mixed.median().is_err());
34061        Ok(())
34062    }
34063
34064    #[test]
34065    fn period_index_argmax_argmin_argsort_match_pandas_qg8u5() -> Result<(), super::IndexError> {
34066        use fp_types::{Period, PeriodFreq};
34067        let p1 = Period::new(10, PeriodFreq::Monthly);
34068        let p2 = Period::new(11, PeriodFreq::Monthly);
34069        let p3 = Period::new(12, PeriodFreq::Monthly);
34070        let pi = super::PeriodIndex::new(vec![p2, p3, p1]);
34071
34072        assert_eq!(pi.argmax()?, 1);
34073        assert_eq!(pi.argmin()?, 2);
34074        assert_eq!(pi.argsort()?, vec![2, 0, 1]);
34075
34076        let empty = super::PeriodIndex::new(Vec::new());
34077        assert!(empty.argmax().is_err());
34078        assert!(empty.argmin().is_err());
34079        assert!(empty.argsort()?.is_empty());
34080
34081        let mixed = super::PeriodIndex::new(vec![p1, Period::new(10, PeriodFreq::ANNUAL)]);
34082        assert!(mixed.argmax().is_err());
34083        assert!(mixed.argsort().is_err());
34084        Ok(())
34085    }
34086
34087    #[test]
34088    fn period_index_shift_match_pandas_pnaui() -> Result<(), super::IndexError> {
34089        use fp_types::{Period, PeriodFreq};
34090        let p1 = Period::new(10, PeriodFreq::Monthly);
34091        let p2 = Period::new(11, PeriodFreq::Monthly);
34092        let pi = super::PeriodIndex::new(vec![p1, p2]).set_name("p");
34093
34094        let shifted = pi.shift(2)?;
34095        assert_eq!(shifted.values()[0].ordinal, 12);
34096        assert_eq!(shifted.values()[1].ordinal, 13);
34097        assert_eq!(shifted.name().map(|n| n.as_str()), Some("p"));
34098
34099        // Negative shift.
34100        let back = pi.shift(-1)?;
34101        assert_eq!(back.values()[0].ordinal, 9);
34102
34103        // Mixed-freq rejects.
34104        let mixed = super::PeriodIndex::new(vec![p1, Period::new(10, PeriodFreq::ANNUAL)]);
34105        assert!(mixed.shift(1).is_err());
34106        Ok(())
34107    }
34108
34109    #[test]
34110    fn period_index_is_full_match_pandas_7i32m() {
34111        use fp_types::{Period, PeriodFreq};
34112        let p1 = Period::new(10, PeriodFreq::Monthly);
34113        let p2 = Period::new(11, PeriodFreq::Monthly);
34114        let p3 = Period::new(12, PeriodFreq::Monthly);
34115        let p5 = Period::new(14, PeriodFreq::Monthly);
34116
34117        // Contiguous.
34118        let full = super::PeriodIndex::new(vec![p1, p2, p3]);
34119        assert!(full.is_full());
34120
34121        // Out-of-order but contiguous (sort first).
34122        let unsorted = super::PeriodIndex::new(vec![p3, p1, p2]);
34123        assert!(unsorted.is_full());
34124
34125        // Gap.
34126        let gap = super::PeriodIndex::new(vec![p1, p2, p5]);
34127        assert!(!gap.is_full());
34128
34129        // Empty / single-element.
34130        assert!(super::PeriodIndex::new(Vec::new()).is_full());
34131        assert!(super::PeriodIndex::new(vec![p1]).is_full());
34132
34133        // Mixed-frequency.
34134        let mixed = super::PeriodIndex::new(vec![p1, Period::new(10, PeriodFreq::ANNUAL)]);
34135        assert!(!mixed.is_full());
34136    }
34137
34138    #[test]
34139    fn period_index_min_max_match_pandas_fwlv4() -> Result<(), super::IndexError> {
34140        use fp_types::{Period, PeriodFreq};
34141        let p1 = Period::new(10, PeriodFreq::Monthly);
34142        let p2 = Period::new(11, PeriodFreq::Monthly);
34143        let p3 = Period::new(12, PeriodFreq::Monthly);
34144        let pi = super::PeriodIndex::new(vec![p3, p1, p2]);
34145        assert_eq!(pi.min()?, Some(p1));
34146        assert_eq!(pi.max()?, Some(p3));
34147
34148        let empty = super::PeriodIndex::new(Vec::new());
34149        assert_eq!(empty.min()?, None);
34150        assert_eq!(empty.max()?, None);
34151
34152        // Mixed freq rejects.
34153        let mixed = super::PeriodIndex::new(vec![
34154            Period::new(10, PeriodFreq::Monthly),
34155            Period::new(10, PeriodFreq::ANNUAL),
34156        ]);
34157        assert!(mixed.min().is_err());
34158        assert!(mixed.max().is_err());
34159        Ok(())
34160    }
34161
34162    #[test]
34163    fn range_index_sort_values_closed_form_mhcge() {
34164        let asc = super::RangeIndex::new(0, 5, 1).unwrap();
34165        assert!(asc.sort_values().equals(&asc));
34166        assert!(asc.sort().equals(&asc));
34167
34168        let desc = super::RangeIndex::new(10, 0, -2).unwrap();
34169        // Original values 10, 8, 6, 4, 2 → sorted ascending 2, 4, 6, 8, 10.
34170        let sorted = desc.sort_values();
34171        let sorted_alias = desc.sort();
34172        assert_eq!(sorted.values().to_vec(), vec![2, 4, 6, 8, 10]);
34173        assert_eq!(sorted_alias.values().to_vec(), sorted.values().to_vec());
34174
34175        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
34176        assert!(empty.sort_values().is_empty());
34177        assert!(empty.sort().is_empty());
34178
34179        let zero_step = super::RangeIndex::new(0, 5, 1).unwrap();
34180        assert!(zero_step.sort_values().equals(&zero_step));
34181        assert!(zero_step.sort().equals(&zero_step));
34182    }
34183
34184    #[test]
34185    fn range_index_sort_values_keeps_singleton_min_step_uza04177() {
34186        let singleton = super::RangeIndex::new(0, i64::MIN, i64::MIN)
34187            .unwrap()
34188            .set_name("row");
34189
34190        assert_eq!(singleton.len(), 1);
34191        assert_eq!(singleton.sort_values(), singleton);
34192    }
34193
34194    #[test]
34195    fn range_index_descending_ops_match_pandas_dustysummit() {
34196        use super::RangeIndex;
34197        // Regression coverage for descending-range handling — the exact smell
34198        // that was buggy in the set operations. All expected values verified
34199        // against pandas 2.2.3 (R(10,0,-2) = [10,8,6,4,2]).
34200        let vals = |idx: &super::Index| -> Vec<i64> {
34201            idx.labels()
34202                .iter()
34203                .filter_map(|l| match l {
34204                    super::IndexLabel::Int64(v) => Some(*v),
34205                    _ => None,
34206                })
34207                .collect()
34208        };
34209        let desc = RangeIndex::new(10, 0, -2).unwrap();
34210        let asc = RangeIndex::new(0, 10, 2).unwrap();
34211
34212        // argsort: the permutation that sorts values ascending.
34213        assert_eq!(desc.argsort(), vec![4, 3, 2, 1, 0]);
34214        assert_eq!(asc.argsort(), vec![0, 1, 2, 3, 4]);
34215
34216        // sort_values: ascending (descending rebuilds an ascending range).
34217        assert_eq!(
34218            vals(&desc.sort_values().to_flat_index()),
34219            vec![2, 4, 6, 8, 10]
34220        );
34221        assert_eq!(
34222            vals(&asc.sort_values().to_flat_index()),
34223            vec![0, 2, 4, 6, 8]
34224        );
34225
34226        // factorize: identity codes; uniques preserve the (descending) order.
34227        let (codes, uniques) = desc.factorize();
34228        assert_eq!(codes, vec![0, 1, 2, 3, 4]);
34229        assert_eq!(vals(&uniques.to_flat_index()), vec![10, 8, 6, 4, 2]);
34230
34231        // take / repeat: order-preserving over the descending values.
34232        assert_eq!(vals(&desc.take(&[0, 2, 4]).unwrap()), vec![10, 6, 2]);
34233        assert_eq!(vals(&desc.repeat(2)), vec![10, 10, 8, 8, 6, 6, 4, 4, 2, 2]);
34234
34235        // where keeps the value where cond is TRUE (replaces where false);
34236        // putmask replaces where the mask is TRUE — opposite conventions.
34237        let m = [true, false, true, false, true];
34238        assert_eq!(vals(&desc.r#where(&m, 99).unwrap()), vec![10, 99, 6, 99, 2]);
34239        assert_eq!(vals(&desc.putmask(&m, 99).unwrap()), vec![99, 8, 99, 4, 99]);
34240    }
34241
34242    #[test]
34243    fn test_range_index_extended_parity_methods() {
34244        let r = RangeIndex::from_range(2, 10, 2).unwrap();
34245        assert_eq!(r.len(), 4);
34246        assert!(r.contains(2));
34247        assert!(r.contains(4));
34248        assert!(r.contains(6));
34249        assert!(r.contains(8));
34250        assert!(!r.contains(0));
34251        assert!(!r.contains(10));
34252        assert!(!r.contains(3));
34253
34254        assert_eq!(r.get_slice_bound(4, "left").unwrap(), 1);
34255        assert_eq!(r.get_slice_bound(4, "right").unwrap(), 2);
34256
34257        assert!(r.all());
34258        assert!(r.any());
34259        assert_eq!(r.argmax().unwrap(), 3);
34260        assert_eq!(r.argmin().unwrap(), 0);
34261        assert_eq!(r.argsort(), vec![0, 1, 2, 3]);
34262
34263        assert!(!r.hasnans());
34264        assert_eq!(r.nlevels(), 1);
34265        assert_eq!(r.isna(), vec![false, false, false, false]);
34266        assert_eq!(r.isnull(), vec![false, false, false, false]);
34267        assert_eq!(r.notna(), vec![true, true, true, true]);
34268        assert_eq!(r.notnull(), vec![true, true, true, true]);
34269        assert_eq!(r.unique(), r);
34270        assert_eq!(r.drop_duplicates(), r);
34271        assert_eq!(
34272            r.duplicated(DuplicateKeep::First),
34273            vec![false, false, false, false]
34274        );
34275
34276        // Range containing 0
34277        let r_with_zero = RangeIndex::new(0, 5, 1).unwrap();
34278        assert!(!r_with_zero.all());
34279        assert!(r_with_zero.any());
34280
34281        // Empty range
34282        let r_empty = RangeIndex::new(0, 0, 1).unwrap();
34283        assert!(r_empty.all());
34284        assert!(!r_empty.any());
34285        assert!(r_empty.argmax().is_err());
34286        assert!(r_empty.argmin().is_err());
34287        assert!(r_empty.argsort().is_empty());
34288        assert!(!r_empty.contains(0));
34289
34290        // Descending range
34291        let r_desc = RangeIndex::new(10, 0, -2).unwrap();
34292        assert_eq!(r_desc.argmax().unwrap(), 0);
34293        assert_eq!(r_desc.argmin().unwrap(), 4);
34294        assert_eq!(r_desc.argsort(), vec![4, 3, 2, 1, 0]);
34295        assert!(r_desc.all());
34296        assert!(r_desc.any());
34297    }
34298
34299    #[test]
34300    #[allow(clippy::type_complexity)]
34301    fn range_index_set_ops_match_pandas_2_2_3_differential_dustysummit() {
34302        use super::RangeIndex;
34303        // Data-driven differential vs pandas 2.2.3 for all four set operations.
34304        // intersection uses sort=False (result ascending EXCEPT both operands
34305        // descending -> descending); union/difference/symmetric_difference use
34306        // sort=None (ascending EXCEPT empty-operand or value-equal passthrough).
34307        // Cases cover descending operands, non-aligned step lattices, empty
34308        // operands, value-equal operands, disjoint / overlapping / subset
34309        // overlaps. Expected values were computed by real pandas; see
34310        // testdata_rangeset_pandas_cases.rs.
34311        let cases: &[(
34312            (i64, i64, i64),
34313            (i64, i64, i64),
34314            &[i64],
34315            &[i64],
34316            &[i64],
34317            &[i64],
34318        )] = &include!("testdata_rangeset_pandas_cases.rs");
34319
34320        let vals = |idx: &super::Index| -> Vec<i64> {
34321            idx.labels()
34322                .iter()
34323                .filter_map(|l| match l {
34324                    super::IndexLabel::Int64(v) => Some(*v),
34325                    _ => None,
34326                })
34327                .collect()
34328        };
34329        let r = |(s, e, st): (i64, i64, i64)| RangeIndex::new(s, e, st).unwrap();
34330
34331        let mut fails: Vec<String> = Vec::new();
34332        for (i, (a, b, want_i, want_u, want_d, want_s)) in cases.iter().enumerate() {
34333            let (ra, rb) = (r(*a), r(*b));
34334            let got_i = vals(&ra.intersection(&rb));
34335            let got_u = vals(&ra.union(&rb));
34336            let got_d = vals(&ra.difference(&rb));
34337            let got_s = vals(&ra.symmetric_difference(&rb));
34338            if got_i != *want_i {
34339                fails.push(format!(
34340                    "#{i} inter {a:?}∩{b:?}: got {got_i:?} want {want_i:?}"
34341                ));
34342            }
34343            if got_u != *want_u {
34344                fails.push(format!(
34345                    "#{i} union {a:?}∪{b:?}: got {got_u:?} want {want_u:?}"
34346                ));
34347            }
34348            if got_d != *want_d {
34349                fails.push(format!(
34350                    "#{i} diff {a:?}∖{b:?}: got {got_d:?} want {want_d:?}"
34351                ));
34352            }
34353            if got_s != *want_s {
34354                fails.push(format!(
34355                    "#{i} symm {a:?}∆{b:?}: got {got_s:?} want {want_s:?}"
34356                ));
34357            }
34358        }
34359        assert!(
34360            fails.is_empty(),
34361            "{} RangeIndex set-op divergences from pandas 2.2.3:\n{}",
34362            fails.len(),
34363            fails.join("\n")
34364        );
34365    }
34366
34367    #[test]
34368    fn range_index_reduction_edge_cases_match_pandas_dustysummit() {
34369        use super::RangeIndex;
34370        // Empty range: min/max/median None; argmin/argmax error; both
34371        // monotonicity predicates True (an empty index is monotonic in pandas);
34372        // nunique 0.
34373        let empty = RangeIndex::new(5, 5, 1).unwrap();
34374        assert_eq!(empty.len(), 0);
34375        assert_eq!(empty.min(), None);
34376        assert_eq!(empty.max(), None);
34377        assert_eq!(empty.median(), None);
34378        assert!(empty.argmin().is_err());
34379        assert!(empty.argmax().is_err());
34380        assert!(empty.is_monotonic_increasing());
34381        assert!(empty.is_monotonic_decreasing());
34382        assert_eq!(empty.nunique(), 0);
34383
34384        // Single element: min == max; median == the value; argmin == argmax == 0;
34385        // monotonic both ways.
34386        let single = RangeIndex::new(7, 8, 1).unwrap();
34387        assert_eq!(single.len(), 1);
34388        assert_eq!(single.min(), Some(7));
34389        assert_eq!(single.max(), Some(7));
34390        assert_eq!(single.median(), Some(7.0));
34391        assert_eq!(single.argmin().unwrap(), 0);
34392        assert_eq!(single.argmax().unwrap(), 0);
34393        assert!(single.is_monotonic_increasing());
34394        assert!(single.is_monotonic_decreasing());
34395
34396        // Descending (odd length): [10,8,6,4,2]. min=2 (pos 4), max=10 (pos 0),
34397        // median=6; increasing False, decreasing True.
34398        let desc = RangeIndex::new(10, 0, -2).unwrap();
34399        assert_eq!(desc.len(), 5);
34400        assert_eq!(desc.min(), Some(2));
34401        assert_eq!(desc.max(), Some(10));
34402        assert_eq!(desc.median(), Some(6.0));
34403        assert_eq!(desc.argmin().unwrap(), 4);
34404        assert_eq!(desc.argmax().unwrap(), 0);
34405        assert!(!desc.is_monotonic_increasing());
34406        assert!(desc.is_monotonic_decreasing());
34407        assert_eq!(desc.nunique(), 5);
34408
34409        // Descending (even length): [10,8,6,4]. median = (8+6)/2 = 7; argmin = 3.
34410        let desc_even = RangeIndex::new(10, 2, -2).unwrap();
34411        assert_eq!(desc_even.len(), 4);
34412        assert_eq!(desc_even.median(), Some(7.0));
34413        assert_eq!(desc_even.argmin().unwrap(), 3);
34414        assert_eq!(desc_even.argmax().unwrap(), 0);
34415    }
34416
34417    #[test]
34418    fn range_index_std_var_median_closed_form_tkc0m() {
34419        let r = super::RangeIndex::new(1, 11, 1).unwrap();
34420        // 1..=10: median = 5.5; var = sum((x - 5.5)^2)/9; std = sqrt(var).
34421        assert_eq!(r.median(), Some(5.5));
34422        let var = r.var().unwrap();
34423        // Expected variance for 1..=10 is 9.166666...
34424        assert!((var - 9.1666666666).abs() < 1e-6);
34425        let std_val = r.std().unwrap();
34426        assert!((std_val - var.sqrt()).abs() < 1e-12);
34427
34428        // Single element: var/std None; median = the value.
34429        let one = super::RangeIndex::new(5, 6, 1).unwrap();
34430        assert_eq!(one.median(), Some(5.0));
34431        assert_eq!(one.var(), None);
34432        assert_eq!(one.std(), None);
34433
34434        let descending = super::RangeIndex::new(9, 0, -4).unwrap();
34435        assert_eq!(descending.median(), Some(5.0));
34436
34437        let even_step = super::RangeIndex::new(2, 14, 3).unwrap();
34438        assert_eq!(even_step.median(), Some(6.5));
34439
34440        // Empty: all None.
34441        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
34442        assert_eq!(empty.median(), None);
34443        assert_eq!(empty.var(), None);
34444    }
34445
34446    #[test]
34447    fn range_index_prod_match_pandas_8yxw8() {
34448        // 1..=5 prod = 120.
34449        let r = super::RangeIndex::new(1, 6, 1).unwrap();
34450        assert_eq!(r.prod(), 120);
34451
34452        // Empty prod = 1.
34453        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
34454        assert_eq!(empty.prod(), 1);
34455
34456        // Includes zero → prod = 0.
34457        let with_zero = super::RangeIndex::new(0, 5, 1).unwrap();
34458        assert_eq!(with_zero.prod(), 0);
34459    }
34460
34461    #[test]
34462    fn range_index_var_prod_use_direct_values_tzvt3() {
34463        let descending = super::RangeIndex::new(9, 0, -4).unwrap();
34464        assert_eq!(descending.var(), Some(16.0));
34465        assert_eq!(descending.std(), Some(4.0));
34466        assert_eq!(descending.prod(), 45);
34467
34468        let negative_step = super::RangeIndex::new(2, -7, -3).unwrap();
34469        assert_eq!(negative_step.var(), Some(9.0));
34470        assert_eq!(negative_step.prod(), 8);
34471
34472        let overflow = super::RangeIndex::new(i64::MAX, i64::MAX - 2, -1).unwrap();
34473        assert_eq!(overflow.prod(), i64::MAX);
34474    }
34475
34476    #[test]
34477    fn range_index_prod_positive_saturation_matches_former_e87gz() {
34478        fn former(range: &super::RangeIndex) -> i64 {
34479            let mut total: i128 = 1;
34480            for position in 0..range.len() {
34481                total = total.saturating_mul(i128::from(range.value_at(position)));
34482            }
34483            i64::try_from(total).unwrap_or(if total > 0 { i64::MAX } else { i64::MIN })
34484        }
34485
34486        for range in [
34487            super::RangeIndex::new(0, 0, 1).unwrap(),
34488            super::RangeIndex::new(1, 10, 1).unwrap(),
34489            super::RangeIndex::new(1, 10_001, 1).unwrap(),
34490            super::RangeIndex::new(10_000, 0, -1).unwrap(),
34491            super::RangeIndex::new(-3, 4, 1).unwrap(),
34492            super::RangeIndex::new(-1, -30, -1).unwrap(),
34493            super::RangeIndex::new(i64::MAX - 4, i64::MAX, 1).unwrap(),
34494        ] {
34495            assert_eq!(range.prod(), former(&range));
34496        }
34497    }
34498
34499    #[test]
34500    fn range_index_reductions_use_wide_length_uza04173() {
34501        let asc = super::RangeIndex::new(i64::MIN, i64::MAX, 1).unwrap();
34502        assert_eq!(asc.min(), Some(i64::MIN));
34503        assert_eq!(asc.max(), Some(i64::MAX - 1));
34504        assert_eq!(asc.sum(), i64::MIN);
34505        assert_eq!(asc.mean(), Some(-1.0));
34506
34507        let desc = super::RangeIndex::new(i64::MAX, i64::MIN, -1).unwrap();
34508        assert_eq!(desc.min(), Some(i64::MIN + 1));
34509        assert_eq!(desc.max(), Some(i64::MAX));
34510        assert_eq!(desc.sum(), 0);
34511        assert_eq!(desc.mean(), Some(0.0));
34512    }
34513
34514    #[test]
34515    fn range_index_memory_usage_saturates_uza04175() {
34516        let small = super::RangeIndex::new(2, 11, 3).unwrap();
34517        assert_eq!(small.memory_usage(false), 3 * std::mem::size_of::<i64>());
34518        assert_eq!(small.nbytes(), small.memory_usage(false));
34519
34520        let wide = super::RangeIndex::new(i64::MIN, i64::MAX, 1).unwrap();
34521        assert_eq!(wide.memory_usage(false), usize::MAX);
34522        assert_eq!(wide.nbytes(), usize::MAX);
34523    }
34524
34525    #[test]
34526    fn range_index_searchsorted_direct_values_mv1e4() -> Result<(), super::IndexError> {
34527        let stepped = super::RangeIndex::new(2, 20, 3).unwrap();
34528
34529        assert_eq!(stepped.searchsorted(1, "left")?, 0);
34530        assert_eq!(stepped.searchsorted(2, "left")?, 0);
34531        assert_eq!(stepped.searchsorted(2, "right")?, 1);
34532        assert_eq!(stepped.searchsorted(8, "left")?, 2);
34533        assert_eq!(stepped.searchsorted(9, "left")?, 3);
34534        assert_eq!(stepped.searchsorted(20, "left")?, 6);
34535
34536        let empty = super::RangeIndex::new(5, 5, 1).unwrap();
34537        assert_eq!(empty.searchsorted(5, "left")?, 0);
34538
34539        let descending = super::RangeIndex::new(9, 0, -3).unwrap();
34540        assert!(descending.searchsorted(6, "left").is_err());
34541
34542        Ok(())
34543    }
34544
34545    #[test]
34546    fn range_index_searchsorted_uses_closed_form_uza04174() -> Result<(), super::IndexError> {
34547        let stepped = super::RangeIndex::new(i64::MIN, i64::MIN + 10, 2).unwrap();
34548        assert_eq!(stepped.searchsorted(i64::MIN, "left")?, 0);
34549        assert_eq!(stepped.searchsorted(i64::MIN, "right")?, 1);
34550        assert_eq!(stepped.searchsorted(i64::MIN + 3, "left")?, 2);
34551        assert_eq!(stepped.searchsorted(i64::MIN + 4, "right")?, 3);
34552
34553        let wide = super::RangeIndex::new(i64::MIN, i64::MAX, 1).unwrap();
34554        let zero_pos = usize::try_from(i128::from(i64::MAX) + 1).unwrap();
34555        assert_eq!(wide.searchsorted(0, "left")?, zero_pos);
34556        assert_eq!(wide.searchsorted(0, "right")?, zero_pos + 1);
34557        assert_eq!(wide.searchsorted(i64::MAX, "left")?, wide.len());
34558        Ok(())
34559    }
34560
34561    #[test]
34562    fn range_index_min_max_sum_mean_closed_form_fwlv4() {
34563        let asc = super::RangeIndex::new(1, 11, 1).unwrap();
34564        // Values 1..=10
34565        assert_eq!(asc.min(), Some(1));
34566        assert_eq!(asc.max(), Some(10));
34567        assert_eq!(asc.sum(), 55);
34568        assert_eq!(asc.mean(), Some(5.5));
34569
34570        let desc = super::RangeIndex::new(10, 0, -2).unwrap();
34571        // Values 10, 8, 6, 4, 2 — sum=30, mean=6, min=2, max=10
34572        assert_eq!(desc.min(), Some(2));
34573        assert_eq!(desc.max(), Some(10));
34574        assert_eq!(desc.sum(), 30);
34575        assert_eq!(desc.mean(), Some(6.0));
34576
34577        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
34578        assert_eq!(empty.min(), None);
34579        assert_eq!(empty.max(), None);
34580        assert_eq!(empty.sum(), 0);
34581        assert_eq!(empty.mean(), None);
34582    }
34583
34584    #[test]
34585    fn datetime_index_where_putmask_match_pandas_nwqty() -> Result<(), super::IndexError> {
34586        const NS: i64 = 1_000_000_000;
34587        let a = 1_704_067_200_i64 * NS;
34588        let b = 1_705_276_800_i64 * NS;
34589        let c = 1_706_140_800_i64 * NS;
34590        let dt = super::DatetimeIndex::new(vec![a, b, c]).set_name("ts");
34591
34592        // where: keep position 0 and 2; replace position 1 with i64::MIN (NAT).
34593        let masked = dt.r#where(&[true, false, true], i64::MIN)?;
34594        assert_eq!(masked.values(), vec![Some(a), None, Some(c)]);
34595        assert_eq!(masked.name().map(|n| n.as_str()), Some("ts"));
34596
34597        // putmask: replace positions where mask=true with c.
34598        let put = dt.putmask(&[true, false, false], c)?;
34599        assert_eq!(put.values(), vec![Some(c), Some(b), Some(c)]);
34600
34601        // Length mismatch errors.
34602        let bad_cond = dt.r#where(&[true, false], i64::MIN).unwrap_err();
34603        assert!(matches!(
34604            bad_cond,
34605            super::IndexError::LengthMismatch {
34606                expected: 3,
34607                actual: 2,
34608                ..
34609            }
34610        ));
34611        let bad_mask = dt.putmask(&[true; 5], c).unwrap_err();
34612        assert!(matches!(
34613            bad_mask,
34614            super::IndexError::LengthMismatch {
34615                expected: 3,
34616                actual: 5,
34617                ..
34618            }
34619        ));
34620        Ok(())
34621    }
34622
34623    #[test]
34624    fn timedelta_index_where_putmask_match_pandas_nwqty() -> Result<(), super::IndexError> {
34625        let nat = fp_types::Timedelta::NAT;
34626        let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]).set_name("d");
34627
34628        let masked = td.r#where(&[false, true, false], nat)?;
34629        assert_eq!(masked.values(), vec![None, Some(200), None]);
34630        assert_eq!(masked.name().map(|n| n.as_str()), Some("d"));
34631
34632        let put = td.putmask(&[false, true, true], 999)?;
34633        assert_eq!(put.values(), vec![Some(100), Some(999), Some(999)]);
34634
34635        let bad = td.r#where(&[true, false], nat).unwrap_err();
34636        assert!(matches!(
34637            bad,
34638            super::IndexError::LengthMismatch {
34639                expected: 3,
34640                actual: 2,
34641                ..
34642            }
34643        ));
34644        Ok(())
34645    }
34646
34647    #[test]
34648    fn index_variants_searchsorted_match_pandas_tam73() -> Result<(), super::IndexError> {
34649        const NS: i64 = 1_000_000_000;
34650        let a = 1_704_067_200_i64 * NS;
34651        let b = 1_705_276_800_i64 * NS;
34652        let c = 1_706_140_800_i64 * NS;
34653        let dt = super::DatetimeIndex::new(vec![a, b, c]);
34654
34655        assert_eq!(dt.searchsorted(a, "left")?, 0);
34656        assert_eq!(dt.searchsorted(a, "right")?, 1);
34657        assert_eq!(dt.searchsorted(c, "right")?, 3);
34658        // Mid-range insertion (between a and b).
34659        let mid = a + 1;
34660        assert_eq!(dt.searchsorted(mid, "left")?, 1);
34661
34662        // Bad side.
34663        assert!(dt.searchsorted(a, "middle").is_err());
34664
34665        let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]);
34666        assert_eq!(td.searchsorted(150, "left")?, 1);
34667        assert_eq!(td.searchsorted(200, "right")?, 2);
34668
34669        use fp_types::{Period, PeriodFreq};
34670        let p1 = Period::new(10, PeriodFreq::Monthly);
34671        let p2 = Period::new(11, PeriodFreq::Monthly);
34672        let p3 = Period::new(12, PeriodFreq::Monthly);
34673        let pi = super::PeriodIndex::new(vec![p1, p2, p3]);
34674        assert_eq!(pi.searchsorted(p2, "left")?, 1);
34675        assert_eq!(pi.searchsorted(p3, "right")?, 3);
34676        // Mismatched freq rejects.
34677        let mismatch = Period::new(10, PeriodFreq::ANNUAL);
34678        assert!(pi.searchsorted(mismatch, "left").is_err());
34679
34680        let r = super::RangeIndex::new(0, 10, 2).unwrap();
34681        // Range values: [0, 2, 4, 6, 8].
34682        assert_eq!(r.searchsorted(4, "left")?, 2);
34683        assert_eq!(r.searchsorted(4, "right")?, 3);
34684        assert_eq!(r.searchsorted(7, "left")?, 4);
34685
34686        // Descending range rejects.
34687        let desc = super::RangeIndex::new(10, 0, -2).unwrap();
34688        assert!(desc.searchsorted(4, "left").is_err());
34689        Ok(())
34690    }
34691
34692    #[test]
34693    fn datetime_timedelta_get_indexer_non_unique_match_pandas_sm32a() {
34694        const NS: i64 = 1_000_000_000;
34695        let a = 1_704_067_200_i64 * NS;
34696        let b = 1_705_276_800_i64 * NS;
34697        // 4-element index with a duplicated `a`.
34698        let dt = super::DatetimeIndex::new(vec![a, b, a, b]);
34699        let (positions, missing) = dt.get_indexer_non_unique(&[a, b + 99]);
34700        // a matches positions 0 and 2; b+99 is missing.
34701        assert_eq!(positions, vec![0, 2, -1]);
34702        assert_eq!(missing, vec![1]);
34703
34704        let td = super::TimedeltaIndex::new(vec![100_i64, 200, 100]);
34705        let (positions, missing) = td.get_indexer_non_unique(&[100, 999]);
34706        assert_eq!(positions, vec![0, 2, -1]);
34707        assert_eq!(missing, vec![1]);
34708    }
34709
34710    #[test]
34711    fn datetime_timedelta_get_loc_get_indexer_match_pandas_6x9de() -> Result<(), super::IndexError>
34712    {
34713        const NS: i64 = 1_000_000_000;
34714        let a = 1_704_067_200_i64 * NS;
34715        let b = 1_705_276_800_i64 * NS;
34716        let c = 1_706_140_800_i64 * NS;
34717        let dt = super::DatetimeIndex::new(vec![a, b, c]);
34718
34719        // get_loc finds first position.
34720        assert_eq!(dt.get_loc(b)?, 1);
34721        let missing_err = dt.get_loc(b + 1).unwrap_err();
34722        assert!(matches!(
34723            missing_err,
34724            super::IndexError::InvalidArgument(ref msg) if msg.contains("get_loc")
34725        ));
34726
34727        // get_indexer maps each target.
34728        let mapped = dt.get_indexer(&[c, a, b + 999]);
34729        assert_eq!(mapped, vec![2, 0, -1]);
34730
34731        // TimedeltaIndex spot check.
34732        let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]);
34733        assert_eq!(td.get_loc(200)?, 1);
34734        assert_eq!(td.get_indexer(&[300, 999, 100]), vec![2, -1, 0]);
34735        Ok(())
34736    }
34737
34738    #[test]
34739    fn datetime_timedelta_slice_indexer_match_pandas_95eqf() -> Result<(), super::IndexError> {
34740        const NS: i64 = 1_000_000_000;
34741        let a = 1_704_067_200_i64 * NS;
34742        let b = 1_705_276_800_i64 * NS;
34743        let c = 1_706_140_800_i64 * NS;
34744        let dt = super::DatetimeIndex::new(vec![a, b, c]);
34745        assert_eq!(dt.slice_indexer(b, c)?, 1..3);
34746        assert_eq!(dt.slice_indexer(a, c)?, 0..3);
34747
34748        let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]);
34749        assert_eq!(td.slice_indexer(150, 250)?, 1..2);
34750        Ok(())
34751    }
34752
34753    #[test]
34754    fn datetime_timedelta_get_slice_bound_match_pandas_x7r04() -> Result<(), super::IndexError> {
34755        const NS: i64 = 1_000_000_000;
34756        let a = 1_704_067_200_i64 * NS;
34757        let b = 1_705_276_800_i64 * NS;
34758        let c = 1_706_140_800_i64 * NS;
34759        let dt = super::DatetimeIndex::new(vec![a, b, c]);
34760        assert_eq!(dt.get_slice_bound(b, "left")?, 1);
34761        assert_eq!(dt.get_slice_bound(b, "right")?, 2);
34762        assert!(dt.get_slice_bound(b, "middle").is_err());
34763
34764        let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]);
34765        assert_eq!(td.get_slice_bound(150, "left")?, 1);
34766        assert_eq!(td.get_slice_bound(200, "right")?, 2);
34767        Ok(())
34768    }
34769
34770    #[test]
34771    fn datetime_timedelta_slice_locs_match_pandas_mxedz() -> Result<(), super::IndexError> {
34772        const NS: i64 = 1_000_000_000;
34773        let a = 1_704_067_200_i64 * NS;
34774        let b = 1_705_276_800_i64 * NS;
34775        let c = 1_706_140_800_i64 * NS;
34776        let d = 1_707_350_400_i64 * NS;
34777        let dt = super::DatetimeIndex::new(vec![a, b, c, d]);
34778
34779        // Slice [b, c]: positions [1, 3) (right is exclusive in slice_locs).
34780        assert_eq!(dt.slice_locs(b, c)?, (1, 3));
34781        // Slice [a, d]: full range.
34782        assert_eq!(dt.slice_locs(a, d)?, (0, 4));
34783        // Slice past the end: empty range.
34784        assert_eq!(dt.slice_locs(d + 1, d + 2)?, (4, 4));
34785
34786        // Non-monotonic rejects.
34787        let unsorted = super::DatetimeIndex::new(vec![c, a, b, d]);
34788        assert!(unsorted.slice_locs(a, c).is_err());
34789
34790        // TimedeltaIndex spot check.
34791        let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]);
34792        assert_eq!(td.slice_locs(150, 250)?, (1, 2));
34793
34794        Ok(())
34795    }
34796
34797    #[test]
34798    fn index_variants_to_flat_index_match_pandas_wcpw5() {
34799        const NS: i64 = 1_000_000_000;
34800        let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS]).set_name("ts");
34801        let dt_flat = dt.to_flat_index();
34802        assert_eq!(dt_flat.len(), 1);
34803        assert_eq!(dt_flat.name().map(|n| n.as_str()), Some("ts"));
34804        assert!(matches!(
34805            dt_flat.labels()[0],
34806            super::IndexLabel::Datetime64(_)
34807        ));
34808        assert_eq!(dt.to_frame(), dt_flat.to_frame());
34809        assert_eq!(dt.to_series(), dt_flat.to_series());
34810
34811        let td = super::TimedeltaIndex::new(vec![100_i64]).set_name("d");
34812        let td_flat = td.to_flat_index();
34813        assert_eq!(td_flat.len(), 1);
34814        assert_eq!(td_flat.name().map(|n| n.as_str()), Some("d"));
34815        assert_eq!(td.to_frame(), td_flat.to_frame());
34816        assert_eq!(td.to_series(), td_flat.to_series());
34817
34818        use fp_types::{Period, PeriodFreq};
34819        // TEST-CHANGE (45fzr): the flat labels are the periods themselves
34820        // (they were their text; pandas' PeriodIndex.to_flat_index is the
34821        // PeriodIndex).
34822        let pi = super::PeriodIndex::new(vec![Period::new(10, PeriodFreq::Monthly)]).set_name("p");
34823        let pi_flat = pi.to_flat_index();
34824        assert_eq!(pi_flat.len(), 1);
34825        assert_eq!(
34826            pi_flat.labels()[0],
34827            super::IndexLabel::Period(Period::new(10, PeriodFreq::Monthly))
34828        );
34829        assert_eq!(pi.to_frame(), pi_flat.to_frame());
34830        assert_eq!(pi.to_series(), pi_flat.to_series());
34831
34832        let r = super::RangeIndex::new(0, 3, 1).unwrap().set_name("r");
34833        let r_flat = r.to_flat_index();
34834        assert_eq!(r_flat.len(), 3);
34835        assert_eq!(r_flat.name().map(|n| n.as_str()), Some("r"));
34836        assert_eq!(r.to_frame(), r_flat.to_frame());
34837        assert_eq!(r.to_series(), r_flat.to_series());
34838
34839        let cat = super::CategoricalIndex::from_values(vec!["a".to_owned(), "b".to_owned()], false);
34840        let cat_flat = cat.to_flat_index();
34841        assert_eq!(cat_flat.len(), 2);
34842        assert_eq!(cat.to_frame(), cat_flat.to_frame());
34843        assert_eq!(cat.to_series(), cat_flat.to_series());
34844    }
34845
34846    #[test]
34847    fn index_variants_all_any_forward_flat_truthiness_ejwyw() {
34848        const NS: i64 = 1_000_000_000;
34849
34850        let dt = super::DatetimeIndex::new(vec![0, NS]);
34851        let dt_flat = dt.to_flat_index();
34852        assert_eq!(dt.any(), dt_flat.any());
34853        assert_eq!(dt.all(), dt_flat.all());
34854        assert!(dt.any());
34855        assert!(!dt.all());
34856
34857        let td = super::TimedeltaIndex::new(vec![0, 5]);
34858        let td_flat = td.to_flat_index();
34859        assert_eq!(td.any(), td_flat.any());
34860        assert_eq!(td.all(), td_flat.all());
34861        assert!(td.any());
34862        assert!(!td.all());
34863
34864        use fp_types::{Period, PeriodFreq};
34865        let pi = super::PeriodIndex::new(vec![
34866            Period::new(1, PeriodFreq::Monthly),
34867            Period::new(2, PeriodFreq::Monthly),
34868        ]);
34869        let pi_flat = pi.to_flat_index();
34870        assert_eq!(pi.any(), pi_flat.any());
34871        assert_eq!(pi.all(), pi_flat.all());
34872        assert!(pi.any());
34873        assert!(pi.all());
34874
34875        let empty_pi = super::PeriodIndex::new(Vec::new());
34876        assert_eq!(empty_pi.any(), empty_pi.to_flat_index().any());
34877        assert!(!empty_pi.any());
34878
34879        // TEST-CHANGE (45fzr): a NaT period label is missing in the flat
34880        // index now (it was its text 'NaT', truthy), so a NaT-only index
34881        // is not any (pandas raises TypeError for PeriodIndex.any).
34882        let nat_pi = super::PeriodIndex::new(vec![Period::new(i64::MIN, PeriodFreq::Daily)]);
34883        assert_eq!(nat_pi.any(), nat_pi.to_flat_index().any());
34884        assert!(!nat_pi.any());
34885
34886        let range = super::RangeIndex::new(0, 3, 1).unwrap();
34887        let range_flat = range.to_flat_index();
34888        assert_eq!(range.any(), range_flat.any());
34889        assert_eq!(range.all(), range_flat.all());
34890        assert!(range.any());
34891        assert!(!range.all());
34892
34893        let empty_range = super::RangeIndex::new(0, 0, 1).unwrap();
34894        assert!(!empty_range.any());
34895        assert!(empty_range.all());
34896
34897        let cat = super::CategoricalIndex::from_values(vec![String::new(), "x".to_owned()], false);
34898        let cat_flat = cat.to_flat_index();
34899        assert_eq!(cat.any(), cat_flat.any());
34900        assert_eq!(cat.all(), cat_flat.all());
34901        assert!(cat.any());
34902        assert!(!cat.all());
34903    }
34904
34905    #[test]
34906    #[ignore = "profile harness for br-frankenpandas-8blqp"]
34907    fn period_index_any_nonempty_profile_8blqp() {
34908        use fp_types::{Period, PeriodFreq};
34909
34910        fn former(index: &super::PeriodIndex) -> bool {
34911            index.to_flat_index().any()
34912        }
34913
34914        fn candidate(index: &super::PeriodIndex) -> bool {
34915            index.any()
34916        }
34917
34918        fn percentile(sorted_samples: &[u128], percentile: usize) -> u128 {
34919            let rank = sorted_samples
34920                .len()
34921                .saturating_mul(percentile)
34922                .div_ceil(100)
34923                .saturating_sub(1);
34924            sorted_samples[rank]
34925        }
34926
34927        let parity_cases = [
34928            super::PeriodIndex::new(Vec::new()),
34929            super::PeriodIndex::new(vec![Period::new(i64::MIN, PeriodFreq::Daily)]),
34930            super::PeriodIndex::new(vec![Period::new(0, PeriodFreq::ANNUAL)]).set_name("annual"),
34931            super::PeriodIndex::new(vec![
34932                Period::new(i64::MIN, PeriodFreq::Monthly),
34933                Period::new(-1, PeriodFreq::QUARTERLY),
34934                Period::new(0, PeriodFreq::Daily),
34935                Period::new(i64::MAX, PeriodFreq::Secondly),
34936            ]),
34937        ];
34938        for index in &parity_cases {
34939            assert_eq!(candidate(index), former(index));
34940        }
34941
34942        let index =
34943            super::PeriodIndex::from_range(Period::new(-8_192, PeriodFreq::Minutely), 16_384)
34944                .set_name("minute");
34945        assert_eq!(candidate(&index), former(&index));
34946
34947        for _ in 0..2 {
34948            std::hint::black_box(former(std::hint::black_box(&index)));
34949            std::hint::black_box(candidate(std::hint::black_box(&index)));
34950        }
34951
34952        let mut former_ns = Vec::with_capacity(12);
34953        let mut candidate_ns = Vec::with_capacity(12);
34954        for sample in 0..12 {
34955            let (former_elapsed, candidate_elapsed) = if sample % 2 == 0 {
34956                let started = std::time::Instant::now();
34957                std::hint::black_box(former(std::hint::black_box(&index)));
34958                let former_elapsed = started.elapsed().as_nanos();
34959
34960                let started = std::time::Instant::now();
34961                std::hint::black_box(candidate(std::hint::black_box(&index)));
34962                (former_elapsed, started.elapsed().as_nanos())
34963            } else {
34964                let started = std::time::Instant::now();
34965                std::hint::black_box(candidate(std::hint::black_box(&index)));
34966                let candidate_elapsed = started.elapsed().as_nanos();
34967
34968                let started = std::time::Instant::now();
34969                std::hint::black_box(former(std::hint::black_box(&index)));
34970                (started.elapsed().as_nanos(), candidate_elapsed)
34971            };
34972            former_ns.push(former_elapsed);
34973            candidate_ns.push(candidate_elapsed);
34974        }
34975
34976        former_ns.sort_unstable();
34977        candidate_ns.sort_unstable();
34978        let former_p50 = percentile(&former_ns, 50);
34979        let candidate_p50 = percentile(&candidate_ns, 50);
34980        println!(
34981            "PERIOD_INDEX_ANY former_ns={former_ns:?} candidate_ns={candidate_ns:?} \
34982             former_p50_ns={former_p50} former_p95_ns={} former_p99_ns={} \
34983             candidate_p50_ns={candidate_p50} candidate_p95_ns={} candidate_p99_ns={} \
34984             ratio={:.6}",
34985            percentile(&former_ns, 95),
34986            percentile(&former_ns, 99),
34987            percentile(&candidate_ns, 95),
34988            percentile(&candidate_ns, 99),
34989            former_p50 as f64 / candidate_p50 as f64,
34990        );
34991    }
34992
34993    #[test]
34994    fn index_variants_get_level_values_forward_flat_xf0zn() -> Result<(), super::IndexError> {
34995        const NS: i64 = 1_000_000_000;
34996
34997        let dt = super::DatetimeIndex::new(vec![NS, 2 * NS]).set_name("ts");
34998        assert_eq!(dt.get_level_values(0)?, dt.to_flat_index());
34999
35000        let td = super::TimedeltaIndex::new(vec![5, 10]).set_name("delta");
35001        assert_eq!(td.get_level_values(0)?, td.to_flat_index());
35002
35003        use fp_types::{Period, PeriodFreq};
35004        let pi =
35005            super::PeriodIndex::new(vec![Period::new(1, PeriodFreq::Monthly)]).set_name("period");
35006        assert_eq!(pi.get_level_values(0)?, pi.to_flat_index());
35007
35008        let range = super::RangeIndex::new(1, 4, 1)?.set_name("row");
35009        assert_eq!(range.get_level_values(0)?, range.to_flat_index());
35010
35011        let cat =
35012            super::CategoricalIndex::from_values(vec!["a".to_owned()], false).set_name("category");
35013        assert_eq!(cat.get_level_values(0)?, cat.to_flat_index());
35014
35015        assert!(matches!(
35016            cat.get_level_values(1),
35017            Err(super::IndexError::OutOfBounds {
35018                position: 1,
35019                length: 1
35020            })
35021        ));
35022
35023        Ok(())
35024    }
35025
35026    #[test]
35027    fn range_index_level_ops_handle_flat_contract_directly_ckbyh() -> Result<(), super::IndexError>
35028    {
35029        let range = super::RangeIndex::new(9, 0, -4)?.set_name("row");
35030
35031        let level_values = range.get_level_values(0)?;
35032        assert_eq!(level_values.name().map(|n| n.as_str()), Some("row"));
35033        assert_eq!(
35034            level_values.labels.int64_view().unwrap().as_slice(),
35035            &[9, 5, 1]
35036        );
35037        assert!(
35038            level_values.labels.materialized.get().is_none(),
35039            "RangeIndex::get_level_values should keep typed Int64 output backing"
35040        );
35041
35042        assert!(matches!(
35043            range.get_level_values(2),
35044            Err(super::IndexError::OutOfBounds {
35045                position: 2,
35046                length: 1
35047            })
35048        ));
35049        assert!(matches!(
35050            range.droplevel(0),
35051            Err(super::IndexError::InvalidArgument(message))
35052                if message == "cannot remove the only level from a flat Index"
35053        ));
35054        assert!(matches!(
35055            range.droplevel(2),
35056            Err(super::IndexError::OutOfBounds {
35057                position: 2,
35058                length: 1
35059            })
35060        ));
35061
35062        Ok(())
35063    }
35064
35065    #[test]
35066    fn index_variants_droplevel_forward_flat_errors_t8vpw() -> Result<(), super::IndexError> {
35067        const NS: i64 = 1_000_000_000;
35068
35069        let dt = super::DatetimeIndex::new(vec![NS, 2 * NS]).set_name("ts");
35070        assert!(matches!(
35071            dt.droplevel(0),
35072            Err(super::IndexError::InvalidArgument(message))
35073                if message == "cannot remove the only level from a flat Index"
35074        ));
35075
35076        let td = super::TimedeltaIndex::new(vec![5, 10]).set_name("delta");
35077        assert!(matches!(
35078            td.droplevel(0),
35079            Err(super::IndexError::InvalidArgument(message))
35080                if message == "cannot remove the only level from a flat Index"
35081        ));
35082
35083        use fp_types::{Period, PeriodFreq};
35084        let pi =
35085            super::PeriodIndex::new(vec![Period::new(1, PeriodFreq::Monthly)]).set_name("period");
35086        assert!(matches!(
35087            pi.droplevel(0),
35088            Err(super::IndexError::InvalidArgument(message))
35089                if message == "cannot remove the only level from a flat Index"
35090        ));
35091
35092        let range = super::RangeIndex::new(1, 4, 1)?.set_name("row");
35093        assert!(matches!(
35094            range.droplevel(0),
35095            Err(super::IndexError::InvalidArgument(message))
35096                if message == "cannot remove the only level from a flat Index"
35097        ));
35098
35099        let cat =
35100            super::CategoricalIndex::from_values(vec!["a".to_owned()], false).set_name("category");
35101        assert!(matches!(
35102            cat.droplevel(1),
35103            Err(super::IndexError::OutOfBounds {
35104                position: 1,
35105                length: 1
35106            })
35107        ));
35108
35109        Ok(())
35110    }
35111
35112    #[test]
35113    fn index_variants_groupby_forward_flat_buckets_vypi3() {
35114        const NS: i64 = 1_000_000_000;
35115
35116        let dt = super::DatetimeIndex::new(vec![NS, 2 * NS, NS]);
35117        assert_eq!(dt.groupby(), dt.to_flat_index().groupby());
35118
35119        let td = super::TimedeltaIndex::new(vec![5, 10, 5]);
35120        assert_eq!(td.groupby(), td.to_flat_index().groupby());
35121
35122        use fp_types::{Period, PeriodFreq};
35123        let pi = super::PeriodIndex::new(vec![
35124            Period::new(1, PeriodFreq::Monthly),
35125            Period::new(2, PeriodFreq::Monthly),
35126            Period::new(1, PeriodFreq::Monthly),
35127        ]);
35128        assert_eq!(pi.groupby(), pi.to_flat_index().groupby());
35129
35130        let range = super::RangeIndex::new(2, 8, 2).unwrap();
35131        assert_eq!(range.groupby(), range.to_flat_index().groupby());
35132
35133        let cat = super::CategoricalIndex::from_values(
35134            vec!["a".to_owned(), "b".to_owned(), "a".to_owned()],
35135            false,
35136        );
35137        assert_eq!(cat.groupby(), cat.to_flat_index().groupby());
35138        assert_eq!(
35139            cat.groupby()
35140                .get(&super::IndexLabel::Utf8("a".to_owned()))
35141                .cloned(),
35142            Some(vec![0, 2])
35143        );
35144    }
35145
35146    #[test]
35147    fn index_variants_map_forward_flat_and_preserve_name_vxlfs() {
35148        const NS: i64 = 1_000_000_000;
35149
35150        let dt = super::DatetimeIndex::new(vec![NS, 2 * NS]).set_name("ts");
35151        let dt_mapped = dt.map(|label| match label {
35152            super::IndexLabel::Datetime64(nanos) => super::IndexLabel::Int64(*nanos / NS),
35153            other => other.clone(),
35154        });
35155        assert_eq!(
35156            dt_mapped.labels(),
35157            &[super::IndexLabel::Int64(1), super::IndexLabel::Int64(2)]
35158        );
35159        assert_eq!(dt_mapped.name().map(|n| n.as_str()), Some("ts"));
35160
35161        let td = super::TimedeltaIndex::new(vec![5, 10]).set_name("delta");
35162        assert_eq!(
35163            td.map(|label| match label {
35164                super::IndexLabel::Timedelta64(nanos) => super::IndexLabel::Int64(*nanos * 2),
35165                other => other.clone(),
35166            }),
35167            td.to_flat_index().map(|label| match label {
35168                super::IndexLabel::Timedelta64(nanos) => super::IndexLabel::Int64(*nanos * 2),
35169                other => other.clone(),
35170            })
35171        );
35172
35173        use fp_types::{Period, PeriodFreq};
35174        let pi = super::PeriodIndex::new(vec![Period::new(1, PeriodFreq::Monthly)]);
35175        assert_eq!(
35176            pi.map(|label| super::IndexLabel::Utf8(format!("p:{label}"))),
35177            pi.to_flat_index()
35178                .map(|label| super::IndexLabel::Utf8(format!("p:{label}")))
35179        );
35180
35181        let range = super::RangeIndex::new(1, 4, 1).unwrap();
35182        assert_eq!(
35183            range.map(|label| match label {
35184                super::IndexLabel::Int64(v) => super::IndexLabel::Int64(*v + 10),
35185                other => other.clone(),
35186            }),
35187            range.to_flat_index().map(|label| match label {
35188                super::IndexLabel::Int64(v) => super::IndexLabel::Int64(*v + 10),
35189                other => other.clone(),
35190            })
35191        );
35192
35193        let cat = super::CategoricalIndex::from_values(vec!["a".to_owned()], false);
35194        assert_eq!(
35195            cat.map(|label| super::IndexLabel::Utf8(label.to_string().to_uppercase())),
35196            cat.to_flat_index()
35197                .map(|label| super::IndexLabel::Utf8(label.to_string().to_uppercase()))
35198        );
35199    }
35200
35201    #[test]
35202    fn index_variants_astype_forward_flat_and_preserve_name_o5pyg() {
35203        const NS: i64 = 1_000_000_000;
35204
35205        let dt = super::DatetimeIndex::new(vec![NS, 2 * NS]).set_name("ts");
35206        assert_eq!(
35207            dt.astype("int64").unwrap(),
35208            dt.to_flat_index().astype("int64").unwrap()
35209        );
35210        assert_eq!(
35211            dt.astype("int64").unwrap().name().map(|n| n.as_str()),
35212            Some("ts")
35213        );
35214        assert!(dt.astype("float64").is_err());
35215
35216        let td = super::TimedeltaIndex::new(vec![5, 10]).set_name("delta");
35217        assert_eq!(
35218            td.astype("string").unwrap(),
35219            td.to_flat_index().astype("string").unwrap()
35220        );
35221        assert_eq!(
35222            td.astype("string").unwrap().name().map(|n| n.as_str()),
35223            Some("delta")
35224        );
35225
35226        use fp_types::{Period, PeriodFreq};
35227        let pi = super::PeriodIndex::new(vec![Period::new(1, PeriodFreq::Monthly)]);
35228        assert_eq!(
35229            pi.astype("object").unwrap(),
35230            pi.to_flat_index().astype("object").unwrap()
35231        );
35232
35233        let range = super::RangeIndex::new(1, 4, 1).unwrap().set_name("r");
35234        assert_eq!(
35235            range.astype("str").unwrap(),
35236            range.to_flat_index().astype("str").unwrap()
35237        );
35238        assert_eq!(
35239            range.astype("str").unwrap().name().map(|n| n.as_str()),
35240            Some("r")
35241        );
35242
35243        let cat = super::CategoricalIndex::from_values(vec!["7".to_owned()], false);
35244        assert_eq!(
35245            cat.astype("int").unwrap(),
35246            cat.to_flat_index().astype("int").unwrap()
35247        );
35248        assert!(cat.astype("datetime64[ns]").is_err());
35249    }
35250
35251    #[test]
35252    fn range_index_astype_uses_direct_values_up4dq() {
35253        let range = super::RangeIndex::new(9, 0, -4).unwrap().set_name("r");
35254
35255        let as_int = range.astype("int64").unwrap();
35256        assert_eq!(as_int.name().map(|n| n.as_str()), Some("r"));
35257        assert_eq!(as_int.labels.int64_view().unwrap().as_slice(), &[9, 5, 1]);
35258        assert!(
35259            as_int.labels.materialized.get().is_none(),
35260            "RangeIndex::astype(int64) should keep typed Int64 output backing"
35261        );
35262
35263        let as_string = range.astype("string").unwrap();
35264        assert_eq!(as_string.name().map(|n| n.as_str()), Some("r"));
35265        assert_eq!(
35266            as_string.labels(),
35267            &[
35268                super::IndexLabel::Utf8("9".to_owned()),
35269                super::IndexLabel::Utf8("5".to_owned()),
35270                super::IndexLabel::Utf8("1".to_owned()),
35271            ]
35272        );
35273
35274        assert!(matches!(
35275            range.astype("float64"),
35276            Err(super::IndexError::InvalidArgument(message))
35277                if message == "unsupported Index.astype dtype \"float64\""
35278        ));
35279        assert!(matches!(
35280            range.astype("datetime64[ns]"),
35281            Err(super::IndexError::InvalidArgument(message))
35282                if message == "DatetimeIndex requires homogeneous DatetimeIndex labels"
35283        ));
35284        assert!(matches!(
35285            range.astype("timedelta64[ns]"),
35286            Err(super::IndexError::InvalidArgument(message))
35287                if message == "TimedeltaIndex requires homogeneous TimedeltaIndex labels"
35288        ));
35289
35290        let empty = super::RangeIndex::new(0, 0, 1).unwrap().set_name("empty");
35291        assert_eq!(
35292            empty
35293                .astype("datetime64[ns]")
35294                .unwrap()
35295                .name()
35296                .map(|n| n.as_str()),
35297            Some("empty")
35298        );
35299        assert_eq!(empty.astype("timedelta64[ns]").unwrap().len(), 0);
35300    }
35301
35302    #[test]
35303    fn index_variants_asof_forward_flat_and_mask_locs_955dj() {
35304        const NS: i64 = 1_000_000_000;
35305
35306        let dt = super::DatetimeIndex::new(vec![NS, 3 * NS, 5 * NS]);
35307        let dt_key = super::IndexLabel::Datetime64(4 * NS);
35308        assert_eq!(dt.asof(&dt_key), dt.to_flat_index().asof(&dt_key));
35309        assert_eq!(dt.asof(&super::IndexLabel::Datetime64(0)), None);
35310
35311        let td = super::TimedeltaIndex::new(vec![10, 20, 30]);
35312        let where_td = super::Index::new(vec![
35313            super::IndexLabel::Timedelta64(5),
35314            super::IndexLabel::Timedelta64(20),
35315            super::IndexLabel::Timedelta64(25),
35316        ]);
35317        let mask = [false, true, true];
35318        assert_eq!(
35319            td.asof_locs(&where_td, Some(&mask)),
35320            td.to_flat_index().asof_locs(&where_td, Some(&mask))
35321        );
35322        assert_eq!(
35323            td.asof_locs(&where_td, Some(&mask)),
35324            vec![None, Some(1), Some(1)]
35325        );
35326
35327        use fp_types::{Period, PeriodFreq};
35328        let pi = super::PeriodIndex::new(vec![
35329            Period::new(1, PeriodFreq::Monthly),
35330            Period::new(2, PeriodFreq::Monthly),
35331        ]);
35332        let period_key = pi.to_flat_index().labels()[1].clone();
35333        assert_eq!(pi.asof(&period_key), pi.to_flat_index().asof(&period_key));
35334
35335        let range = super::RangeIndex::new(2, 8, 2).unwrap();
35336        let range_key = super::IndexLabel::Int64(5);
35337        assert_eq!(
35338            range.asof(&range_key),
35339            range.to_flat_index().asof(&range_key)
35340        );
35341
35342        let cat = super::CategoricalIndex::from_values(
35343            vec!["a".to_owned(), "c".to_owned(), "e".to_owned()],
35344            false,
35345        );
35346        let cat_key = super::IndexLabel::Utf8("d".to_owned());
35347        assert_eq!(cat.asof(&cat_key), cat.to_flat_index().asof(&cat_key));
35348    }
35349
35350    #[test]
35351    fn range_index_asof_locs_uses_direct_values_vuftp() {
35352        let range = super::RangeIndex::new(2, 10, 2).unwrap();
35353        let where_index = super::Index::from_i64_values(vec![1, 4, 5, 11]);
35354        assert_eq!(
35355            range.asof_locs(&where_index, None),
35356            range.to_flat_index().asof_locs(&where_index, None)
35357        );
35358        assert_eq!(
35359            range.asof_locs(&where_index, None),
35360            vec![None, Some(1), Some(1), Some(3)]
35361        );
35362
35363        let mask = [true, false, true, true];
35364        assert_eq!(
35365            range.asof_locs(&where_index, Some(&mask)),
35366            range.to_flat_index().asof_locs(&where_index, Some(&mask))
35367        );
35368        assert_eq!(
35369            range.asof_locs(&where_index, Some(&mask)),
35370            vec![None, Some(0), Some(0), Some(3)]
35371        );
35372
35373        let descending = super::RangeIndex::new(9, 0, -4).unwrap();
35374        let descending_where = super::Index::from_i64_values(vec![0, 5, 10]);
35375        assert_eq!(
35376            descending.asof_locs(&descending_where, None),
35377            descending
35378                .to_flat_index()
35379                .asof_locs(&descending_where, None)
35380        );
35381
35382        let mixed_where = super::Index::new(vec![super::IndexLabel::Utf8("z".to_owned())]);
35383        assert_eq!(
35384            range.asof_locs(&mixed_where, Some(&[true, true])),
35385            range
35386                .to_flat_index()
35387                .asof_locs(&mixed_where, Some(&[true, true]))
35388        );
35389    }
35390
35391    #[test]
35392    fn index_variants_drop_join_sortlevel_forward_flat_gr6kj() {
35393        const NS: i64 = 1_000_000_000;
35394
35395        let dt = super::DatetimeIndex::new(vec![NS, 3 * NS, 5 * NS]).set_name("ts");
35396        let drop_dt = [super::IndexLabel::Datetime64(3 * NS)];
35397        assert_eq!(dt.drop(&drop_dt), dt.to_flat_index().drop(&drop_dt));
35398        assert_eq!(dt.drop(&drop_dt).name().map(|n| n.as_str()), Some("ts"));
35399
35400        let td = super::TimedeltaIndex::new(vec![30, 10, 20]);
35401        let (td_sorted, td_order) = td.sortlevel();
35402        let (flat_td_sorted, flat_td_order) = td.to_flat_index().sortlevel();
35403        assert_eq!(td_sorted, flat_td_sorted);
35404        assert_eq!(td_order, flat_td_order);
35405
35406        use fp_types::{Period, PeriodFreq};
35407        let pi = super::PeriodIndex::new(vec![
35408            Period::new(2, PeriodFreq::Monthly),
35409            Period::new(1, PeriodFreq::Monthly),
35410        ]);
35411        assert_eq!(
35412            pi.join(&pi.to_flat_index(), "outer").unwrap(),
35413            pi.to_flat_index()
35414        );
35415
35416        let range = super::RangeIndex::new(2, 8, 2).unwrap();
35417        let other = super::Index::new(vec![
35418            super::IndexLabel::Int64(4),
35419            super::IndexLabel::Int64(6),
35420            super::IndexLabel::Int64(9),
35421        ]);
35422        assert_eq!(
35423            range.join(&other, "inner").unwrap(),
35424            range.to_flat_index().join(&other, "inner").unwrap()
35425        );
35426        assert!(range.join(&other, "sideways").is_err());
35427
35428        let cat = super::CategoricalIndex::from_values(
35429            vec!["b".to_owned(), "a".to_owned(), "b".to_owned()],
35430            false,
35431        );
35432        let (cat_sorted, cat_order) = cat.sortlevel();
35433        let (flat_cat_sorted, flat_cat_order) = cat.to_flat_index().sortlevel();
35434        assert_eq!(cat_sorted, flat_cat_sorted);
35435        assert_eq!(cat_order, flat_cat_order);
35436        let drop_cat = [super::IndexLabel::Utf8("b".to_owned())];
35437        assert_eq!(cat.drop(&drop_cat), cat.to_flat_index().drop(&drop_cat));
35438    }
35439
35440    #[test]
35441    fn index_variants_temporal_rounding_forwarders_dznxu() {
35442        let hour = fp_types::Timedelta::NANOS_PER_HOUR;
35443        let minute = fp_types::Timedelta::NANOS_PER_MIN;
35444        let nat = fp_types::Timedelta::NAT;
35445        let dt =
35446            super::DatetimeIndex::new(vec![hour / 2, hour + 31 * minute, i64::MIN]).set_name("ts");
35447
35448        let dt_floor = dt.floor("h").unwrap();
35449        assert_eq!(dt_floor.asi8(), vec![0, hour, i64::MIN]);
35450        assert_eq!(dt_floor.name().map(|n| n.as_str()), Some("ts"));
35451
35452        let dt_ceil = dt.ceil("h").unwrap();
35453        assert_eq!(dt_ceil.asi8(), vec![hour, 2 * hour, i64::MIN]);
35454
35455        let dt_round = dt.round("h").unwrap();
35456        assert_eq!(dt_round.asi8(), vec![0, 2 * hour, i64::MIN]);
35457
35458        let dt_snap = dt.snap("h").unwrap();
35459        assert_eq!(dt_snap.asi8(), dt.asi8());
35460        assert!(dt.floor("not-a-frequency").is_err());
35461        assert!(dt.snap("not-a-frequency").is_err());
35462
35463        let td = super::TimedeltaIndex::new(vec![hour / 2, hour + 31 * minute, nat]).set_name("d");
35464        assert_eq!(td.floor("h").unwrap().asi8(), vec![0, hour, nat]);
35465        assert_eq!(td.ceil("h").unwrap().asi8(), vec![hour, 2 * hour, nat]);
35466        assert_eq!(td.round("h").unwrap().asi8(), vec![0, 2 * hour, nat]);
35467        assert_eq!(td.round("h").unwrap().name().map(|n| n.as_str()), Some("d"));
35468        assert!(td.ceil("not-a-frequency").is_err());
35469
35470        use fp_types::{Period, PeriodFreq};
35471        let periods = super::PeriodIndex::new(vec![
35472            Period::new(10, PeriodFreq::Monthly),
35473            Period::new(11, PeriodFreq::Monthly),
35474        ])
35475        .set_name("p");
35476        let rounded_periods = periods.round("not-a-frequency");
35477        assert_eq!(rounded_periods.values(), periods.values());
35478        assert_eq!(rounded_periods.name().map(|n| n.as_str()), Some("p"));
35479    }
35480
35481    #[test]
35482    fn index_variants_diff_forwarders_lqs0a() {
35483        let day = fp_types::Timedelta::NANOS_PER_DAY;
35484        let nat = fp_types::Timedelta::NAT;
35485
35486        let dt = super::DatetimeIndex::new(vec![day, 3 * day, i64::MIN, 10 * day]).set_name("ts");
35487        assert_eq!(dt.diff(1).asi8(), vec![nat, 2 * day, nat, nat]);
35488        assert_eq!(dt.diff(-1).asi8(), vec![-2 * day, nat, nat, nat]);
35489        assert_eq!(dt.diff(0).asi8(), vec![0, 0, nat, 0]);
35490        assert_eq!(dt.diff(1).name().map(|n| n.as_str()), Some("ts"));
35491
35492        let td = super::TimedeltaIndex::new(vec![day, 4 * day, nat, 9 * day]).set_name("delta");
35493        assert_eq!(td.diff(2).asi8(), vec![nat, nat, nat, 5 * day]);
35494        assert_eq!(td.diff(-1).asi8(), vec![-3 * day, nat, nat, nat]);
35495        assert_eq!(td.diff(0).asi8(), vec![0, 0, nat, 0]);
35496        assert_eq!(td.diff(1).name().map(|n| n.as_str()), Some("delta"));
35497
35498        use fp_types::{Period, PeriodFreq};
35499        let periods = super::PeriodIndex::new(vec![
35500            Period::new(10, PeriodFreq::Monthly),
35501            Period::new(12, PeriodFreq::Monthly),
35502            Period::new(13, PeriodFreq::QUARTERLY),
35503            Period::new(15, PeriodFreq::QUARTERLY),
35504        ]);
35505        assert_eq!(periods.diff(1), vec![None, Some(2), None, Some(2)]);
35506        assert_eq!(periods.diff(-1), vec![Some(-2), None, Some(-2), None]);
35507        assert_eq!(periods.diff(0), vec![Some(0), Some(0), Some(0), Some(0)]);
35508
35509        let range = super::RangeIndex::new(2, 10, 2).unwrap().set_name("r");
35510        assert_eq!(range.diff(1), vec![None, Some(2), Some(2), Some(2)]);
35511        assert_eq!(range.diff(-2), vec![Some(-4), Some(-4), None, None]);
35512        assert_eq!(range.diff(0), vec![Some(0), Some(0), Some(0), Some(0)]);
35513        assert_eq!(range.name().map(|n| n.as_str()), Some("r"));
35514
35515        let descending = super::RangeIndex::new(9, 0, -3).unwrap();
35516        assert_eq!(descending.diff(1), vec![None, Some(-3), Some(-3)]);
35517        assert_eq!(descending.diff(-1), vec![Some(3), Some(3), None]);
35518
35519        let wide = super::RangeIndex::new(i64::MIN, i64::MAX, i64::MAX).unwrap();
35520        assert_eq!(wide.diff(1), vec![None, Some(i64::MAX), Some(i64::MAX)]);
35521        assert_eq!(wide.diff(-1), vec![Some(-i64::MAX), Some(-i64::MAX), None]);
35522        assert_eq!(wide.diff(2), vec![None, None, None]);
35523        assert_eq!(wide.diff(-2), vec![None, None, None]);
35524
35525        let cat = super::CategoricalIndex::from_values(vec!["a".to_owned(), "b".to_owned()], false);
35526        let err = cat.diff(1).unwrap_err();
35527        assert!(matches!(
35528            err,
35529            super::IndexError::InvalidArgument(message)
35530                if message.contains("Categorical has no 'diff' method")
35531        ));
35532    }
35533
35534    #[test]
35535    fn datetime_index_to_period_matches_pandas_ordinals_002sq()
35536    -> Result<(), Box<dyn std::error::Error>> {
35537        fn ns(value: &str) -> Result<i64, super::DateRangeError> {
35538            super::parse_datetime_to_nanos(value)
35539        }
35540
35541        use fp_types::{Period, PeriodFreq};
35542
35543        let dt = super::DatetimeIndex::new(vec![
35544            ns("1969-12-31 23:59:59")?,
35545            ns("1970-01-01 00:00:00")?,
35546            ns("2024-02-29 12:34:56")?,
35547        ])
35548        .set_name("ts");
35549
35550        assert_eq!(
35551            dt.to_period("Y")?.values(),
35552            &[
35553                Period::new(-1, PeriodFreq::ANNUAL),
35554                Period::new(0, PeriodFreq::ANNUAL),
35555                Period::new(54, PeriodFreq::ANNUAL),
35556            ]
35557        );
35558        assert_eq!(
35559            dt.to_period("Q")?.values(),
35560            &[
35561                Period::new(-1, PeriodFreq::QUARTERLY),
35562                Period::new(0, PeriodFreq::QUARTERLY),
35563                Period::new(216, PeriodFreq::QUARTERLY),
35564            ]
35565        );
35566        assert_eq!(
35567            dt.to_period("M")?.values(),
35568            &[
35569                Period::new(-1, PeriodFreq::Monthly),
35570                Period::new(0, PeriodFreq::Monthly),
35571                Period::new(649, PeriodFreq::Monthly),
35572            ]
35573        );
35574        assert_eq!(
35575            dt.to_period("D")?.values(),
35576            &[
35577                Period::new(-1, PeriodFreq::Daily),
35578                Period::new(0, PeriodFreq::Daily),
35579                Period::new(19_782, PeriodFreq::Daily),
35580            ]
35581        );
35582        assert_eq!(
35583            dt.to_period("W")?.values(),
35584            &[
35585                Period::new(1, PeriodFreq::WEEKLY),
35586                Period::new(1, PeriodFreq::WEEKLY),
35587                Period::new(2_827, PeriodFreq::WEEKLY),
35588            ]
35589        );
35590        assert_eq!(
35591            dt.to_period("B")?.values(),
35592            &[
35593                Period::new(-1, PeriodFreq::Business),
35594                Period::new(0, PeriodFreq::Business),
35595                Period::new(14_130, PeriodFreq::Business),
35596            ]
35597        );
35598        assert_eq!(
35599            dt.to_period("H")?.values(),
35600            &[
35601                Period::new(-1, PeriodFreq::Hourly),
35602                Period::new(0, PeriodFreq::Hourly),
35603                Period::new(474_780, PeriodFreq::Hourly),
35604            ]
35605        );
35606        let minutely = dt.to_period("min")?;
35607        assert_eq!(
35608            minutely.values(),
35609            &[
35610                Period::new(-1, PeriodFreq::Minutely),
35611                Period::new(0, PeriodFreq::Minutely),
35612                Period::new(28_486_834, PeriodFreq::Minutely),
35613            ]
35614        );
35615        assert_eq!(minutely.name().map(|n| n.as_str()), Some("ts"));
35616        assert_eq!(
35617            dt.to_period("S")?.values(),
35618            &[
35619                Period::new(-1, PeriodFreq::Secondly),
35620                Period::new(0, PeriodFreq::Secondly),
35621                Period::new(1_709_210_096, PeriodFreq::Secondly),
35622            ]
35623        );
35624
35625        assert!(matches!(
35626            super::DatetimeIndex::new(vec![i64::MIN]).to_period("M"),
35627            Err(super::IndexError::InvalidArgument(message))
35628                if message.contains("invalid or NaT datetime nanos")
35629        ));
35630        assert!(matches!(
35631            dt.to_period("fortnight"),
35632            Err(super::IndexError::InvalidArgument(message))
35633                if message.contains("unsupported frequency")
35634        ));
35635
35636        Ok(())
35637    }
35638
35639    /// The RENDERED labels for the same three timestamps the ordinal test above
35640    /// checks — the half that was missing, and the half that was wrong.
35641    ///
35642    /// ⚠️ CORRECT ORDINALS DO NOT IMPLY CORRECT LABELS. That test verified
35643    /// `to_period("W")` produces ordinals 1, 1, 2827 and `to_period("B")`
35644    /// produces -1, 0, 14130, all of which agree with pandas — and every one of
35645    /// them then rendered decades wrong, because those two ordinals are a WEEK
35646    /// COUNT and a BUSINESS-DAY COUNT rather than day indices (fixed in
35647    /// 08363d42f). Checking only the ordinal is what let it through.
35648    ///
35649    /// This is also the path that makes the frequencies reachable at all:
35650    /// `PeriodIndex::format` matches `pd.PeriodIndex.format()`, and `to_index`,
35651    /// `to_flat_index` and the `.str` accessor all render through the same
35652    /// `Display`. Every string below is transcribed from live pandas 2.2.3.
35653    #[test]
35654    fn period_index_labels_match_pandas_not_just_the_ordinals()
35655    -> Result<(), Box<dyn std::error::Error>> {
35656        fn ns(value: &str) -> Result<i64, super::DateRangeError> {
35657            super::parse_datetime_to_nanos(value)
35658        }
35659
35660        let dt = super::DatetimeIndex::new(vec![
35661            ns("1969-12-31 23:59:59")?,
35662            ns("1970-01-01 00:00:00")?,
35663            ns("2024-02-29 12:34:56")?,
35664        ]);
35665
35666        // WEEKLY IS A RANGE. The first two timestamps straddle the epoch and
35667        // land in the SAME week, which is why they render identically.
35668        assert_eq!(
35669            dt.to_period("W")?.format(),
35670            vec![
35671                "1969-12-29/1970-01-04".to_owned(),
35672                "1969-12-29/1970-01-04".to_owned(),
35673                "2024-02-26/2024-03-03".to_owned(),
35674            ]
35675        );
35676
35677        // BUSINESS is a single date, but off a five-per-week axis.
35678        assert_eq!(
35679            dt.to_period("B")?.format(),
35680            vec![
35681                "1969-12-31".to_owned(),
35682                "1970-01-01".to_owned(),
35683                "2024-02-29".to_owned(),
35684            ]
35685        );
35686
35687        // The frequencies whose ordinal IS a count of its own unit were always
35688        // right; pinned here so the two groups are compared side by side.
35689        assert_eq!(
35690            dt.to_period("D")?.format(),
35691            vec![
35692                "1969-12-31".to_owned(),
35693                "1970-01-01".to_owned(),
35694                "2024-02-29".to_owned(),
35695            ]
35696        );
35697        assert_eq!(
35698            dt.to_period("M")?.format(),
35699            vec![
35700                "1969-12".to_owned(),
35701                "1970-01".to_owned(),
35702                "2024-02".to_owned(),
35703            ]
35704        );
35705
35706        // to_index / to_flat_index labels render through the same Display,
35707        // so the weekly range has to survive the trip into a flat Index too.
35708        // TEST-CHANGE (45fzr): the flat labels are periods (they were Utf8
35709        // text); their text is compared.
35710        assert_eq!(
35711            dt.to_period("W")?
35712                .to_flat_index()
35713                .labels()
35714                .iter()
35715                .map(ToString::to_string)
35716                .collect::<Vec<_>>(),
35717            vec![
35718                "1969-12-29/1970-01-04".to_owned(),
35719                "1969-12-29/1970-01-04".to_owned(),
35720                "2024-02-26/2024-03-03".to_owned(),
35721            ]
35722        );
35723
35724        Ok(())
35725    }
35726
35727    #[test]
35728    fn period_index_asfreq_boundary_conversion_h1zia() -> Result<(), super::IndexError> {
35729        use fp_types::{Period, PeriodFreq};
35730
35731        let annual = super::PeriodIndex::new(vec![
35732            Period::new(0, PeriodFreq::ANNUAL),
35733            Period::new(1, PeriodFreq::ANNUAL),
35734        ])
35735        .set_name("p");
35736        assert_eq!(
35737            annual.asfreq("M")?.values(),
35738            &[
35739                Period::new(11, PeriodFreq::Monthly),
35740                Period::new(23, PeriodFreq::Monthly),
35741            ]
35742        );
35743        let annual_start = annual.asfreq_with_how("M", "start")?;
35744        assert_eq!(
35745            annual_start.values(),
35746            &[
35747                Period::new(0, PeriodFreq::Monthly),
35748                Period::new(12, PeriodFreq::Monthly),
35749            ]
35750        );
35751        assert_eq!(annual_start.name().map(|n| n.as_str()), Some("p"));
35752
35753        let quarterly = super::PeriodIndex::new(vec![
35754            Period::new(0, PeriodFreq::QUARTERLY),
35755            Period::new(1, PeriodFreq::QUARTERLY),
35756        ]);
35757        assert_eq!(
35758            quarterly.asfreq("D")?.values(),
35759            &[
35760                Period::new(89, PeriodFreq::Daily),
35761                Period::new(180, PeriodFreq::Daily),
35762            ]
35763        );
35764        assert_eq!(
35765            quarterly.asfreq_with_how("D", "s")?.values(),
35766            &[
35767                Period::new(0, PeriodFreq::Daily),
35768                Period::new(90, PeriodFreq::Daily),
35769            ]
35770        );
35771
35772        let monthly = super::PeriodIndex::new(vec![
35773            Period::new(0, PeriodFreq::Monthly),
35774            Period::new(1, PeriodFreq::Monthly),
35775        ]);
35776        assert_eq!(
35777            monthly.asfreq("S")?.values(),
35778            &[
35779                Period::new(2_678_399, PeriodFreq::Secondly),
35780                Period::new(5_097_599, PeriodFreq::Secondly),
35781            ]
35782        );
35783        assert_eq!(
35784            monthly.asfreq_with_how("S", "begin")?.values(),
35785            &[
35786                Period::new(0, PeriodFreq::Secondly),
35787                Period::new(2_678_400, PeriodFreq::Secondly),
35788            ]
35789        );
35790        assert_eq!(
35791            monthly.asfreq("B")?.values(),
35792            &[
35793                Period::new(21, PeriodFreq::Business),
35794                Period::new(41, PeriodFreq::Business),
35795            ]
35796        );
35797        assert_eq!(
35798            monthly.asfreq_with_how("W", "start")?.values(),
35799            &[
35800                Period::new(1, PeriodFreq::WEEKLY),
35801                Period::new(5, PeriodFreq::WEEKLY),
35802            ]
35803        );
35804        assert!(matches!(
35805            monthly.asfreq_with_how("D", "middle"),
35806            Err(super::IndexError::InvalidArgument(message))
35807                if message.contains("asfreq how must be 'start' or 'end'")
35808        ));
35809        assert!(matches!(
35810            monthly.asfreq("fortnight"),
35811            Err(super::IndexError::InvalidArgument(message))
35812                if message.contains("unsupported frequency")
35813        ));
35814
35815        Ok(())
35816    }
35817
35818    /// asfreq across the sub-second frequencies, in BOTH directions.
35819    ///
35820    /// `asfreq_with_how` never enumerates frequencies itself -- it takes the
35821    /// period's boundary instant and asks which target period contains it. That
35822    /// means ms/us/ns came for free with the ordinal arms, and this test is what
35823    /// proves "for free" was not "untested": every ordinal below is transcribed
35824    /// from live pandas 2.2.3, `Timestamp(base).to_period(src).asfreq(dst, how)`.
35825    ///
35826    /// The sweep behind it covered all 10x10 frequency pairs x 2 boundaries x 4
35827    /// base timestamps -- 800 cases, 0 mismatches -- so the rows kept here are
35828    /// the ones that would move first if the model were wrong: a coarse period
35829    /// widening into ns (where the multiply is largest), a ns period collapsing
35830    /// back, and the pre-epoch cases where a truncating divide would differ from
35831    /// a floor.
35832    #[test]
35833    fn period_index_asfreq_subsecond_both_directions() -> Result<(), super::IndexError> {
35834        use fp_types::{Period, PeriodFreq};
35835
35836        // 2024-03-15, one whole day, widened to nanoseconds. End is the LAST
35837        // nanosecond of the day, not the first of the next.
35838        let daily = super::PeriodIndex::new(vec![Period::new(19_797, PeriodFreq::Daily)]);
35839        assert_eq!(
35840            daily.asfreq_with_how("ns", "start")?.values(),
35841            &[Period::new(
35842                1_710_460_800_000_000_000,
35843                PeriodFreq::Nanoseconds
35844            )]
35845        );
35846        assert_eq!(
35847            daily.asfreq_with_how("ns", "end")?.values(),
35848            &[Period::new(
35849                1_710_547_199_999_999_999,
35850                PeriodFreq::Nanoseconds
35851            )]
35852        );
35853        // ...and the same day widened to milliseconds from the epoch.
35854        let epoch_day = super::PeriodIndex::new(vec![Period::new(0, PeriodFreq::Daily)]);
35855        assert_eq!(
35856            epoch_day.asfreq_with_how("ms", "start")?.values(),
35857            &[Period::new(0, PeriodFreq::Milliseconds)]
35858        );
35859        assert_eq!(
35860            epoch_day.asfreq_with_how("ms", "end")?.values(),
35861            &[Period::new(86_399_999, PeriodFreq::Milliseconds)]
35862        );
35863
35864        // Nanoseconds collapsing back: a 1ns period has start == end, so both
35865        // boundaries land on the same coarser period.
35866        let nanos = super::PeriodIndex::new(vec![Period::new(
35867            1_710_498_645_123_456_789,
35868            PeriodFreq::Nanoseconds,
35869        )]);
35870        assert_eq!(
35871            nanos.asfreq_with_how("D", "start")?.values(),
35872            &[Period::new(19_797, PeriodFreq::Daily)]
35873        );
35874        assert_eq!(
35875            nanos.asfreq_with_how("D", "end")?.values(),
35876            &[Period::new(19_797, PeriodFreq::Daily)]
35877        );
35878        assert_eq!(
35879            nanos.asfreq_with_how("ms", "start")?.values(),
35880            &[Period::new(1_710_498_645_123, PeriodFreq::Milliseconds)]
35881        );
35882
35883        // One step between adjacent sub-second units, each way.
35884        let millis = super::PeriodIndex::new(vec![Period::new(
35885            1_710_498_645_123,
35886            PeriodFreq::Milliseconds,
35887        )]);
35888        assert_eq!(
35889            millis.asfreq_with_how("ns", "start")?.values(),
35890            &[Period::new(
35891                1_710_498_645_123_000_000,
35892                PeriodFreq::Nanoseconds
35893            )]
35894        );
35895        assert_eq!(
35896            millis.asfreq_with_how("ns", "end")?.values(),
35897            &[Period::new(
35898                1_710_498_645_123_999_999,
35899                PeriodFreq::Nanoseconds
35900            )]
35901        );
35902        let secondly =
35903            super::PeriodIndex::new(vec![Period::new(1_710_498_645, PeriodFreq::Secondly)]);
35904        assert_eq!(
35905            secondly.asfreq_with_how("us", "start")?.values(),
35906            &[Period::new(1_710_498_645_000_000, PeriodFreq::Microseconds)]
35907        );
35908        assert_eq!(
35909            secondly.asfreq_with_how("us", "end")?.values(),
35910            &[Period::new(1_710_498_645_999_999, PeriodFreq::Microseconds)]
35911        );
35912
35913        // ⚠️ PRE-EPOCH, where a truncating divide would disagree with the floor.
35914        // 1969-12-31 23:59:59.999000001 is ns ordinal -999999, and the ms period
35915        // containing it is -1 (NOT 0).
35916        let pre_epoch =
35917            super::PeriodIndex::new(vec![Period::new(-999_999, PeriodFreq::Nanoseconds)]);
35918        assert_eq!(
35919            pre_epoch.asfreq_with_how("ms", "start")?.values(),
35920            &[Period::new(-1, PeriodFreq::Milliseconds)]
35921        );
35922        assert_eq!(
35923            pre_epoch.asfreq_with_how("ms", "end")?.values(),
35924            &[Period::new(-1, PeriodFreq::Milliseconds)]
35925        );
35926        // ...and back out: ms period -1 spans ns ordinals -1_000_000 ..= -1.
35927        let pre_epoch_ms = super::PeriodIndex::new(vec![Period::new(-1, PeriodFreq::Milliseconds)]);
35928        assert_eq!(
35929            pre_epoch_ms.asfreq_with_how("ns", "start")?.values(),
35930            &[Period::new(-1_000_000, PeriodFreq::Nanoseconds)]
35931        );
35932        assert_eq!(
35933            pre_epoch_ms.asfreq_with_how("ns", "end")?.values(),
35934            &[Period::new(-1, PeriodFreq::Nanoseconds)]
35935        );
35936
35937        Ok(())
35938    }
35939
35940    #[test]
35941    fn period_index_timestamp_boundaries_d44wh() -> Result<(), Box<dyn std::error::Error>> {
35942        fn ns(value: &str) -> Result<i64, super::DateRangeError> {
35943            super::parse_datetime_to_nanos(value)
35944        }
35945
35946        use fp_types::{Period, PeriodFreq};
35947
35948        let monthly = super::PeriodIndex::new(vec![
35949            Period::new(0, PeriodFreq::Monthly),
35950            Period::new(1, PeriodFreq::Monthly),
35951        ])
35952        .set_name("period");
35953        assert_eq!(
35954            monthly.start_time()?.asi8(),
35955            vec![ns("1970-01-01 00:00:00")?, ns("1970-02-01 00:00:00")?]
35956        );
35957        assert_eq!(
35958            monthly.end_time()?.asi8(),
35959            vec![
35960                ns("1970-02-01 00:00:00")? - 1,
35961                ns("1970-03-01 00:00:00")? - 1
35962            ]
35963        );
35964        assert_eq!(
35965            monthly.to_timestamp("start")?.asi8(),
35966            monthly.start_time()?.asi8()
35967        );
35968        assert_eq!(
35969            monthly.to_timestamp("end")?.asi8(),
35970            monthly.end_time()?.asi8()
35971        );
35972        assert_eq!(
35973            monthly.to_timestamp("")?.name().map(|n| n.as_str()),
35974            Some("period")
35975        );
35976        assert_eq!(monthly.qyear()?, vec![1970, 1970]);
35977        assert!(matches!(
35978            monthly.to_timestamp("middle"),
35979            Err(super::IndexError::InvalidArgument(message))
35980                if message.contains("to_timestamp how must be 'start' or 'end'")
35981        ));
35982
35983        let quarterly = super::PeriodIndex::new(vec![
35984            Period::new(-1, PeriodFreq::QUARTERLY),
35985            Period::new(0, PeriodFreq::QUARTERLY),
35986        ]);
35987        assert_eq!(
35988            quarterly.start_time()?.asi8(),
35989            vec![ns("1969-10-01 00:00:00")?, ns("1970-01-01 00:00:00")?]
35990        );
35991        assert_eq!(
35992            quarterly.end_time()?.asi8(),
35993            vec![
35994                ns("1970-01-01 00:00:00")? - 1,
35995                ns("1970-04-01 00:00:00")? - 1
35996            ]
35997        );
35998        assert_eq!(quarterly.qyear()?, vec![1969, 1970]);
35999
36000        let mixed_freq = super::PeriodIndex::new(vec![
36001            Period::new(1, PeriodFreq::WEEKLY),
36002            Period::new(2, PeriodFreq::Business),
36003            Period::new(1, PeriodFreq::Hourly),
36004        ]);
36005        assert_eq!(
36006            mixed_freq.start_time()?.asi8(),
36007            vec![
36008                ns("1969-12-29 00:00:00")?,
36009                ns("1970-01-05 00:00:00")?,
36010                fp_types::Timedelta::NANOS_PER_HOUR
36011            ]
36012        );
36013        assert_eq!(
36014            mixed_freq.end_time()?.asi8(),
36015            vec![
36016                ns("1970-01-05 00:00:00")? - 1,
36017                ns("1970-01-06 00:00:00")? - 1,
36018                2 * fp_types::Timedelta::NANOS_PER_HOUR - 1
36019            ]
36020        );
36021        assert_eq!(mixed_freq.qyear()?, vec![1970, 1970, 1970]);
36022
36023        Ok(())
36024    }
36025
36026    #[test]
36027    fn index_variants_view_transpose_ravel_nlevels_infer_objects_match_pandas_d0ph1() {
36028        const NS: i64 = 1_000_000_000;
36029        let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS, i64::MIN]).set_name("ts");
36030        assert!(dt.view().equals(&dt));
36031        assert!(dt.transpose().equals(&dt));
36032        assert!(dt.T().identical(&dt));
36033        assert_eq!(dt.ravel(), dt.values());
36034        assert_eq!(dt.nlevels(), 1);
36035        assert!(dt.infer_objects().equals(&dt));
36036
36037        let td = super::TimedeltaIndex::new(vec![100_i64, fp_types::Timedelta::NAT]).set_name("d");
36038        assert!(td.view().equals(&td));
36039        assert!(td.T().identical(&td));
36040        assert_eq!(td.ravel(), td.values());
36041        assert_eq!(td.nlevels(), 1);
36042
36043        use fp_types::{Period, PeriodFreq};
36044        let pi = super::PeriodIndex::new(vec![
36045            Period::new(10, PeriodFreq::Monthly),
36046            Period::new(11, PeriodFreq::Monthly),
36047        ]);
36048        assert_eq!(pi.view().values(), pi.values());
36049        assert!(pi.T().identical(&pi));
36050        assert_eq!(pi.ravel(), pi.values().to_vec());
36051        assert_eq!(pi.nlevels(), 1);
36052
36053        let r = super::RangeIndex::new(0, 5, 1).unwrap();
36054        assert!(r.view().equals(&r));
36055        assert!(r.T().identical(&r));
36056        assert_eq!(r.ravel(), r.values().to_vec());
36057        assert_eq!(r.nlevels(), 1);
36058
36059        let cat = super::CategoricalIndex::from_values(vec!["a".to_owned(), "b".to_owned()], false);
36060        assert_eq!(cat.view().labels(), cat.labels());
36061        assert!(cat.T().identical(&cat));
36062        assert_eq!(cat.ravel(), cat.labels().to_vec());
36063        assert_eq!(cat.nlevels(), 1);
36064    }
36065
36066    #[test]
36067    fn datetime_index_set_ops_match_pandas_ik8if() {
36068        const NS: i64 = 1_000_000_000;
36069        let a = 1_704_067_200_i64 * NS;
36070        let b = 1_705_276_800_i64 * NS;
36071        let c = 1_706_140_800_i64 * NS;
36072        let d = 1_707_350_400_i64 * NS;
36073        let left = super::DatetimeIndex::new(vec![a, b, c]).set_name("ts");
36074        let right = super::DatetimeIndex::new(vec![b, c, d]).set_name("ts");
36075
36076        // intersection: b, c (in self order).
36077        let inter = left.intersection(&right);
36078        assert_eq!(inter.values(), vec![Some(b), Some(c)]);
36079        assert_eq!(inter.name().map(|n| n.as_str()), Some("ts"));
36080
36081        // union: a, b, c then d.
36082        let union = left.union(&right);
36083        assert_eq!(union.values(), vec![Some(a), Some(b), Some(c), Some(d)]);
36084
36085        // difference: a (only in self).
36086        let diff = left.difference(&right);
36087        assert_eq!(diff.values(), vec![Some(a)]);
36088
36089        // symmetric_difference: a (self-only) then d (other-only).
36090        let sym = left.symmetric_difference(&right);
36091        assert_eq!(sym.values(), vec![Some(a), Some(d)]);
36092
36093        // Mismatched names drop the name.
36094        let mismatched = super::DatetimeIndex::new(vec![b]).set_name("other");
36095        assert_eq!(left.intersection(&mismatched).name(), None);
36096        assert_eq!(left.union(&mismatched).name(), None);
36097    }
36098
36099    #[test]
36100    fn timedelta_index_set_ops_match_pandas_ik8if() {
36101        let left = super::TimedeltaIndex::new(vec![100_i64, 200, 300]).set_name("d");
36102        let right = super::TimedeltaIndex::new(vec![200_i64, 300, 400]).set_name("d");
36103
36104        let inter = left.intersection(&right);
36105        assert_eq!(inter.values(), vec![Some(200), Some(300)]);
36106        assert_eq!(inter.name().map(|n| n.as_str()), Some("d"));
36107
36108        let union = left.union(&right);
36109        assert_eq!(
36110            union.values(),
36111            vec![Some(100), Some(200), Some(300), Some(400)]
36112        );
36113
36114        let diff = left.difference(&right);
36115        assert_eq!(diff.values(), vec![Some(100)]);
36116
36117        let sym = left.symmetric_difference(&right);
36118        assert_eq!(sym.values(), vec![Some(100), Some(400)]);
36119    }
36120
36121    #[test]
36122    fn timedelta_index_sum_match_pandas_qi04e() {
36123        let nat = fp_types::Timedelta::NAT;
36124        let td = super::TimedeltaIndex::new(vec![10_i64, 20, 30, nat]);
36125        assert_eq!(td.sum(), Some(60));
36126
36127        let only_nat = super::TimedeltaIndex::new(vec![nat, nat]);
36128        assert_eq!(only_nat.sum(), Some(0));
36129
36130        let empty = super::TimedeltaIndex::new(vec![]);
36131        assert_eq!(empty.sum(), Some(0));
36132    }
36133
36134    #[test]
36135    fn datetime_timedelta_var_match_pandas_pw5sn() {
36136        // [10, 20, 30] sample variance with ddof=1: ((100 + 0 + 100)/2) = 100.
36137        let td = super::TimedeltaIndex::new(vec![10_i64, 20, 30]);
36138        assert!((td.var().unwrap() - 100.0).abs() < 1e-9);
36139
36140        // Single element: not enough data.
36141        let one = super::TimedeltaIndex::new(vec![5_i64]);
36142        assert_eq!(one.var(), None);
36143
36144        // DatetimeIndex spot check.
36145        const NS: i64 = 1_000_000_000;
36146        let dt = super::DatetimeIndex::new(vec![10 * NS, 20 * NS, 30 * NS]);
36147        assert!(dt.var().is_some());
36148    }
36149
36150    #[test]
36151    fn datetime_timedelta_std_match_pandas_3hb3t() {
36152        // [10, 20, 30] sample std with ddof=1: sqrt((100 + 0 + 100) / 2) = 10.
36153        let td = super::TimedeltaIndex::new(vec![10_i64, 20, 30]);
36154        assert_eq!(td.std(), Some(10));
36155
36156        // [10, 30] sample std: sqrt(((10-20)^2 + (30-20)^2) / 1) = sqrt(200).
36157        let td2 = super::TimedeltaIndex::new(vec![10_i64, 30]);
36158        let expected = 200f64.sqrt() as i64;
36159        assert_eq!(td2.std(), Some(expected));
36160
36161        // Single element / NAT-only: not enough data.
36162        let one = super::TimedeltaIndex::new(vec![5_i64]);
36163        assert_eq!(one.std(), None);
36164        let nat = super::TimedeltaIndex::new(vec![fp_types::Timedelta::NAT]);
36165        assert_eq!(nat.std(), None);
36166
36167        // DatetimeIndex spot check.
36168        const NS: i64 = 1_000_000_000;
36169        let dt = super::DatetimeIndex::new(vec![10 * NS, 20 * NS, 30 * NS]);
36170        assert!(dt.std().is_some());
36171    }
36172
36173    #[test]
36174    fn datetime_timedelta_shift_match_pandas_1y3sx() {
36175        const NS: i64 = 1_000_000_000;
36176        let day_ns = 86_400 * NS;
36177        let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS, i64::MIN]).set_name("ts");
36178
36179        // Shift by 2 days.
36180        let shifted = dt.shift(2, day_ns);
36181        assert_eq!(
36182            shifted.values()[0],
36183            Some(1_704_067_200_i64 * NS + 2 * day_ns)
36184        );
36185        assert_eq!(shifted.values()[1], None);
36186        assert_eq!(shifted.name().map(|n| n.as_str()), Some("ts"));
36187
36188        // Negative shift.
36189        let back = dt.shift(-1, day_ns);
36190        assert_eq!(back.values()[0], Some(1_704_067_200_i64 * NS - day_ns));
36191
36192        // TimedeltaIndex spot check.
36193        let td = super::TimedeltaIndex::new(vec![100_i64, fp_types::Timedelta::NAT]);
36194        let shifted_td = td.shift(3, 50);
36195        assert_eq!(shifted_td.values()[0], Some(250));
36196        assert_eq!(shifted_td.values()[1], None);
36197    }
36198
36199    #[test]
36200    fn datetime_timedelta_mean_median_match_pandas_wp0gr() {
36201        const NS: i64 = 1_000_000_000;
36202        let a = 1_000_000_000_i64 * NS;
36203        let b = 2_000_000_000_i64 * NS;
36204        let c = 3_000_000_000_i64 * NS;
36205        let dt = super::DatetimeIndex::new(vec![a, b, c, i64::MIN]);
36206        // Mean: (a + b + c) / 3 = b (the middle, since arithmetic).
36207        assert_eq!(dt.mean(), Some(b));
36208        // Median: middle of three sorted values = b.
36209        assert_eq!(dt.median(), Some(b));
36210
36211        // Even-length set: median is average of two middles.
36212        let dt_even = super::DatetimeIndex::new(vec![a, b]);
36213        let total = i128::from(a) + i128::from(b);
36214        let expected = i64::try_from(total / 2).unwrap();
36215        assert_eq!(dt_even.median(), Some(expected));
36216
36217        // All-NAT.
36218        let nat = super::DatetimeIndex::new(vec![i64::MIN; 3]);
36219        assert_eq!(nat.mean(), None);
36220        assert_eq!(nat.median(), None);
36221
36222        // Timedelta spot check.
36223        let td = super::TimedeltaIndex::new(vec![10_i64, 20, 30]);
36224        assert_eq!(td.mean(), Some(20));
36225        assert_eq!(td.median(), Some(20));
36226    }
36227
36228    #[test]
36229    fn datetime_index_min_max_sort_values_match_pandas_kastf() {
36230        const NS: i64 = 1_000_000_000;
36231        let a = 1_704_067_200_i64 * NS;
36232        let b = 1_705_276_800_i64 * NS;
36233        let c = 1_706_140_800_i64 * NS;
36234        let dt = super::DatetimeIndex::new(vec![b, c, i64::MIN, a]).set_name("ts");
36235
36236        assert_eq!(dt.min(), Some(a));
36237        assert_eq!(dt.max(), Some(c));
36238
36239        let sorted = dt.sort_values();
36240        let sorted_alias = dt.sort();
36241        // NAT sorts first (na_position='first' default).
36242        assert_eq!(sorted.values(), vec![None, Some(a), Some(b), Some(c)]);
36243        assert_eq!(sorted_alias.values(), sorted.values());
36244        assert_eq!(sorted.name().map(|n| n.as_str()), Some("ts"));
36245        assert_eq!(sorted_alias.name().map(|n| n.as_str()), Some("ts"));
36246
36247        let all_nat = super::DatetimeIndex::new(vec![i64::MIN, i64::MIN]);
36248        assert_eq!(all_nat.min(), None);
36249        assert_eq!(all_nat.max(), None);
36250
36251        let empty = super::DatetimeIndex::new(vec![]);
36252        assert_eq!(empty.min(), None);
36253        assert_eq!(empty.max(), None);
36254        assert!(empty.sort_values().is_empty());
36255        assert!(empty.sort().is_empty());
36256    }
36257
36258    #[test]
36259    fn timedelta_index_min_max_sort_values_match_pandas_kastf() {
36260        let nat = fp_types::Timedelta::NAT;
36261        let td = super::TimedeltaIndex::new(vec![300_i64, nat, 100, 200]).set_name("d");
36262
36263        assert_eq!(td.min(), Some(100));
36264        assert_eq!(td.max(), Some(300));
36265
36266        let sorted = td.sort_values();
36267        let sorted_alias = td.sort();
36268        assert_eq!(sorted.values(), vec![None, Some(100), Some(200), Some(300)]);
36269        assert_eq!(sorted_alias.values(), sorted.values());
36270        assert_eq!(sorted.name().map(|n| n.as_str()), Some("d"));
36271        assert_eq!(sorted_alias.name().map(|n| n.as_str()), Some("d"));
36272
36273        let all_nat = super::TimedeltaIndex::new(vec![nat, nat]);
36274        assert_eq!(all_nat.min(), None);
36275        assert_eq!(all_nat.max(), None);
36276
36277        let empty = super::TimedeltaIndex::new(vec![]);
36278        assert_eq!(empty.min(), None);
36279        assert_eq!(empty.max(), None);
36280        assert!(empty.sort().is_empty());
36281    }
36282
36283    #[test]
36284    fn datetime_index_append_delete_match_pandas_834v9() -> Result<(), super::IndexError> {
36285        const NS: i64 = 1_000_000_000;
36286        let a = 1_704_067_200_i64 * NS;
36287        let b = 1_705_276_800_i64 * NS;
36288        let c = 1_706_140_800_i64 * NS;
36289        let left = super::DatetimeIndex::new(vec![a, b]).set_name("ts");
36290        let right = super::DatetimeIndex::new(vec![c]).set_name("ts");
36291
36292        let merged = left.append(&right);
36293        assert_eq!(merged.values(), vec![Some(a), Some(b), Some(c)]);
36294        assert_eq!(merged.name().map(|n| n.as_str()), Some("ts"));
36295
36296        let mismatched = super::DatetimeIndex::new(vec![c]).set_name("other");
36297        assert_eq!(left.append(&mismatched).name(), None);
36298
36299        let trimmed = left.append(&right).delete(1)?;
36300        assert_eq!(trimmed.values(), vec![Some(a), Some(c)]);
36301        assert_eq!(trimmed.name().map(|n| n.as_str()), Some("ts"));
36302
36303        let oob = left.delete(5).unwrap_err();
36304        assert!(matches!(
36305            oob,
36306            super::IndexError::OutOfBounds {
36307                position: 5,
36308                length: 2
36309            }
36310        ));
36311        Ok(())
36312    }
36313
36314    #[test]
36315    fn timedelta_index_append_delete_match_pandas_834v9() -> Result<(), super::IndexError> {
36316        let left = super::TimedeltaIndex::new(vec![1_i64, 2]).set_name("d");
36317        let right = super::TimedeltaIndex::new(vec![3_i64]).set_name("d");
36318        let merged = left.append(&right);
36319        assert_eq!(merged.values(), vec![Some(1), Some(2), Some(3)]);
36320        assert_eq!(merged.name().map(|n| n.as_str()), Some("d"));
36321
36322        let trimmed = merged.delete(0)?;
36323        assert_eq!(trimmed.values(), vec![Some(2), Some(3)]);
36324
36325        assert!(matches!(
36326            left.delete(7).unwrap_err(),
36327            super::IndexError::OutOfBounds {
36328                position: 7,
36329                length: 2
36330            }
36331        ));
36332        Ok(())
36333    }
36334
36335    #[test]
36336    fn period_index_append_delete_match_pandas_834v9() -> Result<(), super::IndexError> {
36337        use fp_types::{Period, PeriodFreq};
36338        let p1 = Period::new(10, PeriodFreq::Monthly);
36339        let p2 = Period::new(11, PeriodFreq::Monthly);
36340        let p3 = Period::new(12, PeriodFreq::Monthly);
36341        let left = super::PeriodIndex::new(vec![p1, p2]).set_name("p");
36342        let right = super::PeriodIndex::new(vec![p3]).set_name("p");
36343
36344        let merged = left.append(&right);
36345        assert_eq!(merged.values(), &[p1, p2, p3]);
36346        assert_eq!(merged.name().map(|n| n.as_str()), Some("p"));
36347
36348        let mismatched = super::PeriodIndex::new(vec![p3]).set_name("other");
36349        assert_eq!(left.append(&mismatched).name(), None);
36350
36351        let trimmed = merged.delete(1)?;
36352        assert_eq!(trimmed.values(), &[p1, p3]);
36353
36354        assert!(matches!(
36355            left.delete(5).unwrap_err(),
36356            super::IndexError::OutOfBounds {
36357                position: 5,
36358                length: 2
36359            }
36360        ));
36361        Ok(())
36362    }
36363
36364    #[test]
36365    fn range_index_append_delete_match_pandas_834v9() -> Result<(), super::IndexError> {
36366        let left = super::RangeIndex::new(0, 3, 1).unwrap();
36367        let right = super::RangeIndex::new(10, 12, 1).unwrap();
36368        let merged = left.append(&right);
36369        let merged_labels = int64_labels(&merged);
36370        assert_eq!(merged_labels, vec![0, 1, 2, 10, 11]);
36371
36372        let trimmed = left.delete(1)?;
36373        let trimmed_labels = int64_labels(&trimmed);
36374        assert_eq!(trimmed_labels, vec![0, 2]);
36375
36376        assert!(matches!(
36377            left.delete(99).unwrap_err(),
36378            super::IndexError::OutOfBounds {
36379                position: 99,
36380                length: 3
36381            }
36382        ));
36383        Ok(())
36384    }
36385
36386    #[test]
36387    fn range_index_values_generate_arithmetic_progression_without_flat_index_w6q7d() {
36388        let positive = super::RangeIndex::new(2, 11, 3).unwrap();
36389        assert_eq!(positive.values().to_vec(), vec![2, 5, 8]);
36390        assert_eq!(positive.values().get(3), None);
36391
36392        let descending = super::RangeIndex::new(9, 0, -4).unwrap();
36393        assert_eq!(descending.values().to_vec(), vec![9, 5, 1]);
36394
36395        let empty = super::RangeIndex::new(5, 5, 1).unwrap();
36396        assert!(empty.values().is_empty());
36397    }
36398
36399    #[test]
36400    fn range_index_equals_compares_sequence_shape_x7tr6() {
36401        let empty_a = super::RangeIndex::new(5, 5, 1).unwrap();
36402        let empty_b = super::RangeIndex::new(10, 0, 2).unwrap();
36403        assert!(empty_a.equals(&empty_b));
36404
36405        let singleton_a = super::RangeIndex::new(7, 8, 1).unwrap();
36406        let singleton_b = super::RangeIndex::new(7, 100, 93).unwrap();
36407        assert!(singleton_a.equals(&singleton_b));
36408
36409        let same_values_a = super::RangeIndex::new(0, 5, 2).unwrap();
36410        let same_values_b = super::RangeIndex::new(0, 6, 2).unwrap();
36411        assert!(same_values_a.equals(&same_values_b));
36412
36413        let different_step = super::RangeIndex::new(0, 6, 3).unwrap();
36414        assert!(!same_values_a.equals(&different_step));
36415    }
36416
36417    #[test]
36418    fn index_repeat_capacity_checks_output_length_uza04182() {
36419        assert_eq!(super::repeat_output_capacity(3, 4), 12);
36420        assert_eq!(super::repeat_output_capacity(0, usize::MAX), 0);
36421    }
36422
36423    #[test]
36424    #[should_panic(expected = "index repeat output length overflow")]
36425    fn index_repeat_capacity_rejects_overflow_uza04182() {
36426        let _ = super::repeat_output_capacity(usize::MAX, 2);
36427    }
36428
36429    #[test]
36430    fn index_combined_capacity_checks_output_length_uza04183() {
36431        assert_eq!(super::combined_output_capacity(3, 4), 7);
36432        assert_eq!(super::insert_output_capacity(3), 4);
36433    }
36434
36435    #[test]
36436    #[should_panic(expected = "index combined output length overflow")]
36437    fn index_combined_capacity_rejects_overflow_uza04183() {
36438        let _ = super::combined_output_capacity(usize::MAX, 1);
36439    }
36440
36441    #[test]
36442    #[should_panic(expected = "index insert output length overflow")]
36443    fn index_insert_capacity_rejects_overflow_uza04183() {
36444        let _ = super::insert_output_capacity(usize::MAX);
36445    }
36446
36447    #[test]
36448    fn index_aggregate_capacity_checks_output_length_uza04185() {
36449        assert_eq!(super::aggregate_output_capacity([2, 3, 4]), 9);
36450        assert_eq!(super::aggregate_output_capacity([0, 0]), 0);
36451    }
36452
36453    #[test]
36454    #[should_panic(expected = "index aggregate output length overflow")]
36455    fn index_aggregate_capacity_rejects_overflow_uza04185() {
36456        let _ = super::aggregate_output_capacity([usize::MAX, 1]);
36457    }
36458
36459    #[test]
36460    fn range_index_take_repeat_keep_typed_backing_uza04166() -> Result<(), super::IndexError> {
36461        let range = super::RangeIndex::new(2, 11, 3).unwrap().set_name("r");
36462
36463        let taken = range.take(&[2, 0, 2])?;
36464        assert_eq!(taken.name().map(|n| n.as_str()), Some("r"));
36465        assert_eq!(taken.labels.int64_view().unwrap().as_slice(), &[8, 2, 8]);
36466        assert!(
36467            taken.labels.materialized.get().is_none(),
36468            "RangeIndex::take should keep typed Int64 output backing"
36469        );
36470
36471        let repeated = range.repeat(2);
36472        assert_eq!(repeated.name().map(|n| n.as_str()), Some("r"));
36473        assert_eq!(
36474            repeated.labels.int64_view().unwrap().as_slice(),
36475            &[2, 2, 5, 5, 8, 8]
36476        );
36477        assert!(
36478            repeated.labels.materialized.get().is_none(),
36479            "RangeIndex::repeat should keep typed Int64 output backing"
36480        );
36481
36482        Ok(())
36483    }
36484
36485    #[test]
36486    fn range_index_take_arithmetic_keep_affine_uza04205() -> Result<(), super::IndexError> {
36487        let range = super::RangeIndex::new(10, 40, 3).unwrap().set_name("r");
36488
36489        let ascending = range.take(&[1, 3, 5])?;
36490        assert_eq!(ascending.name().map(|n| n.as_str()), Some("r"));
36491        assert_eq!(
36492            ascending.labels.int64_view().unwrap().as_slice(),
36493            &[13, 19, 25]
36494        );
36495        let affine = ascending
36496            .labels
36497            .int64_affine_range()
36498            .expect("arithmetic take should keep lazy affine backing");
36499        assert_eq!((affine.start, affine.step, affine.len), (13, 6, 3));
36500        assert!(
36501            ascending.labels.materialized.get().is_none(),
36502            "arithmetic RangeIndex::take should not materialize labels"
36503        );
36504
36505        let descending = range.take(&[5, 3, 1])?;
36506        assert_eq!(
36507            descending.labels.int64_view().unwrap().as_slice(),
36508            &[25, 19, 13]
36509        );
36510        let affine = descending
36511            .labels
36512            .int64_affine_range()
36513            .expect("descending arithmetic take should keep lazy affine backing");
36514        assert_eq!((affine.start, affine.step, affine.len), (25, -6, 3));
36515
36516        let singleton = range.take(&[4])?;
36517        assert_eq!(singleton.labels.int64_view().unwrap().as_slice(), &[22]);
36518        assert!(
36519            singleton.labels.int64_affine_range().is_some(),
36520            "singleton take can stay lazy affine"
36521        );
36522
36523        let empty = range.take(&[])?;
36524        assert!(empty.labels.int64_view().unwrap().is_empty());
36525        assert!(
36526            empty.labels.int64_affine_range().is_some(),
36527            "empty take can stay lazy affine"
36528        );
36529
36530        let duplicate = range.take(&[1, 1, 2])?;
36531        assert_eq!(
36532            duplicate.labels.int64_view().unwrap().as_slice(),
36533            &[13, 13, 16]
36534        );
36535        assert!(
36536            duplicate.labels.int64_affine_range().is_none(),
36537            "duplicate selectors must preserve materialized typed fallback"
36538        );
36539        assert!(
36540            duplicate.labels.materialized.get().is_none(),
36541            "fallback should remain typed Int64, not enum materialized"
36542        );
36543
36544        Ok(())
36545    }
36546
36547    #[test]
36548    fn range_index_take_uses_wide_position_values_uza04176() -> Result<(), super::IndexError> {
36549        let range = super::RangeIndex::new(i64::MIN, i64::MAX, 1)
36550            .unwrap()
36551            .set_name("wide");
36552        let zero_pos = usize::try_from(i128::from(i64::MAX) + 1).unwrap();
36553        let taken = range.take(&[0, zero_pos, range.len() - 1])?;
36554
36555        assert_eq!(taken.name().map(|n| n.as_str()), Some("wide"));
36556        assert_eq!(
36557            taken.labels.int64_view().unwrap().as_slice(),
36558            &[i64::MIN, 0, i64::MAX - 1]
36559        );
36560        Ok(())
36561    }
36562
36563    #[test]
36564    fn range_index_take_repeat_use_direct_values_86gwy() -> Result<(), super::IndexError> {
36565        let range = super::RangeIndex::new(9, 0, -4).unwrap().set_name("r");
36566
36567        let taken = range.take(&[2, 0])?;
36568        assert_eq!(taken.name().map(|n| n.as_str()), Some("r"));
36569        assert_eq!(taken.labels.int64_view().unwrap().as_slice(), &[1, 9]);
36570        assert!(
36571            taken.labels.materialized.get().is_none(),
36572            "RangeIndex::take should gather direct i64 labels into typed backing"
36573        );
36574
36575        let oob = range.take(&[3]).unwrap_err();
36576        assert!(matches!(
36577            oob,
36578            super::IndexError::OutOfBounds {
36579                position: 3,
36580                length: 3
36581            }
36582        ));
36583
36584        let repeated = range.repeat(2);
36585        assert_eq!(repeated.name().map(|n| n.as_str()), Some("r"));
36586        assert_eq!(
36587            repeated.labels.int64_view().unwrap().as_slice(),
36588            &[9, 9, 5, 5, 1, 1]
36589        );
36590        assert!(
36591            repeated.labels.materialized.get().is_none(),
36592            "RangeIndex::repeat should emit direct i64 labels into typed backing"
36593        );
36594
36595        Ok(())
36596    }
36597
36598    #[test]
36599    fn range_index_to_flat_index_keeps_typed_backing_uza04167() {
36600        let range = super::RangeIndex::new(9, 0, -4).unwrap().set_name("r");
36601        let flat = range.to_flat_index();
36602
36603        assert_eq!(flat.name().map(|n| n.as_str()), Some("r"));
36604        assert_eq!(flat.labels.int64_view().unwrap().as_slice(), &[9, 5, 1]);
36605        assert!(
36606            flat.labels.materialized.get().is_none(),
36607            "RangeIndex::to_flat_index should keep typed Int64 output backing"
36608        );
36609
36610        let positive = super::RangeIndex::new(2, 11, 3).unwrap().to_flat_index();
36611        assert_eq!(positive.labels.int64_view().unwrap().as_slice(), &[2, 5, 8]);
36612        assert!(positive.labels.materialized.get().is_none());
36613
36614        let empty = super::RangeIndex::new(5, 5, 1).unwrap().to_flat_index();
36615        assert!(empty.is_empty());
36616        assert!(empty.labels.materialized.get().is_none());
36617    }
36618
36619    #[test]
36620    fn range_index_where_putmask_keep_typed_backing_uza04153() -> Result<(), super::IndexError> {
36621        let range = super::RangeIndex::new(2, 11, 3).unwrap().set_name("r");
36622
36623        let replaced = range.r#where(&[true, false, true], 99)?;
36624        assert_eq!(replaced.name().map(|n| n.as_str()), Some("r"));
36625        assert_eq!(
36626            replaced.labels.int64_view().unwrap().as_slice(),
36627            &[2, 99, 8]
36628        );
36629        assert!(
36630            replaced.labels.materialized.get().is_none(),
36631            "RangeIndex::where should keep typed Int64 output backing"
36632        );
36633
36634        let masked = range.putmask(&[false, true, false], -7)?;
36635        assert_eq!(masked.name().map(|n| n.as_str()), Some("r"));
36636        assert_eq!(masked.labels.int64_view().unwrap().as_slice(), &[2, -7, 8]);
36637        assert!(
36638            masked.labels.materialized.get().is_none(),
36639            "RangeIndex::putmask should keep typed Int64 output backing"
36640        );
36641
36642        Ok(())
36643    }
36644
36645    #[test]
36646    fn range_index_where_putmask_use_direct_values_k1xts() -> Result<(), super::IndexError> {
36647        let range = super::RangeIndex::new(9, 0, -4).unwrap().set_name("r");
36648
36649        let replaced = range.r#where(&[true, false, true], 99)?;
36650        assert_eq!(replaced.name().map(|n| n.as_str()), Some("r"));
36651        assert_eq!(
36652            replaced.labels.int64_view().unwrap().as_slice(),
36653            &[9, 99, 1]
36654        );
36655        assert!(
36656            replaced.labels.materialized.get().is_none(),
36657            "RangeIndex::where should mask direct i64 labels into typed backing"
36658        );
36659
36660        let masked = range.putmask(&[false, true, false], -7)?;
36661        assert_eq!(masked.name().map(|n| n.as_str()), Some("r"));
36662        assert_eq!(masked.labels.int64_view().unwrap().as_slice(), &[9, -7, 1]);
36663        assert!(
36664            masked.labels.materialized.get().is_none(),
36665            "RangeIndex::putmask should mask direct i64 labels into typed backing"
36666        );
36667
36668        let where_err = range.r#where(&[true], 0).unwrap_err();
36669        assert!(matches!(
36670            where_err,
36671            super::IndexError::LengthMismatch {
36672                expected: 3,
36673                actual: 1,
36674                ..
36675            }
36676        ));
36677        let putmask_err = range.putmask(&[false, true], 0).unwrap_err();
36678        assert!(matches!(
36679            putmask_err,
36680            super::IndexError::LengthMismatch {
36681                expected: 3,
36682                actual: 2,
36683                ..
36684            }
36685        ));
36686
36687        Ok(())
36688    }
36689
36690    #[test]
36691    fn range_index_set_ops_keep_typed_backing_uza04168() {
36692        let left = super::RangeIndex::new(0, 5, 1).unwrap().set_name("k");
36693        let right = super::RangeIndex::new(2, 7, 1).unwrap().set_name("k");
36694
36695        let intersection = left.intersection(&right);
36696        let union = left.union(&right);
36697        let difference = left.difference(&right);
36698        let symmetric = left.symmetric_difference(&right);
36699
36700        assert_eq!(intersection.name().map(|n| n.as_str()), Some("k"));
36701        assert_eq!(union.name().map(|n| n.as_str()), Some("k"));
36702        assert_eq!(difference.name().map(|n| n.as_str()), Some("k"));
36703        assert_eq!(symmetric.name().map(|n| n.as_str()), Some("k"));
36704        assert_eq!(
36705            intersection.labels.int64_view().unwrap().as_slice(),
36706            &[2, 3, 4]
36707        );
36708        assert_eq!(
36709            union.labels.int64_view().unwrap().as_slice(),
36710            &[0, 1, 2, 3, 4, 5, 6]
36711        );
36712        assert_eq!(difference.labels.int64_view().unwrap().as_slice(), &[0, 1]);
36713        assert_eq!(
36714            symmetric.labels.int64_view().unwrap().as_slice(),
36715            &[0, 1, 5, 6]
36716        );
36717
36718        for output in [&intersection, &union, &difference, &symmetric] {
36719            assert!(
36720                output.labels.materialized.get().is_none(),
36721                "RangeIndex set ops should keep typed Int64 output backing"
36722            );
36723        }
36724    }
36725
36726    #[test]
36727    fn range_index_set_ops_use_direct_values_b7nxg() {
36728        let left = super::RangeIndex::new(9, -3, -3).unwrap().set_name("k");
36729        let right = super::RangeIndex::new(6, -6, -3).unwrap().set_name("k");
36730
36731        let intersection = left.intersection(&right);
36732        let union = left.union(&right);
36733        let difference = left.difference(&right);
36734        let symmetric = left.symmetric_difference(&right);
36735
36736        assert_eq!(intersection.name().map(|n| n.as_str()), Some("k"));
36737        assert_eq!(union.name().map(|n| n.as_str()), Some("k"));
36738        assert_eq!(difference.name().map(|n| n.as_str()), Some("k"));
36739        assert_eq!(symmetric.name().map(|n| n.as_str()), Some("k"));
36740        // pandas 2.2.3: intersection uses sort=False (self-order, descending
36741        // preserved); union/difference/symmetric_difference use sort=None and
36742        // return ascending-sorted results for these both-non-empty operands.
36743        assert_eq!(
36744            intersection.labels.int64_view().unwrap().as_slice(),
36745            &[6, 3, 0]
36746        );
36747        assert_eq!(
36748            union.labels.int64_view().unwrap().as_slice(),
36749            &[-3, 0, 3, 6, 9]
36750        );
36751        assert_eq!(difference.labels.int64_view().unwrap().as_slice(), &[9]);
36752        assert_eq!(symmetric.labels.int64_view().unwrap().as_slice(), &[-3, 9]);
36753
36754        let mismatched = right.set_name("other");
36755        assert_eq!(left.intersection(&mismatched).name(), None);
36756        assert_eq!(left.union(&mismatched).name(), None);
36757        assert_eq!(left.symmetric_difference(&mismatched).name(), None);
36758        assert_eq!(
36759            left.difference(&mismatched).name().map(|n| n.as_str()),
36760            Some("k")
36761        );
36762
36763        // intersection (self-order) and this single-span difference keep lazy
36764        // affine backing; union/symmetric materialize because reconciling the
36765        // interleaved descending lattices to pandas' ascending order requires a
36766        // sort (the affine fast paths still apply to aligned ascending inputs).
36767        for output in [&intersection, &difference] {
36768            assert!(
36769                output.labels.materialized.get().is_none(),
36770                "self-order intersection and single-span difference keep typed lazy backing"
36771            );
36772        }
36773    }
36774
36775    #[test]
36776    fn range_index_set_ops_closed_form_membership_preserves_order_iatnc() {
36777        let left = super::RangeIndex::new(9, -3, -3).unwrap().set_name("k");
36778        let right = super::RangeIndex::new(6, -9, -6).unwrap().set_name("k");
36779
36780        let intersection = left.intersection(&right);
36781        let union = left.union(&right);
36782        let difference = left.difference(&right);
36783        let symmetric = left.symmetric_difference(&right);
36784
36785        assert_eq!(intersection.name().map(|n| n.as_str()), Some("k"));
36786        assert_eq!(union.name().map(|n| n.as_str()), Some("k"));
36787        assert_eq!(difference.name().map(|n| n.as_str()), Some("k"));
36788        assert_eq!(symmetric.name().map(|n| n.as_str()), Some("k"));
36789        // pandas 2.2.3: intersection sort=False (self-order); union/difference/
36790        // symmetric_difference sort=None -> ascending for both-non-empty inputs.
36791        assert_eq!(
36792            intersection.labels.int64_view().unwrap().as_slice(),
36793            &[6, 0]
36794        );
36795        assert_eq!(
36796            union.labels.int64_view().unwrap().as_slice(),
36797            &[-6, 0, 3, 6, 9]
36798        );
36799        assert_eq!(difference.labels.int64_view().unwrap().as_slice(), &[3, 9]);
36800        assert_eq!(
36801            symmetric.labels.int64_view().unwrap().as_slice(),
36802            &[-6, 3, 9]
36803        );
36804
36805        let disjoint = super::RangeIndex::new(20, 26, 2).unwrap().set_name("k");
36806        assert!(left.intersection(&disjoint).is_empty());
36807        assert_eq!(
36808            left.symmetric_difference(&disjoint)
36809                .labels
36810                .int64_view()
36811                .unwrap()
36812                .as_slice(),
36813            &[0, 3, 6, 9, 20, 22, 24]
36814        );
36815
36816        // intersection keeps self-order lazy backing; union/difference/
36817        // symmetric materialize when the ascending sort reorders the
36818        // interleaved descending lattices (pandas sort=None).
36819        assert!(
36820            intersection.labels.materialized.get().is_none(),
36821            "self-order intersection keeps typed lazy backing"
36822        );
36823    }
36824
36825    #[test]
36826    fn range_index_set_ops_return_affine_spans_iatnc() {
36827        let left = super::RangeIndex::new(0, 1_000_000, 1)
36828            .unwrap()
36829            .set_name("k");
36830        let right = super::RangeIndex::new(500_000, 1_500_000, 1)
36831            .unwrap()
36832            .set_name("k");
36833
36834        let intersection = left.intersection(&right);
36835        let union = left.union(&right);
36836        let difference = left.difference(&right);
36837        let symmetric = left.symmetric_difference(&right);
36838
36839        assert_eq!(
36840            intersection.labels.int64_affine_range(),
36841            Some(Int64AffineLabels {
36842                start: 500_000,
36843                step: 1,
36844                len: 500_000,
36845            })
36846        );
36847        assert_eq!(
36848            union.labels.int64_affine_range(),
36849            Some(Int64AffineLabels {
36850                start: 0,
36851                step: 1,
36852                len: 1_500_000,
36853            })
36854        );
36855        assert_eq!(
36856            difference.labels.int64_affine_range(),
36857            Some(Int64AffineLabels {
36858                start: 0,
36859                step: 1,
36860                len: 500_000,
36861            })
36862        );
36863        for output in [&intersection, &union, &difference] {
36864            assert!(
36865                output.labels.materialized.get().is_none(),
36866                "single-span RangeIndex set ops should return lazy affine backing"
36867            );
36868        }
36869        assert_eq!(symmetric.len(), 1_000_000);
36870        assert!(
36871            symmetric.labels.int64_affine_range().is_none(),
36872            "split symmetric_difference should not lie as one affine span"
36873        );
36874        assert_eq!(
36875            symmetric.labels.int64_two_affine.as_deref().copied(),
36876            Some(Int64TwoAffineLabels {
36877                first: Int64AffineLabels {
36878                    start: 0,
36879                    step: 1,
36880                    len: 500_000,
36881                },
36882                second: Int64AffineLabels {
36883                    start: 1_000_000,
36884                    step: 1,
36885                    len: 500_000,
36886                },
36887            })
36888        );
36889        assert!(
36890            symmetric.labels.materialized.get().is_none(),
36891            "split symmetric_difference should carry two lazy Int64 runs"
36892        );
36893
36894        let descending_left = super::RangeIndex::new(9, -3, -3).unwrap().set_name("k");
36895        let descending_right = super::RangeIndex::new(6, -6, -3).unwrap().set_name("k");
36896        assert_eq!(
36897            descending_left
36898                .intersection(&descending_right)
36899                .labels
36900                .int64_affine_range(),
36901            Some(Int64AffineLabels {
36902                start: 6,
36903                step: -3,
36904                len: 3,
36905            })
36906        );
36907        // pandas 2.2.3 union (sort=None) returns ascending [-3, 0, 3, 6, 9] for
36908        // these interleaved descending lattices; reconciling to ascending order
36909        // materializes the labels rather than returning a descending affine span.
36910        // (The aligned-ascending union above still returns a lazy affine span.)
36911        assert_eq!(
36912            descending_left
36913                .union(&descending_right)
36914                .labels
36915                .int64_view()
36916                .unwrap()
36917                .as_slice(),
36918            &[-3, 0, 3, 6, 9]
36919        );
36920
36921        let adjacent_left = super::RangeIndex::new(0, 3, 1).unwrap().set_name("k");
36922        let adjacent_right = super::RangeIndex::new(3, 6, 1).unwrap().set_name("k");
36923        assert_eq!(
36924            adjacent_left
36925                .symmetric_difference(&adjacent_right)
36926                .labels
36927                .int64_affine_range(),
36928            Some(Int64AffineLabels {
36929                start: 0,
36930                step: 1,
36931                len: 6,
36932            })
36933        );
36934    }
36935
36936    #[test]
36937    fn range_index_splice_outputs_keep_typed_backing_uza04169() -> Result<(), super::IndexError> {
36938        let left = super::RangeIndex::new(0, 3, 1).unwrap().set_name("k");
36939        let right = super::RangeIndex::new(10, 12, 1).unwrap().set_name("k");
36940
36941        let inserted = left.insert(1, 99)?;
36942        let appended = left.append(&right);
36943        let deleted = left.delete(1)?;
36944
36945        assert_eq!(inserted.name().map(|n| n.as_str()), Some("k"));
36946        assert_eq!(appended.name().map(|n| n.as_str()), Some("k"));
36947        assert_eq!(deleted.name().map(|n| n.as_str()), Some("k"));
36948        assert_eq!(
36949            inserted.labels.int64_view().unwrap().as_slice(),
36950            &[0, 99, 1, 2]
36951        );
36952        assert_eq!(
36953            appended.labels.int64_view().unwrap().as_slice(),
36954            &[0, 1, 2, 10, 11]
36955        );
36956        assert_eq!(deleted.labels.int64_view().unwrap().as_slice(), &[0, 2]);
36957        assert_eq!(
36958            appended.labels.int64_two_affine.as_deref().copied(),
36959            Some(Int64TwoAffineLabels {
36960                first: Int64AffineLabels {
36961                    start: 0,
36962                    step: 1,
36963                    len: 3,
36964                },
36965                second: Int64AffineLabels {
36966                    start: 10,
36967                    step: 1,
36968                    len: 2,
36969                },
36970            })
36971        );
36972        assert_eq!(
36973            deleted.labels.int64_two_affine.as_deref().copied(),
36974            Some(Int64TwoAffineLabels {
36975                first: Int64AffineLabels {
36976                    start: 0,
36977                    step: 1,
36978                    len: 1,
36979                },
36980                second: Int64AffineLabels {
36981                    start: 2,
36982                    step: 1,
36983                    len: 1,
36984                },
36985            })
36986        );
36987
36988        for output in [&inserted, &appended, &deleted] {
36989            assert!(
36990                output.labels.materialized.get().is_none(),
36991                "RangeIndex splice outputs should keep typed Int64 output backing"
36992            );
36993        }
36994
36995        Ok(())
36996    }
36997
36998    #[test]
36999    fn range_index_splice_uses_direct_values_un6on() -> Result<(), super::IndexError> {
37000        let left = super::RangeIndex::new(9, 0, -4).unwrap().set_name("k");
37001        let right = super::RangeIndex::new(-1, -6, -2).unwrap().set_name("k");
37002
37003        let inserted = left.insert(2, 99)?;
37004        assert_eq!(inserted.name().map(|n| n.as_str()), Some("k"));
37005        assert_eq!(
37006            inserted.labels.int64_view().unwrap().as_slice(),
37007            &[9, 5, 99, 1]
37008        );
37009
37010        let appended = left.append(&right);
37011        assert_eq!(appended.name().map(|n| n.as_str()), Some("k"));
37012        assert_eq!(
37013            appended.labels.int64_view().unwrap().as_slice(),
37014            &[9, 5, 1, -1, -3, -5]
37015        );
37016        assert_eq!(
37017            appended.labels.int64_two_affine.as_deref().copied(),
37018            Some(Int64TwoAffineLabels {
37019                first: Int64AffineLabels {
37020                    start: 9,
37021                    step: -4,
37022                    len: 3,
37023                },
37024                second: Int64AffineLabels {
37025                    start: -1,
37026                    step: -2,
37027                    len: 3,
37028                },
37029            })
37030        );
37031
37032        let mismatched_name = right.set_name("other");
37033        assert_eq!(left.append(&mismatched_name).name(), None);
37034
37035        let deleted = left.delete(1)?;
37036        assert_eq!(deleted.name().map(|n| n.as_str()), Some("k"));
37037        assert_eq!(deleted.labels.int64_view().unwrap().as_slice(), &[9, 1]);
37038        assert_eq!(
37039            deleted.labels.int64_two_affine.as_deref().copied(),
37040            Some(Int64TwoAffineLabels {
37041                first: Int64AffineLabels {
37042                    start: 9,
37043                    step: -4,
37044                    len: 1,
37045                },
37046                second: Int64AffineLabels {
37047                    start: 1,
37048                    step: -4,
37049                    len: 1,
37050                },
37051            })
37052        );
37053
37054        let insert_err = left.insert(4, 0).unwrap_err();
37055        assert!(matches!(
37056            insert_err,
37057            super::IndexError::OutOfBounds {
37058                position: 4,
37059                length: 3
37060            }
37061        ));
37062
37063        let delete_err = left.delete(3).unwrap_err();
37064        assert!(matches!(
37065            delete_err,
37066            super::IndexError::OutOfBounds {
37067                position: 3,
37068                length: 3
37069            }
37070        ));
37071
37072        for output in [&inserted, &appended, &deleted] {
37073            assert!(
37074                output.labels.materialized.get().is_none(),
37075                "RangeIndex splice should stream direct i64 labels into typed backing"
37076            );
37077        }
37078
37079        Ok(())
37080    }
37081
37082    #[test]
37083    fn datetime_index_take_repeat_isin_match_pandas_bbgg3() -> Result<(), super::IndexError> {
37084        const NS: i64 = 1_000_000_000;
37085        let a = 1_704_067_200_i64 * NS;
37086        let b = 1_705_276_800_i64 * NS;
37087        let c = 1_706_140_800_i64 * NS;
37088        let dt = super::DatetimeIndex::new(vec![a, b, c]).set_name("ts");
37089
37090        let taken = dt.take(&[2, 0, 0])?;
37091        assert_eq!(taken.values(), vec![Some(c), Some(a), Some(a)]);
37092        assert_eq!(taken.name().map(|n| n.as_str()), Some("ts"));
37093
37094        let oob = dt.take(&[3]).unwrap_err();
37095        assert!(matches!(
37096            oob,
37097            super::IndexError::OutOfBounds {
37098                position: 3,
37099                length: 3
37100            }
37101        ));
37102
37103        let repeated = dt.repeat(2);
37104        assert_eq!(
37105            repeated.values(),
37106            vec![Some(a), Some(a), Some(b), Some(b), Some(c), Some(c)]
37107        );
37108        assert_eq!(repeated.name().map(|n| n.as_str()), Some("ts"));
37109
37110        let mask = dt.isin(&[a, c]);
37111        assert_eq!(mask, vec![true, false, true]);
37112
37113        let nat_idx = super::DatetimeIndex::new(vec![i64::MIN, a]);
37114        assert_eq!(nat_idx.isin(&[i64::MIN]), vec![true, false]);
37115        Ok(())
37116    }
37117
37118    #[test]
37119    fn timedelta_index_take_repeat_isin_match_pandas_bbgg3() -> Result<(), super::IndexError> {
37120        let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]).set_name("d");
37121        let taken = td.take(&[2, 0])?;
37122        assert_eq!(taken.values(), vec![Some(300), Some(100)]);
37123        assert_eq!(taken.name().map(|n| n.as_str()), Some("d"));
37124
37125        assert!(matches!(
37126            td.take(&[7]).unwrap_err(),
37127            super::IndexError::OutOfBounds {
37128                position: 7,
37129                length: 3
37130            }
37131        ));
37132
37133        let repeated = td.repeat(2);
37134        assert_eq!(
37135            repeated.values(),
37136            vec![
37137                Some(100),
37138                Some(100),
37139                Some(200),
37140                Some(200),
37141                Some(300),
37142                Some(300)
37143            ]
37144        );
37145
37146        let mask = td.isin(&[200, 999]);
37147        assert_eq!(mask, vec![false, true, false]);
37148        Ok(())
37149    }
37150
37151    #[test]
37152    fn period_index_take_repeat_isin_match_pandas_bbgg3() -> Result<(), super::IndexError> {
37153        use fp_types::{Period, PeriodFreq};
37154        let p1 = Period::new(10, PeriodFreq::Monthly);
37155        let p2 = Period::new(11, PeriodFreq::Monthly);
37156        let p3 = Period::new(12, PeriodFreq::Monthly);
37157        let pi = super::PeriodIndex::new(vec![p1, p2, p3]).set_name("pp");
37158
37159        let taken = pi.take(&[2, 1])?;
37160        assert_eq!(taken.values(), &[p3, p2]);
37161        assert_eq!(taken.name().map(|n| n.as_str()), Some("pp"));
37162
37163        assert!(matches!(
37164            pi.take(&[5]).unwrap_err(),
37165            super::IndexError::OutOfBounds {
37166                position: 5,
37167                length: 3
37168            }
37169        ));
37170
37171        let repeated = pi.repeat(2);
37172        assert_eq!(repeated.values(), &[p1, p1, p2, p2, p3, p3]);
37173
37174        let mask = pi.isin(&[p1, p3]);
37175        assert_eq!(mask, vec![true, false, true]);
37176        Ok(())
37177    }
37178
37179    #[test]
37180    fn range_index_take_repeat_isin_match_pandas_bbgg3() -> Result<(), super::IndexError> {
37181        let r = super::RangeIndex::new(0, 5, 1).unwrap();
37182        let taken = r.take(&[2, 4, 0])?;
37183        let labels = int64_labels(&taken);
37184        assert_eq!(labels, vec![2, 4, 0]);
37185
37186        assert!(matches!(
37187            r.take(&[10]).unwrap_err(),
37188            super::IndexError::OutOfBounds {
37189                position: 10,
37190                length: 5
37191            }
37192        ));
37193
37194        let repeated = r.repeat(2);
37195        let repeat_labels = int64_labels(&repeated);
37196        assert_eq!(repeat_labels, vec![0, 0, 1, 1, 2, 2, 3, 3, 4, 4]);
37197
37198        let mask = r.isin(&[1, 3, 99]);
37199        assert_eq!(mask, vec![false, true, false, true, false]);
37200        Ok(())
37201    }
37202
37203    #[test]
37204    fn range_index_isin_iterates_direct_values_djhvr() {
37205        let descending = super::RangeIndex::new(10, 0, -2).unwrap();
37206        assert_eq!(
37207            descending.isin(&[4, 10, 4, 99]),
37208            vec![true, false, false, true, false]
37209        );
37210
37211        let empty = super::RangeIndex::new(5, 5, 1).unwrap();
37212        assert!(empty.isin(&[5]).is_empty());
37213    }
37214
37215    #[test]
37216    fn range_index_isin_marks_positions_without_hash_ruthb() {
37217        let ascending = super::RangeIndex::new(-2, 5, 2).unwrap();
37218        assert_eq!(
37219            ascending.isin(&[4, -2, 4, 99, 1]),
37220            vec![true, false, false, true]
37221        );
37222
37223        let descending = super::RangeIndex::new(9, -3, -3).unwrap();
37224        assert_eq!(
37225            descending.isin(&[0, 12, 9, 0, -3]),
37226            vec![true, false, false, true]
37227        );
37228
37229        let empty = super::RangeIndex::new(3, 3, 1).unwrap();
37230        assert!(empty.isin(&[3, 99]).is_empty());
37231    }
37232
37233    #[test]
37234    fn range_index_any_all_closed_form_taw0w() {
37235        let empty = super::RangeIndex::new(5, 5, 1).unwrap();
37236        assert!(!empty.any());
37237        assert!(empty.all());
37238
37239        let singleton_zero = super::RangeIndex::new(0, 1, 1).unwrap();
37240        assert!(!singleton_zero.any());
37241        assert!(!singleton_zero.all());
37242
37243        let ascending_with_zero = super::RangeIndex::new(-2, 3, 1).unwrap();
37244        assert!(ascending_with_zero.any());
37245        assert!(!ascending_with_zero.all());
37246
37247        let descending_with_zero = super::RangeIndex::new(4, -2, -2).unwrap();
37248        assert!(descending_with_zero.any());
37249        assert!(!descending_with_zero.all());
37250
37251        let nonzero = super::RangeIndex::new(2, 8, 2).unwrap();
37252        assert!(nonzero.any());
37253        assert!(nonzero.all());
37254    }
37255
37256    #[test]
37257    fn range_index_groupby_builds_direct_buckets_wvlfh() {
37258        let descending = super::RangeIndex::new(8, 0, -2).unwrap();
37259        let groups = descending.groupby();
37260
37261        assert_eq!(groups[&IndexLabel::Int64(8)], vec![0]);
37262        assert_eq!(groups[&IndexLabel::Int64(6)], vec![1]);
37263        assert_eq!(groups[&IndexLabel::Int64(4)], vec![2]);
37264        assert_eq!(groups[&IndexLabel::Int64(2)], vec![3]);
37265        assert_eq!(groups.len(), 4);
37266
37267        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
37268        assert!(empty.groupby().is_empty());
37269    }
37270
37271    #[test]
37272    fn range_index_map_iterates_direct_labels_80jbg() {
37273        let range = super::RangeIndex::new(5, -1, -2).unwrap().set_name("r");
37274        let mapped = range.map(|label| match label {
37275            IndexLabel::Int64(value) => IndexLabel::Utf8(format!("v{value}")),
37276            other => other.clone(),
37277        });
37278
37279        assert_eq!(mapped.name().map(|n| n.as_str()), Some("r"));
37280        assert_eq!(
37281            mapped.labels(),
37282            &[
37283                IndexLabel::Utf8("v5".to_owned()),
37284                IndexLabel::Utf8("v3".to_owned()),
37285                IndexLabel::Utf8("v1".to_owned())
37286            ]
37287        );
37288
37289        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
37290        assert!(empty.map(|label| label.clone()).is_empty());
37291    }
37292
37293    #[test]
37294    fn range_index_asof_scans_direct_labels_ue0y9() {
37295        let ascending = super::RangeIndex::new(2, 10, 2).unwrap();
37296        assert_eq!(
37297            ascending.asof(&IndexLabel::Int64(7)),
37298            Some(IndexLabel::Int64(6))
37299        );
37300        assert_eq!(ascending.asof(&IndexLabel::Int64(1)), None);
37301        assert_eq!(
37302            ascending.asof(&IndexLabel::Utf8("x".to_owned())),
37303            Some(IndexLabel::Int64(8))
37304        );
37305
37306        let descending = super::RangeIndex::new(8, 0, -2).unwrap();
37307        assert_eq!(descending.asof(&IndexLabel::Int64(7)), None);
37308
37309        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
37310        assert_eq!(empty.asof(&IndexLabel::Int64(0)), None);
37311    }
37312
37313    #[test]
37314    fn range_index_asof_uses_closed_form_for_ascending_i64_jlv2o() {
37315        let range = super::RangeIndex::new(-7, 20, 4).unwrap();
37316        for needle in [-20, -7, -6, 0, 1, 17, 18, 99] {
37317            let key = IndexLabel::Int64(needle);
37318            assert_eq!(range.asof(&key), range.to_flat_index().asof(&key));
37319        }
37320
37321        let singleton = super::RangeIndex::new(42, 100, 1000).unwrap();
37322        assert_eq!(
37323            singleton.asof(&IndexLabel::Int64(42)),
37324            Some(IndexLabel::Int64(42))
37325        );
37326        assert_eq!(singleton.asof(&IndexLabel::Int64(41)), None);
37327
37328        let descending = super::RangeIndex::new(8, 0, -2).unwrap();
37329        assert_eq!(descending.asof(&IndexLabel::Int64(7)), None);
37330
37331        let empty = super::RangeIndex::new(5, 5, 1).unwrap();
37332        assert_eq!(empty.asof(&IndexLabel::Int64(5)), None);
37333    }
37334
37335    #[test]
37336    fn range_index_drop_filters_direct_values_ayakf() {
37337        let range = super::RangeIndex::new(8, 0, -2).unwrap().set_name("r");
37338        let dropped = range.drop(&[
37339            IndexLabel::Int64(6),
37340            IndexLabel::Utf8("6".to_owned()),
37341            IndexLabel::Int64(2),
37342        ]);
37343
37344        assert_eq!(dropped.name().map(|n| n.as_str()), Some("r"));
37345        assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[8, 4]);
37346        assert!(
37347            dropped.labels.materialized.get().is_none(),
37348            "RangeIndex::drop should keep typed Int64 output backing"
37349        );
37350
37351        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
37352        assert!(empty.drop(&[IndexLabel::Int64(0)]).is_empty());
37353    }
37354
37355    #[test]
37356    fn range_index_drop_marks_positions_without_hash_uza04155() {
37357        let range = super::RangeIndex::new(9, -3, -3).unwrap().set_name("r");
37358        let dropped = range.drop(&[
37359            IndexLabel::Int64(6),
37360            IndexLabel::Int64(6),
37361            IndexLabel::Utf8("6".to_owned()),
37362            IndexLabel::Int64(99),
37363            IndexLabel::Int64(0),
37364        ]);
37365
37366        assert_eq!(dropped.name().map(|n| n.as_str()), Some("r"));
37367        assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[9, 3]);
37368        assert!(
37369            dropped.labels.materialized.get().is_none(),
37370            "RangeIndex::drop should write a typed Int64 result without object materialization"
37371        );
37372
37373        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
37374        assert!(
37375            empty
37376                .drop(&[IndexLabel::Int64(0), IndexLabel::Utf8("0".to_owned())])
37377                .is_empty()
37378        );
37379    }
37380
37381    #[test]
37382    fn range_index_sortlevel_builds_direct_output_puano() {
37383        let descending = super::RangeIndex::new(8, 0, -2).unwrap().set_name("r");
37384        let (sorted, order) = descending.sortlevel();
37385
37386        assert_eq!(order, vec![3, 2, 1, 0]);
37387        assert_eq!(sorted.name().map(|n| n.as_str()), Some("r"));
37388        assert_eq!(
37389            sorted.labels.int64_view().unwrap().as_slice(),
37390            &[2, 4, 6, 8]
37391        );
37392        assert!(
37393            sorted.labels.materialized.get().is_none(),
37394            "RangeIndex::sortlevel should keep typed Int64 output backing"
37395        );
37396
37397        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
37398        let (empty_sorted, empty_order) = empty.sortlevel();
37399        assert!(empty_sorted.is_empty());
37400        assert!(empty_order.is_empty());
37401    }
37402
37403    #[test]
37404    fn range_index_join_direct_i64_matches_flat_oracle_uza04190() -> Result<(), super::IndexError> {
37405        let range = super::RangeIndex::new(9, 0, -3).unwrap().set_name("k");
37406        let other = super::Index::from_i64_values(vec![6, 12, 6, 0]).set_name("k");
37407
37408        let inner = range.join(&other, "inner")?;
37409        assert_eq!(inner.name().map(|n| n.as_str()), Some("k"));
37410        assert_eq!(inner.labels.int64_view().unwrap().as_slice(), &[6]);
37411        assert!(
37412            inner.labels.materialized.get().is_none(),
37413            "RangeIndex::join(inner) should keep typed Int64 output backing"
37414        );
37415
37416        let outer = range.join(&other, "outer")?;
37417        assert_eq!(outer.name().map(|n| n.as_str()), Some("k"));
37418        assert_eq!(
37419            outer.labels.int64_view().unwrap().as_slice(),
37420            &[9, 6, 6, 3, 12, 0]
37421        );
37422        assert!(
37423            outer.labels.materialized.get().is_none(),
37424            "RangeIndex::join(outer) should keep typed Int64 output backing"
37425        );
37426
37427        for how in ["left", "right", "inner", "outer"] {
37428            let direct = range.join(&other, how)?;
37429            let oracle = range.to_flat_index().join(&other, how)?;
37430            assert_eq!(direct.name(), oracle.name(), "name mismatch for {how}");
37431            assert_eq!(direct, oracle, "label mismatch for {how}");
37432        }
37433
37434        let seq_range = super::RangeIndex::new(0, 6, 1).unwrap().set_name("k");
37435        let seq_other = super::Index::from_i64_values(vec![3, 4, 5, 6, 7]).set_name("k");
37436        let seq_inner = seq_range.join(&seq_other, "inner")?;
37437        assert_eq!(
37438            seq_inner.labels.int64_view().unwrap().as_slice(),
37439            &[3, 4, 5]
37440        );
37441        assert!(
37442            seq_inner.labels.materialized.get().is_none(),
37443            "same-lattice RangeIndex::join(inner) should stay lazy"
37444        );
37445        let seq_outer = seq_range.join(&seq_other, "outer")?;
37446        assert_eq!(
37447            seq_outer.labels.int64_view().unwrap().as_slice(),
37448            &[0, 1, 2, 3, 4, 5, 6, 7]
37449        );
37450        assert!(
37451            seq_outer.labels.materialized.get().is_none(),
37452            "same-lattice RangeIndex::join(outer) should stay lazy"
37453        );
37454        for how in ["inner", "outer"] {
37455            assert_eq!(
37456                seq_range.join(&seq_other, how)?,
37457                seq_range.to_flat_index().join(&seq_other, how)?
37458            );
37459        }
37460
37461        let mismatched_name = other.set_name("other");
37462        assert_eq!(range.join(&mismatched_name, "inner")?.name(), None);
37463        assert_eq!(range.join(&mismatched_name, "outer")?.name(), None);
37464
37465        let mixed = super::Index::new(vec![
37466            super::IndexLabel::Int64(6),
37467            super::IndexLabel::Utf8("x".to_owned()),
37468        ]);
37469        assert_eq!(
37470            range.join(&mixed, "inner")?,
37471            range.to_flat_index().join(&mixed, "inner")?
37472        );
37473        assert!(matches!(
37474            range.join(&other, "sideways"),
37475            Err(super::IndexError::InvalidArgument(message))
37476                if message == "join: how must be 'left', 'right', 'inner', or 'outer', got \"sideways\""
37477        ));
37478
37479        Ok(())
37480    }
37481
37482    #[test]
37483    fn range_index_frame_series_views_materialize_directly_u2jv1() {
37484        let descending = super::RangeIndex::new(6, 0, -2).unwrap();
37485
37486        assert_eq!(
37487            descending.to_frame(),
37488            vec![
37489                vec![IndexLabel::Int64(6)],
37490                vec![IndexLabel::Int64(4)],
37491                vec![IndexLabel::Int64(2)]
37492            ]
37493        );
37494        assert_eq!(
37495            descending.to_series(),
37496            vec![
37497                (IndexLabel::Int64(6), IndexLabel::Int64(6)),
37498                (IndexLabel::Int64(4), IndexLabel::Int64(4)),
37499                (IndexLabel::Int64(2), IndexLabel::Int64(2))
37500            ]
37501        );
37502
37503        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
37504        assert!(empty.to_frame().is_empty());
37505        assert!(empty.to_series().is_empty());
37506    }
37507
37508    #[test]
37509    fn period_index_forwarder_methods_match_pandas_zke9k() {
37510        use fp_types::{Period, PeriodFreq};
37511        let p1 = Period::new(10, PeriodFreq::Monthly);
37512        let p2 = Period::new(11, PeriodFreq::Monthly);
37513        let p3 = Period::new(12, PeriodFreq::Monthly);
37514        let pi = super::PeriodIndex::new(vec![p1, p2, p1, p3, p2, p1]).set_name("p");
37515
37516        let unique = pi.unique();
37517        assert_eq!(unique.values(), &[p1, p2, p3]);
37518        assert_eq!(unique.name().map(|n| n.as_str()), Some("p"));
37519
37520        let dup_first = pi.duplicated(super::DuplicateKeep::First);
37521        assert_eq!(dup_first, vec![false, false, true, false, true, true]);
37522
37523        let dup_last = pi.duplicated(super::DuplicateKeep::Last);
37524        assert_eq!(dup_last, vec![true, true, true, false, false, false]);
37525
37526        let dup_none = pi.duplicated(super::DuplicateKeep::None);
37527        // None marks every position whose value occurs >1 time.
37528        assert_eq!(dup_none, vec![true, true, true, false, true, true]);
37529
37530        let dropped = pi.drop_duplicates();
37531        assert_eq!(dropped.values(), &[p1, p2, p3]);
37532
37533        let counts = pi.value_counts();
37534        let total: usize = counts.iter().map(|(_, n)| n).sum();
37535        assert_eq!(total, pi.len());
37536        // First entry is the most frequent (p1 with 3 occurrences).
37537        assert_eq!(counts[0].1, 3);
37538        let p1_count = counts
37539            .iter()
37540            .find_map(|(period, n)| (*period == p1).then_some(*n))
37541            .expect("p1 should be counted");
37542        assert_eq!(p1_count, 3);
37543
37544        let (codes, factor_uniques) = pi.factorize();
37545        assert_eq!(codes, vec![0, 1, 0, 2, 1, 0]);
37546        assert_eq!(factor_uniques.values(), &[p1, p2, p3]);
37547    }
37548
37549    #[test]
37550    fn period_index_unique_handles_empty_zke9k() {
37551        let pi = super::PeriodIndex::new(Vec::new());
37552        assert!(pi.unique().is_empty());
37553        assert!(pi.drop_duplicates().is_empty());
37554        assert!(pi.value_counts().is_empty());
37555        let (codes, uniques) = pi.factorize();
37556        assert!(codes.is_empty());
37557        assert!(uniques.is_empty());
37558    }
37559
37560    fn period_index_is_unique_hash_former_dcqru(index: &super::PeriodIndex) -> bool {
37561        let unique: super::FxHashSet<&fp_types::Period> = index.values().iter().collect();
37562        unique.len() == index.len()
37563    }
37564
37565    #[test]
37566    fn period_index_is_unique_monotonic_matches_hash_fallback_dcqru() {
37567        use fp_types::{Period, PeriodFreq};
37568
37569        let cases = [
37570            Vec::new(),
37571            vec![Period::new(7, PeriodFreq::Monthly)],
37572            vec![
37573                Period::new(1, PeriodFreq::Monthly),
37574                Period::new(2, PeriodFreq::Monthly),
37575                Period::new(3, PeriodFreq::Monthly),
37576            ],
37577            vec![
37578                Period::new(3, PeriodFreq::Monthly),
37579                Period::new(2, PeriodFreq::Monthly),
37580                Period::new(1, PeriodFreq::Monthly),
37581            ],
37582            vec![
37583                Period::new(1, PeriodFreq::Monthly),
37584                Period::new(2, PeriodFreq::Monthly),
37585                Period::new(2, PeriodFreq::Monthly),
37586            ],
37587            vec![
37588                Period::new(2, PeriodFreq::Monthly),
37589                Period::new(1, PeriodFreq::Monthly),
37590                Period::new(3, PeriodFreq::Monthly),
37591            ],
37592            vec![
37593                Period::new(1, PeriodFreq::Monthly),
37594                Period::new(1, PeriodFreq::Daily),
37595                Period::new(2, PeriodFreq::Monthly),
37596            ],
37597            vec![
37598                Period::new(1, PeriodFreq::Monthly),
37599                Period::new(1, PeriodFreq::Daily),
37600                Period::new(1, PeriodFreq::Monthly),
37601            ],
37602        ];
37603        for values in cases {
37604            let index = super::PeriodIndex::new(values);
37605            assert_eq!(
37606                index.is_unique(),
37607                period_index_is_unique_hash_former_dcqru(&index)
37608            );
37609        }
37610    }
37611
37612    #[test]
37613    #[ignore = "foreground release attribution harness"]
37614    fn period_index_is_unique_monotonic_ab_dcqru() {
37615        use fp_types::{Period, PeriodFreq};
37616
37617        fn elapsed(index: &super::PeriodIndex, candidate: bool) -> u128 {
37618            let started = std::time::Instant::now();
37619            let result = if candidate {
37620                std::hint::black_box(index).is_unique()
37621            } else {
37622                period_index_is_unique_hash_former_dcqru(std::hint::black_box(index))
37623            };
37624            std::hint::black_box(result);
37625            started.elapsed().as_nanos()
37626        }
37627
37628        fn percentile(samples: &mut [u128], pct: usize) -> u128 {
37629            samples.sort_unstable();
37630            let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
37631            samples[rank]
37632        }
37633
37634        let index =
37635            super::PeriodIndex::from_range(Period::new(-100_000, PeriodFreq::Minutely), 200_000);
37636        assert!(index.is_unique());
37637        assert!(period_index_is_unique_hash_former_dcqru(&index));
37638
37639        for _ in 0..2 {
37640            std::hint::black_box(elapsed(&index, false));
37641            std::hint::black_box(elapsed(&index, true));
37642        }
37643
37644        let mut former_a = Vec::with_capacity(9);
37645        let mut former_b = Vec::with_capacity(9);
37646        let mut candidate_a = Vec::with_capacity(9);
37647        let mut candidate_b = Vec::with_capacity(9);
37648        for block in 0_usize..9 {
37649            if block.is_multiple_of(2) {
37650                former_a.push(elapsed(&index, false));
37651                candidate_a.push(elapsed(&index, true));
37652                candidate_b.push(elapsed(&index, true));
37653                former_b.push(elapsed(&index, false));
37654            } else {
37655                candidate_b.push(elapsed(&index, true));
37656                former_b.push(elapsed(&index, false));
37657                former_a.push(elapsed(&index, false));
37658                candidate_a.push(elapsed(&index, true));
37659            }
37660        }
37661
37662        let former_a_p50 = percentile(&mut former_a, 50);
37663        let former_b_p50 = percentile(&mut former_b, 50);
37664        let candidate_a_p50 = percentile(&mut candidate_a, 50);
37665        let candidate_b_p50 = percentile(&mut candidate_b, 50);
37666        let former_p50 = (former_a_p50 + former_b_p50) as f64 / 2.0;
37667        let candidate_p50 = (candidate_a_p50 + candidate_b_p50) as f64 / 2.0;
37668        eprintln!(
37669            "PERIOD_INDEX_IS_UNIQUE_ATTRIBUTION len={} former_a_p50_ns={former_a_p50} former_b_p50_ns={former_b_p50} candidate_a_p50_ns={candidate_a_p50} candidate_b_p50_ns={candidate_b_p50} ratio={:.6}",
37670            index.len(),
37671            former_p50 / candidate_p50,
37672        );
37673        eprintln!("PERIOD_INDEX_IS_UNIQUE_ATTRIBUTION former_a_ns={former_a:?}");
37674        eprintln!("PERIOD_INDEX_IS_UNIQUE_ATTRIBUTION former_b_ns={former_b:?}");
37675        eprintln!("PERIOD_INDEX_IS_UNIQUE_ATTRIBUTION candidate_a_ns={candidate_a:?}");
37676        eprintln!("PERIOD_INDEX_IS_UNIQUE_ATTRIBUTION candidate_b_ns={candidate_b:?}");
37677    }
37678
37679    #[test]
37680    fn categorical_index_missingness_methods_are_closed_form_c0knj() {
37681        let cat = super::CategoricalIndex::from_values(
37682            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
37683            false,
37684        );
37685        assert_eq!(cat.isnull(), vec![false, false, false]);
37686        assert_eq!(cat.notnull(), vec![true, true, true]);
37687        assert!(!cat.hasnans());
37688        let dropped = cat.dropna();
37689        assert_eq!(dropped.labels(), cat.labels());
37690        let filled = cat
37691            .fillna(&IndexLabel::from("z"))
37692            .expect("fillna of an index with no missing label");
37693        assert_eq!(filled.labels(), cat.labels());
37694
37695        let empty = super::CategoricalIndex::from_values(Vec::<String>::new(), false);
37696        assert_eq!(empty.isnull(), Vec::<bool>::new());
37697        assert!(!empty.hasnans());
37698    }
37699
37700    /// pandas 2.2.3: a CategoricalIndex holds any label kind and missing
37701    /// labels (br-frankenpandas-lztvp; it held non-missing text only).
37702    #[test]
37703    fn categorical_index_typed_and_missing_labels_like_pandas_lztvp()
37704    -> Result<(), super::IndexError> {
37705        let nan = || IndexLabel::Null(fp_types::NullKind::NaN);
37706        // CategoricalIndex([3, 1, 3, 2], categories=[1, 2, 3]).
37707        let ints = super::CategoricalIndex::with_categories(
37708            vec![3_i64, 1, 3, 2],
37709            vec![1_i64, 2, 3],
37710            false,
37711        )?;
37712        assert_eq!(ints.codes(), vec![Some(2), Some(0), Some(2), Some(1)]);
37713        assert_eq!(ints.categories()[0], IndexLabel::Int64(1));
37714        assert_eq!(ints.get_loc(&IndexLabel::Int64(2))?, 3);
37715        assert_eq!(
37716            ints.value_counts(),
37717            vec![
37718                (IndexLabel::Int64(3), 2),
37719                (IndexLabel::Int64(1), 1),
37720                (IndexLabel::Int64(2), 1)
37721            ]
37722        );
37723        // A label outside the categories (and a missing one) is NaN.
37724        let text = super::CategoricalIndex::with_categories(
37725            vec![
37726                IndexLabel::from("b"),
37727                nan(),
37728                IndexLabel::from("z"),
37729                IndexLabel::from("a"),
37730            ],
37731            vec!["a", "b"],
37732            false,
37733        )?;
37734        assert_eq!(text.isna(), vec![false, true, true, false]);
37735        assert!(text.hasnans());
37736        assert_eq!(text.codes(), vec![Some(1), None, None, Some(0)]);
37737        assert_eq!(text.nunique(), 2);
37738        assert_eq!(
37739            text.value_counts(),
37740            vec![(IndexLabel::from("b"), 1), (IndexLabel::from("a"), 1)]
37741        );
37742        // factorize: NaN is -1 and no unique.
37743        let (codes, uniques) = text.factorize();
37744        assert_eq!(codes, vec![0, -1, -1, 1]);
37745        assert_eq!(
37746            uniques.labels(),
37747            &[IndexLabel::from("b"), IndexLabel::from("a")]
37748        );
37749        // Sorting puts NaN last; dropna drops it; fillna with a category fills.
37750        assert_eq!(
37751            text.sort_values().labels(),
37752            &[IndexLabel::from("a"), IndexLabel::from("b"), nan(), nan()]
37753        );
37754        assert_eq!(
37755            text.dropna().labels(),
37756            &[IndexLabel::from("b"), IndexLabel::from("a")]
37757        );
37758        assert_eq!(
37759            text.fillna(&IndexLabel::from("a"))?.labels(),
37760            &[
37761                IndexLabel::from("b"),
37762                IndexLabel::from("a"),
37763                IndexLabel::from("a"),
37764                IndexLabel::from("a")
37765            ]
37766        );
37767        // Negatives: filling with a new category, inserting one, and
37768        // repeated or missing categories are refused.
37769        assert!(text.fillna(&IndexLabel::from("z")).is_err());
37770        assert!(text.insert(0, &IndexLabel::from("z")).is_err());
37771        assert!(
37772            super::CategoricalIndex::with_categories(vec!["a"], vec!["a", "a"], false).is_err()
37773        );
37774        assert!(super::CategoricalIndex::with_categories(vec!["a"], vec![nan()], false).is_err());
37775        Ok(())
37776    }
37777
37778    #[test]
37779    fn categorical_index_append_delete_insert_repeat_match_pandas_tns52()
37780    -> Result<(), super::IndexError> {
37781        let cat = super::CategoricalIndex::with_categories(
37782            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
37783            vec![
37784                "a".to_owned(),
37785                "b".to_owned(),
37786                "c".to_owned(),
37787                "d".to_owned(),
37788            ],
37789            false,
37790        )?
37791        .set_name("level");
37792
37793        // append: merge categories.
37794        let other = super::CategoricalIndex::with_categories(
37795            vec!["d".to_owned()],
37796            vec!["d".to_owned(), "e".to_owned()],
37797            false,
37798        )?
37799        .set_name("level");
37800        let merged = cat.append(&other);
37801        assert_eq!(
37802            merged.labels(),
37803            vec![
37804                IndexLabel::from("a"),
37805                IndexLabel::from("b"),
37806                IndexLabel::from("c"),
37807                IndexLabel::from("d")
37808            ]
37809            .as_slice()
37810        );
37811        assert_eq!(merged.name().map(|n| n.as_str()), Some("level"));
37812        assert!(merged.categories().contains(&IndexLabel::from("e")));
37813
37814        // delete OOB.
37815        assert!(matches!(
37816            cat.delete(99).unwrap_err(),
37817            super::IndexError::OutOfBounds {
37818                position: 99,
37819                length: 3
37820            }
37821        ));
37822        let trimmed = cat.delete(0)?;
37823        assert_eq!(
37824            trimmed.labels(),
37825            vec![IndexLabel::from("b"), IndexLabel::from("c")].as_slice()
37826        );
37827
37828        // insert.
37829        let inserted = cat.insert(1, &IndexLabel::from("d"))?;
37830        assert_eq!(
37831            inserted.labels(),
37832            vec![
37833                IndexLabel::from("a"),
37834                IndexLabel::from("d"),
37835                IndexLabel::from("b"),
37836                IndexLabel::from("c")
37837            ]
37838            .as_slice()
37839        );
37840        assert!(cat.insert(1, &IndexLabel::from("zzz")).is_err());
37841
37842        // repeat.
37843        let repeated = cat.repeat(2);
37844        assert_eq!(repeated.labels().len(), 6);
37845        assert_eq!(repeated.labels()[0], IndexLabel::from("a"));
37846        assert_eq!(repeated.labels()[1], IndexLabel::from("a"));
37847        assert_eq!(repeated.labels()[2], IndexLabel::from("b"));
37848        Ok(())
37849    }
37850
37851    #[test]
37852    fn categorical_index_slice_locs_indexer_match_pandas_y93vb() -> Result<(), super::IndexError> {
37853        let cat = super::CategoricalIndex::with_categories(
37854            vec![
37855                "a".to_owned(),
37856                "b".to_owned(),
37857                "c".to_owned(),
37858                "d".to_owned(),
37859            ],
37860            vec![
37861                "a".to_owned(),
37862                "b".to_owned(),
37863                "c".to_owned(),
37864                "d".to_owned(),
37865            ],
37866            true,
37867        )?;
37868        assert_eq!(
37869            cat.slice_locs(&IndexLabel::from("b"), &IndexLabel::from("c"))?,
37870            (1, 3)
37871        );
37872        assert_eq!(
37873            cat.slice_indexer(&IndexLabel::from("b"), &IndexLabel::from("c"))?,
37874            1..3
37875        );
37876        assert_eq!(
37877            cat.slice_locs(&IndexLabel::from("a"), &IndexLabel::from("d"))?,
37878            (0, 4)
37879        );
37880
37881        // Non-monotonic rejects.
37882        let unsorted = super::CategoricalIndex::from_values(
37883            vec!["c".to_owned(), "a".to_owned(), "b".to_owned()],
37884            false,
37885        );
37886        assert!(
37887            unsorted
37888                .slice_locs(&IndexLabel::from("a"), &IndexLabel::from("c"))
37889                .is_err()
37890        );
37891        Ok(())
37892    }
37893
37894    #[test]
37895    fn categorical_index_searchsorted_set_ops_match_pandas_cmvs7() -> Result<(), super::IndexError>
37896    {
37897        let cat = super::CategoricalIndex::with_categories(
37898            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
37899            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
37900            true,
37901        )?;
37902
37903        // searchsorted on the sorted utf8 index.
37904        assert_eq!(cat.searchsorted(&IndexLabel::from("b"), "left")?, 1);
37905        assert_eq!(cat.searchsorted(&IndexLabel::from("c"), "right")?, 3);
37906        assert!(cat.searchsorted(&IndexLabel::from("b"), "middle").is_err());
37907
37908        let other = super::CategoricalIndex::from_values(
37909            vec!["b".to_owned(), "c".to_owned(), "d".to_owned()],
37910            false,
37911        );
37912        assert_eq!(
37913            cat.intersection(&other).labels(),
37914            vec![IndexLabel::from("b"), IndexLabel::from("c")].as_slice()
37915        );
37916        assert_eq!(
37917            cat.union(&other).labels(),
37918            vec![
37919                IndexLabel::from("a"),
37920                IndexLabel::from("b"),
37921                IndexLabel::from("c"),
37922                IndexLabel::from("d"),
37923            ]
37924            .as_slice()
37925        );
37926        assert_eq!(
37927            cat.difference(&other).labels(),
37928            vec![IndexLabel::from("a")].as_slice()
37929        );
37930        // symmetric_difference: a (only in cat) + d (only in other).
37931        assert_eq!(
37932            cat.symmetric_difference(&other).labels(),
37933            vec![IndexLabel::from("a"), IndexLabel::from("d")].as_slice()
37934        );
37935        Ok(())
37936    }
37937
37938    #[test]
37939    fn categorical_index_argmax_argmin_match_pandas_d46wi() -> Result<(), super::IndexError> {
37940        let cat = super::CategoricalIndex::with_categories(
37941            vec!["b".to_owned(), "a".to_owned(), "c".to_owned()],
37942            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
37943            true,
37944        )?;
37945        assert_eq!(cat.argmax()?, 2);
37946        assert_eq!(cat.argmin()?, 1);
37947
37948        let empty = super::CategoricalIndex::from_values(Vec::<String>::new(), false);
37949        assert!(empty.argmax().is_err());
37950        assert!(empty.argmin().is_err());
37951        Ok(())
37952    }
37953
37954    #[test]
37955    fn categorical_index_forwarders_match_pandas_e2p82() -> Result<(), super::IndexError> {
37956        let cat = super::CategoricalIndex::with_categories(
37957            vec![
37958                "b".to_owned(),
37959                "a".to_owned(),
37960                "c".to_owned(),
37961                "a".to_owned(),
37962            ],
37963            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
37964            true,
37965        )?;
37966
37967        // argsort: positions sorted by lexicographic label.
37968        let positions = cat.argsort();
37969        let labels: Vec<&IndexLabel> = positions.iter().map(|&p| &cat.labels()[p]).collect();
37970        for w in labels.windows(2) {
37971            assert!(w[0] <= w[1]);
37972        }
37973
37974        // take swaps positions.
37975        let taken = cat.take(&[2, 0, 0])?;
37976        assert_eq!(
37977            taken.labels(),
37978            vec![
37979                IndexLabel::from("c"),
37980                IndexLabel::from("b"),
37981                IndexLabel::from("b")
37982            ]
37983            .as_slice()
37984        );
37985        assert!(matches!(
37986            cat.take(&[7]).unwrap_err(),
37987            super::IndexError::OutOfBounds {
37988                position: 7,
37989                length: 4
37990            }
37991        ));
37992
37993        // isin membership.
37994        assert_eq!(
37995            cat.isin(&[IndexLabel::from("a"), IndexLabel::from("z")]),
37996            vec![false, true, false, true]
37997        );
37998
37999        // get_loc finds first; missing rejects.
38000        assert_eq!(cat.get_loc(&IndexLabel::from("c"))?, 2);
38001        assert!(cat.get_loc(&IndexLabel::from("zzz")).is_err());
38002
38003        // min/max with ordered=true uses category order.
38004        assert_eq!(cat.min(), Some(&IndexLabel::from("a")));
38005        assert_eq!(cat.max(), Some(&IndexLabel::from("c")));
38006
38007        // Empty.
38008        let empty = super::CategoricalIndex::from_values(Vec::<String>::new(), false);
38009        assert_eq!(empty.min(), None);
38010        assert_eq!(empty.max(), None);
38011        assert!(empty.argsort().is_empty());
38012        Ok(())
38013    }
38014
38015    #[test]
38016    fn categorical_index_category_management_match_pandas_zy2vd() -> Result<(), super::IndexError> {
38017        let cat = super::CategoricalIndex::with_categories(
38018            vec!["a".to_owned(), "b".to_owned()],
38019            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
38020            false,
38021        )?;
38022
38023        // as_ordered / as_unordered.
38024        assert!(cat.as_ordered().ordered());
38025        assert!(!cat.as_ordered().as_unordered().ordered());
38026
38027        // add_categories: appends "d".
38028        let added = cat.add_categories(vec!["d".to_owned()])?;
38029        assert_eq!(
38030            added.categories(),
38031            vec![
38032                IndexLabel::from("a"),
38033                IndexLabel::from("b"),
38034                IndexLabel::from("c"),
38035                IndexLabel::from("d")
38036            ]
38037            .as_slice()
38038        );
38039        // Adding a duplicate rejects.
38040        assert!(cat.add_categories(vec!["a".to_owned()]).is_err());
38041
38042        // remove_categories drops "c" (unused).
38043        let pruned = cat.remove_categories(&[IndexLabel::from("c")])?;
38044        assert_eq!(
38045            pruned.categories(),
38046            vec![IndexLabel::from("a"), IndexLabel::from("b")].as_slice()
38047        );
38048        // Removing a category that's still in use makes its labels NaN,
38049        // as pandas' remove_categories.
38050        let removed_in_use = cat.remove_categories(&[IndexLabel::from("a")])?;
38051        assert_eq!(
38052            removed_in_use.labels(),
38053            vec![
38054                IndexLabel::Null(fp_types::NullKind::NaN),
38055                IndexLabel::from("b")
38056            ]
38057            .as_slice()
38058        );
38059        assert!(removed_in_use.labels()[0].is_missing());
38060        assert_eq!(
38061            removed_in_use.categories(),
38062            vec![IndexLabel::from("b"), IndexLabel::from("c")].as_slice()
38063        );
38064        // Removing a missing category rejects.
38065        assert!(cat.remove_categories(&[IndexLabel::from("zzz")]).is_err());
38066
38067        // remove_unused_categories trims "c" automatically.
38068        let trimmed = cat.remove_unused_categories();
38069        assert_eq!(
38070            trimmed.categories(),
38071            vec![IndexLabel::from("a"), IndexLabel::from("b")].as_slice()
38072        );
38073
38074        // set_categories: extending to {a, b, c, d}.
38075        let extended = cat.set_categories(vec![
38076            "a".to_owned(),
38077            "b".to_owned(),
38078            "c".to_owned(),
38079            "d".to_owned(),
38080        ])?;
38081        assert_eq!(extended.categories().len(), 4);
38082        // set_categories dropping a current label's category makes that
38083        // label NaN, as pandas' set_categories.
38084        let narrowed = cat.set_categories(vec!["b".to_owned(), "c".to_owned()])?;
38085        assert_eq!(
38086            narrowed.labels(),
38087            vec![
38088                IndexLabel::Null(fp_types::NullKind::NaN),
38089                IndexLabel::from("b")
38090            ]
38091            .as_slice()
38092        );
38093        assert!(narrowed.labels()[0].is_missing());
38094        assert_eq!(
38095            narrowed.categories(),
38096            vec![IndexLabel::from("b"), IndexLabel::from("c")].as_slice()
38097        );
38098        // A duplicate among the new categories rejects.
38099        assert!(
38100            cat.set_categories(vec!["a".to_owned(), "a".to_owned()])
38101                .is_err()
38102        );
38103
38104        // rename_categories: a→A, b→B, c→C.
38105        let renamed =
38106            cat.rename_categories(vec!["A".to_owned(), "B".to_owned(), "C".to_owned()])?;
38107        assert_eq!(
38108            renamed.labels(),
38109            vec![IndexLabel::from("A"), IndexLabel::from("B")].as_slice()
38110        );
38111        assert_eq!(
38112            renamed.categories(),
38113            vec![
38114                IndexLabel::from("A"),
38115                IndexLabel::from("B"),
38116                IndexLabel::from("C")
38117            ]
38118            .as_slice()
38119        );
38120        // Wrong length rejects.
38121        assert!(cat.rename_categories(vec!["X".to_owned()]).is_err());
38122
38123        // reorder_categories: permutation passes; ordered flag flips.
38124        let reordered =
38125            cat.reorder_categories(vec!["c".to_owned(), "b".to_owned(), "a".to_owned()], true)?;
38126        assert!(reordered.ordered());
38127        assert_eq!(
38128            reordered.categories(),
38129            vec![
38130                IndexLabel::from("c"),
38131                IndexLabel::from("b"),
38132                IndexLabel::from("a")
38133            ]
38134            .as_slice()
38135        );
38136        // Non-permutation rejects.
38137        assert!(
38138            cat.reorder_categories(vec!["a".to_owned(), "b".to_owned(), "x".to_owned()], false)
38139                .is_err()
38140        );
38141        // Duplicate-bearing input rejects.
38142        assert!(
38143            cat.reorder_categories(vec!["a".to_owned(), "a".to_owned(), "b".to_owned()], false)
38144                .is_err()
38145        );
38146
38147        Ok(())
38148    }
38149
38150    #[test]
38151    fn categorical_index_forwarder_methods_match_pandas_i1q1c() {
38152        let labels = vec![
38153            "low".to_owned(),
38154            "high".to_owned(),
38155            "low".to_owned(),
38156            "med".to_owned(),
38157            "high".to_owned(),
38158            "low".to_owned(),
38159        ];
38160        let categorical =
38161            super::CategoricalIndex::from_values(labels.clone(), false).set_name("level");
38162
38163        // unique: first-seen low, high, med.
38164        let unique = categorical.unique();
38165        assert_eq!(
38166            unique.labels(),
38167            vec![
38168                IndexLabel::from("low"),
38169                IndexLabel::from("high"),
38170                IndexLabel::from("med")
38171            ]
38172            .as_slice()
38173        );
38174        assert_eq!(unique.name().map(|n| n.as_str()), Some("level"));
38175
38176        // duplicated keep=First: positions 2, 4, 5 are duplicates of earlier.
38177        let dup_first = categorical.duplicated(super::DuplicateKeep::First);
38178        assert_eq!(dup_first, vec![false, false, true, false, true, true]);
38179
38180        // drop_duplicates returns same as unique.
38181        let dropped = categorical.drop_duplicates();
38182        assert_eq!(dropped.labels(), unique.labels());
38183
38184        // value_counts: low=3, high=2, med=1; total = 6 = len.
38185        let counts = categorical.value_counts();
38186        let total: usize = counts.iter().map(|(_, n)| n).sum();
38187        assert_eq!(total, categorical.len());
38188        let low_count = counts
38189            .iter()
38190            .find_map(|(label, n)| (*label == IndexLabel::from("low")).then_some(*n))
38191            .expect("low should be counted");
38192        assert_eq!(low_count, 3);
38193        // First entry is the most frequent (descending sort).
38194        assert_eq!(counts[0].1, 3);
38195
38196        // factorize: codes encode first-seen positions; uniques == unique().
38197        let (codes, factor_uniques) = categorical.factorize();
38198        assert_eq!(codes.len(), categorical.len());
38199        assert_eq!(codes, vec![0, 1, 0, 2, 1, 0]);
38200        assert_eq!(factor_uniques.labels(), unique.labels());
38201    }
38202
38203    #[test]
38204    fn categorical_index_unique_preserves_categories_and_ordered_i1q1c() {
38205        let labels = vec!["a".to_owned(), "b".to_owned(), "a".to_owned()];
38206        let categories = vec![
38207            IndexLabel::from("a"),
38208            IndexLabel::from("b"),
38209            IndexLabel::from("c"),
38210        ];
38211        let cat = super::CategoricalIndex::with_categories(labels, categories.clone(), true)
38212            .expect("with_categories");
38213        let unique = cat.unique();
38214        assert_eq!(unique.categories(), categories.as_slice());
38215        assert!(unique.ordered());
38216    }
38217
38218    #[test]
38219    fn categorical_index_monotonic_scans_ranks_without_codes_vec_uza04196() {
38220        let increasing = super::CategoricalIndex::with_categories(
38221            vec![
38222                "bronze".to_owned(),
38223                "silver".to_owned(),
38224                "silver".to_owned(),
38225                "gold".to_owned(),
38226            ],
38227            vec!["bronze".to_owned(), "silver".to_owned(), "gold".to_owned()],
38228            true,
38229        )
38230        .expect("categorical index");
38231        assert!(increasing.is_monotonic_increasing());
38232        assert!(!increasing.is_monotonic_decreasing());
38233        let mut increasing_without_codes = increasing.clone();
38234        increasing_without_codes.category_codes = None;
38235        assert_eq!(
38236            increasing_without_codes.is_monotonic_increasing(),
38237            increasing.is_monotonic_increasing()
38238        );
38239        assert_eq!(
38240            increasing_without_codes.is_monotonic_decreasing(),
38241            increasing.is_monotonic_decreasing()
38242        );
38243        let mut increasing_malformed_codes = increasing.clone();
38244        increasing_malformed_codes.category_codes = Some(vec![usize::MAX; increasing.len()]);
38245        assert_eq!(
38246            increasing_malformed_codes.is_monotonic_increasing(),
38247            increasing_without_codes.is_monotonic_increasing()
38248        );
38249        assert_eq!(
38250            increasing_malformed_codes.is_monotonic_decreasing(),
38251            increasing_without_codes.is_monotonic_decreasing()
38252        );
38253
38254        let decreasing = super::CategoricalIndex::with_categories(
38255            vec![
38256                "gold".to_owned(),
38257                "silver".to_owned(),
38258                "silver".to_owned(),
38259                "bronze".to_owned(),
38260            ],
38261            vec!["bronze".to_owned(), "silver".to_owned(), "gold".to_owned()],
38262            true,
38263        )
38264        .expect("categorical index");
38265        assert!(!decreasing.is_monotonic_increasing());
38266        assert!(decreasing.is_monotonic_decreasing());
38267
38268        let invalid = super::CategoricalIndex {
38269            labels: vec![IndexLabel::from("missing"), IndexLabel::from("bronze")],
38270            categories: vec![IndexLabel::from("bronze")],
38271            ordered: true,
38272            name: None,
38273            category_codes: None,
38274        };
38275        let codes = invalid.codes();
38276        assert_eq!(codes, vec![None, Some(0)]);
38277        assert_eq!(
38278            invalid.is_monotonic_increasing(),
38279            codes.windows(2).all(|window| window[0] <= window[1])
38280        );
38281        assert_eq!(
38282            invalid.is_monotonic_decreasing(),
38283            codes.windows(2).all(|window| window[0] >= window[1])
38284        );
38285    }
38286
38287    #[test]
38288    fn categorical_index_unique_nunique_use_rank_bitset_uza04197() {
38289        let categories = vec![
38290            "low".to_owned(),
38291            "med".to_owned(),
38292            "high".to_owned(),
38293            "unused".to_owned(),
38294        ];
38295        let repeated = super::CategoricalIndex::with_categories(
38296            vec![
38297                "low".to_owned(),
38298                "high".to_owned(),
38299                "low".to_owned(),
38300                "med".to_owned(),
38301            ],
38302            categories.clone(),
38303            true,
38304        )
38305        .expect("categorical index");
38306        assert!(repeated.category_rank_unique_scan_is_bounded());
38307        assert!(!repeated.is_unique());
38308        assert!(repeated.has_duplicates());
38309        assert_eq!(repeated.nunique(), 3);
38310
38311        let mut without_codes = repeated.clone();
38312        without_codes.category_codes = None;
38313        assert_eq!(without_codes.is_unique(), repeated.is_unique());
38314        assert_eq!(without_codes.nunique(), repeated.nunique());
38315
38316        let mut malformed_codes = repeated.clone();
38317        malformed_codes.category_codes = Some(vec![usize::MAX; repeated.len()]);
38318        assert_eq!(malformed_codes.is_unique(), repeated.is_unique());
38319        assert_eq!(malformed_codes.nunique(), repeated.nunique());
38320
38321        let unique = super::CategoricalIndex::with_categories(
38322            vec!["high".to_owned(), "low".to_owned(), "med".to_owned()],
38323            categories,
38324            true,
38325        )
38326        .expect("categorical index");
38327        assert!(unique.is_unique());
38328        assert!(!unique.has_duplicates());
38329        assert_eq!(unique.nunique(), 3);
38330
38331        let invalid = super::CategoricalIndex {
38332            labels: vec![
38333                IndexLabel::from("ghost"),
38334                IndexLabel::from("low"),
38335                IndexLabel::from("ghost"),
38336                IndexLabel::from("other"),
38337                IndexLabel::from("low"),
38338            ],
38339            categories: vec![IndexLabel::from("low")],
38340            ordered: false,
38341            name: None,
38342            category_codes: None,
38343        };
38344        let mut oracle = std::collections::HashSet::<&IndexLabel>::new();
38345        for label in invalid.labels() {
38346            oracle.insert(label);
38347        }
38348        assert_eq!(invalid.nunique(), oracle.len());
38349        assert_eq!(invalid.is_unique(), oracle.len() == invalid.len());
38350
38351        let mut large_categories = vec![IndexLabel::from("a"), IndexLabel::from("b")];
38352        large_categories.extend((0..50).map(|value| IndexLabel::Utf8(format!("unused-{value}"))));
38353        let sparse = super::CategoricalIndex {
38354            labels: vec![
38355                IndexLabel::from("a"),
38356                IndexLabel::from("b"),
38357                IndexLabel::from("a"),
38358            ],
38359            categories: large_categories,
38360            ordered: false,
38361            name: None,
38362            category_codes: None,
38363        };
38364        assert!(!sparse.category_rank_unique_scan_is_bounded());
38365        assert!(!sparse.is_unique());
38366        assert_eq!(sparse.nunique(), 2);
38367    }
38368
38369    #[test]
38370    fn categorical_index_duplicated_uses_rank_bitset_uza04198() {
38371        fn assert_matches_flat(index: &super::CategoricalIndex) {
38372            for keep in [
38373                super::DuplicateKeep::First,
38374                super::DuplicateKeep::Last,
38375                super::DuplicateKeep::None,
38376            ] {
38377                assert_eq!(
38378                    index.duplicated(keep),
38379                    index.to_flat_index().duplicated(keep)
38380                );
38381            }
38382        }
38383
38384        let categories = vec![
38385            "low".to_owned(),
38386            "med".to_owned(),
38387            "high".to_owned(),
38388            "unused".to_owned(),
38389        ];
38390        let repeated = super::CategoricalIndex::with_categories(
38391            vec![
38392                "low".to_owned(),
38393                "high".to_owned(),
38394                "low".to_owned(),
38395                "med".to_owned(),
38396                "high".to_owned(),
38397                "low".to_owned(),
38398            ],
38399            categories,
38400            true,
38401        )
38402        .expect("categorical index");
38403        assert!(repeated.category_rank_unique_scan_is_bounded());
38404        assert_eq!(
38405            repeated.duplicated(super::DuplicateKeep::First),
38406            vec![false, false, true, false, true, true]
38407        );
38408        assert_eq!(
38409            repeated.duplicated(super::DuplicateKeep::Last),
38410            vec![true, true, true, false, false, false]
38411        );
38412        assert_eq!(
38413            repeated.duplicated(super::DuplicateKeep::None),
38414            vec![true, true, true, false, true, true]
38415        );
38416        assert_matches_flat(&repeated);
38417        let same_public_state_without_sidecar = super::CategoricalIndex {
38418            labels: repeated.labels().to_vec(),
38419            categories: repeated.categories().to_vec(),
38420            ordered: repeated.ordered(),
38421            name: repeated.name().cloned(),
38422            category_codes: None,
38423        };
38424        assert_matches_flat(&same_public_state_without_sidecar);
38425        for keep in [
38426            super::DuplicateKeep::First,
38427            super::DuplicateKeep::Last,
38428            super::DuplicateKeep::None,
38429        ] {
38430            assert_eq!(
38431                repeated.duplicated(keep),
38432                same_public_state_without_sidecar.duplicated(keep)
38433            );
38434        }
38435        let malformed_sidecar = super::CategoricalIndex {
38436            labels: repeated.labels().to_vec(),
38437            categories: repeated.categories().to_vec(),
38438            ordered: repeated.ordered(),
38439            name: repeated.name().cloned(),
38440            category_codes: Some(vec![usize::MAX; repeated.len()]),
38441        };
38442        assert_matches_flat(&malformed_sidecar);
38443        for keep in [
38444            super::DuplicateKeep::First,
38445            super::DuplicateKeep::Last,
38446            super::DuplicateKeep::None,
38447        ] {
38448            assert_eq!(
38449                repeated.duplicated(keep),
38450                malformed_sidecar.duplicated(keep)
38451            );
38452        }
38453
38454        let invalid = super::CategoricalIndex {
38455            labels: vec![
38456                IndexLabel::from("ghost"),
38457                IndexLabel::from("low"),
38458                IndexLabel::from("ghost"),
38459                IndexLabel::from("other"),
38460                IndexLabel::from("low"),
38461            ],
38462            categories: vec![IndexLabel::from("low")],
38463            ordered: false,
38464            name: None,
38465            category_codes: None,
38466        };
38467        assert_matches_flat(&invalid);
38468
38469        let mut large_categories = vec![IndexLabel::from("a"), IndexLabel::from("b")];
38470        large_categories.extend((0..50).map(|value| IndexLabel::Utf8(format!("unused-{value}"))));
38471        let sparse = super::CategoricalIndex {
38472            labels: vec![
38473                IndexLabel::from("a"),
38474                IndexLabel::from("b"),
38475                IndexLabel::from("a"),
38476                IndexLabel::from("b"),
38477            ],
38478            categories: large_categories,
38479            ordered: false,
38480            name: None,
38481            category_codes: None,
38482        };
38483        assert!(!sparse.category_rank_unique_scan_is_bounded());
38484        assert_matches_flat(&sparse);
38485    }
38486
38487    #[test]
38488    fn categorical_index_unique_drop_duplicates_use_rank_bitset_uza04199() {
38489        fn first_seen_oracle(labels: &[IndexLabel]) -> Vec<IndexLabel> {
38490            let mut seen = std::collections::HashSet::<&IndexLabel>::new();
38491            let mut unique = Vec::new();
38492            for label in labels {
38493                if seen.insert(label) {
38494                    unique.push(label.clone());
38495                }
38496            }
38497            unique
38498        }
38499
38500        fn assert_unique_matches_oracle(index: &super::CategoricalIndex) {
38501            let expected = first_seen_oracle(index.labels());
38502            let unique = index.unique();
38503            assert_eq!(unique.labels(), expected.as_slice());
38504            assert_eq!(unique.categories(), index.categories());
38505            assert_eq!(unique.ordered(), index.ordered());
38506            assert_eq!(unique.name(), index.name());
38507            assert_eq!(index.drop_duplicates().labels(), unique.labels());
38508        }
38509
38510        let categories = vec![
38511            "low".to_owned(),
38512            "med".to_owned(),
38513            "high".to_owned(),
38514            "unused".to_owned(),
38515        ];
38516        let repeated = super::CategoricalIndex::with_categories(
38517            vec![
38518                "low".to_owned(),
38519                "high".to_owned(),
38520                "low".to_owned(),
38521                "med".to_owned(),
38522                "high".to_owned(),
38523                "low".to_owned(),
38524            ],
38525            categories,
38526            true,
38527        )
38528        .expect("categorical index")
38529        .set_name("priority");
38530        assert!(repeated.category_rank_unique_scan_is_bounded());
38531        assert_unique_matches_oracle(&repeated);
38532        assert_eq!(
38533            repeated.unique().category_codes.as_deref(),
38534            Some([0usize, 2, 1].as_slice())
38535        );
38536
38537        let mut without_codes = repeated.clone();
38538        without_codes.category_codes = None;
38539        assert_unique_matches_oracle(&without_codes);
38540
38541        let mut malformed_codes = repeated.clone();
38542        malformed_codes.category_codes = Some(vec![usize::MAX; repeated.len()]);
38543        assert_unique_matches_oracle(&malformed_codes);
38544
38545        let invalid = super::CategoricalIndex {
38546            labels: vec![
38547                IndexLabel::from("ghost"),
38548                IndexLabel::from("low"),
38549                IndexLabel::from("ghost"),
38550                IndexLabel::from("other"),
38551                IndexLabel::from("low"),
38552            ],
38553            categories: vec![IndexLabel::from("low")],
38554            ordered: true,
38555            name: Some("dirty".into()),
38556            category_codes: None,
38557        };
38558        assert!(invalid.category_rank_unique_scan_is_bounded());
38559        assert_unique_matches_oracle(&invalid);
38560
38561        let mut large_categories = vec![IndexLabel::from("a"), IndexLabel::from("b")];
38562        large_categories.extend((0..50).map(|value| IndexLabel::Utf8(format!("unused-{value}"))));
38563        let sparse = super::CategoricalIndex {
38564            labels: vec![
38565                IndexLabel::from("a"),
38566                IndexLabel::from("b"),
38567                IndexLabel::from("a"),
38568                IndexLabel::from("b"),
38569            ],
38570            categories: large_categories,
38571            ordered: false,
38572            name: None,
38573            category_codes: None,
38574        };
38575        assert!(!sparse.category_rank_unique_scan_is_bounded());
38576        assert_unique_matches_oracle(&sparse);
38577    }
38578
38579    #[test]
38580    fn categorical_index_value_counts_use_rank_counts_uza04200() {
38581        fn value_counts_oracle(labels: &[IndexLabel]) -> Vec<(IndexLabel, usize)> {
38582            let mut order = Vec::<&IndexLabel>::new();
38583            let mut counts = std::collections::HashMap::<&IndexLabel, usize>::new();
38584            for label in labels {
38585                let entry = counts.entry(label).or_insert_with(|| {
38586                    order.push(label);
38587                    0
38588                });
38589                *entry += 1;
38590            }
38591            let mut pairs: Vec<(IndexLabel, usize)> = order
38592                .iter()
38593                .map(|label| {
38594                    let label = *label;
38595                    (label.clone(), counts[label])
38596                })
38597                .collect();
38598            pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
38599            pairs
38600        }
38601
38602        fn assert_value_counts_matches_oracle(index: &super::CategoricalIndex) {
38603            assert_eq!(index.value_counts(), value_counts_oracle(index.labels()));
38604        }
38605
38606        let categories = vec![
38607            "low".to_owned(),
38608            "med".to_owned(),
38609            "high".to_owned(),
38610            "unused".to_owned(),
38611        ];
38612        let repeated = super::CategoricalIndex::with_categories(
38613            vec![
38614                "low".to_owned(),
38615                "high".to_owned(),
38616                "low".to_owned(),
38617                "med".to_owned(),
38618                "high".to_owned(),
38619                "low".to_owned(),
38620            ],
38621            categories,
38622            true,
38623        )
38624        .expect("categorical index");
38625        assert!(repeated.category_rank_unique_scan_is_bounded());
38626        assert_eq!(
38627            repeated.value_counts(),
38628            vec![
38629                (IndexLabel::from("low"), 3),
38630                (IndexLabel::from("high"), 2),
38631                (IndexLabel::from("med"), 1),
38632            ]
38633        );
38634        assert_value_counts_matches_oracle(&repeated);
38635        let same_public_state_without_sidecar = super::CategoricalIndex {
38636            labels: repeated.labels().to_vec(),
38637            categories: repeated.categories().to_vec(),
38638            ordered: repeated.ordered(),
38639            name: repeated.name().cloned(),
38640            category_codes: None,
38641        };
38642        assert_eq!(
38643            repeated.value_counts(),
38644            same_public_state_without_sidecar.value_counts()
38645        );
38646        assert_value_counts_matches_oracle(&same_public_state_without_sidecar);
38647        let malformed_sidecar = super::CategoricalIndex {
38648            labels: repeated.labels().to_vec(),
38649            categories: repeated.categories().to_vec(),
38650            ordered: repeated.ordered(),
38651            name: repeated.name().cloned(),
38652            category_codes: Some(vec![usize::MAX; repeated.len()]),
38653        };
38654        assert_eq!(repeated.value_counts(), malformed_sidecar.value_counts());
38655        assert_value_counts_matches_oracle(&malformed_sidecar);
38656
38657        let tied = super::CategoricalIndex::with_categories(
38658            vec![
38659                "b".to_owned(),
38660                "a".to_owned(),
38661                "b".to_owned(),
38662                "a".to_owned(),
38663                "c".to_owned(),
38664            ],
38665            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
38666            false,
38667        )
38668        .expect("categorical index");
38669        assert_eq!(
38670            tied.value_counts(),
38671            vec![
38672                (IndexLabel::from("b"), 2),
38673                (IndexLabel::from("a"), 2),
38674                (IndexLabel::from("c"), 1),
38675            ]
38676        );
38677        assert_value_counts_matches_oracle(&tied);
38678
38679        let invalid = super::CategoricalIndex {
38680            labels: vec![
38681                IndexLabel::from("ghost"),
38682                IndexLabel::from("low"),
38683                IndexLabel::from("ghost"),
38684                IndexLabel::from("other"),
38685                IndexLabel::from("low"),
38686            ],
38687            categories: vec![IndexLabel::from("low")],
38688            ordered: false,
38689            name: None,
38690            category_codes: None,
38691        };
38692        assert!(invalid.category_rank_unique_scan_is_bounded());
38693        assert_eq!(
38694            invalid.value_counts(),
38695            vec![
38696                (IndexLabel::from("ghost"), 2),
38697                (IndexLabel::from("low"), 2),
38698                (IndexLabel::from("other"), 1),
38699            ]
38700        );
38701        assert_value_counts_matches_oracle(&invalid);
38702
38703        let mut large_categories = vec![IndexLabel::from("a"), IndexLabel::from("b")];
38704        large_categories.extend((0..50).map(|value| IndexLabel::Utf8(format!("unused-{value}"))));
38705        let sparse = super::CategoricalIndex {
38706            labels: vec![
38707                IndexLabel::from("a"),
38708                IndexLabel::from("b"),
38709                IndexLabel::from("a"),
38710                IndexLabel::from("b"),
38711            ],
38712            categories: large_categories,
38713            ordered: false,
38714            name: None,
38715            category_codes: None,
38716        };
38717        assert!(!sparse.category_rank_unique_scan_is_bounded());
38718        assert_value_counts_matches_oracle(&sparse);
38719    }
38720
38721    #[test]
38722    fn categorical_index_factorize_uses_rank_codes_uza04201() {
38723        fn factorize_oracle(labels: &[IndexLabel]) -> (Vec<isize>, Vec<IndexLabel>) {
38724            let mut positions = std::collections::HashMap::<&IndexLabel, isize>::new();
38725            let mut uniques = Vec::<IndexLabel>::new();
38726            let mut codes = Vec::<isize>::with_capacity(labels.len());
38727            for label in labels {
38728                if let Some(code) = positions.get(label) {
38729                    codes.push(*code);
38730                } else {
38731                    let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
38732                    positions.insert(label, code);
38733                    uniques.push(label.clone());
38734                    codes.push(code);
38735                }
38736            }
38737            (codes, uniques)
38738        }
38739
38740        fn assert_factorize_matches_oracle(index: &super::CategoricalIndex) {
38741            let (expected_codes, expected_uniques) = factorize_oracle(index.labels());
38742            let (codes, uniques) = index.factorize();
38743            assert_eq!(codes, expected_codes);
38744            assert_eq!(uniques.labels(), expected_uniques.as_slice());
38745            assert_eq!(uniques.categories(), index.categories());
38746            assert_eq!(uniques.ordered(), index.ordered());
38747            assert_eq!(uniques.name(), index.name());
38748        }
38749
38750        let categories = vec![
38751            "low".to_owned(),
38752            "med".to_owned(),
38753            "high".to_owned(),
38754            "unused".to_owned(),
38755        ];
38756        let repeated = super::CategoricalIndex::with_categories(
38757            vec![
38758                "low".to_owned(),
38759                "high".to_owned(),
38760                "low".to_owned(),
38761                "med".to_owned(),
38762                "high".to_owned(),
38763                "low".to_owned(),
38764            ],
38765            categories,
38766            true,
38767        )
38768        .expect("categorical index")
38769        .set_name("priority");
38770        assert!(repeated.category_rank_unique_scan_is_bounded());
38771        let (codes, uniques) = repeated.factorize();
38772        assert_eq!(codes, vec![0, 1, 0, 2, 1, 0]);
38773        assert_eq!(
38774            uniques.labels(),
38775            vec![
38776                IndexLabel::from("low"),
38777                IndexLabel::from("high"),
38778                IndexLabel::from("med")
38779            ]
38780            .as_slice()
38781        );
38782        assert_factorize_matches_oracle(&repeated);
38783        let same_public_state_without_sidecar = super::CategoricalIndex {
38784            labels: repeated.labels().to_vec(),
38785            categories: repeated.categories().to_vec(),
38786            ordered: repeated.ordered(),
38787            name: repeated.name().cloned(),
38788            category_codes: None,
38789        };
38790        assert_eq!(repeated, same_public_state_without_sidecar);
38791        assert_factorize_matches_oracle(&same_public_state_without_sidecar);
38792
38793        let invalid = super::CategoricalIndex {
38794            labels: vec![
38795                IndexLabel::from("ghost"),
38796                IndexLabel::from("low"),
38797                IndexLabel::from("ghost"),
38798                IndexLabel::from("other"),
38799                IndexLabel::from("low"),
38800            ],
38801            categories: vec![IndexLabel::from("low")],
38802            ordered: true,
38803            name: Some("dirty".into()),
38804            category_codes: None,
38805        };
38806        assert!(invalid.category_rank_unique_scan_is_bounded());
38807        assert_factorize_matches_oracle(&invalid);
38808
38809        let mut large_categories = vec![IndexLabel::from("a"), IndexLabel::from("b")];
38810        large_categories.extend((0..50).map(|value| IndexLabel::Utf8(format!("unused-{value}"))));
38811        let sparse = super::CategoricalIndex {
38812            labels: vec![
38813                IndexLabel::from("a"),
38814                IndexLabel::from("b"),
38815                IndexLabel::from("a"),
38816                IndexLabel::from("b"),
38817            ],
38818            categories: large_categories,
38819            ordered: false,
38820            name: None,
38821            category_codes: None,
38822        };
38823        assert!(!sparse.category_rank_unique_scan_is_bounded());
38824        assert_factorize_matches_oracle(&sparse);
38825    }
38826
38827    #[test]
38828    fn timedelta_index_forwarder_methods_match_index_vq4pf() -> Result<(), super::IndexError> {
38829        let a: i64 = 1_000;
38830        let b: i64 = 2_000;
38831        let c: i64 = 3_000;
38832        let nat = fp_types::Timedelta::NAT;
38833
38834        // a, c, b, a, NAT, c (duplicates + NAT)
38835        let td = super::TimedeltaIndex::new(vec![a, c, b, a, nat, c]);
38836
38837        assert_eq!(td.argmax()?, 1);
38838        assert_eq!(td.argmin()?, 0);
38839
38840        let positions = td.argsort();
38841        assert_eq!(positions.len(), td.len());
38842
38843        let unique = td.unique()?;
38844        assert_eq!(unique.values(), vec![Some(a), Some(c), Some(b), None]);
38845
38846        let (codes, uniques) = td.factorize()?;
38847        assert_eq!(codes.len(), td.len());
38848        assert_eq!(uniques.values(), vec![Some(a), Some(c), Some(b)]);
38849        assert_eq!(codes[4], -1);
38850
38851        let counts = td.value_counts();
38852        let total: usize = counts.iter().map(|(_, n)| n).sum();
38853        assert_eq!(total, 5); // NAT dropped
38854
38855        let dup_first = td.duplicated(super::DuplicateKeep::First);
38856        assert_eq!(dup_first, vec![false, false, false, true, false, true]);
38857
38858        let deduped = td.drop_duplicates()?;
38859        assert_eq!(deduped.values(), vec![Some(a), Some(c), Some(b), None]);
38860
38861        let dropped = td.dropna();
38862        assert_eq!(
38863            dropped.values(),
38864            vec![Some(a), Some(c), Some(b), Some(a), Some(c)]
38865        );
38866        Ok(())
38867    }
38868
38869    #[test]
38870    fn timedelta_index_argmax_argmin_reject_empty_vq4pf() {
38871        let empty = super::TimedeltaIndex::new(vec![]);
38872        let err_max = empty.argmax().unwrap_err();
38873        assert!(matches!(
38874            err_max,
38875            super::IndexError::InvalidArgument(ref message)
38876                if message == "attempt to get argmax of an empty sequence"
38877        ));
38878        let err_min = empty.argmin().unwrap_err();
38879        assert!(matches!(
38880            err_min,
38881            super::IndexError::InvalidArgument(ref message)
38882                if message == "attempt to get argmin of an empty sequence"
38883        ));
38884
38885        let only_nat =
38886            super::TimedeltaIndex::new(vec![fp_types::Timedelta::NAT, fp_types::Timedelta::NAT]);
38887        assert!(only_nat.argmax().is_err());
38888        assert!(only_nat.argmin().is_err());
38889    }
38890
38891    #[test]
38892    fn timedelta_index_dropna_preserves_name_vq4pf() {
38893        let td =
38894            super::TimedeltaIndex::new(vec![fp_types::Timedelta::NAT, 0_i64]).set_name("delta");
38895        let dropped = td.dropna();
38896        assert_eq!(dropped.values(), vec![Some(0)]);
38897        assert_eq!(dropped.name().map(|n| n.as_str()), Some("delta"));
38898    }
38899
38900    #[test]
38901    fn datetime_index_forwarder_methods_match_index_z9guv() -> Result<(), super::IndexError> {
38902        const NS: i64 = 1_000_000_000;
38903        let a = 1_704_067_200_i64 * NS;
38904        let b = 1_705_276_800_i64 * NS;
38905        let c = 1_706_140_800_i64 * NS;
38906
38907        // a, c, b, a, NAT, c (duplicates + NAT to exercise every branch).
38908        let dt = super::DatetimeIndex::new(vec![a, c, b, a, i64::MIN, c]);
38909
38910        // argmax / argmin skip NAT to match pandas skipna=True default.
38911        assert_eq!(dt.argmax()?, 1); // c at position 1 is first-seen max
38912        assert_eq!(dt.argmin()?, 0); // a at position 0 is first-seen min
38913
38914        // argsort returns positions in ascending label order (NAT sorts lowest
38915        // because i64::MIN < every datetime). Stable on ties.
38916        let positions = dt.argsort();
38917        assert_eq!(positions.len(), dt.len());
38918        let sorted_labels: Vec<&super::IndexLabel> = positions
38919            .iter()
38920            .map(|&p| &dt.as_index().labels()[p])
38921            .collect();
38922        for w in sorted_labels.windows(2) {
38923            assert!(w[0].cmp(w[1]).is_le());
38924        }
38925
38926        let unique = dt.unique()?;
38927        // First-seen order including NAT: a, c, b, NAT.
38928        assert_eq!(unique.values(), vec![Some(a), Some(c), Some(b), None]);
38929
38930        let (codes, uniques) = dt.factorize()?;
38931        assert_eq!(codes.len(), dt.len());
38932        // factorize skips NAT in the uniques and emits -1 codes for NAT inputs
38933        // (matches pandas).
38934        assert_eq!(uniques.values(), vec![Some(a), Some(c), Some(b)]);
38935        // Position 4 is the NAT input.
38936        assert_eq!(codes[4], -1);
38937
38938        let counts = dt.value_counts();
38939        // value_counts drops NAT by default (matches pandas dropna=True), so
38940        // total = 5: a:2, c:2, b:1.
38941        let total_count: usize = counts.iter().map(|(_, n)| n).sum();
38942        assert_eq!(total_count, 5);
38943        let a_count = counts
38944            .iter()
38945            .find_map(|(label, n)| match label {
38946                super::IndexLabel::Datetime64(nanos) if *nanos == a => Some(*n),
38947                _ => None,
38948            })
38949            .expect("a should be counted");
38950        assert_eq!(a_count, 2);
38951
38952        let dup_first = dt.duplicated(super::DuplicateKeep::First);
38953        // Positions 3 (second a) and 5 (second c) are duplicates.
38954        assert_eq!(dup_first, vec![false, false, false, true, false, true]);
38955
38956        let deduped = dt.drop_duplicates()?;
38957        // drop_duplicates preserves the NAT entry — only literal duplicates go.
38958        assert_eq!(deduped.values(), vec![Some(a), Some(c), Some(b), None]);
38959
38960        let dropped = dt.dropna();
38961        assert_eq!(
38962            dropped.values(),
38963            vec![Some(a), Some(c), Some(b), Some(a), Some(c)]
38964        );
38965        Ok(())
38966    }
38967
38968    #[test]
38969    fn datetime_index_argmax_argmin_reject_empty_z9guv() {
38970        let empty = super::DatetimeIndex::new(vec![]);
38971        let err_max = empty.argmax().unwrap_err();
38972        assert!(matches!(
38973            err_max,
38974            super::IndexError::InvalidArgument(ref message)
38975                if message == "attempt to get argmax of an empty sequence"
38976        ));
38977        let err_min = empty.argmin().unwrap_err();
38978        assert!(matches!(
38979            err_min,
38980            super::IndexError::InvalidArgument(ref message)
38981                if message == "attempt to get argmin of an empty sequence"
38982        ));
38983        assert!(empty.argsort().is_empty());
38984        assert!(empty.dropna().is_empty());
38985    }
38986
38987    #[test]
38988    fn datetime_index_dropna_preserves_name_z9guv() {
38989        let dt = super::DatetimeIndex::new(vec![i64::MIN, 0_i64, i64::MIN]).set_name("ts");
38990        let dropped = dt.dropna();
38991        assert_eq!(dropped.values(), vec![Some(0)]);
38992        assert_eq!(dropped.name().map(|n| n.as_str()), Some("ts"));
38993    }
38994
38995    #[test]
38996    fn datetime_index_asi8_round_trips_nanos_teeck() {
38997        const NS: i64 = 1_000_000_000;
38998        let total: i64 = 1_704_067_200_i64 * NS + 123;
38999        let dt = super::DatetimeIndex::new(vec![total, i64::MIN, 0]);
39000        assert_eq!(dt.asi8(), vec![total, i64::MIN, 0]);
39001
39002        let empty = super::DatetimeIndex::new(vec![]);
39003        assert!(empty.asi8().is_empty());
39004    }
39005
39006    #[test]
39007    fn datetime_index_strftime_formats_each_label_teeck() {
39008        const NS: i64 = 1_000_000_000;
39009        // 2024-01-15T12:34:56.789Z:
39010        //   2024-01-01 00:00:00Z = 1704067200 sec.
39011        //   + 14 * 86400 = 1209600  -> 2024-01-15 00:00:00 = 1705276800
39012        //   + 12*3600 + 34*60 + 56  -> 1705322096
39013        //   * 1e9 + 789_000_000 ns
39014        let with_ms: i64 = 1_705_322_096_i64 * NS + 789_000_000;
39015        let dt = super::DatetimeIndex::new(vec![with_ms, i64::MIN]);
39016        // TEST-CHANGE: this used chrono's `%.3f`, which pandas (Python's
39017        // strftime) does not know - it prints '%.3f' as written (measured,
39018        // pandas 2.2.3); Python's `%f` is six-digit microseconds.
39019        assert_eq!(
39020            dt.strftime("%Y-%m-%dT%H:%M:%S.%f"),
39021            vec![Some("2024-01-15T12:34:56.789000".to_owned()), None]
39022        );
39023        assert_eq!(
39024            dt.strftime("%Y-%m-%dT%H:%M:%S%.3f"),
39025            vec![Some("2024-01-15T12:34:56%.3f".to_owned()), None]
39026        );
39027    }
39028
39029    #[test]
39030    fn range_span_marks_a_range_index_and_slices_like_python_fvsao_18() {
39031        // The default index is pandas' RangeIndex, kept by a clone and a
39032        // slice; an Index that merely holds 0..n is not one.
39033        let default = Index::default_range(4);
39034        assert_eq!(default.range_span(), Some((0, 4, 1)));
39035        assert_eq!(default.clone().range_span(), Some((0, 4, 1)));
39036        assert_eq!(Index::from_i64(vec![0, 1, 2, 3]).range_span(), None);
39037        assert_eq!(default.slice(1, 2).range_span(), Some((1, 3, 1)));
39038        assert_eq!(default.slice(9, 2).range_span(), Some((4, 4, 1)));
39039        // A take, even of every position in order, is a plain Index.
39040        assert_eq!(default.take(&[0, 1, 2, 3]).range_span(), None);
39041        // Python's range slicing: range(4)[1::2] is range(1, 4, 2), [::-1]
39042        // range(3, -1, -1); a range(2, 11, 3) slice scales by its step.
39043        assert_eq!(default.sliced_range_span(1, 4, 2), Some((1, 4, 2)));
39044        assert_eq!(default.sliced_range_span(3, -1, -1), Some((3, -1, -1)));
39045        let stepped = Index::from_range(2, 11, 3);
39046        assert_eq!(stepped.range_span(), Some((2, 11, 3)));
39047        assert_eq!(stepped.sliced_range_span(2, -1, -1), Some((8, -1, -3)));
39048        assert_eq!(Index::from_i64(vec![0, 2]).sliced_range_span(0, 2, 1), None);
39049        // A span that no longer describes the labels answers nothing.
39050        let stale = Index::from_i64(vec![0, 1, 5]).with_range_span(Some((0, 3, 1)));
39051        assert_eq!(stale.range_span(), None);
39052        let short = Index::from_i64(vec![0, 1]).with_range_span(Some((0, 3, 1)));
39053        assert_eq!(short.range_span(), None);
39054        // The labels' own range, the stop one step past the last.
39055        assert_eq!(
39056            Index::from_i64(vec![8, 5, 2]).int64_range_span(),
39057            Some((8, -1, -3))
39058        );
39059        assert_eq!(Index::from_i64(vec![0, 1, 3]).int64_range_span(), None);
39060        // Equality ignores the mark.
39061        assert_eq!(default, Index::from_i64(vec![0, 1, 2, 3]));
39062    }
39063
39064    #[test]
39065    fn datetime_index_freq_is_carried_and_inferred_like_pandas_fvsao_61() {
39066        // Live pandas 2.2.3 (br-frankenpandas-rc0923-epic-python-honest-dropin-fvsao.61).
39067        const DAY: i64 = 86_400_000_000_000;
39068        let canonical = |alias: &str| super::canonical_freq(alias);
39069        assert_eq!(canonical("W").as_deref(), Some("W-SUN"));
39070        assert_eq!(canonical("12H").as_deref(), Some("12h"));
39071        assert_eq!(canonical("M").as_deref(), Some("ME"));
39072        assert_eq!(canonical("Q").as_deref(), Some("QE-DEC"));
39073        assert_eq!(canonical("QS").as_deref(), Some("QS-JAN"));
39074        assert_eq!(canonical("SME").as_deref(), Some("SME-15"));
39075        assert_eq!(canonical("T").as_deref(), Some("min"));
39076        assert_eq!(canonical("1D").as_deref(), Some("D"));
39077        assert_eq!(canonical("D1"), None);
39078        assert_eq!(super::scale_freq("D", 2).as_deref(), Some("2D"));
39079        assert_eq!(super::scale_freq("D", -1).as_deref(), Some("-1D"));
39080        // pandas' Tick * float / Tick / number (b9lc7).
39081        let times = |freq: &str, factor: f64| super::multiply_tick_freq(freq, factor);
39082        assert_eq!(times("D", 1.5), Ok(Some("36h".to_owned())));
39083        assert_eq!(times("D", 0.1), Ok(Some("144min".to_owned())));
39084        assert_eq!(times("s", 0.0015), Ok(Some("1500us".to_owned())));
39085        assert_eq!(times("D", -0.5), Ok(Some("-12h".to_owned())));
39086        assert_eq!(times("3h", 2.0), Ok(Some("6h".to_owned())));
39087        assert_eq!(times("D", 0.0), Ok(None));
39088        assert_eq!(times("D", f64::NAN), Ok(None));
39089        assert_eq!(times("ME", 1.5), Ok(None));
39090        assert!(times("ns", 1.5).is_err());
39091        let over = |freq: &str, divisor: f64| super::divide_tick_freq(freq, divisor);
39092        assert_eq!(over("D", 2.0).as_deref(), Some("12h"));
39093        assert_eq!(over("D", 7.0).as_deref(), Some("12342s"));
39094        assert_eq!(over("-1D", 7.0).as_deref(), Some("-12342s"));
39095        assert_eq!(over("h", 7.0).as_deref(), Some("514s"));
39096        assert_eq!(over("D", 0.5).as_deref(), Some("2D"));
39097        assert_eq!(over("D", 2.5).as_deref(), Some("576min"));
39098        assert_eq!(over("5us", 2.0).as_deref(), Some("2us"));
39099        assert_eq!(over("3h", -2.0).as_deref(), Some("-90min"));
39100        // A second / 3 truncates to nothing at second resolution.
39101        assert_eq!(over("s", 3.0), None);
39102        assert_eq!(over("ns", 2.0), None);
39103        assert_eq!(over("D", 0.0), None);
39104        assert_eq!(over("W-SUN", 2.0), None);
39105
39106        let days = |values: &[&str]| {
39107            let nanos: Vec<i64> = values
39108                .iter()
39109                .map(|text| fp_types::Timestamp::parse(text).unwrap().nanos)
39110                .collect();
39111            DatetimeIndex::new(nanos)
39112        };
39113        let infer = |values: &[&str]| days(values).inferred_freq();
39114        assert_eq!(
39115            infer(&["2024-01-01", "2024-01-02", "2024-01-03"]).as_deref(),
39116            Some("D")
39117        );
39118        assert_eq!(
39119            infer(&["2024-01-01", "2024-02-01", "2024-03-01"]).as_deref(),
39120            Some("MS")
39121        );
39122        assert_eq!(
39123            infer(&["2024-01-31", "2024-02-29", "2024-03-31"]).as_deref(),
39124            Some("ME")
39125        );
39126        // pandas' quarter naming quirk: a January-April-July run is QS-OCT.
39127        assert_eq!(
39128            infer(&["2024-01-01", "2024-04-01", "2024-07-01"]).as_deref(),
39129            Some("QS-OCT")
39130        );
39131        assert_eq!(
39132            infer(&["2024-01-07", "2024-01-14", "2024-01-21"]).as_deref(),
39133            Some("W-SUN")
39134        );
39135        assert_eq!(
39136            infer(&["2024-01-04", "2024-01-05", "2024-01-08", "2024-01-09"]).as_deref(),
39137            Some("B")
39138        );
39139        assert_eq!(
39140            infer(&["2024-01-03", "2024-01-02", "2024-01-01"]).as_deref(),
39141            Some("-1D")
39142        );
39143        // NEGATIVES: an irregular run and fewer than three labels have none.
39144        assert_eq!(infer(&["2024-01-01", "2024-01-02", "2024-01-04"]), None);
39145        assert_eq!(infer(&["2024-01-01", "2024-01-02"]), None);
39146
39147        let range = DatetimeIndex::new((0..6).map(|day| day * DAY).collect())
39148            .with_freq(Some("D".to_owned()));
39149        assert_eq!(range.freq().as_deref(), Some("D"));
39150        // pandas' take reads positions in one constant step as a slice: the
39151        // freq scales by the step; a gap or a repeat drops it.
39152        assert_eq!(range.take(&[1, 2, 3]).unwrap().freq().as_deref(), Some("D"));
39153        assert_eq!(range.take(&[0, 2]).unwrap().freq().as_deref(), Some("2D"));
39154        assert_eq!(range.take(&[3, 2]).unwrap().freq().as_deref(), Some("-1D"));
39155        assert_eq!(range.take(&[0, 1, 3]).unwrap().freq(), None);
39156        assert_eq!(range.take(&[0, 0]).unwrap().freq(), None);
39157        assert_eq!(
39158            range.as_index().slice(2, 3).freq(),
39159            Some("D"),
39160            "a slice keeps the freq"
39161        );
39162        assert_eq!(range.shift(1, DAY).freq().as_deref(), Some("D"));
39163        // pandas keeps it through tz_localize only for UTC.
39164        assert_eq!(
39165            range.tz_localize(Some("UTC")).unwrap().freq().as_deref(),
39166            Some("D")
39167        );
39168        assert_eq!(range.tz_localize(Some("US/Eastern")).unwrap().freq(), None);
39169        // Adjacent runs union into one run; equality ignores the freq.
39170        let (head, tail) = (
39171            range.take(&[0, 1, 2]).unwrap(),
39172            range.take(&[3, 4, 5]).unwrap(),
39173        );
39174        assert_eq!(head.union(&tail).freq().as_deref(), Some("D"));
39175        assert_eq!(
39176            range,
39177            DatetimeIndex::new((0..6).map(|day| day * DAY).collect())
39178        );
39179    }
39180
39181    #[test]
39182    fn format_datetime_ns_keeps_subsecond_and_pre_epoch_precision_dt64fmt() {
39183        const NS: i64 = 1_000_000_000;
39184        let base: i64 = 1_705_322_096_i64 * NS; // 2024-01-15 12:34:56 UTC
39185
39186        // No subsecond: unchanged plain "%Y-%m-%d %H:%M:%S".
39187        assert_eq!(super::format_datetime_ns(base), "2024-01-15 12:34:56");
39188        // Millisecond fraction is carried (was DROPPED before dt64fmt), with the
39189        // same trailing-zero trimming format_naive_datetime uses.
39190        assert_eq!(
39191            super::format_datetime_ns(base + 789_000_000),
39192            "2024-01-15 12:34:56.789"
39193        );
39194        // Full nanosecond precision survives.
39195        assert_eq!(
39196            super::format_datetime_ns(base + 123_456_789),
39197            "2024-01-15 12:34:56.123456789"
39198        );
39199        // Pre-epoch instants decompose with floor semantics: -0.5s is
39200        // 1969-12-31 23:59:59.5, not 1970-01-01 00:00:00.5.
39201        assert_eq!(
39202            super::format_datetime_ns(-500_000_000),
39203            "1969-12-31 23:59:59.5"
39204        );
39205        // NaT sentinel is preserved.
39206        assert_eq!(super::format_datetime_ns(i64::MIN), "NaT");
39207    }
39208
39209    #[test]
39210    fn format_datetime_ns_bit_identical_to_chrono_over_full_range_dtns() {
39211        // Differential guard for the hand-rolled civil+ASCII rewrite
39212        // (br-frankenpandas-dtns): must match chrono byte-for-byte across the
39213        // entire i64-ns datetime64 range, both whole-second and sub-second.
39214        fn chrono_ref(nanos: i64) -> String {
39215            if nanos == i64::MIN {
39216                return "NaT".to_owned();
39217            }
39218            let dt = chrono::DateTime::from_timestamp_nanos(nanos);
39219            let mut rendered = dt.format("%Y-%m-%d %H:%M:%S").to_string();
39220            let subsec_nanos = dt.timestamp_subsec_nanos();
39221            if subsec_nanos != 0 {
39222                let mut fractional = format!("{subsec_nanos:09}");
39223                while fractional.ends_with('0') {
39224                    fractional.pop();
39225                }
39226                rendered.push('.');
39227                rendered.push_str(&fractional);
39228            }
39229            rendered
39230        }
39231
39232        // Edge cases: the representable datetime64[ns] bounds, the epoch, and
39233        // pre-epoch fractions where floor semantics bite.
39234        let edges = [
39235            i64::MIN,
39236            i64::MIN + 1, // 1677-09-21 ...
39237            i64::MAX,     // 2262-04-11 ...
39238            0,
39239            -1,
39240            1,
39241            -500_000_000,
39242            -999_999_999,
39243            -1_000_000_000,
39244            500_000_000,
39245            123_456_789,
39246            -86_400_000_000_000, // exactly one day pre-epoch
39247        ];
39248        for ns in edges {
39249            assert_eq!(super::format_datetime_ns(ns), chrono_ref(ns), "ns={ns}");
39250        }
39251
39252        // Dense sweep across the full range with a large odd step (covers every
39253        // month/day/leap combination + sub-second fractions via the prime step).
39254        let step: i64 = 4_801_357_913_i64; // ~4.8s, coprime-ish, exercises subsec
39255        let mut ns = i64::MIN + 1;
39256        let mut count = 0u64;
39257        while count < 3_000_000 {
39258            assert_eq!(super::format_datetime_ns(ns), chrono_ref(ns), "ns={ns}");
39259            match ns.checked_add(step) {
39260                Some(next) => ns = next,
39261                None => break,
39262            }
39263            count += 1;
39264        }
39265    }
39266
39267    #[test]
39268    fn timedelta_index_asi8_microseconds_nanoseconds_match_pandas_teeck() -> Result<(), &'static str>
39269    {
39270        // 1 day + 2:34:56.789012345
39271        let one_day = fp_types::Timedelta::NANOS_PER_DAY;
39272        let extra = 2 * fp_types::Timedelta::NANOS_PER_HOUR
39273            + 34 * fp_types::Timedelta::NANOS_PER_MIN
39274            + 56 * fp_types::Timedelta::NANOS_PER_SEC
39275            + 789_012_345;
39276        let total = one_day + extra;
39277        let td = super::TimedeltaIndex::new(vec![total, fp_types::Timedelta::NAT, 0, -1]);
39278
39279        assert_eq!(td.asi8(), vec![total, fp_types::Timedelta::NAT, 0, -1]);
39280        // microseconds: 789_012_345 % 1_000_000_000 / 1_000 == 789_012
39281        assert_eq!(
39282            td.microseconds(),
39283            vec![Some(789_012), None, Some(0), Some(999_999)]
39284        );
39285        // nanoseconds: 789_012_345 % 1_000 == 345
39286        assert_eq!(td.nanoseconds(), vec![Some(345), None, Some(0), Some(999)]);
39287
39288        let components = td.components();
39289        let positive = components
39290            .first()
39291            .copied()
39292            .flatten()
39293            .ok_or("positive components")?;
39294        assert_eq!(positive.days, 1);
39295        assert_eq!(positive.hours, 2);
39296        assert_eq!(positive.minutes, 34);
39297        assert_eq!(positive.seconds, 56);
39298        assert_eq!(positive.milliseconds, 789);
39299        assert_eq!(positive.microseconds, 12);
39300        assert_eq!(positive.nanoseconds, 345);
39301
39302        assert_eq!(
39303            components.get(1).copied().flatten().map(|row| row.days),
39304            None
39305        );
39306
39307        let zero = components
39308            .get(2)
39309            .copied()
39310            .flatten()
39311            .ok_or("zero components")?;
39312        assert_eq!(zero.days, 0);
39313        assert_eq!(zero.hours, 0);
39314        assert_eq!(zero.minutes, 0);
39315        assert_eq!(zero.seconds, 0);
39316        assert_eq!(zero.milliseconds, 0);
39317        assert_eq!(zero.microseconds, 0);
39318        assert_eq!(zero.nanoseconds, 0);
39319
39320        let negative = components
39321            .get(3)
39322            .copied()
39323            .flatten()
39324            .ok_or("negative components")?;
39325        assert_eq!(negative.days, -1);
39326        assert_eq!(negative.hours, 23);
39327        assert_eq!(negative.minutes, 59);
39328        assert_eq!(negative.seconds, 59);
39329        assert_eq!(negative.milliseconds, 999);
39330        assert_eq!(negative.microseconds, 999);
39331        assert_eq!(negative.nanoseconds, 999);
39332
39333        Ok(())
39334    }
39335
39336    #[test]
39337    fn datetime_index_month_name_and_day_name_match_pandas_fqkiu() {
39338        // 2024-01-15 (Monday in January), 2024-12-31 (Tuesday in December),
39339        // i64::MIN (NAT).
39340        const NS: i64 = 1_000_000_000;
39341        let mon_jan: i64 = 1_705_276_800_i64 * NS;
39342        let tue_dec: i64 = 1_735_603_200_i64 * NS;
39343        let dt = super::DatetimeIndex::new(vec![mon_jan, tue_dec, i64::MIN]);
39344
39345        assert_eq!(
39346            dt.month_name(),
39347            vec![
39348                Some("January".to_owned()),
39349                Some("December".to_owned()),
39350                None
39351            ]
39352        );
39353        assert_eq!(
39354            dt.day_name(),
39355            vec![Some("Monday".to_owned()), Some("Tuesday".to_owned()), None]
39356        );
39357    }
39358
39359    #[test]
39360    fn datetime_index_normalize_truncates_to_midnight_utc_fqkiu() {
39361        const NS: i64 = 1_000_000_000;
39362        // 2024-01-15 12:34:56.789Z plus midnight 2024-01-21Z plus NAT.
39363        let mid_day: i64 = 1_705_276_800_i64 * NS + 12 * 3600 * NS + 34 * 60 * NS + 56 * NS + 789;
39364        let midnight: i64 = 1_705_795_200_i64 * NS;
39365        let nat = i64::MIN;
39366
39367        let dt = super::DatetimeIndex::new(vec![mid_day, midnight, nat]).set_name("when");
39368        let normed = dt.normalize().expect("a naive index normalizes");
39369
39370        // Each non-NAT entry is now at midnight; NAT stays NAT; name preserved.
39371        assert_eq!(
39372            normed.values(),
39373            vec![Some(1_705_276_800_i64 * NS), Some(midnight), None]
39374        );
39375        assert_eq!(normed.name().map(|n| n.as_str()), Some("when"));
39376        assert!(normed.is_normalized());
39377    }
39378
39379    #[test]
39380    fn datetime_index_is_normalized_returns_false_when_any_non_midnight_fqkiu() {
39381        const NS: i64 = 1_000_000_000;
39382        let mid_day: i64 = 1_705_276_800_i64 * NS + 1; // 1ns past midnight
39383        let midnight: i64 = 1_705_795_200_i64 * NS;
39384        let mixed = super::DatetimeIndex::new(vec![midnight, mid_day]);
39385        assert!(!mixed.is_normalized());
39386
39387        let only_midnight = super::DatetimeIndex::new(vec![midnight]);
39388        assert!(only_midnight.is_normalized());
39389
39390        let only_nat = super::DatetimeIndex::new(vec![i64::MIN, i64::MIN]);
39391        assert!(only_nat.is_normalized());
39392
39393        let empty = super::DatetimeIndex::new(vec![]);
39394        assert!(empty.is_normalized());
39395    }
39396
39397    #[test]
39398    fn datetime_index_feb_28_in_non_leap_year_is_month_end_qy7yd() {
39399        // 2023-02-28 00:00:00Z is the month-end of February 2023 (28 days).
39400        let feb_28_2023: i64 = 1_677_542_400_i64 * 1_000_000_000;
39401        let dt = super::DatetimeIndex::new(vec![feb_28_2023]);
39402        assert_eq!(dt.is_month_end(), vec![Some(true)]);
39403    }
39404
39405    #[test]
39406    fn datetime_index_leap_year_century_rule_k860x() {
39407        // 2000-06-15 (leap), 2100-06-15 (not leap), 2024-02-15 (leap),
39408        // 2023-02-15 (not leap), Feb in leap vs non-leap year.
39409        let y2000: i64 = 960_076_800 * 1_000_000_000;
39410        let y2100: i64 = 4_117_046_400 * 1_000_000_000;
39411        let y2024feb: i64 = 1_708_002_000 * 1_000_000_000;
39412        let y2023feb: i64 = 1_676_466_000 * 1_000_000_000;
39413
39414        let dt = super::DatetimeIndex::new(vec![y2000, y2100, y2024feb, y2023feb]);
39415        assert_eq!(
39416            dt.is_leap_year(),
39417            vec![Some(true), Some(false), Some(true), Some(false)]
39418        );
39419        // Feb in leap year -> 29 days; non-leap -> 28.
39420        let dim = dt.days_in_month();
39421        assert_eq!(dim[2], Some(29));
39422        assert_eq!(dim[3], Some(28));
39423    }
39424
39425    #[test]
39426    fn datetime_index_time_of_day_accessors_handle_empty_znejf() {
39427        let dt = super::DatetimeIndex::new(vec![]);
39428        assert!(dt.hour().is_empty());
39429        assert!(dt.minute().is_empty());
39430        assert!(dt.second().is_empty());
39431        assert!(dt.microsecond().is_empty());
39432        assert!(dt.nanosecond().is_empty());
39433    }
39434
39435    #[test]
39436    fn range_index_missingness_methods_are_closed_form_a4fih() {
39437        let asc = super::RangeIndex::new(0, 5, 1).unwrap();
39438        assert_eq!(asc.isna(), vec![false; 5]);
39439        assert_eq!(asc.isnull(), vec![false; 5]);
39440        assert_eq!(asc.notna(), vec![true; 5]);
39441        assert_eq!(asc.notnull(), vec![true; 5]);
39442        assert!(!asc.hasnans());
39443        assert!(asc.dropna().equals(&asc));
39444        assert!(asc.fillna(99).equals(&asc));
39445
39446        let desc = super::RangeIndex::new(10, 0, -2).unwrap();
39447        assert_eq!(desc.isna().len(), desc.len());
39448        assert!(!desc.hasnans());
39449        assert!(desc.dropna().equals(&desc));
39450
39451        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
39452        assert_eq!(empty.isna(), Vec::<bool>::new());
39453        assert_eq!(empty.notna(), Vec::<bool>::new());
39454        assert!(!empty.hasnans());
39455        assert!(empty.dropna().is_empty());
39456        assert!(empty.fillna(0).is_empty());
39457    }
39458
39459    #[test]
39460    fn range_index_format_stringifies_each_value_a4fih() {
39461        let asc = super::RangeIndex::new(0, 4, 1).unwrap();
39462        assert_eq!(asc.format(), vec!["0", "1", "2", "3"]);
39463
39464        let desc = super::RangeIndex::new(5, 0, -2).unwrap();
39465        assert_eq!(desc.format(), vec!["5", "3", "1"]);
39466
39467        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
39468        assert_eq!(empty.format(), Vec::<String>::new());
39469    }
39470
39471    #[test]
39472    fn range_index_format_uses_direct_values_nkivs() {
39473        let stepped = super::RangeIndex::new(-3, 6, 3).unwrap();
39474        assert_eq!(stepped.format(), vec!["-3", "0", "3"]);
39475
39476        let descending = super::RangeIndex::new(4, -5, -4).unwrap();
39477        assert_eq!(descending.format(), vec!["4", "0", "-4"]);
39478    }
39479
39480    #[test]
39481    fn range_index_factorize_is_identity_a4fih() {
39482        let asc = super::RangeIndex::new(0, 5, 1).unwrap();
39483        let (codes, uniques) = asc.factorize();
39484        assert_eq!(codes, vec![0, 1, 2, 3, 4]);
39485        assert!(uniques.equals(&asc));
39486
39487        let desc = super::RangeIndex::new(10, 0, -2).unwrap();
39488        let (desc_codes, desc_uniques) = desc.factorize();
39489        assert_eq!(desc_codes, (0..desc.len()).collect::<Vec<_>>());
39490        assert!(desc_uniques.equals(&desc));
39491
39492        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
39493        let (empty_codes, empty_uniques) = empty.factorize();
39494        assert!(empty_codes.is_empty());
39495        assert!(empty_uniques.is_empty());
39496    }
39497
39498    #[test]
39499    fn range_index_duplicated_drop_duplicates_are_no_ops_mrchb() {
39500        let asc = super::RangeIndex::new(0, 5, 1).unwrap();
39501        for keep in [
39502            super::DuplicateKeep::First,
39503            super::DuplicateKeep::Last,
39504            super::DuplicateKeep::None,
39505        ] {
39506            assert_eq!(asc.duplicated(keep), vec![false; asc.len()]);
39507        }
39508        let cloned = asc.drop_duplicates();
39509        assert!(cloned.equals(&asc));
39510        assert_eq!(cloned.len(), asc.len());
39511
39512        let empty = super::RangeIndex::new(0, 0, 1).unwrap();
39513        assert_eq!(
39514            empty.duplicated(super::DuplicateKeep::First),
39515            Vec::<bool>::new()
39516        );
39517        assert!(empty.drop_duplicates().is_empty());
39518    }
39519
39520    #[test]
39521    fn multi_index_asof_rejects_tuple_comparison_d89fe13() -> Result<(), super::IndexError> {
39522        let string_level = MultiIndex::from_tuples(vec![
39523            vec!["a".into(), 1_i64.into()],
39524            vec!["b".into(), 2_i64.into()],
39525        ])?;
39526        let int_level = MultiIndex::from_tuples(vec![
39527            vec![1_i64.into(), "a".into()],
39528            vec![2_i64.into(), "b".into()],
39529        ])?;
39530
39531        let string_err = string_level
39532            .asof(&[IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)])
39533            .unwrap_err();
39534        let int_err = int_level
39535            .asof(&[IndexLabel::Int64(1), IndexLabel::Utf8("a".into())])
39536            .unwrap_err();
39537
39538        assert!(matches!(
39539            string_err,
39540            super::IndexError::InvalidArgument(message)
39541                if message == "'<' not supported between instances of 'tuple' and 'str'"
39542        ));
39543        assert!(matches!(
39544            int_err,
39545            super::IndexError::InvalidArgument(message)
39546                if message == "'<' not supported between instances of 'tuple' and 'int'"
39547        ));
39548        assert_eq!(MultiIndex::from_tuples(Vec::new())?.asof(&[])?, None);
39549
39550        Ok(())
39551    }
39552
39553    #[test]
39554    fn multi_index_asof_locs_rejects_mask_and_broadcast_paths_d89fe14()
39555    -> Result<(), super::IndexError> {
39556        let source = MultiIndex::from_tuples(vec![
39557            vec!["a".into(), 1_i64.into()],
39558            vec!["a".into(), 3_i64.into()],
39559            vec!["b".into(), 2_i64.into()],
39560        ])?;
39561        let where_index = MultiIndex::from_tuples(vec![
39562            vec!["a".into(), 0_i64.into()],
39563            vec!["a".into(), 2_i64.into()],
39564            vec!["b".into(), 2_i64.into()],
39565        ])?;
39566
39567        let no_mask = source.asof_locs(&where_index, None).unwrap_err();
39568        let mismatched_mask = source
39569            .asof_locs(&where_index, Some(&[true, true]))
39570            .unwrap_err();
39571        let empty_take = source
39572            .asof_locs(&where_index, Some(&[false, false, false]))
39573            .unwrap_err();
39574        let broadcast = source
39575            .asof_locs(&where_index, Some(&[true, false, true]))
39576            .unwrap_err();
39577        let empty_source = MultiIndex::from_arrays(vec![Vec::new(), Vec::new()])?;
39578        let empty_mask = empty_source
39579            .asof_locs(&empty_source, Some(&[]))
39580            .unwrap_err();
39581
39582        assert!(matches!(
39583            no_mask,
39584            super::IndexError::InvalidArgument(message)
39585                if message == "object too deep for desired array"
39586        ));
39587        assert!(matches!(
39588            mismatched_mask,
39589            super::IndexError::InvalidArgument(message)
39590                if message == "boolean index did not match indexed array along axis 0; size of axis is 3 but size of corresponding boolean axis is 2"
39591        ));
39592        assert!(matches!(
39593            empty_take,
39594            super::IndexError::InvalidArgument(message)
39595                if message == "cannot do a non-empty take from an empty axes."
39596        ));
39597        assert!(matches!(
39598            broadcast,
39599            super::IndexError::InvalidArgument(message)
39600                if message == "operands could not be broadcast together with shapes (3,) (2,)"
39601        ));
39602        assert!(matches!(
39603            empty_mask,
39604            super::IndexError::InvalidArgument(message)
39605                if message == "attempt to get argmax of an empty sequence"
39606        ));
39607
39608        Ok(())
39609    }
39610
39611    #[test]
39612    fn multi_index_drop_duplicates_append_repeat_and_dropna() {
39613        let left = MultiIndex::from_tuples(vec![
39614            vec!["a".into(), 1_i64.into()],
39615            vec!["a".into(), 1_i64.into()],
39616            vec!["b".into(), 2_i64.into()],
39617            vec![IndexLabel::Datetime64(i64::MIN), 3_i64.into()],
39618            vec![
39619                IndexLabel::Datetime64(i64::MIN),
39620                IndexLabel::Timedelta64(Timedelta::NAT),
39621            ],
39622        ])
39623        .unwrap()
39624        .set_names(vec![Some("letter".into()), Some("number".into())]);
39625
39626        assert_eq!(
39627            left.drop_duplicates().to_list(),
39628            vec![
39629                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
39630                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
39631                vec![IndexLabel::Datetime64(i64::MIN), IndexLabel::Int64(3)],
39632                vec![
39633                    IndexLabel::Datetime64(i64::MIN),
39634                    IndexLabel::Timedelta64(Timedelta::NAT),
39635                ],
39636            ]
39637        );
39638        assert_eq!(
39639            left.dropna().to_list(),
39640            vec![
39641                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
39642                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
39643                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
39644            ]
39645        );
39646        assert_eq!(left.dropna_all().len(), 4);
39647
39648        let right = MultiIndex::from_tuples(vec![vec!["c".into(), 3_i64.into()]])
39649            .unwrap()
39650            .set_names(vec![Some("letter".into()), Some("other".into())]);
39651        let appended = left.append(&right).unwrap();
39652        assert_eq!(appended.len(), 6);
39653        assert_eq!(appended.names(), &[Some("letter".into()), None]);
39654
39655        let repeated = right.repeat(2);
39656        assert_eq!(
39657            repeated.to_list(),
39658            vec![
39659                vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
39660                vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
39661            ]
39662        );
39663        assert_eq!(right.repeat(0).len(), 0);
39664    }
39665
39666    #[test]
39667    fn multi_index_insert_delete_and_drop_tuples() {
39668        let mi = MultiIndex::from_tuples(vec![
39669            vec!["b".into(), 2_i64.into()],
39670            vec!["a".into(), 2_i64.into()],
39671            vec!["a".into(), 1_i64.into()],
39672            vec!["b".into(), 2_i64.into()],
39673        ])
39674        .unwrap()
39675        .set_names(vec![Some("letter".into()), Some("number".into())]);
39676
39677        let inserted = mi.insert(1, vec!["z".into(), 9_i64.into()]).unwrap();
39678        assert_eq!(
39679            inserted.to_list(),
39680            vec![
39681                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
39682                vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(9)],
39683                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
39684                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
39685                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
39686            ]
39687        );
39688        assert_eq!(inserted.names(), mi.names());
39689
39690        let deleted = inserted.delete(1).unwrap();
39691        assert_eq!(deleted, mi);
39692        assert!(mi.insert(0, vec!["short".into()]).is_err());
39693        assert!(mi.delete(99).is_err());
39694
39695        let dropped = mi
39696            .drop(&[vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)]])
39697            .unwrap();
39698        assert_eq!(
39699            dropped.to_list(),
39700            vec![
39701                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
39702                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
39703            ]
39704        );
39705        assert!(
39706            mi.drop(&[vec![
39707                IndexLabel::Utf8("missing".into()),
39708                IndexLabel::Int64(0)
39709            ]])
39710            .is_err()
39711        );
39712    }
39713
39714    #[test]
39715    fn multi_index_factorize_sort_and_reduce_tuples() {
39716        let mi = MultiIndex::from_tuples(vec![
39717            vec!["b".into(), 2_i64.into()],
39718            vec!["a".into(), 2_i64.into()],
39719            vec!["a".into(), 1_i64.into()],
39720            vec!["b".into(), 2_i64.into()],
39721            vec!["a".into(), 2_i64.into()],
39722            vec!["c".into(), 3_i64.into()],
39723        ])
39724        .unwrap()
39725        .set_names(vec![Some("letter".into()), Some("number".into())]);
39726
39727        let (codes, uniques) = mi.factorize();
39728        assert_eq!(codes, vec![0, 1, 2, 0, 1, 3]);
39729        assert_eq!(
39730            uniques.to_list(),
39731            vec![
39732                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
39733                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
39734                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
39735                vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
39736            ]
39737        );
39738        assert_eq!(uniques.names(), mi.names());
39739        assert_eq!(mi.unique(), uniques);
39740        assert_eq!(mi.nunique(), 4);
39741        assert_eq!(
39742            mi.value_counts(),
39743            vec![
39744                (vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)], 2),
39745                (vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)], 2),
39746                (vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)], 1),
39747                (vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)], 1),
39748            ]
39749        );
39750
39751        let sorted = mi.sort_values();
39752        assert_eq!(
39753            sorted.to_list(),
39754            vec![
39755                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
39756                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
39757                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
39758                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
39759                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
39760                vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
39761            ]
39762        );
39763        let (sortlevel, order) = mi.sortlevel();
39764        assert_eq!(sortlevel, sorted);
39765        assert_eq!(order, vec![2, 1, 4, 0, 3, 5]);
39766        assert_eq!(mi.sort(), sorted);
39767        assert_eq!(
39768            mi.min().unwrap(),
39769            vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)]
39770        );
39771        assert_eq!(
39772            mi.max().unwrap(),
39773            vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)]
39774        );
39775        assert_eq!(mi.argmin(), Some(2));
39776        assert_eq!(mi.argmax(), Some(5));
39777
39778        let empty = MultiIndex::from_tuples(Vec::new()).unwrap();
39779        assert_eq!(empty.min(), None);
39780        assert_eq!(empty.max(), None);
39781        assert_eq!(empty.argmin(), None);
39782        assert_eq!(empty.argmax(), None);
39783    }
39784
39785    #[test]
39786    fn multi_index_factorize_value_counts_fxhash_order_uza04194() {
39787        let mi = MultiIndex::from_tuples(vec![
39788            vec!["z".into(), 2_i64.into()],
39789            vec!["a".into(), 1_i64.into()],
39790            vec!["z".into(), 2_i64.into()],
39791            vec!["b".into(), 1_i64.into()],
39792            vec!["a".into(), 1_i64.into()],
39793            vec!["b".into(), 1_i64.into()],
39794            vec!["c".into(), 3_i64.into()],
39795        ])
39796        .unwrap()
39797        .set_names(vec![Some("letter".into()), Some("number".into())]);
39798
39799        let (codes, uniques) = mi.factorize();
39800        assert_eq!(codes, vec![0, 1, 0, 2, 1, 2, 3]);
39801        assert_eq!(
39802            uniques.to_list(),
39803            vec![
39804                vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(2)],
39805                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
39806                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
39807                vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
39808            ]
39809        );
39810        assert_eq!(uniques.names(), mi.names());
39811        assert_eq!(
39812            mi.value_counts(),
39813            vec![
39814                (vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)], 2),
39815                (vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)], 2),
39816                (vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(2)], 2),
39817                (vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)], 1),
39818            ]
39819        );
39820    }
39821
39822    #[test]
39823    fn multi_index_value_counts_compact_matches_tuple_oracle() {
39824        fn oracle(mi: &MultiIndex) -> Vec<(Vec<IndexLabel>, usize)> {
39825            let mut counts = std::collections::HashMap::<Vec<IndexLabel>, usize>::new();
39826            for tuple in mi.to_list() {
39827                *counts.entry(tuple).or_insert(0) += 1;
39828            }
39829            let mut pairs: Vec<_> = counts.into_iter().collect();
39830            pairs.sort_by(|(left_tuple, left_count), (right_tuple, right_count)| {
39831                right_count
39832                    .cmp(left_count)
39833                    .then_with(|| left_tuple.cmp(right_tuple))
39834            });
39835            pairs
39836        }
39837
39838        let mi = MultiIndex::from_tuples(vec![
39839            vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(2)],
39840            vec![IndexLabel::Int64(7), IndexLabel::Utf8("a".into())],
39841            vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(2)],
39842            vec![
39843                IndexLabel::Bool(true),
39844                IndexLabel::Null(fp_types::NullKind::NaN),
39845            ],
39846            vec![IndexLabel::Int64(7), IndexLabel::Utf8("a".into())],
39847            vec![
39848                IndexLabel::Bool(false),
39849                IndexLabel::Null(fp_types::NullKind::NaN),
39850            ],
39851            vec![
39852                IndexLabel::Bool(true),
39853                IndexLabel::Null(fp_types::NullKind::NaN),
39854            ],
39855        ])
39856        .expect("two-level MultiIndex");
39857        assert!(mi.compact_two_level_identity_layout().is_some());
39858        assert_eq!(mi.value_counts(), oracle(&mi));
39859
39860        let without_sidecar = super::MultiIndex {
39861            levels: mi.levels.clone(),
39862            names: mi.names.clone(),
39863            identity_codes: None,
39864            missing_is_a_level: false,
39865        };
39866        assert!(
39867            without_sidecar
39868                .compact_two_level_identity_layout()
39869                .is_none()
39870        );
39871        assert_eq!(without_sidecar.value_counts(), oracle(&without_sidecar));
39872        assert_eq!(mi.value_counts(), without_sidecar.value_counts());
39873    }
39874
39875    #[test]
39876    fn multi_index_nunique_counts_without_unique_output_uza04195() {
39877        let mi = MultiIndex::from_tuples(vec![
39878            vec!["z".into(), 2_i64.into()],
39879            vec!["a".into(), 1_i64.into()],
39880            vec!["z".into(), 2_i64.into()],
39881            vec!["b".into(), 1_i64.into()],
39882            vec!["a".into(), 1_i64.into()],
39883        ])
39884        .unwrap();
39885        assert_eq!(mi.nunique(), 3);
39886        assert_eq!(mi.nunique(), mi.unique().len());
39887
39888        let zero_row = vec![IndexLabel::Int64(0); 65];
39889        let one_row = vec![IndexLabel::Int64(1); 65];
39890        let wide = MultiIndex::from_tuples(vec![zero_row.clone(), one_row, zero_row]).unwrap();
39891        assert_eq!(wide.nunique(), 2);
39892        assert_eq!(wide.nunique(), wide.unique().len());
39893    }
39894
39895    #[test]
39896    fn multi_index_tuple_set_ops_preserve_order_and_shared_names() {
39897        let left = MultiIndex::from_tuples(vec![
39898            vec!["a".into(), 1_i64.into()],
39899            vec!["a".into(), 2_i64.into()],
39900            vec!["b".into(), 1_i64.into()],
39901            vec!["a".into(), 1_i64.into()],
39902        ])
39903        .unwrap()
39904        .set_names(vec![Some("letter".into()), Some("number".into())]);
39905        let right = MultiIndex::from_tuples(vec![
39906            vec!["a".into(), 2_i64.into()],
39907            vec!["c".into(), 3_i64.into()],
39908        ])
39909        .unwrap()
39910        .set_names(vec![Some("letter".into()), Some("other".into())]);
39911
39912        let intersection = left.intersection(&right).unwrap();
39913        assert_eq!(
39914            intersection.to_list(),
39915            vec![vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)]]
39916        );
39917        assert_eq!(intersection.names(), &[Some("letter".into()), None]);
39918
39919        assert_eq!(
39920            left.union(&right).unwrap().to_list(),
39921            vec![
39922                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
39923                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
39924                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
39925                vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
39926            ]
39927        );
39928        assert_eq!(
39929            left.difference(&right).unwrap().to_list(),
39930            vec![
39931                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
39932                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
39933            ]
39934        );
39935        assert_eq!(
39936            left.symmetric_difference(&right).unwrap().to_list(),
39937            vec![
39938                vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
39939                vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
39940                vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
39941            ]
39942        );
39943    }
39944
39945    #[test]
39946    fn multi_index_reorder_levels() {
39947        let mi = MultiIndex::from_tuples(vec![
39948            vec!["a".into(), 1_i64.into(), "x".into()],
39949            vec!["b".into(), 2_i64.into(), "y".into()],
39950        ])
39951        .unwrap()
39952        .set_names(vec![
39953            Some("letter".into()),
39954            Some("number".into()),
39955            Some("code".into()),
39956        ]);
39957
39958        // Reorder: [2, 0, 1] → code, letter, number.
39959        let reordered = mi.reorder_levels(&[2, 0, 1]).unwrap();
39960        assert_eq!(reordered.nlevels(), 3);
39961        assert_eq!(
39962            reordered.names(),
39963            &[
39964                Some("code".into()),
39965                Some("letter".into()),
39966                Some("number".into())
39967            ]
39968        );
39969
39970        // First row should be ("x", "a", 1).
39971        let tuple = reordered.get_tuple(0).unwrap();
39972        assert_eq!(tuple[0], &IndexLabel::Utf8("x".into()));
39973        assert_eq!(tuple[1], &IndexLabel::Utf8("a".into()));
39974        assert_eq!(tuple[2], &IndexLabel::Int64(1));
39975    }
39976
39977    #[test]
39978    fn multi_index_reorder_levels_identity() {
39979        let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
39980
39981        // Identity reorder [0, 1] should be a no-op.
39982        let same = mi.reorder_levels(&[0, 1]).unwrap();
39983        assert_eq!(same, mi);
39984    }
39985
39986    #[test]
39987    fn multi_index_reorder_levels_wrong_length_errors() {
39988        let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
39989
39990        assert!(mi.reorder_levels(&[0]).is_err());
39991        assert!(mi.reorder_levels(&[0, 1, 2]).is_err());
39992    }
39993
39994    #[test]
39995    fn multi_index_reorder_levels_duplicate_index_errors() {
39996        let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
39997
39998        assert!(mi.reorder_levels(&[0, 0]).is_err());
39999    }
40000
40001    #[test]
40002    fn multi_index_reorder_levels_out_of_bounds_errors() {
40003        let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
40004
40005        assert!(mi.reorder_levels(&[0, 5]).is_err());
40006    }
40007
40008    // ── is_monotonic / is_lexsorted tests (br-frankenpandas-w4uu) ───────
40009
40010    #[test]
40011    fn multi_index_is_monotonic_increasing_on_sorted() {
40012        // Rows: [(A,1), (A,2), (B,1)] — strictly increasing lexicographic.
40013        let mi = MultiIndex::from_tuples(vec![
40014            vec!["A".into(), 1_i64.into()],
40015            vec!["A".into(), 2_i64.into()],
40016            vec!["B".into(), 1_i64.into()],
40017        ])
40018        .unwrap();
40019        assert!(mi.is_monotonic_increasing());
40020        assert!(mi.is_lexsorted());
40021        assert!(!mi.is_monotonic_decreasing());
40022    }
40023
40024    #[test]
40025    fn multi_index_is_monotonic_decreasing_on_reverse_sorted() {
40026        // Rows: [(B,2), (B,1), (A,1)].
40027        let mi = MultiIndex::from_tuples(vec![
40028            vec!["B".into(), 2_i64.into()],
40029            vec!["B".into(), 1_i64.into()],
40030            vec!["A".into(), 1_i64.into()],
40031        ])
40032        .unwrap();
40033        assert!(mi.is_monotonic_decreasing());
40034        assert!(!mi.is_monotonic_increasing());
40035    }
40036
40037    #[test]
40038    fn multi_index_is_monotonic_both_directions_on_constant_inner() {
40039        // Equal-level-value rows: [(A,1), (A,1)] — both monotonic trivially.
40040        let mi = MultiIndex::from_tuples(vec![
40041            vec!["A".into(), 1_i64.into()],
40042            vec!["A".into(), 1_i64.into()],
40043        ])
40044        .unwrap();
40045        assert!(mi.is_monotonic_increasing());
40046        assert!(mi.is_monotonic_decreasing());
40047    }
40048
40049    #[test]
40050    fn multi_index_empty_is_monotonic() {
40051        let mi = MultiIndex::from_tuples(Vec::new()).unwrap();
40052        assert!(mi.is_monotonic_increasing());
40053        assert!(mi.is_monotonic_decreasing());
40054        assert!(mi.is_lexsorted());
40055    }
40056
40057    #[test]
40058    fn multi_index_single_row_is_monotonic() {
40059        let mi = MultiIndex::from_tuples(vec![vec!["A".into(), 1_i64.into()]]).unwrap();
40060        assert!(mi.is_monotonic_increasing());
40061        assert!(mi.is_monotonic_decreasing());
40062        assert!(mi.is_lexsorted());
40063    }
40064
40065    #[test]
40066    fn multi_index_unsorted_is_neither() {
40067        // Rows: [(B,1), (A,2), (B,2)] — unsorted at the outer level.
40068        let mi = MultiIndex::from_tuples(vec![
40069            vec!["B".into(), 1_i64.into()],
40070            vec!["A".into(), 2_i64.into()],
40071            vec!["B".into(), 2_i64.into()],
40072        ])
40073        .unwrap();
40074        assert!(!mi.is_monotonic_increasing());
40075        assert!(!mi.is_monotonic_decreasing());
40076        assert!(!mi.is_lexsorted());
40077    }
40078
40079    #[test]
40080    fn multi_index_outer_ascending_inner_descending_is_not_monotonic() {
40081        // Rows: [(A,5), (A,1), (B,3)] — outer ascending, inner within A descends.
40082        let mi = MultiIndex::from_tuples(vec![
40083            vec!["A".into(), 5_i64.into()],
40084            vec!["A".into(), 1_i64.into()],
40085            vec!["B".into(), 3_i64.into()],
40086        ])
40087        .unwrap();
40088        // Lexicographically (A,5) > (A,1) so the "increasing" check fails.
40089        assert!(!mi.is_monotonic_increasing());
40090        // (A,5) > (A,1) but (A,1) < (B,3) so decreasing also fails.
40091        assert!(!mi.is_monotonic_decreasing());
40092    }
40093
40094    #[test]
40095    fn index_lookup_methods_match_pandas() {
40096        use super::{Index, IndexLabel};
40097        let i = Index::new(vec![
40098            IndexLabel::Int64(1),
40099            IndexLabel::Int64(3),
40100            IndexLabel::Int64(5),
40101            IndexLabel::Int64(7),
40102        ]);
40103
40104        // get_indexer (exact): -1/None for labels not present (verified vs
40105        // pandas Index([1,3,5,7]).get_indexer([2,3,6,7]) == [-1,1,-1,3]).
40106        let target = Index::new(vec![
40107            IndexLabel::Int64(2),
40108            IndexLabel::Int64(3),
40109            IndexLabel::Int64(6),
40110            IndexLabel::Int64(7),
40111        ]);
40112        assert_eq!(
40113            i.get_indexer(&target),
40114            vec![None, Some(1), None, Some(3)],
40115            "get_indexer exact"
40116        );
40117
40118        // searchsorted left/right (pandas: 3->1/2, 4->2, 8->4, 0->0).
40119        assert_eq!(i.searchsorted(&IndexLabel::Int64(3), "left").unwrap(), 1);
40120        assert_eq!(i.searchsorted(&IndexLabel::Int64(3), "right").unwrap(), 2);
40121        assert_eq!(i.searchsorted(&IndexLabel::Int64(4), "left").unwrap(), 2);
40122        assert_eq!(i.searchsorted(&IndexLabel::Int64(8), "left").unwrap(), 4);
40123        assert_eq!(i.searchsorted(&IndexLabel::Int64(0), "left").unwrap(), 0);
40124
40125        // asof: last label <= key (pandas: 4->3, 0->NaN, 7->7, 10->7).
40126        assert_eq!(
40127            i.asof(&IndexLabel::Int64(4)),
40128            Some(IndexLabel::Int64(3)),
40129            "asof 4"
40130        );
40131        assert_eq!(i.asof(&IndexLabel::Int64(0)), None, "asof before all");
40132        assert_eq!(
40133            i.asof(&IndexLabel::Int64(7)),
40134            Some(IndexLabel::Int64(7)),
40135            "asof exact"
40136        );
40137        assert_eq!(
40138            i.asof(&IndexLabel::Int64(10)),
40139            Some(IndexLabel::Int64(7)),
40140            "asof after all"
40141        );
40142
40143        // factorize: first-appearance order (pandas: ['b','a','b','c'] ->
40144        // codes [0,1,0,2], uniques ['b','a','c']).
40145        let f = Index::new(vec![
40146            IndexLabel::Utf8("b".into()),
40147            IndexLabel::Utf8("a".into()),
40148            IndexLabel::Utf8("b".into()),
40149            IndexLabel::Utf8("c".into()),
40150        ]);
40151        let (codes, uniques) = f.factorize();
40152        assert_eq!(codes, vec![0_isize, 1, 0, 2], "factorize codes");
40153        assert_eq!(
40154            uniques.labels(),
40155            &[
40156                IndexLabel::Utf8("b".into()),
40157                IndexLabel::Utf8("a".into()),
40158                IndexLabel::Utf8("c".into())
40159            ],
40160            "factorize uniques"
40161        );
40162    }
40163}
40164
40165/// Single-binary, single-invocation A/B for the `to_flat_index` `core::fmt`
40166/// removal (cc_fp). Both arms are compiled into THIS binary and alternate inside
40167/// ONE test run, so worker identity and time-varying load cancel: `rch exec` has
40168/// no `--worker` flag and picks workers non-deterministically, which makes any
40169/// ratio split across two invocations invalid. The run also asserts the two arms
40170/// produce identical labels, so parity and perf are proven by the same execution.
40171///
40172/// Run: `rch exec -- cargo test -p fp-index --profile release-perf \
40173///        -- --ignored --nocapture ab_to_flat_index`
40174#[cfg(test)]
40175mod ab_to_flat_index_ccfp {
40176    use std::{fmt::Write as _, time::Instant};
40177
40178    use sha2::{Digest, Sha256};
40179
40180    use super::{IndexLabel, MultiIndex};
40181
40182    const BLOCKS: usize = 25;
40183    const BOOTSTRAP_RESAMPLES: usize = 10_000;
40184    const DECIDABILITY_MARGIN: f64 = 2.0;
40185
40186    fn build_mi(n: usize) -> MultiIndex {
40187        // Two levels of the shape wide_to_long / set_index_multi actually produce:
40188        // a Utf8 key level and an Int64 level. Both hit `Display` in the ORIG arm.
40189        let lvl0: Vec<IndexLabel> = (0..n)
40190            .map(|i| IndexLabel::Utf8(format!("r{:06}", i % 100_000)))
40191            .collect();
40192        let lvl1: Vec<IndexLabel> = (0..n)
40193            .map(|i| IndexLabel::Int64((i as i64) % 9_973))
40194            .collect();
40195        MultiIndex::from_arrays(vec![lvl0, lvl1]).expect("multiindex")
40196    }
40197
40198    fn median(xs: &[f64]) -> f64 {
40199        let mut sorted = xs.to_vec();
40200        sorted.sort_by(f64::total_cmp);
40201        sorted[sorted.len() / 2]
40202    }
40203
40204    fn stats(xs: &[f64]) -> (f64, f64) {
40205        let mean = xs.iter().sum::<f64>() / xs.len() as f64;
40206        let var = xs.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / xs.len() as f64;
40207        (mean, 100.0 * var.sqrt() / mean)
40208    }
40209
40210    fn bootstrap_median_ci(values: &[f64]) -> (f64, f64) {
40211        let mut state = 0xf2a2_0260_725d_1ce5_u64;
40212        let mut medians = Vec::with_capacity(BOOTSTRAP_RESAMPLES);
40213        let mut sample = vec![0.0; values.len()];
40214        for _ in 0..BOOTSTRAP_RESAMPLES {
40215            for slot in &mut sample {
40216                state = state
40217                    .wrapping_mul(6_364_136_223_846_793_005)
40218                    .wrapping_add(1_442_695_040_888_963_407);
40219                *slot = values[(state as usize) % values.len()];
40220            }
40221            medians.push(median(&sample));
40222        }
40223        medians.sort_by(f64::total_cmp);
40224        (
40225            medians[BOOTSTRAP_RESAMPLES / 40],
40226            medians[(BOOTSTRAP_RESAMPLES * 39 / 40).min(BOOTSTRAP_RESAMPLES - 1)],
40227        )
40228    }
40229
40230    fn binary_sha256() -> String {
40231        let path = std::env::current_exe().expect("current test binary");
40232        let bytes = std::fs::read(path).expect("read current test binary");
40233        let digest = Sha256::digest(&bytes);
40234        let mut hex = String::with_capacity(64);
40235        for byte in digest {
40236            write!(&mut hex, "{byte:02x}").expect("writing to String cannot fail");
40237        }
40238        hex
40239    }
40240
40241    fn time_orig(mi: &MultiIndex, reps: usize) -> f64 {
40242        let mut best = f64::INFINITY;
40243        for _ in 0..reps {
40244            let started = Instant::now();
40245            std::hint::black_box(mi.to_flat_index_ref_write_fmt("_"));
40246            best = best.min(started.elapsed().as_secs_f64() * 1e3);
40247        }
40248        best
40249    }
40250
40251    fn time_candidate(mi: &MultiIndex, reps: usize) -> f64 {
40252        let mut best = f64::INFINITY;
40253        for _ in 0..reps {
40254            let started = Instant::now();
40255            std::hint::black_box(mi.to_flat_index("_"));
40256            best = best.min(started.elapsed().as_secs_f64() * 1e3);
40257        }
40258        best
40259    }
40260
40261    fn ab_regime(label: &str, n: usize, reps: usize) {
40262        let mi = build_mi(n);
40263        // Parity in this same binary: the arms must be bit-identical.
40264        assert_eq!(
40265            mi.to_flat_index_ref_write_fmt("_").labels(),
40266            mi.to_flat_index("_").labels(),
40267            "{label}: CAND diverged from the ORIG write! formatter"
40268        );
40269        for _ in 0..2 {
40270            std::hint::black_box(mi.to_flat_index_ref_write_fmt("_"));
40271            std::hint::black_box(mi.to_flat_index_ref_write_fmt("_"));
40272            std::hint::black_box(mi.to_flat_index("_"));
40273        }
40274        let mut orig_ms = Vec::with_capacity(BLOCKS);
40275        let mut null_ms = Vec::with_capacity(BLOCKS);
40276        let mut candidate_ms = Vec::with_capacity(BLOCKS);
40277        for block in 0..BLOCKS {
40278            if block % 2 == 0 {
40279                orig_ms.push(time_orig(&mi, reps));
40280                null_ms.push(time_orig(&mi, reps));
40281                candidate_ms.push(time_candidate(&mi, reps));
40282            } else {
40283                candidate_ms.push(time_candidate(&mi, reps));
40284                null_ms.push(time_orig(&mi, reps));
40285                orig_ms.push(time_orig(&mi, reps));
40286            }
40287        }
40288        let null_ratios: Vec<f64> = orig_ms
40289            .iter()
40290            .zip(&null_ms)
40291            .map(|(arm_a, arm_b)| arm_a / arm_b)
40292            .collect();
40293        let candidate_ratios: Vec<f64> = orig_ms
40294            .iter()
40295            .zip(&candidate_ms)
40296            .map(|(arm_a, arm_b)| arm_a / arm_b)
40297            .collect();
40298        let (orig_mean, orig_cv) = stats(&orig_ms);
40299        let (candidate_mean, candidate_cv) = stats(&candidate_ms);
40300        let null_median = median(&null_ratios);
40301        let (ci_low, ci_high) = bootstrap_median_ci(&null_ratios);
40302        let ratio = median(&candidate_ratios);
40303        let required_log_effect = DECIDABILITY_MARGIN * ci_low.ln().abs().max(ci_high.ln().abs());
40304        let decidable = ratio.ln().abs() >= required_log_effect;
40305        let verdict = if !decidable {
40306            "NULL_UNDECIDABLE"
40307        } else if ratio > 1.0 {
40308            "KEEP"
40309        } else {
40310            "REJECT"
40311        };
40312
40313        println!("[{label}] n={n} blocks={BLOCKS} reps={reps}");
40314        println!("  ORIG_MS {orig_ms:?}");
40315        println!("  NULL_MS {null_ms:?}");
40316        println!("  CANDIDATE_MS {candidate_ms:?}");
40317        println!("  NULL_RATIOS {null_ratios:?}");
40318        println!("  CANDIDATE_RATIOS {candidate_ratios:?}");
40319        println!("  ORIG mean={orig_mean:9.4} ms cv={orig_cv:5.2}%");
40320        println!("  CAND variant-fmt mean={candidate_mean:9.4} ms cv={candidate_cv:5.2}%");
40321        println!("  NULL_MEDIAN_CI median={null_median:.6} low={ci_low:.6} high={ci_high:.6}");
40322        println!(
40323            "  MEDIAN_CI_GATE ratio={ratio:.6} required_log_effect={required_log_effect:.8} \
40324             cv_is_provenance_only=true verdict={verdict}"
40325        );
40326    }
40327
40328    #[test]
40329    #[ignore = "perf A/B; run with --ignored --nocapture"]
40330    fn ab_to_flat_index_core_fmt() {
40331        println!("AB to_flat_index (ONE binary, ONE rch invocation; arms alternate in-block)");
40332        println!("BINARY_SHA256 {}", binary_sha256());
40333        // SERIAL regime: n below FLATIDX_PAR_MIN_ROWS (50_000) so neither arm spawns
40334        // threads. Isolates the per-row formatting cost with no scheduler noise.
40335        ab_regime("serial", 49_000, 60);
40336        // PARALLEL regime: the shipped path at reshape scale.
40337        ab_regime("parallel", 1_000_000, 5);
40338    }
40339}
40340
40341#[cfg(test)]
40342mod cached_parallelism_tests {
40343    use super::cached_available_parallelism;
40344
40345    /// br-frankenpandas-q1evw. THE NEGATIVE CASE, mirrored from `fp-columnar`'s
40346    /// `cached_parallelism_reports_the_real_machine_not_a_constant_kko5z`: the
40347    /// cheap way to make the cgroup walk disappear is to stop asking the OS at
40348    /// all and return a constant. That passes every timing test and silently
40349    /// serialises — or over-subscribes — the parallel `to_flat_index` path, and
40350    /// no benchmark here would catch it, because they all report the thread
40351    /// count the kernel CHOSE rather than the one it should have had.
40352    ///
40353    /// `fp-index` carries its own six-line copy of the helper (it deliberately
40354    /// has no `fp-columnar` dependency), so it needs its own pin: the copy can
40355    /// rot independently of the original.
40356    #[test]
40357    fn cached_parallelism_reports_the_real_machine_not_a_constant_q1evw() {
40358        let cached = cached_available_parallelism();
40359        let live = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
40360        assert_eq!(
40361            cached, live,
40362            "cached parallelism must equal what the OS reports, not a hardcoded value"
40363        );
40364        assert!(
40365            cached >= 1,
40366            "worker counts are sized from this; 0 would divide"
40367        );
40368    }
40369
40370    /// The cache must be a cache: one answer per process, so the two call sites
40371    /// that split `to_flat_index` cannot size their work from two different
40372    /// worker counts.
40373    #[test]
40374    fn cached_parallelism_is_stable_across_calls_q1evw() {
40375        let first = cached_available_parallelism();
40376        for _ in 0..64 {
40377            assert_eq!(cached_available_parallelism(), first);
40378        }
40379    }
40380}
40381
40382#[cfg(test)]
40383mod index_slice_tests {
40384    use super::{IndexLabel, IndexSlice};
40385
40386    #[test]
40387    fn test_index_slice_constructors() {
40388        let s_all: IndexSlice = IndexSlice::all();
40389        assert_eq!(s_all.start, None);
40390        assert_eq!(s_all.stop, None);
40391        assert_eq!(s_all.step, None);
40392
40393        let s_bounds =
40394            IndexSlice::from_bounds(Some(IndexLabel::Int64(0)), Some(IndexLabel::Int64(10)));
40395        assert_eq!(s_bounds.start, Some(IndexLabel::Int64(0)));
40396        assert_eq!(s_bounds.stop, Some(IndexLabel::Int64(10)));
40397        assert_eq!(s_bounds.step, None);
40398
40399        let s_start = IndexSlice::from_start(IndexLabel::Utf8("a".into()));
40400        assert_eq!(s_start.start, Some(IndexLabel::Utf8("a".into())));
40401        assert_eq!(s_start.stop, None);
40402
40403        let s_stop = IndexSlice::from_stop(IndexLabel::Utf8("z".into()));
40404        assert_eq!(s_stop.start, None);
40405        assert_eq!(s_stop.stop, Some(IndexLabel::Utf8("z".into())));
40406
40407        let s_step = IndexSlice::new(Some(0_i64), Some(20_i64), Some(2));
40408        assert_eq!(s_step.step, Some(2));
40409    }
40410}
40411
40412#[cfg(test)]
40413mod interval_index_tests {
40414    use fp_types::{Interval, IntervalClosed};
40415
40416    use super::{Index, IndexLabel, IntervalIndex, OrderedF64};
40417
40418    #[test]
40419    fn test_interval_index_constructors() {
40420        // from_breaks
40421        let ii = IntervalIndex::from_breaks(&[0.0, 1.0, 2.0, 3.0], IntervalClosed::Right)
40422            .expect("from_breaks");
40423        assert_eq!(ii.len(), 3);
40424        assert_eq!(ii.closed(), IntervalClosed::Right);
40425        assert!(!ii.is_empty());
40426        assert_eq!(ii.shape(), (3,));
40427        assert_eq!(ii.dtype(), "interval[float64, right]");
40428
40429        // Invalid breaks (< 2)
40430        assert!(IntervalIndex::from_breaks(&[0.0], IntervalClosed::Right).is_err());
40431
40432        // from_tuples
40433        let ii_tuples = IntervalIndex::from_tuples(&[(0.0, 1.0), (1.0, 2.0)], IntervalClosed::Both);
40434        assert_eq!(ii_tuples.len(), 2);
40435        assert_eq!(ii_tuples.closed(), IntervalClosed::Both);
40436
40437        // from_arrays
40438        let ii_arrays = IntervalIndex::from_arrays(&[0.0, 5.0], &[5.0, 10.0], IntervalClosed::Left)
40439            .expect("from_arrays");
40440        assert_eq!(ii_arrays.len(), 2);
40441        assert_eq!(ii_arrays.closed(), IntervalClosed::Left);
40442
40443        // Mismatched arrays length
40444        assert!(IntervalIndex::from_arrays(&[0.0], &[1.0, 2.0], IntervalClosed::Right).is_err());
40445
40446        // from_range
40447        let ii_range = IntervalIndex::from_range(
40448            Some(0.0),
40449            Some(10.0),
40450            Some(5),
40451            None,
40452            Some(IntervalClosed::Right),
40453        )
40454        .expect("from_range");
40455        assert_eq!(ii_range.len(), 5);
40456        assert_eq!(ii_range.values()[0].left, 0.0);
40457        assert_eq!(ii_range.values()[0].right, 2.0);
40458    }
40459
40460    #[test]
40461    fn test_interval_index_accessors_and_properties() {
40462        let ii = IntervalIndex::from_breaks(&[0.0, 2.0, 5.0], IntervalClosed::Right)
40463            .expect("from_breaks")
40464            .set_name("my_intervals");
40465
40466        assert_eq!(ii.name().map(|n| n.as_str()), Some("my_intervals"));
40467        assert_eq!(ii.names(), vec![Some("my_intervals".to_string())]);
40468
40469        let left_idx = ii.left();
40470        assert_eq!(left_idx.len(), 2);
40471        assert_eq!(left_idx.labels()[0], IndexLabel::Float64(OrderedF64(0.0)));
40472        assert_eq!(left_idx.labels()[1], IndexLabel::Float64(OrderedF64(2.0)));
40473
40474        let right_idx = ii.right();
40475        assert_eq!(right_idx.labels()[0], IndexLabel::Float64(OrderedF64(2.0)));
40476        assert_eq!(right_idx.labels()[1], IndexLabel::Float64(OrderedF64(5.0)));
40477
40478        let mid_idx = ii.mid();
40479        assert_eq!(mid_idx.labels()[0], IndexLabel::Float64(OrderedF64(1.0)));
40480        assert_eq!(mid_idx.labels()[1], IndexLabel::Float64(OrderedF64(3.5)));
40481
40482        let len_idx = ii.length();
40483        assert_eq!(len_idx.labels()[0], IndexLabel::Float64(OrderedF64(2.0)));
40484        assert_eq!(len_idx.labels()[1], IndexLabel::Float64(OrderedF64(3.0)));
40485
40486        // Monotonicity and uniqueness
40487        assert!(ii.is_unique());
40488        assert!(ii.is_monotonic_increasing());
40489        assert!(!ii.is_monotonic_decreasing());
40490        assert!(!ii.is_overlapping());
40491
40492        // Null masks
40493        assert!(!ii.hasnans());
40494        assert_eq!(ii.isna(), vec![false, false]);
40495        assert_eq!(ii.isnull(), vec![false, false]);
40496        assert_eq!(ii.notna(), vec![true, true]);
40497        assert_eq!(ii.notnull(), vec![true, true]);
40498        assert_eq!(ii.dropna(), ii);
40499
40500        // Rename
40501        let renamed = ii.rename_index(Some("new_name"));
40502        assert_eq!(renamed.name().map(|n| n.as_str()), Some("new_name"));
40503    }
40504
40505    #[test]
40506    fn test_interval_index_loc_and_contains() {
40507        let ii = IntervalIndex::from_breaks(&[0.0, 10.0, 20.0], IntervalClosed::Right)
40508            .expect("from_breaks");
40509
40510        // contains point
40511        assert_eq!(ii.contains(5.0), vec![true, false]);
40512        assert_eq!(ii.contains(15.0), vec![false, true]);
40513        assert_eq!(ii.contains(0.0), vec![false, false]); // right closed: (0, 10]
40514        assert_eq!(ii.contains(10.0), vec![true, false]);
40515
40516        // get_loc
40517        assert_eq!(ii.get_loc(5.0).unwrap(), 0);
40518        assert_eq!(ii.get_loc(15.0).unwrap(), 1);
40519        assert!(ii.get_loc(25.0).is_err());
40520
40521        // get_indexer
40522        let idxs = ii.get_indexer(&[5.0, 15.0, 25.0]);
40523        assert_eq!(idxs, vec![Some(0), Some(1), None]);
40524
40525        // get_loc_interval
40526        let target = Interval::new(0.0, 10.0, IntervalClosed::Right);
40527        assert_eq!(ii.get_loc_interval(&target).unwrap(), 0);
40528        let missing_target = Interval::new(0.0, 10.0, IntervalClosed::Left);
40529        assert!(ii.get_loc_interval(&missing_target).is_err());
40530
40531        // Overlapping detection
40532        let overlapping_ii = IntervalIndex::new(vec![
40533            Interval::new(0.0, 10.0, IntervalClosed::Both),
40534            Interval::new(5.0, 15.0, IntervalClosed::Both),
40535        ]);
40536        assert!(overlapping_ii.is_overlapping());
40537        // get_loc on overlapping point 7.0 should return error
40538        assert!(overlapping_ii.get_loc(7.0).is_err());
40539    }
40540
40541    #[test]
40542    fn test_interval_index_slicing_and_conversion() {
40543        let ii = IntervalIndex::from_breaks(&[0.0, 1.0, 2.0, 3.0, 4.0], IntervalClosed::Right)
40544            .expect("from_breaks")
40545            .set_name("sample");
40546
40547        assert_eq!(
40548            ii.get_item(0).unwrap(),
40549            Interval::new(0.0, 1.0, IntervalClosed::Right)
40550        );
40551        assert_eq!(
40552            ii.get_item(-1).unwrap(),
40553            Interval::new(3.0, 4.0, IntervalClosed::Right)
40554        );
40555        assert!(ii.get_item(10).is_err());
40556
40557        let h = ii.head(2);
40558        assert_eq!(h.len(), 2);
40559        assert_eq!(
40560            h.get_item(1).unwrap(),
40561            Interval::new(1.0, 2.0, IntervalClosed::Right)
40562        );
40563
40564        let t = ii.tail(2);
40565        assert_eq!(t.len(), 2);
40566        assert_eq!(
40567            t.get_item(0).unwrap(),
40568            Interval::new(2.0, 3.0, IntervalClosed::Right)
40569        );
40570
40571        let taken = ii.take(&[0, 2]).expect("take");
40572        assert_eq!(taken.len(), 2);
40573        assert_eq!(
40574            taken.get_item(0).unwrap(),
40575            Interval::new(0.0, 1.0, IntervalClosed::Right)
40576        );
40577        assert_eq!(
40578            taken.get_item(1).unwrap(),
40579            Interval::new(2.0, 3.0, IntervalClosed::Right)
40580        );
40581
40582        // set_closed
40583        let both = ii.set_closed(IntervalClosed::Both);
40584        assert_eq!(both.closed(), IntervalClosed::Both);
40585        assert_eq!(both.get_item(0).unwrap().closed, IntervalClosed::Both);
40586
40587        // to_index
40588        let idx = ii.to_index();
40589        assert_eq!(idx.len(), 4);
40590        assert_eq!(idx.name().map(|n| n.as_str()), Some("sample"));
40591
40592        // From<IntervalIndex> for Index
40593        let idx_from: Index = ii.into();
40594        assert_eq!(idx_from.len(), 4);
40595    }
40596
40597    #[test]
40598    fn test_interval_index_closed_and_tuples() {
40599        let ii_right = IntervalIndex::from_breaks(&[0.0, 1.5, 3.0], IntervalClosed::Right)
40600            .expect("from_breaks");
40601        assert!(!ii_right.closed_left());
40602        assert!(ii_right.closed_right());
40603        assert!(ii_right.open_left());
40604        assert!(!ii_right.open_right());
40605        assert!(ii_right.is_non_overlapping_monotonic());
40606        assert_eq!(ii_right.to_tuples(), vec![(0.0, 1.5), (1.5, 3.0)]);
40607        assert_eq!(ii_right.to_list().len(), 2);
40608        assert_eq!(ii_right.tolist().len(), 2);
40609
40610        let ii_both = IntervalIndex::from_breaks(&[0.0, 1.5, 3.0], IntervalClosed::Both)
40611            .expect("from_breaks");
40612        assert!(ii_both.closed_left());
40613        assert!(ii_both.closed_right());
40614        assert!(!ii_both.open_left());
40615        assert!(!ii_both.open_right());
40616        // Touching endpoints with Both are overlapping at 1.5
40617        assert!(ii_both.is_overlapping());
40618        assert!(!ii_both.is_non_overlapping_monotonic());
40619
40620        let ii_left =
40621            IntervalIndex::from_breaks(&[0.0, 1.0], IntervalClosed::Left).expect("from_breaks");
40622        assert!(ii_left.closed_left());
40623        assert!(!ii_left.closed_right());
40624        assert!(!ii_left.open_left());
40625        assert!(ii_left.open_right());
40626
40627        let ii_neither =
40628            IntervalIndex::from_breaks(&[0.0, 1.0], IntervalClosed::Neither).expect("from_breaks");
40629        assert!(!ii_neither.closed_left());
40630        assert!(!ii_neither.closed_right());
40631        assert!(ii_neither.open_left());
40632        assert!(ii_neither.open_right());
40633
40634        // Decreasing non-overlapping
40635        let ii_dec =
40636            IntervalIndex::from_tuples(&[(3.0, 5.0), (1.0, 3.0), (0.0, 1.0)], IntervalClosed::Left);
40637        assert!(ii_dec.is_monotonic_decreasing());
40638        assert!(!ii_dec.is_monotonic_increasing());
40639        assert!(!ii_dec.is_overlapping());
40640        assert!(ii_dec.is_non_overlapping_monotonic());
40641    }
40642
40643    /// pandas 2.2.3 (numpy `around`, halves to even):
40644    /// Index([1.25, 2.5, 3.5, -0.5, 0.125]).round(0) -> [1.0, 2.0, 4.0, -0.0, 0.0],
40645    /// Index([1.25, 2.5, 0.125]).round(1) -> [1.2, 2.5, 0.1],
40646    /// Index([15, 25, 14]).round(-1) -> [20, 20, 10]; the name is kept.
40647    /// `round` used to return the index unchanged (fvsao.5).
40648    #[test]
40649    fn round_halves_to_even_like_numpy_fvsao5() {
40650        let floats = |xs: &[f64]| {
40651            Index::new(
40652                xs.iter()
40653                    .map(|&x| IndexLabel::Float64(OrderedF64(x)))
40654                    .collect(),
40655            )
40656        };
40657        let values = |idx: &Index| -> Vec<IndexLabel> { idx.labels().to_vec() };
40658        let named = floats(&[1.25, 2.5, 3.5, -0.5, 0.125]).rename_index(Some("n"));
40659        let rounded = named.round(0);
40660        assert_eq!(
40661            values(&rounded),
40662            values(&floats(&[1.0, 2.0, 4.0, -0.0, 0.0]))
40663        );
40664        assert_eq!(rounded.name().map(|n| n.as_str()), Some("n"));
40665        assert_eq!(
40666            values(&floats(&[1.25, 2.5, 0.125]).round(1)),
40667            values(&floats(&[1.2, 2.5, 0.1]))
40668        );
40669        let ints = Index::new(vec![
40670            IndexLabel::Int64(15),
40671            IndexLabel::Int64(25),
40672            IndexLabel::Int64(14),
40673        ]);
40674        assert_eq!(
40675            values(&ints.round(-1)),
40676            vec![
40677                IndexLabel::Int64(20),
40678                IndexLabel::Int64(20),
40679                IndexLabel::Int64(10)
40680            ]
40681        );
40682        // Integers are untouched by a non-negative decimals, and so is a
40683        // string label.
40684        assert_eq!(values(&ints.round(2)), values(&ints));
40685        let text = Index::new(vec![IndexLabel::Utf8("1.25".to_owned())]);
40686        assert_eq!(values(&text.round(0)), values(&text));
40687    }
40688}
40689
40690/// infer_freq as pandas' `_FrequencyInferer` (acelo): month / quarter / year
40691/// starts and ends with their anchors, weeks, business days, weeks of the
40692/// month, signed steps. Each row is pandas 2.2.3's `date_range` of that
40693/// family and its `infer_freq`.
40694#[cfg(test)]
40695mod infer_freq_like_pandas_acelo {
40696    use super::infer_freq_from_timestamps;
40697
40698    #[test]
40699    fn every_family_as_pandas_infers_it() {
40700        // Each row: the stamps, then pandas' answer after "->".
40701        let cases = [
40702            "2024-01-01 2024-02-01 2024-03-01 2024-04-01 -> MS",
40703            "2024-01-31 2024-02-29 2024-03-31 2024-04-30 -> ME",
40704            // pandas anchors QS on the month sharing its first month's
40705            // remainder by 3: January -> QS-OCT.
40706            "2024-01-01 2024-04-01 2024-07-01 2024-10-01 -> QS-OCT",
40707            "2024-02-29 2024-05-31 2024-08-31 2024-11-30 -> QE-NOV",
40708            "2024-01-01 2025-01-01 2026-01-01 2027-01-01 -> YS-JAN",
40709            "2024-06-30 2025-06-30 2026-06-30 2027-06-30 -> YE-JUN",
40710            "2024-01-07 2024-01-14 2024-01-21 2024-01-28 -> W-SUN",
40711            "2024-01-05 2024-01-19 2024-02-02 2024-02-16 -> 2W-FRI",
40712            "2024-01-04 2024-01-05 2024-01-08 2024-01-09 -> B",
40713            "2024-01-01 2024-01-03 2024-01-05 2024-01-07 -> 2D",
40714            "2024-01-01T00:00:00 2024-01-01T03:00:00 2024-01-01T06:00:00 -> 3h",
40715            "2024-01-01T00:00:00 2024-01-01T00:15:00 2024-01-01T00:30:00 -> 15min",
40716            "2024-01-31 2024-02-29 2024-03-29 2024-04-30 -> BME",
40717            "2024-03-29 2024-06-28 2024-09-30 2024-12-31 -> BQE-DEC",
40718            "2024-01-31 2024-07-31 2025-01-31 2025-07-31 -> 2QE-OCT",
40719            "2024-01-19 2024-02-16 2024-03-15 2024-04-19 -> WOM-3FRI",
40720            "2024-01-04 2024-01-03 2024-01-02 2024-01-01 -> -1D",
40721            // NEGATIVE: irregular steps, one day of the month that is neither
40722            // start nor end, and year starts with a two-year gap stay None.
40723            "2024-01-01 2024-01-02 2024-01-05 -> None",
40724            "2024-03-15 2024-04-15 2024-05-15 -> None",
40725            "2024-01-01 2025-01-01 2026-01-01 2028-01-03 -> None",
40726        ];
40727        for case in cases {
40728            let (stamps, want) = case.split_once(" -> ").unwrap();
40729            let stamps: Vec<&str> = stamps.split_whitespace().collect();
40730            let got = infer_freq_from_timestamps(&stamps).unwrap();
40731            assert_eq!(got.as_deref().unwrap_or("None"), want, "{case}");
40732        }
40733    }
40734}