1#![forbid(unsafe_code)]
2#![warn(rustdoc::broken_intra_doc_links)]
3
4use serde::{Deserialize, Serialize};
71use thiserror::Error;
72
73#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
74#[serde(rename_all = "snake_case")]
75pub enum DType {
76 Null,
77 Bool,
78 #[serde(rename = "boolean")]
80 BoolNullable,
81 Int64,
82 #[serde(rename = "Int64")]
84 Int64Nullable,
85 Float64,
86 #[serde(rename = "Float64")]
107 Float64Nullable,
108 #[serde(alias = "string", alias = "str")]
109 Utf8,
110 Categorical,
111 Timedelta64,
112 Datetime64 {
117 #[serde(default, skip_serializing_if = "Option::is_none")]
118 tz: Option<String>,
119 },
120 Period,
122 Interval,
124 Sparse,
125}
126
127impl DType {
128 #[must_use]
130 pub const fn is_numeric(&self) -> bool {
131 matches!(
132 self,
133 Self::Int64 | Self::Int64Nullable | Self::Float64 | Self::Float64Nullable
134 )
135 }
136
137 #[must_use]
139 pub const fn is_integer(&self) -> bool {
140 matches!(self, Self::Int64 | Self::Int64Nullable)
141 }
142
143 #[must_use]
145 pub const fn is_floating(&self) -> bool {
146 matches!(self, Self::Float64 | Self::Float64Nullable)
147 }
148
149 #[must_use]
151 pub const fn is_bool(&self) -> bool {
152 matches!(self, Self::Bool | Self::BoolNullable)
153 }
154
155 #[must_use]
157 pub const fn is_object(&self) -> bool {
158 matches!(self, Self::Utf8)
159 }
160
161 #[must_use]
163 pub const fn is_datetime(&self) -> bool {
164 matches!(self, Self::Datetime64 { .. })
165 }
166
167 #[must_use]
169 pub const fn is_timedelta(&self) -> bool {
170 matches!(self, Self::Timedelta64)
171 }
172
173 #[must_use]
175 pub const fn is_categorical(&self) -> bool {
176 matches!(self, Self::Categorical)
177 }
178
179 #[must_use]
181 pub const fn is_sparse(&self) -> bool {
182 matches!(self, Self::Sparse)
183 }
184
185 #[must_use]
187 pub const fn is_period(&self) -> bool {
188 matches!(self, Self::Period)
189 }
190
191 #[must_use]
193 pub const fn is_interval(&self) -> bool {
194 matches!(self, Self::Interval)
195 }
196
197 #[must_use]
201 pub const fn name(&self) -> &'static str {
202 match self {
203 Self::Bool => "bool",
204 Self::BoolNullable => "boolean",
205 Self::Int64 => "int64",
206 Self::Int64Nullable => "Int64",
207 Self::Float64 => "float64",
208 Self::Float64Nullable => "Float64",
211 Self::Utf8 => "object",
212 Self::Datetime64 { .. } => "datetime64[ns]",
213 Self::Timedelta64 => "timedelta64[ns]",
214 Self::Categorical => "category",
215 Self::Period => "period",
216 Self::Interval => "interval",
217 Self::Sparse => "Sparse",
218 Self::Null => "object",
219 }
220 }
221
222 #[must_use]
226 pub const fn kind(&self) -> char {
227 match self {
228 Self::Bool | Self::BoolNullable => 'b',
229 Self::Int64 | Self::Int64Nullable => 'i',
230 Self::Float64 | Self::Float64Nullable => 'f',
234 Self::Utf8 => 'O',
235 Self::Datetime64 { .. } => 'M',
236 Self::Timedelta64 => 'm',
237 Self::Categorical => 'O',
238 Self::Period => 'O',
239 Self::Interval => 'O',
240 Self::Sparse => 'O',
241 Self::Null => 'O',
242 }
243 }
244
245 #[must_use]
249 pub const fn itemsize(&self) -> usize {
250 match self {
251 Self::Bool | Self::BoolNullable => 1,
252 Self::Int64
253 | Self::Int64Nullable
254 | Self::Float64
255 | Self::Float64Nullable
256 | Self::Datetime64 { .. }
257 | Self::Timedelta64
258 | Self::Period => 8,
259 Self::Utf8 | Self::Categorical | Self::Interval | Self::Sparse | Self::Null => 8,
260 }
261 }
262
263 #[must_use]
267 pub const fn is_extension(&self) -> bool {
268 matches!(
269 self,
270 Self::Categorical
271 | Self::Sparse
272 | Self::Period
273 | Self::Interval
274 | Self::Int64Nullable
275 | Self::Float64Nullable
276 | Self::BoolNullable
277 )
278 }
279
280 #[must_use]
285 pub const fn is_nullable(&self) -> bool {
286 matches!(
287 self,
288 Self::Int64Nullable | Self::Float64Nullable | Self::BoolNullable
289 )
290 }
291
292 #[must_use]
297 pub fn to_non_nullable(&self) -> Self {
298 match self {
299 Self::Int64Nullable => Self::Int64,
300 Self::Float64Nullable => Self::Float64,
301 Self::BoolNullable => Self::Bool,
302 other => other.clone(),
303 }
304 }
305
306 #[must_use]
311 pub fn to_nullable(&self) -> Self {
312 match self {
313 Self::Int64 => Self::Int64Nullable,
314 Self::Float64 => Self::Float64Nullable,
315 Self::Bool => Self::BoolNullable,
316 other => other.clone(),
317 }
318 }
319
320 #[must_use]
324 pub const fn is_signed_integer(&self) -> bool {
325 matches!(self, Self::Int64 | Self::Int64Nullable)
326 }
327
328 #[must_use]
348 pub const fn is_string_dtype(&self) -> bool {
349 matches!(self, Self::Utf8)
350 }
351
352 #[must_use]
356 pub const fn is_any_real_numeric(&self) -> bool {
357 self.is_numeric()
358 }
359
360 #[must_use]
364 pub const fn is_datetime_like(&self) -> bool {
365 matches!(
366 self,
367 Self::Datetime64 { .. } | Self::Timedelta64 | Self::Period
368 )
369 }
370
371 #[must_use]
375 pub const fn char(&self) -> char {
376 match self {
377 Self::Bool | Self::BoolNullable => '?',
378 Self::Int64 | Self::Int64Nullable => 'l',
379 Self::Float64 | Self::Float64Nullable => 'd',
380 Self::Utf8 => 'O',
381 Self::Datetime64 { .. } => 'M',
382 Self::Timedelta64 => 'm',
383 Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => 'O',
384 }
385 }
386
387 #[must_use]
391 pub const fn num(&self) -> i32 {
392 match self {
393 Self::Bool | Self::BoolNullable => 0,
394 Self::Int64 | Self::Int64Nullable => 7,
395 Self::Float64 | Self::Float64Nullable => 12,
396 Self::Utf8 => 17,
397 Self::Datetime64 { .. } => 21,
398 Self::Timedelta64 => 22,
399 Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => 17,
400 }
401 }
402
403 #[must_use]
407 pub const fn byteorder(&self) -> char {
408 '='
409 }
410
411 #[must_use]
415 pub const fn str_repr(&self) -> &'static str {
416 match self {
417 Self::Bool | Self::BoolNullable => "|b1",
418 Self::Int64 | Self::Int64Nullable => "<i8",
419 Self::Float64 | Self::Float64Nullable => "<f8",
420 Self::Utf8 => "|O8",
421 Self::Datetime64 { .. } => "<M8[ns]",
422 Self::Timedelta64 => "<m8[ns]",
423 Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => "|O8",
424 }
425 }
426
427 #[must_use]
429 pub const fn datetime64_naive() -> Self {
430 Self::Datetime64 { tz: None }
431 }
432
433 #[must_use]
435 pub fn datetime64_tz(tz: impl Into<String>) -> Self {
436 Self::Datetime64 {
437 tz: Some(tz.into()),
438 }
439 }
440
441 #[must_use]
443 pub fn timezone(&self) -> Option<&str> {
444 match self {
445 Self::Datetime64 { tz } => tz.as_deref(),
446 _ => None,
447 }
448 }
449
450 #[must_use]
452 pub fn display_name(&self) -> String {
453 match self {
454 Self::Datetime64 { tz: Some(tz) } => format!("datetime64[ns, {tz}]"),
455 _ => self.name().to_owned(),
456 }
457 }
458}
459
460impl std::str::FromStr for DType {
461 type Err = TypeError;
462
463 fn from_str(s: &str) -> Result<Self, Self::Err> {
464 let trimmed = s.trim();
465 match trimmed {
466 "int64" | "int" | "i8" | "integer" | "<i8" => Ok(Self::Int64),
467 "Int64" | "Int64Dtype" => Ok(Self::Int64Nullable),
468 "float64" | "float" | "f8" | "floating" | "<f8" => Ok(Self::Float64),
469 "Float64" | "Float64Dtype" => Ok(Self::Float64Nullable),
470 "bool" | "|b1" => Ok(Self::Bool),
471 "boolean" | "BooleanDtype" => Ok(Self::BoolNullable),
472 "string" | "str" | "object" | "utf8" | "Utf8" | "O" | "|O8" => Ok(Self::Utf8),
473 "category" | "categorical" | "CategoricalDtype" => Ok(Self::Categorical),
474 "timedelta64" | "timedelta64[ns]" | "timedelta" | "Timedelta" | "<m8[ns]" => {
475 Ok(Self::Timedelta64)
476 }
477 "period" | "Period" => Ok(Self::Period),
478 "interval" | "Interval" => Ok(Self::Interval),
479 "sparse" | "Sparse" => Ok(Self::Sparse),
480 "null" | "Null" => Ok(Self::Null),
481 _ if trimmed.starts_with("period[") || trimmed.starts_with("Period[") => {
482 Ok(Self::Period)
483 }
484 _ if trimmed.starts_with("interval[") || trimmed.starts_with("Interval[") => {
485 Ok(Self::Interval)
486 }
487 _ if trimmed.starts_with("sparse[") || trimmed.starts_with("Sparse[") => {
488 Ok(Self::Sparse)
489 }
490 _ if trimmed.starts_with("datetime64")
491 || trimmed.starts_with("datetime")
492 || trimmed.starts_with("<M8") =>
493 {
494 if let Some(idx) = trimmed.find(',') {
495 let tz_part = if let Some(rest) = trimmed.get(idx + 1..) {
496 rest.trim().trim_end_matches(']').trim().to_string()
497 } else {
498 String::new()
499 };
500 Ok(Self::Datetime64 { tz: Some(tz_part) })
501 } else {
502 Ok(Self::Datetime64 { tz: None })
503 }
504 }
505 _ => Err(TypeError::ValueNotParseable {
506 value: s.to_string(),
507 target: "DType".to_string(),
508 }),
509 }
510 }
511}
512
513impl std::fmt::Display for DType {
514 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515 write!(f, "{}", self.display_name())
516 }
517}
518
519#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
537pub enum NumericWidth {
538 #[serde(rename = "int8")]
539 Int8,
540 #[serde(rename = "int16")]
541 Int16,
542 #[serde(rename = "int32")]
543 Int32,
544 #[serde(rename = "uint8")]
545 UInt8,
546 #[serde(rename = "uint16")]
547 UInt16,
548 #[serde(rename = "uint32")]
549 UInt32,
550 #[serde(rename = "uint64")]
551 UInt64,
552 #[serde(rename = "float32")]
553 Float32,
554}
555
556impl NumericWidth {
557 pub const ALL: [Self; 8] = [
559 Self::Int8,
560 Self::Int16,
561 Self::Int32,
562 Self::UInt8,
563 Self::UInt16,
564 Self::UInt32,
565 Self::UInt64,
566 Self::Float32,
567 ];
568
569 #[must_use]
572 pub const fn name(self, nullable: bool) -> &'static str {
573 match (self, nullable) {
574 (Self::Int8, false) => "int8",
575 (Self::Int16, false) => "int16",
576 (Self::Int32, false) => "int32",
577 (Self::UInt8, false) => "uint8",
578 (Self::UInt16, false) => "uint16",
579 (Self::UInt32, false) => "uint32",
580 (Self::UInt64, false) => "uint64",
581 (Self::Float32, false) => "float32",
582 (Self::Int8, true) => "Int8",
583 (Self::Int16, true) => "Int16",
584 (Self::Int32, true) => "Int32",
585 (Self::UInt8, true) => "UInt8",
586 (Self::UInt16, true) => "UInt16",
587 (Self::UInt32, true) => "UInt32",
588 (Self::UInt64, true) => "UInt64",
589 (Self::Float32, true) => "Float32",
590 }
591 }
592
593 #[must_use]
598 pub fn parse(name: &str) -> Option<(Self, bool)> {
599 let name = name.trim();
600 let name = name
601 .strip_prefix('<')
602 .or_else(|| name.strip_prefix('|'))
603 .or_else(|| name.strip_prefix('='))
604 .unwrap_or(name);
605 let found = match name {
606 "int8" | "i1" | "byte" => (Self::Int8, false),
607 "int16" | "i2" | "short" => (Self::Int16, false),
608 "int32" | "i4" | "intc" => (Self::Int32, false),
609 "uint8" | "u1" | "ubyte" => (Self::UInt8, false),
610 "uint16" | "u2" | "ushort" => (Self::UInt16, false),
611 "uint32" | "u4" | "uintc" => (Self::UInt32, false),
612 "uint64" | "u8" | "uint" | "ulonglong" | "uintp" => (Self::UInt64, false),
613 "float32" | "f4" | "single" => (Self::Float32, false),
614 "Int8" | "Int8Dtype" => (Self::Int8, true),
615 "Int16" | "Int16Dtype" => (Self::Int16, true),
616 "Int32" | "Int32Dtype" => (Self::Int32, true),
617 "UInt8" | "UInt8Dtype" => (Self::UInt8, true),
618 "UInt16" | "UInt16Dtype" => (Self::UInt16, true),
619 "UInt32" | "UInt32Dtype" => (Self::UInt32, true),
620 "UInt64" | "UInt64Dtype" => (Self::UInt64, true),
621 "Float32" | "Float32Dtype" => (Self::Float32, true),
622 _ => return None,
623 };
624 Some(found)
625 }
626
627 #[must_use]
629 pub const fn storage(self, nullable: bool) -> DType {
630 match (self.is_float(), nullable) {
631 (true, false) => DType::Float64,
632 (true, true) => DType::Float64Nullable,
633 (false, false) => DType::Int64,
634 (false, true) => DType::Int64Nullable,
635 }
636 }
637
638 #[must_use]
641 pub const fn fits_storage(self, dtype: &DType) -> bool {
642 if self.is_float() {
643 matches!(dtype, DType::Float64 | DType::Float64Nullable)
644 } else {
645 matches!(dtype, DType::Int64 | DType::Int64Nullable)
646 }
647 }
648
649 #[must_use]
651 pub const fn itemsize(self) -> usize {
652 match self {
653 Self::Int8 | Self::UInt8 => 1,
654 Self::Int16 | Self::UInt16 => 2,
655 Self::Int32 | Self::UInt32 | Self::Float32 => 4,
656 Self::UInt64 => 8,
657 }
658 }
659
660 #[must_use]
662 pub const fn kind(self) -> char {
663 match self {
664 Self::Int8 | Self::Int16 | Self::Int32 => 'i',
665 Self::UInt8 | Self::UInt16 | Self::UInt32 | Self::UInt64 => 'u',
666 Self::Float32 => 'f',
667 }
668 }
669
670 #[must_use]
671 pub const fn is_float(self) -> bool {
672 matches!(self, Self::Float32)
673 }
674
675 #[must_use]
676 pub const fn is_unsigned(self) -> bool {
677 matches!(
678 self,
679 Self::UInt8 | Self::UInt16 | Self::UInt32 | Self::UInt64
680 )
681 }
682
683 #[must_use]
687 pub const fn int_bounds(self) -> Option<(i64, i64)> {
688 match self {
689 Self::Int8 => Some((i8::MIN as i64, i8::MAX as i64)),
690 Self::Int16 => Some((i16::MIN as i64, i16::MAX as i64)),
691 Self::Int32 => Some((i32::MIN as i64, i32::MAX as i64)),
692 Self::UInt8 => Some((0, u8::MAX as i64)),
693 Self::UInt16 => Some((0, u16::MAX as i64)),
694 Self::UInt32 => Some((0, u32::MAX as i64)),
695 Self::UInt64 => Some((0, i64::MAX)),
696 Self::Float32 => None,
697 }
698 }
699
700 #[must_use]
702 pub const fn holds_int(self, value: i64) -> bool {
703 match self.int_bounds() {
704 Some((low, high)) => low <= value && value <= high,
705 None => false,
706 }
707 }
708
709 #[must_use]
715 pub const fn wrap_int(self, value: i64) -> Option<i64> {
716 match self {
717 Self::Int8 => Some(value as i8 as i64),
718 Self::Int16 => Some(value as i16 as i64),
719 Self::Int32 => Some(value as i32 as i64),
720 Self::UInt8 => Some(value as u8 as i64),
721 Self::UInt16 => Some(value as u16 as i64),
722 Self::UInt32 => Some(value as u32 as i64),
723 Self::UInt64 if value >= 0 => Some(value),
724 Self::UInt64 | Self::Float32 => None,
725 }
726 }
727
728 #[must_use]
732 #[allow(clippy::cast_possible_truncation)]
733 pub fn round_f32(value: f64) -> f64 {
734 f64::from(value as f32)
735 }
736
737 #[must_use]
741 pub const fn smallest_signed(low: i64, high: i64) -> Option<Self> {
742 if low >= i8::MIN as i64 && high <= i8::MAX as i64 {
743 Some(Self::Int8)
744 } else if low >= i16::MIN as i64 && high <= i16::MAX as i64 {
745 Some(Self::Int16)
746 } else if low >= i32::MIN as i64 && high <= i32::MAX as i64 {
747 Some(Self::Int32)
748 } else {
749 None
750 }
751 }
752
753 #[must_use]
757 pub const fn smallest_unsigned(low: i64, high: i64) -> Option<Self> {
758 if low < 0 {
759 None
760 } else if high <= u8::MAX as i64 {
761 Some(Self::UInt8)
762 } else if high <= u16::MAX as i64 {
763 Some(Self::UInt16)
764 } else if high <= u32::MAX as i64 {
765 Some(Self::UInt32)
766 } else {
767 Some(Self::UInt64)
768 }
769 }
770
771 #[must_use]
776 pub const fn for_category_codes(categories: usize) -> Option<Self> {
777 if categories < i8::MAX as usize {
778 Some(Self::Int8)
779 } else if categories < i16::MAX as usize {
780 Some(Self::Int16)
781 } else if categories < i32::MAX as usize {
782 Some(Self::Int32)
783 } else {
784 None
785 }
786 }
787}
788
789#[must_use]
799pub fn numpy_pairwise_sum<T>(values: &[T]) -> T
800where
801 T: Copy + Default + std::ops::Add<Output = T>,
802{
803 if values.len() <= PAIRWISE_BLOCK {
805 return pairwise_block(values);
806 }
807 let mut half = values.len() / 2;
808 half -= half % 8;
809 numpy_pairwise_sum(&values[..half]) + numpy_pairwise_sum(&values[half..])
810}
811
812const PAIRWISE_BLOCK: usize = 128;
814
815pub fn numpy_pairwise_sum_by<T, F>(len: usize, fill: &F) -> T
820where
821 T: Copy + Default + std::ops::Add<Output = T>,
822 F: Fn(usize, &mut [T]),
823{
824 pairwise_range(0, len, fill)
825}
826
827fn pairwise_range<T, F>(start: usize, len: usize, fill: &F) -> T
829where
830 T: Copy + Default + std::ops::Add<Output = T>,
831 F: Fn(usize, &mut [T]),
832{
833 if len <= PAIRWISE_BLOCK {
834 let mut buffer = [T::default(); PAIRWISE_BLOCK];
835 let block = &mut buffer[..len];
836 fill(start, block);
837 return pairwise_block(block);
838 }
839 let mut half = len / 2;
840 half -= half % 8;
841 pairwise_range(start, half, fill) + pairwise_range(start + half, len - half, fill)
842}
843
844fn numpy_pairwise_sum_of<T, F>(values: &[f64], term: &F) -> T
847where
848 T: Copy + Default + std::ops::Add<Output = T>,
849 F: Fn(f64) -> T,
850{
851 if values.len() > PAIRWISE_BLOCK {
852 let mut half = values.len() / 2;
853 half -= half % 8;
854 return numpy_pairwise_sum_of(&values[..half], term)
855 + numpy_pairwise_sum_of(&values[half..], term);
856 }
857 let n = values.len();
858 if n < 8 {
859 return values
860 .iter()
861 .fold(T::default(), |acc, &value| acc + term(value));
862 }
863 let mut sums: [T; 8] = std::array::from_fn(|lane| term(values[lane]));
864 let whole = n - n % 8;
865 for block in values[8..whole].as_chunks::<8>().0 {
866 for (sum, &value) in sums.iter_mut().zip(block) {
867 *sum = *sum + term(value);
868 }
869 }
870 let folded =
871 ((sums[0] + sums[1]) + (sums[2] + sums[3])) + ((sums[4] + sums[5]) + (sums[6] + sums[7]));
872 values[whole..]
873 .iter()
874 .fold(folded, |acc, &value| acc + term(value))
875}
876
877fn pairwise_block<T>(values: &[T]) -> T
879where
880 T: Copy + Default + std::ops::Add<Output = T>,
881{
882 let n = values.len();
883 if n < 8 {
884 return values.iter().fold(T::default(), |acc, &value| acc + value);
885 }
886 let mut sums = [T::default(); 8];
887 sums.copy_from_slice(&values[..8]);
888 let whole = n - n % 8;
889 for block in values[8..whole].as_chunks::<8>().0 {
890 for (sum, &value) in sums.iter_mut().zip(block) {
891 *sum = *sum + value;
892 }
893 }
894 let folded =
895 ((sums[0] + sums[1]) + (sums[2] + sums[3])) + ((sums[4] + sums[5]) + (sums[6] + sums[7]));
896 values[whole..]
897 .iter()
898 .fold(folded, |acc, &value| acc + value)
899}
900
901#[derive(Debug, Clone, Copy)]
906pub enum ReductionValues<'a> {
907 Float(&'a [f64]),
908 Int(&'a [i64]),
909 FloatChunks(&'a [&'a [f64]]),
910 IntChunks(&'a [&'a [i64]]),
911}
912
913impl ReductionValues<'_> {
914 fn len(self) -> usize {
915 match self {
916 Self::Float(values) => values.len(),
917 Self::Int(values) => values.len(),
918 Self::FloatChunks(chunks) => chunks.iter().map(|chunk| chunk.len()).sum(),
919 Self::IntChunks(chunks) => chunks.iter().map(|chunk| chunk.len()).sum(),
920 }
921 }
922}
923
924struct ValueReader<'a> {
927 values: ReductionValues<'a>,
928 cursor: std::cell::Cell<(usize, usize)>,
930}
931
932impl<'a> ValueReader<'a> {
933 fn new(values: ReductionValues<'a>) -> Self {
934 Self {
935 values,
936 cursor: std::cell::Cell::new((0, 0)),
937 }
938 }
939
940 #[allow(clippy::cast_precision_loss)] fn read(&self, start: usize, block: &mut [f64]) {
943 match self.values {
944 ReductionValues::Float(values) => {
945 block.copy_from_slice(&values[start..start + block.len()]);
946 }
947 ReductionValues::Int(values) => {
948 for (slot, &value) in block.iter_mut().zip(&values[start..]) {
949 *slot = value as f64;
950 }
951 }
952 ReductionValues::FloatChunks(chunks) => {
953 self.read_chunks(chunks, start, block, |slots, values| {
954 slots.copy_from_slice(values);
955 });
956 }
957 ReductionValues::IntChunks(chunks) => {
958 self.read_chunks(chunks, start, block, |slots, values| {
959 for (slot, &value) in slots.iter_mut().zip(values) {
960 *slot = value as f64;
961 }
962 });
963 }
964 }
965 }
966
967 fn read_chunks<T>(
968 &self,
969 chunks: &[&[T]],
970 start: usize,
971 block: &mut [f64],
972 copy: impl Fn(&mut [f64], &[T]),
973 ) {
974 let (mut chunk, mut chunk_start) = self.cursor.get();
975 if start < chunk_start {
976 (chunk, chunk_start) = (0, 0);
977 }
978 while start >= chunk_start + chunks[chunk].len() {
979 chunk_start += chunks[chunk].len();
980 chunk += 1;
981 }
982 self.cursor.set((chunk, chunk_start));
983 let mut filled = 0;
984 while filled < block.len() {
985 let offset = start + filled - chunk_start;
986 let take = (chunks[chunk].len() - offset).min(block.len() - filled);
987 copy(
988 &mut block[filled..filled + take],
989 &chunks[chunk][offset..offset + take],
990 );
991 filled += take;
992 if filled < block.len() {
993 chunk_start += chunks[chunk].len();
994 chunk += 1;
995 }
996 }
997 }
998}
999
1000#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1003pub enum MissingLayout {
1004 Numpy,
1008 Masked,
1011}
1012
1013const NUMPY_CAST_BUFFER: usize = 8192;
1016
1017#[derive(Debug, Clone, Copy)]
1023pub struct PandasReductions<'a> {
1024 values: ReductionValues<'a>,
1025 present: Option<&'a [u64]>,
1028 nan_missing: bool,
1030 layout: MissingLayout,
1031 len: usize,
1032 count: usize,
1033 total: Option<f64>,
1035}
1036
1037impl<'a> PandasReductions<'a> {
1038 #[must_use]
1041 pub fn numpy_nan_missing(values: ReductionValues<'a>) -> Self {
1042 let len = values.len();
1043 let mut reductions = Self {
1044 values,
1045 present: None,
1046 nan_missing: true,
1047 layout: MissingLayout::Numpy,
1048 len,
1049 count: len,
1050 total: None,
1051 };
1052 if let ReductionValues::Float(_) | ReductionValues::FloatChunks(_) = values {
1053 let SumPair(total, count) = reductions.add_reduce(|value| SumPair(value, 1), false);
1055 reductions.count = count;
1056 reductions.total = Some(total);
1057 }
1058 reductions.nan_missing = reductions.count < len;
1059 reductions
1060 }
1061
1062 #[must_use]
1064 pub fn new(
1065 values: ReductionValues<'a>,
1066 present: Option<&'a [u64]>,
1067 layout: MissingLayout,
1068 ) -> Self {
1069 let len = values.len();
1070 let count = present.map_or(len, |words| {
1071 let whole: usize = words[..len / 64]
1072 .iter()
1073 .map(|word| word.count_ones() as usize)
1074 .sum();
1075 let tail = len % 64;
1076 whole
1077 + if tail == 0 {
1078 0
1079 } else {
1080 (words[len / 64] & ((1_u64 << tail) - 1)).count_ones() as usize
1081 }
1082 });
1083 Self {
1084 values,
1085 present: present.filter(|_| count < len),
1086 nan_missing: false,
1087 layout,
1088 len,
1089 count,
1090 total: None,
1091 }
1092 }
1093
1094 #[must_use]
1096 pub fn count(&self) -> usize {
1097 self.count
1098 }
1099
1100 fn next_slot(&self, from: usize, end: usize, present: bool) -> usize {
1102 let Some(words) = self.present else {
1103 return if present { from } else { end };
1104 };
1105 let mut i = from;
1106 while i < end {
1107 let word = if present {
1108 words[i / 64]
1109 } else {
1110 !words[i / 64]
1111 };
1112 let ahead = word >> (i % 64);
1113 if ahead != 0 {
1114 return (i + ahead.trailing_zeros() as usize).min(end);
1115 }
1116 i += 64 - i % 64;
1117 }
1118 end
1119 }
1120
1121 fn add_reduce<T>(&self, term: impl Fn(f64) -> T, cast_buffered: bool) -> T
1126 where
1127 T: Copy + Default + std::ops::Add<Output = T>,
1128 {
1129 let reader = ValueReader::new(self.values);
1130 let read_terms = |first: usize, block: &mut [T]| {
1132 let mut values = [0.0_f64; PAIRWISE_BLOCK];
1133 let values = &mut values[..block.len()];
1134 reader.read(first, values);
1135 let terms = block.iter_mut().zip(values.iter());
1136 if self.nan_missing {
1137 for (slot, &value) in terms {
1139 *slot = if value.is_nan() {
1140 T::default()
1141 } else {
1142 term(value)
1143 };
1144 }
1145 } else {
1146 for (slot, &value) in terms {
1147 *slot = term(value);
1148 }
1149 }
1150 };
1151 let buffer = if cast_buffered {
1152 NUMPY_CAST_BUFFER
1153 } else {
1154 self.len.max(1)
1155 };
1156 let mut total = T::default();
1157 let mut chunk_start = 0;
1158 while chunk_start < self.len {
1159 let chunk_end = (chunk_start + buffer).min(self.len);
1160 match self.layout {
1161 MissingLayout::Numpy => {
1162 if let (ReductionValues::Float(values), None) = (self.values, self.present) {
1163 let values = &values[chunk_start..chunk_end];
1164 let part = if self.nan_missing {
1165 let term = |value: f64| {
1167 if value.is_nan() {
1168 T::default()
1169 } else {
1170 term(value)
1171 }
1172 };
1173 numpy_pairwise_sum_of(values, &term)
1174 } else {
1175 numpy_pairwise_sum_of(values, &term)
1176 };
1177 total = total + part;
1178 chunk_start = chunk_end;
1179 continue;
1180 }
1181 let fill = |start: usize, block: &mut [T]| {
1182 let first = chunk_start + start;
1183 read_terms(first, block);
1184 let end = first + block.len();
1186 let mut slot = self.next_slot(first, end, false);
1187 while slot < end {
1188 let run_end = self.next_slot(slot, end, true);
1189 block[slot - first..run_end - first].fill(T::default());
1190 slot = self.next_slot(run_end, end, false);
1191 }
1192 };
1193 total = total + numpy_pairwise_sum_by(chunk_end - chunk_start, &fill);
1194 }
1195 MissingLayout::Masked => {
1196 let mut run_start = self.next_slot(chunk_start, chunk_end, true);
1197 while run_start < chunk_end {
1198 let run_end = self.next_slot(run_start, chunk_end, false);
1199 let fill = |start: usize, block: &mut [T]| {
1200 read_terms(run_start + start, block);
1201 };
1202 total = total + numpy_pairwise_sum_by(run_end - run_start, &fill);
1203 run_start = self.next_slot(run_end, chunk_end, true);
1204 }
1205 }
1206 }
1207 chunk_start = chunk_end;
1208 }
1209 total
1210 }
1211
1212 fn total(&self, cast_buffered: bool) -> f64 {
1215 if let Some(total) = self.total {
1216 return total;
1217 }
1218 if let (ReductionValues::Float(values), None, false) =
1219 (self.values, self.present, self.nan_missing)
1220 {
1221 return 0.0 + numpy_pairwise_sum(values);
1222 }
1223 self.add_reduce(|value| value, cast_buffered)
1224 }
1225
1226 fn mean_total(&self) -> f64 {
1229 let int = matches!(
1230 self.values,
1231 ReductionValues::Int(_) | ReductionValues::IntChunks(_)
1232 );
1233 self.total(int)
1234 }
1235
1236 #[must_use]
1238 pub fn sum(&self) -> f64 {
1239 self.total(false)
1240 }
1241
1242 #[must_use]
1244 #[allow(clippy::cast_precision_loss)] pub fn mean(&self) -> f64 {
1246 if self.count == 0 {
1247 return f64::NAN;
1248 }
1249 self.mean_total() / self.count as f64
1250 }
1251
1252 #[must_use]
1254 #[allow(clippy::cast_precision_loss)] pub fn var(&self, ddof: usize) -> f64 {
1256 if self.count <= ddof {
1257 return f64::NAN;
1258 }
1259 let total = if self.layout == MissingLayout::Masked {
1262 self.mean_total()
1263 } else {
1264 self.total(false)
1265 };
1266 let mean = total / self.count as f64;
1267 let squares = self.add_reduce(
1268 |value| {
1269 let deviation = mean - value;
1270 deviation * deviation
1271 },
1272 false,
1273 );
1274 squares / (self.count - ddof) as f64
1275 }
1276
1277 #[must_use]
1279 pub fn std(&self, ddof: usize) -> f64 {
1280 self.var(ddof).sqrt()
1281 }
1282
1283 fn as_numpy(&self) -> Self {
1286 Self {
1287 layout: MissingLayout::Numpy,
1288 ..*self
1289 }
1290 }
1291
1292 #[must_use]
1294 #[allow(clippy::cast_precision_loss)] pub fn sem(&self, ddof: usize) -> f64 {
1296 self.as_numpy().var(ddof).sqrt() / (self.count as f64).sqrt()
1297 }
1298
1299 #[allow(clippy::cast_precision_loss)] fn central_moments(&self, fourth: bool) -> (f64, f64) {
1302 let numpy = self.as_numpy();
1303 let mean = numpy.total(false) / self.count as f64;
1304 let SumPair(m2, higher) = numpy.add_reduce(
1306 |value| {
1307 let deviation = value - mean;
1308 let square = deviation * deviation;
1309 let higher = if fourth {
1310 square * square
1311 } else {
1312 square * deviation
1313 };
1314 SumPair(square, higher)
1315 },
1316 false,
1317 );
1318 (m2, higher)
1319 }
1320
1321 #[must_use]
1324 #[allow(clippy::cast_precision_loss)] pub fn skew(&self) -> f64 {
1326 if self.count < 3 {
1327 return f64::NAN;
1328 }
1329 let (m2, m3) = self.central_moments(false);
1330 let (m2, m3) = (zero_out_fperr(m2), zero_out_fperr(m3));
1331 if m2 == 0.0 {
1332 return 0.0;
1333 }
1334 let count = self.count as f64;
1335 let half = std::hint::black_box(0.5);
1338 (count * (count - 1.0).powf(half) / (count - 2.0)) * (m3 / m2.powf(1.5))
1339 }
1340
1341 #[must_use]
1344 #[allow(clippy::cast_precision_loss)] pub fn kurt(&self) -> f64 {
1346 if self.count < 4 {
1347 return f64::NAN;
1348 }
1349 let (m2, m4) = self.central_moments(true);
1350 let count = self.count as f64;
1351 let numerator = zero_out_fperr(count * (count + 1.0) * (count - 1.0) * m4);
1352 let denominator = zero_out_fperr((count - 2.0) * (count - 3.0) * (m2 * m2));
1353 if denominator == 0.0 {
1354 return 0.0;
1355 }
1356 let adjustment = 3.0 * ((count - 1.0) * (count - 1.0)) / ((count - 2.0) * (count - 3.0));
1357 numerator / denominator - adjustment
1358 }
1359}
1360
1361#[derive(Debug, Clone, Copy, Default)]
1364struct SumPair<A, B = A>(A, B);
1365
1366impl<A: std::ops::Add<Output = A>, B: std::ops::Add<Output = B>> std::ops::Add for SumPair<A, B> {
1367 type Output = Self;
1368
1369 fn add(self, other: Self) -> Self {
1370 Self(self.0 + other.0, self.1 + other.1)
1371 }
1372}
1373
1374fn zero_out_fperr(value: f64) -> f64 {
1376 if value.abs() < 1e-14 { 0.0 } else { value }
1377}
1378
1379#[derive(Debug, Clone, Copy, PartialEq)]
1383pub enum PandasDecimal {
1384 Value(f64),
1386 Rejected,
1390 NotDecimal,
1393}
1394
1395const PANDAS_DECIMAL_DIGITS: usize = 17;
1398
1399#[derive(Default)]
1403struct PandasSignificand {
1404 exact: u64,
1405 float: f64,
1406 rounding: bool,
1407 digits: usize,
1408}
1409
1410impl PandasSignificand {
1411 fn push(&mut self, digit: u8) {
1412 self.digits += 1;
1413 if !self.rounding {
1414 let next = self.exact * 10 + u64::from(digit);
1415 if next <= 1 << 53 {
1416 self.exact = next;
1417 return;
1418 }
1419 self.rounding = true;
1420 #[allow(clippy::cast_precision_loss)] let exact = self.exact as f64;
1422 self.float = exact;
1423 }
1424 self.float = self.float * 10.0 + f64::from(digit);
1425 }
1426
1427 #[allow(clippy::cast_precision_loss)] fn value(&self) -> f64 {
1429 if self.rounding {
1430 self.float
1431 } else {
1432 self.exact as f64
1433 }
1434 }
1435}
1436
1437static PANDAS_POW10: std::sync::LazyLock<[f64; 309]> = std::sync::LazyLock::new(|| {
1439 std::array::from_fn(|power| format!("1e{power}").parse().unwrap_or(f64::INFINITY))
1440});
1441
1442#[must_use]
1455pub fn pandas_decimal_to_f64(token: &[u8]) -> PandasDecimal {
1456 let (negative, body) = match token.first() {
1457 Some(b'-') => (true, &token[1..]),
1458 Some(b'+') => (false, &token[1..]),
1459 _ => (false, token),
1460 };
1461 let mut significand = PandasSignificand::default();
1462 let mut exponent = 0_i32;
1463 let mut pos = 0;
1464 while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1465 if significand.digits < PANDAS_DECIMAL_DIGITS {
1466 significand.push(byte - b'0');
1467 } else {
1468 exponent = exponent.wrapping_add(1);
1469 }
1470 pos += 1;
1471 }
1472 let mut seen_digit = pos > 0;
1473 if body.get(pos) == Some(&b'.') {
1474 pos += 1;
1475 while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1476 if significand.digits < PANDAS_DECIMAL_DIGITS {
1477 significand.push(byte - b'0');
1478 exponent = exponent.wrapping_sub(1);
1479 }
1480 seen_digit = true;
1481 pos += 1;
1482 }
1483 }
1484 if !seen_digit {
1485 return PandasDecimal::NotDecimal;
1486 }
1487 if let Some(b'e' | b'E') = body.get(pos) {
1488 pos += 1;
1489 let negative_exponent = match body.get(pos) {
1490 Some(b'-') => {
1491 pos += 1;
1492 true
1493 }
1494 Some(b'+') => {
1495 pos += 1;
1496 false
1497 }
1498 _ => false,
1499 };
1500 let start = pos;
1501 let mut written = 0_i32;
1502 while pos - start < PANDAS_DECIMAL_DIGITS
1503 && let Some(&byte @ b'0'..=b'9') = body.get(pos)
1504 {
1505 written = written
1506 .wrapping_mul(10)
1507 .wrapping_add(i32::from(byte - b'0'));
1508 pos += 1;
1509 }
1510 if pos == start {
1511 return PandasDecimal::Rejected;
1512 }
1513 exponent = exponent.wrapping_add(if negative_exponent {
1514 written.wrapping_neg()
1515 } else {
1516 written
1517 });
1518 }
1519 if pos != body.len() {
1520 return PandasDecimal::Rejected;
1521 }
1522 let value = significand.value();
1523 let pow10 = |power: i32| PANDAS_POW10[power.unsigned_abs() as usize];
1524 let magnitude = match exponent {
1525 309.. => return PandasDecimal::Rejected,
1526 0.. => value * pow10(exponent),
1527 -308.. => value / pow10(exponent),
1528 -616.. => value / pow10(-308 - exponent) / pow10(308),
1529 _ => return PandasDecimal::Value(0.0),
1530 };
1531 if magnitude.is_infinite() {
1532 return PandasDecimal::Rejected;
1533 }
1534 PandasDecimal::Value(if negative { -magnitude } else { magnitude })
1535}
1536
1537#[must_use]
1541#[allow(clippy::cast_precision_loss)] pub fn pandas_int_to_f64(value: i64) -> f64 {
1543 if value.unsigned_abs() <= 1 << 53 {
1544 return value as f64;
1545 }
1546 match pandas_decimal_to_f64(value.to_string().as_bytes()) {
1547 PandasDecimal::Value(parsed) => parsed,
1548 PandasDecimal::Rejected | PandasDecimal::NotDecimal => value as f64,
1550 }
1551}
1552
1553#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1556pub enum NumpyNumeric {
1557 Bool,
1558 Int(u8),
1559 UInt(u8),
1560 Float(u8),
1561}
1562
1563impl NumpyNumeric {
1564 #[must_use]
1568 pub const fn of(dtype: &DType, width: Option<NumericWidth>) -> Option<Self> {
1569 match (dtype, width) {
1570 (DType::Bool | DType::BoolNullable, None) => Some(Self::Bool),
1571 (DType::Int64 | DType::Int64Nullable, None) => Some(Self::Int(64)),
1572 (DType::Float64 | DType::Float64Nullable, None) => Some(Self::Float(64)),
1573 (DType::Int64 | DType::Int64Nullable, Some(width)) if !width.is_float() => {
1574 Some(Self::of_width(width))
1575 }
1576 (DType::Float64 | DType::Float64Nullable, Some(NumericWidth::Float32)) => {
1577 Some(Self::Float(32))
1578 }
1579 _ => None,
1580 }
1581 }
1582
1583 #[must_use]
1584 pub const fn of_width(width: NumericWidth) -> Self {
1585 match width {
1586 NumericWidth::Int8 => Self::Int(8),
1587 NumericWidth::Int16 => Self::Int(16),
1588 NumericWidth::Int32 => Self::Int(32),
1589 NumericWidth::UInt8 => Self::UInt(8),
1590 NumericWidth::UInt16 => Self::UInt(16),
1591 NumericWidth::UInt32 => Self::UInt(32),
1592 NumericWidth::UInt64 => Self::UInt(64),
1593 NumericWidth::Float32 => Self::Float(32),
1594 }
1595 }
1596
1597 #[must_use]
1600 pub const fn width(self) -> Option<NumericWidth> {
1601 match self {
1602 Self::Int(8) => Some(NumericWidth::Int8),
1603 Self::Int(16) => Some(NumericWidth::Int16),
1604 Self::Int(32) => Some(NumericWidth::Int32),
1605 Self::UInt(8) => Some(NumericWidth::UInt8),
1606 Self::UInt(16) => Some(NumericWidth::UInt16),
1607 Self::UInt(32) => Some(NumericWidth::UInt32),
1608 Self::UInt(64) => Some(NumericWidth::UInt64),
1609 Self::Float(32) => Some(NumericWidth::Float32),
1610 _ => None,
1611 }
1612 }
1613
1614 #[must_use]
1615 pub const fn is_float(self) -> bool {
1616 matches!(self, Self::Float(_))
1617 }
1618
1619 #[must_use]
1624 pub const fn result_type(self, other: Self) -> Self {
1625 const fn wider(a: u8, b: u8) -> u8 {
1626 if a > b { a } else { b }
1627 }
1628 match (self, other) {
1629 (Self::Bool, x) | (x, Self::Bool) => x,
1630 (Self::Int(a), Self::Int(b)) => Self::Int(wider(a, b)),
1631 (Self::UInt(a), Self::UInt(b)) => Self::UInt(wider(a, b)),
1632 (Self::Int(signed), Self::UInt(unsigned))
1633 | (Self::UInt(unsigned), Self::Int(signed)) => {
1634 if signed > unsigned {
1635 Self::Int(signed)
1636 } else if unsigned < 64 {
1637 Self::Int(wider(signed, unsigned * 2))
1638 } else {
1639 Self::Float(64)
1640 }
1641 }
1642 (Self::Float(a), Self::Float(b)) => Self::Float(wider(a, b)),
1643 (Self::Float(bits), Self::Int(int_bits) | Self::UInt(int_bits))
1644 | (Self::Int(int_bits) | Self::UInt(int_bits), Self::Float(bits)) => {
1645 if int_bits <= 16 {
1646 Self::Float(bits)
1647 } else {
1648 Self::Float(64)
1649 }
1650 }
1651 }
1652 }
1653
1654 #[must_use]
1658 pub const fn with_python_int(self) -> Self {
1659 match self {
1660 Self::Bool => Self::Int(64),
1661 other => other,
1662 }
1663 }
1664
1665 #[must_use]
1669 pub const fn with_python_float(self) -> Self {
1670 match self {
1671 Self::Float(bits) => Self::Float(bits),
1672 _ => Self::Float(64),
1673 }
1674 }
1675}
1676
1677pub trait AsDType {
1679 fn as_dtype(&self) -> DType;
1681}
1682
1683impl AsDType for DType {
1684 fn as_dtype(&self) -> DType {
1685 self.clone()
1686 }
1687}
1688
1689impl AsDType for &DType {
1690 fn as_dtype(&self) -> DType {
1691 (*self).clone()
1692 }
1693}
1694
1695impl AsDType for &str {
1696 fn as_dtype(&self) -> DType {
1697 self.parse::<DType>().unwrap_or(DType::Utf8)
1698 }
1699}
1700
1701impl AsDType for String {
1702 fn as_dtype(&self) -> DType {
1703 self.as_str().as_dtype()
1704 }
1705}
1706
1707pub mod api {
1708 pub mod types {
1711 use crate::{AsDType, DType, Scalar, TypeError};
1714
1715 #[must_use]
1717 pub fn is_bool_dtype(dtype: &impl AsDType) -> bool {
1718 dtype.as_dtype().is_bool()
1719 }
1720
1721 #[must_use]
1723 pub fn is_numeric_dtype(dtype: &impl AsDType) -> bool {
1724 dtype.as_dtype().is_numeric()
1725 }
1726
1727 #[must_use]
1729 pub fn is_integer_dtype(dtype: &impl AsDType) -> bool {
1730 dtype.as_dtype().is_integer()
1731 }
1732
1733 #[must_use]
1735 pub fn is_signed_integer_dtype(dtype: &impl AsDType) -> bool {
1736 dtype.as_dtype().is_signed_integer()
1737 }
1738
1739 #[must_use]
1741 pub fn is_unsigned_integer_dtype(_dtype: &impl AsDType) -> bool {
1742 false
1743 }
1744
1745 #[must_use]
1747 pub fn is_float_dtype(dtype: &impl AsDType) -> bool {
1748 dtype.as_dtype().is_floating()
1749 }
1750
1751 #[must_use]
1753 pub fn is_string_dtype(dtype: &impl AsDType) -> bool {
1754 dtype.as_dtype().is_string_dtype()
1755 }
1756
1757 #[must_use]
1759 pub fn is_datetime64_any_dtype(dtype: &impl AsDType) -> bool {
1760 dtype.as_dtype().is_datetime()
1761 }
1762
1763 #[must_use]
1765 pub fn is_datetime64_dtype(dtype: &impl AsDType) -> bool {
1766 dtype.as_dtype().is_datetime()
1767 }
1768
1769 #[must_use]
1771 pub fn is_datetime64_ns_dtype(dtype: &impl AsDType) -> bool {
1772 dtype.as_dtype().is_datetime()
1773 }
1774
1775 #[must_use]
1777 pub fn is_timedelta64_dtype(dtype: &impl AsDType) -> bool {
1778 dtype.as_dtype().is_timedelta()
1779 }
1780
1781 #[must_use]
1783 pub fn is_timedelta64_ns_dtype(dtype: &impl AsDType) -> bool {
1784 dtype.as_dtype().is_timedelta()
1785 }
1786
1787 #[must_use]
1789 pub fn is_period_dtype(dtype: &impl AsDType) -> bool {
1790 dtype.as_dtype().is_period()
1791 }
1792
1793 #[must_use]
1795 pub fn is_categorical_dtype(dtype: &impl AsDType) -> bool {
1796 dtype.as_dtype().is_categorical()
1797 }
1798
1799 #[must_use]
1801 pub fn is_interval_dtype(dtype: &impl AsDType) -> bool {
1802 dtype.as_dtype().is_interval()
1803 }
1804
1805 #[must_use]
1807 pub fn is_sparse(dtype: &impl AsDType) -> bool {
1808 dtype.as_dtype().is_sparse()
1809 }
1810
1811 #[must_use]
1813 pub fn is_extension_array_dtype(dtype: &impl AsDType) -> bool {
1814 dtype.as_dtype().is_extension()
1815 }
1816
1817 #[must_use]
1819 pub fn is_object_dtype(dtype: &impl AsDType) -> bool {
1820 dtype.as_dtype().is_object()
1821 }
1822
1823 #[must_use]
1825 pub fn is_int64_dtype(dtype: &impl AsDType) -> bool {
1826 matches!(dtype.as_dtype(), DType::Int64 | DType::Int64Nullable)
1827 }
1828
1829 #[must_use]
1831 pub fn is_dtype_equal(source: &impl AsDType, target: &impl AsDType) -> bool {
1832 source.as_dtype() == target.as_dtype()
1833 }
1834
1835 #[must_use]
1837 pub const fn is_scalar(_scalar: &Scalar) -> bool {
1838 true
1839 }
1840
1841 pub fn pandas_dtype(name: &str) -> Result<DType, TypeError> {
1847 name.parse::<DType>()
1848 }
1849
1850 #[must_use]
1852 pub fn infer_dtype(scalars: &[Scalar], skipna: bool) -> &'static str {
1853 if scalars.is_empty() {
1854 return "empty";
1855 }
1856 let mut has_int = false;
1857 let mut has_float = false;
1858 let mut has_bool = false;
1859 let mut has_str = false;
1860 let mut has_ts = false;
1861 let mut has_td = false;
1862 let mut has_period = false;
1863 let mut count = 0;
1864
1865 for s in scalars {
1866 if s.is_null() {
1867 if !skipna {
1868 return "mixed";
1869 }
1870 continue;
1871 }
1872 count += 1;
1873 match s {
1874 Scalar::Bool(_) => has_bool = true,
1875 Scalar::Int64(_) => has_int = true,
1876 Scalar::Float64(_) => has_float = true,
1877 Scalar::Utf8(_) => has_str = true,
1878 Scalar::Datetime64(_) => has_ts = true,
1879 Scalar::Timedelta64(_) => has_td = true,
1880 Scalar::Period(_) => has_period = true,
1881 _ => {}
1882 }
1883 }
1884
1885 if count == 0 {
1886 return "empty";
1887 }
1888 if has_bool && !has_int && !has_float && !has_str && !has_ts && !has_td && !has_period {
1889 return "boolean";
1890 }
1891 if has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td && !has_period {
1892 return "integer";
1893 }
1894 if (has_float || (has_int && has_float))
1895 && !has_bool
1896 && !has_str
1897 && !has_ts
1898 && !has_td
1899 && !has_period
1900 {
1901 return "floating";
1902 }
1903 if has_str && !has_int && !has_float && !has_bool && !has_ts && !has_td && !has_period {
1904 return "string";
1905 }
1906 if has_ts && !has_int && !has_float && !has_bool && !has_str && !has_td && !has_period {
1907 return "datetime64";
1908 }
1909 if has_td && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_period {
1910 return "timedelta64";
1911 }
1912 if has_period && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td {
1913 return "period";
1914 }
1915 "mixed"
1916 }
1917
1918 #[must_use]
1920 pub fn is_float64_dtype(dtype: &impl AsDType) -> bool {
1921 matches!(dtype.as_dtype(), DType::Float64 | DType::Float64Nullable)
1922 }
1923
1924 #[must_use]
1926 pub fn is_int32_dtype(_dtype: &impl AsDType) -> bool {
1927 false
1928 }
1929
1930 #[must_use]
1932 pub fn is_number(scalar: &Scalar) -> bool {
1933 scalar.is_numeric() || matches!(scalar, Scalar::Bool(_))
1934 }
1935
1936 #[must_use]
1938 pub fn is_bool(scalar: &Scalar) -> bool {
1939 matches!(scalar, Scalar::Bool(_))
1940 }
1941
1942 #[must_use]
1944 pub fn is_integer(scalar: &Scalar) -> bool {
1945 matches!(scalar, Scalar::Int64(_))
1946 }
1947
1948 #[must_use]
1950 pub fn is_float(scalar: &Scalar) -> bool {
1951 matches!(scalar, Scalar::Float64(_))
1952 }
1953 }
1954
1955 pub mod extensions {
1956 pub fn register_dataframe_accessor(_name: &str) {}
1960
1961 pub fn register_series_accessor(_name: &str) {}
1963
1964 pub fn register_index_accessor(_name: &str) {}
1966 }
1967
1968 pub mod indexers {
1969 #[derive(Debug, Clone, PartialEq, Eq, Default)]
1973 pub struct BaseIndexer {
1974 pub window_size: usize,
1975 pub step: usize,
1976 }
1977
1978 impl BaseIndexer {
1979 #[must_use]
1980 pub const fn new(window_size: usize, step: usize) -> Self {
1981 Self { window_size, step }
1982 }
1983 }
1984
1985 #[derive(Debug, Clone, PartialEq, Eq, Default)]
1987 pub struct FixedForwardWindowIndexer {
1988 pub window_size: usize,
1989 }
1990
1991 impl FixedForwardWindowIndexer {
1992 #[must_use]
1993 pub const fn new(window_size: usize) -> Self {
1994 Self { window_size }
1995 }
1996 }
1997
1998 #[derive(Debug, Clone, PartialEq, Eq, Default)]
2000 pub struct VariableOffsetWindowIndexer {
2001 pub index_offset: i64,
2002 }
2003
2004 impl VariableOffsetWindowIndexer {
2005 #[must_use]
2006 pub const fn new(index_offset: i64) -> Self {
2007 Self { index_offset }
2008 }
2009 }
2010 }
2011}
2012
2013pub use api::types::pandas_dtype;
2014
2015#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2016pub struct SparseDType {
2017 pub value_dtype: DType,
2018 pub fill_value: Scalar,
2019}
2020
2021impl SparseDType {
2022 pub fn new(value_dtype: DType, fill_value: Scalar) -> Result<Self, TypeError> {
2028 if matches!(value_dtype, DType::Null | DType::Sparse) {
2029 return Err(TypeError::InvalidSparseValueDType { dtype: value_dtype });
2030 }
2031
2032 let fill_value = if fill_value.is_missing() {
2033 Scalar::missing_for_dtype(value_dtype.clone())
2034 } else {
2035 cast_scalar_owned(fill_value, value_dtype.clone())?
2036 };
2037
2038 Ok(Self {
2039 value_dtype,
2040 fill_value,
2041 })
2042 }
2043
2044 #[must_use]
2071 pub fn pandas_name(&self) -> String {
2072 format!(
2073 "Sparse[{}, {}]",
2074 self.value_dtype.name(),
2075 scalar_to_string_for_astype(self.fill_value.clone())
2076 )
2077 }
2078}
2079
2080impl AsDType for SparseDType {
2081 fn as_dtype(&self) -> DType {
2082 DType::Sparse
2083 }
2084}
2085
2086#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
2090pub struct CategoricalDtype {
2091 pub categories: Option<Vec<String>>,
2092 pub ordered: bool,
2093}
2094
2095pub type CategoricalDType = CategoricalDtype;
2096
2097impl CategoricalDtype {
2098 #[must_use]
2100 pub const fn new(categories: Option<Vec<String>>, ordered: bool) -> Self {
2101 Self {
2102 categories,
2103 ordered,
2104 }
2105 }
2106
2107 #[must_use]
2109 pub fn categories(&self) -> Option<&[String]> {
2110 self.categories.as_deref()
2111 }
2112
2113 #[must_use]
2115 pub const fn ordered(&self) -> bool {
2116 self.ordered
2117 }
2118
2119 #[must_use]
2121 pub const fn name(&self) -> &'static str {
2122 "category"
2123 }
2124
2125 #[must_use]
2127 pub const fn kind(&self) -> &'static str {
2128 "O"
2129 }
2130}
2131
2132impl AsDType for CategoricalDtype {
2133 fn as_dtype(&self) -> DType {
2134 DType::Categorical
2135 }
2136}
2137
2138impl std::fmt::Display for CategoricalDtype {
2139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2140 let ord_str = if self.ordered { "True" } else { "False" };
2141 match &self.categories {
2142 Some(cats) => write!(
2143 f,
2144 "CategoricalDtype(categories={cats:?}, ordered={ord_str})"
2145 ),
2146 None => write!(f, "CategoricalDtype(categories=None, ordered={ord_str})"),
2147 }
2148 }
2149}
2150
2151#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2155pub struct PeriodDtype {
2156 pub freq: String,
2157}
2158
2159pub type PeriodDType = PeriodDtype;
2160
2161impl PeriodDtype {
2162 #[must_use]
2164 pub fn new(freq: impl Into<String>) -> Self {
2165 Self { freq: freq.into() }
2166 }
2167
2168 #[must_use]
2170 pub fn freq(&self) -> &str {
2171 &self.freq
2172 }
2173
2174 #[must_use]
2176 pub fn name(&self) -> String {
2177 format!("period[{}]", self.freq)
2178 }
2179
2180 #[must_use]
2182 pub const fn kind(&self) -> &'static str {
2183 "O"
2184 }
2185}
2186
2187impl Default for PeriodDtype {
2188 fn default() -> Self {
2189 Self {
2190 freq: "D".to_string(),
2191 }
2192 }
2193}
2194
2195impl AsDType for PeriodDtype {
2196 fn as_dtype(&self) -> DType {
2197 DType::Period
2198 }
2199}
2200
2201impl std::fmt::Display for PeriodDtype {
2202 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2203 write!(f, "period[{}]", self.freq)
2204 }
2205}
2206
2207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2211pub struct IntervalDtype {
2212 pub subtype: DType,
2213 pub closed: Option<IntervalClosed>,
2214}
2215
2216pub type IntervalDType = IntervalDtype;
2217
2218impl IntervalDtype {
2219 #[must_use]
2221 pub const fn new(subtype: DType, closed: Option<IntervalClosed>) -> Self {
2222 Self { subtype, closed }
2223 }
2224
2225 #[must_use]
2227 pub const fn subtype(&self) -> &DType {
2228 &self.subtype
2229 }
2230
2231 #[must_use]
2233 pub const fn closed(&self) -> Option<IntervalClosed> {
2234 self.closed
2235 }
2236
2237 #[must_use]
2239 pub const fn name(&self) -> &'static str {
2240 "interval"
2241 }
2242
2243 #[must_use]
2245 pub const fn kind(&self) -> &'static str {
2246 "O"
2247 }
2248}
2249
2250impl Default for IntervalDtype {
2251 fn default() -> Self {
2252 Self {
2253 subtype: DType::Float64,
2254 closed: Some(IntervalClosed::Right),
2255 }
2256 }
2257}
2258
2259impl AsDType for IntervalDtype {
2260 fn as_dtype(&self) -> DType {
2261 DType::Interval
2262 }
2263}
2264
2265impl std::fmt::Display for IntervalDtype {
2266 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2267 match self.closed {
2268 Some(c) => write!(f, "interval[{}, {c}]", self.subtype.name()),
2269 None => write!(f, "interval[{}]", self.subtype.name()),
2270 }
2271 }
2272}
2273
2274#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
2275#[serde(rename_all = "snake_case")]
2276pub enum NullKind {
2277 Null,
2278 NaN,
2279 NaT,
2280}
2281
2282mod float64_json {
2290 use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
2291
2292 pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
2293 if value.is_infinite() {
2294 serializer.serialize_str(if value.is_sign_positive() {
2295 "inf"
2296 } else {
2297 "-inf"
2298 })
2299 } else {
2300 serializer.serialize_f64(*value)
2301 }
2302 }
2303
2304 #[derive(Deserialize)]
2305 #[serde(untagged)]
2306 enum Repr {
2307 Number(f64),
2308 Text(String),
2309 Null(()),
2310 }
2311
2312 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
2313 match Repr::deserialize(deserializer)? {
2314 Repr::Number(value) => Ok(value),
2315 Repr::Text(text) => match text.as_str() {
2316 "inf" => Ok(f64::INFINITY),
2317 "-inf" => Ok(f64::NEG_INFINITY),
2318 other => Err(D::Error::custom(format!(
2319 "float64 value must be a number, \"inf\" or \"-inf\", got {other:?}"
2320 ))),
2321 },
2322 Repr::Null(()) => Ok(f64::NAN),
2323 }
2324 }
2325}
2326
2327#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2328#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
2329pub enum Scalar {
2330 Null(NullKind),
2331 Bool(bool),
2332 Int64(i64),
2333 Float64(#[serde(with = "float64_json")] f64),
2334 #[serde(alias = "string", alias = "str")]
2335 Utf8(String),
2336 Timedelta64(i64),
2337 Datetime64(i64),
2340 Period(Period),
2346 Interval(Interval),
2348 Object(ObjectValue),
2352}
2353
2354#[derive(Clone)]
2358pub enum ObjectValue {
2359 List(std::sync::Arc<[Scalar]>),
2361 Bytes(std::sync::Arc<[u8]>),
2365 Host(HostValue),
2367}
2368
2369pub trait HostObject: Send + Sync {
2372 fn host_eq(&self, other: &dyn HostObject) -> bool;
2374 fn host_repr(&self) -> String;
2376 fn host_str(&self) -> String;
2378 fn host_pprint(&self) -> String {
2382 self.host_str()
2383 }
2384 fn host_hash(&self) -> Option<u64>;
2386 fn host_cmp(&self, other: &dyn HostObject) -> Option<std::cmp::Ordering>;
2390 fn host_eq_scalar(&self, _other: &Scalar) -> bool {
2393 false
2394 }
2395 fn host_type_name(&self) -> String {
2398 "object".to_owned()
2399 }
2400 fn as_any(&self) -> &dyn std::any::Any;
2402}
2403
2404static LIVE_HOST_VALUES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2406
2407static HOST_LOCK_DECLARED: std::sync::atomic::AtomicBool =
2410 std::sync::atomic::AtomicBool::new(false);
2411
2412pub fn declare_host_lock() {
2416 HOST_LOCK_DECLARED.store(true, std::sync::atomic::Ordering::Relaxed);
2417}
2418
2419#[must_use]
2427pub fn host_values_block_workers() -> bool {
2428 workers_blocked(
2429 HOST_LOCK_DECLARED.load(std::sync::atomic::Ordering::Relaxed),
2430 LIVE_HOST_VALUES.load(std::sync::atomic::Ordering::Relaxed),
2431 )
2432}
2433
2434const fn workers_blocked(host_lock_declared: bool, live_host_values: usize) -> bool {
2436 host_lock_declared && live_host_values > 0
2437}
2438
2439struct HostSlot(Box<dyn HostObject>);
2441
2442impl Drop for HostSlot {
2443 fn drop(&mut self) {
2444 LIVE_HOST_VALUES.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2445 }
2446}
2447
2448#[derive(Clone)]
2450pub struct HostValue(std::sync::Arc<HostSlot>);
2451
2452impl HostValue {
2453 #[must_use]
2454 pub fn new(object: impl HostObject + 'static) -> Self {
2455 LIVE_HOST_VALUES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2456 Self(std::sync::Arc::new(HostSlot(Box::new(object))))
2457 }
2458
2459 #[must_use]
2460 pub fn object(&self) -> &dyn HostObject {
2461 &*self.0.0
2462 }
2463}
2464
2465impl PartialEq for HostValue {
2466 fn eq(&self, other: &Self) -> bool {
2467 std::sync::Arc::ptr_eq(&self.0, &other.0) || self.object().host_eq(other.object())
2468 }
2469}
2470
2471impl std::fmt::Debug for HostValue {
2472 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2473 formatter.write_str(&self.object().host_repr())
2474 }
2475}
2476
2477impl ObjectValue {
2478 #[must_use]
2480 pub fn list(items: Vec<Scalar>) -> Self {
2481 Self::List(items.into())
2482 }
2483
2484 #[must_use]
2486 pub fn as_list(&self) -> Option<&[Scalar]> {
2487 match self {
2488 Self::List(items) => Some(items),
2489 Self::Bytes(_) | Self::Host(_) => None,
2490 }
2491 }
2492
2493 #[must_use]
2495 pub fn bytes(data: Vec<u8>) -> Self {
2496 Self::Bytes(data.into())
2497 }
2498
2499 #[must_use]
2501 pub fn as_bytes(&self) -> Option<&[u8]> {
2502 match self {
2503 Self::Bytes(data) => Some(data),
2504 Self::List(_) | Self::Host(_) => None,
2505 }
2506 }
2507
2508 #[must_use]
2510 pub fn repr(&self) -> String {
2511 match self {
2512 Self::List(items) => {
2513 let parts: Vec<String> = items.iter().map(Scalar::python_repr).collect();
2514 format!("[{}]", parts.join(", "))
2515 }
2516 Self::Bytes(data) => python_bytes_repr(data),
2517 Self::Host(value) => value.object().host_repr(),
2518 }
2519 }
2520
2521 #[must_use]
2524 pub fn pprint(&self) -> String {
2525 match self {
2526 Self::List(items) => {
2527 let parts: Vec<String> = items
2528 .iter()
2529 .map(|item| match item {
2530 Scalar::Utf8(text) => text.clone(),
2531 Scalar::Object(object) => object.pprint(),
2532 other => other.python_repr(),
2533 })
2534 .collect();
2535 format!("[{}]", parts.join(", "))
2536 }
2537 Self::Bytes(data) => python_bytes_repr(data),
2538 Self::Host(value) => value.object().host_pprint(),
2539 }
2540 }
2541
2542 #[must_use]
2545 pub fn type_name(&self) -> String {
2546 match self {
2547 Self::List(_) => "list".to_owned(),
2548 Self::Bytes(_) => "bytes".to_owned(),
2549 Self::Host(value) => value.object().host_type_name(),
2550 }
2551 }
2552
2553 #[must_use]
2557 pub fn python_eq_scalar(&self, other: &Scalar) -> bool {
2558 match self {
2559 Self::Host(value) => value.object().host_eq_scalar(other),
2560 Self::List(_) | Self::Bytes(_) => false,
2561 }
2562 }
2563
2564 #[must_use]
2568 pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2569 match (self, other) {
2570 (Self::Bytes(left), Self::Bytes(right)) => Some(left.cmp(right)),
2571 (Self::Host(left), Self::Host(right)) => {
2572 if left == right {
2573 Some(std::cmp::Ordering::Equal)
2574 } else {
2575 left.object().host_cmp(right.object())
2576 }
2577 }
2578 (Self::List(left), Self::List(right)) => {
2579 for (a, b) in left.iter().zip(right.iter()) {
2580 if a != b {
2581 let ordering = a.python_cmp(b)?;
2582 if ordering.is_ne() {
2583 return Some(ordering);
2584 }
2585 }
2586 }
2587 Some(left.len().cmp(&right.len()))
2588 }
2589 _ => None,
2590 }
2591 }
2592
2593 #[must_use]
2598 pub fn total_cmp(&self, other: &Self) -> std::cmp::Ordering {
2599 use std::cmp::Ordering;
2600 if self == other {
2601 return Ordering::Equal;
2602 }
2603 if let Some(ordering) = self.python_cmp(other).filter(|ordering| ordering.is_ne()) {
2604 return ordering;
2605 }
2606 let rank = |cell: &Self| match cell {
2607 Self::List(_) => 0_u8,
2608 Self::Bytes(_) => 1,
2609 Self::Host(_) => 2,
2610 };
2611 rank(self)
2612 .cmp(&rank(other))
2613 .then_with(|| self.repr().cmp(&other.repr()))
2614 .then_with(|| self.address().cmp(&other.address()))
2615 }
2616
2617 fn address(&self) -> usize {
2620 match self {
2621 Self::List(items) => items.as_ptr().addr(),
2622 Self::Bytes(data) => data.as_ptr().addr(),
2623 Self::Host(value) => std::sync::Arc::as_ptr(&value.0).cast::<()>().addr(),
2624 }
2625 }
2626}
2627
2628#[must_use]
2632pub fn python_bytes_repr(data: &[u8]) -> String {
2633 let quote = if data.contains(&b'\'') && !data.contains(&b'"') {
2634 b'"'
2635 } else {
2636 b'\''
2637 };
2638 let mut out = String::with_capacity(data.len() + 3);
2639 out.push('b');
2640 out.push(char::from(quote));
2641 for &byte in data {
2642 match byte {
2643 b'\\' => out.push_str("\\\\"),
2644 b'\t' => out.push_str("\\t"),
2645 b'\n' => out.push_str("\\n"),
2646 b'\r' => out.push_str("\\r"),
2647 _ if byte == quote => {
2648 out.push('\\');
2649 out.push(char::from(byte));
2650 }
2651 0x20..=0x7e => out.push(char::from(byte)),
2652 _ => out.push_str(&format!("\\x{byte:02x}")),
2653 }
2654 }
2655 out.push(char::from(quote));
2656 out
2657}
2658
2659impl PartialOrd for ObjectValue {
2660 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2661 Some(self.cmp(other))
2662 }
2663}
2664
2665impl Ord for ObjectValue {
2667 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2668 self.total_cmp(other)
2669 }
2670}
2671
2672impl PartialEq for ObjectValue {
2673 fn eq(&self, other: &Self) -> bool {
2674 match (self, other) {
2675 (Self::List(left), Self::List(right)) => left == right,
2676 (Self::Bytes(left), Self::Bytes(right)) => left == right,
2677 (Self::Host(left), Self::Host(right)) => left == right,
2678 _ => false,
2679 }
2680 }
2681}
2682
2683impl Eq for ObjectValue {}
2687
2688impl std::hash::Hash for ObjectValue {
2689 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2690 match self {
2691 Self::List(items) => {
2692 0_u8.hash(state);
2693 for item in items.iter() {
2694 item.python_repr().hash(state);
2695 }
2696 }
2697 Self::Bytes(data) => {
2698 2_u8.hash(state);
2699 data.hash(state);
2700 }
2701 Self::Host(value) => {
2702 1_u8.hash(state);
2703 match value.object().host_hash() {
2704 Some(hash) => hash.hash(state),
2705 None => value.object().host_repr().hash(state),
2706 }
2707 }
2708 }
2709 }
2710}
2711
2712impl std::fmt::Debug for ObjectValue {
2713 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2714 formatter.write_str(&self.repr())
2715 }
2716}
2717
2718impl std::fmt::Display for ObjectValue {
2722 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2723 match self {
2724 Self::List(_) | Self::Bytes(_) => formatter.write_str(&self.repr()),
2725 Self::Host(value) => formatter.write_str(&value.object().host_str()),
2726 }
2727 }
2728}
2729
2730impl Serialize for ObjectValue {
2733 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2734 match self {
2735 Self::List(items) => items.as_ref().serialize(serializer),
2736 Self::Bytes(data) => SerializedObject::Bytes {
2737 bytes: data.to_vec(),
2738 }
2739 .serialize(serializer),
2740 Self::Host(_) => Err(serde::ser::Error::custom(
2741 "a host-language object cell cannot be serialized",
2742 )),
2743 }
2744 }
2745}
2746
2747#[derive(Serialize, Deserialize)]
2750#[serde(untagged)]
2751enum SerializedObject {
2752 List(Vec<Scalar>),
2753 Bytes { bytes: Vec<u8> },
2754}
2755
2756impl<'de> Deserialize<'de> for ObjectValue {
2757 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2758 Ok(match SerializedObject::deserialize(deserializer)? {
2759 SerializedObject::List(items) => Self::list(items),
2760 SerializedObject::Bytes { bytes } => Self::bytes(bytes),
2761 })
2762 }
2763}
2764
2765impl std::fmt::Display for Scalar {
2766 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2767 match self {
2768 Self::Null(NullKind::NaN) => write!(f, "NaN"),
2769 Self::Null(NullKind::NaT) => write!(f, "NaT"),
2770 Self::Null(NullKind::Null) => write!(f, "None"),
2771 Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
2772 Self::Int64(v) => write!(f, "{v}"),
2773 Self::Float64(v) => write!(f, "{v}"),
2774 Self::Utf8(s) => write!(f, "{s}"),
2775 Self::Timedelta64(nanos) => write!(f, "{}", Timedelta::format(*nanos)),
2776 Self::Datetime64(nanos) => {
2777 if *nanos == Timestamp::NAT {
2778 write!(f, "NaT")
2779 } else {
2780 write!(f, "Timestamp[{nanos}]")
2781 }
2782 }
2783 Self::Period(p) => {
2784 if p.ordinal == i64::MIN {
2785 write!(f, "NaT")
2786 } else {
2787 write!(f, "{}", p.calendar_string())
2788 }
2789 }
2790 Self::Interval(interval) => write!(f, "{interval}"),
2791 Self::Object(object) => write!(f, "{object}"),
2792 }
2793 }
2794}
2795
2796impl Scalar {
2797 #[must_use]
2804 pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2805 let numeric =
2806 |value: &Self| matches!(value, Self::Bool(_) | Self::Int64(_) | Self::Float64(_));
2807 match (self, other) {
2808 (Self::Utf8(a), Self::Utf8(b)) => Some(a.cmp(b)),
2809 (Self::Datetime64(a), Self::Datetime64(b))
2810 | (Self::Timedelta64(a), Self::Timedelta64(b)) => Some(a.cmp(b)),
2811 (Self::Period(a), Self::Period(b)) if a.freq == b.freq => {
2812 Some(a.ordinal.cmp(&b.ordinal))
2813 }
2814 (Self::Interval(a), Self::Interval(b)) => Some(
2815 a.left
2816 .partial_cmp(&b.left)?
2817 .then(a.right.partial_cmp(&b.right)?),
2818 ),
2819 (Self::Object(a), Self::Object(b)) => a.python_cmp(b),
2820 _ if numeric(self) && numeric(other) => {
2821 self.to_f64().ok()?.partial_cmp(&other.to_f64().ok()?)
2822 }
2823 _ => None,
2824 }
2825 }
2826
2827 #[must_use]
2832 pub fn python_cmp_type_names(&self, other: &Self) -> (String, String) {
2833 if let (Self::Object(ObjectValue::List(left)), Self::Object(ObjectValue::List(right))) =
2834 (self, other)
2835 && let Some((a, b)) = left.iter().zip(right.iter()).find(|(a, b)| a != b)
2836 {
2837 return a.python_cmp_type_names(b);
2838 }
2839 (self.python_type_name(), other.python_type_name())
2840 }
2841
2842 #[must_use]
2845 pub fn python_type_name(&self) -> String {
2846 match self {
2847 Self::Null(NullKind::NaN) | Self::Float64(_) => "float",
2848 Self::Null(NullKind::NaT) => "NaTType",
2849 Self::Null(NullKind::Null) => "NoneType",
2850 Self::Bool(_) => "bool",
2851 Self::Int64(_) => "int",
2852 Self::Utf8(_) => "str",
2853 Self::Timedelta64(_) => "Timedelta",
2854 Self::Datetime64(_) => "Timestamp",
2855 Self::Period(_) => "Period",
2856 Self::Interval(_) => "Interval",
2857 Self::Object(object) => return object.type_name(),
2858 }
2859 .to_owned()
2860 }
2861
2862 #[must_use]
2866 pub fn python_repr(&self) -> String {
2867 match self {
2868 Self::Null(NullKind::NaN) => "nan".to_owned(),
2869 Self::Null(NullKind::NaT) => "NaT".to_owned(),
2870 Self::Null(NullKind::Null) => "None".to_owned(),
2871 Self::Utf8(text) => {
2872 let quote = if text.contains('\'') && !text.contains('"') {
2873 '"'
2874 } else {
2875 '\''
2876 };
2877 let mut out = String::with_capacity(text.len() + 2);
2878 out.push(quote);
2879 for ch in text.chars() {
2880 match ch {
2881 '\\' => out.push_str("\\\\"),
2882 '\n' => out.push_str("\\n"),
2883 '\r' => out.push_str("\\r"),
2884 '\t' => out.push_str("\\t"),
2885 c if c == quote => {
2886 out.push('\\');
2887 out.push(c);
2888 }
2889 c => out.push(c),
2890 }
2891 }
2892 out.push(quote);
2893 out
2894 }
2895 Self::Float64(value) => {
2896 if value.is_nan() {
2897 "nan".to_owned()
2898 } else if value.is_infinite() {
2899 if *value > 0.0 { "inf" } else { "-inf" }.to_owned()
2900 } else if value.fract() == 0.0 && value.abs() < 1e16 {
2901 format!("{value:.1}")
2902 } else {
2903 format!("{value}")
2904 }
2905 }
2906 Self::Object(object) => object.repr(),
2907 other => other.to_string(),
2908 }
2909 }
2910}
2911
2912pub const NA: Scalar = Scalar::Null(NullKind::Null);
2914
2915pub const NAT: Scalar = Scalar::Null(NullKind::NaT);
2917
2918#[allow(non_upper_case_globals)]
2920pub const NaT: Scalar = NAT;
2921
2922impl From<bool> for Scalar {
2932 fn from(value: bool) -> Self {
2933 Self::Bool(value)
2934 }
2935}
2936
2937impl From<i64> for Scalar {
2938 fn from(value: i64) -> Self {
2939 Self::Int64(value)
2940 }
2941}
2942
2943impl From<f64> for Scalar {
2944 fn from(value: f64) -> Self {
2945 Self::Float64(value)
2946 }
2947}
2948
2949impl From<&str> for Scalar {
2950 fn from(value: &str) -> Self {
2951 Self::Utf8(value.to_owned())
2952 }
2953}
2954
2955impl From<String> for Scalar {
2956 fn from(value: String) -> Self {
2957 Self::Utf8(value)
2958 }
2959}
2960
2961impl Scalar {
2962 #[inline]
2963 const fn debug_variant_name(&self) -> &'static str {
2964 match self {
2965 Self::Null(_) => "Null",
2966 Self::Bool(_) => "Bool",
2967 Self::Int64(_) => "Int64",
2968 Self::Float64(_) => "Float64",
2969 Self::Utf8(_) => "Utf8",
2970 Self::Timedelta64(_) => "Timedelta64",
2971 Self::Datetime64(_) => "Datetime64",
2972 Self::Period(_) => "Period",
2973 Self::Interval(_) => "Interval",
2974 Self::Object(_) => "Object",
2975 }
2976 }
2977
2978 #[must_use]
2979 pub fn dtype(&self) -> DType {
2980 match self {
2981 Self::Null(_) => DType::Null,
2982 Self::Bool(_) => DType::Bool,
2983 Self::Int64(_) => DType::Int64,
2984 Self::Float64(_) => DType::Float64,
2985 Self::Utf8(_) => DType::Utf8,
2986 Self::Timedelta64(_) => DType::Timedelta64,
2987 Self::Datetime64(_) => DType::datetime64_naive(),
2988 Self::Period(_) => DType::Period,
2989 Self::Interval(_) => DType::Interval,
2990 Self::Object(_) => DType::Utf8,
2992 }
2993 }
2994
2995 #[must_use]
2996 pub fn is_missing(&self) -> bool {
2997 match self {
2998 Self::Null(_) => true,
2999 Self::Float64(v) => v.is_nan(),
3000 Self::Timedelta64(v) => *v == Timedelta::NAT,
3001 Self::Datetime64(v) => *v == Timestamp::NAT,
3002 Self::Period(p) => p.ordinal == i64::MIN,
3003 _ => false,
3004 }
3005 }
3006
3007 #[must_use]
3008 pub fn is_nan(&self) -> bool {
3009 matches!(self, Self::Null(NullKind::NaN)) || matches!(self, Self::Float64(v) if v.is_nan())
3010 }
3011
3012 #[must_use]
3014 pub const fn is_bool(&self) -> bool {
3015 matches!(self, Self::Bool(_))
3016 }
3017
3018 #[must_use]
3020 pub const fn is_integer(&self) -> bool {
3021 matches!(self, Self::Int64(_))
3022 }
3023
3024 #[must_use]
3026 pub const fn is_float(&self) -> bool {
3027 matches!(self, Self::Float64(_))
3028 }
3029
3030 #[must_use]
3032 pub const fn is_numeric(&self) -> bool {
3033 matches!(self, Self::Int64(_) | Self::Float64(_))
3034 }
3035
3036 #[must_use]
3038 pub const fn is_string(&self) -> bool {
3039 matches!(self, Self::Utf8(_))
3040 }
3041
3042 #[must_use]
3044 pub const fn is_datetime(&self) -> bool {
3045 matches!(self, Self::Datetime64(_))
3046 }
3047
3048 #[must_use]
3050 pub const fn is_timedelta(&self) -> bool {
3051 matches!(self, Self::Timedelta64(_))
3052 }
3053
3054 #[must_use]
3056 pub const fn is_period(&self) -> bool {
3057 matches!(self, Self::Period(_))
3058 }
3059
3060 #[must_use]
3062 pub const fn is_interval(&self) -> bool {
3063 matches!(self, Self::Interval(_))
3064 }
3065
3066 #[must_use]
3068 pub const fn as_i64(&self) -> Option<i64> {
3069 match self {
3070 Self::Int64(v) => Some(*v),
3071 _ => None,
3072 }
3073 }
3074
3075 #[must_use]
3077 pub const fn as_int(&self) -> Option<i64> {
3078 self.as_i64()
3079 }
3080
3081 #[must_use]
3083 pub const fn as_f64(&self) -> Option<f64> {
3084 match self {
3085 Self::Float64(v) => Some(*v),
3086 _ => None,
3087 }
3088 }
3089
3090 #[must_use]
3092 pub const fn as_float(&self) -> Option<f64> {
3093 self.as_f64()
3094 }
3095
3096 #[must_use]
3098 pub const fn as_bool(&self) -> Option<bool> {
3099 match self {
3100 Self::Bool(v) => Some(*v),
3101 _ => None,
3102 }
3103 }
3104
3105 #[must_use]
3107 pub fn as_str(&self) -> Option<&str> {
3108 match self {
3109 Self::Utf8(s) => Some(s.as_str()),
3110 _ => None,
3111 }
3112 }
3113
3114 #[must_use]
3116 pub const fn as_datetime_nanos(&self) -> Option<i64> {
3117 match self {
3118 Self::Datetime64(v) => Some(*v),
3119 _ => None,
3120 }
3121 }
3122
3123 #[must_use]
3125 pub const fn as_timedelta_nanos(&self) -> Option<i64> {
3126 match self {
3127 Self::Timedelta64(v) => Some(*v),
3128 _ => None,
3129 }
3130 }
3131
3132 #[must_use]
3134 pub const fn as_period_ordinal(&self) -> Option<i64> {
3135 match self {
3136 Self::Period(p) => Some(p.ordinal),
3137 _ => None,
3138 }
3139 }
3140
3141 #[must_use]
3143 pub const fn as_interval(&self) -> Option<Interval> {
3144 match self {
3145 Self::Interval(i) => Some(*i),
3146 _ => None,
3147 }
3148 }
3149
3150 #[must_use]
3151 pub fn missing_for_dtype(dtype: DType) -> Self {
3152 match dtype {
3153 DType::Float64 => Self::Null(NullKind::NaN),
3154 DType::Float64Nullable => Self::Null(NullKind::Null),
3162 DType::Timedelta64 => Self::Timedelta64(Timedelta::NAT),
3163 DType::Datetime64 { .. } => Self::Datetime64(Timestamp::NAT),
3164 DType::Period => Self::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
3165 DType::Null => Self::Null(NullKind::Null),
3166 DType::Bool
3167 | DType::BoolNullable
3168 | DType::Int64
3169 | DType::Int64Nullable
3170 | DType::Utf8
3171 | DType::Categorical
3172 | DType::Interval
3173 | DType::Sparse => Self::Null(NullKind::Null),
3174 }
3175 }
3176
3177 #[must_use]
3178 pub fn semantic_eq(&self, other: &Self) -> bool {
3179 match (self, other) {
3180 (Self::Float64(a), Self::Float64(b)) => {
3181 if a.is_nan() && b.is_nan() {
3182 return true;
3183 }
3184 if *a == *b {
3185 return true;
3186 }
3187 let diff = (*a - *b).abs();
3188 let max_abs = a.abs().max(b.abs());
3189 if max_abs == 0.0 {
3190 diff < f64::EPSILON
3191 } else {
3192 diff / max_abs < 1e-14
3193 }
3194 }
3195 (Self::Null(_), Self::Float64(v)) | (Self::Float64(v), Self::Null(_)) => v.is_nan(),
3196 (Self::Null(_), Self::Null(_)) => true,
3203 _ if self.is_missing() && other.is_missing() => true,
3230 (Self::Interval(a), Self::Interval(b)) => a == b && a.subtype == b.subtype,
3235 _ => self == other,
3236 }
3237 }
3238
3239 #[must_use]
3240 pub fn semantic_le(&self, other: &Self) -> bool {
3241 match self.semantic_cmp(other) {
3242 std::cmp::Ordering::Less | std::cmp::Ordering::Equal => true,
3243 std::cmp::Ordering::Greater => false,
3244 }
3245 }
3246
3247 #[must_use]
3248 pub fn semantic_ge(&self, other: &Self) -> bool {
3249 match self.semantic_cmp(other) {
3250 std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => true,
3251 std::cmp::Ordering::Less => false,
3252 }
3253 }
3254
3255 #[must_use]
3256 pub fn is_null(&self) -> bool {
3257 matches!(self, Self::Null(_))
3258 }
3259
3260 #[must_use]
3261 pub fn is_na(&self) -> bool {
3262 self.is_missing()
3263 }
3264
3265 #[must_use]
3267 pub fn isna(&self) -> bool {
3268 self.is_missing()
3269 }
3270
3271 #[must_use]
3273 pub fn isnull(&self) -> bool {
3274 self.is_null()
3275 }
3276
3277 #[must_use]
3279 pub fn notna(&self) -> bool {
3280 !self.is_missing()
3281 }
3282
3283 #[must_use]
3285 pub fn notnull(&self) -> bool {
3286 !self.is_missing()
3287 }
3288
3289 #[must_use]
3291 pub fn is_not_na(&self) -> bool {
3292 !self.is_missing()
3293 }
3294
3295 #[must_use]
3297 pub fn not_na(&self) -> bool {
3298 !self.is_missing()
3299 }
3300
3301 #[must_use]
3302 pub fn coalesce(&self, other: &Self) -> Self {
3303 if self.is_missing() {
3304 other.clone()
3305 } else {
3306 self.clone()
3307 }
3308 }
3309
3310 #[must_use]
3311 pub fn semantic_cmp(&self, other: &Self) -> std::cmp::Ordering {
3312 match (self, other) {
3313 (Self::Int64(a), Self::Int64(b)) => a.cmp(b),
3314 (Self::Float64(a), Self::Float64(b)) => {
3315 a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
3316 }
3317 (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
3318 (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
3319 (Self::Null(a), Self::Null(b)) => a.cmp(b),
3320 (Self::Timedelta64(a), Self::Timedelta64(b)) => {
3321 if *a == Timedelta::NAT || *b == Timedelta::NAT {
3322 std::cmp::Ordering::Equal
3323 } else {
3324 a.cmp(b)
3325 }
3326 }
3327 (Self::Datetime64(a), Self::Datetime64(b)) => {
3328 if *a == Timestamp::NAT || *b == Timestamp::NAT {
3329 std::cmp::Ordering::Equal
3330 } else {
3331 a.cmp(b)
3332 }
3333 }
3334 (Self::Period(a), Self::Period(b)) => {
3335 if a.ordinal == i64::MIN || b.ordinal == i64::MIN {
3336 std::cmp::Ordering::Equal
3337 } else {
3338 a.ordinal.cmp(&b.ordinal)
3339 }
3340 }
3341 (Self::Interval(a), Self::Interval(b)) => a
3342 .left
3343 .partial_cmp(&b.left)
3344 .unwrap_or(std::cmp::Ordering::Equal)
3345 .then_with(|| {
3346 a.right
3347 .partial_cmp(&b.right)
3348 .unwrap_or(std::cmp::Ordering::Equal)
3349 })
3350 .then_with(|| a.closed.cmp(&b.closed)),
3351 (Self::Object(a), Self::Object(b)) => a.cmp(b),
3353 (Self::Int64(a), Self::Float64(b)) => (*a as f64)
3355 .partial_cmp(b)
3356 .unwrap_or(std::cmp::Ordering::Equal),
3357 (Self::Float64(a), Self::Int64(b)) => a
3358 .partial_cmp(&(*b as f64))
3359 .unwrap_or(std::cmp::Ordering::Equal),
3360 (a, b) => a.debug_variant_name().cmp(b.debug_variant_name()),
3364 }
3365 }
3366
3367 pub fn to_f64(&self) -> Result<f64, TypeError> {
3368 match self {
3369 Self::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
3370 Self::Int64(v) => Ok(*v as f64),
3371 Self::Float64(v) => Ok(*v),
3372 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3373 Self::Utf8(v) => Err(TypeError::NonNumericValue {
3374 value: v.clone(),
3375 dtype: DType::Utf8,
3376 }),
3377 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3378 kind: NullKind::NaT,
3379 }),
3380 Self::Timedelta64(v) => Err(TypeError::NonNumericValue {
3381 value: Timedelta::format(*v),
3382 dtype: DType::Timedelta64,
3383 }),
3384 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3385 kind: NullKind::NaT,
3386 }),
3387 Self::Datetime64(v) => Err(TypeError::NonNumericValue {
3388 value: format!("Timestamp[{v}]"),
3389 dtype: DType::datetime64_naive(),
3390 }),
3391 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3392 kind: NullKind::NaT,
3393 }),
3394 Self::Period(p) => Err(TypeError::NonNumericValue {
3395 value: p.calendar_string(),
3396 dtype: DType::Period,
3397 }),
3398 Self::Interval(v) => Err(TypeError::NonNumericValue {
3399 value: v.to_string(),
3400 dtype: DType::Interval,
3401 }),
3402 Self::Object(object) => Err(TypeError::NonNumericValue {
3403 value: object.repr(),
3404 dtype: DType::Utf8,
3405 }),
3406 }
3407 }
3408
3409 pub fn to_i64(&self) -> Result<i64, TypeError> {
3411 match self {
3412 Self::Bool(v) => Ok(if *v { 1 } else { 0 }),
3413 Self::Int64(v) => Ok(*v),
3414 Self::Float64(v) => Ok(*v as i64),
3415 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3416 Self::Utf8(v) => Err(TypeError::NonNumericValue {
3417 value: v.clone(),
3418 dtype: DType::Utf8,
3419 }),
3420 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3421 kind: NullKind::NaT,
3422 }),
3423 Self::Timedelta64(v) => Ok(*v),
3424 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3425 kind: NullKind::NaT,
3426 }),
3427 Self::Datetime64(v) => Ok(*v),
3428 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3429 kind: NullKind::NaT,
3430 }),
3431 Self::Period(p) => Ok(p.ordinal),
3432 Self::Interval(v) => Err(TypeError::NonNumericValue {
3433 value: v.to_string(),
3434 dtype: DType::Interval,
3435 }),
3436 Self::Object(object) => Err(TypeError::NonNumericValue {
3437 value: object.repr(),
3438 dtype: DType::Utf8,
3439 }),
3440 }
3441 }
3442
3443 pub fn to_bool(&self) -> Result<bool, TypeError> {
3445 match self {
3446 Self::Bool(v) => Ok(*v),
3447 Self::Int64(v) => Ok(*v != 0),
3448 Self::Float64(v) => Ok(*v != 0.0 && !v.is_nan()),
3449 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3450 Self::Utf8(v) => Ok(!v.is_empty()),
3451 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3452 kind: NullKind::NaT,
3453 }),
3454 Self::Timedelta64(v) => Ok(*v != 0),
3455 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3456 kind: NullKind::NaT,
3457 }),
3458 Self::Datetime64(v) => Ok(*v != 0),
3459 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3460 kind: NullKind::NaT,
3461 }),
3462 Self::Period(p) => Ok(p.ordinal != 0),
3463 Self::Interval(_) => Ok(true),
3464 Self::Object(ObjectValue::List(items)) => Ok(!items.is_empty()),
3467 Self::Object(ObjectValue::Bytes(data)) => Ok(!data.is_empty()),
3468 Self::Object(ObjectValue::Host(_)) => Ok(true),
3469 }
3470 }
3471
3472 pub fn to_str(&self) -> String {
3474 match self {
3475 Self::Bool(v) => if *v { "True" } else { "False" }.to_string(),
3476 Self::Int64(v) => v.to_string(),
3477 Self::Float64(v) => {
3478 if v.is_nan() {
3479 "nan".to_string()
3480 } else if v.is_infinite() {
3481 if *v > 0.0 { "inf" } else { "-inf" }.to_string()
3482 } else {
3483 v.to_string()
3484 }
3485 }
3486 Self::Null(_) => "NaN".to_string(),
3487 Self::Utf8(v) => v.clone(),
3488 Self::Timedelta64(v) => Timedelta::format(*v),
3489 Self::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_string(),
3490 Self::Datetime64(v) => Timestamp::from_nanos(*v).isoformat(),
3491 Self::Period(p) if p.ordinal == i64::MIN => "NaT".to_string(),
3492 Self::Period(p) => p.calendar_string(),
3493 Self::Interval(v) => v.to_string(),
3494 Self::Object(object) => object.to_string(),
3495 }
3496 }
3497}
3498
3499#[derive(Debug, Error, Clone, PartialEq)]
3500pub enum TypeError {
3501 #[error("dtype coercion from {left:?} to {right:?} has no compatible common type")]
3502 IncompatibleDtypes { left: DType, right: DType },
3503 #[error("cannot cast scalar of dtype {from:?} to {to:?}")]
3504 InvalidCast { from: DType, to: DType },
3505 #[error("cannot cast float {value} to int64 without loss")]
3506 LossyFloatToInt { value: f64 },
3507 #[error("expected 0/1 for bool cast from int64 but found {value}")]
3508 InvalidBoolInt { value: i64 },
3509 #[error("expected 0.0/1.0 for bool cast from float64 but found {value}")]
3510 InvalidBoolFloat { value: f64 },
3511 #[error("value {value:?} has non-numeric dtype {dtype:?}")]
3512 NonNumericValue { value: String, dtype: DType },
3513 #[error("value is missing ({kind:?})")]
3514 ValueIsMissing { kind: NullKind },
3515 #[error("sparse value dtype cannot be {dtype:?}")]
3516 InvalidSparseValueDType { dtype: DType },
3517 #[error("interval_range step must be finite, positive, and not NaN (got {step})")]
3518 InvalidIntervalStep { step: f64 },
3519 #[error("interval_range step {step} does not evenly divide range end-start={span}")]
3520 IntervalStepDoesNotDivide { step: f64, span: f64 },
3521 #[error("interval_range requires exactly 3 of (start, end, periods, freq) to be specified")]
3522 IntervalRangeParameterCount,
3523 #[error("cannot parse '{value}' as {target}")]
3524 ValueNotParseable { value: String, target: String },
3525}
3526
3527pub fn common_dtype(left: DType, right: DType) -> Result<DType, TypeError> {
3528 use DType::{
3529 Bool, BoolNullable, Categorical, Float64, Float64Nullable, Int64, Int64Nullable, Null,
3530 Sparse, Timedelta64,
3531 };
3532
3533 let out = match (&left, &right) {
3534 (a, b) if a == b => a.clone(),
3535 (Null, other) | (other, Null) => other.clone(),
3536 (Categorical, Categorical) => Categorical,
3537
3538 (Bool, Int64) | (Int64, Bool) => Int64,
3540 (Bool, Int64Nullable) | (Int64Nullable, Bool) => Int64Nullable,
3541 (BoolNullable, Int64) | (Int64, BoolNullable) => Int64Nullable,
3542 (BoolNullable, Int64Nullable) | (Int64Nullable, BoolNullable) => Int64Nullable,
3543 (Bool, BoolNullable) | (BoolNullable, Bool) => BoolNullable,
3544 (Bool, Float64) | (Float64, Bool) => Float64,
3545 (BoolNullable, Float64) | (Float64, BoolNullable) => Float64Nullable,
3551
3552 (Int64, Float64) | (Float64, Int64) => Float64,
3554 (Int64Nullable, Float64) | (Float64, Int64Nullable) => Float64Nullable,
3568 (Int64, Int64Nullable) | (Int64Nullable, Int64) => Int64Nullable,
3569
3570 (Float64Nullable, Float64) | (Float64, Float64Nullable) => Float64Nullable,
3587 (Float64Nullable, Int64) | (Int64, Float64Nullable) => Float64Nullable,
3588 (Float64Nullable, Int64Nullable) | (Int64Nullable, Float64Nullable) => Float64Nullable,
3589 (Float64Nullable, Bool) | (Bool, Float64Nullable) => Float64Nullable,
3590 (Float64Nullable, BoolNullable) | (BoolNullable, Float64Nullable) => Float64Nullable,
3591
3592 (Timedelta64, Timedelta64) => Timedelta64,
3594 (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
3595 if left_tz == right_tz =>
3596 {
3597 DType::Datetime64 {
3598 tz: left_tz.clone(),
3599 }
3600 }
3601
3602 (Sparse, _) | (_, Sparse) => {
3603 return Err(TypeError::IncompatibleDtypes {
3604 left: left.clone(),
3605 right: right.clone(),
3606 });
3607 }
3608 _ => {
3609 return Err(TypeError::IncompatibleDtypes { left, right });
3610 }
3611 };
3612
3613 Ok(out)
3614}
3615
3616pub fn infer_dtype(values: &[Scalar]) -> Result<DType, TypeError> {
3617 let mut current = DType::Null;
3618 let mut saw_utf8 = false;
3619 let mut saw_timedelta = false;
3620 let mut saw_datetime = false;
3621 let mut saw_non_utf8_non_null = false;
3622 let mut saw_bool = false;
3629 let mut saw_numeric = false;
3630
3631 for value in values {
3645 match value.dtype() {
3646 DType::Null => {}
3647 DType::Utf8 => saw_utf8 = true,
3648 DType::Bool => {
3649 saw_bool = true;
3650 saw_non_utf8_non_null = true;
3651 current = common_dtype(current, DType::Bool)?;
3652 }
3653 DType::Int64 | DType::Float64 => {
3654 saw_numeric = true;
3655 saw_non_utf8_non_null = true;
3656 current = common_dtype(current, value.dtype())?;
3657 }
3658 DType::Timedelta64 => {
3659 saw_timedelta = true;
3660 if current == DType::Null {
3661 current = DType::Timedelta64;
3662 } else if current != DType::Timedelta64 {
3663 return Err(TypeError::IncompatibleDtypes {
3664 left: current,
3665 right: DType::Timedelta64,
3666 });
3667 }
3668 }
3669 DType::Datetime64 { .. } => {
3670 saw_datetime = true;
3671 if current == DType::Null {
3672 current = DType::datetime64_naive();
3673 } else if !current.is_datetime() {
3674 return Err(TypeError::IncompatibleDtypes {
3675 left: current,
3676 right: DType::datetime64_naive(),
3677 });
3678 }
3679 }
3680 other => {
3681 saw_non_utf8_non_null = true;
3682 current = common_dtype(current, other)?;
3683 }
3684 }
3685
3686 if saw_bool && saw_numeric {
3687 return Ok(DType::Utf8);
3691 }
3692 if saw_utf8 && saw_non_utf8_non_null {
3693 return Ok(DType::Utf8);
3697 }
3698 if saw_timedelta && saw_non_utf8_non_null {
3699 return Err(TypeError::IncompatibleDtypes {
3700 left: DType::Timedelta64,
3701 right: current,
3702 });
3703 }
3704 if saw_datetime && saw_non_utf8_non_null {
3705 return Err(TypeError::IncompatibleDtypes {
3706 left: DType::datetime64_naive(),
3707 right: current,
3708 });
3709 }
3710 }
3711
3712 if saw_utf8 {
3713 Ok(DType::Utf8)
3714 } else {
3715 Ok(current)
3716 }
3717}
3718
3719pub fn cast_scalar_owned(value: Scalar, target: DType) -> Result<Scalar, TypeError> {
3722 let from = value.dtype();
3723 if from == target {
3724 return Ok(value);
3725 }
3726 if (from == DType::Int64 && target == DType::Int64Nullable)
3728 || (from == DType::Int64Nullable && target == DType::Int64)
3729 {
3730 return Ok(value);
3731 }
3732 if (from == DType::Bool && target == DType::BoolNullable)
3734 || (from == DType::BoolNullable && target == DType::Bool)
3735 {
3736 return Ok(value);
3737 }
3738 if (from == DType::Float64 && target == DType::Float64Nullable)
3746 || (from == DType::Float64Nullable && target == DType::Float64)
3747 {
3748 return Ok(value);
3749 }
3750 if from.is_datetime() && target.is_datetime() {
3754 return Ok(value);
3755 }
3756 if target == DType::Utf8 {
3757 return Ok(Scalar::Utf8(scalar_to_string_for_astype(value)));
3758 }
3759 if target == DType::Bool
3765 && let Scalar::Float64(v) = &value
3766 && v.is_nan()
3767 {
3768 return Ok(Scalar::Bool(true));
3769 }
3770 if target == DType::Bool {
3796 match &value {
3797 Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3798 return Ok(Scalar::Bool(*nanos != 0));
3799 }
3800 _ => {}
3801 }
3802 }
3803 if target == DType::Int64 {
3828 match &value {
3829 Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3830 return Ok(Scalar::Int64(*nanos));
3831 }
3832 _ => {}
3833 }
3834 }
3835 if value.is_missing() {
3836 return Ok(Scalar::missing_for_dtype(target));
3837 }
3838
3839 match target {
3842 DType::Null => Ok(Scalar::Null(NullKind::Null)),
3843 DType::Bool => match &value {
3844 Scalar::Int64(v) => Ok(Scalar::Bool(*v != 0)),
3847 Scalar::Float64(v) => Ok(Scalar::Bool(*v != 0.0)),
3850 _ => Err(TypeError::InvalidCast { from, to: target }),
3851 },
3852 DType::BoolNullable => match &value {
3853 Scalar::Bool(b) => Ok(Scalar::Bool(*b)),
3858 Scalar::Int64(0) => Ok(Scalar::Bool(false)),
3859 Scalar::Int64(1) => Ok(Scalar::Bool(true)),
3860 Scalar::Int64(v) => Err(TypeError::InvalidBoolInt { value: *v }),
3861 Scalar::Float64(v) if *v == 0.0 => Ok(Scalar::Bool(false)),
3862 Scalar::Float64(v) if *v == 1.0 => Ok(Scalar::Bool(true)),
3863 Scalar::Float64(v) => Err(TypeError::InvalidBoolFloat { value: *v }),
3864 _ => Err(TypeError::InvalidCast { from, to: target }),
3865 },
3866 DType::Int64 | DType::Int64Nullable => match &value {
3867 Scalar::Bool(v) => Ok(Scalar::Int64(i64::from(*v))),
3868 Scalar::Float64(v) => {
3869 if !v.is_finite() {
3876 return Err(TypeError::LossyFloatToInt { value: *v });
3877 }
3878 if *v < i64::MIN as f64 || *v >= 9223372036854775808.0 {
3879 return Err(TypeError::LossyFloatToInt { value: *v });
3880 }
3881 Ok(Scalar::Int64(*v as i64))
3882 }
3883 Scalar::Utf8(s) => {
3884 if let Ok(v) = s.parse::<i64>() {
3887 return Ok(Scalar::Int64(v));
3888 }
3889 if let Ok(f) = s.parse::<f64>()
3890 && f.is_finite()
3891 && f.fract() == 0.0
3892 && f >= i64::MIN as f64
3893 && f < 9223372036854775808.0
3894 {
3895 return Ok(Scalar::Int64(f as i64));
3896 }
3897 Err(TypeError::InvalidCast { from, to: target })
3898 }
3899 _ => Err(TypeError::InvalidCast { from, to: target }),
3900 },
3901 DType::Float64 | DType::Float64Nullable => match &value {
3905 Scalar::Bool(v) => Ok(Scalar::Float64(if *v { 1.0 } else { 0.0 })),
3906 Scalar::Int64(v) => Ok(Scalar::Float64(*v as f64)),
3907 Scalar::Utf8(s) => s
3908 .parse::<f64>()
3909 .map(Scalar::Float64)
3910 .map_err(|_| TypeError::InvalidCast { from, to: target }),
3911 _ => Err(TypeError::InvalidCast { from, to: target }),
3912 },
3913 DType::Utf8 => Ok(Scalar::Utf8(scalar_to_string_for_astype(value))),
3914 DType::Categorical => Err(TypeError::InvalidCast { from, to: target }),
3915 DType::Timedelta64 => match &value {
3916 Scalar::Bool(v) => Ok(Scalar::Timedelta64(i64::from(*v))),
3927 Scalar::Int64(v) => Ok(Scalar::Timedelta64(*v)),
3928 Scalar::Float64(v) => Ok(Scalar::Timedelta64(float_to_temporal_nanos(*v))),
3929 Scalar::Utf8(s) => Timedelta::parse(s)
3930 .map(Scalar::Timedelta64)
3931 .map_err(|_| TypeError::InvalidCast { from, to: target }),
3932 _ => Err(TypeError::InvalidCast { from, to: target }),
3933 },
3934 DType::Datetime64 { .. } => match &value {
3935 Scalar::Bool(v) => Ok(Scalar::Datetime64(i64::from(*v))),
3938 Scalar::Int64(v) => Ok(Scalar::Datetime64(*v)),
3939 Scalar::Float64(v) => Ok(Scalar::Datetime64(float_to_temporal_nanos(*v))),
3940 Scalar::Utf8(s) => Timestamp::parse(s)
3941 .map(|timestamp| Scalar::Datetime64(timestamp.nanos))
3942 .map_err(|_| TypeError::InvalidCast { from, to: target }),
3943 _ => Err(TypeError::InvalidCast { from, to: target }),
3944 },
3945 DType::Period => match &value {
3946 Scalar::Int64(v) => Ok(Scalar::Period(Period::new(*v, PeriodFreq::Daily))),
3949 Scalar::Utf8(s) => Period::parse(s)
3950 .map(Scalar::Period)
3951 .map_err(|_| TypeError::InvalidCast { from, to: target }),
3952 _ => Err(TypeError::InvalidCast { from, to: target }),
3953 },
3954 DType::Interval => match &value {
3955 Scalar::Utf8(s) => Interval::parse(s)
3956 .map(Scalar::Interval)
3957 .map_err(|_| TypeError::InvalidCast { from, to: target }),
3958 _ => Err(TypeError::InvalidCast { from, to: target }),
3959 },
3960 DType::Sparse => Err(TypeError::InvalidCast { from, to: target }),
3961 }
3962}
3963
3964fn float_to_temporal_nanos(value: f64) -> i64 {
4000 if value.is_finite() && value > (i64::MIN as f64) && value < (i64::MAX as f64) {
4003 value as i64
4005 } else {
4006 Timestamp::NAT
4009 }
4010}
4011
4012fn scalar_to_string_for_astype(value: Scalar) -> String {
4013 match value {
4014 Scalar::Null(NullKind::Null) => "None".to_owned(),
4015 Scalar::Null(NullKind::NaN) => "nan".to_owned(),
4016 Scalar::Null(NullKind::NaT) => "NaT".to_owned(),
4017 Scalar::Bool(true) => "True".to_owned(),
4018 Scalar::Bool(false) => "False".to_owned(),
4019 Scalar::Int64(v) => v.to_string(),
4020 Scalar::Float64(v) => float_to_string_for_astype(v),
4021 Scalar::Utf8(s) => s,
4022 Scalar::Timedelta64(v) if v == Timedelta::NAT => "NaT".to_owned(),
4023 Scalar::Timedelta64(v) => Timedelta::format(v),
4024 Scalar::Datetime64(v) if v == Timestamp::NAT => "NaT".to_owned(),
4025 Scalar::Datetime64(v) => format!("Timestamp[{v}]"),
4026 Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
4027 Scalar::Period(p) => p.calendar_string(),
4028 Scalar::Interval(v) => v.to_string(),
4029 Scalar::Object(object) => object.to_string(),
4031 }
4032}
4033
4034pub fn float_to_string_for_astype(value: f64) -> String {
4035 use std::fmt::Write as _;
4036
4037 if value.is_nan() {
4038 return "nan".to_owned();
4039 }
4040 if value.is_infinite() {
4041 return value.to_string(); }
4043 let mut rendered = String::with_capacity(32);
4055 let _ = write!(rendered, "{value:?}");
4056 let Some(exponent_marker) = rendered.find('e') else {
4057 return rendered;
4058 };
4059
4060 let sign_position = exponent_marker + 1;
4061 let digits_position = match rendered.as_bytes().get(sign_position) {
4062 Some(b'+' | b'-') => sign_position + 1,
4063 _ => {
4064 rendered.insert(sign_position, '+');
4065 sign_position + 1
4066 }
4067 };
4068 if rendered.len() - digits_position == 1 {
4069 rendered.insert(digits_position, '0');
4070 }
4071 rendered
4072}
4073
4074static ENG_FLOAT_ACCURACY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(3);
4075static ENG_FLOAT_USE_PREFIX: std::sync::atomic::AtomicBool =
4076 std::sync::atomic::AtomicBool::new(false);
4077static ENG_FLOAT_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
4078
4079pub fn eng_float_format(num: f64, accuracy: Option<usize>, use_eng_prefix: bool) -> String {
4081 if num.is_nan() {
4082 return "NaN".to_string();
4083 }
4084 if num.is_infinite() {
4085 return if num < 0.0 {
4086 "-inf".to_string()
4087 } else {
4088 "inf".to_string()
4089 };
4090 }
4091
4092 let sign = if num < 0.0 { -1.0 } else { 1.0 };
4093 let abs_num = num.abs();
4094
4095 let pow10 = if abs_num != 0.0 {
4096 let p = (abs_num.log10() / 3.0).floor() as i32 * 3;
4097 p.clamp(-24, 24)
4098 } else {
4099 0
4100 };
4101
4102 let prefix = if use_eng_prefix {
4103 match pow10 {
4104 -24 => "y",
4105 -21 => "z",
4106 -18 => "a",
4107 -15 => "f",
4108 -12 => "p",
4109 -9 => "n",
4110 -6 => "u",
4111 -3 => "m",
4112 0 => "",
4113 3 => "k",
4114 6 => "M",
4115 9 => "G",
4116 12 => "T",
4117 15 => "P",
4118 18 => "E",
4119 21 => "Z",
4120 24 => "Y",
4121 _ => "",
4122 }
4123 .to_string()
4124 } else if pow10 < 0 {
4125 format!("E-{:02}", -pow10)
4126 } else {
4127 format!("E+{:02}", pow10)
4128 };
4129
4130 let mant = (sign * abs_num) / 10f64.powi(pow10);
4131
4132 if let Some(acc) = accuracy {
4133 format!("{mant:.acc$}{prefix}", acc = acc)
4134 } else {
4135 format!("{mant}{prefix}")
4136 }
4137}
4138
4139pub fn set_eng_float_format(accuracy: usize, use_eng_prefix: bool) {
4142 use std::sync::atomic::Ordering;
4143 ENG_FLOAT_ACCURACY.store(accuracy, Ordering::Relaxed);
4144 ENG_FLOAT_USE_PREFIX.store(use_eng_prefix, Ordering::Relaxed);
4145 ENG_FLOAT_ACTIVE.store(true, Ordering::Relaxed);
4146}
4147
4148pub fn reset_eng_float_format() {
4150 use std::sync::atomic::Ordering;
4151 ENG_FLOAT_ACTIVE.store(false, Ordering::Relaxed);
4152}
4153
4154pub fn get_eng_float_format() -> Option<(usize, bool)> {
4156 use std::sync::atomic::Ordering;
4157 if ENG_FLOAT_ACTIVE.load(Ordering::Relaxed) {
4158 Some((
4159 ENG_FLOAT_ACCURACY.load(Ordering::Relaxed),
4160 ENG_FLOAT_USE_PREFIX.load(Ordering::Relaxed),
4161 ))
4162 } else {
4163 None
4164 }
4165}
4166
4167#[derive(Debug, Error, Clone, PartialEq, Eq)]
4171pub enum OptionError {
4172 #[error("no such option: '{pat}'")]
4173 NotFound { pat: String },
4174 #[error("option pattern '{pat}' matches multiple options: {matches:?}")]
4175 Ambiguous { pat: String, matches: Vec<String> },
4176 #[error("invalid option value for '{pat}': {reason}")]
4177 InvalidValue { pat: String, reason: String },
4178}
4179
4180#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4182pub enum OptionValue {
4183 None,
4184 Int(i64),
4185 Float(f64),
4186 Bool(bool),
4187 Str(String),
4188}
4189
4190impl OptionValue {
4191 #[must_use]
4192 pub const fn is_none(&self) -> bool {
4193 matches!(self, Self::None)
4194 }
4195
4196 #[must_use]
4197 pub const fn as_int(&self) -> Option<i64> {
4198 match self {
4199 Self::Int(i) => Some(*i),
4200 _ => None,
4201 }
4202 }
4203
4204 #[must_use]
4205 pub const fn as_float(&self) -> Option<f64> {
4206 match self {
4207 Self::Float(f) => Some(*f),
4208 _ => None,
4209 }
4210 }
4211
4212 #[must_use]
4213 pub const fn as_bool(&self) -> Option<bool> {
4214 match self {
4215 Self::Bool(b) => Some(*b),
4216 _ => None,
4217 }
4218 }
4219
4220 #[must_use]
4221 pub fn as_str(&self) -> Option<&str> {
4222 match self {
4223 Self::Str(s) => Some(s.as_str()),
4224 _ => None,
4225 }
4226 }
4227}
4228
4229impl std::fmt::Display for OptionValue {
4230 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4231 match self {
4232 Self::None => write!(f, "None"),
4233 Self::Int(i) => write!(f, "{i}"),
4234 Self::Float(fl) => write!(f, "{fl}"),
4235 Self::Bool(b) => write!(f, "{b}"),
4236 Self::Str(s) => write!(f, "{s}"),
4237 }
4238 }
4239}
4240
4241impl From<i64> for OptionValue {
4242 fn from(v: i64) -> Self {
4243 Self::Int(v)
4244 }
4245}
4246
4247impl From<i32> for OptionValue {
4248 fn from(v: i32) -> Self {
4249 Self::Int(i64::from(v))
4250 }
4251}
4252
4253impl From<usize> for OptionValue {
4254 fn from(v: usize) -> Self {
4255 Self::Int(i64::try_from(v).unwrap_or(i64::MAX))
4256 }
4257}
4258
4259impl From<f64> for OptionValue {
4260 fn from(v: f64) -> Self {
4261 Self::Float(v)
4262 }
4263}
4264
4265impl From<bool> for OptionValue {
4266 fn from(v: bool) -> Self {
4267 Self::Bool(v)
4268 }
4269}
4270
4271impl From<&str> for OptionValue {
4272 fn from(v: &str) -> Self {
4273 Self::Str(v.to_string())
4274 }
4275}
4276
4277impl From<String> for OptionValue {
4278 fn from(v: String) -> Self {
4279 Self::Str(v)
4280 }
4281}
4282
4283impl From<()> for OptionValue {
4284 fn from(_: ()) -> Self {
4285 Self::None
4286 }
4287}
4288
4289fn default_options_map() -> std::collections::BTreeMap<String, OptionValue> {
4290 let mut m = std::collections::BTreeMap::new();
4291 m.insert("display.max_rows".to_string(), OptionValue::Int(60));
4292 m.insert("display.min_rows".to_string(), OptionValue::Int(10));
4293 m.insert("display.max_columns".to_string(), OptionValue::Int(0));
4294 m.insert("display.width".to_string(), OptionValue::Int(80));
4295 m.insert("display.precision".to_string(), OptionValue::Int(6));
4296 m.insert("display.max_colwidth".to_string(), OptionValue::Int(50));
4297 m.insert(
4298 "display.show_dimensions".to_string(),
4299 OptionValue::Bool(true),
4300 );
4301 m.insert("display.float_format".to_string(), OptionValue::None);
4302 m.insert(
4303 "display.large_repr".to_string(),
4304 OptionValue::Str("truncate".to_string()),
4305 );
4306 m.insert(
4307 "display.max_info_columns".to_string(),
4308 OptionValue::Int(100),
4309 );
4310 m.insert(
4311 "display.max_info_rows".to_string(),
4312 OptionValue::Int(1690785),
4313 );
4314 m.insert("display.memory_usage".to_string(), OptionValue::Bool(true));
4315 m.insert(
4316 "display.colheader_justify".to_string(),
4317 OptionValue::Str("right".to_string()),
4318 );
4319 m.insert("display.chop_threshold".to_string(), OptionValue::None);
4320 m.insert(
4321 "display.date_dayfirst".to_string(),
4322 OptionValue::Bool(false),
4323 );
4324 m.insert(
4325 "display.date_yearfirst".to_string(),
4326 OptionValue::Bool(false),
4327 );
4328 m.insert(
4329 "display.encoding".to_string(),
4330 OptionValue::Str("utf-8".to_string()),
4331 );
4332 m.insert("mode.sim_interactive".to_string(), OptionValue::Bool(false));
4333 m.insert(
4334 "mode.chained_assignment".to_string(),
4335 OptionValue::Str("warn".to_string()),
4336 );
4337 m.insert("mode.use_inf_as_na".to_string(), OptionValue::Bool(false));
4338 m.insert("mode.copy_on_write".to_string(), OptionValue::Bool(false));
4339 m.insert(
4340 "mode.data_manager".to_string(),
4341 OptionValue::Str("block".to_string()),
4342 );
4343 m.insert(
4344 "compute.use_bottleneck".to_string(),
4345 OptionValue::Bool(true),
4346 );
4347 m.insert("compute.use_numba".to_string(), OptionValue::Bool(false));
4348 m.insert(
4349 "io.excel.zip.reader".to_string(),
4350 OptionValue::Str("zipfile".to_string()),
4351 );
4352 m.insert(
4353 "io.parquet.engine".to_string(),
4354 OptionValue::Str("auto".to_string()),
4355 );
4356 m.insert(
4357 "io.sql.engine".to_string(),
4358 OptionValue::Str("auto".to_string()),
4359 );
4360 m.insert(
4361 "plotting.backend".to_string(),
4362 OptionValue::Str("matplotlib".to_string()),
4363 );
4364 m.insert(
4365 "plotting.matplotlib.register_converters".to_string(),
4366 OptionValue::Bool(true),
4367 );
4368 m
4369}
4370
4371static GLOBAL_OPTIONS: std::sync::LazyLock<
4372 std::sync::Mutex<std::collections::BTreeMap<String, OptionValue>>,
4373> = std::sync::LazyLock::new(|| std::sync::Mutex::new(default_options_map()));
4374
4375fn resolve_option_key(
4376 pat: &str,
4377 map: &std::collections::BTreeMap<String, OptionValue>,
4378) -> Result<String, OptionError> {
4379 if map.contains_key(pat) {
4380 return Ok(pat.to_string());
4381 }
4382 let matches: Vec<String> = map
4383 .keys()
4384 .filter(|k| k.ends_with(pat) || k.contains(pat))
4385 .cloned()
4386 .collect();
4387 if matches.len() == 1 {
4388 Ok(matches[0].clone())
4389 } else if matches.is_empty() {
4390 Err(OptionError::NotFound {
4391 pat: pat.to_string(),
4392 })
4393 } else {
4394 Err(OptionError::Ambiguous {
4395 pat: pat.to_string(),
4396 matches,
4397 })
4398 }
4399}
4400
4401pub fn get_option(pat: &str) -> Result<OptionValue, OptionError> {
4407 let map = GLOBAL_OPTIONS
4408 .lock()
4409 .unwrap_or_else(std::sync::PoisonError::into_inner);
4410 let key = resolve_option_key(pat, &map)?;
4411 Ok(map.get(&key).cloned().unwrap_or(OptionValue::None))
4412}
4413
4414pub fn set_option(pat: &str, val: impl Into<OptionValue>) -> Result<(), OptionError> {
4420 let mut map = GLOBAL_OPTIONS
4421 .lock()
4422 .unwrap_or_else(std::sync::PoisonError::into_inner);
4423 let key = resolve_option_key(pat, &map)?;
4424 let v = val.into();
4425 map.insert(key, v);
4426 Ok(())
4427}
4428
4429pub fn reset_option(pat: Option<&str>) -> Result<(), OptionError> {
4436 let mut map = GLOBAL_OPTIONS
4437 .lock()
4438 .unwrap_or_else(std::sync::PoisonError::into_inner);
4439 let defaults = default_options_map();
4440 let p = pat.unwrap_or("all");
4441 if p == "all" {
4442 *map = defaults;
4443 return Ok(());
4444 }
4445 let key = resolve_option_key(p, &defaults)?;
4446 if let Some(def_val) = defaults.get(&key) {
4447 map.insert(key, def_val.clone());
4448 }
4449 Ok(())
4450}
4451
4452pub fn describe_option(pat: Option<&str>) -> Result<String, OptionError> {
4457 use std::fmt::Write as _;
4458 let map = GLOBAL_OPTIONS
4459 .lock()
4460 .unwrap_or_else(std::sync::PoisonError::into_inner);
4461 let mut out = String::with_capacity(map.len() * 40);
4462 let mut matched = 0;
4463 for (k, v) in map.iter() {
4464 if let Some(p) = pat
4465 && !k.contains(p)
4466 {
4467 continue;
4468 }
4469 if matched > 0 {
4470 out.push('\n');
4471 }
4472 let _ = write!(out, "{k} : [currently: {v}]");
4473 matched += 1;
4474 }
4475 if matched == 0
4476 && let Some(p) = pat
4477 {
4478 return Err(OptionError::NotFound { pat: p.to_string() });
4479 }
4480 Ok(out)
4481}
4482
4483#[derive(Debug)]
4485pub struct OptionContextGuard {
4486 saved: Vec<(String, OptionValue)>,
4487}
4488
4489impl Drop for OptionContextGuard {
4490 fn drop(&mut self) {
4491 let mut map = GLOBAL_OPTIONS
4492 .lock()
4493 .unwrap_or_else(std::sync::PoisonError::into_inner);
4494 for (k, old) in self.saved.drain(..) {
4495 map.insert(k, old);
4496 }
4497 }
4498}
4499
4500pub fn option_context(entries: &[(&str, OptionValue)]) -> Result<OptionContextGuard, OptionError> {
4505 let mut map = GLOBAL_OPTIONS
4506 .lock()
4507 .unwrap_or_else(std::sync::PoisonError::into_inner);
4508 let mut saved = Vec::with_capacity(entries.len());
4509 for (pat, new_val) in entries {
4510 let key = resolve_option_key(pat, &map)?;
4511 if let Some(old) = map.get(&key) {
4512 saved.push((key.clone(), old.clone()));
4513 }
4514 map.insert(key, new_val.clone());
4515 }
4516 Ok(OptionContextGuard { saved })
4517}
4518
4519pub fn cast_scalar(value: &Scalar, target: DType) -> Result<Scalar, TypeError> {
4521 cast_scalar_owned(value.clone(), target)
4522}
4523
4524#[derive(Debug, Error, Clone, PartialEq)]
4527pub enum TimedeltaError {
4528 #[error("invalid timedelta string: {0}")]
4529 InvalidFormat(String),
4530 #[error("overflow in timedelta computation")]
4531 Overflow,
4532}
4533
4534impl TimedeltaError {
4535 #[must_use]
4541 pub const fn pandas_error(&self) -> Option<PandasTemporalError> {
4542 match self {
4543 Self::Overflow => Some(PandasTemporalError::OutOfBoundsTimedelta),
4546 Self::InvalidFormat(_) => None,
4547 }
4548 }
4549}
4550
4551#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4552pub struct CategoricalMetadata {
4553 pub categories: Vec<Scalar>,
4555 pub ordered: bool,
4557}
4558
4559impl CategoricalMetadata {
4560 #[must_use]
4561 pub fn new(categories: Vec<Scalar>, ordered: bool) -> Self {
4562 Self {
4563 categories,
4564 ordered,
4565 }
4566 }
4567}
4568
4569#[derive(Debug, Clone, Copy, Default)]
4570pub struct TimedeltaComponents {
4571 pub days: i64,
4572 pub hours: i64,
4573 pub minutes: i64,
4574 pub seconds: i64,
4575 pub milliseconds: i64,
4576 pub microseconds: i64,
4577 pub nanoseconds: i64,
4578}
4579
4580#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4592pub enum PandasTemporalError {
4593 Overflow,
4597 OutOfBoundsDatetime,
4600 OutOfBoundsTimedelta,
4605 OverflowInTimedeltaOperation,
4608 ZeroDivision,
4617}
4618
4619#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4622pub struct TemporalFailure {
4623 pub op: &'static str,
4625 pub pandas_error: PandasTemporalError,
4627 pub operands: Option<(i64, i64)>,
4632}
4633
4634impl TemporalFailure {
4635 #[must_use]
4636 pub const fn new(op: &'static str, pandas_error: PandasTemporalError) -> Self {
4637 Self {
4638 op,
4639 pandas_error,
4640 operands: None,
4641 }
4642 }
4643
4644 #[must_use]
4646 pub const fn with_operands(mut self, lhs: i64, rhs: i64) -> Self {
4647 self.operands = Some((lhs, rhs));
4648 self
4649 }
4650}
4651
4652#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4662pub struct TemporalRecovery {
4663 pub op: &'static str,
4665 pub pandas_error: PandasTemporalError,
4667 pub operands: Option<(i64, i64)>,
4669 pub recovered_as: i64,
4671}
4672
4673pub mod overflow_audit {
4682 use std::cell::RefCell;
4683
4684 use super::TemporalRecovery;
4685
4686 thread_local! {
4687 static LOG: RefCell<Option<Vec<TemporalRecovery>>> = const { RefCell::new(None) };
4688 }
4689
4690 pub fn enable() {
4692 LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
4693 }
4694
4695 pub fn disable() {
4697 LOG.with(|log| *log.borrow_mut() = None);
4698 }
4699
4700 #[must_use]
4702 pub fn is_enabled() -> bool {
4703 LOG.with(|log| log.borrow().is_some())
4704 }
4705
4706 #[must_use]
4708 pub fn drain() -> Vec<TemporalRecovery> {
4709 LOG.with(|log| match log.borrow_mut().as_mut() {
4710 Some(entries) => std::mem::take(entries),
4711 None => Vec::new(),
4712 })
4713 }
4714
4715 pub(super) fn record(entry: TemporalRecovery) {
4717 LOG.with(|log| {
4718 if let Some(entries) = log.borrow_mut().as_mut() {
4719 entries.push(entry);
4720 }
4721 });
4722 }
4723}
4724
4725#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
4738pub enum OverflowPolicy {
4739 #[default]
4742 SurfaceNat,
4743 Strict,
4745 HardenedNat,
4753}
4754
4755impl OverflowPolicy {
4756 pub fn resolve<T>(
4764 self,
4765 outcome: Result<T, TemporalFailure>,
4766 nat: T,
4767 ) -> Result<T, TemporalFailure> {
4768 self.resolve_recording(outcome, nat, i64::MIN)
4769 }
4770
4771 pub fn resolve_recording<T>(
4780 self,
4781 outcome: Result<T, TemporalFailure>,
4782 nat: T,
4783 recovered_as: i64,
4784 ) -> Result<T, TemporalFailure> {
4785 match (self, outcome) {
4786 (_, Ok(value)) => Ok(value),
4787 (Self::SurfaceNat, Err(_)) => Ok(nat),
4788 (Self::Strict, Err(failure)) => Err(failure),
4789 (Self::HardenedNat, Err(failure)) => {
4790 overflow_audit::record(TemporalRecovery {
4792 op: failure.op,
4793 pandas_error: failure.pandas_error,
4794 operands: failure.operands,
4795 recovered_as,
4796 });
4797 Ok(nat)
4798 }
4799 }
4800 }
4801}
4802
4803pub struct Timedelta;
4804
4805impl Timedelta {
4806 pub const NANOS_PER_MICRO: i64 = 1_000;
4807 pub const NANOS_PER_MILLI: i64 = 1_000_000;
4808 pub const NANOS_PER_SEC: i64 = 1_000_000_000;
4809 pub const NANOS_PER_MIN: i64 = 60 * Self::NANOS_PER_SEC;
4810 pub const NANOS_PER_HOUR: i64 = 60 * Self::NANOS_PER_MIN;
4811 pub const NANOS_PER_DAY: i64 = 24 * Self::NANOS_PER_HOUR;
4812 pub const NANOS_PER_WEEK: i64 = 7 * Self::NANOS_PER_DAY;
4813
4814 pub const NAT: i64 = i64::MIN;
4815
4816 pub fn parse(s: &str) -> Result<i64, TimedeltaError> {
4817 let s = s.trim();
4818
4819 if s.eq_ignore_ascii_case("nat") {
4820 return Ok(Self::NAT);
4821 }
4822
4823 let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
4824 (true, rest.trim())
4825 } else {
4826 (false, s)
4827 };
4828
4829 if let Some(nanos) = Self::try_parse_time_format(s) {
4830 return Ok(if negative { -nanos } else { nanos });
4831 }
4832
4833 if let Some(nanos) = Self::try_parse_iso8601_duration(s) {
4834 return Ok(if negative { -nanos } else { nanos });
4835 }
4836
4837 let (units, clock) = Self::parse_compound(s)?;
4843 let units = if negative { -units } else { units };
4844 units.checked_add(clock).ok_or(TimedeltaError::Overflow)
4845 }
4846
4847 fn try_parse_iso8601_duration(s: &str) -> Option<i64> {
4855 let mut rest = s.strip_prefix('P')?;
4856 if rest.is_empty() {
4857 return None;
4858 }
4859 let mut total: i64 = 0;
4860 let mut saw_component = false;
4861 while !rest.is_empty() {
4862 if let Some(after_t) = rest.strip_prefix('T') {
4863 rest = after_t;
4864 continue;
4865 }
4866 let num_end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')?;
4867 if num_end == 0 {
4868 return None;
4869 }
4870 let num_str = &rest[..num_end];
4871 let unit = rest.as_bytes()[num_end];
4872 let is_fractional = num_str.contains('.');
4873 rest = &rest[num_end + 1..];
4874
4875 let (multiplier, frac_ok) = match unit {
4876 b'W' => (Self::NANOS_PER_WEEK, false),
4877 b'D' => (Self::NANOS_PER_DAY, false),
4878 b'H' => (Self::NANOS_PER_HOUR, false),
4879 b'M' => (Self::NANOS_PER_MIN, false),
4880 b'S' => (Self::NANOS_PER_SEC, true),
4881 _ => return None,
4882 };
4883 if is_fractional {
4884 if !frac_ok {
4885 return None;
4886 }
4887 let value: f64 = num_str.parse().ok()?;
4888 let product = value * multiplier as f64;
4889 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
4890 return None;
4891 }
4892 total = total.checked_add(product.round() as i64)?;
4893 } else {
4894 let value: i64 = num_str.parse().ok()?;
4895 total = total.checked_add(value.checked_mul(multiplier)?)?;
4896 }
4897 saw_component = true;
4898 }
4899 saw_component.then_some(total)
4900 }
4901
4902 fn try_parse_time_format(s: &str) -> Option<i64> {
4903 let parts: Vec<&str> = s.split(':').collect();
4904 if parts.len() < 2 || parts.len() > 3 {
4905 return None;
4906 }
4907
4908 let hours: i64 = parts[0].parse().ok()?;
4909 let minutes: i64 = parts[1].parse().ok()?;
4910
4911 let (seconds, frac_nanos) = if parts.len() == 3 {
4912 if let Some((sec_str, frac_str)) = parts[2].split_once('.') {
4913 let sec: i64 = sec_str.parse().ok()?;
4914 if !frac_str.bytes().all(|byte| byte.is_ascii_digit()) {
4915 return None;
4916 }
4917 let mut frac = 0_i64;
4918 let taken = frac_str.len().min(9);
4919 for byte in frac_str.bytes().take(9) {
4920 frac = frac * 10 + i64::from(byte - b'0');
4921 }
4922 for _ in taken..9 {
4923 frac *= 10;
4924 }
4925 (sec, frac)
4926 } else {
4927 let sec: i64 = parts[2].parse().ok()?;
4928 (sec, 0)
4929 }
4930 } else {
4931 (0, 0)
4932 };
4933
4934 hours
4935 .checked_mul(Self::NANOS_PER_HOUR)?
4936 .checked_add(minutes.checked_mul(Self::NANOS_PER_MIN)?)?
4937 .checked_add(seconds.checked_mul(Self::NANOS_PER_SEC)?)?
4938 .checked_add(frac_nanos)
4939 }
4940
4941 fn parse_compound(s: &str) -> Result<(i64, i64), TimedeltaError> {
4947 let mut total: i64 = 0;
4948 let mut clock: i64 = 0;
4949 let mut remaining = s;
4950
4951 while !remaining.is_empty() {
4952 remaining = remaining.trim_start();
4953 if remaining.is_empty() {
4954 break;
4955 }
4956 if remaining.starts_with('-') {
4957 return Err(TimedeltaError::InvalidFormat(format!(
4958 "only leading negative signs are allowed: {s}"
4959 )));
4960 }
4961
4962 if remaining.contains(':')
4965 && let Some(time_nanos) = Self::try_parse_time_format(remaining)
4966 {
4967 clock = time_nanos;
4968 break;
4969 }
4970
4971 let num_end = remaining
4972 .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
4973 .unwrap_or(remaining.len());
4974
4975 if num_end == 0 {
4976 return Err(TimedeltaError::InvalidFormat(s.to_string()));
4977 }
4978
4979 let num_str = &remaining[..num_end];
4980 let num: f64 = num_str
4981 .parse()
4982 .map_err(|_| TimedeltaError::InvalidFormat(s.to_string()))?;
4983
4984 remaining = remaining[num_end..].trim_start();
4985
4986 let unit_end = remaining
4987 .find(|c: char| c.is_ascii_digit() || c.is_whitespace())
4988 .unwrap_or(remaining.len());
4989
4990 let unit = &remaining[..unit_end];
4991 remaining = &remaining[unit_end..];
4992
4993 let multiplier = Self::unit_to_nanos(unit)
4994 .ok_or_else(|| TimedeltaError::InvalidFormat(s.to_string()))?;
4995
4996 let product = num * multiplier as f64;
5001 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5002 return Err(TimedeltaError::Overflow);
5003 }
5004 let nanos = product.round() as i64;
5005 total = total.checked_add(nanos).ok_or(TimedeltaError::Overflow)?;
5006 }
5007
5008 Ok((total, clock))
5018 }
5019
5020 #[must_use]
5034 pub fn unit_to_nanos(unit: &str) -> Option<i64> {
5035 match unit.to_lowercase().as_str() {
5036 "w" | "week" | "weeks" => Some(Self::NANOS_PER_WEEK),
5037 "d" | "day" | "days" => Some(Self::NANOS_PER_DAY),
5038 "h" | "hr" | "hour" | "hours" => Some(Self::NANOS_PER_HOUR),
5039 "m" | "min" | "minute" | "minutes" | "t" => Some(Self::NANOS_PER_MIN),
5040 "s" | "sec" | "second" | "seconds" => Some(Self::NANOS_PER_SEC),
5041 "ms" | "milli" | "millis" | "millisecond" | "milliseconds" | "l" => {
5042 Some(Self::NANOS_PER_MILLI)
5043 }
5044 "us" | "µs" | "micro" | "micros" | "microsecond" | "microseconds" | "u" => {
5045 Some(Self::NANOS_PER_MICRO)
5046 }
5047 "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" | "n" => Some(1),
5048 "" => Some(Self::NANOS_PER_DAY),
5049 _ => None,
5050 }
5051 }
5052
5053 pub fn components(nanos: i64) -> TimedeltaComponents {
5054 if nanos == Self::NAT {
5055 return TimedeltaComponents::default();
5056 }
5057
5058 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5063 let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5064
5065 let hours = rem / Self::NANOS_PER_HOUR;
5066 let rem = rem % Self::NANOS_PER_HOUR;
5067
5068 let minutes = rem / Self::NANOS_PER_MIN;
5069 let rem = rem % Self::NANOS_PER_MIN;
5070
5071 let seconds = rem / Self::NANOS_PER_SEC;
5072 let rem = rem % Self::NANOS_PER_SEC;
5073
5074 let milliseconds = rem / Self::NANOS_PER_MILLI;
5075 let rem = rem % Self::NANOS_PER_MILLI;
5076
5077 let microseconds = rem / Self::NANOS_PER_MICRO;
5078 let nanoseconds = rem % Self::NANOS_PER_MICRO;
5079
5080 TimedeltaComponents {
5081 days,
5082 hours,
5083 minutes,
5084 seconds,
5085 milliseconds,
5086 microseconds,
5087 nanoseconds,
5088 }
5089 }
5090
5091 pub fn total_seconds(nanos: i64) -> f64 {
5092 if nanos == Self::NAT {
5093 f64::NAN
5094 } else {
5095 nanos as f64 / Self::NANOS_PER_SEC as f64
5096 }
5097 }
5098
5099 #[must_use]
5103 pub fn as_unit(nanos: i64, unit: &str) -> f64 {
5104 if nanos == Self::NAT {
5105 return f64::NAN;
5106 }
5107 let nanos_f = nanos as f64;
5108 match unit {
5109 "ns" | "nanoseconds" => nanos_f,
5110 "us" | "microseconds" => nanos_f / Self::NANOS_PER_MICRO as f64,
5111 "ms" | "milliseconds" => nanos_f / Self::NANOS_PER_MILLI as f64,
5112 "s" | "seconds" => nanos_f / Self::NANOS_PER_SEC as f64,
5113 "m" | "minutes" => nanos_f / Self::NANOS_PER_MIN as f64,
5114 "h" | "hours" => nanos_f / Self::NANOS_PER_HOUR as f64,
5115 "D" | "days" => nanos_f / Self::NANOS_PER_DAY as f64,
5116 _ => f64::NAN,
5117 }
5118 }
5119
5120 #[must_use]
5140 pub fn days(nanos: i64) -> Option<i64> {
5141 if nanos == Self::NAT {
5142 return None;
5143 }
5144 Some(nanos.div_euclid(Self::NANOS_PER_DAY))
5146 }
5147
5148 #[must_use]
5151 pub fn seconds(nanos: i64) -> Option<i64> {
5152 if nanos == Self::NAT {
5153 return None;
5154 }
5155 Some(nanos.rem_euclid(Self::NANOS_PER_DAY) / Self::NANOS_PER_SEC)
5157 }
5158
5159 #[must_use]
5162 pub fn microseconds(nanos: i64) -> Option<i64> {
5163 if nanos == Self::NAT {
5164 return None;
5165 }
5166 Some(nanos.rem_euclid(Self::NANOS_PER_SEC) / Self::NANOS_PER_MICRO)
5167 }
5168
5169 #[must_use]
5172 pub fn nanoseconds(nanos: i64) -> Option<i64> {
5173 if nanos == Self::NAT {
5174 return None;
5175 }
5176 Some(nanos.rem_euclid(Self::NANOS_PER_MICRO))
5177 }
5178
5179 #[must_use]
5185 pub const fn string_resolution(nanos: i64) -> TimedeltaStringResolution {
5186 if nanos == Self::NAT || nanos.rem_euclid(Self::NANOS_PER_DAY) == 0 {
5187 TimedeltaStringResolution::Days
5188 } else {
5189 TimedeltaStringResolution::Full
5190 }
5191 }
5192
5193 #[must_use]
5201 pub fn format_at_resolution(nanos: i64, resolution: TimedeltaStringResolution) -> String {
5202 if nanos == Self::NAT {
5203 return "NaT".to_string();
5204 }
5205 match resolution {
5206 TimedeltaStringResolution::Full => Self::format(nanos),
5207 TimedeltaStringResolution::Days => {
5210 format!("{} days", nanos.div_euclid(Self::NANOS_PER_DAY))
5211 }
5212 }
5213 }
5214
5215 pub fn format(nanos: i64) -> String {
5216 use std::fmt::Write as _;
5217
5218 if nanos == Self::NAT {
5219 return "NaT".to_string();
5220 }
5221
5222 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5228 let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5229 let hours = rem / Self::NANOS_PER_HOUR;
5230 let minutes = (rem % Self::NANOS_PER_HOUR) / Self::NANOS_PER_MIN;
5231 let seconds = (rem % Self::NANOS_PER_MIN) / Self::NANOS_PER_SEC;
5232 let frac = rem % Self::NANOS_PER_SEC;
5233
5234 let mut result = String::with_capacity(32);
5237 let _ = write!(result, "{days} days ");
5238 if days < 0 {
5240 result.push('+');
5241 }
5242 let _ = write!(result, "{hours:02}:{minutes:02}:{seconds:02}");
5243 if frac > 0 {
5244 if frac % 1_000 == 0 {
5248 let _ = write!(result, ".{:06}", frac / 1_000);
5249 } else {
5250 let _ = write!(result, ".{frac:09}");
5251 }
5252 }
5253 result
5254 }
5255
5256 pub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError> {
5273 let multiplier = Self::unit_to_nanos(unit)
5274 .ok_or_else(|| TimedeltaError::InvalidFormat(unit.to_string()))?;
5275 if value.is_nan() {
5276 return Ok(Self::NAT);
5277 }
5278 let product = value * multiplier as f64;
5279 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5280 return Err(TimedeltaError::Overflow);
5281 }
5282 Ok(product.round() as i64)
5283 }
5284
5285 pub fn try_add(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5325 if a == Self::NAT || b == Self::NAT {
5326 return Ok(Self::NAT);
5327 }
5328 a.checked_add(b).ok_or(
5329 TemporalFailure::new("Timedelta::add", PandasTemporalError::Overflow)
5330 .with_operands(a, b),
5331 )
5332 }
5333
5334 #[must_use]
5336 pub fn add(a: i64, b: i64) -> i64 {
5337 Self::try_add(a, b).unwrap_or(Self::NAT)
5338 }
5339
5340 pub fn try_sub(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5345 if a == Self::NAT || b == Self::NAT {
5346 return Ok(Self::NAT);
5347 }
5348 a.checked_sub(b).ok_or(
5349 TemporalFailure::new("Timedelta::sub", PandasTemporalError::Overflow)
5350 .with_operands(a, b),
5351 )
5352 }
5353
5354 #[must_use]
5356 pub fn sub(a: i64, b: i64) -> i64 {
5357 Self::try_sub(a, b).unwrap_or(Self::NAT)
5358 }
5359
5360 #[must_use]
5378 pub fn neg(a: i64) -> i64 {
5379 if a == Self::NAT {
5380 return Self::NAT;
5381 }
5382 a.saturating_neg()
5383 }
5384
5385 #[must_use]
5392 pub fn abs(a: i64) -> i64 {
5393 if a == Self::NAT {
5394 return Self::NAT;
5395 }
5396 a.saturating_abs()
5397 }
5398
5399 #[must_use]
5405 pub fn mul_scalar(a: i64, factor: i64) -> i64 {
5406 Self::try_mul_scalar(a, factor).unwrap_or(Self::NAT)
5407 }
5408
5409 #[must_use]
5430 pub fn mul_scalar_with_policy(a: i64, factor: i64, policy: OverflowPolicy) -> i64 {
5431 if a == Self::NAT {
5432 return Self::NAT;
5433 }
5434 if matches!(policy, OverflowPolicy::Strict) {
5435 return a.wrapping_mul(factor);
5436 }
5437 policy
5438 .resolve_recording(Self::try_mul_scalar(a, factor), Self::NAT, Self::NAT)
5439 .unwrap_or(Self::NAT)
5440 }
5441
5442 pub fn try_mul_scalar(a: i64, factor: i64) -> Result<i64, TemporalFailure> {
5450 if a == Self::NAT {
5451 return Ok(Self::NAT);
5452 }
5453 a.checked_mul(factor).ok_or(
5454 TemporalFailure::new("Timedelta::mul_scalar", PandasTemporalError::Overflow)
5455 .with_operands(a, factor),
5456 )
5457 }
5458
5459 #[must_use]
5469 pub fn div_scalar(a: i64, divisor: i64) -> i64 {
5470 Self::try_div_scalar(a, divisor).unwrap_or(Self::NAT)
5471 }
5472
5473 pub fn try_div_scalar(a: i64, divisor: i64) -> Result<i64, TemporalFailure> {
5488 if divisor == 0 {
5489 return Err(TemporalFailure::new(
5490 "Timedelta::div_scalar",
5491 PandasTemporalError::ZeroDivision,
5492 )
5493 .with_operands(a, divisor));
5494 }
5495 if a == Self::NAT {
5496 return Ok(Self::NAT);
5497 }
5498 Ok(Self::div_scalar_inner(a, divisor))
5499 }
5500
5501 fn div_scalar_inner(a: i64, divisor: i64) -> i64 {
5502 let q = a / divisor;
5507 let r = a % divisor;
5508 if r != 0 && (r < 0) != (divisor < 0) {
5512 q - 1
5513 } else {
5514 q
5515 }
5516 }
5517
5518 #[must_use]
5522 pub fn div_timedelta(a: i64, b: i64) -> f64 {
5523 if a == Self::NAT || b == Self::NAT {
5524 return f64::NAN;
5525 }
5526 (a as f64) / (b as f64)
5527 }
5528
5529 #[must_use]
5537 pub fn isoformat(nanos: i64) -> String {
5538 use std::fmt::Write as _;
5539
5540 if nanos == Self::NAT {
5541 return "NaT".to_string();
5542 }
5543
5544 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5545 let remaining = nanos.rem_euclid(Self::NANOS_PER_DAY);
5546
5547 let hours = remaining / Self::NANOS_PER_HOUR;
5548 let remaining = remaining % Self::NANOS_PER_HOUR;
5549
5550 let minutes = remaining / Self::NANOS_PER_MIN;
5551 let remaining = remaining % Self::NANOS_PER_MIN;
5552
5553 let seconds = remaining / Self::NANOS_PER_SEC;
5554 let sub_sec_nanos = remaining % Self::NANOS_PER_SEC;
5555
5556 let mut result = String::with_capacity(40);
5560 let _ = write!(result, "P{days}DT{hours}H{minutes}M{seconds}");
5562 if sub_sec_nanos != 0 {
5563 result.push('.');
5564 let _ = write!(result, "{sub_sec_nanos:09}");
5565 while result.ends_with('0') {
5566 result.pop();
5567 }
5568 }
5569 result.push('S');
5570 result
5571 }
5572
5573 #[must_use]
5577 pub fn floor(nanos: i64, freq: &str) -> i64 {
5578 if nanos == Self::NAT {
5579 return Self::NAT;
5580 }
5581 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5582 return Self::NAT;
5583 };
5584 if unit_nanos == 0 {
5585 return Self::NAT;
5586 }
5587 nanos
5588 .div_euclid(unit_nanos)
5589 .checked_mul(unit_nanos)
5590 .unwrap_or(Self::NAT)
5591 }
5592
5593 #[must_use]
5600 pub fn ceil(nanos: i64, freq: &str) -> i64 {
5601 if nanos == Self::NAT {
5602 return Self::NAT;
5603 }
5604 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5605 return Self::NAT;
5606 };
5607 if unit_nanos == 0 {
5608 return Self::NAT;
5609 }
5610 let remainder = nanos.rem_euclid(unit_nanos);
5611 if remainder == 0 {
5612 nanos
5613 } else {
5614 nanos
5615 .checked_add(unit_nanos - remainder)
5616 .unwrap_or(Self::NAT)
5617 }
5618 }
5619
5620 #[must_use]
5625 pub fn round(nanos: i64, freq: &str) -> i64 {
5626 if nanos == Self::NAT {
5627 return Self::NAT;
5628 }
5629 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5630 return Self::NAT;
5631 };
5632 if unit_nanos == 0 {
5633 return Self::NAT;
5634 }
5635 let negative = nanos < 0;
5636 let abs_nanos = nanos.saturating_abs();
5637
5638 let quotient = abs_nanos / unit_nanos;
5639 let remainder = abs_nanos % unit_nanos;
5640 let half = unit_nanos / 2;
5641
5642 let round_up = || {
5650 quotient
5651 .checked_add(1)
5652 .and_then(|q| q.checked_mul(unit_nanos))
5653 };
5654 let rounded = if remainder > half {
5655 round_up()
5656 } else if remainder < half {
5657 Some(quotient * unit_nanos)
5658 } else {
5659 if quotient % 2 == 0 {
5661 Some(quotient * unit_nanos)
5662 } else {
5663 round_up()
5664 }
5665 };
5666
5667 match rounded {
5668 Some(rounded) => {
5671 if negative {
5672 -rounded
5673 } else {
5674 rounded
5675 }
5676 }
5677 None => Self::NAT,
5678 }
5679 }
5680}
5681
5682#[derive(Debug, Clone, PartialEq, Eq, Error)]
5690pub enum TimeZoneError {
5691 #[error("'{0}'")]
5694 Unknown(String),
5695 #[error("{0}")]
5698 NonExistent(String),
5699 #[error("Cannot infer dst time from {0}, try using the 'ambiguous' argument")]
5701 Ambiguous(String),
5702}
5703
5704enum Zone {
5706 Fixed(chrono::FixedOffset),
5707 Named(chrono_tz::Tz),
5708}
5709
5710impl Zone {
5711 fn parse(tz: &str) -> Result<Self, TimeZoneError> {
5715 use chrono::Offset;
5716 let name = tz.trim();
5717 if name == "UTC" || name == "Z" {
5718 return Ok(Self::Fixed(chrono::Utc.fix()));
5719 }
5720 let offset = name
5721 .strip_prefix("UTC")
5722 .filter(|rest| rest.starts_with(['+', '-']))
5723 .unwrap_or(name);
5724 let bytes = offset.as_bytes();
5725 if bytes.len() == 6
5726 && matches!(bytes[0], b'+' | b'-')
5727 && bytes[3] == b':'
5728 && [1, 2, 4, 5].iter().all(|&i| bytes[i].is_ascii_digit())
5729 {
5730 let hours: i32 = offset[1..3].parse().unwrap_or(24);
5731 let minutes: i32 = offset[4..6].parse().unwrap_or(60);
5732 let sign = if bytes[0] == b'-' { -1 } else { 1 };
5733 return (hours <= 23 && minutes <= 59)
5734 .then(|| chrono::FixedOffset::east_opt(sign * (hours * 3_600 + minutes * 60)))
5735 .flatten()
5736 .map(Self::Fixed)
5737 .ok_or_else(|| TimeZoneError::Unknown(name.to_owned()));
5738 }
5739 name.parse::<chrono_tz::Tz>()
5740 .map(Self::Named)
5741 .map_err(|_| TimeZoneError::Unknown(name.to_owned()))
5742 }
5743
5744 fn offset_seconds(&self, utc_nanos: i64) -> i32 {
5746 use chrono::{Offset, TimeZone};
5747 match self {
5748 Self::Fixed(offset) => offset.local_minus_utc(),
5749 Self::Named(zone) => {
5750 let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5751 zone.offset_from_utc_datetime(&utc).fix().local_minus_utc()
5752 }
5753 }
5754 }
5755}
5756
5757pub fn tz_validate(tz: &str) -> Result<(), TimeZoneError> {
5759 Zone::parse(tz).map(|_| ())
5760}
5761
5762pub fn tz_canonical_name(tz: &str) -> Result<String, TimeZoneError> {
5766 Ok(match Zone::parse(tz)? {
5767 Zone::Fixed(offset) if offset.local_minus_utc() == 0 => "UTC".to_owned(),
5768 Zone::Fixed(offset) => format!("UTC{offset}"),
5769 Zone::Named(_) => tz.trim().to_owned(),
5770 })
5771}
5772
5773pub fn tz_abbreviation(tz: &str, utc_nanos: i64) -> Result<String, TimeZoneError> {
5777 use chrono::TimeZone;
5778 match Zone::parse(tz)? {
5779 Zone::Named(zone) => {
5780 let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5781 let offset = zone.offset_from_utc_datetime(&utc);
5782 Ok(chrono_tz::OffsetName::abbreviation(&offset)
5783 .map_or_else(|| tz.trim().to_owned(), str::to_owned))
5784 }
5785 Zone::Fixed(_) => tz_canonical_name(tz),
5786 }
5787}
5788
5789pub fn tz_offset_seconds(tz: &str, utc_nanos: i64) -> Result<i32, TimeZoneError> {
5793 Ok(Zone::parse(tz)?.offset_seconds(utc_nanos))
5794}
5795
5796pub fn tz_utc_to_wall_nanos(tz: &str, utc_nanos: i64) -> Result<i64, TimeZoneError> {
5799 if utc_nanos == i64::MIN {
5800 return Ok(utc_nanos);
5801 }
5802 let offset = Zone::parse(tz)?.offset_seconds(utc_nanos);
5803 Ok(utc_nanos.saturating_add(i64::from(offset) * 1_000_000_000))
5804}
5805
5806pub fn tz_wall_to_utc_nanos(tz: &str, wall_nanos: i64) -> Result<i64, TimeZoneError> {
5811 tz_wall_to_utc_nanos_with(tz, wall_nanos, AmbiguousTime::Raise, NonexistentTime::Raise)
5812}
5813
5814#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5818pub enum AmbiguousTime {
5819 Raise,
5820 Earliest,
5821 Latest,
5822 NaT,
5823}
5824
5825#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5831pub enum NonexistentTime {
5832 Raise,
5833 ShiftForward,
5834 ShiftBackward,
5835 NaT,
5836 Shift(i64),
5837}
5838
5839pub fn tz_wall_to_utc_nanos_with(
5842 tz: &str,
5843 wall_nanos: i64,
5844 ambiguous: AmbiguousTime,
5845 nonexistent: NonexistentTime,
5846) -> Result<i64, TimeZoneError> {
5847 use chrono::{LocalResult, TimeZone};
5848 if wall_nanos == i64::MIN {
5849 return Ok(wall_nanos);
5850 }
5851 let zone = Zone::parse(tz)?;
5852 let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
5853 let local = match &zone {
5854 Zone::Fixed(offset) => offset
5855 .from_local_datetime(&naive)
5856 .map(|at| at.fixed_offset()),
5857 Zone::Named(zone) => zone.from_local_datetime(&naive).map(|at| at.fixed_offset()),
5858 };
5859 let nanos_of = |at: chrono::DateTime<chrono::FixedOffset>| {
5860 at.timestamp_nanos_opt()
5861 .ok_or_else(|| TimeZoneError::NonExistent(naive.to_string()))
5862 };
5863 match local {
5864 LocalResult::Single(at) => nanos_of(at),
5865 LocalResult::Ambiguous(earliest, latest) => match ambiguous {
5866 AmbiguousTime::Raise => Err(TimeZoneError::Ambiguous(naive.to_string())),
5867 AmbiguousTime::Earliest => nanos_of(earliest),
5868 AmbiguousTime::Latest => nanos_of(latest),
5869 AmbiguousTime::NaT => Ok(i64::MIN),
5870 },
5871 LocalResult::None => match nonexistent {
5872 NonexistentTime::Raise => Err(TimeZoneError::NonExistent(naive.to_string())),
5873 NonexistentTime::NaT => Ok(i64::MIN),
5874 NonexistentTime::Shift(delta) => {
5875 let shifted = wall_nanos
5876 .checked_add(delta)
5877 .ok_or_else(|| TimeZoneError::NonExistent(naive.to_string()))?;
5878 tz_wall_to_utc_nanos_with(tz, shifted, ambiguous, NonexistentTime::Raise)
5879 }
5880 NonexistentTime::ShiftForward | NonexistentTime::ShiftBackward => {
5881 const DAY: i64 = 86_400_000_000_000;
5888 let offset_at = |utc: i64| i64::from(zone.offset_seconds(utc)) * 1_000_000_000;
5889 let before = wall_nanos.saturating_sub(offset_at(wall_nanos.saturating_sub(DAY)));
5890 let after = wall_nanos.saturating_sub(offset_at(wall_nanos.saturating_add(DAY)));
5891 let (mut low, mut high) = (before.min(after), before.max(after));
5892 let later = offset_at(high);
5893 while high - low > 1 {
5894 let middle = low + (high - low) / 2;
5895 if offset_at(middle) == later {
5896 high = middle;
5897 } else {
5898 low = middle;
5899 }
5900 }
5901 Ok(if nonexistent == NonexistentTime::ShiftForward {
5902 high
5903 } else {
5904 high - 1
5905 })
5906 }
5907 },
5908 }
5909}
5910
5911#[must_use]
5921pub fn strftime_python(wall_nanos: i64, format: &str, zone: Option<(i32, &str)>) -> String {
5922 const DAYS: [&str; 7] = [
5923 "Sunday",
5924 "Monday",
5925 "Tuesday",
5926 "Wednesday",
5927 "Thursday",
5928 "Friday",
5929 "Saturday",
5930 ];
5931 const MONTHS: [&str; 12] = [
5932 "January",
5933 "February",
5934 "March",
5935 "April",
5936 "May",
5937 "June",
5938 "July",
5939 "August",
5940 "September",
5941 "October",
5942 "November",
5943 "December",
5944 ];
5945 let total_secs = wall_nanos.div_euclid(1_000_000_000);
5948 let sub_nanos = wall_nanos.rem_euclid(1_000_000_000);
5949 let days = total_secs.div_euclid(86_400);
5950 let secs_of_day = total_secs.rem_euclid(86_400);
5951 let (year, month, day) = civil_from_days(days);
5952 let (hour, minute, second) = (
5953 secs_of_day / 3_600,
5954 (secs_of_day % 3_600) / 60,
5955 secs_of_day % 60,
5956 );
5957 let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
5958 let weekday = (days + 4).rem_euclid(7); let yday = days - days_from_civil(year, 1, 1); let iso_weekday = if weekday == 0 { 7 } else { weekday };
5961 let (iso_year, iso_week) = {
5962 let week = (yday + 1 - iso_weekday + 10).div_euclid(7);
5963 if week < 1 {
5964 (year - 1, iso_weeks_in_year(year - 1))
5965 } else if week > iso_weeks_in_year(year) {
5966 (year + 1, 1)
5967 } else {
5968 (year, week)
5969 }
5970 };
5971 let month_name = MONTHS[(month as usize).saturating_sub(1) % 12];
5972 let day_name = DAYS[weekday as usize];
5973
5974 let mut out = String::with_capacity(format.len().saturating_add(16));
5975 let mut chars = format.chars().peekable();
5976 while let Some(ch) = chars.next() {
5977 if ch != '%' {
5978 out.push(ch);
5979 continue;
5980 }
5981 let flag = chars.next_if(|c| matches!(c, '-' | '_' | '0' | '^'));
5982 let Some(conversion) = chars.next() else {
5983 out.push('%');
5984 if let Some(flag) = flag {
5985 out.push(flag);
5986 }
5987 break;
5988 };
5989 let number = |value: i64, width: usize, pad: char| -> String {
5992 match flag.unwrap_or(pad) {
5993 '-' => value.to_string(),
5994 '_' | ' ' => format!("{value:>width$}"),
5995 _ => format!("{value:0width$}"),
5996 }
5997 };
5998 let text = |value: &str| -> String {
5999 if flag == Some('^') {
6000 value.to_uppercase()
6001 } else {
6002 value.to_owned()
6003 }
6004 };
6005 let piece = match conversion {
6006 'a' => text(&day_name[..3]),
6007 'A' => text(day_name),
6008 'b' | 'h' => text(&month_name[..3]),
6009 'B' => text(month_name),
6010 'c' => text(&strftime_python(wall_nanos, "%a %b %e %H:%M:%S %Y", zone)),
6011 'C' => number(year.div_euclid(100), 2, '0'),
6012 'd' => number(i64::from(day), 2, '0'),
6013 'D' | 'x' => strftime_python(wall_nanos, "%m/%d/%y", zone),
6014 'e' => number(i64::from(day), 2, ' '),
6015 'f' => number(sub_nanos / 1_000, 6, '0'),
6016 'F' => strftime_python(wall_nanos, "%Y-%m-%d", zone),
6017 'g' => number(iso_year.rem_euclid(100), 2, '0'),
6018 'G' => number(iso_year, 1, '0'),
6019 'H' => number(hour, 2, '0'),
6020 'I' => number(hour12, 2, '0'),
6021 'j' => number(yday + 1, 3, '0'),
6022 'k' => number(hour, 2, ' '),
6023 'l' => number(hour12, 2, ' '),
6024 'm' => number(i64::from(month), 2, '0'),
6025 'M' => number(minute, 2, '0'),
6026 'n' => "\n".to_owned(),
6027 'p' => text(if hour < 12 { "AM" } else { "PM" }),
6028 'P' => (if hour < 12 { "am" } else { "pm" }).to_owned(),
6029 'r' => strftime_python(wall_nanos, "%I:%M:%S %p", zone),
6030 'R' => strftime_python(wall_nanos, "%H:%M", zone),
6031 'S' => number(second, 2, '0'),
6032 't' => "\t".to_owned(),
6033 'T' | 'X' => strftime_python(wall_nanos, "%H:%M:%S", zone),
6034 'u' => number(iso_weekday, 1, '0'),
6035 'U' => number((yday + 7 - weekday).div_euclid(7), 2, '0'),
6036 'V' => number(iso_week, 2, '0'),
6037 'w' => number(weekday, 1, '0'),
6038 'W' => number(
6039 (yday + 7 - (weekday + 6).rem_euclid(7)).div_euclid(7),
6040 2,
6041 '0',
6042 ),
6043 'y' => number(year.rem_euclid(100), 2, '0'),
6044 'Y' => number(year, 1, '0'),
6045 'z' => zone.map_or_else(String::new, |(offset, _)| {
6046 let sign = if offset < 0 { '-' } else { '+' };
6047 let offset = offset.unsigned_abs();
6048 let (h, m, s) = (offset / 3_600, (offset % 3_600) / 60, offset % 60);
6049 if s == 0 {
6050 format!("{sign}{h:02}{m:02}")
6051 } else {
6052 format!("{sign}{h:02}{m:02}{s:02}")
6053 }
6054 }),
6055 'Z' => zone.map_or_else(String::new, |(_, name)| text(name)),
6056 '%' => "%".to_owned(),
6057 other => {
6058 out.push('%');
6060 if let Some(flag) = flag {
6061 out.push(flag);
6062 }
6063 out.push(other);
6064 continue;
6065 }
6066 };
6067 out.push_str(&piece);
6068 }
6069 out
6070}
6071
6072#[must_use]
6076pub fn strftime_in_zone(nanos: i64, format: &str, tz: Option<&str>) -> String {
6077 let aware = tz.and_then(|zone| {
6078 let offset = tz_offset_seconds(zone, nanos).ok()?;
6079 let name = tz_abbreviation(zone, nanos).ok()?;
6080 Some((offset, name))
6081 });
6082 match aware {
6083 Some((offset, name)) => strftime_python(
6084 nanos.saturating_add(i64::from(offset) * 1_000_000_000),
6085 format,
6086 Some((offset, &name)),
6087 ),
6088 None => strftime_python(nanos, format, None),
6089 }
6090}
6091
6092#[must_use]
6097pub fn timestamp_text_in_zone(nanos: i64, tz: &str) -> String {
6098 let offset = tz_offset_seconds(tz, nanos).unwrap_or(0);
6099 let wall = nanos.saturating_add(i64::from(offset) * 1_000_000_000);
6100 let mut text = strftime_python(wall, "%Y-%m-%d %H:%M:%S", None);
6101 let fraction = wall.rem_euclid(1_000_000_000);
6102 if fraction % 1_000 != 0 {
6103 text.push_str(&format!(".{fraction:09}"));
6104 } else if fraction != 0 {
6105 text.push_str(&format!(".{:06}", fraction / 1_000));
6106 }
6107 let sign = if offset < 0 { '-' } else { '+' };
6108 let minutes = offset.unsigned_abs() / 60;
6109 text.push_str(&format!("{sign}{:02}:{:02}", minutes / 60, minutes % 60));
6110 text
6111}
6112
6113fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
6117 let (month, day) = (i64::from(month), i64::from(day));
6118 let year = if month <= 2 { year - 1 } else { year };
6119 let era = if year >= 0 { year } else { year - 399 } / 400;
6120 let yoe = year - era * 400;
6121 let doy = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
6122 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
6123 era * 146_097 + doe - 719_468
6124}
6125
6126fn days_in_month(year: i64, month: u32) -> Option<u32> {
6135 if !(1..=12).contains(&month) {
6136 return None;
6137 }
6138 let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
6139 let days: [u32; 12] = [
6140 31,
6141 if is_leap { 29 } else { 28 },
6142 31,
6143 30,
6144 31,
6145 30,
6146 31,
6147 31,
6148 30,
6149 31,
6150 30,
6151 31,
6152 ];
6153 Some(days[(month - 1) as usize])
6154}
6155
6156fn iso_weeks_in_year(year: i64) -> i64 {
6163 fn p(y: i64) -> i64 {
6164 (y + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400)).rem_euclid(7)
6165 }
6166 if p(year) == 4 || p(year - 1) == 3 {
6167 53
6168 } else {
6169 52
6170 }
6171}
6172
6173#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
6179pub struct Timestamp {
6180 pub nanos: i64,
6182 #[serde(default, skip_serializing_if = "Option::is_none")]
6186 pub tz: Option<String>,
6187}
6188
6189#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6210pub enum TimedeltaStringResolution {
6211 Days,
6213 Full,
6215}
6216
6217#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6237pub enum DatetimeStringResolution {
6238 Date,
6240 Second,
6242 Milli,
6244 Micro,
6246 Nano,
6248}
6249
6250impl Timestamp {
6251 pub const NAT: i64 = i64::MIN;
6253
6254 #[must_use]
6257 pub const fn from_nanos(nanos: i64) -> Self {
6258 Self { nanos, tz: None }
6259 }
6260
6261 #[must_use]
6266 pub fn from_nanos_tz(nanos: i64, tz_name: impl Into<String>) -> Self {
6267 Self {
6268 nanos,
6269 tz: Some(tz_name.into()),
6270 }
6271 }
6272
6273 #[must_use]
6289 pub fn now() -> Self {
6290 use std::time::{SystemTime, UNIX_EPOCH};
6291 let duration = SystemTime::now()
6292 .duration_since(UNIX_EPOCH)
6293 .unwrap_or_default();
6294 let nanos = duration.as_nanos() as i64;
6295 Self { nanos, tz: None }
6296 }
6297
6298 #[must_use]
6300 pub fn utcnow() -> Self {
6301 Self::now()
6302 }
6303
6304 #[must_use]
6308 pub fn today() -> Self {
6309 let now = Self::now();
6310 now.normalize()
6311 }
6312
6313 #[must_use]
6315 pub const fn nat() -> Self {
6316 Self {
6317 nanos: Self::NAT,
6318 tz: None,
6319 }
6320 }
6321
6322 #[must_use]
6324 pub const fn is_nat(&self) -> bool {
6325 self.nanos == Self::NAT
6326 }
6327
6328 #[must_use]
6330 pub const fn value(&self) -> i64 {
6331 self.nanos
6332 }
6333
6334 #[must_use]
6339 pub const fn unit(&self) -> Option<&'static str> {
6340 if self.is_nat() { None } else { Some("ns") }
6341 }
6342
6343 #[must_use]
6347 pub const fn resolution(&self) -> Option<&'static str> {
6348 if self.is_nat() { None } else { Some("ns") }
6349 }
6350
6351 #[must_use]
6353 pub const fn asm8(&self) -> i64 {
6354 self.value()
6355 }
6356
6357 #[must_use]
6359 pub const fn to_datetime64(&self) -> i64 {
6360 self.value()
6361 }
6362
6363 #[must_use]
6365 pub const fn to_numpy(&self) -> i64 {
6366 self.value()
6367 }
6368
6369 pub fn timestamp(&self) -> Result<f64, TypeError> {
6375 if self.is_nat() {
6376 return Err(TypeError::ValueIsMissing {
6377 kind: NullKind::NaT,
6378 });
6379 }
6380 let seconds = self.nanos as f64 / 1_000_000_000.0;
6381 let rounded = format!("{seconds:.6}").parse().unwrap_or(seconds);
6382 Ok(rounded)
6383 }
6384
6385 #[must_use]
6393 pub fn add_timedelta(&self, td_nanos: i64) -> Self {
6394 self.try_add_timedelta(td_nanos)
6395 .unwrap_or_else(|_| Self::nat())
6396 }
6397
6398 pub fn try_add_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6409 if self.is_nat() || td_nanos == Timedelta::NAT {
6410 return Ok(Self::nat());
6411 }
6412 match self.nanos.checked_add(td_nanos) {
6413 Some(nanos) => Ok(Self {
6414 nanos,
6415 tz: self.tz.clone(),
6416 }),
6417 None => Err(TemporalFailure::new(
6421 "Timestamp::add_timedelta",
6422 PandasTemporalError::OutOfBoundsDatetime,
6423 )
6424 .with_operands(self.nanos, td_nanos)),
6425 }
6426 }
6427
6428 #[must_use]
6430 pub fn sub_timedelta(&self, td_nanos: i64) -> Self {
6431 self.try_sub_timedelta(td_nanos)
6432 .unwrap_or_else(|_| Self::nat())
6433 }
6434
6435 pub fn try_sub_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6441 if self.is_nat() || td_nanos == Timedelta::NAT {
6442 return Ok(Self::nat());
6443 }
6444 match self.nanos.checked_sub(td_nanos) {
6445 Some(nanos) => Ok(Self {
6446 nanos,
6447 tz: self.tz.clone(),
6448 }),
6449 None => Err(TemporalFailure::new(
6450 "Timestamp::sub_timedelta",
6451 PandasTemporalError::OutOfBoundsDatetime,
6452 )
6453 .with_operands(self.nanos, td_nanos)),
6454 }
6455 }
6456
6457 #[must_use]
6461 pub fn sub_timestamp(&self, other: &Self) -> i64 {
6462 self.try_sub_timestamp(other).unwrap_or(Timedelta::NAT)
6463 }
6464
6465 pub fn try_sub_timestamp(&self, other: &Self) -> Result<i64, TemporalFailure> {
6471 if self.is_nat() || other.is_nat() {
6472 return Ok(Timedelta::NAT);
6473 }
6474 self.nanos.checked_sub(other.nanos).ok_or(
6475 TemporalFailure::new(
6476 "Timestamp::sub_timestamp",
6477 PandasTemporalError::OutOfBoundsDatetime,
6478 )
6479 .with_operands(self.nanos, other.nanos),
6480 )
6481 }
6482
6483 #[must_use]
6488 pub fn semantic_eq(&self, other: &Self) -> bool {
6489 if self.is_nat() && other.is_nat() {
6490 return true;
6491 }
6492 if self.is_nat() || other.is_nat() {
6493 return false;
6494 }
6495 self.nanos == other.nanos && self.tz == other.tz
6496 }
6497
6498 #[must_use]
6511 pub fn floor_to(&self, unit_nanos: i64) -> Self {
6512 if self.is_nat() || unit_nanos <= 0 {
6513 return Self::nat();
6514 }
6515 let Some(nanos) = self.nanos.div_euclid(unit_nanos).checked_mul(unit_nanos) else {
6516 return Self::nat();
6517 };
6518 Self {
6519 nanos,
6520 tz: self.tz.clone(),
6521 }
6522 }
6523
6524 #[must_use]
6529 pub fn ceil_to(&self, unit_nanos: i64) -> Self {
6530 if self.is_nat() || unit_nanos <= 0 {
6531 return Self::nat();
6532 }
6533 let rem = self.nanos.rem_euclid(unit_nanos);
6534 let nanos = if rem == 0 {
6535 self.nanos
6536 } else {
6537 let Some(nanos) = self.nanos.checked_add(unit_nanos - rem) else {
6542 return Self::nat();
6543 };
6544 nanos
6545 };
6546 Self {
6547 nanos,
6548 tz: self.tz.clone(),
6549 }
6550 }
6551
6552 #[must_use]
6558 pub fn round_to(&self, unit_nanos: i64) -> Self {
6559 if self.is_nat() || unit_nanos <= 0 {
6560 return Self::nat();
6561 }
6562 let floor = self.nanos.div_euclid(unit_nanos);
6563 let rem = self.nanos.rem_euclid(unit_nanos);
6564 let half = unit_nanos / 2;
6565 let chosen_floor = if rem < half {
6566 floor
6567 } else if rem > half {
6568 floor + 1
6569 } else if unit_nanos % 2 != 0 {
6570 floor + 1
6572 } else {
6573 if floor % 2 == 0 { floor } else { floor + 1 }
6575 };
6576 let Some(nanos) = chosen_floor.checked_mul(unit_nanos) else {
6580 return Self::nat();
6581 };
6582 Self {
6583 nanos,
6584 tz: self.tz.clone(),
6585 }
6586 }
6587
6588 fn fixed_freq_nanos(freq: &str) -> Option<i64> {
6600 Timedelta::unit_to_nanos(freq).or_else(|| Timedelta::parse(freq).ok())
6601 }
6602
6603 #[must_use]
6607 pub fn floor_to_unit(&self, unit: &str) -> Self {
6608 match Self::fixed_freq_nanos(unit) {
6609 Some(unit_nanos) => self.floor_to(unit_nanos),
6610 None => Self::nat(),
6611 }
6612 }
6613
6614 #[must_use]
6618 pub fn ceil_to_unit(&self, unit: &str) -> Self {
6619 match Self::fixed_freq_nanos(unit) {
6620 Some(unit_nanos) => self.ceil_to(unit_nanos),
6621 None => Self::nat(),
6622 }
6623 }
6624
6625 #[must_use]
6629 pub fn round_to_unit(&self, unit: &str) -> Self {
6630 match Self::fixed_freq_nanos(unit) {
6631 Some(unit_nanos) => self.round_to(unit_nanos),
6632 None => Self::nat(),
6633 }
6634 }
6635
6636 #[must_use]
6638 pub fn floor(&self, freq: &str) -> Self {
6639 self.floor_to_unit(freq)
6640 }
6641
6642 #[must_use]
6644 pub fn ceil(&self, freq: &str) -> Self {
6645 self.ceil_to_unit(freq)
6646 }
6647
6648 #[must_use]
6650 pub fn round(&self, freq: &str) -> Self {
6651 self.round_to_unit(freq)
6652 }
6653
6654 #[must_use]
6658 pub fn year(&self) -> Option<i64> {
6659 if self.is_nat() {
6660 return None;
6661 }
6662 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6666 let days = days_since_epoch + 719_468;
6667 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6668 let doe = days - era * 146_097;
6669 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6670 let y = yoe + era * 400;
6671 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6672 let mp = (5 * doy + 2) / 153;
6673 let m = if mp < 10 { mp + 3 } else { mp - 9 };
6674 Some(if m <= 2 { y + 1 } else { y })
6675 }
6676
6677 #[must_use]
6681 pub fn month(&self) -> Option<i64> {
6682 if self.is_nat() {
6683 return None;
6684 }
6685 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6689 let days = days_since_epoch + 719_468;
6690 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6691 let doe = days - era * 146_097;
6692 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6693 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6694 let mp = (5 * doy + 2) / 153;
6695 Some(if mp < 10 { mp + 3 } else { mp - 9 })
6696 }
6697
6698 #[must_use]
6702 pub fn day(&self) -> Option<i64> {
6703 if self.is_nat() {
6704 return None;
6705 }
6706 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6710 let days = days_since_epoch + 719_468;
6711 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6712 let doe = days - era * 146_097;
6713 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6714 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6715 let mp = (5 * doy + 2) / 153;
6716 Some(doy - (153 * mp + 2) / 5 + 1)
6717 }
6718
6719 #[must_use]
6723 pub fn hour(&self) -> Option<i64> {
6724 if self.is_nat() {
6725 return None;
6726 }
6727 let secs_of_day =
6731 self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6732 Some(secs_of_day / 3600)
6733 }
6734
6735 #[must_use]
6739 pub fn minute(&self) -> Option<i64> {
6740 if self.is_nat() {
6741 return None;
6742 }
6743 let secs_of_day =
6747 self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6748 Some((secs_of_day % 3600) / 60)
6749 }
6750
6751 #[must_use]
6755 pub fn second(&self) -> Option<i64> {
6756 if self.is_nat() {
6757 return None;
6758 }
6759 let secs_of_day =
6763 self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6764 Some(secs_of_day % 60)
6765 }
6766
6767 #[must_use]
6771 pub fn microsecond(&self) -> Option<i64> {
6772 if self.is_nat() {
6773 return None;
6774 }
6775 let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
6778 Some((sub_nanos / 1000) as i64)
6779 }
6780
6781 #[must_use]
6785 pub fn nanosecond(&self) -> Option<i64> {
6786 if self.is_nat() {
6787 return None;
6788 }
6789 let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
6792 Some((sub_nanos % 1000) as i64)
6793 }
6794
6795 #[must_use]
6799 pub fn dayofweek(&self) -> Option<i64> {
6800 if self.is_nat() {
6801 return None;
6802 }
6803 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6805 let dow = ((days_since_epoch + 3) % 7 + 7) % 7;
6806 Some(dow)
6807 }
6808
6809 #[must_use]
6811 pub fn weekday(&self) -> Option<i64> {
6812 self.dayofweek()
6813 }
6814
6815 #[must_use]
6817 pub fn day_of_week(&self) -> Option<i64> {
6818 self.dayofweek()
6819 }
6820
6821 #[must_use]
6825 pub fn dayofyear(&self) -> Option<i64> {
6826 if self.is_nat() {
6827 return None;
6828 }
6829 let m = self.month()?;
6830 let d = self.day()?;
6831 let y = self.year()?;
6832 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
6833 let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
6834 let base = days_before[(m - 1) as usize] + d;
6835 if is_leap && m > 2 {
6836 Some(base + 1)
6837 } else {
6838 Some(base)
6839 }
6840 }
6841
6842 #[must_use]
6844 pub fn day_of_year(&self) -> Option<i64> {
6845 self.dayofyear()
6846 }
6847
6848 #[must_use]
6852 pub fn toordinal(&self) -> Option<i64> {
6853 if self.is_nat() {
6854 return None;
6855 }
6856 let y = self.year()?;
6857 let m = self.month()?;
6858 let d = self.day()?;
6859 let y_minus_1 = y - 1;
6863 let mut ordinal = y_minus_1 * 365 + y_minus_1 / 4 - y_minus_1 / 100 + y_minus_1 / 400;
6864 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
6865 let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
6866 ordinal += days_before[(m - 1) as usize];
6867 if is_leap && m > 2 {
6868 ordinal += 1;
6869 }
6870 ordinal += d;
6871 Some(ordinal)
6872 }
6873
6874 #[must_use]
6878 pub fn fromordinal(ordinal: i64) -> Self {
6879 if ordinal <= 0 {
6880 return Self {
6881 nanos: Self::NAT,
6882 tz: None,
6883 };
6884 }
6885 let days_since_epoch = ordinal - 719163;
6888 match days_since_epoch.checked_mul(Timedelta::NANOS_PER_DAY) {
6889 Some(nanos) => Self { nanos, tz: None },
6890 None => Self::nat(),
6891 }
6892 }
6893
6894 #[must_use]
6900 pub fn to_julian_date(&self) -> f64 {
6901 if self.is_nat() {
6902 return f64::NAN;
6903 }
6904 let ordinal = match self.toordinal() {
6908 Some(o) => o,
6909 None => return f64::NAN,
6910 };
6911 let h = self.hour().unwrap_or(0) as f64;
6913 let m = self.minute().unwrap_or(0) as f64;
6914 let s = self.second().unwrap_or(0) as f64;
6915 let us = self.microsecond().unwrap_or(0) as f64;
6916 let ns = self.nanosecond().unwrap_or(0) as f64;
6917 let frac_day =
6918 (h + m / 60.0 + s / 3600.0 + us / 3_600_000_000.0 + ns / 3_600_000_000_000.0) / 24.0;
6919 1721424.5 + ordinal as f64 + frac_day
6921 }
6922
6923 #[must_use]
6927 pub fn quarter(&self) -> Option<i64> {
6928 self.month().map(|m| (m - 1) / 3 + 1)
6929 }
6930
6931 #[must_use]
6935 pub fn weekofyear(&self) -> Option<i64> {
6936 if self.is_nat() {
6937 return None;
6938 }
6939 let doy = self.dayofyear()?;
6940 let dow = self.dayofweek()?;
6941 let year = self.year()?;
6942 let iso_dow = if dow == 6 { 7 } else { dow + 1 };
6943 let week = (doy - iso_dow + 10) / 7;
6944 if week < 1 {
6950 Some(iso_weeks_in_year(year - 1))
6951 } else if week > iso_weeks_in_year(year) {
6952 Some(1)
6953 } else {
6954 Some(week)
6955 }
6956 }
6957
6958 #[must_use]
6960 pub fn week(&self) -> Option<i64> {
6961 self.weekofyear()
6962 }
6963
6964 #[must_use]
6969 pub fn to_unit(&self, unit: &str) -> Option<i64> {
6970 if self.is_nat() {
6971 return None;
6972 }
6973 match unit {
6974 "ns" | "nanosecond" | "nanoseconds" => Some(self.nanos),
6975 "us" | "microsecond" | "microseconds" => Some(self.nanos / 1_000),
6976 "ms" | "millisecond" | "milliseconds" => Some(self.nanos / 1_000_000),
6977 "s" | "second" | "seconds" => Some(self.nanos / 1_000_000_000),
6978 _ => None,
6979 }
6980 }
6981
6982 #[must_use]
6986 pub fn is_leap_year(&self) -> Option<bool> {
6987 self.year()
6988 .map(|y| (y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
6989 }
6990
6991 #[must_use]
6995 pub fn is_month_start(&self) -> Option<bool> {
6996 self.day().map(|d| d == 1)
6997 }
6998
6999 #[must_use]
7003 pub fn is_month_end(&self) -> Option<bool> {
7004 let y = self.year()?;
7005 let m = self.month()?;
7006 let d = self.day()?;
7007 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7008 let days_in_month: [i64; 12] = [
7009 31,
7010 if is_leap { 29 } else { 28 },
7011 31,
7012 30,
7013 31,
7014 30,
7015 31,
7016 31,
7017 30,
7018 31,
7019 30,
7020 31,
7021 ];
7022 Some(d == days_in_month[(m - 1) as usize])
7023 }
7024
7025 #[must_use]
7029 pub fn is_quarter_start(&self) -> Option<bool> {
7030 let m = self.month()?;
7031 let d = self.day()?;
7032 Some(d == 1 && (m == 1 || m == 4 || m == 7 || m == 10))
7033 }
7034
7035 #[must_use]
7039 pub fn is_quarter_end(&self) -> Option<bool> {
7040 let m = self.month()?;
7041 let d = self.day()?;
7042 Some(
7043 (m == 3 && d == 31)
7044 || (m == 6 && d == 30)
7045 || (m == 9 && d == 30)
7046 || (m == 12 && d == 31),
7047 )
7048 }
7049
7050 #[must_use]
7054 pub fn is_year_start(&self) -> Option<bool> {
7055 let m = self.month()?;
7056 let d = self.day()?;
7057 Some(m == 1 && d == 1)
7058 }
7059
7060 #[must_use]
7064 pub fn is_year_end(&self) -> Option<bool> {
7065 let m = self.month()?;
7066 let d = self.day()?;
7067 Some(m == 12 && d == 31)
7068 }
7069
7070 #[must_use]
7074 pub fn days_in_month(&self) -> Option<i64> {
7075 let y = self.year()?;
7076 let m = self.month()?;
7077 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7078 let days: [i64; 12] = [
7079 31,
7080 if is_leap { 29 } else { 28 },
7081 31,
7082 30,
7083 31,
7084 30,
7085 31,
7086 31,
7087 30,
7088 31,
7089 30,
7090 31,
7091 ];
7092 Some(days[(m - 1) as usize])
7093 }
7094
7095 #[must_use]
7097 pub fn daysinmonth(&self) -> Option<i64> {
7098 self.days_in_month()
7099 }
7100
7101 #[must_use]
7103 pub fn normalize(&self) -> Self {
7104 self.floor_to(Timedelta::NANOS_PER_DAY)
7105 }
7106
7107 #[must_use]
7111 #[allow(clippy::too_many_arguments)]
7112 pub fn replace(
7113 &self,
7114 year: Option<i64>,
7115 month: Option<i64>,
7116 day: Option<i64>,
7117 hour: Option<i64>,
7118 minute: Option<i64>,
7119 second: Option<i64>,
7120 microsecond: Option<i64>,
7121 nanosecond: Option<i64>,
7122 ) -> Self {
7123 if self.is_nat() {
7124 return self.clone();
7125 }
7126 let cur_year = self.year().unwrap_or(1970);
7127 let cur_month = self.month().unwrap_or(1);
7128 let cur_day = self.day().unwrap_or(1);
7129 let cur_hour = self.hour().unwrap_or(0);
7130 let cur_minute = self.minute().unwrap_or(0);
7131 let cur_second = self.second().unwrap_or(0);
7132 let cur_micro = self.microsecond().unwrap_or(0);
7133 let cur_nano = self.nanosecond().unwrap_or(0);
7134
7135 let y = year.unwrap_or(cur_year);
7136 let mo = month.unwrap_or(cur_month);
7137 let d = day.unwrap_or(cur_day);
7138 let h = hour.unwrap_or(cur_hour);
7139 let mi = minute.unwrap_or(cur_minute);
7140 let s = second.unwrap_or(cur_second);
7141 let us = microsecond.unwrap_or(cur_micro);
7142 let ns = nanosecond.unwrap_or(cur_nano);
7143
7144 if !(1..=12).contains(&mo)
7145 || !(1..=days_in_month(y, mo as u32).unwrap_or(0) as i64).contains(&d)
7146 || !(0..=23).contains(&h)
7147 || !(0..=59).contains(&mi)
7148 || !(0..=59).contains(&s)
7149 || !(0..=999_999).contains(&us)
7150 || !(0..=999).contains(&ns)
7151 {
7152 return Self::nat();
7153 }
7154
7155 let days_from_epoch = Self::days_from_ymd(y, mo, d);
7167 let secs = h * 3600 + mi * 60 + s;
7168 let Some(total_nanos) = days_from_epoch
7169 .checked_mul(Timedelta::NANOS_PER_DAY)
7170 .and_then(|nanos| {
7171 secs.checked_mul(Timedelta::NANOS_PER_SEC)
7172 .and_then(|s_nanos| nanos.checked_add(s_nanos))
7173 })
7174 .and_then(|nanos| {
7175 us.checked_mul(Timedelta::NANOS_PER_MICRO)
7176 .and_then(|us_nanos| nanos.checked_add(us_nanos))
7177 })
7178 .and_then(|nanos| nanos.checked_add(ns))
7179 else {
7180 return Self::nat();
7181 };
7182
7183 Self {
7184 nanos: total_nanos,
7185 tz: self.tz.clone(),
7186 }
7187 }
7188
7189 fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
7190 let y = if month <= 2 { year - 1 } else { year };
7191 let era = if y >= 0 { y } else { y - 399 } / 400;
7192 let yoe = y - era * 400;
7193 let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
7194 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
7195 era * 146097 + doe - 719468
7196 }
7197
7198 #[must_use]
7202 pub fn isoformat(&self) -> String {
7203 use std::fmt::Write as _;
7204
7205 if self.is_nat() {
7206 return "NaT".to_string();
7207 }
7208 let display_nanos = self
7209 .tz
7210 .as_deref()
7211 .and_then(Self::fixed_utc_offset_seconds)
7212 .and_then(|offset| self.nanos.checked_add(offset * Timedelta::NANOS_PER_SEC))
7213 .unwrap_or(self.nanos);
7214 let days_since_epoch = display_nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7217 let nanos_of_day = display_nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7218 let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7219 let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7220
7221 let days = days_since_epoch + 719_468;
7222 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7223 let doe = days - era * 146_097;
7224 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7225 let y = yoe + era * 400;
7226 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7227 let mp = (5 * doy + 2) / 153;
7228 let d = doy - (153 * mp + 2) / 5 + 1;
7229 let m = if mp < 10 { mp + 3 } else { mp - 9 };
7230 let year = if m <= 2 { y + 1 } else { y };
7231
7232 let hour = secs_of_day / 3600;
7233 let minute = (secs_of_day % 3600) / 60;
7234 let second = secs_of_day % 60;
7235
7236 let suffix_capacity = self
7240 .tz
7241 .as_ref()
7242 .map_or(0, |tz| if tz == "UTC" { 6 } else { tz.len() + 2 });
7243 let mut result = String::with_capacity(29 + suffix_capacity);
7244 if sub_nanos == 0 {
7245 let _ = write!(
7246 result,
7247 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}"
7248 );
7249 } else if sub_nanos.is_multiple_of(1_000) {
7250 let _ = write!(
7251 result,
7252 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{:06}",
7253 sub_nanos / 1_000
7254 );
7255 } else {
7256 let _ = write!(
7257 result,
7258 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{sub_nanos:09}"
7259 );
7260 }
7261 match &self.tz {
7262 Some(tz) if tz == "UTC" => result.push_str("+00:00"),
7263 Some(tz) if Self::fixed_utc_offset_seconds(tz).is_some() => {
7264 result.push_str(tz.strip_prefix("UTC").unwrap_or(tz));
7265 }
7266 Some(tz) => {
7267 result.push('[');
7268 result.push_str(tz);
7269 result.push(']');
7270 }
7271 None => {}
7272 }
7273 result
7274 }
7275
7276 #[must_use]
7278 pub fn to_iso8601(&self) -> String {
7279 self.isoformat()
7280 }
7281
7282 #[must_use]
7291 pub const fn string_resolution(nanos: i64) -> DatetimeStringResolution {
7292 if nanos == Self::NAT {
7293 return DatetimeStringResolution::Date;
7294 }
7295 if nanos.rem_euclid(Timedelta::NANOS_PER_DAY) == 0 {
7296 DatetimeStringResolution::Date
7297 } else if nanos.rem_euclid(Timedelta::NANOS_PER_SEC) == 0 {
7298 DatetimeStringResolution::Second
7299 } else if nanos.rem_euclid(Timedelta::NANOS_PER_MILLI) == 0 {
7300 DatetimeStringResolution::Milli
7301 } else if nanos.rem_euclid(Timedelta::NANOS_PER_MICRO) == 0 {
7302 DatetimeStringResolution::Micro
7303 } else {
7304 DatetimeStringResolution::Nano
7305 }
7306 }
7307
7308 #[must_use]
7328 pub fn format_at_resolution(nanos: i64, resolution: DatetimeStringResolution) -> String {
7329 use std::fmt::Write as _;
7330
7331 if nanos == Self::NAT {
7332 return "NaT".to_string();
7333 }
7334 let days_since_epoch = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7339 let nanos_of_day = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7340 let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7341 let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC);
7342 let (year, month, day) = civil_from_days(days_since_epoch);
7345
7346 let mut result = String::with_capacity(30);
7349 let _ = write!(result, "{year:04}-{month:02}-{day:02}");
7351 if matches!(resolution, DatetimeStringResolution::Date) {
7352 return result;
7353 }
7354 let _ = write!(
7355 result,
7356 " {:02}:{:02}:{:02}",
7357 secs_of_day / 3600,
7358 (secs_of_day % 3600) / 60,
7359 secs_of_day % 60
7360 );
7361 let (fraction, width) = match resolution {
7362 DatetimeStringResolution::Date | DatetimeStringResolution::Second => return result,
7363 DatetimeStringResolution::Milli => (sub_nanos / Timedelta::NANOS_PER_MILLI, 3_usize),
7364 DatetimeStringResolution::Micro => (sub_nanos / Timedelta::NANOS_PER_MICRO, 6_usize),
7365 DatetimeStringResolution::Nano => (sub_nanos, 9_usize),
7366 };
7367 let _ = write!(result, ".{fraction:0width$}", width = width);
7368 result
7369 }
7370
7371 pub fn parse(s: &str) -> Result<Self, TypeError> {
7384 let s = s.trim();
7385
7386 if s.eq_ignore_ascii_case("nat") {
7387 return Ok(Self::nat());
7388 }
7389
7390 let Some((datetime_part, tz)) = Self::split_timezone(s) else {
7391 return Err(TypeError::ValueNotParseable {
7392 value: s.to_string(),
7393 target: "Timestamp".to_string(),
7394 });
7395 };
7396
7397 let (date_part, time_part) = if datetime_part.contains('T') {
7398 datetime_part
7399 .split_once('T')
7400 .ok_or_else(|| TypeError::ValueNotParseable {
7401 value: s.to_string(),
7402 target: "Timestamp".to_string(),
7403 })?
7404 } else if datetime_part.contains(' ')
7405 && datetime_part.chars().filter(|&c| c == ' ').count() == 1
7406 {
7407 datetime_part
7408 .split_once(' ')
7409 .ok_or_else(|| TypeError::ValueNotParseable {
7410 value: s.to_string(),
7411 target: "Timestamp".to_string(),
7412 })?
7413 } else {
7414 (datetime_part, "00:00:00")
7415 };
7416
7417 let (year, month, day) =
7418 Self::parse_date(date_part).ok_or_else(|| TypeError::ValueNotParseable {
7419 value: s.to_string(),
7420 target: "Timestamp".to_string(),
7421 })?;
7422
7423 let (hour, minute, second, nanos) =
7424 Self::parse_time(time_part).ok_or_else(|| TypeError::ValueNotParseable {
7425 value: s.to_string(),
7426 target: "Timestamp".to_string(),
7427 })?;
7428
7429 let wall_nanos = Self::ymd_hms_to_nanos(year, month, day, hour, minute, second, nanos)
7432 .ok_or_else(|| TypeError::ValueNotParseable {
7433 value: s.to_string(),
7434 target: "Timestamp".to_string(),
7435 })?;
7436 let offset = tz
7440 .as_deref()
7441 .and_then(Self::fixed_utc_offset_seconds)
7442 .unwrap_or(0);
7443 let total_nanos = offset
7444 .checked_mul(1_000_000_000)
7445 .and_then(|offset| wall_nanos.checked_sub(offset))
7446 .ok_or_else(|| TypeError::ValueNotParseable {
7447 value: s.to_string(),
7448 target: "Timestamp".to_string(),
7449 })?;
7450
7451 Ok(if let Some(tz_name) = tz {
7452 Self::from_nanos_tz(total_nanos, tz_name)
7453 } else {
7454 Self::from_nanos(total_nanos)
7455 })
7456 }
7457
7458 fn split_timezone(s: &str) -> Option<(&str, Option<String>)> {
7459 if let Some(stripped) = s.strip_suffix('Z') {
7460 Some((stripped, Some("UTC".to_string())))
7461 } else if let Some(idx) = s.rfind('+') {
7462 if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7463 Some((&s[..idx], Some(s[idx..].to_string())))
7464 } else if idx > 10 {
7465 None
7466 } else {
7467 Some((s, None))
7468 }
7469 } else if let Some(idx) = s.rfind('-') {
7470 if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7471 Some((&s[..idx], Some(s[idx..].to_string())))
7472 } else if idx > 10 {
7473 None
7474 } else {
7475 Some((s, None))
7476 }
7477 } else {
7478 Some((s, None))
7479 }
7480 }
7481
7482 fn fixed_utc_offset_seconds(tz: &str) -> Option<i64> {
7483 if tz == "UTC" {
7484 return Some(0);
7485 }
7486 let offset = tz.strip_prefix("UTC").unwrap_or(tz);
7487 if !Self::is_timezone_offset(offset) {
7488 return None;
7489 }
7490 let sign = if offset.starts_with('+') { 1 } else { -1 };
7491 let hours = offset[1..3].parse::<i64>().ok()?;
7492 let minutes = offset[4..6].parse::<i64>().ok()?;
7493 Some(sign * (hours * 3_600 + minutes * 60))
7494 }
7495
7496 fn is_timezone_offset(s: &str) -> bool {
7497 let bytes = s.as_bytes();
7498 if bytes.len() != 6 || !matches!(bytes[0], b'+' | b'-') || bytes[3] != b':' {
7499 return false;
7500 }
7501 if !bytes[1..3].iter().all(u8::is_ascii_digit)
7502 || !bytes[4..6].iter().all(u8::is_ascii_digit)
7503 {
7504 return false;
7505 }
7506 let hour = u32::from(bytes[1] - b'0') * 10 + u32::from(bytes[2] - b'0');
7507 let minute = u32::from(bytes[4] - b'0') * 10 + u32::from(bytes[5] - b'0');
7508 hour <= 23 && minute <= 59
7509 }
7510
7511 fn parse_date(s: &str) -> Option<(i64, u32, u32)> {
7512 let parts: Vec<&str> = s.split('-').collect();
7513 if parts.len() != 3 {
7514 return None;
7515 }
7516 let year: i64 = parts[0].parse().ok()?;
7517 let month: u32 = parts[1].parse().ok()?;
7518 let day: u32 = parts[2].parse().ok()?;
7519 if !(1..=days_in_month(year, month)?).contains(&day) {
7520 return None;
7521 }
7522 Some((year, month, day))
7523 }
7524
7525 fn parse_time(s: &str) -> Option<(u32, u32, u32, u64)> {
7526 let (time_str, frac_str) = match s.split_once('.') {
7527 Some((time, frac)) => (time, Some(frac)),
7528 None => (s, None),
7529 };
7530 let parts: Vec<&str> = time_str.split(':').collect();
7531 if parts.is_empty() || parts.len() > 3 {
7532 return None;
7533 }
7534 let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
7535 let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
7536 let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
7537
7538 if hour > 23 || minute > 59 || second > 59 {
7539 return None;
7540 }
7541
7542 let nanos = match frac_str {
7543 None => 0,
7544 Some(frac) => {
7545 if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
7546 return None;
7547 }
7548 let digits = frac.len().min(9);
7549 let mut nanos = 0_u64;
7550 for byte in frac.bytes().take(digits) {
7551 nanos = nanos * 10 + u64::from(byte - b'0');
7552 }
7553 for _ in digits..9 {
7554 nanos *= 10;
7555 }
7556 nanos
7557 }
7558 };
7559
7560 Some((hour, minute, second, nanos))
7561 }
7562
7563 fn ymd_hms_to_nanos(
7585 year: i64,
7586 month: u32,
7587 day: u32,
7588 hour: u32,
7589 minute: u32,
7590 second: u32,
7591 sub_nanos: u64,
7592 ) -> Option<i64> {
7593 let m = month as i64;
7594 let d = day as i64;
7595
7596 let y = if m <= 2 { year.checked_sub(1)? } else { year };
7597 let era = if y >= 0 { y } else { y.checked_sub(399)? } / 400;
7598 let yoe = y.checked_sub(era.checked_mul(400)?)?;
7599 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
7600 let doe = yoe
7601 .checked_mul(365)?
7602 .checked_add(yoe / 4 - yoe / 100)?
7603 .checked_add(doy)?;
7604 let days_since_epoch = era
7605 .checked_mul(146_097)?
7606 .checked_add(doe)?
7607 .checked_sub(719_468)?;
7608
7609 let total_seconds = days_since_epoch
7610 .checked_mul(86400)?
7611 .checked_add(i64::from(hour) * 3600)?
7612 .checked_add(i64::from(minute) * 60)?
7613 .checked_add(i64::from(second))?;
7614 total_seconds
7615 .checked_mul(Timedelta::NANOS_PER_SEC)?
7616 .checked_add(sub_nanos as i64)
7617 }
7618
7619 #[must_use]
7626 pub fn strftime(&self, format: &str) -> String {
7627 if self.is_nat() {
7628 return "NaT".to_string();
7629 }
7630 strftime_in_zone(self.nanos, format, self.tz.as_deref())
7631 }
7632
7633 #[must_use]
7637 pub fn day_name(&self) -> String {
7638 const NAMES: [&str; 7] = [
7639 "Thursday",
7640 "Friday",
7641 "Saturday",
7642 "Sunday",
7643 "Monday",
7644 "Tuesday",
7645 "Wednesday",
7646 ];
7647 if self.is_nat() {
7648 return "NaT".to_string();
7649 }
7650 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7656 let dow = ((days_since_epoch % 7) + 7) % 7;
7657 NAMES[dow as usize].to_string()
7658 }
7659
7660 #[must_use]
7664 pub fn month_name(&self) -> String {
7665 const NAMES: [&str; 12] = [
7666 "January",
7667 "February",
7668 "March",
7669 "April",
7670 "May",
7671 "June",
7672 "July",
7673 "August",
7674 "September",
7675 "October",
7676 "November",
7677 "December",
7678 ];
7679 if self.is_nat() {
7680 return "NaT".to_string();
7681 }
7682 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7686 let days = days_since_epoch + 719_468;
7687 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7688 let doe = days - era * 146_097;
7689 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7690 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7691 let mp = (5 * doy + 2) / 153;
7692 let m = if mp < 10 { mp + 3 } else { mp - 9 };
7693 NAMES[(m - 1) as usize].to_string()
7694 }
7695
7696 #[must_use]
7701 pub fn tz_localize(&self, tz: Option<&str>) -> Self {
7702 if self.is_nat() {
7703 return Self::nat();
7704 }
7705 Self {
7706 nanos: self.nanos,
7707 tz: tz.map(String::from),
7708 }
7709 }
7710
7711 #[must_use]
7717 pub fn tz_convert(&self, tz: &str) -> Self {
7718 if self.is_nat() {
7719 return Self::nat();
7720 }
7721 Self {
7722 nanos: self.nanos,
7723 tz: Some(tz.to_string()),
7724 }
7725 }
7726
7727 #[must_use]
7732 pub fn fromtimestamp(ts: f64, tz: Option<&str>) -> Self {
7733 if ts.is_nan() || ts.is_infinite() {
7734 return Self::nat();
7735 }
7736 let nanos_f64 = ts * 1_000_000_000.0;
7737 const MAX_NANOS: f64 = i64::MAX as f64;
7739 const MIN_NANOS: f64 = i64::MIN as f64;
7740 if !(MIN_NANOS..=MAX_NANOS).contains(&nanos_f64) {
7741 return Self::nat();
7742 }
7743 Self {
7744 nanos: nanos_f64 as i64,
7745 tz: tz.map(String::from),
7746 }
7747 }
7748
7749 #[must_use]
7756 pub fn from_millis(ms: i64, tz: Option<&str>) -> Self {
7757 let Some(nanos) = ms.checked_mul(1_000_000) else {
7758 return Self::nat();
7759 };
7760 Self {
7761 nanos,
7762 tz: tz.map(String::from),
7763 }
7764 }
7765
7766 #[must_use]
7770 pub fn from_micros(us: i64, tz: Option<&str>) -> Self {
7771 let Some(nanos) = us.checked_mul(1_000) else {
7772 return Self::nat();
7773 };
7774 Self {
7775 nanos,
7776 tz: tz.map(String::from),
7777 }
7778 }
7779
7780 #[must_use]
7782 pub fn tzinfo(&self) -> Option<&str> {
7783 self.tz.as_deref()
7784 }
7785
7786 #[must_use]
7790 pub fn tzname(&self) -> Option<&str> {
7791 self.tzinfo()
7792 }
7793}
7794
7795impl std::fmt::Display for Timestamp {
7796 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7799 if self.is_nat() {
7800 return f.write_str("NaT");
7801 }
7802 match &self.tz {
7803 Some(tz) => write!(f, "Timestamp[{}, {}]", self.nanos, tz),
7804 None => write!(f, "Timestamp[{}, UTC]", self.nanos),
7805 }
7806 }
7807}
7808
7809impl PartialOrd for Timestamp {
7810 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
7815 if self.is_nat() || other.is_nat() {
7816 return None;
7817 }
7818 Some(self.nanos.cmp(&other.nanos))
7819 }
7820}
7821
7822pub fn isna(values: &[Scalar]) -> Vec<bool> {
7825 values.iter().map(Scalar::is_missing).collect()
7826}
7827
7828pub fn isnull(values: &[Scalar]) -> Vec<bool> {
7829 isna(values)
7830}
7831
7832pub fn notna(values: &[Scalar]) -> Vec<bool> {
7833 values.iter().map(|v| !v.is_missing()).collect()
7834}
7835
7836pub fn notnull(values: &[Scalar]) -> Vec<bool> {
7837 notna(values)
7838}
7839
7840pub fn count_na(values: &[Scalar]) -> usize {
7841 values.iter().filter(|v| v.is_missing()).count()
7842}
7843
7844pub fn fill_na(values: &[Scalar], fill: &Scalar) -> Vec<Scalar> {
7845 values
7846 .iter()
7847 .map(|v| {
7848 if v.is_missing() {
7849 fill.clone()
7850 } else {
7851 v.clone()
7852 }
7853 })
7854 .collect()
7855}
7856
7857pub fn dropna(values: &[Scalar]) -> Vec<Scalar> {
7858 values.iter().filter(|v| !v.is_missing()).cloned().collect()
7859}
7860
7861fn collect_finite(values: &[Scalar]) -> Vec<f64> {
7864 values
7865 .iter()
7866 .filter(|v| !v.is_missing())
7867 .filter_map(|v| v.to_f64().ok())
7868 .collect()
7869}
7870
7871fn collect_timedelta_ns(values: &[Scalar]) -> Option<(i128, usize)> {
7879 let mut sum: i128 = 0;
7880 let mut count: usize = 0;
7881 let mut saw_timedelta = false;
7882 for v in values {
7883 match v {
7884 Scalar::Timedelta64(ns) => {
7885 saw_timedelta = true;
7886 if v.is_missing() {
7887 continue;
7888 }
7889 sum += i128::from(*ns);
7890 count += 1;
7891 }
7892 _ if v.is_missing() => continue,
7893 _ => return None,
7896 }
7897 }
7898 if saw_timedelta {
7899 Some((sum, count))
7900 } else {
7901 None
7902 }
7903}
7904
7905fn timedelta_ns_to_scalar(ns: i128) -> Scalar {
7924 if ns > i128::from(i64::MAX) || ns <= i128::from(i64::MIN) {
7925 return Scalar::Timedelta64(Timedelta::NAT);
7926 }
7927 Scalar::Timedelta64(ns as i64)
7928}
7929
7930pub fn nansum(values: &[Scalar]) -> Scalar {
7931 if let Some((sum, _)) = collect_timedelta_ns(values) {
7932 return timedelta_ns_to_scalar(sum);
7933 }
7934 let mut sum = 0.0_f64;
7939 for v in values {
7940 if v.is_missing() {
7941 continue;
7942 }
7943 if let Ok(x) = v.to_f64() {
7944 sum += x;
7945 }
7946 }
7947 Scalar::Float64(sum)
7948}
7949
7950#[must_use]
7987pub fn nansum_utf8(values: &[Scalar]) -> Scalar {
7988 let mut out: Option<String> = None;
7989 for v in values {
7990 if v.is_missing() {
7991 continue;
7992 }
7993 if let Scalar::Utf8(part) = v {
7994 out.get_or_insert_with(String::new).push_str(part);
7995 }
7996 }
7997 match out {
7998 Some(joined) => Scalar::Utf8(joined),
7999 None => Scalar::Int64(0),
8001 }
8002}
8003
8004pub fn nanmean(values: &[Scalar]) -> Scalar {
8005 if let Some((sum, count)) = collect_timedelta_ns(values) {
8006 if count == 0 {
8007 return Scalar::Timedelta64(Timedelta::NAT);
8008 }
8009 return timedelta_ns_to_scalar(sum / count as i128);
8012 }
8013 if let Some((sum, count)) = collect_datetime_ns(values) {
8020 if count == 0 {
8021 return Scalar::Datetime64(Timestamp::NAT);
8022 }
8023 let mean = sum / count as i128;
8024 if mean > i128::from(i64::MAX) || mean <= i128::from(i64::MIN) {
8025 return Scalar::Datetime64(Timestamp::NAT);
8026 }
8027 return Scalar::Datetime64(mean as i64);
8028 }
8029 let mut sum = 0.0_f64;
8033 let mut count = 0usize;
8034 for v in values {
8035 if v.is_missing() {
8036 continue;
8037 }
8038 if let Ok(x) = v.to_f64() {
8039 sum += x;
8040 count += 1;
8041 }
8042 }
8043 if count == 0 {
8044 return Scalar::Null(NullKind::NaN);
8045 }
8046 Scalar::Float64(sum / count as f64)
8047}
8048
8049pub fn nanany(values: &[Scalar]) -> Scalar {
8050 for v in values {
8051 if v.is_missing() {
8052 continue;
8053 }
8054 match v {
8055 Scalar::Bool(flag) if *flag => return Scalar::Bool(true),
8056 Scalar::Int64(val) if *val != 0 => return Scalar::Bool(true),
8057 Scalar::Float64(val) if !val.is_nan() && *val != 0.0 => return Scalar::Bool(true),
8058 Scalar::Utf8(val) if !val.is_empty() => return Scalar::Bool(true),
8059 Scalar::Timedelta64(ns) if *ns != 0 => return Scalar::Bool(true),
8062 _ => continue,
8063 }
8064 }
8065 Scalar::Bool(false)
8066}
8067
8068pub fn nanall(values: &[Scalar]) -> Scalar {
8069 for v in values {
8070 if v.is_missing() {
8071 continue;
8072 }
8073 match v {
8074 Scalar::Bool(flag) if !*flag => return Scalar::Bool(false),
8075 Scalar::Int64(val) if *val == 0 => return Scalar::Bool(false),
8076 Scalar::Float64(val) if val.is_nan() || *val == 0.0 => return Scalar::Bool(false),
8077 Scalar::Utf8(val) if val.is_empty() => return Scalar::Bool(false),
8078 Scalar::Timedelta64(ns) if *ns == 0 => return Scalar::Bool(false),
8081 _ => continue,
8082 }
8083 }
8084 Scalar::Bool(true)
8085}
8086
8087pub fn nancount(values: &[Scalar]) -> Scalar {
8088 let n = values.iter().filter(|v| !v.is_missing()).count();
8089 Scalar::Int64(n as i64)
8090}
8091
8092pub fn nanmin(values: &[Scalar]) -> Scalar {
8093 let mut min: Option<&Scalar> = None;
8094 for v in values {
8095 if v.is_missing() {
8096 continue;
8097 }
8098 match (min, v) {
8099 (None, _) => min = Some(v),
8100 (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8101 if b < a {
8102 min = Some(v)
8103 }
8104 }
8105 (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8106 if *b < *a {
8107 min = Some(v)
8108 }
8109 }
8110 (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8111 if b < a {
8112 min = Some(v)
8113 }
8114 }
8115 (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8116 if b < a {
8117 min = Some(v)
8118 }
8119 }
8120 (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8125 if b < a {
8126 min = Some(v)
8127 }
8128 }
8129 (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8134 if b < a {
8135 min = Some(v)
8136 }
8137 }
8138 (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8151 if a.freq != b.freq {
8152 return Scalar::Null(NullKind::NaN);
8153 }
8154 if b.ordinal < a.ordinal {
8155 min = Some(v)
8156 }
8157 }
8158 (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8173 if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8174 return Scalar::Null(NullKind::NaN);
8175 }
8176 if (b.left, b.right) < (a.left, a.right) {
8177 min = Some(v)
8178 }
8179 }
8180 (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8181 (Ok(af), Ok(bf)) if bf < af => min = Some(v),
8182 (Ok(_), Ok(_)) => {}
8183 _ => return Scalar::Null(NullKind::NaN),
8184 },
8185 }
8186 }
8187 match min {
8188 Some(v) => v.clone(),
8189 None => Scalar::Null(NullKind::NaN),
8190 }
8191}
8192
8193pub fn nanmax(values: &[Scalar]) -> Scalar {
8194 let mut max: Option<&Scalar> = None;
8195 for v in values {
8196 if v.is_missing() {
8197 continue;
8198 }
8199 match (max, v) {
8200 (None, _) => max = Some(v),
8201 (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8202 if b > a {
8203 max = Some(v)
8204 }
8205 }
8206 (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8207 if *b > *a {
8208 max = Some(v)
8209 }
8210 }
8211 (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8212 if b > a {
8213 max = Some(v)
8214 }
8215 }
8216 (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8217 if b > a {
8218 max = Some(v)
8219 }
8220 }
8221 (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8225 if b > a {
8226 max = Some(v)
8227 }
8228 }
8229 (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8231 if b > a {
8232 max = Some(v)
8233 }
8234 }
8235 (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8237 if a.freq != b.freq {
8238 return Scalar::Null(NullKind::NaN);
8239 }
8240 if b.ordinal > a.ordinal {
8241 max = Some(v)
8242 }
8243 }
8244 (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8247 if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8248 return Scalar::Null(NullKind::NaN);
8249 }
8250 if (b.left, b.right) > (a.left, a.right) {
8251 max = Some(v)
8252 }
8253 }
8254 (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8255 (Ok(af), Ok(bf)) if bf > af => max = Some(v),
8256 (Ok(_), Ok(_)) => {}
8257 _ => return Scalar::Null(NullKind::NaN),
8258 },
8259 }
8260 }
8261 match max {
8262 Some(v) => v.clone(),
8263 None => Scalar::Null(NullKind::NaN),
8264 }
8265}
8266
8267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8279enum TemporalFamily {
8280 Timedelta,
8281 Datetime,
8282 Period(PeriodFreq),
8284}
8285
8286impl TemporalFamily {
8287 fn make(self, raw: i64) -> Scalar {
8289 match self {
8290 Self::Timedelta => Scalar::Timedelta64(raw),
8291 Self::Datetime => Scalar::Datetime64(raw),
8292 Self::Period(freq) => Scalar::Period(Period::new(raw, freq)),
8293 }
8294 }
8295
8296 fn nat(self) -> Scalar {
8298 self.make(i64::MIN)
8299 }
8300}
8301
8302fn collect_temporal_backing(values: &[Scalar]) -> Option<(Vec<f64>, TemporalFamily)> {
8317 let mut out = Vec::with_capacity(values.len());
8318 let mut family: Option<TemporalFamily> = None;
8319 for v in values {
8320 let (raw, this) = match v {
8321 Scalar::Timedelta64(ns) => (*ns, TemporalFamily::Timedelta),
8322 Scalar::Datetime64(ns) => (*ns, TemporalFamily::Datetime),
8323 Scalar::Period(p) => (p.ordinal, TemporalFamily::Period(p.freq)),
8324 _ if v.is_missing() => continue,
8325 _ => return None,
8326 };
8327 match family {
8329 Some(existing) if existing != this => return None,
8330 _ => family = Some(this),
8331 }
8332 if v.is_missing() {
8333 continue;
8334 }
8335 out.push(raw as f64);
8336 }
8337 family.map(|f| (out, f))
8338}
8339
8340fn collect_timedelta_ns_f64(values: &[Scalar]) -> Option<Vec<f64>> {
8347 match collect_temporal_backing(values) {
8348 Some((out, TemporalFamily::Timedelta)) => Some(out),
8349 _ => None,
8350 }
8351}
8352
8353fn float_ns_to_timedelta(value: f64) -> Scalar {
8355 float_ns_to_temporal(value, TemporalFamily::Timedelta)
8356}
8357
8358fn float_ns_to_temporal(value: f64, make: TemporalFamily) -> Scalar {
8361 if !value.is_finite() {
8362 return make.nat();
8363 }
8364 let clamped = value.clamp(i64::MIN as f64, i64::MAX as f64);
8365 make.make(clamped as i64)
8366}
8367
8368pub fn nanmedian(values: &[Scalar]) -> Scalar {
8369 let Some((_, make)) = collect_temporal_backing(values) else {
8383 return nanmedian_numeric(values);
8385 };
8386 let mut td: Vec<i64> = values
8387 .iter()
8388 .filter(|value| !value.is_missing())
8389 .filter_map(|value| match value {
8390 Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
8391 Scalar::Period(p) => Some(p.ordinal),
8392 _ => None,
8393 })
8394 .collect();
8395 if td.is_empty() {
8396 return nanmedian_numeric(values);
8404 }
8405 let n = td.len();
8408 let mid = n / 2;
8409 let (left, mid_ref, _right) = td.select_nth_unstable(mid);
8410 let mid_val = *mid_ref;
8411 let median_ns = if n.is_multiple_of(2) {
8412 let lower = left.iter().copied().fold(i64::MIN, i64::max);
8413 (i128::from(lower) + i128::from(mid_val)) / 2
8415 } else {
8416 i128::from(mid_val)
8417 };
8418 make.make(median_ns as i64)
8419}
8420
8421fn nanmedian_numeric(values: &[Scalar]) -> Scalar {
8425 let mut nums = collect_finite(values);
8426 if nums.is_empty() {
8427 return Scalar::Null(NullKind::NaN);
8428 }
8429 let n = nums.len();
8436 let mid = n / 2;
8437 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
8438 let (left, mid_ref, _right) = nums.select_nth_unstable_by(mid, cmp);
8439 let mid_val = *mid_ref;
8440 if n.is_multiple_of(2) {
8441 let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
8442 Scalar::Float64((lower + mid_val) / 2.0)
8443 } else {
8444 Scalar::Float64(mid_val)
8445 }
8446}
8447
8448pub fn nanvar(values: &[Scalar], ddof: usize) -> Scalar {
8449 if let Some(td) = collect_timedelta_ns_f64(values) {
8452 if td.len() <= ddof {
8453 return Scalar::Timedelta64(Timedelta::NAT);
8454 }
8455 let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8456 let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8457 return float_ns_to_timedelta(sum_sq / (td.len() - ddof) as f64);
8458 }
8459 let nums = collect_finite(values);
8460 if nums.len() <= ddof {
8461 return Scalar::Null(NullKind::NaN);
8462 }
8463 let mean: f64 = nums.iter().sum::<f64>() / nums.len() as f64;
8464 let sum_sq: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
8465 Scalar::Float64(sum_sq / (nums.len() - ddof) as f64)
8466}
8467
8468pub fn nanstd(values: &[Scalar], ddof: usize) -> Scalar {
8469 if let Some((td, family)) = collect_temporal_backing(values)
8488 && !matches!(family, TemporalFamily::Period(_))
8489 {
8490 if td.len() <= ddof {
8491 return Scalar::Timedelta64(Timedelta::NAT);
8492 }
8493 let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8494 let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8495 let var = sum_sq / (td.len() - ddof) as f64;
8496 return float_ns_to_timedelta(var.sqrt());
8497 }
8498 match nanvar(values, ddof) {
8499 Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
8500 other => other,
8501 }
8502}
8503
8504pub fn nansem(values: &[Scalar], ddof: usize) -> Scalar {
8510 if let Some(td) = collect_timedelta_ns_f64(values) {
8512 if td.len() <= ddof {
8513 return Scalar::Timedelta64(Timedelta::NAT);
8514 }
8515 let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8516 let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8517 let var = sum_sq / (td.len() - ddof) as f64;
8518 let std = var.sqrt();
8519 return float_ns_to_timedelta(std / (td.len() as f64).sqrt());
8520 }
8521 let nums = collect_finite(values);
8522 if nums.len() <= ddof {
8523 return Scalar::Null(NullKind::NaN);
8524 }
8525 let n = nums.len();
8526 let mean = nums.iter().sum::<f64>() / n as f64;
8527 let sum_sq = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
8528 let var = sum_sq / (n - ddof) as f64;
8529 let std = var.sqrt();
8530 Scalar::Float64(std / (n as f64).sqrt())
8531}
8532
8533pub fn nansem_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8539 if collect_timedelta_ns_f64(values).is_some() {
8540 return nansem(values, ddof);
8541 }
8542 grouped_moments(values)
8543 .sem(ddof)
8544 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8545}
8546
8547#[derive(Clone, Copy, Debug, Default, PartialEq)]
8554pub struct KahanSum {
8555 sum: f64,
8556 compensation: f64,
8557}
8558
8559impl KahanSum {
8560 #[inline]
8562 pub fn add(&mut self, value: f64) {
8563 let y = value - self.compensation;
8564 let t = self.sum + y;
8565 self.compensation = t - self.sum - y;
8566 if self.compensation.is_nan() {
8567 self.compensation = 0.0;
8568 }
8569 self.sum = t;
8570 }
8571
8572 #[inline]
8574 #[must_use]
8575 pub fn sum(self) -> f64 {
8576 self.sum
8577 }
8578}
8579
8580#[derive(Clone, Copy, Debug, Default, PartialEq)]
8587pub struct WelfordVar {
8588 count: usize,
8589 mean: f64,
8590 m2: f64,
8591}
8592
8593impl WelfordVar {
8594 #[inline]
8596 pub fn add(&mut self, value: f64) {
8597 self.count += 1;
8598 let old = self.mean;
8599 self.mean += (value - old) / self.count as f64;
8600 self.m2 += (value - self.mean) * (value - old);
8601 }
8602
8603 #[must_use]
8605 pub fn count(self) -> usize {
8606 self.count
8607 }
8608
8609 #[must_use]
8611 pub fn var(self, ddof: usize) -> Option<f64> {
8612 (self.count > ddof).then(|| self.m2 / (self.count - ddof) as f64)
8613 }
8614
8615 #[must_use]
8617 pub fn std(self, ddof: usize) -> Option<f64> {
8618 self.var(ddof).map(f64::sqrt)
8619 }
8620
8621 #[must_use]
8623 pub fn sem(self, ddof: usize) -> Option<f64> {
8624 self.var(ddof).map(|var| (var / self.count as f64).sqrt())
8625 }
8626}
8627
8628#[derive(Clone, Copy, Debug, Default, PartialEq)]
8636pub struct SkewMoments {
8637 count: usize,
8638 m1: f64,
8639 m2: f64,
8640 m3: f64,
8641}
8642
8643impl SkewMoments {
8644 #[inline]
8646 pub fn add(&mut self, value: f64) {
8647 let before = self.count as f64;
8648 self.count += 1;
8649 let n = self.count as f64;
8650 let delta = value - self.m1;
8651 let delta_n = delta / n;
8652 let term1 = delta * delta_n * before;
8653 self.m1 += delta_n;
8654 self.m3 += term1 * delta_n * (n - 2.0) - 3.0 * delta_n * self.m2;
8655 self.m2 += term1;
8656 }
8657
8658 #[must_use]
8660 pub fn count(self) -> usize {
8661 self.count
8662 }
8663
8664 #[must_use]
8666 pub fn skew(self) -> Option<f64> {
8667 if self.count < 3 {
8668 return None;
8669 }
8670 if self.m2 == 0.0 {
8671 return Some(0.0);
8672 }
8673 let n = self.count as f64;
8674 let half = std::hint::black_box(0.5);
8678 Some((n * (n - 1.0).powf(half) / (n - 2.0)) * (self.m3 / self.m2.powf(1.5)))
8679 }
8680}
8681
8682#[must_use]
8685pub fn nanskew_grouped(values: &[Scalar]) -> Scalar {
8686 let mut moments = SkewMoments::default();
8687 for value in values {
8688 if value.is_missing() {
8689 continue;
8690 }
8691 if let Ok(x) = value.to_f64() {
8692 moments.add(x);
8693 }
8694 }
8695 moments
8696 .skew()
8697 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8698}
8699
8700fn grouped_moments(values: &[Scalar]) -> WelfordVar {
8702 let mut moments = WelfordVar::default();
8703 for value in values {
8704 if value.is_missing() {
8705 continue;
8706 }
8707 if let Ok(x) = value.to_f64() {
8708 moments.add(x);
8709 }
8710 }
8711 moments
8712}
8713
8714#[must_use]
8718pub fn nansum_grouped(values: &[Scalar]) -> Scalar {
8719 if collect_timedelta_ns(values).is_some() {
8720 return nansum(values);
8721 }
8722 let mut sum = KahanSum::default();
8723 for value in values {
8724 if value.is_missing() {
8725 continue;
8726 }
8727 if let Ok(x) = value.to_f64() {
8728 sum.add(x);
8729 }
8730 }
8731 Scalar::Float64(sum.sum())
8732}
8733
8734#[must_use]
8737pub fn nanmean_grouped(values: &[Scalar]) -> Scalar {
8738 if collect_timedelta_ns(values).is_some() || collect_datetime_ns(values).is_some() {
8739 return nanmean(values);
8740 }
8741 let mut sum = KahanSum::default();
8742 let mut count = 0_usize;
8743 for value in values {
8744 if value.is_missing() {
8745 continue;
8746 }
8747 if let Ok(x) = value.to_f64() {
8748 sum.add(x);
8749 count += 1;
8750 }
8751 }
8752 if count == 0 {
8753 return Scalar::Null(NullKind::NaN);
8754 }
8755 Scalar::Float64(sum.sum() / count as f64)
8756}
8757
8758#[must_use]
8761pub fn nanvar_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8762 if collect_timedelta_ns_f64(values).is_some() {
8763 return nanvar(values, ddof);
8764 }
8765 grouped_moments(values)
8766 .var(ddof)
8767 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8768}
8769
8770#[must_use]
8773pub fn nanstd_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8774 if collect_temporal_backing(values).is_some() {
8775 return nanstd(values, ddof);
8776 }
8777 grouped_moments(values)
8778 .std(ddof)
8779 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8780}
8781
8782pub fn nanptp(values: &[Scalar]) -> Scalar {
8787 if is_datetime_input(values) {
8795 let (mut lo, mut hi) = (i64::MAX, i64::MIN);
8796 for value in values {
8797 if value.is_missing() {
8798 continue;
8799 }
8800 if let Scalar::Datetime64(ns) = value {
8801 lo = lo.min(*ns);
8802 hi = hi.max(*ns);
8803 }
8804 }
8805 return timedelta_ns_to_scalar(i128::from(hi) - i128::from(lo));
8806 }
8807 let (mut td_lo, mut td_hi) = (i64::MAX, i64::MIN);
8811 let mut saw_timedelta = false;
8812 let mut all_timedelta = true;
8813 for value in values {
8814 if value.is_missing() {
8815 continue;
8816 }
8817 match value {
8818 Scalar::Timedelta64(ns) => {
8819 saw_timedelta = true;
8820 td_lo = td_lo.min(*ns);
8821 td_hi = td_hi.max(*ns);
8822 }
8823 _ => {
8824 all_timedelta = false;
8825 break;
8826 }
8827 }
8828 }
8829 if all_timedelta && saw_timedelta {
8830 return timedelta_ns_to_scalar(i128::from(td_hi) - i128::from(td_lo));
8834 }
8835 let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
8840 let mut seen = false;
8841 for v in values {
8842 if v.is_missing() {
8843 continue;
8844 }
8845 if let Ok(x) = v.to_f64() {
8846 seen = true;
8847 if x < lo {
8848 lo = x;
8849 }
8850 if x > hi {
8851 hi = x;
8852 }
8853 }
8854 }
8855 if !seen {
8856 return Scalar::Null(NullKind::NaN);
8857 }
8858 Scalar::Float64(hi - lo)
8859}
8860
8861pub fn nanskew(values: &[Scalar]) -> Scalar {
8867 let nums = collect_finite(values);
8868 let n = nums.len() as f64;
8869 if n < 3.0 {
8870 return Scalar::Null(NullKind::NaN);
8871 }
8872 let mean = nums.iter().sum::<f64>() / n;
8873 let (mut m2, mut m3) = (0.0_f64, 0.0_f64);
8877 for x in nums {
8878 let delta = x - mean;
8879 let d2 = delta * delta;
8885 m2 += d2;
8886 m3 += d2 * delta;
8887 }
8888 let s2 = m2 / (n - 1.0);
8889 if s2 == 0.0 {
8890 return Scalar::Float64(0.0);
8891 }
8892 let s3 = s2.powf(1.5);
8893 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
8894}
8895
8896pub fn nankurt(values: &[Scalar]) -> Scalar {
8903 let nums = collect_finite(values);
8904 let n = nums.len() as f64;
8905 if n < 4.0 {
8906 return Scalar::Null(NullKind::NaN);
8907 }
8908 let mean = nums.iter().sum::<f64>() / n;
8909 let (mut m2, mut m4) = (0.0_f64, 0.0_f64);
8913 for x in nums {
8914 let delta = x - mean;
8915 let d2 = delta * delta;
8918 m2 += d2;
8919 m4 += d2 * d2;
8920 }
8921 let s2 = m2 / (n - 1.0);
8922 if s2 == 0.0 {
8923 return Scalar::Float64(0.0);
8924 }
8925 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
8926 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
8927 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
8928}
8929
8930pub fn nanprod(values: &[Scalar]) -> Scalar {
8932 if is_timedelta_input(values) {
8939 return Scalar::Null(NullKind::NaN);
8940 }
8941 let mut prod = 1.0_f64;
8946 for v in values {
8947 if v.is_missing() {
8948 continue;
8949 }
8950 if let Ok(x) = v.to_f64() {
8951 prod *= x;
8952 }
8953 }
8954 Scalar::Float64(prod)
8955}
8956
8957fn is_timedelta_input(values: &[Scalar]) -> bool {
8963 let mut saw_td = false;
8964 for v in values {
8965 if v.is_missing() {
8966 continue;
8967 }
8968 match v {
8969 Scalar::Timedelta64(_) => saw_td = true,
8970 _ => return false,
8971 }
8972 }
8973 saw_td
8974}
8975
8976fn collect_datetime_ns(values: &[Scalar]) -> Option<(i128, usize)> {
8986 let mut sum: i128 = 0;
8987 let mut count: usize = 0;
8988 let mut saw_datetime = false;
8989 for v in values {
8990 match v {
8991 Scalar::Datetime64(ns) => {
8992 saw_datetime = true;
8993 if v.is_missing() {
8994 continue;
8995 }
8996 sum += i128::from(*ns);
8997 count += 1;
8998 }
8999 _ if v.is_missing() => continue,
9000 _ => return None,
9001 }
9002 }
9003 if saw_datetime {
9004 Some((sum, count))
9005 } else {
9006 None
9007 }
9008}
9009
9010fn is_datetime_input(values: &[Scalar]) -> bool {
9017 let mut saw_dt = false;
9018 for v in values {
9019 if v.is_missing() {
9020 continue;
9021 }
9022 match v {
9023 Scalar::Datetime64(_) => saw_dt = true,
9024 _ => return false,
9025 }
9026 }
9027 saw_dt
9028}
9029
9030fn is_int64_input(values: &[Scalar]) -> bool {
9032 let mut saw_int = false;
9033 for value in values {
9034 if value.is_missing() {
9035 continue;
9036 }
9037 match value {
9038 Scalar::Int64(_) => saw_int = true,
9039 _ => return false,
9040 }
9041 }
9042 saw_int
9043}
9044
9045fn is_interval_input(values: &[Scalar]) -> bool {
9048 let mut saw_interval = false;
9049 for v in values {
9050 if v.is_missing() {
9051 continue;
9052 }
9053 match v {
9054 Scalar::Interval(_) => saw_interval = true,
9055 _ => return false,
9056 }
9057 }
9058 saw_interval
9059}
9060
9061fn nanarg_interval(values: &[Scalar], find_max: bool) -> Option<usize> {
9073 let mut best: Option<(usize, (f64, f64))> = None;
9074 for (index, value) in values.iter().enumerate() {
9075 if value.is_missing() {
9076 continue;
9077 }
9078 let Scalar::Interval(iv) = value else {
9079 continue;
9080 };
9081 if iv.left.is_nan() || iv.right.is_nan() {
9082 return None;
9083 }
9084 let key = (iv.left, iv.right);
9085 match best {
9086 None => best = Some((index, key)),
9087 Some((_, current)) if (find_max && key > current) || (!find_max && key < current) => {
9090 best = Some((index, key));
9091 }
9092 _ => {}
9093 }
9094 }
9095 best.map(|(index, _)| index)
9096}
9097
9098fn nanarg_i64(values: &[Scalar], find_max: bool) -> Option<usize> {
9099 let mut best: Option<(usize, i64)> = None;
9100 for (index, value) in values.iter().enumerate() {
9101 if value.is_missing() {
9102 continue;
9103 }
9104 let candidate = match value {
9113 Scalar::Int64(raw) | Scalar::Timedelta64(raw) | Scalar::Datetime64(raw) => raw,
9114 Scalar::Period(p) => &p.ordinal,
9115 _ => continue,
9116 };
9117 match best {
9118 None => best = Some((index, *candidate)),
9119 Some((_, current))
9120 if (find_max && *candidate > current) || (!find_max && *candidate < current) =>
9121 {
9122 best = Some((index, *candidate));
9123 }
9124 _ => {}
9125 }
9126 }
9127 best.map(|(index, _)| index)
9128}
9129
9130fn timedelta_cumulative<F>(values: &[Scalar], init: i128, mut step: F) -> Vec<Scalar>
9135where
9136 F: FnMut(i128, i128) -> i128,
9137{
9138 let mut out = Vec::with_capacity(values.len());
9139 let mut running: i128 = init;
9140 for v in values {
9141 if v.is_missing() {
9142 out.push(Scalar::Null(NullKind::NaT));
9143 continue;
9144 }
9145 if let Scalar::Timedelta64(ns) = v {
9146 running = step(running, i128::from(*ns));
9153 out.push(timedelta_ns_to_scalar(running));
9154 } else {
9155 out.push(Scalar::Null(NullKind::NaT));
9156 }
9157 }
9158 out
9159}
9160
9161fn timedelta_cumulative_extrema<F>(
9169 values: &[Scalar],
9170 sentinel: i64,
9171 make: TemporalFamily,
9172 mut step: F,
9173) -> Vec<Scalar>
9174where
9175 F: FnMut(i64, i64) -> i64,
9176{
9177 let mut out = Vec::with_capacity(values.len());
9178 let mut running: Option<i64> = None;
9179 for v in values {
9180 if v.is_missing() {
9181 out.push(Scalar::Null(NullKind::NaT));
9182 continue;
9183 }
9184 let raw = match v {
9186 Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
9187 Scalar::Period(p) => Some(p.ordinal),
9188 _ => None,
9189 };
9190 if let Some(ns) = raw.as_ref() {
9191 let new_val = match running {
9192 Some(prev) => step(prev, *ns),
9193 None => *ns,
9194 };
9195 running = Some(new_val);
9196 out.push(make.make(new_val));
9197 } else {
9198 out.push(Scalar::Null(NullKind::NaT));
9199 }
9200 }
9201 let _ = sentinel; out
9203}
9204
9205#[must_use]
9226pub fn nancumsum_with_policy(values: &[Scalar], policy: OverflowPolicy) -> Vec<Scalar> {
9227 if !matches!(policy, OverflowPolicy::Strict) || !is_timedelta_input(values) {
9228 return nancumsum(values);
9229 }
9230 let mut out = Vec::with_capacity(values.len());
9231 let mut running: i64 = 0;
9232 for value in values {
9233 if value.is_missing() {
9234 out.push(Scalar::Null(NullKind::NaT));
9235 continue;
9236 }
9237 if let Scalar::Timedelta64(ns) = value {
9238 running = running.wrapping_add(*ns);
9241 out.push(Scalar::Timedelta64(running));
9242 } else {
9243 out.push(Scalar::Null(NullKind::NaT));
9244 }
9245 }
9246 out
9247}
9248
9249pub fn nancumsum(values: &[Scalar]) -> Vec<Scalar> {
9250 if is_timedelta_input(values) {
9254 return timedelta_cumulative(values, 0_i128, |acc, x| acc.saturating_add(x));
9255 }
9256 let mut out = Vec::with_capacity(values.len());
9257 let mut running = 0.0_f64;
9258 for v in values {
9259 if v.is_missing() {
9260 out.push(Scalar::Null(NullKind::NaN));
9261 continue;
9262 }
9263 match v.to_f64() {
9264 Ok(x) if !x.is_nan() => {
9265 running += x;
9266 out.push(Scalar::Float64(running));
9267 }
9268 _ => out.push(Scalar::Null(NullKind::NaN)),
9269 }
9270 }
9271 out
9272}
9273
9274pub fn nancumprod(values: &[Scalar]) -> Vec<Scalar> {
9279 let mut out = Vec::with_capacity(values.len());
9280 let mut running = 1.0_f64;
9281 for v in values {
9282 if v.is_missing() {
9283 out.push(Scalar::Null(NullKind::NaN));
9284 continue;
9285 }
9286 match v.to_f64() {
9287 Ok(x) if !x.is_nan() => {
9288 running *= x;
9289 out.push(Scalar::Float64(running));
9290 }
9291 _ => out.push(Scalar::Null(NullKind::NaN)),
9292 }
9293 }
9294 out
9295}
9296
9297pub fn nancummax(values: &[Scalar]) -> Vec<Scalar> {
9303 if let Some((_, family)) = collect_temporal_backing(values) {
9309 return timedelta_cumulative_extrema(values, i64::MAX, family, |acc, x| acc.max(x));
9310 }
9311 let mut out = Vec::with_capacity(values.len());
9312 let mut running: Option<f64> = None;
9313 for v in values {
9314 if v.is_missing() {
9315 out.push(Scalar::Null(NullKind::NaN));
9316 continue;
9317 }
9318 match v.to_f64() {
9319 Ok(x) if !x.is_nan() => {
9320 let new_val = match running {
9321 Some(prev) => prev.max(x),
9322 None => x,
9323 };
9324 running = Some(new_val);
9325 out.push(Scalar::Float64(new_val));
9326 }
9327 _ => out.push(Scalar::Null(NullKind::NaN)),
9328 }
9329 }
9330 out
9331}
9332
9333pub fn nancummin(values: &[Scalar]) -> Vec<Scalar> {
9337 if is_timedelta_input(values) {
9339 return timedelta_cumulative_extrema(
9340 values,
9341 i64::MIN,
9342 TemporalFamily::Timedelta,
9343 |acc, x| acc.min(x),
9344 );
9345 }
9346 if let Some((_, family)) = collect_temporal_backing(values) {
9348 return timedelta_cumulative_extrema(values, i64::MIN, family, |acc, x| acc.min(x));
9349 }
9350 let mut out = Vec::with_capacity(values.len());
9351 let mut running: Option<f64> = None;
9352 for v in values {
9353 if v.is_missing() {
9354 out.push(Scalar::Null(NullKind::NaN));
9355 continue;
9356 }
9357 match v.to_f64() {
9358 Ok(x) if !x.is_nan() => {
9359 let new_val = match running {
9360 Some(prev) => prev.min(x),
9361 None => x,
9362 };
9363 running = Some(new_val);
9364 out.push(Scalar::Float64(new_val));
9365 }
9366 _ => out.push(Scalar::Null(NullKind::NaN)),
9367 }
9368 }
9369 out
9370}
9371
9372pub fn nanquantile(values: &[Scalar], q: f64) -> Scalar {
9378 if !(0.0..=1.0).contains(&q) {
9379 return Scalar::Null(NullKind::NaN);
9380 }
9381 if let Some((mut td, make)) = collect_temporal_backing(values) {
9384 if td.is_empty() {
9385 return make.nat();
9386 }
9387 let n = td.len();
9388 if n == 1 {
9389 return float_ns_to_temporal(td[0], make);
9390 }
9391 let pos = q * (n - 1) as f64;
9392 let lo = pos.floor() as usize;
9393 let hi = pos.ceil() as usize;
9394 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9398 let (_left, lo_ref, right) = td.select_nth_unstable_by(lo, cmp);
9399 let lo_val = *lo_ref;
9400 let ns = if lo == hi {
9401 lo_val
9402 } else {
9403 let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9404 let weight = pos - lo as f64;
9405 lo_val + (hi_val - lo_val) * weight
9406 };
9407 return float_ns_to_temporal(ns, make);
9408 }
9409 let mut nums = collect_finite(values);
9410 if nums.is_empty() {
9411 return Scalar::Null(NullKind::NaN);
9412 }
9413 let n = nums.len();
9414 if n == 1 {
9415 return Scalar::Float64(nums[0]);
9416 }
9417 let pos = q * (n - 1) as f64;
9418 let lo = pos.floor() as usize;
9419 let hi = pos.ceil() as usize;
9420 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9425 let (_left, lo_ref, right) = nums.select_nth_unstable_by(lo, cmp);
9426 let lo_val = *lo_ref;
9427 if lo == hi {
9428 return Scalar::Float64(lo_val);
9429 }
9430 let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9431 let weight = pos - lo as f64;
9432 Scalar::Float64(lo_val + (hi_val - lo_val) * weight)
9433}
9434
9435pub fn nanargmax(values: &[Scalar]) -> Option<usize> {
9440 if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9445 return nanarg_i64(values, true);
9446 }
9447 if is_interval_input(values) {
9451 return nanarg_interval(values, true);
9452 }
9453 let mut best: Option<(usize, f64)> = None;
9454 for (i, v) in values.iter().enumerate() {
9455 if v.is_missing() {
9456 continue;
9457 }
9458 if let Ok(x) = v.to_f64() {
9459 if x.is_nan() {
9460 continue;
9461 }
9462 match best {
9463 None => best = Some((i, x)),
9464 Some((_, cur)) if x > cur => best = Some((i, x)),
9465 _ => {}
9466 }
9467 }
9468 }
9469 best.map(|(i, _)| i)
9470}
9471
9472pub fn nanargmin(values: &[Scalar]) -> Option<usize> {
9476 if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9479 return nanarg_i64(values, false);
9480 }
9481 if is_interval_input(values) {
9483 return nanarg_interval(values, false);
9484 }
9485 let mut best: Option<(usize, f64)> = None;
9486 for (i, v) in values.iter().enumerate() {
9487 if v.is_missing() {
9488 continue;
9489 }
9490 if let Ok(x) = v.to_f64() {
9491 if x.is_nan() {
9492 continue;
9493 }
9494 match best {
9495 None => best = Some((i, x)),
9496 Some((_, cur)) if x < cur => best = Some((i, x)),
9497 _ => {}
9498 }
9499 }
9500 }
9501 best.map(|(i, _)| i)
9502}
9503
9504pub fn nannunique(values: &[Scalar]) -> Scalar {
9506 use rustc_hash::FxHashSet;
9507 #[derive(Hash, PartialEq, Eq)]
9508 enum ScalarKey<'a> {
9509 Bool(bool),
9510 Int64(i64),
9511 FloatBits(u64),
9512 Utf8(&'a str),
9513 Timedelta64(i64),
9514 Datetime64(i64),
9515 Period(i64, PeriodFreq),
9516 Interval(u64, u64, IntervalClosed),
9517 Object(String),
9520 }
9521
9522 let mut seen = FxHashSet::default();
9523 for val in values {
9524 if val.is_missing() {
9525 continue;
9526 }
9527 let key = match val {
9528 Scalar::Bool(v) => ScalarKey::Bool(*v),
9529 Scalar::Int64(v) => ScalarKey::Int64(*v),
9530 Scalar::Float64(v) => {
9531 let normalized = if *v == 0.0 { 0.0 } else { *v };
9532 ScalarKey::FloatBits(normalized.to_bits())
9533 }
9534 Scalar::Utf8(v) => ScalarKey::Utf8(v.as_str()),
9535 Scalar::Timedelta64(v) => ScalarKey::Timedelta64(*v),
9536 Scalar::Datetime64(v) => ScalarKey::Datetime64(*v),
9537 Scalar::Period(p) => ScalarKey::Period(p.ordinal, p.freq),
9538 Scalar::Interval(v) => ScalarKey::Interval(
9539 normalized_float_bits(v.left),
9540 normalized_float_bits(v.right),
9541 v.closed,
9542 ),
9543 Scalar::Object(object) => ScalarKey::Object(object.repr()),
9544 Scalar::Null(_) => continue,
9545 };
9546 seen.insert(key);
9547 }
9548 Scalar::Int64(seen.len() as i64)
9549}
9550
9551fn normalized_float_bits(value: f64) -> u64 {
9552 let normalized = if value == 0.0 { 0.0 } else { value };
9553 normalized.to_bits()
9554}
9555
9556#[derive(
9576 Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
9577)]
9578#[serde(rename_all = "snake_case")]
9579#[non_exhaustive]
9580pub enum IntervalClosed {
9581 Left,
9583 #[default]
9585 Right,
9586 Both,
9588 Neither,
9590}
9591
9592impl IntervalClosed {
9593 #[must_use]
9595 pub fn left_closed(self) -> bool {
9596 matches!(self, Self::Left | Self::Both)
9597 }
9598
9599 #[must_use]
9601 pub fn right_closed(self) -> bool {
9602 matches!(self, Self::Right | Self::Both)
9603 }
9604}
9605
9606impl std::fmt::Display for IntervalClosed {
9607 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9608 match self {
9609 Self::Left => write!(f, "left"),
9610 Self::Right => write!(f, "right"),
9611 Self::Both => write!(f, "both"),
9612 Self::Neither => write!(f, "neither"),
9613 }
9614 }
9615}
9616
9617#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
9622#[serde(rename_all = "snake_case")]
9623pub enum IntervalSubtype {
9624 #[default]
9625 Float64,
9626 Int64,
9627}
9628
9629impl IntervalSubtype {
9630 #[must_use]
9632 pub const fn is_float(&self) -> bool {
9633 matches!(self, Self::Float64)
9634 }
9635
9636 #[must_use]
9638 pub const fn name(&self) -> &'static str {
9639 match self {
9640 Self::Float64 => "float64",
9641 Self::Int64 => "int64",
9642 }
9643 }
9644}
9645
9646#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
9653pub struct Interval {
9654 pub left: f64,
9655 pub right: f64,
9656 #[serde(default)]
9657 pub closed: IntervalClosed,
9658 #[serde(default, skip_serializing_if = "IntervalSubtype::is_float")]
9660 pub subtype: IntervalSubtype,
9661}
9662
9663impl PartialEq for Interval {
9664 fn eq(&self, other: &Self) -> bool {
9665 self.left == other.left && self.right == other.right && self.closed == other.closed
9666 }
9667}
9668
9669impl Eq for Interval {}
9673
9674impl Interval {
9675 fn endpoint_key(value: f64) -> f64 {
9677 if value == 0.0 { 0.0 } else { value }
9678 }
9679}
9680
9681impl std::hash::Hash for Interval {
9684 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
9685 Self::endpoint_key(self.left).to_bits().hash(state);
9686 Self::endpoint_key(self.right).to_bits().hash(state);
9687 self.closed.hash(state);
9688 }
9689}
9690
9691impl Ord for Interval {
9694 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
9695 Self::endpoint_key(self.left)
9696 .total_cmp(&Self::endpoint_key(other.left))
9697 .then_with(|| {
9698 Self::endpoint_key(self.right).total_cmp(&Self::endpoint_key(other.right))
9699 })
9700 .then_with(|| self.closed.cmp(&other.closed))
9701 }
9702}
9703
9704impl PartialOrd for Interval {
9705 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
9706 Some(self.cmp(other))
9707 }
9708}
9709
9710impl Interval {
9711 #[must_use]
9714 pub const fn new(left: f64, right: f64, closed: IntervalClosed) -> Self {
9715 Self {
9716 left,
9717 right,
9718 closed,
9719 subtype: IntervalSubtype::Float64,
9720 }
9721 }
9722
9723 #[must_use]
9726 pub fn with_int_endpoints(self) -> Self {
9727 if self.left.fract() == 0.0 && self.right.fract() == 0.0 {
9728 Self {
9729 subtype: IntervalSubtype::Int64,
9730 ..self
9731 }
9732 } else {
9733 self
9734 }
9735 }
9736
9737 #[must_use]
9739 pub fn length(&self) -> f64 {
9740 self.right - self.left
9741 }
9742
9743 #[must_use]
9745 pub fn mid(&self) -> f64 {
9746 (self.left + self.right) / 2.0
9747 }
9748
9749 #[must_use]
9752 pub fn is_empty(&self) -> bool {
9753 self.left == self.right && !matches!(self.closed, IntervalClosed::Both)
9754 }
9755
9756 #[must_use]
9761 pub fn contains(&self, value: f64) -> bool {
9762 if value.is_nan() {
9763 return false;
9764 }
9765 let left_ok = if self.closed.left_closed() {
9766 value >= self.left
9767 } else {
9768 value > self.left
9769 };
9770 let right_ok = if self.closed.right_closed() {
9771 value <= self.right
9772 } else {
9773 value < self.right
9774 };
9775 left_ok && right_ok
9776 }
9777
9778 #[must_use]
9785 pub fn overlaps(&self, other: &Self) -> bool {
9786 if self.left > other.right || other.left > self.right {
9787 return false;
9788 }
9789 if self.right == other.left {
9791 return self.closed.right_closed() && other.closed.left_closed();
9792 }
9793 if other.right == self.left {
9794 return other.closed.right_closed() && self.closed.left_closed();
9795 }
9796 true
9797 }
9798
9799 pub fn parse(s: &str) -> Result<Self, TypeError> {
9805 let s = s.trim();
9806 if s.len() < 5 {
9807 return Err(TypeError::ValueNotParseable {
9808 value: s.to_string(),
9809 target: "Interval".to_string(),
9810 });
9811 }
9812
9813 let first_char = s.chars().next().unwrap();
9814 let last_char = s.chars().last().unwrap();
9815
9816 let left_closed = match first_char {
9817 '[' => true,
9818 '(' => false,
9819 _ => {
9820 return Err(TypeError::ValueNotParseable {
9821 value: s.to_string(),
9822 target: "Interval".to_string(),
9823 });
9824 }
9825 };
9826
9827 let right_closed = match last_char {
9828 ']' => true,
9829 ')' => false,
9830 _ => {
9831 return Err(TypeError::ValueNotParseable {
9832 value: s.to_string(),
9833 target: "Interval".to_string(),
9834 });
9835 }
9836 };
9837
9838 let closed = match (left_closed, right_closed) {
9839 (true, true) => IntervalClosed::Both,
9840 (true, false) => IntervalClosed::Left,
9841 (false, true) => IntervalClosed::Right,
9842 (false, false) => IntervalClosed::Neither,
9843 };
9844
9845 let inner = &s[1..s.len() - 1];
9846 let Some((left_text, right_text)) = inner.split_once(',') else {
9847 return Err(TypeError::ValueNotParseable {
9848 value: s.to_string(),
9849 target: "Interval".to_string(),
9850 });
9851 };
9852 if right_text.contains(',') {
9853 return Err(TypeError::ValueNotParseable {
9854 value: s.to_string(),
9855 target: "Interval".to_string(),
9856 });
9857 }
9858
9859 let left: f64 = left_text
9860 .trim()
9861 .parse()
9862 .map_err(|_| TypeError::ValueNotParseable {
9863 value: s.to_string(),
9864 target: "Interval".to_string(),
9865 })?;
9866
9867 let right: f64 = right_text
9868 .trim()
9869 .parse()
9870 .map_err(|_| TypeError::ValueNotParseable {
9871 value: s.to_string(),
9872 target: "Interval".to_string(),
9873 })?;
9874
9875 Ok(Self::new(left, right, closed))
9876 }
9877}
9878
9879impl std::fmt::Display for Interval {
9880 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9887 let left_bracket = if self.closed.left_closed() { '[' } else { '(' };
9888 let right_bracket = if self.closed.right_closed() { ']' } else { ')' };
9889 #[allow(clippy::cast_possible_truncation)] let endpoint = |value: f64| match self.subtype {
9892 IntervalSubtype::Int64 if value.fract() == 0.0 => format!("{}", value as i64),
9893 _ => float_to_string_for_astype(value),
9894 };
9895 write!(
9896 f,
9897 "{left_bracket}{}, {}{right_bracket}",
9898 endpoint(self.left),
9899 endpoint(self.right)
9900 )
9901 }
9902}
9903
9904#[must_use]
9922pub fn interval_range_by_periods(
9923 start: f64,
9924 end: f64,
9925 periods: usize,
9926 closed: IntervalClosed,
9927) -> Vec<Interval> {
9928 if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
9929 return Vec::new();
9930 }
9931 let step = (end - start) / (periods as f64);
9932 let mut out = Vec::with_capacity(periods);
9933 for i in 0..periods {
9934 let left = start + step * (i as f64);
9935 let right = if i + 1 == periods {
9937 end
9938 } else {
9939 start + step * ((i + 1) as f64)
9940 };
9941 out.push(Interval::new(left, right, closed));
9942 }
9943 out
9944}
9945
9946pub fn interval_range_by_step(
9957 start: f64,
9958 end: f64,
9959 step: f64,
9960 closed: IntervalClosed,
9961) -> Result<Vec<Interval>, TypeError> {
9962 if !step.is_finite() || !step.is_sign_positive() || step == 0.0 {
9963 return Err(TypeError::InvalidIntervalStep { step });
9964 }
9965 if !start.is_finite() || !end.is_finite() || start >= end {
9966 return Ok(Vec::new());
9967 }
9968 let span = end - start;
9969 let periods_f = span / step;
9970 let periods = periods_f.round() as i64;
9971 if periods <= 0 {
9972 return Ok(Vec::new());
9973 }
9974 let reconstructed = step * (periods as f64);
9975 if (span - reconstructed).abs() > span.abs() * 1e-9 + 1e-12 {
9977 return Err(TypeError::IntervalStepDoesNotDivide { step, span });
9978 }
9979 let periods = periods as usize;
9980 let mut out = Vec::with_capacity(periods);
9981 for i in 0..periods {
9982 let left = start + step * (i as f64);
9983 let right = if i + 1 == periods {
9984 end
9985 } else {
9986 start + step * ((i + 1) as f64)
9987 };
9988 out.push(Interval::new(left, right, closed));
9989 }
9990 Ok(out)
9991}
9992
9993pub fn interval_range(
10005 start: Option<f64>,
10006 end: Option<f64>,
10007 periods: Option<usize>,
10008 freq: Option<f64>,
10009 closed: Option<IntervalClosed>,
10010) -> Result<Vec<Interval>, TypeError> {
10011 let count = usize::from(start.is_some())
10012 + usize::from(end.is_some())
10013 + usize::from(periods.is_some())
10014 + usize::from(freq.is_some());
10015 if count != 3 {
10016 return Err(TypeError::IntervalRangeParameterCount);
10017 }
10018 let closed = closed.unwrap_or(IntervalClosed::Right);
10019
10020 match (start, end, periods, freq) {
10021 (Some(start), Some(end), Some(periods), None) => {
10022 Ok(interval_range_by_periods(start, end, periods, closed))
10023 }
10024 (Some(start), Some(end), None, Some(freq)) => {
10025 interval_range_by_step(start, end, freq, closed)
10026 }
10027 (Some(start), None, Some(periods), Some(freq)) => {
10028 if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10029 return Err(TypeError::InvalidIntervalStep { step: freq });
10030 }
10031 if !start.is_finite() || periods == 0 {
10032 return Ok(Vec::new());
10033 }
10034 let mut out = Vec::with_capacity(periods);
10035 for i in 0..periods {
10036 let left = start + freq * (i as f64);
10037 let right = start + freq * ((i + 1) as f64);
10038 out.push(Interval::new(left, right, closed));
10039 }
10040 Ok(out)
10041 }
10042 (None, Some(end), Some(periods), Some(freq)) => {
10043 if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10044 return Err(TypeError::InvalidIntervalStep { step: freq });
10045 }
10046 if !end.is_finite() || periods == 0 {
10047 return Ok(Vec::new());
10048 }
10049 let start = end - freq * (periods as f64);
10050 let mut out = Vec::with_capacity(periods);
10051 for i in 0..periods {
10052 let left = start + freq * (i as f64);
10053 let right = if i + 1 == periods {
10054 end
10055 } else {
10056 start + freq * ((i + 1) as f64)
10057 };
10058 out.push(Interval::new(left, right, closed));
10059 }
10060 Ok(out)
10061 }
10062 _ => Err(TypeError::IntervalRangeParameterCount),
10063 }
10064}
10065
10066#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10085#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
10086#[non_exhaustive]
10087pub enum PeriodFreq {
10088 Annual,
10090 Quarterly,
10092 Monthly,
10094 Weekly,
10096 Daily,
10098 Business,
10100 Hourly,
10102 Minutely,
10104 Secondly,
10106 Milliseconds,
10108 Microseconds,
10110 Nanoseconds,
10112}
10113
10114impl PeriodFreq {
10115 pub fn parse(alias: &str) -> Option<Self> {
10123 if alias.eq_ignore_ascii_case("ms") && alias != "MS" {
10133 return Some(Self::Milliseconds);
10134 }
10135 match alias.to_ascii_uppercase().as_str() {
10136 "A" | "Y" | "A-DEC" | "Y-DEC" | "ANNUAL" | "YEARLY" => Some(Self::Annual),
10137 "Q" | "Q-DEC" | "QUARTERLY" => Some(Self::Quarterly),
10138 "M" | "MONTHLY" => Some(Self::Monthly),
10139 "W" | "W-SUN" | "WEEKLY" => Some(Self::Weekly),
10140 "D" | "DAILY" => Some(Self::Daily),
10141 "B" | "BUSINESS" => Some(Self::Business),
10142 "H" | "HOURLY" => Some(Self::Hourly),
10143 "T" | "MIN" | "MINUTELY" => Some(Self::Minutely),
10144 "S" | "SECONDLY" => Some(Self::Secondly),
10145 "US" | "MICROSECOND" | "MICROSECONDS" => Some(Self::Microseconds),
10146 "NS" | "NANOSECOND" | "NANOSECONDS" => Some(Self::Nanoseconds),
10147 "MILLISECOND" | "MILLISECONDS" => Some(Self::Milliseconds),
10150 _ => None,
10151 }
10152 }
10153
10154 #[must_use]
10156 pub const fn alias(self) -> &'static str {
10157 match self {
10158 Self::Annual => "Y-DEC",
10159 Self::Quarterly => "Q-DEC",
10160 Self::Monthly => "M",
10161 Self::Weekly => "W-SUN",
10162 Self::Daily => "D",
10163 Self::Business => "B",
10164 Self::Hourly => "h",
10165 Self::Minutely => "min",
10166 Self::Secondly => "s",
10167 Self::Milliseconds => "ms",
10168 Self::Microseconds => "us",
10169 Self::Nanoseconds => "ns",
10170 }
10171 }
10172
10173 #[must_use]
10192 pub const fn resolution(self) -> Option<&'static str> {
10193 match self {
10194 Self::Annual => Some("year"),
10195 Self::Quarterly => Some("quarter"),
10196 Self::Monthly => Some("month"),
10197 Self::Daily => Some("day"),
10198 Self::Hourly => Some("hour"),
10199 Self::Minutely => Some("minute"),
10200 Self::Secondly => Some("second"),
10201 Self::Milliseconds => Some("millisecond"),
10202 Self::Microseconds => Some("microsecond"),
10203 Self::Nanoseconds => Some("nanosecond"),
10204 Self::Weekly | Self::Business => None,
10207 }
10208 }
10209}
10210
10211impl std::fmt::Display for PeriodFreq {
10212 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10213 f.write_str(self.alias())
10214 }
10215}
10216
10217#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10225pub struct Period {
10226 pub ordinal: i64,
10227 pub freq: PeriodFreq,
10228}
10229
10230impl Period {
10231 #[must_use]
10232 pub const fn new(ordinal: i64, freq: PeriodFreq) -> Self {
10233 Self { ordinal, freq }
10234 }
10235
10236 #[must_use]
10239 pub const fn is_nat(&self) -> bool {
10240 self.ordinal == i64::MIN
10241 }
10242
10243 #[must_use]
10246 pub const fn ordinal(&self) -> i64 {
10247 self.ordinal
10248 }
10249
10250 #[must_use]
10252 pub const fn freq(&self) -> PeriodFreq {
10253 self.freq
10254 }
10255
10256 #[must_use]
10258 pub const fn freqstr(&self) -> &'static str {
10259 self.freq.alias()
10260 }
10261
10262 #[must_use]
10265 pub fn cmp_same_freq(&self, other: &Self) -> Option<std::cmp::Ordering> {
10266 if self.freq != other.freq {
10267 return None;
10268 }
10269 Some(self.ordinal.cmp(&other.ordinal))
10270 }
10271
10272 #[must_use]
10275 pub fn shift(&self, n: i64) -> Self {
10276 Self {
10277 ordinal: self.ordinal.saturating_add(n),
10278 freq: self.freq,
10279 }
10280 }
10281
10282 #[must_use]
10285 pub fn diff(&self, other: &Self) -> Option<i64> {
10286 if self.freq != other.freq {
10287 return None;
10288 }
10289 Some(self.ordinal.saturating_sub(other.ordinal))
10290 }
10291
10292 pub fn parse(s: &str) -> Result<Self, TypeError> {
10299 let trimmed = s.trim();
10300 if trimmed.eq_ignore_ascii_case("nat") {
10301 return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
10302 }
10303
10304 if let Some((year, quarter)) = parse_quarter_period(trimmed) {
10305 let ordinal = year
10306 .checked_sub(1970)
10307 .and_then(|offset| offset.checked_mul(4))
10308 .and_then(|base| base.checked_add(i64::from(quarter) - 1))
10309 .ok_or_else(|| TypeError::ValueNotParseable {
10310 value: s.to_owned(),
10311 target: "Period".to_owned(),
10312 })?;
10313 return Ok(Self::new(ordinal, PeriodFreq::Quarterly));
10314 }
10315
10316 if let Some((year, month, day)) = parse_ymd_period(trimmed) {
10317 let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
10318 return Ok(Self::new(ordinal, PeriodFreq::Daily));
10319 }
10320
10321 if let Some((year, month)) = parse_year_month_period(trimmed) {
10322 let ordinal = year
10323 .checked_sub(1970)
10324 .and_then(|offset| offset.checked_mul(12))
10325 .and_then(|base| base.checked_add(i64::from(month) - 1))
10326 .ok_or_else(|| TypeError::ValueNotParseable {
10327 value: s.to_owned(),
10328 target: "Period".to_owned(),
10329 })?;
10330 return Ok(Self::new(ordinal, PeriodFreq::Monthly));
10331 }
10332
10333 if let Some(year) = parse_annual_period(trimmed) {
10334 let ordinal = year
10335 .checked_sub(1970)
10336 .ok_or_else(|| TypeError::ValueNotParseable {
10337 value: s.to_owned(),
10338 target: "Period".to_owned(),
10339 })?;
10340 return Ok(Self::new(ordinal, PeriodFreq::Annual));
10341 }
10342
10343 Err(TypeError::ValueNotParseable {
10344 value: s.to_owned(),
10345 target: "Period".to_owned(),
10346 })
10347 }
10348
10349 #[must_use]
10374 pub fn calendar_string(&self) -> String {
10375 let mut rendered = String::new();
10376 let _ = self.write_calendar(&mut rendered);
10378 rendered
10379 }
10380
10381 fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
10382 if self.ordinal == i64::MIN {
10383 return rendered.write_str("NaT");
10384 }
10385 let ord = self.ordinal;
10386 match self.freq {
10387 PeriodFreq::Annual => {
10388 let year = 1970 + ord;
10389 write!(rendered, "{year}")
10390 }
10391 PeriodFreq::Quarterly => {
10392 let year = 1970 + ord.div_euclid(4);
10393 let quarter = ord.rem_euclid(4) + 1;
10394 write!(rendered, "{year}Q{quarter}")
10395 }
10396 PeriodFreq::Monthly => {
10397 let year = 1970 + ord.div_euclid(12);
10398 let month = ord.rem_euclid(12) + 1;
10399 write!(rendered, "{year:04}-{month:02}")
10400 }
10401 PeriodFreq::Daily => {
10402 let (y, m, d) = civil_from_days(ord);
10403 write!(rendered, "{y:04}-{m:02}-{d:02}")
10404 }
10405 PeriodFreq::Business => {
10416 const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
10417 let offset = WEEKDAY_OFFSET[ord.rem_euclid(5) as usize];
10420 let days = ord.div_euclid(5).saturating_mul(7).saturating_add(offset);
10421 let (y, m, d) = civil_from_days(days);
10422 write!(rendered, "{y:04}-{m:02}-{d:02}")
10423 }
10424 PeriodFreq::Weekly => {
10434 const WEEK_ANCHOR_DAY: i64 = -10;
10436 let start = ord.saturating_mul(7).saturating_add(WEEK_ANCHOR_DAY);
10437 let (sy, sm, sd) = civil_from_days(start);
10438 let (ey, em, ed) = civil_from_days(start.saturating_add(6));
10439 write!(rendered, "{sy:04}-{sm:02}-{sd:02}/{ey:04}-{em:02}-{ed:02}")
10440 }
10441 PeriodFreq::Hourly => {
10442 let (y, m, d) = civil_from_days(ord.div_euclid(24));
10443 let hour = ord.rem_euclid(24);
10444 write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
10445 }
10446 PeriodFreq::Minutely => {
10447 let day = ord.div_euclid(1440);
10448 let mins = ord.rem_euclid(1440);
10449 let (y, m, d) = civil_from_days(day);
10450 write!(
10451 rendered,
10452 "{y:04}-{m:02}-{d:02} {:02}:{:02}",
10453 mins / 60,
10454 mins % 60
10455 )
10456 }
10457 PeriodFreq::Secondly => {
10458 let day = ord.div_euclid(86_400);
10459 let secs = ord.rem_euclid(86_400);
10460 let (y, m, d) = civil_from_days(day);
10461 write!(
10462 rendered,
10463 "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
10464 secs / 3600,
10465 (secs % 3600) / 60,
10466 secs % 60
10467 )
10468 }
10469 PeriodFreq::Milliseconds | PeriodFreq::Microseconds | PeriodFreq::Nanoseconds => {
10476 let (per_sec, width) = match self.freq {
10477 PeriodFreq::Milliseconds => (1_000_i64, 3_usize),
10478 PeriodFreq::Microseconds => (1_000_000_i64, 6_usize),
10479 _ => (1_000_000_000_i64, 9_usize),
10480 };
10481 let per_day = 86_400 * per_sec;
10483 let day = ord.div_euclid(per_day);
10484 let rest = ord.rem_euclid(per_day);
10485 let secs = rest / per_sec;
10486 let frac = rest % per_sec;
10487 let (y, m, d) = civil_from_days(day);
10488 write!(
10489 rendered,
10490 "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{:0width$}",
10491 secs / 3600,
10492 (secs % 3600) / 60,
10493 secs % 60,
10494 frac,
10495 width = width
10496 )
10497 }
10498 }
10499 }
10500}
10501
10502fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
10506 let days = days_since_epoch + 719_468;
10507 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
10508 let doe = days - era * 146_097;
10509 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
10510 let y = yoe + era * 400;
10511 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
10512 let mp = (5 * doy + 2) / 153;
10513 let d = doy - (153 * mp + 2) / 5 + 1;
10514 let m = if mp < 10 { mp + 3 } else { mp - 9 };
10515 let year = if m <= 2 { y + 1 } else { y };
10516 (year, m as u32, d as u32)
10517}
10518
10519fn parse_annual_period(value: &str) -> Option<i64> {
10520 (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
10521 .then(|| value.parse::<i64>().ok())
10522 .flatten()
10523}
10524
10525fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
10526 let (year, month) = value.split_once('-')?;
10527 if year.len() != 4 || month.len() != 2 {
10528 return None;
10529 }
10530 let year = year.parse::<i64>().ok()?;
10531 let month = month.parse::<u32>().ok()?;
10532 (1..=12).contains(&month).then_some((year, month))
10533}
10534
10535fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
10536 let mut parts = value.split('-');
10537 let year = parts.next()?;
10538 let month = parts.next()?;
10539 let day = parts.next()?;
10540 if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
10541 return None;
10542 }
10543 let year = year.parse::<i64>().ok()?;
10544 let month = month.parse::<u32>().ok()?;
10545 let day = day.parse::<u32>().ok()?;
10546 (1..=days_in_month(year, month)?)
10547 .contains(&day)
10548 .then_some((year, month, day))
10549}
10550
10551fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
10552 let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
10553 if year.len() != 4 || quarter.len() != 1 {
10554 return None;
10555 }
10556 let year = year.parse::<i64>().ok()?;
10557 let quarter = quarter.parse::<u32>().ok()?;
10558 (1..=4).contains(&quarter).then_some((year, quarter))
10559}
10560
10561impl std::fmt::Display for Period {
10562 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10565 self.write_calendar(f)
10566 }
10567}
10568
10569#[must_use]
10588pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
10589 (0..periods).map(|i| start.shift(i as i64)).collect()
10590}
10591
10592#[cfg(test)]
10593mod tests {
10594 use super::{
10595 DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
10596 cast_scalar, common_dtype, infer_dtype,
10597 };
10598
10599 struct Named(&'static str);
10602
10603 impl super::HostObject for Named {
10604 fn host_eq(&self, other: &dyn super::HostObject) -> bool {
10605 other
10606 .as_any()
10607 .downcast_ref::<Named>()
10608 .is_some_and(|other| other.0 == self.0)
10609 }
10610 fn host_repr(&self) -> String {
10611 format!("Named({:?})", self.0)
10612 }
10613 fn host_str(&self) -> String {
10614 self.0.to_owned()
10615 }
10616 fn host_hash(&self) -> Option<u64> {
10617 (!self.0.is_empty()).then_some(self.0.len() as u64)
10618 }
10619 fn host_cmp(&self, other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
10621 let other = other.as_any().downcast_ref::<Named>()?;
10622 (!self.0.starts_with('!') && !other.0.starts_with('!')).then(|| self.0.cmp(other.0))
10623 }
10624 fn as_any(&self) -> &dyn std::any::Any {
10625 self
10626 }
10627 }
10628
10629 #[test]
10630 fn host_values_block_workers_only_under_a_declared_host_lock_4qg5w_13() {
10631 use std::sync::atomic::Ordering;
10632
10633 use super::{HostValue, LIVE_HOST_VALUES, workers_blocked};
10634 assert!(workers_blocked(true, 1));
10638 assert!(!workers_blocked(true, 0));
10639 assert!(!workers_blocked(false, 3));
10640 let first = HostValue::new(Named("held"));
10645 assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
10646 let clone = first.clone();
10647 drop(first);
10648 assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
10649 assert_eq!(clone.object().host_str(), "held");
10650 }
10651
10652 #[test]
10653 fn object_cells_order_like_python_then_totally_fvsao_66() {
10654 use std::cmp::Ordering;
10655
10656 use super::{HostValue, ObjectValue};
10657 let host = |name: &'static str| ObjectValue::Host(HostValue::new(Named(name)));
10658 let list = |items: Vec<Scalar>| ObjectValue::list(items);
10659 assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
10662 assert!(host("b") > host("a"));
10663 assert_eq!(host("a").cmp(&host("a")), Ordering::Equal);
10664 let one_ten = list(vec![Scalar::Int64(1), Scalar::Int64(10)]);
10667 let one_two = list(vec![Scalar::Int64(1), Scalar::Int64(2)]);
10668 assert_eq!(one_two.python_cmp(&one_ten), Some(Ordering::Less));
10669 assert!(list(vec![Scalar::Int64(1)]) < one_two);
10670 let mixed = list(vec![Scalar::Float64(1.0), Scalar::Int64(3)]);
10672 assert_eq!(one_two.python_cmp(&mixed), Some(Ordering::Less));
10673 assert_eq!(one_two.python_cmp(&host("a")), None);
10676 assert!(one_two < host("a"));
10677 assert_eq!(host("!z").python_cmp(&host("!a")), None);
10678 assert!(host("!a") < host("!z"));
10679 let text = list(vec![Scalar::Utf8("a".to_owned())]);
10680 assert_eq!(one_two.python_cmp(&text), None);
10681 assert_ne!(one_two.cmp(&text), Ordering::Equal);
10682 let nan = || list(vec![Scalar::Float64(f64::NAN)]);
10685 let (first, second) = (nan(), nan());
10686 assert_ne!(first, second);
10687 assert_ne!(first.cmp(&second), Ordering::Equal);
10688 assert_eq!(first.cmp(&second), second.cmp(&first).reverse());
10689 }
10690
10691 #[test]
10692 fn bytes_cells_print_order_and_serialize_like_python_bytes_4qg5w_8() {
10693 use std::cmp::Ordering;
10694
10695 use super::ObjectValue;
10696 let bytes = |data: &[u8]| Scalar::Object(ObjectValue::bytes(data.to_vec()));
10697 assert_eq!(bytes(b"ab").python_repr(), "b'ab'");
10700 assert_eq!(bytes(b"a'b").python_repr(), "b\"a'b\"");
10701 assert_eq!(bytes(b"a'\"").python_repr(), "b'a\\'\"'");
10702 assert_eq!(bytes(b"\x00\t\\\xff").python_repr(), "b'\\x00\\t\\\\\\xff'");
10703 assert_eq!(bytes(b"ab").python_type_name(), "bytes");
10704 assert_eq!(bytes(b"ab").python_cmp(&bytes(b"b")), Some(Ordering::Less));
10706 assert_eq!(bytes(b"a").python_cmp(&bytes(b"ab")), Some(Ordering::Less));
10707 assert_eq!(bytes(b"a").python_cmp(&Scalar::Utf8("a".to_owned())), None);
10708 assert_ne!(bytes(b"a"), Scalar::Utf8("a".to_owned()));
10709 assert!(!bytes(b"").to_bool().unwrap());
10710 let json = serde_json::to_string(&bytes(b"hi")).unwrap();
10712 assert_eq!(json, r#"{"kind":"object","value":{"bytes":[104,105]}}"#);
10713 let back: Scalar = serde_json::from_str(&json).unwrap();
10714 assert_eq!(back, bytes(b"hi"));
10715 let list: Scalar =
10717 serde_json::from_str(r#"{"kind":"object","value":[{"kind":"int64","value":1}]}"#)
10718 .unwrap();
10719 assert_eq!(
10720 list,
10721 Scalar::Object(ObjectValue::list(vec![Scalar::Int64(1)]))
10722 );
10723 }
10724
10725 #[test]
10726 fn values_order_and_name_their_types_as_python_does_fvsao_71() {
10727 use std::cmp::Ordering;
10728
10729 use super::{HostValue, ObjectValue};
10730 let text = |value: &str| Scalar::Utf8(value.to_owned());
10731 let host =
10732 |name: &'static str| Scalar::Object(ObjectValue::Host(HostValue::new(Named(name))));
10733 let list = |items: Vec<Scalar>| Scalar::Object(ObjectValue::list(items));
10734 assert_eq!(
10737 Scalar::Bool(true).python_cmp(&Scalar::Float64(1.5)),
10738 Some(Ordering::Less)
10739 );
10740 assert_eq!(
10741 Scalar::Int64(2).python_cmp(&Scalar::Float64(2.0)),
10742 Some(Ordering::Equal)
10743 );
10744 assert_eq!(text("b").python_cmp(&text("a")), Some(Ordering::Greater));
10745 assert_eq!(
10746 Scalar::Datetime64(5).python_cmp(&Scalar::Datetime64(9)),
10747 Some(Ordering::Less)
10748 );
10749 let interval = |left: f64, right: f64| {
10750 Scalar::Interval(Interval::new(left, right, IntervalClosed::Right))
10751 };
10752 assert_eq!(
10753 interval(0.0, 5.0).python_cmp(&interval(0.0, 2.0)),
10754 Some(Ordering::Greater)
10755 );
10756 assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
10757 assert_eq!(text("a").python_cmp(&Scalar::Int64(1)), None);
10760 assert_eq!(
10761 Scalar::Datetime64(1).python_cmp(&Scalar::Timedelta64(1)),
10762 None
10763 );
10764 assert_eq!(host("a").python_cmp(&Scalar::Int64(1)), None);
10765 assert_eq!(host("!a").python_cmp(&host("b")), None);
10766 assert_eq!(text("a").python_type_name(), "str");
10770 assert_eq!(Scalar::Bool(true).python_type_name(), "bool");
10771 assert_eq!(Scalar::Datetime64(1).python_type_name(), "Timestamp");
10772 assert_eq!(list(vec![]).python_type_name(), "list");
10773 assert_eq!(host("a").python_type_name(), "object");
10774 let (left, right) = list(vec![Scalar::Int64(1), Scalar::Int64(2)])
10775 .python_cmp_type_names(&list(vec![Scalar::Int64(1), text("x")]));
10776 assert_eq!((left.as_str(), right.as_str()), ("int", "str"));
10777 let (left, right) = text("a").python_cmp_type_names(&list(vec![]));
10778 assert_eq!((left.as_str(), right.as_str()), ("str", "list"));
10779 }
10780
10781 #[test]
10782 fn object_cells_print_compare_and_hash_like_python_fvsao_33() {
10783 use std::hash::{Hash, Hasher};
10784
10785 use super::{HostValue, ObjectValue};
10786 let hash = |value: &ObjectValue| {
10787 let mut hasher = std::collections::hash_map::DefaultHasher::new();
10788 value.hash(&mut hasher);
10789 hasher.finish()
10790 };
10791 let list = ObjectValue::list(vec![
10792 Scalar::Int64(1),
10793 Scalar::Utf8("a".to_owned()),
10794 Scalar::Null(NullKind::Null),
10795 Scalar::Float64(2.0),
10796 Scalar::Object(ObjectValue::list(vec![Scalar::Utf8("b".to_owned())])),
10797 ]);
10798 assert_eq!(list.repr(), "[1, 'a', None, 2.0, ['b']]");
10801 assert_eq!(list.to_string(), "[1, 'a', None, 2.0, ['b']]");
10802 assert_eq!(list.pprint(), "[1, a, None, 2.0, [b]]");
10803 assert_eq!(Scalar::Object(list.clone()).dtype(), DType::Utf8);
10805 assert!(!Scalar::Object(list.clone()).is_missing());
10806 let same = ObjectValue::list(list.as_list().unwrap().to_vec());
10809 assert_eq!(list, same);
10810 assert_eq!(hash(&list), hash(&same));
10811 let other = ObjectValue::list(vec![Scalar::Int64(1)]);
10812 assert_ne!(list, other);
10813 let host = ObjectValue::Host(HostValue::new(Named("x")));
10814 assert_ne!(list, host);
10815 assert_eq!(host, ObjectValue::Host(HostValue::new(Named("x"))));
10817 assert_ne!(host, ObjectValue::Host(HostValue::new(Named("y"))));
10818 assert_eq!(host.repr(), "Named(\"x\")");
10819 assert_eq!(host.to_string(), "x");
10820 assert!(
10822 !Scalar::Object(ObjectValue::list(Vec::new()))
10823 .to_bool()
10824 .unwrap()
10825 );
10826 assert!(Scalar::Object(host.clone()).to_bool().unwrap());
10827 assert!(Scalar::Object(list.clone()).to_f64().is_err());
10829 let json = serde_json::to_string(&Scalar::Object(other.clone())).unwrap();
10832 assert_eq!(
10833 serde_json::from_str::<Scalar>(&json).unwrap(),
10834 Scalar::Object(other)
10835 );
10836 assert!(serde_json::to_string(&Scalar::Object(host)).is_err());
10837 }
10838
10839 #[test]
10840 fn a_host_cell_displays_by_its_pprint_and_stringifies_by_its_str() {
10841 use super::{HostValue, ObjectValue};
10842
10843 struct Pair;
10845 impl super::HostObject for Pair {
10846 fn host_eq(&self, _other: &dyn super::HostObject) -> bool {
10847 false
10848 }
10849 fn host_repr(&self) -> String {
10850 "('a', 1)".to_owned()
10851 }
10852 fn host_str(&self) -> String {
10853 "('a', 1)".to_owned()
10854 }
10855 fn host_pprint(&self) -> String {
10856 "(a, 1)".to_owned()
10857 }
10858 fn host_hash(&self) -> Option<u64> {
10859 None
10860 }
10861 fn host_cmp(&self, _other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
10862 None
10863 }
10864 fn as_any(&self) -> &dyn std::any::Any {
10865 self
10866 }
10867 }
10868 let pair = ObjectValue::Host(HostValue::new(Pair));
10869 assert_eq!(pair.pprint(), "(a, 1)");
10870 let list = ObjectValue::list(vec![Scalar::Object(pair.clone())]);
10872 assert_eq!(list.pprint(), "[(a, 1)]");
10873 assert_eq!(pair.to_string(), "('a', 1)");
10875 let named = ObjectValue::Host(HostValue::new(Named("x")));
10877 assert_eq!(named.pprint(), "x");
10878 }
10879
10880 #[test]
10881 fn float64_json_spells_infinity_and_round_trips() {
10882 let json = |s: &Scalar| serde_json::to_string(s).expect("serialize");
10886 let back = |text: &str| serde_json::from_str::<Scalar>(text);
10887 assert_eq!(
10888 json(&Scalar::Float64(f64::INFINITY)),
10889 r#"{"kind":"float64","value":"inf"}"#
10890 );
10891 assert_eq!(
10892 json(&Scalar::Float64(f64::NEG_INFINITY)),
10893 r#"{"kind":"float64","value":"-inf"}"#
10894 );
10895 assert_eq!(
10897 json(&Scalar::Float64(1.5)),
10898 r#"{"kind":"float64","value":1.5}"#
10899 );
10900 assert_eq!(
10901 json(&Scalar::Float64(-0.0)),
10902 r#"{"kind":"float64","value":-0.0}"#
10903 );
10904 assert_eq!(
10905 json(&Scalar::Float64(f64::NAN)),
10906 r#"{"kind":"float64","value":null}"#
10907 );
10908 for value in [f64::INFINITY, f64::NEG_INFINITY, 1.5, -2.25e300] {
10909 let scalar = Scalar::Float64(value);
10910 assert_eq!(back(&json(&scalar)).expect("round trip"), scalar);
10911 }
10912 let negative_zero = back(r#"{"kind":"float64","value":-0.0}"#).expect("-0.0");
10913 assert!(matches!(negative_zero, Scalar::Float64(v) if v == 0.0 && v.is_sign_negative()));
10914 assert!(matches!(
10915 back(r#"{"kind":"float64","value":null}"#).expect("null"),
10916 Scalar::Float64(v) if v.is_nan()
10917 ));
10918 assert!(back(r#"{"kind":"float64","value":"Infinity"}"#).is_err());
10920 assert!(back(r#"{"kind":"float64","value":"1.5"}"#).is_err());
10921 }
10922
10923 #[test]
10933 fn semantic_cmp_cross_numeric_int_float_cdpai() {
10934 use std::cmp::Ordering;
10937 let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
10938 let mut next = || {
10939 st = st
10940 .wrapping_mul(6_364_136_223_846_793_005)
10941 .wrapping_add(1_442_695_040_888_963_407);
10942 (st >> 33) as u32
10943 };
10944 for _ in 0..3000u32 {
10945 let i = (next() % 21) as i64 - 10;
10946 let f = (next() % 400) as f64 / 20.0 - 10.0; let exp = (i as f64).partial_cmp(&f).unwrap();
10948 assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
10949 assert_eq!(
10950 Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
10951 exp.reverse()
10952 );
10953 }
10954 assert_eq!(
10956 Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
10957 Ordering::Equal
10958 );
10959 assert_eq!(
10960 Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
10961 Ordering::Equal
10962 );
10963 assert_eq!(
10964 Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
10965 Ordering::Less
10966 );
10967 assert_eq!(
10968 Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
10969 Ordering::Greater
10970 );
10971 }
10972
10973 #[test]
10974 fn semantic_cmp_nat_degeneracy_temporal_767ak() {
10975 use std::cmp::Ordering;
10976 const NAT: i64 = i64::MIN;
10977
10978 let td_nat = Scalar::Timedelta64(NAT);
10980 for v in [-3i64, 0, 5, 99] {
10981 let td = Scalar::Timedelta64(v);
10982 assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
10983 assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
10984 }
10985 assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
10986
10987 let dt_nat = Scalar::Datetime64(NAT);
10989 for v in [-3i64, 0, 5, 99] {
10990 let dt = Scalar::Datetime64(v);
10991 assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
10992 assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
10993 }
10994 assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
10995
10996 for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
10998 let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
10999 assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
11000 assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
11002 let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
11003 assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
11004 }
11005 }
11006
11007 fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
11008 [
11009 Scalar::Null(NullKind::Null),
11010 Scalar::Bool(true),
11011 Scalar::Int64(-7),
11012 Scalar::Float64(3.5),
11013 Scalar::Utf8("mixed".to_owned()),
11014 Scalar::Timedelta64(11),
11015 Scalar::Datetime64(1_735_732_800_123_456_789),
11016 Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
11017 Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
11018 ]
11019 }
11020
11021 fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
11022 !matches!(
11023 (left, right),
11024 (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
11025 )
11026 }
11027
11028 #[test]
11029 fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
11030 let values = semantic_cmp_cross_variant_values_d5ikg();
11031 for (left_index, left) in values.iter().enumerate() {
11032 for (right_index, right) in values.iter().enumerate() {
11033 if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11034 {
11035 assert_eq!(
11036 left.semantic_cmp(right),
11037 format!("{left:?}").cmp(&format!("{right:?}")),
11038 "cross-variant order mismatch: {left:?} vs {right:?}"
11039 );
11040 }
11041 }
11042 }
11043 }
11044
11045 #[test]
11046 #[ignore = "foreground release attribution harness"]
11047 fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
11048 use std::cmp::Ordering;
11049
11050 const BATCH: usize = 4_096;
11051 const BLOCKS: usize = 9;
11052
11053 fn former(left: &Scalar, right: &Scalar) -> Ordering {
11054 format!("{left:?}").cmp(&format!("{right:?}"))
11055 }
11056
11057 fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
11058 left.semantic_cmp(right)
11059 }
11060
11061 fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
11062 let mut less = 0usize;
11063 let started = std::time::Instant::now();
11064 for _ in 0..BATCH {
11065 for (left_index, left) in values.iter().enumerate() {
11066 for (right_index, right) in values.iter().enumerate() {
11067 if left_index != right_index
11068 && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11069 && compare(std::hint::black_box(left), std::hint::black_box(right))
11070 == Ordering::Less
11071 {
11072 less += 1;
11073 }
11074 }
11075 }
11076 }
11077 std::hint::black_box(less);
11078 started.elapsed().as_nanos()
11079 }
11080
11081 fn median(samples: &mut [u128]) -> u128 {
11082 samples.sort_unstable();
11083 samples[samples.len() / 2]
11084 }
11085
11086 let values = semantic_cmp_cross_variant_values_d5ikg();
11087
11088 for (left_index, left) in values.iter().enumerate() {
11089 for (right_index, right) in values.iter().enumerate() {
11090 if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11091 {
11092 assert_eq!(
11093 former(left, right),
11094 candidate(left, right),
11095 "cross-variant order mismatch: {left:?} vs {right:?}"
11096 );
11097 }
11098 }
11099 }
11100
11101 std::hint::black_box(elapsed(&values, former));
11102 std::hint::black_box(elapsed(&values, candidate));
11103
11104 let mut former_samples = Vec::with_capacity(BLOCKS * 2);
11105 let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
11106 for block in 0..BLOCKS {
11107 if block.is_multiple_of(2) {
11108 former_samples.push(elapsed(&values, former));
11109 candidate_samples.push(elapsed(&values, candidate));
11110 candidate_samples.push(elapsed(&values, candidate));
11111 former_samples.push(elapsed(&values, former));
11112 } else {
11113 candidate_samples.push(elapsed(&values, candidate));
11114 former_samples.push(elapsed(&values, former));
11115 former_samples.push(elapsed(&values, former));
11116 candidate_samples.push(elapsed(&values, candidate));
11117 }
11118 }
11119
11120 let former_p50 = median(&mut former_samples);
11121 let candidate_p50 = median(&mut candidate_samples);
11122 eprintln!(
11123 "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
11124 former_p50 as f64 / candidate_p50 as f64
11125 );
11126 }
11127
11128 #[test]
11129 fn semantic_cmp_total_order_axioms_ay8o9() {
11130 use std::cmp::Ordering;
11131
11132 let mut state: u64 = 0xc0ff_eeba_df00_d123;
11133 let mut next = || {
11134 state = state
11135 .wrapping_mul(6_364_136_223_846_793_005)
11136 .wrapping_add(1_442_695_040_888_963_407);
11137 (state >> 33) as u32
11138 };
11139
11140 for iter in 0..6000u32 {
11141 let dt = next() % 4;
11142 let mk = |r: u32| match dt {
11144 0 => Scalar::Int64((r % 11) as i64 - 5),
11145 1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
11147 2 => Scalar::Utf8(format!("s{}", r % 5)),
11148 _ => Scalar::Bool(r.is_multiple_of(2)),
11149 };
11150 let a = mk(next());
11151 let b = mk(next());
11152 let c = mk(next());
11153 let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
11154
11155 assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
11157 assert_eq!(
11159 a.semantic_cmp(&b),
11160 b.semantic_cmp(&a).reverse(),
11161 "antisymmetric {ctx}"
11162 );
11163 let ab = a.semantic_cmp(&b);
11165 assert_eq!(
11166 a.semantic_le(&b),
11167 ab != Ordering::Greater,
11168 "le-consistent {ctx}"
11169 );
11170 assert_eq!(
11171 a.semantic_ge(&b),
11172 ab != Ordering::Less,
11173 "ge-consistent {ctx}"
11174 );
11175 assert_eq!(
11176 a.semantic_le(&b) && a.semantic_ge(&b),
11177 ab == Ordering::Equal,
11178 "le&ge<=>eq {ctx}"
11179 );
11180 if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
11182 assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
11183 }
11184 }
11185
11186 let nan = Scalar::Float64(f64::NAN);
11190 for v in [
11191 Scalar::Float64(-3.5),
11192 Scalar::Float64(0.0),
11193 Scalar::Float64(7.25),
11194 ] {
11195 assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
11196 assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
11197 }
11198 assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
11199 }
11200
11201 #[test]
11207 fn common_dtype_lattice_axioms_be314() {
11208 let all: [DType; 14] = [
11209 DType::Null,
11210 DType::Bool,
11211 DType::BoolNullable,
11212 DType::Int64,
11213 DType::Int64Nullable,
11214 DType::Float64,
11215 DType::Float64Nullable,
11218 DType::Utf8,
11219 DType::Categorical,
11220 DType::Timedelta64,
11221 DType::datetime64_naive(),
11222 DType::Period,
11223 DType::Interval,
11224 DType::Sparse,
11225 ];
11226
11227 for a in &all {
11228 assert_eq!(
11230 common_dtype(a.clone(), a.clone()),
11231 Ok(a.clone()),
11232 "idempotent {a:?}"
11233 );
11234 assert_eq!(
11236 common_dtype(DType::Null, a.clone()),
11237 Ok(a.clone()),
11238 "null-left identity {a:?}"
11239 );
11240 assert_eq!(
11241 common_dtype(a.clone(), DType::Null),
11242 Ok(a.clone()),
11243 "null-right identity {a:?}"
11244 );
11245
11246 for b in &all {
11247 assert_eq!(
11250 common_dtype(a.clone(), b.clone()).ok(),
11251 common_dtype(b.clone(), a.clone()).ok(),
11252 "commutative value {a:?},{b:?}"
11253 );
11254 assert_eq!(
11255 common_dtype(a.clone(), b.clone()).is_ok(),
11256 common_dtype(b.clone(), a.clone()).is_ok(),
11257 "commutative ok-ness {a:?},{b:?}"
11258 );
11259 }
11260 }
11261
11262 for a in &all {
11265 for b in &all {
11266 for c in &all {
11267 if let (Ok(ab), Ok(bc)) = (
11268 common_dtype(a.clone(), b.clone()),
11269 common_dtype(b.clone(), c.clone()),
11270 ) && let (Ok(left), Ok(right)) =
11271 (common_dtype(ab, c.clone()), common_dtype(a.clone(), bc))
11272 {
11273 assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
11274 }
11275 }
11276 }
11277 }
11278 }
11279
11280 #[test]
11283 fn infer_dtype_coercion_rules_e3sfq() {
11284 use DType::{Bool, Float64, Int64, Null, Utf8};
11285
11286 assert_eq!(infer_dtype(&[]), Ok(Null));
11288 assert_eq!(
11289 infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
11290 Ok(Null)
11291 );
11292
11293 let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
11295 let mut next = || {
11296 s = s
11297 .wrapping_mul(6_364_136_223_846_793_005)
11298 .wrapping_add(1_442_695_040_888_963_407);
11299 (s >> 33) as u32
11300 };
11301 for _ in 0..600u32 {
11302 let n = (next() % 6) as usize + 1;
11303 let ints: Vec<Scalar> = (0..n)
11304 .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
11305 .collect();
11306 assert_eq!(infer_dtype(&ints), Ok(Int64));
11307 let floats: Vec<Scalar> = (0..n)
11308 .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
11309 .collect();
11310 assert_eq!(infer_dtype(&floats), Ok(Float64));
11311 let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
11312 assert_eq!(infer_dtype(&bools), Ok(Bool));
11313 let strs: Vec<Scalar> = (0..n)
11314 .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
11315 .collect();
11316 assert_eq!(infer_dtype(&strs), Ok(Utf8));
11317 }
11318
11319 assert_eq!(
11321 infer_dtype(&[
11322 Scalar::Int64(1),
11323 Scalar::Null(NullKind::Null),
11324 Scalar::Int64(2)
11325 ]),
11326 Ok(Int64),
11327 "Int64 + nulls -> Int64"
11328 );
11329 assert_eq!(
11330 infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
11331 Ok(Float64),
11332 "Int64 + Float64 -> Float64"
11333 );
11334 assert_eq!(
11338 infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
11339 Ok(Utf8),
11340 "Bool + Int64 -> object bucket (pandas constructs object)"
11341 );
11342 assert_eq!(
11343 infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
11344 Ok(Utf8),
11345 "Utf8 + Int64 -> Utf8 (object fallback)"
11346 );
11347 }
11348
11349 #[test]
11354 fn missing_for_dtype_always_missing_1ews0() {
11355 let all: [DType; 14] = [
11356 DType::Null,
11357 DType::Bool,
11358 DType::BoolNullable,
11359 DType::Int64,
11360 DType::Int64Nullable,
11361 DType::Float64,
11362 DType::Float64Nullable,
11363 DType::Utf8,
11364 DType::Categorical,
11365 DType::Timedelta64,
11366 DType::datetime64_naive(),
11367 DType::Period,
11368 DType::Interval,
11369 DType::Sparse,
11370 ];
11371 for dt in &all {
11372 let m = Scalar::missing_for_dtype(dt.clone());
11373 assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
11374 for target in &all {
11375 let cast = cast_scalar(&m, target.clone()).expect("cast of missing");
11376 if target == &DType::Utf8 {
11377 assert!(
11380 matches!(cast, Scalar::Utf8(_)),
11381 "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
11382 );
11383 } else if matches!(dt, DType::Timedelta64 | DType::Datetime64 { .. })
11384 && matches!(target, DType::Bool | DType::Int64)
11385 {
11386 match target {
11402 DType::Bool => assert_eq!(
11403 cast,
11404 Scalar::Bool(true),
11405 "cast(missing {dt:?} -> Bool) is pandas' nonzero-truthy \
11406 read of the NaT bits"
11407 ),
11408 _ => assert_eq!(
11409 cast,
11410 Scalar::Int64(i64::MIN),
11411 "cast(missing {dt:?} -> Int64) is the NaT sentinel itself"
11412 ),
11413 }
11414 } else {
11415 assert!(
11418 cast.is_missing(),
11419 "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
11420 );
11421 }
11422 }
11423 }
11424 }
11425
11426 #[test]
11427 fn cast_scalar_bool_int_roundtrip_6w07b() {
11428 use super::cast_scalar;
11429 assert_eq!(
11431 cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
11432 Scalar::Int64(1)
11433 );
11434 assert_eq!(
11435 cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
11436 Scalar::Int64(0)
11437 );
11438 assert_eq!(
11439 cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
11440 Scalar::Bool(false)
11441 );
11442 let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
11443 let mut next = || {
11444 st = st
11445 .wrapping_mul(6_364_136_223_846_793_005)
11446 .wrapping_add(1_442_695_040_888_963_407);
11447 (st >> 33) as u32
11448 };
11449 for _ in 0..2000u32 {
11450 let v = (next() % 21) as i64 - 10;
11451 assert_eq!(
11452 cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
11453 Scalar::Bool(v != 0),
11454 "int->bool v={v}"
11455 );
11456 }
11457 }
11458
11459 #[test]
11461 fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
11462 use super::cast_scalar;
11463 let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
11466 let mut next = || {
11467 st = st
11468 .wrapping_mul(6_364_136_223_846_793_005)
11469 .wrapping_add(1_442_695_040_888_963_407);
11470 (st >> 33) as u32
11471 };
11472 for (f, exp) in [
11474 (-3.7, -3i64),
11475 (3.7, 3),
11476 (-3.2, -3),
11477 (3.2, 3),
11478 (-0.9, 0),
11479 (0.9, 0),
11480 (-5.0, -5),
11481 (5.0, 5),
11482 ] {
11483 assert_eq!(
11484 cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
11485 Scalar::Int64(exp),
11486 "cast {f}"
11487 );
11488 }
11489 for _ in 0..3000u32 {
11491 let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
11493 assert_eq!(
11494 got,
11495 Scalar::Int64(v.trunc() as i64),
11496 "trunc-toward-zero v={v}"
11497 );
11498 }
11499 }
11500
11501 #[test]
11510 fn cast_scalar_float_to_temporal_truncates_to_nanoseconds() {
11511 use super::{Timedelta, Timestamp, cast_scalar};
11512
11513 for (input, want) in [
11516 (1.5_f64, 1_i64),
11517 (-1.5, -1),
11518 (0.9, 0),
11519 (-0.9, 0),
11520 (2.5, 2),
11521 (-2.5, -2),
11522 (1.999_999, 1),
11523 (-1.999_999, -1),
11524 (2.0, 2),
11525 (1e18, 1_000_000_000_000_000_000),
11526 ] {
11527 assert_eq!(
11528 cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11529 Scalar::Datetime64(want),
11530 "datetime64 cast of {input}"
11531 );
11532 assert_eq!(
11533 cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11534 Scalar::Timedelta64(want),
11535 "timedelta64 cast of {input}"
11536 );
11537 }
11538
11539 for input in [
11543 f64::NAN,
11544 f64::INFINITY,
11545 f64::NEG_INFINITY,
11546 1e30,
11547 -1e30,
11548 9.3e18,
11549 -9.3e18,
11550 9_223_372_036_854_775_808.0, -9_223_372_036_854_775_808.0, ] {
11553 assert_eq!(
11554 cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11555 Scalar::Datetime64(Timestamp::NAT),
11556 "datetime64 cast of {input} must be NaT"
11557 );
11558 assert_eq!(
11559 cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11560 Scalar::Timedelta64(Timedelta::NAT),
11561 "timedelta64 cast of {input} must be NaT"
11562 );
11563 }
11564
11565 let just_inside = 9_223_372_036_854_774_784.0_f64; assert_eq!(
11569 cast_scalar(&Scalar::Float64(just_inside), DType::datetime64_naive()).unwrap(),
11570 Scalar::Datetime64(9_223_372_036_854_774_784),
11571 "the largest representable float must NOT be treated as NaT"
11572 );
11573
11574 assert_eq!(
11577 cast_scalar(&Scalar::Float64(1.5), DType::datetime64_naive()).unwrap(),
11578 Scalar::Datetime64(1)
11579 );
11580 assert_eq!(
11581 cast_scalar(&Scalar::Float64(1.5), DType::Int64).unwrap(),
11582 Scalar::Int64(1),
11583 "the SHARED cast truncates here too; it is the explicit constructor \
11584 that refuses, via Column::new's LossyFloatToInt pre-check"
11585 );
11586 }
11587
11588 #[test]
11593 fn cast_scalar_temporal_to_int64_is_raw_nanoseconds() {
11594 use super::{Timedelta, Timestamp, cast_scalar};
11595
11596 for nanos in [1_710_498_645_123_456_789_i64, 93_784_005_006_007, 0, -1] {
11599 assert_eq!(
11600 cast_scalar(&Scalar::Datetime64(nanos), DType::Int64).unwrap(),
11601 Scalar::Int64(nanos),
11602 "datetime64 -> int64 must be the raw nanos ({nanos})"
11603 );
11604 assert_eq!(
11605 cast_scalar(&Scalar::Timedelta64(nanos), DType::Int64).unwrap(),
11606 Scalar::Int64(nanos)
11607 );
11608 }
11609
11610 assert_eq!(
11616 cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Int64).unwrap(),
11617 Scalar::Int64(i64::MIN),
11618 "NaT -> int64 is the sentinel i64::MIN, not a missing value"
11619 );
11620 assert_eq!(
11621 cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Int64).unwrap(),
11622 Scalar::Int64(i64::MIN)
11623 );
11624
11625 for target in [DType::Int64Nullable, DType::Float64, DType::Float64Nullable] {
11634 assert!(
11635 cast_scalar(
11636 &Scalar::Datetime64(1_710_498_645_123_456_789),
11637 target.clone()
11638 )
11639 .is_err(),
11640 "datetime64 -> {target:?} must stay refused"
11641 );
11642 assert!(
11643 cast_scalar(&Scalar::Timedelta64(93_784_005_006_007), target.clone()).is_err(),
11644 "timedelta64 -> {target:?} must stay refused"
11645 );
11646 }
11647
11648 for (flag, want) in [(true, 1_i64), (false, 0)] {
11650 assert_eq!(
11651 cast_scalar(&Scalar::Bool(flag), DType::datetime64_naive()).unwrap(),
11652 Scalar::Datetime64(want)
11653 );
11654 assert_eq!(
11655 cast_scalar(&Scalar::Bool(flag), DType::Timedelta64).unwrap(),
11656 Scalar::Timedelta64(want)
11657 );
11658 }
11659 }
11660
11661 #[test]
11665 fn timestamp_string_resolution_and_formatting_match_pandas() {
11666 use super::{DatetimeStringResolution as Res, Timestamp};
11667
11668 const MIDNIGHT: i64 = 1_710_460_800_000_000_000; assert_eq!(Timestamp::string_resolution(MIDNIGHT), Res::Date);
11672 assert_eq!(
11673 Timestamp::string_resolution(MIDNIGHT + 37_845_000_000_000),
11674 Res::Second
11675 );
11676 assert_eq!(
11677 Timestamp::string_resolution(MIDNIGHT + 37_845_123_000_000),
11678 Res::Milli
11679 );
11680 assert_eq!(
11681 Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_000),
11682 Res::Micro
11683 );
11684 assert_eq!(
11685 Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_789),
11686 Res::Nano
11687 );
11688 assert_eq!(
11690 Timestamp::string_resolution(MIDNIGHT + 300_000_000_000),
11691 Res::Second
11692 );
11693 assert_eq!(Timestamp::string_resolution(Timestamp::NAT), Res::Date);
11696
11697 assert!(Res::Date < Res::Second);
11699 assert!(Res::Second < Res::Milli);
11700 assert!(Res::Milli < Res::Micro);
11701 assert!(Res::Micro < Res::Nano);
11702
11703 let value = MIDNIGHT + 37_845_123_456_789;
11705 assert_eq!(
11706 Timestamp::format_at_resolution(value, Res::Date),
11707 "2024-03-15"
11708 );
11709 assert_eq!(
11710 Timestamp::format_at_resolution(value, Res::Second),
11711 "2024-03-15 10:30:45"
11712 );
11713 assert_eq!(
11714 Timestamp::format_at_resolution(value, Res::Milli),
11715 "2024-03-15 10:30:45.123"
11716 );
11717 assert_eq!(
11718 Timestamp::format_at_resolution(value, Res::Micro),
11719 "2024-03-15 10:30:45.123456"
11720 );
11721 assert_eq!(
11722 Timestamp::format_at_resolution(value, Res::Nano),
11723 "2024-03-15 10:30:45.123456789"
11724 );
11725
11726 assert_eq!(
11729 Timestamp::format_at_resolution(MIDNIGHT, Res::Nano),
11730 "2024-03-15 00:00:00.000000000"
11731 );
11732
11733 assert_eq!(
11735 Timestamp::format_at_resolution(MIDNIGHT, Res::Second),
11736 "2024-03-15 00:00:00"
11737 );
11738
11739 for resolution in [Res::Date, Res::Second, Res::Milli, Res::Micro, Res::Nano] {
11741 assert_eq!(
11742 Timestamp::format_at_resolution(Timestamp::NAT, resolution),
11743 "NaT"
11744 );
11745 }
11746
11747 assert_eq!(
11750 Timestamp::format_at_resolution(-1, Res::Nano),
11751 "1969-12-31 23:59:59.999999999"
11752 );
11753
11754 assert_eq!(
11756 Timestamp::format_at_resolution(-9_223_372_036_854_775_806, Res::Nano),
11757 "1677-09-21 00:12:43.145224194"
11758 );
11759 assert_eq!(
11760 Timestamp::format_at_resolution(9_223_372_036_854_775_807, Res::Nano),
11761 "2262-04-11 23:47:16.854775807"
11762 );
11763 }
11764
11765 #[test]
11769 fn cast_scalar_temporal_to_bool_is_nonzero_on_the_nanos() {
11770 use super::{Timedelta, Timestamp, cast_scalar};
11771
11772 for (nanos, want) in [
11774 (0_i64, false),
11775 (1_710_498_645_123_456_789, true),
11776 (-1, true),
11777 (86_400_000_000_000, true),
11778 (1, true),
11779 ] {
11780 assert_eq!(
11781 cast_scalar(&Scalar::Datetime64(nanos), DType::Bool).unwrap(),
11782 Scalar::Bool(want),
11783 "datetime64 {nanos} -> bool"
11784 );
11785 assert_eq!(
11786 cast_scalar(&Scalar::Timedelta64(nanos), DType::Bool).unwrap(),
11787 Scalar::Bool(want),
11788 "timedelta64 {nanos} -> bool"
11789 );
11790 }
11791
11792 assert_eq!(
11796 cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Bool).unwrap(),
11797 Scalar::Bool(true),
11798 "NaT -> bool is true in pandas, not a missing value"
11799 );
11800 assert_eq!(
11801 cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Bool).unwrap(),
11802 Scalar::Bool(true)
11803 );
11804
11805 for nanos in [0_i64, 1, -1, 1_710_498_645_123_456_789] {
11816 assert!(
11817 cast_scalar(&Scalar::Datetime64(nanos), DType::BoolNullable).is_err(),
11818 "datetime64 {nanos} -> nullable boolean must stay refused"
11819 );
11820 assert!(
11821 cast_scalar(&Scalar::Timedelta64(nanos), DType::BoolNullable).is_err(),
11822 "timedelta64 {nanos} -> nullable boolean must stay refused"
11823 );
11824 }
11825 }
11826
11827 #[test]
11828 fn nancount_nunique_prod_any_all_mx60x() {
11829 use super::{nanall, nanany, nancount, nannunique, nanprod};
11830 let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
11833 let mut next = || {
11834 s = s
11835 .wrapping_mul(6_364_136_223_846_793_005)
11836 .wrapping_add(1_442_695_040_888_963_407);
11837 (s >> 33) as u32
11838 };
11839 let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
11840 let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
11841 for iter in 0..1000u32 {
11842 let n = (next() % 10) as usize + 1;
11843 let raw: Vec<f64> = (0..n)
11844 .map(|_| {
11845 if next() % 4 == 0 {
11846 f64::NAN
11847 } else {
11848 (next() % 5) as f64
11849 }
11850 })
11851 .collect();
11852 let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
11853 if finite.is_empty() {
11854 continue;
11855 }
11856 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
11857 let distinct: std::collections::HashSet<u64> =
11858 finite.iter().map(|x| x.to_bits()).collect();
11859 let prod: f64 = finite.iter().product();
11860 assert!(
11861 (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
11862 "nancount iter={iter}"
11863 );
11864 assert!(
11865 (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
11866 "nannunique iter={iter}"
11867 );
11868 assert!(
11869 (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
11870 "nanprod iter={iter}"
11871 );
11872 assert_eq!(
11873 asb(nanany(&scalars)),
11874 finite.iter().any(|&x| x != 0.0),
11875 "nanany iter={iter}"
11876 );
11877 assert_eq!(
11878 asb(nanall(&scalars)),
11879 finite.iter().all(|&x| x != 0.0),
11880 "nanall iter={iter}"
11881 );
11882 }
11883 }
11884
11885 #[test]
11886 fn nan_reduction_kernels_skip_correctness_1uagc() {
11887 use super::{nanmax, nanmedian, nanmin, nansum};
11888 let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
11891 let mut next = || {
11892 s = s
11893 .wrapping_mul(6_364_136_223_846_793_005)
11894 .wrapping_add(1_442_695_040_888_963_407);
11895 (s >> 33) as u32
11896 };
11897 let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
11898 for iter in 0..1000u32 {
11899 let n = (next() % 12) as usize + 1;
11900 let raw: Vec<f64> = (0..n)
11901 .map(|_| {
11902 if next() % 4 == 0 {
11903 f64::NAN
11904 } else {
11905 (next() % 200) as f64 - 100.0
11906 }
11907 })
11908 .collect();
11909 let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
11910 if finite.is_empty() {
11911 continue;
11912 }
11913 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
11914 let sum: f64 = finite.iter().sum();
11915 let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
11916 let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
11917 finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
11918 let m = finite.len();
11919 let med = if m % 2 == 1 {
11920 finite[m / 2]
11921 } else {
11922 (finite[m / 2 - 1] + finite[m / 2]) / 2.0
11923 };
11924 assert!(
11925 (val(nansum(&scalars)) - sum).abs() < 1e-7,
11926 "nansum iter={iter}"
11927 );
11928 assert!(
11929 (val(nanmin(&scalars)) - mn).abs() < 1e-9,
11930 "nanmin iter={iter}"
11931 );
11932 assert!(
11933 (val(nanmax(&scalars)) - mx).abs() < 1e-9,
11934 "nanmax iter={iter}"
11935 );
11936 assert!(
11937 (val(nanmedian(&scalars)) - med).abs() < 1e-9,
11938 "nanmedian iter={iter}"
11939 );
11940 }
11941 }
11942
11943 #[test]
11944 fn nanvar_ddof_nanstd_nan_skip_p00ag() {
11945 use super::{nanmean, nanstd, nanvar};
11946 let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
11949 let mut next = || {
11950 s = s
11951 .wrapping_mul(6_364_136_223_846_793_005)
11952 .wrapping_add(1_442_695_040_888_963_407);
11953 (s >> 33) as u32
11954 };
11955 let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
11956 for iter in 0..1000u32 {
11957 let n = (next() % 10) as usize + 2;
11958 let raw: Vec<f64> = (0..n)
11959 .map(|_| {
11960 if next() % 4 == 0 {
11961 f64::NAN
11962 } else {
11963 (next() % 200) as f64 / 7.0
11964 }
11965 })
11966 .collect();
11967 let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
11968 if finite.len() < 2 {
11969 continue;
11970 }
11971 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
11972 let nf = finite.len() as f64;
11973 let mean = finite.iter().sum::<f64>() / nf;
11974 let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
11975 assert!(
11976 (val(nanmean(&scalars)) - mean).abs() < 1e-7,
11977 "nanmean iter={iter}"
11978 );
11979 assert!(
11980 (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
11981 "nanvar ddof0 iter={iter}"
11982 );
11983 assert!(
11984 (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
11985 "nanvar ddof1 iter={iter}"
11986 );
11987 assert!(
11988 (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
11989 "nanstd ddof1 iter={iter}"
11990 );
11991 }
11992 }
11993
11994 #[test]
11995 fn nanskew_nankurt_min_sample_and_known_xybnq() {
11996 use super::{nankurt, nanskew};
11999 let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
12000 let val = |s: Scalar| -> Option<f64> {
12001 if s.is_missing() {
12002 None
12003 } else {
12004 s.to_f64().ok()
12005 }
12006 };
12007
12008 assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
12010 let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
12011 assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
12012 let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
12013 assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
12014
12015 assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
12017 let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
12018 assert!(
12019 (k - (-1.2)).abs() < 1e-6,
12020 "pandas kurt([1..5]) == -1.2, got {k}"
12021 );
12022 }
12023
12024 #[test]
12025 #[ignore = "foreground release attribution harness"]
12026 fn nanskew_fused_moment_scan_ab_mavln() {
12027 const ROWS: usize = 100_000;
12028 const BATCH: usize = 8;
12029
12030 fn former(values: &[Scalar]) -> Scalar {
12031 let nums = super::collect_finite(values);
12032 let n = nums.len() as f64;
12033 if n < 3.0 {
12034 return Scalar::Null(NullKind::NaN);
12035 }
12036 let mean = nums.iter().sum::<f64>() / n;
12037 let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12038 let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
12039 let s2 = m2 / (n - 1.0);
12040 if s2 == 0.0 {
12041 return Scalar::Float64(0.0);
12042 }
12043 let s3 = s2.powf(1.5);
12044 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
12045 }
12046
12047 fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12048 match (former, candidate) {
12049 (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12050 (a, b) => assert_eq!(a, b),
12051 }
12052 }
12053
12054 fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
12055 std::hint::black_box(skew(std::hint::black_box(values)));
12056 let started = std::time::Instant::now();
12057 for _ in 0..BATCH {
12058 std::hint::black_box(skew(std::hint::black_box(values)));
12059 }
12060 started.elapsed().as_nanos()
12061 }
12062
12063 fn median(samples: &mut [u128]) -> u128 {
12064 samples.sort_unstable();
12065 samples[samples.len() / 2]
12066 }
12067
12068 for values in [
12069 vec![],
12070 vec![Scalar::Int64(1), Scalar::Int64(2)],
12071 vec![Scalar::Int64(7); 16],
12072 vec![
12073 Scalar::Int64(-3),
12074 Scalar::Null(NullKind::NaN),
12075 Scalar::Float64(2.5),
12076 Scalar::Utf8("skip".to_owned()),
12077 Scalar::Int64(11),
12078 ],
12079 ] {
12080 assert_bits_eq(former(&values), super::nanskew(&values));
12081 }
12082
12083 let values = (0..ROWS)
12084 .map(|i| {
12085 if i % 257 == 0 {
12086 Scalar::Null(NullKind::NaN)
12087 } else {
12088 Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12089 }
12090 })
12091 .collect::<Vec<_>>();
12092 assert_bits_eq(former(&values), super::nanskew(&values));
12093
12094 for _ in 0..2 {
12095 std::hint::black_box(elapsed(&values, former));
12096 std::hint::black_box(elapsed(&values, super::nanskew));
12097 }
12098
12099 let mut former_samples = Vec::with_capacity(18);
12100 let mut candidate_samples = Vec::with_capacity(18);
12101 for block in 0_usize..9 {
12102 if block.is_multiple_of(2) {
12103 former_samples.push(elapsed(&values, former));
12104 candidate_samples.push(elapsed(&values, super::nanskew));
12105 candidate_samples.push(elapsed(&values, super::nanskew));
12106 former_samples.push(elapsed(&values, former));
12107 } else {
12108 candidate_samples.push(elapsed(&values, super::nanskew));
12109 former_samples.push(elapsed(&values, former));
12110 former_samples.push(elapsed(&values, former));
12111 candidate_samples.push(elapsed(&values, super::nanskew));
12112 }
12113 }
12114
12115 let former_p50 = median(&mut former_samples);
12116 let candidate_p50 = median(&mut candidate_samples);
12117 eprintln!(
12118 "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12119 former_p50 as f64 / candidate_p50 as f64,
12120 );
12121 eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
12122 eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12123 }
12124
12125 #[test]
12126 #[ignore = "foreground performance probe"]
12127 fn nankurt_fused_moment_scan_ab_idka7() {
12128 const ROWS: usize = 65_536;
12129 const BATCH: usize = 4;
12130
12131 fn former(values: &[Scalar]) -> Scalar {
12132 let nums = super::collect_finite(values);
12133 let n = nums.len() as f64;
12134 if n < 4.0 {
12135 return Scalar::Null(NullKind::NaN);
12136 }
12137 let mean = nums.iter().sum::<f64>() / n;
12138 let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12139 let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
12140 let s2 = m2 / (n - 1.0);
12141 if s2 == 0.0 {
12142 return Scalar::Float64(0.0);
12143 }
12144 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
12145 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
12146 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
12147 }
12148
12149 fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12150 match (former, candidate) {
12151 (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12152 (a, b) => assert_eq!(a, b),
12153 }
12154 }
12155
12156 fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
12157 let started = std::time::Instant::now();
12158 for _ in 0..BATCH {
12159 std::hint::black_box(kurt(std::hint::black_box(values)));
12160 }
12161 started.elapsed().as_nanos()
12162 }
12163
12164 fn median(samples: &mut [u128]) -> u128 {
12165 samples.sort_unstable();
12166 samples[samples.len() / 2]
12167 }
12168
12169 for values in [
12170 vec![],
12171 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12172 vec![Scalar::Int64(7); 16],
12173 vec![
12174 Scalar::Int64(-3),
12175 Scalar::Null(NullKind::NaN),
12176 Scalar::Float64(2.5),
12177 Scalar::Utf8("skip".to_owned()),
12178 Scalar::Int64(11),
12179 Scalar::Float64(-7.25),
12180 ],
12181 ] {
12182 assert_bits_eq(former(&values), super::nankurt(&values));
12183 }
12184
12185 let values = (0..ROWS)
12186 .map(|i| {
12187 if i % 257 == 0 {
12188 Scalar::Null(NullKind::NaN)
12189 } else {
12190 Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12191 }
12192 })
12193 .collect::<Vec<_>>();
12194 assert_bits_eq(former(&values), super::nankurt(&values));
12195
12196 for _ in 0..2 {
12197 std::hint::black_box(elapsed(&values, former));
12198 std::hint::black_box(elapsed(&values, super::nankurt));
12199 }
12200
12201 let mut former_samples = Vec::with_capacity(10);
12202 let mut candidate_samples = Vec::with_capacity(10);
12203 for block in 0_usize..5 {
12204 if block.is_multiple_of(2) {
12205 former_samples.push(elapsed(&values, former));
12206 candidate_samples.push(elapsed(&values, super::nankurt));
12207 candidate_samples.push(elapsed(&values, super::nankurt));
12208 former_samples.push(elapsed(&values, former));
12209 } else {
12210 candidate_samples.push(elapsed(&values, super::nankurt));
12211 former_samples.push(elapsed(&values, former));
12212 former_samples.push(elapsed(&values, former));
12213 candidate_samples.push(elapsed(&values, super::nankurt));
12214 }
12215 }
12216
12217 let former_p50 = median(&mut former_samples);
12218 let candidate_p50 = median(&mut candidate_samples);
12219 eprintln!(
12220 "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12221 former_p50 as f64 / candidate_p50 as f64,
12222 );
12223 eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
12224 eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12225 }
12226
12227 #[test]
12230 fn cast_scalar_to_utf8_formatting_yes7i() {
12231 let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
12234 let mut next = || {
12235 st = st
12236 .wrapping_mul(6_364_136_223_846_793_005)
12237 .wrapping_add(1_442_695_040_888_963_407);
12238 (st >> 33) as u32
12239 };
12240 for _ in 0..3000u32 {
12241 let n = (next() % 4_000_001) as i64 - 2_000_000;
12242 assert_eq!(
12243 cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
12244 Scalar::Utf8(n.to_string())
12245 );
12246 }
12247 assert_eq!(
12248 cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
12249 Scalar::Utf8("True".to_string())
12250 );
12251 assert_eq!(
12252 cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
12253 Scalar::Utf8("False".to_string())
12254 );
12255 }
12256
12257 #[test]
12258 fn cast_scalar_coercion_rules_6a83t() {
12259 let mut state: u64 = 0x5a17_c0de_1234_abcd;
12260 let mut next = || {
12261 state = state
12262 .wrapping_mul(6_364_136_223_846_793_005)
12263 .wrapping_add(1_442_695_040_888_963_407);
12264 (state >> 33) as u32
12265 };
12266
12267 for _ in 0..4000u32 {
12268 let n = (next() % 21) as i64 - 10; let b = next() % 2 == 0;
12270 let f = f64::from((next() % 41) as i32 - 20) / 4.0; let i = Scalar::Int64(n);
12273 let bo = Scalar::Bool(b);
12274 let fl = Scalar::Float64(f);
12275
12276 assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
12278 assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
12279 assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
12280
12281 assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
12283 assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
12284
12285 assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
12287 assert_eq!(
12288 cast_scalar(&i, DType::Float64),
12289 Ok(Scalar::Float64(n as f64))
12290 );
12291
12292 assert_eq!(
12294 cast_scalar(&bo, DType::Int64),
12295 Ok(Scalar::Int64(i64::from(b)))
12296 );
12297 assert_eq!(
12298 cast_scalar(&bo, DType::Float64),
12299 Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
12300 );
12301
12302 assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
12304 }
12305 }
12306
12307 #[test]
12309 fn scalar_from_primitive_types() {
12310 assert_eq!(Scalar::from(true), Scalar::Bool(true));
12312 assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
12313 assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
12314 assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
12315 assert_eq!(
12316 Scalar::from(String::from("world")),
12317 Scalar::Utf8("world".to_owned())
12318 );
12319
12320 let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
12324 assert_eq!(mixed[0], Scalar::Int64(1));
12325 assert_eq!(mixed[1], Scalar::Float64(2.0));
12326 assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
12327 }
12328
12329 #[test]
12330 fn dtype_inference_routes_bool_numeric_mix_to_object_bucket_rh1od() {
12331 let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
12336 assert_eq!(
12337 infer_dtype(&values).expect("dtype should infer"),
12338 DType::Utf8
12339 );
12340 }
12341
12342 #[test]
12343 fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
12344 let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
12345 let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
12346 assert_eq!(left.dtype(), DType::Interval);
12347 assert!(!left.is_missing());
12348 assert_eq!(
12349 infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
12350 DType::Interval
12351 );
12352 assert_eq!(
12353 common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
12354 DType::Interval
12355 );
12356 assert_eq!(
12357 cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
12358 Scalar::Null(NullKind::Null)
12359 );
12360 assert_eq!(
12361 cast_scalar(&left, DType::Utf8).expect("interval string cast"),
12362 Scalar::Utf8("(0.0, 1.0]".to_owned())
12363 );
12364 assert_eq!(
12365 super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
12366 Scalar::Int64(2)
12367 );
12368 }
12369
12370 #[test]
12371 fn cast_scalar_parses_temporal_extension_strings_avm08() {
12372 let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
12373 .expect("timestamp parse")
12374 .nanos;
12375 assert_eq!(
12376 cast_scalar(
12377 &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
12378 DType::datetime64_naive()
12379 )
12380 .expect("datetime cast"),
12381 Scalar::Datetime64(expected_nanos)
12382 );
12383 assert_eq!(
12384 cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
12385 Scalar::Period(Period::new(216, PeriodFreq::Quarterly))
12386 );
12387 assert_eq!(
12388 cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
12389 .expect("interval cast"),
12390 Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
12391 );
12392 }
12393
12394 #[test]
12395 fn missing_values_get_target_missing_marker() {
12396 let missing = Scalar::Null(NullKind::Null);
12397 let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
12398 assert_eq!(cast, Scalar::Null(NullKind::NaN));
12399 }
12400
12401 #[test]
12402 fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
12403 let cases = [
12404 (Scalar::Bool(true), "True"),
12405 (Scalar::Bool(false), "False"),
12406 (Scalar::Int64(-7), "-7"),
12407 (Scalar::Float64(1.0), "1.0"),
12408 (Scalar::Float64(1.5), "1.5"),
12409 (Scalar::Float64(f64::NAN), "nan"),
12410 (Scalar::Null(NullKind::Null), "None"),
12411 (Scalar::Null(NullKind::NaN), "nan"),
12412 (Scalar::Null(NullKind::NaT), "NaT"),
12413 ];
12414
12415 for (value, expected) in cases {
12416 assert_eq!(
12417 cast_scalar(&value, DType::Utf8).expect("cast"),
12418 Scalar::Utf8(expected.to_owned())
12419 );
12420 }
12421 }
12422
12423 #[test]
12424 fn semantic_eq_treats_nan_as_equal() {
12425 let left = Scalar::Float64(f64::NAN);
12426 let right = Scalar::Null(NullKind::NaN);
12427 assert!(left.semantic_eq(&right));
12428 }
12429
12430 #[test]
12431 fn semantic_eq_treats_nan_as_missing_null() {
12432 let left = Scalar::Float64(f64::NAN);
12433 let right = Scalar::Null(NullKind::Null);
12434 assert!(left.semantic_eq(&right));
12435 }
12436
12437 #[test]
12456 fn semantic_eq_unifies_dtype_sentinel_missing_with_null_xwxci() {
12457 for sentinel in [
12458 Scalar::Timedelta64(Timedelta::NAT),
12459 Scalar::Datetime64(Timestamp::NAT),
12460 Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
12461 ] {
12462 assert!(sentinel.is_missing(), "{sentinel:?} must report missing");
12463 for marker in [
12464 Scalar::Null(NullKind::Null),
12465 Scalar::Null(NullKind::NaN),
12466 Scalar::Null(NullKind::NaT),
12467 ] {
12468 assert!(
12469 sentinel.semantic_eq(&marker),
12470 "{sentinel:?} vs {marker:?} are both missing"
12471 );
12472 assert!(marker.semantic_eq(&sentinel), "and symmetrically");
12473 }
12474 }
12475
12476 let present = Scalar::Timedelta64(-60);
12478 assert!(!Scalar::Timedelta64(Timedelta::NAT).semantic_eq(&present));
12479 assert!(!present.semantic_eq(&Scalar::Null(NullKind::Null)));
12480 assert!(!present.semantic_eq(&Scalar::Timedelta64(-61)));
12482 }
12483
12484 #[test]
12485 fn common_dtype_rejects_string_numeric_mix() {
12486 let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
12487 assert_eq!(
12488 err.to_string(),
12489 "dtype coercion from Utf8 to Int64 has no compatible common type"
12490 );
12491 let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
12492 assert_eq!(
12493 err.to_string(),
12494 "dtype coercion from Float64 to Utf8 has no compatible common type"
12495 );
12496 }
12497
12498 #[test]
12499 fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
12500 let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
12501
12502 assert_eq!(dtype.value_dtype, DType::Float64);
12503 assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
12504 }
12505
12506 #[test]
12507 fn sparse_dtype_rejects_sparse_value_dtype() {
12508 let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
12509
12510 assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
12511 }
12512
12513 #[test]
12514 fn common_dtype_rejects_sparse_dense_mix() {
12515 let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
12516
12517 assert_eq!(
12518 err.to_string(),
12519 "dtype coercion from Sparse to Int64 has no compatible common type"
12520 );
12521 }
12522
12523 #[test]
12526 fn nullable_int64_promotion_matrix() {
12527 assert_eq!(
12529 common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
12530 DType::Int64Nullable
12531 );
12532 assert_eq!(
12533 common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
12534 DType::Int64Nullable
12535 );
12536
12537 assert_eq!(
12544 common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
12545 DType::Float64Nullable
12546 );
12547 assert_eq!(
12548 common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
12549 DType::Float64Nullable
12550 );
12551
12552 assert_eq!(
12554 common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
12555 DType::Int64Nullable
12556 );
12557
12558 assert_eq!(
12560 common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
12561 DType::Int64Nullable
12562 );
12563
12564 assert_eq!(
12566 common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
12567 DType::Int64Nullable
12568 );
12569 }
12570
12571 #[test]
12572 fn nullable_bool_promotion_matrix() {
12573 assert_eq!(
12575 common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
12576 DType::BoolNullable
12577 );
12578 assert_eq!(
12579 common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
12580 DType::BoolNullable
12581 );
12582
12583 assert_eq!(
12590 common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
12591 DType::Float64Nullable
12592 );
12593
12594 assert_eq!(
12597 common_dtype(DType::Bool, DType::Float64).unwrap(),
12598 DType::Float64
12599 );
12600 }
12601
12602 #[test]
12603 fn dtype_is_nullable_helper() {
12604 assert!(DType::Int64Nullable.is_nullable());
12605 assert!(DType::BoolNullable.is_nullable());
12606 assert!(!DType::Int64.is_nullable());
12607 assert!(!DType::Bool.is_nullable());
12608 assert!(!DType::Float64.is_nullable());
12609 assert!(!DType::Utf8.is_nullable());
12610 }
12611
12612 #[test]
12613 fn dtype_to_nullable_conversions() {
12614 assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
12615 assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
12616 assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
12626 assert_eq!(
12627 DType::Float64Nullable.to_nullable(),
12628 DType::Float64Nullable,
12629 "idempotent: already nullable"
12630 );
12631 assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
12632 }
12633
12634 #[test]
12635 fn dtype_to_non_nullable_conversions() {
12636 assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
12637 assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
12638 assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
12640 }
12641
12642 #[test]
12643 fn nullable_dtype_name_reports_pandas_style() {
12644 assert_eq!(DType::Int64.name(), "int64");
12645 assert_eq!(DType::Int64Nullable.name(), "Int64"); assert_eq!(DType::Bool.name(), "bool");
12647 assert_eq!(DType::BoolNullable.name(), "boolean");
12648 }
12649
12650 #[test]
12651 fn cast_scalar_int64_nullable_identity() {
12652 let val = Scalar::Int64(42);
12653 let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
12655 assert_eq!(result, Scalar::Int64(42));
12656
12657 let result2 = cast_scalar(&val, DType::Int64).unwrap();
12659 assert_eq!(result2, Scalar::Int64(42));
12660 }
12661
12662 #[test]
12663 fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
12664 let cases: &[(f64, &str)] = &[
12669 (1.0, "1.0"),
12670 (2.5, "2.5"),
12671 (100.0, "100.0"),
12672 (0.1, "0.1"),
12673 (0.0001, "0.0001"),
12674 (1e16, "1e+16"),
12675 (1e20, "1e+20"),
12676 (1e-5, "1e-05"),
12677 (1e-7, "1e-07"),
12678 (f64::INFINITY, "inf"),
12679 (f64::NEG_INFINITY, "-inf"),
12680 ];
12681 for (v, expected) in cases {
12682 assert_eq!(
12683 cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
12684 Scalar::Utf8((*expected).to_owned()),
12685 "float {v} -> str"
12686 );
12687 }
12688 }
12689
12690 fn float_to_string_for_astype_former(value: f64) -> String {
12691 if value.is_nan() {
12692 return "nan".to_owned();
12693 }
12694 if value.is_infinite() {
12695 return value.to_string();
12696 }
12697 let rendered = format!("{value:?}");
12698 match rendered.split_once('e') {
12699 None => rendered,
12700 Some((mantissa, exponent)) => {
12701 let (sign, digits) = match exponent.strip_prefix('-') {
12702 Some(digits) => ('-', digits),
12703 None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
12704 };
12705 format!("{mantissa}e{sign}{digits:0>2}")
12706 }
12707 }
12708 }
12709
12710 fn scientific_astype_values(len: usize) -> Vec<f64> {
12711 const EXPONENTS: [i32; 16] = [
12712 -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
12713 ];
12714 (0..len)
12715 .map(|position| {
12716 let mantissa = 1.0 + (position % 997) as f64 / 997.0;
12717 let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
12718 if position.is_multiple_of(2) {
12719 magnitude
12720 } else {
12721 -magnitude
12722 }
12723 })
12724 .collect()
12725 }
12726
12727 #[test]
12728 fn float_to_string_for_astype_in_place_matches_former() {
12729 let fixed = [
12730 f64::NAN,
12731 f64::INFINITY,
12732 f64::NEG_INFINITY,
12733 0.0,
12734 -0.0,
12735 f64::MIN_POSITIVE,
12736 f64::MAX,
12737 f64::MIN,
12738 1e16,
12739 -1e16,
12740 1e-5,
12741 -1e-5,
12742 1.234_567_890_123_456_8e20,
12743 -9.876_543_210_987_654e-123,
12744 ];
12745 for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
12746 assert_eq!(
12747 super::float_to_string_for_astype(value),
12748 float_to_string_for_astype_former(value),
12749 "value={value:?}"
12750 );
12751 }
12752 }
12753
12754 #[test]
12755 #[ignore = "foreground performance probe"]
12756 fn float_to_string_for_astype_in_place_ab() {
12757 use std::time::Instant;
12758
12759 const VALUES: usize = 16_384;
12760 const SAMPLES: usize = 10;
12761 let values = scientific_astype_values(VALUES);
12762 for &value in &values {
12763 let former = float_to_string_for_astype_former(value);
12764 assert!(former.contains('e'), "benchmark value must be scientific");
12765 assert_eq!(super::float_to_string_for_astype(value), former);
12766 }
12767
12768 for _ in 0..2 {
12769 for &value in &values {
12770 std::hint::black_box(float_to_string_for_astype_former(value));
12771 std::hint::black_box(super::float_to_string_for_astype(value));
12772 }
12773 }
12774
12775 let mut former_ns = Vec::with_capacity(SAMPLES);
12776 let mut public_ns = Vec::with_capacity(SAMPLES);
12777 for sample in 0..SAMPLES {
12778 let run = |formatter: fn(f64) -> String| {
12779 let started = Instant::now();
12780 for &value in std::hint::black_box(&values) {
12781 std::hint::black_box(formatter(std::hint::black_box(value)));
12782 }
12783 started.elapsed().as_nanos()
12784 };
12785 if sample.is_multiple_of(2) {
12786 former_ns.push(run(float_to_string_for_astype_former));
12787 public_ns.push(run(super::float_to_string_for_astype));
12788 } else {
12789 public_ns.push(run(super::float_to_string_for_astype));
12790 former_ns.push(run(float_to_string_for_astype_former));
12791 }
12792 }
12793
12794 former_ns.sort_unstable();
12795 public_ns.sort_unstable();
12796 let former_p50 = former_ns[SAMPLES / 2];
12797 let public_p50 = public_ns[SAMPLES / 2];
12798 println!(
12799 "float_to_string_for_astype_in_place_ab values={VALUES} former_p50_ns={former_p50} public_p50_ns={public_p50} speedup={:.6} former_samples={former_ns:?} public_samples={public_ns:?}",
12800 former_p50 as f64 / public_p50 as f64
12801 );
12802 }
12803
12804 #[test]
12805 fn cast_float_to_utf8_threshold_boundaries_match_python() {
12806 let cases: &[(f64, &str)] = &[
12811 (1e15, "1000000000000000.0"),
12812 (9_999_999_999_999_998.0, "9999999999999998.0"),
12813 (1_234_567_890_123_456.0, "1234567890123456.0"),
12814 (123_456_789_012_345.0, "123456789012345.0"),
12815 (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
12816 (1e16, "1e+16"),
12817 (1.5e16, "1.5e+16"),
12818 (1e17, "1e+17"),
12819 (1e-4, "0.0001"),
12820 (5e-5, "5e-05"),
12821 (-1e15, "-1000000000000000.0"),
12822 (-1e16, "-1e+16"),
12823 (-1e-5, "-1e-05"),
12824 ];
12825 for (v, expected) in cases {
12826 assert_eq!(
12827 cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
12828 Scalar::Utf8((*expected).to_owned()),
12829 "float {v} -> str"
12830 );
12831 }
12832 }
12833
12834 #[test]
12835 fn cast_to_bool_uses_pandas_nonzero_truthiness() {
12836 let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
12840 for (v, expected) in cases_int {
12841 assert_eq!(
12842 cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
12843 Scalar::Bool(*expected),
12844 "int {v} -> bool"
12845 );
12846 }
12847 let cases_float: &[(f64, bool)] = &[
12848 (0.0, false),
12849 (-0.0, false),
12850 (0.1, true),
12851 (2.5, true),
12852 (1.0, true),
12853 (f64::NAN, true),
12855 ];
12856 for (v, expected) in cases_float {
12857 assert_eq!(
12858 cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
12859 Scalar::Bool(*expected),
12860 "float {v} -> bool"
12861 );
12862 }
12863 }
12864
12865 #[test]
12866 fn nullable_dtype_is_extension() {
12867 assert!(DType::Int64Nullable.is_extension());
12868 assert!(DType::BoolNullable.is_extension());
12869 assert!(!DType::Int64.is_extension());
12870 assert!(!DType::Bool.is_extension());
12871 }
12872
12873 #[test]
12874 fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
12875 let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
12876 assert_eq!(
12877 infer_dtype(&values).expect("dtype should infer"),
12878 DType::Utf8
12879 );
12880 }
12881
12882 #[test]
12883 fn infer_dtype_routes_bool_numeric_mix_to_utf8_object_bucket_rh1od() {
12884 let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Bool(false)];
12890 assert_eq!(
12891 infer_dtype(&values).expect("dtype should infer"),
12892 DType::Utf8
12893 );
12894 let with_float = vec![Scalar::Int64(1), Scalar::Float64(2.5), Scalar::Bool(true)];
12895 assert_eq!(
12896 infer_dtype(&with_float).expect("dtype should infer"),
12897 DType::Utf8
12898 );
12899 let with_null = vec![
12900 Scalar::Bool(true),
12901 Scalar::Null(NullKind::Null),
12902 Scalar::Int64(2),
12903 ];
12904 assert_eq!(
12905 infer_dtype(&with_null).expect("dtype should infer"),
12906 DType::Utf8
12907 );
12908 }
12909
12910 #[test]
12911 fn infer_dtype_keeps_nonmixed_bool_and_numeric_paths_rh1od() {
12912 assert_eq!(
12916 infer_dtype(&[Scalar::Bool(true), Scalar::Bool(false)]).expect("dtype should infer"),
12917 DType::Bool
12918 );
12919 assert_eq!(
12920 infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]).expect("dtype should infer"),
12921 DType::Float64
12922 );
12923 }
12924
12925 #[test]
12928 fn is_null_detects_explicit_nulls() {
12929 assert!(Scalar::Null(NullKind::Null).is_null());
12930 assert!(Scalar::Null(NullKind::NaN).is_null());
12931 assert!(!Scalar::Int64(42).is_null());
12932 assert!(!Scalar::Float64(f64::NAN).is_null());
12933 }
12934
12935 #[test]
12936 fn is_na_matches_is_missing() {
12937 let vals = vec![
12938 Scalar::Null(NullKind::Null),
12939 Scalar::Float64(f64::NAN),
12940 Scalar::Int64(0),
12941 Scalar::Bool(false),
12942 ];
12943 for v in &vals {
12944 assert_eq!(v.is_na(), v.is_missing());
12945 }
12946 }
12947
12948 #[test]
12949 fn coalesce_picks_first_non_missing() {
12950 let null = Scalar::Null(NullKind::Null);
12951 let fill = Scalar::Int64(99);
12952 assert_eq!(null.coalesce(&fill), fill);
12953 assert_eq!(fill.coalesce(&null), fill);
12954 }
12955
12956 #[test]
12959 fn isna_notna_complement() {
12960 let vals = vec![
12961 Scalar::Int64(1),
12962 Scalar::Null(NullKind::Null),
12963 Scalar::Float64(f64::NAN),
12964 Scalar::Float64(3.0),
12965 ];
12966 let na = super::isna(&vals);
12967 let not = super::notna(&vals);
12968 assert_eq!(na, vec![false, true, true, false]);
12969 for (a, b) in na.iter().zip(not.iter()) {
12970 assert_ne!(a, b);
12971 }
12972 }
12973
12974 #[test]
12975 fn count_na_counts_missing() {
12976 let vals = vec![
12977 Scalar::Int64(1),
12978 Scalar::Null(NullKind::Null),
12979 Scalar::Float64(f64::NAN),
12980 ];
12981 assert_eq!(super::count_na(&vals), 2);
12982 }
12983
12984 #[test]
12985 fn fill_na_replaces_missing() {
12986 let vals = vec![
12987 Scalar::Int64(1),
12988 Scalar::Null(NullKind::Null),
12989 Scalar::Float64(f64::NAN),
12990 Scalar::Int64(4),
12991 ];
12992 let filled = super::fill_na(&vals, &Scalar::Int64(0));
12993 assert_eq!(filled[0], Scalar::Int64(1));
12994 assert_eq!(filled[1], Scalar::Int64(0));
12995 assert_eq!(filled[2], Scalar::Int64(0));
12996 assert_eq!(filled[3], Scalar::Int64(4));
12997 }
12998
12999 #[test]
13000 fn dropna_removes_missing() {
13001 let vals = vec![
13002 Scalar::Int64(1),
13003 Scalar::Null(NullKind::Null),
13004 Scalar::Int64(3),
13005 Scalar::Float64(f64::NAN),
13006 ];
13007 let kept = super::dropna(&vals);
13008 assert_eq!(kept.len(), 2);
13009 assert_eq!(kept[0], Scalar::Int64(1));
13010 assert_eq!(kept[1], Scalar::Int64(3));
13011 }
13012
13013 #[test]
13014 fn null_helpers_match_scalar_oracle_imt0c() {
13015 fn next(seed: &mut u64) -> u64 {
13018 *seed = seed
13019 .wrapping_mul(3202034522624059733)
13020 .wrapping_add(4354685564936845319);
13021 *seed
13022 }
13023
13024 fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
13025 let expected_missing = values.iter().filter(|value| value.is_missing()).count();
13026 let expected_dropped = values
13027 .iter()
13028 .filter(|value| !value.is_missing())
13029 .cloned()
13030 .collect::<Vec<_>>();
13031 let expected_filled = values
13032 .iter()
13033 .map(|value| {
13034 if value.is_missing() {
13035 fill.clone()
13036 } else {
13037 value.clone()
13038 }
13039 })
13040 .collect::<Vec<_>>();
13041
13042 assert_eq!(
13043 super::count_na(values),
13044 expected_missing,
13045 "case={case}: count_na mismatch for {values:?}"
13046 );
13047
13048 let dropped = super::dropna(values);
13049 assert_eq!(
13050 dropped.len(),
13051 expected_dropped.len(),
13052 "case={case}: dropna length mismatch for {values:?}"
13053 );
13054 for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
13055 {
13056 assert!(
13057 actual.semantic_eq(expected),
13058 "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
13059 );
13060 }
13061
13062 let filled = super::fill_na(values, fill);
13063 assert_eq!(
13064 filled.len(),
13065 expected_filled.len(),
13066 "case={case}: fill_na length mismatch for {values:?}"
13067 );
13068 for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
13069 assert!(
13070 actual.semantic_eq(expected),
13071 "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
13072 );
13073 }
13074 }
13075
13076 let all_missing = [
13077 Scalar::Null(NullKind::Null),
13078 Scalar::Null(NullKind::NaN),
13079 Scalar::Float64(f64::NAN),
13080 Scalar::Timedelta64(i64::MIN),
13081 ];
13082 assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
13083
13084 let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
13085 for case in 0..260 {
13086 let len = (next(&mut seed) % 83 + 1) as usize;
13087 let mut values = Vec::with_capacity(len);
13088 for pos in 0..len {
13089 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13090 values.push(match next(&mut seed) % 11 {
13091 0 => Scalar::Null(NullKind::Null),
13092 1 => Scalar::Null(NullKind::NaN),
13093 2 => Scalar::Float64(f64::NAN),
13094 3 => Scalar::Timedelta64(i64::MIN),
13095 4 => Scalar::Bool(raw & 1 == 0),
13096 5 => Scalar::Int64(raw),
13097 6 => Scalar::Float64(raw as f64 / 37.0),
13098 7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
13099 8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
13100 9 => Scalar::Utf8(String::new()),
13101 _ => Scalar::Timedelta64(raw),
13102 });
13103 }
13104
13105 let fill = match case % 5 {
13106 0 => Scalar::Bool(true),
13107 1 => Scalar::Int64(-777),
13108 2 => Scalar::Float64(12.5),
13109 3 => Scalar::Utf8("filled".into()),
13110 _ => Scalar::Timedelta64(123_456),
13111 };
13112 assert_null_helpers(case, &values, &fill);
13113 }
13114 }
13115
13116 #[test]
13119 fn nansum_skips_nulls() {
13120 let vals = vec![
13121 Scalar::Float64(1.0),
13122 Scalar::Null(NullKind::Null),
13123 Scalar::Float64(2.0),
13124 Scalar::Float64(f64::NAN),
13125 Scalar::Int64(7),
13126 ];
13127 assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
13128 }
13129
13130 #[test]
13131 fn nansum_empty_returns_zero() {
13132 assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
13133 }
13134
13135 #[test]
13136 fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
13137 fn next(seed: &mut u64) -> u64 {
13140 *seed = seed
13141 .wrapping_mul(6364136223846793005)
13142 .wrapping_add(1442695040888963407);
13143 *seed
13144 }
13145
13146 fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
13147 let mut sum = 0.0;
13148 let mut count = 0usize;
13149 for value in values {
13150 if value.is_missing() {
13151 continue;
13152 }
13153 if let Ok(value) = value.to_f64() {
13154 sum += value;
13155 count += 1;
13156 }
13157 }
13158 let mean = if count == 0 {
13159 Scalar::Null(NullKind::NaN)
13160 } else {
13161 Scalar::Float64(sum / count as f64)
13162 };
13163 (Scalar::Float64(sum), mean)
13164 }
13165
13166 fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
13167 let mut sum = 0_i128;
13168 let mut count = 0_i128;
13169 for value in values {
13170 if let Scalar::Timedelta64(ns) = value
13171 && !value.is_missing()
13172 {
13173 sum += i128::from(*ns);
13174 count += 1;
13175 }
13176 }
13177 if count == 0 {
13178 return (Scalar::Timedelta64(0), Scalar::Timedelta64(Timedelta::NAT));
13179 }
13180 (
13186 super::timedelta_ns_to_scalar(sum),
13187 super::timedelta_ns_to_scalar(sum / count),
13188 )
13189 }
13190
13191 fn assert_sum_mean(
13192 case: usize,
13193 family: &str,
13194 values: &[Scalar],
13195 expected_sum: Scalar,
13196 expected_mean: Scalar,
13197 ) {
13198 let actual_sum = super::nansum(values);
13199 let actual_mean = super::nanmean(values);
13200 assert!(
13201 actual_sum.semantic_eq(&expected_sum),
13202 "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
13203 );
13204 assert!(
13205 actual_mean.semantic_eq(&expected_mean),
13206 "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
13207 );
13208 }
13209
13210 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13211 let (sum, mean) = expected_numeric(&all_missing);
13212 assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
13213
13214 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
13215 let (sum, mean) = expected_timedelta(&td_all_missing);
13216 assert_sum_mean(
13217 usize::MAX - 1,
13218 "timedelta_all_missing",
13219 &td_all_missing,
13220 sum,
13221 mean,
13222 );
13223
13224 let mut seed = 0x511d_ed5a_7a11_1a55_u64;
13225 for case in 0..260 {
13226 let len = (next(&mut seed) % 89 + 1) as usize;
13227
13228 let mut numeric = Vec::with_capacity(len);
13229 numeric.push(Scalar::Int64(case as i64 - 130));
13230 for _ in 1..len {
13231 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13232 numeric.push(match next(&mut seed) % 8 {
13233 0 => Scalar::Null(NullKind::Null),
13234 1 => Scalar::Null(NullKind::NaN),
13235 2 => Scalar::Float64(f64::NAN),
13236 3 => Scalar::Bool(raw & 1 == 0),
13237 4 => Scalar::Int64(raw % 257),
13238 5 => Scalar::Float64(raw as f64 / 67.0),
13239 6 => Scalar::Float64(0.0),
13240 _ => Scalar::Float64(-0.0),
13241 });
13242 }
13243 let (sum, mean) = expected_numeric(&numeric);
13244 assert_sum_mean(case, "numeric", &numeric, sum, mean);
13245
13246 let mut timedeltas = Vec::with_capacity(len);
13247 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
13248 for _ in 1..len {
13249 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13250 timedeltas.push(match next(&mut seed) % 7 {
13251 0 => Scalar::Null(NullKind::Null),
13252 1 => Scalar::Timedelta64(i64::MIN),
13253 _ => Scalar::Timedelta64(raw),
13254 });
13255 }
13256 let (sum, mean) = expected_timedelta(&timedeltas);
13257 assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
13258 }
13259 }
13260
13261 #[test]
13262 fn nannunique_merges_negative_zero_and_zero() {
13263 let vals = vec![
13264 Scalar::Float64(-0.0),
13265 Scalar::Float64(0.0),
13266 Scalar::Float64(1.0),
13267 ];
13268 assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
13269 }
13270
13271 #[test]
13272 fn nannunique_matches_scalar_bucket_oracle_elvbg() {
13273 fn next(seed: &mut u64) -> u64 {
13276 *seed = seed
13277 .wrapping_mul(2862933555777941757)
13278 .wrapping_add(3037000493);
13279 *seed
13280 }
13281
13282 fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
13283 match (left, right) {
13284 (Scalar::Float64(left), Scalar::Float64(right)) => {
13285 let left = if *left == 0.0 { 0.0 } else { *left };
13286 let right = if *right == 0.0 { 0.0 } else { *right };
13287 left.to_bits() == right.to_bits()
13288 }
13289 _ => left == right,
13290 }
13291 }
13292
13293 fn expected_nunique(values: &[Scalar]) -> i64 {
13294 let mut seen = Vec::<Scalar>::new();
13295 for value in values {
13296 if value.is_missing() {
13297 continue;
13298 }
13299 if !seen.iter().any(|existing| same_bucket(existing, value)) {
13300 seen.push(value.clone());
13301 }
13302 }
13303 seen.len() as i64
13304 }
13305
13306 fn assert_nannunique(case: usize, values: &[Scalar]) {
13307 assert_eq!(
13308 super::nannunique(values),
13309 Scalar::Int64(expected_nunique(values)),
13310 "case={case}: nannunique mismatch for {values:?}"
13311 );
13312 }
13313
13314 assert_nannunique(
13315 usize::MAX,
13316 &[
13317 Scalar::Float64(-0.0),
13318 Scalar::Float64(0.0),
13319 Scalar::Float64(f64::NAN),
13320 Scalar::Null(NullKind::Null),
13321 Scalar::Timedelta64(i64::MIN),
13322 ],
13323 );
13324
13325 let mut seed = 0x0e1b_60d0_b5e7_u64;
13326 for case in 0..320 {
13327 let len = (next(&mut seed) % 97 + 1) as usize;
13328 let mut values = Vec::with_capacity(len);
13329 for pos in 0..len {
13330 let raw = (next(&mut seed) % 1_001) as i64 - 500;
13331 values.push(match next(&mut seed) % 11 {
13332 0 => Scalar::Null(NullKind::Null),
13333 1 => Scalar::Null(NullKind::NaN),
13334 2 => Scalar::Float64(f64::NAN),
13335 3 => Scalar::Bool(raw & 1 == 0),
13336 4 => Scalar::Int64(raw % 37),
13337 5 => Scalar::Float64(raw as f64 / 19.0),
13338 6 => Scalar::Float64(0.0),
13339 7 => Scalar::Float64(-0.0),
13340 8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
13341 9 => Scalar::Utf8(String::new()),
13342 _ => Scalar::Timedelta64(raw % 41),
13343 });
13344 }
13345 assert_nannunique(case, &values);
13346 }
13347 }
13348
13349 #[test]
13350 fn nanmean_basic() {
13351 let vals = vec![
13352 Scalar::Float64(2.0),
13353 Scalar::Null(NullKind::Null),
13354 Scalar::Float64(4.0),
13355 ];
13356 assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
13357 }
13358
13359 #[test]
13360 fn nanmean_all_null_returns_nan() {
13361 let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13362 assert!(super::nanmean(&vals).is_missing());
13363 }
13364
13365 #[test]
13366 fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
13367 let one_hour = 3_600 * 1_000_000_000_i64;
13371 let vals = vec![
13372 Scalar::Timedelta64(one_hour),
13373 Scalar::Timedelta64(2 * one_hour),
13374 Scalar::Timedelta64(3 * one_hour),
13375 ];
13376 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
13377 assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13378 }
13379
13380 #[test]
13381 fn nansum_nanmean_timedelta64_skips_nat_620mj() {
13382 let one_hour = 3_600 * 1_000_000_000_i64;
13383 let vals = vec![
13384 Scalar::Timedelta64(Timedelta::NAT),
13385 Scalar::Timedelta64(one_hour),
13386 Scalar::Timedelta64(3 * one_hour),
13387 Scalar::Timedelta64(Timedelta::NAT),
13388 ];
13389 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
13391 assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13392 }
13393
13394 #[test]
13401 fn nansum_timedelta_overflow_is_nat_not_fabricated_max_opz27() {
13402 let vals = vec![Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MAX)];
13403 let got = super::nansum(&vals);
13404 assert!(
13405 got.is_missing(),
13406 "overflowing sum must be missing, got {got:?}"
13407 );
13408 assert_eq!(got, Scalar::Timedelta64(Timedelta::NAT));
13409 assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13410 }
13411
13412 #[test]
13417 fn nansum_timedelta_negative_overflow_is_nat_opz27() {
13418 let min_repr = i64::MIN + 1; let vals = vec![Scalar::Timedelta64(min_repr), Scalar::Timedelta64(min_repr)];
13420 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(Timedelta::NAT));
13421
13422 let exact = vec![Scalar::Timedelta64(min_repr + 1), Scalar::Timedelta64(-1)];
13425 let got = super::nansum(&exact);
13426 assert_eq!(got, Scalar::Timedelta64(min_repr));
13427 assert!(!got.is_missing(), "Timedelta.min is representable, not NaT");
13428 }
13429
13430 #[test]
13434 fn nanptp_timedelta_overflow_is_nat_opz27() {
13435 let vals = vec![
13436 Scalar::Timedelta64(i64::MIN + 1),
13437 Scalar::Timedelta64(i64::MAX),
13438 ];
13439 let got = super::nanptp(&vals);
13440 assert!(
13441 got.is_missing(),
13442 "unrepresentable range must be NaT, got {got:?}"
13443 );
13444 assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13445
13446 let hour = 3_600 * 1_000_000_000_i64;
13449 let ok = vec![Scalar::Timedelta64(hour), Scalar::Timedelta64(4 * hour)];
13450 assert_eq!(super::nanptp(&ok), Scalar::Timedelta64(3 * hour));
13451 }
13452
13453 #[test]
13458 fn nancumsum_timedelta_overflow_recovers_exact_value_opz27() {
13459 let vals = vec![
13460 Scalar::Timedelta64(i64::MAX),
13461 Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MIN + 1), ];
13464 let out = super::nancumsum(&vals);
13465 assert_eq!(out.len(), 3);
13466 assert_eq!(out[0], Scalar::Timedelta64(i64::MAX));
13467 assert!(
13468 out[1].is_missing(),
13469 "overflowed index must be NaT, got {:?}",
13470 out[1]
13471 );
13472 assert_eq!(
13473 out[2],
13474 Scalar::Timedelta64(i64::MAX),
13475 "exact i128 accumulation must recover; a clamped running sum cannot"
13476 );
13477 }
13478
13479 #[test]
13482 fn nancumsum_timedelta_exact_path_unchanged_opz27() {
13483 let sec = 1_000_000_000_i64;
13484 let vals = vec![
13485 Scalar::Timedelta64(sec),
13486 Scalar::Timedelta64(Timedelta::NAT),
13487 Scalar::Timedelta64(2 * sec),
13488 ];
13489 let out = super::nancumsum(&vals);
13490 assert_eq!(out[0], Scalar::Timedelta64(sec));
13491 assert!(out[1].is_missing());
13492 assert_eq!(out[2], Scalar::Timedelta64(3 * sec));
13493 }
13494
13495 const DAY_NS: i64 = 86_400 * 1_000_000_000;
13496 const DT_2020: i64 = 1_577_836_800_000_000_000;
13498
13499 #[test]
13507 fn datetime64_ordering_reductions_match_pandas_axhhk() {
13508 let d = Scalar::Datetime64;
13509 let vals = vec![
13510 d(DT_2020),
13511 d(DT_2020 + 60 * DAY_NS),
13512 d(DT_2020 + 31 * DAY_NS),
13513 ];
13514
13515 assert_eq!(super::nanmin(&vals), d(DT_2020));
13516 assert_eq!(super::nanmax(&vals), d(DT_2020 + 60 * DAY_NS));
13517 assert_eq!(super::nanargmin(&vals), Some(0));
13518 assert_eq!(super::nanargmax(&vals), Some(1));
13519
13520 let span = super::nanptp(&vals);
13522 assert_eq!(span, Scalar::Timedelta64(60 * DAY_NS));
13523 assert_eq!(span.dtype(), DType::Timedelta64);
13524
13525 assert_eq!(
13526 super::nancummax(&vals),
13527 vec![
13528 d(DT_2020),
13529 d(DT_2020 + 60 * DAY_NS),
13530 d(DT_2020 + 60 * DAY_NS)
13531 ]
13532 );
13533 assert_eq!(
13534 super::nancummin(&vals),
13535 vec![d(DT_2020), d(DT_2020), d(DT_2020)]
13536 );
13537 }
13538
13539 #[test]
13546 fn datetime64_min_max_size_dependence_pinned_axhhk() {
13547 let d = Scalar::Datetime64;
13548 let one = vec![d(DT_2020)];
13549 assert_eq!(super::nanmin(&one), d(DT_2020));
13550 assert_eq!(super::nanmax(&one), d(DT_2020));
13551
13552 let two = vec![d(DT_2020 + DAY_NS), d(DT_2020)];
13553 let got_min = super::nanmin(&two);
13554 assert!(
13555 !got_min.is_missing(),
13556 "2-element datetime min must not be missing, got {got_min:?}"
13557 );
13558 assert_eq!(got_min, d(DT_2020));
13559 assert_eq!(super::nanmax(&two), d(DT_2020 + DAY_NS));
13560 }
13561
13562 #[test]
13565 fn datetime64_reductions_skip_nat_and_guard_span_overflow_axhhk() {
13566 let d = Scalar::Datetime64;
13567 let with_nat = vec![
13568 d(Timestamp::NAT),
13569 d(DT_2020 + 31 * DAY_NS),
13570 d(DT_2020),
13571 d(Timestamp::NAT),
13572 ];
13573 assert_eq!(super::nanmin(&with_nat), d(DT_2020));
13574 assert_eq!(super::nanmax(&with_nat), d(DT_2020 + 31 * DAY_NS));
13575 assert_eq!(super::nanptp(&with_nat), Scalar::Timedelta64(31 * DAY_NS));
13576 assert_eq!(super::nanargmin(&with_nat), Some(2));
13578 assert_eq!(super::nanargmax(&with_nat), Some(1));
13579
13580 let huge = vec![d(i64::MIN + 1), d(i64::MAX)];
13582 let span = super::nanptp(&huge);
13583 assert!(span.is_missing(), "unrepresentable span must be NaT");
13584 assert_ne!(span, Scalar::Timedelta64(i64::MAX));
13585 }
13586
13587 #[test]
13594 fn datetime64_averaging_reductions_match_pandas_adv58() {
13595 let d = Scalar::Datetime64;
13596 let vals = vec![
13597 d(DT_2020),
13598 d(DT_2020 + 60 * DAY_NS),
13599 d(DT_2020 + 31 * DAY_NS),
13600 ];
13601 assert_eq!(super::nanmean(&vals), d(1_580_457_600_000_000_000));
13603 assert_eq!(super::nanmedian(&vals), d(1_580_515_200_000_000_000));
13604 assert_eq!(super::nanquantile(&vals, 0.5), d(1_580_515_200_000_000_000));
13605 assert_eq!(
13606 super::nanquantile(&vals, 0.25),
13607 d(1_579_176_000_000_000_000)
13608 );
13609 }
13610
13611 #[test]
13617 fn datetime64_mean_median_round_toward_zero_adv58() {
13618 let d = Scalar::Datetime64;
13619 for (a, b, want) in [
13620 (0_i64, 1_i64, 0_i64),
13621 (0, 3, 1),
13622 (1, 2, 1),
13623 (-1, 0, 0),
13624 (-3, 0, -1),
13625 (-2, -1, -1),
13626 (0, 2, 1),
13627 (-2, 0, -1),
13628 ] {
13629 let vals = vec![d(a), d(b)];
13630 assert_eq!(
13631 super::nanmean(&vals),
13632 d(want),
13633 "mean of [{a}, {b}] should be {want}"
13634 );
13635 assert_eq!(
13636 super::nanmedian(&vals),
13637 d(want),
13638 "median of [{a}, {b}] should be {want}"
13639 );
13640 }
13641 }
13642
13643 #[test]
13646 fn datetime64_averaging_skips_nat_adv58() {
13647 let d = Scalar::Datetime64;
13648 let vals = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
13649 assert_eq!(super::nanmean(&vals), d(DT_2020 + DAY_NS));
13651 assert_eq!(super::nanmedian(&vals), d(DT_2020 + DAY_NS));
13652
13653 let all_nat = vec![d(Timestamp::NAT), d(Timestamp::NAT)];
13654 let got = super::nanmean(&all_nat);
13655 assert!(
13656 got.is_missing(),
13657 "all-NaT mean must be missing, got {got:?}"
13658 );
13659 assert_eq!(
13660 got.dtype(),
13661 DType::datetime64_naive(),
13662 "must stay Datetime64"
13663 );
13664 }
13665
13666 #[test]
13673 fn datetime64_averaging_is_exact_where_pandas_snaps_adv58() {
13674 let d = Scalar::Datetime64;
13675
13676 let constant = vec![d(DT_2020 + 1), d(DT_2020 + 1)];
13678 assert_eq!(super::nanmean(&constant), d(DT_2020 + 1));
13679 assert_eq!(super::nanmedian(&constant), d(DT_2020 + 1));
13680
13681 let odd = vec![d(DT_2020), d(DT_2020 + 129), d(DT_2020 + 258)];
13683 let med = super::nanmedian(&odd);
13684 assert_eq!(med, d(DT_2020 + 129));
13685 assert!(
13686 odd.contains(&med),
13687 "odd-count median must be one of the inputs; pandas returns B+256, which is not"
13688 );
13689 }
13690
13691 #[test]
13698 fn datetime64_std_matches_pandas_ddof_variants_40ujm() {
13699 let d = Scalar::Datetime64;
13700 let vals = vec![
13701 d(DT_2020),
13702 d(DT_2020 + 60 * DAY_NS),
13703 d(DT_2020 + 31 * DAY_NS),
13704 ];
13705 let s1 = super::nanstd(&vals, 1);
13707 assert_eq!(s1, Scalar::Timedelta64(2_592_479_955_563_784));
13708 assert_eq!(s1.dtype(), DType::Timedelta64);
13709 assert_eq!(
13710 super::nanstd(&vals, 0),
13711 Scalar::Timedelta64(2_116_751_019_841_492)
13712 );
13713 assert_eq!(
13714 super::nanstd(&vals, 2),
13715 Scalar::Timedelta64(3_666_320_313_338_702)
13716 );
13717 assert!(super::nanstd(&vals, 3).is_missing());
13719 }
13720
13721 #[test]
13725 fn datetime64_std_equals_timedelta64_std_on_same_ns_40ujm() {
13726 let offsets = [0_i64, 60 * DAY_NS, 31 * DAY_NS];
13727 let dt: Vec<Scalar> = offsets.iter().map(|o| Scalar::Datetime64(*o)).collect();
13728 let td: Vec<Scalar> = offsets.iter().map(|o| Scalar::Timedelta64(*o)).collect();
13729 assert_eq!(super::nanstd(&dt, 1), super::nanstd(&td, 1));
13730 assert_eq!(
13731 super::nanstd(&dt, 1),
13732 Scalar::Timedelta64(2_592_479_955_563_784)
13733 );
13734 }
13735
13736 #[test]
13740 fn datetime64_std_skips_nat_and_var_sem_stay_unsupported_40ujm() {
13741 let d = Scalar::Datetime64;
13742 let with_nat = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
13743 let without = vec![d(DT_2020), d(DT_2020 + 2 * DAY_NS)];
13744 assert_eq!(super::nanstd(&with_nat, 1), super::nanstd(&without, 1));
13746 assert_eq!(
13747 super::nanstd(&with_nat, 1),
13748 Scalar::Timedelta64(122_188_051_789_035)
13749 );
13750
13751 assert!(super::nanstd(&[d(DT_2020)], 1).is_missing());
13753 assert!(super::nanstd(&[d(Timestamp::NAT)], 1).is_missing());
13754
13755 let vals = vec![d(DT_2020), d(DT_2020 + 60 * DAY_NS)];
13759 assert!(super::nanvar(&vals, 1).is_missing());
13760 assert!(super::nansem(&vals, 1).is_missing());
13761 }
13762
13763 #[test]
13768 fn period_min_max_match_pandas_qoabs() {
13769 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13770 let vals = vec![p(600), p(602), p(601)];
13771 assert_eq!(super::nanmin(&vals), p(600));
13772 assert_eq!(super::nanmax(&vals), p(602));
13773
13774 assert_eq!(super::nanmin(&[p(600)]), p(600));
13778 let two = vec![p(602), p(600)];
13779 assert!(!super::nanmin(&two).is_missing());
13780 assert_eq!(super::nanmin(&two), p(600));
13781 assert_eq!(super::nanmax(&two), p(602));
13782 }
13783
13784 #[test]
13787 fn period_min_max_skip_nat_qoabs() {
13788 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13789 let nat = Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly));
13790 let vals = vec![nat.clone(), p(602), p(600), nat.clone()];
13791 assert_eq!(super::nanmin(&vals), p(600));
13792 assert_eq!(super::nanmax(&vals), p(602));
13793 assert!(super::nanmin(&[nat.clone(), nat]).is_missing());
13794 }
13795
13796 #[test]
13803 fn period_mixed_freq_is_not_ordered_qoabs() {
13804 let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
13805 let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
13806 let vals = vec![month.clone(), day.clone()];
13807 let got_min = super::nanmin(&vals);
13808 assert!(
13809 got_min.is_missing(),
13810 "mixed-freq Period min must not be ordered, got {got_min:?}"
13811 );
13812 assert_ne!(
13813 got_min, day,
13814 "must not rank the daily period by raw ordinal"
13815 );
13816 assert!(super::nanmax(&vals).is_missing());
13817 }
13818
13819 #[test]
13826 fn period_full_reduction_family_matches_pandas_d7zjp() {
13827 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13828 let vals = vec![p(600), p(602), p(601)];
13829
13830 assert_eq!(super::nanmedian(&vals), p(601));
13831 assert_eq!(super::nanquantile(&vals, 0.5), p(601));
13832 assert_eq!(super::nanargmin(&vals), Some(0));
13833 assert_eq!(super::nanargmax(&vals), Some(1));
13834 assert_eq!(super::nancummax(&vals), vec![p(600), p(602), p(602)]);
13835 assert_eq!(super::nancummin(&vals), vec![p(600), p(600), p(600)]);
13836 }
13837
13838 #[test]
13843 fn period_even_count_median_truncates_toward_zero_d7zjp() {
13844 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13845 assert_eq!(super::nanmedian(&[p(600), p(603)]), p(601));
13846 assert_eq!(super::nanmedian(&[p(600), p(601)]), p(600));
13847 }
13848
13849 #[test]
13855 fn period_mixed_freq_not_ordered_by_any_reduction_d7zjp() {
13856 let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
13857 let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
13858 let vals = vec![month, day];
13859
13860 assert!(super::nanmedian(&vals).is_missing());
13861 assert!(super::nanquantile(&vals, 0.5).is_missing());
13862 assert_eq!(super::nanargmin(&vals), None);
13863 assert_eq!(super::nanargmax(&vals), None);
13864 assert!(super::nancummax(&vals).iter().all(Scalar::is_missing));
13866 assert!(super::nancummin(&vals).iter().all(Scalar::is_missing));
13867 }
13868
13869 #[test]
13875 fn period_unsupported_reductions_stay_missing_d7zjp() {
13876 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13877 let vals = vec![p(600), p(602), p(601)];
13878 assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
13879 assert!(super::nanvar(&vals, 1).is_missing(), "pandas raises var");
13880 assert!(super::nansem(&vals, 1).is_missing(), "pandas raises sem");
13881 assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
13882 }
13883
13884 #[test]
13889 fn interval_min_max_match_pandas_srqdo() {
13890 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13891 let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
13892 assert_eq!(super::nanmin(&vals), iv(0.0, 1.0));
13893 assert_eq!(super::nanmax(&vals), iv(4.0, 5.0));
13894
13895 assert_eq!(super::nanmin(&[iv(2.0, 3.0)]), iv(2.0, 3.0));
13898 let two = vec![iv(4.0, 5.0), iv(0.0, 1.0)];
13899 assert!(!super::nanmin(&two).is_missing());
13900 assert_eq!(super::nanmin(&two), iv(0.0, 1.0));
13901 assert_eq!(super::nanmax(&two), iv(4.0, 5.0));
13902 }
13903
13904 #[test]
13909 fn interval_ties_on_left_order_by_right_srqdo() {
13910 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13911 let vals = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
13912 assert_eq!(super::nanmin(&vals), iv(0.0, 2.0));
13913 assert_eq!(super::nanmax(&vals), iv(0.0, 9.0));
13914 }
13915
13916 #[test]
13922 fn interval_nan_bound_is_not_ordered_srqdo() {
13923 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13924 let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
13925 assert!(super::nanmin(&vals).is_missing());
13926 assert!(super::nanmax(&vals).is_missing());
13927 }
13928
13929 #[test]
13933 fn interval_unsupported_reductions_stay_missing_srqdo() {
13934 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13935 let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
13936 assert!(super::nanmedian(&vals).is_missing(), "pandas raises median");
13937 assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
13938 assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
13939 assert!(
13940 super::nanquantile(&vals, 0.5).is_missing(),
13941 "pandas raises quantile"
13942 );
13943 assert!(
13944 super::nancummax(&vals).iter().all(Scalar::is_missing),
13945 "pandas NotImplementedErrors cummax"
13946 );
13947 }
13948
13949 #[test]
13953 fn interval_argmin_argmax_match_pandas_2h9dm() {
13954 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13955 let vals = vec![iv(4.0, 5.0), iv(0.0, 1.0), iv(2.0, 3.0)];
13957 assert_eq!(super::nanargmin(&vals), Some(1));
13958 assert_eq!(super::nanargmax(&vals), Some(0));
13959
13960 let tie = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
13963 assert_eq!(super::nanargmin(&tie), Some(1));
13964 assert_eq!(super::nanargmax(&tie), Some(2));
13965 }
13966
13967 #[test]
13972 fn interval_arg_first_occurrence_and_missing_2h9dm() {
13973 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13974 let dup = vec![iv(0.0, 1.0), iv(0.0, 1.0), iv(9.0, 9.0)];
13975 assert_eq!(
13976 super::nanargmin(&dup),
13977 Some(0),
13978 "first occurrence, not last"
13979 );
13980 assert_eq!(super::nanargmax(&dup), Some(2));
13981
13982 let with_missing = vec![iv(4.0, 5.0), Scalar::Null(NullKind::NaN), iv(0.0, 1.0)];
13983 assert_eq!(super::nanargmin(&with_missing), Some(2));
13984 assert_eq!(super::nanargmax(&with_missing), Some(0));
13985 }
13986
13987 #[test]
13991 fn interval_arg_nan_bound_declines_2h9dm() {
13992 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13993 let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
13994 assert_eq!(super::nanargmin(&vals), None);
13995 assert_eq!(super::nanargmax(&vals), None);
13996 }
13997
13998 #[test]
14005 fn overflow_policy_carrier_preserves_default_behavior_f29nz() {
14006 let mut state: u64 = 0x5DEE_CE66_D125_1F00;
14008 let mut next = || {
14009 state = state
14010 .wrapping_mul(6_364_136_223_846_793_005)
14011 .wrapping_add(1_442_695_040_888_963_407);
14012 state
14013 };
14014 let mut corpus: Vec<i64> = vec![
14016 0,
14017 1,
14018 -1,
14019 2,
14020 -2,
14021 i64::MAX,
14022 i64::MIN,
14023 i64::MIN + 1,
14024 i64::MAX - 1,
14025 i64::MAX / 2,
14026 -(i64::MAX / 2),
14027 ];
14028 for _ in 0..400 {
14029 let raw = next() as i64;
14030 corpus.push(raw);
14031 corpus.push(raw / 3);
14032 }
14033
14034 let policy = super::OverflowPolicy::default();
14035 assert_eq!(
14036 policy,
14037 super::OverflowPolicy::SurfaceNat,
14038 "default must not move"
14039 );
14040
14041 for &a in &corpus {
14042 for &b in &corpus {
14043 assert_eq!(
14045 Timedelta::add(a, b),
14046 policy
14047 .resolve(Timedelta::try_add(a, b), Timedelta::NAT)
14048 .expect("SurfaceNat never errors"),
14049 "add({a}, {b}) diverged"
14050 );
14051 assert_eq!(
14052 Timedelta::sub(a, b),
14053 policy
14054 .resolve(Timedelta::try_sub(a, b), Timedelta::NAT)
14055 .expect("SurfaceNat never errors"),
14056 "sub({a}, {b}) diverged"
14057 );
14058 assert_eq!(
14059 Timedelta::mul_scalar(a, b),
14060 policy
14061 .resolve(Timedelta::try_mul_scalar(a, b), Timedelta::NAT)
14062 .expect("SurfaceNat never errors"),
14063 "mul_scalar({a}, {b}) diverged"
14064 );
14065
14066 let ts = Timestamp::from_nanos(a);
14069 assert_eq!(
14070 ts.add_timedelta(b),
14071 ts.try_add_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14072 "add_timedelta({a}, {b}) diverged"
14073 );
14074 assert_eq!(
14075 ts.sub_timedelta(b),
14076 ts.try_sub_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14077 "sub_timedelta({a}, {b}) diverged"
14078 );
14079 let other = Timestamp::from_nanos(b);
14080 assert_eq!(
14081 ts.sub_timestamp(&other),
14082 ts.try_sub_timestamp(&other).unwrap_or(Timedelta::NAT),
14083 "sub_timestamp({a}, {b}) diverged"
14084 );
14085 }
14086 }
14087 }
14088
14089 #[test]
14094 fn overflow_policy_strict_reports_op_and_pandas_class_f29nz() {
14095 use super::{OverflowPolicy, PandasTemporalError};
14096
14097 let strict = OverflowPolicy::Strict;
14098
14099 let err = strict
14101 .resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT)
14102 .expect_err("must surface under Strict");
14103 assert_eq!(err.op, "Timedelta::add");
14104 assert_eq!(err.pandas_error, PandasTemporalError::Overflow);
14105
14106 let ts = Timestamp::from_nanos(i64::MAX);
14108 let err = strict
14109 .resolve(ts.try_add_timedelta(1), Timestamp::nat())
14110 .expect_err("must surface under Strict");
14111 assert_eq!(err.op, "Timestamp::add_timedelta");
14112 assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14113
14114 let err = strict
14116 .resolve(
14117 Timestamp::from_nanos(i64::MIN + 1)
14118 .try_sub_timestamp(&Timestamp::from_nanos(i64::MAX)),
14119 Timedelta::NAT,
14120 )
14121 .expect_err("must surface under Strict");
14122 assert_eq!(err.op, "Timestamp::sub_timestamp");
14123 assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14124
14125 assert_eq!(
14127 strict
14128 .resolve(Timedelta::try_add(Timedelta::NAT, 1), Timedelta::NAT)
14129 .expect("NaT propagation is not an overflow"),
14130 Timedelta::NAT
14131 );
14132 assert_eq!(
14134 strict
14135 .resolve(Timedelta::try_add(2, 3), Timedelta::NAT)
14136 .expect("no overflow"),
14137 5
14138 );
14139 }
14140
14141 #[test]
14149 fn timedelta_scalar_zero_division_taxonomy_t7ht2() {
14150 use super::{OverflowPolicy, PandasTemporalError};
14151
14152 let err = Timedelta::try_div_scalar(1_000_000_000, 0)
14154 .expect_err("scalar divide-by-zero must be reportable");
14155 assert_eq!(err.op, "Timedelta::div_scalar");
14156 assert_eq!(err.pandas_error, PandasTemporalError::ZeroDivision);
14157
14158 assert_eq!(Timedelta::div_scalar(1_000_000_000, 0), Timedelta::NAT);
14162 assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 0), Timedelta::NAT);
14163
14164 assert_eq!(
14167 OverflowPolicy::default()
14168 .resolve(Timedelta::try_div_scalar(1_000_000_000, 0), Timedelta::NAT)
14169 .expect("SurfaceNat never errors"),
14170 Timedelta::NAT
14171 );
14172
14173 assert_eq!(Timedelta::try_div_scalar(-7, 2), Ok(-4));
14176 assert_eq!(Timedelta::div_scalar(-7, 2), -4);
14177 assert_eq!(Timedelta::try_div_scalar(7, 2), Ok(3));
14178 assert_eq!(
14180 Timedelta::try_div_scalar(Timedelta::NAT, 2),
14181 Ok(Timedelta::NAT)
14182 );
14183 }
14184
14185 #[test]
14190 fn timedelta_constructor_error_maps_to_out_of_bounds_t7ht2() {
14191 use super::{PandasTemporalError, TimedeltaError};
14192
14193 assert_eq!(
14194 TimedeltaError::Overflow.pandas_error(),
14195 Some(PandasTemporalError::OutOfBoundsTimedelta)
14196 );
14197 assert_eq!(
14199 TimedeltaError::InvalidFormat("nonsense".into()).pandas_error(),
14200 None
14201 );
14202 assert!(Timedelta::from_unit(f64::INFINITY, "s").is_err());
14204 assert_eq!(
14205 Timedelta::from_unit(f64::INFINITY, "s")
14206 .unwrap_err()
14207 .pandas_error(),
14208 Some(PandasTemporalError::OutOfBoundsTimedelta)
14209 );
14210 }
14211
14212 #[test]
14218 fn hardened_audit_values_are_bit_identical_to_surface_nat_vllv6() {
14219 use super::{OverflowPolicy, overflow_audit};
14220
14221 overflow_audit::enable();
14222 let mut state: u64 = 0x1234_5678_9ABC_DEF0;
14223 let mut next = || {
14224 state = state
14225 .wrapping_mul(6_364_136_223_846_793_005)
14226 .wrapping_add(1_442_695_040_888_963_407);
14227 state
14228 };
14229 let mut corpus: Vec<i64> = vec![
14230 0,
14231 1,
14232 -1,
14233 2,
14234 -2,
14235 i64::MAX,
14236 i64::MIN,
14237 i64::MIN + 1,
14238 i64::MAX - 1,
14239 ];
14240 for _ in 0..120 {
14241 corpus.push(next() as i64);
14242 }
14243
14244 for &a in &corpus {
14245 for &b in &corpus {
14246 for op in [
14247 Timedelta::try_add as fn(i64, i64) -> Result<i64, super::TemporalFailure>,
14248 Timedelta::try_sub,
14249 Timedelta::try_mul_scalar,
14250 Timedelta::try_div_scalar,
14251 ] {
14252 let soft = OverflowPolicy::SurfaceNat
14253 .resolve(op(a, b), Timedelta::NAT)
14254 .expect("SurfaceNat never errors");
14255 let hard = OverflowPolicy::HardenedNat
14256 .resolve(op(a, b), Timedelta::NAT)
14257 .expect("HardenedNat never errors");
14258 assert_eq!(hard, soft, "HARDENED changed a value for ({a}, {b})");
14259 }
14260 }
14261 }
14262 overflow_audit::disable();
14263 }
14264
14265 #[test]
14270 fn hardened_audit_records_deterministic_recovery_entries_vllv6() {
14271 use super::{OverflowPolicy, PandasTemporalError, overflow_audit};
14272
14273 overflow_audit::enable();
14274 assert!(overflow_audit::is_enabled());
14275 assert!(overflow_audit::drain().is_empty(), "starts empty");
14276
14277 let _ =
14279 OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14280 let _ = OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(2, 3), Timedelta::NAT);
14281 let _ =
14282 OverflowPolicy::HardenedNat.resolve(Timedelta::try_div_scalar(5, 0), Timedelta::NAT);
14283
14284 let entries = overflow_audit::drain();
14285 assert_eq!(entries.len(), 2, "only the two failures are recorded");
14286
14287 assert_eq!(entries[0].op, "Timedelta::add");
14288 assert_eq!(entries[0].pandas_error, PandasTemporalError::Overflow);
14289 assert_eq!(entries[0].operands, Some((i64::MAX, 1)));
14290 assert_eq!(entries[0].recovered_as, i64::MIN);
14291
14292 assert_eq!(entries[1].op, "Timedelta::div_scalar");
14293 assert_eq!(entries[1].pandas_error, PandasTemporalError::ZeroDivision);
14294 assert_eq!(entries[1].operands, Some((5, 0)));
14295
14296 assert!(overflow_audit::drain().is_empty());
14298
14299 let _ = OverflowPolicy::SurfaceNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14301 let _ = OverflowPolicy::Strict.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14302 assert!(
14303 overflow_audit::drain().is_empty(),
14304 "SurfaceNat/Strict must not write to the audit trail"
14305 );
14306
14307 overflow_audit::disable();
14308 assert!(!overflow_audit::is_enabled());
14309 let _ =
14311 OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14312 assert!(
14313 overflow_audit::drain().is_empty(),
14314 "disabled must not record"
14315 );
14316 }
14317
14318 #[test]
14336 fn strict_reproduces_pandas_silent_timedelta_wrap_s4lkx() {
14337 use super::{OverflowPolicy, nancumsum_with_policy};
14338
14339 assert_eq!(
14341 Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::Strict),
14342 -2,
14343 "STRICT must reproduce pandas' wrap, not repair it"
14344 );
14345
14346 let max = Scalar::Timedelta64(i64::MAX);
14349 let out = nancumsum_with_policy(
14350 &[max.clone(), max.clone(), max.clone()],
14351 OverflowPolicy::Strict,
14352 );
14353 assert_eq!(
14354 out,
14355 vec![
14356 Scalar::Timedelta64(i64::MAX),
14357 Scalar::Timedelta64(-2),
14358 Scalar::Timedelta64(i64::MAX - 2),
14359 ],
14360 "STRICT cumsum must reproduce pandas' int64 wraparound exactly"
14361 );
14362
14363 assert_eq!(
14365 Timedelta::mul_scalar_with_policy(Timedelta::NAT, 2, OverflowPolicy::Strict),
14366 Timedelta::NAT
14367 );
14368 }
14369
14370 #[test]
14376 fn non_strict_policies_still_refuse_to_wrap_s4lkx() {
14377 use super::{OverflowPolicy, nancumsum_with_policy, overflow_audit};
14378
14379 for policy in [OverflowPolicy::SurfaceNat, OverflowPolicy::HardenedNat] {
14380 assert_eq!(
14381 Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14382 Timedelta::NAT,
14383 "{policy:?} must NOT wrap"
14384 );
14385 assert_ne!(
14386 Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14387 -2,
14388 "{policy:?} must not reproduce the pandas quirk"
14389 );
14390 }
14391 assert_eq!(
14393 Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::default()),
14394 Timedelta::NAT
14395 );
14396
14397 let max = Scalar::Timedelta64(i64::MAX);
14399 let soft = nancumsum_with_policy(&[max.clone(), max.clone()], OverflowPolicy::SurfaceNat);
14400 assert!(soft[1].is_missing(), "non-STRICT cumsum must NaT, not wrap");
14401 assert_eq!(soft, super::nancumsum(&[max.clone(), max]));
14402
14403 overflow_audit::enable();
14406 let _ = Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::HardenedNat);
14407 assert_eq!(
14408 overflow_audit::drain().len(),
14409 1,
14410 "HARDENED must record the recovery it performed"
14411 );
14412 overflow_audit::disable();
14413 }
14414
14415 #[test]
14418 fn datetime64_mixed_input_still_falls_back_axhhk() {
14419 let vals = vec![Scalar::Datetime64(DT_2020), Scalar::Int64(5)];
14420 assert!(super::nanmin(&vals).is_missing());
14431 assert_eq!(super::nanptp(&vals), Scalar::Float64(0.0));
14432 }
14433
14434 #[test]
14435 fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
14436 let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
14440 assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
14442 }
14443
14444 #[test]
14445 fn nancount_counts_non_missing() {
14446 let vals = vec![
14447 Scalar::Int64(1),
14448 Scalar::Null(NullKind::Null),
14449 Scalar::Float64(3.0),
14450 ];
14451 assert_eq!(super::nancount(&vals), Scalar::Int64(2));
14452 }
14453
14454 #[test]
14455 fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
14456 fn next(seed: &mut u64) -> u64 {
14459 *seed = seed
14460 .wrapping_mul(6364136223846793005)
14461 .wrapping_add(1442695040888963407);
14462 *seed
14463 }
14464
14465 fn truthy(value: &Scalar) -> Option<bool> {
14466 if value.is_missing() {
14467 return None;
14468 }
14469 match value {
14470 Scalar::Bool(value) => Some(*value),
14471 Scalar::Int64(value) => Some(*value != 0),
14472 Scalar::Float64(value) => Some(*value != 0.0),
14473 Scalar::Utf8(value) => Some(!value.is_empty()),
14474 Scalar::Timedelta64(value) => Some(*value != 0),
14475 _ => None,
14476 }
14477 }
14478
14479 fn assert_nanops(case: usize, values: &[Scalar]) {
14480 let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
14481 let expected_any = truth_values.iter().any(|value| *value);
14482 let expected_all = !truth_values.iter().any(|value| !*value);
14483 let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
14484
14485 assert_eq!(
14486 super::nanany(values),
14487 Scalar::Bool(expected_any),
14488 "case={case}: nanany mismatch for {values:?}"
14489 );
14490 assert_eq!(
14491 super::nanall(values),
14492 Scalar::Bool(expected_all),
14493 "case={case}: nanall mismatch for {values:?}"
14494 );
14495 assert_eq!(
14496 super::nancount(values),
14497 Scalar::Int64(expected_count),
14498 "case={case}: nancount mismatch for {values:?}"
14499 );
14500 }
14501
14502 assert_nanops(
14503 usize::MAX,
14504 &[
14505 Scalar::Null(NullKind::Null),
14506 Scalar::Null(NullKind::NaN),
14507 Scalar::Float64(f64::NAN),
14508 Scalar::Timedelta64(i64::MIN),
14509 ],
14510 );
14511
14512 let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
14513 for case in 0..320 {
14514 let len = (next(&mut seed) % 89 + 1) as usize;
14515 let mut values = Vec::with_capacity(len);
14516 for pos in 0..len {
14517 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
14518 let value = match next(&mut seed) % 12 {
14519 0 => Scalar::Null(NullKind::Null),
14520 1 => Scalar::Null(NullKind::NaN),
14521 2 => Scalar::Float64(f64::NAN),
14522 3 => Scalar::Bool(raw & 1 == 0),
14523 4 => Scalar::Bool(false),
14524 5 => Scalar::Int64(raw % 17),
14525 6 => Scalar::Int64(0),
14526 7 => Scalar::Float64(raw as f64 / 23.0),
14527 8 => Scalar::Float64(0.0),
14528 9 => Scalar::Utf8(if raw & 1 == 0 {
14529 String::new()
14530 } else {
14531 format!("nanops_{case}_{pos}")
14532 }),
14533 10 => Scalar::Timedelta64(raw),
14534 _ => Scalar::Timedelta64(0),
14535 };
14536 values.push(value);
14537 }
14538 assert_nanops(case, &values);
14539 }
14540 }
14541
14542 #[test]
14543 fn nanmin_basic() {
14544 let vals = vec![
14545 Scalar::Float64(5.0),
14546 Scalar::Null(NullKind::Null),
14547 Scalar::Float64(2.0),
14548 Scalar::Float64(8.0),
14549 ];
14550 assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
14551 }
14552
14553 #[test]
14554 fn nanmax_basic() {
14555 let vals = vec![
14556 Scalar::Float64(5.0),
14557 Scalar::Float64(f64::NAN),
14558 Scalar::Float64(8.0),
14559 ];
14560 assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
14561 }
14562
14563 #[test]
14564 fn nanmin_nanmax_empty_returns_nan() {
14565 assert!(super::nanmin(&[]).is_missing());
14566 assert!(super::nanmax(&[]).is_missing());
14567 }
14568
14569 #[test]
14570 fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
14571 fn next(seed: &mut u64) -> u64 {
14574 *seed = seed
14575 .wrapping_mul(6364136223846793005)
14576 .wrapping_add(1442695040888963407);
14577 *seed
14578 }
14579
14580 fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
14581 match (left, right) {
14582 (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
14583 (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
14584 (Scalar::Float64(left), Scalar::Float64(right)) => {
14585 left.partial_cmp(right).expect("finite floats")
14586 }
14587 (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
14588 (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
14589 _ => std::cmp::Ordering::Equal,
14592 }
14593 }
14594
14595 fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
14596 let present = values
14597 .iter()
14598 .filter(|value| !value.is_missing())
14599 .cloned()
14600 .collect::<Vec<_>>();
14601 let actual_min = super::nanmin(values);
14602 let actual_max = super::nanmax(values);
14603 if present.is_empty() {
14604 assert!(
14605 actual_min.is_missing(),
14606 "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
14607 );
14608 assert!(
14609 actual_max.is_missing(),
14610 "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
14611 );
14612 return;
14613 }
14614
14615 let is_expected_family = |value: &Scalar| match family {
14616 "int" => matches!(value, Scalar::Int64(_)),
14617 "float" => matches!(value, Scalar::Float64(_)),
14618 "bool" => matches!(value, Scalar::Bool(_)),
14619 "utf8" => matches!(value, Scalar::Utf8(_)),
14620 "timedelta" => matches!(value, Scalar::Timedelta64(_)),
14621 _ => false,
14622 };
14623 assert!(
14624 present.iter().all(is_expected_family),
14625 "case={case} family={family}: mixed family escaped generator: {values:?}"
14626 );
14627
14628 let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
14629 let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
14630 assert!(
14631 actual_min.semantic_eq(expected_min.expect("min")),
14632 "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
14633 expected_min.expect("min")
14634 );
14635 assert!(
14636 actual_max.semantic_eq(expected_max.expect("max")),
14637 "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
14638 expected_max.expect("max")
14639 );
14640 }
14641
14642 let all_missing = [
14643 Scalar::Null(NullKind::Null),
14644 Scalar::Null(NullKind::NaN),
14645 Scalar::Float64(f64::NAN),
14646 Scalar::Timedelta64(i64::MIN),
14647 ];
14648 assert_minmax(usize::MAX, "all_missing", &all_missing);
14649
14650 let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
14651 for case in 0..240 {
14652 let len = (next(&mut seed) % 73 + 1) as usize;
14653
14654 let mut ints = Vec::with_capacity(len);
14655 ints.push(Scalar::Int64(case as i64 - 120));
14656 for _ in 1..len {
14657 let raw = (next(&mut seed) % 1_001) as i64 - 500;
14658 ints.push(match next(&mut seed) % 6 {
14659 0 => Scalar::Null(NullKind::Null),
14660 1 => Scalar::Null(NullKind::NaN),
14661 _ => Scalar::Int64(raw),
14662 });
14663 }
14664 assert_minmax(case, "int", &ints);
14665
14666 let mut floats = Vec::with_capacity(len);
14667 floats.push(Scalar::Float64(case as f64 / 11.0));
14668 for _ in 1..len {
14669 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14670 floats.push(match next(&mut seed) % 8 {
14671 0 | 1 => Scalar::Float64(f64::NAN),
14672 2 => Scalar::Float64(f64::INFINITY),
14673 3 => Scalar::Float64(f64::NEG_INFINITY),
14674 4 => Scalar::Float64(0.0),
14675 5 => Scalar::Float64(-0.0),
14676 _ => Scalar::Float64(raw as f64 / 41.0),
14677 });
14678 }
14679 assert_minmax(case, "float", &floats);
14680
14681 let mut bools = Vec::with_capacity(len);
14682 bools.push(Scalar::Bool(case & 1 == 0));
14683 for _ in 1..len {
14684 bools.push(match next(&mut seed) % 5 {
14685 0 => Scalar::Null(NullKind::Null),
14686 1 => Scalar::Null(NullKind::NaN),
14687 raw => Scalar::Bool(raw & 1 == 0),
14688 });
14689 }
14690 assert_minmax(case, "bool", &bools);
14691
14692 let mut utf8 = Vec::with_capacity(len);
14693 utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
14694 for pos in 1..len {
14695 utf8.push(match next(&mut seed) % 7 {
14696 0 => Scalar::Null(NullKind::Null),
14697 1 => Scalar::Null(NullKind::NaN),
14698 raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
14699 });
14700 }
14701 assert_minmax(case, "utf8", &utf8);
14702
14703 let mut timedeltas = Vec::with_capacity(len);
14704 timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
14705 for _ in 1..len {
14706 let raw = (next(&mut seed) % 1_003) as i64 - 501;
14707 timedeltas.push(match next(&mut seed) % 7 {
14708 0 => Scalar::Null(NullKind::Null),
14709 1 => Scalar::Timedelta64(i64::MIN),
14710 _ => Scalar::Timedelta64(raw),
14711 });
14712 }
14713 assert_minmax(case, "timedelta", &timedeltas);
14714 }
14715 }
14716
14717 #[test]
14718 fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
14719 let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
14720 assert!(super::nanmin(&vals).is_missing());
14721 assert!(super::nanmax(&vals).is_missing());
14722
14723 let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
14724 assert!(super::nanmin(&vals2).is_missing());
14725 assert!(super::nanmax(&vals2).is_missing());
14726 }
14727
14728 #[test]
14729 fn nanmin_nanmax_compatible_numeric_types_ok() {
14730 let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
14731 assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
14732 assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
14733 }
14734
14735 #[test]
14736 fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
14737 let one_hour = 3_600 * 1_000_000_000_i64;
14741 let vals = vec![
14742 Scalar::Timedelta64(3 * one_hour),
14743 Scalar::Timedelta64(one_hour),
14744 Scalar::Timedelta64(2 * one_hour),
14745 ];
14746 assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
14747 assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
14748 }
14749
14750 #[test]
14751 fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
14752 let one_hour = 3_600 * 1_000_000_000_i64;
14753 let vals = vec![
14754 Scalar::Timedelta64(Timedelta::NAT),
14755 Scalar::Timedelta64(one_hour),
14756 Scalar::Timedelta64(2 * one_hour),
14757 Scalar::Timedelta64(Timedelta::NAT),
14758 ];
14759 assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
14760 assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
14761 }
14762
14763 #[test]
14764 fn nanmedian_odd_count() {
14765 let vals = vec![
14766 Scalar::Float64(3.0),
14767 Scalar::Null(NullKind::Null),
14768 Scalar::Float64(1.0),
14769 Scalar::Float64(2.0),
14770 ];
14771 assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
14772 }
14773
14774 #[test]
14775 fn nanmedian_even_count() {
14776 let vals = vec![
14777 Scalar::Float64(1.0),
14778 Scalar::Float64(3.0),
14779 Scalar::Float64(2.0),
14780 Scalar::Float64(4.0),
14781 ];
14782 assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
14783 }
14784
14785 #[test]
14786 fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
14787 fn next(seed: &mut u64) -> u64 {
14790 *seed = seed
14791 .wrapping_mul(6364136223846793005)
14792 .wrapping_add(1442695040888963407);
14793 *seed
14794 }
14795
14796 fn expected_numeric(values: &[Scalar]) -> Scalar {
14797 let mut finite = values
14798 .iter()
14799 .filter(|value| !value.is_missing())
14800 .filter_map(|value| value.to_f64().ok())
14801 .filter(|value| !value.is_nan())
14802 .collect::<Vec<_>>();
14803 if finite.is_empty() {
14804 return Scalar::Null(NullKind::NaN);
14805 }
14806 finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
14807 let mid = finite.len() / 2;
14808 if finite.len().is_multiple_of(2) {
14809 Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
14810 } else {
14811 Scalar::Float64(finite[mid])
14812 }
14813 }
14814
14815 fn expected_timedelta(values: &[Scalar]) -> Scalar {
14816 let mut finite = values
14817 .iter()
14818 .filter_map(|value| match value {
14819 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns),
14820 _ => None,
14821 })
14822 .collect::<Vec<_>>();
14823 if finite.is_empty() {
14824 return Scalar::Null(NullKind::NaN);
14825 }
14826 finite.sort_unstable();
14827 let mid = finite.len() / 2;
14828 let median = if finite.len().is_multiple_of(2) {
14829 (i128::from(finite[mid - 1]) + i128::from(finite[mid])) / 2
14830 } else {
14831 i128::from(finite[mid])
14832 };
14833 Scalar::Timedelta64(median as i64)
14834 }
14835
14836 fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
14837 let actual = super::nanmedian(values);
14838 assert!(
14839 actual.semantic_eq(&expected),
14840 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
14841 );
14842 }
14843
14844 assert_median(
14845 usize::MAX,
14846 "numeric_all_missing",
14847 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
14848 Scalar::Null(NullKind::NaN),
14849 );
14850 assert_median(
14851 usize::MAX - 1,
14852 "timedelta_all_missing",
14853 &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
14854 Scalar::Null(NullKind::NaN),
14855 );
14856 let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
14857 assert_median(
14858 usize::MAX - 2,
14859 "timedelta_odd_median_beyond_f64_exactness",
14860 &[
14861 Scalar::Timedelta64(beyond_f64_exact_ns),
14862 Scalar::Timedelta64(beyond_f64_exact_ns + 1),
14863 Scalar::Timedelta64(beyond_f64_exact_ns + 2),
14864 Scalar::Timedelta64(Timedelta::NAT),
14865 ],
14866 Scalar::Timedelta64(beyond_f64_exact_ns + 1),
14867 );
14868
14869 let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
14870 for case in 0..220 {
14871 let len = (next(&mut seed) % 79 + 1) as usize;
14872
14873 let mut numeric = Vec::with_capacity(len);
14874 numeric.push(Scalar::Int64(case as i64 - 110));
14875 for _ in 1..len {
14876 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14877 numeric.push(match next(&mut seed) % 8 {
14878 0 => Scalar::Null(NullKind::Null),
14879 1 => Scalar::Null(NullKind::NaN),
14880 2 => Scalar::Float64(f64::NAN),
14881 3 => Scalar::Bool(raw & 1 == 0),
14882 4 => Scalar::Int64(raw % 251),
14883 5 => Scalar::Float64(raw as f64 / 61.0),
14884 6 => Scalar::Float64(0.0),
14885 _ => Scalar::Float64(-0.0),
14886 });
14887 }
14888 assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
14889
14890 let mut timedeltas = Vec::with_capacity(len);
14891 timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
14892 for _ in 1..len {
14893 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14894 timedeltas.push(match next(&mut seed) % 7 {
14895 0 => Scalar::Null(NullKind::Null),
14896 1 => Scalar::Timedelta64(i64::MIN),
14897 _ => Scalar::Timedelta64(raw),
14898 });
14899 }
14900 assert_median(
14901 case,
14902 "timedelta",
14903 &timedeltas,
14904 expected_timedelta(&timedeltas),
14905 );
14906 }
14907 }
14908
14909 #[test]
14910 fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
14911 fn next(seed: &mut u64) -> u64 {
14914 *seed = seed
14915 .wrapping_mul(2862933555777941757)
14916 .wrapping_add(3037000493);
14917 *seed
14918 }
14919
14920 fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
14921 values
14922 .iter()
14923 .filter(|value| !value.is_missing())
14924 .filter_map(|value| value.to_f64().ok())
14925 .collect()
14926 }
14927
14928 fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
14929 values
14930 .iter()
14931 .filter_map(|value| match value {
14932 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
14933 _ => None,
14934 })
14935 .collect()
14936 }
14937
14938 fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
14939 if samples.len() <= ddof {
14940 return None;
14941 }
14942 let mean = samples.iter().sum::<f64>() / samples.len() as f64;
14943 let sum_sq = samples
14944 .iter()
14945 .map(|value| (value - mean).powi(2))
14946 .sum::<f64>();
14947 let var = sum_sq / (samples.len() - ddof) as f64;
14948 let std = var.sqrt();
14949 let sem = std / (samples.len() as f64).sqrt();
14950 Some((var, std, sem))
14951 }
14952
14953 fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
14954 let samples = numeric_samples(values);
14955 let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
14956 let missing = Scalar::Null(NullKind::NaN);
14957 return (missing.clone(), missing.clone(), missing);
14958 };
14959 (
14960 Scalar::Float64(var),
14961 Scalar::Float64(std),
14962 Scalar::Float64(sem),
14963 )
14964 }
14965
14966 fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
14967 let samples = timedelta_samples(values);
14968 if samples.is_empty() {
14969 let missing = Scalar::Timedelta64(Timedelta::NAT);
14970 return (missing.clone(), missing.clone(), missing);
14971 }
14972 let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
14973 let missing = Scalar::Timedelta64(i64::MIN);
14974 return (missing.clone(), missing.clone(), missing);
14975 };
14976 (
14977 Scalar::Timedelta64(var as i64),
14978 Scalar::Timedelta64(std as i64),
14979 Scalar::Timedelta64(sem as i64),
14980 )
14981 }
14982
14983 fn assert_reductions(
14984 case: usize,
14985 family: &str,
14986 values: &[Scalar],
14987 ddof: usize,
14988 expected: (Scalar, Scalar, Scalar),
14989 ) {
14990 let (expected_var, expected_std, expected_sem) = expected;
14991 let actual_var = super::nanvar(values, ddof);
14992 let actual_std = super::nanstd(values, ddof);
14993 let actual_sem = super::nansem(values, ddof);
14994 assert!(
14995 actual_var.semantic_eq(&expected_var),
14996 "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
14997 );
14998 assert!(
14999 actual_std.semantic_eq(&expected_std),
15000 "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
15001 );
15002 assert!(
15003 actual_sem.semantic_eq(&expected_sem),
15004 "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
15005 );
15006 }
15007
15008 let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15009 assert_reductions(
15010 usize::MAX,
15011 "numeric_all_missing",
15012 &numeric_all_missing,
15013 0,
15014 expected_numeric(&numeric_all_missing, 0),
15015 );
15016
15017 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
15018 assert_reductions(
15019 usize::MAX - 1,
15020 "timedelta_all_missing",
15021 &td_all_missing,
15022 0,
15023 expected_timedelta(&td_all_missing, 0),
15024 );
15025
15026 let mut seed = 0x7a11_c0de_5eed_0421_u64;
15027 for case in 0..240 {
15028 let len = (next(&mut seed) % 83 + 1) as usize;
15029 let ddof = (next(&mut seed) % 4) as usize;
15030
15031 let mut numeric = Vec::with_capacity(len);
15032 numeric.push(Scalar::Float64(case as f64 / 13.0));
15033 for _ in 1..len {
15034 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15035 numeric.push(match next(&mut seed) % 8 {
15036 0 => Scalar::Null(NullKind::Null),
15037 1 => Scalar::Null(NullKind::NaN),
15038 2 => Scalar::Float64(f64::NAN),
15039 3 => Scalar::Bool(raw & 1 == 0),
15040 4 => Scalar::Int64(raw % 251),
15041 5 => Scalar::Float64(raw as f64 / 73.0),
15042 6 => Scalar::Float64(0.0),
15043 _ => Scalar::Float64(-0.0),
15044 });
15045 }
15046 assert_reductions(
15047 case,
15048 "numeric",
15049 &numeric,
15050 ddof,
15051 expected_numeric(&numeric, ddof),
15052 );
15053
15054 let mut timedeltas = Vec::with_capacity(len);
15055 timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15056 for _ in 1..len {
15057 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15058 timedeltas.push(match next(&mut seed) % 7 {
15059 0 => Scalar::Null(NullKind::Null),
15060 1 => Scalar::Timedelta64(i64::MIN),
15061 _ => Scalar::Timedelta64(raw),
15062 });
15063 }
15064 assert_reductions(
15065 case,
15066 "timedelta",
15067 &timedeltas,
15068 ddof,
15069 expected_timedelta(&timedeltas, ddof),
15070 );
15071 }
15072 }
15073
15074 #[test]
15075 fn nanvar_population() {
15076 let vals = vec![
15077 Scalar::Float64(2.0),
15078 Scalar::Float64(4.0),
15079 Scalar::Float64(4.0),
15080 Scalar::Float64(4.0),
15081 Scalar::Float64(5.0),
15082 Scalar::Float64(5.0),
15083 Scalar::Float64(7.0),
15084 Scalar::Float64(9.0),
15085 ];
15086 let var = super::nanvar(&vals, 0);
15087 assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15088 if let Scalar::Float64(v) = var {
15089 assert!((v - 4.0).abs() < 1e-10);
15090 }
15091 }
15092
15093 #[test]
15094 fn nanvar_sample_ddof1() {
15095 let vals = vec![
15096 Scalar::Float64(2.0),
15097 Scalar::Float64(4.0),
15098 Scalar::Float64(4.0),
15099 Scalar::Float64(4.0),
15100 Scalar::Float64(5.0),
15101 Scalar::Float64(5.0),
15102 Scalar::Float64(7.0),
15103 Scalar::Float64(9.0),
15104 ];
15105 let var = super::nanvar(&vals, 1);
15106 assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15107 if let Scalar::Float64(v) = var {
15108 assert!((v - 32.0 / 7.0).abs() < 1e-10);
15109 }
15110 }
15111
15112 #[test]
15113 fn nanvar_insufficient_values_returns_nan() {
15114 let vals = vec![Scalar::Float64(5.0)];
15115 assert!(super::nanvar(&vals, 1).is_missing());
15116 }
15117
15118 #[test]
15119 fn nanstd_is_sqrt_of_var() {
15120 let vals = vec![
15121 Scalar::Float64(2.0),
15122 Scalar::Float64(4.0),
15123 Scalar::Float64(4.0),
15124 Scalar::Float64(4.0),
15125 Scalar::Float64(5.0),
15126 Scalar::Float64(5.0),
15127 Scalar::Float64(7.0),
15128 Scalar::Float64(9.0),
15129 ];
15130 let std = super::nanstd(&vals, 0);
15131 assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
15132 if let Scalar::Float64(v) = std {
15133 assert!((v - 2.0).abs() < 1e-10);
15134 }
15135 }
15136
15137 #[test]
15138 fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
15139 let one_hour = 3_600 * 1_000_000_000_i64;
15142 let vals = vec![
15143 Scalar::Timedelta64(one_hour),
15144 Scalar::Timedelta64(2 * one_hour),
15145 Scalar::Timedelta64(3 * one_hour),
15146 ];
15147 assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
15148 }
15149
15150 #[test]
15151 fn nanstd_timedelta64_preserves_dtype_j8ntk() {
15152 let one_hour: i64 = 3_600 * 1_000_000_000;
15156 let vals = vec![
15157 Scalar::Timedelta64(one_hour),
15158 Scalar::Timedelta64(2 * one_hour),
15159 Scalar::Timedelta64(3 * one_hour),
15160 ];
15161 let std = super::nanstd(&vals, 0);
15162 assert!(matches!(std, Scalar::Timedelta64(_)));
15163 if let Scalar::Timedelta64(ns) = std {
15164 let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
15165 assert!(
15166 (ns as f64 - expected).abs() < 1e6,
15167 "expected ~{expected} ns, got {ns}"
15168 );
15169 }
15170 }
15171
15172 #[test]
15173 fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
15174 let one_hour = 3_600 * 1_000_000_000_i64;
15175 let vals = vec![Scalar::Timedelta64(one_hour)];
15176 assert_eq!(super::nanstd(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15178 assert_eq!(super::nansem(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15179 }
15180
15181 #[test]
15182 fn nanops_with_mixed_types() {
15183 let vals = vec![
15184 Scalar::Bool(true),
15185 Scalar::Int64(3),
15186 Scalar::Float64(6.0),
15187 Scalar::Null(NullKind::Null),
15188 ];
15189 assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
15190 assert_eq!(super::nancount(&vals), Scalar::Int64(3));
15191 }
15192
15193 #[test]
15194 fn nanops_all_missing_returns_identity() {
15195 let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15196 assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
15197 assert!(super::nanmean(&vals).is_missing());
15198 assert!(super::nanmedian(&vals).is_missing());
15199 assert!(super::nanvar(&vals, 0).is_missing());
15200 assert!(super::nanstd(&vals, 0).is_missing());
15201 }
15202
15203 #[test]
15206 fn timedelta_parse_simple_units() {
15207 use super::Timedelta;
15208 assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
15209 assert_eq!(
15210 Timedelta::parse("2h").unwrap(),
15211 2 * Timedelta::NANOS_PER_HOUR
15212 );
15213 assert_eq!(
15214 Timedelta::parse("30m").unwrap(),
15215 30 * Timedelta::NANOS_PER_MIN
15216 );
15217 assert_eq!(
15218 Timedelta::parse("45s").unwrap(),
15219 45 * Timedelta::NANOS_PER_SEC
15220 );
15221 assert_eq!(
15222 Timedelta::parse("100ms").unwrap(),
15223 100 * Timedelta::NANOS_PER_MILLI
15224 );
15225 assert_eq!(
15226 Timedelta::parse("500us").unwrap(),
15227 500 * Timedelta::NANOS_PER_MICRO
15228 );
15229 assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
15230 }
15231
15232 #[test]
15233 fn timedelta_parse_zero_valued_compound() {
15234 use super::Timedelta;
15235 for s in [
15242 "0 seconds",
15243 "0 second",
15244 "0 sec",
15245 "0s",
15246 "0 days",
15247 "0d",
15248 "0 hours",
15249 "0.0 hours",
15250 "0 minutes",
15251 "0ms",
15252 "0us",
15253 "0ns",
15254 "0",
15255 "0 days 0 seconds",
15256 ] {
15257 assert_eq!(Timedelta::parse(s).unwrap(), 0, "parse({s:?}) should be 0");
15258 }
15259 assert_eq!(Timedelta::parse("-0 seconds").unwrap(), 0);
15261 assert!(Timedelta::parse("0 fortnights").is_err());
15264 assert!(Timedelta::parse("seconds").is_err());
15265 }
15266
15267 #[test]
15268 fn timedelta_parse_compound() {
15269 use super::Timedelta;
15270 let expected = Timedelta::NANOS_PER_DAY
15271 + 2 * Timedelta::NANOS_PER_HOUR
15272 + 30 * Timedelta::NANOS_PER_MIN;
15273 assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
15274 assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
15275 }
15276
15277 #[test]
15278 fn timedelta_parse_leading_sign_spares_the_clock_part() {
15279 use super::Timedelta;
15280 const S: i64 = Timedelta::NANOS_PER_SEC;
15281 assert_eq!(Timedelta::parse("-1 days 02:03:04").unwrap(), -79_016 * S);
15284 assert_eq!(Timedelta::parse("-1 days +02:03:04").unwrap(), -79_016 * S);
15285 assert_eq!(
15286 Timedelta::parse("-3 days +23:59:59.5").unwrap(),
15287 -172_800 * S - S / 2
15288 );
15289 assert_eq!(Timedelta::parse("-0 days 01:00:00").unwrap(), 3_600 * S);
15290 assert_eq!(Timedelta::parse("-1d2h").unwrap(), -93_600 * S);
15292 assert_eq!(Timedelta::parse("-02:03:04").unwrap(), -7_384 * S);
15293 assert!(Timedelta::parse("-1 days -02:03:04").is_err());
15295 assert!(Timedelta::parse("1 days -02:00:00").is_err());
15296 }
15297
15298 #[test]
15299 fn timedelta_parse_iso8601_matches_pandas_tdiso() {
15300 use super::Timedelta;
15301 assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
15303 assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
15304 assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
15305 assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
15306 assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
15307 assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
15308 assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
15310 assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
15311 assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
15312 assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
15313 assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
15314 assert!(Timedelta::parse("P1Y").is_err());
15316 assert!(Timedelta::parse("p1d").is_err());
15317 assert!(Timedelta::parse("P").is_err());
15318 assert!(Timedelta::parse("PT").is_err());
15319 }
15320
15321 #[test]
15322 fn timedelta_parse_time_format() {
15323 use super::Timedelta;
15324 let expected = Timedelta::NANOS_PER_HOUR
15325 + 30 * Timedelta::NANOS_PER_MIN
15326 + 45 * Timedelta::NANOS_PER_SEC;
15327 assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
15328 }
15329
15330 #[test]
15331 fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
15332 use super::{Timedelta, TimedeltaError};
15333 let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
15334 .expect_err("non-ASCII fractional seconds must reject");
15335 assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15336 }
15337
15338 #[test]
15339 fn timedelta_parse_time_format_rejects_overflow_without_panic() {
15340 use super::{Timedelta, TimedeltaError};
15341 let err = Timedelta::parse("9223372036854775807:00")
15342 .expect_err("oversized hour component must reject");
15343 assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15344 }
15345
15346 #[test]
15347 fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
15348 use super::{Timedelta, TimedeltaError};
15355 let huge = format!("{} days", "9".repeat(18));
15356 assert!(matches!(
15357 Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
15358 TimedeltaError::Overflow
15359 ));
15360 }
15361
15362 #[test]
15363 fn timedelta_parse_nat() {
15364 use super::Timedelta;
15365 assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
15366 assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
15367 }
15368
15369 #[test]
15370 fn timedelta_parse_negative() {
15371 use super::Timedelta;
15372 assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
15373 }
15374
15375 #[test]
15376 fn timedelta_components() {
15377 use super::Timedelta;
15378 let nanos = Timedelta::NANOS_PER_DAY
15379 + Timedelta::NANOS_PER_HOUR
15380 + Timedelta::NANOS_PER_MIN
15381 + Timedelta::NANOS_PER_SEC
15382 + Timedelta::NANOS_PER_MILLI
15383 + 2 * Timedelta::NANOS_PER_MICRO
15384 + 3;
15385 let comp = Timedelta::components(nanos);
15386 assert_eq!(comp.days, 1);
15387 assert_eq!(comp.hours, 1);
15388 assert_eq!(comp.minutes, 1);
15389 assert_eq!(comp.seconds, 1);
15390 assert_eq!(comp.milliseconds, 1);
15391 assert_eq!(comp.microseconds, 2);
15392 assert_eq!(comp.nanoseconds, 3);
15393 }
15394
15395 #[test]
15396 fn timedelta_negative_components_floor_div() {
15397 use super::Timedelta;
15398 let neg_1s = -Timedelta::NANOS_PER_SEC;
15401 assert_eq!(Timedelta::days(neg_1s), Some(-1));
15402 assert_eq!(Timedelta::seconds(neg_1s), Some(86399));
15403 assert_eq!(Timedelta::microseconds(neg_1s), Some(0));
15404 assert_eq!(Timedelta::nanoseconds(neg_1s), Some(0));
15405 let comp = Timedelta::components(neg_1s);
15406 assert_eq!(
15407 (
15408 comp.days,
15409 comp.hours,
15410 comp.minutes,
15411 comp.seconds,
15412 comp.milliseconds,
15413 comp.microseconds,
15414 comp.nanoseconds
15415 ),
15416 (-1, 23, 59, 59, 0, 0, 0)
15417 );
15418
15419 let neg = -86_401 * Timedelta::NANOS_PER_SEC;
15421 assert_eq!(Timedelta::days(neg), Some(-2));
15422 assert_eq!(Timedelta::seconds(neg), Some(86399));
15423 }
15424
15425 #[test]
15440 fn timedelta_components_are_missing_for_nat_not_zero_406ni() {
15441 use super::Timedelta;
15442 assert_eq!(Timedelta::days(Timedelta::NAT), None);
15443 assert_eq!(Timedelta::seconds(Timedelta::NAT), None);
15444 assert_eq!(Timedelta::microseconds(Timedelta::NAT), None);
15445 assert_eq!(Timedelta::nanoseconds(Timedelta::NAT), None);
15446
15447 let one_day = Timedelta::NANOS_PER_DAY;
15452 assert_eq!(Timedelta::days(one_day), Some(1));
15453 assert_eq!(Timedelta::seconds(one_day), Some(0));
15454 assert_eq!(Timedelta::microseconds(one_day), Some(0));
15455 assert_eq!(Timedelta::nanoseconds(one_day), Some(0));
15456 }
15457
15458 #[test]
15459 fn timedelta_total_seconds() {
15460 use super::Timedelta;
15461 let nanos = 90_000_000_000i64; assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
15463 assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
15464 }
15465
15466 #[test]
15467 fn timedelta_format_basic() {
15468 use super::Timedelta;
15469 assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
15470 assert_eq!(
15471 Timedelta::format(Timedelta::NANOS_PER_DAY),
15472 "1 days 00:00:00"
15473 );
15474 assert_eq!(
15475 Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
15476 "1 days 02:00:00"
15477 );
15478 }
15479
15480 #[test]
15481 fn timedelta_format_subsecond_matches_pandas() {
15482 use super::Timedelta;
15483 assert_eq!(
15487 Timedelta::format(1_500_000_000), "0 days 00:00:01.500000"
15489 );
15490 assert_eq!(
15491 Timedelta::format(1_000_000), "0 days 00:00:00.001000"
15493 );
15494 assert_eq!(
15495 Timedelta::format(123_456_000), "0 days 00:00:00.123456"
15497 );
15498 assert_eq!(
15500 Timedelta::format(500), "0 days 00:00:00.000000500"
15502 );
15503 assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
15504 }
15505
15506 #[test]
15507 fn timedelta_format_negative_uses_python_borrow_form() {
15508 use super::Timedelta;
15509 assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
15513 assert_eq!(
15514 Timedelta::format(-Timedelta::NANOS_PER_DAY),
15515 "-1 days +00:00:00"
15516 );
15517 assert_eq!(
15518 Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
15519 "-2 days +23:00:00"
15520 );
15521 assert_eq!(
15522 Timedelta::format(-1_500_000_000),
15523 "-1 days +23:59:58.500000"
15524 );
15525 assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
15526 assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
15527 }
15528
15529 #[test]
15530 #[ignore = "foreground release attribution harness"]
15531 fn timedelta_format_single_buffer_ab_5ro9h() {
15532 use std::{hint::black_box, time::Instant};
15533
15534 use super::Timedelta;
15535
15536 fn former(nanos: i64) -> String {
15537 if nanos == Timedelta::NAT {
15538 return "NaT".to_string();
15539 }
15540
15541 let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
15542 let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
15543 let hours = rem / Timedelta::NANOS_PER_HOUR;
15544 let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
15545 let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
15546 let frac = rem % Timedelta::NANOS_PER_SEC;
15547
15548 let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
15549 let sep = if days < 0 { "+" } else { "" };
15550 if frac > 0 {
15551 if frac % 1_000 == 0 {
15552 format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
15553 } else {
15554 format!("{days} days {sep}{time_part}.{frac:09}")
15555 }
15556 } else {
15557 format!("{days} days {sep}{time_part}")
15558 }
15559 }
15560
15561 fn candidate(nanos: i64) -> String {
15562 Timedelta::format(nanos)
15563 }
15564
15565 fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
15566 let started = Instant::now();
15567 let mut digest = 0_usize;
15568 for &value in values {
15569 digest = digest.wrapping_add(black_box(format(black_box(value))).len());
15570 }
15571 black_box(digest);
15572 started.elapsed().as_nanos()
15573 }
15574
15575 fn median(samples: &mut [u128]) -> u128 {
15576 samples.sort_unstable();
15577 samples[samples.len() / 2]
15578 }
15579
15580 let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
15581 let values: Vec<i64> = (0..16_384)
15582 .map(|i| {
15583 seed = seed
15584 .wrapping_mul(6_364_136_223_846_793_005)
15585 .wrapping_add(1_442_695_040_888_963_407);
15586 let magnitude = (seed & i64::MAX as u64) as i64;
15587 match i % 4 {
15588 0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
15589 1 => magnitude,
15590 2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
15591 _ => -magnitude,
15592 }
15593 })
15594 .collect();
15595
15596 for &value in &[
15597 Timedelta::NAT,
15598 0,
15599 1,
15600 -1,
15601 Timedelta::NANOS_PER_DAY,
15602 -Timedelta::NANOS_PER_DAY,
15603 i64::MAX,
15604 i64::MIN + 1,
15605 ] {
15606 assert_eq!(former(value), candidate(value));
15607 }
15608 for &value in &values {
15609 assert_eq!(former(value), candidate(value));
15610 }
15611
15612 for _ in 0..2 {
15613 black_box(elapsed(&values, former));
15614 black_box(elapsed(&values, candidate));
15615 }
15616
15617 let mut former_samples = Vec::with_capacity(18);
15618 let mut candidate_samples = Vec::with_capacity(18);
15619 for block in 0_usize..9 {
15620 if block.is_multiple_of(2) {
15621 former_samples.push(elapsed(&values, former));
15622 candidate_samples.push(elapsed(&values, candidate));
15623 candidate_samples.push(elapsed(&values, candidate));
15624 former_samples.push(elapsed(&values, former));
15625 } else {
15626 candidate_samples.push(elapsed(&values, candidate));
15627 former_samples.push(elapsed(&values, former));
15628 former_samples.push(elapsed(&values, former));
15629 candidate_samples.push(elapsed(&values, candidate));
15630 }
15631 }
15632
15633 let former_p50 = median(&mut former_samples);
15634 let candidate_p50 = median(&mut candidate_samples);
15635 eprintln!(
15636 "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
15637 values.len(),
15638 former_p50 as f64 / candidate_p50 as f64,
15639 );
15640 eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
15641 eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
15642 }
15643
15644 #[test]
15645 fn timedelta_isoformat_basic() {
15646 use super::Timedelta;
15647 assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
15648 assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
15649 assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
15650 assert_eq!(
15651 Timedelta::isoformat(
15652 Timedelta::NANOS_PER_DAY
15653 + 2 * Timedelta::NANOS_PER_HOUR
15654 + 30 * Timedelta::NANOS_PER_MIN
15655 + 45 * Timedelta::NANOS_PER_SEC
15656 ),
15657 "P1DT2H30M45S"
15658 );
15659 assert_eq!(
15660 Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
15661 "P0DT0H0M1.5S"
15662 );
15663 assert_eq!(
15668 Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
15669 "P-2DT23H0M0S"
15670 );
15671 assert_eq!(Timedelta::isoformat(-1), "P-1DT23H59M59.999999999S");
15672 }
15673
15674 #[test]
15675 #[ignore = "foreground release attribution harness"]
15676 fn timedelta_isoformat_single_buffer_ab_7jra1() {
15677 use std::{hint::black_box, time::Instant};
15678
15679 use super::Timedelta;
15680
15681 fn former_impl(nanos: i64) -> String {
15682 if nanos == Timedelta::NAT {
15683 return "NaT".to_string();
15684 }
15685
15686 let negative = nanos < 0;
15687 let abs_nanos = nanos.saturating_abs();
15688 let days = abs_nanos / Timedelta::NANOS_PER_DAY;
15689 let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
15690 let hours = remaining / Timedelta::NANOS_PER_HOUR;
15691 let remaining = remaining % Timedelta::NANOS_PER_HOUR;
15692 let minutes = remaining / Timedelta::NANOS_PER_MIN;
15693 let remaining = remaining % Timedelta::NANOS_PER_MIN;
15694 let seconds = remaining / Timedelta::NANOS_PER_SEC;
15695 let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
15696
15697 let mut result = String::new();
15698 if negative {
15699 result.push('-');
15700 }
15701
15702 result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
15703
15704 if sub_sec_nanos == 0 {
15705 result.push_str(&format!("{seconds}S"));
15706 } else {
15707 let frac = format!("{sub_sec_nanos:09}");
15708 let trimmed = frac.trim_end_matches('0');
15709 result.push_str(&format!("{seconds}.{trimmed}S"));
15710 }
15711
15712 result
15713 }
15714
15715 fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
15716 let start = Instant::now();
15717 let mut digest = 0_usize;
15718 for &value in values {
15719 digest = digest.wrapping_add(black_box(format(black_box(value))).len());
15720 }
15721 black_box(digest);
15722 start.elapsed().as_nanos()
15723 }
15724
15725 fn median(values: &mut [u128]) -> u128 {
15726 values.sort_unstable();
15727 values[values.len() / 2]
15728 }
15729
15730 let mut seed = 0x7d5a_4c31_91e2_b607_u64;
15731 let values: Vec<i64> = (0..16_384)
15732 .map(|i| {
15733 seed = seed
15734 .wrapping_mul(6_364_136_223_846_793_005)
15735 .wrapping_add(1_442_695_040_888_963_407);
15736 let magnitude =
15737 (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
15738 match i % 4 {
15739 0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
15740 1 => magnitude,
15741 2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
15742 _ => -magnitude,
15743 }
15744 })
15745 .collect();
15746
15747 for &value in &[Timedelta::NAT, 0, 1, Timedelta::NANOS_PER_DAY, i64::MAX] {
15751 assert_eq!(former_impl(value), Timedelta::isoformat(value));
15752 }
15753 for &value in values.iter().filter(|value| **value >= 0) {
15754 assert_eq!(former_impl(value), Timedelta::isoformat(value));
15755 }
15756
15757 for _ in 0..2 {
15758 black_box(elapsed(&values, former_impl));
15759 black_box(elapsed(&values, Timedelta::isoformat));
15760 }
15761
15762 let mut former = Vec::with_capacity(18);
15763 let mut candidate = Vec::with_capacity(18);
15764 for block in 0..9 {
15765 if block % 2 == 0 {
15766 former.push(elapsed(&values, former_impl));
15767 candidate.push(elapsed(&values, Timedelta::isoformat));
15768 candidate.push(elapsed(&values, Timedelta::isoformat));
15769 former.push(elapsed(&values, former_impl));
15770 } else {
15771 candidate.push(elapsed(&values, Timedelta::isoformat));
15772 former.push(elapsed(&values, former_impl));
15773 former.push(elapsed(&values, former_impl));
15774 candidate.push(elapsed(&values, Timedelta::isoformat));
15775 }
15776 }
15777
15778 let former_p50 = median(&mut former);
15779 let candidate_p50 = median(&mut candidate);
15780 eprintln!(
15781 "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
15782 values.len(),
15783 former_p50,
15784 candidate_p50,
15785 former_p50 as f64 / candidate_p50 as f64,
15786 former_p50 as f64 / values.len() as f64,
15787 candidate_p50 as f64 / values.len() as f64,
15788 );
15789 eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
15790 eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
15791 }
15792
15793 #[test]
15794 fn timedelta_floor_ceil_round() {
15795 use super::Timedelta;
15796 let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
15797
15798 assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
15800 assert_eq!(Timedelta::floor(nanos, "d"), 0);
15801
15802 assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
15804 assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
15805
15806 assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
15808
15809 assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
15811 assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
15812 assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
15813
15814 assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
15816 }
15817
15818 #[test]
15819 fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
15820 use super::Timedelta;
15821
15822 assert_eq!(
15823 Timedelta::floor(-1, "s"),
15824 -Timedelta::NANOS_PER_SEC,
15825 "floor(-1ns, 1s)"
15826 );
15827 assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
15828 assert_eq!(
15829 Timedelta::floor(-1_500_000_000, "s"),
15830 -2 * Timedelta::NANOS_PER_SEC
15831 );
15832 assert_eq!(
15833 Timedelta::ceil(-1_500_000_000, "s"),
15834 -Timedelta::NANOS_PER_SEC
15835 );
15836 assert_eq!(
15837 Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
15838 -Timedelta::NANOS_PER_SEC
15839 );
15840 assert_eq!(
15841 Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
15842 -Timedelta::NANOS_PER_SEC
15843 );
15844 assert_eq!(
15845 Timedelta::floor(1_500_000_000, "s"),
15846 Timedelta::NANOS_PER_SEC
15847 );
15848 assert_eq!(
15849 Timedelta::ceil(1_500_000_000, "s"),
15850 2 * Timedelta::NANOS_PER_SEC
15851 );
15852 }
15853
15854 #[test]
15855 fn timedelta_scalar_dtype() {
15856 let td = Scalar::Timedelta64(86_400_000_000_000);
15857 assert_eq!(td.dtype(), DType::Timedelta64);
15858 }
15859
15860 #[test]
15861 fn timedelta_scalar_is_missing() {
15862 use super::Timedelta;
15863 let valid = Scalar::Timedelta64(1000);
15864 let nat = Scalar::Timedelta64(Timedelta::NAT);
15865 assert!(!valid.is_missing());
15866 assert!(nat.is_missing());
15867 }
15868
15869 #[test]
15870 fn dtype_utf8_deserializes_legacy_aliases() {
15871 let dtype: DType = serde_json::from_str("\"str\"").unwrap();
15872 assert_eq!(dtype, DType::Utf8);
15873
15874 let dtype: DType = serde_json::from_str("\"string\"").unwrap();
15875 assert_eq!(dtype, DType::Utf8);
15876 }
15877
15878 #[test]
15879 fn datetime64_dtype_carries_timezone_00ze3() {
15880 let naive = DType::datetime64_naive();
15881 assert_eq!(naive.timezone(), None);
15882 assert_eq!(naive.display_name(), "datetime64[ns]");
15883
15884 let aware = DType::datetime64_tz("America/New_York");
15885 assert_eq!(aware.timezone(), Some("America/New_York"));
15886 assert_eq!(aware.display_name(), "datetime64[ns, America/New_York]");
15887 assert_ne!(aware, naive, "timezone must participate in dtype identity");
15888
15889 let json = serde_json::to_string(&aware).expect("serialize timezone dtype");
15890 assert_eq!(
15891 serde_json::from_str::<DType>(&json).expect("deserialize timezone dtype"),
15892 aware
15893 );
15894 }
15895
15896 #[test]
15897 fn scalar_utf8_deserializes_legacy_aliases() {
15898 let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
15899 assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
15900
15901 let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
15902 assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
15903 }
15904
15905 #[test]
15906 fn nancumsum_skips_nulls_and_accumulates() {
15907 let values = vec![
15908 Scalar::Float64(1.0),
15909 Scalar::Null(NullKind::NaN),
15910 Scalar::Float64(2.0),
15911 Scalar::Float64(3.0),
15912 ];
15913 let out = super::nancumsum(&values);
15914 assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
15915 assert!(out[1].is_missing());
15916 assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
15917 assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
15918 }
15919
15920 #[test]
15921 fn nancumprod_skips_nulls_and_multiplies() {
15922 let values = vec![
15923 Scalar::Float64(2.0),
15924 Scalar::Null(NullKind::NaN),
15925 Scalar::Float64(3.0),
15926 Scalar::Float64(4.0),
15927 ];
15928 let out = super::nancumprod(&values);
15929 assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
15930 assert!(out[1].is_missing());
15931 assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
15932 assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
15933 }
15934
15935 #[test]
15936 fn nancummax_tracks_running_max() {
15937 let values = vec![
15938 Scalar::Float64(1.0),
15939 Scalar::Float64(3.0),
15940 Scalar::Null(NullKind::NaN),
15941 Scalar::Float64(2.0),
15942 Scalar::Float64(5.0),
15943 ];
15944 let out = super::nancummax(&values);
15945 assert_eq!(out[0], Scalar::Float64(1.0));
15946 assert_eq!(out[1], Scalar::Float64(3.0));
15947 assert!(out[2].is_missing());
15948 assert_eq!(out[3], Scalar::Float64(3.0));
15949 assert_eq!(out[4], Scalar::Float64(5.0));
15950 }
15951
15952 #[test]
15953 fn nancummin_tracks_running_min() {
15954 let values = vec![
15955 Scalar::Float64(5.0),
15956 Scalar::Float64(3.0),
15957 Scalar::Null(NullKind::NaN),
15958 Scalar::Float64(4.0),
15959 Scalar::Float64(1.0),
15960 ];
15961 let out = super::nancummin(&values);
15962 assert_eq!(out[0], Scalar::Float64(5.0));
15963 assert_eq!(out[1], Scalar::Float64(3.0));
15964 assert!(out[2].is_missing());
15965 assert_eq!(out[3], Scalar::Float64(3.0));
15966 assert_eq!(out[4], Scalar::Float64(1.0));
15967 }
15968
15969 #[test]
15970 fn nancumsum_timedelta64_preserves_dtype_x0x91() {
15971 let one_hour = 3_600 * 1_000_000_000_i64;
15974 let values = vec![
15975 Scalar::Timedelta64(one_hour),
15976 Scalar::Timedelta64(2 * one_hour),
15977 Scalar::Timedelta64(3 * one_hour),
15978 ];
15979 let out = super::nancumsum(&values);
15980 assert_eq!(out[0], Scalar::Timedelta64(one_hour));
15981 assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
15982 assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
15983 }
15984
15985 #[test]
15986 fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
15987 let one_hour = 3_600 * 1_000_000_000_i64;
15988 let values = vec![
15989 Scalar::Timedelta64(2 * one_hour),
15990 Scalar::Timedelta64(5 * one_hour),
15991 Scalar::Timedelta64(one_hour),
15992 Scalar::Timedelta64(3 * one_hour),
15993 ];
15994 let mx = super::nancummax(&values);
15995 assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
15996 assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
15997 assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
15998 assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
15999
16000 let mn = super::nancummin(&values);
16001 assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
16002 assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
16003 assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
16004 assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
16005 }
16006
16007 #[test]
16008 fn nancumulative_timedelta64_skips_nat_x0x91() {
16009 let one_hour = 3_600 * 1_000_000_000_i64;
16010 let values = vec![
16011 Scalar::Timedelta64(one_hour),
16012 Scalar::Timedelta64(Timedelta::NAT),
16013 Scalar::Timedelta64(2 * one_hour),
16014 ];
16015 let cs = super::nancumsum(&values);
16016 assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
16017 assert!(cs[1].is_missing());
16018 assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
16019 }
16020
16021 #[test]
16022 fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
16023 fn next(seed: &mut u64) -> u64 {
16026 *seed = seed
16027 .wrapping_mul(3202034522624059733)
16028 .wrapping_add(4354685564936845319);
16029 *seed
16030 }
16031
16032 fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
16033 assert_eq!(
16034 actual.len(),
16035 expected.len(),
16036 "case={case} family={family} op={op}: length mismatch"
16037 );
16038 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
16039 assert!(
16040 actual.semantic_eq(expected),
16041 "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
16042 );
16043 }
16044 }
16045
16046 fn expected_numeric(
16047 values: &[Scalar],
16048 ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16049 let mut sum = Vec::with_capacity(values.len());
16050 let mut prod = Vec::with_capacity(values.len());
16051 let mut max = Vec::with_capacity(values.len());
16052 let mut min = Vec::with_capacity(values.len());
16053 let mut running_sum = 0.0_f64;
16054 let mut running_prod = 1.0_f64;
16055 let mut running_max: Option<f64> = None;
16056 let mut running_min: Option<f64> = None;
16057
16058 for value in values {
16059 if value.is_missing() {
16060 sum.push(Scalar::Null(NullKind::NaN));
16061 prod.push(Scalar::Null(NullKind::NaN));
16062 max.push(Scalar::Null(NullKind::NaN));
16063 min.push(Scalar::Null(NullKind::NaN));
16064 continue;
16065 }
16066 let Ok(value) = value.to_f64() else {
16067 sum.push(Scalar::Null(NullKind::NaN));
16068 prod.push(Scalar::Null(NullKind::NaN));
16069 max.push(Scalar::Null(NullKind::NaN));
16070 min.push(Scalar::Null(NullKind::NaN));
16071 continue;
16072 };
16073 if value.is_nan() {
16074 sum.push(Scalar::Null(NullKind::NaN));
16075 prod.push(Scalar::Null(NullKind::NaN));
16076 max.push(Scalar::Null(NullKind::NaN));
16077 min.push(Scalar::Null(NullKind::NaN));
16078 continue;
16079 }
16080 running_sum += value;
16081 running_prod *= value;
16082 running_max = Some(running_max.map_or(value, |current| current.max(value)));
16083 running_min = Some(running_min.map_or(value, |current| current.min(value)));
16084 sum.push(Scalar::Float64(running_sum));
16085 prod.push(Scalar::Float64(running_prod));
16086 max.push(Scalar::Float64(running_max.expect("initialized")));
16087 min.push(Scalar::Float64(running_min.expect("initialized")));
16088 }
16089
16090 (sum, prod, max, min)
16091 }
16092
16093 fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16094 let mut sum = Vec::with_capacity(values.len());
16095 let mut max = Vec::with_capacity(values.len());
16096 let mut min = Vec::with_capacity(values.len());
16097 let mut running_sum = 0_i128;
16098 let mut running_max: Option<i64> = None;
16099 let mut running_min: Option<i64> = None;
16100
16101 for value in values {
16102 if value.is_missing() {
16103 sum.push(Scalar::Null(NullKind::NaT));
16104 max.push(Scalar::Null(NullKind::NaT));
16105 min.push(Scalar::Null(NullKind::NaT));
16106 continue;
16107 }
16108 let Scalar::Timedelta64(ns) = value else {
16109 sum.push(Scalar::Null(NullKind::NaT));
16110 max.push(Scalar::Null(NullKind::NaT));
16111 min.push(Scalar::Null(NullKind::NaT));
16112 continue;
16113 };
16114 running_sum = running_sum.saturating_add(i128::from(*ns));
16115 running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
16116 running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
16117 sum.push(super::timedelta_ns_to_scalar(running_sum));
16120 max.push(Scalar::Timedelta64(running_max.expect("initialized")));
16121 min.push(Scalar::Timedelta64(running_min.expect("initialized")));
16122 }
16123
16124 (sum, max, min)
16125 }
16126
16127 let mut seed = 0xc0de_c63a_5eed_0421_u64;
16128 for case in 0..260 {
16129 let len = (next(&mut seed) % 89 + 1) as usize;
16130
16131 let mut numeric = Vec::with_capacity(len);
16132 numeric.push(Scalar::Int64(case as i64 - 130));
16133 for _ in 1..len {
16134 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16135 numeric.push(match next(&mut seed) % 8 {
16136 0 => Scalar::Null(NullKind::Null),
16137 1 => Scalar::Null(NullKind::NaN),
16138 2 => Scalar::Float64(f64::NAN),
16139 3 => Scalar::Bool(raw & 1 == 0),
16140 4 => Scalar::Int64(raw % 251),
16141 5 => Scalar::Float64(raw as f64 / 79.0),
16142 6 => Scalar::Float64(0.0),
16143 _ => Scalar::Float64(-0.0),
16144 });
16145 }
16146 let (sum, prod, max, min) = expected_numeric(&numeric);
16147 assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
16148 assert_vec(
16149 case,
16150 "numeric",
16151 "cumprod",
16152 &super::nancumprod(&numeric),
16153 &prod,
16154 );
16155 assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
16156 assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
16157
16158 let mut timedeltas = Vec::with_capacity(len);
16159 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16160 for _ in 1..len {
16161 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16162 timedeltas.push(match next(&mut seed) % 7 {
16163 0 => Scalar::Null(NullKind::Null),
16164 1 => Scalar::Timedelta64(i64::MIN),
16165 _ => Scalar::Timedelta64(raw),
16166 });
16167 }
16168 let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
16169 assert_vec(
16170 case,
16171 "timedelta",
16172 "cumsum",
16173 &super::nancumsum(&timedeltas),
16174 &td_sum,
16175 );
16176 assert_vec(
16177 case,
16178 "timedelta",
16179 "cummax",
16180 &super::nancummax(&timedeltas),
16181 &td_max,
16182 );
16183 assert_vec(
16184 case,
16185 "timedelta",
16186 "cummin",
16187 &super::nancummin(&timedeltas),
16188 &td_min,
16189 );
16190 }
16191 }
16192
16193 #[test]
16194 fn nanquantile_linear_interpolation_matches_numpy() {
16195 let values = vec![
16196 Scalar::Float64(1.0),
16197 Scalar::Float64(2.0),
16198 Scalar::Float64(3.0),
16199 Scalar::Float64(4.0),
16200 Scalar::Float64(5.0),
16201 ];
16202 let q = super::nanquantile(&values, 0.5);
16204 assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
16205 let q25 = super::nanquantile(&values, 0.25);
16207 assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16208 }
16209
16210 #[test]
16211 fn nanquantile_ignores_nulls() {
16212 let values = vec![
16213 Scalar::Float64(1.0),
16214 Scalar::Null(NullKind::NaN),
16215 Scalar::Float64(3.0),
16216 ];
16217 let q = super::nanquantile(&values, 0.5);
16218 assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16219 }
16220
16221 #[test]
16222 fn nanquantile_empty_and_out_of_range_yield_null() {
16223 assert!(super::nanquantile(&[], 0.5).is_missing());
16224 assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
16225 assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
16226 }
16227
16228 #[test]
16229 fn nanquantile_timedelta64_preserves_dtype_5djk7() {
16230 let one_hour: i64 = 3_600 * 1_000_000_000;
16233 let vals = vec![
16234 Scalar::Timedelta64(one_hour),
16235 Scalar::Timedelta64(2 * one_hour),
16236 Scalar::Timedelta64(3 * one_hour),
16237 Scalar::Timedelta64(4 * one_hour),
16238 Scalar::Timedelta64(5 * one_hour),
16239 ];
16240 assert_eq!(
16241 super::nanquantile(&vals, 0.5),
16242 Scalar::Timedelta64(3 * one_hour)
16243 );
16244 assert_eq!(
16245 super::nanquantile(&vals, 0.0),
16246 Scalar::Timedelta64(one_hour)
16247 );
16248 assert_eq!(
16249 super::nanquantile(&vals, 1.0),
16250 Scalar::Timedelta64(5 * one_hour)
16251 );
16252 }
16253
16254 #[test]
16255 fn nanquantile_timedelta64_linear_interpolation_5djk7() {
16256 let one_hour: i64 = 3_600 * 1_000_000_000;
16257 let vals = vec![
16258 Scalar::Timedelta64(one_hour),
16259 Scalar::Timedelta64(3 * one_hour),
16260 ];
16261 assert_eq!(
16263 super::nanquantile(&vals, 0.5),
16264 Scalar::Timedelta64(2 * one_hour)
16265 );
16266 }
16267
16268 #[test]
16269 fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
16270 fn next(seed: &mut u64) -> u64 {
16273 *seed = seed
16274 .wrapping_mul(3202034522624059733)
16275 .wrapping_add(4354685564936845319);
16276 *seed
16277 }
16278
16279 fn interpolated(sorted: &[f64], q: f64) -> f64 {
16280 if sorted.len() == 1 {
16281 return sorted[0];
16282 }
16283 let pos = q * (sorted.len() - 1) as f64;
16284 let lo = pos.floor() as usize;
16285 let hi = pos.ceil() as usize;
16286 if lo == hi {
16287 sorted[lo]
16288 } else {
16289 let weight = pos - lo as f64;
16290 sorted[lo] + (sorted[hi] - sorted[lo]) * weight
16291 }
16292 }
16293
16294 fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
16295 if !(0.0..=1.0).contains(&q) {
16296 return Scalar::Null(NullKind::NaN);
16297 }
16298 let mut samples = values
16299 .iter()
16300 .filter(|value| !value.is_missing())
16301 .filter_map(|value| value.to_f64().ok())
16302 .collect::<Vec<_>>();
16303 if samples.is_empty() {
16304 return Scalar::Null(NullKind::NaN);
16305 }
16306 samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16307 Scalar::Float64(interpolated(&samples, q))
16308 }
16309
16310 fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
16311 if !(0.0..=1.0).contains(&q) {
16312 return Scalar::Null(NullKind::NaN);
16313 }
16314 let mut samples = values
16315 .iter()
16316 .filter_map(|value| match value {
16317 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
16318 _ => None,
16319 })
16320 .collect::<Vec<_>>();
16321 if samples.is_empty() {
16322 return Scalar::Timedelta64(Timedelta::NAT);
16325 }
16326 samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16327 Scalar::Timedelta64(interpolated(&samples, q) as i64)
16328 }
16329
16330 fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
16331 let actual = super::nanquantile(values, q);
16332 assert!(
16333 actual.semantic_eq(&expected),
16334 "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
16335 );
16336 }
16337
16338 let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16339 assert_quantile(
16340 usize::MAX,
16341 "numeric_all_missing",
16342 &numeric_all_missing,
16343 0.5,
16344 expected_numeric(&numeric_all_missing, 0.5),
16345 );
16346 assert_quantile(
16347 usize::MAX - 1,
16348 "numeric_out_of_range",
16349 &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
16350 1.25,
16351 Scalar::Null(NullKind::NaN),
16352 );
16353
16354 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16355 assert_quantile(
16356 usize::MAX - 2,
16357 "timedelta_all_missing",
16358 &td_all_missing,
16359 0.5,
16360 expected_timedelta(&td_all_missing, 0.5),
16361 );
16362 assert_quantile(
16363 usize::MAX - 3,
16364 "timedelta_out_of_range",
16365 &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
16366 -0.25,
16367 Scalar::Null(NullKind::NaN),
16368 );
16369
16370 let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
16371 for case in 0..260 {
16372 let len = (next(&mut seed) % 83 + 1) as usize;
16373 let q = match next(&mut seed) % 8 {
16374 0 => 0.0,
16375 1 => 0.25,
16376 2 => 0.5,
16377 3 => 0.75,
16378 4 => 1.0,
16379 _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
16380 };
16381
16382 let mut numeric = Vec::with_capacity(len);
16383 numeric.push(Scalar::Int64(case as i64 - 130));
16384 for _ in 1..len {
16385 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16386 numeric.push(match next(&mut seed) % 8 {
16387 0 => Scalar::Null(NullKind::Null),
16388 1 => Scalar::Null(NullKind::NaN),
16389 2 => Scalar::Float64(f64::NAN),
16390 3 => Scalar::Bool(raw & 1 == 0),
16391 4 => Scalar::Int64(raw % 251),
16392 5 => Scalar::Float64(raw as f64 / 67.0),
16393 6 => Scalar::Float64(0.0),
16394 _ => Scalar::Float64(-0.0),
16395 });
16396 }
16397 assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
16398
16399 let mut timedeltas = Vec::with_capacity(len);
16400 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16401 for _ in 1..len {
16402 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16403 timedeltas.push(match next(&mut seed) % 7 {
16404 0 => Scalar::Null(NullKind::Null),
16405 1 => Scalar::Timedelta64(i64::MIN),
16406 _ => Scalar::Timedelta64(raw),
16407 });
16408 }
16409 assert_quantile(
16410 case,
16411 "timedelta",
16412 &timedeltas,
16413 q,
16414 expected_timedelta(&timedeltas, q),
16415 );
16416 }
16417 }
16418
16419 #[test]
16420 fn nanargmax_returns_first_position() {
16421 let values = vec![
16422 Scalar::Float64(1.0),
16423 Scalar::Null(NullKind::NaN),
16424 Scalar::Float64(4.0),
16425 Scalar::Float64(4.0),
16426 Scalar::Float64(2.0),
16427 ];
16428 assert_eq!(super::nanargmax(&values), Some(2));
16429 }
16430
16431 #[test]
16432 fn nanargmin_returns_first_position() {
16433 let values = vec![
16434 Scalar::Float64(3.0),
16435 Scalar::Null(NullKind::NaN),
16436 Scalar::Float64(1.0),
16437 Scalar::Float64(1.0),
16438 ];
16439 assert_eq!(super::nanargmin(&values), Some(2));
16440 }
16441
16442 #[test]
16443 fn nanargmax_all_missing_returns_none() {
16444 let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
16445 assert_eq!(super::nanargmax(&values), None);
16446 assert_eq!(super::nanargmin(&values), None);
16447 }
16448
16449 #[test]
16450 fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
16451 fn next(seed: &mut u64) -> u64 {
16454 *seed = seed
16455 .wrapping_mul(2862933555777941757)
16456 .wrapping_add(3037000493);
16457 *seed
16458 }
16459
16460 fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
16461 let mut best: Option<(usize, f64)> = None;
16462 for (idx, value) in values.iter().enumerate() {
16463 if value.is_missing() {
16464 continue;
16465 }
16466 let Ok(value) = value.to_f64() else {
16467 continue;
16468 };
16469 if value.is_nan() {
16470 continue;
16471 }
16472 match best {
16473 None => best = Some((idx, value)),
16474 Some((_, current))
16475 if (find_max && value > current) || (!find_max && value < current) =>
16476 {
16477 best = Some((idx, value));
16478 }
16479 _ => {}
16480 }
16481 }
16482 best.map(|(idx, _)| idx)
16483 }
16484
16485 fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
16486 let mut best: Option<(usize, i64)> = None;
16487 for (idx, value) in values.iter().enumerate() {
16488 if value.is_missing() {
16489 continue;
16490 }
16491 let Scalar::Timedelta64(ns) = value else {
16492 continue;
16493 };
16494 match best {
16495 None => best = Some((idx, *ns)),
16496 Some((_, current))
16497 if (find_max && *ns > current) || (!find_max && *ns < current) =>
16498 {
16499 best = Some((idx, *ns));
16500 }
16501 _ => {}
16502 }
16503 }
16504 best.map(|(idx, _)| idx)
16505 }
16506
16507 fn assert_args(
16508 case: usize,
16509 family: &str,
16510 values: &[Scalar],
16511 expected_min: Option<usize>,
16512 expected_max: Option<usize>,
16513 ) {
16514 assert_eq!(
16515 super::nanargmin(values),
16516 expected_min,
16517 "case={case} family={family}: nanargmin mismatch for {values:?}"
16518 );
16519 assert_eq!(
16520 super::nanargmax(values),
16521 expected_max,
16522 "case={case} family={family}: nanargmax mismatch for {values:?}"
16523 );
16524 }
16525
16526 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16527 assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
16528 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16529 assert_args(
16530 usize::MAX - 1,
16531 "timedelta_all_missing",
16532 &td_all_missing,
16533 None,
16534 None,
16535 );
16536 let positive_int64_endpoint = [
16537 Scalar::Int64(i64::MAX - 1),
16538 Scalar::Null(NullKind::Null),
16539 Scalar::Int64(i64::MAX),
16540 ];
16541 assert_args(
16542 usize::MAX - 2,
16543 "int64_positive_endpoint_exact_order",
16544 &positive_int64_endpoint,
16545 Some(0),
16546 Some(2),
16547 );
16548 let negative_int64_endpoint = [
16549 Scalar::Int64(i64::MIN + 2),
16550 Scalar::Null(NullKind::NaN),
16551 Scalar::Int64(i64::MIN + 1),
16552 ];
16553 assert_args(
16554 usize::MAX - 3,
16555 "int64_negative_endpoint_exact_order",
16556 &negative_int64_endpoint,
16557 Some(2),
16558 Some(0),
16559 );
16560
16561 let mut seed = 0xa126_5eed_ed9e_u64;
16562 for case in 0..260 {
16563 let len = (next(&mut seed) % 83 + 1) as usize;
16564
16565 let mut numeric = Vec::with_capacity(len);
16566 numeric.push(Scalar::Int64(case as i64 - 130));
16567 if len > 1 {
16568 numeric.push(Scalar::Int64(case as i64 - 130));
16569 }
16570 for _ in numeric.len()..len {
16571 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16572 numeric.push(match next(&mut seed) % 9 {
16573 0 => Scalar::Null(NullKind::Null),
16574 1 => Scalar::Null(NullKind::NaN),
16575 2 => Scalar::Float64(f64::NAN),
16576 3 => Scalar::Bool(raw & 1 == 0),
16577 4 => Scalar::Int64(raw % 211),
16578 5 => Scalar::Float64(raw as f64 / 47.0),
16579 6 => Scalar::Float64(0.0),
16580 7 => Scalar::Float64(-0.0),
16581 _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
16582 });
16583 }
16584 assert_args(
16585 case,
16586 "numeric",
16587 &numeric,
16588 expected_numeric(&numeric, false),
16589 expected_numeric(&numeric, true),
16590 );
16591
16592 let mut timedeltas = Vec::with_capacity(len);
16593 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16594 if len > 1 {
16595 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16596 }
16597 for _ in timedeltas.len()..len {
16598 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16599 timedeltas.push(match next(&mut seed) % 7 {
16600 0 => Scalar::Null(NullKind::Null),
16601 1 => Scalar::Timedelta64(i64::MIN),
16602 _ => Scalar::Timedelta64(raw),
16603 });
16604 }
16605 assert_args(
16606 case,
16607 "timedelta",
16608 &timedeltas,
16609 expected_timedelta(&timedeltas, false),
16610 expected_timedelta(&timedeltas, true),
16611 );
16612 }
16613 }
16614
16615 #[test]
16616 fn nansem_matches_std_over_sqrt_n() {
16617 let values = vec![
16618 Scalar::Float64(2.0),
16619 Scalar::Float64(4.0),
16620 Scalar::Float64(4.0),
16621 Scalar::Float64(4.0),
16622 Scalar::Float64(5.0),
16623 Scalar::Float64(5.0),
16624 Scalar::Float64(7.0),
16625 Scalar::Float64(9.0),
16626 ];
16627 let sem = super::nansem(&values, 1);
16629 assert!(matches!(sem, Scalar::Float64(_)));
16630 let Scalar::Float64(v) = sem else {
16631 return;
16632 };
16633 assert!((v - 0.7559289460184544).abs() < 1e-9);
16634 }
16635
16636 #[test]
16637 fn nansem_grouped_is_sqrt_var_over_n_7hxqv() {
16638 let values = [
16641 Scalar::Float64(1.0),
16642 Scalar::Null(NullKind::NaN),
16643 Scalar::Float64(4.0),
16644 ];
16645 assert_eq!(super::nansem_grouped(&values, 1), Scalar::Float64(1.5));
16646 assert_eq!(
16648 super::nansem(&values, 1),
16649 Scalar::Float64(1.499_999_999_999_999_8)
16650 );
16651 assert!(super::nansem_grouped(&values[..1], 1).is_missing());
16652 }
16653
16654 #[test]
16655 fn grouped_reducers_add_as_pandas_group_kernels_xhogl() {
16656 let tenths: Vec<Scalar> = (0..10).map(|_| Scalar::Float64(0.1)).collect();
16660 assert_eq!(super::nansum_grouped(&tenths), Scalar::Float64(1.0));
16661 assert_eq!(super::nanmean_grouped(&tenths), Scalar::Float64(0.1));
16662 assert_eq!(super::nanvar_grouped(&tenths, 1), Scalar::Float64(0.0));
16663 assert_eq!(super::nanstd_grouped(&tenths, 1), Scalar::Float64(0.0));
16664 assert_eq!(
16666 super::nansum(&tenths),
16667 Scalar::Float64(0.999_999_999_999_999_9)
16668 );
16669 let mut sum = super::KahanSum::default();
16671 for value in [1.0, f64::INFINITY, 2.0] {
16672 sum.add(value);
16673 }
16674 assert_eq!(sum.sum(), f64::INFINITY);
16675 let gapped = [
16677 Scalar::Float64(1.0),
16678 Scalar::Null(NullKind::NaN),
16679 Scalar::Float64(4.0),
16680 ];
16681 assert_eq!(super::nanmean_grouped(&gapped), Scalar::Float64(2.5));
16682 assert_eq!(super::nanvar_grouped(&gapped, 1), Scalar::Float64(4.5));
16683 assert!(super::nanvar_grouped(&gapped[..1], 1).is_missing());
16684 let spans = [Scalar::Timedelta64(1), Scalar::Timedelta64(2)];
16686 assert_eq!(super::nansum_grouped(&spans), super::nansum(&spans));
16687 }
16688
16689 #[test]
16690 fn grouped_skew_is_pandas_online_group_skew_vjfq9() {
16691 let group = [
16694 Scalar::Float64(1.0),
16695 Scalar::Null(NullKind::NaN),
16696 Scalar::Float64(4.0),
16697 Scalar::Float64(8.0),
16698 ];
16699 assert_eq!(
16700 super::nanskew_grouped(&group),
16701 Scalar::Float64(0.423_273_160_268_006_15)
16702 );
16703 let long: Vec<Scalar> = (0..2922_i32)
16706 .map(|i| Scalar::Float64(f64::from((i * 7919) % 1000) / 7.0))
16707 .collect();
16708 let glibc_pow = Scalar::Float64(-0.002_284_383_734_800_801_4);
16709 if cfg!(all(target_os = "linux", target_env = "gnu")) {
16715 assert_eq!(super::nanskew_grouped(&long), glibc_pow);
16716 } else {
16717 let sqrt = Scalar::Float64(-0.002_284_383_734_800_802);
16718 assert!([glibc_pow, sqrt].contains(&super::nanskew_grouped(&long)));
16719 }
16720 let constant = [7.0; 3].map(Scalar::Float64);
16723 assert_eq!(super::nanskew_grouped(&constant), Scalar::Float64(0.0));
16724 assert!(super::nanskew_grouped(&group[..2]).is_missing());
16725 let with_inf = [1.0, f64::INFINITY, 2.0, 5.0].map(Scalar::Float64);
16726 assert!(super::nanskew_grouped(&with_inf).is_missing());
16727 }
16728
16729 #[test]
16730 fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
16731 fn former(values: &[Scalar], ddof: usize) -> Scalar {
16732 let nums = super::collect_finite(values);
16733 if nums.len() <= ddof {
16734 return Scalar::Null(NullKind::NaN);
16735 }
16736 match super::nanstd(values, ddof) {
16737 Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
16738 other => other,
16739 }
16740 }
16741
16742 fn assert_same_bits(values: &[Scalar], ddof: usize) {
16743 let expected = former(values, ddof);
16744 let actual = super::nansem(values, ddof);
16745 match (&expected, &actual) {
16746 (Scalar::Float64(expected), Scalar::Float64(actual)) => {
16747 assert_eq!(
16748 actual.to_bits(),
16749 expected.to_bits(),
16750 "values={values:?} ddof={ddof}"
16751 );
16752 }
16753 _ => assert!(
16754 actual.semantic_eq(&expected),
16755 "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
16756 ),
16757 }
16758 }
16759
16760 let mut generated = Vec::with_capacity(4_096);
16761 for idx in 0..4_096_i64 {
16762 generated.push(match idx % 257 {
16763 0 => Scalar::Null(NullKind::NaN),
16764 1 => Scalar::Float64(-0.0),
16765 2 => Scalar::Float64(0.0),
16766 _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
16767 _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
16768 });
16769 }
16770
16771 let cases = [
16772 Vec::new(),
16773 vec![Scalar::Int64(1)],
16774 vec![
16775 Scalar::Null(NullKind::Null),
16776 Scalar::Float64(f64::NAN),
16777 Scalar::Int64(i64::MIN),
16778 Scalar::Int64(i64::MAX),
16779 Scalar::Float64(-0.0),
16780 Scalar::Float64(0.0),
16781 ],
16782 generated,
16783 ];
16784 for values in &cases {
16785 for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
16786 assert_same_bits(values, ddof);
16787 }
16788 }
16789 }
16790
16791 #[test]
16792 #[ignore = "foreground release A/B harness"]
16793 fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
16794 const ROWS: usize = 262_144;
16795 const BATCH: usize = 8;
16796 const BLOCKS: usize = 9;
16797 const PRECONDITION_CALLS: usize = 2;
16798
16799 fn former(values: &[Scalar], ddof: usize) -> Scalar {
16800 let nums = super::collect_finite(values);
16801 if nums.len() <= ddof {
16802 return Scalar::Null(NullKind::NaN);
16803 }
16804 match super::nanstd(values, ddof) {
16805 Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
16806 other => other,
16807 }
16808 }
16809
16810 fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
16811 let values = std::hint::black_box(values);
16812 if candidate {
16813 super::nansem(values, 1)
16814 } else {
16815 former(values, 1)
16816 }
16817 }
16818
16819 fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
16820 for _ in 0..PRECONDITION_CALLS {
16821 std::hint::black_box(evaluate(values, candidate));
16822 }
16823 let started = std::time::Instant::now();
16824 for _ in 0..BATCH {
16825 std::hint::black_box(evaluate(values, candidate));
16826 }
16827 started.elapsed().as_nanos()
16828 }
16829
16830 fn median(mut samples: Vec<u128>) -> u128 {
16831 samples.sort_unstable();
16832 samples[samples.len() / 2]
16833 }
16834
16835 fn spread(a: u128, b: u128) -> f64 {
16836 a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
16837 }
16838
16839 let values = (0..ROWS)
16840 .map(|idx| {
16841 if idx % 257 == 0 {
16842 Scalar::Null(NullKind::NaN)
16843 } else {
16844 Scalar::Int64((idx % 8_191) as i64 - 4_095)
16845 }
16846 })
16847 .collect::<Vec<_>>();
16848
16849 let expected_bits = match former(&values, 1) {
16850 Scalar::Float64(value) => Some(value.to_bits()),
16851 _ => None,
16852 };
16853 let actual_bits = match super::nansem(&values, 1) {
16854 Scalar::Float64(value) => Some(value.to_bits()),
16855 _ => None,
16856 };
16857 assert!(
16858 expected_bits.is_some(),
16859 "numeric nansem must return Float64"
16860 );
16861 assert_eq!(actual_bits, expected_bits, "A/B output bits");
16862
16863 std::hint::black_box(evaluate(&values, false));
16864 std::hint::black_box(evaluate(&values, true));
16865
16866 let body_started = std::time::Instant::now();
16867 let mut former_a = Vec::with_capacity(BLOCKS);
16868 let mut former_b = Vec::with_capacity(BLOCKS);
16869 let mut candidate_a = Vec::with_capacity(BLOCKS);
16870 let mut candidate_b = Vec::with_capacity(BLOCKS);
16871 for block in 0..BLOCKS {
16872 let order = if block % 2 == 0 {
16873 [(false, 0), (true, 0), (true, 1), (false, 1)]
16874 } else {
16875 [(true, 1), (false, 1), (false, 0), (true, 0)]
16876 };
16877 for (candidate, duplicate) in order {
16878 let elapsed = elapsed_ns(&values, candidate);
16879 match (candidate, duplicate) {
16880 (false, 0) => former_a.push(elapsed),
16881 (false, _) => former_b.push(elapsed),
16882 (true, 0) => candidate_a.push(elapsed),
16883 (true, _) => candidate_b.push(elapsed),
16884 }
16885 }
16886 }
16887
16888 let former_a = median(former_a) / BATCH as u128;
16889 let former_b = median(former_b) / BATCH as u128;
16890 let candidate_a = median(candidate_a) / BATCH as u128;
16891 let candidate_b = median(candidate_b) / BATCH as u128;
16892 let former_mean = (former_a + former_b) as f64 / 2.0;
16893 let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
16894 println!(
16895 "NANSEM_SINGLE_BUFFER_AB rows={ROWS} former_a_ns={former_a} former_b_ns={former_b} candidate_a_ns={candidate_a} candidate_b_ns={candidate_b} former_spread={:.6} candidate_spread={:.6} speedup={:.6} body_seconds={:.6}",
16896 spread(former_a, former_b),
16897 spread(candidate_a, candidate_b),
16898 former_mean / candidate_mean,
16899 body_started.elapsed().as_secs_f64()
16900 );
16901 }
16902
16903 #[test]
16904 fn nansem_empty_returns_null() {
16905 assert!(super::nansem(&[], 1).is_missing());
16906 assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
16907 }
16908
16909 #[test]
16910 fn nanptp_returns_max_minus_min() {
16911 let values = vec![
16912 Scalar::Float64(3.0),
16913 Scalar::Null(NullKind::NaN),
16914 Scalar::Float64(7.0),
16915 Scalar::Float64(1.0),
16916 ];
16917 assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
16918 }
16919
16920 #[test]
16921 fn nanptp_empty_returns_null() {
16922 assert!(super::nanptp(&[]).is_missing());
16923 assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
16924 }
16925
16926 #[test]
16927 fn nanptp_timedelta64_preserves_dtype_u2g0r() {
16928 let one_hour: i64 = 3_600 * 1_000_000_000;
16930 let values = vec![
16931 Scalar::Timedelta64(one_hour),
16932 Scalar::Timedelta64(5 * one_hour),
16933 Scalar::Timedelta64(2 * one_hour),
16934 ];
16935 assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
16936 }
16937
16938 #[test]
16939 fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
16940 fn next(seed: &mut u64) -> u64 {
16943 *seed = seed
16944 .wrapping_mul(3202034522624059733)
16945 .wrapping_add(4354685564936845319);
16946 *seed
16947 }
16948
16949 fn expected_numeric(values: &[Scalar]) -> Scalar {
16950 let mut lo = f64::INFINITY;
16951 let mut hi = f64::NEG_INFINITY;
16952 let mut seen = false;
16953 for value in values {
16954 if value.is_missing() {
16955 continue;
16956 }
16957 if let Ok(value) = value.to_f64() {
16958 seen = true;
16959 lo = lo.min(value);
16960 hi = hi.max(value);
16961 }
16962 }
16963 if seen {
16964 Scalar::Float64(hi - lo)
16965 } else {
16966 Scalar::Null(NullKind::NaN)
16967 }
16968 }
16969
16970 fn expected_timedelta(values: &[Scalar]) -> Scalar {
16971 let mut lo = i64::MAX;
16972 let mut hi = i64::MIN;
16973 let mut seen = false;
16974 for value in values {
16975 if let Scalar::Timedelta64(ns) = value
16976 && !value.is_missing()
16977 {
16978 seen = true;
16979 lo = lo.min(*ns);
16980 hi = hi.max(*ns);
16981 }
16982 }
16983 if seen {
16984 Scalar::Timedelta64(hi - lo)
16985 } else {
16986 Scalar::Null(NullKind::NaN)
16987 }
16988 }
16989
16990 fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
16991 let actual = super::nanptp(values);
16992 assert!(
16993 actual.semantic_eq(&expected),
16994 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
16995 );
16996 }
16997
16998 assert_ptp(
16999 usize::MAX,
17000 "numeric_all_missing",
17001 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17002 Scalar::Null(NullKind::NaN),
17003 );
17004 assert_ptp(
17005 usize::MAX - 1,
17006 "timedelta_all_missing",
17007 &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
17008 Scalar::Null(NullKind::NaN),
17009 );
17010 let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
17011 assert_ptp(
17012 usize::MAX - 2,
17013 "timedelta_one_ns_range_beyond_f64_exactness",
17014 &[
17015 Scalar::Timedelta64(beyond_f64_exact_ns),
17016 Scalar::Timedelta64(beyond_f64_exact_ns - 1),
17017 Scalar::Timedelta64(Timedelta::NAT),
17018 ],
17019 Scalar::Timedelta64(1),
17020 );
17021
17022 let mut seed = 0xa22f_17ed_57a7_15e5_u64;
17023 for case in 0..260 {
17024 let len = (next(&mut seed) % 83 + 1) as usize;
17025
17026 let mut numeric = Vec::with_capacity(len);
17027 numeric.push(Scalar::Int64(case as i64 - 130));
17028 for _ in 1..len {
17029 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17030 numeric.push(match next(&mut seed) % 9 {
17031 0 => Scalar::Null(NullKind::Null),
17032 1 => Scalar::Null(NullKind::NaN),
17033 2 => Scalar::Float64(f64::NAN),
17034 3 => Scalar::Bool(raw & 1 == 0),
17035 4 => Scalar::Int64(raw),
17036 5 => Scalar::Float64(raw as f64 / 53.0),
17037 6 => Scalar::Float64(0.0),
17038 7 => Scalar::Float64(-0.0),
17039 _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
17040 });
17041 }
17042 assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
17043
17044 let mut timedeltas = Vec::with_capacity(len);
17045 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17046 for _ in 1..len {
17047 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17048 timedeltas.push(match next(&mut seed) % 7 {
17049 0 => Scalar::Null(NullKind::Null),
17050 1 => Scalar::Timedelta64(i64::MIN),
17051 _ => Scalar::Timedelta64(raw),
17052 });
17053 }
17054 assert_ptp(
17055 case,
17056 "timedelta",
17057 &timedeltas,
17058 expected_timedelta(&timedeltas),
17059 );
17060 }
17061 }
17062
17063 #[test]
17064 fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
17065 let one_hour: i64 = 3_600 * 1_000_000_000;
17068 let values = vec![
17069 Scalar::Timedelta64(2 * one_hour),
17070 Scalar::Timedelta64(5 * one_hour),
17071 Scalar::Timedelta64(one_hour),
17072 Scalar::Timedelta64(3 * one_hour),
17073 ];
17074 assert_eq!(super::nanargmax(&values), Some(1));
17075 assert_eq!(super::nanargmin(&values), Some(2));
17076 }
17077
17078 #[test]
17079 fn nanprod_timedelta64_returns_null_szq6a() {
17080 let one_hour: i64 = 3_600 * 1_000_000_000;
17084 let values = vec![
17085 Scalar::Timedelta64(2 * one_hour),
17086 Scalar::Timedelta64(3 * one_hour),
17087 ];
17088 assert!(super::nanprod(&values).is_missing());
17089 }
17090
17091 #[test]
17092 fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
17093 fn next(seed: &mut u64) -> u64 {
17096 *seed = seed
17097 .wrapping_mul(6364136223846793005)
17098 .wrapping_add(1442695040888963407);
17099 *seed
17100 }
17101
17102 fn expected_numeric(values: &[Scalar]) -> Scalar {
17103 let mut product = 1.0_f64;
17104 for value in values {
17105 if value.is_missing() {
17106 continue;
17107 }
17108 if let Ok(value) = value.to_f64() {
17109 product *= value;
17110 }
17111 }
17112 Scalar::Float64(product)
17113 }
17114
17115 fn expected_timedelta(values: &[Scalar]) -> Scalar {
17116 if values
17117 .iter()
17118 .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
17119 {
17120 Scalar::Null(NullKind::NaN)
17121 } else {
17122 Scalar::Float64(1.0)
17123 }
17124 }
17125
17126 fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
17127 let actual = super::nanprod(values);
17128 assert!(
17129 actual.semantic_eq(&expected),
17130 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
17131 );
17132 }
17133
17134 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17135 assert_prod(
17136 usize::MAX,
17137 "numeric_all_missing",
17138 &all_missing,
17139 Scalar::Float64(1.0),
17140 );
17141
17142 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17143 assert_prod(
17144 usize::MAX - 1,
17145 "timedelta_all_missing",
17146 &td_all_missing,
17147 expected_timedelta(&td_all_missing),
17148 );
17149
17150 let mut seed = 0x6e0d_9938_a11c_0de5_u64;
17151 for case in 0..280 {
17152 let len = (next(&mut seed) % 89 + 1) as usize;
17153
17154 let mut numeric = Vec::with_capacity(len);
17155 numeric.push(Scalar::Int64((case % 17) as i64 - 8));
17156 for _ in 1..len {
17157 let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
17158 numeric.push(match next(&mut seed) % 9 {
17159 0 => Scalar::Null(NullKind::Null),
17160 1 => Scalar::Null(NullKind::NaN),
17161 2 => Scalar::Float64(f64::NAN),
17162 3 => Scalar::Bool(raw & 1 == 0),
17163 4 => Scalar::Int64(raw % 19),
17164 5 => Scalar::Float64(raw as f64 / 97.0),
17165 6 => Scalar::Float64(0.0),
17166 7 => Scalar::Float64(-0.0),
17167 _ => Scalar::Float64(1.0),
17168 });
17169 }
17170 assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
17171
17172 let mut timedeltas = Vec::with_capacity(len);
17173 timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
17174 for _ in 1..len {
17175 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17176 timedeltas.push(match next(&mut seed) % 7 {
17177 0 => Scalar::Null(NullKind::Null),
17178 1 => Scalar::Timedelta64(i64::MIN),
17179 _ => Scalar::Timedelta64(raw),
17180 });
17181 }
17182 assert_prod(
17183 case,
17184 "timedelta",
17185 &timedeltas,
17186 expected_timedelta(&timedeltas),
17187 );
17188 }
17189 }
17190
17191 #[test]
17192 fn nanskew_symmetric_distribution_near_zero() {
17193 let values = vec![
17194 Scalar::Float64(1.0),
17195 Scalar::Float64(2.0),
17196 Scalar::Float64(3.0),
17197 Scalar::Float64(4.0),
17198 Scalar::Float64(5.0),
17199 ];
17200 let skew = super::nanskew(&values);
17202 assert!(matches!(skew, Scalar::Float64(_)));
17203 let Scalar::Float64(v) = skew else {
17204 return;
17205 };
17206 assert!(v.abs() < 1e-9);
17207 }
17208
17209 #[test]
17210 fn nanskew_too_few_values_returns_null() {
17211 assert!(super::nanskew(&[]).is_missing());
17212 assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
17213 }
17214
17215 #[test]
17216 fn nankurt_symmetric_uniform_distribution() {
17217 let values = vec![
17218 Scalar::Float64(1.0),
17219 Scalar::Float64(2.0),
17220 Scalar::Float64(3.0),
17221 Scalar::Float64(4.0),
17222 Scalar::Float64(5.0),
17223 ];
17224 let kurt = super::nankurt(&values);
17226 assert!(matches!(kurt, Scalar::Float64(_)));
17227 let Scalar::Float64(v) = kurt else {
17228 return;
17229 };
17230 assert!((v + 1.2).abs() < 1e-9);
17231 }
17232
17233 #[test]
17234 fn nankurt_too_few_values_returns_null() {
17235 let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
17236 assert!(super::nankurt(&vals).is_missing());
17237 }
17238
17239 #[test]
17240 fn nanskew_constant_series_returns_zero() {
17241 let values = vec![
17242 Scalar::Float64(5.0),
17243 Scalar::Float64(5.0),
17244 Scalar::Float64(5.0),
17245 ];
17246 assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
17247 assert_eq!(
17248 super::nankurt(&[
17249 Scalar::Float64(5.0),
17250 Scalar::Float64(5.0),
17251 Scalar::Float64(5.0),
17252 Scalar::Float64(5.0),
17253 ]),
17254 Scalar::Float64(0.0)
17255 );
17256 }
17257
17258 #[test]
17259 fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
17260 fn next(seed: &mut u64) -> u64 {
17263 *seed = seed
17264 .wrapping_mul(2862933555777941757)
17265 .wrapping_add(3037000493);
17266 *seed
17267 }
17268
17269 fn samples(values: &[Scalar]) -> Vec<f64> {
17270 values
17271 .iter()
17272 .filter(|value| !value.is_missing())
17273 .filter_map(|value| value.to_f64().ok())
17274 .collect()
17275 }
17276
17277 fn expected_skew(values: &[Scalar]) -> Scalar {
17278 let samples = samples(values);
17279 let n = samples.len() as f64;
17280 if n < 3.0 {
17281 return Scalar::Null(NullKind::NaN);
17282 }
17283 let mean = samples.iter().sum::<f64>() / n;
17284 let m2 = samples
17285 .iter()
17286 .map(|value| (value - mean).powi(2))
17287 .sum::<f64>();
17288 let m3 = samples
17289 .iter()
17290 .map(|value| (value - mean).powi(3))
17291 .sum::<f64>();
17292 let s2 = m2 / (n - 1.0);
17293 if s2 == 0.0 {
17294 return Scalar::Float64(0.0);
17295 }
17296 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
17297 }
17298
17299 fn expected_kurt(values: &[Scalar]) -> Scalar {
17300 let samples = samples(values);
17301 let n = samples.len() as f64;
17302 if n < 4.0 {
17303 return Scalar::Null(NullKind::NaN);
17304 }
17305 let mean = samples.iter().sum::<f64>() / n;
17306 let m2 = samples
17307 .iter()
17308 .map(|value| (value - mean).powi(2))
17309 .sum::<f64>();
17310 let m4 = samples
17311 .iter()
17312 .map(|value| (value - mean).powi(4))
17313 .sum::<f64>();
17314 let s2 = m2 / (n - 1.0);
17315 if s2 == 0.0 {
17316 return Scalar::Float64(0.0);
17317 }
17318 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
17319 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
17320 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
17321 }
17322
17323 fn assert_moments(case: usize, values: &[Scalar]) {
17324 let expected_skew = expected_skew(values);
17325 let expected_kurt = expected_kurt(values);
17326 let actual_skew = super::nanskew(values);
17327 let actual_kurt = super::nankurt(values);
17328 assert!(
17329 actual_skew.semantic_eq(&expected_skew),
17330 "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
17331 );
17332 assert!(
17333 actual_kurt.semantic_eq(&expected_kurt),
17334 "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
17335 );
17336 }
17337
17338 assert_moments(
17339 usize::MAX,
17340 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17341 );
17342 assert_moments(
17343 usize::MAX - 1,
17344 &[
17345 Scalar::Float64(7.0),
17346 Scalar::Float64(7.0),
17347 Scalar::Float64(7.0),
17348 Scalar::Float64(7.0),
17349 ],
17350 );
17351
17352 let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
17353 for case in 0..260 {
17354 let len = (next(&mut seed) % 89 + 1) as usize;
17355 let mut values = Vec::with_capacity(len);
17356 if case % 11 == 0 {
17357 values.extend((0..len).map(|_| Scalar::Float64(3.0)));
17358 } else {
17359 values.push(Scalar::Float64(case as f64 / 19.0));
17360 for _ in 1..len {
17361 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17362 values.push(match next(&mut seed) % 8 {
17363 0 => Scalar::Null(NullKind::Null),
17364 1 => Scalar::Null(NullKind::NaN),
17365 2 => Scalar::Float64(f64::NAN),
17366 3 => Scalar::Bool(raw & 1 == 0),
17367 4 => Scalar::Int64(raw % 251),
17368 5 => Scalar::Float64(raw as f64 / 83.0),
17369 6 => Scalar::Float64(0.0),
17370 _ => Scalar::Float64(-0.0),
17371 });
17372 }
17373 }
17374 assert_moments(case, &values);
17375 }
17376 }
17377
17378 #[test]
17381 fn interval_default_closed_is_right() {
17382 assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
17383 }
17384
17385 #[test]
17386 fn interval_left_and_right_closed_helpers() {
17387 assert!(IntervalClosed::Left.left_closed());
17388 assert!(!IntervalClosed::Left.right_closed());
17389 assert!(!IntervalClosed::Right.left_closed());
17390 assert!(IntervalClosed::Right.right_closed());
17391 assert!(IntervalClosed::Both.left_closed());
17392 assert!(IntervalClosed::Both.right_closed());
17393 assert!(!IntervalClosed::Neither.left_closed());
17394 assert!(!IntervalClosed::Neither.right_closed());
17395 }
17396
17397 #[test]
17398 fn interval_display_matches_pandas_notation() {
17399 assert_eq!(
17400 Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
17401 "(0.0, 5.0]"
17402 );
17403 assert_eq!(
17404 Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
17405 "[0.0, 5.0)"
17406 );
17407 assert_eq!(
17408 Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
17409 "[0.0, 5.0]"
17410 );
17411 assert_eq!(
17412 Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
17413 "(0.0, 5.0)"
17414 );
17415 assert_eq!(
17416 Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
17417 "(2.5, 3.5]"
17418 );
17419 assert_eq!(
17420 Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
17421 "(-1.0, 0.0]"
17422 );
17423 assert_eq!(
17424 Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
17425 "(1e+20, 2e+20]"
17426 );
17427 }
17428
17429 #[test]
17430 fn interval_length_and_mid() {
17431 let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
17432 assert_eq!(i.length(), 8.0);
17433 assert_eq!(i.mid(), 6.0);
17434 }
17435
17436 #[test]
17437 fn interval_contains_matches_closed_policy() {
17438 let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
17439 assert!(!right.contains(0.0));
17440 assert!(right.contains(2.5));
17441 assert!(right.contains(5.0));
17442
17443 let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
17444 assert!(left.contains(0.0));
17445 assert!(left.contains(2.5));
17446 assert!(!left.contains(5.0));
17447
17448 let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
17449 assert!(both.contains(0.0));
17450 assert!(both.contains(5.0));
17451
17452 let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
17453 assert!(!neither.contains(0.0));
17454 assert!(!neither.contains(5.0));
17455 assert!(neither.contains(2.5));
17456 }
17457
17458 #[test]
17459 fn interval_contains_nan_returns_false() {
17460 let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
17461 assert!(!i.contains(f64::NAN));
17462 }
17463
17464 #[test]
17465 fn interval_is_empty_matches_pandas() {
17466 assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
17468 assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
17469 assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
17470 assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
17472 assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
17474 }
17475
17476 #[test]
17477 fn interval_overlaps_disjoint_returns_false() {
17478 let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
17479 let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
17480 assert!(!a.overlaps(&b));
17481 assert!(!b.overlaps(&a));
17482 }
17483
17484 #[test]
17485 fn interval_overlaps_nested_returns_true() {
17486 let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
17487 let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
17488 assert!(outer.overlaps(&inner));
17489 assert!(inner.overlaps(&outer));
17490 }
17491
17492 #[test]
17493 fn interval_overlaps_touching_respects_closed_policy() {
17494 let right_right = (
17496 Interval::new(0.0, 1.0, IntervalClosed::Right),
17497 Interval::new(1.0, 2.0, IntervalClosed::Right),
17498 );
17499 assert!(!right_right.0.overlaps(&right_right.1));
17501
17502 let both_both = (
17504 Interval::new(0.0, 1.0, IntervalClosed::Both),
17505 Interval::new(1.0, 2.0, IntervalClosed::Both),
17506 );
17507 assert!(both_both.0.overlaps(&both_both.1));
17508 }
17509
17510 #[test]
17511 fn interval_roundtrips_through_serde_json() {
17512 let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
17513 let json = serde_json::to_string(&i).expect("serialize");
17514 let back: Interval = serde_json::from_str(&json).expect("deserialize");
17515 assert_eq!(i, back);
17516 }
17517
17518 #[test]
17519 fn interval_serde_default_closed_is_right_when_missing() {
17520 let back: Interval =
17522 serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
17523 assert_eq!(back.closed, IntervalClosed::Right);
17524 }
17525
17526 #[test]
17529 fn period_freq_parses_canonical_aliases() {
17530 assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::Annual));
17531 assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::Annual));
17532 assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::Quarterly));
17533 assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
17534 assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::Weekly));
17535 assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
17536 assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
17537 assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
17538 assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
17539 assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
17540 assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
17541 }
17542
17543 #[test]
17544 fn period_freq_parse_is_case_insensitive() {
17545 assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::Quarterly));
17546 assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
17547 }
17548
17549 #[test]
17550 fn period_freq_rejects_unknown_aliases() {
17551 assert_eq!(PeriodFreq::parse("nanosec"), None);
17552 assert_eq!(PeriodFreq::parse(""), None);
17553 assert_eq!(PeriodFreq::parse("xyz"), None);
17554 }
17555
17556 #[test]
17557 fn period_freq_alias_roundtrip() {
17558 for freq in [
17559 PeriodFreq::Annual,
17560 PeriodFreq::Quarterly,
17561 PeriodFreq::Monthly,
17562 PeriodFreq::Weekly,
17563 PeriodFreq::Daily,
17564 PeriodFreq::Business,
17565 PeriodFreq::Hourly,
17566 PeriodFreq::Minutely,
17567 PeriodFreq::Secondly,
17568 PeriodFreq::Milliseconds,
17569 PeriodFreq::Microseconds,
17570 PeriodFreq::Nanoseconds,
17571 ] {
17572 assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
17573 }
17574 }
17575
17576 #[test]
17580 fn period_freq_subsecond_units_match_pandas() {
17581 assert_eq!(PeriodFreq::Milliseconds.alias(), "ms");
17583 assert_eq!(PeriodFreq::Microseconds.alias(), "us");
17584 assert_eq!(PeriodFreq::Nanoseconds.alias(), "ns");
17585 assert_eq!(PeriodFreq::Milliseconds.resolution(), Some("millisecond"));
17586 assert_eq!(PeriodFreq::Microseconds.resolution(), Some("microsecond"));
17587 assert_eq!(PeriodFreq::Nanoseconds.resolution(), Some("nanosecond"));
17588
17589 assert_eq!(PeriodFreq::parse("ms"), Some(PeriodFreq::Milliseconds));
17592 assert_eq!(PeriodFreq::parse("Ms"), Some(PeriodFreq::Milliseconds));
17593 assert_eq!(PeriodFreq::parse("mS"), Some(PeriodFreq::Milliseconds));
17594 assert_eq!(PeriodFreq::parse("MS"), None);
17595 assert_eq!(PeriodFreq::parse("us"), Some(PeriodFreq::Microseconds));
17597 assert_eq!(PeriodFreq::parse("US"), Some(PeriodFreq::Microseconds));
17598 assert_eq!(PeriodFreq::parse("ns"), Some(PeriodFreq::Nanoseconds));
17599 assert_eq!(PeriodFreq::parse("NS"), Some(PeriodFreq::Nanoseconds));
17600
17601 assert_eq!(
17604 Period::new(1_710_498_645_123, PeriodFreq::Milliseconds).calendar_string(),
17605 "2024-03-15 10:30:45.123"
17606 );
17607 assert_eq!(
17608 Period::new(1_710_498_645_123_456, PeriodFreq::Microseconds).calendar_string(),
17609 "2024-03-15 10:30:45.123456"
17610 );
17611 assert_eq!(
17612 Period::new(1_710_498_645_123_456_789, PeriodFreq::Nanoseconds).calendar_string(),
17613 "2024-03-15 10:30:45.123456789"
17614 );
17615
17616 assert_eq!(
17620 Period::new(0, PeriodFreq::Milliseconds).calendar_string(),
17621 "1970-01-01 00:00:00.000"
17622 );
17623 assert_eq!(
17624 Period::new(-1, PeriodFreq::Milliseconds).calendar_string(),
17625 "1969-12-31 23:59:59.999"
17626 );
17627 assert_eq!(
17628 Period::new(-1_000, PeriodFreq::Microseconds).calendar_string(),
17629 "1969-12-31 23:59:59.999000"
17630 );
17631 assert_eq!(
17632 Period::new(-999_999, PeriodFreq::Nanoseconds).calendar_string(),
17633 "1969-12-31 23:59:59.999000001"
17634 );
17635 }
17636
17637 #[test]
17638 fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
17639 assert_eq!(PeriodFreq::Annual.alias(), "Y-DEC");
17640 assert_eq!(PeriodFreq::Quarterly.alias(), "Q-DEC");
17641 assert_eq!(PeriodFreq::Weekly.alias(), "W-SUN");
17642
17643 assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::Annual));
17644 assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::Annual));
17645 assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::Annual));
17646 assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::Quarterly));
17647 assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::Quarterly));
17648 assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::Weekly));
17649 assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::Weekly));
17650 }
17651
17652 #[test]
17653 fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
17654 assert_eq!(PeriodFreq::Hourly.alias(), "h");
17655 assert_eq!(PeriodFreq::Minutely.alias(), "min");
17656 assert_eq!(PeriodFreq::Secondly.alias(), "s");
17657
17658 assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
17659 assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
17660 assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
17661 }
17662
17663 #[test]
17667 fn period_freq_resolution_is_the_component_word_not_the_alias() {
17668 assert_eq!(PeriodFreq::Annual.resolution(), Some("year"));
17669 assert_eq!(PeriodFreq::Quarterly.resolution(), Some("quarter"));
17670 assert_eq!(PeriodFreq::Monthly.resolution(), Some("month"));
17671 assert_eq!(PeriodFreq::Daily.resolution(), Some("day"));
17672 assert_eq!(PeriodFreq::Hourly.resolution(), Some("hour"));
17673 assert_eq!(PeriodFreq::Minutely.resolution(), Some("minute"));
17674 assert_eq!(PeriodFreq::Secondly.resolution(), Some("second"));
17675
17676 assert_eq!(PeriodFreq::Weekly.resolution(), None);
17678 assert_eq!(PeriodFreq::Business.resolution(), None);
17679
17680 for freq in [
17685 PeriodFreq::Annual,
17686 PeriodFreq::Quarterly,
17687 PeriodFreq::Monthly,
17688 PeriodFreq::Weekly,
17689 PeriodFreq::Daily,
17690 PeriodFreq::Business,
17691 PeriodFreq::Hourly,
17692 PeriodFreq::Minutely,
17693 PeriodFreq::Secondly,
17694 ] {
17695 assert_ne!(
17696 Some(freq.alias()),
17697 freq.resolution(),
17698 "{freq:?} reports its alias as its resolution again"
17699 );
17700 }
17701 }
17702
17703 #[test]
17704 fn period_scalar_accessors_match_pandas_star8() {
17705 let period = Period::new(600, PeriodFreq::Monthly);
17706
17707 assert_eq!(period.ordinal(), 600);
17708 assert_eq!(period.freq(), PeriodFreq::Monthly);
17709 assert_eq!(period.freqstr(), "M");
17710 }
17711
17712 #[test]
17713 fn period_parse_common_pandas_ordinals_avm08() {
17714 assert_eq!(
17715 Period::parse("2024").unwrap(),
17716 Period::new(54, PeriodFreq::Annual)
17717 );
17718 assert_eq!(
17719 Period::parse("2024Q1").unwrap(),
17720 Period::new(216, PeriodFreq::Quarterly)
17721 );
17722 assert_eq!(
17723 Period::parse("2024-01").unwrap(),
17724 Period::new(648, PeriodFreq::Monthly)
17725 );
17726 assert_eq!(
17727 Period::parse("2024-01-15").unwrap(),
17728 Period::new(19_737, PeriodFreq::Daily)
17729 );
17730 assert!(Period::parse("216").is_err());
17731 }
17732
17733 #[test]
17734 fn period_shift_advances_ordinal() {
17735 let q1 = Period::new(216, PeriodFreq::Quarterly);
17736 let q2 = q1.shift(1);
17737 assert_eq!(q2.ordinal, 217);
17738 assert_eq!(q2.freq, PeriodFreq::Quarterly);
17739 let q0 = q1.shift(-1);
17740 assert_eq!(q0.ordinal, 215);
17741 }
17742
17743 #[test]
17744 fn period_shift_saturates_on_overflow() {
17745 let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
17746 assert_eq!(p.shift(100).ordinal, i64::MAX);
17747 let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
17748 assert_eq!(p.shift(-100).ordinal, i64::MIN);
17749 }
17750
17751 #[test]
17752 fn period_diff_returns_period_count() {
17753 let a = Period::new(216, PeriodFreq::Quarterly);
17754 let b = Period::new(220, PeriodFreq::Quarterly);
17755 assert_eq!(b.diff(&a), Some(4));
17756 assert_eq!(a.diff(&b), Some(-4));
17757 }
17758
17759 #[test]
17760 fn period_diff_rejects_mismatched_freq() {
17761 let monthly = Period::new(100, PeriodFreq::Monthly);
17762 let quarterly = Period::new(100, PeriodFreq::Quarterly);
17763 assert_eq!(monthly.diff(&quarterly), None);
17764 assert_eq!(quarterly.diff(&monthly), None);
17765 }
17766
17767 #[test]
17768 fn period_cmp_same_freq_respects_ordinal_order() {
17769 use std::cmp::Ordering;
17770 let a = Period::new(10, PeriodFreq::Monthly);
17771 let b = Period::new(20, PeriodFreq::Monthly);
17772 assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
17773 assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
17774 assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
17775 }
17776
17777 #[test]
17778 fn period_cmp_cross_freq_returns_none() {
17779 let m = Period::new(1, PeriodFreq::Monthly);
17780 let q = Period::new(1, PeriodFreq::Quarterly);
17781 assert_eq!(m.cmp_same_freq(&q), None);
17782 }
17783
17784 #[test]
17785 fn period_arithmetic_matches_seeded_oracles_bac28() {
17786 use std::cmp::Ordering;
17787
17788 fn next(seed: &mut u64) -> u64 {
17789 *seed = seed
17790 .wrapping_mul(2862933555777941757)
17791 .wrapping_add(3037000493);
17792 *seed
17793 }
17794
17795 fn freq_for(raw: u64) -> PeriodFreq {
17796 match raw % 12 {
17799 0 => PeriodFreq::Annual,
17800 1 => PeriodFreq::Quarterly,
17801 2 => PeriodFreq::Monthly,
17802 3 => PeriodFreq::Weekly,
17803 4 => PeriodFreq::Daily,
17804 5 => PeriodFreq::Business,
17805 6 => PeriodFreq::Hourly,
17806 7 => PeriodFreq::Minutely,
17807 8 => PeriodFreq::Secondly,
17808 9 => PeriodFreq::Milliseconds,
17809 10 => PeriodFreq::Microseconds,
17810 _ => PeriodFreq::Nanoseconds,
17811 }
17812 }
17813
17814 fn different_freq(freq: PeriodFreq) -> PeriodFreq {
17815 match freq {
17816 PeriodFreq::Annual => PeriodFreq::Quarterly,
17817 PeriodFreq::Quarterly => PeriodFreq::Monthly,
17818 PeriodFreq::Monthly => PeriodFreq::Weekly,
17819 PeriodFreq::Weekly => PeriodFreq::Daily,
17820 PeriodFreq::Daily => PeriodFreq::Business,
17821 PeriodFreq::Business => PeriodFreq::Hourly,
17822 PeriodFreq::Hourly => PeriodFreq::Minutely,
17823 PeriodFreq::Minutely => PeriodFreq::Secondly,
17824 PeriodFreq::Secondly => PeriodFreq::Milliseconds,
17828 PeriodFreq::Milliseconds => PeriodFreq::Microseconds,
17829 PeriodFreq::Microseconds => PeriodFreq::Nanoseconds,
17830 PeriodFreq::Nanoseconds => PeriodFreq::Annual,
17831 }
17832 }
17833
17834 fn assert_period_case(
17835 case: usize,
17836 freq: PeriodFreq,
17837 ordinal: i64,
17838 shift_by: i64,
17839 other_ordinal: i64,
17840 ) {
17841 let period = Period::new(ordinal, freq);
17842 let shifted = period.shift(shift_by);
17843 assert_eq!(
17844 shifted.ordinal,
17845 ordinal.saturating_add(shift_by),
17846 "case {case}: shift ordinal"
17847 );
17848 assert_eq!(shifted.freq, freq, "case {case}: shift freq");
17849
17850 let same_freq_other = Period::new(other_ordinal, freq);
17851 assert_eq!(
17852 period.diff(&same_freq_other),
17853 Some(ordinal.saturating_sub(other_ordinal)),
17854 "case {case}: same-freq diff"
17855 );
17856 assert_eq!(
17857 period.cmp_same_freq(&same_freq_other),
17858 Some(ordinal.cmp(&other_ordinal)),
17859 "case {case}: same-freq cmp"
17860 );
17861
17862 let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
17863 assert_eq!(
17864 period.diff(&cross_freq_other),
17865 None,
17866 "case {case}: cross-freq diff"
17867 );
17868 assert_eq!(
17869 period.cmp_same_freq(&cross_freq_other),
17870 None,
17871 "case {case}: cross-freq cmp"
17872 );
17873 }
17874
17875 assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
17876 assert_period_case(
17877 usize::MAX - 1,
17878 PeriodFreq::Daily,
17879 i64::MIN + 2,
17880 -10,
17881 i64::MAX,
17882 );
17883 assert_eq!(
17884 Period::new(10, PeriodFreq::Monthly)
17885 .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
17886 Some(Ordering::Equal)
17887 );
17888
17889 let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
17890 for case in 0..260 {
17891 let freq = freq_for(next(&mut seed));
17892 let ordinal = match case % 53 {
17893 0 => i64::MAX - (next(&mut seed) % 8) as i64,
17894 1 => i64::MIN + (next(&mut seed) % 8) as i64,
17895 _ => (next(&mut seed) % 200_001) as i64 - 100_000,
17896 };
17897 let shift_by = match case % 47 {
17898 0 => 512,
17899 1 => -512,
17900 _ => (next(&mut seed) % 4097) as i64 - 2048,
17901 };
17902 let other_ordinal = match case % 41 {
17903 0 => i64::MAX,
17904 1 => i64::MIN,
17905 _ => (next(&mut seed) % 200_001) as i64 - 100_000,
17906 };
17907 assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
17908 }
17909 }
17910
17911 #[test]
17912 fn period_display_is_pandas_calendar_string() {
17913 assert_eq!(
17915 Period::new(216, PeriodFreq::Quarterly).to_string(),
17916 "2024Q1"
17917 );
17918 assert_eq!(Period::new(54, PeriodFreq::Annual).to_string(), "2024");
17920 assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
17922 assert_eq!(
17924 Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
17925 "2024-01-15"
17926 );
17927 assert_eq!(
17928 Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
17929 "NaT"
17930 );
17931 }
17932
17933 #[test]
17941 fn weekly_and_business_periods_do_not_index_days() {
17942 for (ordinal, want) in [
17947 (0_i64, "1969-12-22/1969-12-28"),
17948 (1, "1969-12-29/1970-01-04"),
17949 (2829, "2024-03-11/2024-03-17"),
17950 (1540, "1999-06-28/1999-07-04"),
17951 (15237, "2261-12-30/2262-01-05"),
17952 (-1, "1969-12-15/1969-12-21"),
17954 (-2829, "1915-10-04/1915-10-10"),
17955 ] {
17956 assert_eq!(
17957 Period::new(ordinal, PeriodFreq::Weekly).to_string(),
17958 want,
17959 "weekly ordinal {ordinal}"
17960 );
17961 }
17962
17963 for (ordinal, want) in [
17967 (0_i64, "1970-01-01"), (1, "1970-01-02"), (2, "1970-01-05"), (3, "1970-01-06"),
17971 (4, "1970-01-07"),
17972 (5, "1970-01-08"),
17973 (14141, "2024-03-15"),
17974 (76179, "2262-01-01"),
17975 (7697, "1999-07-05"),
17978 (-1, "1969-12-31"),
17979 (-5, "1969-12-25"),
17980 (-6, "1969-12-24"),
17981 ] {
17982 assert_eq!(
17983 Period::new(ordinal, PeriodFreq::Business).to_string(),
17984 want,
17985 "business ordinal {ordinal}"
17986 );
17987 }
17988
17989 for ordinal in -400_i64..400 {
17993 let rendered = Period::new(ordinal, PeriodFreq::Business).to_string();
17994 let later = Period::new(ordinal + 5, PeriodFreq::Business).to_string();
17995 assert_ne!(rendered, later, "business ordinals must not repeat");
17996 }
17997
17998 assert_eq!(Period::new(i64::MIN, PeriodFreq::Weekly).to_string(), "NaT");
17999 assert_eq!(
18000 Period::new(i64::MIN, PeriodFreq::Business).to_string(),
18001 "NaT"
18002 );
18003 }
18004
18005 fn period_display_former_profile(period: &Period) -> String {
18006 let calendar = period.calendar_string();
18007 let mut rendered = String::new();
18008 rendered.push_str(&calendar);
18009 rendered
18010 }
18011
18012 fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
18013 use std::{hint::black_box, time::Instant};
18014
18015 let started = Instant::now();
18016 let mut checksum = 0usize;
18017 for period in periods {
18018 let rendered = render(black_box(period));
18019 checksum = checksum.wrapping_add(rendered.len());
18020 drop(black_box(rendered));
18021 }
18022 black_box(checksum);
18023 started.elapsed().as_nanos()
18024 }
18025
18026 #[test]
18027 #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
18028 fn profile_period_display_direct_sink_ab_6pqra() {
18029 const FREQUENCIES: [PeriodFreq; 9] = [
18030 PeriodFreq::Annual,
18031 PeriodFreq::Quarterly,
18032 PeriodFreq::Monthly,
18033 PeriodFreq::Weekly,
18034 PeriodFreq::Daily,
18035 PeriodFreq::Business,
18036 PeriodFreq::Hourly,
18037 PeriodFreq::Minutely,
18038 PeriodFreq::Secondly,
18039 ];
18040 const SAMPLES: usize = 10;
18041
18042 let periods = (0..65_536)
18043 .map(|index| {
18044 let ordinal = if index % 4093 == 0 {
18045 i64::MIN
18046 } else {
18047 ((index as i64 * 7_919) % 4_000_001) - 2_000_000
18048 };
18049 Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
18050 })
18051 .collect::<Vec<_>>();
18052
18053 for period in &periods {
18054 assert_eq!(period_display_former_profile(period), period.to_string());
18055 }
18056
18057 for _ in 0..2 {
18058 measure_period_renderer(&periods, period_display_former_profile);
18059 measure_period_renderer(&periods, Period::to_string);
18060 }
18061
18062 let mut former_ns = Vec::with_capacity(SAMPLES);
18063 let mut public_ns = Vec::with_capacity(SAMPLES);
18064 for sample in 0..SAMPLES {
18065 if sample % 2 == 0 {
18066 former_ns.push(measure_period_renderer(
18067 &periods,
18068 period_display_former_profile,
18069 ));
18070 public_ns.push(measure_period_renderer(&periods, Period::to_string));
18071 } else {
18072 public_ns.push(measure_period_renderer(&periods, Period::to_string));
18073 former_ns.push(measure_period_renderer(
18074 &periods,
18075 period_display_former_profile,
18076 ));
18077 }
18078 }
18079 former_ns.sort_unstable();
18080 public_ns.sort_unstable();
18081 let former_p50 = former_ns[SAMPLES / 2];
18082 let public_p50 = public_ns[SAMPLES / 2];
18083 let former_p95 = former_ns[SAMPLES - 1];
18084 let public_p95 = public_ns[SAMPLES - 1];
18085 println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
18086 println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
18087 println!(
18088 "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
18089 former_p50 as f64 / public_p50 as f64
18090 );
18091 println!(
18092 "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
18093 former_p95 as f64 / public_p95 as f64
18094 );
18095 }
18096
18097 #[cfg(test)]
18098 fn fp_days(ymd: &str) -> i64 {
18099 Period::parse(ymd).expect("daily period").ordinal
18100 }
18101
18102 #[test]
18103 fn period_roundtrips_through_serde_json() {
18104 let p = Period::new(42, PeriodFreq::Weekly);
18105 let json = serde_json::to_string(&p).expect("serialize");
18106 let back: Period = serde_json::from_str(&json).expect("deserialize");
18107 assert_eq!(p, back);
18108 }
18109
18110 use super::period_range;
18113
18114 #[test]
18115 fn period_range_zero_periods_is_empty() {
18116 let start = Period::new(216, PeriodFreq::Quarterly);
18117 assert!(period_range(start, 0).is_empty());
18118 }
18119
18120 #[test]
18121 fn period_range_single_period_returns_start_only() {
18122 let start = Period::new(216, PeriodFreq::Quarterly);
18123 let r = period_range(start, 1);
18124 assert_eq!(r.len(), 1);
18125 assert_eq!(r[0], start);
18126 }
18127
18128 #[test]
18129 fn period_range_increments_ordinal_by_one_per_step() {
18130 let start = Period::new(216, PeriodFreq::Quarterly);
18131 let r = period_range(start, 4);
18132 assert_eq!(r.len(), 4);
18133 assert_eq!(r[0].ordinal, 216);
18134 assert_eq!(r[1].ordinal, 217);
18135 assert_eq!(r[2].ordinal, 218);
18136 assert_eq!(r[3].ordinal, 219);
18137 }
18138
18139 #[test]
18140 fn period_range_preserves_frequency() {
18141 let start = Period::new(0, PeriodFreq::Monthly);
18142 let r = period_range(start, 12);
18143 assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
18144 }
18145
18146 #[test]
18147 fn period_range_negative_starting_ordinal_works() {
18148 let start = Period::new(-3, PeriodFreq::Annual);
18150 let r = period_range(start, 5);
18151 assert_eq!(
18152 r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
18153 vec![-3, -2, -1, 0, 1]
18154 );
18155 }
18156
18157 #[test]
18158 fn period_range_large_n_does_not_panic() {
18159 let start = Period::new(0, PeriodFreq::Monthly);
18161 let r = period_range(start, 1024);
18162 assert_eq!(r.len(), 1024);
18163 assert_eq!(r[1023].ordinal, 1023);
18164 }
18165
18166 #[test]
18167 fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
18168 fn next(seed: &mut u64) -> u64 {
18169 *seed = seed
18170 .wrapping_mul(6364136223846793005)
18171 .wrapping_add(1442695040888963407);
18172 *seed
18173 }
18174
18175 fn freq_for(raw: u64) -> PeriodFreq {
18176 match raw % 12 {
18179 0 => PeriodFreq::Annual,
18180 1 => PeriodFreq::Quarterly,
18181 2 => PeriodFreq::Monthly,
18182 3 => PeriodFreq::Weekly,
18183 4 => PeriodFreq::Daily,
18184 5 => PeriodFreq::Business,
18185 6 => PeriodFreq::Hourly,
18186 7 => PeriodFreq::Minutely,
18187 8 => PeriodFreq::Secondly,
18188 9 => PeriodFreq::Milliseconds,
18189 10 => PeriodFreq::Microseconds,
18190 _ => PeriodFreq::Nanoseconds,
18191 }
18192 }
18193
18194 fn assert_oracle_case(case: usize, start: Period, periods: usize) {
18195 let got = period_range(start, periods);
18196 assert_eq!(got.len(), periods, "case {case}: length");
18197
18198 for (position, period) in got.iter().enumerate() {
18199 let expected_ordinal = start.ordinal.saturating_add(position as i64);
18200 assert_eq!(
18201 period.ordinal, expected_ordinal,
18202 "case {case}: ordinal at {position}"
18203 );
18204 assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
18205 }
18206 }
18207
18208 assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
18209 assert_oracle_case(
18210 usize::MAX - 1,
18211 Period::new(i64::MAX - 3, PeriodFreq::Daily),
18212 8,
18213 );
18214
18215 let mut seed = 0x9e21_0d1c_5eed_0421_u64;
18216 for case in 0..260 {
18217 let freq = freq_for(next(&mut seed));
18218 let periods = (next(&mut seed) % 80) as usize;
18219 let start_ordinal = if case % 37 == 0 {
18220 i64::MAX - 7
18221 } else {
18222 (next(&mut seed) % 20_001) as i64 - 10_000
18223 };
18224 assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
18225 }
18226 }
18227
18228 use super::{TypeError, interval_range, interval_range_by_periods, interval_range_by_step};
18231
18232 #[test]
18233 fn interval_range_by_periods_matches_pandas_default_case() {
18234 let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
18236 assert_eq!(bins.len(), 5);
18237 for (i, bin) in bins.iter().enumerate() {
18238 assert_eq!(bin.left, (i as f64) * 2.0);
18239 assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
18240 assert_eq!(bin.closed, IntervalClosed::Right);
18241 }
18242 }
18243
18244 #[test]
18245 fn interval_range_by_periods_final_edge_is_exact_end() {
18246 let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
18248 assert_eq!(bins.last().unwrap().right, 1.0);
18249 }
18250
18251 #[test]
18252 fn interval_range_by_periods_zero_periods_is_empty() {
18253 assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
18254 }
18255
18256 #[test]
18257 fn interval_range_by_periods_reversed_range_is_empty() {
18258 assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
18260 }
18261
18262 #[test]
18263 fn interval_range_by_periods_preserves_closed_policy() {
18264 for closed in [
18265 IntervalClosed::Left,
18266 IntervalClosed::Right,
18267 IntervalClosed::Both,
18268 IntervalClosed::Neither,
18269 ] {
18270 let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
18271 assert!(bins.iter().all(|b| b.closed == closed));
18272 }
18273 }
18274
18275 #[test]
18276 fn interval_range_by_step_matches_pandas_default_case() {
18277 let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
18279 assert_eq!(bins.len(), 5);
18280 assert_eq!(bins[0].left, 0.0);
18281 assert_eq!(bins[4].right, 10.0);
18282 }
18283
18284 #[test]
18285 fn interval_range_by_step_rejects_non_positive_step() {
18286 assert!(matches!(
18287 interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
18288 Err(TypeError::InvalidIntervalStep { .. })
18289 ));
18290 assert!(matches!(
18291 interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
18292 Err(TypeError::InvalidIntervalStep { .. })
18293 ));
18294 assert!(matches!(
18295 interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
18296 Err(TypeError::InvalidIntervalStep { .. })
18297 ));
18298 assert!(matches!(
18299 interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
18300 Err(TypeError::InvalidIntervalStep { .. })
18301 ));
18302 }
18303
18304 #[test]
18305 fn interval_range_by_step_rejects_non_dividing_step() {
18306 assert!(matches!(
18309 interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
18310 Err(TypeError::IntervalStepDoesNotDivide { .. })
18311 ));
18312 }
18313
18314 #[test]
18315 fn interval_range_by_step_reversed_range_is_empty() {
18316 let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
18317 assert!(bins.is_empty());
18318 }
18319
18320 #[test]
18321 fn interval_range_by_step_degenerate_zero_span_is_empty() {
18322 let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
18323 assert!(bins.is_empty());
18324 }
18325
18326 #[test]
18327 fn interval_range_by_step_accepts_float_step_within_tolerance() {
18328 let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
18330 assert_eq!(bins.len(), 10);
18331 assert_eq!(bins.last().unwrap().right, 1.0);
18332 }
18333
18334 #[test]
18335 fn interval_range_unified_api_tests() {
18336 let r1 = interval_range(Some(0.0), Some(10.0), Some(5), None, None).expect("ok");
18338 assert_eq!(r1.len(), 5);
18339 assert_eq!(r1[0].left, 0.0);
18340 assert_eq!(r1[0].right, 2.0);
18341 assert_eq!(r1[4].right, 10.0);
18342 assert_eq!(r1[0].closed, IntervalClosed::Right);
18343
18344 let r2 = interval_range(Some(0.0), Some(10.0), None, Some(2.0), None).expect("ok");
18346 assert_eq!(r2.len(), 5);
18347 assert_eq!(r2[0].left, 0.0);
18348 assert_eq!(r2[4].right, 10.0);
18349
18350 let r3 = interval_range(
18352 Some(0.0),
18353 None,
18354 Some(5),
18355 Some(2.0),
18356 Some(IntervalClosed::Both),
18357 )
18358 .expect("ok");
18359 assert_eq!(r3.len(), 5);
18360 assert_eq!(r3[0].left, 0.0);
18361 assert_eq!(r3[4].right, 10.0);
18362 assert_eq!(r3[0].closed, IntervalClosed::Both);
18363
18364 let r4 = interval_range(
18366 None,
18367 Some(10.0),
18368 Some(5),
18369 Some(2.0),
18370 Some(IntervalClosed::Left),
18371 )
18372 .expect("ok");
18373 assert_eq!(r4.len(), 5);
18374 assert_eq!(r4[0].left, 0.0);
18375 assert_eq!(r4[4].right, 10.0);
18376 assert_eq!(r4[0].closed, IntervalClosed::Left);
18377
18378 assert!(matches!(
18380 interval_range(None, None, None, None, None),
18381 Err(TypeError::IntervalRangeParameterCount)
18382 ));
18383 assert!(matches!(
18384 interval_range(Some(0.0), Some(10.0), None, None, None),
18385 Err(TypeError::IntervalRangeParameterCount)
18386 ));
18387 assert!(matches!(
18388 interval_range(Some(0.0), Some(10.0), Some(5), Some(2.0), None),
18389 Err(TypeError::IntervalRangeParameterCount)
18390 ));
18391
18392 assert!(matches!(
18394 interval_range(Some(0.0), None, Some(5), Some(-1.0), None),
18395 Err(TypeError::InvalidIntervalStep { .. })
18396 ));
18397 assert!(matches!(
18398 interval_range(Some(0.0), None, Some(5), Some(0.0), None),
18399 Err(TypeError::InvalidIntervalStep { .. })
18400 ));
18401 }
18402
18403 #[test]
18404 fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
18405 fn next(seed: &mut u64) -> u64 {
18408 *seed = seed
18409 .wrapping_mul(2862933555777941757)
18410 .wrapping_add(3037000493);
18411 *seed
18412 }
18413
18414 fn closed_for(raw: u64) -> IntervalClosed {
18415 match raw % 4 {
18416 0 => IntervalClosed::Left,
18417 1 => IntervalClosed::Right,
18418 2 => IntervalClosed::Both,
18419 _ => IntervalClosed::Neither,
18420 }
18421 }
18422
18423 fn assert_interval(
18424 case: usize,
18425 kind: &str,
18426 pos: usize,
18427 actual: &Interval,
18428 expected: &Interval,
18429 ) {
18430 assert!(
18431 (actual.left - expected.left).abs() < 1e-12,
18432 "case={case} kind={kind} pos={pos}: expected left {}, got {}",
18433 expected.left,
18434 actual.left
18435 );
18436 assert!(
18437 (actual.right - expected.right).abs() < 1e-12,
18438 "case={case} kind={kind} pos={pos}: expected right {}, got {}",
18439 expected.right,
18440 actual.right
18441 );
18442 assert_eq!(
18443 actual.closed, expected.closed,
18444 "case={case} kind={kind} pos={pos}: closed mismatch"
18445 );
18446 }
18447
18448 fn expected_by_periods(
18449 start: f64,
18450 end: f64,
18451 periods: usize,
18452 closed: IntervalClosed,
18453 ) -> Vec<Interval> {
18454 if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
18455 return Vec::new();
18456 }
18457 let step = (end - start) / periods as f64;
18458 (0..periods)
18459 .map(|pos| {
18460 let left = start + step * pos as f64;
18461 let right = if pos + 1 == periods {
18462 end
18463 } else {
18464 start + step * (pos + 1) as f64
18465 };
18466 Interval::new(left, right, closed)
18467 })
18468 .collect()
18469 }
18470
18471 fn expected_by_step(
18472 start: f64,
18473 end: f64,
18474 step: f64,
18475 closed: IntervalClosed,
18476 ) -> Vec<Interval> {
18477 if start >= end {
18478 return Vec::new();
18479 }
18480 let count = ((end - start) / step).round() as usize;
18481 (0..count)
18482 .map(|pos| {
18483 let left = start + step * pos as f64;
18484 let right = if pos + 1 == count {
18485 end
18486 } else {
18487 start + step * (pos + 1) as f64
18488 };
18489 Interval::new(left, right, closed)
18490 })
18491 .collect()
18492 }
18493
18494 assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
18495 assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
18496 assert!(
18497 interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
18498 .expect("zero span")
18499 .is_empty()
18500 );
18501
18502 let mut seed = 0x171e_7a11_c0de_5eed_u64;
18503 for case in 0..220 {
18504 let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
18505 let periods = (next(&mut seed) % 24 + 1) as usize;
18506 let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
18507 let end = start + width;
18508 let closed = closed_for(next(&mut seed));
18509
18510 let actual = interval_range_by_periods(start, end, periods, closed);
18511 let expected = expected_by_periods(start, end, periods, closed);
18512 assert_eq!(
18513 actual.len(),
18514 expected.len(),
18515 "case={case} periods: length mismatch"
18516 );
18517 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18518 assert_interval(case, "periods", pos, actual, expected);
18519 }
18520
18521 let step_count = (next(&mut seed) % 20 + 1) as usize;
18522 let step = (next(&mut seed) % 25 + 1) as f64;
18523 let step_end = start + step * step_count as f64;
18524 let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
18525 let expected = expected_by_step(start, step_end, step, closed);
18526 assert_eq!(
18527 actual.len(),
18528 expected.len(),
18529 "case={case} step: length mismatch"
18530 );
18531 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18532 assert_interval(case, "step", pos, actual, expected);
18533 }
18534 }
18535 }
18536
18537 use super::Timedelta;
18540
18541 #[test]
18542 fn timedelta_add_sums_non_nat() {
18543 let one_hour = Timedelta::NANOS_PER_HOUR;
18544 let one_day = Timedelta::NANOS_PER_DAY;
18545 assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
18546 }
18547
18548 #[test]
18549 fn timedelta_add_propagates_nat() {
18550 assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
18551 assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
18552 assert_eq!(
18553 Timedelta::add(Timedelta::NAT, Timedelta::NAT),
18554 Timedelta::NAT
18555 );
18556 }
18557
18558 #[test]
18559 fn timedelta_add_returns_nat_on_overflow() {
18560 assert_eq!(Timedelta::add(i64::MAX - 10, 100), Timedelta::NAT);
18567 assert_eq!(Timedelta::add(i64::MIN + 10, -100), Timedelta::NAT);
18570 }
18571
18572 #[test]
18573 fn timedelta_sub_subtracts_non_nat() {
18574 let one_hour = Timedelta::NANOS_PER_HOUR;
18575 assert_eq!(
18576 Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
18577 one_hour - Timedelta::NANOS_PER_MIN
18578 );
18579 }
18580
18581 #[test]
18582 fn timedelta_sub_propagates_nat() {
18583 assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
18584 assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
18585 }
18586
18587 #[test]
18588 fn timedelta_neg_flips_sign_non_nat() {
18589 assert_eq!(Timedelta::neg(5), -5);
18590 assert_eq!(Timedelta::neg(-5), 5);
18591 assert_eq!(Timedelta::neg(0), 0);
18592 }
18593
18594 #[test]
18595 fn timedelta_neg_preserves_nat() {
18596 assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
18597 }
18598
18599 #[test]
18600 fn timedelta_abs_returns_magnitude() {
18601 assert_eq!(Timedelta::abs(-5), 5);
18602 assert_eq!(Timedelta::abs(5), 5);
18603 assert_eq!(Timedelta::abs(0), 0);
18604 assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
18605 }
18606
18607 #[test]
18608 fn neg_and_abs_at_the_representable_floor_are_not_overflow_fyr1z() {
18609 const MAX: i64 = i64::MAX;
18627 const MIN_OK: i64 = i64::MIN + 1; assert_eq!(MIN_OK, -MAX);
18632 assert_eq!(Timedelta::NAT, i64::MIN);
18633
18634 assert_eq!(Timedelta::neg(MIN_OK), MAX);
18636 assert_eq!(Timedelta::neg(MAX), MIN_OK);
18637 assert_eq!(Timedelta::abs(MIN_OK), MAX);
18638 assert_eq!(Timedelta::abs(MAX), MAX);
18639
18640 assert_eq!(Timedelta::neg(Timedelta::neg(MIN_OK)), MIN_OK);
18644 assert_ne!(Timedelta::neg(MIN_OK), Timedelta::NAT);
18645 assert_ne!(Timedelta::abs(MIN_OK), Timedelta::NAT);
18646
18647 assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
18650 assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
18651 }
18652
18653 #[test]
18654 fn overflow_divergence_surface_is_only_where_pandas_refuses_fyr1z() {
18655 const MAX: i64 = i64::MAX;
18667 const MIN_OK: i64 = i64::MIN + 1;
18668
18669 assert_eq!(Timedelta::div_scalar(MAX, 0), Timedelta::NAT);
18674 assert_eq!(Timedelta::div_scalar(MIN_OK, 0), Timedelta::NAT);
18675 assert_eq!(Timedelta::div_scalar(0, 0), Timedelta::NAT);
18676
18677 assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT); assert_eq!(Timedelta::sub(MIN_OK, 2), Timedelta::NAT); assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
18687 assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(2).is_nat());
18688
18689 assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
18693 assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
18694 assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
18695
18696 assert_eq!(Timedelta::div_scalar(MAX, 1), MAX);
18698 assert_eq!(Timedelta::div_scalar(-100, 3), -34); assert_eq!(Timedelta::div_scalar(100, -3), -34);
18700 assert_eq!(Timedelta::sub(MIN_OK + 2, 1), MIN_OK + 1);
18701 }
18702
18703 #[test]
18704 fn timedelta_mul_scalar_scales() {
18705 let three_hours = Timedelta::NANOS_PER_HOUR * 3;
18706 assert_eq!(
18707 Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
18708 three_hours
18709 );
18710 assert_eq!(Timedelta::mul_scalar(100, 0), 0);
18711 assert_eq!(Timedelta::mul_scalar(100, -2), -200);
18712 }
18713
18714 #[test]
18715 fn timedelta_mul_scalar_returns_nat_on_overflow() {
18716 assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), Timedelta::NAT);
18719 assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), Timedelta::NAT);
18720 }
18721
18722 #[test]
18723 fn from_unit_nan_is_nat_and_overflow_is_err_8v92m() {
18724 use super::TimedeltaError;
18725
18726 assert_eq!(Timedelta::from_unit(f64::NAN, "s"), Ok(Timedelta::NAT));
18744 assert_ne!(Timedelta::from_unit(f64::NAN, "s"), Ok(0));
18745 assert_eq!(Timedelta::from_unit(f64::NAN, "D"), Ok(Timedelta::NAT));
18746
18747 assert_eq!(
18749 Timedelta::from_unit(f64::INFINITY, "s"),
18750 Err(TimedeltaError::Overflow)
18751 );
18752 assert_eq!(
18753 Timedelta::from_unit(f64::NEG_INFINITY, "s"),
18754 Err(TimedeltaError::Overflow)
18755 );
18756 assert_eq!(
18757 Timedelta::from_unit(1e30, "s"),
18758 Err(TimedeltaError::Overflow)
18759 );
18760 assert_eq!(
18761 Timedelta::from_unit(1e30, "D"),
18762 Err(TimedeltaError::Overflow)
18763 );
18764
18765 assert_eq!(Timedelta::from_unit(1.5, "s"), Ok(1_500_000_000));
18768 assert_eq!(Timedelta::from_unit(0.0, "s"), Ok(0));
18769 assert_eq!(Timedelta::from_unit(-2.5, "s"), Ok(-2_500_000_000));
18770 assert_eq!(Timedelta::from_unit(1.0, "D"), Ok(Timedelta::NANOS_PER_DAY));
18771 assert_eq!(
18772 Timedelta::from_unit(3.0, "h"),
18773 Ok(3 * Timedelta::NANOS_PER_HOUR)
18774 );
18775 let big_days = 100_000.0_f64;
18778 let expected = (big_days * Timedelta::NANOS_PER_DAY as f64).round() as i64;
18779 assert_eq!(Timedelta::from_unit(big_days, "D"), Ok(expected));
18780 assert!(expected > 0, "fixture must stay in range to be a control");
18781
18782 assert!(matches!(
18785 Timedelta::from_unit(1.0, "nonsense-unit"),
18786 Err(TimedeltaError::InvalidFormat(_))
18787 ));
18788 assert!(matches!(
18789 Timedelta::from_unit(f64::NAN, "nonsense-unit"),
18790 Err(TimedeltaError::InvalidFormat(_)),
18791 ));
18792
18793 let huge = format!("{} days", "9".repeat(18));
18798 assert!(matches!(
18799 Timedelta::parse(&huge),
18800 Err(TimedeltaError::Overflow)
18801 ));
18802 assert!(matches!(
18803 Timedelta::parse("1e100 days"),
18804 Err(TimedeltaError::InvalidFormat(_))
18805 ));
18806 }
18807
18808 #[test]
18809 fn rounding_and_ms_us_overflow_never_fabricates_a_finite_value_kyd16() {
18810 const MAX: i64 = i64::MAX;
18829 const MIN_OK: i64 = i64::MIN + 1;
18830 const DAY: i64 = Timedelta::NANOS_PER_DAY;
18831
18832 let rounded = Timedelta::round(MAX, "D");
18834 assert_eq!(
18835 rounded,
18836 Timedelta::NAT,
18837 "rounding i64::MAX up to a whole day overflows; the old unchecked \
18838 multiply panicked in debug and wrapped in release"
18839 );
18840 assert!(
18844 rounded == Timedelta::NAT || rounded > 0,
18845 "a positive duration must never round to a negative one"
18846 );
18847 assert_eq!(Timedelta::round(MIN_OK, "D"), Timedelta::NAT);
18848
18849 assert_eq!(Timedelta::ceil(MAX, "D"), Timedelta::NAT);
18851 assert_eq!(Timedelta::floor(MIN_OK, "D"), Timedelta::NAT);
18852 assert!(Timestamp::from_nanos(MAX).ceil_to(DAY).is_nat());
18853 assert!(Timestamp::from_nanos(MAX).round_to(DAY).is_nat());
18854 assert!(Timestamp::from_nanos(MIN_OK).floor_to(DAY).is_nat());
18855 assert!(Timestamp::from_nanos(MIN_OK).round_to(DAY).is_nat());
18856
18857 assert!(Timestamp::from_millis(MAX, None).is_nat());
18859 assert!(Timestamp::from_millis(MIN_OK, None).is_nat());
18860 assert!(Timestamp::from_micros(MAX, None).is_nat());
18861 assert!(Timestamp::from_micros(MIN_OK, Some("US/Eastern")).is_nat());
18862
18863 let max_floor = Timestamp::from_nanos(MAX).floor_to(DAY);
18870 assert!(!max_floor.is_nat(), "Timestamp.max.floor(D) must succeed");
18871 assert_eq!(max_floor.nanos, (MAX / DAY) * DAY);
18872 assert_eq!(Timedelta::floor(MAX, "D"), (MAX / DAY) * DAY);
18873 assert_eq!(
18874 Timedelta::ceil(MIN_OK, "D"),
18875 (MIN_OK.div_euclid(DAY) + 1) * DAY
18876 );
18877
18878 let hour = Timedelta::NANOS_PER_HOUR;
18880 assert_eq!(Timedelta::floor(90 * 60 * 1_000_000_000, "h"), hour);
18881 assert_eq!(Timedelta::ceil(90 * 60 * 1_000_000_000, "h"), 2 * hour);
18882 assert_eq!(Timedelta::round(90 * 60 * 1_000_000_000, "h"), 2 * hour);
18883 assert_eq!(Timedelta::round(-90 * 60 * 1_000_000_000, "h"), -2 * hour);
18884 assert_eq!(Timedelta::round(29 * 60 * 1_000_000_000, "h"), 0);
18885 assert_eq!(Timestamp::from_millis(1_500, None).nanos, 1_500_000_000);
18886 assert_eq!(Timestamp::from_micros(-2_000, None).nanos, -2_000_000);
18887 assert_eq!(
18888 Timestamp::from_nanos(hour + 1).floor_to(hour).nanos,
18889 hour,
18890 "in-range floor unchanged"
18891 );
18892 assert_eq!(
18893 Timestamp::from_nanos(hour + 1).ceil_to(hour).nanos,
18894 2 * hour,
18895 "in-range ceil unchanged"
18896 );
18897
18898 assert_eq!(Timedelta::round(Timedelta::NAT, "D"), Timedelta::NAT);
18900 assert_eq!(Timedelta::floor(Timedelta::NAT, "D"), Timedelta::NAT);
18901 assert_eq!(Timedelta::ceil(1_000, "nonsense-unit"), Timedelta::NAT);
18902 assert!(Timestamp::nat().ceil_to(DAY).is_nat());
18903 assert!(Timestamp::from_nanos(0).round_to(0).is_nat());
18904 assert_eq!(
18906 Timestamp::from_nanos_tz(hour + 1, "US/Eastern")
18907 .ceil_to(hour)
18908 .tz
18909 .as_deref(),
18910 Some("US/Eastern")
18911 );
18912 }
18913
18914 #[test]
18915 fn timedelta_mul_scalar_propagates_nat() {
18916 assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
18917 }
18918
18919 #[test]
18920 fn arithmetic_overflow_never_fabricates_a_finite_value_lgyy8() {
18921 const MAX: i64 = i64::MAX;
18936 const MIN_OK: i64 = i64::MIN + 1; assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
18940 assert_eq!(Timedelta::add(MAX - 10, 100), Timedelta::NAT);
18941 assert_eq!(Timedelta::sub(MAX, -1), Timedelta::NAT);
18942 assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
18943 assert_eq!(Timedelta::mul_scalar(MAX / 2 + 2, 2), Timedelta::NAT);
18944 assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
18945 assert!(Timestamp::from_nanos(MAX).sub_timedelta(-1).is_nat());
18946 assert_eq!(
18950 Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(MIN_OK)),
18951 Timedelta::NAT
18952 );
18953
18954 assert_eq!(Timedelta::add(MIN_OK, -1), Timedelta::NAT);
18956 assert_eq!(Timedelta::add(MIN_OK, -2), Timedelta::NAT);
18957 assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
18958 assert_eq!(Timedelta::mul_scalar(MIN_OK, 2), Timedelta::NAT);
18959 assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
18960 assert!(Timestamp::from_nanos(MIN_OK).add_timedelta(-1).is_nat());
18961 assert_eq!(
18962 Timestamp::from_nanos(MIN_OK).sub_timestamp(&Timestamp::from_nanos(MAX)),
18963 Timedelta::NAT
18964 );
18965
18966 assert_eq!(Timedelta::add(MAX - 1, 1), MAX);
18972 assert_eq!(Timedelta::add(MAX, 0), MAX);
18973 assert_eq!(Timedelta::sub(MAX, 1), MAX - 1);
18974 assert_eq!(Timedelta::add(MIN_OK + 1, -1), MIN_OK);
18975 assert_eq!(Timedelta::mul_scalar(MAX / 2, 2), (MAX / 2) * 2);
18976 assert_eq!(Timedelta::mul_scalar(MIN_OK, 1), MIN_OK);
18977 assert_eq!(Timestamp::from_nanos(MAX - 1).add_timedelta(1).nanos, MAX);
18978 assert_eq!(
18979 Timestamp::from_nanos(MIN_OK + 1).sub_timedelta(1).nanos,
18980 MIN_OK
18981 );
18982 assert_eq!(
18983 Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(0)),
18984 MAX
18985 );
18986 assert_eq!(Timedelta::add(1_000, 2_345), 3_345);
18988 assert_eq!(Timedelta::sub(1_000, 2_345), -1_345);
18989 assert_eq!(Timedelta::mul_scalar(-7, 6), -42);
18990
18991 assert_eq!(MIN_OK - 1, i64::MIN);
18998 assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
18999 assert_eq!(Timedelta::add(MIN_OK, 0), MIN_OK);
19000
19001 assert!(Timestamp::nat().add_timedelta(1).is_nat());
19004 assert!(
19005 Timestamp::from_nanos(0)
19006 .add_timedelta(Timedelta::NAT)
19007 .is_nat()
19008 );
19009 let tzed = Timestamp::from_nanos_tz(MAX, "US/Eastern");
19010 let overflowed = tzed.add_timedelta(1);
19011 assert!(overflowed.is_nat());
19012 assert_eq!(overflowed.tz, None, "an overflow NaT carries no zone");
19013 assert_eq!(
19015 Timestamp::from_nanos_tz(0, "US/Eastern")
19016 .add_timedelta(Timedelta::NANOS_PER_DAY)
19017 .tz
19018 .as_deref(),
19019 Some("US/Eastern")
19020 );
19021 }
19022
19023 #[test]
19024 fn timedelta_div_scalar_floor_divides() {
19025 assert_eq!(Timedelta::div_scalar(100, 3), 33);
19027 assert_eq!(Timedelta::div_scalar(-100, 3), -34);
19028 assert_eq!(Timedelta::div_scalar(100, -3), -34);
19029 assert_eq!(Timedelta::div_scalar(-100, -3), 33);
19030 }
19031
19032 #[test]
19033 fn timedelta_div_scalar_zero_divisor_returns_nat() {
19034 assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
19035 }
19036
19037 #[test]
19038 fn timedelta_div_scalar_min_neg_one_propagates_nat() {
19039 assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
19042 assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
19044 }
19045
19046 #[test]
19047 fn timedelta_div_scalar_propagates_nat() {
19048 assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
19049 }
19050
19051 #[test]
19052 fn timedelta_div_timedelta_returns_float_ratio() {
19053 let two_hours = Timedelta::NANOS_PER_HOUR * 2;
19054 let one_hour = Timedelta::NANOS_PER_HOUR;
19055 assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
19056 assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
19057 }
19058
19059 #[test]
19060 fn timedelta_div_timedelta_nat_returns_nan() {
19061 assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
19062 assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
19063 }
19064
19065 use super::Timestamp;
19068
19069 #[test]
19070 fn timestamp_from_nanos_is_naive_utc() {
19071 let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
19072 assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
19073 assert_eq!(ts.tz, None);
19074 assert!(!ts.is_nat());
19075 }
19076
19077 #[test]
19078 fn timestamp_from_nanos_tz_carries_tz_name() {
19079 let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19080 assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
19081 }
19082
19083 #[test]
19084 fn timestamp_now_returns_current_time() {
19085 let before = std::time::SystemTime::now()
19086 .duration_since(std::time::UNIX_EPOCH)
19087 .unwrap()
19088 .as_nanos() as i64;
19089 let ts = Timestamp::now();
19090 let after = std::time::SystemTime::now()
19091 .duration_since(std::time::UNIX_EPOCH)
19092 .unwrap()
19093 .as_nanos() as i64;
19094 assert!(ts.nanos >= before);
19095 assert!(ts.nanos <= after);
19096 assert!(!ts.is_nat());
19097 }
19098
19099 #[test]
19100 fn timestamp_today_returns_midnight() {
19101 let ts = Timestamp::today();
19102 assert!(!ts.is_nat());
19103 assert_eq!(ts.hour(), Some(0));
19105 assert_eq!(ts.minute(), Some(0));
19106 assert_eq!(ts.second(), Some(0));
19107 }
19108
19109 #[test]
19110 fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
19111 let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
19112 let one_day = Timedelta::NANOS_PER_DAY;
19113 let shifted = ts.add_timedelta(one_day);
19114 assert_eq!(shifted.nanos, one_day);
19115 assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
19116 }
19117
19118 #[test]
19119 fn timestamp_add_timedelta_returns_nat_on_overflow() {
19120 let ts = Timestamp::from_nanos(i64::MAX - 10);
19124 assert!(ts.add_timedelta(100).is_nat());
19125 }
19126
19127 #[test]
19128 fn timestamp_add_timedelta_propagates_nat() {
19129 assert!(Timestamp::nat().add_timedelta(100).is_nat());
19131 assert!(
19133 Timestamp::from_nanos(0)
19134 .add_timedelta(Timedelta::NAT)
19135 .is_nat()
19136 );
19137 }
19138
19139 #[test]
19140 fn timestamp_sub_timedelta_shifts_backward() {
19141 let ts = Timestamp::from_nanos(1_000);
19142 let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
19143 assert_eq!(shifted.nanos, 0);
19144 }
19145
19146 #[test]
19147 fn timestamp_sub_timestamp_returns_timedelta_nanos() {
19148 let t0 = Timestamp::from_nanos(0);
19149 let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
19150 assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
19151 assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
19152 }
19153
19154 #[test]
19155 fn timestamp_sub_timestamp_nat_propagates() {
19156 let ts = Timestamp::from_nanos(1_000);
19157 assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
19158 assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
19159 }
19160
19161 #[test]
19162 fn timestamp_semantic_eq_treats_two_nat_as_equal() {
19163 assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
19164 assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
19165 assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
19166 }
19167
19168 #[test]
19169 fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
19170 use std::cmp::Ordering;
19171 let a = Timestamp::from_nanos(0);
19172 let b = Timestamp::from_nanos(100);
19173 assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
19174 assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
19175 assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
19176 assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
19177 assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
19178 }
19179
19180 #[test]
19181 fn time_zone_offsets_and_wall_clock_conversions_follow_pandas() {
19182 use crate::{
19183 TimeZoneError, tz_abbreviation, tz_canonical_name, tz_offset_seconds,
19184 tz_utc_to_wall_nanos, tz_validate, tz_wall_to_utc_nanos,
19185 };
19186 let hour = 3_600_000_000_000_i64;
19187 let instant = 1_710_081_000_000_000_000_i64;
19190 assert_eq!(tz_offset_seconds("Asia/Tokyo", instant), Ok(9 * 3_600));
19191 assert_eq!(tz_offset_seconds("US/Eastern", instant), Ok(-4 * 3_600));
19192 assert_eq!(
19193 tz_offset_seconds("US/Eastern", instant - 24 * hour),
19194 Ok(-5 * 3_600)
19195 );
19196 assert_eq!(tz_offset_seconds("+05:30", 0), Ok(19_800));
19197 assert_eq!(tz_offset_seconds("UTC+05:30", 0), Ok(19_800));
19198 assert_eq!(tz_offset_seconds("-03:00", 0), Ok(-10_800));
19199 assert_eq!(tz_offset_seconds("UTC", instant), Ok(0));
19200 assert_eq!(
19201 tz_utc_to_wall_nanos("Asia/Tokyo", instant),
19202 Ok(instant + 9 * hour)
19203 );
19204 let wall_noon = 19_723 * 24 * hour + 12 * hour;
19206 assert_eq!(
19207 tz_wall_to_utc_nanos("US/Eastern", wall_noon),
19208 Ok(wall_noon + 5 * hour)
19209 );
19210 assert_eq!(
19211 tz_utc_to_wall_nanos("US/Eastern", wall_noon + 5 * hour),
19212 Ok(wall_noon)
19213 );
19214 assert_eq!(tz_wall_to_utc_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19216 assert_eq!(tz_utc_to_wall_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19217 let skipped = 19_792 * 24 * hour + 2 * hour + 30 * 60_000_000_000;
19221 assert_eq!(
19222 tz_wall_to_utc_nanos("US/Eastern", skipped),
19223 Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19224 );
19225 let repeated = 20_030 * 24 * hour + hour + 30 * 60_000_000_000;
19226 assert_eq!(
19227 tz_wall_to_utc_nanos("US/Eastern", repeated),
19228 Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19229 );
19230 assert_eq!(
19231 tz_offset_seconds("Mars/Olympus", 0),
19232 Err(TimeZoneError::Unknown("Mars/Olympus".to_owned()))
19233 );
19234 assert!(tz_validate("+24:00").is_err());
19235 assert!(tz_validate("+5:30").is_err());
19236 assert!(tz_validate("Europe/Paris").is_ok());
19237 assert_eq!(tz_canonical_name("+05:30").as_deref(), Ok("UTC+05:30"));
19239 assert_eq!(tz_canonical_name("UTC-03:00").as_deref(), Ok("UTC-03:00"));
19240 assert_eq!(tz_canonical_name("+00:00").as_deref(), Ok("UTC"));
19241 assert_eq!(tz_canonical_name("Z").as_deref(), Ok("UTC"));
19242 assert_eq!(tz_canonical_name("US/Eastern").as_deref(), Ok("US/Eastern"));
19243 assert_eq!(tz_abbreviation("US/Eastern", instant).as_deref(), Ok("EDT"));
19245 assert_eq!(
19246 tz_abbreviation("US/Eastern", instant - 24 * hour).as_deref(),
19247 Ok("EST")
19248 );
19249 assert_eq!(tz_abbreviation("+05:30", 0).as_deref(), Ok("UTC+05:30"));
19250 }
19251
19252 #[test]
19259 fn tz_localize_policies_follow_pandas_84w06() {
19260 use super::{
19261 AmbiguousTime as A, NonexistentTime as N, TimeZoneError,
19262 tz_wall_to_utc_nanos_with as at,
19263 };
19264 let hour = 3_600_000_000_000_i64;
19265 let minute = 60_000_000_000_i64;
19266 let skipped = 19_792 * 24 * hour + 2 * hour + 30 * minute;
19267 let transition = 19_792 * 24 * hour + 7 * hour;
19268 let zone = "America/New_York";
19269 assert_eq!(at(zone, skipped, A::Raise, N::ShiftForward), Ok(transition));
19270 assert_eq!(
19271 at(zone, skipped, A::Raise, N::ShiftBackward),
19272 Ok(transition - 1)
19273 );
19274 assert_eq!(at(zone, skipped, A::Raise, N::NaT), Ok(i64::MIN));
19275 assert_eq!(
19276 at(zone, skipped, A::Raise, N::Shift(hour)),
19277 Ok(transition + 30 * minute)
19278 );
19279 let repeated = 20_030 * 24 * hour + hour + 30 * minute;
19280 assert_eq!(
19281 at(zone, repeated, A::Earliest, N::Raise),
19282 Ok(repeated + 4 * hour)
19283 );
19284 assert_eq!(
19285 at(zone, repeated, A::Latest, N::Raise),
19286 Ok(repeated + 5 * hour)
19287 );
19288 assert_eq!(at(zone, repeated, A::NaT, N::Raise), Ok(i64::MIN));
19289 let noon = 19_723 * 24 * hour + 12 * hour;
19292 assert_eq!(at(zone, noon, A::NaT, N::NaT), Ok(noon + 5 * hour));
19293 assert_eq!(
19294 at(zone, skipped, A::NaT, N::Raise),
19295 Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19296 );
19297 assert_eq!(
19298 at(zone, repeated, A::Raise, N::NaT),
19299 Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19300 );
19301 }
19302
19303 #[test]
19304 fn timestamp_display_matches_phase2_debug_format() {
19305 assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
19306 assert_eq!(
19307 Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
19308 "Timestamp[42, US/Eastern]"
19309 );
19310 assert_eq!(Timestamp::nat().to_string(), "NaT");
19311 }
19312
19313 #[test]
19314 fn timestamp_value_and_unit_match_pandas_l0edr() {
19315 let ts = Timestamp::from_nanos(1_000_000_123);
19316 assert_eq!(ts.value(), 1_000_000_123);
19317 assert_eq!(ts.unit(), Some("ns"));
19318
19319 let nat = Timestamp::nat();
19320 assert_eq!(nat.value(), Timestamp::NAT);
19321 assert_eq!(nat.unit(), None);
19322 }
19323
19324 #[test]
19325 fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
19326 let ts = Timestamp::from_nanos(1_000_000_123);
19327 assert_eq!(ts.asm8(), ts.value());
19328 assert_eq!(ts.to_datetime64(), ts.value());
19329 assert_eq!(ts.to_numpy(), ts.value());
19330
19331 let nat = Timestamp::nat();
19332 assert_eq!(nat.asm8(), Timestamp::NAT);
19333 assert_eq!(nat.to_datetime64(), Timestamp::NAT);
19334 assert_eq!(nat.to_numpy(), Timestamp::NAT);
19335 }
19336
19337 #[test]
19338 fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
19339 assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
19340 assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
19341 assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
19342 assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
19343 assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
19344
19345 assert!(matches!(
19346 Timestamp::from_nanos(-500).timestamp(),
19347 Ok(value) if value == -0.0 && value.is_sign_negative()
19348 ));
19349 assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
19350 assert_eq!(
19351 Timestamp::nat().timestamp(),
19352 Err(TypeError::ValueIsMissing {
19353 kind: NullKind::NaT,
19354 })
19355 );
19356 }
19357
19358 #[test]
19359 fn timestamp_roundtrips_through_serde_json() {
19360 let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
19361 let json = serde_json::to_string(&naive).expect("serialize");
19362 let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19363 assert_eq!(naive, back);
19364
19365 let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19366 let json = serde_json::to_string(&tz_aware).expect("serialize");
19367 let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19368 assert_eq!(tz_aware, back);
19369 }
19370
19371 #[test]
19372 fn timestamp_is_send_and_sync() {
19373 fn assert_send_sync<T: Send + Sync>() {}
19374 assert_send_sync::<Timestamp>();
19375 }
19376
19377 #[test]
19380 fn timestamp_pre_epoch_accessors_floor_not_truncate() {
19381 let ts = Timestamp::from_nanos(-1);
19385 assert_eq!(ts.year(), Some(1969));
19386 assert_eq!(ts.month(), Some(12));
19387 assert_eq!(ts.day(), Some(31));
19388 assert_eq!(ts.hour(), Some(23));
19389 assert_eq!(ts.minute(), Some(59));
19390 assert_eq!(ts.second(), Some(59));
19391 assert_eq!(ts.microsecond(), Some(999_999));
19392 assert_eq!(ts.nanosecond(), Some(999));
19393 assert_eq!(ts.dayofweek(), Some(2));
19395
19396 let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
19398 assert_eq!(noon.year(), Some(1969));
19399 assert_eq!(noon.month(), Some(12));
19400 assert_eq!(noon.day(), Some(31));
19401 assert_eq!(noon.hour(), Some(12));
19402
19403 let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
19405 assert_eq!(midnight.year(), Some(1969));
19406 assert_eq!(midnight.day(), Some(31));
19407 assert_eq!(midnight.hour(), Some(0));
19408 }
19409
19410 #[test]
19411 fn timestamp_floor_to_rounds_down() {
19412 let h = Timedelta::NANOS_PER_HOUR;
19414 let twelve_h = h * 12;
19415 let twelve_thirty_four =
19416 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19417 let ts = Timestamp::from_nanos(twelve_thirty_four);
19418 let floored = ts.floor_to(h);
19419 assert_eq!(floored.nanos, twelve_h);
19420 }
19421
19422 #[test]
19423 fn timestamp_floor_to_handles_already_aligned() {
19424 let h = Timedelta::NANOS_PER_HOUR;
19426 let twelve_h = h * 12;
19427 let ts = Timestamp::from_nanos(twelve_h);
19428 assert_eq!(ts.floor_to(h).nanos, twelve_h);
19429 }
19430
19431 #[test]
19432 fn timestamp_floor_to_handles_negative_nanos() {
19433 let ts = Timestamp::from_nanos(-100);
19437 assert_eq!(ts.floor_to(60).nanos, -120);
19438 }
19439
19440 #[test]
19441 fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
19442 let ts = Timestamp::from_nanos(i64::MIN + 1);
19443 assert!(ts.floor_to(10).is_nat());
19444
19445 let safe = Timestamp::from_nanos(i64::MIN + 10);
19446 assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
19447
19448 let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
19449 assert_eq!(tz.nanos, -120);
19450 assert_eq!(tz.tz.as_deref(), Some("UTC"));
19451 }
19452
19453 #[test]
19454 fn timestamp_ceil_to_rounds_up() {
19455 let h = Timedelta::NANOS_PER_HOUR;
19457 let twelve_h = h * 12;
19458 let thirteen_h = h * 13;
19459 let twelve_thirty_four =
19460 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19461 let ts = Timestamp::from_nanos(twelve_thirty_four);
19462 assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
19463 }
19464
19465 #[test]
19466 fn timestamp_ceil_to_no_op_on_aligned() {
19467 let h = Timedelta::NANOS_PER_HOUR;
19468 let twelve_h = h * 12;
19469 let ts = Timestamp::from_nanos(twelve_h);
19470 assert_eq!(ts.ceil_to(h).nanos, twelve_h);
19471 }
19472
19473 #[test]
19474 fn timestamp_round_to_rounds_to_nearest() {
19475 let h = Timedelta::NANOS_PER_HOUR;
19477 let twelve_h = h * 12;
19478 let twelve_thirty_one_sec =
19479 twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
19480 let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
19481 assert_eq!(ts.round_to(h).nanos, h * 13);
19482
19483 let twelve_twenty_nine_sec =
19485 twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
19486 let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
19487 assert_eq!(ts.round_to(h).nanos, twelve_h);
19488 }
19489
19490 #[test]
19491 fn timestamp_round_to_bankers_tie_to_even() {
19492 assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
19498 assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
19499 assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
19500 assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
19501 }
19502
19503 #[test]
19504 fn timestamp_round_to_zero_unit_returns_nat() {
19505 let ts = Timestamp::from_nanos(100);
19506 assert!(ts.round_to(0).is_nat());
19507 assert!(ts.floor_to(0).is_nat());
19508 assert!(ts.ceil_to(0).is_nat());
19509 }
19510
19511 #[test]
19512 fn timestamp_round_to_negative_unit_returns_nat() {
19513 let ts = Timestamp::from_nanos(100);
19514 assert!(ts.round_to(-10).is_nat());
19515 assert!(ts.floor_to(-10).is_nat());
19516 assert!(ts.ceil_to(-10).is_nat());
19517 }
19518
19519 #[test]
19520 fn timestamp_rounding_propagates_nat() {
19521 let nat = Timestamp::nat();
19522 assert!(nat.floor_to(60).is_nat());
19523 assert!(nat.ceil_to(60).is_nat());
19524 assert!(nat.round_to(60).is_nat());
19525 }
19526
19527 #[test]
19528 fn timestamp_rounding_preserves_tz() {
19529 let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
19530 assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
19531 assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
19532 assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
19533 }
19534
19535 #[test]
19538 fn timestamp_floor_to_unit_h_rounds_to_hour() {
19539 let h = Timedelta::NANOS_PER_HOUR;
19540 let twelve_h = h * 12;
19541 let twelve_thirty_four =
19542 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19543 let ts = Timestamp::from_nanos(twelve_thirty_four);
19544 assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
19545 assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
19546 assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
19547 assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
19548 assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
19549 }
19550
19551 #[test]
19552 fn timestamp_ceil_to_unit_d_rounds_to_day() {
19553 let h = Timedelta::NANOS_PER_HOUR;
19555 let d = Timedelta::NANOS_PER_DAY;
19556 let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
19557 let ts = Timestamp::from_nanos(twelve_thirty_four);
19558 assert_eq!(ts.ceil_to_unit("D").nanos, d);
19559 assert_eq!(ts.ceil_to_unit("day").nanos, d);
19560 assert_eq!(ts.ceil_to_unit("days").nanos, d);
19561 }
19562
19563 #[test]
19564 fn timestamp_round_to_unit_min_rounds_to_minute() {
19565 let m = Timedelta::NANOS_PER_MIN;
19567 let twelve_thirty_four_thirty_one =
19568 Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
19569 let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
19570 let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
19571 assert_eq!(ts.round_to_unit("min").nanos, expected);
19572 assert_eq!(ts.round_to_unit("T").nanos, expected); assert_eq!(ts.round_to_unit("minute").nanos, expected);
19574 }
19575
19576 #[test]
19577 fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
19578 let ts = Timestamp::from_nanos(
19579 Timedelta::NANOS_PER_HOUR * 12
19580 + Timedelta::NANOS_PER_MIN * 34
19581 + Timedelta::NANOS_PER_SEC * 31,
19582 );
19583
19584 assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
19585 assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
19586 assert_eq!(ts.round("min"), ts.round_to_unit("min"));
19587 }
19588
19589 #[test]
19590 fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
19591 let ts = Timestamp::from_nanos_tz(
19592 Timedelta::NANOS_PER_DAY * 3
19593 + Timedelta::NANOS_PER_HOUR * 12
19594 + Timedelta::NANOS_PER_MIN * 34,
19595 "US/Eastern",
19596 );
19597 let normalized = ts.normalize();
19598
19599 assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
19600 assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
19601 assert!(Timestamp::nat().normalize().is_nat());
19602 for nanos in [
19603 i64::MIN + 1,
19604 -Timedelta::NANOS_PER_DAY - 1,
19605 -Timedelta::NANOS_PER_DAY,
19606 -1,
19607 0,
19608 Timedelta::NANOS_PER_DAY - 1,
19609 Timedelta::NANOS_PER_DAY,
19610 i64::MAX,
19611 ] {
19612 let timestamp = Timestamp::from_nanos(nanos);
19613 assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
19614 }
19615 }
19616
19617 #[test]
19618 #[ignore = "foreground profile-first A/B"]
19619 fn timestamp_normalize_direct_day_profile_dk721() {
19620 use std::{hint::black_box, time::Instant};
19621
19622 fn former(timestamp: &Timestamp) -> Timestamp {
19623 timestamp.floor_to_unit("D")
19624 }
19625
19626 fn candidate(timestamp: &Timestamp) -> Timestamp {
19627 timestamp.normalize()
19628 }
19629
19630 fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
19631 let started = Instant::now();
19632 let mut checksum = 0_u64;
19633 for timestamp in input {
19634 let normalized = normalize(black_box(timestamp));
19635 checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
19636 }
19637 black_box(checksum);
19638 started.elapsed().as_nanos()
19639 }
19640
19641 fn percentile(samples: &mut [u128], percent: usize) -> u128 {
19642 samples.sort_unstable();
19643 let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
19644 samples[rank]
19645 }
19646
19647 let parity_cases = [
19648 Timestamp::nat(),
19649 Timestamp::from_nanos(i64::MIN + 1),
19650 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
19651 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
19652 Timestamp::from_nanos(-1),
19653 Timestamp::from_nanos(0),
19654 Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
19655 Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
19656 Timestamp::from_nanos(i64::MAX),
19657 Timestamp::from_nanos_tz(-1, "US/Eastern"),
19658 Timestamp::from_nanos_tz(
19659 Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
19660 "Asia/Tokyo",
19661 ),
19662 ];
19663 for timestamp in &parity_cases {
19664 assert_eq!(former(timestamp), candidate(timestamp));
19665 assert_eq!(timestamp.normalize(), former(timestamp));
19666 }
19667
19668 const ROWS: usize = 16_384;
19669 const SAMPLES: usize = 20;
19670 let input = (0..ROWS)
19671 .map(|index| {
19672 let day = index as i64 % 4_096 - 2_048;
19673 let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
19674 % Timedelta::NANOS_PER_DAY as u64) as i64;
19675 Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
19676 })
19677 .collect::<Vec<_>>();
19678 for timestamp in &input {
19679 assert_eq!(former(timestamp), candidate(timestamp));
19680 }
19681
19682 for _ in 0..3 {
19683 black_box(elapsed(&input, former));
19684 black_box(elapsed(&input, candidate));
19685 }
19686
19687 let mut former_ns = Vec::with_capacity(SAMPLES);
19688 let mut candidate_ns = Vec::with_capacity(SAMPLES);
19689 for sample in 0..SAMPLES {
19690 if sample % 2 == 0 {
19691 former_ns.push(elapsed(&input, former));
19692 candidate_ns.push(elapsed(&input, candidate));
19693 } else {
19694 candidate_ns.push(elapsed(&input, candidate));
19695 former_ns.push(elapsed(&input, former));
19696 }
19697 }
19698
19699 let mut former_sorted = former_ns.clone();
19700 let mut candidate_sorted = candidate_ns.clone();
19701 let former_p50 = percentile(&mut former_sorted, 50);
19702 let former_p95 = percentile(&mut former_sorted, 95);
19703 let former_p99 = percentile(&mut former_sorted, 99);
19704 let candidate_p50 = percentile(&mut candidate_sorted, 50);
19705 let candidate_p95 = percentile(&mut candidate_sorted, 95);
19706 let candidate_p99 = percentile(&mut candidate_sorted, 99);
19707 println!(
19708 "TIMESTAMP_NORMALIZE_DIRECT_DAY rows={ROWS} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup_p50={:.6} former_p95_ns={former_p95} candidate_p95_ns={candidate_p95} speedup_p95={:.6} former_p99_ns={former_p99} candidate_p99_ns={candidate_p99} speedup_p99={:.6} former_samples={former_ns:?} candidate_samples={candidate_ns:?}",
19709 former_p50 as f64 / candidate_p50 as f64,
19710 former_p95 as f64 / candidate_p95 as f64,
19711 former_p99 as f64 / candidate_p99 as f64,
19712 );
19713 }
19714
19715 #[test]
19716 fn timestamp_unit_rounding_unknown_unit_returns_nat() {
19717 let ts = Timestamp::from_nanos(100);
19718 assert!(ts.floor_to_unit("fortnight").is_nat());
19719 assert!(ts.ceil_to_unit("century").is_nat());
19720 assert!(ts.round_to_unit("xyz").is_nat());
19721 }
19722
19723 #[test]
19726 fn timestamp_rounding_reads_a_multiple_of_a_unit_3agof() {
19727 let (min, sec) = (Timedelta::NANOS_PER_MIN, Timedelta::NANOS_PER_SEC);
19728 let base = 1_710_460_800 * sec; let ts = Timestamp::from_nanos(base + 13 * Timedelta::NANOS_PER_HOUR + 47 * min + 21 * sec);
19730 let at = |minutes: i64, seconds: i64| base + minutes * min + seconds * sec;
19731 assert_eq!(ts.round("15min").nanos, at(13 * 60 + 45, 0));
19732 assert_eq!(ts.floor("15min").nanos, at(13 * 60 + 45, 0));
19733 assert_eq!(ts.ceil("15min").nanos, at(14 * 60, 0));
19734 assert_eq!(ts.round("30s").nanos, at(13 * 60 + 47, 30));
19735 assert_eq!(ts.ceil("1D").nanos, base + Timedelta::NANOS_PER_DAY);
19736 assert_eq!(ts.floor("7D").nanos, 19_796 * Timedelta::NANOS_PER_DAY);
19739 assert!(ts.round("ME").is_nat());
19741 }
19742
19743 #[test]
19744 fn timestamp_unit_rounding_propagates_nat() {
19745 let nat = Timestamp::nat();
19746 assert!(nat.floor_to_unit("H").is_nat());
19747 assert!(nat.ceil_to_unit("H").is_nat());
19748 assert!(nat.round_to_unit("H").is_nat());
19749 }
19750
19751 #[test]
19752 fn timestamp_unit_rounding_preserves_tz() {
19753 let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
19754 assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19755 assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19756 assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19757 }
19758
19759 #[test]
19760 fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
19761 assert_eq!(
19763 Timedelta::unit_to_nanos("W"),
19764 Some(Timedelta::NANOS_PER_WEEK)
19765 );
19766 assert_eq!(
19767 Timedelta::unit_to_nanos("D"),
19768 Some(Timedelta::NANOS_PER_DAY)
19769 );
19770 assert_eq!(
19771 Timedelta::unit_to_nanos("H"),
19772 Some(Timedelta::NANOS_PER_HOUR)
19773 );
19774 assert_eq!(
19775 Timedelta::unit_to_nanos("min"),
19776 Some(Timedelta::NANOS_PER_MIN)
19777 );
19778 assert_eq!(
19779 Timedelta::unit_to_nanos("s"),
19780 Some(Timedelta::NANOS_PER_SEC)
19781 );
19782 assert_eq!(
19783 Timedelta::unit_to_nanos("ms"),
19784 Some(Timedelta::NANOS_PER_MILLI)
19785 );
19786 assert_eq!(
19787 Timedelta::unit_to_nanos("us"),
19788 Some(Timedelta::NANOS_PER_MICRO)
19789 );
19790 assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
19791 assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
19793 assert_eq!(Timedelta::unit_to_nanos("century"), None);
19795 }
19796
19797 #[test]
19798 fn timestamp_isoformat_basic() {
19799 let ts = Timestamp::from_nanos(0);
19800 assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
19801
19802 let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
19803 assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
19804
19805 let ts_fixed_offset = Timestamp::from_nanos_tz(0, "UTC+05:30");
19806 assert_eq!(
19807 ts_fixed_offset.isoformat(),
19808 "1970-01-01T05:30:00+05:30",
19809 "a fixed-offset timestamp must render local wall time rather than a UTC instant with an annotation"
19810 );
19811
19812 let ts_tz = Timestamp::from_nanos_tz(
19813 Timedelta::NANOS_PER_DAY
19814 + Timedelta::NANOS_PER_HOUR * 14
19815 + Timedelta::NANOS_PER_MIN * 30,
19816 "America/New_York",
19817 );
19818 assert!(ts_tz.isoformat().contains("1970-01-02T14:30:00"));
19819 assert!(ts_tz.isoformat().contains("[America/New_York]"));
19820
19821 assert_eq!(Timestamp::nat().isoformat(), "NaT");
19822 }
19823
19824 #[test]
19825 fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
19826 assert_eq!(
19827 Timestamp::from_nanos(-1).isoformat(),
19828 "1969-12-31T23:59:59.999999999"
19829 );
19830 assert_eq!(
19831 Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
19832 "1969-12-31T23:59:59"
19833 );
19834 assert_eq!(
19835 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
19836 "1969-12-31T00:00:00"
19837 );
19838 assert_eq!(
19839 Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
19840 "1969-12-31T23:59:59.999999999+00:00"
19841 );
19842 }
19843
19844 #[test]
19845 fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
19846 assert_eq!(
19847 Timestamp::from_nanos(123_456_789).isoformat(),
19848 "1970-01-01T00:00:00.123456789"
19849 );
19850 assert_eq!(
19851 Timestamp::from_nanos(123_456_000).isoformat(),
19852 "1970-01-01T00:00:00.123456"
19853 );
19854 assert_eq!(
19855 Timestamp::from_nanos(123_000_000).isoformat(),
19856 "1970-01-01T00:00:00.123000"
19857 );
19858 assert_eq!(
19859 Timestamp::from_nanos_tz(1, "UTC").isoformat(),
19860 "1970-01-01T00:00:00.000000001+00:00"
19861 );
19862 }
19863
19864 fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
19865 if timestamp.is_nat() {
19866 return "NaT".to_owned();
19867 }
19868 let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
19869 match ×tamp.tz {
19870 Some(tz) if tz == "UTC" => format!("{base}+00:00"),
19871 Some(tz) => format!("{base}[{tz}]"),
19872 None => base,
19873 }
19874 }
19875
19876 #[test]
19877 fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
19878 let nanos = [
19879 Timestamp::NAT,
19880 -Timedelta::NANOS_PER_DAY - 1,
19881 -Timedelta::NANOS_PER_SEC,
19882 -1,
19883 0,
19884 1,
19885 123_456_000,
19886 123_456_789,
19887 i64::MAX,
19888 ];
19889 let timezones = [
19890 None,
19891 Some("UTC"),
19892 Some("America/New_York"),
19893 Some(""),
19894 Some("Etc/Γ"),
19895 ];
19896 for value in nanos {
19897 for timezone in timezones {
19898 let timestamp = Timestamp {
19899 nanos: value,
19900 tz: timezone.map(str::to_owned),
19901 };
19902 assert_eq!(
19903 timestamp.isoformat(),
19904 timestamp_isoformat_former_q8g50(×tamp),
19905 "nanos={value} timezone={timezone:?}"
19906 );
19907 }
19908 }
19909 }
19910
19911 #[test]
19912 #[ignore = "foreground release A/B only"]
19913 fn timestamp_isoformat_one_buffer_ab_q8g50() {
19914 use std::{hint::black_box, time::Instant};
19915
19916 const ITEMS: usize = 8_192;
19917 const SAMPLES: usize = 10;
19918
19919 fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
19920 let started = Instant::now();
19921 let mut checksum = 0usize;
19922 for timestamp in black_box(values) {
19923 checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
19924 }
19925 black_box(checksum);
19926 started.elapsed().as_nanos()
19927 }
19928
19929 let values = (0..ITEMS)
19930 .map(|idx| {
19931 let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
19932 let timezone = if idx.is_multiple_of(2) {
19933 "UTC"
19934 } else {
19935 "America/New_York"
19936 };
19937 Timestamp::from_nanos_tz(nanos, timezone)
19938 })
19939 .collect::<Vec<_>>();
19940 for timestamp in &values {
19941 assert_eq!(
19942 timestamp.isoformat(),
19943 timestamp_isoformat_former_q8g50(timestamp)
19944 );
19945 }
19946
19947 black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
19948 black_box(elapsed(&values, Timestamp::isoformat));
19949
19950 let mut former_ns = Vec::with_capacity(SAMPLES);
19951 let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
19952 for sample in 0..SAMPLES {
19953 if sample.is_multiple_of(2) {
19954 former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
19955 one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
19956 } else {
19957 one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
19958 former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
19959 }
19960 }
19961 former_ns.sort_unstable();
19962 one_buffer_ns.sort_unstable();
19963 let former_p50 = former_ns[SAMPLES / 2];
19964 let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
19965 println!(
19966 "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
19967 former_p50 as f64 / one_buffer_p50 as f64
19968 );
19969 println!("former_samples_ns={former_ns:?}");
19970 println!("one_buffer_samples_ns={one_buffer_ns:?}");
19971 }
19972
19973 #[test]
19974 fn timestamp_strftime_basic() {
19975 let ts = Timestamp::from_nanos(
19976 Timedelta::NANOS_PER_DAY * 365
19977 + Timedelta::NANOS_PER_HOUR * 9
19978 + Timedelta::NANOS_PER_MIN * 15,
19979 );
19980 assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
19981 assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
19982 assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
19983 assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%Y|%01|%Q|%|λ");
19986 assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
19987 }
19988
19989 #[test]
19990 fn strftime_follows_python_directives_and_zones() {
19991 let ts = Timestamp::from_nanos(
19994 Timedelta::NANOS_PER_DAY * 365
19995 + Timedelta::NANOS_PER_HOUR * 9
19996 + Timedelta::NANOS_PER_MIN * 15,
19997 );
19998 assert_eq!(
19999 ts.strftime("%-d %_m %^a %e %k %l %P %C %g %D %F %T %R %r %h %n %t|"),
20000 "1 1 FRI 1 9 9 am 19 70 01/01/71 1971-01-01 09:15:00 09:15 09:15:00 AM Jan \n \t|"
20001 );
20002 assert_eq!(
20003 ts.strftime("%a %A %b %B %c|%x %X|%I %p %j %U %W %w %y"),
20004 "Fri Friday Jan January Fri Jan 1 09:15:00 1971|01/01/71 09:15:00|09 AM 001 00 00 5 71"
20005 );
20006 let sunday = Timestamp::parse("2021-01-03").expect("date");
20008 assert_eq!(sunday.strftime("%G-%V-%u %U %W %j"), "2020-53-7 01 00 003");
20009 let fraction = Timestamp::parse("2024-03-05 14:07:09.123456789").expect("ts");
20011 assert_eq!(fraction.strftime("%f|%z|%Z|abc%"), "123456|||abc%");
20012 let eastern = Timestamp::from_nanos_tz(fraction.nanos, "US/Eastern");
20014 assert_eq!(
20015 eastern.strftime("%Y-%m-%d %H:%M %z %Z"),
20016 "2024-03-05 09:07 -0500 EST"
20017 );
20018 assert_eq!(
20019 crate::strftime_in_zone(fraction.nanos, "%H:%M %z", Some("+05:30")),
20020 "19:37 +0530"
20021 );
20022 }
20023
20024 #[test]
20025 fn timestamp_strftime_floors_pre_epoch_instants_1pmlp() {
20026 let apollo = Timestamp::parse("1969-07-20T20:17:40").unwrap();
20027 assert_eq!(
20028 apollo.strftime("%Y-%m-%d %H:%M:%S.%f"),
20029 "1969-07-20 20:17:40.000000"
20030 );
20031
20032 let one_ns_before_epoch = Timestamp::from_nanos(-1);
20035 assert_eq!(
20036 one_ns_before_epoch.strftime("%Y-%m-%d %H:%M:%S.%f"),
20037 "1969-12-31 23:59:59.999999"
20038 );
20039 }
20040
20041 #[test]
20042 #[ignore = "foreground normal-release attribution harness"]
20043 fn timestamp_strftime_one_buffer_profile_8qzbo() {
20044 use std::{hint::black_box, time::Instant};
20045
20046 const ITEMS: usize = 8_192;
20047 const SAMPLES: usize = 10;
20048 const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
20049
20050 fn former(timestamp: &Timestamp, format: &str) -> String {
20051 if timestamp.is_nat() {
20052 return "NaT".to_string();
20053 }
20054 let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
20055 let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
20056
20057 let days_since_epoch = total_secs / 86400;
20058 let secs_of_day = (total_secs % 86400 + 86400) % 86400;
20059 let days = days_since_epoch + 719_468;
20060 let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
20061 let doe = days - era * 146_097;
20062 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
20063 let y = yoe + era * 400;
20064 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
20065 let mp = (5 * doy + 2) / 153;
20066 let d = doy - (153 * mp + 2) / 5 + 1;
20067 let m = if mp < 10 { mp + 3 } else { mp - 9 };
20068 let year = if m <= 2 { y + 1 } else { y };
20069 let hour = secs_of_day / 3600;
20070 let minute = (secs_of_day % 3600) / 60;
20071 let second = secs_of_day % 60;
20072 let micros = sub_nanos / 1000;
20073
20074 format
20075 .replace("%Y", &format!("{year:04}"))
20076 .replace("%m", &format!("{m:02}"))
20077 .replace("%d", &format!("{d:02}"))
20078 .replace("%H", &format!("{hour:02}"))
20079 .replace("%M", &format!("{minute:02}"))
20080 .replace("%S", &format!("{second:02}"))
20081 .replace("%f", &format!("{micros:06}"))
20082 }
20083
20084 fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
20085 let started = Instant::now();
20086 let mut digest = 0_usize;
20087 for timestamp in timestamps {
20088 let value = formatter(black_box(timestamp), black_box(FORMAT));
20089 digest = digest.wrapping_add(value.len());
20090 digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
20091 black_box(value);
20092 }
20093 black_box(digest);
20094 started.elapsed().as_nanos()
20095 }
20096
20097 fn percentile(samples: &mut [u128], pct: usize) -> u128 {
20098 samples.sort_unstable();
20099 let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
20100 samples[rank]
20101 }
20102
20103 let edge_timestamps = [
20104 Timestamp::nat(),
20105 Timestamp::from_nanos(i64::MIN + 1),
20106 Timestamp::from_nanos(-1_234_567_890),
20107 Timestamp::from_nanos(0),
20108 Timestamp::from_nanos(1_735_732_800_123_456_789),
20109 Timestamp::from_nanos(i64::MAX),
20110 ];
20111 let edge_formats = [
20112 "",
20113 "%Y-%m-%d %H:%M:%S.%f",
20114 "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
20115 "%%Y|%%%m|%Q|%|λ",
20116 FORMAT,
20117 ];
20118 for timestamp in &edge_timestamps {
20119 for format in edge_formats {
20120 assert_eq!(former(timestamp, format), timestamp.strftime(format));
20121 }
20122 }
20123
20124 let timestamps = (0..ITEMS)
20125 .map(|index| {
20126 let centered = index as i64 - ITEMS as i64 / 2;
20127 Timestamp::from_nanos(centered * 987_654_321_123_456)
20128 })
20129 .collect::<Vec<_>>();
20130 for timestamp in ×tamps {
20131 assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
20132 }
20133
20134 black_box(elapsed(×tamps, former));
20135 black_box(elapsed(×tamps, Timestamp::strftime));
20136
20137 let mut former_samples = Vec::with_capacity(SAMPLES);
20138 let mut public_samples = Vec::with_capacity(SAMPLES);
20139 for sample in 0..SAMPLES {
20140 if sample.is_multiple_of(2) {
20141 former_samples.push(elapsed(×tamps, former));
20142 public_samples.push(elapsed(×tamps, Timestamp::strftime));
20143 } else {
20144 public_samples.push(elapsed(×tamps, Timestamp::strftime));
20145 former_samples.push(elapsed(×tamps, former));
20146 }
20147 }
20148 let former_p50 = percentile(&mut former_samples, 50);
20149 let former_p95 = percentile(&mut former_samples, 95);
20150 let public_p50 = percentile(&mut public_samples, 50);
20151 let public_p95 = percentile(&mut public_samples, 95);
20152 println!(
20153 "TIMESTAMP_STRFTIME_AB items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} former_p95_ns={former_p95} public_p50_ns={public_p50} public_p95_ns={public_p95} p50_speedup={:.6} p95_speedup={:.6}",
20154 former_p50 as f64 / public_p50 as f64,
20155 former_p95 as f64 / public_p95 as f64,
20156 );
20157 println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
20158 println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
20159 }
20160
20161 #[test]
20162 fn timestamp_day_name_and_month_name() {
20163 let ts = Timestamp::from_nanos(0);
20164 assert_eq!(ts.day_name(), "Thursday");
20165 assert_eq!(ts.month_name(), "January");
20166
20167 let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20168 assert_eq!(ts2.day_name(), "Friday");
20169 assert_eq!(ts2.month_name(), "January");
20170
20171 assert_eq!(Timestamp::nat().day_name(), "NaT");
20172 assert_eq!(Timestamp::nat().month_name(), "NaT");
20173 }
20174
20175 #[test]
20176 fn timestamp_replace_validates_components_zw0y2() {
20177 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20178 let replaced = ts.replace(
20179 Some(2024),
20180 Some(2),
20181 Some(29),
20182 Some(23),
20183 Some(59),
20184 Some(58),
20185 Some(987_654),
20186 Some(321),
20187 );
20188 assert_eq!(replaced.year(), Some(2024));
20189 assert_eq!(replaced.month(), Some(2));
20190 assert_eq!(replaced.day(), Some(29));
20191 assert_eq!(replaced.hour(), Some(23));
20192 assert_eq!(replaced.minute(), Some(59));
20193 assert_eq!(replaced.second(), Some(58));
20194 assert_eq!(replaced.microsecond(), Some(987_654));
20195 assert_eq!(replaced.nanosecond(), Some(321));
20196
20197 let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20198 assert_eq!(
20199 tz.replace(None, Some(2), Some(29), None, None, None, None, None)
20200 .tz
20201 .as_deref(),
20202 Some("UTC")
20203 );
20204
20205 assert!(
20206 ts.replace(None, Some(13), None, None, None, None, None, None)
20207 .is_nat()
20208 );
20209 assert!(
20210 ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
20211 .is_nat()
20212 );
20213 assert!(
20214 ts.replace(None, None, None, Some(24), None, None, None, None)
20215 .is_nat()
20216 );
20217 assert!(
20218 ts.replace(None, None, None, None, Some(60), None, None, None)
20219 .is_nat()
20220 );
20221 assert!(
20222 ts.replace(None, None, None, None, None, Some(60), None, None)
20223 .is_nat()
20224 );
20225 assert!(
20226 ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
20227 .is_nat()
20228 );
20229 assert!(
20230 ts.replace(None, None, None, None, None, None, None, Some(1_000))
20231 .is_nat()
20232 );
20233 assert!(
20234 Timestamp::nat()
20235 .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
20236 .is_nat()
20237 );
20238 }
20239
20240 #[test]
20247 fn timestamp_replace_returns_nat_on_nanosecond_overflow_dzz6x() {
20248 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20249
20250 for year in [3000, 10_000, 300_000, i64::MAX / 400] {
20251 let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20252 assert!(
20253 out.is_nat(),
20254 "replace(year={year}) is unrepresentable in i64 ns and must be \
20255 NaT, got nanos={:?} (year {:?}) — this is the silent wrap",
20256 out.nanos,
20257 out.year()
20258 );
20259 }
20260 for year in [-3000, -100_000, i64::MIN / 400] {
20261 let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20262 assert!(out.is_nat(), "replace(year={year}) must be NaT");
20263 }
20264
20265 let in_range = ts.replace(
20270 Some(2262),
20271 Some(1),
20272 Some(1),
20273 Some(0),
20274 Some(0),
20275 Some(0),
20276 Some(0),
20277 Some(0),
20278 );
20279 assert!(
20280 !in_range.is_nat(),
20281 "2262-01-01 is representable and must survive"
20282 );
20283 assert_eq!(in_range.year(), Some(2262));
20284 assert!(
20285 ts.replace(
20286 Some(2263),
20287 Some(12),
20288 Some(31),
20289 Some(23),
20290 Some(59),
20291 Some(59),
20292 Some(999_999),
20293 Some(999)
20294 )
20295 .is_nat(),
20296 "end of 2263 exceeds the i64 ns axis and must be NaT"
20297 );
20298
20299 let unchanged = ts.replace(
20303 Some(1999),
20304 Some(6),
20305 Some(30),
20306 Some(12),
20307 Some(1),
20308 Some(2),
20309 Some(3),
20310 Some(4),
20311 );
20312 assert_eq!(unchanged.year(), Some(1999));
20313 assert_eq!(unchanged.month(), Some(6));
20314 assert_eq!(unchanged.day(), Some(30));
20315 assert_eq!(unchanged.hour(), Some(12));
20316 assert_eq!(unchanged.minute(), Some(1));
20317 assert_eq!(unchanged.second(), Some(2));
20318 assert_eq!(unchanged.microsecond(), Some(3));
20319 assert_eq!(unchanged.nanosecond(), Some(4));
20320 let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20321 assert_eq!(
20322 tz.replace(Some(1999), None, None, None, None, None, None, None)
20323 .tz
20324 .as_deref(),
20325 Some("UTC")
20326 );
20327 }
20328
20329 #[test]
20330 fn timestamp_component_accessors() {
20331 let ts = Timestamp::from_nanos(0);
20332 assert_eq!(ts.year(), Some(1970));
20333 assert_eq!(ts.month(), Some(1));
20334 assert_eq!(ts.day(), Some(1));
20335 assert_eq!(ts.hour(), Some(0));
20336 assert_eq!(ts.minute(), Some(0));
20337 assert_eq!(ts.second(), Some(0));
20338 assert_eq!(ts.microsecond(), Some(0));
20339 assert_eq!(ts.nanosecond(), Some(0));
20340
20341 let ts2 = Timestamp::from_nanos(
20342 Timedelta::NANOS_PER_DAY * 365
20343 + Timedelta::NANOS_PER_HOUR * 14
20344 + Timedelta::NANOS_PER_MIN * 30
20345 + Timedelta::NANOS_PER_SEC * 45
20346 + 123_456_789,
20347 );
20348 assert_eq!(ts2.year(), Some(1971));
20349 assert_eq!(ts2.month(), Some(1));
20350 assert_eq!(ts2.day(), Some(1));
20351 assert_eq!(ts2.hour(), Some(14));
20352 assert_eq!(ts2.minute(), Some(30));
20353 assert_eq!(ts2.second(), Some(45));
20354 assert_eq!(ts2.microsecond(), Some(123456));
20355 assert_eq!(ts2.nanosecond(), Some(789));
20356
20357 assert_eq!(Timestamp::nat().year(), None);
20358 assert_eq!(Timestamp::nat().month(), None);
20359 assert_eq!(Timestamp::nat().day(), None);
20360 }
20361
20362 #[test]
20363 fn timestamp_dayofweek_dayofyear_quarter() {
20364 let ts = Timestamp::from_nanos(0);
20365 assert_eq!(ts.dayofweek(), Some(3));
20366 assert_eq!(ts.weekday(), Some(3));
20367 assert_eq!(ts.dayofyear(), Some(1));
20368 assert_eq!(ts.quarter(), Some(1));
20369
20370 let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
20371 assert_eq!(ts2.quarter(), Some(2));
20372
20373 let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20374 assert_eq!(ts3.dayofyear(), Some(1));
20375 assert_eq!(ts3.dayofweek(), Some(4));
20376
20377 assert_eq!(Timestamp::nat().dayofweek(), None);
20378 assert_eq!(Timestamp::nat().dayofyear(), None);
20379 assert_eq!(Timestamp::nat().quarter(), None);
20380 }
20381
20382 #[test]
20383 fn timestamp_is_boundary_methods() {
20384 let jan1 = Timestamp::from_nanos(0);
20385 assert_eq!(jan1.is_leap_year(), Some(false));
20386 assert_eq!(jan1.is_month_start(), Some(true));
20387 assert_eq!(jan1.is_month_end(), Some(false));
20388 assert_eq!(jan1.is_quarter_start(), Some(true));
20389 assert_eq!(jan1.is_quarter_end(), Some(false));
20390 assert_eq!(jan1.is_year_start(), Some(true));
20391 assert_eq!(jan1.is_year_end(), Some(false));
20392
20393 let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
20394 assert_eq!(dec31.is_month_start(), Some(false));
20395 assert_eq!(dec31.is_month_end(), Some(true));
20396 assert_eq!(dec31.is_quarter_end(), Some(true));
20397 assert_eq!(dec31.is_year_end(), Some(true));
20398
20399 assert_eq!(Timestamp::nat().is_leap_year(), None);
20400 assert_eq!(Timestamp::nat().is_month_start(), None);
20401 }
20402
20403 #[test]
20404 fn timestamp_days_in_month() {
20405 let jan = Timestamp::from_nanos(0);
20406 assert_eq!(jan.days_in_month(), Some(31));
20407 assert_eq!(jan.daysinmonth(), Some(31));
20408
20409 let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
20410 assert_eq!(feb_non_leap.days_in_month(), Some(28));
20411
20412 assert_eq!(Timestamp::nat().days_in_month(), None);
20413 }
20414
20415 #[test]
20416 fn timestamp_weekofyear() {
20417 let jan1 = Timestamp::from_nanos(0);
20418 assert_eq!(jan1.weekofyear(), Some(1));
20419 assert_eq!(jan1.week(), Some(1));
20420
20421 let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
20422 assert_eq!(jan8.weekofyear(), Some(2));
20423
20424 assert_eq!(Timestamp::nat().weekofyear(), None);
20425 assert_eq!(Timestamp::nat().week(), None);
20426 }
20427
20428 #[test]
20429 fn timestamp_weekofyear_iso_53_week_boundaries() {
20430 fn week_of(date_days: i64) -> Option<i64> {
20433 Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
20434 }
20435 assert_eq!(week_of(18_628), Some(53)); assert_eq!(week_of(16_801), Some(53)); assert_eq!(week_of(20_818), Some(53)); assert_eq!(week_of(18_627), Some(53)); assert_eq!(week_of(19_358), Some(52)); assert_eq!(week_of(20_087), Some(1)); assert_eq!(week_of(18_260), Some(1)); }
20449
20450 #[test]
20451 fn iso_weeks_in_year_53_week_years() {
20452 use super::iso_weeks_in_year;
20453 for y in [2004, 2009, 2015, 2020, 2026] {
20455 assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
20456 }
20457 for y in [2018, 2019, 2021, 2022, 2023, 2024] {
20458 assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
20459 }
20460 }
20461
20462 #[test]
20463 fn timestamp_to_unit() {
20464 let ts = Timestamp::from_nanos(1_000_000_000);
20465 assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
20466 assert_eq!(ts.to_unit("us"), Some(1_000_000));
20467 assert_eq!(ts.to_unit("ms"), Some(1_000));
20468 assert_eq!(ts.to_unit("s"), Some(1));
20469 assert_eq!(ts.to_unit("invalid"), None);
20470
20471 assert_eq!(Timestamp::nat().to_unit("ns"), None);
20472 }
20473
20474 #[test]
20475 fn timestamp_toordinal() {
20476 let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
20479 let ts = Timestamp::from_nanos(nanos_2026_01_01);
20480 assert_eq!(ts.toordinal(), Some(738886));
20481
20482 assert_eq!(Timestamp::nat().toordinal(), None);
20484 }
20485
20486 #[test]
20487 fn timestamp_fromordinal() {
20488 let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
20491 let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
20492 let ordinal = ts_orig.toordinal().unwrap();
20493
20494 let ts = Timestamp::fromordinal(ordinal);
20496 assert_eq!(ts.year(), ts_orig.year());
20497 assert_eq!(ts.month(), ts_orig.month());
20498 assert_eq!(ts.day(), ts_orig.day());
20499
20500 let nat = Timestamp::fromordinal(0);
20502 assert!(nat.is_nat());
20503 }
20504
20505 #[test]
20506 fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
20507 const EPOCH_ORDINAL: i64 = 719_163;
20508 let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
20509 let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
20510
20511 let max_valid = Timestamp::fromordinal(max_valid_ordinal);
20512 assert!(!max_valid.is_nat());
20513 assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
20514
20515 assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
20516 assert!(Timestamp::fromordinal(i64::MAX).is_nat());
20517 }
20518
20519 #[test]
20520 fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
20521 const EPOCH_ORDINAL: i64 = 719_163;
20522 const DAY: i64 = Timedelta::NANOS_PER_DAY;
20523
20524 fn next(seed: &mut u64) -> u64 {
20525 *seed = seed
20526 .wrapping_mul(3202034522624059733)
20527 .wrapping_add(4354685564936845319);
20528 *seed
20529 }
20530
20531 fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
20532 let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
20533 let ts = Timestamp::from_nanos(nanos);
20534 let expected_day_offset = nanos.div_euclid(DAY);
20535 let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
20536
20537 assert_eq!(
20538 ts.toordinal(),
20539 Some(expected_ordinal),
20540 "case {case}: toordinal"
20541 );
20542
20543 let midnight = Timestamp::fromordinal(expected_ordinal);
20544 assert_eq!(
20545 midnight.nanos,
20546 expected_day_offset * DAY,
20547 "case {case}: fromordinal nanos"
20548 );
20549 assert_eq!(
20550 midnight.toordinal(),
20551 Some(expected_ordinal),
20552 "case {case}: fromordinal roundtrip"
20553 );
20554 }
20555
20556 assert_eq!(Timestamp::nat().toordinal(), None);
20557 assert!(Timestamp::fromordinal(0).is_nat());
20558 assert!(Timestamp::fromordinal(-1).is_nat());
20559
20560 assert_ordinal_case(usize::MAX, -1, DAY - 1);
20561 assert_ordinal_case(usize::MAX - 1, 0, -1);
20562 assert_ordinal_case(usize::MAX - 2, 19_723, 0);
20563
20564 let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
20565 for case in 0..260 {
20566 let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
20567 let subday_nanos = match case % 7 {
20568 0 => 0,
20569 1 => DAY - 1,
20570 2 => -1,
20571 _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
20572 };
20573 assert_ordinal_case(case, day_offset, subday_nanos);
20574 }
20575 }
20576
20577 #[test]
20584 fn timestamp_parse_rejects_unrepresentable_years_94o1u() {
20585 for s in [
20586 "300000-01-01",
20587 "10000000-06-15T12:30:45",
20588 "999999999-01-01",
20589 "-300000-01-01",
20590 "-99999999-12-31T23:59:59",
20591 ] {
20592 let got = Timestamp::parse(s);
20593 assert!(
20594 got.is_err(),
20595 "parse({s:?}) is unrepresentable in i64 ns and must be Err, got {:?} \
20596 — this is the silent wrap",
20597 got.map(|ts| (ts.nanos, ts.year()))
20598 );
20599 }
20600
20601 let ok = Timestamp::parse("2262-01-01").expect("2262-01-01 is representable");
20604 assert_eq!(ok.year(), Some(2262));
20605 assert!(
20606 Timestamp::parse("2263-12-31T23:59:59").is_err(),
20607 "end of 2263 exceeds the i64 ns axis and must be Err"
20608 );
20609
20610 assert_eq!(Timestamp::parse("2024-01-15").unwrap().year(), Some(2024));
20614 assert_eq!(
20615 Timestamp::parse("2024-01-15T10:30:45").unwrap().hour(),
20616 Some(10)
20617 );
20618 assert_eq!(
20619 Timestamp::parse("2024-01-15 10:30:45").unwrap().minute(),
20620 Some(30)
20621 );
20622 assert_eq!(
20623 Timestamp::parse("2024-01-15T10:30:45.123456789")
20624 .unwrap()
20625 .nanosecond(),
20626 Some(789)
20627 );
20628 assert_eq!(
20629 Timestamp::parse("2024-01-15T00:00:00Z").unwrap().year(),
20630 Some(2024)
20631 );
20632 assert_eq!(Timestamp::parse("1900-01-01").unwrap().year(), Some(1900));
20634 }
20635
20636 #[test]
20637 fn timestamp_parse_iso8601_date_only() {
20638 let ts = Timestamp::parse("2024-01-15").unwrap();
20639 assert_eq!(ts.year(), Some(2024));
20640 assert_eq!(ts.month(), Some(1));
20641 assert_eq!(ts.day(), Some(15));
20642 assert_eq!(ts.hour(), Some(0));
20643 assert_eq!(ts.minute(), Some(0));
20644 assert_eq!(ts.second(), Some(0));
20645 }
20646
20647 #[test]
20648 fn timestamp_parse_iso8601_datetime() {
20649 let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
20650 assert_eq!(ts.year(), Some(2024));
20651 assert_eq!(ts.month(), Some(1));
20652 assert_eq!(ts.day(), Some(15));
20653 assert_eq!(ts.hour(), Some(10));
20654 assert_eq!(ts.minute(), Some(30));
20655 assert_eq!(ts.second(), Some(45));
20656 }
20657
20658 #[test]
20659 fn timestamp_parse_space_separator() {
20660 let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
20661 assert_eq!(ts.year(), Some(2024));
20662 assert_eq!(ts.hour(), Some(10));
20663 }
20664
20665 #[test]
20666 fn timestamp_parse_with_fractional_seconds() {
20667 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20668 assert_eq!(ts.second(), Some(45));
20669 assert_eq!(ts.microsecond(), Some(123456));
20670 assert_eq!(ts.nanosecond(), Some(789));
20671 }
20672
20673 #[test]
20674 fn timestamp_parse_utc_timezone() {
20675 let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
20676 assert_eq!(ts.tz, Some("UTC".to_string()));
20677 }
20678
20679 #[test]
20680 fn timestamp_parse_offset_timezone() {
20681 let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
20682 assert_eq!(ts.tz, Some("+05:30".to_string()));
20683 let utc = |text: &str| Timestamp::parse(text).unwrap().nanos;
20686 assert_eq!(ts.nanos, utc("2024-01-15T05:00:45"));
20687
20688 let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
20689 assert_eq!(ts.tz, Some("-05:30".to_string()));
20690 assert_eq!(ts.nanos, utc("2024-01-15T16:00:45"));
20691 assert_eq!(
20693 Timestamp::parse("2024-01-15T10:30:45Z").unwrap().nanos,
20694 utc("2024-01-15T10:30:45")
20695 );
20696 }
20697
20698 #[test]
20699 fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
20700 assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
20701 assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
20702 assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
20703 assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
20704 assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
20705 }
20706
20707 #[test]
20708 fn timestamp_parse_nat() {
20709 let ts = Timestamp::parse("NaT").unwrap();
20710 assert!(ts.is_nat());
20711 let ts2 = Timestamp::parse("nat").unwrap();
20712 assert!(ts2.is_nat());
20713 }
20714
20715 #[test]
20716 fn timestamp_parse_invalid() {
20717 assert!(Timestamp::parse("not a date").is_err());
20718 assert!(Timestamp::parse("2024-13-01").is_err()); assert!(Timestamp::parse("2024-01-32").is_err()); }
20721
20722 #[test]
20723 fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
20724 assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
20725 assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
20726 assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
20727 assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
20728 assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
20729
20730 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
20731 assert_eq!(ts.second(), Some(45));
20732 assert_eq!(ts.microsecond(), Some(123456));
20733 assert_eq!(ts.nanosecond(), Some(789));
20734 }
20735
20736 #[test]
20737 #[ignore = "foreground profile-first A/B"]
20738 fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
20739 use std::{hint::black_box, time::Instant};
20740
20741 const CALLS: usize = 131_072;
20742 const SAMPLES: usize = 12;
20743 type ParsedTime = Option<(u32, u32, u32, u64)>;
20744 const VALID: [&str; 16] = [
20745 "00:00:00.0",
20746 "01:02:03.1",
20747 "02:03:04.01",
20748 "03:04:05.001",
20749 "04:05:06.0001",
20750 "05:06:07.00001",
20751 "06:07:08.000001",
20752 "07:08:09.0000001",
20753 "08:09:10.00000001",
20754 "09:10:11.000000001",
20755 "10:11:12.123456789",
20756 "11:12:13.999999999",
20757 "12:13:14.123456789987",
20758 "13:14:15.000000000001",
20759 "14:15:16.101010101010",
20760 "23:59:59.987654321234",
20761 ];
20762
20763 #[inline(never)]
20764 fn former(s: &str) -> ParsedTime {
20765 let (time_str, frac_str) = match s.split_once('.') {
20766 Some((time, frac)) => (time, Some(frac)),
20767 None => (s, None),
20768 };
20769 let parts: Vec<&str> = time_str.split(':').collect();
20770 if parts.is_empty() || parts.len() > 3 {
20771 return None;
20772 }
20773 let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
20774 let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
20775 let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
20776
20777 if hour > 23 || minute > 59 || second > 59 {
20778 return None;
20779 }
20780
20781 let nanos = match frac_str {
20782 None => 0,
20783 Some(frac) => {
20784 if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
20785 return None;
20786 }
20787 let truncated = &frac[..frac.len().min(9)];
20788 let padded = format!("{truncated:0<9}");
20789 padded.parse::<u64>().ok()?
20790 }
20791 };
20792
20793 Some((hour, minute, second, nanos))
20794 }
20795
20796 #[inline(never)]
20797 fn candidate(s: &str) -> ParsedTime {
20798 Timestamp::parse_time(s)
20799 }
20800
20801 fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
20802 let started = Instant::now();
20803 for input in black_box(inputs) {
20804 black_box(parser(black_box(*input)));
20805 }
20806 started.elapsed().as_nanos()
20807 }
20808
20809 fn percentile(samples: &[u128], percent: usize) -> u128 {
20810 let mut sorted = samples.to_vec();
20811 sorted.sort_unstable();
20812 let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
20813 sorted[rank]
20814 }
20815
20816 let invalid = [
20817 "",
20818 "24:00:00.1",
20819 "12:60:00.1",
20820 "12:00:60.1",
20821 "12:00:00.",
20822 "12:00:00.abc",
20823 "12:00:00.-1",
20824 "12:00:00.123",
20825 "12:00:00.123456789x",
20826 "12:00:00.1.2",
20827 "12:00:00:01.1",
20828 ];
20829 for input in VALID.iter().chain(invalid.iter()) {
20830 assert_eq!(candidate(input), former(input), "input={input:?}");
20831 }
20832
20833 let inputs = (0..CALLS)
20834 .map(|index| VALID[index % VALID.len()])
20835 .collect::<Vec<_>>();
20836 for _ in 0..2 {
20837 black_box(elapsed(&inputs, former));
20838 black_box(elapsed(&inputs, candidate));
20839 }
20840
20841 let mut former_ns = Vec::with_capacity(SAMPLES);
20842 let mut candidate_ns = Vec::with_capacity(SAMPLES);
20843 for sample in 0..SAMPLES {
20844 if sample.is_multiple_of(2) {
20845 former_ns.push(elapsed(&inputs, former));
20846 candidate_ns.push(elapsed(&inputs, candidate));
20847 } else {
20848 candidate_ns.push(elapsed(&inputs, candidate));
20849 former_ns.push(elapsed(&inputs, former));
20850 }
20851 }
20852
20853 let former_p50 = percentile(&former_ns, 50);
20854 let former_p95 = percentile(&former_ns, 95);
20855 let former_p99 = percentile(&former_ns, 99);
20856 let candidate_p50 = percentile(&candidate_ns, 50);
20857 let candidate_p95 = percentile(&candidate_ns, 95);
20858 let candidate_p99 = percentile(&candidate_ns, 99);
20859 println!(
20860 "TIMESTAMP_FRACTION_PARSE calls={CALLS} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup_p50={:.6} former_p95_ns={former_p95} candidate_p95_ns={candidate_p95} speedup_p95={:.6} former_p99_ns={former_p99} candidate_p99_ns={candidate_p99} speedup_p99={:.6} former_samples={former_ns:?} candidate_samples={candidate_ns:?}",
20861 former_p50 as f64 / candidate_p50 as f64,
20862 former_p95 as f64 / candidate_p95 as f64,
20863 former_p99 as f64 / candidate_p99 as f64,
20864 );
20865 }
20866
20867 #[test]
20868 fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
20869 fn next(seed: &mut u64) -> u64 {
20870 *seed = seed
20871 .wrapping_mul(3935559000370003845)
20872 .wrapping_add(2691343689449507681);
20873 *seed
20874 }
20875
20876 fn leap(year: i64) -> bool {
20877 (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
20878 }
20879
20880 fn month_len(year: i64, month: u32) -> u32 {
20881 match month {
20882 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
20883 4 | 6 | 9 | 11 => 30,
20884 2 if leap(year) => 29,
20885 2 => 28,
20886 _ => 0,
20887 }
20888 }
20889
20890 struct Components {
20891 year: i64,
20892 month: u32,
20893 day: u32,
20894 hour: u32,
20895 minute: u32,
20896 second: u32,
20897 nanos: u64,
20898 }
20899
20900 fn assert_components(case: usize, text: &str, expected: Components) {
20901 let ts = Timestamp::parse(text).expect("seeded valid timestamp");
20902 let Components {
20903 year,
20904 month,
20905 day,
20906 hour,
20907 minute,
20908 second,
20909 nanos,
20910 } = expected;
20911 assert_eq!(ts.year(), Some(year), "case {case}: year");
20912 assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
20913 assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
20914 assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
20915 assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
20916 assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
20917 assert_eq!(
20918 ts.microsecond(),
20919 Some((nanos / 1000) as i64),
20920 "case {case}: microsecond"
20921 );
20922 assert_eq!(
20923 ts.nanosecond(),
20924 Some((nanos % 1000) as i64),
20925 "case {case}: nanosecond"
20926 );
20927 }
20928
20929 assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
20930 assert!(
20931 Timestamp::parse("nAt")
20932 .expect("mixed-case NaT parses")
20933 .is_nat()
20934 );
20935 assert!(Timestamp::parse("1900-02-29").is_err());
20936 assert!(Timestamp::parse("2001-04-31").is_err());
20937 assert!(Timestamp::parse("2024-00-15").is_err());
20938
20939 assert_components(
20940 usize::MAX,
20941 "2000-02-29",
20942 Components {
20943 year: 2000,
20944 month: 2,
20945 day: 29,
20946 hour: 0,
20947 minute: 0,
20948 second: 0,
20949 nanos: 0,
20950 },
20951 );
20952 assert_components(
20953 usize::MAX - 1,
20954 "2024-02-29T23:59:59.000000001",
20955 Components {
20956 year: 2024,
20957 month: 2,
20958 day: 29,
20959 hour: 23,
20960 minute: 59,
20961 second: 59,
20962 nanos: 1,
20963 },
20964 );
20965
20966 let mut seed = 0x15e0_1d50_1f0a_cade_u64;
20967 for case in 0..260 {
20968 let year = 1900 + (next(&mut seed) % 201) as i64;
20969 let month = 1 + (next(&mut seed) % 12) as u32;
20970 let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
20971 let hour = (next(&mut seed) % 24) as u32;
20972 let minute = (next(&mut seed) % 60) as u32;
20973 let second = (next(&mut seed) % 60) as u32;
20974 let nanos = next(&mut seed) % 1_000_000_000;
20975
20976 match case % 4 {
20977 0 => {
20978 let text = format!("{year:04}-{month:02}-{day:02}");
20979 assert_components(
20980 case,
20981 &text,
20982 Components {
20983 year,
20984 month,
20985 day,
20986 hour: 0,
20987 minute: 0,
20988 second: 0,
20989 nanos: 0,
20990 },
20991 );
20992 }
20993 1 => {
20994 let text =
20995 format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
20996 assert_components(
20997 case,
20998 &text,
20999 Components {
21000 year,
21001 month,
21002 day,
21003 hour,
21004 minute,
21005 second,
21006 nanos: 0,
21007 },
21008 );
21009 }
21010 2 => {
21011 let text =
21012 format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
21013 assert_components(
21014 case,
21015 &text,
21016 Components {
21017 year,
21018 month,
21019 day,
21020 hour,
21021 minute,
21022 second,
21023 nanos: 0,
21024 },
21025 );
21026 }
21027 _ => {
21028 let text = format!(
21029 "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
21030 );
21031 assert_components(
21032 case,
21033 &text,
21034 Components {
21035 year,
21036 month,
21037 day,
21038 hour,
21039 minute,
21040 second,
21041 nanos,
21042 },
21043 );
21044 }
21045 }
21046 }
21047 }
21048
21049 #[test]
21050 fn period_parse_annual() {
21051 let p = Period::parse("2024").unwrap();
21052 assert_eq!(p.freq(), PeriodFreq::Annual);
21053 assert_eq!(p.ordinal(), 2024 - 1970);
21054 }
21055
21056 #[test]
21057 fn period_parse_quarterly() {
21058 let p = Period::parse("2024Q1").unwrap();
21059 assert_eq!(p.freq(), PeriodFreq::Quarterly);
21060 assert_eq!(p.ordinal(), (2024 - 1970) * 4);
21061
21062 let p2 = Period::parse("2024q3").unwrap();
21063 assert_eq!(p2.freq(), PeriodFreq::Quarterly);
21064 assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
21065 }
21066
21067 #[test]
21068 fn period_parse_monthly() {
21069 let p = Period::parse("2024-01").unwrap();
21070 assert_eq!(p.freq(), PeriodFreq::Monthly);
21071 assert_eq!(p.ordinal(), (2024 - 1970) * 12);
21072
21073 let p2 = Period::parse("2024-12").unwrap();
21074 assert_eq!(p2.freq(), PeriodFreq::Monthly);
21075 assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
21076 }
21077
21078 #[test]
21079 fn period_parse_nat() {
21080 let p = Period::parse("NaT").unwrap();
21081 assert_eq!(p.ordinal(), i64::MIN);
21082 }
21083
21084 #[test]
21085 fn period_parse_invalid() {
21086 assert!(Period::parse("not a period").is_err());
21087 assert!(Period::parse("2024Q5").is_err()); assert!(Period::parse("2024-13").is_err()); }
21090
21091 #[test]
21092 fn interval_parse_basic() {
21093 let i = Interval::parse("[0, 1]").unwrap();
21094 assert_eq!(i.left, 0.0);
21095 assert_eq!(i.right, 1.0);
21096 assert_eq!(i.closed, IntervalClosed::Both);
21097
21098 let i2 = Interval::parse("(0, 1)").unwrap();
21099 assert_eq!(i2.left, 0.0);
21100 assert_eq!(i2.right, 1.0);
21101 assert_eq!(i2.closed, IntervalClosed::Neither);
21102
21103 let i3 = Interval::parse("[0, 1)").unwrap();
21104 assert_eq!(i3.closed, IntervalClosed::Left);
21105
21106 let i4 = Interval::parse("(0, 1]").unwrap();
21107 assert_eq!(i4.closed, IntervalClosed::Right);
21108 }
21109
21110 #[test]
21111 fn interval_parse_floats() {
21112 let i = Interval::parse("[-1.5, 2.5)").unwrap();
21113 assert_eq!(i.left, -1.5);
21114 assert_eq!(i.right, 2.5);
21115 assert_eq!(i.closed, IntervalClosed::Left);
21116 }
21117
21118 #[test]
21119 fn interval_parse_invalid() {
21120 assert!(Interval::parse("invalid").is_err());
21121 assert!(Interval::parse("[0]").is_err());
21122 assert!(Interval::parse("0, 1").is_err()); }
21124
21125 fn interval_parse_error_profile(s: &str) -> super::TypeError {
21126 super::TypeError::ValueNotParseable {
21127 value: s.to_string(),
21128 target: "Interval".to_string(),
21129 }
21130 }
21131
21132 #[inline(never)]
21133 fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
21134 let s = std::hint::black_box(s).trim();
21135 if s.len() < 5 {
21136 return Err(interval_parse_error_profile(s));
21137 }
21138
21139 let first_char = s.chars().next().unwrap();
21140 let last_char = s.chars().last().unwrap();
21141 let left_closed = match first_char {
21142 '[' => true,
21143 '(' => false,
21144 _ => return Err(interval_parse_error_profile(s)),
21145 };
21146 let right_closed = match last_char {
21147 ']' => true,
21148 ')' => false,
21149 _ => return Err(interval_parse_error_profile(s)),
21150 };
21151 let closed = match (left_closed, right_closed) {
21152 (true, true) => IntervalClosed::Both,
21153 (true, false) => IntervalClosed::Left,
21154 (false, true) => IntervalClosed::Right,
21155 (false, false) => IntervalClosed::Neither,
21156 };
21157
21158 let inner = &s[1..s.len() - 1];
21159 let parts: Vec<&str> = inner.split(',').collect();
21160 if parts.len() != 2 {
21161 return Err(interval_parse_error_profile(s));
21162 }
21163 let left = parts[0]
21164 .trim()
21165 .parse()
21166 .map_err(|_| interval_parse_error_profile(s))?;
21167 let right = parts[1]
21168 .trim()
21169 .parse()
21170 .map_err(|_| interval_parse_error_profile(s))?;
21171 Ok(Interval::new(left, right, closed))
21172 }
21173
21174 #[inline(never)]
21175 fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
21176 Interval::parse(std::hint::black_box(s))
21177 }
21178
21179 fn assert_interval_parse_profile_parity(s: &str) {
21180 match (
21181 interval_parse_former_profile(s),
21182 interval_parse_split_once_profile(s),
21183 ) {
21184 (Ok(former), Ok(candidate)) => {
21185 assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
21186 assert_eq!(
21187 former.right.to_bits(),
21188 candidate.right.to_bits(),
21189 "right: {s}"
21190 );
21191 assert_eq!(former.closed, candidate.closed, "closed: {s}");
21192 }
21193 (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
21194 (former, candidate) => assert_eq!(
21195 former.is_ok(),
21196 candidate.is_ok(),
21197 "parse result mismatch for {s}: {former:?} != {candidate:?}"
21198 ),
21199 }
21200 }
21201
21202 #[inline(never)]
21203 fn measure_interval_parser_profile(
21204 parser: fn(&str) -> Result<Interval, super::TypeError>,
21205 inputs: &[&str],
21206 rounds: usize,
21207 ) -> u128 {
21208 use std::{hint::black_box, time::Instant};
21209
21210 let started = Instant::now();
21211 let mut checksum = 0_u64;
21212 for _ in 0..rounds {
21213 for input in inputs {
21214 let parsed = parser(black_box(input)).expect("profile input must parse");
21215 let closed = match parsed.closed {
21216 IntervalClosed::Left => 1_u64,
21217 IntervalClosed::Right => 2,
21218 IntervalClosed::Both => 3,
21219 IntervalClosed::Neither => 4,
21220 };
21221 checksum = checksum
21222 .wrapping_add(parsed.left.to_bits().rotate_left(7))
21223 .wrapping_add(parsed.right.to_bits().rotate_right(11))
21224 .wrapping_add(closed);
21225 black_box(parsed);
21226 }
21227 }
21228 black_box(checksum);
21229 started.elapsed().as_nanos()
21230 }
21231
21232 #[test]
21233 #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
21234 fn profile_interval_parse_endpoint_split_ab_81jjv() {
21235 const VALID: [&str; 8] = [
21236 "[0, 1]",
21237 "(-0.0, 0.0]",
21238 " [ -1.5e3 , 2.75E-4 ) ",
21239 "(NaN, -0]",
21240 "[-inf, inf)",
21241 "[9.25, -7.5]",
21242 "(4.9406564584124654e-324, 1.7976931348623157e308)",
21243 "[-42, 17.125)",
21244 ];
21245 const INVALID: [&str; 12] = [
21246 "invalid",
21247 "[0]",
21248 "0, 1",
21249 "[0 1]",
21250 "[0, 1, 2]",
21251 "[0, 1,]",
21252 "[0,,1]",
21253 "[, 1]",
21254 "[0, ]",
21255 "{0, 1}",
21256 "[0, 1}",
21257 " ⟦0, 1⟧ ",
21258 ];
21259 const ROUNDS: usize = 16_384;
21260 const SAMPLES: usize = 10;
21261
21262 for input in VALID.iter().chain(INVALID.iter()) {
21263 assert_interval_parse_profile_parity(input);
21264 }
21265 for _ in 0..2 {
21266 measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
21267 measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
21268 }
21269
21270 let mut former_ns = Vec::with_capacity(SAMPLES);
21271 let mut candidate_ns = Vec::with_capacity(SAMPLES);
21272 for sample in 0..SAMPLES {
21273 if sample % 2 == 0 {
21274 former_ns.push(measure_interval_parser_profile(
21275 interval_parse_former_profile,
21276 &VALID,
21277 ROUNDS,
21278 ));
21279 candidate_ns.push(measure_interval_parser_profile(
21280 interval_parse_split_once_profile,
21281 &VALID,
21282 ROUNDS,
21283 ));
21284 } else {
21285 candidate_ns.push(measure_interval_parser_profile(
21286 interval_parse_split_once_profile,
21287 &VALID,
21288 ROUNDS,
21289 ));
21290 former_ns.push(measure_interval_parser_profile(
21291 interval_parse_former_profile,
21292 &VALID,
21293 ROUNDS,
21294 ));
21295 }
21296 }
21297 former_ns.sort_unstable();
21298 candidate_ns.sort_unstable();
21299 let former_p50 = former_ns[SAMPLES / 2];
21300 let candidate_p50 = candidate_ns[SAMPLES / 2];
21301 let former_p95 = former_ns[SAMPLES - 1];
21302 let candidate_p95 = candidate_ns[SAMPLES - 1];
21303 println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
21304 println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
21305 println!(
21306 "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
21307 former_p50 as f64 / candidate_p50 as f64
21308 );
21309 println!(
21310 "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
21311 former_p95 as f64 / candidate_p95 as f64
21312 );
21313 }
21314}
21315
21316#[cfg(test)]
21322mod float64_nullable_qkqfb {
21323 use super::{DType, NullKind, Scalar, cast_scalar, common_dtype};
21324
21325 #[test]
21336 fn the_two_float_flavours_have_different_missing_markers_qkqfb() {
21337 assert_eq!(
21338 Scalar::missing_for_dtype(DType::Float64Nullable),
21339 Scalar::Null(NullKind::Null),
21340 "the extension lane stores pd.NA"
21341 );
21342 assert_eq!(
21343 Scalar::missing_for_dtype(DType::Float64),
21344 Scalar::Null(NullKind::NaN),
21345 "the numpy lane stores a real NaN"
21346 );
21347 assert_ne!(
21350 Scalar::missing_for_dtype(DType::Float64Nullable),
21351 Scalar::missing_for_dtype(DType::Float64),
21352 );
21353 }
21354
21355 #[test]
21359 fn spelling_is_pandas_spelling_qkqfb() {
21360 assert_eq!(DType::Float64Nullable.name(), "Float64");
21361 assert_eq!(DType::Float64.name(), "float64");
21362 assert_ne!(DType::Float64Nullable.name(), DType::Float64.name());
21363 }
21364
21365 #[test]
21372 fn serde_round_trips_and_does_not_collide_with_numpy_float64_qkqfb() {
21373 let ext = serde_json::to_string(&DType::Float64Nullable).expect("serialize");
21374 let numpy = serde_json::to_string(&DType::Float64).expect("serialize");
21375 assert_eq!(ext, "\"Float64\"");
21376 assert_eq!(numpy, "\"float64\"");
21377 assert_ne!(ext, numpy);
21378
21379 assert_eq!(
21380 serde_json::from_str::<DType>(&ext).expect("deserialize"),
21381 DType::Float64Nullable
21382 );
21383 assert_eq!(
21384 serde_json::from_str::<DType>(&numpy).expect("deserialize"),
21385 DType::Float64
21386 );
21387 }
21388
21389 #[test]
21392 fn predicates_place_it_in_the_right_families_qkqfb() {
21393 assert!(DType::Float64Nullable.is_floating());
21394 assert!(DType::Float64Nullable.is_numeric());
21395 assert!(DType::Float64Nullable.is_any_real_numeric());
21396 assert!(DType::Float64Nullable.is_nullable());
21397 assert!(DType::Float64Nullable.is_extension());
21398 assert!(!DType::Float64Nullable.is_integer());
21401 assert!(!DType::Float64Nullable.is_signed_integer());
21402 assert!(!DType::Float64Nullable.is_bool());
21403 assert_eq!(DType::Float64Nullable.kind(), 'f');
21406 assert_eq!(DType::Float64Nullable.kind(), DType::Float64.kind());
21407 assert_eq!(DType::Float64Nullable.itemsize(), 8);
21408 }
21409
21410 #[test]
21413 fn nullable_pairing_is_an_involution_qkqfb() {
21414 assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
21415 assert_eq!(DType::Float64Nullable.to_non_nullable(), DType::Float64);
21416 assert_eq!(DType::Float64Nullable.to_nullable(), DType::Float64Nullable);
21418 assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
21419 assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
21421 assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
21422 }
21423
21424 #[test]
21434 fn the_nullable_float_absorbs_every_numeric_flavour_qkqfb() {
21435 for other in [
21436 DType::Float64,
21437 DType::Int64,
21438 DType::Int64Nullable,
21439 DType::Bool,
21440 DType::BoolNullable,
21441 DType::Float64Nullable,
21442 ] {
21443 assert_eq!(
21444 common_dtype(DType::Float64Nullable, other.clone()),
21445 Ok(DType::Float64Nullable),
21446 "Float64Nullable + {other:?}"
21447 );
21448 assert_eq!(
21452 common_dtype(other.clone(), DType::Float64Nullable),
21453 Ok(DType::Float64Nullable),
21454 "{other:?} + Float64Nullable"
21455 );
21456 }
21457 assert_eq!(
21459 common_dtype(DType::Null, DType::Float64Nullable),
21460 Ok(DType::Float64Nullable)
21461 );
21462 }
21463
21464 #[test]
21473 fn casts_preserve_values_and_convert_only_the_marker_qkqfb() {
21474 let present = Scalar::Float64(1.5);
21475 assert_eq!(
21476 cast_scalar(&present, DType::Float64Nullable),
21477 Ok(Scalar::Float64(1.5))
21478 );
21479 assert_eq!(
21480 cast_scalar(&Scalar::Float64(1.5), DType::Float64),
21481 Ok(Scalar::Float64(1.5))
21482 );
21483 assert_eq!(
21485 cast_scalar(&Scalar::Int64(1), DType::Float64Nullable),
21486 Ok(Scalar::Float64(1.0))
21487 );
21488 assert_eq!(
21489 cast_scalar(&Scalar::Bool(true), DType::Float64Nullable),
21490 Ok(Scalar::Float64(1.0))
21491 );
21492
21493 assert_eq!(
21496 cast_scalar(&Scalar::Null(NullKind::NaN), DType::Float64Nullable),
21497 Ok(Scalar::Null(NullKind::Null)),
21498 "numpy NaN entering an extension lane becomes pd.NA"
21499 );
21500 assert_eq!(
21501 cast_scalar(&Scalar::Null(NullKind::Null), DType::Float64),
21502 Ok(Scalar::Null(NullKind::NaN)),
21503 "pd.NA entering a numpy lane becomes NaN"
21504 );
21505 }
21506
21507 #[test]
21517 fn int64nullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
21518 assert_eq!(
21519 common_dtype(DType::Int64Nullable, DType::Float64),
21520 Ok(DType::Float64Nullable)
21521 );
21522 assert_eq!(
21523 common_dtype(DType::Float64, DType::Int64Nullable),
21524 Ok(DType::Float64Nullable)
21525 );
21526 }
21527
21528 #[test]
21536 fn boolnullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
21537 assert_eq!(
21538 common_dtype(DType::BoolNullable, DType::Float64),
21539 Ok(DType::Float64Nullable)
21540 );
21541 assert_eq!(
21542 common_dtype(DType::Bool, DType::Float64),
21543 Ok(DType::Float64),
21544 "numpy bool + numpy float stays entirely on the numpy side"
21545 );
21546 }
21547
21548 #[test]
21559 fn the_nullable_float_flip_is_associative_on_its_witness_triple_qkqfb() {
21560 let (bn, i64n, f64d) = (DType::BoolNullable, DType::Int64, DType::Float64);
21561
21562 let left = common_dtype(
21563 common_dtype(bn.clone(), i64n.clone()).unwrap(),
21564 f64d.clone(),
21565 )
21566 .unwrap();
21567 let right = common_dtype(bn, common_dtype(i64n, f64d).unwrap()).unwrap();
21568
21569 assert_eq!(left, right, "promotion order must not change the result");
21570 assert_eq!(left, DType::Float64Nullable);
21571 }
21572}
21573
21574#[cfg(test)]
21579mod sparse_dtype_pandas_name_3gxc6 {
21580 use super::{DType, Scalar, SparseDType};
21581
21582 fn name(value_dtype: DType, fill: Scalar) -> String {
21583 SparseDType::new(value_dtype, fill)
21584 .expect("sparse descriptor")
21585 .pandas_name()
21586 }
21587
21588 #[test]
21591 fn int64_fill_zero_is_the_fixture_row() {
21592 assert_eq!(name(DType::Int64, Scalar::Int64(0)), "Sparse[int64, 0]");
21593 }
21594
21595 #[test]
21598 fn the_fill_value_is_actually_rendered() {
21599 assert_eq!(name(DType::Int64, Scalar::Int64(7)), "Sparse[int64, 7]");
21600 assert_ne!(
21601 name(DType::Int64, Scalar::Int64(0)),
21602 name(DType::Int64, Scalar::Int64(7)),
21603 "two different fills must not collapse to one name"
21604 );
21605 }
21606
21607 #[test]
21609 fn float64_nan_fill_is_lowercase_nan() {
21610 assert_eq!(
21611 name(DType::Float64, Scalar::Float64(f64::NAN)),
21612 "Sparse[float64, nan]"
21613 );
21614 }
21615
21616 #[test]
21619 fn float64_zero_fill_keeps_its_trailing_point_zero() {
21620 assert_eq!(
21621 name(DType::Float64, Scalar::Float64(0.0)),
21622 "Sparse[float64, 0.0]"
21623 );
21624 assert_ne!(
21625 name(DType::Float64, Scalar::Float64(0.0)),
21626 name(DType::Int64, Scalar::Int64(0)),
21627 "float64 and int64 zero fills are different dtypes"
21628 );
21629 }
21630
21631 #[test]
21633 fn bool_fill_uses_python_capitalisation() {
21634 assert_eq!(
21635 name(DType::Bool, Scalar::Bool(false)),
21636 "Sparse[bool, False]"
21637 );
21638 assert_eq!(name(DType::Bool, Scalar::Bool(true)), "Sparse[bool, True]");
21639 }
21640
21641 #[test]
21644 fn utf8_subtype_renders_as_object() {
21645 let rendered = name(DType::Utf8, Scalar::Null(crate::NullKind::NaN));
21646 assert!(
21647 rendered.starts_with("Sparse[object, "),
21648 "expected an object subtype, got {rendered}"
21649 );
21650 }
21651
21652 #[test]
21655 fn no_constructible_descriptor_renders_the_bare_name() {
21656 for (dtype, fill) in [
21657 (DType::Int64, Scalar::Int64(0)),
21658 (DType::Float64, Scalar::Float64(1.5)),
21659 (DType::Bool, Scalar::Bool(true)),
21660 (DType::Utf8, Scalar::Utf8("x".to_owned())),
21661 ] {
21662 let rendered = name(dtype.clone(), fill);
21663 assert_ne!(rendered, "Sparse", "bare name regressed for {dtype:?}");
21664 assert!(
21665 rendered.starts_with("Sparse[") && rendered.ends_with(']'),
21666 "malformed sparse name {rendered}"
21667 );
21668 }
21669 }
21670
21671 #[test]
21672 fn test_dtype_from_str_and_display() {
21673 use std::str::FromStr;
21674
21675 use crate::DType;
21676
21677 assert_eq!(DType::from_str("int64").unwrap(), DType::Int64);
21678 assert_eq!(DType::from_str("Int64").unwrap(), DType::Int64Nullable);
21679 assert_eq!(DType::from_str("float64").unwrap(), DType::Float64);
21680 assert_eq!(DType::from_str("Float64").unwrap(), DType::Float64Nullable);
21681 assert_eq!(DType::from_str("bool").unwrap(), DType::Bool);
21682 assert_eq!(DType::from_str("boolean").unwrap(), DType::BoolNullable);
21683 assert_eq!(DType::from_str("string").unwrap(), DType::Utf8);
21684 assert_eq!(DType::from_str("category").unwrap(), DType::Categorical);
21685 assert_eq!(
21686 DType::from_str("timedelta64[ns]").unwrap(),
21687 DType::Timedelta64
21688 );
21689 assert_eq!(
21690 DType::from_str("datetime64[ns]").unwrap(),
21691 DType::Datetime64 { tz: None }
21692 );
21693 assert_eq!(
21694 DType::from_str("datetime64[ns, UTC]").unwrap(),
21695 DType::Datetime64 {
21696 tz: Some("UTC".to_string())
21697 }
21698 );
21699 assert_eq!(DType::from_str("period").unwrap(), DType::Period);
21700 assert_eq!(DType::from_str("interval").unwrap(), DType::Interval);
21701 assert_eq!(DType::from_str("sparse").unwrap(), DType::Sparse);
21702
21703 assert_eq!(format!("{}", DType::Int64), "int64");
21704 assert_eq!(
21705 format!(
21706 "{}",
21707 DType::Datetime64 {
21708 tz: Some("UTC".to_string())
21709 }
21710 ),
21711 "datetime64[ns, UTC]"
21712 );
21713 }
21714
21715 #[test]
21716 fn test_api_types_inspection_and_infer_dtype() {
21717 use crate::{
21718 DType, Scalar,
21719 api::types::{
21720 infer_dtype, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype,
21721 is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_int64_dtype,
21722 is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_object_dtype,
21723 is_period_dtype, is_scalar, is_signed_integer_dtype, is_sparse, is_string_dtype,
21724 is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype,
21725 },
21726 };
21727
21728 assert!(is_numeric_dtype(&DType::Int64));
21729 assert!(is_numeric_dtype(&DType::Float64));
21730 assert!(!is_numeric_dtype(&DType::Utf8));
21731 assert!(!is_numeric_dtype(&DType::Bool));
21732
21733 assert!(is_integer_dtype(&DType::Int64));
21734 assert!(is_integer_dtype(&DType::Int64Nullable));
21735 assert!(!is_integer_dtype(&DType::Float64));
21736
21737 assert!(is_int64_dtype(&DType::Int64));
21738 assert!(is_int64_dtype(&DType::Int64Nullable));
21739 assert!(!is_int64_dtype(&DType::Float64));
21740
21741 assert!(is_object_dtype(&DType::Utf8));
21742 assert!(!is_object_dtype(&DType::Int64));
21743
21744 assert!(is_dtype_equal(&DType::Int64, &DType::Int64));
21745 assert!(is_dtype_equal(&"int64", &DType::Int64));
21746 assert!(!is_dtype_equal(&DType::Int64, &DType::Float64));
21747
21748 assert!(is_signed_integer_dtype(&DType::Int64));
21749 assert!(!is_unsigned_integer_dtype(&DType::Int64));
21750
21751 assert!(is_float_dtype(&DType::Float64));
21752 assert!(is_bool_dtype(&DType::Bool));
21753 assert!(is_string_dtype(&DType::Utf8));
21754 assert!(is_datetime64_any_dtype(&DType::Datetime64 { tz: None }));
21755 assert!(is_timedelta64_dtype(&DType::Timedelta64));
21756 assert!(is_categorical_dtype(&DType::Categorical));
21757 assert!(is_period_dtype(&DType::Period));
21758 assert!(is_interval_dtype(&DType::Interval));
21759 assert!(is_sparse(&DType::Sparse));
21760 assert!(is_extension_array_dtype(&DType::Categorical));
21761 assert!(is_scalar(&Scalar::Int64(42)));
21762
21763 assert_eq!(pandas_dtype("float64").unwrap(), DType::Float64);
21764 assert!(pandas_dtype("invalid_dtype_xyz").is_err());
21765
21766 let ints = vec![Scalar::Int64(1), Scalar::Int64(2)];
21767 assert_eq!(infer_dtype(&ints, true), "integer");
21768
21769 let floats = vec![Scalar::Float64(1.0), Scalar::Float64(2.5)];
21770 assert_eq!(infer_dtype(&floats, true), "floating");
21771
21772 let bools = vec![Scalar::Bool(true), Scalar::Bool(false)];
21773 assert_eq!(infer_dtype(&bools, true), "boolean");
21774
21775 let strings = vec![Scalar::Utf8("a".to_string()), Scalar::Utf8("b".to_string())];
21776 assert_eq!(infer_dtype(&strings, true), "string");
21777
21778 let mixed = vec![Scalar::Int64(1), Scalar::Utf8("a".to_string())];
21779 assert_eq!(infer_dtype(&mixed, true), "mixed");
21780
21781 assert_eq!(infer_dtype(&[], true), "empty");
21782 }
21783
21784 #[test]
21785 fn test_na_nat_sentinels_and_eng_float_format() {
21786 use super::{
21787 NA, NAT, NaT, eng_float_format, get_eng_float_format, reset_eng_float_format,
21788 set_eng_float_format,
21789 };
21790
21791 assert!(NA.is_null());
21793 assert!(NAT.is_null());
21794 assert_eq!(NAT, NaT);
21795 assert_eq!(format!("{NA}"), "None");
21796 assert_eq!(format!("{NAT}"), "NaT");
21797
21798 assert_eq!(eng_float_format(1000.0, Some(3), false), "1.000E+03");
21800 assert_eq!(eng_float_format(0.005, Some(3), false), "5.000E-03");
21801 assert_eq!(eng_float_format(1234567.0, Some(3), false), "1.235E+06");
21802 assert_eq!(eng_float_format(-9876.54, Some(3), false), "-9.877E+03");
21803 assert_eq!(eng_float_format(0.0, Some(3), false), "0.000E+00");
21804
21805 assert_eq!(eng_float_format(1000.0, Some(3), true), "1.000k");
21807 assert_eq!(eng_float_format(0.005, Some(3), true), "5.000m");
21808 assert_eq!(eng_float_format(1234567.0, Some(3), true), "1.235M");
21809 assert_eq!(eng_float_format(-9876.54, Some(3), true), "-9.877k");
21810 assert_eq!(eng_float_format(0.0, Some(3), true), "0.000");
21811 assert_eq!(eng_float_format(1.5, Some(3), true), "1.500");
21812
21813 assert_eq!(eng_float_format(f64::NAN, Some(3), true), "NaN");
21815 assert_eq!(eng_float_format(f64::INFINITY, Some(3), true), "inf");
21816 assert_eq!(eng_float_format(f64::NEG_INFINITY, Some(3), true), "-inf");
21817
21818 reset_eng_float_format();
21820 assert_eq!(get_eng_float_format(), None);
21821 set_eng_float_format(4, true);
21822 assert_eq!(get_eng_float_format(), Some((4, true)));
21823 reset_eng_float_format();
21824 assert_eq!(get_eng_float_format(), None);
21825 }
21826
21827 #[test]
21828 fn test_options_system() {
21829 use super::{
21830 OptionError, OptionValue, describe_option, get_option, option_context, reset_option,
21831 set_option,
21832 };
21833
21834 reset_option(None).unwrap();
21836
21837 let max_rows = get_option("display.max_rows").unwrap();
21839 assert_eq!(max_rows.as_int(), Some(60));
21840 assert_eq!(max_rows, OptionValue::Int(60));
21841 assert!(!max_rows.is_none());
21842
21843 let min_rows = get_option("min_rows").unwrap();
21845 assert_eq!(min_rows.as_int(), Some(10));
21846
21847 set_option("display.max_rows", 100).unwrap();
21849 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
21850
21851 set_option("mode.sim_interactive", true).unwrap();
21852 assert_eq!(
21853 get_option("mode.sim_interactive").unwrap().as_bool(),
21854 Some(true)
21855 );
21856
21857 set_option("mode.chained_assignment", "raise").unwrap();
21858 assert_eq!(
21859 get_option("mode.chained_assignment").unwrap().as_str(),
21860 Some("raise")
21861 );
21862
21863 assert!(matches!(
21865 get_option("nonexistent.option"),
21866 Err(OptionError::NotFound { .. })
21867 ));
21868 assert!(matches!(
21869 get_option("display"),
21870 Err(OptionError::Ambiguous { .. })
21871 ));
21872
21873 let desc = describe_option(Some("max_rows")).unwrap();
21875 assert!(desc.contains("display.max_rows : [currently: 100]"));
21876
21877 let desc_all = describe_option(None).unwrap();
21878 assert!(desc_all.contains("display.width"));
21879 assert!(desc_all.contains("compute.use_bottleneck"));
21880
21881 {
21883 let _guard = option_context(&[
21884 ("display.max_rows", OptionValue::Int(999)),
21885 ("display.precision", OptionValue::Int(2)),
21886 ])
21887 .unwrap();
21888
21889 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(999));
21890 assert_eq!(get_option("display.precision").unwrap().as_int(), Some(2));
21891 }
21892 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
21894 assert_eq!(get_option("display.precision").unwrap().as_int(), Some(6));
21895
21896 reset_option(Some("display.max_rows")).unwrap();
21898 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(60));
21899
21900 reset_option(Some("all")).unwrap();
21901 assert_eq!(
21902 get_option("mode.chained_assignment").unwrap().as_str(),
21903 Some("warn")
21904 );
21905
21906 assert_eq!(
21908 get_option("mode.copy_on_write").unwrap().as_bool(),
21909 Some(false)
21910 );
21911 assert_eq!(
21912 get_option("mode.data_manager").unwrap().as_str(),
21913 Some("block")
21914 );
21915 assert_eq!(
21916 get_option("display.large_repr").unwrap().as_str(),
21917 Some("truncate")
21918 );
21919 assert_eq!(
21920 get_option("display.max_info_columns").unwrap().as_int(),
21921 Some(100)
21922 );
21923 assert_eq!(
21924 get_option("display.memory_usage").unwrap().as_bool(),
21925 Some(true)
21926 );
21927 assert_eq!(
21928 get_option("display.colheader_justify").unwrap().as_str(),
21929 Some("right")
21930 );
21931 assert!(get_option("display.chop_threshold").unwrap().is_none());
21932 assert_eq!(
21933 get_option("io.parquet.engine").unwrap().as_str(),
21934 Some("auto")
21935 );
21936 assert_eq!(
21937 get_option("plotting.backend").unwrap().as_str(),
21938 Some("matplotlib")
21939 );
21940 assert_eq!(
21941 get_option("plotting.matplotlib.register_converters")
21942 .unwrap()
21943 .as_bool(),
21944 Some(true)
21945 );
21946
21947 set_option("display.chop_threshold", ()).unwrap();
21949 assert!(get_option("display.chop_threshold").unwrap().is_none());
21950 }
21951
21952 #[test]
21953 fn test_scalar_typed_accessors() {
21954 use super::{Interval, IntervalClosed, Period, PeriodFreq, Scalar};
21955
21956 let s_i64 = Scalar::Int64(42);
21957 assert_eq!(s_i64.as_i64(), Some(42));
21958 assert_eq!(s_i64.as_int(), Some(42));
21959 assert_eq!(s_i64.as_f64(), None);
21960 assert_eq!(s_i64.as_float(), None);
21961 assert_eq!(s_i64.as_bool(), None);
21962 assert_eq!(s_i64.as_str(), None);
21963
21964 let s_f64 = Scalar::Float64(2.75);
21965 assert_eq!(s_f64.as_f64(), Some(2.75));
21966 assert_eq!(s_f64.as_float(), Some(2.75));
21967 assert_eq!(s_f64.as_i64(), None);
21968 assert_eq!(s_f64.as_int(), None);
21969
21970 let s_bool = Scalar::Bool(true);
21971 assert_eq!(s_bool.as_bool(), Some(true));
21972 assert_eq!(s_bool.as_int(), None);
21973
21974 let s_str = Scalar::Utf8("pandas".to_string());
21975 assert_eq!(s_str.as_str(), Some("pandas"));
21976 assert_eq!(s_str.as_bool(), None);
21977
21978 let s_dt = Scalar::Datetime64(1_000_000_000);
21979 assert_eq!(s_dt.as_datetime_nanos(), Some(1_000_000_000));
21980 assert_eq!(s_dt.as_str(), None);
21981
21982 let s_td = Scalar::Timedelta64(500_000);
21983 assert_eq!(s_td.as_timedelta_nanos(), Some(500_000));
21984 assert_eq!(s_td.as_int(), None);
21985
21986 let s_per = Scalar::Period(Period::new(2024, PeriodFreq::Daily));
21987 assert_eq!(s_per.as_period_ordinal(), Some(2024));
21988
21989 let s_iv = Scalar::Interval(Interval::new(0.0, 10.0, IntervalClosed::Both));
21990 assert_eq!(
21991 s_iv.as_interval(),
21992 Some(Interval::new(0.0, 10.0, IntervalClosed::Both))
21993 );
21994 }
21995
21996 #[test]
21997 fn test_api_submodules_and_types_inspectors() {
21998 use super::{
21999 DType, Scalar,
22000 api::{extensions, indexers, types},
22001 };
22002
22003 assert!(types::is_number(&Scalar::Int64(42)));
22005 assert!(types::is_number(&Scalar::Float64(42.5)));
22006 assert!(types::is_number(&Scalar::Bool(true)));
22007 assert!(!types::is_number(&Scalar::Utf8("pandas".into())));
22008
22009 assert!(types::is_bool(&Scalar::Bool(false)));
22010 assert!(!types::is_bool(&Scalar::Int64(0)));
22011
22012 assert!(types::is_integer(&Scalar::Int64(10)));
22013 assert!(!types::is_integer(&Scalar::Float64(10.0)));
22014
22015 assert!(types::is_float(&Scalar::Float64(10.0)));
22016 assert!(!types::is_float(&Scalar::Int64(10)));
22017
22018 assert!(types::is_float64_dtype(&DType::Float64));
22020 assert!(types::is_float64_dtype(&DType::Float64Nullable));
22021 assert!(!types::is_float64_dtype(&DType::Int64));
22022 assert!(!types::is_int32_dtype(&DType::Int64));
22023
22024 extensions::register_dataframe_accessor("geo");
22026 extensions::register_series_accessor("geo");
22027 extensions::register_index_accessor("geo");
22028
22029 let base = indexers::BaseIndexer::new(5, 1);
22031 assert_eq!(base.window_size, 5);
22032 assert_eq!(base.step, 1);
22033
22034 let fwd = indexers::FixedForwardWindowIndexer::new(3);
22035 assert_eq!(fwd.window_size, 3);
22036
22037 let var = indexers::VariableOffsetWindowIndexer::new(100);
22038 assert_eq!(var.index_offset, 100);
22039 }
22040
22041 #[test]
22042 fn test_extension_dtypes_and_parameterized_parsing() {
22043 use super::{
22044 AsDType, CategoricalDtype, DType, IntervalClosed, IntervalDtype, PeriodDtype, Scalar,
22045 SparseDType, api::types, pandas_dtype,
22046 };
22047
22048 let cat_default = CategoricalDtype::default();
22050 assert_eq!(cat_default.name(), "category");
22051 assert_eq!(cat_default.kind(), "O");
22052 assert!(!cat_default.ordered());
22053 assert_eq!(cat_default.categories(), None);
22054 assert_eq!(cat_default.as_dtype(), DType::Categorical);
22055 assert!(types::is_categorical_dtype(&cat_default));
22056 assert_eq!(
22057 cat_default.to_string(),
22058 "CategoricalDtype(categories=None, ordered=False)"
22059 );
22060
22061 let cat_custom =
22062 CategoricalDtype::new(Some(vec!["low".to_string(), "high".to_string()]), true);
22063 assert!(cat_custom.ordered());
22064 assert_eq!(
22065 cat_custom.categories(),
22066 Some(&["low".to_string(), "high".to_string()][..])
22067 );
22068 assert!(cat_custom.to_string().contains("ordered=True"));
22069
22070 let per_default = PeriodDtype::default();
22072 assert_eq!(per_default.freq(), "D");
22073 assert_eq!(per_default.name(), "period[D]");
22074 assert_eq!(per_default.kind(), "O");
22075 assert_eq!(per_default.as_dtype(), DType::Period);
22076 assert!(types::is_period_dtype(&per_default));
22077 assert_eq!(per_default.to_string(), "period[D]");
22078
22079 let per_custom = PeriodDtype::new("M");
22080 assert_eq!(per_custom.freq(), "M");
22081 assert_eq!(per_custom.to_string(), "period[M]");
22082
22083 let int_default = IntervalDtype::default();
22085 assert_eq!(*int_default.subtype(), DType::Float64);
22086 assert_eq!(int_default.closed(), Some(IntervalClosed::Right));
22087 assert_eq!(int_default.name(), "interval");
22088 assert_eq!(int_default.kind(), "O");
22089 assert_eq!(int_default.as_dtype(), DType::Interval);
22090 assert!(types::is_interval_dtype(&int_default));
22091 assert_eq!(int_default.to_string(), "interval[float64, right]");
22092
22093 let int_custom = IntervalDtype::new(DType::Int64, Some(IntervalClosed::Both));
22094 assert_eq!(*int_custom.subtype(), DType::Int64);
22095 assert_eq!(int_custom.closed(), Some(IntervalClosed::Both));
22096 assert_eq!(int_custom.to_string(), "interval[int64, both]");
22097
22098 let sp = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).unwrap();
22100 assert_eq!(sp.as_dtype(), DType::Sparse);
22101 assert!(types::is_sparse(&sp));
22102
22103 assert_eq!(pandas_dtype("period[D]").unwrap(), DType::Period);
22105 assert_eq!(pandas_dtype("Period[M]").unwrap(), DType::Period);
22106 assert_eq!(pandas_dtype("interval[float64]").unwrap(), DType::Interval);
22107 assert_eq!(pandas_dtype("Interval[int64]").unwrap(), DType::Interval);
22108 assert_eq!(pandas_dtype("sparse[float64]").unwrap(), DType::Sparse);
22109 assert_eq!(pandas_dtype("Sparse[int64, 0]").unwrap(), DType::Sparse);
22110 }
22111}
22112
22113#[cfg(test)]
22116mod numeric_width_fvsao23 {
22117 use super::{DType, NumericWidth, NumpyNumeric, numpy_pairwise_sum};
22118
22119 #[test]
22120 fn float32_sum_is_numpys_pairwise_sum_bit_for_bit() {
22121 let cases: [(usize, u32); 5] = [
22125 (5, 1_083_829_126),
22126 (64, 1_136_679_190),
22127 (129, 1_145_981_108),
22128 (1000, 1_170_926_592),
22129 (4097, 1_188_011_795),
22130 ];
22131 for (n, bits) in cases {
22132 #[allow(clippy::cast_precision_loss)] let values: Vec<f32> = (0..n)
22134 .map(|k| ((k * 37) % 1000) as f32 * 0.013_f32)
22135 .collect();
22136 assert_eq!(numpy_pairwise_sum(&values).to_bits(), bits, "n={n}");
22137 if n < 100 {
22138 #[allow(clippy::cast_possible_truncation)]
22139 let rounded_once = values.iter().map(|&v| f64::from(v)).sum::<f64>() as f32;
22140 assert_ne!(rounded_once.to_bits(), bits, "n={n}");
22141 }
22142 }
22143 assert_eq!(numpy_pairwise_sum::<f32>(&[]), 0.0);
22144 }
22145
22146 #[test]
22147 fn names_parse_and_round_trip() {
22148 for width in NumericWidth::ALL {
22149 for nullable in [false, true] {
22150 assert_eq!(
22151 NumericWidth::parse(width.name(nullable)),
22152 Some((width, nullable))
22153 );
22154 }
22155 }
22156 for (name, expected) in [
22157 ("<i4", (NumericWidth::Int32, false)),
22158 ("f4", (NumericWidth::Float32, false)),
22159 ("UInt8Dtype", (NumericWidth::UInt8, true)),
22160 ] {
22161 assert_eq!(NumericWidth::parse(name), Some(expected), "{name}");
22162 }
22163 for name in ["int64", "Int64", "float64", "i8", "f8", "int", "float"] {
22165 assert_eq!(NumericWidth::parse(name), None, "{name}");
22166 }
22167 }
22168
22169 #[test]
22170 fn wrapping_is_numpys_modular_cast_not_saturation() {
22171 assert_eq!(NumericWidth::Int8.wrap_int(300), Some(44));
22173 assert_eq!(NumericWidth::UInt8.wrap_int(-5), Some(251));
22175 assert_eq!(NumericWidth::UInt16.wrap_int(-5), Some(65531));
22176 assert_eq!(NumericWidth::UInt32.wrap_int(-5), Some(4_294_967_291));
22177 assert_eq!(NumericWidth::Int8.wrap_int(200), Some(-56));
22179 assert_eq!(
22180 NumericWidth::Int32.wrap_int(i64::from(i32::MAX) + 1),
22181 Some(i64::from(i32::MIN))
22182 );
22183 let product = 50_000_i64.wrapping_pow(5);
22185 assert_eq!(
22186 NumericWidth::Int32.wrap_int(product),
22187 Some(i64::from(50_000_i32.wrapping_pow(5)))
22188 );
22189 assert_eq!(NumericWidth::UInt64.wrap_int(-1), None);
22191 assert_eq!(NumericWidth::UInt64.wrap_int(7), Some(7));
22192 assert_eq!(NumericWidth::Float32.wrap_int(1), None);
22193 assert!(NumericWidth::Int8.holds_int(-128) && !NumericWidth::Int8.holds_int(128));
22194 }
22195
22196 #[test]
22197 fn float32_rounding_is_to_nearest_not_truncation() {
22198 assert_eq!(NumericWidth::round_f32(0.1), 0.100_000_001_490_116_12);
22200 let sum =
22203 NumericWidth::round_f32(NumericWidth::round_f32(0.1) + NumericWidth::round_f32(0.2));
22204 assert_eq!(sum, 0.300_000_011_920_928_96);
22205 assert_eq!(NumericWidth::round_f32(1.0 + 2f64.powi(-24)), 1.0);
22208 let above_tie = 1.0 + 3.0 * 2f64.powi(-25);
22209 assert_eq!(NumericWidth::round_f32(above_tie), 1.0 + 2f64.powi(-23));
22210 assert!(NumericWidth::round_f32(f64::NAN).is_nan());
22211 assert_eq!(NumericWidth::round_f32(1e300), f64::INFINITY);
22212 }
22213
22214 #[test]
22215 fn result_type_matches_numpy_promotion() {
22216 use NumpyNumeric::{Bool, Float, Int, UInt};
22217 let cases = [
22218 (Int(32), Int(64), Int(64)), (Int(8), UInt(8), Int(16)), (Int(16), UInt(8), Int(16)),
22221 (Int(8), UInt(16), Int(32)),
22222 (Int(32), UInt(32), Int(64)),
22223 (Int(64), UInt(64), Float(64)), (UInt(8), UInt(32), UInt(32)),
22225 (Float(32), Int(8), Float(32)), (Float(32), UInt(16), Float(32)),
22227 (Float(32), Int(32), Float(64)), (Float(32), Float(64), Float(64)),
22229 (Bool, Int(8), Int(8)),
22230 (Bool, Float(32), Float(32)),
22231 ];
22232 for (a, b, expected) in cases {
22233 assert_eq!(a.result_type(b), expected, "{a:?} {b:?}");
22234 assert_eq!(b.result_type(a), expected, "{b:?} {a:?}");
22235 }
22236 assert_eq!(Int(32).with_python_int(), Int(32));
22239 assert_eq!(Int(32).with_python_float(), Float(64));
22240 assert_eq!(Float(32).with_python_float(), Float(32));
22241 assert_eq!(Bool.with_python_int(), Int(64));
22242 }
22243
22244 #[test]
22245 fn columns_map_to_numpy_dtypes() {
22246 let cases = [
22247 (DType::Int64, None, Some(NumpyNumeric::Int(64))),
22248 (
22249 DType::Int64Nullable,
22250 Some(NumericWidth::UInt8),
22251 Some(NumpyNumeric::UInt(8)),
22252 ),
22253 (
22254 DType::Float64,
22255 Some(NumericWidth::Float32),
22256 Some(NumpyNumeric::Float(32)),
22257 ),
22258 (DType::Float64, Some(NumericWidth::Int8), None),
22260 (DType::Utf8, None, None),
22261 ];
22262 for (dtype, width, expected) in cases {
22263 assert_eq!(NumpyNumeric::of(&dtype, width), expected, "{dtype:?}");
22264 }
22265 for width in NumericWidth::ALL {
22266 assert_eq!(NumpyNumeric::of_width(width).width(), Some(width));
22267 assert!(width.fits_storage(&width.storage(false)));
22268 assert!(width.fits_storage(&width.storage(true)));
22269 }
22270 assert_eq!(NumpyNumeric::Int(64).width(), None);
22271 }
22272
22273 #[test]
22274 fn downcast_and_category_code_widths() {
22275 let int32_max_plus_one = i64::from(i32::MAX) + 1;
22278 let signed = [
22279 ((1, 2), Some(NumericWidth::Int8)),
22280 ((1, 300), Some(NumericWidth::Int16)),
22281 ((0, int32_max_plus_one), None),
22282 ];
22283 for ((low, high), expected) in signed {
22284 assert_eq!(NumericWidth::smallest_signed(low, high), expected);
22285 }
22286 let unsigned = [((1, 300), Some(NumericWidth::UInt16)), ((-1, 3), None)];
22287 for ((low, high), expected) in unsigned {
22288 assert_eq!(NumericWidth::smallest_unsigned(low, high), expected);
22289 }
22290 for (categories, expected) in [
22292 (2, NumericWidth::Int8),
22293 (126, NumericWidth::Int8),
22294 (127, NumericWidth::Int16),
22295 (200, NumericWidth::Int16),
22296 ] {
22297 assert_eq!(NumericWidth::for_category_codes(categories), Some(expected));
22298 }
22299 assert_eq!(NumericWidth::itemsize(NumericWidth::Int8), 1);
22300 assert_eq!(NumericWidth::Float32.itemsize(), 4);
22301 }
22302}
22303
22304#[cfg(test)]
22309mod pandas_reductions_9iim6 {
22310 use super::{MissingLayout, PandasReductions, ReductionValues};
22311
22312 #[allow(clippy::cast_precision_loss)] fn floats(n: usize) -> (Vec<f64>, Vec<u64>) {
22316 let mut present = vec![0_u64; n.div_ceil(64)];
22317 let values = (0..n)
22318 .map(|k| {
22319 if k % 11 != 3 {
22320 present[k / 64] |= 1 << (k % 64);
22321 }
22322 let base = ((k * 7919 + 13) % 100_003) as f64 / 7.0 - 7000.0;
22323 if k % 5 == 0 { base * 1e6 } else { base }
22324 })
22325 .collect();
22326 (values, present)
22327 }
22328
22329 fn ints(n: usize) -> Vec<i64> {
22331 (0..n)
22332 .map(|k| i64::try_from((k * 7919 + 13) % 100_003).unwrap() * 3_000_000_007)
22333 .collect()
22334 }
22335
22336 fn assert_bits(got: &[f64], expected: &[u64], case: &str) {
22337 let got: Vec<u64> = got.iter().map(|value| value.to_bits()).collect();
22338 assert_eq!(got, expected, "{case}");
22339 }
22340
22341 #[test]
22342 fn numpy_float64_with_nan_matches_pandas_bits() {
22343 let cases: [(usize, [u64; 7]); 7] = [
22345 (
22346 7,
22347 [
22348 0xc1ff_1185_2dcb_6db6,
22349 0xc1d4_b658_c932_4924,
22350 0x43db_301d_4a8d_87a3,
22351 0x41e4_db58_e2f1_458e,
22352 0x41d1_078f_09d3_9c5c,
22353 0xc002_1f47_ceae_1b43,
22354 0x4014_c8bc_93df_56e6,
22355 ],
22356 ),
22357 (
22358 8,
22359 [
22360 0xc1ff_1184_f43d_b6da,
22361 0xc1d1_c0de_426c_687d,
22362 0x43d7_9d3c_ecd2_da2b,
22363 0x41e3_7012_7d6c_71a5,
22364 0x41cd_631d_3379_9929,
22365 0xc003_b196_82f9_28dc,
22366 0x4018_9de2_eba9_5ecc,
22367 ],
22368 ),
22369 (
22370 127,
22371 [
22372 0x4200_324e_3389_2490,
22373 0x4192_0704_ad1e_360d,
22374 0x43c9_4a6b_3390_577d,
22375 0x41dc_72bf_d6fa_9808,
22376 0x41a5_38f5_8417_ae1e,
22377 0x3fd0_b6bf_045c_e4d5,
22378 0x4017_1585_bf13_21c4,
22379 ],
22380 ),
22381 (
22382 128,
22383 [
22384 0x4200_324d_7236_db6e,
22385 0x4191_df3a_f99d_a2ae,
22386 0x43c9_1234_ffb7_4a93,
22387 0x41dc_5310_c97c_292c,
22388 0x41a5_09f4_cfcf_9206,
22389 0x3fd0_d9df_0d68_00b0,
22390 0x4017_61b6_5653_ae82,
22391 ],
22392 ),
22393 (
22394 129,
22395 [
22396 0x4200_324c_d43e_db71,
22397 0x4191_b81f_8a1d_61da,
22398 0x43c8_daf6_85d3_386f,
22399 0x41dc_33ca_af49_8c24,
22400 0x41a4_dbc2_8609_a567,
22401 0x3fd0_fcc5_39d9_6901,
22402 0x4017_ade4_7855_7c25,
22403 ],
22404 ),
22405 (
22406 1000,
22407 [
22408 0x421a_d4f6_8061_248e,
22409 0x417e_39f9_3e1a_a248,
22410 0x43c7_9481_cba1_263b,
22411 0x41db_7825_28c0_37cc,
22412 0x418d_27ba_a0ea_2f9a,
22413 0x3fc8_e53a_e277_3d7f,
22414 0x4018_3c97_3603_dfd0,
22415 ],
22416 ),
22417 (
22418 100_000,
22419 [
22420 0x4283_088c_316e_46dc,
22421 0x417b_7135_0c27_1185,
22422 0x43c7_a0de_3b8e_ea34,
22423 0x41db_7f57_6673_8d6b,
22424 0x4157_58cc_33fd_4ae6,
22425 0x3fc7_f1cf_b14a_14c8,
22426 0x4018_06b5_f26a_c384,
22427 ],
22428 ),
22429 ];
22430 let all = |r: &PandasReductions<'_>| {
22431 [
22432 r.sum(),
22433 r.mean(),
22434 r.var(1),
22435 r.std(1),
22436 r.sem(1),
22437 r.skew(),
22438 r.kurt(),
22439 ]
22440 };
22441 for (n, expected) in cases {
22442 let (values, present) = floats(n);
22443 let r = PandasReductions::new(
22444 ReductionValues::Float(&values),
22445 Some(&present),
22446 MissingLayout::Numpy,
22447 );
22448 assert_bits(&all(&r), &expected, &format!("float64 n={n}"));
22449 let with_nan: Vec<f64> = values
22452 .iter()
22453 .enumerate()
22454 .map(|(k, &value)| if k % 11 == 3 { f64::NAN } else { value })
22455 .collect();
22456 let r = PandasReductions::numpy_nan_missing(ReductionValues::Float(&with_nan));
22457 assert_bits(&all(&r), &expected, &format!("float64 NaN n={n}"));
22458 let (head, tail) = with_nan.split_at(n / 3);
22459 let chunks = [head, tail];
22460 let r = PandasReductions::numpy_nan_missing(ReductionValues::FloatChunks(&chunks));
22461 assert_bits(&all(&r), &expected, &format!("float64 NaN chunks n={n}"));
22462 }
22463 let (values, present) = floats(100_000);
22465 let left_fold: f64 = values
22466 .iter()
22467 .enumerate()
22468 .filter(|&(k, _)| present[k / 64] >> (k % 64) & 1 == 1)
22469 .map(|(_, value)| value)
22470 .sum();
22471 assert_ne!(left_fold.to_bits(), 0x4283_088c_316e_46dc);
22472 }
22473
22474 #[test]
22475 fn numpy_int64_mean_sums_through_the_cast_buffer() {
22476 let cases: [(usize, [u64; 5]); 3] = [
22478 (
22479 129,
22480 [
22481 0x42e0_dda2_9987_3f9e,
22482 0x45b9_0e2a_887d_aeda,
22483 0x429c_34a1_c273_372f,
22484 0x3f95_9e9d_c69e_ec88,
22485 0xbff3_844b_ba13_eac1,
22486 ],
22487 ),
22488 (
22489 8193,
22490 [
22491 0x42e1_0d5b_e407_5aa7,
22492 0x45b8_3bf5_04f5_f2fc,
22493 0x426b_d893_c5c9_85b1,
22494 0x3f42_7452_ff15_86c7,
22495 0xbff3_318c_611b_b59c,
22496 ],
22497 ),
22498 (
22499 20_000,
22500 [
22501 0x42e1_0d17_ebf8_272d,
22502 0x45b8_3c24_c921_82b6,
22503 0x4261_d2a2_f139_68e2,
22504 0x3f31_a21c_d4bb_ff52,
22505 0xbff3_328c_4edc_26ee,
22506 ],
22507 ),
22508 ];
22509 for (n, expected) in cases {
22510 let values = ints(n);
22511 let r =
22512 PandasReductions::new(ReductionValues::Int(&values), None, MissingLayout::Numpy);
22513 let got = [r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()];
22514 assert_bits(&got, &expected, &format!("int64 n={n}"));
22515 let (head, tail) = values.split_at(n / 3);
22517 let (middle, rest) = tail.split_at(1);
22518 let chunks = [head, middle, &[][..], rest];
22519 let chunked = PandasReductions::new(
22520 ReductionValues::IntChunks(&chunks),
22521 None,
22522 MissingLayout::Numpy,
22523 );
22524 let got = [
22525 chunked.mean(),
22526 chunked.var(1),
22527 chunked.sem(1),
22528 chunked.skew(),
22529 chunked.kurt(),
22530 ];
22531 assert_bits(&got, &expected, &format!("int64 chunks n={n}"));
22532 }
22533 }
22534
22535 #[test]
22536 fn masked_columns_add_runs_of_present_values() {
22537 let cases: [(usize, [u64; 4]); 3] = [
22541 (
22542 129,
22543 [
22544 0x4200_324c_d43e_db6e,
22545 0x4191_b81f_8a1d_61d6,
22546 0x43c8_daf6_85d3_3872,
22547 0x41a4_dbc2_8609_a567,
22548 ],
22549 ),
22550 (
22551 1000,
22552 [
22553 0x421a_d4f6_8061_2492,
22554 0x417e_39f9_3e1a_a24c,
22555 0x43c7_9481_cba1_263a,
22556 0x418d_27ba_a0ea_2f9a,
22557 ],
22558 ),
22559 (
22560 100_000,
22561 [
22562 0x4283_088c_316e_46de,
22563 0x417b_7135_0c27_1188,
22564 0x43c7_a0de_3b8e_ea37,
22565 0x4157_58cc_33fd_4ae6,
22566 ],
22567 ),
22568 ];
22569 for (n, expected) in cases {
22570 let (values, present) = floats(n);
22571 let r = PandasReductions::new(
22572 ReductionValues::Float(&values),
22573 Some(&present),
22574 MissingLayout::Masked,
22575 );
22576 assert_bits(
22577 &[r.sum(), r.mean(), r.var(1), r.sem(1)],
22578 &expected,
22579 &format!("Float64 n={n}"),
22580 );
22581 let (head, tail) = values.split_at(n / 2 + 1);
22582 let chunks = [head, tail];
22583 let chunked = PandasReductions::new(
22584 ReductionValues::FloatChunks(&chunks),
22585 Some(&present),
22586 MissingLayout::Masked,
22587 );
22588 let got = [
22589 chunked.sum(),
22590 chunked.mean(),
22591 chunked.var(1),
22592 chunked.sem(1),
22593 ];
22594 assert_bits(&got, &expected, &format!("Float64 chunks n={n}"));
22595 }
22596 for (n, expected) in [
22599 (8193, [0x42e1_0f35_29c2_807b_u64, 0x45b8_39ed_8746_bdcc]),
22600 (20_000, [0x42e1_0cf2_cc56_752a, 0x45b8_3c63_72fc_fad5]),
22601 ] {
22602 let values = ints(n);
22603 let mut present = vec![0_u64; n.div_ceil(64)];
22604 for k in (0..n).filter(|k| k % 997 != 5) {
22605 present[k / 64] |= 1 << (k % 64);
22606 }
22607 let r = PandasReductions::new(
22608 ReductionValues::Int(&values),
22609 Some(&present),
22610 MissingLayout::Masked,
22611 );
22612 assert_bits(&[r.mean(), r.var(1)], &expected, &format!("Int64 n={n}"));
22613 }
22614 }
22615
22616 #[test]
22617 fn edge_cases_match_pandas() {
22618 let reductions = |values: &[f64], present: Option<&[u64]>| {
22619 let r = PandasReductions::new(
22620 ReductionValues::Float(values),
22621 present,
22622 MissingLayout::Numpy,
22623 );
22624 [r.sum(), r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()]
22625 };
22626 let constant = reductions(&[1.5; 10], None);
22629 assert_eq!(constant, [15.0, 1.5, 0.0, 0.0, 0.0, 0.0]);
22630 assert!(reductions(&[2.0; 3], None)[5].is_nan());
22631 assert!(reductions(&[1.0, 2.0], None)[4].is_nan());
22633 assert_eq!(
22634 reductions(&[1.0, 2.0, 4.0], None)[4],
22635 0.935_219_529_582_823_7
22636 );
22637 let empty = reductions(&[], None);
22639 assert_eq!(empty[0], 0.0);
22640 assert!(empty[1..].iter().all(|value| value.is_nan()));
22641 let all_missing = reductions(&[3.0; 5], Some(&[0]));
22642 assert_eq!(all_missing[0], 0.0);
22643 assert!(all_missing[1].is_nan());
22644 assert_eq!(
22646 reductions(&[-0.0; 10], None)[0].to_bits(),
22647 0.0_f64.to_bits()
22648 );
22649 let inf = reductions(&[1.0, f64::INFINITY, 2.0, 5.0], None);
22651 assert_eq!(inf[0], f64::INFINITY);
22652 assert!(inf[2..].iter().all(|value| value.is_nan()));
22653 }
22654}
22655
22656#[cfg(test)]
22660mod pandas_decimal_py3c0 {
22661 use super::{PandasDecimal, pandas_decimal_to_f64, pandas_int_to_f64};
22662
22663 fn bits(token: &str) -> u64 {
22664 match pandas_decimal_to_f64(token.as_bytes()) {
22665 PandasDecimal::Value(value) => value.to_bits(),
22666 other => panic!("{token:?}: {other:?}"),
22667 }
22668 }
22669
22670 #[test]
22671 fn tokens_convert_to_pandas_bits() {
22672 let cases = [
22673 ("9.890295358649789", 0x4023_c7d4_cb12_5ce4),
22674 ("0.8690736625851781286570704999", 0x3feb_cf73_91d3_c8f1),
22675 ("0.000000068288360759838675650889", 0x3e72_54bd_8bcd_610b),
22676 ("-0.0080749473608410608782560", 0xbf80_8999_16a7_63f3),
22677 ("99999999999999999", 0x4376_3457_85d8_a001),
22678 ("1234567890123456789012345", 0x44f0_56e0_f36a_6444),
22679 ("00000000000000000.5", 0x0000_0000_0000_0000),
22681 ("-00000000000000000.5", 0x8000_0000_0000_0000),
22682 ("1.5E+10", 0x420b_f08e_b000_0000),
22683 ("-.5e-3", 0xbf40_624d_d2f1_a9fc),
22684 ("5.", 0x4014_0000_0000_0000),
22685 ("1e-320", 0x0000_0000_0000_07e8),
22686 ("2.5e-310", 0x0000_2e05_5c9a_3f6c),
22687 ("-1e-400", 0x8000_0000_0000_0000),
22688 ("-1e-700", 0x0000_0000_0000_0000),
22690 ("1e-4294967296", 0x3ff0_0000_0000_0000),
22692 ("1.7976931348623157e308", 0x7fef_ffff_ffff_ffff),
22693 ("0.001e310", 0x7fac_7b1f_3cac_7433),
22694 ];
22695 for (token, expected) in cases {
22696 assert_eq!(bits(token), expected, "{token:?}");
22697 }
22698 let correctly_rounded: f64 = "9.890295358649789".parse().unwrap();
22700 assert_ne!(correctly_rounded.to_bits(), 0x4023_c7d4_cb12_5ce4);
22701 }
22702
22703 #[test]
22704 fn what_pandas_does_not_read_as_a_float() {
22705 for token in [
22706 "1e309",
22707 "0e400",
22708 "1.8e308",
22709 "1e+0000000000000000001",
22710 "1e-2147483649",
22711 "1e",
22712 "1e+",
22713 "1.5d3",
22714 "0x10",
22715 "1_000.5",
22716 "1..5",
22717 ] {
22718 assert_eq!(
22719 pandas_decimal_to_f64(token.as_bytes()),
22720 PandasDecimal::Rejected,
22721 "{token:?}"
22722 );
22723 }
22724 for token in ["inf", "-Infinity", "nan", ".", "-", "e5", "+.e1", "--1", ""] {
22725 assert_eq!(
22726 pandas_decimal_to_f64(token.as_bytes()),
22727 PandasDecimal::NotDecimal,
22728 "{token:?}"
22729 );
22730 }
22731 }
22732
22733 #[test]
22734 fn an_integer_in_a_float_column_takes_the_same_conversion() {
22735 assert_eq!(pandas_int_to_f64(-42).to_bits(), (-42.0_f64).to_bits());
22736 assert_eq!(
22737 pandas_int_to_f64(99_999_999_999_999_999).to_bits(),
22738 0x4376_3457_85d8_a001
22739 );
22740 assert_eq!(
22741 pandas_int_to_f64(-99_999_999_999_999_999).to_bits(),
22742 0xc376_3457_85d8_a001
22743 );
22744 }
22745}