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
1374#[must_use]
1383pub const fn spread_float_bits(bits: u64) -> u64 {
1384 bits ^ (bits >> 32)
1385}
1386
1387fn zero_out_fperr(value: f64) -> f64 {
1389 if value.abs() < 1e-14 { 0.0 } else { value }
1390}
1391
1392#[derive(Debug, Clone, Copy, PartialEq)]
1396pub enum PandasDecimal {
1397 Value(f64),
1399 Rejected,
1403 NotDecimal,
1406}
1407
1408const PANDAS_DECIMAL_DIGITS: usize = 17;
1411
1412#[derive(Default)]
1416struct PandasSignificand {
1417 exact: u64,
1418 float: f64,
1419 rounding: bool,
1420 digits: usize,
1421}
1422
1423impl PandasSignificand {
1424 fn push(&mut self, digit: u8) {
1425 self.digits += 1;
1426 if !self.rounding {
1427 let next = self.exact * 10 + u64::from(digit);
1428 if next <= 1 << 53 {
1429 self.exact = next;
1430 return;
1431 }
1432 self.rounding = true;
1433 #[allow(clippy::cast_precision_loss)] let exact = self.exact as f64;
1435 self.float = exact;
1436 }
1437 self.float = self.float * 10.0 + f64::from(digit);
1438 }
1439
1440 #[allow(clippy::cast_precision_loss)] fn value(&self) -> f64 {
1442 if self.rounding {
1443 self.float
1444 } else {
1445 self.exact as f64
1446 }
1447 }
1448}
1449
1450static PANDAS_POW10: std::sync::LazyLock<[f64; 309]> = std::sync::LazyLock::new(|| {
1452 std::array::from_fn(|power| format!("1e{power}").parse().unwrap_or(f64::INFINITY))
1453});
1454
1455#[must_use]
1468pub fn pandas_decimal_to_f64(token: &[u8]) -> PandasDecimal {
1469 let (negative, body) = match token.first() {
1470 Some(b'-') => (true, &token[1..]),
1471 Some(b'+') => (false, &token[1..]),
1472 _ => (false, token),
1473 };
1474 let mut significand = PandasSignificand::default();
1475 let mut exponent = 0_i32;
1476 let mut pos = 0;
1477 while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1478 if significand.digits < PANDAS_DECIMAL_DIGITS {
1479 significand.push(byte - b'0');
1480 } else {
1481 exponent = exponent.wrapping_add(1);
1482 }
1483 pos += 1;
1484 }
1485 let mut seen_digit = pos > 0;
1486 if body.get(pos) == Some(&b'.') {
1487 pos += 1;
1488 while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1489 if significand.digits < PANDAS_DECIMAL_DIGITS {
1490 significand.push(byte - b'0');
1491 exponent = exponent.wrapping_sub(1);
1492 }
1493 seen_digit = true;
1494 pos += 1;
1495 }
1496 }
1497 if !seen_digit {
1498 return PandasDecimal::NotDecimal;
1499 }
1500 if let Some(b'e' | b'E') = body.get(pos) {
1501 pos += 1;
1502 let negative_exponent = match body.get(pos) {
1503 Some(b'-') => {
1504 pos += 1;
1505 true
1506 }
1507 Some(b'+') => {
1508 pos += 1;
1509 false
1510 }
1511 _ => false,
1512 };
1513 let start = pos;
1514 let mut written = 0_i32;
1515 while pos - start < PANDAS_DECIMAL_DIGITS
1516 && let Some(&byte @ b'0'..=b'9') = body.get(pos)
1517 {
1518 written = written
1519 .wrapping_mul(10)
1520 .wrapping_add(i32::from(byte - b'0'));
1521 pos += 1;
1522 }
1523 if pos == start {
1524 return PandasDecimal::Rejected;
1525 }
1526 exponent = exponent.wrapping_add(if negative_exponent {
1527 written.wrapping_neg()
1528 } else {
1529 written
1530 });
1531 }
1532 if pos != body.len() {
1533 return PandasDecimal::Rejected;
1534 }
1535 let value = significand.value();
1536 let pow10 = |power: i32| PANDAS_POW10[power.unsigned_abs() as usize];
1537 let magnitude = match exponent {
1538 309.. => return PandasDecimal::Rejected,
1539 0.. => value * pow10(exponent),
1540 -308.. => value / pow10(exponent),
1541 -616.. => value / pow10(-308 - exponent) / pow10(308),
1542 _ => return PandasDecimal::Value(0.0),
1543 };
1544 if magnitude.is_infinite() {
1545 return PandasDecimal::Rejected;
1546 }
1547 PandasDecimal::Value(if negative { -magnitude } else { magnitude })
1548}
1549
1550#[must_use]
1554#[allow(clippy::cast_precision_loss)] pub fn pandas_int_to_f64(value: i64) -> f64 {
1556 if value.unsigned_abs() <= 1 << 53 {
1557 return value as f64;
1558 }
1559 match pandas_decimal_to_f64(value.to_string().as_bytes()) {
1560 PandasDecimal::Value(parsed) => parsed,
1561 PandasDecimal::Rejected | PandasDecimal::NotDecimal => value as f64,
1563 }
1564}
1565
1566#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1569pub enum NumpyNumeric {
1570 Bool,
1571 Int(u8),
1572 UInt(u8),
1573 Float(u8),
1574}
1575
1576impl NumpyNumeric {
1577 #[must_use]
1581 pub const fn of(dtype: &DType, width: Option<NumericWidth>) -> Option<Self> {
1582 match (dtype, width) {
1583 (DType::Bool | DType::BoolNullable, None) => Some(Self::Bool),
1584 (DType::Int64 | DType::Int64Nullable, None) => Some(Self::Int(64)),
1585 (DType::Float64 | DType::Float64Nullable, None) => Some(Self::Float(64)),
1586 (DType::Int64 | DType::Int64Nullable, Some(width)) if !width.is_float() => {
1587 Some(Self::of_width(width))
1588 }
1589 (DType::Float64 | DType::Float64Nullable, Some(NumericWidth::Float32)) => {
1590 Some(Self::Float(32))
1591 }
1592 _ => None,
1593 }
1594 }
1595
1596 #[must_use]
1597 pub const fn of_width(width: NumericWidth) -> Self {
1598 match width {
1599 NumericWidth::Int8 => Self::Int(8),
1600 NumericWidth::Int16 => Self::Int(16),
1601 NumericWidth::Int32 => Self::Int(32),
1602 NumericWidth::UInt8 => Self::UInt(8),
1603 NumericWidth::UInt16 => Self::UInt(16),
1604 NumericWidth::UInt32 => Self::UInt(32),
1605 NumericWidth::UInt64 => Self::UInt(64),
1606 NumericWidth::Float32 => Self::Float(32),
1607 }
1608 }
1609
1610 #[must_use]
1613 pub const fn width(self) -> Option<NumericWidth> {
1614 match self {
1615 Self::Int(8) => Some(NumericWidth::Int8),
1616 Self::Int(16) => Some(NumericWidth::Int16),
1617 Self::Int(32) => Some(NumericWidth::Int32),
1618 Self::UInt(8) => Some(NumericWidth::UInt8),
1619 Self::UInt(16) => Some(NumericWidth::UInt16),
1620 Self::UInt(32) => Some(NumericWidth::UInt32),
1621 Self::UInt(64) => Some(NumericWidth::UInt64),
1622 Self::Float(32) => Some(NumericWidth::Float32),
1623 _ => None,
1624 }
1625 }
1626
1627 #[must_use]
1628 pub const fn is_float(self) -> bool {
1629 matches!(self, Self::Float(_))
1630 }
1631
1632 #[must_use]
1637 pub const fn result_type(self, other: Self) -> Self {
1638 const fn wider(a: u8, b: u8) -> u8 {
1639 if a > b { a } else { b }
1640 }
1641 match (self, other) {
1642 (Self::Bool, x) | (x, Self::Bool) => x,
1643 (Self::Int(a), Self::Int(b)) => Self::Int(wider(a, b)),
1644 (Self::UInt(a), Self::UInt(b)) => Self::UInt(wider(a, b)),
1645 (Self::Int(signed), Self::UInt(unsigned))
1646 | (Self::UInt(unsigned), Self::Int(signed)) => {
1647 if signed > unsigned {
1648 Self::Int(signed)
1649 } else if unsigned < 64 {
1650 Self::Int(wider(signed, unsigned * 2))
1651 } else {
1652 Self::Float(64)
1653 }
1654 }
1655 (Self::Float(a), Self::Float(b)) => Self::Float(wider(a, b)),
1656 (Self::Float(bits), Self::Int(int_bits) | Self::UInt(int_bits))
1657 | (Self::Int(int_bits) | Self::UInt(int_bits), Self::Float(bits)) => {
1658 if int_bits <= 16 {
1659 Self::Float(bits)
1660 } else {
1661 Self::Float(64)
1662 }
1663 }
1664 }
1665 }
1666
1667 #[must_use]
1671 pub const fn with_python_int(self) -> Self {
1672 match self {
1673 Self::Bool => Self::Int(64),
1674 other => other,
1675 }
1676 }
1677
1678 #[must_use]
1682 pub const fn with_python_float(self) -> Self {
1683 match self {
1684 Self::Float(bits) => Self::Float(bits),
1685 _ => Self::Float(64),
1686 }
1687 }
1688}
1689
1690pub trait AsDType {
1692 fn as_dtype(&self) -> DType;
1694}
1695
1696impl AsDType for DType {
1697 fn as_dtype(&self) -> DType {
1698 self.clone()
1699 }
1700}
1701
1702impl AsDType for &DType {
1703 fn as_dtype(&self) -> DType {
1704 (*self).clone()
1705 }
1706}
1707
1708impl AsDType for &str {
1709 fn as_dtype(&self) -> DType {
1710 self.parse::<DType>().unwrap_or(DType::Utf8)
1711 }
1712}
1713
1714impl AsDType for String {
1715 fn as_dtype(&self) -> DType {
1716 self.as_str().as_dtype()
1717 }
1718}
1719
1720pub mod api {
1721 pub mod types {
1724 use crate::{AsDType, DType, Scalar, TypeError};
1727
1728 #[must_use]
1730 pub fn is_bool_dtype(dtype: &impl AsDType) -> bool {
1731 dtype.as_dtype().is_bool()
1732 }
1733
1734 #[must_use]
1736 pub fn is_numeric_dtype(dtype: &impl AsDType) -> bool {
1737 dtype.as_dtype().is_numeric()
1738 }
1739
1740 #[must_use]
1742 pub fn is_integer_dtype(dtype: &impl AsDType) -> bool {
1743 dtype.as_dtype().is_integer()
1744 }
1745
1746 #[must_use]
1748 pub fn is_signed_integer_dtype(dtype: &impl AsDType) -> bool {
1749 dtype.as_dtype().is_signed_integer()
1750 }
1751
1752 #[must_use]
1754 pub fn is_unsigned_integer_dtype(_dtype: &impl AsDType) -> bool {
1755 false
1756 }
1757
1758 #[must_use]
1760 pub fn is_float_dtype(dtype: &impl AsDType) -> bool {
1761 dtype.as_dtype().is_floating()
1762 }
1763
1764 #[must_use]
1766 pub fn is_string_dtype(dtype: &impl AsDType) -> bool {
1767 dtype.as_dtype().is_string_dtype()
1768 }
1769
1770 #[must_use]
1772 pub fn is_datetime64_any_dtype(dtype: &impl AsDType) -> bool {
1773 dtype.as_dtype().is_datetime()
1774 }
1775
1776 #[must_use]
1778 pub fn is_datetime64_dtype(dtype: &impl AsDType) -> bool {
1779 dtype.as_dtype().is_datetime()
1780 }
1781
1782 #[must_use]
1784 pub fn is_datetime64_ns_dtype(dtype: &impl AsDType) -> bool {
1785 dtype.as_dtype().is_datetime()
1786 }
1787
1788 #[must_use]
1790 pub fn is_timedelta64_dtype(dtype: &impl AsDType) -> bool {
1791 dtype.as_dtype().is_timedelta()
1792 }
1793
1794 #[must_use]
1796 pub fn is_timedelta64_ns_dtype(dtype: &impl AsDType) -> bool {
1797 dtype.as_dtype().is_timedelta()
1798 }
1799
1800 #[must_use]
1802 pub fn is_period_dtype(dtype: &impl AsDType) -> bool {
1803 dtype.as_dtype().is_period()
1804 }
1805
1806 #[must_use]
1808 pub fn is_categorical_dtype(dtype: &impl AsDType) -> bool {
1809 dtype.as_dtype().is_categorical()
1810 }
1811
1812 #[must_use]
1814 pub fn is_interval_dtype(dtype: &impl AsDType) -> bool {
1815 dtype.as_dtype().is_interval()
1816 }
1817
1818 #[must_use]
1820 pub fn is_sparse(dtype: &impl AsDType) -> bool {
1821 dtype.as_dtype().is_sparse()
1822 }
1823
1824 #[must_use]
1826 pub fn is_extension_array_dtype(dtype: &impl AsDType) -> bool {
1827 dtype.as_dtype().is_extension()
1828 }
1829
1830 #[must_use]
1832 pub fn is_object_dtype(dtype: &impl AsDType) -> bool {
1833 dtype.as_dtype().is_object()
1834 }
1835
1836 #[must_use]
1838 pub fn is_int64_dtype(dtype: &impl AsDType) -> bool {
1839 matches!(dtype.as_dtype(), DType::Int64 | DType::Int64Nullable)
1840 }
1841
1842 #[must_use]
1844 pub fn is_dtype_equal(source: &impl AsDType, target: &impl AsDType) -> bool {
1845 source.as_dtype() == target.as_dtype()
1846 }
1847
1848 #[must_use]
1850 pub const fn is_scalar(_scalar: &Scalar) -> bool {
1851 true
1852 }
1853
1854 pub fn pandas_dtype(name: &str) -> Result<DType, TypeError> {
1860 name.parse::<DType>()
1861 }
1862
1863 #[must_use]
1865 pub fn infer_dtype(scalars: &[Scalar], skipna: bool) -> &'static str {
1866 if scalars.is_empty() {
1867 return "empty";
1868 }
1869 let mut has_int = false;
1870 let mut has_float = false;
1871 let mut has_bool = false;
1872 let mut has_str = false;
1873 let mut has_ts = false;
1874 let mut has_td = false;
1875 let mut has_period = false;
1876 let mut count = 0;
1877
1878 for s in scalars {
1879 if s.is_null() {
1880 if !skipna {
1881 return "mixed";
1882 }
1883 continue;
1884 }
1885 count += 1;
1886 match s {
1887 Scalar::Bool(_) => has_bool = true,
1888 Scalar::Int64(_) => has_int = true,
1889 Scalar::Float64(_) => has_float = true,
1890 Scalar::Utf8(_) => has_str = true,
1891 Scalar::Datetime64(_) => has_ts = true,
1892 Scalar::Timedelta64(_) => has_td = true,
1893 Scalar::Period(_) => has_period = true,
1894 _ => {}
1895 }
1896 }
1897
1898 if count == 0 {
1899 return "empty";
1900 }
1901 if has_bool && !has_int && !has_float && !has_str && !has_ts && !has_td && !has_period {
1902 return "boolean";
1903 }
1904 if has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td && !has_period {
1905 return "integer";
1906 }
1907 if (has_float || (has_int && has_float))
1908 && !has_bool
1909 && !has_str
1910 && !has_ts
1911 && !has_td
1912 && !has_period
1913 {
1914 return "floating";
1915 }
1916 if has_str && !has_int && !has_float && !has_bool && !has_ts && !has_td && !has_period {
1917 return "string";
1918 }
1919 if has_ts && !has_int && !has_float && !has_bool && !has_str && !has_td && !has_period {
1920 return "datetime64";
1921 }
1922 if has_td && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_period {
1923 return "timedelta64";
1924 }
1925 if has_period && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td {
1926 return "period";
1927 }
1928 "mixed"
1929 }
1930
1931 #[must_use]
1933 pub fn is_float64_dtype(dtype: &impl AsDType) -> bool {
1934 matches!(dtype.as_dtype(), DType::Float64 | DType::Float64Nullable)
1935 }
1936
1937 #[must_use]
1939 pub fn is_int32_dtype(_dtype: &impl AsDType) -> bool {
1940 false
1941 }
1942
1943 #[must_use]
1945 pub fn is_number(scalar: &Scalar) -> bool {
1946 scalar.is_numeric() || matches!(scalar, Scalar::Bool(_))
1947 }
1948
1949 #[must_use]
1951 pub fn is_bool(scalar: &Scalar) -> bool {
1952 matches!(scalar, Scalar::Bool(_))
1953 }
1954
1955 #[must_use]
1957 pub fn is_integer(scalar: &Scalar) -> bool {
1958 matches!(scalar, Scalar::Int64(_))
1959 }
1960
1961 #[must_use]
1963 pub fn is_float(scalar: &Scalar) -> bool {
1964 matches!(scalar, Scalar::Float64(_))
1965 }
1966 }
1967
1968 pub mod extensions {
1969 pub fn register_dataframe_accessor(_name: &str) {}
1973
1974 pub fn register_series_accessor(_name: &str) {}
1976
1977 pub fn register_index_accessor(_name: &str) {}
1979 }
1980
1981 pub mod indexers {
1982 #[derive(Debug, Clone, PartialEq, Eq, Default)]
1986 pub struct BaseIndexer {
1987 pub window_size: usize,
1988 pub step: usize,
1989 }
1990
1991 impl BaseIndexer {
1992 #[must_use]
1993 pub const fn new(window_size: usize, step: usize) -> Self {
1994 Self { window_size, step }
1995 }
1996 }
1997
1998 #[derive(Debug, Clone, PartialEq, Eq, Default)]
2000 pub struct FixedForwardWindowIndexer {
2001 pub window_size: usize,
2002 }
2003
2004 impl FixedForwardWindowIndexer {
2005 #[must_use]
2006 pub const fn new(window_size: usize) -> Self {
2007 Self { window_size }
2008 }
2009 }
2010
2011 #[derive(Debug, Clone, PartialEq, Eq, Default)]
2013 pub struct VariableOffsetWindowIndexer {
2014 pub index_offset: i64,
2015 }
2016
2017 impl VariableOffsetWindowIndexer {
2018 #[must_use]
2019 pub const fn new(index_offset: i64) -> Self {
2020 Self { index_offset }
2021 }
2022 }
2023 }
2024}
2025
2026pub use api::types::pandas_dtype;
2027
2028#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2029pub struct SparseDType {
2030 pub value_dtype: DType,
2031 pub fill_value: Scalar,
2032}
2033
2034impl SparseDType {
2035 pub fn new(value_dtype: DType, fill_value: Scalar) -> Result<Self, TypeError> {
2041 if matches!(value_dtype, DType::Null | DType::Sparse) {
2042 return Err(TypeError::InvalidSparseValueDType { dtype: value_dtype });
2043 }
2044
2045 let fill_value = if fill_value.is_missing() {
2046 Scalar::missing_for_dtype(value_dtype.clone())
2047 } else {
2048 cast_scalar_owned(fill_value, value_dtype.clone())?
2049 };
2050
2051 Ok(Self {
2052 value_dtype,
2053 fill_value,
2054 })
2055 }
2056
2057 #[must_use]
2084 pub fn pandas_name(&self) -> String {
2085 format!(
2086 "Sparse[{}, {}]",
2087 self.value_dtype.name(),
2088 scalar_to_string_for_astype(self.fill_value.clone())
2089 )
2090 }
2091}
2092
2093impl AsDType for SparseDType {
2094 fn as_dtype(&self) -> DType {
2095 DType::Sparse
2096 }
2097}
2098
2099#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
2103pub struct CategoricalDtype {
2104 pub categories: Option<Vec<String>>,
2105 pub ordered: bool,
2106}
2107
2108pub type CategoricalDType = CategoricalDtype;
2109
2110impl CategoricalDtype {
2111 #[must_use]
2113 pub const fn new(categories: Option<Vec<String>>, ordered: bool) -> Self {
2114 Self {
2115 categories,
2116 ordered,
2117 }
2118 }
2119
2120 #[must_use]
2122 pub fn categories(&self) -> Option<&[String]> {
2123 self.categories.as_deref()
2124 }
2125
2126 #[must_use]
2128 pub const fn ordered(&self) -> bool {
2129 self.ordered
2130 }
2131
2132 #[must_use]
2134 pub const fn name(&self) -> &'static str {
2135 "category"
2136 }
2137
2138 #[must_use]
2140 pub const fn kind(&self) -> &'static str {
2141 "O"
2142 }
2143}
2144
2145impl AsDType for CategoricalDtype {
2146 fn as_dtype(&self) -> DType {
2147 DType::Categorical
2148 }
2149}
2150
2151impl std::fmt::Display for CategoricalDtype {
2152 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2153 let ord_str = if self.ordered { "True" } else { "False" };
2154 match &self.categories {
2155 Some(cats) => write!(
2156 f,
2157 "CategoricalDtype(categories={cats:?}, ordered={ord_str})"
2158 ),
2159 None => write!(f, "CategoricalDtype(categories=None, ordered={ord_str})"),
2160 }
2161 }
2162}
2163
2164#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2168pub struct PeriodDtype {
2169 pub freq: String,
2170}
2171
2172pub type PeriodDType = PeriodDtype;
2173
2174impl PeriodDtype {
2175 #[must_use]
2177 pub fn new(freq: impl Into<String>) -> Self {
2178 Self { freq: freq.into() }
2179 }
2180
2181 #[must_use]
2183 pub fn freq(&self) -> &str {
2184 &self.freq
2185 }
2186
2187 #[must_use]
2189 pub fn name(&self) -> String {
2190 format!("period[{}]", self.freq)
2191 }
2192
2193 #[must_use]
2195 pub const fn kind(&self) -> &'static str {
2196 "O"
2197 }
2198}
2199
2200impl Default for PeriodDtype {
2201 fn default() -> Self {
2202 Self {
2203 freq: "D".to_string(),
2204 }
2205 }
2206}
2207
2208impl AsDType for PeriodDtype {
2209 fn as_dtype(&self) -> DType {
2210 DType::Period
2211 }
2212}
2213
2214impl std::fmt::Display for PeriodDtype {
2215 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2216 write!(f, "period[{}]", self.freq)
2217 }
2218}
2219
2220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2224pub struct IntervalDtype {
2225 pub subtype: DType,
2226 pub closed: Option<IntervalClosed>,
2227}
2228
2229pub type IntervalDType = IntervalDtype;
2230
2231impl IntervalDtype {
2232 #[must_use]
2234 pub const fn new(subtype: DType, closed: Option<IntervalClosed>) -> Self {
2235 Self { subtype, closed }
2236 }
2237
2238 #[must_use]
2240 pub const fn subtype(&self) -> &DType {
2241 &self.subtype
2242 }
2243
2244 #[must_use]
2246 pub const fn closed(&self) -> Option<IntervalClosed> {
2247 self.closed
2248 }
2249
2250 #[must_use]
2252 pub const fn name(&self) -> &'static str {
2253 "interval"
2254 }
2255
2256 #[must_use]
2258 pub const fn kind(&self) -> &'static str {
2259 "O"
2260 }
2261}
2262
2263impl Default for IntervalDtype {
2264 fn default() -> Self {
2265 Self {
2266 subtype: DType::Float64,
2267 closed: Some(IntervalClosed::Right),
2268 }
2269 }
2270}
2271
2272impl AsDType for IntervalDtype {
2273 fn as_dtype(&self) -> DType {
2274 DType::Interval
2275 }
2276}
2277
2278impl std::fmt::Display for IntervalDtype {
2279 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2280 match self.closed {
2281 Some(c) => write!(f, "interval[{}, {c}]", self.subtype.name()),
2282 None => write!(f, "interval[{}]", self.subtype.name()),
2283 }
2284 }
2285}
2286
2287#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
2288#[serde(rename_all = "snake_case")]
2289pub enum NullKind {
2290 Null,
2291 NaN,
2292 NaT,
2293}
2294
2295mod float64_json {
2303 use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
2304
2305 pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
2306 if value.is_infinite() {
2307 serializer.serialize_str(if value.is_sign_positive() {
2308 "inf"
2309 } else {
2310 "-inf"
2311 })
2312 } else {
2313 serializer.serialize_f64(*value)
2314 }
2315 }
2316
2317 #[derive(Deserialize)]
2318 #[serde(untagged)]
2319 enum Repr {
2320 Number(f64),
2321 Text(String),
2322 Null(()),
2323 }
2324
2325 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
2326 match Repr::deserialize(deserializer)? {
2327 Repr::Number(value) => Ok(value),
2328 Repr::Text(text) => match text.as_str() {
2329 "inf" => Ok(f64::INFINITY),
2330 "-inf" => Ok(f64::NEG_INFINITY),
2331 other => Err(D::Error::custom(format!(
2332 "float64 value must be a number, \"inf\" or \"-inf\", got {other:?}"
2333 ))),
2334 },
2335 Repr::Null(()) => Ok(f64::NAN),
2336 }
2337 }
2338}
2339
2340#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2341#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
2342pub enum Scalar {
2343 Null(NullKind),
2344 Bool(bool),
2345 Int64(i64),
2346 Float64(#[serde(with = "float64_json")] f64),
2347 #[serde(alias = "string", alias = "str")]
2348 Utf8(String),
2349 Timedelta64(i64),
2350 Datetime64(i64),
2353 Period(Period),
2359 Interval(Interval),
2361 Object(ObjectValue),
2365}
2366
2367#[derive(Clone)]
2371pub enum ObjectValue {
2372 List(std::sync::Arc<[Scalar]>),
2374 Bytes(std::sync::Arc<[u8]>),
2378 Host(HostValue),
2380}
2381
2382pub trait HostObject: Send + Sync {
2385 fn host_eq(&self, other: &dyn HostObject) -> bool;
2387 fn host_repr(&self) -> String;
2389 fn host_str(&self) -> String;
2391 fn host_pprint(&self) -> String {
2395 self.host_str()
2396 }
2397 fn host_hash(&self) -> Option<u64>;
2399 fn host_cmp(&self, other: &dyn HostObject) -> Option<std::cmp::Ordering>;
2403 fn host_eq_scalar(&self, _other: &Scalar) -> bool {
2406 false
2407 }
2408 fn host_type_name(&self) -> String {
2411 "object".to_owned()
2412 }
2413 fn as_any(&self) -> &dyn std::any::Any;
2415}
2416
2417static LIVE_HOST_VALUES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2419
2420static HOST_LOCK_DECLARED: std::sync::atomic::AtomicBool =
2423 std::sync::atomic::AtomicBool::new(false);
2424
2425pub fn declare_host_lock() {
2429 HOST_LOCK_DECLARED.store(true, std::sync::atomic::Ordering::Relaxed);
2430}
2431
2432#[must_use]
2440pub fn host_values_block_workers() -> bool {
2441 workers_blocked(
2442 HOST_LOCK_DECLARED.load(std::sync::atomic::Ordering::Relaxed),
2443 LIVE_HOST_VALUES.load(std::sync::atomic::Ordering::Relaxed),
2444 )
2445}
2446
2447const fn workers_blocked(host_lock_declared: bool, live_host_values: usize) -> bool {
2449 host_lock_declared && live_host_values > 0
2450}
2451
2452struct HostSlot(Box<dyn HostObject>);
2454
2455impl Drop for HostSlot {
2456 fn drop(&mut self) {
2457 LIVE_HOST_VALUES.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2458 }
2459}
2460
2461#[derive(Clone)]
2463pub struct HostValue(std::sync::Arc<HostSlot>);
2464
2465impl HostValue {
2466 #[must_use]
2467 pub fn new(object: impl HostObject + 'static) -> Self {
2468 LIVE_HOST_VALUES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2469 Self(std::sync::Arc::new(HostSlot(Box::new(object))))
2470 }
2471
2472 #[must_use]
2473 pub fn object(&self) -> &dyn HostObject {
2474 &*self.0.0
2475 }
2476}
2477
2478impl PartialEq for HostValue {
2479 fn eq(&self, other: &Self) -> bool {
2480 std::sync::Arc::ptr_eq(&self.0, &other.0) || self.object().host_eq(other.object())
2481 }
2482}
2483
2484impl std::fmt::Debug for HostValue {
2485 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2486 formatter.write_str(&self.object().host_repr())
2487 }
2488}
2489
2490impl ObjectValue {
2491 #[must_use]
2493 pub fn list(items: Vec<Scalar>) -> Self {
2494 Self::List(items.into())
2495 }
2496
2497 #[must_use]
2499 pub fn as_list(&self) -> Option<&[Scalar]> {
2500 match self {
2501 Self::List(items) => Some(items),
2502 Self::Bytes(_) | Self::Host(_) => None,
2503 }
2504 }
2505
2506 #[must_use]
2508 pub fn bytes(data: Vec<u8>) -> Self {
2509 Self::Bytes(data.into())
2510 }
2511
2512 #[must_use]
2514 pub fn as_bytes(&self) -> Option<&[u8]> {
2515 match self {
2516 Self::Bytes(data) => Some(data),
2517 Self::List(_) | Self::Host(_) => None,
2518 }
2519 }
2520
2521 #[must_use]
2523 pub fn repr(&self) -> String {
2524 match self {
2525 Self::List(items) => {
2526 let parts: Vec<String> = items.iter().map(Scalar::python_repr).collect();
2527 format!("[{}]", parts.join(", "))
2528 }
2529 Self::Bytes(data) => python_bytes_repr(data),
2530 Self::Host(value) => value.object().host_repr(),
2531 }
2532 }
2533
2534 #[must_use]
2537 pub fn pprint(&self) -> String {
2538 match self {
2539 Self::List(items) => {
2540 let parts: Vec<String> = items
2541 .iter()
2542 .map(|item| match item {
2543 Scalar::Utf8(text) => text.clone(),
2544 Scalar::Object(object) => object.pprint(),
2545 other => other.python_repr(),
2546 })
2547 .collect();
2548 format!("[{}]", parts.join(", "))
2549 }
2550 Self::Bytes(data) => python_bytes_repr(data),
2551 Self::Host(value) => value.object().host_pprint(),
2552 }
2553 }
2554
2555 #[must_use]
2558 pub fn type_name(&self) -> String {
2559 match self {
2560 Self::List(_) => "list".to_owned(),
2561 Self::Bytes(_) => "bytes".to_owned(),
2562 Self::Host(value) => value.object().host_type_name(),
2563 }
2564 }
2565
2566 #[must_use]
2570 pub fn python_eq_scalar(&self, other: &Scalar) -> bool {
2571 match self {
2572 Self::Host(value) => value.object().host_eq_scalar(other),
2573 Self::List(_) | Self::Bytes(_) => false,
2574 }
2575 }
2576
2577 #[must_use]
2581 pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2582 match (self, other) {
2583 (Self::Bytes(left), Self::Bytes(right)) => Some(left.cmp(right)),
2584 (Self::Host(left), Self::Host(right)) => {
2585 if left == right {
2586 Some(std::cmp::Ordering::Equal)
2587 } else {
2588 left.object().host_cmp(right.object())
2589 }
2590 }
2591 (Self::List(left), Self::List(right)) => {
2592 for (a, b) in left.iter().zip(right.iter()) {
2593 if a != b {
2594 let ordering = a.python_cmp(b)?;
2595 if ordering.is_ne() {
2596 return Some(ordering);
2597 }
2598 }
2599 }
2600 Some(left.len().cmp(&right.len()))
2601 }
2602 _ => None,
2603 }
2604 }
2605
2606 #[must_use]
2611 pub fn total_cmp(&self, other: &Self) -> std::cmp::Ordering {
2612 use std::cmp::Ordering;
2613 if self == other {
2614 return Ordering::Equal;
2615 }
2616 if let Some(ordering) = self.python_cmp(other).filter(|ordering| ordering.is_ne()) {
2617 return ordering;
2618 }
2619 let rank = |cell: &Self| match cell {
2620 Self::List(_) => 0_u8,
2621 Self::Bytes(_) => 1,
2622 Self::Host(_) => 2,
2623 };
2624 rank(self)
2625 .cmp(&rank(other))
2626 .then_with(|| self.repr().cmp(&other.repr()))
2627 .then_with(|| self.address().cmp(&other.address()))
2628 }
2629
2630 fn address(&self) -> usize {
2633 match self {
2634 Self::List(items) => items.as_ptr().addr(),
2635 Self::Bytes(data) => data.as_ptr().addr(),
2636 Self::Host(value) => std::sync::Arc::as_ptr(&value.0).cast::<()>().addr(),
2637 }
2638 }
2639}
2640
2641#[must_use]
2645pub fn python_bytes_repr(data: &[u8]) -> String {
2646 let quote = if data.contains(&b'\'') && !data.contains(&b'"') {
2647 b'"'
2648 } else {
2649 b'\''
2650 };
2651 let mut out = String::with_capacity(data.len() + 3);
2652 out.push('b');
2653 out.push(char::from(quote));
2654 for &byte in data {
2655 match byte {
2656 b'\\' => out.push_str("\\\\"),
2657 b'\t' => out.push_str("\\t"),
2658 b'\n' => out.push_str("\\n"),
2659 b'\r' => out.push_str("\\r"),
2660 _ if byte == quote => {
2661 out.push('\\');
2662 out.push(char::from(byte));
2663 }
2664 0x20..=0x7e => out.push(char::from(byte)),
2665 _ => out.push_str(&format!("\\x{byte:02x}")),
2666 }
2667 }
2668 out.push(char::from(quote));
2669 out
2670}
2671
2672impl PartialOrd for ObjectValue {
2673 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2674 Some(self.cmp(other))
2675 }
2676}
2677
2678impl Ord for ObjectValue {
2680 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2681 self.total_cmp(other)
2682 }
2683}
2684
2685impl PartialEq for ObjectValue {
2686 fn eq(&self, other: &Self) -> bool {
2687 match (self, other) {
2688 (Self::List(left), Self::List(right)) => left == right,
2689 (Self::Bytes(left), Self::Bytes(right)) => left == right,
2690 (Self::Host(left), Self::Host(right)) => left == right,
2691 _ => false,
2692 }
2693 }
2694}
2695
2696impl Eq for ObjectValue {}
2700
2701impl std::hash::Hash for ObjectValue {
2702 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2703 match self {
2704 Self::List(items) => {
2705 0_u8.hash(state);
2706 for item in items.iter() {
2707 item.python_repr().hash(state);
2708 }
2709 }
2710 Self::Bytes(data) => {
2711 2_u8.hash(state);
2712 data.hash(state);
2713 }
2714 Self::Host(value) => {
2715 1_u8.hash(state);
2716 match value.object().host_hash() {
2717 Some(hash) => hash.hash(state),
2718 None => value.object().host_repr().hash(state),
2719 }
2720 }
2721 }
2722 }
2723}
2724
2725impl std::fmt::Debug for ObjectValue {
2726 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2727 formatter.write_str(&self.repr())
2728 }
2729}
2730
2731impl std::fmt::Display for ObjectValue {
2735 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2736 match self {
2737 Self::List(_) | Self::Bytes(_) => formatter.write_str(&self.repr()),
2738 Self::Host(value) => formatter.write_str(&value.object().host_str()),
2739 }
2740 }
2741}
2742
2743impl Serialize for ObjectValue {
2746 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2747 match self {
2748 Self::List(items) => items.as_ref().serialize(serializer),
2749 Self::Bytes(data) => SerializedObject::Bytes {
2750 bytes: data.to_vec(),
2751 }
2752 .serialize(serializer),
2753 Self::Host(_) => Err(serde::ser::Error::custom(
2754 "a host-language object cell cannot be serialized",
2755 )),
2756 }
2757 }
2758}
2759
2760#[derive(Serialize, Deserialize)]
2763#[serde(untagged)]
2764enum SerializedObject {
2765 List(Vec<Scalar>),
2766 Bytes { bytes: Vec<u8> },
2767}
2768
2769impl<'de> Deserialize<'de> for ObjectValue {
2770 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2771 Ok(match SerializedObject::deserialize(deserializer)? {
2772 SerializedObject::List(items) => Self::list(items),
2773 SerializedObject::Bytes { bytes } => Self::bytes(bytes),
2774 })
2775 }
2776}
2777
2778impl std::fmt::Display for Scalar {
2779 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2780 match self {
2781 Self::Null(NullKind::NaN) => write!(f, "NaN"),
2782 Self::Null(NullKind::NaT) => write!(f, "NaT"),
2783 Self::Null(NullKind::Null) => write!(f, "None"),
2784 Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
2785 Self::Int64(v) => write!(f, "{v}"),
2786 Self::Float64(v) => write!(f, "{v}"),
2787 Self::Utf8(s) => write!(f, "{s}"),
2788 Self::Timedelta64(nanos) => write!(f, "{}", Timedelta::format(*nanos)),
2789 Self::Datetime64(nanos) => {
2790 if *nanos == Timestamp::NAT {
2791 write!(f, "NaT")
2792 } else {
2793 write!(f, "Timestamp[{nanos}]")
2794 }
2795 }
2796 Self::Period(p) => {
2797 if p.ordinal == i64::MIN {
2798 write!(f, "NaT")
2799 } else {
2800 write!(f, "{}", p.calendar_string())
2801 }
2802 }
2803 Self::Interval(interval) => write!(f, "{interval}"),
2804 Self::Object(object) => write!(f, "{object}"),
2805 }
2806 }
2807}
2808
2809impl Scalar {
2810 #[must_use]
2817 pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2818 let numeric =
2819 |value: &Self| matches!(value, Self::Bool(_) | Self::Int64(_) | Self::Float64(_));
2820 match (self, other) {
2821 (Self::Utf8(a), Self::Utf8(b)) => Some(a.cmp(b)),
2822 (Self::Datetime64(a), Self::Datetime64(b))
2823 | (Self::Timedelta64(a), Self::Timedelta64(b)) => Some(a.cmp(b)),
2824 (Self::Period(a), Self::Period(b)) if a.freq == b.freq => {
2825 Some(a.ordinal.cmp(&b.ordinal))
2826 }
2827 (Self::Interval(a), Self::Interval(b)) => Some(
2828 a.left
2829 .partial_cmp(&b.left)?
2830 .then(a.right.partial_cmp(&b.right)?),
2831 ),
2832 (Self::Object(a), Self::Object(b)) => a.python_cmp(b),
2833 _ if numeric(self) && numeric(other) => {
2834 self.to_f64().ok()?.partial_cmp(&other.to_f64().ok()?)
2835 }
2836 _ => None,
2837 }
2838 }
2839
2840 #[must_use]
2845 pub fn python_cmp_type_names(&self, other: &Self) -> (String, String) {
2846 if let (Self::Object(ObjectValue::List(left)), Self::Object(ObjectValue::List(right))) =
2847 (self, other)
2848 && let Some((a, b)) = left.iter().zip(right.iter()).find(|(a, b)| a != b)
2849 {
2850 return a.python_cmp_type_names(b);
2851 }
2852 (self.python_type_name(), other.python_type_name())
2853 }
2854
2855 #[must_use]
2858 pub fn python_type_name(&self) -> String {
2859 match self {
2860 Self::Null(NullKind::NaN) | Self::Float64(_) => "float",
2861 Self::Null(NullKind::NaT) => "NaTType",
2862 Self::Null(NullKind::Null) => "NoneType",
2863 Self::Bool(_) => "bool",
2864 Self::Int64(_) => "int",
2865 Self::Utf8(_) => "str",
2866 Self::Timedelta64(_) => "Timedelta",
2867 Self::Datetime64(_) => "Timestamp",
2868 Self::Period(_) => "Period",
2869 Self::Interval(_) => "Interval",
2870 Self::Object(object) => return object.type_name(),
2871 }
2872 .to_owned()
2873 }
2874
2875 #[must_use]
2879 pub fn python_repr(&self) -> String {
2880 match self {
2881 Self::Null(NullKind::NaN) => "nan".to_owned(),
2882 Self::Null(NullKind::NaT) => "NaT".to_owned(),
2883 Self::Null(NullKind::Null) => "None".to_owned(),
2884 Self::Utf8(text) => {
2885 let quote = if text.contains('\'') && !text.contains('"') {
2886 '"'
2887 } else {
2888 '\''
2889 };
2890 let mut out = String::with_capacity(text.len() + 2);
2891 out.push(quote);
2892 for ch in text.chars() {
2893 match ch {
2894 '\\' => out.push_str("\\\\"),
2895 '\n' => out.push_str("\\n"),
2896 '\r' => out.push_str("\\r"),
2897 '\t' => out.push_str("\\t"),
2898 c if c == quote => {
2899 out.push('\\');
2900 out.push(c);
2901 }
2902 c => out.push(c),
2903 }
2904 }
2905 out.push(quote);
2906 out
2907 }
2908 Self::Float64(value) => {
2909 if value.is_nan() {
2910 "nan".to_owned()
2911 } else if value.is_infinite() {
2912 if *value > 0.0 { "inf" } else { "-inf" }.to_owned()
2913 } else if value.fract() == 0.0 && value.abs() < 1e16 {
2914 format!("{value:.1}")
2915 } else {
2916 format!("{value}")
2917 }
2918 }
2919 Self::Object(object) => object.repr(),
2920 other => other.to_string(),
2921 }
2922 }
2923}
2924
2925pub const NA: Scalar = Scalar::Null(NullKind::Null);
2927
2928pub const NAT: Scalar = Scalar::Null(NullKind::NaT);
2930
2931#[allow(non_upper_case_globals)]
2933pub const NaT: Scalar = NAT;
2934
2935impl From<bool> for Scalar {
2945 fn from(value: bool) -> Self {
2946 Self::Bool(value)
2947 }
2948}
2949
2950impl From<i64> for Scalar {
2951 fn from(value: i64) -> Self {
2952 Self::Int64(value)
2953 }
2954}
2955
2956impl From<f64> for Scalar {
2957 fn from(value: f64) -> Self {
2958 Self::Float64(value)
2959 }
2960}
2961
2962impl From<&str> for Scalar {
2963 fn from(value: &str) -> Self {
2964 Self::Utf8(value.to_owned())
2965 }
2966}
2967
2968impl From<String> for Scalar {
2969 fn from(value: String) -> Self {
2970 Self::Utf8(value)
2971 }
2972}
2973
2974impl Scalar {
2975 #[inline]
2976 const fn debug_variant_name(&self) -> &'static str {
2977 match self {
2978 Self::Null(_) => "Null",
2979 Self::Bool(_) => "Bool",
2980 Self::Int64(_) => "Int64",
2981 Self::Float64(_) => "Float64",
2982 Self::Utf8(_) => "Utf8",
2983 Self::Timedelta64(_) => "Timedelta64",
2984 Self::Datetime64(_) => "Datetime64",
2985 Self::Period(_) => "Period",
2986 Self::Interval(_) => "Interval",
2987 Self::Object(_) => "Object",
2988 }
2989 }
2990
2991 #[must_use]
2992 pub fn dtype(&self) -> DType {
2993 match self {
2994 Self::Null(_) => DType::Null,
2995 Self::Bool(_) => DType::Bool,
2996 Self::Int64(_) => DType::Int64,
2997 Self::Float64(_) => DType::Float64,
2998 Self::Utf8(_) => DType::Utf8,
2999 Self::Timedelta64(_) => DType::Timedelta64,
3000 Self::Datetime64(_) => DType::datetime64_naive(),
3001 Self::Period(_) => DType::Period,
3002 Self::Interval(_) => DType::Interval,
3003 Self::Object(_) => DType::Utf8,
3005 }
3006 }
3007
3008 #[must_use]
3009 pub fn is_missing(&self) -> bool {
3010 match self {
3011 Self::Null(_) => true,
3012 Self::Float64(v) => v.is_nan(),
3013 Self::Timedelta64(v) => *v == Timedelta::NAT,
3014 Self::Datetime64(v) => *v == Timestamp::NAT,
3015 Self::Period(p) => p.ordinal == i64::MIN,
3016 _ => false,
3017 }
3018 }
3019
3020 #[must_use]
3021 pub fn is_nan(&self) -> bool {
3022 matches!(self, Self::Null(NullKind::NaN)) || matches!(self, Self::Float64(v) if v.is_nan())
3023 }
3024
3025 #[must_use]
3027 pub const fn is_bool(&self) -> bool {
3028 matches!(self, Self::Bool(_))
3029 }
3030
3031 #[must_use]
3033 pub const fn is_integer(&self) -> bool {
3034 matches!(self, Self::Int64(_))
3035 }
3036
3037 #[must_use]
3039 pub const fn is_float(&self) -> bool {
3040 matches!(self, Self::Float64(_))
3041 }
3042
3043 #[must_use]
3045 pub const fn is_numeric(&self) -> bool {
3046 matches!(self, Self::Int64(_) | Self::Float64(_))
3047 }
3048
3049 #[must_use]
3051 pub const fn is_string(&self) -> bool {
3052 matches!(self, Self::Utf8(_))
3053 }
3054
3055 #[must_use]
3057 pub const fn is_datetime(&self) -> bool {
3058 matches!(self, Self::Datetime64(_))
3059 }
3060
3061 #[must_use]
3063 pub const fn is_timedelta(&self) -> bool {
3064 matches!(self, Self::Timedelta64(_))
3065 }
3066
3067 #[must_use]
3069 pub const fn is_period(&self) -> bool {
3070 matches!(self, Self::Period(_))
3071 }
3072
3073 #[must_use]
3075 pub const fn is_interval(&self) -> bool {
3076 matches!(self, Self::Interval(_))
3077 }
3078
3079 #[must_use]
3081 pub const fn as_i64(&self) -> Option<i64> {
3082 match self {
3083 Self::Int64(v) => Some(*v),
3084 _ => None,
3085 }
3086 }
3087
3088 #[must_use]
3090 pub const fn as_int(&self) -> Option<i64> {
3091 self.as_i64()
3092 }
3093
3094 #[must_use]
3096 pub const fn as_f64(&self) -> Option<f64> {
3097 match self {
3098 Self::Float64(v) => Some(*v),
3099 _ => None,
3100 }
3101 }
3102
3103 #[must_use]
3105 pub const fn as_float(&self) -> Option<f64> {
3106 self.as_f64()
3107 }
3108
3109 #[must_use]
3111 pub const fn as_bool(&self) -> Option<bool> {
3112 match self {
3113 Self::Bool(v) => Some(*v),
3114 _ => None,
3115 }
3116 }
3117
3118 #[must_use]
3120 pub fn as_str(&self) -> Option<&str> {
3121 match self {
3122 Self::Utf8(s) => Some(s.as_str()),
3123 _ => None,
3124 }
3125 }
3126
3127 #[must_use]
3129 pub const fn as_datetime_nanos(&self) -> Option<i64> {
3130 match self {
3131 Self::Datetime64(v) => Some(*v),
3132 _ => None,
3133 }
3134 }
3135
3136 #[must_use]
3138 pub const fn as_timedelta_nanos(&self) -> Option<i64> {
3139 match self {
3140 Self::Timedelta64(v) => Some(*v),
3141 _ => None,
3142 }
3143 }
3144
3145 #[must_use]
3147 pub const fn as_period_ordinal(&self) -> Option<i64> {
3148 match self {
3149 Self::Period(p) => Some(p.ordinal),
3150 _ => None,
3151 }
3152 }
3153
3154 #[must_use]
3156 pub const fn as_interval(&self) -> Option<Interval> {
3157 match self {
3158 Self::Interval(i) => Some(*i),
3159 _ => None,
3160 }
3161 }
3162
3163 #[must_use]
3164 pub fn missing_for_dtype(dtype: DType) -> Self {
3165 match dtype {
3166 DType::Float64 => Self::Null(NullKind::NaN),
3167 DType::Float64Nullable => Self::Null(NullKind::Null),
3175 DType::Timedelta64 => Self::Timedelta64(Timedelta::NAT),
3176 DType::Datetime64 { .. } => Self::Datetime64(Timestamp::NAT),
3177 DType::Period => Self::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
3178 DType::Null => Self::Null(NullKind::Null),
3179 DType::Bool
3180 | DType::BoolNullable
3181 | DType::Int64
3182 | DType::Int64Nullable
3183 | DType::Utf8
3184 | DType::Categorical
3185 | DType::Interval
3186 | DType::Sparse => Self::Null(NullKind::Null),
3187 }
3188 }
3189
3190 #[must_use]
3191 pub fn semantic_eq(&self, other: &Self) -> bool {
3192 match (self, other) {
3193 (Self::Float64(a), Self::Float64(b)) => {
3194 if a.is_nan() && b.is_nan() {
3195 return true;
3196 }
3197 if *a == *b {
3198 return true;
3199 }
3200 let diff = (*a - *b).abs();
3201 let max_abs = a.abs().max(b.abs());
3202 if max_abs == 0.0 {
3203 diff < f64::EPSILON
3204 } else {
3205 diff / max_abs < 1e-14
3206 }
3207 }
3208 (Self::Null(_), Self::Float64(v)) | (Self::Float64(v), Self::Null(_)) => v.is_nan(),
3209 (Self::Null(_), Self::Null(_)) => true,
3216 _ if self.is_missing() && other.is_missing() => true,
3243 (Self::Interval(a), Self::Interval(b)) => a == b && a.subtype == b.subtype,
3248 _ => self == other,
3249 }
3250 }
3251
3252 #[must_use]
3253 pub fn semantic_le(&self, other: &Self) -> bool {
3254 match self.semantic_cmp(other) {
3255 std::cmp::Ordering::Less | std::cmp::Ordering::Equal => true,
3256 std::cmp::Ordering::Greater => false,
3257 }
3258 }
3259
3260 #[must_use]
3261 pub fn semantic_ge(&self, other: &Self) -> bool {
3262 match self.semantic_cmp(other) {
3263 std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => true,
3264 std::cmp::Ordering::Less => false,
3265 }
3266 }
3267
3268 #[must_use]
3269 pub fn is_null(&self) -> bool {
3270 matches!(self, Self::Null(_))
3271 }
3272
3273 #[must_use]
3274 pub fn is_na(&self) -> bool {
3275 self.is_missing()
3276 }
3277
3278 #[must_use]
3280 pub fn isna(&self) -> bool {
3281 self.is_missing()
3282 }
3283
3284 #[must_use]
3286 pub fn isnull(&self) -> bool {
3287 self.is_null()
3288 }
3289
3290 #[must_use]
3292 pub fn notna(&self) -> bool {
3293 !self.is_missing()
3294 }
3295
3296 #[must_use]
3298 pub fn notnull(&self) -> bool {
3299 !self.is_missing()
3300 }
3301
3302 #[must_use]
3304 pub fn is_not_na(&self) -> bool {
3305 !self.is_missing()
3306 }
3307
3308 #[must_use]
3310 pub fn not_na(&self) -> bool {
3311 !self.is_missing()
3312 }
3313
3314 #[must_use]
3315 pub fn coalesce(&self, other: &Self) -> Self {
3316 if self.is_missing() {
3317 other.clone()
3318 } else {
3319 self.clone()
3320 }
3321 }
3322
3323 #[must_use]
3324 pub fn semantic_cmp(&self, other: &Self) -> std::cmp::Ordering {
3325 match (self, other) {
3326 (Self::Int64(a), Self::Int64(b)) => a.cmp(b),
3327 (Self::Float64(a), Self::Float64(b)) => {
3328 a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
3329 }
3330 (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
3331 (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
3332 (Self::Null(a), Self::Null(b)) => a.cmp(b),
3333 (Self::Timedelta64(a), Self::Timedelta64(b)) => {
3334 if *a == Timedelta::NAT || *b == Timedelta::NAT {
3335 std::cmp::Ordering::Equal
3336 } else {
3337 a.cmp(b)
3338 }
3339 }
3340 (Self::Datetime64(a), Self::Datetime64(b)) => {
3341 if *a == Timestamp::NAT || *b == Timestamp::NAT {
3342 std::cmp::Ordering::Equal
3343 } else {
3344 a.cmp(b)
3345 }
3346 }
3347 (Self::Period(a), Self::Period(b)) => {
3348 if a.ordinal == i64::MIN || b.ordinal == i64::MIN {
3349 std::cmp::Ordering::Equal
3350 } else {
3351 a.ordinal.cmp(&b.ordinal)
3352 }
3353 }
3354 (Self::Interval(a), Self::Interval(b)) => a
3355 .left
3356 .partial_cmp(&b.left)
3357 .unwrap_or(std::cmp::Ordering::Equal)
3358 .then_with(|| {
3359 a.right
3360 .partial_cmp(&b.right)
3361 .unwrap_or(std::cmp::Ordering::Equal)
3362 })
3363 .then_with(|| a.closed.cmp(&b.closed)),
3364 (Self::Object(a), Self::Object(b)) => a.cmp(b),
3366 (Self::Int64(a), Self::Float64(b)) => (*a as f64)
3368 .partial_cmp(b)
3369 .unwrap_or(std::cmp::Ordering::Equal),
3370 (Self::Float64(a), Self::Int64(b)) => a
3371 .partial_cmp(&(*b as f64))
3372 .unwrap_or(std::cmp::Ordering::Equal),
3373 (a, b) => a.debug_variant_name().cmp(b.debug_variant_name()),
3377 }
3378 }
3379
3380 pub fn to_f64(&self) -> Result<f64, TypeError> {
3381 match self {
3382 Self::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
3383 Self::Int64(v) => Ok(*v as f64),
3384 Self::Float64(v) => Ok(*v),
3385 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3386 Self::Utf8(v) => Err(TypeError::NonNumericValue {
3387 value: v.clone(),
3388 dtype: DType::Utf8,
3389 }),
3390 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3391 kind: NullKind::NaT,
3392 }),
3393 Self::Timedelta64(v) => Err(TypeError::NonNumericValue {
3394 value: Timedelta::format(*v),
3395 dtype: DType::Timedelta64,
3396 }),
3397 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3398 kind: NullKind::NaT,
3399 }),
3400 Self::Datetime64(v) => Err(TypeError::NonNumericValue {
3401 value: format!("Timestamp[{v}]"),
3402 dtype: DType::datetime64_naive(),
3403 }),
3404 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3405 kind: NullKind::NaT,
3406 }),
3407 Self::Period(p) => Err(TypeError::NonNumericValue {
3408 value: p.calendar_string(),
3409 dtype: DType::Period,
3410 }),
3411 Self::Interval(v) => Err(TypeError::NonNumericValue {
3412 value: v.to_string(),
3413 dtype: DType::Interval,
3414 }),
3415 Self::Object(object) => Err(TypeError::NonNumericValue {
3416 value: object.repr(),
3417 dtype: DType::Utf8,
3418 }),
3419 }
3420 }
3421
3422 pub fn to_i64(&self) -> Result<i64, TypeError> {
3424 match self {
3425 Self::Bool(v) => Ok(if *v { 1 } else { 0 }),
3426 Self::Int64(v) => Ok(*v),
3427 Self::Float64(v) => Ok(*v as i64),
3428 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3429 Self::Utf8(v) => Err(TypeError::NonNumericValue {
3430 value: v.clone(),
3431 dtype: DType::Utf8,
3432 }),
3433 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3434 kind: NullKind::NaT,
3435 }),
3436 Self::Timedelta64(v) => Ok(*v),
3437 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3438 kind: NullKind::NaT,
3439 }),
3440 Self::Datetime64(v) => Ok(*v),
3441 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3442 kind: NullKind::NaT,
3443 }),
3444 Self::Period(p) => Ok(p.ordinal),
3445 Self::Interval(v) => Err(TypeError::NonNumericValue {
3446 value: v.to_string(),
3447 dtype: DType::Interval,
3448 }),
3449 Self::Object(object) => Err(TypeError::NonNumericValue {
3450 value: object.repr(),
3451 dtype: DType::Utf8,
3452 }),
3453 }
3454 }
3455
3456 pub fn to_bool(&self) -> Result<bool, TypeError> {
3458 match self {
3459 Self::Bool(v) => Ok(*v),
3460 Self::Int64(v) => Ok(*v != 0),
3461 Self::Float64(v) => Ok(*v != 0.0 && !v.is_nan()),
3462 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3463 Self::Utf8(v) => Ok(!v.is_empty()),
3464 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3465 kind: NullKind::NaT,
3466 }),
3467 Self::Timedelta64(v) => Ok(*v != 0),
3468 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3469 kind: NullKind::NaT,
3470 }),
3471 Self::Datetime64(v) => Ok(*v != 0),
3472 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3473 kind: NullKind::NaT,
3474 }),
3475 Self::Period(p) => Ok(p.ordinal != 0),
3476 Self::Interval(_) => Ok(true),
3477 Self::Object(ObjectValue::List(items)) => Ok(!items.is_empty()),
3480 Self::Object(ObjectValue::Bytes(data)) => Ok(!data.is_empty()),
3481 Self::Object(ObjectValue::Host(_)) => Ok(true),
3482 }
3483 }
3484
3485 pub fn to_str(&self) -> String {
3487 match self {
3488 Self::Bool(v) => if *v { "True" } else { "False" }.to_string(),
3489 Self::Int64(v) => v.to_string(),
3490 Self::Float64(v) => {
3491 if v.is_nan() {
3492 "nan".to_string()
3493 } else if v.is_infinite() {
3494 if *v > 0.0 { "inf" } else { "-inf" }.to_string()
3495 } else {
3496 v.to_string()
3497 }
3498 }
3499 Self::Null(_) => "NaN".to_string(),
3500 Self::Utf8(v) => v.clone(),
3501 Self::Timedelta64(v) => Timedelta::format(*v),
3502 Self::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_string(),
3503 Self::Datetime64(v) => Timestamp::from_nanos(*v).isoformat(),
3504 Self::Period(p) if p.ordinal == i64::MIN => "NaT".to_string(),
3505 Self::Period(p) => p.calendar_string(),
3506 Self::Interval(v) => v.to_string(),
3507 Self::Object(object) => object.to_string(),
3508 }
3509 }
3510}
3511
3512#[derive(Debug, Error, Clone, PartialEq)]
3513pub enum TypeError {
3514 #[error("dtype coercion from {left:?} to {right:?} has no compatible common type")]
3515 IncompatibleDtypes { left: DType, right: DType },
3516 #[error("cannot cast scalar of dtype {from:?} to {to:?}")]
3517 InvalidCast { from: DType, to: DType },
3518 #[error("cannot cast float {value} to int64 without loss")]
3519 LossyFloatToInt { value: f64 },
3520 #[error("expected 0/1 for bool cast from int64 but found {value}")]
3521 InvalidBoolInt { value: i64 },
3522 #[error("expected 0.0/1.0 for bool cast from float64 but found {value}")]
3523 InvalidBoolFloat { value: f64 },
3524 #[error("value {value:?} has non-numeric dtype {dtype:?}")]
3525 NonNumericValue { value: String, dtype: DType },
3526 #[error("value is missing ({kind:?})")]
3527 ValueIsMissing { kind: NullKind },
3528 #[error("sparse value dtype cannot be {dtype:?}")]
3529 InvalidSparseValueDType { dtype: DType },
3530 #[error("interval_range step must be finite, positive, and not NaN (got {step})")]
3531 InvalidIntervalStep { step: f64 },
3532 #[error("interval_range step {step} does not evenly divide range end-start={span}")]
3533 IntervalStepDoesNotDivide { step: f64, span: f64 },
3534 #[error("interval_range requires exactly 3 of (start, end, periods, freq) to be specified")]
3535 IntervalRangeParameterCount,
3536 #[error("cannot parse '{value}' as {target}")]
3537 ValueNotParseable { value: String, target: String },
3538}
3539
3540pub fn common_dtype(left: DType, right: DType) -> Result<DType, TypeError> {
3541 use DType::{
3542 Bool, BoolNullable, Categorical, Float64, Float64Nullable, Int64, Int64Nullable, Null,
3543 Sparse, Timedelta64,
3544 };
3545
3546 let out = match (&left, &right) {
3547 (a, b) if a == b => a.clone(),
3548 (Null, other) | (other, Null) => other.clone(),
3549 (Categorical, Categorical) => Categorical,
3550
3551 (Bool, Int64) | (Int64, Bool) => Int64,
3553 (Bool, Int64Nullable) | (Int64Nullable, Bool) => Int64Nullable,
3554 (BoolNullable, Int64) | (Int64, BoolNullable) => Int64Nullable,
3555 (BoolNullable, Int64Nullable) | (Int64Nullable, BoolNullable) => Int64Nullable,
3556 (Bool, BoolNullable) | (BoolNullable, Bool) => BoolNullable,
3557 (Bool, Float64) | (Float64, Bool) => Float64,
3558 (BoolNullable, Float64) | (Float64, BoolNullable) => Float64Nullable,
3564
3565 (Int64, Float64) | (Float64, Int64) => Float64,
3567 (Int64Nullable, Float64) | (Float64, Int64Nullable) => Float64Nullable,
3581 (Int64, Int64Nullable) | (Int64Nullable, Int64) => Int64Nullable,
3582
3583 (Float64Nullable, Float64) | (Float64, Float64Nullable) => Float64Nullable,
3600 (Float64Nullable, Int64) | (Int64, Float64Nullable) => Float64Nullable,
3601 (Float64Nullable, Int64Nullable) | (Int64Nullable, Float64Nullable) => Float64Nullable,
3602 (Float64Nullable, Bool) | (Bool, Float64Nullable) => Float64Nullable,
3603 (Float64Nullable, BoolNullable) | (BoolNullable, Float64Nullable) => Float64Nullable,
3604
3605 (Timedelta64, Timedelta64) => Timedelta64,
3607 (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
3608 if left_tz == right_tz =>
3609 {
3610 DType::Datetime64 {
3611 tz: left_tz.clone(),
3612 }
3613 }
3614
3615 (Sparse, _) | (_, Sparse) => {
3616 return Err(TypeError::IncompatibleDtypes {
3617 left: left.clone(),
3618 right: right.clone(),
3619 });
3620 }
3621 _ => {
3622 return Err(TypeError::IncompatibleDtypes { left, right });
3623 }
3624 };
3625
3626 Ok(out)
3627}
3628
3629pub fn infer_dtype(values: &[Scalar]) -> Result<DType, TypeError> {
3630 let mut current = DType::Null;
3631 let mut saw_utf8 = false;
3632 let mut saw_timedelta = false;
3633 let mut saw_datetime = false;
3634 let mut saw_non_utf8_non_null = false;
3635 let mut saw_bool = false;
3642 let mut saw_numeric = false;
3643
3644 for value in values {
3658 match value.dtype() {
3659 DType::Null => {}
3660 DType::Utf8 => saw_utf8 = true,
3661 DType::Bool => {
3662 saw_bool = true;
3663 saw_non_utf8_non_null = true;
3664 current = common_dtype(current, DType::Bool)?;
3665 }
3666 DType::Int64 | DType::Float64 => {
3667 saw_numeric = true;
3668 saw_non_utf8_non_null = true;
3669 current = common_dtype(current, value.dtype())?;
3670 }
3671 DType::Timedelta64 => {
3672 saw_timedelta = true;
3673 if current == DType::Null {
3674 current = DType::Timedelta64;
3675 } else if current != DType::Timedelta64 {
3676 return Err(TypeError::IncompatibleDtypes {
3677 left: current,
3678 right: DType::Timedelta64,
3679 });
3680 }
3681 }
3682 DType::Datetime64 { .. } => {
3683 saw_datetime = true;
3684 if current == DType::Null {
3685 current = DType::datetime64_naive();
3686 } else if !current.is_datetime() {
3687 return Err(TypeError::IncompatibleDtypes {
3688 left: current,
3689 right: DType::datetime64_naive(),
3690 });
3691 }
3692 }
3693 other => {
3694 saw_non_utf8_non_null = true;
3695 current = common_dtype(current, other)?;
3696 }
3697 }
3698
3699 if saw_bool && saw_numeric {
3700 return Ok(DType::Utf8);
3704 }
3705 if saw_utf8 && saw_non_utf8_non_null {
3706 return Ok(DType::Utf8);
3710 }
3711 if saw_timedelta && saw_non_utf8_non_null {
3712 return Err(TypeError::IncompatibleDtypes {
3713 left: DType::Timedelta64,
3714 right: current,
3715 });
3716 }
3717 if saw_datetime && saw_non_utf8_non_null {
3718 return Err(TypeError::IncompatibleDtypes {
3719 left: DType::datetime64_naive(),
3720 right: current,
3721 });
3722 }
3723 }
3724
3725 if saw_utf8 {
3726 Ok(DType::Utf8)
3727 } else {
3728 Ok(current)
3729 }
3730}
3731
3732pub fn cast_scalar_owned(value: Scalar, target: DType) -> Result<Scalar, TypeError> {
3735 let from = value.dtype();
3736 if from == target {
3737 return Ok(value);
3738 }
3739 if (from == DType::Int64 && target == DType::Int64Nullable)
3741 || (from == DType::Int64Nullable && target == DType::Int64)
3742 {
3743 return Ok(value);
3744 }
3745 if (from == DType::Bool && target == DType::BoolNullable)
3747 || (from == DType::BoolNullable && target == DType::Bool)
3748 {
3749 return Ok(value);
3750 }
3751 if (from == DType::Float64 && target == DType::Float64Nullable)
3759 || (from == DType::Float64Nullable && target == DType::Float64)
3760 {
3761 return Ok(value);
3762 }
3763 if from.is_datetime() && target.is_datetime() {
3767 return Ok(value);
3768 }
3769 if target == DType::Utf8 {
3770 return Ok(Scalar::Utf8(scalar_to_string_for_astype(value)));
3771 }
3772 if target == DType::Bool
3778 && let Scalar::Float64(v) = &value
3779 && v.is_nan()
3780 {
3781 return Ok(Scalar::Bool(true));
3782 }
3783 if target == DType::Bool {
3809 match &value {
3810 Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3811 return Ok(Scalar::Bool(*nanos != 0));
3812 }
3813 _ => {}
3814 }
3815 }
3816 if target == DType::Int64 {
3841 match &value {
3842 Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3843 return Ok(Scalar::Int64(*nanos));
3844 }
3845 _ => {}
3846 }
3847 }
3848 if value.is_missing() {
3849 return Ok(Scalar::missing_for_dtype(target));
3850 }
3851
3852 match target {
3855 DType::Null => Ok(Scalar::Null(NullKind::Null)),
3856 DType::Bool => match &value {
3857 Scalar::Int64(v) => Ok(Scalar::Bool(*v != 0)),
3860 Scalar::Float64(v) => Ok(Scalar::Bool(*v != 0.0)),
3863 _ => Err(TypeError::InvalidCast { from, to: target }),
3864 },
3865 DType::BoolNullable => match &value {
3866 Scalar::Bool(b) => Ok(Scalar::Bool(*b)),
3871 Scalar::Int64(0) => Ok(Scalar::Bool(false)),
3872 Scalar::Int64(1) => Ok(Scalar::Bool(true)),
3873 Scalar::Int64(v) => Err(TypeError::InvalidBoolInt { value: *v }),
3874 Scalar::Float64(v) if *v == 0.0 => Ok(Scalar::Bool(false)),
3875 Scalar::Float64(v) if *v == 1.0 => Ok(Scalar::Bool(true)),
3876 Scalar::Float64(v) => Err(TypeError::InvalidBoolFloat { value: *v }),
3877 _ => Err(TypeError::InvalidCast { from, to: target }),
3878 },
3879 DType::Int64 | DType::Int64Nullable => match &value {
3880 Scalar::Bool(v) => Ok(Scalar::Int64(i64::from(*v))),
3881 Scalar::Float64(v) => {
3882 if !v.is_finite() {
3889 return Err(TypeError::LossyFloatToInt { value: *v });
3890 }
3891 if *v < i64::MIN as f64 || *v >= 9223372036854775808.0 {
3892 return Err(TypeError::LossyFloatToInt { value: *v });
3893 }
3894 Ok(Scalar::Int64(*v as i64))
3895 }
3896 Scalar::Utf8(s) => {
3897 if let Ok(v) = s.parse::<i64>() {
3900 return Ok(Scalar::Int64(v));
3901 }
3902 if let Ok(f) = s.parse::<f64>()
3903 && f.is_finite()
3904 && f.fract() == 0.0
3905 && f >= i64::MIN as f64
3906 && f < 9223372036854775808.0
3907 {
3908 return Ok(Scalar::Int64(f as i64));
3909 }
3910 Err(TypeError::InvalidCast { from, to: target })
3911 }
3912 _ => Err(TypeError::InvalidCast { from, to: target }),
3913 },
3914 DType::Float64 | DType::Float64Nullable => match &value {
3918 Scalar::Bool(v) => Ok(Scalar::Float64(if *v { 1.0 } else { 0.0 })),
3919 Scalar::Int64(v) => Ok(Scalar::Float64(*v as f64)),
3920 Scalar::Utf8(s) => s
3921 .parse::<f64>()
3922 .map(Scalar::Float64)
3923 .map_err(|_| TypeError::InvalidCast { from, to: target }),
3924 _ => Err(TypeError::InvalidCast { from, to: target }),
3925 },
3926 DType::Utf8 => Ok(Scalar::Utf8(scalar_to_string_for_astype(value))),
3927 DType::Categorical => Err(TypeError::InvalidCast { from, to: target }),
3928 DType::Timedelta64 => match &value {
3929 Scalar::Bool(v) => Ok(Scalar::Timedelta64(i64::from(*v))),
3940 Scalar::Int64(v) => Ok(Scalar::Timedelta64(*v)),
3941 Scalar::Float64(v) => Ok(Scalar::Timedelta64(float_to_temporal_nanos(*v))),
3942 Scalar::Utf8(s) => Timedelta::parse(s)
3943 .map(Scalar::Timedelta64)
3944 .map_err(|_| TypeError::InvalidCast { from, to: target }),
3945 _ => Err(TypeError::InvalidCast { from, to: target }),
3946 },
3947 DType::Datetime64 { .. } => match &value {
3948 Scalar::Bool(v) => Ok(Scalar::Datetime64(i64::from(*v))),
3951 Scalar::Int64(v) => Ok(Scalar::Datetime64(*v)),
3952 Scalar::Float64(v) => Ok(Scalar::Datetime64(float_to_temporal_nanos(*v))),
3953 Scalar::Utf8(s) => Timestamp::parse(s)
3954 .map(|timestamp| Scalar::Datetime64(timestamp.nanos))
3955 .map_err(|_| TypeError::InvalidCast { from, to: target }),
3956 _ => Err(TypeError::InvalidCast { from, to: target }),
3957 },
3958 DType::Period => match &value {
3959 Scalar::Int64(v) => Ok(Scalar::Period(Period::new(*v, PeriodFreq::Daily))),
3962 Scalar::Utf8(s) => Period::parse(s)
3963 .map(Scalar::Period)
3964 .map_err(|_| TypeError::InvalidCast { from, to: target }),
3965 _ => Err(TypeError::InvalidCast { from, to: target }),
3966 },
3967 DType::Interval => match &value {
3968 Scalar::Utf8(s) => Interval::parse(s)
3969 .map(Scalar::Interval)
3970 .map_err(|_| TypeError::InvalidCast { from, to: target }),
3971 _ => Err(TypeError::InvalidCast { from, to: target }),
3972 },
3973 DType::Sparse => Err(TypeError::InvalidCast { from, to: target }),
3974 }
3975}
3976
3977fn float_to_temporal_nanos(value: f64) -> i64 {
4013 if value.is_finite() && value > (i64::MIN as f64) && value < (i64::MAX as f64) {
4016 value as i64
4018 } else {
4019 Timestamp::NAT
4022 }
4023}
4024
4025fn scalar_to_string_for_astype(value: Scalar) -> String {
4026 match value {
4027 Scalar::Null(NullKind::Null) => "None".to_owned(),
4028 Scalar::Null(NullKind::NaN) => "nan".to_owned(),
4029 Scalar::Null(NullKind::NaT) => "NaT".to_owned(),
4030 Scalar::Bool(true) => "True".to_owned(),
4031 Scalar::Bool(false) => "False".to_owned(),
4032 Scalar::Int64(v) => v.to_string(),
4033 Scalar::Float64(v) => float_to_string_for_astype(v),
4034 Scalar::Utf8(s) => s,
4035 Scalar::Timedelta64(v) if v == Timedelta::NAT => "NaT".to_owned(),
4036 Scalar::Timedelta64(v) => Timedelta::format(v),
4037 Scalar::Datetime64(v) if v == Timestamp::NAT => "NaT".to_owned(),
4038 Scalar::Datetime64(v) => timestamp_text(v),
4039 Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
4040 Scalar::Period(p) => p.calendar_string(),
4041 Scalar::Interval(v) => v.to_string(),
4042 Scalar::Object(object) => object.to_string(),
4044 }
4045}
4046
4047pub fn float_to_string_for_astype(value: f64) -> String {
4048 use std::fmt::Write as _;
4049
4050 if value.is_nan() {
4051 return "nan".to_owned();
4052 }
4053 if value.is_infinite() {
4054 return value.to_string(); }
4056 let mut rendered = String::with_capacity(32);
4068 let _ = write!(rendered, "{value:?}");
4069 let Some(exponent_marker) = rendered.find('e') else {
4070 return rendered;
4071 };
4072
4073 let sign_position = exponent_marker + 1;
4074 let digits_position = match rendered.as_bytes().get(sign_position) {
4075 Some(b'+' | b'-') => sign_position + 1,
4076 _ => {
4077 rendered.insert(sign_position, '+');
4078 sign_position + 1
4079 }
4080 };
4081 if rendered.len() - digits_position == 1 {
4082 rendered.insert(digits_position, '0');
4083 }
4084 rendered
4085}
4086
4087static ENG_FLOAT_ACCURACY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(3);
4088static ENG_FLOAT_USE_PREFIX: std::sync::atomic::AtomicBool =
4089 std::sync::atomic::AtomicBool::new(false);
4090static ENG_FLOAT_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
4091
4092pub fn eng_float_format(num: f64, accuracy: Option<usize>, use_eng_prefix: bool) -> String {
4094 if num.is_nan() {
4095 return "NaN".to_string();
4096 }
4097 if num.is_infinite() {
4098 return if num < 0.0 {
4099 "-inf".to_string()
4100 } else {
4101 "inf".to_string()
4102 };
4103 }
4104
4105 let sign = if num < 0.0 { -1.0 } else { 1.0 };
4106 let abs_num = num.abs();
4107
4108 let pow10 = if abs_num != 0.0 {
4109 let p = (abs_num.log10() / 3.0).floor() as i32 * 3;
4110 p.clamp(-24, 24)
4111 } else {
4112 0
4113 };
4114
4115 let prefix = if use_eng_prefix {
4116 match pow10 {
4117 -24 => "y",
4118 -21 => "z",
4119 -18 => "a",
4120 -15 => "f",
4121 -12 => "p",
4122 -9 => "n",
4123 -6 => "u",
4124 -3 => "m",
4125 0 => "",
4126 3 => "k",
4127 6 => "M",
4128 9 => "G",
4129 12 => "T",
4130 15 => "P",
4131 18 => "E",
4132 21 => "Z",
4133 24 => "Y",
4134 _ => "",
4135 }
4136 .to_string()
4137 } else if pow10 < 0 {
4138 format!("E-{:02}", -pow10)
4139 } else {
4140 format!("E+{:02}", pow10)
4141 };
4142
4143 let mant = (sign * abs_num) / 10f64.powi(pow10);
4144
4145 if let Some(acc) = accuracy {
4146 format!("{mant:.acc$}{prefix}", acc = acc)
4147 } else {
4148 format!("{mant}{prefix}")
4149 }
4150}
4151
4152pub fn set_eng_float_format(accuracy: usize, use_eng_prefix: bool) {
4155 use std::sync::atomic::Ordering;
4156 ENG_FLOAT_ACCURACY.store(accuracy, Ordering::Relaxed);
4157 ENG_FLOAT_USE_PREFIX.store(use_eng_prefix, Ordering::Relaxed);
4158 ENG_FLOAT_ACTIVE.store(true, Ordering::Relaxed);
4159}
4160
4161pub fn reset_eng_float_format() {
4163 use std::sync::atomic::Ordering;
4164 ENG_FLOAT_ACTIVE.store(false, Ordering::Relaxed);
4165}
4166
4167pub fn get_eng_float_format() -> Option<(usize, bool)> {
4169 use std::sync::atomic::Ordering;
4170 if ENG_FLOAT_ACTIVE.load(Ordering::Relaxed) {
4171 Some((
4172 ENG_FLOAT_ACCURACY.load(Ordering::Relaxed),
4173 ENG_FLOAT_USE_PREFIX.load(Ordering::Relaxed),
4174 ))
4175 } else {
4176 None
4177 }
4178}
4179
4180#[derive(Debug, Error, Clone, PartialEq, Eq)]
4184pub enum OptionError {
4185 #[error("no such option: '{pat}'")]
4186 NotFound { pat: String },
4187 #[error("option pattern '{pat}' matches multiple options: {matches:?}")]
4188 Ambiguous { pat: String, matches: Vec<String> },
4189 #[error("invalid option value for '{pat}': {reason}")]
4190 InvalidValue { pat: String, reason: String },
4191}
4192
4193#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4195pub enum OptionValue {
4196 None,
4197 Int(i64),
4198 Float(f64),
4199 Bool(bool),
4200 Str(String),
4201}
4202
4203impl OptionValue {
4204 #[must_use]
4205 pub const fn is_none(&self) -> bool {
4206 matches!(self, Self::None)
4207 }
4208
4209 #[must_use]
4210 pub const fn as_int(&self) -> Option<i64> {
4211 match self {
4212 Self::Int(i) => Some(*i),
4213 _ => None,
4214 }
4215 }
4216
4217 #[must_use]
4218 pub const fn as_float(&self) -> Option<f64> {
4219 match self {
4220 Self::Float(f) => Some(*f),
4221 _ => None,
4222 }
4223 }
4224
4225 #[must_use]
4226 pub const fn as_bool(&self) -> Option<bool> {
4227 match self {
4228 Self::Bool(b) => Some(*b),
4229 _ => None,
4230 }
4231 }
4232
4233 #[must_use]
4234 pub fn as_str(&self) -> Option<&str> {
4235 match self {
4236 Self::Str(s) => Some(s.as_str()),
4237 _ => None,
4238 }
4239 }
4240}
4241
4242impl std::fmt::Display for OptionValue {
4243 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4244 match self {
4245 Self::None => write!(f, "None"),
4246 Self::Int(i) => write!(f, "{i}"),
4247 Self::Float(fl) => write!(f, "{fl}"),
4248 Self::Bool(b) => write!(f, "{b}"),
4249 Self::Str(s) => write!(f, "{s}"),
4250 }
4251 }
4252}
4253
4254impl From<i64> for OptionValue {
4255 fn from(v: i64) -> Self {
4256 Self::Int(v)
4257 }
4258}
4259
4260impl From<i32> for OptionValue {
4261 fn from(v: i32) -> Self {
4262 Self::Int(i64::from(v))
4263 }
4264}
4265
4266impl From<usize> for OptionValue {
4267 fn from(v: usize) -> Self {
4268 Self::Int(i64::try_from(v).unwrap_or(i64::MAX))
4269 }
4270}
4271
4272impl From<f64> for OptionValue {
4273 fn from(v: f64) -> Self {
4274 Self::Float(v)
4275 }
4276}
4277
4278impl From<bool> for OptionValue {
4279 fn from(v: bool) -> Self {
4280 Self::Bool(v)
4281 }
4282}
4283
4284impl From<&str> for OptionValue {
4285 fn from(v: &str) -> Self {
4286 Self::Str(v.to_string())
4287 }
4288}
4289
4290impl From<String> for OptionValue {
4291 fn from(v: String) -> Self {
4292 Self::Str(v)
4293 }
4294}
4295
4296impl From<()> for OptionValue {
4297 fn from(_: ()) -> Self {
4298 Self::None
4299 }
4300}
4301
4302fn default_options_map() -> std::collections::BTreeMap<String, OptionValue> {
4303 let mut m = std::collections::BTreeMap::new();
4304 m.insert("display.max_rows".to_string(), OptionValue::Int(60));
4305 m.insert("display.min_rows".to_string(), OptionValue::Int(10));
4306 m.insert("display.max_columns".to_string(), OptionValue::Int(0));
4307 m.insert("display.width".to_string(), OptionValue::Int(80));
4308 m.insert("display.precision".to_string(), OptionValue::Int(6));
4309 m.insert("display.max_colwidth".to_string(), OptionValue::Int(50));
4310 m.insert(
4311 "display.show_dimensions".to_string(),
4312 OptionValue::Bool(true),
4313 );
4314 m.insert("display.float_format".to_string(), OptionValue::None);
4315 m.insert(
4316 "display.large_repr".to_string(),
4317 OptionValue::Str("truncate".to_string()),
4318 );
4319 m.insert(
4320 "display.max_info_columns".to_string(),
4321 OptionValue::Int(100),
4322 );
4323 m.insert(
4324 "display.max_info_rows".to_string(),
4325 OptionValue::Int(1690785),
4326 );
4327 m.insert("display.memory_usage".to_string(), OptionValue::Bool(true));
4328 m.insert(
4329 "display.colheader_justify".to_string(),
4330 OptionValue::Str("right".to_string()),
4331 );
4332 m.insert("display.chop_threshold".to_string(), OptionValue::None);
4333 m.insert(
4334 "display.date_dayfirst".to_string(),
4335 OptionValue::Bool(false),
4336 );
4337 m.insert(
4338 "display.date_yearfirst".to_string(),
4339 OptionValue::Bool(false),
4340 );
4341 m.insert(
4342 "display.encoding".to_string(),
4343 OptionValue::Str("utf-8".to_string()),
4344 );
4345 m.insert("mode.sim_interactive".to_string(), OptionValue::Bool(false));
4346 m.insert(
4347 "mode.chained_assignment".to_string(),
4348 OptionValue::Str("warn".to_string()),
4349 );
4350 m.insert("mode.use_inf_as_na".to_string(), OptionValue::Bool(false));
4351 m.insert("mode.copy_on_write".to_string(), OptionValue::Bool(false));
4352 m.insert(
4353 "mode.data_manager".to_string(),
4354 OptionValue::Str("block".to_string()),
4355 );
4356 m.insert(
4357 "compute.use_bottleneck".to_string(),
4358 OptionValue::Bool(true),
4359 );
4360 m.insert("compute.use_numba".to_string(), OptionValue::Bool(false));
4361 m.insert(
4362 "io.excel.zip.reader".to_string(),
4363 OptionValue::Str("zipfile".to_string()),
4364 );
4365 m.insert(
4366 "io.parquet.engine".to_string(),
4367 OptionValue::Str("auto".to_string()),
4368 );
4369 m.insert(
4370 "io.sql.engine".to_string(),
4371 OptionValue::Str("auto".to_string()),
4372 );
4373 m.insert(
4374 "plotting.backend".to_string(),
4375 OptionValue::Str("matplotlib".to_string()),
4376 );
4377 m.insert(
4378 "plotting.matplotlib.register_converters".to_string(),
4379 OptionValue::Bool(true),
4380 );
4381 m
4382}
4383
4384static GLOBAL_OPTIONS: std::sync::LazyLock<
4385 std::sync::Mutex<std::collections::BTreeMap<String, OptionValue>>,
4386> = std::sync::LazyLock::new(|| std::sync::Mutex::new(default_options_map()));
4387
4388fn resolve_option_key(
4389 pat: &str,
4390 map: &std::collections::BTreeMap<String, OptionValue>,
4391) -> Result<String, OptionError> {
4392 if map.contains_key(pat) {
4393 return Ok(pat.to_string());
4394 }
4395 let matches: Vec<String> = map
4396 .keys()
4397 .filter(|k| k.ends_with(pat) || k.contains(pat))
4398 .cloned()
4399 .collect();
4400 if matches.len() == 1 {
4401 Ok(matches[0].clone())
4402 } else if matches.is_empty() {
4403 Err(OptionError::NotFound {
4404 pat: pat.to_string(),
4405 })
4406 } else {
4407 Err(OptionError::Ambiguous {
4408 pat: pat.to_string(),
4409 matches,
4410 })
4411 }
4412}
4413
4414pub fn get_option(pat: &str) -> Result<OptionValue, OptionError> {
4420 let map = GLOBAL_OPTIONS
4421 .lock()
4422 .unwrap_or_else(std::sync::PoisonError::into_inner);
4423 let key = resolve_option_key(pat, &map)?;
4424 Ok(map.get(&key).cloned().unwrap_or(OptionValue::None))
4425}
4426
4427pub fn set_option(pat: &str, val: impl Into<OptionValue>) -> Result<(), OptionError> {
4433 let mut map = GLOBAL_OPTIONS
4434 .lock()
4435 .unwrap_or_else(std::sync::PoisonError::into_inner);
4436 let key = resolve_option_key(pat, &map)?;
4437 let v = val.into();
4438 map.insert(key, v);
4439 Ok(())
4440}
4441
4442pub fn reset_option(pat: Option<&str>) -> Result<(), OptionError> {
4449 let mut map = GLOBAL_OPTIONS
4450 .lock()
4451 .unwrap_or_else(std::sync::PoisonError::into_inner);
4452 let defaults = default_options_map();
4453 let p = pat.unwrap_or("all");
4454 if p == "all" {
4455 *map = defaults;
4456 return Ok(());
4457 }
4458 let key = resolve_option_key(p, &defaults)?;
4459 if let Some(def_val) = defaults.get(&key) {
4460 map.insert(key, def_val.clone());
4461 }
4462 Ok(())
4463}
4464
4465pub fn describe_option(pat: Option<&str>) -> Result<String, OptionError> {
4470 use std::fmt::Write as _;
4471 let map = GLOBAL_OPTIONS
4472 .lock()
4473 .unwrap_or_else(std::sync::PoisonError::into_inner);
4474 let mut out = String::with_capacity(map.len() * 40);
4475 let mut matched = 0;
4476 for (k, v) in map.iter() {
4477 if let Some(p) = pat
4478 && !k.contains(p)
4479 {
4480 continue;
4481 }
4482 if matched > 0 {
4483 out.push('\n');
4484 }
4485 let _ = write!(out, "{k} : [currently: {v}]");
4486 matched += 1;
4487 }
4488 if matched == 0
4489 && let Some(p) = pat
4490 {
4491 return Err(OptionError::NotFound { pat: p.to_string() });
4492 }
4493 Ok(out)
4494}
4495
4496#[derive(Debug)]
4498pub struct OptionContextGuard {
4499 saved: Vec<(String, OptionValue)>,
4500}
4501
4502impl Drop for OptionContextGuard {
4503 fn drop(&mut self) {
4504 let mut map = GLOBAL_OPTIONS
4505 .lock()
4506 .unwrap_or_else(std::sync::PoisonError::into_inner);
4507 for (k, old) in self.saved.drain(..) {
4508 map.insert(k, old);
4509 }
4510 }
4511}
4512
4513pub fn option_context(entries: &[(&str, OptionValue)]) -> Result<OptionContextGuard, OptionError> {
4518 let mut map = GLOBAL_OPTIONS
4519 .lock()
4520 .unwrap_or_else(std::sync::PoisonError::into_inner);
4521 let mut saved = Vec::with_capacity(entries.len());
4522 for (pat, new_val) in entries {
4523 let key = resolve_option_key(pat, &map)?;
4524 if let Some(old) = map.get(&key) {
4525 saved.push((key.clone(), old.clone()));
4526 }
4527 map.insert(key, new_val.clone());
4528 }
4529 Ok(OptionContextGuard { saved })
4530}
4531
4532pub fn cast_scalar(value: &Scalar, target: DType) -> Result<Scalar, TypeError> {
4534 cast_scalar_owned(value.clone(), target)
4535}
4536
4537#[derive(Debug, Error, Clone, PartialEq)]
4540pub enum TimedeltaError {
4541 #[error("invalid timedelta string: {0}")]
4542 InvalidFormat(String),
4543 #[error("overflow in timedelta computation")]
4544 Overflow,
4545}
4546
4547impl TimedeltaError {
4548 #[must_use]
4554 pub const fn pandas_error(&self) -> Option<PandasTemporalError> {
4555 match self {
4556 Self::Overflow => Some(PandasTemporalError::OutOfBoundsTimedelta),
4559 Self::InvalidFormat(_) => None,
4560 }
4561 }
4562}
4563
4564#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4565pub struct CategoricalMetadata {
4566 pub categories: Vec<Scalar>,
4568 pub ordered: bool,
4570}
4571
4572impl CategoricalMetadata {
4573 #[must_use]
4574 pub fn new(categories: Vec<Scalar>, ordered: bool) -> Self {
4575 Self {
4576 categories,
4577 ordered,
4578 }
4579 }
4580}
4581
4582#[derive(Debug, Clone, Copy, Default)]
4583pub struct TimedeltaComponents {
4584 pub days: i64,
4585 pub hours: i64,
4586 pub minutes: i64,
4587 pub seconds: i64,
4588 pub milliseconds: i64,
4589 pub microseconds: i64,
4590 pub nanoseconds: i64,
4591}
4592
4593#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4605pub enum PandasTemporalError {
4606 Overflow,
4610 OutOfBoundsDatetime,
4613 OutOfBoundsTimedelta,
4618 OverflowInTimedeltaOperation,
4621 ZeroDivision,
4630}
4631
4632#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4635pub struct TemporalFailure {
4636 pub op: &'static str,
4638 pub pandas_error: PandasTemporalError,
4640 pub operands: Option<(i64, i64)>,
4645}
4646
4647impl TemporalFailure {
4648 #[must_use]
4649 pub const fn new(op: &'static str, pandas_error: PandasTemporalError) -> Self {
4650 Self {
4651 op,
4652 pandas_error,
4653 operands: None,
4654 }
4655 }
4656
4657 #[must_use]
4659 pub const fn with_operands(mut self, lhs: i64, rhs: i64) -> Self {
4660 self.operands = Some((lhs, rhs));
4661 self
4662 }
4663}
4664
4665#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4675pub struct TemporalRecovery {
4676 pub op: &'static str,
4678 pub pandas_error: PandasTemporalError,
4680 pub operands: Option<(i64, i64)>,
4682 pub recovered_as: i64,
4684}
4685
4686pub mod overflow_audit {
4695 use std::cell::RefCell;
4696
4697 use super::TemporalRecovery;
4698
4699 thread_local! {
4700 static LOG: RefCell<Option<Vec<TemporalRecovery>>> = const { RefCell::new(None) };
4701 }
4702
4703 pub fn enable() {
4705 LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
4706 }
4707
4708 pub fn disable() {
4710 LOG.with(|log| *log.borrow_mut() = None);
4711 }
4712
4713 #[must_use]
4715 pub fn is_enabled() -> bool {
4716 LOG.with(|log| log.borrow().is_some())
4717 }
4718
4719 #[must_use]
4721 pub fn drain() -> Vec<TemporalRecovery> {
4722 LOG.with(|log| match log.borrow_mut().as_mut() {
4723 Some(entries) => std::mem::take(entries),
4724 None => Vec::new(),
4725 })
4726 }
4727
4728 pub(super) fn record(entry: TemporalRecovery) {
4730 LOG.with(|log| {
4731 if let Some(entries) = log.borrow_mut().as_mut() {
4732 entries.push(entry);
4733 }
4734 });
4735 }
4736}
4737
4738#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
4751pub enum OverflowPolicy {
4752 #[default]
4755 SurfaceNat,
4756 Strict,
4758 HardenedNat,
4766}
4767
4768impl OverflowPolicy {
4769 pub fn resolve<T>(
4777 self,
4778 outcome: Result<T, TemporalFailure>,
4779 nat: T,
4780 ) -> Result<T, TemporalFailure> {
4781 self.resolve_recording(outcome, nat, i64::MIN)
4782 }
4783
4784 pub fn resolve_recording<T>(
4793 self,
4794 outcome: Result<T, TemporalFailure>,
4795 nat: T,
4796 recovered_as: i64,
4797 ) -> Result<T, TemporalFailure> {
4798 match (self, outcome) {
4799 (_, Ok(value)) => Ok(value),
4800 (Self::SurfaceNat, Err(_)) => Ok(nat),
4801 (Self::Strict, Err(failure)) => Err(failure),
4802 (Self::HardenedNat, Err(failure)) => {
4803 overflow_audit::record(TemporalRecovery {
4805 op: failure.op,
4806 pandas_error: failure.pandas_error,
4807 operands: failure.operands,
4808 recovered_as,
4809 });
4810 Ok(nat)
4811 }
4812 }
4813 }
4814}
4815
4816pub struct Timedelta;
4817
4818impl Timedelta {
4819 pub const NANOS_PER_MICRO: i64 = 1_000;
4820 pub const NANOS_PER_MILLI: i64 = 1_000_000;
4821 pub const NANOS_PER_SEC: i64 = 1_000_000_000;
4822 pub const NANOS_PER_MIN: i64 = 60 * Self::NANOS_PER_SEC;
4823 pub const NANOS_PER_HOUR: i64 = 60 * Self::NANOS_PER_MIN;
4824 pub const NANOS_PER_DAY: i64 = 24 * Self::NANOS_PER_HOUR;
4825 pub const NANOS_PER_WEEK: i64 = 7 * Self::NANOS_PER_DAY;
4826
4827 pub const NAT: i64 = i64::MIN;
4828
4829 pub fn parse(s: &str) -> Result<i64, TimedeltaError> {
4830 let s = s.trim();
4831
4832 if s.eq_ignore_ascii_case("nat") {
4833 return Ok(Self::NAT);
4834 }
4835
4836 let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
4837 (true, rest.trim())
4838 } else {
4839 (false, s)
4840 };
4841
4842 if let Some(nanos) = Self::try_parse_time_format(s) {
4843 return Ok(if negative { -nanos } else { nanos });
4844 }
4845
4846 if let Some(nanos) = Self::try_parse_iso8601_duration(s) {
4847 return Ok(if negative { -nanos } else { nanos });
4848 }
4849
4850 let (units, clock) = Self::parse_compound(s)?;
4856 let units = if negative { -units } else { units };
4857 units.checked_add(clock).ok_or(TimedeltaError::Overflow)
4858 }
4859
4860 fn try_parse_iso8601_duration(s: &str) -> Option<i64> {
4868 let mut rest = s.strip_prefix('P')?;
4869 if rest.is_empty() {
4870 return None;
4871 }
4872 let mut total: i64 = 0;
4873 let mut saw_component = false;
4874 while !rest.is_empty() {
4875 if let Some(after_t) = rest.strip_prefix('T') {
4876 rest = after_t;
4877 continue;
4878 }
4879 let num_end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')?;
4880 if num_end == 0 {
4881 return None;
4882 }
4883 let num_str = &rest[..num_end];
4884 let unit = rest.as_bytes()[num_end];
4885 let is_fractional = num_str.contains('.');
4886 rest = &rest[num_end + 1..];
4887
4888 let (multiplier, frac_ok) = match unit {
4889 b'W' => (Self::NANOS_PER_WEEK, false),
4890 b'D' => (Self::NANOS_PER_DAY, false),
4891 b'H' => (Self::NANOS_PER_HOUR, false),
4892 b'M' => (Self::NANOS_PER_MIN, false),
4893 b'S' => (Self::NANOS_PER_SEC, true),
4894 _ => return None,
4895 };
4896 if is_fractional {
4897 if !frac_ok {
4898 return None;
4899 }
4900 let value: f64 = num_str.parse().ok()?;
4901 let product = value * multiplier as f64;
4902 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
4903 return None;
4904 }
4905 total = total.checked_add(product.round() as i64)?;
4906 } else {
4907 let value: i64 = num_str.parse().ok()?;
4908 total = total.checked_add(value.checked_mul(multiplier)?)?;
4909 }
4910 saw_component = true;
4911 }
4912 saw_component.then_some(total)
4913 }
4914
4915 fn try_parse_time_format(s: &str) -> Option<i64> {
4916 let parts: Vec<&str> = s.split(':').collect();
4917 if parts.len() < 2 || parts.len() > 3 {
4918 return None;
4919 }
4920
4921 let hours: i64 = parts[0].parse().ok()?;
4922 let minutes: i64 = parts[1].parse().ok()?;
4923
4924 let (seconds, frac_nanos) = if parts.len() == 3 {
4925 if let Some((sec_str, frac_str)) = parts[2].split_once('.') {
4926 let sec: i64 = sec_str.parse().ok()?;
4927 if !frac_str.bytes().all(|byte| byte.is_ascii_digit()) {
4928 return None;
4929 }
4930 let mut frac = 0_i64;
4931 let taken = frac_str.len().min(9);
4932 for byte in frac_str.bytes().take(9) {
4933 frac = frac * 10 + i64::from(byte - b'0');
4934 }
4935 for _ in taken..9 {
4936 frac *= 10;
4937 }
4938 (sec, frac)
4939 } else {
4940 let sec: i64 = parts[2].parse().ok()?;
4941 (sec, 0)
4942 }
4943 } else {
4944 (0, 0)
4945 };
4946
4947 hours
4948 .checked_mul(Self::NANOS_PER_HOUR)?
4949 .checked_add(minutes.checked_mul(Self::NANOS_PER_MIN)?)?
4950 .checked_add(seconds.checked_mul(Self::NANOS_PER_SEC)?)?
4951 .checked_add(frac_nanos)
4952 }
4953
4954 fn parse_compound(s: &str) -> Result<(i64, i64), TimedeltaError> {
4960 let mut total: i64 = 0;
4961 let mut clock: i64 = 0;
4962 let mut remaining = s;
4963
4964 while !remaining.is_empty() {
4965 remaining = remaining.trim_start();
4966 if remaining.is_empty() {
4967 break;
4968 }
4969 if remaining.starts_with('-') {
4970 return Err(TimedeltaError::InvalidFormat(format!(
4971 "only leading negative signs are allowed: {s}"
4972 )));
4973 }
4974
4975 if remaining.contains(':')
4978 && let Some(time_nanos) = Self::try_parse_time_format(remaining)
4979 {
4980 clock = time_nanos;
4981 break;
4982 }
4983
4984 let num_end = remaining
4985 .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
4986 .unwrap_or(remaining.len());
4987
4988 if num_end == 0 {
4989 return Err(TimedeltaError::InvalidFormat(s.to_string()));
4990 }
4991
4992 let num_str = &remaining[..num_end];
4993 let num: f64 = num_str
4994 .parse()
4995 .map_err(|_| TimedeltaError::InvalidFormat(s.to_string()))?;
4996
4997 remaining = remaining[num_end..].trim_start();
4998
4999 let unit_end = remaining
5000 .find(|c: char| c.is_ascii_digit() || c.is_whitespace())
5001 .unwrap_or(remaining.len());
5002
5003 let unit = &remaining[..unit_end];
5004 remaining = &remaining[unit_end..];
5005
5006 let multiplier = Self::unit_to_nanos(unit)
5007 .ok_or_else(|| TimedeltaError::InvalidFormat(s.to_string()))?;
5008
5009 let product = num * multiplier as f64;
5014 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5015 return Err(TimedeltaError::Overflow);
5016 }
5017 let nanos = product.round() as i64;
5018 total = total.checked_add(nanos).ok_or(TimedeltaError::Overflow)?;
5019 }
5020
5021 Ok((total, clock))
5031 }
5032
5033 #[must_use]
5047 pub fn unit_to_nanos(unit: &str) -> Option<i64> {
5048 match unit.to_lowercase().as_str() {
5049 "w" | "week" | "weeks" => Some(Self::NANOS_PER_WEEK),
5050 "d" | "day" | "days" => Some(Self::NANOS_PER_DAY),
5051 "h" | "hr" | "hour" | "hours" => Some(Self::NANOS_PER_HOUR),
5052 "m" | "min" | "minute" | "minutes" | "t" => Some(Self::NANOS_PER_MIN),
5053 "s" | "sec" | "second" | "seconds" => Some(Self::NANOS_PER_SEC),
5054 "ms" | "milli" | "millis" | "millisecond" | "milliseconds" | "l" => {
5055 Some(Self::NANOS_PER_MILLI)
5056 }
5057 "us" | "µs" | "micro" | "micros" | "microsecond" | "microseconds" | "u" => {
5058 Some(Self::NANOS_PER_MICRO)
5059 }
5060 "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" | "n" => Some(1),
5061 "" => Some(Self::NANOS_PER_DAY),
5062 _ => None,
5063 }
5064 }
5065
5066 pub fn components(nanos: i64) -> TimedeltaComponents {
5067 if nanos == Self::NAT {
5068 return TimedeltaComponents::default();
5069 }
5070
5071 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5076 let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5077
5078 let hours = rem / Self::NANOS_PER_HOUR;
5079 let rem = rem % Self::NANOS_PER_HOUR;
5080
5081 let minutes = rem / Self::NANOS_PER_MIN;
5082 let rem = rem % Self::NANOS_PER_MIN;
5083
5084 let seconds = rem / Self::NANOS_PER_SEC;
5085 let rem = rem % Self::NANOS_PER_SEC;
5086
5087 let milliseconds = rem / Self::NANOS_PER_MILLI;
5088 let rem = rem % Self::NANOS_PER_MILLI;
5089
5090 let microseconds = rem / Self::NANOS_PER_MICRO;
5091 let nanoseconds = rem % Self::NANOS_PER_MICRO;
5092
5093 TimedeltaComponents {
5094 days,
5095 hours,
5096 minutes,
5097 seconds,
5098 milliseconds,
5099 microseconds,
5100 nanoseconds,
5101 }
5102 }
5103
5104 pub fn total_seconds(nanos: i64) -> f64 {
5105 if nanos == Self::NAT {
5106 f64::NAN
5107 } else {
5108 nanos as f64 / Self::NANOS_PER_SEC as f64
5109 }
5110 }
5111
5112 #[must_use]
5116 pub fn as_unit(nanos: i64, unit: &str) -> f64 {
5117 if nanos == Self::NAT {
5118 return f64::NAN;
5119 }
5120 let nanos_f = nanos as f64;
5121 match unit {
5122 "ns" | "nanoseconds" => nanos_f,
5123 "us" | "microseconds" => nanos_f / Self::NANOS_PER_MICRO as f64,
5124 "ms" | "milliseconds" => nanos_f / Self::NANOS_PER_MILLI as f64,
5125 "s" | "seconds" => nanos_f / Self::NANOS_PER_SEC as f64,
5126 "m" | "minutes" => nanos_f / Self::NANOS_PER_MIN as f64,
5127 "h" | "hours" => nanos_f / Self::NANOS_PER_HOUR as f64,
5128 "D" | "days" => nanos_f / Self::NANOS_PER_DAY as f64,
5129 _ => f64::NAN,
5130 }
5131 }
5132
5133 #[must_use]
5153 pub fn days(nanos: i64) -> Option<i64> {
5154 if nanos == Self::NAT {
5155 return None;
5156 }
5157 Some(nanos.div_euclid(Self::NANOS_PER_DAY))
5159 }
5160
5161 #[must_use]
5164 pub fn seconds(nanos: i64) -> Option<i64> {
5165 if nanos == Self::NAT {
5166 return None;
5167 }
5168 Some(nanos.rem_euclid(Self::NANOS_PER_DAY) / Self::NANOS_PER_SEC)
5170 }
5171
5172 #[must_use]
5175 pub fn microseconds(nanos: i64) -> Option<i64> {
5176 if nanos == Self::NAT {
5177 return None;
5178 }
5179 Some(nanos.rem_euclid(Self::NANOS_PER_SEC) / Self::NANOS_PER_MICRO)
5180 }
5181
5182 #[must_use]
5185 pub fn nanoseconds(nanos: i64) -> Option<i64> {
5186 if nanos == Self::NAT {
5187 return None;
5188 }
5189 Some(nanos.rem_euclid(Self::NANOS_PER_MICRO))
5190 }
5191
5192 #[must_use]
5198 pub const fn string_resolution(nanos: i64) -> TimedeltaStringResolution {
5199 if nanos == Self::NAT || nanos.rem_euclid(Self::NANOS_PER_DAY) == 0 {
5200 TimedeltaStringResolution::Days
5201 } else {
5202 TimedeltaStringResolution::Full
5203 }
5204 }
5205
5206 #[must_use]
5214 pub fn format_at_resolution(nanos: i64, resolution: TimedeltaStringResolution) -> String {
5215 if nanos == Self::NAT {
5216 return "NaT".to_string();
5217 }
5218 match resolution {
5219 TimedeltaStringResolution::Full => Self::format(nanos),
5220 TimedeltaStringResolution::Days => {
5223 format!("{} days", nanos.div_euclid(Self::NANOS_PER_DAY))
5224 }
5225 }
5226 }
5227
5228 pub fn format(nanos: i64) -> String {
5229 use std::fmt::Write as _;
5230
5231 if nanos == Self::NAT {
5232 return "NaT".to_string();
5233 }
5234
5235 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5241 let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5242 let hours = rem / Self::NANOS_PER_HOUR;
5243 let minutes = (rem % Self::NANOS_PER_HOUR) / Self::NANOS_PER_MIN;
5244 let seconds = (rem % Self::NANOS_PER_MIN) / Self::NANOS_PER_SEC;
5245 let frac = rem % Self::NANOS_PER_SEC;
5246
5247 let mut result = String::with_capacity(32);
5250 let _ = write!(result, "{days} days ");
5251 if days < 0 {
5253 result.push('+');
5254 }
5255 let _ = write!(result, "{hours:02}:{minutes:02}:{seconds:02}");
5256 if frac > 0 {
5257 if frac % 1_000 == 0 {
5261 let _ = write!(result, ".{:06}", frac / 1_000);
5262 } else {
5263 let _ = write!(result, ".{frac:09}");
5264 }
5265 }
5266 result
5267 }
5268
5269 pub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError> {
5286 let multiplier = Self::unit_to_nanos(unit)
5287 .ok_or_else(|| TimedeltaError::InvalidFormat(unit.to_string()))?;
5288 if value.is_nan() {
5289 return Ok(Self::NAT);
5290 }
5291 let product = value * multiplier as f64;
5292 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5293 return Err(TimedeltaError::Overflow);
5294 }
5295 Ok(product.round() as i64)
5296 }
5297
5298 pub fn try_add(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5338 if a == Self::NAT || b == Self::NAT {
5339 return Ok(Self::NAT);
5340 }
5341 a.checked_add(b).ok_or(
5342 TemporalFailure::new("Timedelta::add", PandasTemporalError::Overflow)
5343 .with_operands(a, b),
5344 )
5345 }
5346
5347 #[must_use]
5349 pub fn add(a: i64, b: i64) -> i64 {
5350 Self::try_add(a, b).unwrap_or(Self::NAT)
5351 }
5352
5353 pub fn try_sub(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5358 if a == Self::NAT || b == Self::NAT {
5359 return Ok(Self::NAT);
5360 }
5361 a.checked_sub(b).ok_or(
5362 TemporalFailure::new("Timedelta::sub", PandasTemporalError::Overflow)
5363 .with_operands(a, b),
5364 )
5365 }
5366
5367 #[must_use]
5369 pub fn sub(a: i64, b: i64) -> i64 {
5370 Self::try_sub(a, b).unwrap_or(Self::NAT)
5371 }
5372
5373 #[must_use]
5391 pub fn neg(a: i64) -> i64 {
5392 if a == Self::NAT {
5393 return Self::NAT;
5394 }
5395 a.saturating_neg()
5396 }
5397
5398 #[must_use]
5405 pub fn abs(a: i64) -> i64 {
5406 if a == Self::NAT {
5407 return Self::NAT;
5408 }
5409 a.saturating_abs()
5410 }
5411
5412 #[must_use]
5418 pub fn mul_scalar(a: i64, factor: i64) -> i64 {
5419 Self::try_mul_scalar(a, factor).unwrap_or(Self::NAT)
5420 }
5421
5422 #[must_use]
5443 pub fn mul_scalar_with_policy(a: i64, factor: i64, policy: OverflowPolicy) -> i64 {
5444 if a == Self::NAT {
5445 return Self::NAT;
5446 }
5447 if matches!(policy, OverflowPolicy::Strict) {
5448 return a.wrapping_mul(factor);
5449 }
5450 policy
5451 .resolve_recording(Self::try_mul_scalar(a, factor), Self::NAT, Self::NAT)
5452 .unwrap_or(Self::NAT)
5453 }
5454
5455 pub fn try_mul_scalar(a: i64, factor: i64) -> Result<i64, TemporalFailure> {
5463 if a == Self::NAT {
5464 return Ok(Self::NAT);
5465 }
5466 a.checked_mul(factor).ok_or(
5467 TemporalFailure::new("Timedelta::mul_scalar", PandasTemporalError::Overflow)
5468 .with_operands(a, factor),
5469 )
5470 }
5471
5472 #[must_use]
5482 pub fn div_scalar(a: i64, divisor: i64) -> i64 {
5483 Self::try_div_scalar(a, divisor).unwrap_or(Self::NAT)
5484 }
5485
5486 pub fn try_div_scalar(a: i64, divisor: i64) -> Result<i64, TemporalFailure> {
5501 if divisor == 0 {
5502 return Err(TemporalFailure::new(
5503 "Timedelta::div_scalar",
5504 PandasTemporalError::ZeroDivision,
5505 )
5506 .with_operands(a, divisor));
5507 }
5508 if a == Self::NAT {
5509 return Ok(Self::NAT);
5510 }
5511 Ok(Self::div_scalar_inner(a, divisor))
5512 }
5513
5514 fn div_scalar_inner(a: i64, divisor: i64) -> i64 {
5515 let q = a / divisor;
5520 let r = a % divisor;
5521 if r != 0 && (r < 0) != (divisor < 0) {
5525 q - 1
5526 } else {
5527 q
5528 }
5529 }
5530
5531 #[must_use]
5535 pub fn div_timedelta(a: i64, b: i64) -> f64 {
5536 if a == Self::NAT || b == Self::NAT {
5537 return f64::NAN;
5538 }
5539 (a as f64) / (b as f64)
5540 }
5541
5542 #[must_use]
5550 pub fn isoformat(nanos: i64) -> String {
5551 use std::fmt::Write as _;
5552
5553 if nanos == Self::NAT {
5554 return "NaT".to_string();
5555 }
5556
5557 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5558 let remaining = nanos.rem_euclid(Self::NANOS_PER_DAY);
5559
5560 let hours = remaining / Self::NANOS_PER_HOUR;
5561 let remaining = remaining % Self::NANOS_PER_HOUR;
5562
5563 let minutes = remaining / Self::NANOS_PER_MIN;
5564 let remaining = remaining % Self::NANOS_PER_MIN;
5565
5566 let seconds = remaining / Self::NANOS_PER_SEC;
5567 let sub_sec_nanos = remaining % Self::NANOS_PER_SEC;
5568
5569 let mut result = String::with_capacity(40);
5573 let _ = write!(result, "P{days}DT{hours}H{minutes}M{seconds}");
5575 if sub_sec_nanos != 0 {
5576 result.push('.');
5577 let _ = write!(result, "{sub_sec_nanos:09}");
5578 while result.ends_with('0') {
5579 result.pop();
5580 }
5581 }
5582 result.push('S');
5583 result
5584 }
5585
5586 #[must_use]
5590 pub fn floor(nanos: i64, freq: &str) -> i64 {
5591 if nanos == Self::NAT {
5592 return Self::NAT;
5593 }
5594 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5595 return Self::NAT;
5596 };
5597 if unit_nanos == 0 {
5598 return Self::NAT;
5599 }
5600 nanos
5601 .div_euclid(unit_nanos)
5602 .checked_mul(unit_nanos)
5603 .unwrap_or(Self::NAT)
5604 }
5605
5606 #[must_use]
5613 pub fn ceil(nanos: i64, freq: &str) -> i64 {
5614 if nanos == Self::NAT {
5615 return Self::NAT;
5616 }
5617 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5618 return Self::NAT;
5619 };
5620 if unit_nanos == 0 {
5621 return Self::NAT;
5622 }
5623 let remainder = nanos.rem_euclid(unit_nanos);
5624 if remainder == 0 {
5625 nanos
5626 } else {
5627 nanos
5628 .checked_add(unit_nanos - remainder)
5629 .unwrap_or(Self::NAT)
5630 }
5631 }
5632
5633 #[must_use]
5638 pub fn round(nanos: i64, freq: &str) -> i64 {
5639 if nanos == Self::NAT {
5640 return Self::NAT;
5641 }
5642 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5643 return Self::NAT;
5644 };
5645 if unit_nanos == 0 {
5646 return Self::NAT;
5647 }
5648 let negative = nanos < 0;
5649 let abs_nanos = nanos.saturating_abs();
5650
5651 let quotient = abs_nanos / unit_nanos;
5652 let remainder = abs_nanos % unit_nanos;
5653 let half = unit_nanos / 2;
5654
5655 let round_up = || {
5663 quotient
5664 .checked_add(1)
5665 .and_then(|q| q.checked_mul(unit_nanos))
5666 };
5667 let rounded = if remainder > half {
5668 round_up()
5669 } else if remainder < half {
5670 Some(quotient * unit_nanos)
5671 } else {
5672 if quotient % 2 == 0 {
5674 Some(quotient * unit_nanos)
5675 } else {
5676 round_up()
5677 }
5678 };
5679
5680 match rounded {
5681 Some(rounded) => {
5684 if negative {
5685 -rounded
5686 } else {
5687 rounded
5688 }
5689 }
5690 None => Self::NAT,
5691 }
5692 }
5693}
5694
5695#[derive(Debug, Clone, PartialEq, Eq, Error)]
5703pub enum TimeZoneError {
5704 #[error("'{0}'")]
5707 Unknown(String),
5708 #[error("{0}")]
5711 NonExistent(String),
5712 #[error("Cannot infer dst time from {0}, try using the 'ambiguous' argument")]
5714 Ambiguous(String),
5715}
5716
5717enum Zone {
5719 Fixed(chrono::FixedOffset),
5720 Named(chrono_tz::Tz),
5721}
5722
5723impl Zone {
5724 fn parse(tz: &str) -> Result<Self, TimeZoneError> {
5728 use chrono::Offset;
5729 let name = tz.trim();
5730 if name == "UTC" || name == "Z" {
5731 return Ok(Self::Fixed(chrono::Utc.fix()));
5732 }
5733 let offset = name
5734 .strip_prefix("UTC")
5735 .filter(|rest| rest.starts_with(['+', '-']))
5736 .unwrap_or(name);
5737 let bytes = offset.as_bytes();
5738 if bytes.len() == 6
5739 && matches!(bytes[0], b'+' | b'-')
5740 && bytes[3] == b':'
5741 && [1, 2, 4, 5].iter().all(|&i| bytes[i].is_ascii_digit())
5742 {
5743 let hours: i32 = offset[1..3].parse().unwrap_or(24);
5744 let minutes: i32 = offset[4..6].parse().unwrap_or(60);
5745 let sign = if bytes[0] == b'-' { -1 } else { 1 };
5746 return (hours <= 23 && minutes <= 59)
5747 .then(|| chrono::FixedOffset::east_opt(sign * (hours * 3_600 + minutes * 60)))
5748 .flatten()
5749 .map(Self::Fixed)
5750 .ok_or_else(|| TimeZoneError::Unknown(name.to_owned()));
5751 }
5752 name.parse::<chrono_tz::Tz>()
5753 .map(Self::Named)
5754 .map_err(|_| TimeZoneError::Unknown(name.to_owned()))
5755 }
5756
5757 fn offset_seconds(&self, utc_nanos: i64) -> i32 {
5759 use chrono::{Offset, TimeZone};
5760 match self {
5761 Self::Fixed(offset) => offset.local_minus_utc(),
5762 Self::Named(zone) => {
5763 let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5764 zone.offset_from_utc_datetime(&utc).fix().local_minus_utc()
5765 }
5766 }
5767 }
5768}
5769
5770pub fn tz_validate(tz: &str) -> Result<(), TimeZoneError> {
5772 Zone::parse(tz).map(|_| ())
5773}
5774
5775pub fn tz_canonical_name(tz: &str) -> Result<String, TimeZoneError> {
5779 Ok(match Zone::parse(tz)? {
5780 Zone::Fixed(offset) if offset.local_minus_utc() == 0 => "UTC".to_owned(),
5781 Zone::Fixed(offset) => format!("UTC{offset}"),
5782 Zone::Named(_) => tz.trim().to_owned(),
5783 })
5784}
5785
5786pub fn tz_abbreviation(tz: &str, utc_nanos: i64) -> Result<String, TimeZoneError> {
5790 use chrono::TimeZone;
5791 match Zone::parse(tz)? {
5792 Zone::Named(zone) => {
5793 let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5794 let offset = zone.offset_from_utc_datetime(&utc);
5795 Ok(chrono_tz::OffsetName::abbreviation(&offset)
5796 .map_or_else(|| tz.trim().to_owned(), str::to_owned))
5797 }
5798 Zone::Fixed(_) => tz_canonical_name(tz),
5799 }
5800}
5801
5802pub fn tz_offset_seconds(tz: &str, utc_nanos: i64) -> Result<i32, TimeZoneError> {
5806 Ok(Zone::parse(tz)?.offset_seconds(utc_nanos))
5807}
5808
5809pub fn tz_utc_to_wall_nanos(tz: &str, utc_nanos: i64) -> Result<i64, TimeZoneError> {
5812 if utc_nanos == i64::MIN {
5813 return Ok(utc_nanos);
5814 }
5815 let offset = Zone::parse(tz)?.offset_seconds(utc_nanos);
5816 Ok(utc_nanos.saturating_add(i64::from(offset) * 1_000_000_000))
5817}
5818
5819pub fn tz_wall_to_utc_nanos(tz: &str, wall_nanos: i64) -> Result<i64, TimeZoneError> {
5824 tz_wall_to_utc_nanos_with(tz, wall_nanos, AmbiguousTime::Raise, NonexistentTime::Raise)
5825}
5826
5827#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5831pub enum AmbiguousTime {
5832 Raise,
5833 Earliest,
5834 Latest,
5835 NaT,
5836}
5837
5838#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5844pub enum NonexistentTime {
5845 Raise,
5846 ShiftForward,
5847 ShiftBackward,
5848 NaT,
5849 Shift(i64),
5850}
5851
5852pub fn tz_wall_to_utc_nanos_with(
5855 tz: &str,
5856 wall_nanos: i64,
5857 ambiguous: AmbiguousTime,
5858 nonexistent: NonexistentTime,
5859) -> Result<i64, TimeZoneError> {
5860 use chrono::{LocalResult, TimeZone};
5861 if wall_nanos == i64::MIN {
5862 return Ok(wall_nanos);
5863 }
5864 let zone = Zone::parse(tz)?;
5865 let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
5866 let local = match &zone {
5867 Zone::Fixed(offset) => offset
5868 .from_local_datetime(&naive)
5869 .map(|at| at.fixed_offset()),
5870 Zone::Named(zone) => zone.from_local_datetime(&naive).map(|at| at.fixed_offset()),
5871 };
5872 let nanos_of = |at: chrono::DateTime<chrono::FixedOffset>| {
5873 at.timestamp_nanos_opt()
5874 .ok_or_else(|| TimeZoneError::NonExistent(naive.to_string()))
5875 };
5876 match local {
5877 LocalResult::Single(at) => nanos_of(at),
5878 LocalResult::Ambiguous(earliest, latest) => match ambiguous {
5879 AmbiguousTime::Raise => Err(TimeZoneError::Ambiguous(naive.to_string())),
5880 AmbiguousTime::Earliest => nanos_of(earliest),
5881 AmbiguousTime::Latest => nanos_of(latest),
5882 AmbiguousTime::NaT => Ok(i64::MIN),
5883 },
5884 LocalResult::None => match nonexistent {
5885 NonexistentTime::Raise => Err(TimeZoneError::NonExistent(naive.to_string())),
5886 NonexistentTime::NaT => Ok(i64::MIN),
5887 NonexistentTime::Shift(delta) => {
5888 let shifted = wall_nanos
5889 .checked_add(delta)
5890 .ok_or_else(|| TimeZoneError::NonExistent(naive.to_string()))?;
5891 tz_wall_to_utc_nanos_with(tz, shifted, ambiguous, NonexistentTime::Raise)
5892 }
5893 NonexistentTime::ShiftForward | NonexistentTime::ShiftBackward => {
5894 const DAY: i64 = 86_400_000_000_000;
5901 let offset_at = |utc: i64| i64::from(zone.offset_seconds(utc)) * 1_000_000_000;
5902 let before = wall_nanos.saturating_sub(offset_at(wall_nanos.saturating_sub(DAY)));
5903 let after = wall_nanos.saturating_sub(offset_at(wall_nanos.saturating_add(DAY)));
5904 let (mut low, mut high) = (before.min(after), before.max(after));
5905 let later = offset_at(high);
5906 while high - low > 1 {
5907 let middle = low + (high - low) / 2;
5908 if offset_at(middle) == later {
5909 high = middle;
5910 } else {
5911 low = middle;
5912 }
5913 }
5914 Ok(if nonexistent == NonexistentTime::ShiftForward {
5915 high
5916 } else {
5917 high - 1
5918 })
5919 }
5920 },
5921 }
5922}
5923
5924#[must_use]
5934pub fn strftime_python(wall_nanos: i64, format: &str, zone: Option<(i32, &str)>) -> String {
5935 const DAYS: [&str; 7] = [
5936 "Sunday",
5937 "Monday",
5938 "Tuesday",
5939 "Wednesday",
5940 "Thursday",
5941 "Friday",
5942 "Saturday",
5943 ];
5944 const MONTHS: [&str; 12] = [
5945 "January",
5946 "February",
5947 "March",
5948 "April",
5949 "May",
5950 "June",
5951 "July",
5952 "August",
5953 "September",
5954 "October",
5955 "November",
5956 "December",
5957 ];
5958 let total_secs = wall_nanos.div_euclid(1_000_000_000);
5961 let sub_nanos = wall_nanos.rem_euclid(1_000_000_000);
5962 let days = total_secs.div_euclid(86_400);
5963 let secs_of_day = total_secs.rem_euclid(86_400);
5964 let (year, month, day) = civil_from_days(days);
5965 let (hour, minute, second) = (
5966 secs_of_day / 3_600,
5967 (secs_of_day % 3_600) / 60,
5968 secs_of_day % 60,
5969 );
5970 let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
5971 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 };
5974 let (iso_year, iso_week) = {
5975 let week = (yday + 1 - iso_weekday + 10).div_euclid(7);
5976 if week < 1 {
5977 (year - 1, iso_weeks_in_year(year - 1))
5978 } else if week > iso_weeks_in_year(year) {
5979 (year + 1, 1)
5980 } else {
5981 (year, week)
5982 }
5983 };
5984 let month_name = MONTHS[(month as usize).saturating_sub(1) % 12];
5985 let day_name = DAYS[weekday as usize];
5986
5987 let mut out = String::with_capacity(format.len().saturating_add(16));
5988 let mut chars = format.chars().peekable();
5989 while let Some(ch) = chars.next() {
5990 if ch != '%' {
5991 out.push(ch);
5992 continue;
5993 }
5994 let flag = chars.next_if(|c| matches!(c, '-' | '_' | '0' | '^'));
5995 let Some(conversion) = chars.next() else {
5996 out.push('%');
5997 if let Some(flag) = flag {
5998 out.push(flag);
5999 }
6000 break;
6001 };
6002 let number = |value: i64, width: usize, pad: char| -> String {
6005 match flag.unwrap_or(pad) {
6006 '-' => value.to_string(),
6007 '_' | ' ' => format!("{value:>width$}"),
6008 _ => format!("{value:0width$}"),
6009 }
6010 };
6011 let text = |value: &str| -> String {
6012 if flag == Some('^') {
6013 value.to_uppercase()
6014 } else {
6015 value.to_owned()
6016 }
6017 };
6018 let piece = match conversion {
6019 'a' => text(&day_name[..3]),
6020 'A' => text(day_name),
6021 'b' | 'h' => text(&month_name[..3]),
6022 'B' => text(month_name),
6023 'c' => text(&strftime_python(wall_nanos, "%a %b %e %H:%M:%S %Y", zone)),
6024 'C' => number(year.div_euclid(100), 2, '0'),
6025 'd' => number(i64::from(day), 2, '0'),
6026 'D' | 'x' => strftime_python(wall_nanos, "%m/%d/%y", zone),
6027 'e' => number(i64::from(day), 2, ' '),
6028 'f' => number(sub_nanos / 1_000, 6, '0'),
6029 'F' => strftime_python(wall_nanos, "%Y-%m-%d", zone),
6030 'g' => number(iso_year.rem_euclid(100), 2, '0'),
6031 'G' => number(iso_year, 1, '0'),
6032 'H' => number(hour, 2, '0'),
6033 'I' => number(hour12, 2, '0'),
6034 'j' => number(yday + 1, 3, '0'),
6035 'k' => number(hour, 2, ' '),
6036 'l' => number(hour12, 2, ' '),
6037 'm' => number(i64::from(month), 2, '0'),
6038 'M' => number(minute, 2, '0'),
6039 'n' => "\n".to_owned(),
6040 'p' => text(if hour < 12 { "AM" } else { "PM" }),
6041 'P' => (if hour < 12 { "am" } else { "pm" }).to_owned(),
6042 'r' => strftime_python(wall_nanos, "%I:%M:%S %p", zone),
6043 'R' => strftime_python(wall_nanos, "%H:%M", zone),
6044 'S' => number(second, 2, '0'),
6045 't' => "\t".to_owned(),
6046 'T' | 'X' => strftime_python(wall_nanos, "%H:%M:%S", zone),
6047 'u' => number(iso_weekday, 1, '0'),
6048 'U' => number((yday + 7 - weekday).div_euclid(7), 2, '0'),
6049 'V' => number(iso_week, 2, '0'),
6050 'w' => number(weekday, 1, '0'),
6051 'W' => number(
6052 (yday + 7 - (weekday + 6).rem_euclid(7)).div_euclid(7),
6053 2,
6054 '0',
6055 ),
6056 'y' => number(year.rem_euclid(100), 2, '0'),
6057 'Y' => number(year, 1, '0'),
6058 'z' => zone.map_or_else(String::new, |(offset, _)| {
6059 let sign = if offset < 0 { '-' } else { '+' };
6060 let offset = offset.unsigned_abs();
6061 let (h, m, s) = (offset / 3_600, (offset % 3_600) / 60, offset % 60);
6062 if s == 0 {
6063 format!("{sign}{h:02}{m:02}")
6064 } else {
6065 format!("{sign}{h:02}{m:02}{s:02}")
6066 }
6067 }),
6068 'Z' => zone.map_or_else(String::new, |(_, name)| text(name)),
6069 '%' => "%".to_owned(),
6070 other => {
6071 out.push('%');
6073 if let Some(flag) = flag {
6074 out.push(flag);
6075 }
6076 out.push(other);
6077 continue;
6078 }
6079 };
6080 out.push_str(&piece);
6081 }
6082 out
6083}
6084
6085#[must_use]
6089pub fn strftime_in_zone(nanos: i64, format: &str, tz: Option<&str>) -> String {
6090 let aware = tz.and_then(|zone| {
6091 let offset = tz_offset_seconds(zone, nanos).ok()?;
6092 let name = tz_abbreviation(zone, nanos).ok()?;
6093 Some((offset, name))
6094 });
6095 match aware {
6096 Some((offset, name)) => strftime_python(
6097 nanos.saturating_add(i64::from(offset) * 1_000_000_000),
6098 format,
6099 Some((offset, &name)),
6100 ),
6101 None => strftime_python(nanos, format, None),
6102 }
6103}
6104
6105#[must_use]
6111pub fn timestamp_text(nanos: i64) -> String {
6112 let mut text = strftime_python(nanos, "%Y-%m-%d %H:%M:%S", None);
6113 let fraction = nanos.rem_euclid(1_000_000_000);
6114 if fraction % 1_000 != 0 {
6115 text.push_str(&format!(".{fraction:09}"));
6116 } else if fraction != 0 {
6117 text.push_str(&format!(".{:06}", fraction / 1_000));
6118 }
6119 text
6120}
6121
6122#[must_use]
6126pub fn timestamp_text_in_zone(nanos: i64, tz: &str) -> String {
6127 let offset = tz_offset_seconds(tz, nanos).unwrap_or(0);
6128 let mut text = timestamp_text(nanos.saturating_add(i64::from(offset) * 1_000_000_000));
6129 let sign = if offset < 0 { '-' } else { '+' };
6130 let minutes = offset.unsigned_abs() / 60;
6131 text.push_str(&format!("{sign}{:02}:{:02}", minutes / 60, minutes % 60));
6132 text
6133}
6134
6135fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
6139 let (month, day) = (i64::from(month), i64::from(day));
6140 let year = if month <= 2 { year - 1 } else { year };
6141 let era = if year >= 0 { year } else { year - 399 } / 400;
6142 let yoe = year - era * 400;
6143 let doy = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
6144 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
6145 era * 146_097 + doe - 719_468
6146}
6147
6148fn days_in_month(year: i64, month: u32) -> Option<u32> {
6157 if !(1..=12).contains(&month) {
6158 return None;
6159 }
6160 let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
6161 let days: [u32; 12] = [
6162 31,
6163 if is_leap { 29 } else { 28 },
6164 31,
6165 30,
6166 31,
6167 30,
6168 31,
6169 31,
6170 30,
6171 31,
6172 30,
6173 31,
6174 ];
6175 Some(days[(month - 1) as usize])
6176}
6177
6178fn iso_weeks_in_year(year: i64) -> i64 {
6185 fn p(y: i64) -> i64 {
6186 (y + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400)).rem_euclid(7)
6187 }
6188 if p(year) == 4 || p(year - 1) == 3 {
6189 53
6190 } else {
6191 52
6192 }
6193}
6194
6195#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
6201pub struct Timestamp {
6202 pub nanos: i64,
6204 #[serde(default, skip_serializing_if = "Option::is_none")]
6208 pub tz: Option<String>,
6209}
6210
6211#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6232pub enum TimedeltaStringResolution {
6233 Days,
6235 Full,
6237}
6238
6239#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6259pub enum DatetimeStringResolution {
6260 Date,
6262 Second,
6264 Milli,
6266 Micro,
6268 Nano,
6270}
6271
6272impl Timestamp {
6273 pub const NAT: i64 = i64::MIN;
6275
6276 #[must_use]
6279 pub const fn from_nanos(nanos: i64) -> Self {
6280 Self { nanos, tz: None }
6281 }
6282
6283 #[must_use]
6288 pub fn from_nanos_tz(nanos: i64, tz_name: impl Into<String>) -> Self {
6289 Self {
6290 nanos,
6291 tz: Some(tz_name.into()),
6292 }
6293 }
6294
6295 #[must_use]
6311 pub fn now() -> Self {
6312 use std::time::{SystemTime, UNIX_EPOCH};
6313 let duration = SystemTime::now()
6314 .duration_since(UNIX_EPOCH)
6315 .unwrap_or_default();
6316 let nanos = duration.as_nanos() as i64;
6317 Self { nanos, tz: None }
6318 }
6319
6320 #[must_use]
6322 pub fn utcnow() -> Self {
6323 Self::now()
6324 }
6325
6326 #[must_use]
6330 pub fn today() -> Self {
6331 let now = Self::now();
6332 now.normalize()
6333 }
6334
6335 #[must_use]
6337 pub const fn nat() -> Self {
6338 Self {
6339 nanos: Self::NAT,
6340 tz: None,
6341 }
6342 }
6343
6344 #[must_use]
6346 pub const fn is_nat(&self) -> bool {
6347 self.nanos == Self::NAT
6348 }
6349
6350 #[must_use]
6352 pub const fn value(&self) -> i64 {
6353 self.nanos
6354 }
6355
6356 #[must_use]
6361 pub const fn unit(&self) -> Option<&'static str> {
6362 if self.is_nat() { None } else { Some("ns") }
6363 }
6364
6365 #[must_use]
6369 pub const fn resolution(&self) -> Option<&'static str> {
6370 if self.is_nat() { None } else { Some("ns") }
6371 }
6372
6373 #[must_use]
6375 pub const fn asm8(&self) -> i64 {
6376 self.value()
6377 }
6378
6379 #[must_use]
6381 pub const fn to_datetime64(&self) -> i64 {
6382 self.value()
6383 }
6384
6385 #[must_use]
6387 pub const fn to_numpy(&self) -> i64 {
6388 self.value()
6389 }
6390
6391 pub fn timestamp(&self) -> Result<f64, TypeError> {
6397 if self.is_nat() {
6398 return Err(TypeError::ValueIsMissing {
6399 kind: NullKind::NaT,
6400 });
6401 }
6402 let seconds = self.nanos as f64 / 1_000_000_000.0;
6403 let rounded = format!("{seconds:.6}").parse().unwrap_or(seconds);
6404 Ok(rounded)
6405 }
6406
6407 #[must_use]
6415 pub fn add_timedelta(&self, td_nanos: i64) -> Self {
6416 self.try_add_timedelta(td_nanos)
6417 .unwrap_or_else(|_| Self::nat())
6418 }
6419
6420 pub fn try_add_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6431 if self.is_nat() || td_nanos == Timedelta::NAT {
6432 return Ok(Self::nat());
6433 }
6434 match self.nanos.checked_add(td_nanos) {
6435 Some(nanos) => Ok(Self {
6436 nanos,
6437 tz: self.tz.clone(),
6438 }),
6439 None => Err(TemporalFailure::new(
6443 "Timestamp::add_timedelta",
6444 PandasTemporalError::OutOfBoundsDatetime,
6445 )
6446 .with_operands(self.nanos, td_nanos)),
6447 }
6448 }
6449
6450 #[must_use]
6452 pub fn sub_timedelta(&self, td_nanos: i64) -> Self {
6453 self.try_sub_timedelta(td_nanos)
6454 .unwrap_or_else(|_| Self::nat())
6455 }
6456
6457 pub fn try_sub_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6463 if self.is_nat() || td_nanos == Timedelta::NAT {
6464 return Ok(Self::nat());
6465 }
6466 match self.nanos.checked_sub(td_nanos) {
6467 Some(nanos) => Ok(Self {
6468 nanos,
6469 tz: self.tz.clone(),
6470 }),
6471 None => Err(TemporalFailure::new(
6472 "Timestamp::sub_timedelta",
6473 PandasTemporalError::OutOfBoundsDatetime,
6474 )
6475 .with_operands(self.nanos, td_nanos)),
6476 }
6477 }
6478
6479 #[must_use]
6483 pub fn sub_timestamp(&self, other: &Self) -> i64 {
6484 self.try_sub_timestamp(other).unwrap_or(Timedelta::NAT)
6485 }
6486
6487 pub fn try_sub_timestamp(&self, other: &Self) -> Result<i64, TemporalFailure> {
6493 if self.is_nat() || other.is_nat() {
6494 return Ok(Timedelta::NAT);
6495 }
6496 self.nanos.checked_sub(other.nanos).ok_or(
6497 TemporalFailure::new(
6498 "Timestamp::sub_timestamp",
6499 PandasTemporalError::OutOfBoundsDatetime,
6500 )
6501 .with_operands(self.nanos, other.nanos),
6502 )
6503 }
6504
6505 #[must_use]
6510 pub fn semantic_eq(&self, other: &Self) -> bool {
6511 if self.is_nat() && other.is_nat() {
6512 return true;
6513 }
6514 if self.is_nat() || other.is_nat() {
6515 return false;
6516 }
6517 self.nanos == other.nanos && self.tz == other.tz
6518 }
6519
6520 #[must_use]
6533 pub fn floor_to(&self, unit_nanos: i64) -> Self {
6534 if self.is_nat() || unit_nanos <= 0 {
6535 return Self::nat();
6536 }
6537 let Some(nanos) = self.nanos.div_euclid(unit_nanos).checked_mul(unit_nanos) else {
6538 return Self::nat();
6539 };
6540 Self {
6541 nanos,
6542 tz: self.tz.clone(),
6543 }
6544 }
6545
6546 #[must_use]
6551 pub fn ceil_to(&self, unit_nanos: i64) -> Self {
6552 if self.is_nat() || unit_nanos <= 0 {
6553 return Self::nat();
6554 }
6555 let rem = self.nanos.rem_euclid(unit_nanos);
6556 let nanos = if rem == 0 {
6557 self.nanos
6558 } else {
6559 let Some(nanos) = self.nanos.checked_add(unit_nanos - rem) else {
6564 return Self::nat();
6565 };
6566 nanos
6567 };
6568 Self {
6569 nanos,
6570 tz: self.tz.clone(),
6571 }
6572 }
6573
6574 #[must_use]
6580 pub fn round_to(&self, unit_nanos: i64) -> Self {
6581 if self.is_nat() || unit_nanos <= 0 {
6582 return Self::nat();
6583 }
6584 let floor = self.nanos.div_euclid(unit_nanos);
6585 let rem = self.nanos.rem_euclid(unit_nanos);
6586 let half = unit_nanos / 2;
6587 let chosen_floor = if rem < half {
6588 floor
6589 } else if rem > half {
6590 floor + 1
6591 } else if unit_nanos % 2 != 0 {
6592 floor + 1
6594 } else {
6595 if floor % 2 == 0 { floor } else { floor + 1 }
6597 };
6598 let Some(nanos) = chosen_floor.checked_mul(unit_nanos) else {
6602 return Self::nat();
6603 };
6604 Self {
6605 nanos,
6606 tz: self.tz.clone(),
6607 }
6608 }
6609
6610 fn fixed_freq_nanos(freq: &str) -> Option<i64> {
6622 Timedelta::unit_to_nanos(freq).or_else(|| Timedelta::parse(freq).ok())
6623 }
6624
6625 #[must_use]
6629 pub fn floor_to_unit(&self, unit: &str) -> Self {
6630 match Self::fixed_freq_nanos(unit) {
6631 Some(unit_nanos) => self.floor_to(unit_nanos),
6632 None => Self::nat(),
6633 }
6634 }
6635
6636 #[must_use]
6640 pub fn ceil_to_unit(&self, unit: &str) -> Self {
6641 match Self::fixed_freq_nanos(unit) {
6642 Some(unit_nanos) => self.ceil_to(unit_nanos),
6643 None => Self::nat(),
6644 }
6645 }
6646
6647 #[must_use]
6651 pub fn round_to_unit(&self, unit: &str) -> Self {
6652 match Self::fixed_freq_nanos(unit) {
6653 Some(unit_nanos) => self.round_to(unit_nanos),
6654 None => Self::nat(),
6655 }
6656 }
6657
6658 #[must_use]
6660 pub fn floor(&self, freq: &str) -> Self {
6661 self.floor_to_unit(freq)
6662 }
6663
6664 #[must_use]
6666 pub fn ceil(&self, freq: &str) -> Self {
6667 self.ceil_to_unit(freq)
6668 }
6669
6670 #[must_use]
6672 pub fn round(&self, freq: &str) -> Self {
6673 self.round_to_unit(freq)
6674 }
6675
6676 #[must_use]
6680 pub fn year(&self) -> Option<i64> {
6681 if self.is_nat() {
6682 return None;
6683 }
6684 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6688 let days = days_since_epoch + 719_468;
6689 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6690 let doe = days - era * 146_097;
6691 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6692 let y = yoe + era * 400;
6693 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6694 let mp = (5 * doy + 2) / 153;
6695 let m = if mp < 10 { mp + 3 } else { mp - 9 };
6696 Some(if m <= 2 { y + 1 } else { y })
6697 }
6698
6699 #[must_use]
6703 pub fn month(&self) -> Option<i64> {
6704 if self.is_nat() {
6705 return None;
6706 }
6707 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6711 let days = days_since_epoch + 719_468;
6712 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6713 let doe = days - era * 146_097;
6714 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6715 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6716 let mp = (5 * doy + 2) / 153;
6717 Some(if mp < 10 { mp + 3 } else { mp - 9 })
6718 }
6719
6720 #[must_use]
6724 pub fn day(&self) -> Option<i64> {
6725 if self.is_nat() {
6726 return None;
6727 }
6728 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6732 let days = days_since_epoch + 719_468;
6733 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6734 let doe = days - era * 146_097;
6735 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6736 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6737 let mp = (5 * doy + 2) / 153;
6738 Some(doy - (153 * mp + 2) / 5 + 1)
6739 }
6740
6741 #[must_use]
6745 pub fn hour(&self) -> Option<i64> {
6746 if self.is_nat() {
6747 return None;
6748 }
6749 let secs_of_day =
6753 self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6754 Some(secs_of_day / 3600)
6755 }
6756
6757 #[must_use]
6761 pub fn minute(&self) -> Option<i64> {
6762 if self.is_nat() {
6763 return None;
6764 }
6765 let secs_of_day =
6769 self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6770 Some((secs_of_day % 3600) / 60)
6771 }
6772
6773 #[must_use]
6777 pub fn second(&self) -> Option<i64> {
6778 if self.is_nat() {
6779 return None;
6780 }
6781 let secs_of_day =
6785 self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6786 Some(secs_of_day % 60)
6787 }
6788
6789 #[must_use]
6793 pub fn microsecond(&self) -> Option<i64> {
6794 if self.is_nat() {
6795 return None;
6796 }
6797 let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
6800 Some((sub_nanos / 1000) as i64)
6801 }
6802
6803 #[must_use]
6807 pub fn nanosecond(&self) -> Option<i64> {
6808 if self.is_nat() {
6809 return None;
6810 }
6811 let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
6814 Some((sub_nanos % 1000) as i64)
6815 }
6816
6817 #[must_use]
6821 pub fn dayofweek(&self) -> Option<i64> {
6822 if self.is_nat() {
6823 return None;
6824 }
6825 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6827 let dow = ((days_since_epoch + 3) % 7 + 7) % 7;
6828 Some(dow)
6829 }
6830
6831 #[must_use]
6833 pub fn weekday(&self) -> Option<i64> {
6834 self.dayofweek()
6835 }
6836
6837 #[must_use]
6839 pub fn day_of_week(&self) -> Option<i64> {
6840 self.dayofweek()
6841 }
6842
6843 #[must_use]
6847 pub fn dayofyear(&self) -> Option<i64> {
6848 if self.is_nat() {
6849 return None;
6850 }
6851 let m = self.month()?;
6852 let d = self.day()?;
6853 let y = self.year()?;
6854 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
6855 let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
6856 let base = days_before[(m - 1) as usize] + d;
6857 if is_leap && m > 2 {
6858 Some(base + 1)
6859 } else {
6860 Some(base)
6861 }
6862 }
6863
6864 #[must_use]
6866 pub fn day_of_year(&self) -> Option<i64> {
6867 self.dayofyear()
6868 }
6869
6870 #[must_use]
6874 pub fn toordinal(&self) -> Option<i64> {
6875 if self.is_nat() {
6876 return None;
6877 }
6878 let y = self.year()?;
6879 let m = self.month()?;
6880 let d = self.day()?;
6881 let y_minus_1 = y - 1;
6885 let mut ordinal = y_minus_1 * 365 + y_minus_1 / 4 - y_minus_1 / 100 + y_minus_1 / 400;
6886 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
6887 let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
6888 ordinal += days_before[(m - 1) as usize];
6889 if is_leap && m > 2 {
6890 ordinal += 1;
6891 }
6892 ordinal += d;
6893 Some(ordinal)
6894 }
6895
6896 #[must_use]
6900 pub fn fromordinal(ordinal: i64) -> Self {
6901 if ordinal <= 0 {
6902 return Self {
6903 nanos: Self::NAT,
6904 tz: None,
6905 };
6906 }
6907 let days_since_epoch = ordinal - 719163;
6910 match days_since_epoch.checked_mul(Timedelta::NANOS_PER_DAY) {
6911 Some(nanos) => Self { nanos, tz: None },
6912 None => Self::nat(),
6913 }
6914 }
6915
6916 #[must_use]
6922 pub fn to_julian_date(&self) -> f64 {
6923 if self.is_nat() {
6924 return f64::NAN;
6925 }
6926 let ordinal = match self.toordinal() {
6930 Some(o) => o,
6931 None => return f64::NAN,
6932 };
6933 let h = self.hour().unwrap_or(0) as f64;
6935 let m = self.minute().unwrap_or(0) as f64;
6936 let s = self.second().unwrap_or(0) as f64;
6937 let us = self.microsecond().unwrap_or(0) as f64;
6938 let ns = self.nanosecond().unwrap_or(0) as f64;
6939 let frac_day =
6940 (h + m / 60.0 + s / 3600.0 + us / 3_600_000_000.0 + ns / 3_600_000_000_000.0) / 24.0;
6941 1721424.5 + ordinal as f64 + frac_day
6943 }
6944
6945 #[must_use]
6949 pub fn quarter(&self) -> Option<i64> {
6950 self.month().map(|m| (m - 1) / 3 + 1)
6951 }
6952
6953 #[must_use]
6957 pub fn weekofyear(&self) -> Option<i64> {
6958 if self.is_nat() {
6959 return None;
6960 }
6961 let doy = self.dayofyear()?;
6962 let dow = self.dayofweek()?;
6963 let year = self.year()?;
6964 let iso_dow = if dow == 6 { 7 } else { dow + 1 };
6965 let week = (doy - iso_dow + 10) / 7;
6966 if week < 1 {
6972 Some(iso_weeks_in_year(year - 1))
6973 } else if week > iso_weeks_in_year(year) {
6974 Some(1)
6975 } else {
6976 Some(week)
6977 }
6978 }
6979
6980 #[must_use]
6982 pub fn week(&self) -> Option<i64> {
6983 self.weekofyear()
6984 }
6985
6986 #[must_use]
6991 pub fn to_unit(&self, unit: &str) -> Option<i64> {
6992 if self.is_nat() {
6993 return None;
6994 }
6995 match unit {
6996 "ns" | "nanosecond" | "nanoseconds" => Some(self.nanos),
6997 "us" | "microsecond" | "microseconds" => Some(self.nanos / 1_000),
6998 "ms" | "millisecond" | "milliseconds" => Some(self.nanos / 1_000_000),
6999 "s" | "second" | "seconds" => Some(self.nanos / 1_000_000_000),
7000 _ => None,
7001 }
7002 }
7003
7004 #[must_use]
7008 pub fn is_leap_year(&self) -> Option<bool> {
7009 self.year()
7010 .map(|y| (y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
7011 }
7012
7013 #[must_use]
7017 pub fn is_month_start(&self) -> Option<bool> {
7018 self.day().map(|d| d == 1)
7019 }
7020
7021 #[must_use]
7025 pub fn is_month_end(&self) -> Option<bool> {
7026 let y = self.year()?;
7027 let m = self.month()?;
7028 let d = self.day()?;
7029 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7030 let days_in_month: [i64; 12] = [
7031 31,
7032 if is_leap { 29 } else { 28 },
7033 31,
7034 30,
7035 31,
7036 30,
7037 31,
7038 31,
7039 30,
7040 31,
7041 30,
7042 31,
7043 ];
7044 Some(d == days_in_month[(m - 1) as usize])
7045 }
7046
7047 #[must_use]
7051 pub fn is_quarter_start(&self) -> Option<bool> {
7052 let m = self.month()?;
7053 let d = self.day()?;
7054 Some(d == 1 && (m == 1 || m == 4 || m == 7 || m == 10))
7055 }
7056
7057 #[must_use]
7061 pub fn is_quarter_end(&self) -> Option<bool> {
7062 let m = self.month()?;
7063 let d = self.day()?;
7064 Some(
7065 (m == 3 && d == 31)
7066 || (m == 6 && d == 30)
7067 || (m == 9 && d == 30)
7068 || (m == 12 && d == 31),
7069 )
7070 }
7071
7072 #[must_use]
7076 pub fn is_year_start(&self) -> Option<bool> {
7077 let m = self.month()?;
7078 let d = self.day()?;
7079 Some(m == 1 && d == 1)
7080 }
7081
7082 #[must_use]
7086 pub fn is_year_end(&self) -> Option<bool> {
7087 let m = self.month()?;
7088 let d = self.day()?;
7089 Some(m == 12 && d == 31)
7090 }
7091
7092 #[must_use]
7096 pub fn days_in_month(&self) -> Option<i64> {
7097 let y = self.year()?;
7098 let m = self.month()?;
7099 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7100 let days: [i64; 12] = [
7101 31,
7102 if is_leap { 29 } else { 28 },
7103 31,
7104 30,
7105 31,
7106 30,
7107 31,
7108 31,
7109 30,
7110 31,
7111 30,
7112 31,
7113 ];
7114 Some(days[(m - 1) as usize])
7115 }
7116
7117 #[must_use]
7119 pub fn daysinmonth(&self) -> Option<i64> {
7120 self.days_in_month()
7121 }
7122
7123 #[must_use]
7125 pub fn normalize(&self) -> Self {
7126 self.floor_to(Timedelta::NANOS_PER_DAY)
7127 }
7128
7129 #[must_use]
7133 #[allow(clippy::too_many_arguments)]
7134 pub fn replace(
7135 &self,
7136 year: Option<i64>,
7137 month: Option<i64>,
7138 day: Option<i64>,
7139 hour: Option<i64>,
7140 minute: Option<i64>,
7141 second: Option<i64>,
7142 microsecond: Option<i64>,
7143 nanosecond: Option<i64>,
7144 ) -> Self {
7145 if self.is_nat() {
7146 return self.clone();
7147 }
7148 let cur_year = self.year().unwrap_or(1970);
7149 let cur_month = self.month().unwrap_or(1);
7150 let cur_day = self.day().unwrap_or(1);
7151 let cur_hour = self.hour().unwrap_or(0);
7152 let cur_minute = self.minute().unwrap_or(0);
7153 let cur_second = self.second().unwrap_or(0);
7154 let cur_micro = self.microsecond().unwrap_or(0);
7155 let cur_nano = self.nanosecond().unwrap_or(0);
7156
7157 let y = year.unwrap_or(cur_year);
7158 let mo = month.unwrap_or(cur_month);
7159 let d = day.unwrap_or(cur_day);
7160 let h = hour.unwrap_or(cur_hour);
7161 let mi = minute.unwrap_or(cur_minute);
7162 let s = second.unwrap_or(cur_second);
7163 let us = microsecond.unwrap_or(cur_micro);
7164 let ns = nanosecond.unwrap_or(cur_nano);
7165
7166 if !(1..=12).contains(&mo)
7167 || !(1..=days_in_month(y, mo as u32).unwrap_or(0) as i64).contains(&d)
7168 || !(0..=23).contains(&h)
7169 || !(0..=59).contains(&mi)
7170 || !(0..=59).contains(&s)
7171 || !(0..=999_999).contains(&us)
7172 || !(0..=999).contains(&ns)
7173 {
7174 return Self::nat();
7175 }
7176
7177 let days_from_epoch = Self::days_from_ymd(y, mo, d);
7189 let secs = h * 3600 + mi * 60 + s;
7190 let Some(total_nanos) = days_from_epoch
7191 .checked_mul(Timedelta::NANOS_PER_DAY)
7192 .and_then(|nanos| {
7193 secs.checked_mul(Timedelta::NANOS_PER_SEC)
7194 .and_then(|s_nanos| nanos.checked_add(s_nanos))
7195 })
7196 .and_then(|nanos| {
7197 us.checked_mul(Timedelta::NANOS_PER_MICRO)
7198 .and_then(|us_nanos| nanos.checked_add(us_nanos))
7199 })
7200 .and_then(|nanos| nanos.checked_add(ns))
7201 else {
7202 return Self::nat();
7203 };
7204
7205 Self {
7206 nanos: total_nanos,
7207 tz: self.tz.clone(),
7208 }
7209 }
7210
7211 fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
7212 let y = if month <= 2 { year - 1 } else { year };
7213 let era = if y >= 0 { y } else { y - 399 } / 400;
7214 let yoe = y - era * 400;
7215 let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
7216 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
7217 era * 146097 + doe - 719468
7218 }
7219
7220 #[must_use]
7224 pub fn isoformat(&self) -> String {
7225 use std::fmt::Write as _;
7226
7227 if self.is_nat() {
7228 return "NaT".to_string();
7229 }
7230 let display_nanos = self
7231 .tz
7232 .as_deref()
7233 .and_then(Self::fixed_utc_offset_seconds)
7234 .and_then(|offset| self.nanos.checked_add(offset * Timedelta::NANOS_PER_SEC))
7235 .unwrap_or(self.nanos);
7236 let days_since_epoch = display_nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7239 let nanos_of_day = display_nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7240 let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7241 let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7242
7243 let days = days_since_epoch + 719_468;
7244 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7245 let doe = days - era * 146_097;
7246 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7247 let y = yoe + era * 400;
7248 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7249 let mp = (5 * doy + 2) / 153;
7250 let d = doy - (153 * mp + 2) / 5 + 1;
7251 let m = if mp < 10 { mp + 3 } else { mp - 9 };
7252 let year = if m <= 2 { y + 1 } else { y };
7253
7254 let hour = secs_of_day / 3600;
7255 let minute = (secs_of_day % 3600) / 60;
7256 let second = secs_of_day % 60;
7257
7258 let suffix_capacity = self
7262 .tz
7263 .as_ref()
7264 .map_or(0, |tz| if tz == "UTC" { 6 } else { tz.len() + 2 });
7265 let mut result = String::with_capacity(29 + suffix_capacity);
7266 if sub_nanos == 0 {
7267 let _ = write!(
7268 result,
7269 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}"
7270 );
7271 } else if sub_nanos.is_multiple_of(1_000) {
7272 let _ = write!(
7273 result,
7274 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{:06}",
7275 sub_nanos / 1_000
7276 );
7277 } else {
7278 let _ = write!(
7279 result,
7280 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{sub_nanos:09}"
7281 );
7282 }
7283 match &self.tz {
7284 Some(tz) if tz == "UTC" => result.push_str("+00:00"),
7285 Some(tz) if Self::fixed_utc_offset_seconds(tz).is_some() => {
7286 result.push_str(tz.strip_prefix("UTC").unwrap_or(tz));
7287 }
7288 Some(tz) => {
7289 result.push('[');
7290 result.push_str(tz);
7291 result.push(']');
7292 }
7293 None => {}
7294 }
7295 result
7296 }
7297
7298 #[must_use]
7300 pub fn to_iso8601(&self) -> String {
7301 self.isoformat()
7302 }
7303
7304 #[must_use]
7313 pub const fn string_resolution(nanos: i64) -> DatetimeStringResolution {
7314 if nanos == Self::NAT {
7315 return DatetimeStringResolution::Date;
7316 }
7317 if nanos.rem_euclid(Timedelta::NANOS_PER_DAY) == 0 {
7318 DatetimeStringResolution::Date
7319 } else if nanos.rem_euclid(Timedelta::NANOS_PER_SEC) == 0 {
7320 DatetimeStringResolution::Second
7321 } else if nanos.rem_euclid(Timedelta::NANOS_PER_MILLI) == 0 {
7322 DatetimeStringResolution::Milli
7323 } else if nanos.rem_euclid(Timedelta::NANOS_PER_MICRO) == 0 {
7324 DatetimeStringResolution::Micro
7325 } else {
7326 DatetimeStringResolution::Nano
7327 }
7328 }
7329
7330 #[must_use]
7350 pub fn format_at_resolution(nanos: i64, resolution: DatetimeStringResolution) -> String {
7351 use std::fmt::Write as _;
7352
7353 if nanos == Self::NAT {
7354 return "NaT".to_string();
7355 }
7356 let days_since_epoch = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7361 let nanos_of_day = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7362 let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7363 let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC);
7364 let (year, month, day) = civil_from_days(days_since_epoch);
7367
7368 let mut result = String::with_capacity(30);
7371 let _ = write!(result, "{year:04}-{month:02}-{day:02}");
7373 if matches!(resolution, DatetimeStringResolution::Date) {
7374 return result;
7375 }
7376 let _ = write!(
7377 result,
7378 " {:02}:{:02}:{:02}",
7379 secs_of_day / 3600,
7380 (secs_of_day % 3600) / 60,
7381 secs_of_day % 60
7382 );
7383 let (fraction, width) = match resolution {
7384 DatetimeStringResolution::Date | DatetimeStringResolution::Second => return result,
7385 DatetimeStringResolution::Milli => (sub_nanos / Timedelta::NANOS_PER_MILLI, 3_usize),
7386 DatetimeStringResolution::Micro => (sub_nanos / Timedelta::NANOS_PER_MICRO, 6_usize),
7387 DatetimeStringResolution::Nano => (sub_nanos, 9_usize),
7388 };
7389 let _ = write!(result, ".{fraction:0width$}", width = width);
7390 result
7391 }
7392
7393 pub fn parse(s: &str) -> Result<Self, TypeError> {
7406 let s = s.trim();
7407
7408 if s.eq_ignore_ascii_case("nat") {
7409 return Ok(Self::nat());
7410 }
7411
7412 let Some((datetime_part, tz)) = Self::split_timezone(s) else {
7413 return Err(TypeError::ValueNotParseable {
7414 value: s.to_string(),
7415 target: "Timestamp".to_string(),
7416 });
7417 };
7418
7419 let (date_part, time_part) = if datetime_part.contains('T') {
7420 datetime_part
7421 .split_once('T')
7422 .ok_or_else(|| TypeError::ValueNotParseable {
7423 value: s.to_string(),
7424 target: "Timestamp".to_string(),
7425 })?
7426 } else if datetime_part.contains(' ')
7427 && datetime_part.chars().filter(|&c| c == ' ').count() == 1
7428 {
7429 datetime_part
7430 .split_once(' ')
7431 .ok_or_else(|| TypeError::ValueNotParseable {
7432 value: s.to_string(),
7433 target: "Timestamp".to_string(),
7434 })?
7435 } else {
7436 (datetime_part, "00:00:00")
7437 };
7438
7439 let (year, month, day) =
7440 Self::parse_date(date_part).ok_or_else(|| TypeError::ValueNotParseable {
7441 value: s.to_string(),
7442 target: "Timestamp".to_string(),
7443 })?;
7444
7445 let (hour, minute, second, nanos) =
7446 Self::parse_time(time_part).ok_or_else(|| TypeError::ValueNotParseable {
7447 value: s.to_string(),
7448 target: "Timestamp".to_string(),
7449 })?;
7450
7451 let wall_nanos = Self::ymd_hms_to_nanos(year, month, day, hour, minute, second, nanos)
7454 .ok_or_else(|| TypeError::ValueNotParseable {
7455 value: s.to_string(),
7456 target: "Timestamp".to_string(),
7457 })?;
7458 let offset = tz
7462 .as_deref()
7463 .and_then(Self::fixed_utc_offset_seconds)
7464 .unwrap_or(0);
7465 let total_nanos = offset
7466 .checked_mul(1_000_000_000)
7467 .and_then(|offset| wall_nanos.checked_sub(offset))
7468 .ok_or_else(|| TypeError::ValueNotParseable {
7469 value: s.to_string(),
7470 target: "Timestamp".to_string(),
7471 })?;
7472
7473 Ok(if let Some(tz_name) = tz {
7474 Self::from_nanos_tz(total_nanos, tz_name)
7475 } else {
7476 Self::from_nanos(total_nanos)
7477 })
7478 }
7479
7480 fn split_timezone(s: &str) -> Option<(&str, Option<String>)> {
7481 if let Some(stripped) = s.strip_suffix('Z') {
7482 Some((stripped, Some("UTC".to_string())))
7483 } else if let Some(idx) = s.rfind('+') {
7484 if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7485 Some((&s[..idx], Some(s[idx..].to_string())))
7486 } else if idx > 10 {
7487 None
7488 } else {
7489 Some((s, None))
7490 }
7491 } else if let Some(idx) = s.rfind('-') {
7492 if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7493 Some((&s[..idx], Some(s[idx..].to_string())))
7494 } else if idx > 10 {
7495 None
7496 } else {
7497 Some((s, None))
7498 }
7499 } else {
7500 Some((s, None))
7501 }
7502 }
7503
7504 fn fixed_utc_offset_seconds(tz: &str) -> Option<i64> {
7505 if tz == "UTC" {
7506 return Some(0);
7507 }
7508 let offset = tz.strip_prefix("UTC").unwrap_or(tz);
7509 if !Self::is_timezone_offset(offset) {
7510 return None;
7511 }
7512 let sign = if offset.starts_with('+') { 1 } else { -1 };
7513 let hours = offset[1..3].parse::<i64>().ok()?;
7514 let minutes = offset[4..6].parse::<i64>().ok()?;
7515 Some(sign * (hours * 3_600 + minutes * 60))
7516 }
7517
7518 fn is_timezone_offset(s: &str) -> bool {
7519 let bytes = s.as_bytes();
7520 if bytes.len() != 6 || !matches!(bytes[0], b'+' | b'-') || bytes[3] != b':' {
7521 return false;
7522 }
7523 if !bytes[1..3].iter().all(u8::is_ascii_digit)
7524 || !bytes[4..6].iter().all(u8::is_ascii_digit)
7525 {
7526 return false;
7527 }
7528 let hour = u32::from(bytes[1] - b'0') * 10 + u32::from(bytes[2] - b'0');
7529 let minute = u32::from(bytes[4] - b'0') * 10 + u32::from(bytes[5] - b'0');
7530 hour <= 23 && minute <= 59
7531 }
7532
7533 fn parse_date(s: &str) -> Option<(i64, u32, u32)> {
7534 let parts: Vec<&str> = s.split('-').collect();
7535 if parts.len() != 3 {
7536 return None;
7537 }
7538 let year: i64 = parts[0].parse().ok()?;
7539 let month: u32 = parts[1].parse().ok()?;
7540 let day: u32 = parts[2].parse().ok()?;
7541 if !(1..=days_in_month(year, month)?).contains(&day) {
7542 return None;
7543 }
7544 Some((year, month, day))
7545 }
7546
7547 fn parse_time(s: &str) -> Option<(u32, u32, u32, u64)> {
7548 let (time_str, frac_str) = match s.split_once('.') {
7549 Some((time, frac)) => (time, Some(frac)),
7550 None => (s, None),
7551 };
7552 let parts: Vec<&str> = time_str.split(':').collect();
7553 if parts.is_empty() || parts.len() > 3 {
7554 return None;
7555 }
7556 let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
7557 let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
7558 let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
7559
7560 if hour > 23 || minute > 59 || second > 59 {
7561 return None;
7562 }
7563
7564 let nanos = match frac_str {
7565 None => 0,
7566 Some(frac) => {
7567 if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
7568 return None;
7569 }
7570 let digits = frac.len().min(9);
7571 let mut nanos = 0_u64;
7572 for byte in frac.bytes().take(digits) {
7573 nanos = nanos * 10 + u64::from(byte - b'0');
7574 }
7575 for _ in digits..9 {
7576 nanos *= 10;
7577 }
7578 nanos
7579 }
7580 };
7581
7582 Some((hour, minute, second, nanos))
7583 }
7584
7585 fn ymd_hms_to_nanos(
7607 year: i64,
7608 month: u32,
7609 day: u32,
7610 hour: u32,
7611 minute: u32,
7612 second: u32,
7613 sub_nanos: u64,
7614 ) -> Option<i64> {
7615 let m = month as i64;
7616 let d = day as i64;
7617
7618 let y = if m <= 2 { year.checked_sub(1)? } else { year };
7619 let era = if y >= 0 { y } else { y.checked_sub(399)? } / 400;
7620 let yoe = y.checked_sub(era.checked_mul(400)?)?;
7621 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
7622 let doe = yoe
7623 .checked_mul(365)?
7624 .checked_add(yoe / 4 - yoe / 100)?
7625 .checked_add(doy)?;
7626 let days_since_epoch = era
7627 .checked_mul(146_097)?
7628 .checked_add(doe)?
7629 .checked_sub(719_468)?;
7630
7631 let total_seconds = days_since_epoch
7632 .checked_mul(86400)?
7633 .checked_add(i64::from(hour) * 3600)?
7634 .checked_add(i64::from(minute) * 60)?
7635 .checked_add(i64::from(second))?;
7636 total_seconds
7637 .checked_mul(Timedelta::NANOS_PER_SEC)?
7638 .checked_add(sub_nanos as i64)
7639 }
7640
7641 #[must_use]
7648 pub fn strftime(&self, format: &str) -> String {
7649 if self.is_nat() {
7650 return "NaT".to_string();
7651 }
7652 strftime_in_zone(self.nanos, format, self.tz.as_deref())
7653 }
7654
7655 #[must_use]
7659 pub fn day_name(&self) -> String {
7660 const NAMES: [&str; 7] = [
7661 "Thursday",
7662 "Friday",
7663 "Saturday",
7664 "Sunday",
7665 "Monday",
7666 "Tuesday",
7667 "Wednesday",
7668 ];
7669 if self.is_nat() {
7670 return "NaT".to_string();
7671 }
7672 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7678 let dow = ((days_since_epoch % 7) + 7) % 7;
7679 NAMES[dow as usize].to_string()
7680 }
7681
7682 #[must_use]
7686 pub fn month_name(&self) -> String {
7687 const NAMES: [&str; 12] = [
7688 "January",
7689 "February",
7690 "March",
7691 "April",
7692 "May",
7693 "June",
7694 "July",
7695 "August",
7696 "September",
7697 "October",
7698 "November",
7699 "December",
7700 ];
7701 if self.is_nat() {
7702 return "NaT".to_string();
7703 }
7704 let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7708 let days = days_since_epoch + 719_468;
7709 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7710 let doe = days - era * 146_097;
7711 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7712 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7713 let mp = (5 * doy + 2) / 153;
7714 let m = if mp < 10 { mp + 3 } else { mp - 9 };
7715 NAMES[(m - 1) as usize].to_string()
7716 }
7717
7718 #[must_use]
7723 pub fn tz_localize(&self, tz: Option<&str>) -> Self {
7724 if self.is_nat() {
7725 return Self::nat();
7726 }
7727 Self {
7728 nanos: self.nanos,
7729 tz: tz.map(String::from),
7730 }
7731 }
7732
7733 #[must_use]
7739 pub fn tz_convert(&self, tz: &str) -> Self {
7740 if self.is_nat() {
7741 return Self::nat();
7742 }
7743 Self {
7744 nanos: self.nanos,
7745 tz: Some(tz.to_string()),
7746 }
7747 }
7748
7749 #[must_use]
7754 pub fn fromtimestamp(ts: f64, tz: Option<&str>) -> Self {
7755 if ts.is_nan() || ts.is_infinite() {
7756 return Self::nat();
7757 }
7758 let nanos_f64 = ts * 1_000_000_000.0;
7759 const MAX_NANOS: f64 = i64::MAX as f64;
7761 const MIN_NANOS: f64 = i64::MIN as f64;
7762 if !(MIN_NANOS..=MAX_NANOS).contains(&nanos_f64) {
7763 return Self::nat();
7764 }
7765 Self {
7766 nanos: nanos_f64 as i64,
7767 tz: tz.map(String::from),
7768 }
7769 }
7770
7771 #[must_use]
7778 pub fn from_millis(ms: i64, tz: Option<&str>) -> Self {
7779 let Some(nanos) = ms.checked_mul(1_000_000) else {
7780 return Self::nat();
7781 };
7782 Self {
7783 nanos,
7784 tz: tz.map(String::from),
7785 }
7786 }
7787
7788 #[must_use]
7792 pub fn from_micros(us: i64, tz: Option<&str>) -> Self {
7793 let Some(nanos) = us.checked_mul(1_000) else {
7794 return Self::nat();
7795 };
7796 Self {
7797 nanos,
7798 tz: tz.map(String::from),
7799 }
7800 }
7801
7802 #[must_use]
7804 pub fn tzinfo(&self) -> Option<&str> {
7805 self.tz.as_deref()
7806 }
7807
7808 #[must_use]
7812 pub fn tzname(&self) -> Option<&str> {
7813 self.tzinfo()
7814 }
7815}
7816
7817impl std::fmt::Display for Timestamp {
7818 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7821 if self.is_nat() {
7822 return f.write_str("NaT");
7823 }
7824 match &self.tz {
7825 Some(tz) => write!(f, "Timestamp[{}, {}]", self.nanos, tz),
7826 None => write!(f, "Timestamp[{}, UTC]", self.nanos),
7827 }
7828 }
7829}
7830
7831impl PartialOrd for Timestamp {
7832 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
7837 if self.is_nat() || other.is_nat() {
7838 return None;
7839 }
7840 Some(self.nanos.cmp(&other.nanos))
7841 }
7842}
7843
7844pub fn isna(values: &[Scalar]) -> Vec<bool> {
7847 values.iter().map(Scalar::is_missing).collect()
7848}
7849
7850pub fn isnull(values: &[Scalar]) -> Vec<bool> {
7851 isna(values)
7852}
7853
7854pub fn notna(values: &[Scalar]) -> Vec<bool> {
7855 values.iter().map(|v| !v.is_missing()).collect()
7856}
7857
7858pub fn notnull(values: &[Scalar]) -> Vec<bool> {
7859 notna(values)
7860}
7861
7862pub fn count_na(values: &[Scalar]) -> usize {
7863 values.iter().filter(|v| v.is_missing()).count()
7864}
7865
7866pub fn fill_na(values: &[Scalar], fill: &Scalar) -> Vec<Scalar> {
7867 values
7868 .iter()
7869 .map(|v| {
7870 if v.is_missing() {
7871 fill.clone()
7872 } else {
7873 v.clone()
7874 }
7875 })
7876 .collect()
7877}
7878
7879pub fn dropna(values: &[Scalar]) -> Vec<Scalar> {
7880 values.iter().filter(|v| !v.is_missing()).cloned().collect()
7881}
7882
7883fn collect_finite(values: &[Scalar]) -> Vec<f64> {
7886 values
7887 .iter()
7888 .filter(|v| !v.is_missing())
7889 .filter_map(|v| v.to_f64().ok())
7890 .collect()
7891}
7892
7893fn collect_timedelta_ns(values: &[Scalar]) -> Option<(i128, usize)> {
7901 let mut sum: i128 = 0;
7902 let mut count: usize = 0;
7903 let mut saw_timedelta = false;
7904 for v in values {
7905 match v {
7906 Scalar::Timedelta64(ns) => {
7907 saw_timedelta = true;
7908 if v.is_missing() {
7909 continue;
7910 }
7911 sum += i128::from(*ns);
7912 count += 1;
7913 }
7914 _ if v.is_missing() => continue,
7915 _ => return None,
7918 }
7919 }
7920 if saw_timedelta {
7921 Some((sum, count))
7922 } else {
7923 None
7924 }
7925}
7926
7927fn timedelta_ns_to_scalar(ns: i128) -> Scalar {
7946 if ns > i128::from(i64::MAX) || ns <= i128::from(i64::MIN) {
7947 return Scalar::Timedelta64(Timedelta::NAT);
7948 }
7949 Scalar::Timedelta64(ns as i64)
7950}
7951
7952pub fn nansum(values: &[Scalar]) -> Scalar {
7953 if let Some((sum, _)) = collect_timedelta_ns(values) {
7954 return timedelta_ns_to_scalar(sum);
7955 }
7956 let mut sum = 0.0_f64;
7961 for v in values {
7962 if v.is_missing() {
7963 continue;
7964 }
7965 if let Ok(x) = v.to_f64() {
7966 sum += x;
7967 }
7968 }
7969 Scalar::Float64(sum)
7970}
7971
7972#[must_use]
8009pub fn nansum_utf8(values: &[Scalar]) -> Scalar {
8010 let mut out: Option<String> = None;
8011 for v in values {
8012 if v.is_missing() {
8013 continue;
8014 }
8015 if let Scalar::Utf8(part) = v {
8016 out.get_or_insert_with(String::new).push_str(part);
8017 }
8018 }
8019 match out {
8020 Some(joined) => Scalar::Utf8(joined),
8021 None => Scalar::Int64(0),
8023 }
8024}
8025
8026pub fn nanmean(values: &[Scalar]) -> Scalar {
8027 if let Some((sum, count)) = collect_timedelta_ns(values) {
8028 if count == 0 {
8029 return Scalar::Timedelta64(Timedelta::NAT);
8030 }
8031 return timedelta_ns_to_scalar(sum / count as i128);
8034 }
8035 if let Some((sum, count)) = collect_datetime_ns(values) {
8042 if count == 0 {
8043 return Scalar::Datetime64(Timestamp::NAT);
8044 }
8045 let mean = sum / count as i128;
8046 if mean > i128::from(i64::MAX) || mean <= i128::from(i64::MIN) {
8047 return Scalar::Datetime64(Timestamp::NAT);
8048 }
8049 return Scalar::Datetime64(mean as i64);
8050 }
8051 let mut sum = 0.0_f64;
8055 let mut count = 0usize;
8056 for v in values {
8057 if v.is_missing() {
8058 continue;
8059 }
8060 if let Ok(x) = v.to_f64() {
8061 sum += x;
8062 count += 1;
8063 }
8064 }
8065 if count == 0 {
8066 return Scalar::Null(NullKind::NaN);
8067 }
8068 Scalar::Float64(sum / count as f64)
8069}
8070
8071pub fn nanany(values: &[Scalar]) -> Scalar {
8072 for v in values {
8073 if v.is_missing() {
8074 continue;
8075 }
8076 match v {
8077 Scalar::Bool(flag) if *flag => return Scalar::Bool(true),
8078 Scalar::Int64(val) if *val != 0 => return Scalar::Bool(true),
8079 Scalar::Float64(val) if !val.is_nan() && *val != 0.0 => return Scalar::Bool(true),
8080 Scalar::Utf8(val) if !val.is_empty() => return Scalar::Bool(true),
8081 Scalar::Timedelta64(ns) if *ns != 0 => return Scalar::Bool(true),
8084 _ => continue,
8085 }
8086 }
8087 Scalar::Bool(false)
8088}
8089
8090pub fn nanall(values: &[Scalar]) -> Scalar {
8091 for v in values {
8092 if v.is_missing() {
8093 continue;
8094 }
8095 match v {
8096 Scalar::Bool(flag) if !*flag => return Scalar::Bool(false),
8097 Scalar::Int64(val) if *val == 0 => return Scalar::Bool(false),
8098 Scalar::Float64(val) if val.is_nan() || *val == 0.0 => return Scalar::Bool(false),
8099 Scalar::Utf8(val) if val.is_empty() => return Scalar::Bool(false),
8100 Scalar::Timedelta64(ns) if *ns == 0 => return Scalar::Bool(false),
8103 _ => continue,
8104 }
8105 }
8106 Scalar::Bool(true)
8107}
8108
8109pub fn nancount(values: &[Scalar]) -> Scalar {
8110 let n = values.iter().filter(|v| !v.is_missing()).count();
8111 Scalar::Int64(n as i64)
8112}
8113
8114pub fn nanmin(values: &[Scalar]) -> Scalar {
8115 let mut min: Option<&Scalar> = None;
8116 for v in values {
8117 if v.is_missing() {
8118 continue;
8119 }
8120 match (min, v) {
8121 (None, _) => min = Some(v),
8122 (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8123 if b < a {
8124 min = Some(v)
8125 }
8126 }
8127 (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8128 if *b < *a {
8129 min = Some(v)
8130 }
8131 }
8132 (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8133 if b < a {
8134 min = Some(v)
8135 }
8136 }
8137 (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8138 if b < a {
8139 min = Some(v)
8140 }
8141 }
8142 (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8147 if b < a {
8148 min = Some(v)
8149 }
8150 }
8151 (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8156 if b < a {
8157 min = Some(v)
8158 }
8159 }
8160 (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8173 if a.freq != b.freq {
8174 return Scalar::Null(NullKind::NaN);
8175 }
8176 if b.ordinal < a.ordinal {
8177 min = Some(v)
8178 }
8179 }
8180 (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8195 if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8196 return Scalar::Null(NullKind::NaN);
8197 }
8198 if (b.left, b.right) < (a.left, a.right) {
8199 min = Some(v)
8200 }
8201 }
8202 (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8203 (Ok(af), Ok(bf)) if bf < af => min = Some(v),
8204 (Ok(_), Ok(_)) => {}
8205 _ => return Scalar::Null(NullKind::NaN),
8206 },
8207 }
8208 }
8209 match min {
8210 Some(v) => v.clone(),
8211 None => Scalar::Null(NullKind::NaN),
8212 }
8213}
8214
8215pub fn nanmax(values: &[Scalar]) -> Scalar {
8216 let mut max: Option<&Scalar> = None;
8217 for v in values {
8218 if v.is_missing() {
8219 continue;
8220 }
8221 match (max, v) {
8222 (None, _) => max = Some(v),
8223 (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8224 if b > a {
8225 max = Some(v)
8226 }
8227 }
8228 (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8229 if *b > *a {
8230 max = Some(v)
8231 }
8232 }
8233 (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8234 if b > a {
8235 max = Some(v)
8236 }
8237 }
8238 (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8239 if b > a {
8240 max = Some(v)
8241 }
8242 }
8243 (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8247 if b > a {
8248 max = Some(v)
8249 }
8250 }
8251 (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8253 if b > a {
8254 max = Some(v)
8255 }
8256 }
8257 (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8259 if a.freq != b.freq {
8260 return Scalar::Null(NullKind::NaN);
8261 }
8262 if b.ordinal > a.ordinal {
8263 max = Some(v)
8264 }
8265 }
8266 (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8269 if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8270 return Scalar::Null(NullKind::NaN);
8271 }
8272 if (b.left, b.right) > (a.left, a.right) {
8273 max = Some(v)
8274 }
8275 }
8276 (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8277 (Ok(af), Ok(bf)) if bf > af => max = Some(v),
8278 (Ok(_), Ok(_)) => {}
8279 _ => return Scalar::Null(NullKind::NaN),
8280 },
8281 }
8282 }
8283 match max {
8284 Some(v) => v.clone(),
8285 None => Scalar::Null(NullKind::NaN),
8286 }
8287}
8288
8289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8301enum TemporalFamily {
8302 Timedelta,
8303 Datetime,
8304 Period(PeriodFreq),
8306}
8307
8308impl TemporalFamily {
8309 fn make(self, raw: i64) -> Scalar {
8311 match self {
8312 Self::Timedelta => Scalar::Timedelta64(raw),
8313 Self::Datetime => Scalar::Datetime64(raw),
8314 Self::Period(freq) => Scalar::Period(Period::new(raw, freq)),
8315 }
8316 }
8317
8318 fn nat(self) -> Scalar {
8320 self.make(i64::MIN)
8321 }
8322}
8323
8324fn collect_temporal_backing(values: &[Scalar]) -> Option<(Vec<f64>, TemporalFamily)> {
8339 let mut out = Vec::with_capacity(values.len());
8340 let mut family: Option<TemporalFamily> = None;
8341 for v in values {
8342 let (raw, this) = match v {
8343 Scalar::Timedelta64(ns) => (*ns, TemporalFamily::Timedelta),
8344 Scalar::Datetime64(ns) => (*ns, TemporalFamily::Datetime),
8345 Scalar::Period(p) => (p.ordinal, TemporalFamily::Period(p.freq)),
8346 _ if v.is_missing() => continue,
8347 _ => return None,
8348 };
8349 match family {
8351 Some(existing) if existing != this => return None,
8352 _ => family = Some(this),
8353 }
8354 if v.is_missing() {
8355 continue;
8356 }
8357 out.push(raw as f64);
8358 }
8359 family.map(|f| (out, f))
8360}
8361
8362fn collect_timedelta_ns_f64(values: &[Scalar]) -> Option<Vec<f64>> {
8369 match collect_temporal_backing(values) {
8370 Some((out, TemporalFamily::Timedelta)) => Some(out),
8371 _ => None,
8372 }
8373}
8374
8375fn float_ns_to_timedelta(value: f64) -> Scalar {
8377 float_ns_to_temporal(value, TemporalFamily::Timedelta)
8378}
8379
8380fn float_ns_to_temporal(value: f64, make: TemporalFamily) -> Scalar {
8383 if !value.is_finite() {
8384 return make.nat();
8385 }
8386 let clamped = value.clamp(i64::MIN as f64, i64::MAX as f64);
8387 make.make(clamped as i64)
8388}
8389
8390pub fn nanmedian(values: &[Scalar]) -> Scalar {
8391 let Some((_, make)) = collect_temporal_backing(values) else {
8405 return nanmedian_numeric(values);
8407 };
8408 let mut td: Vec<i64> = values
8409 .iter()
8410 .filter(|value| !value.is_missing())
8411 .filter_map(|value| match value {
8412 Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
8413 Scalar::Period(p) => Some(p.ordinal),
8414 _ => None,
8415 })
8416 .collect();
8417 if td.is_empty() {
8418 return nanmedian_numeric(values);
8426 }
8427 let n = td.len();
8430 let mid = n / 2;
8431 let (left, mid_ref, _right) = td.select_nth_unstable(mid);
8432 let mid_val = *mid_ref;
8433 let median_ns = if n.is_multiple_of(2) {
8434 let lower = left.iter().copied().fold(i64::MIN, i64::max);
8435 (i128::from(lower) + i128::from(mid_val)) / 2
8437 } else {
8438 i128::from(mid_val)
8439 };
8440 make.make(median_ns as i64)
8441}
8442
8443fn nanmedian_numeric(values: &[Scalar]) -> Scalar {
8447 let mut nums = collect_finite(values);
8448 if nums.is_empty() {
8449 return Scalar::Null(NullKind::NaN);
8450 }
8451 let n = nums.len();
8458 let mid = n / 2;
8459 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
8460 let (left, mid_ref, _right) = nums.select_nth_unstable_by(mid, cmp);
8461 let mid_val = *mid_ref;
8462 if n.is_multiple_of(2) {
8463 let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
8464 Scalar::Float64((lower + mid_val) / 2.0)
8465 } else {
8466 Scalar::Float64(mid_val)
8467 }
8468}
8469
8470pub fn nanvar(values: &[Scalar], ddof: usize) -> Scalar {
8471 if let Some(td) = collect_timedelta_ns_f64(values) {
8474 if td.len() <= ddof {
8475 return Scalar::Timedelta64(Timedelta::NAT);
8476 }
8477 let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8478 let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8479 return float_ns_to_timedelta(sum_sq / (td.len() - ddof) as f64);
8480 }
8481 let nums = collect_finite(values);
8482 if nums.len() <= ddof {
8483 return Scalar::Null(NullKind::NaN);
8484 }
8485 let mean: f64 = nums.iter().sum::<f64>() / nums.len() as f64;
8486 let sum_sq: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
8487 Scalar::Float64(sum_sq / (nums.len() - ddof) as f64)
8488}
8489
8490pub fn nanstd(values: &[Scalar], ddof: usize) -> Scalar {
8491 if let Some((td, family)) = collect_temporal_backing(values)
8510 && !matches!(family, TemporalFamily::Period(_))
8511 {
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 return float_ns_to_timedelta(var.sqrt());
8519 }
8520 match nanvar(values, ddof) {
8521 Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
8522 other => other,
8523 }
8524}
8525
8526pub fn nansem(values: &[Scalar], ddof: usize) -> Scalar {
8532 if let Some(td) = collect_timedelta_ns_f64(values) {
8534 if td.len() <= ddof {
8535 return Scalar::Timedelta64(Timedelta::NAT);
8536 }
8537 let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8538 let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8539 let var = sum_sq / (td.len() - ddof) as f64;
8540 let std = var.sqrt();
8541 return float_ns_to_timedelta(std / (td.len() as f64).sqrt());
8542 }
8543 let nums = collect_finite(values);
8544 if nums.len() <= ddof {
8545 return Scalar::Null(NullKind::NaN);
8546 }
8547 let n = nums.len();
8548 let mean = nums.iter().sum::<f64>() / n as f64;
8549 let sum_sq = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
8550 let var = sum_sq / (n - ddof) as f64;
8551 let std = var.sqrt();
8552 Scalar::Float64(std / (n as f64).sqrt())
8553}
8554
8555pub fn nansem_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8561 if collect_timedelta_ns_f64(values).is_some() {
8562 return nansem(values, ddof);
8563 }
8564 grouped_moments(values)
8565 .sem(ddof)
8566 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8567}
8568
8569#[derive(Clone, Copy, Debug, Default, PartialEq)]
8576pub struct KahanSum {
8577 sum: f64,
8578 compensation: f64,
8579}
8580
8581impl KahanSum {
8582 #[inline]
8584 pub fn add(&mut self, value: f64) {
8585 let y = value - self.compensation;
8586 let t = self.sum + y;
8587 self.compensation = t - self.sum - y;
8588 if self.compensation.is_nan() {
8589 self.compensation = 0.0;
8590 }
8591 self.sum = t;
8592 }
8593
8594 #[inline]
8596 #[must_use]
8597 pub fn sum(self) -> f64 {
8598 self.sum
8599 }
8600}
8601
8602#[derive(Clone, Copy, Debug, Default, PartialEq)]
8609pub struct WelfordVar {
8610 count: usize,
8611 mean: f64,
8612 m2: f64,
8613}
8614
8615impl WelfordVar {
8616 #[inline]
8618 pub fn add(&mut self, value: f64) {
8619 self.count += 1;
8620 let old = self.mean;
8621 self.mean += (value - old) / self.count as f64;
8622 self.m2 += (value - self.mean) * (value - old);
8623 }
8624
8625 #[must_use]
8627 pub fn count(self) -> usize {
8628 self.count
8629 }
8630
8631 #[must_use]
8633 pub fn var(self, ddof: usize) -> Option<f64> {
8634 (self.count > ddof).then(|| self.m2 / (self.count - ddof) as f64)
8635 }
8636
8637 #[must_use]
8639 pub fn std(self, ddof: usize) -> Option<f64> {
8640 self.var(ddof).map(f64::sqrt)
8641 }
8642
8643 #[must_use]
8645 pub fn sem(self, ddof: usize) -> Option<f64> {
8646 self.var(ddof).map(|var| (var / self.count as f64).sqrt())
8647 }
8648}
8649
8650#[derive(Clone, Copy, Debug, Default, PartialEq)]
8658pub struct SkewMoments {
8659 count: usize,
8660 m1: f64,
8661 m2: f64,
8662 m3: f64,
8663}
8664
8665impl SkewMoments {
8666 #[inline]
8668 pub fn add(&mut self, value: f64) {
8669 let before = self.count as f64;
8670 self.count += 1;
8671 let n = self.count as f64;
8672 let delta = value - self.m1;
8673 let delta_n = delta / n;
8674 let term1 = delta * delta_n * before;
8675 self.m1 += delta_n;
8676 self.m3 += term1 * delta_n * (n - 2.0) - 3.0 * delta_n * self.m2;
8677 self.m2 += term1;
8678 }
8679
8680 #[must_use]
8682 pub fn count(self) -> usize {
8683 self.count
8684 }
8685
8686 #[must_use]
8688 pub fn skew(self) -> Option<f64> {
8689 if self.count < 3 {
8690 return None;
8691 }
8692 if self.m2 == 0.0 {
8693 return Some(0.0);
8694 }
8695 let n = self.count as f64;
8696 let half = std::hint::black_box(0.5);
8700 Some((n * (n - 1.0).powf(half) / (n - 2.0)) * (self.m3 / self.m2.powf(1.5)))
8701 }
8702}
8703
8704#[must_use]
8707pub fn nanskew_grouped(values: &[Scalar]) -> Scalar {
8708 let mut moments = SkewMoments::default();
8709 for value in values {
8710 if value.is_missing() {
8711 continue;
8712 }
8713 if let Ok(x) = value.to_f64() {
8714 moments.add(x);
8715 }
8716 }
8717 moments
8718 .skew()
8719 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8720}
8721
8722fn grouped_moments(values: &[Scalar]) -> WelfordVar {
8724 let mut moments = WelfordVar::default();
8725 for value in values {
8726 if value.is_missing() {
8727 continue;
8728 }
8729 if let Ok(x) = value.to_f64() {
8730 moments.add(x);
8731 }
8732 }
8733 moments
8734}
8735
8736#[must_use]
8740pub fn nansum_grouped(values: &[Scalar]) -> Scalar {
8741 if collect_timedelta_ns(values).is_some() {
8742 return nansum(values);
8743 }
8744 let mut sum = KahanSum::default();
8745 for value in values {
8746 if value.is_missing() {
8747 continue;
8748 }
8749 if let Ok(x) = value.to_f64() {
8750 sum.add(x);
8751 }
8752 }
8753 Scalar::Float64(sum.sum())
8754}
8755
8756#[must_use]
8759pub fn nanmean_grouped(values: &[Scalar]) -> Scalar {
8760 if collect_timedelta_ns(values).is_some() || collect_datetime_ns(values).is_some() {
8761 return nanmean(values);
8762 }
8763 let mut sum = KahanSum::default();
8764 let mut count = 0_usize;
8765 for value in values {
8766 if value.is_missing() {
8767 continue;
8768 }
8769 if let Ok(x) = value.to_f64() {
8770 sum.add(x);
8771 count += 1;
8772 }
8773 }
8774 if count == 0 {
8775 return Scalar::Null(NullKind::NaN);
8776 }
8777 Scalar::Float64(sum.sum() / count as f64)
8778}
8779
8780#[must_use]
8783pub fn nanvar_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8784 if collect_timedelta_ns_f64(values).is_some() {
8785 return nanvar(values, ddof);
8786 }
8787 grouped_moments(values)
8788 .var(ddof)
8789 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8790}
8791
8792#[must_use]
8795pub fn nanstd_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8796 if collect_temporal_backing(values).is_some() {
8797 return nanstd(values, ddof);
8798 }
8799 grouped_moments(values)
8800 .std(ddof)
8801 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8802}
8803
8804pub fn nanptp(values: &[Scalar]) -> Scalar {
8809 if is_datetime_input(values) {
8817 let (mut lo, mut hi) = (i64::MAX, i64::MIN);
8818 for value in values {
8819 if value.is_missing() {
8820 continue;
8821 }
8822 if let Scalar::Datetime64(ns) = value {
8823 lo = lo.min(*ns);
8824 hi = hi.max(*ns);
8825 }
8826 }
8827 return timedelta_ns_to_scalar(i128::from(hi) - i128::from(lo));
8828 }
8829 let (mut td_lo, mut td_hi) = (i64::MAX, i64::MIN);
8833 let mut saw_timedelta = false;
8834 let mut all_timedelta = true;
8835 for value in values {
8836 if value.is_missing() {
8837 continue;
8838 }
8839 match value {
8840 Scalar::Timedelta64(ns) => {
8841 saw_timedelta = true;
8842 td_lo = td_lo.min(*ns);
8843 td_hi = td_hi.max(*ns);
8844 }
8845 _ => {
8846 all_timedelta = false;
8847 break;
8848 }
8849 }
8850 }
8851 if all_timedelta && saw_timedelta {
8852 return timedelta_ns_to_scalar(i128::from(td_hi) - i128::from(td_lo));
8856 }
8857 let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
8862 let mut seen = false;
8863 for v in values {
8864 if v.is_missing() {
8865 continue;
8866 }
8867 if let Ok(x) = v.to_f64() {
8868 seen = true;
8869 if x < lo {
8870 lo = x;
8871 }
8872 if x > hi {
8873 hi = x;
8874 }
8875 }
8876 }
8877 if !seen {
8878 return Scalar::Null(NullKind::NaN);
8879 }
8880 Scalar::Float64(hi - lo)
8881}
8882
8883pub fn nanskew(values: &[Scalar]) -> Scalar {
8889 let nums = collect_finite(values);
8890 let n = nums.len() as f64;
8891 if n < 3.0 {
8892 return Scalar::Null(NullKind::NaN);
8893 }
8894 let mean = nums.iter().sum::<f64>() / n;
8895 let (mut m2, mut m3) = (0.0_f64, 0.0_f64);
8899 for x in nums {
8900 let delta = x - mean;
8901 let d2 = delta * delta;
8907 m2 += d2;
8908 m3 += d2 * delta;
8909 }
8910 let s2 = m2 / (n - 1.0);
8911 if s2 == 0.0 {
8912 return Scalar::Float64(0.0);
8913 }
8914 let s3 = s2.powf(1.5);
8915 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
8916}
8917
8918pub fn nankurt(values: &[Scalar]) -> Scalar {
8925 let nums = collect_finite(values);
8926 let n = nums.len() as f64;
8927 if n < 4.0 {
8928 return Scalar::Null(NullKind::NaN);
8929 }
8930 let mean = nums.iter().sum::<f64>() / n;
8931 let (mut m2, mut m4) = (0.0_f64, 0.0_f64);
8935 for x in nums {
8936 let delta = x - mean;
8937 let d2 = delta * delta;
8940 m2 += d2;
8941 m4 += d2 * d2;
8942 }
8943 let s2 = m2 / (n - 1.0);
8944 if s2 == 0.0 {
8945 return Scalar::Float64(0.0);
8946 }
8947 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
8948 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
8949 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
8950}
8951
8952pub fn nanprod(values: &[Scalar]) -> Scalar {
8954 if is_timedelta_input(values) {
8961 return Scalar::Null(NullKind::NaN);
8962 }
8963 let mut prod = 1.0_f64;
8968 for v in values {
8969 if v.is_missing() {
8970 continue;
8971 }
8972 if let Ok(x) = v.to_f64() {
8973 prod *= x;
8974 }
8975 }
8976 Scalar::Float64(prod)
8977}
8978
8979fn is_timedelta_input(values: &[Scalar]) -> bool {
8985 let mut saw_td = false;
8986 for v in values {
8987 if v.is_missing() {
8988 continue;
8989 }
8990 match v {
8991 Scalar::Timedelta64(_) => saw_td = true,
8992 _ => return false,
8993 }
8994 }
8995 saw_td
8996}
8997
8998fn collect_datetime_ns(values: &[Scalar]) -> Option<(i128, usize)> {
9008 let mut sum: i128 = 0;
9009 let mut count: usize = 0;
9010 let mut saw_datetime = false;
9011 for v in values {
9012 match v {
9013 Scalar::Datetime64(ns) => {
9014 saw_datetime = true;
9015 if v.is_missing() {
9016 continue;
9017 }
9018 sum += i128::from(*ns);
9019 count += 1;
9020 }
9021 _ if v.is_missing() => continue,
9022 _ => return None,
9023 }
9024 }
9025 if saw_datetime {
9026 Some((sum, count))
9027 } else {
9028 None
9029 }
9030}
9031
9032fn is_datetime_input(values: &[Scalar]) -> bool {
9039 let mut saw_dt = false;
9040 for v in values {
9041 if v.is_missing() {
9042 continue;
9043 }
9044 match v {
9045 Scalar::Datetime64(_) => saw_dt = true,
9046 _ => return false,
9047 }
9048 }
9049 saw_dt
9050}
9051
9052fn is_int64_input(values: &[Scalar]) -> bool {
9054 let mut saw_int = false;
9055 for value in values {
9056 if value.is_missing() {
9057 continue;
9058 }
9059 match value {
9060 Scalar::Int64(_) => saw_int = true,
9061 _ => return false,
9062 }
9063 }
9064 saw_int
9065}
9066
9067fn is_interval_input(values: &[Scalar]) -> bool {
9070 let mut saw_interval = false;
9071 for v in values {
9072 if v.is_missing() {
9073 continue;
9074 }
9075 match v {
9076 Scalar::Interval(_) => saw_interval = true,
9077 _ => return false,
9078 }
9079 }
9080 saw_interval
9081}
9082
9083fn nanarg_interval(values: &[Scalar], find_max: bool) -> Option<usize> {
9095 let mut best: Option<(usize, (f64, f64))> = None;
9096 for (index, value) in values.iter().enumerate() {
9097 if value.is_missing() {
9098 continue;
9099 }
9100 let Scalar::Interval(iv) = value else {
9101 continue;
9102 };
9103 if iv.left.is_nan() || iv.right.is_nan() {
9104 return None;
9105 }
9106 let key = (iv.left, iv.right);
9107 match best {
9108 None => best = Some((index, key)),
9109 Some((_, current)) if (find_max && key > current) || (!find_max && key < current) => {
9112 best = Some((index, key));
9113 }
9114 _ => {}
9115 }
9116 }
9117 best.map(|(index, _)| index)
9118}
9119
9120fn nanarg_i64(values: &[Scalar], find_max: bool) -> Option<usize> {
9121 let mut best: Option<(usize, i64)> = None;
9122 for (index, value) in values.iter().enumerate() {
9123 if value.is_missing() {
9124 continue;
9125 }
9126 let candidate = match value {
9135 Scalar::Int64(raw) | Scalar::Timedelta64(raw) | Scalar::Datetime64(raw) => raw,
9136 Scalar::Period(p) => &p.ordinal,
9137 _ => continue,
9138 };
9139 match best {
9140 None => best = Some((index, *candidate)),
9141 Some((_, current))
9142 if (find_max && *candidate > current) || (!find_max && *candidate < current) =>
9143 {
9144 best = Some((index, *candidate));
9145 }
9146 _ => {}
9147 }
9148 }
9149 best.map(|(index, _)| index)
9150}
9151
9152fn timedelta_cumulative<F>(values: &[Scalar], init: i128, mut step: F) -> Vec<Scalar>
9157where
9158 F: FnMut(i128, i128) -> i128,
9159{
9160 let mut out = Vec::with_capacity(values.len());
9161 let mut running: i128 = init;
9162 for v in values {
9163 if v.is_missing() {
9164 out.push(Scalar::Null(NullKind::NaT));
9165 continue;
9166 }
9167 if let Scalar::Timedelta64(ns) = v {
9168 running = step(running, i128::from(*ns));
9175 out.push(timedelta_ns_to_scalar(running));
9176 } else {
9177 out.push(Scalar::Null(NullKind::NaT));
9178 }
9179 }
9180 out
9181}
9182
9183fn timedelta_cumulative_extrema<F>(
9191 values: &[Scalar],
9192 sentinel: i64,
9193 make: TemporalFamily,
9194 mut step: F,
9195) -> Vec<Scalar>
9196where
9197 F: FnMut(i64, i64) -> i64,
9198{
9199 let mut out = Vec::with_capacity(values.len());
9200 let mut running: Option<i64> = None;
9201 for v in values {
9202 if v.is_missing() {
9203 out.push(Scalar::Null(NullKind::NaT));
9204 continue;
9205 }
9206 let raw = match v {
9208 Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
9209 Scalar::Period(p) => Some(p.ordinal),
9210 _ => None,
9211 };
9212 if let Some(ns) = raw.as_ref() {
9213 let new_val = match running {
9214 Some(prev) => step(prev, *ns),
9215 None => *ns,
9216 };
9217 running = Some(new_val);
9218 out.push(make.make(new_val));
9219 } else {
9220 out.push(Scalar::Null(NullKind::NaT));
9221 }
9222 }
9223 let _ = sentinel; out
9225}
9226
9227#[must_use]
9248pub fn nancumsum_with_policy(values: &[Scalar], policy: OverflowPolicy) -> Vec<Scalar> {
9249 if !matches!(policy, OverflowPolicy::Strict) || !is_timedelta_input(values) {
9250 return nancumsum(values);
9251 }
9252 let mut out = Vec::with_capacity(values.len());
9253 let mut running: i64 = 0;
9254 for value in values {
9255 if value.is_missing() {
9256 out.push(Scalar::Null(NullKind::NaT));
9257 continue;
9258 }
9259 if let Scalar::Timedelta64(ns) = value {
9260 running = running.wrapping_add(*ns);
9263 out.push(Scalar::Timedelta64(running));
9264 } else {
9265 out.push(Scalar::Null(NullKind::NaT));
9266 }
9267 }
9268 out
9269}
9270
9271pub fn nancumsum(values: &[Scalar]) -> Vec<Scalar> {
9272 if is_timedelta_input(values) {
9276 return timedelta_cumulative(values, 0_i128, |acc, x| acc.saturating_add(x));
9277 }
9278 let mut out = Vec::with_capacity(values.len());
9279 let mut running = 0.0_f64;
9280 for v in values {
9281 if v.is_missing() {
9282 out.push(Scalar::Null(NullKind::NaN));
9283 continue;
9284 }
9285 match v.to_f64() {
9286 Ok(x) if !x.is_nan() => {
9287 running += x;
9288 out.push(Scalar::Float64(running));
9289 }
9290 _ => out.push(Scalar::Null(NullKind::NaN)),
9291 }
9292 }
9293 out
9294}
9295
9296pub fn nancumprod(values: &[Scalar]) -> Vec<Scalar> {
9301 let mut out = Vec::with_capacity(values.len());
9302 let mut running = 1.0_f64;
9303 for v in values {
9304 if v.is_missing() {
9305 out.push(Scalar::Null(NullKind::NaN));
9306 continue;
9307 }
9308 match v.to_f64() {
9309 Ok(x) if !x.is_nan() => {
9310 running *= x;
9311 out.push(Scalar::Float64(running));
9312 }
9313 _ => out.push(Scalar::Null(NullKind::NaN)),
9314 }
9315 }
9316 out
9317}
9318
9319pub fn nancummax(values: &[Scalar]) -> Vec<Scalar> {
9325 if let Some((_, family)) = collect_temporal_backing(values) {
9331 return timedelta_cumulative_extrema(values, i64::MAX, family, |acc, x| acc.max(x));
9332 }
9333 let mut out = Vec::with_capacity(values.len());
9334 let mut running: Option<f64> = None;
9335 for v in values {
9336 if v.is_missing() {
9337 out.push(Scalar::Null(NullKind::NaN));
9338 continue;
9339 }
9340 match v.to_f64() {
9341 Ok(x) if !x.is_nan() => {
9342 let new_val = match running {
9343 Some(prev) => prev.max(x),
9344 None => x,
9345 };
9346 running = Some(new_val);
9347 out.push(Scalar::Float64(new_val));
9348 }
9349 _ => out.push(Scalar::Null(NullKind::NaN)),
9350 }
9351 }
9352 out
9353}
9354
9355pub fn nancummin(values: &[Scalar]) -> Vec<Scalar> {
9359 if is_timedelta_input(values) {
9361 return timedelta_cumulative_extrema(
9362 values,
9363 i64::MIN,
9364 TemporalFamily::Timedelta,
9365 |acc, x| acc.min(x),
9366 );
9367 }
9368 if let Some((_, family)) = collect_temporal_backing(values) {
9370 return timedelta_cumulative_extrema(values, i64::MIN, family, |acc, x| acc.min(x));
9371 }
9372 let mut out = Vec::with_capacity(values.len());
9373 let mut running: Option<f64> = None;
9374 for v in values {
9375 if v.is_missing() {
9376 out.push(Scalar::Null(NullKind::NaN));
9377 continue;
9378 }
9379 match v.to_f64() {
9380 Ok(x) if !x.is_nan() => {
9381 let new_val = match running {
9382 Some(prev) => prev.min(x),
9383 None => x,
9384 };
9385 running = Some(new_val);
9386 out.push(Scalar::Float64(new_val));
9387 }
9388 _ => out.push(Scalar::Null(NullKind::NaN)),
9389 }
9390 }
9391 out
9392}
9393
9394pub fn nanquantile(values: &[Scalar], q: f64) -> Scalar {
9400 if !(0.0..=1.0).contains(&q) {
9401 return Scalar::Null(NullKind::NaN);
9402 }
9403 if let Some((mut td, make)) = collect_temporal_backing(values) {
9406 if td.is_empty() {
9407 return make.nat();
9408 }
9409 let n = td.len();
9410 if n == 1 {
9411 return float_ns_to_temporal(td[0], make);
9412 }
9413 let pos = q * (n - 1) as f64;
9414 let lo = pos.floor() as usize;
9415 let hi = pos.ceil() as usize;
9416 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9420 let (_left, lo_ref, right) = td.select_nth_unstable_by(lo, cmp);
9421 let lo_val = *lo_ref;
9422 let ns = if lo == hi {
9423 lo_val
9424 } else {
9425 let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9426 let weight = pos - lo as f64;
9427 lo_val + (hi_val - lo_val) * weight
9428 };
9429 return float_ns_to_temporal(ns, make);
9430 }
9431 let mut nums = collect_finite(values);
9432 if nums.is_empty() {
9433 return Scalar::Null(NullKind::NaN);
9434 }
9435 let n = nums.len();
9436 if n == 1 {
9437 return Scalar::Float64(nums[0]);
9438 }
9439 let pos = q * (n - 1) as f64;
9440 let lo = pos.floor() as usize;
9441 let hi = pos.ceil() as usize;
9442 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9447 let (_left, lo_ref, right) = nums.select_nth_unstable_by(lo, cmp);
9448 let lo_val = *lo_ref;
9449 if lo == hi {
9450 return Scalar::Float64(lo_val);
9451 }
9452 let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9453 let weight = pos - lo as f64;
9454 Scalar::Float64(lo_val + (hi_val - lo_val) * weight)
9455}
9456
9457pub fn nanargmax(values: &[Scalar]) -> Option<usize> {
9462 if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9467 return nanarg_i64(values, true);
9468 }
9469 if is_interval_input(values) {
9473 return nanarg_interval(values, true);
9474 }
9475 let mut best: Option<(usize, f64)> = None;
9476 for (i, v) in values.iter().enumerate() {
9477 if v.is_missing() {
9478 continue;
9479 }
9480 if let Ok(x) = v.to_f64() {
9481 if x.is_nan() {
9482 continue;
9483 }
9484 match best {
9485 None => best = Some((i, x)),
9486 Some((_, cur)) if x > cur => best = Some((i, x)),
9487 _ => {}
9488 }
9489 }
9490 }
9491 best.map(|(i, _)| i)
9492}
9493
9494pub fn nanargmin(values: &[Scalar]) -> Option<usize> {
9498 if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9501 return nanarg_i64(values, false);
9502 }
9503 if is_interval_input(values) {
9505 return nanarg_interval(values, false);
9506 }
9507 let mut best: Option<(usize, f64)> = None;
9508 for (i, v) in values.iter().enumerate() {
9509 if v.is_missing() {
9510 continue;
9511 }
9512 if let Ok(x) = v.to_f64() {
9513 if x.is_nan() {
9514 continue;
9515 }
9516 match best {
9517 None => best = Some((i, x)),
9518 Some((_, cur)) if x < cur => best = Some((i, x)),
9519 _ => {}
9520 }
9521 }
9522 }
9523 best.map(|(i, _)| i)
9524}
9525
9526pub fn nannunique(values: &[Scalar]) -> Scalar {
9528 use rustc_hash::FxHashSet;
9529 #[derive(Hash, PartialEq, Eq)]
9530 enum ScalarKey<'a> {
9531 Bool(bool),
9532 Int64(i64),
9533 FloatBits(u64),
9534 Utf8(&'a str),
9535 Timedelta64(i64),
9536 Datetime64(i64),
9537 Period(i64, PeriodFreq),
9538 Interval(u64, u64, IntervalClosed),
9539 Object(String),
9542 }
9543
9544 let mut seen = FxHashSet::default();
9545 for val in values {
9546 if val.is_missing() {
9547 continue;
9548 }
9549 let key = match val {
9550 Scalar::Bool(v) => ScalarKey::Bool(*v),
9551 Scalar::Int64(v) => ScalarKey::Int64(*v),
9552 Scalar::Float64(v) => {
9553 let normalized = if *v == 0.0 { 0.0 } else { *v };
9554 ScalarKey::FloatBits(normalized.to_bits())
9555 }
9556 Scalar::Utf8(v) => ScalarKey::Utf8(v.as_str()),
9557 Scalar::Timedelta64(v) => ScalarKey::Timedelta64(*v),
9558 Scalar::Datetime64(v) => ScalarKey::Datetime64(*v),
9559 Scalar::Period(p) => ScalarKey::Period(p.ordinal, p.freq),
9560 Scalar::Interval(v) => ScalarKey::Interval(
9561 normalized_float_bits(v.left),
9562 normalized_float_bits(v.right),
9563 v.closed,
9564 ),
9565 Scalar::Object(object) => ScalarKey::Object(object.repr()),
9566 Scalar::Null(_) => continue,
9567 };
9568 seen.insert(key);
9569 }
9570 Scalar::Int64(seen.len() as i64)
9571}
9572
9573fn normalized_float_bits(value: f64) -> u64 {
9574 let normalized = if value == 0.0 { 0.0 } else { value };
9575 normalized.to_bits()
9576}
9577
9578#[derive(
9598 Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
9599)]
9600#[serde(rename_all = "snake_case")]
9601#[non_exhaustive]
9602pub enum IntervalClosed {
9603 Left,
9605 #[default]
9607 Right,
9608 Both,
9610 Neither,
9612}
9613
9614impl IntervalClosed {
9615 #[must_use]
9617 pub fn left_closed(self) -> bool {
9618 matches!(self, Self::Left | Self::Both)
9619 }
9620
9621 #[must_use]
9623 pub fn right_closed(self) -> bool {
9624 matches!(self, Self::Right | Self::Both)
9625 }
9626}
9627
9628impl std::fmt::Display for IntervalClosed {
9629 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9630 match self {
9631 Self::Left => write!(f, "left"),
9632 Self::Right => write!(f, "right"),
9633 Self::Both => write!(f, "both"),
9634 Self::Neither => write!(f, "neither"),
9635 }
9636 }
9637}
9638
9639#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
9644#[serde(rename_all = "snake_case")]
9645pub enum IntervalSubtype {
9646 #[default]
9647 Float64,
9648 Int64,
9649}
9650
9651impl IntervalSubtype {
9652 #[must_use]
9654 pub const fn is_float(&self) -> bool {
9655 matches!(self, Self::Float64)
9656 }
9657
9658 #[must_use]
9660 pub const fn name(&self) -> &'static str {
9661 match self {
9662 Self::Float64 => "float64",
9663 Self::Int64 => "int64",
9664 }
9665 }
9666}
9667
9668#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
9675pub struct Interval {
9676 pub left: f64,
9677 pub right: f64,
9678 #[serde(default)]
9679 pub closed: IntervalClosed,
9680 #[serde(default, skip_serializing_if = "IntervalSubtype::is_float")]
9682 pub subtype: IntervalSubtype,
9683}
9684
9685impl PartialEq for Interval {
9686 fn eq(&self, other: &Self) -> bool {
9687 self.left == other.left && self.right == other.right && self.closed == other.closed
9688 }
9689}
9690
9691impl Eq for Interval {}
9695
9696impl Interval {
9697 fn endpoint_key(value: f64) -> f64 {
9699 if value == 0.0 { 0.0 } else { value }
9700 }
9701}
9702
9703impl std::hash::Hash for Interval {
9706 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
9707 Self::endpoint_key(self.left).to_bits().hash(state);
9708 Self::endpoint_key(self.right).to_bits().hash(state);
9709 self.closed.hash(state);
9710 }
9711}
9712
9713impl Ord for Interval {
9716 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
9717 Self::endpoint_key(self.left)
9718 .total_cmp(&Self::endpoint_key(other.left))
9719 .then_with(|| {
9720 Self::endpoint_key(self.right).total_cmp(&Self::endpoint_key(other.right))
9721 })
9722 .then_with(|| self.closed.cmp(&other.closed))
9723 }
9724}
9725
9726impl PartialOrd for Interval {
9727 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
9728 Some(self.cmp(other))
9729 }
9730}
9731
9732impl Interval {
9733 #[must_use]
9736 pub const fn new(left: f64, right: f64, closed: IntervalClosed) -> Self {
9737 Self {
9738 left,
9739 right,
9740 closed,
9741 subtype: IntervalSubtype::Float64,
9742 }
9743 }
9744
9745 #[must_use]
9748 pub fn with_int_endpoints(self) -> Self {
9749 if self.left.fract() == 0.0 && self.right.fract() == 0.0 {
9750 Self {
9751 subtype: IntervalSubtype::Int64,
9752 ..self
9753 }
9754 } else {
9755 self
9756 }
9757 }
9758
9759 #[must_use]
9761 pub fn length(&self) -> f64 {
9762 self.right - self.left
9763 }
9764
9765 #[must_use]
9767 pub fn mid(&self) -> f64 {
9768 (self.left + self.right) / 2.0
9769 }
9770
9771 #[must_use]
9774 pub fn is_empty(&self) -> bool {
9775 self.left == self.right && !matches!(self.closed, IntervalClosed::Both)
9776 }
9777
9778 #[must_use]
9783 pub fn contains(&self, value: f64) -> bool {
9784 if value.is_nan() {
9785 return false;
9786 }
9787 let left_ok = if self.closed.left_closed() {
9788 value >= self.left
9789 } else {
9790 value > self.left
9791 };
9792 let right_ok = if self.closed.right_closed() {
9793 value <= self.right
9794 } else {
9795 value < self.right
9796 };
9797 left_ok && right_ok
9798 }
9799
9800 #[must_use]
9807 pub fn overlaps(&self, other: &Self) -> bool {
9808 if self.left > other.right || other.left > self.right {
9809 return false;
9810 }
9811 if self.right == other.left {
9813 return self.closed.right_closed() && other.closed.left_closed();
9814 }
9815 if other.right == self.left {
9816 return other.closed.right_closed() && self.closed.left_closed();
9817 }
9818 true
9819 }
9820
9821 pub fn parse(s: &str) -> Result<Self, TypeError> {
9827 let s = s.trim();
9828 if s.len() < 5 {
9829 return Err(TypeError::ValueNotParseable {
9830 value: s.to_string(),
9831 target: "Interval".to_string(),
9832 });
9833 }
9834
9835 let first_char = s.chars().next().unwrap();
9836 let last_char = s.chars().last().unwrap();
9837
9838 let left_closed = match first_char {
9839 '[' => true,
9840 '(' => false,
9841 _ => {
9842 return Err(TypeError::ValueNotParseable {
9843 value: s.to_string(),
9844 target: "Interval".to_string(),
9845 });
9846 }
9847 };
9848
9849 let right_closed = match last_char {
9850 ']' => true,
9851 ')' => false,
9852 _ => {
9853 return Err(TypeError::ValueNotParseable {
9854 value: s.to_string(),
9855 target: "Interval".to_string(),
9856 });
9857 }
9858 };
9859
9860 let closed = match (left_closed, right_closed) {
9861 (true, true) => IntervalClosed::Both,
9862 (true, false) => IntervalClosed::Left,
9863 (false, true) => IntervalClosed::Right,
9864 (false, false) => IntervalClosed::Neither,
9865 };
9866
9867 let inner = &s[1..s.len() - 1];
9868 let Some((left_text, right_text)) = inner.split_once(',') else {
9869 return Err(TypeError::ValueNotParseable {
9870 value: s.to_string(),
9871 target: "Interval".to_string(),
9872 });
9873 };
9874 if right_text.contains(',') {
9875 return Err(TypeError::ValueNotParseable {
9876 value: s.to_string(),
9877 target: "Interval".to_string(),
9878 });
9879 }
9880
9881 let left: f64 = left_text
9882 .trim()
9883 .parse()
9884 .map_err(|_| TypeError::ValueNotParseable {
9885 value: s.to_string(),
9886 target: "Interval".to_string(),
9887 })?;
9888
9889 let right: f64 = right_text
9890 .trim()
9891 .parse()
9892 .map_err(|_| TypeError::ValueNotParseable {
9893 value: s.to_string(),
9894 target: "Interval".to_string(),
9895 })?;
9896
9897 Ok(Self::new(left, right, closed))
9898 }
9899}
9900
9901impl std::fmt::Display for Interval {
9902 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9909 let left_bracket = if self.closed.left_closed() { '[' } else { '(' };
9910 let right_bracket = if self.closed.right_closed() { ']' } else { ')' };
9911 #[allow(clippy::cast_possible_truncation)] let endpoint = |value: f64| match self.subtype {
9914 IntervalSubtype::Int64 if value.fract() == 0.0 => format!("{}", value as i64),
9915 _ => float_to_string_for_astype(value),
9916 };
9917 write!(
9918 f,
9919 "{left_bracket}{}, {}{right_bracket}",
9920 endpoint(self.left),
9921 endpoint(self.right)
9922 )
9923 }
9924}
9925
9926#[must_use]
9944pub fn interval_range_by_periods(
9945 start: f64,
9946 end: f64,
9947 periods: usize,
9948 closed: IntervalClosed,
9949) -> Vec<Interval> {
9950 if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
9951 return Vec::new();
9952 }
9953 let step = (end - start) / (periods as f64);
9954 let mut out = Vec::with_capacity(periods);
9955 for i in 0..periods {
9956 let left = start + step * (i as f64);
9957 let right = if i + 1 == periods {
9959 end
9960 } else {
9961 start + step * ((i + 1) as f64)
9962 };
9963 out.push(Interval::new(left, right, closed));
9964 }
9965 out
9966}
9967
9968pub fn interval_range_by_step(
9979 start: f64,
9980 end: f64,
9981 step: f64,
9982 closed: IntervalClosed,
9983) -> Result<Vec<Interval>, TypeError> {
9984 if !step.is_finite() || !step.is_sign_positive() || step == 0.0 {
9985 return Err(TypeError::InvalidIntervalStep { step });
9986 }
9987 if !start.is_finite() || !end.is_finite() || start >= end {
9988 return Ok(Vec::new());
9989 }
9990 let span = end - start;
9991 let periods_f = span / step;
9992 let periods = periods_f.round() as i64;
9993 if periods <= 0 {
9994 return Ok(Vec::new());
9995 }
9996 let reconstructed = step * (periods as f64);
9997 if (span - reconstructed).abs() > span.abs() * 1e-9 + 1e-12 {
9999 return Err(TypeError::IntervalStepDoesNotDivide { step, span });
10000 }
10001 let periods = periods as usize;
10002 let mut out = Vec::with_capacity(periods);
10003 for i in 0..periods {
10004 let left = start + step * (i as f64);
10005 let right = if i + 1 == periods {
10006 end
10007 } else {
10008 start + step * ((i + 1) as f64)
10009 };
10010 out.push(Interval::new(left, right, closed));
10011 }
10012 Ok(out)
10013}
10014
10015pub fn interval_range(
10027 start: Option<f64>,
10028 end: Option<f64>,
10029 periods: Option<usize>,
10030 freq: Option<f64>,
10031 closed: Option<IntervalClosed>,
10032) -> Result<Vec<Interval>, TypeError> {
10033 let count = usize::from(start.is_some())
10034 + usize::from(end.is_some())
10035 + usize::from(periods.is_some())
10036 + usize::from(freq.is_some());
10037 if count != 3 {
10038 return Err(TypeError::IntervalRangeParameterCount);
10039 }
10040 let closed = closed.unwrap_or(IntervalClosed::Right);
10041
10042 match (start, end, periods, freq) {
10043 (Some(start), Some(end), Some(periods), None) => {
10044 Ok(interval_range_by_periods(start, end, periods, closed))
10045 }
10046 (Some(start), Some(end), None, Some(freq)) => {
10047 interval_range_by_step(start, end, freq, closed)
10048 }
10049 (Some(start), None, Some(periods), Some(freq)) => {
10050 if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10051 return Err(TypeError::InvalidIntervalStep { step: freq });
10052 }
10053 if !start.is_finite() || periods == 0 {
10054 return Ok(Vec::new());
10055 }
10056 let mut out = Vec::with_capacity(periods);
10057 for i in 0..periods {
10058 let left = start + freq * (i as f64);
10059 let right = start + freq * ((i + 1) as f64);
10060 out.push(Interval::new(left, right, closed));
10061 }
10062 Ok(out)
10063 }
10064 (None, Some(end), Some(periods), Some(freq)) => {
10065 if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10066 return Err(TypeError::InvalidIntervalStep { step: freq });
10067 }
10068 if !end.is_finite() || periods == 0 {
10069 return Ok(Vec::new());
10070 }
10071 let start = end - freq * (periods as f64);
10072 let mut out = Vec::with_capacity(periods);
10073 for i in 0..periods {
10074 let left = start + freq * (i as f64);
10075 let right = if i + 1 == periods {
10076 end
10077 } else {
10078 start + freq * ((i + 1) as f64)
10079 };
10080 out.push(Interval::new(left, right, closed));
10081 }
10082 Ok(out)
10083 }
10084 _ => Err(TypeError::IntervalRangeParameterCount),
10085 }
10086}
10087
10088#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10107#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
10108#[non_exhaustive]
10109pub enum PeriodFreq {
10110 Annual(u8),
10114 Quarterly(u8),
10118 Monthly,
10120 Weekly(u8),
10123 Daily,
10125 Business,
10127 Hourly,
10129 Minutely,
10131 Secondly,
10133 Milliseconds,
10135 Microseconds,
10137 Nanoseconds,
10139}
10140
10141const PERIOD_MONTHS: [&str; 12] = [
10143 "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
10144];
10145const PERIOD_WEEKDAYS: [&str; 7] = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];
10147
10148impl PeriodFreq {
10149 pub const ANNUAL: Self = Self::Annual(12);
10151 pub const QUARTERLY: Self = Self::Quarterly(12);
10153 pub const WEEKLY: Self = Self::Weekly(6);
10155
10156 #[must_use]
10162 pub const fn fiscal_month_shift(self) -> i64 {
10163 match self {
10164 Self::Annual(month) | Self::Quarterly(month) => (12 - (month as i64 % 12)) % 12,
10165 _ => 0,
10166 }
10167 }
10168
10169 #[must_use]
10174 pub const fn week_start_shift(self) -> i64 {
10175 match self {
10176 Self::Weekly(day) => (day as i64 % 7 + 1) % 7,
10177 _ => 0,
10178 }
10179 }
10180
10181 fn parse_anchored(alias: &str) -> Option<Self> {
10184 let (prefix, anchor) = alias.split_once('-')?;
10185 let month = PERIOD_MONTHS.iter().position(|name| *name == anchor);
10186 let day = PERIOD_WEEKDAYS.iter().position(|name| *name == anchor);
10187 match (prefix, month, day) {
10188 ("A" | "Y", Some(month), _) => Some(Self::Annual(month as u8 + 1)),
10189 ("Q", Some(month), _) => Some(Self::Quarterly(month as u8 + 1)),
10190 ("W", _, Some(day)) => Some(Self::Weekly(day as u8)),
10191 _ => None,
10192 }
10193 }
10194
10195 pub fn parse(alias: &str) -> Option<Self> {
10203 if alias.eq_ignore_ascii_case("ms") && alias != "MS" {
10213 return Some(Self::Milliseconds);
10214 }
10215 match alias.to_ascii_uppercase().as_str() {
10216 "A" | "Y" | "ANNUAL" | "YEARLY" => Some(Self::ANNUAL),
10217 "Q" | "QUARTERLY" => Some(Self::QUARTERLY),
10218 "M" | "MONTHLY" => Some(Self::Monthly),
10219 "W" | "WEEKLY" => Some(Self::WEEKLY),
10220 "D" | "DAILY" => Some(Self::Daily),
10221 "B" | "BUSINESS" => Some(Self::Business),
10222 "H" | "HOURLY" => Some(Self::Hourly),
10223 "T" | "MIN" | "MINUTELY" => Some(Self::Minutely),
10224 "S" | "SECONDLY" => Some(Self::Secondly),
10225 "US" | "MICROSECOND" | "MICROSECONDS" => Some(Self::Microseconds),
10226 "NS" | "NANOSECOND" | "NANOSECONDS" => Some(Self::Nanoseconds),
10227 "MILLISECOND" | "MILLISECONDS" => Some(Self::Milliseconds),
10230 anchored => Self::parse_anchored(anchored),
10231 }
10232 }
10233
10234 #[must_use]
10236 pub const fn alias(self) -> &'static str {
10237 const ANNUAL: [&str; 12] = [
10238 "Y-JAN", "Y-FEB", "Y-MAR", "Y-APR", "Y-MAY", "Y-JUN", "Y-JUL", "Y-AUG", "Y-SEP",
10239 "Y-OCT", "Y-NOV", "Y-DEC",
10240 ];
10241 const QUARTERLY: [&str; 12] = [
10242 "Q-JAN", "Q-FEB", "Q-MAR", "Q-APR", "Q-MAY", "Q-JUN", "Q-JUL", "Q-AUG", "Q-SEP",
10243 "Q-OCT", "Q-NOV", "Q-DEC",
10244 ];
10245 const WEEKLY: [&str; 7] = [
10246 "W-MON", "W-TUE", "W-WED", "W-THU", "W-FRI", "W-SAT", "W-SUN",
10247 ];
10248 match self {
10249 Self::Annual(month) => ANNUAL[(month as usize + 11) % 12],
10250 Self::Quarterly(month) => QUARTERLY[(month as usize + 11) % 12],
10251 Self::Monthly => "M",
10252 Self::Weekly(day) => WEEKLY[day as usize % 7],
10253 Self::Daily => "D",
10254 Self::Business => "B",
10255 Self::Hourly => "h",
10256 Self::Minutely => "min",
10257 Self::Secondly => "s",
10258 Self::Milliseconds => "ms",
10259 Self::Microseconds => "us",
10260 Self::Nanoseconds => "ns",
10261 }
10262 }
10263
10264 #[must_use]
10283 pub const fn resolution(self) -> Option<&'static str> {
10284 match self {
10285 Self::Annual(_) => Some("year"),
10286 Self::Quarterly(_) => Some("quarter"),
10287 Self::Monthly => Some("month"),
10288 Self::Daily => Some("day"),
10289 Self::Hourly => Some("hour"),
10290 Self::Minutely => Some("minute"),
10291 Self::Secondly => Some("second"),
10292 Self::Milliseconds => Some("millisecond"),
10293 Self::Microseconds => Some("microsecond"),
10294 Self::Nanoseconds => Some("nanosecond"),
10295 Self::Weekly(_) | Self::Business => None,
10298 }
10299 }
10300}
10301
10302impl std::fmt::Display for PeriodFreq {
10303 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10304 f.write_str(self.alias())
10305 }
10306}
10307
10308#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10316pub struct Period {
10317 pub ordinal: i64,
10318 pub freq: PeriodFreq,
10319}
10320
10321impl Period {
10322 #[must_use]
10323 pub const fn new(ordinal: i64, freq: PeriodFreq) -> Self {
10324 Self { ordinal, freq }
10325 }
10326
10327 #[must_use]
10330 pub const fn is_nat(&self) -> bool {
10331 self.ordinal == i64::MIN
10332 }
10333
10334 #[must_use]
10337 pub const fn ordinal(&self) -> i64 {
10338 self.ordinal
10339 }
10340
10341 #[must_use]
10343 pub const fn freq(&self) -> PeriodFreq {
10344 self.freq
10345 }
10346
10347 #[must_use]
10349 pub const fn freqstr(&self) -> &'static str {
10350 self.freq.alias()
10351 }
10352
10353 #[must_use]
10356 pub fn cmp_same_freq(&self, other: &Self) -> Option<std::cmp::Ordering> {
10357 if self.freq != other.freq {
10358 return None;
10359 }
10360 Some(self.ordinal.cmp(&other.ordinal))
10361 }
10362
10363 #[must_use]
10366 pub fn shift(&self, n: i64) -> Self {
10367 Self {
10368 ordinal: self.ordinal.saturating_add(n),
10369 freq: self.freq,
10370 }
10371 }
10372
10373 #[must_use]
10376 pub fn diff(&self, other: &Self) -> Option<i64> {
10377 if self.freq != other.freq {
10378 return None;
10379 }
10380 Some(self.ordinal.saturating_sub(other.ordinal))
10381 }
10382
10383 pub fn parse(s: &str) -> Result<Self, TypeError> {
10390 let trimmed = s.trim();
10391 if trimmed.eq_ignore_ascii_case("nat") {
10392 return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
10393 }
10394
10395 if let Some((year, quarter)) = parse_quarter_period(trimmed) {
10396 let ordinal = year
10397 .checked_sub(1970)
10398 .and_then(|offset| offset.checked_mul(4))
10399 .and_then(|base| base.checked_add(i64::from(quarter) - 1))
10400 .ok_or_else(|| TypeError::ValueNotParseable {
10401 value: s.to_owned(),
10402 target: "Period".to_owned(),
10403 })?;
10404 return Ok(Self::new(ordinal, PeriodFreq::QUARTERLY));
10405 }
10406
10407 if let Some((year, month, day)) = parse_ymd_period(trimmed) {
10408 let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
10409 return Ok(Self::new(ordinal, PeriodFreq::Daily));
10410 }
10411
10412 if let Some((year, month)) = parse_year_month_period(trimmed) {
10413 let ordinal = year
10414 .checked_sub(1970)
10415 .and_then(|offset| offset.checked_mul(12))
10416 .and_then(|base| base.checked_add(i64::from(month) - 1))
10417 .ok_or_else(|| TypeError::ValueNotParseable {
10418 value: s.to_owned(),
10419 target: "Period".to_owned(),
10420 })?;
10421 return Ok(Self::new(ordinal, PeriodFreq::Monthly));
10422 }
10423
10424 if let Some(year) = parse_annual_period(trimmed) {
10425 let ordinal = year
10426 .checked_sub(1970)
10427 .ok_or_else(|| TypeError::ValueNotParseable {
10428 value: s.to_owned(),
10429 target: "Period".to_owned(),
10430 })?;
10431 return Ok(Self::new(ordinal, PeriodFreq::ANNUAL));
10432 }
10433
10434 Err(TypeError::ValueNotParseable {
10435 value: s.to_owned(),
10436 target: "Period".to_owned(),
10437 })
10438 }
10439
10440 #[must_use]
10465 pub fn calendar_string(&self) -> String {
10466 let mut rendered = String::new();
10467 let _ = self.write_calendar(&mut rendered);
10469 rendered
10470 }
10471
10472 fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
10473 if self.ordinal == i64::MIN {
10474 return rendered.write_str("NaT");
10475 }
10476 let ord = self.ordinal;
10477 match self.freq {
10478 PeriodFreq::Annual(_) => {
10482 let year = 1970 + ord;
10483 write!(rendered, "{year}")
10484 }
10485 PeriodFreq::Quarterly(_) => {
10486 let year = 1970 + ord.div_euclid(4);
10487 let quarter = ord.rem_euclid(4) + 1;
10488 write!(rendered, "{year}Q{quarter}")
10489 }
10490 PeriodFreq::Monthly => {
10491 let year = 1970 + ord.div_euclid(12);
10492 let month = ord.rem_euclid(12) + 1;
10493 write!(rendered, "{year:04}-{month:02}")
10494 }
10495 PeriodFreq::Daily => {
10496 let (y, m, d) = civil_from_days(ord);
10497 write!(rendered, "{y:04}-{m:02}-{d:02}")
10498 }
10499 PeriodFreq::Business => {
10510 const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
10511 let offset = WEEKDAY_OFFSET[ord.rem_euclid(5) as usize];
10514 let days = ord.div_euclid(5).saturating_mul(7).saturating_add(offset);
10515 let (y, m, d) = civil_from_days(days);
10516 write!(rendered, "{y:04}-{m:02}-{d:02}")
10517 }
10518 PeriodFreq::Weekly(_) => {
10528 const WEEK_ANCHOR_DAY: i64 = -10;
10532 let start = ord
10533 .saturating_mul(7)
10534 .saturating_add(WEEK_ANCHOR_DAY + self.freq.week_start_shift());
10535 let (sy, sm, sd) = civil_from_days(start);
10536 let (ey, em, ed) = civil_from_days(start.saturating_add(6));
10537 write!(rendered, "{sy:04}-{sm:02}-{sd:02}/{ey:04}-{em:02}-{ed:02}")
10538 }
10539 PeriodFreq::Hourly => {
10540 let (y, m, d) = civil_from_days(ord.div_euclid(24));
10541 let hour = ord.rem_euclid(24);
10542 write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
10543 }
10544 PeriodFreq::Minutely => {
10545 let day = ord.div_euclid(1440);
10546 let mins = ord.rem_euclid(1440);
10547 let (y, m, d) = civil_from_days(day);
10548 write!(
10549 rendered,
10550 "{y:04}-{m:02}-{d:02} {:02}:{:02}",
10551 mins / 60,
10552 mins % 60
10553 )
10554 }
10555 PeriodFreq::Secondly => {
10556 let day = ord.div_euclid(86_400);
10557 let secs = ord.rem_euclid(86_400);
10558 let (y, m, d) = civil_from_days(day);
10559 write!(
10560 rendered,
10561 "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
10562 secs / 3600,
10563 (secs % 3600) / 60,
10564 secs % 60
10565 )
10566 }
10567 PeriodFreq::Milliseconds | PeriodFreq::Microseconds | PeriodFreq::Nanoseconds => {
10574 let (per_sec, width) = match self.freq {
10575 PeriodFreq::Milliseconds => (1_000_i64, 3_usize),
10576 PeriodFreq::Microseconds => (1_000_000_i64, 6_usize),
10577 _ => (1_000_000_000_i64, 9_usize),
10578 };
10579 let per_day = 86_400 * per_sec;
10581 let day = ord.div_euclid(per_day);
10582 let rest = ord.rem_euclid(per_day);
10583 let secs = rest / per_sec;
10584 let frac = rest % per_sec;
10585 let (y, m, d) = civil_from_days(day);
10586 write!(
10587 rendered,
10588 "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{:0width$}",
10589 secs / 3600,
10590 (secs % 3600) / 60,
10591 secs % 60,
10592 frac,
10593 width = width
10594 )
10595 }
10596 }
10597 }
10598}
10599
10600fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
10604 let days = days_since_epoch + 719_468;
10605 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
10606 let doe = days - era * 146_097;
10607 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
10608 let y = yoe + era * 400;
10609 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
10610 let mp = (5 * doy + 2) / 153;
10611 let d = doy - (153 * mp + 2) / 5 + 1;
10612 let m = if mp < 10 { mp + 3 } else { mp - 9 };
10613 let year = if m <= 2 { y + 1 } else { y };
10614 (year, m as u32, d as u32)
10615}
10616
10617fn parse_annual_period(value: &str) -> Option<i64> {
10618 (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
10619 .then(|| value.parse::<i64>().ok())
10620 .flatten()
10621}
10622
10623fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
10624 let (year, month) = value.split_once('-')?;
10625 if year.len() != 4 || month.len() != 2 {
10626 return None;
10627 }
10628 let year = year.parse::<i64>().ok()?;
10629 let month = month.parse::<u32>().ok()?;
10630 (1..=12).contains(&month).then_some((year, month))
10631}
10632
10633fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
10634 let mut parts = value.split('-');
10635 let year = parts.next()?;
10636 let month = parts.next()?;
10637 let day = parts.next()?;
10638 if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
10639 return None;
10640 }
10641 let year = year.parse::<i64>().ok()?;
10642 let month = month.parse::<u32>().ok()?;
10643 let day = day.parse::<u32>().ok()?;
10644 (1..=days_in_month(year, month)?)
10645 .contains(&day)
10646 .then_some((year, month, day))
10647}
10648
10649fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
10650 let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
10651 if year.len() != 4 || quarter.len() != 1 {
10652 return None;
10653 }
10654 let year = year.parse::<i64>().ok()?;
10655 let quarter = quarter.parse::<u32>().ok()?;
10656 (1..=4).contains(&quarter).then_some((year, quarter))
10657}
10658
10659impl std::fmt::Display for Period {
10660 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10663 self.write_calendar(f)
10664 }
10665}
10666
10667#[must_use]
10686pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
10687 (0..periods).map(|i| start.shift(i as i64)).collect()
10688}
10689
10690#[cfg(test)]
10691mod tests {
10692 use super::{
10693 DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
10694 cast_scalar, common_dtype, infer_dtype,
10695 };
10696
10697 struct Named(&'static str);
10700
10701 impl super::HostObject for Named {
10702 fn host_eq(&self, other: &dyn super::HostObject) -> bool {
10703 other
10704 .as_any()
10705 .downcast_ref::<Named>()
10706 .is_some_and(|other| other.0 == self.0)
10707 }
10708 fn host_repr(&self) -> String {
10709 format!("Named({:?})", self.0)
10710 }
10711 fn host_str(&self) -> String {
10712 self.0.to_owned()
10713 }
10714 fn host_hash(&self) -> Option<u64> {
10715 (!self.0.is_empty()).then_some(self.0.len() as u64)
10716 }
10717 fn host_cmp(&self, other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
10719 let other = other.as_any().downcast_ref::<Named>()?;
10720 (!self.0.starts_with('!') && !other.0.starts_with('!')).then(|| self.0.cmp(other.0))
10721 }
10722 fn as_any(&self) -> &dyn std::any::Any {
10723 self
10724 }
10725 }
10726
10727 #[test]
10728 fn host_values_block_workers_only_under_a_declared_host_lock_4qg5w_13() {
10729 use std::sync::atomic::Ordering;
10730
10731 use super::{HostValue, LIVE_HOST_VALUES, workers_blocked};
10732 assert!(workers_blocked(true, 1));
10736 assert!(!workers_blocked(true, 0));
10737 assert!(!workers_blocked(false, 3));
10738 let first = HostValue::new(Named("held"));
10743 assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
10744 let clone = first.clone();
10745 drop(first);
10746 assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
10747 assert_eq!(clone.object().host_str(), "held");
10748 }
10749
10750 #[test]
10751 fn object_cells_order_like_python_then_totally_fvsao_66() {
10752 use std::cmp::Ordering;
10753
10754 use super::{HostValue, ObjectValue};
10755 let host = |name: &'static str| ObjectValue::Host(HostValue::new(Named(name)));
10756 let list = |items: Vec<Scalar>| ObjectValue::list(items);
10757 assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
10760 assert!(host("b") > host("a"));
10761 assert_eq!(host("a").cmp(&host("a")), Ordering::Equal);
10762 let one_ten = list(vec![Scalar::Int64(1), Scalar::Int64(10)]);
10765 let one_two = list(vec![Scalar::Int64(1), Scalar::Int64(2)]);
10766 assert_eq!(one_two.python_cmp(&one_ten), Some(Ordering::Less));
10767 assert!(list(vec![Scalar::Int64(1)]) < one_two);
10768 let mixed = list(vec![Scalar::Float64(1.0), Scalar::Int64(3)]);
10770 assert_eq!(one_two.python_cmp(&mixed), Some(Ordering::Less));
10771 assert_eq!(one_two.python_cmp(&host("a")), None);
10774 assert!(one_two < host("a"));
10775 assert_eq!(host("!z").python_cmp(&host("!a")), None);
10776 assert!(host("!a") < host("!z"));
10777 let text = list(vec![Scalar::Utf8("a".to_owned())]);
10778 assert_eq!(one_two.python_cmp(&text), None);
10779 assert_ne!(one_two.cmp(&text), Ordering::Equal);
10780 let nan = || list(vec![Scalar::Float64(f64::NAN)]);
10783 let (first, second) = (nan(), nan());
10784 assert_ne!(first, second);
10785 assert_ne!(first.cmp(&second), Ordering::Equal);
10786 assert_eq!(first.cmp(&second), second.cmp(&first).reverse());
10787 }
10788
10789 #[test]
10790 fn bytes_cells_print_order_and_serialize_like_python_bytes_4qg5w_8() {
10791 use std::cmp::Ordering;
10792
10793 use super::ObjectValue;
10794 let bytes = |data: &[u8]| Scalar::Object(ObjectValue::bytes(data.to_vec()));
10795 assert_eq!(bytes(b"ab").python_repr(), "b'ab'");
10798 assert_eq!(bytes(b"a'b").python_repr(), "b\"a'b\"");
10799 assert_eq!(bytes(b"a'\"").python_repr(), "b'a\\'\"'");
10800 assert_eq!(bytes(b"\x00\t\\\xff").python_repr(), "b'\\x00\\t\\\\\\xff'");
10801 assert_eq!(bytes(b"ab").python_type_name(), "bytes");
10802 assert_eq!(bytes(b"ab").python_cmp(&bytes(b"b")), Some(Ordering::Less));
10804 assert_eq!(bytes(b"a").python_cmp(&bytes(b"ab")), Some(Ordering::Less));
10805 assert_eq!(bytes(b"a").python_cmp(&Scalar::Utf8("a".to_owned())), None);
10806 assert_ne!(bytes(b"a"), Scalar::Utf8("a".to_owned()));
10807 assert!(!bytes(b"").to_bool().unwrap());
10808 let json = serde_json::to_string(&bytes(b"hi")).unwrap();
10810 assert_eq!(json, r#"{"kind":"object","value":{"bytes":[104,105]}}"#);
10811 let back: Scalar = serde_json::from_str(&json).unwrap();
10812 assert_eq!(back, bytes(b"hi"));
10813 let list: Scalar =
10815 serde_json::from_str(r#"{"kind":"object","value":[{"kind":"int64","value":1}]}"#)
10816 .unwrap();
10817 assert_eq!(
10818 list,
10819 Scalar::Object(ObjectValue::list(vec![Scalar::Int64(1)]))
10820 );
10821 }
10822
10823 #[test]
10824 fn values_order_and_name_their_types_as_python_does_fvsao_71() {
10825 use std::cmp::Ordering;
10826
10827 use super::{HostValue, ObjectValue};
10828 let text = |value: &str| Scalar::Utf8(value.to_owned());
10829 let host =
10830 |name: &'static str| Scalar::Object(ObjectValue::Host(HostValue::new(Named(name))));
10831 let list = |items: Vec<Scalar>| Scalar::Object(ObjectValue::list(items));
10832 assert_eq!(
10835 Scalar::Bool(true).python_cmp(&Scalar::Float64(1.5)),
10836 Some(Ordering::Less)
10837 );
10838 assert_eq!(
10839 Scalar::Int64(2).python_cmp(&Scalar::Float64(2.0)),
10840 Some(Ordering::Equal)
10841 );
10842 assert_eq!(text("b").python_cmp(&text("a")), Some(Ordering::Greater));
10843 assert_eq!(
10844 Scalar::Datetime64(5).python_cmp(&Scalar::Datetime64(9)),
10845 Some(Ordering::Less)
10846 );
10847 let interval = |left: f64, right: f64| {
10848 Scalar::Interval(Interval::new(left, right, IntervalClosed::Right))
10849 };
10850 assert_eq!(
10851 interval(0.0, 5.0).python_cmp(&interval(0.0, 2.0)),
10852 Some(Ordering::Greater)
10853 );
10854 assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
10855 assert_eq!(text("a").python_cmp(&Scalar::Int64(1)), None);
10858 assert_eq!(
10859 Scalar::Datetime64(1).python_cmp(&Scalar::Timedelta64(1)),
10860 None
10861 );
10862 assert_eq!(host("a").python_cmp(&Scalar::Int64(1)), None);
10863 assert_eq!(host("!a").python_cmp(&host("b")), None);
10864 assert_eq!(text("a").python_type_name(), "str");
10868 assert_eq!(Scalar::Bool(true).python_type_name(), "bool");
10869 assert_eq!(Scalar::Datetime64(1).python_type_name(), "Timestamp");
10870 assert_eq!(list(vec![]).python_type_name(), "list");
10871 assert_eq!(host("a").python_type_name(), "object");
10872 let (left, right) = list(vec![Scalar::Int64(1), Scalar::Int64(2)])
10873 .python_cmp_type_names(&list(vec![Scalar::Int64(1), text("x")]));
10874 assert_eq!((left.as_str(), right.as_str()), ("int", "str"));
10875 let (left, right) = text("a").python_cmp_type_names(&list(vec![]));
10876 assert_eq!((left.as_str(), right.as_str()), ("str", "list"));
10877 }
10878
10879 #[test]
10880 fn object_cells_print_compare_and_hash_like_python_fvsao_33() {
10881 use std::hash::{Hash, Hasher};
10882
10883 use super::{HostValue, ObjectValue};
10884 let hash = |value: &ObjectValue| {
10885 let mut hasher = std::collections::hash_map::DefaultHasher::new();
10886 value.hash(&mut hasher);
10887 hasher.finish()
10888 };
10889 let list = ObjectValue::list(vec![
10890 Scalar::Int64(1),
10891 Scalar::Utf8("a".to_owned()),
10892 Scalar::Null(NullKind::Null),
10893 Scalar::Float64(2.0),
10894 Scalar::Object(ObjectValue::list(vec![Scalar::Utf8("b".to_owned())])),
10895 ]);
10896 assert_eq!(list.repr(), "[1, 'a', None, 2.0, ['b']]");
10899 assert_eq!(list.to_string(), "[1, 'a', None, 2.0, ['b']]");
10900 assert_eq!(list.pprint(), "[1, a, None, 2.0, [b]]");
10901 assert_eq!(Scalar::Object(list.clone()).dtype(), DType::Utf8);
10903 assert!(!Scalar::Object(list.clone()).is_missing());
10904 let same = ObjectValue::list(list.as_list().unwrap().to_vec());
10907 assert_eq!(list, same);
10908 assert_eq!(hash(&list), hash(&same));
10909 let other = ObjectValue::list(vec![Scalar::Int64(1)]);
10910 assert_ne!(list, other);
10911 let host = ObjectValue::Host(HostValue::new(Named("x")));
10912 assert_ne!(list, host);
10913 assert_eq!(host, ObjectValue::Host(HostValue::new(Named("x"))));
10915 assert_ne!(host, ObjectValue::Host(HostValue::new(Named("y"))));
10916 assert_eq!(host.repr(), "Named(\"x\")");
10917 assert_eq!(host.to_string(), "x");
10918 assert!(
10920 !Scalar::Object(ObjectValue::list(Vec::new()))
10921 .to_bool()
10922 .unwrap()
10923 );
10924 assert!(Scalar::Object(host.clone()).to_bool().unwrap());
10925 assert!(Scalar::Object(list.clone()).to_f64().is_err());
10927 let json = serde_json::to_string(&Scalar::Object(other.clone())).unwrap();
10930 assert_eq!(
10931 serde_json::from_str::<Scalar>(&json).unwrap(),
10932 Scalar::Object(other)
10933 );
10934 assert!(serde_json::to_string(&Scalar::Object(host)).is_err());
10935 }
10936
10937 #[test]
10938 fn a_host_cell_displays_by_its_pprint_and_stringifies_by_its_str() {
10939 use super::{HostValue, ObjectValue};
10940
10941 struct Pair;
10943 impl super::HostObject for Pair {
10944 fn host_eq(&self, _other: &dyn super::HostObject) -> bool {
10945 false
10946 }
10947 fn host_repr(&self) -> String {
10948 "('a', 1)".to_owned()
10949 }
10950 fn host_str(&self) -> String {
10951 "('a', 1)".to_owned()
10952 }
10953 fn host_pprint(&self) -> String {
10954 "(a, 1)".to_owned()
10955 }
10956 fn host_hash(&self) -> Option<u64> {
10957 None
10958 }
10959 fn host_cmp(&self, _other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
10960 None
10961 }
10962 fn as_any(&self) -> &dyn std::any::Any {
10963 self
10964 }
10965 }
10966 let pair = ObjectValue::Host(HostValue::new(Pair));
10967 assert_eq!(pair.pprint(), "(a, 1)");
10968 let list = ObjectValue::list(vec![Scalar::Object(pair.clone())]);
10970 assert_eq!(list.pprint(), "[(a, 1)]");
10971 assert_eq!(pair.to_string(), "('a', 1)");
10973 let named = ObjectValue::Host(HostValue::new(Named("x")));
10975 assert_eq!(named.pprint(), "x");
10976 }
10977
10978 #[test]
10979 fn float64_json_spells_infinity_and_round_trips() {
10980 let json = |s: &Scalar| serde_json::to_string(s).expect("serialize");
10984 let back = |text: &str| serde_json::from_str::<Scalar>(text);
10985 assert_eq!(
10986 json(&Scalar::Float64(f64::INFINITY)),
10987 r#"{"kind":"float64","value":"inf"}"#
10988 );
10989 assert_eq!(
10990 json(&Scalar::Float64(f64::NEG_INFINITY)),
10991 r#"{"kind":"float64","value":"-inf"}"#
10992 );
10993 assert_eq!(
10995 json(&Scalar::Float64(1.5)),
10996 r#"{"kind":"float64","value":1.5}"#
10997 );
10998 assert_eq!(
10999 json(&Scalar::Float64(-0.0)),
11000 r#"{"kind":"float64","value":-0.0}"#
11001 );
11002 assert_eq!(
11003 json(&Scalar::Float64(f64::NAN)),
11004 r#"{"kind":"float64","value":null}"#
11005 );
11006 for value in [f64::INFINITY, f64::NEG_INFINITY, 1.5, -2.25e300] {
11007 let scalar = Scalar::Float64(value);
11008 assert_eq!(back(&json(&scalar)).expect("round trip"), scalar);
11009 }
11010 let negative_zero = back(r#"{"kind":"float64","value":-0.0}"#).expect("-0.0");
11011 assert!(matches!(negative_zero, Scalar::Float64(v) if v == 0.0 && v.is_sign_negative()));
11012 assert!(matches!(
11013 back(r#"{"kind":"float64","value":null}"#).expect("null"),
11014 Scalar::Float64(v) if v.is_nan()
11015 ));
11016 assert!(back(r#"{"kind":"float64","value":"Infinity"}"#).is_err());
11018 assert!(back(r#"{"kind":"float64","value":"1.5"}"#).is_err());
11019 }
11020
11021 #[test]
11031 fn semantic_cmp_cross_numeric_int_float_cdpai() {
11032 use std::cmp::Ordering;
11035 let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
11036 let mut next = || {
11037 st = st
11038 .wrapping_mul(6_364_136_223_846_793_005)
11039 .wrapping_add(1_442_695_040_888_963_407);
11040 (st >> 33) as u32
11041 };
11042 for _ in 0..3000u32 {
11043 let i = (next() % 21) as i64 - 10;
11044 let f = (next() % 400) as f64 / 20.0 - 10.0; let exp = (i as f64).partial_cmp(&f).unwrap();
11046 assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
11047 assert_eq!(
11048 Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
11049 exp.reverse()
11050 );
11051 }
11052 assert_eq!(
11054 Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
11055 Ordering::Equal
11056 );
11057 assert_eq!(
11058 Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
11059 Ordering::Equal
11060 );
11061 assert_eq!(
11062 Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
11063 Ordering::Less
11064 );
11065 assert_eq!(
11066 Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
11067 Ordering::Greater
11068 );
11069 }
11070
11071 #[test]
11072 fn semantic_cmp_nat_degeneracy_temporal_767ak() {
11073 use std::cmp::Ordering;
11074 const NAT: i64 = i64::MIN;
11075
11076 let td_nat = Scalar::Timedelta64(NAT);
11078 for v in [-3i64, 0, 5, 99] {
11079 let td = Scalar::Timedelta64(v);
11080 assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
11081 assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
11082 }
11083 assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
11084
11085 let dt_nat = Scalar::Datetime64(NAT);
11087 for v in [-3i64, 0, 5, 99] {
11088 let dt = Scalar::Datetime64(v);
11089 assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
11090 assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
11091 }
11092 assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
11093
11094 for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
11096 let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
11097 assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
11098 assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
11100 let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
11101 assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
11102 }
11103 }
11104
11105 fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
11106 [
11107 Scalar::Null(NullKind::Null),
11108 Scalar::Bool(true),
11109 Scalar::Int64(-7),
11110 Scalar::Float64(3.5),
11111 Scalar::Utf8("mixed".to_owned()),
11112 Scalar::Timedelta64(11),
11113 Scalar::Datetime64(1_735_732_800_123_456_789),
11114 Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
11115 Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
11116 ]
11117 }
11118
11119 fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
11120 !matches!(
11121 (left, right),
11122 (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
11123 )
11124 }
11125
11126 #[test]
11127 fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
11128 let values = semantic_cmp_cross_variant_values_d5ikg();
11129 for (left_index, left) in values.iter().enumerate() {
11130 for (right_index, right) in values.iter().enumerate() {
11131 if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11132 {
11133 assert_eq!(
11134 left.semantic_cmp(right),
11135 format!("{left:?}").cmp(&format!("{right:?}")),
11136 "cross-variant order mismatch: {left:?} vs {right:?}"
11137 );
11138 }
11139 }
11140 }
11141 }
11142
11143 #[test]
11144 #[ignore = "foreground release attribution harness"]
11145 fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
11146 use std::cmp::Ordering;
11147
11148 const BATCH: usize = 4_096;
11149 const BLOCKS: usize = 9;
11150
11151 fn former(left: &Scalar, right: &Scalar) -> Ordering {
11152 format!("{left:?}").cmp(&format!("{right:?}"))
11153 }
11154
11155 fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
11156 left.semantic_cmp(right)
11157 }
11158
11159 fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
11160 let mut less = 0usize;
11161 let started = std::time::Instant::now();
11162 for _ in 0..BATCH {
11163 for (left_index, left) in values.iter().enumerate() {
11164 for (right_index, right) in values.iter().enumerate() {
11165 if left_index != right_index
11166 && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11167 && compare(std::hint::black_box(left), std::hint::black_box(right))
11168 == Ordering::Less
11169 {
11170 less += 1;
11171 }
11172 }
11173 }
11174 }
11175 std::hint::black_box(less);
11176 started.elapsed().as_nanos()
11177 }
11178
11179 fn median(samples: &mut [u128]) -> u128 {
11180 samples.sort_unstable();
11181 samples[samples.len() / 2]
11182 }
11183
11184 let values = semantic_cmp_cross_variant_values_d5ikg();
11185
11186 for (left_index, left) in values.iter().enumerate() {
11187 for (right_index, right) in values.iter().enumerate() {
11188 if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11189 {
11190 assert_eq!(
11191 former(left, right),
11192 candidate(left, right),
11193 "cross-variant order mismatch: {left:?} vs {right:?}"
11194 );
11195 }
11196 }
11197 }
11198
11199 std::hint::black_box(elapsed(&values, former));
11200 std::hint::black_box(elapsed(&values, candidate));
11201
11202 let mut former_samples = Vec::with_capacity(BLOCKS * 2);
11203 let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
11204 for block in 0..BLOCKS {
11205 if block.is_multiple_of(2) {
11206 former_samples.push(elapsed(&values, former));
11207 candidate_samples.push(elapsed(&values, candidate));
11208 candidate_samples.push(elapsed(&values, candidate));
11209 former_samples.push(elapsed(&values, former));
11210 } else {
11211 candidate_samples.push(elapsed(&values, candidate));
11212 former_samples.push(elapsed(&values, former));
11213 former_samples.push(elapsed(&values, former));
11214 candidate_samples.push(elapsed(&values, candidate));
11215 }
11216 }
11217
11218 let former_p50 = median(&mut former_samples);
11219 let candidate_p50 = median(&mut candidate_samples);
11220 eprintln!(
11221 "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
11222 former_p50 as f64 / candidate_p50 as f64
11223 );
11224 }
11225
11226 #[test]
11227 fn semantic_cmp_total_order_axioms_ay8o9() {
11228 use std::cmp::Ordering;
11229
11230 let mut state: u64 = 0xc0ff_eeba_df00_d123;
11231 let mut next = || {
11232 state = state
11233 .wrapping_mul(6_364_136_223_846_793_005)
11234 .wrapping_add(1_442_695_040_888_963_407);
11235 (state >> 33) as u32
11236 };
11237
11238 for iter in 0..6000u32 {
11239 let dt = next() % 4;
11240 let mk = |r: u32| match dt {
11242 0 => Scalar::Int64((r % 11) as i64 - 5),
11243 1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
11245 2 => Scalar::Utf8(format!("s{}", r % 5)),
11246 _ => Scalar::Bool(r.is_multiple_of(2)),
11247 };
11248 let a = mk(next());
11249 let b = mk(next());
11250 let c = mk(next());
11251 let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
11252
11253 assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
11255 assert_eq!(
11257 a.semantic_cmp(&b),
11258 b.semantic_cmp(&a).reverse(),
11259 "antisymmetric {ctx}"
11260 );
11261 let ab = a.semantic_cmp(&b);
11263 assert_eq!(
11264 a.semantic_le(&b),
11265 ab != Ordering::Greater,
11266 "le-consistent {ctx}"
11267 );
11268 assert_eq!(
11269 a.semantic_ge(&b),
11270 ab != Ordering::Less,
11271 "ge-consistent {ctx}"
11272 );
11273 assert_eq!(
11274 a.semantic_le(&b) && a.semantic_ge(&b),
11275 ab == Ordering::Equal,
11276 "le&ge<=>eq {ctx}"
11277 );
11278 if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
11280 assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
11281 }
11282 }
11283
11284 let nan = Scalar::Float64(f64::NAN);
11288 for v in [
11289 Scalar::Float64(-3.5),
11290 Scalar::Float64(0.0),
11291 Scalar::Float64(7.25),
11292 ] {
11293 assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
11294 assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
11295 }
11296 assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
11297 }
11298
11299 #[test]
11305 fn common_dtype_lattice_axioms_be314() {
11306 let all: [DType; 14] = [
11307 DType::Null,
11308 DType::Bool,
11309 DType::BoolNullable,
11310 DType::Int64,
11311 DType::Int64Nullable,
11312 DType::Float64,
11313 DType::Float64Nullable,
11316 DType::Utf8,
11317 DType::Categorical,
11318 DType::Timedelta64,
11319 DType::datetime64_naive(),
11320 DType::Period,
11321 DType::Interval,
11322 DType::Sparse,
11323 ];
11324
11325 for a in &all {
11326 assert_eq!(
11328 common_dtype(a.clone(), a.clone()),
11329 Ok(a.clone()),
11330 "idempotent {a:?}"
11331 );
11332 assert_eq!(
11334 common_dtype(DType::Null, a.clone()),
11335 Ok(a.clone()),
11336 "null-left identity {a:?}"
11337 );
11338 assert_eq!(
11339 common_dtype(a.clone(), DType::Null),
11340 Ok(a.clone()),
11341 "null-right identity {a:?}"
11342 );
11343
11344 for b in &all {
11345 assert_eq!(
11348 common_dtype(a.clone(), b.clone()).ok(),
11349 common_dtype(b.clone(), a.clone()).ok(),
11350 "commutative value {a:?},{b:?}"
11351 );
11352 assert_eq!(
11353 common_dtype(a.clone(), b.clone()).is_ok(),
11354 common_dtype(b.clone(), a.clone()).is_ok(),
11355 "commutative ok-ness {a:?},{b:?}"
11356 );
11357 }
11358 }
11359
11360 for a in &all {
11363 for b in &all {
11364 for c in &all {
11365 if let (Ok(ab), Ok(bc)) = (
11366 common_dtype(a.clone(), b.clone()),
11367 common_dtype(b.clone(), c.clone()),
11368 ) && let (Ok(left), Ok(right)) =
11369 (common_dtype(ab, c.clone()), common_dtype(a.clone(), bc))
11370 {
11371 assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
11372 }
11373 }
11374 }
11375 }
11376 }
11377
11378 #[test]
11381 fn infer_dtype_coercion_rules_e3sfq() {
11382 use DType::{Bool, Float64, Int64, Null, Utf8};
11383
11384 assert_eq!(infer_dtype(&[]), Ok(Null));
11386 assert_eq!(
11387 infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
11388 Ok(Null)
11389 );
11390
11391 let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
11393 let mut next = || {
11394 s = s
11395 .wrapping_mul(6_364_136_223_846_793_005)
11396 .wrapping_add(1_442_695_040_888_963_407);
11397 (s >> 33) as u32
11398 };
11399 for _ in 0..600u32 {
11400 let n = (next() % 6) as usize + 1;
11401 let ints: Vec<Scalar> = (0..n)
11402 .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
11403 .collect();
11404 assert_eq!(infer_dtype(&ints), Ok(Int64));
11405 let floats: Vec<Scalar> = (0..n)
11406 .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
11407 .collect();
11408 assert_eq!(infer_dtype(&floats), Ok(Float64));
11409 let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
11410 assert_eq!(infer_dtype(&bools), Ok(Bool));
11411 let strs: Vec<Scalar> = (0..n)
11412 .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
11413 .collect();
11414 assert_eq!(infer_dtype(&strs), Ok(Utf8));
11415 }
11416
11417 assert_eq!(
11419 infer_dtype(&[
11420 Scalar::Int64(1),
11421 Scalar::Null(NullKind::Null),
11422 Scalar::Int64(2)
11423 ]),
11424 Ok(Int64),
11425 "Int64 + nulls -> Int64"
11426 );
11427 assert_eq!(
11428 infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
11429 Ok(Float64),
11430 "Int64 + Float64 -> Float64"
11431 );
11432 assert_eq!(
11436 infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
11437 Ok(Utf8),
11438 "Bool + Int64 -> object bucket (pandas constructs object)"
11439 );
11440 assert_eq!(
11441 infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
11442 Ok(Utf8),
11443 "Utf8 + Int64 -> Utf8 (object fallback)"
11444 );
11445 }
11446
11447 #[test]
11452 fn missing_for_dtype_always_missing_1ews0() {
11453 let all: [DType; 14] = [
11454 DType::Null,
11455 DType::Bool,
11456 DType::BoolNullable,
11457 DType::Int64,
11458 DType::Int64Nullable,
11459 DType::Float64,
11460 DType::Float64Nullable,
11461 DType::Utf8,
11462 DType::Categorical,
11463 DType::Timedelta64,
11464 DType::datetime64_naive(),
11465 DType::Period,
11466 DType::Interval,
11467 DType::Sparse,
11468 ];
11469 for dt in &all {
11470 let m = Scalar::missing_for_dtype(dt.clone());
11471 assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
11472 for target in &all {
11473 let cast = cast_scalar(&m, target.clone()).expect("cast of missing");
11474 if target == &DType::Utf8 {
11475 assert!(
11478 matches!(cast, Scalar::Utf8(_)),
11479 "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
11480 );
11481 } else if matches!(dt, DType::Timedelta64 | DType::Datetime64 { .. })
11482 && matches!(target, DType::Bool | DType::Int64)
11483 {
11484 match target {
11500 DType::Bool => assert_eq!(
11501 cast,
11502 Scalar::Bool(true),
11503 "cast(missing {dt:?} -> Bool) is pandas' nonzero-truthy \
11504 read of the NaT bits"
11505 ),
11506 _ => assert_eq!(
11507 cast,
11508 Scalar::Int64(i64::MIN),
11509 "cast(missing {dt:?} -> Int64) is the NaT sentinel itself"
11510 ),
11511 }
11512 } else {
11513 assert!(
11516 cast.is_missing(),
11517 "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
11518 );
11519 }
11520 }
11521 }
11522 }
11523
11524 #[test]
11525 fn cast_scalar_bool_int_roundtrip_6w07b() {
11526 use super::cast_scalar;
11527 assert_eq!(
11529 cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
11530 Scalar::Int64(1)
11531 );
11532 assert_eq!(
11533 cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
11534 Scalar::Int64(0)
11535 );
11536 assert_eq!(
11537 cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
11538 Scalar::Bool(false)
11539 );
11540 let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
11541 let mut next = || {
11542 st = st
11543 .wrapping_mul(6_364_136_223_846_793_005)
11544 .wrapping_add(1_442_695_040_888_963_407);
11545 (st >> 33) as u32
11546 };
11547 for _ in 0..2000u32 {
11548 let v = (next() % 21) as i64 - 10;
11549 assert_eq!(
11550 cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
11551 Scalar::Bool(v != 0),
11552 "int->bool v={v}"
11553 );
11554 }
11555 }
11556
11557 #[test]
11559 fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
11560 use super::cast_scalar;
11561 let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
11564 let mut next = || {
11565 st = st
11566 .wrapping_mul(6_364_136_223_846_793_005)
11567 .wrapping_add(1_442_695_040_888_963_407);
11568 (st >> 33) as u32
11569 };
11570 for (f, exp) in [
11572 (-3.7, -3i64),
11573 (3.7, 3),
11574 (-3.2, -3),
11575 (3.2, 3),
11576 (-0.9, 0),
11577 (0.9, 0),
11578 (-5.0, -5),
11579 (5.0, 5),
11580 ] {
11581 assert_eq!(
11582 cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
11583 Scalar::Int64(exp),
11584 "cast {f}"
11585 );
11586 }
11587 for _ in 0..3000u32 {
11589 let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
11591 assert_eq!(
11592 got,
11593 Scalar::Int64(v.trunc() as i64),
11594 "trunc-toward-zero v={v}"
11595 );
11596 }
11597 }
11598
11599 #[test]
11608 fn cast_scalar_float_to_temporal_truncates_to_nanoseconds() {
11609 use super::{Timedelta, Timestamp, cast_scalar};
11610
11611 for (input, want) in [
11614 (1.5_f64, 1_i64),
11615 (-1.5, -1),
11616 (0.9, 0),
11617 (-0.9, 0),
11618 (2.5, 2),
11619 (-2.5, -2),
11620 (1.999_999, 1),
11621 (-1.999_999, -1),
11622 (2.0, 2),
11623 (1e18, 1_000_000_000_000_000_000),
11624 ] {
11625 assert_eq!(
11626 cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11627 Scalar::Datetime64(want),
11628 "datetime64 cast of {input}"
11629 );
11630 assert_eq!(
11631 cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11632 Scalar::Timedelta64(want),
11633 "timedelta64 cast of {input}"
11634 );
11635 }
11636
11637 for input in [
11641 f64::NAN,
11642 f64::INFINITY,
11643 f64::NEG_INFINITY,
11644 1e30,
11645 -1e30,
11646 9.3e18,
11647 -9.3e18,
11648 9_223_372_036_854_775_808.0, -9_223_372_036_854_775_808.0, ] {
11651 assert_eq!(
11652 cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11653 Scalar::Datetime64(Timestamp::NAT),
11654 "datetime64 cast of {input} must be NaT"
11655 );
11656 assert_eq!(
11657 cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11658 Scalar::Timedelta64(Timedelta::NAT),
11659 "timedelta64 cast of {input} must be NaT"
11660 );
11661 }
11662
11663 let just_inside = 9_223_372_036_854_774_784.0_f64; assert_eq!(
11667 cast_scalar(&Scalar::Float64(just_inside), DType::datetime64_naive()).unwrap(),
11668 Scalar::Datetime64(9_223_372_036_854_774_784),
11669 "the largest representable float must NOT be treated as NaT"
11670 );
11671
11672 assert_eq!(
11675 cast_scalar(&Scalar::Float64(1.5), DType::datetime64_naive()).unwrap(),
11676 Scalar::Datetime64(1)
11677 );
11678 assert_eq!(
11679 cast_scalar(&Scalar::Float64(1.5), DType::Int64).unwrap(),
11680 Scalar::Int64(1),
11681 "the SHARED cast truncates here too; it is the explicit constructor \
11682 that refuses, via Column::new's LossyFloatToInt pre-check"
11683 );
11684 }
11685
11686 #[test]
11691 fn cast_scalar_temporal_to_int64_is_raw_nanoseconds() {
11692 use super::{Timedelta, Timestamp, cast_scalar};
11693
11694 for nanos in [1_710_498_645_123_456_789_i64, 93_784_005_006_007, 0, -1] {
11697 assert_eq!(
11698 cast_scalar(&Scalar::Datetime64(nanos), DType::Int64).unwrap(),
11699 Scalar::Int64(nanos),
11700 "datetime64 -> int64 must be the raw nanos ({nanos})"
11701 );
11702 assert_eq!(
11703 cast_scalar(&Scalar::Timedelta64(nanos), DType::Int64).unwrap(),
11704 Scalar::Int64(nanos)
11705 );
11706 }
11707
11708 assert_eq!(
11714 cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Int64).unwrap(),
11715 Scalar::Int64(i64::MIN),
11716 "NaT -> int64 is the sentinel i64::MIN, not a missing value"
11717 );
11718 assert_eq!(
11719 cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Int64).unwrap(),
11720 Scalar::Int64(i64::MIN)
11721 );
11722
11723 for target in [DType::Int64Nullable, DType::Float64, DType::Float64Nullable] {
11732 assert!(
11733 cast_scalar(
11734 &Scalar::Datetime64(1_710_498_645_123_456_789),
11735 target.clone()
11736 )
11737 .is_err(),
11738 "datetime64 -> {target:?} must stay refused"
11739 );
11740 assert!(
11741 cast_scalar(&Scalar::Timedelta64(93_784_005_006_007), target.clone()).is_err(),
11742 "timedelta64 -> {target:?} must stay refused"
11743 );
11744 }
11745
11746 for (flag, want) in [(true, 1_i64), (false, 0)] {
11748 assert_eq!(
11749 cast_scalar(&Scalar::Bool(flag), DType::datetime64_naive()).unwrap(),
11750 Scalar::Datetime64(want)
11751 );
11752 assert_eq!(
11753 cast_scalar(&Scalar::Bool(flag), DType::Timedelta64).unwrap(),
11754 Scalar::Timedelta64(want)
11755 );
11756 }
11757 }
11758
11759 #[test]
11763 fn timestamp_string_resolution_and_formatting_match_pandas() {
11764 use super::{DatetimeStringResolution as Res, Timestamp};
11765
11766 const MIDNIGHT: i64 = 1_710_460_800_000_000_000; assert_eq!(Timestamp::string_resolution(MIDNIGHT), Res::Date);
11770 assert_eq!(
11771 Timestamp::string_resolution(MIDNIGHT + 37_845_000_000_000),
11772 Res::Second
11773 );
11774 assert_eq!(
11775 Timestamp::string_resolution(MIDNIGHT + 37_845_123_000_000),
11776 Res::Milli
11777 );
11778 assert_eq!(
11779 Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_000),
11780 Res::Micro
11781 );
11782 assert_eq!(
11783 Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_789),
11784 Res::Nano
11785 );
11786 assert_eq!(
11788 Timestamp::string_resolution(MIDNIGHT + 300_000_000_000),
11789 Res::Second
11790 );
11791 assert_eq!(Timestamp::string_resolution(Timestamp::NAT), Res::Date);
11794
11795 assert!(Res::Date < Res::Second);
11797 assert!(Res::Second < Res::Milli);
11798 assert!(Res::Milli < Res::Micro);
11799 assert!(Res::Micro < Res::Nano);
11800
11801 let value = MIDNIGHT + 37_845_123_456_789;
11803 assert_eq!(
11804 Timestamp::format_at_resolution(value, Res::Date),
11805 "2024-03-15"
11806 );
11807 assert_eq!(
11808 Timestamp::format_at_resolution(value, Res::Second),
11809 "2024-03-15 10:30:45"
11810 );
11811 assert_eq!(
11812 Timestamp::format_at_resolution(value, Res::Milli),
11813 "2024-03-15 10:30:45.123"
11814 );
11815 assert_eq!(
11816 Timestamp::format_at_resolution(value, Res::Micro),
11817 "2024-03-15 10:30:45.123456"
11818 );
11819 assert_eq!(
11820 Timestamp::format_at_resolution(value, Res::Nano),
11821 "2024-03-15 10:30:45.123456789"
11822 );
11823
11824 assert_eq!(
11827 Timestamp::format_at_resolution(MIDNIGHT, Res::Nano),
11828 "2024-03-15 00:00:00.000000000"
11829 );
11830
11831 assert_eq!(
11833 Timestamp::format_at_resolution(MIDNIGHT, Res::Second),
11834 "2024-03-15 00:00:00"
11835 );
11836
11837 for resolution in [Res::Date, Res::Second, Res::Milli, Res::Micro, Res::Nano] {
11839 assert_eq!(
11840 Timestamp::format_at_resolution(Timestamp::NAT, resolution),
11841 "NaT"
11842 );
11843 }
11844
11845 assert_eq!(
11848 Timestamp::format_at_resolution(-1, Res::Nano),
11849 "1969-12-31 23:59:59.999999999"
11850 );
11851
11852 assert_eq!(
11854 Timestamp::format_at_resolution(-9_223_372_036_854_775_806, Res::Nano),
11855 "1677-09-21 00:12:43.145224194"
11856 );
11857 assert_eq!(
11858 Timestamp::format_at_resolution(9_223_372_036_854_775_807, Res::Nano),
11859 "2262-04-11 23:47:16.854775807"
11860 );
11861 }
11862
11863 #[test]
11867 fn cast_scalar_temporal_to_bool_is_nonzero_on_the_nanos() {
11868 use super::{Timedelta, Timestamp, cast_scalar};
11869
11870 for (nanos, want) in [
11872 (0_i64, false),
11873 (1_710_498_645_123_456_789, true),
11874 (-1, true),
11875 (86_400_000_000_000, true),
11876 (1, true),
11877 ] {
11878 assert_eq!(
11879 cast_scalar(&Scalar::Datetime64(nanos), DType::Bool).unwrap(),
11880 Scalar::Bool(want),
11881 "datetime64 {nanos} -> bool"
11882 );
11883 assert_eq!(
11884 cast_scalar(&Scalar::Timedelta64(nanos), DType::Bool).unwrap(),
11885 Scalar::Bool(want),
11886 "timedelta64 {nanos} -> bool"
11887 );
11888 }
11889
11890 assert_eq!(
11894 cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Bool).unwrap(),
11895 Scalar::Bool(true),
11896 "NaT -> bool is true in pandas, not a missing value"
11897 );
11898 assert_eq!(
11899 cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Bool).unwrap(),
11900 Scalar::Bool(true)
11901 );
11902
11903 for nanos in [0_i64, 1, -1, 1_710_498_645_123_456_789] {
11914 assert!(
11915 cast_scalar(&Scalar::Datetime64(nanos), DType::BoolNullable).is_err(),
11916 "datetime64 {nanos} -> nullable boolean must stay refused"
11917 );
11918 assert!(
11919 cast_scalar(&Scalar::Timedelta64(nanos), DType::BoolNullable).is_err(),
11920 "timedelta64 {nanos} -> nullable boolean must stay refused"
11921 );
11922 }
11923 }
11924
11925 #[test]
11926 fn nancount_nunique_prod_any_all_mx60x() {
11927 use super::{nanall, nanany, nancount, nannunique, nanprod};
11928 let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
11931 let mut next = || {
11932 s = s
11933 .wrapping_mul(6_364_136_223_846_793_005)
11934 .wrapping_add(1_442_695_040_888_963_407);
11935 (s >> 33) as u32
11936 };
11937 let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
11938 let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
11939 for iter in 0..1000u32 {
11940 let n = (next() % 10) as usize + 1;
11941 let raw: Vec<f64> = (0..n)
11942 .map(|_| {
11943 if next() % 4 == 0 {
11944 f64::NAN
11945 } else {
11946 (next() % 5) as f64
11947 }
11948 })
11949 .collect();
11950 let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
11951 if finite.is_empty() {
11952 continue;
11953 }
11954 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
11955 let distinct: std::collections::HashSet<u64> =
11956 finite.iter().map(|x| x.to_bits()).collect();
11957 let prod: f64 = finite.iter().product();
11958 assert!(
11959 (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
11960 "nancount iter={iter}"
11961 );
11962 assert!(
11963 (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
11964 "nannunique iter={iter}"
11965 );
11966 assert!(
11967 (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
11968 "nanprod iter={iter}"
11969 );
11970 assert_eq!(
11971 asb(nanany(&scalars)),
11972 finite.iter().any(|&x| x != 0.0),
11973 "nanany iter={iter}"
11974 );
11975 assert_eq!(
11976 asb(nanall(&scalars)),
11977 finite.iter().all(|&x| x != 0.0),
11978 "nanall iter={iter}"
11979 );
11980 }
11981 }
11982
11983 #[test]
11984 fn nan_reduction_kernels_skip_correctness_1uagc() {
11985 use super::{nanmax, nanmedian, nanmin, nansum};
11986 let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
11989 let mut next = || {
11990 s = s
11991 .wrapping_mul(6_364_136_223_846_793_005)
11992 .wrapping_add(1_442_695_040_888_963_407);
11993 (s >> 33) as u32
11994 };
11995 let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
11996 for iter in 0..1000u32 {
11997 let n = (next() % 12) as usize + 1;
11998 let raw: Vec<f64> = (0..n)
11999 .map(|_| {
12000 if next() % 4 == 0 {
12001 f64::NAN
12002 } else {
12003 (next() % 200) as f64 - 100.0
12004 }
12005 })
12006 .collect();
12007 let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
12008 if finite.is_empty() {
12009 continue;
12010 }
12011 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
12012 let sum: f64 = finite.iter().sum();
12013 let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
12014 let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
12015 finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
12016 let m = finite.len();
12017 let med = if m % 2 == 1 {
12018 finite[m / 2]
12019 } else {
12020 (finite[m / 2 - 1] + finite[m / 2]) / 2.0
12021 };
12022 assert!(
12023 (val(nansum(&scalars)) - sum).abs() < 1e-7,
12024 "nansum iter={iter}"
12025 );
12026 assert!(
12027 (val(nanmin(&scalars)) - mn).abs() < 1e-9,
12028 "nanmin iter={iter}"
12029 );
12030 assert!(
12031 (val(nanmax(&scalars)) - mx).abs() < 1e-9,
12032 "nanmax iter={iter}"
12033 );
12034 assert!(
12035 (val(nanmedian(&scalars)) - med).abs() < 1e-9,
12036 "nanmedian iter={iter}"
12037 );
12038 }
12039 }
12040
12041 #[test]
12042 fn nanvar_ddof_nanstd_nan_skip_p00ag() {
12043 use super::{nanmean, nanstd, nanvar};
12044 let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
12047 let mut next = || {
12048 s = s
12049 .wrapping_mul(6_364_136_223_846_793_005)
12050 .wrapping_add(1_442_695_040_888_963_407);
12051 (s >> 33) as u32
12052 };
12053 let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
12054 for iter in 0..1000u32 {
12055 let n = (next() % 10) as usize + 2;
12056 let raw: Vec<f64> = (0..n)
12057 .map(|_| {
12058 if next() % 4 == 0 {
12059 f64::NAN
12060 } else {
12061 (next() % 200) as f64 / 7.0
12062 }
12063 })
12064 .collect();
12065 let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
12066 if finite.len() < 2 {
12067 continue;
12068 }
12069 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
12070 let nf = finite.len() as f64;
12071 let mean = finite.iter().sum::<f64>() / nf;
12072 let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
12073 assert!(
12074 (val(nanmean(&scalars)) - mean).abs() < 1e-7,
12075 "nanmean iter={iter}"
12076 );
12077 assert!(
12078 (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
12079 "nanvar ddof0 iter={iter}"
12080 );
12081 assert!(
12082 (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
12083 "nanvar ddof1 iter={iter}"
12084 );
12085 assert!(
12086 (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
12087 "nanstd ddof1 iter={iter}"
12088 );
12089 }
12090 }
12091
12092 #[test]
12093 fn nanskew_nankurt_min_sample_and_known_xybnq() {
12094 use super::{nankurt, nanskew};
12097 let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
12098 let val = |s: Scalar| -> Option<f64> {
12099 if s.is_missing() {
12100 None
12101 } else {
12102 s.to_f64().ok()
12103 }
12104 };
12105
12106 assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
12108 let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
12109 assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
12110 let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
12111 assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
12112
12113 assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
12115 let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
12116 assert!(
12117 (k - (-1.2)).abs() < 1e-6,
12118 "pandas kurt([1..5]) == -1.2, got {k}"
12119 );
12120 }
12121
12122 #[test]
12123 #[ignore = "foreground release attribution harness"]
12124 fn nanskew_fused_moment_scan_ab_mavln() {
12125 const ROWS: usize = 100_000;
12126 const BATCH: usize = 8;
12127
12128 fn former(values: &[Scalar]) -> Scalar {
12129 let nums = super::collect_finite(values);
12130 let n = nums.len() as f64;
12131 if n < 3.0 {
12132 return Scalar::Null(NullKind::NaN);
12133 }
12134 let mean = nums.iter().sum::<f64>() / n;
12135 let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12136 let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
12137 let s2 = m2 / (n - 1.0);
12138 if s2 == 0.0 {
12139 return Scalar::Float64(0.0);
12140 }
12141 let s3 = s2.powf(1.5);
12142 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
12143 }
12144
12145 fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12146 match (former, candidate) {
12147 (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12148 (a, b) => assert_eq!(a, b),
12149 }
12150 }
12151
12152 fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
12153 std::hint::black_box(skew(std::hint::black_box(values)));
12154 let started = std::time::Instant::now();
12155 for _ in 0..BATCH {
12156 std::hint::black_box(skew(std::hint::black_box(values)));
12157 }
12158 started.elapsed().as_nanos()
12159 }
12160
12161 fn median(samples: &mut [u128]) -> u128 {
12162 samples.sort_unstable();
12163 samples[samples.len() / 2]
12164 }
12165
12166 for values in [
12167 vec![],
12168 vec![Scalar::Int64(1), Scalar::Int64(2)],
12169 vec![Scalar::Int64(7); 16],
12170 vec![
12171 Scalar::Int64(-3),
12172 Scalar::Null(NullKind::NaN),
12173 Scalar::Float64(2.5),
12174 Scalar::Utf8("skip".to_owned()),
12175 Scalar::Int64(11),
12176 ],
12177 ] {
12178 assert_bits_eq(former(&values), super::nanskew(&values));
12179 }
12180
12181 let values = (0..ROWS)
12182 .map(|i| {
12183 if i % 257 == 0 {
12184 Scalar::Null(NullKind::NaN)
12185 } else {
12186 Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12187 }
12188 })
12189 .collect::<Vec<_>>();
12190 assert_bits_eq(former(&values), super::nanskew(&values));
12191
12192 for _ in 0..2 {
12193 std::hint::black_box(elapsed(&values, former));
12194 std::hint::black_box(elapsed(&values, super::nanskew));
12195 }
12196
12197 let mut former_samples = Vec::with_capacity(18);
12198 let mut candidate_samples = Vec::with_capacity(18);
12199 for block in 0_usize..9 {
12200 if block.is_multiple_of(2) {
12201 former_samples.push(elapsed(&values, former));
12202 candidate_samples.push(elapsed(&values, super::nanskew));
12203 candidate_samples.push(elapsed(&values, super::nanskew));
12204 former_samples.push(elapsed(&values, former));
12205 } else {
12206 candidate_samples.push(elapsed(&values, super::nanskew));
12207 former_samples.push(elapsed(&values, former));
12208 former_samples.push(elapsed(&values, former));
12209 candidate_samples.push(elapsed(&values, super::nanskew));
12210 }
12211 }
12212
12213 let former_p50 = median(&mut former_samples);
12214 let candidate_p50 = median(&mut candidate_samples);
12215 eprintln!(
12216 "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12217 former_p50 as f64 / candidate_p50 as f64,
12218 );
12219 eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
12220 eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12221 }
12222
12223 #[test]
12224 #[ignore = "foreground performance probe"]
12225 fn nankurt_fused_moment_scan_ab_idka7() {
12226 const ROWS: usize = 65_536;
12227 const BATCH: usize = 4;
12228
12229 fn former(values: &[Scalar]) -> Scalar {
12230 let nums = super::collect_finite(values);
12231 let n = nums.len() as f64;
12232 if n < 4.0 {
12233 return Scalar::Null(NullKind::NaN);
12234 }
12235 let mean = nums.iter().sum::<f64>() / n;
12236 let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12237 let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
12238 let s2 = m2 / (n - 1.0);
12239 if s2 == 0.0 {
12240 return Scalar::Float64(0.0);
12241 }
12242 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
12243 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
12244 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
12245 }
12246
12247 fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12248 match (former, candidate) {
12249 (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12250 (a, b) => assert_eq!(a, b),
12251 }
12252 }
12253
12254 fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
12255 let started = std::time::Instant::now();
12256 for _ in 0..BATCH {
12257 std::hint::black_box(kurt(std::hint::black_box(values)));
12258 }
12259 started.elapsed().as_nanos()
12260 }
12261
12262 fn median(samples: &mut [u128]) -> u128 {
12263 samples.sort_unstable();
12264 samples[samples.len() / 2]
12265 }
12266
12267 for values in [
12268 vec![],
12269 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12270 vec![Scalar::Int64(7); 16],
12271 vec![
12272 Scalar::Int64(-3),
12273 Scalar::Null(NullKind::NaN),
12274 Scalar::Float64(2.5),
12275 Scalar::Utf8("skip".to_owned()),
12276 Scalar::Int64(11),
12277 Scalar::Float64(-7.25),
12278 ],
12279 ] {
12280 assert_bits_eq(former(&values), super::nankurt(&values));
12281 }
12282
12283 let values = (0..ROWS)
12284 .map(|i| {
12285 if i % 257 == 0 {
12286 Scalar::Null(NullKind::NaN)
12287 } else {
12288 Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12289 }
12290 })
12291 .collect::<Vec<_>>();
12292 assert_bits_eq(former(&values), super::nankurt(&values));
12293
12294 for _ in 0..2 {
12295 std::hint::black_box(elapsed(&values, former));
12296 std::hint::black_box(elapsed(&values, super::nankurt));
12297 }
12298
12299 let mut former_samples = Vec::with_capacity(10);
12300 let mut candidate_samples = Vec::with_capacity(10);
12301 for block in 0_usize..5 {
12302 if block.is_multiple_of(2) {
12303 former_samples.push(elapsed(&values, former));
12304 candidate_samples.push(elapsed(&values, super::nankurt));
12305 candidate_samples.push(elapsed(&values, super::nankurt));
12306 former_samples.push(elapsed(&values, former));
12307 } else {
12308 candidate_samples.push(elapsed(&values, super::nankurt));
12309 former_samples.push(elapsed(&values, former));
12310 former_samples.push(elapsed(&values, former));
12311 candidate_samples.push(elapsed(&values, super::nankurt));
12312 }
12313 }
12314
12315 let former_p50 = median(&mut former_samples);
12316 let candidate_p50 = median(&mut candidate_samples);
12317 eprintln!(
12318 "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12319 former_p50 as f64 / candidate_p50 as f64,
12320 );
12321 eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
12322 eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12323 }
12324
12325 #[test]
12328 fn cast_scalar_to_utf8_formatting_yes7i() {
12329 let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
12332 let mut next = || {
12333 st = st
12334 .wrapping_mul(6_364_136_223_846_793_005)
12335 .wrapping_add(1_442_695_040_888_963_407);
12336 (st >> 33) as u32
12337 };
12338 for _ in 0..3000u32 {
12339 let n = (next() % 4_000_001) as i64 - 2_000_000;
12340 assert_eq!(
12341 cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
12342 Scalar::Utf8(n.to_string())
12343 );
12344 }
12345 assert_eq!(
12346 cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
12347 Scalar::Utf8("True".to_string())
12348 );
12349 assert_eq!(
12350 cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
12351 Scalar::Utf8("False".to_string())
12352 );
12353 }
12354
12355 #[test]
12356 fn cast_scalar_coercion_rules_6a83t() {
12357 let mut state: u64 = 0x5a17_c0de_1234_abcd;
12358 let mut next = || {
12359 state = state
12360 .wrapping_mul(6_364_136_223_846_793_005)
12361 .wrapping_add(1_442_695_040_888_963_407);
12362 (state >> 33) as u32
12363 };
12364
12365 for _ in 0..4000u32 {
12366 let n = (next() % 21) as i64 - 10; let b = next() % 2 == 0;
12368 let f = f64::from((next() % 41) as i32 - 20) / 4.0; let i = Scalar::Int64(n);
12371 let bo = Scalar::Bool(b);
12372 let fl = Scalar::Float64(f);
12373
12374 assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
12376 assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
12377 assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
12378
12379 assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
12381 assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
12382
12383 assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
12385 assert_eq!(
12386 cast_scalar(&i, DType::Float64),
12387 Ok(Scalar::Float64(n as f64))
12388 );
12389
12390 assert_eq!(
12392 cast_scalar(&bo, DType::Int64),
12393 Ok(Scalar::Int64(i64::from(b)))
12394 );
12395 assert_eq!(
12396 cast_scalar(&bo, DType::Float64),
12397 Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
12398 );
12399
12400 assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
12402 }
12403 }
12404
12405 #[test]
12407 fn scalar_from_primitive_types() {
12408 assert_eq!(Scalar::from(true), Scalar::Bool(true));
12410 assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
12411 assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
12412 assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
12413 assert_eq!(
12414 Scalar::from(String::from("world")),
12415 Scalar::Utf8("world".to_owned())
12416 );
12417
12418 let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
12422 assert_eq!(mixed[0], Scalar::Int64(1));
12423 assert_eq!(mixed[1], Scalar::Float64(2.0));
12424 assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
12425 }
12426
12427 #[test]
12428 fn dtype_inference_routes_bool_numeric_mix_to_object_bucket_rh1od() {
12429 let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
12434 assert_eq!(
12435 infer_dtype(&values).expect("dtype should infer"),
12436 DType::Utf8
12437 );
12438 }
12439
12440 #[test]
12441 fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
12442 let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
12443 let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
12444 assert_eq!(left.dtype(), DType::Interval);
12445 assert!(!left.is_missing());
12446 assert_eq!(
12447 infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
12448 DType::Interval
12449 );
12450 assert_eq!(
12451 common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
12452 DType::Interval
12453 );
12454 assert_eq!(
12455 cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
12456 Scalar::Null(NullKind::Null)
12457 );
12458 assert_eq!(
12459 cast_scalar(&left, DType::Utf8).expect("interval string cast"),
12460 Scalar::Utf8("(0.0, 1.0]".to_owned())
12461 );
12462 assert_eq!(
12463 super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
12464 Scalar::Int64(2)
12465 );
12466 }
12467
12468 #[test]
12469 fn cast_scalar_parses_temporal_extension_strings_avm08() {
12470 let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
12471 .expect("timestamp parse")
12472 .nanos;
12473 assert_eq!(
12474 cast_scalar(
12475 &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
12476 DType::datetime64_naive()
12477 )
12478 .expect("datetime cast"),
12479 Scalar::Datetime64(expected_nanos)
12480 );
12481 assert_eq!(
12482 cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
12483 Scalar::Period(Period::new(216, PeriodFreq::QUARTERLY))
12484 );
12485 assert_eq!(
12486 cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
12487 .expect("interval cast"),
12488 Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
12489 );
12490 }
12491
12492 #[test]
12493 fn missing_values_get_target_missing_marker() {
12494 let missing = Scalar::Null(NullKind::Null);
12495 let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
12496 assert_eq!(cast, Scalar::Null(NullKind::NaN));
12497 }
12498
12499 #[test]
12500 fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
12501 let cases = [
12502 (Scalar::Bool(true), "True"),
12503 (Scalar::Bool(false), "False"),
12504 (Scalar::Int64(-7), "-7"),
12505 (Scalar::Float64(1.0), "1.0"),
12506 (Scalar::Float64(1.5), "1.5"),
12507 (Scalar::Float64(f64::NAN), "nan"),
12508 (Scalar::Null(NullKind::Null), "None"),
12509 (Scalar::Null(NullKind::NaN), "nan"),
12510 (Scalar::Null(NullKind::NaT), "NaT"),
12511 ];
12512
12513 for (value, expected) in cases {
12514 assert_eq!(
12515 cast_scalar(&value, DType::Utf8).expect("cast"),
12516 Scalar::Utf8(expected.to_owned())
12517 );
12518 }
12519 }
12520
12521 #[test]
12522 fn semantic_eq_treats_nan_as_equal() {
12523 let left = Scalar::Float64(f64::NAN);
12524 let right = Scalar::Null(NullKind::NaN);
12525 assert!(left.semantic_eq(&right));
12526 }
12527
12528 #[test]
12529 fn semantic_eq_treats_nan_as_missing_null() {
12530 let left = Scalar::Float64(f64::NAN);
12531 let right = Scalar::Null(NullKind::Null);
12532 assert!(left.semantic_eq(&right));
12533 }
12534
12535 #[test]
12554 fn semantic_eq_unifies_dtype_sentinel_missing_with_null_xwxci() {
12555 for sentinel in [
12556 Scalar::Timedelta64(Timedelta::NAT),
12557 Scalar::Datetime64(Timestamp::NAT),
12558 Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
12559 ] {
12560 assert!(sentinel.is_missing(), "{sentinel:?} must report missing");
12561 for marker in [
12562 Scalar::Null(NullKind::Null),
12563 Scalar::Null(NullKind::NaN),
12564 Scalar::Null(NullKind::NaT),
12565 ] {
12566 assert!(
12567 sentinel.semantic_eq(&marker),
12568 "{sentinel:?} vs {marker:?} are both missing"
12569 );
12570 assert!(marker.semantic_eq(&sentinel), "and symmetrically");
12571 }
12572 }
12573
12574 let present = Scalar::Timedelta64(-60);
12576 assert!(!Scalar::Timedelta64(Timedelta::NAT).semantic_eq(&present));
12577 assert!(!present.semantic_eq(&Scalar::Null(NullKind::Null)));
12578 assert!(!present.semantic_eq(&Scalar::Timedelta64(-61)));
12580 }
12581
12582 #[test]
12583 fn common_dtype_rejects_string_numeric_mix() {
12584 let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
12585 assert_eq!(
12586 err.to_string(),
12587 "dtype coercion from Utf8 to Int64 has no compatible common type"
12588 );
12589 let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
12590 assert_eq!(
12591 err.to_string(),
12592 "dtype coercion from Float64 to Utf8 has no compatible common type"
12593 );
12594 }
12595
12596 #[test]
12597 fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
12598 let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
12599
12600 assert_eq!(dtype.value_dtype, DType::Float64);
12601 assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
12602 }
12603
12604 #[test]
12605 fn sparse_dtype_rejects_sparse_value_dtype() {
12606 let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
12607
12608 assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
12609 }
12610
12611 #[test]
12612 fn common_dtype_rejects_sparse_dense_mix() {
12613 let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
12614
12615 assert_eq!(
12616 err.to_string(),
12617 "dtype coercion from Sparse to Int64 has no compatible common type"
12618 );
12619 }
12620
12621 #[test]
12624 fn nullable_int64_promotion_matrix() {
12625 assert_eq!(
12627 common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
12628 DType::Int64Nullable
12629 );
12630 assert_eq!(
12631 common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
12632 DType::Int64Nullable
12633 );
12634
12635 assert_eq!(
12642 common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
12643 DType::Float64Nullable
12644 );
12645 assert_eq!(
12646 common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
12647 DType::Float64Nullable
12648 );
12649
12650 assert_eq!(
12652 common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
12653 DType::Int64Nullable
12654 );
12655
12656 assert_eq!(
12658 common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
12659 DType::Int64Nullable
12660 );
12661
12662 assert_eq!(
12664 common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
12665 DType::Int64Nullable
12666 );
12667 }
12668
12669 #[test]
12670 fn nullable_bool_promotion_matrix() {
12671 assert_eq!(
12673 common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
12674 DType::BoolNullable
12675 );
12676 assert_eq!(
12677 common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
12678 DType::BoolNullable
12679 );
12680
12681 assert_eq!(
12688 common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
12689 DType::Float64Nullable
12690 );
12691
12692 assert_eq!(
12695 common_dtype(DType::Bool, DType::Float64).unwrap(),
12696 DType::Float64
12697 );
12698 }
12699
12700 #[test]
12701 fn dtype_is_nullable_helper() {
12702 assert!(DType::Int64Nullable.is_nullable());
12703 assert!(DType::BoolNullable.is_nullable());
12704 assert!(!DType::Int64.is_nullable());
12705 assert!(!DType::Bool.is_nullable());
12706 assert!(!DType::Float64.is_nullable());
12707 assert!(!DType::Utf8.is_nullable());
12708 }
12709
12710 #[test]
12711 fn dtype_to_nullable_conversions() {
12712 assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
12713 assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
12714 assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
12724 assert_eq!(
12725 DType::Float64Nullable.to_nullable(),
12726 DType::Float64Nullable,
12727 "idempotent: already nullable"
12728 );
12729 assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
12730 }
12731
12732 #[test]
12733 fn dtype_to_non_nullable_conversions() {
12734 assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
12735 assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
12736 assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
12738 }
12739
12740 #[test]
12741 fn nullable_dtype_name_reports_pandas_style() {
12742 assert_eq!(DType::Int64.name(), "int64");
12743 assert_eq!(DType::Int64Nullable.name(), "Int64"); assert_eq!(DType::Bool.name(), "bool");
12745 assert_eq!(DType::BoolNullable.name(), "boolean");
12746 }
12747
12748 #[test]
12749 fn cast_scalar_int64_nullable_identity() {
12750 let val = Scalar::Int64(42);
12751 let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
12753 assert_eq!(result, Scalar::Int64(42));
12754
12755 let result2 = cast_scalar(&val, DType::Int64).unwrap();
12757 assert_eq!(result2, Scalar::Int64(42));
12758 }
12759
12760 #[test]
12761 fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
12762 let cases: &[(f64, &str)] = &[
12767 (1.0, "1.0"),
12768 (2.5, "2.5"),
12769 (100.0, "100.0"),
12770 (0.1, "0.1"),
12771 (0.0001, "0.0001"),
12772 (1e16, "1e+16"),
12773 (1e20, "1e+20"),
12774 (1e-5, "1e-05"),
12775 (1e-7, "1e-07"),
12776 (f64::INFINITY, "inf"),
12777 (f64::NEG_INFINITY, "-inf"),
12778 ];
12779 for (v, expected) in cases {
12780 assert_eq!(
12781 cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
12782 Scalar::Utf8((*expected).to_owned()),
12783 "float {v} -> str"
12784 );
12785 }
12786 }
12787
12788 fn float_to_string_for_astype_former(value: f64) -> String {
12789 if value.is_nan() {
12790 return "nan".to_owned();
12791 }
12792 if value.is_infinite() {
12793 return value.to_string();
12794 }
12795 let rendered = format!("{value:?}");
12796 match rendered.split_once('e') {
12797 None => rendered,
12798 Some((mantissa, exponent)) => {
12799 let (sign, digits) = match exponent.strip_prefix('-') {
12800 Some(digits) => ('-', digits),
12801 None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
12802 };
12803 format!("{mantissa}e{sign}{digits:0>2}")
12804 }
12805 }
12806 }
12807
12808 fn scientific_astype_values(len: usize) -> Vec<f64> {
12809 const EXPONENTS: [i32; 16] = [
12810 -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
12811 ];
12812 (0..len)
12813 .map(|position| {
12814 let mantissa = 1.0 + (position % 997) as f64 / 997.0;
12815 let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
12816 if position.is_multiple_of(2) {
12817 magnitude
12818 } else {
12819 -magnitude
12820 }
12821 })
12822 .collect()
12823 }
12824
12825 #[test]
12826 fn float_to_string_for_astype_in_place_matches_former() {
12827 let fixed = [
12828 f64::NAN,
12829 f64::INFINITY,
12830 f64::NEG_INFINITY,
12831 0.0,
12832 -0.0,
12833 f64::MIN_POSITIVE,
12834 f64::MAX,
12835 f64::MIN,
12836 1e16,
12837 -1e16,
12838 1e-5,
12839 -1e-5,
12840 1.234_567_890_123_456_8e20,
12841 -9.876_543_210_987_654e-123,
12842 ];
12843 for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
12844 assert_eq!(
12845 super::float_to_string_for_astype(value),
12846 float_to_string_for_astype_former(value),
12847 "value={value:?}"
12848 );
12849 }
12850 }
12851
12852 #[test]
12853 #[ignore = "foreground performance probe"]
12854 fn float_to_string_for_astype_in_place_ab() {
12855 use std::time::Instant;
12856
12857 const VALUES: usize = 16_384;
12858 const SAMPLES: usize = 10;
12859 let values = scientific_astype_values(VALUES);
12860 for &value in &values {
12861 let former = float_to_string_for_astype_former(value);
12862 assert!(former.contains('e'), "benchmark value must be scientific");
12863 assert_eq!(super::float_to_string_for_astype(value), former);
12864 }
12865
12866 for _ in 0..2 {
12867 for &value in &values {
12868 std::hint::black_box(float_to_string_for_astype_former(value));
12869 std::hint::black_box(super::float_to_string_for_astype(value));
12870 }
12871 }
12872
12873 let mut former_ns = Vec::with_capacity(SAMPLES);
12874 let mut public_ns = Vec::with_capacity(SAMPLES);
12875 for sample in 0..SAMPLES {
12876 let run = |formatter: fn(f64) -> String| {
12877 let started = Instant::now();
12878 for &value in std::hint::black_box(&values) {
12879 std::hint::black_box(formatter(std::hint::black_box(value)));
12880 }
12881 started.elapsed().as_nanos()
12882 };
12883 if sample.is_multiple_of(2) {
12884 former_ns.push(run(float_to_string_for_astype_former));
12885 public_ns.push(run(super::float_to_string_for_astype));
12886 } else {
12887 public_ns.push(run(super::float_to_string_for_astype));
12888 former_ns.push(run(float_to_string_for_astype_former));
12889 }
12890 }
12891
12892 former_ns.sort_unstable();
12893 public_ns.sort_unstable();
12894 let former_p50 = former_ns[SAMPLES / 2];
12895 let public_p50 = public_ns[SAMPLES / 2];
12896 println!(
12897 "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:?}",
12898 former_p50 as f64 / public_p50 as f64
12899 );
12900 }
12901
12902 #[test]
12903 fn cast_float_to_utf8_threshold_boundaries_match_python() {
12904 let cases: &[(f64, &str)] = &[
12909 (1e15, "1000000000000000.0"),
12910 (9_999_999_999_999_998.0, "9999999999999998.0"),
12911 (1_234_567_890_123_456.0, "1234567890123456.0"),
12912 (123_456_789_012_345.0, "123456789012345.0"),
12913 (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
12914 (1e16, "1e+16"),
12915 (1.5e16, "1.5e+16"),
12916 (1e17, "1e+17"),
12917 (1e-4, "0.0001"),
12918 (5e-5, "5e-05"),
12919 (-1e15, "-1000000000000000.0"),
12920 (-1e16, "-1e+16"),
12921 (-1e-5, "-1e-05"),
12922 ];
12923 for (v, expected) in cases {
12924 assert_eq!(
12925 cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
12926 Scalar::Utf8((*expected).to_owned()),
12927 "float {v} -> str"
12928 );
12929 }
12930 }
12931
12932 #[test]
12933 fn cast_to_bool_uses_pandas_nonzero_truthiness() {
12934 let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
12938 for (v, expected) in cases_int {
12939 assert_eq!(
12940 cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
12941 Scalar::Bool(*expected),
12942 "int {v} -> bool"
12943 );
12944 }
12945 let cases_float: &[(f64, bool)] = &[
12946 (0.0, false),
12947 (-0.0, false),
12948 (0.1, true),
12949 (2.5, true),
12950 (1.0, true),
12951 (f64::NAN, true),
12953 ];
12954 for (v, expected) in cases_float {
12955 assert_eq!(
12956 cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
12957 Scalar::Bool(*expected),
12958 "float {v} -> bool"
12959 );
12960 }
12961 }
12962
12963 #[test]
12964 fn nullable_dtype_is_extension() {
12965 assert!(DType::Int64Nullable.is_extension());
12966 assert!(DType::BoolNullable.is_extension());
12967 assert!(!DType::Int64.is_extension());
12968 assert!(!DType::Bool.is_extension());
12969 }
12970
12971 #[test]
12972 fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
12973 let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
12974 assert_eq!(
12975 infer_dtype(&values).expect("dtype should infer"),
12976 DType::Utf8
12977 );
12978 }
12979
12980 #[test]
12981 fn infer_dtype_routes_bool_numeric_mix_to_utf8_object_bucket_rh1od() {
12982 let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Bool(false)];
12988 assert_eq!(
12989 infer_dtype(&values).expect("dtype should infer"),
12990 DType::Utf8
12991 );
12992 let with_float = vec![Scalar::Int64(1), Scalar::Float64(2.5), Scalar::Bool(true)];
12993 assert_eq!(
12994 infer_dtype(&with_float).expect("dtype should infer"),
12995 DType::Utf8
12996 );
12997 let with_null = vec![
12998 Scalar::Bool(true),
12999 Scalar::Null(NullKind::Null),
13000 Scalar::Int64(2),
13001 ];
13002 assert_eq!(
13003 infer_dtype(&with_null).expect("dtype should infer"),
13004 DType::Utf8
13005 );
13006 }
13007
13008 #[test]
13009 fn infer_dtype_keeps_nonmixed_bool_and_numeric_paths_rh1od() {
13010 assert_eq!(
13014 infer_dtype(&[Scalar::Bool(true), Scalar::Bool(false)]).expect("dtype should infer"),
13015 DType::Bool
13016 );
13017 assert_eq!(
13018 infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]).expect("dtype should infer"),
13019 DType::Float64
13020 );
13021 }
13022
13023 #[test]
13026 fn is_null_detects_explicit_nulls() {
13027 assert!(Scalar::Null(NullKind::Null).is_null());
13028 assert!(Scalar::Null(NullKind::NaN).is_null());
13029 assert!(!Scalar::Int64(42).is_null());
13030 assert!(!Scalar::Float64(f64::NAN).is_null());
13031 }
13032
13033 #[test]
13034 fn is_na_matches_is_missing() {
13035 let vals = vec![
13036 Scalar::Null(NullKind::Null),
13037 Scalar::Float64(f64::NAN),
13038 Scalar::Int64(0),
13039 Scalar::Bool(false),
13040 ];
13041 for v in &vals {
13042 assert_eq!(v.is_na(), v.is_missing());
13043 }
13044 }
13045
13046 #[test]
13047 fn coalesce_picks_first_non_missing() {
13048 let null = Scalar::Null(NullKind::Null);
13049 let fill = Scalar::Int64(99);
13050 assert_eq!(null.coalesce(&fill), fill);
13051 assert_eq!(fill.coalesce(&null), fill);
13052 }
13053
13054 #[test]
13057 fn isna_notna_complement() {
13058 let vals = vec![
13059 Scalar::Int64(1),
13060 Scalar::Null(NullKind::Null),
13061 Scalar::Float64(f64::NAN),
13062 Scalar::Float64(3.0),
13063 ];
13064 let na = super::isna(&vals);
13065 let not = super::notna(&vals);
13066 assert_eq!(na, vec![false, true, true, false]);
13067 for (a, b) in na.iter().zip(not.iter()) {
13068 assert_ne!(a, b);
13069 }
13070 }
13071
13072 #[test]
13073 fn count_na_counts_missing() {
13074 let vals = vec![
13075 Scalar::Int64(1),
13076 Scalar::Null(NullKind::Null),
13077 Scalar::Float64(f64::NAN),
13078 ];
13079 assert_eq!(super::count_na(&vals), 2);
13080 }
13081
13082 #[test]
13083 fn fill_na_replaces_missing() {
13084 let vals = vec![
13085 Scalar::Int64(1),
13086 Scalar::Null(NullKind::Null),
13087 Scalar::Float64(f64::NAN),
13088 Scalar::Int64(4),
13089 ];
13090 let filled = super::fill_na(&vals, &Scalar::Int64(0));
13091 assert_eq!(filled[0], Scalar::Int64(1));
13092 assert_eq!(filled[1], Scalar::Int64(0));
13093 assert_eq!(filled[2], Scalar::Int64(0));
13094 assert_eq!(filled[3], Scalar::Int64(4));
13095 }
13096
13097 #[test]
13098 fn dropna_removes_missing() {
13099 let vals = vec![
13100 Scalar::Int64(1),
13101 Scalar::Null(NullKind::Null),
13102 Scalar::Int64(3),
13103 Scalar::Float64(f64::NAN),
13104 ];
13105 let kept = super::dropna(&vals);
13106 assert_eq!(kept.len(), 2);
13107 assert_eq!(kept[0], Scalar::Int64(1));
13108 assert_eq!(kept[1], Scalar::Int64(3));
13109 }
13110
13111 #[test]
13112 fn null_helpers_match_scalar_oracle_imt0c() {
13113 fn next(seed: &mut u64) -> u64 {
13116 *seed = seed
13117 .wrapping_mul(3202034522624059733)
13118 .wrapping_add(4354685564936845319);
13119 *seed
13120 }
13121
13122 fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
13123 let expected_missing = values.iter().filter(|value| value.is_missing()).count();
13124 let expected_dropped = values
13125 .iter()
13126 .filter(|value| !value.is_missing())
13127 .cloned()
13128 .collect::<Vec<_>>();
13129 let expected_filled = values
13130 .iter()
13131 .map(|value| {
13132 if value.is_missing() {
13133 fill.clone()
13134 } else {
13135 value.clone()
13136 }
13137 })
13138 .collect::<Vec<_>>();
13139
13140 assert_eq!(
13141 super::count_na(values),
13142 expected_missing,
13143 "case={case}: count_na mismatch for {values:?}"
13144 );
13145
13146 let dropped = super::dropna(values);
13147 assert_eq!(
13148 dropped.len(),
13149 expected_dropped.len(),
13150 "case={case}: dropna length mismatch for {values:?}"
13151 );
13152 for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
13153 {
13154 assert!(
13155 actual.semantic_eq(expected),
13156 "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
13157 );
13158 }
13159
13160 let filled = super::fill_na(values, fill);
13161 assert_eq!(
13162 filled.len(),
13163 expected_filled.len(),
13164 "case={case}: fill_na length mismatch for {values:?}"
13165 );
13166 for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
13167 assert!(
13168 actual.semantic_eq(expected),
13169 "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
13170 );
13171 }
13172 }
13173
13174 let all_missing = [
13175 Scalar::Null(NullKind::Null),
13176 Scalar::Null(NullKind::NaN),
13177 Scalar::Float64(f64::NAN),
13178 Scalar::Timedelta64(i64::MIN),
13179 ];
13180 assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
13181
13182 let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
13183 for case in 0..260 {
13184 let len = (next(&mut seed) % 83 + 1) as usize;
13185 let mut values = Vec::with_capacity(len);
13186 for pos in 0..len {
13187 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13188 values.push(match next(&mut seed) % 11 {
13189 0 => Scalar::Null(NullKind::Null),
13190 1 => Scalar::Null(NullKind::NaN),
13191 2 => Scalar::Float64(f64::NAN),
13192 3 => Scalar::Timedelta64(i64::MIN),
13193 4 => Scalar::Bool(raw & 1 == 0),
13194 5 => Scalar::Int64(raw),
13195 6 => Scalar::Float64(raw as f64 / 37.0),
13196 7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
13197 8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
13198 9 => Scalar::Utf8(String::new()),
13199 _ => Scalar::Timedelta64(raw),
13200 });
13201 }
13202
13203 let fill = match case % 5 {
13204 0 => Scalar::Bool(true),
13205 1 => Scalar::Int64(-777),
13206 2 => Scalar::Float64(12.5),
13207 3 => Scalar::Utf8("filled".into()),
13208 _ => Scalar::Timedelta64(123_456),
13209 };
13210 assert_null_helpers(case, &values, &fill);
13211 }
13212 }
13213
13214 #[test]
13217 fn nansum_skips_nulls() {
13218 let vals = vec![
13219 Scalar::Float64(1.0),
13220 Scalar::Null(NullKind::Null),
13221 Scalar::Float64(2.0),
13222 Scalar::Float64(f64::NAN),
13223 Scalar::Int64(7),
13224 ];
13225 assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
13226 }
13227
13228 #[test]
13229 fn nansum_empty_returns_zero() {
13230 assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
13231 }
13232
13233 #[test]
13234 fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
13235 fn next(seed: &mut u64) -> u64 {
13238 *seed = seed
13239 .wrapping_mul(6364136223846793005)
13240 .wrapping_add(1442695040888963407);
13241 *seed
13242 }
13243
13244 fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
13245 let mut sum = 0.0;
13246 let mut count = 0usize;
13247 for value in values {
13248 if value.is_missing() {
13249 continue;
13250 }
13251 if let Ok(value) = value.to_f64() {
13252 sum += value;
13253 count += 1;
13254 }
13255 }
13256 let mean = if count == 0 {
13257 Scalar::Null(NullKind::NaN)
13258 } else {
13259 Scalar::Float64(sum / count as f64)
13260 };
13261 (Scalar::Float64(sum), mean)
13262 }
13263
13264 fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
13265 let mut sum = 0_i128;
13266 let mut count = 0_i128;
13267 for value in values {
13268 if let Scalar::Timedelta64(ns) = value
13269 && !value.is_missing()
13270 {
13271 sum += i128::from(*ns);
13272 count += 1;
13273 }
13274 }
13275 if count == 0 {
13276 return (Scalar::Timedelta64(0), Scalar::Timedelta64(Timedelta::NAT));
13277 }
13278 (
13284 super::timedelta_ns_to_scalar(sum),
13285 super::timedelta_ns_to_scalar(sum / count),
13286 )
13287 }
13288
13289 fn assert_sum_mean(
13290 case: usize,
13291 family: &str,
13292 values: &[Scalar],
13293 expected_sum: Scalar,
13294 expected_mean: Scalar,
13295 ) {
13296 let actual_sum = super::nansum(values);
13297 let actual_mean = super::nanmean(values);
13298 assert!(
13299 actual_sum.semantic_eq(&expected_sum),
13300 "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
13301 );
13302 assert!(
13303 actual_mean.semantic_eq(&expected_mean),
13304 "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
13305 );
13306 }
13307
13308 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13309 let (sum, mean) = expected_numeric(&all_missing);
13310 assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
13311
13312 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
13313 let (sum, mean) = expected_timedelta(&td_all_missing);
13314 assert_sum_mean(
13315 usize::MAX - 1,
13316 "timedelta_all_missing",
13317 &td_all_missing,
13318 sum,
13319 mean,
13320 );
13321
13322 let mut seed = 0x511d_ed5a_7a11_1a55_u64;
13323 for case in 0..260 {
13324 let len = (next(&mut seed) % 89 + 1) as usize;
13325
13326 let mut numeric = Vec::with_capacity(len);
13327 numeric.push(Scalar::Int64(case as i64 - 130));
13328 for _ in 1..len {
13329 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13330 numeric.push(match next(&mut seed) % 8 {
13331 0 => Scalar::Null(NullKind::Null),
13332 1 => Scalar::Null(NullKind::NaN),
13333 2 => Scalar::Float64(f64::NAN),
13334 3 => Scalar::Bool(raw & 1 == 0),
13335 4 => Scalar::Int64(raw % 257),
13336 5 => Scalar::Float64(raw as f64 / 67.0),
13337 6 => Scalar::Float64(0.0),
13338 _ => Scalar::Float64(-0.0),
13339 });
13340 }
13341 let (sum, mean) = expected_numeric(&numeric);
13342 assert_sum_mean(case, "numeric", &numeric, sum, mean);
13343
13344 let mut timedeltas = Vec::with_capacity(len);
13345 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
13346 for _ in 1..len {
13347 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13348 timedeltas.push(match next(&mut seed) % 7 {
13349 0 => Scalar::Null(NullKind::Null),
13350 1 => Scalar::Timedelta64(i64::MIN),
13351 _ => Scalar::Timedelta64(raw),
13352 });
13353 }
13354 let (sum, mean) = expected_timedelta(&timedeltas);
13355 assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
13356 }
13357 }
13358
13359 #[test]
13360 fn nannunique_merges_negative_zero_and_zero() {
13361 let vals = vec![
13362 Scalar::Float64(-0.0),
13363 Scalar::Float64(0.0),
13364 Scalar::Float64(1.0),
13365 ];
13366 assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
13367 }
13368
13369 #[test]
13370 fn nannunique_matches_scalar_bucket_oracle_elvbg() {
13371 fn next(seed: &mut u64) -> u64 {
13374 *seed = seed
13375 .wrapping_mul(2862933555777941757)
13376 .wrapping_add(3037000493);
13377 *seed
13378 }
13379
13380 fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
13381 match (left, right) {
13382 (Scalar::Float64(left), Scalar::Float64(right)) => {
13383 let left = if *left == 0.0 { 0.0 } else { *left };
13384 let right = if *right == 0.0 { 0.0 } else { *right };
13385 left.to_bits() == right.to_bits()
13386 }
13387 _ => left == right,
13388 }
13389 }
13390
13391 fn expected_nunique(values: &[Scalar]) -> i64 {
13392 let mut seen = Vec::<Scalar>::new();
13393 for value in values {
13394 if value.is_missing() {
13395 continue;
13396 }
13397 if !seen.iter().any(|existing| same_bucket(existing, value)) {
13398 seen.push(value.clone());
13399 }
13400 }
13401 seen.len() as i64
13402 }
13403
13404 fn assert_nannunique(case: usize, values: &[Scalar]) {
13405 assert_eq!(
13406 super::nannunique(values),
13407 Scalar::Int64(expected_nunique(values)),
13408 "case={case}: nannunique mismatch for {values:?}"
13409 );
13410 }
13411
13412 assert_nannunique(
13413 usize::MAX,
13414 &[
13415 Scalar::Float64(-0.0),
13416 Scalar::Float64(0.0),
13417 Scalar::Float64(f64::NAN),
13418 Scalar::Null(NullKind::Null),
13419 Scalar::Timedelta64(i64::MIN),
13420 ],
13421 );
13422
13423 let mut seed = 0x0e1b_60d0_b5e7_u64;
13424 for case in 0..320 {
13425 let len = (next(&mut seed) % 97 + 1) as usize;
13426 let mut values = Vec::with_capacity(len);
13427 for pos in 0..len {
13428 let raw = (next(&mut seed) % 1_001) as i64 - 500;
13429 values.push(match next(&mut seed) % 11 {
13430 0 => Scalar::Null(NullKind::Null),
13431 1 => Scalar::Null(NullKind::NaN),
13432 2 => Scalar::Float64(f64::NAN),
13433 3 => Scalar::Bool(raw & 1 == 0),
13434 4 => Scalar::Int64(raw % 37),
13435 5 => Scalar::Float64(raw as f64 / 19.0),
13436 6 => Scalar::Float64(0.0),
13437 7 => Scalar::Float64(-0.0),
13438 8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
13439 9 => Scalar::Utf8(String::new()),
13440 _ => Scalar::Timedelta64(raw % 41),
13441 });
13442 }
13443 assert_nannunique(case, &values);
13444 }
13445 }
13446
13447 #[test]
13448 fn nanmean_basic() {
13449 let vals = vec![
13450 Scalar::Float64(2.0),
13451 Scalar::Null(NullKind::Null),
13452 Scalar::Float64(4.0),
13453 ];
13454 assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
13455 }
13456
13457 #[test]
13458 fn nanmean_all_null_returns_nan() {
13459 let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13460 assert!(super::nanmean(&vals).is_missing());
13461 }
13462
13463 #[test]
13464 fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
13465 let one_hour = 3_600 * 1_000_000_000_i64;
13469 let vals = vec![
13470 Scalar::Timedelta64(one_hour),
13471 Scalar::Timedelta64(2 * one_hour),
13472 Scalar::Timedelta64(3 * one_hour),
13473 ];
13474 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
13475 assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13476 }
13477
13478 #[test]
13479 fn nansum_nanmean_timedelta64_skips_nat_620mj() {
13480 let one_hour = 3_600 * 1_000_000_000_i64;
13481 let vals = vec![
13482 Scalar::Timedelta64(Timedelta::NAT),
13483 Scalar::Timedelta64(one_hour),
13484 Scalar::Timedelta64(3 * one_hour),
13485 Scalar::Timedelta64(Timedelta::NAT),
13486 ];
13487 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
13489 assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13490 }
13491
13492 #[test]
13499 fn nansum_timedelta_overflow_is_nat_not_fabricated_max_opz27() {
13500 let vals = vec![Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MAX)];
13501 let got = super::nansum(&vals);
13502 assert!(
13503 got.is_missing(),
13504 "overflowing sum must be missing, got {got:?}"
13505 );
13506 assert_eq!(got, Scalar::Timedelta64(Timedelta::NAT));
13507 assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13508 }
13509
13510 #[test]
13515 fn nansum_timedelta_negative_overflow_is_nat_opz27() {
13516 let min_repr = i64::MIN + 1; let vals = vec![Scalar::Timedelta64(min_repr), Scalar::Timedelta64(min_repr)];
13518 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(Timedelta::NAT));
13519
13520 let exact = vec![Scalar::Timedelta64(min_repr + 1), Scalar::Timedelta64(-1)];
13523 let got = super::nansum(&exact);
13524 assert_eq!(got, Scalar::Timedelta64(min_repr));
13525 assert!(!got.is_missing(), "Timedelta.min is representable, not NaT");
13526 }
13527
13528 #[test]
13532 fn nanptp_timedelta_overflow_is_nat_opz27() {
13533 let vals = vec![
13534 Scalar::Timedelta64(i64::MIN + 1),
13535 Scalar::Timedelta64(i64::MAX),
13536 ];
13537 let got = super::nanptp(&vals);
13538 assert!(
13539 got.is_missing(),
13540 "unrepresentable range must be NaT, got {got:?}"
13541 );
13542 assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13543
13544 let hour = 3_600 * 1_000_000_000_i64;
13547 let ok = vec![Scalar::Timedelta64(hour), Scalar::Timedelta64(4 * hour)];
13548 assert_eq!(super::nanptp(&ok), Scalar::Timedelta64(3 * hour));
13549 }
13550
13551 #[test]
13556 fn nancumsum_timedelta_overflow_recovers_exact_value_opz27() {
13557 let vals = vec![
13558 Scalar::Timedelta64(i64::MAX),
13559 Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MIN + 1), ];
13562 let out = super::nancumsum(&vals);
13563 assert_eq!(out.len(), 3);
13564 assert_eq!(out[0], Scalar::Timedelta64(i64::MAX));
13565 assert!(
13566 out[1].is_missing(),
13567 "overflowed index must be NaT, got {:?}",
13568 out[1]
13569 );
13570 assert_eq!(
13571 out[2],
13572 Scalar::Timedelta64(i64::MAX),
13573 "exact i128 accumulation must recover; a clamped running sum cannot"
13574 );
13575 }
13576
13577 #[test]
13580 fn nancumsum_timedelta_exact_path_unchanged_opz27() {
13581 let sec = 1_000_000_000_i64;
13582 let vals = vec![
13583 Scalar::Timedelta64(sec),
13584 Scalar::Timedelta64(Timedelta::NAT),
13585 Scalar::Timedelta64(2 * sec),
13586 ];
13587 let out = super::nancumsum(&vals);
13588 assert_eq!(out[0], Scalar::Timedelta64(sec));
13589 assert!(out[1].is_missing());
13590 assert_eq!(out[2], Scalar::Timedelta64(3 * sec));
13591 }
13592
13593 const DAY_NS: i64 = 86_400 * 1_000_000_000;
13594 const DT_2020: i64 = 1_577_836_800_000_000_000;
13596
13597 #[test]
13605 fn datetime64_ordering_reductions_match_pandas_axhhk() {
13606 let d = Scalar::Datetime64;
13607 let vals = vec![
13608 d(DT_2020),
13609 d(DT_2020 + 60 * DAY_NS),
13610 d(DT_2020 + 31 * DAY_NS),
13611 ];
13612
13613 assert_eq!(super::nanmin(&vals), d(DT_2020));
13614 assert_eq!(super::nanmax(&vals), d(DT_2020 + 60 * DAY_NS));
13615 assert_eq!(super::nanargmin(&vals), Some(0));
13616 assert_eq!(super::nanargmax(&vals), Some(1));
13617
13618 let span = super::nanptp(&vals);
13620 assert_eq!(span, Scalar::Timedelta64(60 * DAY_NS));
13621 assert_eq!(span.dtype(), DType::Timedelta64);
13622
13623 assert_eq!(
13624 super::nancummax(&vals),
13625 vec![
13626 d(DT_2020),
13627 d(DT_2020 + 60 * DAY_NS),
13628 d(DT_2020 + 60 * DAY_NS)
13629 ]
13630 );
13631 assert_eq!(
13632 super::nancummin(&vals),
13633 vec![d(DT_2020), d(DT_2020), d(DT_2020)]
13634 );
13635 }
13636
13637 #[test]
13644 fn datetime64_min_max_size_dependence_pinned_axhhk() {
13645 let d = Scalar::Datetime64;
13646 let one = vec![d(DT_2020)];
13647 assert_eq!(super::nanmin(&one), d(DT_2020));
13648 assert_eq!(super::nanmax(&one), d(DT_2020));
13649
13650 let two = vec![d(DT_2020 + DAY_NS), d(DT_2020)];
13651 let got_min = super::nanmin(&two);
13652 assert!(
13653 !got_min.is_missing(),
13654 "2-element datetime min must not be missing, got {got_min:?}"
13655 );
13656 assert_eq!(got_min, d(DT_2020));
13657 assert_eq!(super::nanmax(&two), d(DT_2020 + DAY_NS));
13658 }
13659
13660 #[test]
13663 fn datetime64_reductions_skip_nat_and_guard_span_overflow_axhhk() {
13664 let d = Scalar::Datetime64;
13665 let with_nat = vec![
13666 d(Timestamp::NAT),
13667 d(DT_2020 + 31 * DAY_NS),
13668 d(DT_2020),
13669 d(Timestamp::NAT),
13670 ];
13671 assert_eq!(super::nanmin(&with_nat), d(DT_2020));
13672 assert_eq!(super::nanmax(&with_nat), d(DT_2020 + 31 * DAY_NS));
13673 assert_eq!(super::nanptp(&with_nat), Scalar::Timedelta64(31 * DAY_NS));
13674 assert_eq!(super::nanargmin(&with_nat), Some(2));
13676 assert_eq!(super::nanargmax(&with_nat), Some(1));
13677
13678 let huge = vec![d(i64::MIN + 1), d(i64::MAX)];
13680 let span = super::nanptp(&huge);
13681 assert!(span.is_missing(), "unrepresentable span must be NaT");
13682 assert_ne!(span, Scalar::Timedelta64(i64::MAX));
13683 }
13684
13685 #[test]
13692 fn datetime64_averaging_reductions_match_pandas_adv58() {
13693 let d = Scalar::Datetime64;
13694 let vals = vec![
13695 d(DT_2020),
13696 d(DT_2020 + 60 * DAY_NS),
13697 d(DT_2020 + 31 * DAY_NS),
13698 ];
13699 assert_eq!(super::nanmean(&vals), d(1_580_457_600_000_000_000));
13701 assert_eq!(super::nanmedian(&vals), d(1_580_515_200_000_000_000));
13702 assert_eq!(super::nanquantile(&vals, 0.5), d(1_580_515_200_000_000_000));
13703 assert_eq!(
13704 super::nanquantile(&vals, 0.25),
13705 d(1_579_176_000_000_000_000)
13706 );
13707 }
13708
13709 #[test]
13715 fn datetime64_mean_median_round_toward_zero_adv58() {
13716 let d = Scalar::Datetime64;
13717 for (a, b, want) in [
13718 (0_i64, 1_i64, 0_i64),
13719 (0, 3, 1),
13720 (1, 2, 1),
13721 (-1, 0, 0),
13722 (-3, 0, -1),
13723 (-2, -1, -1),
13724 (0, 2, 1),
13725 (-2, 0, -1),
13726 ] {
13727 let vals = vec![d(a), d(b)];
13728 assert_eq!(
13729 super::nanmean(&vals),
13730 d(want),
13731 "mean of [{a}, {b}] should be {want}"
13732 );
13733 assert_eq!(
13734 super::nanmedian(&vals),
13735 d(want),
13736 "median of [{a}, {b}] should be {want}"
13737 );
13738 }
13739 }
13740
13741 #[test]
13744 fn datetime64_averaging_skips_nat_adv58() {
13745 let d = Scalar::Datetime64;
13746 let vals = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
13747 assert_eq!(super::nanmean(&vals), d(DT_2020 + DAY_NS));
13749 assert_eq!(super::nanmedian(&vals), d(DT_2020 + DAY_NS));
13750
13751 let all_nat = vec![d(Timestamp::NAT), d(Timestamp::NAT)];
13752 let got = super::nanmean(&all_nat);
13753 assert!(
13754 got.is_missing(),
13755 "all-NaT mean must be missing, got {got:?}"
13756 );
13757 assert_eq!(
13758 got.dtype(),
13759 DType::datetime64_naive(),
13760 "must stay Datetime64"
13761 );
13762 }
13763
13764 #[test]
13771 fn datetime64_averaging_is_exact_where_pandas_snaps_adv58() {
13772 let d = Scalar::Datetime64;
13773
13774 let constant = vec![d(DT_2020 + 1), d(DT_2020 + 1)];
13776 assert_eq!(super::nanmean(&constant), d(DT_2020 + 1));
13777 assert_eq!(super::nanmedian(&constant), d(DT_2020 + 1));
13778
13779 let odd = vec![d(DT_2020), d(DT_2020 + 129), d(DT_2020 + 258)];
13781 let med = super::nanmedian(&odd);
13782 assert_eq!(med, d(DT_2020 + 129));
13783 assert!(
13784 odd.contains(&med),
13785 "odd-count median must be one of the inputs; pandas returns B+256, which is not"
13786 );
13787 }
13788
13789 #[test]
13796 fn datetime64_std_matches_pandas_ddof_variants_40ujm() {
13797 let d = Scalar::Datetime64;
13798 let vals = vec![
13799 d(DT_2020),
13800 d(DT_2020 + 60 * DAY_NS),
13801 d(DT_2020 + 31 * DAY_NS),
13802 ];
13803 let s1 = super::nanstd(&vals, 1);
13805 assert_eq!(s1, Scalar::Timedelta64(2_592_479_955_563_784));
13806 assert_eq!(s1.dtype(), DType::Timedelta64);
13807 assert_eq!(
13808 super::nanstd(&vals, 0),
13809 Scalar::Timedelta64(2_116_751_019_841_492)
13810 );
13811 assert_eq!(
13812 super::nanstd(&vals, 2),
13813 Scalar::Timedelta64(3_666_320_313_338_702)
13814 );
13815 assert!(super::nanstd(&vals, 3).is_missing());
13817 }
13818
13819 #[test]
13823 fn datetime64_std_equals_timedelta64_std_on_same_ns_40ujm() {
13824 let offsets = [0_i64, 60 * DAY_NS, 31 * DAY_NS];
13825 let dt: Vec<Scalar> = offsets.iter().map(|o| Scalar::Datetime64(*o)).collect();
13826 let td: Vec<Scalar> = offsets.iter().map(|o| Scalar::Timedelta64(*o)).collect();
13827 assert_eq!(super::nanstd(&dt, 1), super::nanstd(&td, 1));
13828 assert_eq!(
13829 super::nanstd(&dt, 1),
13830 Scalar::Timedelta64(2_592_479_955_563_784)
13831 );
13832 }
13833
13834 #[test]
13838 fn datetime64_std_skips_nat_and_var_sem_stay_unsupported_40ujm() {
13839 let d = Scalar::Datetime64;
13840 let with_nat = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
13841 let without = vec![d(DT_2020), d(DT_2020 + 2 * DAY_NS)];
13842 assert_eq!(super::nanstd(&with_nat, 1), super::nanstd(&without, 1));
13844 assert_eq!(
13845 super::nanstd(&with_nat, 1),
13846 Scalar::Timedelta64(122_188_051_789_035)
13847 );
13848
13849 assert!(super::nanstd(&[d(DT_2020)], 1).is_missing());
13851 assert!(super::nanstd(&[d(Timestamp::NAT)], 1).is_missing());
13852
13853 let vals = vec![d(DT_2020), d(DT_2020 + 60 * DAY_NS)];
13857 assert!(super::nanvar(&vals, 1).is_missing());
13858 assert!(super::nansem(&vals, 1).is_missing());
13859 }
13860
13861 #[test]
13866 fn period_min_max_match_pandas_qoabs() {
13867 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13868 let vals = vec![p(600), p(602), p(601)];
13869 assert_eq!(super::nanmin(&vals), p(600));
13870 assert_eq!(super::nanmax(&vals), p(602));
13871
13872 assert_eq!(super::nanmin(&[p(600)]), p(600));
13876 let two = vec![p(602), p(600)];
13877 assert!(!super::nanmin(&two).is_missing());
13878 assert_eq!(super::nanmin(&two), p(600));
13879 assert_eq!(super::nanmax(&two), p(602));
13880 }
13881
13882 #[test]
13885 fn period_min_max_skip_nat_qoabs() {
13886 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13887 let nat = Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly));
13888 let vals = vec![nat.clone(), p(602), p(600), nat.clone()];
13889 assert_eq!(super::nanmin(&vals), p(600));
13890 assert_eq!(super::nanmax(&vals), p(602));
13891 assert!(super::nanmin(&[nat.clone(), nat]).is_missing());
13892 }
13893
13894 #[test]
13901 fn period_mixed_freq_is_not_ordered_qoabs() {
13902 let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
13903 let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
13904 let vals = vec![month.clone(), day.clone()];
13905 let got_min = super::nanmin(&vals);
13906 assert!(
13907 got_min.is_missing(),
13908 "mixed-freq Period min must not be ordered, got {got_min:?}"
13909 );
13910 assert_ne!(
13911 got_min, day,
13912 "must not rank the daily period by raw ordinal"
13913 );
13914 assert!(super::nanmax(&vals).is_missing());
13915 }
13916
13917 #[test]
13924 fn period_full_reduction_family_matches_pandas_d7zjp() {
13925 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13926 let vals = vec![p(600), p(602), p(601)];
13927
13928 assert_eq!(super::nanmedian(&vals), p(601));
13929 assert_eq!(super::nanquantile(&vals, 0.5), p(601));
13930 assert_eq!(super::nanargmin(&vals), Some(0));
13931 assert_eq!(super::nanargmax(&vals), Some(1));
13932 assert_eq!(super::nancummax(&vals), vec![p(600), p(602), p(602)]);
13933 assert_eq!(super::nancummin(&vals), vec![p(600), p(600), p(600)]);
13934 }
13935
13936 #[test]
13941 fn period_even_count_median_truncates_toward_zero_d7zjp() {
13942 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13943 assert_eq!(super::nanmedian(&[p(600), p(603)]), p(601));
13944 assert_eq!(super::nanmedian(&[p(600), p(601)]), p(600));
13945 }
13946
13947 #[test]
13953 fn period_mixed_freq_not_ordered_by_any_reduction_d7zjp() {
13954 let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
13955 let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
13956 let vals = vec![month, day];
13957
13958 assert!(super::nanmedian(&vals).is_missing());
13959 assert!(super::nanquantile(&vals, 0.5).is_missing());
13960 assert_eq!(super::nanargmin(&vals), None);
13961 assert_eq!(super::nanargmax(&vals), None);
13962 assert!(super::nancummax(&vals).iter().all(Scalar::is_missing));
13964 assert!(super::nancummin(&vals).iter().all(Scalar::is_missing));
13965 }
13966
13967 #[test]
13973 fn period_unsupported_reductions_stay_missing_d7zjp() {
13974 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13975 let vals = vec![p(600), p(602), p(601)];
13976 assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
13977 assert!(super::nanvar(&vals, 1).is_missing(), "pandas raises var");
13978 assert!(super::nansem(&vals, 1).is_missing(), "pandas raises sem");
13979 assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
13980 }
13981
13982 #[test]
13987 fn interval_min_max_match_pandas_srqdo() {
13988 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13989 let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
13990 assert_eq!(super::nanmin(&vals), iv(0.0, 1.0));
13991 assert_eq!(super::nanmax(&vals), iv(4.0, 5.0));
13992
13993 assert_eq!(super::nanmin(&[iv(2.0, 3.0)]), iv(2.0, 3.0));
13996 let two = vec![iv(4.0, 5.0), iv(0.0, 1.0)];
13997 assert!(!super::nanmin(&two).is_missing());
13998 assert_eq!(super::nanmin(&two), iv(0.0, 1.0));
13999 assert_eq!(super::nanmax(&two), iv(4.0, 5.0));
14000 }
14001
14002 #[test]
14007 fn interval_ties_on_left_order_by_right_srqdo() {
14008 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14009 let vals = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
14010 assert_eq!(super::nanmin(&vals), iv(0.0, 2.0));
14011 assert_eq!(super::nanmax(&vals), iv(0.0, 9.0));
14012 }
14013
14014 #[test]
14020 fn interval_nan_bound_is_not_ordered_srqdo() {
14021 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14022 let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
14023 assert!(super::nanmin(&vals).is_missing());
14024 assert!(super::nanmax(&vals).is_missing());
14025 }
14026
14027 #[test]
14031 fn interval_unsupported_reductions_stay_missing_srqdo() {
14032 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14033 let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
14034 assert!(super::nanmedian(&vals).is_missing(), "pandas raises median");
14035 assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
14036 assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
14037 assert!(
14038 super::nanquantile(&vals, 0.5).is_missing(),
14039 "pandas raises quantile"
14040 );
14041 assert!(
14042 super::nancummax(&vals).iter().all(Scalar::is_missing),
14043 "pandas NotImplementedErrors cummax"
14044 );
14045 }
14046
14047 #[test]
14051 fn interval_argmin_argmax_match_pandas_2h9dm() {
14052 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14053 let vals = vec![iv(4.0, 5.0), iv(0.0, 1.0), iv(2.0, 3.0)];
14055 assert_eq!(super::nanargmin(&vals), Some(1));
14056 assert_eq!(super::nanargmax(&vals), Some(0));
14057
14058 let tie = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
14061 assert_eq!(super::nanargmin(&tie), Some(1));
14062 assert_eq!(super::nanargmax(&tie), Some(2));
14063 }
14064
14065 #[test]
14070 fn interval_arg_first_occurrence_and_missing_2h9dm() {
14071 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14072 let dup = vec![iv(0.0, 1.0), iv(0.0, 1.0), iv(9.0, 9.0)];
14073 assert_eq!(
14074 super::nanargmin(&dup),
14075 Some(0),
14076 "first occurrence, not last"
14077 );
14078 assert_eq!(super::nanargmax(&dup), Some(2));
14079
14080 let with_missing = vec![iv(4.0, 5.0), Scalar::Null(NullKind::NaN), iv(0.0, 1.0)];
14081 assert_eq!(super::nanargmin(&with_missing), Some(2));
14082 assert_eq!(super::nanargmax(&with_missing), Some(0));
14083 }
14084
14085 #[test]
14089 fn interval_arg_nan_bound_declines_2h9dm() {
14090 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14091 let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
14092 assert_eq!(super::nanargmin(&vals), None);
14093 assert_eq!(super::nanargmax(&vals), None);
14094 }
14095
14096 #[test]
14103 fn overflow_policy_carrier_preserves_default_behavior_f29nz() {
14104 let mut state: u64 = 0x5DEE_CE66_D125_1F00;
14106 let mut next = || {
14107 state = state
14108 .wrapping_mul(6_364_136_223_846_793_005)
14109 .wrapping_add(1_442_695_040_888_963_407);
14110 state
14111 };
14112 let mut corpus: Vec<i64> = vec![
14114 0,
14115 1,
14116 -1,
14117 2,
14118 -2,
14119 i64::MAX,
14120 i64::MIN,
14121 i64::MIN + 1,
14122 i64::MAX - 1,
14123 i64::MAX / 2,
14124 -(i64::MAX / 2),
14125 ];
14126 for _ in 0..400 {
14127 let raw = next() as i64;
14128 corpus.push(raw);
14129 corpus.push(raw / 3);
14130 }
14131
14132 let policy = super::OverflowPolicy::default();
14133 assert_eq!(
14134 policy,
14135 super::OverflowPolicy::SurfaceNat,
14136 "default must not move"
14137 );
14138
14139 for &a in &corpus {
14140 for &b in &corpus {
14141 assert_eq!(
14143 Timedelta::add(a, b),
14144 policy
14145 .resolve(Timedelta::try_add(a, b), Timedelta::NAT)
14146 .expect("SurfaceNat never errors"),
14147 "add({a}, {b}) diverged"
14148 );
14149 assert_eq!(
14150 Timedelta::sub(a, b),
14151 policy
14152 .resolve(Timedelta::try_sub(a, b), Timedelta::NAT)
14153 .expect("SurfaceNat never errors"),
14154 "sub({a}, {b}) diverged"
14155 );
14156 assert_eq!(
14157 Timedelta::mul_scalar(a, b),
14158 policy
14159 .resolve(Timedelta::try_mul_scalar(a, b), Timedelta::NAT)
14160 .expect("SurfaceNat never errors"),
14161 "mul_scalar({a}, {b}) diverged"
14162 );
14163
14164 let ts = Timestamp::from_nanos(a);
14167 assert_eq!(
14168 ts.add_timedelta(b),
14169 ts.try_add_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14170 "add_timedelta({a}, {b}) diverged"
14171 );
14172 assert_eq!(
14173 ts.sub_timedelta(b),
14174 ts.try_sub_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14175 "sub_timedelta({a}, {b}) diverged"
14176 );
14177 let other = Timestamp::from_nanos(b);
14178 assert_eq!(
14179 ts.sub_timestamp(&other),
14180 ts.try_sub_timestamp(&other).unwrap_or(Timedelta::NAT),
14181 "sub_timestamp({a}, {b}) diverged"
14182 );
14183 }
14184 }
14185 }
14186
14187 #[test]
14192 fn overflow_policy_strict_reports_op_and_pandas_class_f29nz() {
14193 use super::{OverflowPolicy, PandasTemporalError};
14194
14195 let strict = OverflowPolicy::Strict;
14196
14197 let err = strict
14199 .resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT)
14200 .expect_err("must surface under Strict");
14201 assert_eq!(err.op, "Timedelta::add");
14202 assert_eq!(err.pandas_error, PandasTemporalError::Overflow);
14203
14204 let ts = Timestamp::from_nanos(i64::MAX);
14206 let err = strict
14207 .resolve(ts.try_add_timedelta(1), Timestamp::nat())
14208 .expect_err("must surface under Strict");
14209 assert_eq!(err.op, "Timestamp::add_timedelta");
14210 assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14211
14212 let err = strict
14214 .resolve(
14215 Timestamp::from_nanos(i64::MIN + 1)
14216 .try_sub_timestamp(&Timestamp::from_nanos(i64::MAX)),
14217 Timedelta::NAT,
14218 )
14219 .expect_err("must surface under Strict");
14220 assert_eq!(err.op, "Timestamp::sub_timestamp");
14221 assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14222
14223 assert_eq!(
14225 strict
14226 .resolve(Timedelta::try_add(Timedelta::NAT, 1), Timedelta::NAT)
14227 .expect("NaT propagation is not an overflow"),
14228 Timedelta::NAT
14229 );
14230 assert_eq!(
14232 strict
14233 .resolve(Timedelta::try_add(2, 3), Timedelta::NAT)
14234 .expect("no overflow"),
14235 5
14236 );
14237 }
14238
14239 #[test]
14247 fn timedelta_scalar_zero_division_taxonomy_t7ht2() {
14248 use super::{OverflowPolicy, PandasTemporalError};
14249
14250 let err = Timedelta::try_div_scalar(1_000_000_000, 0)
14252 .expect_err("scalar divide-by-zero must be reportable");
14253 assert_eq!(err.op, "Timedelta::div_scalar");
14254 assert_eq!(err.pandas_error, PandasTemporalError::ZeroDivision);
14255
14256 assert_eq!(Timedelta::div_scalar(1_000_000_000, 0), Timedelta::NAT);
14260 assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 0), Timedelta::NAT);
14261
14262 assert_eq!(
14265 OverflowPolicy::default()
14266 .resolve(Timedelta::try_div_scalar(1_000_000_000, 0), Timedelta::NAT)
14267 .expect("SurfaceNat never errors"),
14268 Timedelta::NAT
14269 );
14270
14271 assert_eq!(Timedelta::try_div_scalar(-7, 2), Ok(-4));
14274 assert_eq!(Timedelta::div_scalar(-7, 2), -4);
14275 assert_eq!(Timedelta::try_div_scalar(7, 2), Ok(3));
14276 assert_eq!(
14278 Timedelta::try_div_scalar(Timedelta::NAT, 2),
14279 Ok(Timedelta::NAT)
14280 );
14281 }
14282
14283 #[test]
14288 fn timedelta_constructor_error_maps_to_out_of_bounds_t7ht2() {
14289 use super::{PandasTemporalError, TimedeltaError};
14290
14291 assert_eq!(
14292 TimedeltaError::Overflow.pandas_error(),
14293 Some(PandasTemporalError::OutOfBoundsTimedelta)
14294 );
14295 assert_eq!(
14297 TimedeltaError::InvalidFormat("nonsense".into()).pandas_error(),
14298 None
14299 );
14300 assert!(Timedelta::from_unit(f64::INFINITY, "s").is_err());
14302 assert_eq!(
14303 Timedelta::from_unit(f64::INFINITY, "s")
14304 .unwrap_err()
14305 .pandas_error(),
14306 Some(PandasTemporalError::OutOfBoundsTimedelta)
14307 );
14308 }
14309
14310 #[test]
14316 fn hardened_audit_values_are_bit_identical_to_surface_nat_vllv6() {
14317 use super::{OverflowPolicy, overflow_audit};
14318
14319 overflow_audit::enable();
14320 let mut state: u64 = 0x1234_5678_9ABC_DEF0;
14321 let mut next = || {
14322 state = state
14323 .wrapping_mul(6_364_136_223_846_793_005)
14324 .wrapping_add(1_442_695_040_888_963_407);
14325 state
14326 };
14327 let mut corpus: Vec<i64> = vec![
14328 0,
14329 1,
14330 -1,
14331 2,
14332 -2,
14333 i64::MAX,
14334 i64::MIN,
14335 i64::MIN + 1,
14336 i64::MAX - 1,
14337 ];
14338 for _ in 0..120 {
14339 corpus.push(next() as i64);
14340 }
14341
14342 for &a in &corpus {
14343 for &b in &corpus {
14344 for op in [
14345 Timedelta::try_add as fn(i64, i64) -> Result<i64, super::TemporalFailure>,
14346 Timedelta::try_sub,
14347 Timedelta::try_mul_scalar,
14348 Timedelta::try_div_scalar,
14349 ] {
14350 let soft = OverflowPolicy::SurfaceNat
14351 .resolve(op(a, b), Timedelta::NAT)
14352 .expect("SurfaceNat never errors");
14353 let hard = OverflowPolicy::HardenedNat
14354 .resolve(op(a, b), Timedelta::NAT)
14355 .expect("HardenedNat never errors");
14356 assert_eq!(hard, soft, "HARDENED changed a value for ({a}, {b})");
14357 }
14358 }
14359 }
14360 overflow_audit::disable();
14361 }
14362
14363 #[test]
14368 fn hardened_audit_records_deterministic_recovery_entries_vllv6() {
14369 use super::{OverflowPolicy, PandasTemporalError, overflow_audit};
14370
14371 overflow_audit::enable();
14372 assert!(overflow_audit::is_enabled());
14373 assert!(overflow_audit::drain().is_empty(), "starts empty");
14374
14375 let _ =
14377 OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14378 let _ = OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(2, 3), Timedelta::NAT);
14379 let _ =
14380 OverflowPolicy::HardenedNat.resolve(Timedelta::try_div_scalar(5, 0), Timedelta::NAT);
14381
14382 let entries = overflow_audit::drain();
14383 assert_eq!(entries.len(), 2, "only the two failures are recorded");
14384
14385 assert_eq!(entries[0].op, "Timedelta::add");
14386 assert_eq!(entries[0].pandas_error, PandasTemporalError::Overflow);
14387 assert_eq!(entries[0].operands, Some((i64::MAX, 1)));
14388 assert_eq!(entries[0].recovered_as, i64::MIN);
14389
14390 assert_eq!(entries[1].op, "Timedelta::div_scalar");
14391 assert_eq!(entries[1].pandas_error, PandasTemporalError::ZeroDivision);
14392 assert_eq!(entries[1].operands, Some((5, 0)));
14393
14394 assert!(overflow_audit::drain().is_empty());
14396
14397 let _ = OverflowPolicy::SurfaceNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14399 let _ = OverflowPolicy::Strict.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14400 assert!(
14401 overflow_audit::drain().is_empty(),
14402 "SurfaceNat/Strict must not write to the audit trail"
14403 );
14404
14405 overflow_audit::disable();
14406 assert!(!overflow_audit::is_enabled());
14407 let _ =
14409 OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14410 assert!(
14411 overflow_audit::drain().is_empty(),
14412 "disabled must not record"
14413 );
14414 }
14415
14416 #[test]
14434 fn strict_reproduces_pandas_silent_timedelta_wrap_s4lkx() {
14435 use super::{OverflowPolicy, nancumsum_with_policy};
14436
14437 assert_eq!(
14439 Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::Strict),
14440 -2,
14441 "STRICT must reproduce pandas' wrap, not repair it"
14442 );
14443
14444 let max = Scalar::Timedelta64(i64::MAX);
14447 let out = nancumsum_with_policy(
14448 &[max.clone(), max.clone(), max.clone()],
14449 OverflowPolicy::Strict,
14450 );
14451 assert_eq!(
14452 out,
14453 vec![
14454 Scalar::Timedelta64(i64::MAX),
14455 Scalar::Timedelta64(-2),
14456 Scalar::Timedelta64(i64::MAX - 2),
14457 ],
14458 "STRICT cumsum must reproduce pandas' int64 wraparound exactly"
14459 );
14460
14461 assert_eq!(
14463 Timedelta::mul_scalar_with_policy(Timedelta::NAT, 2, OverflowPolicy::Strict),
14464 Timedelta::NAT
14465 );
14466 }
14467
14468 #[test]
14474 fn non_strict_policies_still_refuse_to_wrap_s4lkx() {
14475 use super::{OverflowPolicy, nancumsum_with_policy, overflow_audit};
14476
14477 for policy in [OverflowPolicy::SurfaceNat, OverflowPolicy::HardenedNat] {
14478 assert_eq!(
14479 Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14480 Timedelta::NAT,
14481 "{policy:?} must NOT wrap"
14482 );
14483 assert_ne!(
14484 Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14485 -2,
14486 "{policy:?} must not reproduce the pandas quirk"
14487 );
14488 }
14489 assert_eq!(
14491 Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::default()),
14492 Timedelta::NAT
14493 );
14494
14495 let max = Scalar::Timedelta64(i64::MAX);
14497 let soft = nancumsum_with_policy(&[max.clone(), max.clone()], OverflowPolicy::SurfaceNat);
14498 assert!(soft[1].is_missing(), "non-STRICT cumsum must NaT, not wrap");
14499 assert_eq!(soft, super::nancumsum(&[max.clone(), max]));
14500
14501 overflow_audit::enable();
14504 let _ = Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::HardenedNat);
14505 assert_eq!(
14506 overflow_audit::drain().len(),
14507 1,
14508 "HARDENED must record the recovery it performed"
14509 );
14510 overflow_audit::disable();
14511 }
14512
14513 #[test]
14516 fn datetime64_mixed_input_still_falls_back_axhhk() {
14517 let vals = vec![Scalar::Datetime64(DT_2020), Scalar::Int64(5)];
14518 assert!(super::nanmin(&vals).is_missing());
14529 assert_eq!(super::nanptp(&vals), Scalar::Float64(0.0));
14530 }
14531
14532 #[test]
14533 fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
14534 let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
14538 assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
14540 }
14541
14542 #[test]
14543 fn nancount_counts_non_missing() {
14544 let vals = vec![
14545 Scalar::Int64(1),
14546 Scalar::Null(NullKind::Null),
14547 Scalar::Float64(3.0),
14548 ];
14549 assert_eq!(super::nancount(&vals), Scalar::Int64(2));
14550 }
14551
14552 #[test]
14553 fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
14554 fn next(seed: &mut u64) -> u64 {
14557 *seed = seed
14558 .wrapping_mul(6364136223846793005)
14559 .wrapping_add(1442695040888963407);
14560 *seed
14561 }
14562
14563 fn truthy(value: &Scalar) -> Option<bool> {
14564 if value.is_missing() {
14565 return None;
14566 }
14567 match value {
14568 Scalar::Bool(value) => Some(*value),
14569 Scalar::Int64(value) => Some(*value != 0),
14570 Scalar::Float64(value) => Some(*value != 0.0),
14571 Scalar::Utf8(value) => Some(!value.is_empty()),
14572 Scalar::Timedelta64(value) => Some(*value != 0),
14573 _ => None,
14574 }
14575 }
14576
14577 fn assert_nanops(case: usize, values: &[Scalar]) {
14578 let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
14579 let expected_any = truth_values.iter().any(|value| *value);
14580 let expected_all = !truth_values.iter().any(|value| !*value);
14581 let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
14582
14583 assert_eq!(
14584 super::nanany(values),
14585 Scalar::Bool(expected_any),
14586 "case={case}: nanany mismatch for {values:?}"
14587 );
14588 assert_eq!(
14589 super::nanall(values),
14590 Scalar::Bool(expected_all),
14591 "case={case}: nanall mismatch for {values:?}"
14592 );
14593 assert_eq!(
14594 super::nancount(values),
14595 Scalar::Int64(expected_count),
14596 "case={case}: nancount mismatch for {values:?}"
14597 );
14598 }
14599
14600 assert_nanops(
14601 usize::MAX,
14602 &[
14603 Scalar::Null(NullKind::Null),
14604 Scalar::Null(NullKind::NaN),
14605 Scalar::Float64(f64::NAN),
14606 Scalar::Timedelta64(i64::MIN),
14607 ],
14608 );
14609
14610 let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
14611 for case in 0..320 {
14612 let len = (next(&mut seed) % 89 + 1) as usize;
14613 let mut values = Vec::with_capacity(len);
14614 for pos in 0..len {
14615 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
14616 let value = match next(&mut seed) % 12 {
14617 0 => Scalar::Null(NullKind::Null),
14618 1 => Scalar::Null(NullKind::NaN),
14619 2 => Scalar::Float64(f64::NAN),
14620 3 => Scalar::Bool(raw & 1 == 0),
14621 4 => Scalar::Bool(false),
14622 5 => Scalar::Int64(raw % 17),
14623 6 => Scalar::Int64(0),
14624 7 => Scalar::Float64(raw as f64 / 23.0),
14625 8 => Scalar::Float64(0.0),
14626 9 => Scalar::Utf8(if raw & 1 == 0 {
14627 String::new()
14628 } else {
14629 format!("nanops_{case}_{pos}")
14630 }),
14631 10 => Scalar::Timedelta64(raw),
14632 _ => Scalar::Timedelta64(0),
14633 };
14634 values.push(value);
14635 }
14636 assert_nanops(case, &values);
14637 }
14638 }
14639
14640 #[test]
14641 fn nanmin_basic() {
14642 let vals = vec![
14643 Scalar::Float64(5.0),
14644 Scalar::Null(NullKind::Null),
14645 Scalar::Float64(2.0),
14646 Scalar::Float64(8.0),
14647 ];
14648 assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
14649 }
14650
14651 #[test]
14652 fn nanmax_basic() {
14653 let vals = vec![
14654 Scalar::Float64(5.0),
14655 Scalar::Float64(f64::NAN),
14656 Scalar::Float64(8.0),
14657 ];
14658 assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
14659 }
14660
14661 #[test]
14662 fn nanmin_nanmax_empty_returns_nan() {
14663 assert!(super::nanmin(&[]).is_missing());
14664 assert!(super::nanmax(&[]).is_missing());
14665 }
14666
14667 #[test]
14668 fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
14669 fn next(seed: &mut u64) -> u64 {
14672 *seed = seed
14673 .wrapping_mul(6364136223846793005)
14674 .wrapping_add(1442695040888963407);
14675 *seed
14676 }
14677
14678 fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
14679 match (left, right) {
14680 (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
14681 (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
14682 (Scalar::Float64(left), Scalar::Float64(right)) => {
14683 left.partial_cmp(right).expect("finite floats")
14684 }
14685 (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
14686 (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
14687 _ => std::cmp::Ordering::Equal,
14690 }
14691 }
14692
14693 fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
14694 let present = values
14695 .iter()
14696 .filter(|value| !value.is_missing())
14697 .cloned()
14698 .collect::<Vec<_>>();
14699 let actual_min = super::nanmin(values);
14700 let actual_max = super::nanmax(values);
14701 if present.is_empty() {
14702 assert!(
14703 actual_min.is_missing(),
14704 "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
14705 );
14706 assert!(
14707 actual_max.is_missing(),
14708 "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
14709 );
14710 return;
14711 }
14712
14713 let is_expected_family = |value: &Scalar| match family {
14714 "int" => matches!(value, Scalar::Int64(_)),
14715 "float" => matches!(value, Scalar::Float64(_)),
14716 "bool" => matches!(value, Scalar::Bool(_)),
14717 "utf8" => matches!(value, Scalar::Utf8(_)),
14718 "timedelta" => matches!(value, Scalar::Timedelta64(_)),
14719 _ => false,
14720 };
14721 assert!(
14722 present.iter().all(is_expected_family),
14723 "case={case} family={family}: mixed family escaped generator: {values:?}"
14724 );
14725
14726 let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
14727 let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
14728 assert!(
14729 actual_min.semantic_eq(expected_min.expect("min")),
14730 "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
14731 expected_min.expect("min")
14732 );
14733 assert!(
14734 actual_max.semantic_eq(expected_max.expect("max")),
14735 "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
14736 expected_max.expect("max")
14737 );
14738 }
14739
14740 let all_missing = [
14741 Scalar::Null(NullKind::Null),
14742 Scalar::Null(NullKind::NaN),
14743 Scalar::Float64(f64::NAN),
14744 Scalar::Timedelta64(i64::MIN),
14745 ];
14746 assert_minmax(usize::MAX, "all_missing", &all_missing);
14747
14748 let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
14749 for case in 0..240 {
14750 let len = (next(&mut seed) % 73 + 1) as usize;
14751
14752 let mut ints = Vec::with_capacity(len);
14753 ints.push(Scalar::Int64(case as i64 - 120));
14754 for _ in 1..len {
14755 let raw = (next(&mut seed) % 1_001) as i64 - 500;
14756 ints.push(match next(&mut seed) % 6 {
14757 0 => Scalar::Null(NullKind::Null),
14758 1 => Scalar::Null(NullKind::NaN),
14759 _ => Scalar::Int64(raw),
14760 });
14761 }
14762 assert_minmax(case, "int", &ints);
14763
14764 let mut floats = Vec::with_capacity(len);
14765 floats.push(Scalar::Float64(case as f64 / 11.0));
14766 for _ in 1..len {
14767 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14768 floats.push(match next(&mut seed) % 8 {
14769 0 | 1 => Scalar::Float64(f64::NAN),
14770 2 => Scalar::Float64(f64::INFINITY),
14771 3 => Scalar::Float64(f64::NEG_INFINITY),
14772 4 => Scalar::Float64(0.0),
14773 5 => Scalar::Float64(-0.0),
14774 _ => Scalar::Float64(raw as f64 / 41.0),
14775 });
14776 }
14777 assert_minmax(case, "float", &floats);
14778
14779 let mut bools = Vec::with_capacity(len);
14780 bools.push(Scalar::Bool(case & 1 == 0));
14781 for _ in 1..len {
14782 bools.push(match next(&mut seed) % 5 {
14783 0 => Scalar::Null(NullKind::Null),
14784 1 => Scalar::Null(NullKind::NaN),
14785 raw => Scalar::Bool(raw & 1 == 0),
14786 });
14787 }
14788 assert_minmax(case, "bool", &bools);
14789
14790 let mut utf8 = Vec::with_capacity(len);
14791 utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
14792 for pos in 1..len {
14793 utf8.push(match next(&mut seed) % 7 {
14794 0 => Scalar::Null(NullKind::Null),
14795 1 => Scalar::Null(NullKind::NaN),
14796 raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
14797 });
14798 }
14799 assert_minmax(case, "utf8", &utf8);
14800
14801 let mut timedeltas = Vec::with_capacity(len);
14802 timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
14803 for _ in 1..len {
14804 let raw = (next(&mut seed) % 1_003) as i64 - 501;
14805 timedeltas.push(match next(&mut seed) % 7 {
14806 0 => Scalar::Null(NullKind::Null),
14807 1 => Scalar::Timedelta64(i64::MIN),
14808 _ => Scalar::Timedelta64(raw),
14809 });
14810 }
14811 assert_minmax(case, "timedelta", &timedeltas);
14812 }
14813 }
14814
14815 #[test]
14816 fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
14817 let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
14818 assert!(super::nanmin(&vals).is_missing());
14819 assert!(super::nanmax(&vals).is_missing());
14820
14821 let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
14822 assert!(super::nanmin(&vals2).is_missing());
14823 assert!(super::nanmax(&vals2).is_missing());
14824 }
14825
14826 #[test]
14827 fn nanmin_nanmax_compatible_numeric_types_ok() {
14828 let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
14829 assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
14830 assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
14831 }
14832
14833 #[test]
14834 fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
14835 let one_hour = 3_600 * 1_000_000_000_i64;
14839 let vals = vec![
14840 Scalar::Timedelta64(3 * one_hour),
14841 Scalar::Timedelta64(one_hour),
14842 Scalar::Timedelta64(2 * one_hour),
14843 ];
14844 assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
14845 assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
14846 }
14847
14848 #[test]
14849 fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
14850 let one_hour = 3_600 * 1_000_000_000_i64;
14851 let vals = vec![
14852 Scalar::Timedelta64(Timedelta::NAT),
14853 Scalar::Timedelta64(one_hour),
14854 Scalar::Timedelta64(2 * one_hour),
14855 Scalar::Timedelta64(Timedelta::NAT),
14856 ];
14857 assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
14858 assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
14859 }
14860
14861 #[test]
14862 fn nanmedian_odd_count() {
14863 let vals = vec![
14864 Scalar::Float64(3.0),
14865 Scalar::Null(NullKind::Null),
14866 Scalar::Float64(1.0),
14867 Scalar::Float64(2.0),
14868 ];
14869 assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
14870 }
14871
14872 #[test]
14873 fn nanmedian_even_count() {
14874 let vals = vec![
14875 Scalar::Float64(1.0),
14876 Scalar::Float64(3.0),
14877 Scalar::Float64(2.0),
14878 Scalar::Float64(4.0),
14879 ];
14880 assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
14881 }
14882
14883 #[test]
14884 fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
14885 fn next(seed: &mut u64) -> u64 {
14888 *seed = seed
14889 .wrapping_mul(6364136223846793005)
14890 .wrapping_add(1442695040888963407);
14891 *seed
14892 }
14893
14894 fn expected_numeric(values: &[Scalar]) -> Scalar {
14895 let mut finite = values
14896 .iter()
14897 .filter(|value| !value.is_missing())
14898 .filter_map(|value| value.to_f64().ok())
14899 .filter(|value| !value.is_nan())
14900 .collect::<Vec<_>>();
14901 if finite.is_empty() {
14902 return Scalar::Null(NullKind::NaN);
14903 }
14904 finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
14905 let mid = finite.len() / 2;
14906 if finite.len().is_multiple_of(2) {
14907 Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
14908 } else {
14909 Scalar::Float64(finite[mid])
14910 }
14911 }
14912
14913 fn expected_timedelta(values: &[Scalar]) -> Scalar {
14914 let mut finite = values
14915 .iter()
14916 .filter_map(|value| match value {
14917 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns),
14918 _ => None,
14919 })
14920 .collect::<Vec<_>>();
14921 if finite.is_empty() {
14922 return Scalar::Null(NullKind::NaN);
14923 }
14924 finite.sort_unstable();
14925 let mid = finite.len() / 2;
14926 let median = if finite.len().is_multiple_of(2) {
14927 (i128::from(finite[mid - 1]) + i128::from(finite[mid])) / 2
14928 } else {
14929 i128::from(finite[mid])
14930 };
14931 Scalar::Timedelta64(median as i64)
14932 }
14933
14934 fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
14935 let actual = super::nanmedian(values);
14936 assert!(
14937 actual.semantic_eq(&expected),
14938 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
14939 );
14940 }
14941
14942 assert_median(
14943 usize::MAX,
14944 "numeric_all_missing",
14945 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
14946 Scalar::Null(NullKind::NaN),
14947 );
14948 assert_median(
14949 usize::MAX - 1,
14950 "timedelta_all_missing",
14951 &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
14952 Scalar::Null(NullKind::NaN),
14953 );
14954 let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
14955 assert_median(
14956 usize::MAX - 2,
14957 "timedelta_odd_median_beyond_f64_exactness",
14958 &[
14959 Scalar::Timedelta64(beyond_f64_exact_ns),
14960 Scalar::Timedelta64(beyond_f64_exact_ns + 1),
14961 Scalar::Timedelta64(beyond_f64_exact_ns + 2),
14962 Scalar::Timedelta64(Timedelta::NAT),
14963 ],
14964 Scalar::Timedelta64(beyond_f64_exact_ns + 1),
14965 );
14966
14967 let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
14968 for case in 0..220 {
14969 let len = (next(&mut seed) % 79 + 1) as usize;
14970
14971 let mut numeric = Vec::with_capacity(len);
14972 numeric.push(Scalar::Int64(case as i64 - 110));
14973 for _ in 1..len {
14974 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14975 numeric.push(match next(&mut seed) % 8 {
14976 0 => Scalar::Null(NullKind::Null),
14977 1 => Scalar::Null(NullKind::NaN),
14978 2 => Scalar::Float64(f64::NAN),
14979 3 => Scalar::Bool(raw & 1 == 0),
14980 4 => Scalar::Int64(raw % 251),
14981 5 => Scalar::Float64(raw as f64 / 61.0),
14982 6 => Scalar::Float64(0.0),
14983 _ => Scalar::Float64(-0.0),
14984 });
14985 }
14986 assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
14987
14988 let mut timedeltas = Vec::with_capacity(len);
14989 timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
14990 for _ in 1..len {
14991 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14992 timedeltas.push(match next(&mut seed) % 7 {
14993 0 => Scalar::Null(NullKind::Null),
14994 1 => Scalar::Timedelta64(i64::MIN),
14995 _ => Scalar::Timedelta64(raw),
14996 });
14997 }
14998 assert_median(
14999 case,
15000 "timedelta",
15001 &timedeltas,
15002 expected_timedelta(&timedeltas),
15003 );
15004 }
15005 }
15006
15007 #[test]
15008 fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
15009 fn next(seed: &mut u64) -> u64 {
15012 *seed = seed
15013 .wrapping_mul(2862933555777941757)
15014 .wrapping_add(3037000493);
15015 *seed
15016 }
15017
15018 fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
15019 values
15020 .iter()
15021 .filter(|value| !value.is_missing())
15022 .filter_map(|value| value.to_f64().ok())
15023 .collect()
15024 }
15025
15026 fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
15027 values
15028 .iter()
15029 .filter_map(|value| match value {
15030 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
15031 _ => None,
15032 })
15033 .collect()
15034 }
15035
15036 fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
15037 if samples.len() <= ddof {
15038 return None;
15039 }
15040 let mean = samples.iter().sum::<f64>() / samples.len() as f64;
15041 let sum_sq = samples
15042 .iter()
15043 .map(|value| (value - mean).powi(2))
15044 .sum::<f64>();
15045 let var = sum_sq / (samples.len() - ddof) as f64;
15046 let std = var.sqrt();
15047 let sem = std / (samples.len() as f64).sqrt();
15048 Some((var, std, sem))
15049 }
15050
15051 fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
15052 let samples = numeric_samples(values);
15053 let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
15054 let missing = Scalar::Null(NullKind::NaN);
15055 return (missing.clone(), missing.clone(), missing);
15056 };
15057 (
15058 Scalar::Float64(var),
15059 Scalar::Float64(std),
15060 Scalar::Float64(sem),
15061 )
15062 }
15063
15064 fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
15065 let samples = timedelta_samples(values);
15066 if samples.is_empty() {
15067 let missing = Scalar::Timedelta64(Timedelta::NAT);
15068 return (missing.clone(), missing.clone(), missing);
15069 }
15070 let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
15071 let missing = Scalar::Timedelta64(i64::MIN);
15072 return (missing.clone(), missing.clone(), missing);
15073 };
15074 (
15075 Scalar::Timedelta64(var as i64),
15076 Scalar::Timedelta64(std as i64),
15077 Scalar::Timedelta64(sem as i64),
15078 )
15079 }
15080
15081 fn assert_reductions(
15082 case: usize,
15083 family: &str,
15084 values: &[Scalar],
15085 ddof: usize,
15086 expected: (Scalar, Scalar, Scalar),
15087 ) {
15088 let (expected_var, expected_std, expected_sem) = expected;
15089 let actual_var = super::nanvar(values, ddof);
15090 let actual_std = super::nanstd(values, ddof);
15091 let actual_sem = super::nansem(values, ddof);
15092 assert!(
15093 actual_var.semantic_eq(&expected_var),
15094 "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
15095 );
15096 assert!(
15097 actual_std.semantic_eq(&expected_std),
15098 "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
15099 );
15100 assert!(
15101 actual_sem.semantic_eq(&expected_sem),
15102 "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
15103 );
15104 }
15105
15106 let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15107 assert_reductions(
15108 usize::MAX,
15109 "numeric_all_missing",
15110 &numeric_all_missing,
15111 0,
15112 expected_numeric(&numeric_all_missing, 0),
15113 );
15114
15115 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
15116 assert_reductions(
15117 usize::MAX - 1,
15118 "timedelta_all_missing",
15119 &td_all_missing,
15120 0,
15121 expected_timedelta(&td_all_missing, 0),
15122 );
15123
15124 let mut seed = 0x7a11_c0de_5eed_0421_u64;
15125 for case in 0..240 {
15126 let len = (next(&mut seed) % 83 + 1) as usize;
15127 let ddof = (next(&mut seed) % 4) as usize;
15128
15129 let mut numeric = Vec::with_capacity(len);
15130 numeric.push(Scalar::Float64(case as f64 / 13.0));
15131 for _ in 1..len {
15132 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15133 numeric.push(match next(&mut seed) % 8 {
15134 0 => Scalar::Null(NullKind::Null),
15135 1 => Scalar::Null(NullKind::NaN),
15136 2 => Scalar::Float64(f64::NAN),
15137 3 => Scalar::Bool(raw & 1 == 0),
15138 4 => Scalar::Int64(raw % 251),
15139 5 => Scalar::Float64(raw as f64 / 73.0),
15140 6 => Scalar::Float64(0.0),
15141 _ => Scalar::Float64(-0.0),
15142 });
15143 }
15144 assert_reductions(
15145 case,
15146 "numeric",
15147 &numeric,
15148 ddof,
15149 expected_numeric(&numeric, ddof),
15150 );
15151
15152 let mut timedeltas = Vec::with_capacity(len);
15153 timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15154 for _ in 1..len {
15155 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15156 timedeltas.push(match next(&mut seed) % 7 {
15157 0 => Scalar::Null(NullKind::Null),
15158 1 => Scalar::Timedelta64(i64::MIN),
15159 _ => Scalar::Timedelta64(raw),
15160 });
15161 }
15162 assert_reductions(
15163 case,
15164 "timedelta",
15165 &timedeltas,
15166 ddof,
15167 expected_timedelta(&timedeltas, ddof),
15168 );
15169 }
15170 }
15171
15172 #[test]
15173 fn nanvar_population() {
15174 let vals = vec![
15175 Scalar::Float64(2.0),
15176 Scalar::Float64(4.0),
15177 Scalar::Float64(4.0),
15178 Scalar::Float64(4.0),
15179 Scalar::Float64(5.0),
15180 Scalar::Float64(5.0),
15181 Scalar::Float64(7.0),
15182 Scalar::Float64(9.0),
15183 ];
15184 let var = super::nanvar(&vals, 0);
15185 assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15186 if let Scalar::Float64(v) = var {
15187 assert!((v - 4.0).abs() < 1e-10);
15188 }
15189 }
15190
15191 #[test]
15192 fn nanvar_sample_ddof1() {
15193 let vals = vec![
15194 Scalar::Float64(2.0),
15195 Scalar::Float64(4.0),
15196 Scalar::Float64(4.0),
15197 Scalar::Float64(4.0),
15198 Scalar::Float64(5.0),
15199 Scalar::Float64(5.0),
15200 Scalar::Float64(7.0),
15201 Scalar::Float64(9.0),
15202 ];
15203 let var = super::nanvar(&vals, 1);
15204 assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15205 if let Scalar::Float64(v) = var {
15206 assert!((v - 32.0 / 7.0).abs() < 1e-10);
15207 }
15208 }
15209
15210 #[test]
15211 fn nanvar_insufficient_values_returns_nan() {
15212 let vals = vec![Scalar::Float64(5.0)];
15213 assert!(super::nanvar(&vals, 1).is_missing());
15214 }
15215
15216 #[test]
15217 fn nanstd_is_sqrt_of_var() {
15218 let vals = vec![
15219 Scalar::Float64(2.0),
15220 Scalar::Float64(4.0),
15221 Scalar::Float64(4.0),
15222 Scalar::Float64(4.0),
15223 Scalar::Float64(5.0),
15224 Scalar::Float64(5.0),
15225 Scalar::Float64(7.0),
15226 Scalar::Float64(9.0),
15227 ];
15228 let std = super::nanstd(&vals, 0);
15229 assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
15230 if let Scalar::Float64(v) = std {
15231 assert!((v - 2.0).abs() < 1e-10);
15232 }
15233 }
15234
15235 #[test]
15236 fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
15237 let one_hour = 3_600 * 1_000_000_000_i64;
15240 let vals = vec![
15241 Scalar::Timedelta64(one_hour),
15242 Scalar::Timedelta64(2 * one_hour),
15243 Scalar::Timedelta64(3 * one_hour),
15244 ];
15245 assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
15246 }
15247
15248 #[test]
15249 fn nanstd_timedelta64_preserves_dtype_j8ntk() {
15250 let one_hour: i64 = 3_600 * 1_000_000_000;
15254 let vals = vec![
15255 Scalar::Timedelta64(one_hour),
15256 Scalar::Timedelta64(2 * one_hour),
15257 Scalar::Timedelta64(3 * one_hour),
15258 ];
15259 let std = super::nanstd(&vals, 0);
15260 assert!(matches!(std, Scalar::Timedelta64(_)));
15261 if let Scalar::Timedelta64(ns) = std {
15262 let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
15263 assert!(
15264 (ns as f64 - expected).abs() < 1e6,
15265 "expected ~{expected} ns, got {ns}"
15266 );
15267 }
15268 }
15269
15270 #[test]
15271 fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
15272 let one_hour = 3_600 * 1_000_000_000_i64;
15273 let vals = vec![Scalar::Timedelta64(one_hour)];
15274 assert_eq!(super::nanstd(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15276 assert_eq!(super::nansem(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15277 }
15278
15279 #[test]
15280 fn nanops_with_mixed_types() {
15281 let vals = vec![
15282 Scalar::Bool(true),
15283 Scalar::Int64(3),
15284 Scalar::Float64(6.0),
15285 Scalar::Null(NullKind::Null),
15286 ];
15287 assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
15288 assert_eq!(super::nancount(&vals), Scalar::Int64(3));
15289 }
15290
15291 #[test]
15292 fn nanops_all_missing_returns_identity() {
15293 let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15294 assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
15295 assert!(super::nanmean(&vals).is_missing());
15296 assert!(super::nanmedian(&vals).is_missing());
15297 assert!(super::nanvar(&vals, 0).is_missing());
15298 assert!(super::nanstd(&vals, 0).is_missing());
15299 }
15300
15301 #[test]
15304 fn timedelta_parse_simple_units() {
15305 use super::Timedelta;
15306 assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
15307 assert_eq!(
15308 Timedelta::parse("2h").unwrap(),
15309 2 * Timedelta::NANOS_PER_HOUR
15310 );
15311 assert_eq!(
15312 Timedelta::parse("30m").unwrap(),
15313 30 * Timedelta::NANOS_PER_MIN
15314 );
15315 assert_eq!(
15316 Timedelta::parse("45s").unwrap(),
15317 45 * Timedelta::NANOS_PER_SEC
15318 );
15319 assert_eq!(
15320 Timedelta::parse("100ms").unwrap(),
15321 100 * Timedelta::NANOS_PER_MILLI
15322 );
15323 assert_eq!(
15324 Timedelta::parse("500us").unwrap(),
15325 500 * Timedelta::NANOS_PER_MICRO
15326 );
15327 assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
15328 }
15329
15330 #[test]
15331 fn timedelta_parse_zero_valued_compound() {
15332 use super::Timedelta;
15333 for s in [
15340 "0 seconds",
15341 "0 second",
15342 "0 sec",
15343 "0s",
15344 "0 days",
15345 "0d",
15346 "0 hours",
15347 "0.0 hours",
15348 "0 minutes",
15349 "0ms",
15350 "0us",
15351 "0ns",
15352 "0",
15353 "0 days 0 seconds",
15354 ] {
15355 assert_eq!(Timedelta::parse(s).unwrap(), 0, "parse({s:?}) should be 0");
15356 }
15357 assert_eq!(Timedelta::parse("-0 seconds").unwrap(), 0);
15359 assert!(Timedelta::parse("0 fortnights").is_err());
15362 assert!(Timedelta::parse("seconds").is_err());
15363 }
15364
15365 #[test]
15366 fn timedelta_parse_compound() {
15367 use super::Timedelta;
15368 let expected = Timedelta::NANOS_PER_DAY
15369 + 2 * Timedelta::NANOS_PER_HOUR
15370 + 30 * Timedelta::NANOS_PER_MIN;
15371 assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
15372 assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
15373 }
15374
15375 #[test]
15376 fn timedelta_parse_leading_sign_spares_the_clock_part() {
15377 use super::Timedelta;
15378 const S: i64 = Timedelta::NANOS_PER_SEC;
15379 assert_eq!(Timedelta::parse("-1 days 02:03:04").unwrap(), -79_016 * S);
15382 assert_eq!(Timedelta::parse("-1 days +02:03:04").unwrap(), -79_016 * S);
15383 assert_eq!(
15384 Timedelta::parse("-3 days +23:59:59.5").unwrap(),
15385 -172_800 * S - S / 2
15386 );
15387 assert_eq!(Timedelta::parse("-0 days 01:00:00").unwrap(), 3_600 * S);
15388 assert_eq!(Timedelta::parse("-1d2h").unwrap(), -93_600 * S);
15390 assert_eq!(Timedelta::parse("-02:03:04").unwrap(), -7_384 * S);
15391 assert!(Timedelta::parse("-1 days -02:03:04").is_err());
15393 assert!(Timedelta::parse("1 days -02:00:00").is_err());
15394 }
15395
15396 #[test]
15397 fn timedelta_parse_iso8601_matches_pandas_tdiso() {
15398 use super::Timedelta;
15399 assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
15401 assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
15402 assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
15403 assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
15404 assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
15405 assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
15406 assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
15408 assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
15409 assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
15410 assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
15411 assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
15412 assert!(Timedelta::parse("P1Y").is_err());
15414 assert!(Timedelta::parse("p1d").is_err());
15415 assert!(Timedelta::parse("P").is_err());
15416 assert!(Timedelta::parse("PT").is_err());
15417 }
15418
15419 #[test]
15420 fn timedelta_parse_time_format() {
15421 use super::Timedelta;
15422 let expected = Timedelta::NANOS_PER_HOUR
15423 + 30 * Timedelta::NANOS_PER_MIN
15424 + 45 * Timedelta::NANOS_PER_SEC;
15425 assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
15426 }
15427
15428 #[test]
15429 fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
15430 use super::{Timedelta, TimedeltaError};
15431 let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
15432 .expect_err("non-ASCII fractional seconds must reject");
15433 assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15434 }
15435
15436 #[test]
15437 fn timedelta_parse_time_format_rejects_overflow_without_panic() {
15438 use super::{Timedelta, TimedeltaError};
15439 let err = Timedelta::parse("9223372036854775807:00")
15440 .expect_err("oversized hour component must reject");
15441 assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15442 }
15443
15444 #[test]
15445 fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
15446 use super::{Timedelta, TimedeltaError};
15453 let huge = format!("{} days", "9".repeat(18));
15454 assert!(matches!(
15455 Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
15456 TimedeltaError::Overflow
15457 ));
15458 }
15459
15460 #[test]
15461 fn timedelta_parse_nat() {
15462 use super::Timedelta;
15463 assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
15464 assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
15465 }
15466
15467 #[test]
15468 fn timedelta_parse_negative() {
15469 use super::Timedelta;
15470 assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
15471 }
15472
15473 #[test]
15474 fn timedelta_components() {
15475 use super::Timedelta;
15476 let nanos = Timedelta::NANOS_PER_DAY
15477 + Timedelta::NANOS_PER_HOUR
15478 + Timedelta::NANOS_PER_MIN
15479 + Timedelta::NANOS_PER_SEC
15480 + Timedelta::NANOS_PER_MILLI
15481 + 2 * Timedelta::NANOS_PER_MICRO
15482 + 3;
15483 let comp = Timedelta::components(nanos);
15484 assert_eq!(comp.days, 1);
15485 assert_eq!(comp.hours, 1);
15486 assert_eq!(comp.minutes, 1);
15487 assert_eq!(comp.seconds, 1);
15488 assert_eq!(comp.milliseconds, 1);
15489 assert_eq!(comp.microseconds, 2);
15490 assert_eq!(comp.nanoseconds, 3);
15491 }
15492
15493 #[test]
15494 fn timedelta_negative_components_floor_div() {
15495 use super::Timedelta;
15496 let neg_1s = -Timedelta::NANOS_PER_SEC;
15499 assert_eq!(Timedelta::days(neg_1s), Some(-1));
15500 assert_eq!(Timedelta::seconds(neg_1s), Some(86399));
15501 assert_eq!(Timedelta::microseconds(neg_1s), Some(0));
15502 assert_eq!(Timedelta::nanoseconds(neg_1s), Some(0));
15503 let comp = Timedelta::components(neg_1s);
15504 assert_eq!(
15505 (
15506 comp.days,
15507 comp.hours,
15508 comp.minutes,
15509 comp.seconds,
15510 comp.milliseconds,
15511 comp.microseconds,
15512 comp.nanoseconds
15513 ),
15514 (-1, 23, 59, 59, 0, 0, 0)
15515 );
15516
15517 let neg = -86_401 * Timedelta::NANOS_PER_SEC;
15519 assert_eq!(Timedelta::days(neg), Some(-2));
15520 assert_eq!(Timedelta::seconds(neg), Some(86399));
15521 }
15522
15523 #[test]
15538 fn timedelta_components_are_missing_for_nat_not_zero_406ni() {
15539 use super::Timedelta;
15540 assert_eq!(Timedelta::days(Timedelta::NAT), None);
15541 assert_eq!(Timedelta::seconds(Timedelta::NAT), None);
15542 assert_eq!(Timedelta::microseconds(Timedelta::NAT), None);
15543 assert_eq!(Timedelta::nanoseconds(Timedelta::NAT), None);
15544
15545 let one_day = Timedelta::NANOS_PER_DAY;
15550 assert_eq!(Timedelta::days(one_day), Some(1));
15551 assert_eq!(Timedelta::seconds(one_day), Some(0));
15552 assert_eq!(Timedelta::microseconds(one_day), Some(0));
15553 assert_eq!(Timedelta::nanoseconds(one_day), Some(0));
15554 }
15555
15556 #[test]
15557 fn timedelta_total_seconds() {
15558 use super::Timedelta;
15559 let nanos = 90_000_000_000i64; assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
15561 assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
15562 }
15563
15564 #[test]
15565 fn timedelta_format_basic() {
15566 use super::Timedelta;
15567 assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
15568 assert_eq!(
15569 Timedelta::format(Timedelta::NANOS_PER_DAY),
15570 "1 days 00:00:00"
15571 );
15572 assert_eq!(
15573 Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
15574 "1 days 02:00:00"
15575 );
15576 }
15577
15578 #[test]
15579 fn timedelta_format_subsecond_matches_pandas() {
15580 use super::Timedelta;
15581 assert_eq!(
15585 Timedelta::format(1_500_000_000), "0 days 00:00:01.500000"
15587 );
15588 assert_eq!(
15589 Timedelta::format(1_000_000), "0 days 00:00:00.001000"
15591 );
15592 assert_eq!(
15593 Timedelta::format(123_456_000), "0 days 00:00:00.123456"
15595 );
15596 assert_eq!(
15598 Timedelta::format(500), "0 days 00:00:00.000000500"
15600 );
15601 assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
15602 }
15603
15604 #[test]
15605 fn timedelta_format_negative_uses_python_borrow_form() {
15606 use super::Timedelta;
15607 assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
15611 assert_eq!(
15612 Timedelta::format(-Timedelta::NANOS_PER_DAY),
15613 "-1 days +00:00:00"
15614 );
15615 assert_eq!(
15616 Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
15617 "-2 days +23:00:00"
15618 );
15619 assert_eq!(
15620 Timedelta::format(-1_500_000_000),
15621 "-1 days +23:59:58.500000"
15622 );
15623 assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
15624 assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
15625 }
15626
15627 #[test]
15628 #[ignore = "foreground release attribution harness"]
15629 fn timedelta_format_single_buffer_ab_5ro9h() {
15630 use std::{hint::black_box, time::Instant};
15631
15632 use super::Timedelta;
15633
15634 fn former(nanos: i64) -> String {
15635 if nanos == Timedelta::NAT {
15636 return "NaT".to_string();
15637 }
15638
15639 let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
15640 let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
15641 let hours = rem / Timedelta::NANOS_PER_HOUR;
15642 let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
15643 let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
15644 let frac = rem % Timedelta::NANOS_PER_SEC;
15645
15646 let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
15647 let sep = if days < 0 { "+" } else { "" };
15648 if frac > 0 {
15649 if frac % 1_000 == 0 {
15650 format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
15651 } else {
15652 format!("{days} days {sep}{time_part}.{frac:09}")
15653 }
15654 } else {
15655 format!("{days} days {sep}{time_part}")
15656 }
15657 }
15658
15659 fn candidate(nanos: i64) -> String {
15660 Timedelta::format(nanos)
15661 }
15662
15663 fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
15664 let started = Instant::now();
15665 let mut digest = 0_usize;
15666 for &value in values {
15667 digest = digest.wrapping_add(black_box(format(black_box(value))).len());
15668 }
15669 black_box(digest);
15670 started.elapsed().as_nanos()
15671 }
15672
15673 fn median(samples: &mut [u128]) -> u128 {
15674 samples.sort_unstable();
15675 samples[samples.len() / 2]
15676 }
15677
15678 let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
15679 let values: Vec<i64> = (0..16_384)
15680 .map(|i| {
15681 seed = seed
15682 .wrapping_mul(6_364_136_223_846_793_005)
15683 .wrapping_add(1_442_695_040_888_963_407);
15684 let magnitude = (seed & i64::MAX as u64) as i64;
15685 match i % 4 {
15686 0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
15687 1 => magnitude,
15688 2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
15689 _ => -magnitude,
15690 }
15691 })
15692 .collect();
15693
15694 for &value in &[
15695 Timedelta::NAT,
15696 0,
15697 1,
15698 -1,
15699 Timedelta::NANOS_PER_DAY,
15700 -Timedelta::NANOS_PER_DAY,
15701 i64::MAX,
15702 i64::MIN + 1,
15703 ] {
15704 assert_eq!(former(value), candidate(value));
15705 }
15706 for &value in &values {
15707 assert_eq!(former(value), candidate(value));
15708 }
15709
15710 for _ in 0..2 {
15711 black_box(elapsed(&values, former));
15712 black_box(elapsed(&values, candidate));
15713 }
15714
15715 let mut former_samples = Vec::with_capacity(18);
15716 let mut candidate_samples = Vec::with_capacity(18);
15717 for block in 0_usize..9 {
15718 if block.is_multiple_of(2) {
15719 former_samples.push(elapsed(&values, former));
15720 candidate_samples.push(elapsed(&values, candidate));
15721 candidate_samples.push(elapsed(&values, candidate));
15722 former_samples.push(elapsed(&values, former));
15723 } else {
15724 candidate_samples.push(elapsed(&values, candidate));
15725 former_samples.push(elapsed(&values, former));
15726 former_samples.push(elapsed(&values, former));
15727 candidate_samples.push(elapsed(&values, candidate));
15728 }
15729 }
15730
15731 let former_p50 = median(&mut former_samples);
15732 let candidate_p50 = median(&mut candidate_samples);
15733 eprintln!(
15734 "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
15735 values.len(),
15736 former_p50 as f64 / candidate_p50 as f64,
15737 );
15738 eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
15739 eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
15740 }
15741
15742 #[test]
15743 fn timedelta_isoformat_basic() {
15744 use super::Timedelta;
15745 assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
15746 assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
15747 assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
15748 assert_eq!(
15749 Timedelta::isoformat(
15750 Timedelta::NANOS_PER_DAY
15751 + 2 * Timedelta::NANOS_PER_HOUR
15752 + 30 * Timedelta::NANOS_PER_MIN
15753 + 45 * Timedelta::NANOS_PER_SEC
15754 ),
15755 "P1DT2H30M45S"
15756 );
15757 assert_eq!(
15758 Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
15759 "P0DT0H0M1.5S"
15760 );
15761 assert_eq!(
15766 Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
15767 "P-2DT23H0M0S"
15768 );
15769 assert_eq!(Timedelta::isoformat(-1), "P-1DT23H59M59.999999999S");
15770 }
15771
15772 #[test]
15773 #[ignore = "foreground release attribution harness"]
15774 fn timedelta_isoformat_single_buffer_ab_7jra1() {
15775 use std::{hint::black_box, time::Instant};
15776
15777 use super::Timedelta;
15778
15779 fn former_impl(nanos: i64) -> String {
15780 if nanos == Timedelta::NAT {
15781 return "NaT".to_string();
15782 }
15783
15784 let negative = nanos < 0;
15785 let abs_nanos = nanos.saturating_abs();
15786 let days = abs_nanos / Timedelta::NANOS_PER_DAY;
15787 let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
15788 let hours = remaining / Timedelta::NANOS_PER_HOUR;
15789 let remaining = remaining % Timedelta::NANOS_PER_HOUR;
15790 let minutes = remaining / Timedelta::NANOS_PER_MIN;
15791 let remaining = remaining % Timedelta::NANOS_PER_MIN;
15792 let seconds = remaining / Timedelta::NANOS_PER_SEC;
15793 let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
15794
15795 let mut result = String::new();
15796 if negative {
15797 result.push('-');
15798 }
15799
15800 result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
15801
15802 if sub_sec_nanos == 0 {
15803 result.push_str(&format!("{seconds}S"));
15804 } else {
15805 let frac = format!("{sub_sec_nanos:09}");
15806 let trimmed = frac.trim_end_matches('0');
15807 result.push_str(&format!("{seconds}.{trimmed}S"));
15808 }
15809
15810 result
15811 }
15812
15813 fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
15814 let start = Instant::now();
15815 let mut digest = 0_usize;
15816 for &value in values {
15817 digest = digest.wrapping_add(black_box(format(black_box(value))).len());
15818 }
15819 black_box(digest);
15820 start.elapsed().as_nanos()
15821 }
15822
15823 fn median(values: &mut [u128]) -> u128 {
15824 values.sort_unstable();
15825 values[values.len() / 2]
15826 }
15827
15828 let mut seed = 0x7d5a_4c31_91e2_b607_u64;
15829 let values: Vec<i64> = (0..16_384)
15830 .map(|i| {
15831 seed = seed
15832 .wrapping_mul(6_364_136_223_846_793_005)
15833 .wrapping_add(1_442_695_040_888_963_407);
15834 let magnitude =
15835 (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
15836 match i % 4 {
15837 0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
15838 1 => magnitude,
15839 2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
15840 _ => -magnitude,
15841 }
15842 })
15843 .collect();
15844
15845 for &value in &[Timedelta::NAT, 0, 1, Timedelta::NANOS_PER_DAY, i64::MAX] {
15849 assert_eq!(former_impl(value), Timedelta::isoformat(value));
15850 }
15851 for &value in values.iter().filter(|value| **value >= 0) {
15852 assert_eq!(former_impl(value), Timedelta::isoformat(value));
15853 }
15854
15855 for _ in 0..2 {
15856 black_box(elapsed(&values, former_impl));
15857 black_box(elapsed(&values, Timedelta::isoformat));
15858 }
15859
15860 let mut former = Vec::with_capacity(18);
15861 let mut candidate = Vec::with_capacity(18);
15862 for block in 0..9 {
15863 if block % 2 == 0 {
15864 former.push(elapsed(&values, former_impl));
15865 candidate.push(elapsed(&values, Timedelta::isoformat));
15866 candidate.push(elapsed(&values, Timedelta::isoformat));
15867 former.push(elapsed(&values, former_impl));
15868 } else {
15869 candidate.push(elapsed(&values, Timedelta::isoformat));
15870 former.push(elapsed(&values, former_impl));
15871 former.push(elapsed(&values, former_impl));
15872 candidate.push(elapsed(&values, Timedelta::isoformat));
15873 }
15874 }
15875
15876 let former_p50 = median(&mut former);
15877 let candidate_p50 = median(&mut candidate);
15878 eprintln!(
15879 "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
15880 values.len(),
15881 former_p50,
15882 candidate_p50,
15883 former_p50 as f64 / candidate_p50 as f64,
15884 former_p50 as f64 / values.len() as f64,
15885 candidate_p50 as f64 / values.len() as f64,
15886 );
15887 eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
15888 eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
15889 }
15890
15891 #[test]
15892 fn timedelta_floor_ceil_round() {
15893 use super::Timedelta;
15894 let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
15895
15896 assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
15898 assert_eq!(Timedelta::floor(nanos, "d"), 0);
15899
15900 assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
15902 assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
15903
15904 assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
15906
15907 assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
15909 assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
15910 assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
15911
15912 assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
15914 }
15915
15916 #[test]
15917 fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
15918 use super::Timedelta;
15919
15920 assert_eq!(
15921 Timedelta::floor(-1, "s"),
15922 -Timedelta::NANOS_PER_SEC,
15923 "floor(-1ns, 1s)"
15924 );
15925 assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
15926 assert_eq!(
15927 Timedelta::floor(-1_500_000_000, "s"),
15928 -2 * Timedelta::NANOS_PER_SEC
15929 );
15930 assert_eq!(
15931 Timedelta::ceil(-1_500_000_000, "s"),
15932 -Timedelta::NANOS_PER_SEC
15933 );
15934 assert_eq!(
15935 Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
15936 -Timedelta::NANOS_PER_SEC
15937 );
15938 assert_eq!(
15939 Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
15940 -Timedelta::NANOS_PER_SEC
15941 );
15942 assert_eq!(
15943 Timedelta::floor(1_500_000_000, "s"),
15944 Timedelta::NANOS_PER_SEC
15945 );
15946 assert_eq!(
15947 Timedelta::ceil(1_500_000_000, "s"),
15948 2 * Timedelta::NANOS_PER_SEC
15949 );
15950 }
15951
15952 #[test]
15953 fn timedelta_scalar_dtype() {
15954 let td = Scalar::Timedelta64(86_400_000_000_000);
15955 assert_eq!(td.dtype(), DType::Timedelta64);
15956 }
15957
15958 #[test]
15959 fn timedelta_scalar_is_missing() {
15960 use super::Timedelta;
15961 let valid = Scalar::Timedelta64(1000);
15962 let nat = Scalar::Timedelta64(Timedelta::NAT);
15963 assert!(!valid.is_missing());
15964 assert!(nat.is_missing());
15965 }
15966
15967 #[test]
15968 fn dtype_utf8_deserializes_legacy_aliases() {
15969 let dtype: DType = serde_json::from_str("\"str\"").unwrap();
15970 assert_eq!(dtype, DType::Utf8);
15971
15972 let dtype: DType = serde_json::from_str("\"string\"").unwrap();
15973 assert_eq!(dtype, DType::Utf8);
15974 }
15975
15976 #[test]
15977 fn datetime64_dtype_carries_timezone_00ze3() {
15978 let naive = DType::datetime64_naive();
15979 assert_eq!(naive.timezone(), None);
15980 assert_eq!(naive.display_name(), "datetime64[ns]");
15981
15982 let aware = DType::datetime64_tz("America/New_York");
15983 assert_eq!(aware.timezone(), Some("America/New_York"));
15984 assert_eq!(aware.display_name(), "datetime64[ns, America/New_York]");
15985 assert_ne!(aware, naive, "timezone must participate in dtype identity");
15986
15987 let json = serde_json::to_string(&aware).expect("serialize timezone dtype");
15988 assert_eq!(
15989 serde_json::from_str::<DType>(&json).expect("deserialize timezone dtype"),
15990 aware
15991 );
15992 }
15993
15994 #[test]
15995 fn scalar_utf8_deserializes_legacy_aliases() {
15996 let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
15997 assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
15998
15999 let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
16000 assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
16001 }
16002
16003 #[test]
16004 fn nancumsum_skips_nulls_and_accumulates() {
16005 let values = vec![
16006 Scalar::Float64(1.0),
16007 Scalar::Null(NullKind::NaN),
16008 Scalar::Float64(2.0),
16009 Scalar::Float64(3.0),
16010 ];
16011 let out = super::nancumsum(&values);
16012 assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
16013 assert!(out[1].is_missing());
16014 assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
16015 assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
16016 }
16017
16018 #[test]
16019 fn nancumprod_skips_nulls_and_multiplies() {
16020 let values = vec![
16021 Scalar::Float64(2.0),
16022 Scalar::Null(NullKind::NaN),
16023 Scalar::Float64(3.0),
16024 Scalar::Float64(4.0),
16025 ];
16026 let out = super::nancumprod(&values);
16027 assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16028 assert!(out[1].is_missing());
16029 assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
16030 assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
16031 }
16032
16033 #[test]
16034 fn nancummax_tracks_running_max() {
16035 let values = vec![
16036 Scalar::Float64(1.0),
16037 Scalar::Float64(3.0),
16038 Scalar::Null(NullKind::NaN),
16039 Scalar::Float64(2.0),
16040 Scalar::Float64(5.0),
16041 ];
16042 let out = super::nancummax(&values);
16043 assert_eq!(out[0], Scalar::Float64(1.0));
16044 assert_eq!(out[1], Scalar::Float64(3.0));
16045 assert!(out[2].is_missing());
16046 assert_eq!(out[3], Scalar::Float64(3.0));
16047 assert_eq!(out[4], Scalar::Float64(5.0));
16048 }
16049
16050 #[test]
16051 fn nancummin_tracks_running_min() {
16052 let values = vec![
16053 Scalar::Float64(5.0),
16054 Scalar::Float64(3.0),
16055 Scalar::Null(NullKind::NaN),
16056 Scalar::Float64(4.0),
16057 Scalar::Float64(1.0),
16058 ];
16059 let out = super::nancummin(&values);
16060 assert_eq!(out[0], Scalar::Float64(5.0));
16061 assert_eq!(out[1], Scalar::Float64(3.0));
16062 assert!(out[2].is_missing());
16063 assert_eq!(out[3], Scalar::Float64(3.0));
16064 assert_eq!(out[4], Scalar::Float64(1.0));
16065 }
16066
16067 #[test]
16068 fn nancumsum_timedelta64_preserves_dtype_x0x91() {
16069 let one_hour = 3_600 * 1_000_000_000_i64;
16072 let values = vec![
16073 Scalar::Timedelta64(one_hour),
16074 Scalar::Timedelta64(2 * one_hour),
16075 Scalar::Timedelta64(3 * one_hour),
16076 ];
16077 let out = super::nancumsum(&values);
16078 assert_eq!(out[0], Scalar::Timedelta64(one_hour));
16079 assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
16080 assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
16081 }
16082
16083 #[test]
16084 fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
16085 let one_hour = 3_600 * 1_000_000_000_i64;
16086 let values = vec![
16087 Scalar::Timedelta64(2 * one_hour),
16088 Scalar::Timedelta64(5 * one_hour),
16089 Scalar::Timedelta64(one_hour),
16090 Scalar::Timedelta64(3 * one_hour),
16091 ];
16092 let mx = super::nancummax(&values);
16093 assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
16094 assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
16095 assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
16096 assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
16097
16098 let mn = super::nancummin(&values);
16099 assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
16100 assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
16101 assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
16102 assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
16103 }
16104
16105 #[test]
16106 fn nancumulative_timedelta64_skips_nat_x0x91() {
16107 let one_hour = 3_600 * 1_000_000_000_i64;
16108 let values = vec![
16109 Scalar::Timedelta64(one_hour),
16110 Scalar::Timedelta64(Timedelta::NAT),
16111 Scalar::Timedelta64(2 * one_hour),
16112 ];
16113 let cs = super::nancumsum(&values);
16114 assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
16115 assert!(cs[1].is_missing());
16116 assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
16117 }
16118
16119 #[test]
16120 fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
16121 fn next(seed: &mut u64) -> u64 {
16124 *seed = seed
16125 .wrapping_mul(3202034522624059733)
16126 .wrapping_add(4354685564936845319);
16127 *seed
16128 }
16129
16130 fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
16131 assert_eq!(
16132 actual.len(),
16133 expected.len(),
16134 "case={case} family={family} op={op}: length mismatch"
16135 );
16136 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
16137 assert!(
16138 actual.semantic_eq(expected),
16139 "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
16140 );
16141 }
16142 }
16143
16144 fn expected_numeric(
16145 values: &[Scalar],
16146 ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16147 let mut sum = Vec::with_capacity(values.len());
16148 let mut prod = Vec::with_capacity(values.len());
16149 let mut max = Vec::with_capacity(values.len());
16150 let mut min = Vec::with_capacity(values.len());
16151 let mut running_sum = 0.0_f64;
16152 let mut running_prod = 1.0_f64;
16153 let mut running_max: Option<f64> = None;
16154 let mut running_min: Option<f64> = None;
16155
16156 for value in values {
16157 if value.is_missing() {
16158 sum.push(Scalar::Null(NullKind::NaN));
16159 prod.push(Scalar::Null(NullKind::NaN));
16160 max.push(Scalar::Null(NullKind::NaN));
16161 min.push(Scalar::Null(NullKind::NaN));
16162 continue;
16163 }
16164 let Ok(value) = value.to_f64() else {
16165 sum.push(Scalar::Null(NullKind::NaN));
16166 prod.push(Scalar::Null(NullKind::NaN));
16167 max.push(Scalar::Null(NullKind::NaN));
16168 min.push(Scalar::Null(NullKind::NaN));
16169 continue;
16170 };
16171 if value.is_nan() {
16172 sum.push(Scalar::Null(NullKind::NaN));
16173 prod.push(Scalar::Null(NullKind::NaN));
16174 max.push(Scalar::Null(NullKind::NaN));
16175 min.push(Scalar::Null(NullKind::NaN));
16176 continue;
16177 }
16178 running_sum += value;
16179 running_prod *= value;
16180 running_max = Some(running_max.map_or(value, |current| current.max(value)));
16181 running_min = Some(running_min.map_or(value, |current| current.min(value)));
16182 sum.push(Scalar::Float64(running_sum));
16183 prod.push(Scalar::Float64(running_prod));
16184 max.push(Scalar::Float64(running_max.expect("initialized")));
16185 min.push(Scalar::Float64(running_min.expect("initialized")));
16186 }
16187
16188 (sum, prod, max, min)
16189 }
16190
16191 fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16192 let mut sum = Vec::with_capacity(values.len());
16193 let mut max = Vec::with_capacity(values.len());
16194 let mut min = Vec::with_capacity(values.len());
16195 let mut running_sum = 0_i128;
16196 let mut running_max: Option<i64> = None;
16197 let mut running_min: Option<i64> = None;
16198
16199 for value in values {
16200 if value.is_missing() {
16201 sum.push(Scalar::Null(NullKind::NaT));
16202 max.push(Scalar::Null(NullKind::NaT));
16203 min.push(Scalar::Null(NullKind::NaT));
16204 continue;
16205 }
16206 let Scalar::Timedelta64(ns) = value else {
16207 sum.push(Scalar::Null(NullKind::NaT));
16208 max.push(Scalar::Null(NullKind::NaT));
16209 min.push(Scalar::Null(NullKind::NaT));
16210 continue;
16211 };
16212 running_sum = running_sum.saturating_add(i128::from(*ns));
16213 running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
16214 running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
16215 sum.push(super::timedelta_ns_to_scalar(running_sum));
16218 max.push(Scalar::Timedelta64(running_max.expect("initialized")));
16219 min.push(Scalar::Timedelta64(running_min.expect("initialized")));
16220 }
16221
16222 (sum, max, min)
16223 }
16224
16225 let mut seed = 0xc0de_c63a_5eed_0421_u64;
16226 for case in 0..260 {
16227 let len = (next(&mut seed) % 89 + 1) as usize;
16228
16229 let mut numeric = Vec::with_capacity(len);
16230 numeric.push(Scalar::Int64(case as i64 - 130));
16231 for _ in 1..len {
16232 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16233 numeric.push(match next(&mut seed) % 8 {
16234 0 => Scalar::Null(NullKind::Null),
16235 1 => Scalar::Null(NullKind::NaN),
16236 2 => Scalar::Float64(f64::NAN),
16237 3 => Scalar::Bool(raw & 1 == 0),
16238 4 => Scalar::Int64(raw % 251),
16239 5 => Scalar::Float64(raw as f64 / 79.0),
16240 6 => Scalar::Float64(0.0),
16241 _ => Scalar::Float64(-0.0),
16242 });
16243 }
16244 let (sum, prod, max, min) = expected_numeric(&numeric);
16245 assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
16246 assert_vec(
16247 case,
16248 "numeric",
16249 "cumprod",
16250 &super::nancumprod(&numeric),
16251 &prod,
16252 );
16253 assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
16254 assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
16255
16256 let mut timedeltas = Vec::with_capacity(len);
16257 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16258 for _ in 1..len {
16259 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16260 timedeltas.push(match next(&mut seed) % 7 {
16261 0 => Scalar::Null(NullKind::Null),
16262 1 => Scalar::Timedelta64(i64::MIN),
16263 _ => Scalar::Timedelta64(raw),
16264 });
16265 }
16266 let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
16267 assert_vec(
16268 case,
16269 "timedelta",
16270 "cumsum",
16271 &super::nancumsum(&timedeltas),
16272 &td_sum,
16273 );
16274 assert_vec(
16275 case,
16276 "timedelta",
16277 "cummax",
16278 &super::nancummax(&timedeltas),
16279 &td_max,
16280 );
16281 assert_vec(
16282 case,
16283 "timedelta",
16284 "cummin",
16285 &super::nancummin(&timedeltas),
16286 &td_min,
16287 );
16288 }
16289 }
16290
16291 #[test]
16292 fn nanquantile_linear_interpolation_matches_numpy() {
16293 let values = vec![
16294 Scalar::Float64(1.0),
16295 Scalar::Float64(2.0),
16296 Scalar::Float64(3.0),
16297 Scalar::Float64(4.0),
16298 Scalar::Float64(5.0),
16299 ];
16300 let q = super::nanquantile(&values, 0.5);
16302 assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
16303 let q25 = super::nanquantile(&values, 0.25);
16305 assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16306 }
16307
16308 #[test]
16309 fn nanquantile_ignores_nulls() {
16310 let values = vec![
16311 Scalar::Float64(1.0),
16312 Scalar::Null(NullKind::NaN),
16313 Scalar::Float64(3.0),
16314 ];
16315 let q = super::nanquantile(&values, 0.5);
16316 assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16317 }
16318
16319 #[test]
16320 fn nanquantile_empty_and_out_of_range_yield_null() {
16321 assert!(super::nanquantile(&[], 0.5).is_missing());
16322 assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
16323 assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
16324 }
16325
16326 #[test]
16327 fn nanquantile_timedelta64_preserves_dtype_5djk7() {
16328 let one_hour: i64 = 3_600 * 1_000_000_000;
16331 let vals = vec![
16332 Scalar::Timedelta64(one_hour),
16333 Scalar::Timedelta64(2 * one_hour),
16334 Scalar::Timedelta64(3 * one_hour),
16335 Scalar::Timedelta64(4 * one_hour),
16336 Scalar::Timedelta64(5 * one_hour),
16337 ];
16338 assert_eq!(
16339 super::nanquantile(&vals, 0.5),
16340 Scalar::Timedelta64(3 * one_hour)
16341 );
16342 assert_eq!(
16343 super::nanquantile(&vals, 0.0),
16344 Scalar::Timedelta64(one_hour)
16345 );
16346 assert_eq!(
16347 super::nanquantile(&vals, 1.0),
16348 Scalar::Timedelta64(5 * one_hour)
16349 );
16350 }
16351
16352 #[test]
16353 fn nanquantile_timedelta64_linear_interpolation_5djk7() {
16354 let one_hour: i64 = 3_600 * 1_000_000_000;
16355 let vals = vec![
16356 Scalar::Timedelta64(one_hour),
16357 Scalar::Timedelta64(3 * one_hour),
16358 ];
16359 assert_eq!(
16361 super::nanquantile(&vals, 0.5),
16362 Scalar::Timedelta64(2 * one_hour)
16363 );
16364 }
16365
16366 #[test]
16367 fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
16368 fn next(seed: &mut u64) -> u64 {
16371 *seed = seed
16372 .wrapping_mul(3202034522624059733)
16373 .wrapping_add(4354685564936845319);
16374 *seed
16375 }
16376
16377 fn interpolated(sorted: &[f64], q: f64) -> f64 {
16378 if sorted.len() == 1 {
16379 return sorted[0];
16380 }
16381 let pos = q * (sorted.len() - 1) as f64;
16382 let lo = pos.floor() as usize;
16383 let hi = pos.ceil() as usize;
16384 if lo == hi {
16385 sorted[lo]
16386 } else {
16387 let weight = pos - lo as f64;
16388 sorted[lo] + (sorted[hi] - sorted[lo]) * weight
16389 }
16390 }
16391
16392 fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
16393 if !(0.0..=1.0).contains(&q) {
16394 return Scalar::Null(NullKind::NaN);
16395 }
16396 let mut samples = values
16397 .iter()
16398 .filter(|value| !value.is_missing())
16399 .filter_map(|value| value.to_f64().ok())
16400 .collect::<Vec<_>>();
16401 if samples.is_empty() {
16402 return Scalar::Null(NullKind::NaN);
16403 }
16404 samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16405 Scalar::Float64(interpolated(&samples, q))
16406 }
16407
16408 fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
16409 if !(0.0..=1.0).contains(&q) {
16410 return Scalar::Null(NullKind::NaN);
16411 }
16412 let mut samples = values
16413 .iter()
16414 .filter_map(|value| match value {
16415 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
16416 _ => None,
16417 })
16418 .collect::<Vec<_>>();
16419 if samples.is_empty() {
16420 return Scalar::Timedelta64(Timedelta::NAT);
16423 }
16424 samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16425 Scalar::Timedelta64(interpolated(&samples, q) as i64)
16426 }
16427
16428 fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
16429 let actual = super::nanquantile(values, q);
16430 assert!(
16431 actual.semantic_eq(&expected),
16432 "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
16433 );
16434 }
16435
16436 let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16437 assert_quantile(
16438 usize::MAX,
16439 "numeric_all_missing",
16440 &numeric_all_missing,
16441 0.5,
16442 expected_numeric(&numeric_all_missing, 0.5),
16443 );
16444 assert_quantile(
16445 usize::MAX - 1,
16446 "numeric_out_of_range",
16447 &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
16448 1.25,
16449 Scalar::Null(NullKind::NaN),
16450 );
16451
16452 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16453 assert_quantile(
16454 usize::MAX - 2,
16455 "timedelta_all_missing",
16456 &td_all_missing,
16457 0.5,
16458 expected_timedelta(&td_all_missing, 0.5),
16459 );
16460 assert_quantile(
16461 usize::MAX - 3,
16462 "timedelta_out_of_range",
16463 &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
16464 -0.25,
16465 Scalar::Null(NullKind::NaN),
16466 );
16467
16468 let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
16469 for case in 0..260 {
16470 let len = (next(&mut seed) % 83 + 1) as usize;
16471 let q = match next(&mut seed) % 8 {
16472 0 => 0.0,
16473 1 => 0.25,
16474 2 => 0.5,
16475 3 => 0.75,
16476 4 => 1.0,
16477 _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
16478 };
16479
16480 let mut numeric = Vec::with_capacity(len);
16481 numeric.push(Scalar::Int64(case as i64 - 130));
16482 for _ in 1..len {
16483 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16484 numeric.push(match next(&mut seed) % 8 {
16485 0 => Scalar::Null(NullKind::Null),
16486 1 => Scalar::Null(NullKind::NaN),
16487 2 => Scalar::Float64(f64::NAN),
16488 3 => Scalar::Bool(raw & 1 == 0),
16489 4 => Scalar::Int64(raw % 251),
16490 5 => Scalar::Float64(raw as f64 / 67.0),
16491 6 => Scalar::Float64(0.0),
16492 _ => Scalar::Float64(-0.0),
16493 });
16494 }
16495 assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
16496
16497 let mut timedeltas = Vec::with_capacity(len);
16498 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16499 for _ in 1..len {
16500 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16501 timedeltas.push(match next(&mut seed) % 7 {
16502 0 => Scalar::Null(NullKind::Null),
16503 1 => Scalar::Timedelta64(i64::MIN),
16504 _ => Scalar::Timedelta64(raw),
16505 });
16506 }
16507 assert_quantile(
16508 case,
16509 "timedelta",
16510 &timedeltas,
16511 q,
16512 expected_timedelta(&timedeltas, q),
16513 );
16514 }
16515 }
16516
16517 #[test]
16518 fn nanargmax_returns_first_position() {
16519 let values = vec![
16520 Scalar::Float64(1.0),
16521 Scalar::Null(NullKind::NaN),
16522 Scalar::Float64(4.0),
16523 Scalar::Float64(4.0),
16524 Scalar::Float64(2.0),
16525 ];
16526 assert_eq!(super::nanargmax(&values), Some(2));
16527 }
16528
16529 #[test]
16530 fn nanargmin_returns_first_position() {
16531 let values = vec![
16532 Scalar::Float64(3.0),
16533 Scalar::Null(NullKind::NaN),
16534 Scalar::Float64(1.0),
16535 Scalar::Float64(1.0),
16536 ];
16537 assert_eq!(super::nanargmin(&values), Some(2));
16538 }
16539
16540 #[test]
16541 fn nanargmax_all_missing_returns_none() {
16542 let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
16543 assert_eq!(super::nanargmax(&values), None);
16544 assert_eq!(super::nanargmin(&values), None);
16545 }
16546
16547 #[test]
16548 fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
16549 fn next(seed: &mut u64) -> u64 {
16552 *seed = seed
16553 .wrapping_mul(2862933555777941757)
16554 .wrapping_add(3037000493);
16555 *seed
16556 }
16557
16558 fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
16559 let mut best: Option<(usize, f64)> = None;
16560 for (idx, value) in values.iter().enumerate() {
16561 if value.is_missing() {
16562 continue;
16563 }
16564 let Ok(value) = value.to_f64() else {
16565 continue;
16566 };
16567 if value.is_nan() {
16568 continue;
16569 }
16570 match best {
16571 None => best = Some((idx, value)),
16572 Some((_, current))
16573 if (find_max && value > current) || (!find_max && value < current) =>
16574 {
16575 best = Some((idx, value));
16576 }
16577 _ => {}
16578 }
16579 }
16580 best.map(|(idx, _)| idx)
16581 }
16582
16583 fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
16584 let mut best: Option<(usize, i64)> = None;
16585 for (idx, value) in values.iter().enumerate() {
16586 if value.is_missing() {
16587 continue;
16588 }
16589 let Scalar::Timedelta64(ns) = value else {
16590 continue;
16591 };
16592 match best {
16593 None => best = Some((idx, *ns)),
16594 Some((_, current))
16595 if (find_max && *ns > current) || (!find_max && *ns < current) =>
16596 {
16597 best = Some((idx, *ns));
16598 }
16599 _ => {}
16600 }
16601 }
16602 best.map(|(idx, _)| idx)
16603 }
16604
16605 fn assert_args(
16606 case: usize,
16607 family: &str,
16608 values: &[Scalar],
16609 expected_min: Option<usize>,
16610 expected_max: Option<usize>,
16611 ) {
16612 assert_eq!(
16613 super::nanargmin(values),
16614 expected_min,
16615 "case={case} family={family}: nanargmin mismatch for {values:?}"
16616 );
16617 assert_eq!(
16618 super::nanargmax(values),
16619 expected_max,
16620 "case={case} family={family}: nanargmax mismatch for {values:?}"
16621 );
16622 }
16623
16624 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16625 assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
16626 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16627 assert_args(
16628 usize::MAX - 1,
16629 "timedelta_all_missing",
16630 &td_all_missing,
16631 None,
16632 None,
16633 );
16634 let positive_int64_endpoint = [
16635 Scalar::Int64(i64::MAX - 1),
16636 Scalar::Null(NullKind::Null),
16637 Scalar::Int64(i64::MAX),
16638 ];
16639 assert_args(
16640 usize::MAX - 2,
16641 "int64_positive_endpoint_exact_order",
16642 &positive_int64_endpoint,
16643 Some(0),
16644 Some(2),
16645 );
16646 let negative_int64_endpoint = [
16647 Scalar::Int64(i64::MIN + 2),
16648 Scalar::Null(NullKind::NaN),
16649 Scalar::Int64(i64::MIN + 1),
16650 ];
16651 assert_args(
16652 usize::MAX - 3,
16653 "int64_negative_endpoint_exact_order",
16654 &negative_int64_endpoint,
16655 Some(2),
16656 Some(0),
16657 );
16658
16659 let mut seed = 0xa126_5eed_ed9e_u64;
16660 for case in 0..260 {
16661 let len = (next(&mut seed) % 83 + 1) as usize;
16662
16663 let mut numeric = Vec::with_capacity(len);
16664 numeric.push(Scalar::Int64(case as i64 - 130));
16665 if len > 1 {
16666 numeric.push(Scalar::Int64(case as i64 - 130));
16667 }
16668 for _ in numeric.len()..len {
16669 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16670 numeric.push(match next(&mut seed) % 9 {
16671 0 => Scalar::Null(NullKind::Null),
16672 1 => Scalar::Null(NullKind::NaN),
16673 2 => Scalar::Float64(f64::NAN),
16674 3 => Scalar::Bool(raw & 1 == 0),
16675 4 => Scalar::Int64(raw % 211),
16676 5 => Scalar::Float64(raw as f64 / 47.0),
16677 6 => Scalar::Float64(0.0),
16678 7 => Scalar::Float64(-0.0),
16679 _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
16680 });
16681 }
16682 assert_args(
16683 case,
16684 "numeric",
16685 &numeric,
16686 expected_numeric(&numeric, false),
16687 expected_numeric(&numeric, true),
16688 );
16689
16690 let mut timedeltas = Vec::with_capacity(len);
16691 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16692 if len > 1 {
16693 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16694 }
16695 for _ in timedeltas.len()..len {
16696 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16697 timedeltas.push(match next(&mut seed) % 7 {
16698 0 => Scalar::Null(NullKind::Null),
16699 1 => Scalar::Timedelta64(i64::MIN),
16700 _ => Scalar::Timedelta64(raw),
16701 });
16702 }
16703 assert_args(
16704 case,
16705 "timedelta",
16706 &timedeltas,
16707 expected_timedelta(&timedeltas, false),
16708 expected_timedelta(&timedeltas, true),
16709 );
16710 }
16711 }
16712
16713 #[test]
16714 fn nansem_matches_std_over_sqrt_n() {
16715 let values = vec![
16716 Scalar::Float64(2.0),
16717 Scalar::Float64(4.0),
16718 Scalar::Float64(4.0),
16719 Scalar::Float64(4.0),
16720 Scalar::Float64(5.0),
16721 Scalar::Float64(5.0),
16722 Scalar::Float64(7.0),
16723 Scalar::Float64(9.0),
16724 ];
16725 let sem = super::nansem(&values, 1);
16727 assert!(matches!(sem, Scalar::Float64(_)));
16728 let Scalar::Float64(v) = sem else {
16729 return;
16730 };
16731 assert!((v - 0.7559289460184544).abs() < 1e-9);
16732 }
16733
16734 #[test]
16735 fn nansem_grouped_is_sqrt_var_over_n_7hxqv() {
16736 let values = [
16739 Scalar::Float64(1.0),
16740 Scalar::Null(NullKind::NaN),
16741 Scalar::Float64(4.0),
16742 ];
16743 assert_eq!(super::nansem_grouped(&values, 1), Scalar::Float64(1.5));
16744 assert_eq!(
16746 super::nansem(&values, 1),
16747 Scalar::Float64(1.499_999_999_999_999_8)
16748 );
16749 assert!(super::nansem_grouped(&values[..1], 1).is_missing());
16750 }
16751
16752 #[test]
16753 fn grouped_reducers_add_as_pandas_group_kernels_xhogl() {
16754 let tenths: Vec<Scalar> = (0..10).map(|_| Scalar::Float64(0.1)).collect();
16758 assert_eq!(super::nansum_grouped(&tenths), Scalar::Float64(1.0));
16759 assert_eq!(super::nanmean_grouped(&tenths), Scalar::Float64(0.1));
16760 assert_eq!(super::nanvar_grouped(&tenths, 1), Scalar::Float64(0.0));
16761 assert_eq!(super::nanstd_grouped(&tenths, 1), Scalar::Float64(0.0));
16762 assert_eq!(
16764 super::nansum(&tenths),
16765 Scalar::Float64(0.999_999_999_999_999_9)
16766 );
16767 let mut sum = super::KahanSum::default();
16769 for value in [1.0, f64::INFINITY, 2.0] {
16770 sum.add(value);
16771 }
16772 assert_eq!(sum.sum(), f64::INFINITY);
16773 let gapped = [
16775 Scalar::Float64(1.0),
16776 Scalar::Null(NullKind::NaN),
16777 Scalar::Float64(4.0),
16778 ];
16779 assert_eq!(super::nanmean_grouped(&gapped), Scalar::Float64(2.5));
16780 assert_eq!(super::nanvar_grouped(&gapped, 1), Scalar::Float64(4.5));
16781 assert!(super::nanvar_grouped(&gapped[..1], 1).is_missing());
16782 let spans = [Scalar::Timedelta64(1), Scalar::Timedelta64(2)];
16784 assert_eq!(super::nansum_grouped(&spans), super::nansum(&spans));
16785 }
16786
16787 #[test]
16788 fn grouped_skew_is_pandas_online_group_skew_vjfq9() {
16789 let group = [
16792 Scalar::Float64(1.0),
16793 Scalar::Null(NullKind::NaN),
16794 Scalar::Float64(4.0),
16795 Scalar::Float64(8.0),
16796 ];
16797 assert_eq!(
16798 super::nanskew_grouped(&group),
16799 Scalar::Float64(0.423_273_160_268_006_15)
16800 );
16801 let long: Vec<Scalar> = (0..2922_i32)
16804 .map(|i| Scalar::Float64(f64::from((i * 7919) % 1000) / 7.0))
16805 .collect();
16806 let glibc_pow = Scalar::Float64(-0.002_284_383_734_800_801_4);
16807 if cfg!(all(target_os = "linux", target_env = "gnu")) {
16813 assert_eq!(super::nanskew_grouped(&long), glibc_pow);
16814 } else {
16815 let sqrt = Scalar::Float64(-0.002_284_383_734_800_802);
16816 assert!([glibc_pow, sqrt].contains(&super::nanskew_grouped(&long)));
16817 }
16818 let constant = [7.0; 3].map(Scalar::Float64);
16821 assert_eq!(super::nanskew_grouped(&constant), Scalar::Float64(0.0));
16822 assert!(super::nanskew_grouped(&group[..2]).is_missing());
16823 let with_inf = [1.0, f64::INFINITY, 2.0, 5.0].map(Scalar::Float64);
16824 assert!(super::nanskew_grouped(&with_inf).is_missing());
16825 }
16826
16827 #[test]
16828 fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
16829 fn former(values: &[Scalar], ddof: usize) -> Scalar {
16830 let nums = super::collect_finite(values);
16831 if nums.len() <= ddof {
16832 return Scalar::Null(NullKind::NaN);
16833 }
16834 match super::nanstd(values, ddof) {
16835 Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
16836 other => other,
16837 }
16838 }
16839
16840 fn assert_same_bits(values: &[Scalar], ddof: usize) {
16841 let expected = former(values, ddof);
16842 let actual = super::nansem(values, ddof);
16843 match (&expected, &actual) {
16844 (Scalar::Float64(expected), Scalar::Float64(actual)) => {
16845 assert_eq!(
16846 actual.to_bits(),
16847 expected.to_bits(),
16848 "values={values:?} ddof={ddof}"
16849 );
16850 }
16851 _ => assert!(
16852 actual.semantic_eq(&expected),
16853 "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
16854 ),
16855 }
16856 }
16857
16858 let mut generated = Vec::with_capacity(4_096);
16859 for idx in 0..4_096_i64 {
16860 generated.push(match idx % 257 {
16861 0 => Scalar::Null(NullKind::NaN),
16862 1 => Scalar::Float64(-0.0),
16863 2 => Scalar::Float64(0.0),
16864 _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
16865 _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
16866 });
16867 }
16868
16869 let cases = [
16870 Vec::new(),
16871 vec![Scalar::Int64(1)],
16872 vec![
16873 Scalar::Null(NullKind::Null),
16874 Scalar::Float64(f64::NAN),
16875 Scalar::Int64(i64::MIN),
16876 Scalar::Int64(i64::MAX),
16877 Scalar::Float64(-0.0),
16878 Scalar::Float64(0.0),
16879 ],
16880 generated,
16881 ];
16882 for values in &cases {
16883 for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
16884 assert_same_bits(values, ddof);
16885 }
16886 }
16887 }
16888
16889 #[test]
16890 #[ignore = "foreground release A/B harness"]
16891 fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
16892 const ROWS: usize = 262_144;
16893 const BATCH: usize = 8;
16894 const BLOCKS: usize = 9;
16895 const PRECONDITION_CALLS: usize = 2;
16896
16897 fn former(values: &[Scalar], ddof: usize) -> Scalar {
16898 let nums = super::collect_finite(values);
16899 if nums.len() <= ddof {
16900 return Scalar::Null(NullKind::NaN);
16901 }
16902 match super::nanstd(values, ddof) {
16903 Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
16904 other => other,
16905 }
16906 }
16907
16908 fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
16909 let values = std::hint::black_box(values);
16910 if candidate {
16911 super::nansem(values, 1)
16912 } else {
16913 former(values, 1)
16914 }
16915 }
16916
16917 fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
16918 for _ in 0..PRECONDITION_CALLS {
16919 std::hint::black_box(evaluate(values, candidate));
16920 }
16921 let started = std::time::Instant::now();
16922 for _ in 0..BATCH {
16923 std::hint::black_box(evaluate(values, candidate));
16924 }
16925 started.elapsed().as_nanos()
16926 }
16927
16928 fn median(mut samples: Vec<u128>) -> u128 {
16929 samples.sort_unstable();
16930 samples[samples.len() / 2]
16931 }
16932
16933 fn spread(a: u128, b: u128) -> f64 {
16934 a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
16935 }
16936
16937 let values = (0..ROWS)
16938 .map(|idx| {
16939 if idx % 257 == 0 {
16940 Scalar::Null(NullKind::NaN)
16941 } else {
16942 Scalar::Int64((idx % 8_191) as i64 - 4_095)
16943 }
16944 })
16945 .collect::<Vec<_>>();
16946
16947 let expected_bits = match former(&values, 1) {
16948 Scalar::Float64(value) => Some(value.to_bits()),
16949 _ => None,
16950 };
16951 let actual_bits = match super::nansem(&values, 1) {
16952 Scalar::Float64(value) => Some(value.to_bits()),
16953 _ => None,
16954 };
16955 assert!(
16956 expected_bits.is_some(),
16957 "numeric nansem must return Float64"
16958 );
16959 assert_eq!(actual_bits, expected_bits, "A/B output bits");
16960
16961 std::hint::black_box(evaluate(&values, false));
16962 std::hint::black_box(evaluate(&values, true));
16963
16964 let body_started = std::time::Instant::now();
16965 let mut former_a = Vec::with_capacity(BLOCKS);
16966 let mut former_b = Vec::with_capacity(BLOCKS);
16967 let mut candidate_a = Vec::with_capacity(BLOCKS);
16968 let mut candidate_b = Vec::with_capacity(BLOCKS);
16969 for block in 0..BLOCKS {
16970 let order = if block % 2 == 0 {
16971 [(false, 0), (true, 0), (true, 1), (false, 1)]
16972 } else {
16973 [(true, 1), (false, 1), (false, 0), (true, 0)]
16974 };
16975 for (candidate, duplicate) in order {
16976 let elapsed = elapsed_ns(&values, candidate);
16977 match (candidate, duplicate) {
16978 (false, 0) => former_a.push(elapsed),
16979 (false, _) => former_b.push(elapsed),
16980 (true, 0) => candidate_a.push(elapsed),
16981 (true, _) => candidate_b.push(elapsed),
16982 }
16983 }
16984 }
16985
16986 let former_a = median(former_a) / BATCH as u128;
16987 let former_b = median(former_b) / BATCH as u128;
16988 let candidate_a = median(candidate_a) / BATCH as u128;
16989 let candidate_b = median(candidate_b) / BATCH as u128;
16990 let former_mean = (former_a + former_b) as f64 / 2.0;
16991 let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
16992 println!(
16993 "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}",
16994 spread(former_a, former_b),
16995 spread(candidate_a, candidate_b),
16996 former_mean / candidate_mean,
16997 body_started.elapsed().as_secs_f64()
16998 );
16999 }
17000
17001 #[test]
17002 fn nansem_empty_returns_null() {
17003 assert!(super::nansem(&[], 1).is_missing());
17004 assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
17005 }
17006
17007 #[test]
17008 fn nanptp_returns_max_minus_min() {
17009 let values = vec![
17010 Scalar::Float64(3.0),
17011 Scalar::Null(NullKind::NaN),
17012 Scalar::Float64(7.0),
17013 Scalar::Float64(1.0),
17014 ];
17015 assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
17016 }
17017
17018 #[test]
17019 fn nanptp_empty_returns_null() {
17020 assert!(super::nanptp(&[]).is_missing());
17021 assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
17022 }
17023
17024 #[test]
17025 fn nanptp_timedelta64_preserves_dtype_u2g0r() {
17026 let one_hour: i64 = 3_600 * 1_000_000_000;
17028 let values = vec![
17029 Scalar::Timedelta64(one_hour),
17030 Scalar::Timedelta64(5 * one_hour),
17031 Scalar::Timedelta64(2 * one_hour),
17032 ];
17033 assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
17034 }
17035
17036 #[test]
17037 fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
17038 fn next(seed: &mut u64) -> u64 {
17041 *seed = seed
17042 .wrapping_mul(3202034522624059733)
17043 .wrapping_add(4354685564936845319);
17044 *seed
17045 }
17046
17047 fn expected_numeric(values: &[Scalar]) -> Scalar {
17048 let mut lo = f64::INFINITY;
17049 let mut hi = f64::NEG_INFINITY;
17050 let mut seen = false;
17051 for value in values {
17052 if value.is_missing() {
17053 continue;
17054 }
17055 if let Ok(value) = value.to_f64() {
17056 seen = true;
17057 lo = lo.min(value);
17058 hi = hi.max(value);
17059 }
17060 }
17061 if seen {
17062 Scalar::Float64(hi - lo)
17063 } else {
17064 Scalar::Null(NullKind::NaN)
17065 }
17066 }
17067
17068 fn expected_timedelta(values: &[Scalar]) -> Scalar {
17069 let mut lo = i64::MAX;
17070 let mut hi = i64::MIN;
17071 let mut seen = false;
17072 for value in values {
17073 if let Scalar::Timedelta64(ns) = value
17074 && !value.is_missing()
17075 {
17076 seen = true;
17077 lo = lo.min(*ns);
17078 hi = hi.max(*ns);
17079 }
17080 }
17081 if seen {
17082 Scalar::Timedelta64(hi - lo)
17083 } else {
17084 Scalar::Null(NullKind::NaN)
17085 }
17086 }
17087
17088 fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
17089 let actual = super::nanptp(values);
17090 assert!(
17091 actual.semantic_eq(&expected),
17092 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
17093 );
17094 }
17095
17096 assert_ptp(
17097 usize::MAX,
17098 "numeric_all_missing",
17099 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17100 Scalar::Null(NullKind::NaN),
17101 );
17102 assert_ptp(
17103 usize::MAX - 1,
17104 "timedelta_all_missing",
17105 &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
17106 Scalar::Null(NullKind::NaN),
17107 );
17108 let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
17109 assert_ptp(
17110 usize::MAX - 2,
17111 "timedelta_one_ns_range_beyond_f64_exactness",
17112 &[
17113 Scalar::Timedelta64(beyond_f64_exact_ns),
17114 Scalar::Timedelta64(beyond_f64_exact_ns - 1),
17115 Scalar::Timedelta64(Timedelta::NAT),
17116 ],
17117 Scalar::Timedelta64(1),
17118 );
17119
17120 let mut seed = 0xa22f_17ed_57a7_15e5_u64;
17121 for case in 0..260 {
17122 let len = (next(&mut seed) % 83 + 1) as usize;
17123
17124 let mut numeric = Vec::with_capacity(len);
17125 numeric.push(Scalar::Int64(case as i64 - 130));
17126 for _ in 1..len {
17127 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17128 numeric.push(match next(&mut seed) % 9 {
17129 0 => Scalar::Null(NullKind::Null),
17130 1 => Scalar::Null(NullKind::NaN),
17131 2 => Scalar::Float64(f64::NAN),
17132 3 => Scalar::Bool(raw & 1 == 0),
17133 4 => Scalar::Int64(raw),
17134 5 => Scalar::Float64(raw as f64 / 53.0),
17135 6 => Scalar::Float64(0.0),
17136 7 => Scalar::Float64(-0.0),
17137 _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
17138 });
17139 }
17140 assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
17141
17142 let mut timedeltas = Vec::with_capacity(len);
17143 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17144 for _ in 1..len {
17145 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17146 timedeltas.push(match next(&mut seed) % 7 {
17147 0 => Scalar::Null(NullKind::Null),
17148 1 => Scalar::Timedelta64(i64::MIN),
17149 _ => Scalar::Timedelta64(raw),
17150 });
17151 }
17152 assert_ptp(
17153 case,
17154 "timedelta",
17155 &timedeltas,
17156 expected_timedelta(&timedeltas),
17157 );
17158 }
17159 }
17160
17161 #[test]
17162 fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
17163 let one_hour: i64 = 3_600 * 1_000_000_000;
17166 let values = vec![
17167 Scalar::Timedelta64(2 * one_hour),
17168 Scalar::Timedelta64(5 * one_hour),
17169 Scalar::Timedelta64(one_hour),
17170 Scalar::Timedelta64(3 * one_hour),
17171 ];
17172 assert_eq!(super::nanargmax(&values), Some(1));
17173 assert_eq!(super::nanargmin(&values), Some(2));
17174 }
17175
17176 #[test]
17177 fn nanprod_timedelta64_returns_null_szq6a() {
17178 let one_hour: i64 = 3_600 * 1_000_000_000;
17182 let values = vec![
17183 Scalar::Timedelta64(2 * one_hour),
17184 Scalar::Timedelta64(3 * one_hour),
17185 ];
17186 assert!(super::nanprod(&values).is_missing());
17187 }
17188
17189 #[test]
17190 fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
17191 fn next(seed: &mut u64) -> u64 {
17194 *seed = seed
17195 .wrapping_mul(6364136223846793005)
17196 .wrapping_add(1442695040888963407);
17197 *seed
17198 }
17199
17200 fn expected_numeric(values: &[Scalar]) -> Scalar {
17201 let mut product = 1.0_f64;
17202 for value in values {
17203 if value.is_missing() {
17204 continue;
17205 }
17206 if let Ok(value) = value.to_f64() {
17207 product *= value;
17208 }
17209 }
17210 Scalar::Float64(product)
17211 }
17212
17213 fn expected_timedelta(values: &[Scalar]) -> Scalar {
17214 if values
17215 .iter()
17216 .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
17217 {
17218 Scalar::Null(NullKind::NaN)
17219 } else {
17220 Scalar::Float64(1.0)
17221 }
17222 }
17223
17224 fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
17225 let actual = super::nanprod(values);
17226 assert!(
17227 actual.semantic_eq(&expected),
17228 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
17229 );
17230 }
17231
17232 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17233 assert_prod(
17234 usize::MAX,
17235 "numeric_all_missing",
17236 &all_missing,
17237 Scalar::Float64(1.0),
17238 );
17239
17240 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17241 assert_prod(
17242 usize::MAX - 1,
17243 "timedelta_all_missing",
17244 &td_all_missing,
17245 expected_timedelta(&td_all_missing),
17246 );
17247
17248 let mut seed = 0x6e0d_9938_a11c_0de5_u64;
17249 for case in 0..280 {
17250 let len = (next(&mut seed) % 89 + 1) as usize;
17251
17252 let mut numeric = Vec::with_capacity(len);
17253 numeric.push(Scalar::Int64((case % 17) as i64 - 8));
17254 for _ in 1..len {
17255 let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
17256 numeric.push(match next(&mut seed) % 9 {
17257 0 => Scalar::Null(NullKind::Null),
17258 1 => Scalar::Null(NullKind::NaN),
17259 2 => Scalar::Float64(f64::NAN),
17260 3 => Scalar::Bool(raw & 1 == 0),
17261 4 => Scalar::Int64(raw % 19),
17262 5 => Scalar::Float64(raw as f64 / 97.0),
17263 6 => Scalar::Float64(0.0),
17264 7 => Scalar::Float64(-0.0),
17265 _ => Scalar::Float64(1.0),
17266 });
17267 }
17268 assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
17269
17270 let mut timedeltas = Vec::with_capacity(len);
17271 timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
17272 for _ in 1..len {
17273 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17274 timedeltas.push(match next(&mut seed) % 7 {
17275 0 => Scalar::Null(NullKind::Null),
17276 1 => Scalar::Timedelta64(i64::MIN),
17277 _ => Scalar::Timedelta64(raw),
17278 });
17279 }
17280 assert_prod(
17281 case,
17282 "timedelta",
17283 &timedeltas,
17284 expected_timedelta(&timedeltas),
17285 );
17286 }
17287 }
17288
17289 #[test]
17290 fn nanskew_symmetric_distribution_near_zero() {
17291 let values = vec![
17292 Scalar::Float64(1.0),
17293 Scalar::Float64(2.0),
17294 Scalar::Float64(3.0),
17295 Scalar::Float64(4.0),
17296 Scalar::Float64(5.0),
17297 ];
17298 let skew = super::nanskew(&values);
17300 assert!(matches!(skew, Scalar::Float64(_)));
17301 let Scalar::Float64(v) = skew else {
17302 return;
17303 };
17304 assert!(v.abs() < 1e-9);
17305 }
17306
17307 #[test]
17308 fn nanskew_too_few_values_returns_null() {
17309 assert!(super::nanskew(&[]).is_missing());
17310 assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
17311 }
17312
17313 #[test]
17314 fn nankurt_symmetric_uniform_distribution() {
17315 let values = vec![
17316 Scalar::Float64(1.0),
17317 Scalar::Float64(2.0),
17318 Scalar::Float64(3.0),
17319 Scalar::Float64(4.0),
17320 Scalar::Float64(5.0),
17321 ];
17322 let kurt = super::nankurt(&values);
17324 assert!(matches!(kurt, Scalar::Float64(_)));
17325 let Scalar::Float64(v) = kurt else {
17326 return;
17327 };
17328 assert!((v + 1.2).abs() < 1e-9);
17329 }
17330
17331 #[test]
17332 fn nankurt_too_few_values_returns_null() {
17333 let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
17334 assert!(super::nankurt(&vals).is_missing());
17335 }
17336
17337 #[test]
17338 fn nanskew_constant_series_returns_zero() {
17339 let values = vec![
17340 Scalar::Float64(5.0),
17341 Scalar::Float64(5.0),
17342 Scalar::Float64(5.0),
17343 ];
17344 assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
17345 assert_eq!(
17346 super::nankurt(&[
17347 Scalar::Float64(5.0),
17348 Scalar::Float64(5.0),
17349 Scalar::Float64(5.0),
17350 Scalar::Float64(5.0),
17351 ]),
17352 Scalar::Float64(0.0)
17353 );
17354 }
17355
17356 #[test]
17357 fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
17358 fn next(seed: &mut u64) -> u64 {
17361 *seed = seed
17362 .wrapping_mul(2862933555777941757)
17363 .wrapping_add(3037000493);
17364 *seed
17365 }
17366
17367 fn samples(values: &[Scalar]) -> Vec<f64> {
17368 values
17369 .iter()
17370 .filter(|value| !value.is_missing())
17371 .filter_map(|value| value.to_f64().ok())
17372 .collect()
17373 }
17374
17375 fn expected_skew(values: &[Scalar]) -> Scalar {
17376 let samples = samples(values);
17377 let n = samples.len() as f64;
17378 if n < 3.0 {
17379 return Scalar::Null(NullKind::NaN);
17380 }
17381 let mean = samples.iter().sum::<f64>() / n;
17382 let m2 = samples
17383 .iter()
17384 .map(|value| (value - mean).powi(2))
17385 .sum::<f64>();
17386 let m3 = samples
17387 .iter()
17388 .map(|value| (value - mean).powi(3))
17389 .sum::<f64>();
17390 let s2 = m2 / (n - 1.0);
17391 if s2 == 0.0 {
17392 return Scalar::Float64(0.0);
17393 }
17394 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
17395 }
17396
17397 fn expected_kurt(values: &[Scalar]) -> Scalar {
17398 let samples = samples(values);
17399 let n = samples.len() as f64;
17400 if n < 4.0 {
17401 return Scalar::Null(NullKind::NaN);
17402 }
17403 let mean = samples.iter().sum::<f64>() / n;
17404 let m2 = samples
17405 .iter()
17406 .map(|value| (value - mean).powi(2))
17407 .sum::<f64>();
17408 let m4 = samples
17409 .iter()
17410 .map(|value| (value - mean).powi(4))
17411 .sum::<f64>();
17412 let s2 = m2 / (n - 1.0);
17413 if s2 == 0.0 {
17414 return Scalar::Float64(0.0);
17415 }
17416 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
17417 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
17418 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
17419 }
17420
17421 fn assert_moments(case: usize, values: &[Scalar]) {
17422 let expected_skew = expected_skew(values);
17423 let expected_kurt = expected_kurt(values);
17424 let actual_skew = super::nanskew(values);
17425 let actual_kurt = super::nankurt(values);
17426 assert!(
17427 actual_skew.semantic_eq(&expected_skew),
17428 "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
17429 );
17430 assert!(
17431 actual_kurt.semantic_eq(&expected_kurt),
17432 "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
17433 );
17434 }
17435
17436 assert_moments(
17437 usize::MAX,
17438 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17439 );
17440 assert_moments(
17441 usize::MAX - 1,
17442 &[
17443 Scalar::Float64(7.0),
17444 Scalar::Float64(7.0),
17445 Scalar::Float64(7.0),
17446 Scalar::Float64(7.0),
17447 ],
17448 );
17449
17450 let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
17451 for case in 0..260 {
17452 let len = (next(&mut seed) % 89 + 1) as usize;
17453 let mut values = Vec::with_capacity(len);
17454 if case % 11 == 0 {
17455 values.extend((0..len).map(|_| Scalar::Float64(3.0)));
17456 } else {
17457 values.push(Scalar::Float64(case as f64 / 19.0));
17458 for _ in 1..len {
17459 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17460 values.push(match next(&mut seed) % 8 {
17461 0 => Scalar::Null(NullKind::Null),
17462 1 => Scalar::Null(NullKind::NaN),
17463 2 => Scalar::Float64(f64::NAN),
17464 3 => Scalar::Bool(raw & 1 == 0),
17465 4 => Scalar::Int64(raw % 251),
17466 5 => Scalar::Float64(raw as f64 / 83.0),
17467 6 => Scalar::Float64(0.0),
17468 _ => Scalar::Float64(-0.0),
17469 });
17470 }
17471 }
17472 assert_moments(case, &values);
17473 }
17474 }
17475
17476 #[test]
17479 fn interval_default_closed_is_right() {
17480 assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
17481 }
17482
17483 #[test]
17484 fn interval_left_and_right_closed_helpers() {
17485 assert!(IntervalClosed::Left.left_closed());
17486 assert!(!IntervalClosed::Left.right_closed());
17487 assert!(!IntervalClosed::Right.left_closed());
17488 assert!(IntervalClosed::Right.right_closed());
17489 assert!(IntervalClosed::Both.left_closed());
17490 assert!(IntervalClosed::Both.right_closed());
17491 assert!(!IntervalClosed::Neither.left_closed());
17492 assert!(!IntervalClosed::Neither.right_closed());
17493 }
17494
17495 #[test]
17496 fn interval_display_matches_pandas_notation() {
17497 assert_eq!(
17498 Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
17499 "(0.0, 5.0]"
17500 );
17501 assert_eq!(
17502 Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
17503 "[0.0, 5.0)"
17504 );
17505 assert_eq!(
17506 Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
17507 "[0.0, 5.0]"
17508 );
17509 assert_eq!(
17510 Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
17511 "(0.0, 5.0)"
17512 );
17513 assert_eq!(
17514 Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
17515 "(2.5, 3.5]"
17516 );
17517 assert_eq!(
17518 Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
17519 "(-1.0, 0.0]"
17520 );
17521 assert_eq!(
17522 Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
17523 "(1e+20, 2e+20]"
17524 );
17525 }
17526
17527 #[test]
17528 fn interval_length_and_mid() {
17529 let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
17530 assert_eq!(i.length(), 8.0);
17531 assert_eq!(i.mid(), 6.0);
17532 }
17533
17534 #[test]
17535 fn interval_contains_matches_closed_policy() {
17536 let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
17537 assert!(!right.contains(0.0));
17538 assert!(right.contains(2.5));
17539 assert!(right.contains(5.0));
17540
17541 let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
17542 assert!(left.contains(0.0));
17543 assert!(left.contains(2.5));
17544 assert!(!left.contains(5.0));
17545
17546 let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
17547 assert!(both.contains(0.0));
17548 assert!(both.contains(5.0));
17549
17550 let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
17551 assert!(!neither.contains(0.0));
17552 assert!(!neither.contains(5.0));
17553 assert!(neither.contains(2.5));
17554 }
17555
17556 #[test]
17557 fn interval_contains_nan_returns_false() {
17558 let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
17559 assert!(!i.contains(f64::NAN));
17560 }
17561
17562 #[test]
17563 fn interval_is_empty_matches_pandas() {
17564 assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
17566 assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
17567 assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
17568 assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
17570 assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
17572 }
17573
17574 #[test]
17575 fn interval_overlaps_disjoint_returns_false() {
17576 let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
17577 let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
17578 assert!(!a.overlaps(&b));
17579 assert!(!b.overlaps(&a));
17580 }
17581
17582 #[test]
17583 fn interval_overlaps_nested_returns_true() {
17584 let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
17585 let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
17586 assert!(outer.overlaps(&inner));
17587 assert!(inner.overlaps(&outer));
17588 }
17589
17590 #[test]
17591 fn interval_overlaps_touching_respects_closed_policy() {
17592 let right_right = (
17594 Interval::new(0.0, 1.0, IntervalClosed::Right),
17595 Interval::new(1.0, 2.0, IntervalClosed::Right),
17596 );
17597 assert!(!right_right.0.overlaps(&right_right.1));
17599
17600 let both_both = (
17602 Interval::new(0.0, 1.0, IntervalClosed::Both),
17603 Interval::new(1.0, 2.0, IntervalClosed::Both),
17604 );
17605 assert!(both_both.0.overlaps(&both_both.1));
17606 }
17607
17608 #[test]
17609 fn interval_roundtrips_through_serde_json() {
17610 let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
17611 let json = serde_json::to_string(&i).expect("serialize");
17612 let back: Interval = serde_json::from_str(&json).expect("deserialize");
17613 assert_eq!(i, back);
17614 }
17615
17616 #[test]
17617 fn interval_serde_default_closed_is_right_when_missing() {
17618 let back: Interval =
17620 serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
17621 assert_eq!(back.closed, IntervalClosed::Right);
17622 }
17623
17624 #[test]
17627 fn period_freq_parses_canonical_aliases() {
17628 assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
17629 assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
17630 assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
17631 assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
17632 assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
17633 assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
17634 assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
17635 assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
17636 assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
17637 assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
17638 assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
17639 }
17640
17641 #[test]
17642 fn period_freq_parse_is_case_insensitive() {
17643 assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::QUARTERLY));
17644 assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
17645 }
17646
17647 #[test]
17648 fn period_freq_rejects_unknown_aliases() {
17649 assert_eq!(PeriodFreq::parse("nanosec"), None);
17650 assert_eq!(PeriodFreq::parse(""), None);
17651 assert_eq!(PeriodFreq::parse("xyz"), None);
17652 }
17653
17654 #[test]
17655 fn period_freq_alias_roundtrip() {
17656 for freq in [
17657 PeriodFreq::ANNUAL,
17658 PeriodFreq::QUARTERLY,
17659 PeriodFreq::Monthly,
17660 PeriodFreq::WEEKLY,
17661 PeriodFreq::Daily,
17662 PeriodFreq::Business,
17663 PeriodFreq::Hourly,
17664 PeriodFreq::Minutely,
17665 PeriodFreq::Secondly,
17666 PeriodFreq::Milliseconds,
17667 PeriodFreq::Microseconds,
17668 PeriodFreq::Nanoseconds,
17669 ] {
17670 assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
17671 }
17672 }
17673
17674 #[test]
17679 fn anchored_period_freqs_parse_print_and_shift_39h5n() {
17680 for month in 1..=12_u8 {
17681 for freq in [PeriodFreq::Annual(month), PeriodFreq::Quarterly(month)] {
17682 assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
17683 }
17684 }
17685 for day in 0..7_u8 {
17686 assert_eq!(
17687 PeriodFreq::parse(PeriodFreq::Weekly(day).alias()),
17688 Some(PeriodFreq::Weekly(day))
17689 );
17690 }
17691 assert_eq!(PeriodFreq::parse("Y-JUN"), Some(PeriodFreq::Annual(6)));
17692 assert_eq!(PeriodFreq::parse("A-JUN"), Some(PeriodFreq::Annual(6)));
17693 assert_eq!(PeriodFreq::parse("q-jan"), Some(PeriodFreq::Quarterly(1)));
17694 assert_eq!(PeriodFreq::parse("W-MON"), Some(PeriodFreq::Weekly(0)));
17695 assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
17696 assert_eq!(PeriodFreq::parse("Q-XYZ"), None);
17698 assert_eq!(PeriodFreq::parse("M-JAN"), None);
17699 assert_eq!(PeriodFreq::parse("W-JAN"), None);
17700 assert_eq!(PeriodFreq::Annual(6).fiscal_month_shift(), 6);
17701 assert_eq!(PeriodFreq::Quarterly(1).fiscal_month_shift(), 11);
17702 assert_eq!(PeriodFreq::QUARTERLY.fiscal_month_shift(), 0);
17703 assert_eq!(PeriodFreq::Weekly(0).week_start_shift(), 1);
17704 assert_eq!(PeriodFreq::WEEKLY.week_start_shift(), 0);
17705 assert_eq!(
17706 Period::new(2827, PeriodFreq::Weekly(0)).to_string(),
17707 "2024-02-27/2024-03-04"
17708 );
17709 assert_eq!(
17710 Period::new(2826, PeriodFreq::Weekly(5)).to_string(),
17711 "2024-02-25/2024-03-02"
17712 );
17713 assert_eq!(
17714 Period::new(220, PeriodFreq::Quarterly(1)).to_string(),
17715 "2025Q1"
17716 );
17717 }
17718
17719 #[test]
17723 fn period_freq_subsecond_units_match_pandas() {
17724 assert_eq!(PeriodFreq::Milliseconds.alias(), "ms");
17726 assert_eq!(PeriodFreq::Microseconds.alias(), "us");
17727 assert_eq!(PeriodFreq::Nanoseconds.alias(), "ns");
17728 assert_eq!(PeriodFreq::Milliseconds.resolution(), Some("millisecond"));
17729 assert_eq!(PeriodFreq::Microseconds.resolution(), Some("microsecond"));
17730 assert_eq!(PeriodFreq::Nanoseconds.resolution(), Some("nanosecond"));
17731
17732 assert_eq!(PeriodFreq::parse("ms"), Some(PeriodFreq::Milliseconds));
17735 assert_eq!(PeriodFreq::parse("Ms"), Some(PeriodFreq::Milliseconds));
17736 assert_eq!(PeriodFreq::parse("mS"), Some(PeriodFreq::Milliseconds));
17737 assert_eq!(PeriodFreq::parse("MS"), None);
17738 assert_eq!(PeriodFreq::parse("us"), Some(PeriodFreq::Microseconds));
17740 assert_eq!(PeriodFreq::parse("US"), Some(PeriodFreq::Microseconds));
17741 assert_eq!(PeriodFreq::parse("ns"), Some(PeriodFreq::Nanoseconds));
17742 assert_eq!(PeriodFreq::parse("NS"), Some(PeriodFreq::Nanoseconds));
17743
17744 assert_eq!(
17747 Period::new(1_710_498_645_123, PeriodFreq::Milliseconds).calendar_string(),
17748 "2024-03-15 10:30:45.123"
17749 );
17750 assert_eq!(
17751 Period::new(1_710_498_645_123_456, PeriodFreq::Microseconds).calendar_string(),
17752 "2024-03-15 10:30:45.123456"
17753 );
17754 assert_eq!(
17755 Period::new(1_710_498_645_123_456_789, PeriodFreq::Nanoseconds).calendar_string(),
17756 "2024-03-15 10:30:45.123456789"
17757 );
17758
17759 assert_eq!(
17763 Period::new(0, PeriodFreq::Milliseconds).calendar_string(),
17764 "1970-01-01 00:00:00.000"
17765 );
17766 assert_eq!(
17767 Period::new(-1, PeriodFreq::Milliseconds).calendar_string(),
17768 "1969-12-31 23:59:59.999"
17769 );
17770 assert_eq!(
17771 Period::new(-1_000, PeriodFreq::Microseconds).calendar_string(),
17772 "1969-12-31 23:59:59.999000"
17773 );
17774 assert_eq!(
17775 Period::new(-999_999, PeriodFreq::Nanoseconds).calendar_string(),
17776 "1969-12-31 23:59:59.999000001"
17777 );
17778 }
17779
17780 #[test]
17781 fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
17782 assert_eq!(PeriodFreq::ANNUAL.alias(), "Y-DEC");
17783 assert_eq!(PeriodFreq::QUARTERLY.alias(), "Q-DEC");
17784 assert_eq!(PeriodFreq::WEEKLY.alias(), "W-SUN");
17785
17786 assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
17787 assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
17788 assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::ANNUAL));
17789 assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
17790 assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
17791 assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
17792 assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::WEEKLY));
17793 }
17794
17795 #[test]
17796 fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
17797 assert_eq!(PeriodFreq::Hourly.alias(), "h");
17798 assert_eq!(PeriodFreq::Minutely.alias(), "min");
17799 assert_eq!(PeriodFreq::Secondly.alias(), "s");
17800
17801 assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
17802 assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
17803 assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
17804 }
17805
17806 #[test]
17810 fn period_freq_resolution_is_the_component_word_not_the_alias() {
17811 assert_eq!(PeriodFreq::ANNUAL.resolution(), Some("year"));
17812 assert_eq!(PeriodFreq::QUARTERLY.resolution(), Some("quarter"));
17813 assert_eq!(PeriodFreq::Monthly.resolution(), Some("month"));
17814 assert_eq!(PeriodFreq::Daily.resolution(), Some("day"));
17815 assert_eq!(PeriodFreq::Hourly.resolution(), Some("hour"));
17816 assert_eq!(PeriodFreq::Minutely.resolution(), Some("minute"));
17817 assert_eq!(PeriodFreq::Secondly.resolution(), Some("second"));
17818
17819 assert_eq!(PeriodFreq::WEEKLY.resolution(), None);
17821 assert_eq!(PeriodFreq::Business.resolution(), None);
17822
17823 for freq in [
17828 PeriodFreq::ANNUAL,
17829 PeriodFreq::QUARTERLY,
17830 PeriodFreq::Monthly,
17831 PeriodFreq::WEEKLY,
17832 PeriodFreq::Daily,
17833 PeriodFreq::Business,
17834 PeriodFreq::Hourly,
17835 PeriodFreq::Minutely,
17836 PeriodFreq::Secondly,
17837 ] {
17838 assert_ne!(
17839 Some(freq.alias()),
17840 freq.resolution(),
17841 "{freq:?} reports its alias as its resolution again"
17842 );
17843 }
17844 }
17845
17846 #[test]
17847 fn period_scalar_accessors_match_pandas_star8() {
17848 let period = Period::new(600, PeriodFreq::Monthly);
17849
17850 assert_eq!(period.ordinal(), 600);
17851 assert_eq!(period.freq(), PeriodFreq::Monthly);
17852 assert_eq!(period.freqstr(), "M");
17853 }
17854
17855 #[test]
17856 fn period_parse_common_pandas_ordinals_avm08() {
17857 assert_eq!(
17858 Period::parse("2024").unwrap(),
17859 Period::new(54, PeriodFreq::ANNUAL)
17860 );
17861 assert_eq!(
17862 Period::parse("2024Q1").unwrap(),
17863 Period::new(216, PeriodFreq::QUARTERLY)
17864 );
17865 assert_eq!(
17866 Period::parse("2024-01").unwrap(),
17867 Period::new(648, PeriodFreq::Monthly)
17868 );
17869 assert_eq!(
17870 Period::parse("2024-01-15").unwrap(),
17871 Period::new(19_737, PeriodFreq::Daily)
17872 );
17873 assert!(Period::parse("216").is_err());
17874 }
17875
17876 #[test]
17877 fn period_shift_advances_ordinal() {
17878 let q1 = Period::new(216, PeriodFreq::QUARTERLY);
17879 let q2 = q1.shift(1);
17880 assert_eq!(q2.ordinal, 217);
17881 assert_eq!(q2.freq, PeriodFreq::QUARTERLY);
17882 let q0 = q1.shift(-1);
17883 assert_eq!(q0.ordinal, 215);
17884 }
17885
17886 #[test]
17887 fn period_shift_saturates_on_overflow() {
17888 let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
17889 assert_eq!(p.shift(100).ordinal, i64::MAX);
17890 let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
17891 assert_eq!(p.shift(-100).ordinal, i64::MIN);
17892 }
17893
17894 #[test]
17895 fn period_diff_returns_period_count() {
17896 let a = Period::new(216, PeriodFreq::QUARTERLY);
17897 let b = Period::new(220, PeriodFreq::QUARTERLY);
17898 assert_eq!(b.diff(&a), Some(4));
17899 assert_eq!(a.diff(&b), Some(-4));
17900 }
17901
17902 #[test]
17903 fn period_diff_rejects_mismatched_freq() {
17904 let monthly = Period::new(100, PeriodFreq::Monthly);
17905 let quarterly = Period::new(100, PeriodFreq::QUARTERLY);
17906 assert_eq!(monthly.diff(&quarterly), None);
17907 assert_eq!(quarterly.diff(&monthly), None);
17908 }
17909
17910 #[test]
17911 fn period_cmp_same_freq_respects_ordinal_order() {
17912 use std::cmp::Ordering;
17913 let a = Period::new(10, PeriodFreq::Monthly);
17914 let b = Period::new(20, PeriodFreq::Monthly);
17915 assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
17916 assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
17917 assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
17918 }
17919
17920 #[test]
17921 fn period_cmp_cross_freq_returns_none() {
17922 let m = Period::new(1, PeriodFreq::Monthly);
17923 let q = Period::new(1, PeriodFreq::QUARTERLY);
17924 assert_eq!(m.cmp_same_freq(&q), None);
17925 }
17926
17927 #[test]
17928 fn period_arithmetic_matches_seeded_oracles_bac28() {
17929 use std::cmp::Ordering;
17930
17931 fn next(seed: &mut u64) -> u64 {
17932 *seed = seed
17933 .wrapping_mul(2862933555777941757)
17934 .wrapping_add(3037000493);
17935 *seed
17936 }
17937
17938 fn freq_for(raw: u64) -> PeriodFreq {
17939 match raw % 12 {
17942 0 => PeriodFreq::ANNUAL,
17943 1 => PeriodFreq::QUARTERLY,
17944 2 => PeriodFreq::Monthly,
17945 3 => PeriodFreq::WEEKLY,
17946 4 => PeriodFreq::Daily,
17947 5 => PeriodFreq::Business,
17948 6 => PeriodFreq::Hourly,
17949 7 => PeriodFreq::Minutely,
17950 8 => PeriodFreq::Secondly,
17951 9 => PeriodFreq::Milliseconds,
17952 10 => PeriodFreq::Microseconds,
17953 _ => PeriodFreq::Nanoseconds,
17954 }
17955 }
17956
17957 fn different_freq(freq: PeriodFreq) -> PeriodFreq {
17958 match freq {
17959 PeriodFreq::Annual(_) => PeriodFreq::QUARTERLY,
17960 PeriodFreq::Quarterly(_) => PeriodFreq::Monthly,
17961 PeriodFreq::Monthly => PeriodFreq::WEEKLY,
17962 PeriodFreq::Weekly(_) => PeriodFreq::Daily,
17963 PeriodFreq::Daily => PeriodFreq::Business,
17964 PeriodFreq::Business => PeriodFreq::Hourly,
17965 PeriodFreq::Hourly => PeriodFreq::Minutely,
17966 PeriodFreq::Minutely => PeriodFreq::Secondly,
17967 PeriodFreq::Secondly => PeriodFreq::Milliseconds,
17971 PeriodFreq::Milliseconds => PeriodFreq::Microseconds,
17972 PeriodFreq::Microseconds => PeriodFreq::Nanoseconds,
17973 PeriodFreq::Nanoseconds => PeriodFreq::ANNUAL,
17974 }
17975 }
17976
17977 fn assert_period_case(
17978 case: usize,
17979 freq: PeriodFreq,
17980 ordinal: i64,
17981 shift_by: i64,
17982 other_ordinal: i64,
17983 ) {
17984 let period = Period::new(ordinal, freq);
17985 let shifted = period.shift(shift_by);
17986 assert_eq!(
17987 shifted.ordinal,
17988 ordinal.saturating_add(shift_by),
17989 "case {case}: shift ordinal"
17990 );
17991 assert_eq!(shifted.freq, freq, "case {case}: shift freq");
17992
17993 let same_freq_other = Period::new(other_ordinal, freq);
17994 assert_eq!(
17995 period.diff(&same_freq_other),
17996 Some(ordinal.saturating_sub(other_ordinal)),
17997 "case {case}: same-freq diff"
17998 );
17999 assert_eq!(
18000 period.cmp_same_freq(&same_freq_other),
18001 Some(ordinal.cmp(&other_ordinal)),
18002 "case {case}: same-freq cmp"
18003 );
18004
18005 let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
18006 assert_eq!(
18007 period.diff(&cross_freq_other),
18008 None,
18009 "case {case}: cross-freq diff"
18010 );
18011 assert_eq!(
18012 period.cmp_same_freq(&cross_freq_other),
18013 None,
18014 "case {case}: cross-freq cmp"
18015 );
18016 }
18017
18018 assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
18019 assert_period_case(
18020 usize::MAX - 1,
18021 PeriodFreq::Daily,
18022 i64::MIN + 2,
18023 -10,
18024 i64::MAX,
18025 );
18026 assert_eq!(
18027 Period::new(10, PeriodFreq::Monthly)
18028 .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
18029 Some(Ordering::Equal)
18030 );
18031
18032 let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
18033 for case in 0..260 {
18034 let freq = freq_for(next(&mut seed));
18035 let ordinal = match case % 53 {
18036 0 => i64::MAX - (next(&mut seed) % 8) as i64,
18037 1 => i64::MIN + (next(&mut seed) % 8) as i64,
18038 _ => (next(&mut seed) % 200_001) as i64 - 100_000,
18039 };
18040 let shift_by = match case % 47 {
18041 0 => 512,
18042 1 => -512,
18043 _ => (next(&mut seed) % 4097) as i64 - 2048,
18044 };
18045 let other_ordinal = match case % 41 {
18046 0 => i64::MAX,
18047 1 => i64::MIN,
18048 _ => (next(&mut seed) % 200_001) as i64 - 100_000,
18049 };
18050 assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
18051 }
18052 }
18053
18054 #[test]
18055 fn period_display_is_pandas_calendar_string() {
18056 assert_eq!(
18058 Period::new(216, PeriodFreq::QUARTERLY).to_string(),
18059 "2024Q1"
18060 );
18061 assert_eq!(Period::new(54, PeriodFreq::ANNUAL).to_string(), "2024");
18063 assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
18065 assert_eq!(
18067 Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
18068 "2024-01-15"
18069 );
18070 assert_eq!(
18071 Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
18072 "NaT"
18073 );
18074 }
18075
18076 #[test]
18084 fn weekly_and_business_periods_do_not_index_days() {
18085 for (ordinal, want) in [
18090 (0_i64, "1969-12-22/1969-12-28"),
18091 (1, "1969-12-29/1970-01-04"),
18092 (2829, "2024-03-11/2024-03-17"),
18093 (1540, "1999-06-28/1999-07-04"),
18094 (15237, "2261-12-30/2262-01-05"),
18095 (-1, "1969-12-15/1969-12-21"),
18097 (-2829, "1915-10-04/1915-10-10"),
18098 ] {
18099 assert_eq!(
18100 Period::new(ordinal, PeriodFreq::WEEKLY).to_string(),
18101 want,
18102 "weekly ordinal {ordinal}"
18103 );
18104 }
18105
18106 for (ordinal, want) in [
18110 (0_i64, "1970-01-01"), (1, "1970-01-02"), (2, "1970-01-05"), (3, "1970-01-06"),
18114 (4, "1970-01-07"),
18115 (5, "1970-01-08"),
18116 (14141, "2024-03-15"),
18117 (76179, "2262-01-01"),
18118 (7697, "1999-07-05"),
18121 (-1, "1969-12-31"),
18122 (-5, "1969-12-25"),
18123 (-6, "1969-12-24"),
18124 ] {
18125 assert_eq!(
18126 Period::new(ordinal, PeriodFreq::Business).to_string(),
18127 want,
18128 "business ordinal {ordinal}"
18129 );
18130 }
18131
18132 for ordinal in -400_i64..400 {
18136 let rendered = Period::new(ordinal, PeriodFreq::Business).to_string();
18137 let later = Period::new(ordinal + 5, PeriodFreq::Business).to_string();
18138 assert_ne!(rendered, later, "business ordinals must not repeat");
18139 }
18140
18141 assert_eq!(Period::new(i64::MIN, PeriodFreq::WEEKLY).to_string(), "NaT");
18142 assert_eq!(
18143 Period::new(i64::MIN, PeriodFreq::Business).to_string(),
18144 "NaT"
18145 );
18146 }
18147
18148 fn period_display_former_profile(period: &Period) -> String {
18149 let calendar = period.calendar_string();
18150 let mut rendered = String::new();
18151 rendered.push_str(&calendar);
18152 rendered
18153 }
18154
18155 fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
18156 use std::{hint::black_box, time::Instant};
18157
18158 let started = Instant::now();
18159 let mut checksum = 0usize;
18160 for period in periods {
18161 let rendered = render(black_box(period));
18162 checksum = checksum.wrapping_add(rendered.len());
18163 drop(black_box(rendered));
18164 }
18165 black_box(checksum);
18166 started.elapsed().as_nanos()
18167 }
18168
18169 #[test]
18170 #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
18171 fn profile_period_display_direct_sink_ab_6pqra() {
18172 const FREQUENCIES: [PeriodFreq; 9] = [
18173 PeriodFreq::ANNUAL,
18174 PeriodFreq::QUARTERLY,
18175 PeriodFreq::Monthly,
18176 PeriodFreq::WEEKLY,
18177 PeriodFreq::Daily,
18178 PeriodFreq::Business,
18179 PeriodFreq::Hourly,
18180 PeriodFreq::Minutely,
18181 PeriodFreq::Secondly,
18182 ];
18183 const SAMPLES: usize = 10;
18184
18185 let periods = (0..65_536)
18186 .map(|index| {
18187 let ordinal = if index % 4093 == 0 {
18188 i64::MIN
18189 } else {
18190 ((index as i64 * 7_919) % 4_000_001) - 2_000_000
18191 };
18192 Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
18193 })
18194 .collect::<Vec<_>>();
18195
18196 for period in &periods {
18197 assert_eq!(period_display_former_profile(period), period.to_string());
18198 }
18199
18200 for _ in 0..2 {
18201 measure_period_renderer(&periods, period_display_former_profile);
18202 measure_period_renderer(&periods, Period::to_string);
18203 }
18204
18205 let mut former_ns = Vec::with_capacity(SAMPLES);
18206 let mut public_ns = Vec::with_capacity(SAMPLES);
18207 for sample in 0..SAMPLES {
18208 if sample % 2 == 0 {
18209 former_ns.push(measure_period_renderer(
18210 &periods,
18211 period_display_former_profile,
18212 ));
18213 public_ns.push(measure_period_renderer(&periods, Period::to_string));
18214 } else {
18215 public_ns.push(measure_period_renderer(&periods, Period::to_string));
18216 former_ns.push(measure_period_renderer(
18217 &periods,
18218 period_display_former_profile,
18219 ));
18220 }
18221 }
18222 former_ns.sort_unstable();
18223 public_ns.sort_unstable();
18224 let former_p50 = former_ns[SAMPLES / 2];
18225 let public_p50 = public_ns[SAMPLES / 2];
18226 let former_p95 = former_ns[SAMPLES - 1];
18227 let public_p95 = public_ns[SAMPLES - 1];
18228 println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
18229 println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
18230 println!(
18231 "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
18232 former_p50 as f64 / public_p50 as f64
18233 );
18234 println!(
18235 "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
18236 former_p95 as f64 / public_p95 as f64
18237 );
18238 }
18239
18240 #[cfg(test)]
18241 fn fp_days(ymd: &str) -> i64 {
18242 Period::parse(ymd).expect("daily period").ordinal
18243 }
18244
18245 #[test]
18246 fn period_roundtrips_through_serde_json() {
18247 let p = Period::new(42, PeriodFreq::WEEKLY);
18248 let json = serde_json::to_string(&p).expect("serialize");
18249 let back: Period = serde_json::from_str(&json).expect("deserialize");
18250 assert_eq!(p, back);
18251 }
18252
18253 use super::period_range;
18256
18257 #[test]
18258 fn period_range_zero_periods_is_empty() {
18259 let start = Period::new(216, PeriodFreq::QUARTERLY);
18260 assert!(period_range(start, 0).is_empty());
18261 }
18262
18263 #[test]
18264 fn period_range_single_period_returns_start_only() {
18265 let start = Period::new(216, PeriodFreq::QUARTERLY);
18266 let r = period_range(start, 1);
18267 assert_eq!(r.len(), 1);
18268 assert_eq!(r[0], start);
18269 }
18270
18271 #[test]
18272 fn period_range_increments_ordinal_by_one_per_step() {
18273 let start = Period::new(216, PeriodFreq::QUARTERLY);
18274 let r = period_range(start, 4);
18275 assert_eq!(r.len(), 4);
18276 assert_eq!(r[0].ordinal, 216);
18277 assert_eq!(r[1].ordinal, 217);
18278 assert_eq!(r[2].ordinal, 218);
18279 assert_eq!(r[3].ordinal, 219);
18280 }
18281
18282 #[test]
18283 fn period_range_preserves_frequency() {
18284 let start = Period::new(0, PeriodFreq::Monthly);
18285 let r = period_range(start, 12);
18286 assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
18287 }
18288
18289 #[test]
18290 fn period_range_negative_starting_ordinal_works() {
18291 let start = Period::new(-3, PeriodFreq::ANNUAL);
18293 let r = period_range(start, 5);
18294 assert_eq!(
18295 r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
18296 vec![-3, -2, -1, 0, 1]
18297 );
18298 }
18299
18300 #[test]
18301 fn period_range_large_n_does_not_panic() {
18302 let start = Period::new(0, PeriodFreq::Monthly);
18304 let r = period_range(start, 1024);
18305 assert_eq!(r.len(), 1024);
18306 assert_eq!(r[1023].ordinal, 1023);
18307 }
18308
18309 #[test]
18310 fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
18311 fn next(seed: &mut u64) -> u64 {
18312 *seed = seed
18313 .wrapping_mul(6364136223846793005)
18314 .wrapping_add(1442695040888963407);
18315 *seed
18316 }
18317
18318 fn freq_for(raw: u64) -> PeriodFreq {
18319 match raw % 12 {
18322 0 => PeriodFreq::ANNUAL,
18323 1 => PeriodFreq::QUARTERLY,
18324 2 => PeriodFreq::Monthly,
18325 3 => PeriodFreq::WEEKLY,
18326 4 => PeriodFreq::Daily,
18327 5 => PeriodFreq::Business,
18328 6 => PeriodFreq::Hourly,
18329 7 => PeriodFreq::Minutely,
18330 8 => PeriodFreq::Secondly,
18331 9 => PeriodFreq::Milliseconds,
18332 10 => PeriodFreq::Microseconds,
18333 _ => PeriodFreq::Nanoseconds,
18334 }
18335 }
18336
18337 fn assert_oracle_case(case: usize, start: Period, periods: usize) {
18338 let got = period_range(start, periods);
18339 assert_eq!(got.len(), periods, "case {case}: length");
18340
18341 for (position, period) in got.iter().enumerate() {
18342 let expected_ordinal = start.ordinal.saturating_add(position as i64);
18343 assert_eq!(
18344 period.ordinal, expected_ordinal,
18345 "case {case}: ordinal at {position}"
18346 );
18347 assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
18348 }
18349 }
18350
18351 assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
18352 assert_oracle_case(
18353 usize::MAX - 1,
18354 Period::new(i64::MAX - 3, PeriodFreq::Daily),
18355 8,
18356 );
18357
18358 let mut seed = 0x9e21_0d1c_5eed_0421_u64;
18359 for case in 0..260 {
18360 let freq = freq_for(next(&mut seed));
18361 let periods = (next(&mut seed) % 80) as usize;
18362 let start_ordinal = if case % 37 == 0 {
18363 i64::MAX - 7
18364 } else {
18365 (next(&mut seed) % 20_001) as i64 - 10_000
18366 };
18367 assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
18368 }
18369 }
18370
18371 use super::{TypeError, interval_range, interval_range_by_periods, interval_range_by_step};
18374
18375 #[test]
18376 fn interval_range_by_periods_matches_pandas_default_case() {
18377 let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
18379 assert_eq!(bins.len(), 5);
18380 for (i, bin) in bins.iter().enumerate() {
18381 assert_eq!(bin.left, (i as f64) * 2.0);
18382 assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
18383 assert_eq!(bin.closed, IntervalClosed::Right);
18384 }
18385 }
18386
18387 #[test]
18388 fn interval_range_by_periods_final_edge_is_exact_end() {
18389 let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
18391 assert_eq!(bins.last().unwrap().right, 1.0);
18392 }
18393
18394 #[test]
18395 fn interval_range_by_periods_zero_periods_is_empty() {
18396 assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
18397 }
18398
18399 #[test]
18400 fn interval_range_by_periods_reversed_range_is_empty() {
18401 assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
18403 }
18404
18405 #[test]
18406 fn interval_range_by_periods_preserves_closed_policy() {
18407 for closed in [
18408 IntervalClosed::Left,
18409 IntervalClosed::Right,
18410 IntervalClosed::Both,
18411 IntervalClosed::Neither,
18412 ] {
18413 let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
18414 assert!(bins.iter().all(|b| b.closed == closed));
18415 }
18416 }
18417
18418 #[test]
18419 fn interval_range_by_step_matches_pandas_default_case() {
18420 let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
18422 assert_eq!(bins.len(), 5);
18423 assert_eq!(bins[0].left, 0.0);
18424 assert_eq!(bins[4].right, 10.0);
18425 }
18426
18427 #[test]
18428 fn interval_range_by_step_rejects_non_positive_step() {
18429 assert!(matches!(
18430 interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
18431 Err(TypeError::InvalidIntervalStep { .. })
18432 ));
18433 assert!(matches!(
18434 interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
18435 Err(TypeError::InvalidIntervalStep { .. })
18436 ));
18437 assert!(matches!(
18438 interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
18439 Err(TypeError::InvalidIntervalStep { .. })
18440 ));
18441 assert!(matches!(
18442 interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
18443 Err(TypeError::InvalidIntervalStep { .. })
18444 ));
18445 }
18446
18447 #[test]
18448 fn interval_range_by_step_rejects_non_dividing_step() {
18449 assert!(matches!(
18452 interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
18453 Err(TypeError::IntervalStepDoesNotDivide { .. })
18454 ));
18455 }
18456
18457 #[test]
18458 fn interval_range_by_step_reversed_range_is_empty() {
18459 let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
18460 assert!(bins.is_empty());
18461 }
18462
18463 #[test]
18464 fn interval_range_by_step_degenerate_zero_span_is_empty() {
18465 let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
18466 assert!(bins.is_empty());
18467 }
18468
18469 #[test]
18470 fn interval_range_by_step_accepts_float_step_within_tolerance() {
18471 let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
18473 assert_eq!(bins.len(), 10);
18474 assert_eq!(bins.last().unwrap().right, 1.0);
18475 }
18476
18477 #[test]
18478 fn interval_range_unified_api_tests() {
18479 let r1 = interval_range(Some(0.0), Some(10.0), Some(5), None, None).expect("ok");
18481 assert_eq!(r1.len(), 5);
18482 assert_eq!(r1[0].left, 0.0);
18483 assert_eq!(r1[0].right, 2.0);
18484 assert_eq!(r1[4].right, 10.0);
18485 assert_eq!(r1[0].closed, IntervalClosed::Right);
18486
18487 let r2 = interval_range(Some(0.0), Some(10.0), None, Some(2.0), None).expect("ok");
18489 assert_eq!(r2.len(), 5);
18490 assert_eq!(r2[0].left, 0.0);
18491 assert_eq!(r2[4].right, 10.0);
18492
18493 let r3 = interval_range(
18495 Some(0.0),
18496 None,
18497 Some(5),
18498 Some(2.0),
18499 Some(IntervalClosed::Both),
18500 )
18501 .expect("ok");
18502 assert_eq!(r3.len(), 5);
18503 assert_eq!(r3[0].left, 0.0);
18504 assert_eq!(r3[4].right, 10.0);
18505 assert_eq!(r3[0].closed, IntervalClosed::Both);
18506
18507 let r4 = interval_range(
18509 None,
18510 Some(10.0),
18511 Some(5),
18512 Some(2.0),
18513 Some(IntervalClosed::Left),
18514 )
18515 .expect("ok");
18516 assert_eq!(r4.len(), 5);
18517 assert_eq!(r4[0].left, 0.0);
18518 assert_eq!(r4[4].right, 10.0);
18519 assert_eq!(r4[0].closed, IntervalClosed::Left);
18520
18521 assert!(matches!(
18523 interval_range(None, None, None, None, None),
18524 Err(TypeError::IntervalRangeParameterCount)
18525 ));
18526 assert!(matches!(
18527 interval_range(Some(0.0), Some(10.0), None, None, None),
18528 Err(TypeError::IntervalRangeParameterCount)
18529 ));
18530 assert!(matches!(
18531 interval_range(Some(0.0), Some(10.0), Some(5), Some(2.0), None),
18532 Err(TypeError::IntervalRangeParameterCount)
18533 ));
18534
18535 assert!(matches!(
18537 interval_range(Some(0.0), None, Some(5), Some(-1.0), None),
18538 Err(TypeError::InvalidIntervalStep { .. })
18539 ));
18540 assert!(matches!(
18541 interval_range(Some(0.0), None, Some(5), Some(0.0), None),
18542 Err(TypeError::InvalidIntervalStep { .. })
18543 ));
18544 }
18545
18546 #[test]
18547 fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
18548 fn next(seed: &mut u64) -> u64 {
18551 *seed = seed
18552 .wrapping_mul(2862933555777941757)
18553 .wrapping_add(3037000493);
18554 *seed
18555 }
18556
18557 fn closed_for(raw: u64) -> IntervalClosed {
18558 match raw % 4 {
18559 0 => IntervalClosed::Left,
18560 1 => IntervalClosed::Right,
18561 2 => IntervalClosed::Both,
18562 _ => IntervalClosed::Neither,
18563 }
18564 }
18565
18566 fn assert_interval(
18567 case: usize,
18568 kind: &str,
18569 pos: usize,
18570 actual: &Interval,
18571 expected: &Interval,
18572 ) {
18573 assert!(
18574 (actual.left - expected.left).abs() < 1e-12,
18575 "case={case} kind={kind} pos={pos}: expected left {}, got {}",
18576 expected.left,
18577 actual.left
18578 );
18579 assert!(
18580 (actual.right - expected.right).abs() < 1e-12,
18581 "case={case} kind={kind} pos={pos}: expected right {}, got {}",
18582 expected.right,
18583 actual.right
18584 );
18585 assert_eq!(
18586 actual.closed, expected.closed,
18587 "case={case} kind={kind} pos={pos}: closed mismatch"
18588 );
18589 }
18590
18591 fn expected_by_periods(
18592 start: f64,
18593 end: f64,
18594 periods: usize,
18595 closed: IntervalClosed,
18596 ) -> Vec<Interval> {
18597 if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
18598 return Vec::new();
18599 }
18600 let step = (end - start) / periods as f64;
18601 (0..periods)
18602 .map(|pos| {
18603 let left = start + step * pos as f64;
18604 let right = if pos + 1 == periods {
18605 end
18606 } else {
18607 start + step * (pos + 1) as f64
18608 };
18609 Interval::new(left, right, closed)
18610 })
18611 .collect()
18612 }
18613
18614 fn expected_by_step(
18615 start: f64,
18616 end: f64,
18617 step: f64,
18618 closed: IntervalClosed,
18619 ) -> Vec<Interval> {
18620 if start >= end {
18621 return Vec::new();
18622 }
18623 let count = ((end - start) / step).round() as usize;
18624 (0..count)
18625 .map(|pos| {
18626 let left = start + step * pos as f64;
18627 let right = if pos + 1 == count {
18628 end
18629 } else {
18630 start + step * (pos + 1) as f64
18631 };
18632 Interval::new(left, right, closed)
18633 })
18634 .collect()
18635 }
18636
18637 assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
18638 assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
18639 assert!(
18640 interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
18641 .expect("zero span")
18642 .is_empty()
18643 );
18644
18645 let mut seed = 0x171e_7a11_c0de_5eed_u64;
18646 for case in 0..220 {
18647 let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
18648 let periods = (next(&mut seed) % 24 + 1) as usize;
18649 let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
18650 let end = start + width;
18651 let closed = closed_for(next(&mut seed));
18652
18653 let actual = interval_range_by_periods(start, end, periods, closed);
18654 let expected = expected_by_periods(start, end, periods, closed);
18655 assert_eq!(
18656 actual.len(),
18657 expected.len(),
18658 "case={case} periods: length mismatch"
18659 );
18660 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18661 assert_interval(case, "periods", pos, actual, expected);
18662 }
18663
18664 let step_count = (next(&mut seed) % 20 + 1) as usize;
18665 let step = (next(&mut seed) % 25 + 1) as f64;
18666 let step_end = start + step * step_count as f64;
18667 let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
18668 let expected = expected_by_step(start, step_end, step, closed);
18669 assert_eq!(
18670 actual.len(),
18671 expected.len(),
18672 "case={case} step: length mismatch"
18673 );
18674 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18675 assert_interval(case, "step", pos, actual, expected);
18676 }
18677 }
18678 }
18679
18680 use super::Timedelta;
18683
18684 #[test]
18685 fn timedelta_add_sums_non_nat() {
18686 let one_hour = Timedelta::NANOS_PER_HOUR;
18687 let one_day = Timedelta::NANOS_PER_DAY;
18688 assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
18689 }
18690
18691 #[test]
18692 fn timedelta_add_propagates_nat() {
18693 assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
18694 assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
18695 assert_eq!(
18696 Timedelta::add(Timedelta::NAT, Timedelta::NAT),
18697 Timedelta::NAT
18698 );
18699 }
18700
18701 #[test]
18702 fn timedelta_add_returns_nat_on_overflow() {
18703 assert_eq!(Timedelta::add(i64::MAX - 10, 100), Timedelta::NAT);
18710 assert_eq!(Timedelta::add(i64::MIN + 10, -100), Timedelta::NAT);
18713 }
18714
18715 #[test]
18716 fn timedelta_sub_subtracts_non_nat() {
18717 let one_hour = Timedelta::NANOS_PER_HOUR;
18718 assert_eq!(
18719 Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
18720 one_hour - Timedelta::NANOS_PER_MIN
18721 );
18722 }
18723
18724 #[test]
18725 fn timedelta_sub_propagates_nat() {
18726 assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
18727 assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
18728 }
18729
18730 #[test]
18731 fn timedelta_neg_flips_sign_non_nat() {
18732 assert_eq!(Timedelta::neg(5), -5);
18733 assert_eq!(Timedelta::neg(-5), 5);
18734 assert_eq!(Timedelta::neg(0), 0);
18735 }
18736
18737 #[test]
18738 fn timedelta_neg_preserves_nat() {
18739 assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
18740 }
18741
18742 #[test]
18743 fn timedelta_abs_returns_magnitude() {
18744 assert_eq!(Timedelta::abs(-5), 5);
18745 assert_eq!(Timedelta::abs(5), 5);
18746 assert_eq!(Timedelta::abs(0), 0);
18747 assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
18748 }
18749
18750 #[test]
18751 fn neg_and_abs_at_the_representable_floor_are_not_overflow_fyr1z() {
18752 const MAX: i64 = i64::MAX;
18770 const MIN_OK: i64 = i64::MIN + 1; assert_eq!(MIN_OK, -MAX);
18775 assert_eq!(Timedelta::NAT, i64::MIN);
18776
18777 assert_eq!(Timedelta::neg(MIN_OK), MAX);
18779 assert_eq!(Timedelta::neg(MAX), MIN_OK);
18780 assert_eq!(Timedelta::abs(MIN_OK), MAX);
18781 assert_eq!(Timedelta::abs(MAX), MAX);
18782
18783 assert_eq!(Timedelta::neg(Timedelta::neg(MIN_OK)), MIN_OK);
18787 assert_ne!(Timedelta::neg(MIN_OK), Timedelta::NAT);
18788 assert_ne!(Timedelta::abs(MIN_OK), Timedelta::NAT);
18789
18790 assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
18793 assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
18794 }
18795
18796 #[test]
18797 fn overflow_divergence_surface_is_only_where_pandas_refuses_fyr1z() {
18798 const MAX: i64 = i64::MAX;
18810 const MIN_OK: i64 = i64::MIN + 1;
18811
18812 assert_eq!(Timedelta::div_scalar(MAX, 0), Timedelta::NAT);
18817 assert_eq!(Timedelta::div_scalar(MIN_OK, 0), Timedelta::NAT);
18818 assert_eq!(Timedelta::div_scalar(0, 0), Timedelta::NAT);
18819
18820 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());
18830 assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(2).is_nat());
18831
18832 assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
18836 assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
18837 assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
18838
18839 assert_eq!(Timedelta::div_scalar(MAX, 1), MAX);
18841 assert_eq!(Timedelta::div_scalar(-100, 3), -34); assert_eq!(Timedelta::div_scalar(100, -3), -34);
18843 assert_eq!(Timedelta::sub(MIN_OK + 2, 1), MIN_OK + 1);
18844 }
18845
18846 #[test]
18847 fn timedelta_mul_scalar_scales() {
18848 let three_hours = Timedelta::NANOS_PER_HOUR * 3;
18849 assert_eq!(
18850 Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
18851 three_hours
18852 );
18853 assert_eq!(Timedelta::mul_scalar(100, 0), 0);
18854 assert_eq!(Timedelta::mul_scalar(100, -2), -200);
18855 }
18856
18857 #[test]
18858 fn timedelta_mul_scalar_returns_nat_on_overflow() {
18859 assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), Timedelta::NAT);
18862 assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), Timedelta::NAT);
18863 }
18864
18865 #[test]
18866 fn from_unit_nan_is_nat_and_overflow_is_err_8v92m() {
18867 use super::TimedeltaError;
18868
18869 assert_eq!(Timedelta::from_unit(f64::NAN, "s"), Ok(Timedelta::NAT));
18887 assert_ne!(Timedelta::from_unit(f64::NAN, "s"), Ok(0));
18888 assert_eq!(Timedelta::from_unit(f64::NAN, "D"), Ok(Timedelta::NAT));
18889
18890 assert_eq!(
18892 Timedelta::from_unit(f64::INFINITY, "s"),
18893 Err(TimedeltaError::Overflow)
18894 );
18895 assert_eq!(
18896 Timedelta::from_unit(f64::NEG_INFINITY, "s"),
18897 Err(TimedeltaError::Overflow)
18898 );
18899 assert_eq!(
18900 Timedelta::from_unit(1e30, "s"),
18901 Err(TimedeltaError::Overflow)
18902 );
18903 assert_eq!(
18904 Timedelta::from_unit(1e30, "D"),
18905 Err(TimedeltaError::Overflow)
18906 );
18907
18908 assert_eq!(Timedelta::from_unit(1.5, "s"), Ok(1_500_000_000));
18911 assert_eq!(Timedelta::from_unit(0.0, "s"), Ok(0));
18912 assert_eq!(Timedelta::from_unit(-2.5, "s"), Ok(-2_500_000_000));
18913 assert_eq!(Timedelta::from_unit(1.0, "D"), Ok(Timedelta::NANOS_PER_DAY));
18914 assert_eq!(
18915 Timedelta::from_unit(3.0, "h"),
18916 Ok(3 * Timedelta::NANOS_PER_HOUR)
18917 );
18918 let big_days = 100_000.0_f64;
18921 let expected = (big_days * Timedelta::NANOS_PER_DAY as f64).round() as i64;
18922 assert_eq!(Timedelta::from_unit(big_days, "D"), Ok(expected));
18923 assert!(expected > 0, "fixture must stay in range to be a control");
18924
18925 assert!(matches!(
18928 Timedelta::from_unit(1.0, "nonsense-unit"),
18929 Err(TimedeltaError::InvalidFormat(_))
18930 ));
18931 assert!(matches!(
18932 Timedelta::from_unit(f64::NAN, "nonsense-unit"),
18933 Err(TimedeltaError::InvalidFormat(_)),
18934 ));
18935
18936 let huge = format!("{} days", "9".repeat(18));
18941 assert!(matches!(
18942 Timedelta::parse(&huge),
18943 Err(TimedeltaError::Overflow)
18944 ));
18945 assert!(matches!(
18946 Timedelta::parse("1e100 days"),
18947 Err(TimedeltaError::InvalidFormat(_))
18948 ));
18949 }
18950
18951 #[test]
18952 fn rounding_and_ms_us_overflow_never_fabricates_a_finite_value_kyd16() {
18953 const MAX: i64 = i64::MAX;
18972 const MIN_OK: i64 = i64::MIN + 1;
18973 const DAY: i64 = Timedelta::NANOS_PER_DAY;
18974
18975 let rounded = Timedelta::round(MAX, "D");
18977 assert_eq!(
18978 rounded,
18979 Timedelta::NAT,
18980 "rounding i64::MAX up to a whole day overflows; the old unchecked \
18981 multiply panicked in debug and wrapped in release"
18982 );
18983 assert!(
18987 rounded == Timedelta::NAT || rounded > 0,
18988 "a positive duration must never round to a negative one"
18989 );
18990 assert_eq!(Timedelta::round(MIN_OK, "D"), Timedelta::NAT);
18991
18992 assert_eq!(Timedelta::ceil(MAX, "D"), Timedelta::NAT);
18994 assert_eq!(Timedelta::floor(MIN_OK, "D"), Timedelta::NAT);
18995 assert!(Timestamp::from_nanos(MAX).ceil_to(DAY).is_nat());
18996 assert!(Timestamp::from_nanos(MAX).round_to(DAY).is_nat());
18997 assert!(Timestamp::from_nanos(MIN_OK).floor_to(DAY).is_nat());
18998 assert!(Timestamp::from_nanos(MIN_OK).round_to(DAY).is_nat());
18999
19000 assert!(Timestamp::from_millis(MAX, None).is_nat());
19002 assert!(Timestamp::from_millis(MIN_OK, None).is_nat());
19003 assert!(Timestamp::from_micros(MAX, None).is_nat());
19004 assert!(Timestamp::from_micros(MIN_OK, Some("US/Eastern")).is_nat());
19005
19006 let max_floor = Timestamp::from_nanos(MAX).floor_to(DAY);
19013 assert!(!max_floor.is_nat(), "Timestamp.max.floor(D) must succeed");
19014 assert_eq!(max_floor.nanos, (MAX / DAY) * DAY);
19015 assert_eq!(Timedelta::floor(MAX, "D"), (MAX / DAY) * DAY);
19016 assert_eq!(
19017 Timedelta::ceil(MIN_OK, "D"),
19018 (MIN_OK.div_euclid(DAY) + 1) * DAY
19019 );
19020
19021 let hour = Timedelta::NANOS_PER_HOUR;
19023 assert_eq!(Timedelta::floor(90 * 60 * 1_000_000_000, "h"), hour);
19024 assert_eq!(Timedelta::ceil(90 * 60 * 1_000_000_000, "h"), 2 * hour);
19025 assert_eq!(Timedelta::round(90 * 60 * 1_000_000_000, "h"), 2 * hour);
19026 assert_eq!(Timedelta::round(-90 * 60 * 1_000_000_000, "h"), -2 * hour);
19027 assert_eq!(Timedelta::round(29 * 60 * 1_000_000_000, "h"), 0);
19028 assert_eq!(Timestamp::from_millis(1_500, None).nanos, 1_500_000_000);
19029 assert_eq!(Timestamp::from_micros(-2_000, None).nanos, -2_000_000);
19030 assert_eq!(
19031 Timestamp::from_nanos(hour + 1).floor_to(hour).nanos,
19032 hour,
19033 "in-range floor unchanged"
19034 );
19035 assert_eq!(
19036 Timestamp::from_nanos(hour + 1).ceil_to(hour).nanos,
19037 2 * hour,
19038 "in-range ceil unchanged"
19039 );
19040
19041 assert_eq!(Timedelta::round(Timedelta::NAT, "D"), Timedelta::NAT);
19043 assert_eq!(Timedelta::floor(Timedelta::NAT, "D"), Timedelta::NAT);
19044 assert_eq!(Timedelta::ceil(1_000, "nonsense-unit"), Timedelta::NAT);
19045 assert!(Timestamp::nat().ceil_to(DAY).is_nat());
19046 assert!(Timestamp::from_nanos(0).round_to(0).is_nat());
19047 assert_eq!(
19049 Timestamp::from_nanos_tz(hour + 1, "US/Eastern")
19050 .ceil_to(hour)
19051 .tz
19052 .as_deref(),
19053 Some("US/Eastern")
19054 );
19055 }
19056
19057 #[test]
19058 fn timedelta_mul_scalar_propagates_nat() {
19059 assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
19060 }
19061
19062 #[test]
19063 fn arithmetic_overflow_never_fabricates_a_finite_value_lgyy8() {
19064 const MAX: i64 = i64::MAX;
19079 const MIN_OK: i64 = i64::MIN + 1; assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
19083 assert_eq!(Timedelta::add(MAX - 10, 100), Timedelta::NAT);
19084 assert_eq!(Timedelta::sub(MAX, -1), Timedelta::NAT);
19085 assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
19086 assert_eq!(Timedelta::mul_scalar(MAX / 2 + 2, 2), Timedelta::NAT);
19087 assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
19088 assert!(Timestamp::from_nanos(MAX).sub_timedelta(-1).is_nat());
19089 assert_eq!(
19093 Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(MIN_OK)),
19094 Timedelta::NAT
19095 );
19096
19097 assert_eq!(Timedelta::add(MIN_OK, -1), Timedelta::NAT);
19099 assert_eq!(Timedelta::add(MIN_OK, -2), Timedelta::NAT);
19100 assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
19101 assert_eq!(Timedelta::mul_scalar(MIN_OK, 2), Timedelta::NAT);
19102 assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
19103 assert!(Timestamp::from_nanos(MIN_OK).add_timedelta(-1).is_nat());
19104 assert_eq!(
19105 Timestamp::from_nanos(MIN_OK).sub_timestamp(&Timestamp::from_nanos(MAX)),
19106 Timedelta::NAT
19107 );
19108
19109 assert_eq!(Timedelta::add(MAX - 1, 1), MAX);
19115 assert_eq!(Timedelta::add(MAX, 0), MAX);
19116 assert_eq!(Timedelta::sub(MAX, 1), MAX - 1);
19117 assert_eq!(Timedelta::add(MIN_OK + 1, -1), MIN_OK);
19118 assert_eq!(Timedelta::mul_scalar(MAX / 2, 2), (MAX / 2) * 2);
19119 assert_eq!(Timedelta::mul_scalar(MIN_OK, 1), MIN_OK);
19120 assert_eq!(Timestamp::from_nanos(MAX - 1).add_timedelta(1).nanos, MAX);
19121 assert_eq!(
19122 Timestamp::from_nanos(MIN_OK + 1).sub_timedelta(1).nanos,
19123 MIN_OK
19124 );
19125 assert_eq!(
19126 Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(0)),
19127 MAX
19128 );
19129 assert_eq!(Timedelta::add(1_000, 2_345), 3_345);
19131 assert_eq!(Timedelta::sub(1_000, 2_345), -1_345);
19132 assert_eq!(Timedelta::mul_scalar(-7, 6), -42);
19133
19134 assert_eq!(MIN_OK - 1, i64::MIN);
19141 assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
19142 assert_eq!(Timedelta::add(MIN_OK, 0), MIN_OK);
19143
19144 assert!(Timestamp::nat().add_timedelta(1).is_nat());
19147 assert!(
19148 Timestamp::from_nanos(0)
19149 .add_timedelta(Timedelta::NAT)
19150 .is_nat()
19151 );
19152 let tzed = Timestamp::from_nanos_tz(MAX, "US/Eastern");
19153 let overflowed = tzed.add_timedelta(1);
19154 assert!(overflowed.is_nat());
19155 assert_eq!(overflowed.tz, None, "an overflow NaT carries no zone");
19156 assert_eq!(
19158 Timestamp::from_nanos_tz(0, "US/Eastern")
19159 .add_timedelta(Timedelta::NANOS_PER_DAY)
19160 .tz
19161 .as_deref(),
19162 Some("US/Eastern")
19163 );
19164 }
19165
19166 #[test]
19167 fn timedelta_div_scalar_floor_divides() {
19168 assert_eq!(Timedelta::div_scalar(100, 3), 33);
19170 assert_eq!(Timedelta::div_scalar(-100, 3), -34);
19171 assert_eq!(Timedelta::div_scalar(100, -3), -34);
19172 assert_eq!(Timedelta::div_scalar(-100, -3), 33);
19173 }
19174
19175 #[test]
19176 fn timedelta_div_scalar_zero_divisor_returns_nat() {
19177 assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
19178 }
19179
19180 #[test]
19181 fn timedelta_div_scalar_min_neg_one_propagates_nat() {
19182 assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
19185 assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
19187 }
19188
19189 #[test]
19190 fn timedelta_div_scalar_propagates_nat() {
19191 assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
19192 }
19193
19194 #[test]
19195 fn timedelta_div_timedelta_returns_float_ratio() {
19196 let two_hours = Timedelta::NANOS_PER_HOUR * 2;
19197 let one_hour = Timedelta::NANOS_PER_HOUR;
19198 assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
19199 assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
19200 }
19201
19202 #[test]
19203 fn timedelta_div_timedelta_nat_returns_nan() {
19204 assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
19205 assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
19206 }
19207
19208 use super::Timestamp;
19211
19212 #[test]
19213 fn timestamp_from_nanos_is_naive_utc() {
19214 let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
19215 assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
19216 assert_eq!(ts.tz, None);
19217 assert!(!ts.is_nat());
19218 }
19219
19220 #[test]
19221 fn timestamp_from_nanos_tz_carries_tz_name() {
19222 let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19223 assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
19224 }
19225
19226 #[test]
19227 fn timestamp_now_returns_current_time() {
19228 let before = std::time::SystemTime::now()
19229 .duration_since(std::time::UNIX_EPOCH)
19230 .unwrap()
19231 .as_nanos() as i64;
19232 let ts = Timestamp::now();
19233 let after = std::time::SystemTime::now()
19234 .duration_since(std::time::UNIX_EPOCH)
19235 .unwrap()
19236 .as_nanos() as i64;
19237 assert!(ts.nanos >= before);
19238 assert!(ts.nanos <= after);
19239 assert!(!ts.is_nat());
19240 }
19241
19242 #[test]
19243 fn timestamp_today_returns_midnight() {
19244 let ts = Timestamp::today();
19245 assert!(!ts.is_nat());
19246 assert_eq!(ts.hour(), Some(0));
19248 assert_eq!(ts.minute(), Some(0));
19249 assert_eq!(ts.second(), Some(0));
19250 }
19251
19252 #[test]
19253 fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
19254 let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
19255 let one_day = Timedelta::NANOS_PER_DAY;
19256 let shifted = ts.add_timedelta(one_day);
19257 assert_eq!(shifted.nanos, one_day);
19258 assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
19259 }
19260
19261 #[test]
19262 fn timestamp_add_timedelta_returns_nat_on_overflow() {
19263 let ts = Timestamp::from_nanos(i64::MAX - 10);
19267 assert!(ts.add_timedelta(100).is_nat());
19268 }
19269
19270 #[test]
19271 fn timestamp_add_timedelta_propagates_nat() {
19272 assert!(Timestamp::nat().add_timedelta(100).is_nat());
19274 assert!(
19276 Timestamp::from_nanos(0)
19277 .add_timedelta(Timedelta::NAT)
19278 .is_nat()
19279 );
19280 }
19281
19282 #[test]
19283 fn timestamp_sub_timedelta_shifts_backward() {
19284 let ts = Timestamp::from_nanos(1_000);
19285 let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
19286 assert_eq!(shifted.nanos, 0);
19287 }
19288
19289 #[test]
19290 fn timestamp_sub_timestamp_returns_timedelta_nanos() {
19291 let t0 = Timestamp::from_nanos(0);
19292 let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
19293 assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
19294 assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
19295 }
19296
19297 #[test]
19298 fn timestamp_sub_timestamp_nat_propagates() {
19299 let ts = Timestamp::from_nanos(1_000);
19300 assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
19301 assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
19302 }
19303
19304 #[test]
19305 fn timestamp_semantic_eq_treats_two_nat_as_equal() {
19306 assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
19307 assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
19308 assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
19309 }
19310
19311 #[test]
19312 fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
19313 use std::cmp::Ordering;
19314 let a = Timestamp::from_nanos(0);
19315 let b = Timestamp::from_nanos(100);
19316 assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
19317 assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
19318 assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
19319 assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
19320 assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
19321 }
19322
19323 #[test]
19324 fn time_zone_offsets_and_wall_clock_conversions_follow_pandas() {
19325 use crate::{
19326 TimeZoneError, tz_abbreviation, tz_canonical_name, tz_offset_seconds,
19327 tz_utc_to_wall_nanos, tz_validate, tz_wall_to_utc_nanos,
19328 };
19329 let hour = 3_600_000_000_000_i64;
19330 let instant = 1_710_081_000_000_000_000_i64;
19333 assert_eq!(tz_offset_seconds("Asia/Tokyo", instant), Ok(9 * 3_600));
19334 assert_eq!(tz_offset_seconds("US/Eastern", instant), Ok(-4 * 3_600));
19335 assert_eq!(
19336 tz_offset_seconds("US/Eastern", instant - 24 * hour),
19337 Ok(-5 * 3_600)
19338 );
19339 assert_eq!(tz_offset_seconds("+05:30", 0), Ok(19_800));
19340 assert_eq!(tz_offset_seconds("UTC+05:30", 0), Ok(19_800));
19341 assert_eq!(tz_offset_seconds("-03:00", 0), Ok(-10_800));
19342 assert_eq!(tz_offset_seconds("UTC", instant), Ok(0));
19343 assert_eq!(
19344 tz_utc_to_wall_nanos("Asia/Tokyo", instant),
19345 Ok(instant + 9 * hour)
19346 );
19347 let wall_noon = 19_723 * 24 * hour + 12 * hour;
19349 assert_eq!(
19350 tz_wall_to_utc_nanos("US/Eastern", wall_noon),
19351 Ok(wall_noon + 5 * hour)
19352 );
19353 assert_eq!(
19354 tz_utc_to_wall_nanos("US/Eastern", wall_noon + 5 * hour),
19355 Ok(wall_noon)
19356 );
19357 assert_eq!(tz_wall_to_utc_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19359 assert_eq!(tz_utc_to_wall_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19360 let skipped = 19_792 * 24 * hour + 2 * hour + 30 * 60_000_000_000;
19364 assert_eq!(
19365 tz_wall_to_utc_nanos("US/Eastern", skipped),
19366 Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19367 );
19368 let repeated = 20_030 * 24 * hour + hour + 30 * 60_000_000_000;
19369 assert_eq!(
19370 tz_wall_to_utc_nanos("US/Eastern", repeated),
19371 Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19372 );
19373 assert_eq!(
19374 tz_offset_seconds("Mars/Olympus", 0),
19375 Err(TimeZoneError::Unknown("Mars/Olympus".to_owned()))
19376 );
19377 assert!(tz_validate("+24:00").is_err());
19378 assert!(tz_validate("+5:30").is_err());
19379 assert!(tz_validate("Europe/Paris").is_ok());
19380 assert_eq!(tz_canonical_name("+05:30").as_deref(), Ok("UTC+05:30"));
19382 assert_eq!(tz_canonical_name("UTC-03:00").as_deref(), Ok("UTC-03:00"));
19383 assert_eq!(tz_canonical_name("+00:00").as_deref(), Ok("UTC"));
19384 assert_eq!(tz_canonical_name("Z").as_deref(), Ok("UTC"));
19385 assert_eq!(tz_canonical_name("US/Eastern").as_deref(), Ok("US/Eastern"));
19386 assert_eq!(tz_abbreviation("US/Eastern", instant).as_deref(), Ok("EDT"));
19388 assert_eq!(
19389 tz_abbreviation("US/Eastern", instant - 24 * hour).as_deref(),
19390 Ok("EST")
19391 );
19392 assert_eq!(tz_abbreviation("+05:30", 0).as_deref(), Ok("UTC+05:30"));
19393 }
19394
19395 #[test]
19402 fn tz_localize_policies_follow_pandas_84w06() {
19403 use super::{
19404 AmbiguousTime as A, NonexistentTime as N, TimeZoneError,
19405 tz_wall_to_utc_nanos_with as at,
19406 };
19407 let hour = 3_600_000_000_000_i64;
19408 let minute = 60_000_000_000_i64;
19409 let skipped = 19_792 * 24 * hour + 2 * hour + 30 * minute;
19410 let transition = 19_792 * 24 * hour + 7 * hour;
19411 let zone = "America/New_York";
19412 assert_eq!(at(zone, skipped, A::Raise, N::ShiftForward), Ok(transition));
19413 assert_eq!(
19414 at(zone, skipped, A::Raise, N::ShiftBackward),
19415 Ok(transition - 1)
19416 );
19417 assert_eq!(at(zone, skipped, A::Raise, N::NaT), Ok(i64::MIN));
19418 assert_eq!(
19419 at(zone, skipped, A::Raise, N::Shift(hour)),
19420 Ok(transition + 30 * minute)
19421 );
19422 let repeated = 20_030 * 24 * hour + hour + 30 * minute;
19423 assert_eq!(
19424 at(zone, repeated, A::Earliest, N::Raise),
19425 Ok(repeated + 4 * hour)
19426 );
19427 assert_eq!(
19428 at(zone, repeated, A::Latest, N::Raise),
19429 Ok(repeated + 5 * hour)
19430 );
19431 assert_eq!(at(zone, repeated, A::NaT, N::Raise), Ok(i64::MIN));
19432 let noon = 19_723 * 24 * hour + 12 * hour;
19435 assert_eq!(at(zone, noon, A::NaT, N::NaT), Ok(noon + 5 * hour));
19436 assert_eq!(
19437 at(zone, skipped, A::NaT, N::Raise),
19438 Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19439 );
19440 assert_eq!(
19441 at(zone, repeated, A::Raise, N::NaT),
19442 Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19443 );
19444 }
19445
19446 #[test]
19447 fn timestamp_display_matches_phase2_debug_format() {
19448 assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
19449 assert_eq!(
19450 Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
19451 "Timestamp[42, US/Eastern]"
19452 );
19453 assert_eq!(Timestamp::nat().to_string(), "NaT");
19454 }
19455
19456 #[test]
19457 fn a_naive_timestamp_cell_casts_to_its_str_srzqw() {
19458 let text = |nanos: i64| cast_scalar(&Scalar::Datetime64(nanos), DType::Utf8);
19462 let midnight = 1_711_929_600_000_000_000;
19463 assert_eq!(
19464 text(midnight),
19465 Ok(Scalar::Utf8("2024-04-01 00:00:00".into()))
19466 );
19467 assert_eq!(
19468 text(midnight + 1_000),
19469 Ok(Scalar::Utf8("2024-04-01 00:00:00.000001".into()))
19470 );
19471 assert_eq!(
19472 text(midnight + 1),
19473 Ok(Scalar::Utf8("2024-04-01 00:00:00.000000001".into()))
19474 );
19475 assert_eq!(
19476 text(-1),
19477 Ok(Scalar::Utf8("1969-12-31 23:59:59.999999999".into()))
19478 );
19479 assert_eq!(text(Timestamp::NAT), Ok(Scalar::Utf8("NaT".into())));
19480 assert_eq!(
19482 crate::timestamp_text_in_zone(midnight, "US/Eastern"),
19483 "2024-03-31 20:00:00-04:00"
19484 );
19485 }
19486
19487 #[test]
19488 fn timestamp_value_and_unit_match_pandas_l0edr() {
19489 let ts = Timestamp::from_nanos(1_000_000_123);
19490 assert_eq!(ts.value(), 1_000_000_123);
19491 assert_eq!(ts.unit(), Some("ns"));
19492
19493 let nat = Timestamp::nat();
19494 assert_eq!(nat.value(), Timestamp::NAT);
19495 assert_eq!(nat.unit(), None);
19496 }
19497
19498 #[test]
19499 fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
19500 let ts = Timestamp::from_nanos(1_000_000_123);
19501 assert_eq!(ts.asm8(), ts.value());
19502 assert_eq!(ts.to_datetime64(), ts.value());
19503 assert_eq!(ts.to_numpy(), ts.value());
19504
19505 let nat = Timestamp::nat();
19506 assert_eq!(nat.asm8(), Timestamp::NAT);
19507 assert_eq!(nat.to_datetime64(), Timestamp::NAT);
19508 assert_eq!(nat.to_numpy(), Timestamp::NAT);
19509 }
19510
19511 #[test]
19512 fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
19513 assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
19514 assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
19515 assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
19516 assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
19517 assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
19518
19519 assert!(matches!(
19520 Timestamp::from_nanos(-500).timestamp(),
19521 Ok(value) if value == -0.0 && value.is_sign_negative()
19522 ));
19523 assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
19524 assert_eq!(
19525 Timestamp::nat().timestamp(),
19526 Err(TypeError::ValueIsMissing {
19527 kind: NullKind::NaT,
19528 })
19529 );
19530 }
19531
19532 #[test]
19533 fn timestamp_roundtrips_through_serde_json() {
19534 let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
19535 let json = serde_json::to_string(&naive).expect("serialize");
19536 let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19537 assert_eq!(naive, back);
19538
19539 let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19540 let json = serde_json::to_string(&tz_aware).expect("serialize");
19541 let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19542 assert_eq!(tz_aware, back);
19543 }
19544
19545 #[test]
19546 fn timestamp_is_send_and_sync() {
19547 fn assert_send_sync<T: Send + Sync>() {}
19548 assert_send_sync::<Timestamp>();
19549 }
19550
19551 #[test]
19554 fn timestamp_pre_epoch_accessors_floor_not_truncate() {
19555 let ts = Timestamp::from_nanos(-1);
19559 assert_eq!(ts.year(), Some(1969));
19560 assert_eq!(ts.month(), Some(12));
19561 assert_eq!(ts.day(), Some(31));
19562 assert_eq!(ts.hour(), Some(23));
19563 assert_eq!(ts.minute(), Some(59));
19564 assert_eq!(ts.second(), Some(59));
19565 assert_eq!(ts.microsecond(), Some(999_999));
19566 assert_eq!(ts.nanosecond(), Some(999));
19567 assert_eq!(ts.dayofweek(), Some(2));
19569
19570 let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
19572 assert_eq!(noon.year(), Some(1969));
19573 assert_eq!(noon.month(), Some(12));
19574 assert_eq!(noon.day(), Some(31));
19575 assert_eq!(noon.hour(), Some(12));
19576
19577 let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
19579 assert_eq!(midnight.year(), Some(1969));
19580 assert_eq!(midnight.day(), Some(31));
19581 assert_eq!(midnight.hour(), Some(0));
19582 }
19583
19584 #[test]
19585 fn timestamp_floor_to_rounds_down() {
19586 let h = Timedelta::NANOS_PER_HOUR;
19588 let twelve_h = h * 12;
19589 let twelve_thirty_four =
19590 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19591 let ts = Timestamp::from_nanos(twelve_thirty_four);
19592 let floored = ts.floor_to(h);
19593 assert_eq!(floored.nanos, twelve_h);
19594 }
19595
19596 #[test]
19597 fn timestamp_floor_to_handles_already_aligned() {
19598 let h = Timedelta::NANOS_PER_HOUR;
19600 let twelve_h = h * 12;
19601 let ts = Timestamp::from_nanos(twelve_h);
19602 assert_eq!(ts.floor_to(h).nanos, twelve_h);
19603 }
19604
19605 #[test]
19606 fn timestamp_floor_to_handles_negative_nanos() {
19607 let ts = Timestamp::from_nanos(-100);
19611 assert_eq!(ts.floor_to(60).nanos, -120);
19612 }
19613
19614 #[test]
19615 fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
19616 let ts = Timestamp::from_nanos(i64::MIN + 1);
19617 assert!(ts.floor_to(10).is_nat());
19618
19619 let safe = Timestamp::from_nanos(i64::MIN + 10);
19620 assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
19621
19622 let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
19623 assert_eq!(tz.nanos, -120);
19624 assert_eq!(tz.tz.as_deref(), Some("UTC"));
19625 }
19626
19627 #[test]
19628 fn timestamp_ceil_to_rounds_up() {
19629 let h = Timedelta::NANOS_PER_HOUR;
19631 let twelve_h = h * 12;
19632 let thirteen_h = h * 13;
19633 let twelve_thirty_four =
19634 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19635 let ts = Timestamp::from_nanos(twelve_thirty_four);
19636 assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
19637 }
19638
19639 #[test]
19640 fn timestamp_ceil_to_no_op_on_aligned() {
19641 let h = Timedelta::NANOS_PER_HOUR;
19642 let twelve_h = h * 12;
19643 let ts = Timestamp::from_nanos(twelve_h);
19644 assert_eq!(ts.ceil_to(h).nanos, twelve_h);
19645 }
19646
19647 #[test]
19648 fn timestamp_round_to_rounds_to_nearest() {
19649 let h = Timedelta::NANOS_PER_HOUR;
19651 let twelve_h = h * 12;
19652 let twelve_thirty_one_sec =
19653 twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
19654 let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
19655 assert_eq!(ts.round_to(h).nanos, h * 13);
19656
19657 let twelve_twenty_nine_sec =
19659 twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
19660 let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
19661 assert_eq!(ts.round_to(h).nanos, twelve_h);
19662 }
19663
19664 #[test]
19665 fn timestamp_round_to_bankers_tie_to_even() {
19666 assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
19672 assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
19673 assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
19674 assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
19675 }
19676
19677 #[test]
19678 fn timestamp_round_to_zero_unit_returns_nat() {
19679 let ts = Timestamp::from_nanos(100);
19680 assert!(ts.round_to(0).is_nat());
19681 assert!(ts.floor_to(0).is_nat());
19682 assert!(ts.ceil_to(0).is_nat());
19683 }
19684
19685 #[test]
19686 fn timestamp_round_to_negative_unit_returns_nat() {
19687 let ts = Timestamp::from_nanos(100);
19688 assert!(ts.round_to(-10).is_nat());
19689 assert!(ts.floor_to(-10).is_nat());
19690 assert!(ts.ceil_to(-10).is_nat());
19691 }
19692
19693 #[test]
19694 fn timestamp_rounding_propagates_nat() {
19695 let nat = Timestamp::nat();
19696 assert!(nat.floor_to(60).is_nat());
19697 assert!(nat.ceil_to(60).is_nat());
19698 assert!(nat.round_to(60).is_nat());
19699 }
19700
19701 #[test]
19702 fn timestamp_rounding_preserves_tz() {
19703 let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
19704 assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
19705 assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
19706 assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
19707 }
19708
19709 #[test]
19712 fn timestamp_floor_to_unit_h_rounds_to_hour() {
19713 let h = Timedelta::NANOS_PER_HOUR;
19714 let twelve_h = h * 12;
19715 let twelve_thirty_four =
19716 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19717 let ts = Timestamp::from_nanos(twelve_thirty_four);
19718 assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
19719 assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
19720 assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
19721 assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
19722 assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
19723 }
19724
19725 #[test]
19726 fn timestamp_ceil_to_unit_d_rounds_to_day() {
19727 let h = Timedelta::NANOS_PER_HOUR;
19729 let d = Timedelta::NANOS_PER_DAY;
19730 let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
19731 let ts = Timestamp::from_nanos(twelve_thirty_four);
19732 assert_eq!(ts.ceil_to_unit("D").nanos, d);
19733 assert_eq!(ts.ceil_to_unit("day").nanos, d);
19734 assert_eq!(ts.ceil_to_unit("days").nanos, d);
19735 }
19736
19737 #[test]
19738 fn timestamp_round_to_unit_min_rounds_to_minute() {
19739 let m = Timedelta::NANOS_PER_MIN;
19741 let twelve_thirty_four_thirty_one =
19742 Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
19743 let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
19744 let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
19745 assert_eq!(ts.round_to_unit("min").nanos, expected);
19746 assert_eq!(ts.round_to_unit("T").nanos, expected); assert_eq!(ts.round_to_unit("minute").nanos, expected);
19748 }
19749
19750 #[test]
19751 fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
19752 let ts = Timestamp::from_nanos(
19753 Timedelta::NANOS_PER_HOUR * 12
19754 + Timedelta::NANOS_PER_MIN * 34
19755 + Timedelta::NANOS_PER_SEC * 31,
19756 );
19757
19758 assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
19759 assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
19760 assert_eq!(ts.round("min"), ts.round_to_unit("min"));
19761 }
19762
19763 #[test]
19764 fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
19765 let ts = Timestamp::from_nanos_tz(
19766 Timedelta::NANOS_PER_DAY * 3
19767 + Timedelta::NANOS_PER_HOUR * 12
19768 + Timedelta::NANOS_PER_MIN * 34,
19769 "US/Eastern",
19770 );
19771 let normalized = ts.normalize();
19772
19773 assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
19774 assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
19775 assert!(Timestamp::nat().normalize().is_nat());
19776 for nanos in [
19777 i64::MIN + 1,
19778 -Timedelta::NANOS_PER_DAY - 1,
19779 -Timedelta::NANOS_PER_DAY,
19780 -1,
19781 0,
19782 Timedelta::NANOS_PER_DAY - 1,
19783 Timedelta::NANOS_PER_DAY,
19784 i64::MAX,
19785 ] {
19786 let timestamp = Timestamp::from_nanos(nanos);
19787 assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
19788 }
19789 }
19790
19791 #[test]
19792 #[ignore = "foreground profile-first A/B"]
19793 fn timestamp_normalize_direct_day_profile_dk721() {
19794 use std::{hint::black_box, time::Instant};
19795
19796 fn former(timestamp: &Timestamp) -> Timestamp {
19797 timestamp.floor_to_unit("D")
19798 }
19799
19800 fn candidate(timestamp: &Timestamp) -> Timestamp {
19801 timestamp.normalize()
19802 }
19803
19804 fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
19805 let started = Instant::now();
19806 let mut checksum = 0_u64;
19807 for timestamp in input {
19808 let normalized = normalize(black_box(timestamp));
19809 checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
19810 }
19811 black_box(checksum);
19812 started.elapsed().as_nanos()
19813 }
19814
19815 fn percentile(samples: &mut [u128], percent: usize) -> u128 {
19816 samples.sort_unstable();
19817 let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
19818 samples[rank]
19819 }
19820
19821 let parity_cases = [
19822 Timestamp::nat(),
19823 Timestamp::from_nanos(i64::MIN + 1),
19824 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
19825 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
19826 Timestamp::from_nanos(-1),
19827 Timestamp::from_nanos(0),
19828 Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
19829 Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
19830 Timestamp::from_nanos(i64::MAX),
19831 Timestamp::from_nanos_tz(-1, "US/Eastern"),
19832 Timestamp::from_nanos_tz(
19833 Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
19834 "Asia/Tokyo",
19835 ),
19836 ];
19837 for timestamp in &parity_cases {
19838 assert_eq!(former(timestamp), candidate(timestamp));
19839 assert_eq!(timestamp.normalize(), former(timestamp));
19840 }
19841
19842 const ROWS: usize = 16_384;
19843 const SAMPLES: usize = 20;
19844 let input = (0..ROWS)
19845 .map(|index| {
19846 let day = index as i64 % 4_096 - 2_048;
19847 let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
19848 % Timedelta::NANOS_PER_DAY as u64) as i64;
19849 Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
19850 })
19851 .collect::<Vec<_>>();
19852 for timestamp in &input {
19853 assert_eq!(former(timestamp), candidate(timestamp));
19854 }
19855
19856 for _ in 0..3 {
19857 black_box(elapsed(&input, former));
19858 black_box(elapsed(&input, candidate));
19859 }
19860
19861 let mut former_ns = Vec::with_capacity(SAMPLES);
19862 let mut candidate_ns = Vec::with_capacity(SAMPLES);
19863 for sample in 0..SAMPLES {
19864 if sample % 2 == 0 {
19865 former_ns.push(elapsed(&input, former));
19866 candidate_ns.push(elapsed(&input, candidate));
19867 } else {
19868 candidate_ns.push(elapsed(&input, candidate));
19869 former_ns.push(elapsed(&input, former));
19870 }
19871 }
19872
19873 let mut former_sorted = former_ns.clone();
19874 let mut candidate_sorted = candidate_ns.clone();
19875 let former_p50 = percentile(&mut former_sorted, 50);
19876 let former_p95 = percentile(&mut former_sorted, 95);
19877 let former_p99 = percentile(&mut former_sorted, 99);
19878 let candidate_p50 = percentile(&mut candidate_sorted, 50);
19879 let candidate_p95 = percentile(&mut candidate_sorted, 95);
19880 let candidate_p99 = percentile(&mut candidate_sorted, 99);
19881 println!(
19882 "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:?}",
19883 former_p50 as f64 / candidate_p50 as f64,
19884 former_p95 as f64 / candidate_p95 as f64,
19885 former_p99 as f64 / candidate_p99 as f64,
19886 );
19887 }
19888
19889 #[test]
19890 fn timestamp_unit_rounding_unknown_unit_returns_nat() {
19891 let ts = Timestamp::from_nanos(100);
19892 assert!(ts.floor_to_unit("fortnight").is_nat());
19893 assert!(ts.ceil_to_unit("century").is_nat());
19894 assert!(ts.round_to_unit("xyz").is_nat());
19895 }
19896
19897 #[test]
19900 fn timestamp_rounding_reads_a_multiple_of_a_unit_3agof() {
19901 let (min, sec) = (Timedelta::NANOS_PER_MIN, Timedelta::NANOS_PER_SEC);
19902 let base = 1_710_460_800 * sec; let ts = Timestamp::from_nanos(base + 13 * Timedelta::NANOS_PER_HOUR + 47 * min + 21 * sec);
19904 let at = |minutes: i64, seconds: i64| base + minutes * min + seconds * sec;
19905 assert_eq!(ts.round("15min").nanos, at(13 * 60 + 45, 0));
19906 assert_eq!(ts.floor("15min").nanos, at(13 * 60 + 45, 0));
19907 assert_eq!(ts.ceil("15min").nanos, at(14 * 60, 0));
19908 assert_eq!(ts.round("30s").nanos, at(13 * 60 + 47, 30));
19909 assert_eq!(ts.ceil("1D").nanos, base + Timedelta::NANOS_PER_DAY);
19910 assert_eq!(ts.floor("7D").nanos, 19_796 * Timedelta::NANOS_PER_DAY);
19913 assert!(ts.round("ME").is_nat());
19915 }
19916
19917 #[test]
19918 fn timestamp_unit_rounding_propagates_nat() {
19919 let nat = Timestamp::nat();
19920 assert!(nat.floor_to_unit("H").is_nat());
19921 assert!(nat.ceil_to_unit("H").is_nat());
19922 assert!(nat.round_to_unit("H").is_nat());
19923 }
19924
19925 #[test]
19926 fn timestamp_unit_rounding_preserves_tz() {
19927 let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
19928 assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19929 assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19930 assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19931 }
19932
19933 #[test]
19934 fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
19935 assert_eq!(
19937 Timedelta::unit_to_nanos("W"),
19938 Some(Timedelta::NANOS_PER_WEEK)
19939 );
19940 assert_eq!(
19941 Timedelta::unit_to_nanos("D"),
19942 Some(Timedelta::NANOS_PER_DAY)
19943 );
19944 assert_eq!(
19945 Timedelta::unit_to_nanos("H"),
19946 Some(Timedelta::NANOS_PER_HOUR)
19947 );
19948 assert_eq!(
19949 Timedelta::unit_to_nanos("min"),
19950 Some(Timedelta::NANOS_PER_MIN)
19951 );
19952 assert_eq!(
19953 Timedelta::unit_to_nanos("s"),
19954 Some(Timedelta::NANOS_PER_SEC)
19955 );
19956 assert_eq!(
19957 Timedelta::unit_to_nanos("ms"),
19958 Some(Timedelta::NANOS_PER_MILLI)
19959 );
19960 assert_eq!(
19961 Timedelta::unit_to_nanos("us"),
19962 Some(Timedelta::NANOS_PER_MICRO)
19963 );
19964 assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
19965 assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
19967 assert_eq!(Timedelta::unit_to_nanos("century"), None);
19969 }
19970
19971 #[test]
19972 fn timestamp_isoformat_basic() {
19973 let ts = Timestamp::from_nanos(0);
19974 assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
19975
19976 let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
19977 assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
19978
19979 let ts_fixed_offset = Timestamp::from_nanos_tz(0, "UTC+05:30");
19980 assert_eq!(
19981 ts_fixed_offset.isoformat(),
19982 "1970-01-01T05:30:00+05:30",
19983 "a fixed-offset timestamp must render local wall time rather than a UTC instant with an annotation"
19984 );
19985
19986 let ts_tz = Timestamp::from_nanos_tz(
19987 Timedelta::NANOS_PER_DAY
19988 + Timedelta::NANOS_PER_HOUR * 14
19989 + Timedelta::NANOS_PER_MIN * 30,
19990 "America/New_York",
19991 );
19992 assert!(ts_tz.isoformat().contains("1970-01-02T14:30:00"));
19993 assert!(ts_tz.isoformat().contains("[America/New_York]"));
19994
19995 assert_eq!(Timestamp::nat().isoformat(), "NaT");
19996 }
19997
19998 #[test]
19999 fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
20000 assert_eq!(
20001 Timestamp::from_nanos(-1).isoformat(),
20002 "1969-12-31T23:59:59.999999999"
20003 );
20004 assert_eq!(
20005 Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
20006 "1969-12-31T23:59:59"
20007 );
20008 assert_eq!(
20009 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
20010 "1969-12-31T00:00:00"
20011 );
20012 assert_eq!(
20013 Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
20014 "1969-12-31T23:59:59.999999999+00:00"
20015 );
20016 }
20017
20018 #[test]
20019 fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
20020 assert_eq!(
20021 Timestamp::from_nanos(123_456_789).isoformat(),
20022 "1970-01-01T00:00:00.123456789"
20023 );
20024 assert_eq!(
20025 Timestamp::from_nanos(123_456_000).isoformat(),
20026 "1970-01-01T00:00:00.123456"
20027 );
20028 assert_eq!(
20029 Timestamp::from_nanos(123_000_000).isoformat(),
20030 "1970-01-01T00:00:00.123000"
20031 );
20032 assert_eq!(
20033 Timestamp::from_nanos_tz(1, "UTC").isoformat(),
20034 "1970-01-01T00:00:00.000000001+00:00"
20035 );
20036 }
20037
20038 fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
20039 if timestamp.is_nat() {
20040 return "NaT".to_owned();
20041 }
20042 let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
20043 match ×tamp.tz {
20044 Some(tz) if tz == "UTC" => format!("{base}+00:00"),
20045 Some(tz) => format!("{base}[{tz}]"),
20046 None => base,
20047 }
20048 }
20049
20050 #[test]
20051 fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
20052 let nanos = [
20053 Timestamp::NAT,
20054 -Timedelta::NANOS_PER_DAY - 1,
20055 -Timedelta::NANOS_PER_SEC,
20056 -1,
20057 0,
20058 1,
20059 123_456_000,
20060 123_456_789,
20061 i64::MAX,
20062 ];
20063 let timezones = [
20064 None,
20065 Some("UTC"),
20066 Some("America/New_York"),
20067 Some(""),
20068 Some("Etc/Γ"),
20069 ];
20070 for value in nanos {
20071 for timezone in timezones {
20072 let timestamp = Timestamp {
20073 nanos: value,
20074 tz: timezone.map(str::to_owned),
20075 };
20076 assert_eq!(
20077 timestamp.isoformat(),
20078 timestamp_isoformat_former_q8g50(×tamp),
20079 "nanos={value} timezone={timezone:?}"
20080 );
20081 }
20082 }
20083 }
20084
20085 #[test]
20086 #[ignore = "foreground release A/B only"]
20087 fn timestamp_isoformat_one_buffer_ab_q8g50() {
20088 use std::{hint::black_box, time::Instant};
20089
20090 const ITEMS: usize = 8_192;
20091 const SAMPLES: usize = 10;
20092
20093 fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
20094 let started = Instant::now();
20095 let mut checksum = 0usize;
20096 for timestamp in black_box(values) {
20097 checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
20098 }
20099 black_box(checksum);
20100 started.elapsed().as_nanos()
20101 }
20102
20103 let values = (0..ITEMS)
20104 .map(|idx| {
20105 let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
20106 let timezone = if idx.is_multiple_of(2) {
20107 "UTC"
20108 } else {
20109 "America/New_York"
20110 };
20111 Timestamp::from_nanos_tz(nanos, timezone)
20112 })
20113 .collect::<Vec<_>>();
20114 for timestamp in &values {
20115 assert_eq!(
20116 timestamp.isoformat(),
20117 timestamp_isoformat_former_q8g50(timestamp)
20118 );
20119 }
20120
20121 black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
20122 black_box(elapsed(&values, Timestamp::isoformat));
20123
20124 let mut former_ns = Vec::with_capacity(SAMPLES);
20125 let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
20126 for sample in 0..SAMPLES {
20127 if sample.is_multiple_of(2) {
20128 former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
20129 one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
20130 } else {
20131 one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
20132 former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
20133 }
20134 }
20135 former_ns.sort_unstable();
20136 one_buffer_ns.sort_unstable();
20137 let former_p50 = former_ns[SAMPLES / 2];
20138 let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
20139 println!(
20140 "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
20141 former_p50 as f64 / one_buffer_p50 as f64
20142 );
20143 println!("former_samples_ns={former_ns:?}");
20144 println!("one_buffer_samples_ns={one_buffer_ns:?}");
20145 }
20146
20147 #[test]
20148 fn timestamp_strftime_basic() {
20149 let ts = Timestamp::from_nanos(
20150 Timedelta::NANOS_PER_DAY * 365
20151 + Timedelta::NANOS_PER_HOUR * 9
20152 + Timedelta::NANOS_PER_MIN * 15,
20153 );
20154 assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
20155 assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
20156 assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
20157 assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%Y|%01|%Q|%|λ");
20160 assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
20161 }
20162
20163 #[test]
20164 fn strftime_follows_python_directives_and_zones() {
20165 let ts = Timestamp::from_nanos(
20168 Timedelta::NANOS_PER_DAY * 365
20169 + Timedelta::NANOS_PER_HOUR * 9
20170 + Timedelta::NANOS_PER_MIN * 15,
20171 );
20172 assert_eq!(
20173 ts.strftime("%-d %_m %^a %e %k %l %P %C %g %D %F %T %R %r %h %n %t|"),
20174 "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|"
20175 );
20176 assert_eq!(
20177 ts.strftime("%a %A %b %B %c|%x %X|%I %p %j %U %W %w %y"),
20178 "Fri Friday Jan January Fri Jan 1 09:15:00 1971|01/01/71 09:15:00|09 AM 001 00 00 5 71"
20179 );
20180 let sunday = Timestamp::parse("2021-01-03").expect("date");
20182 assert_eq!(sunday.strftime("%G-%V-%u %U %W %j"), "2020-53-7 01 00 003");
20183 let fraction = Timestamp::parse("2024-03-05 14:07:09.123456789").expect("ts");
20185 assert_eq!(fraction.strftime("%f|%z|%Z|abc%"), "123456|||abc%");
20186 let eastern = Timestamp::from_nanos_tz(fraction.nanos, "US/Eastern");
20188 assert_eq!(
20189 eastern.strftime("%Y-%m-%d %H:%M %z %Z"),
20190 "2024-03-05 09:07 -0500 EST"
20191 );
20192 assert_eq!(
20193 crate::strftime_in_zone(fraction.nanos, "%H:%M %z", Some("+05:30")),
20194 "19:37 +0530"
20195 );
20196 }
20197
20198 #[test]
20199 fn timestamp_strftime_floors_pre_epoch_instants_1pmlp() {
20200 let apollo = Timestamp::parse("1969-07-20T20:17:40").unwrap();
20201 assert_eq!(
20202 apollo.strftime("%Y-%m-%d %H:%M:%S.%f"),
20203 "1969-07-20 20:17:40.000000"
20204 );
20205
20206 let one_ns_before_epoch = Timestamp::from_nanos(-1);
20209 assert_eq!(
20210 one_ns_before_epoch.strftime("%Y-%m-%d %H:%M:%S.%f"),
20211 "1969-12-31 23:59:59.999999"
20212 );
20213 }
20214
20215 #[test]
20216 #[ignore = "foreground normal-release attribution harness"]
20217 fn timestamp_strftime_one_buffer_profile_8qzbo() {
20218 use std::{hint::black_box, time::Instant};
20219
20220 const ITEMS: usize = 8_192;
20221 const SAMPLES: usize = 10;
20222 const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
20223
20224 fn former(timestamp: &Timestamp, format: &str) -> String {
20225 if timestamp.is_nat() {
20226 return "NaT".to_string();
20227 }
20228 let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
20229 let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
20230
20231 let days_since_epoch = total_secs / 86400;
20232 let secs_of_day = (total_secs % 86400 + 86400) % 86400;
20233 let days = days_since_epoch + 719_468;
20234 let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
20235 let doe = days - era * 146_097;
20236 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
20237 let y = yoe + era * 400;
20238 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
20239 let mp = (5 * doy + 2) / 153;
20240 let d = doy - (153 * mp + 2) / 5 + 1;
20241 let m = if mp < 10 { mp + 3 } else { mp - 9 };
20242 let year = if m <= 2 { y + 1 } else { y };
20243 let hour = secs_of_day / 3600;
20244 let minute = (secs_of_day % 3600) / 60;
20245 let second = secs_of_day % 60;
20246 let micros = sub_nanos / 1000;
20247
20248 format
20249 .replace("%Y", &format!("{year:04}"))
20250 .replace("%m", &format!("{m:02}"))
20251 .replace("%d", &format!("{d:02}"))
20252 .replace("%H", &format!("{hour:02}"))
20253 .replace("%M", &format!("{minute:02}"))
20254 .replace("%S", &format!("{second:02}"))
20255 .replace("%f", &format!("{micros:06}"))
20256 }
20257
20258 fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
20259 let started = Instant::now();
20260 let mut digest = 0_usize;
20261 for timestamp in timestamps {
20262 let value = formatter(black_box(timestamp), black_box(FORMAT));
20263 digest = digest.wrapping_add(value.len());
20264 digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
20265 black_box(value);
20266 }
20267 black_box(digest);
20268 started.elapsed().as_nanos()
20269 }
20270
20271 fn percentile(samples: &mut [u128], pct: usize) -> u128 {
20272 samples.sort_unstable();
20273 let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
20274 samples[rank]
20275 }
20276
20277 let edge_timestamps = [
20278 Timestamp::nat(),
20279 Timestamp::from_nanos(i64::MIN + 1),
20280 Timestamp::from_nanos(-1_234_567_890),
20281 Timestamp::from_nanos(0),
20282 Timestamp::from_nanos(1_735_732_800_123_456_789),
20283 Timestamp::from_nanos(i64::MAX),
20284 ];
20285 let edge_formats = [
20286 "",
20287 "%Y-%m-%d %H:%M:%S.%f",
20288 "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
20289 "%%Y|%%%m|%Q|%|λ",
20290 FORMAT,
20291 ];
20292 for timestamp in &edge_timestamps {
20293 for format in edge_formats {
20294 assert_eq!(former(timestamp, format), timestamp.strftime(format));
20295 }
20296 }
20297
20298 let timestamps = (0..ITEMS)
20299 .map(|index| {
20300 let centered = index as i64 - ITEMS as i64 / 2;
20301 Timestamp::from_nanos(centered * 987_654_321_123_456)
20302 })
20303 .collect::<Vec<_>>();
20304 for timestamp in ×tamps {
20305 assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
20306 }
20307
20308 black_box(elapsed(×tamps, former));
20309 black_box(elapsed(×tamps, Timestamp::strftime));
20310
20311 let mut former_samples = Vec::with_capacity(SAMPLES);
20312 let mut public_samples = Vec::with_capacity(SAMPLES);
20313 for sample in 0..SAMPLES {
20314 if sample.is_multiple_of(2) {
20315 former_samples.push(elapsed(×tamps, former));
20316 public_samples.push(elapsed(×tamps, Timestamp::strftime));
20317 } else {
20318 public_samples.push(elapsed(×tamps, Timestamp::strftime));
20319 former_samples.push(elapsed(×tamps, former));
20320 }
20321 }
20322 let former_p50 = percentile(&mut former_samples, 50);
20323 let former_p95 = percentile(&mut former_samples, 95);
20324 let public_p50 = percentile(&mut public_samples, 50);
20325 let public_p95 = percentile(&mut public_samples, 95);
20326 println!(
20327 "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}",
20328 former_p50 as f64 / public_p50 as f64,
20329 former_p95 as f64 / public_p95 as f64,
20330 );
20331 println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
20332 println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
20333 }
20334
20335 #[test]
20336 fn timestamp_day_name_and_month_name() {
20337 let ts = Timestamp::from_nanos(0);
20338 assert_eq!(ts.day_name(), "Thursday");
20339 assert_eq!(ts.month_name(), "January");
20340
20341 let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20342 assert_eq!(ts2.day_name(), "Friday");
20343 assert_eq!(ts2.month_name(), "January");
20344
20345 assert_eq!(Timestamp::nat().day_name(), "NaT");
20346 assert_eq!(Timestamp::nat().month_name(), "NaT");
20347 }
20348
20349 #[test]
20350 fn timestamp_replace_validates_components_zw0y2() {
20351 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20352 let replaced = ts.replace(
20353 Some(2024),
20354 Some(2),
20355 Some(29),
20356 Some(23),
20357 Some(59),
20358 Some(58),
20359 Some(987_654),
20360 Some(321),
20361 );
20362 assert_eq!(replaced.year(), Some(2024));
20363 assert_eq!(replaced.month(), Some(2));
20364 assert_eq!(replaced.day(), Some(29));
20365 assert_eq!(replaced.hour(), Some(23));
20366 assert_eq!(replaced.minute(), Some(59));
20367 assert_eq!(replaced.second(), Some(58));
20368 assert_eq!(replaced.microsecond(), Some(987_654));
20369 assert_eq!(replaced.nanosecond(), Some(321));
20370
20371 let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20372 assert_eq!(
20373 tz.replace(None, Some(2), Some(29), None, None, None, None, None)
20374 .tz
20375 .as_deref(),
20376 Some("UTC")
20377 );
20378
20379 assert!(
20380 ts.replace(None, Some(13), None, None, None, None, None, None)
20381 .is_nat()
20382 );
20383 assert!(
20384 ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
20385 .is_nat()
20386 );
20387 assert!(
20388 ts.replace(None, None, None, Some(24), None, None, None, None)
20389 .is_nat()
20390 );
20391 assert!(
20392 ts.replace(None, None, None, None, Some(60), None, None, None)
20393 .is_nat()
20394 );
20395 assert!(
20396 ts.replace(None, None, None, None, None, Some(60), None, None)
20397 .is_nat()
20398 );
20399 assert!(
20400 ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
20401 .is_nat()
20402 );
20403 assert!(
20404 ts.replace(None, None, None, None, None, None, None, Some(1_000))
20405 .is_nat()
20406 );
20407 assert!(
20408 Timestamp::nat()
20409 .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
20410 .is_nat()
20411 );
20412 }
20413
20414 #[test]
20421 fn timestamp_replace_returns_nat_on_nanosecond_overflow_dzz6x() {
20422 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20423
20424 for year in [3000, 10_000, 300_000, i64::MAX / 400] {
20425 let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20426 assert!(
20427 out.is_nat(),
20428 "replace(year={year}) is unrepresentable in i64 ns and must be \
20429 NaT, got nanos={:?} (year {:?}) — this is the silent wrap",
20430 out.nanos,
20431 out.year()
20432 );
20433 }
20434 for year in [-3000, -100_000, i64::MIN / 400] {
20435 let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20436 assert!(out.is_nat(), "replace(year={year}) must be NaT");
20437 }
20438
20439 let in_range = ts.replace(
20444 Some(2262),
20445 Some(1),
20446 Some(1),
20447 Some(0),
20448 Some(0),
20449 Some(0),
20450 Some(0),
20451 Some(0),
20452 );
20453 assert!(
20454 !in_range.is_nat(),
20455 "2262-01-01 is representable and must survive"
20456 );
20457 assert_eq!(in_range.year(), Some(2262));
20458 assert!(
20459 ts.replace(
20460 Some(2263),
20461 Some(12),
20462 Some(31),
20463 Some(23),
20464 Some(59),
20465 Some(59),
20466 Some(999_999),
20467 Some(999)
20468 )
20469 .is_nat(),
20470 "end of 2263 exceeds the i64 ns axis and must be NaT"
20471 );
20472
20473 let unchanged = ts.replace(
20477 Some(1999),
20478 Some(6),
20479 Some(30),
20480 Some(12),
20481 Some(1),
20482 Some(2),
20483 Some(3),
20484 Some(4),
20485 );
20486 assert_eq!(unchanged.year(), Some(1999));
20487 assert_eq!(unchanged.month(), Some(6));
20488 assert_eq!(unchanged.day(), Some(30));
20489 assert_eq!(unchanged.hour(), Some(12));
20490 assert_eq!(unchanged.minute(), Some(1));
20491 assert_eq!(unchanged.second(), Some(2));
20492 assert_eq!(unchanged.microsecond(), Some(3));
20493 assert_eq!(unchanged.nanosecond(), Some(4));
20494 let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20495 assert_eq!(
20496 tz.replace(Some(1999), None, None, None, None, None, None, None)
20497 .tz
20498 .as_deref(),
20499 Some("UTC")
20500 );
20501 }
20502
20503 #[test]
20504 fn timestamp_component_accessors() {
20505 let ts = Timestamp::from_nanos(0);
20506 assert_eq!(ts.year(), Some(1970));
20507 assert_eq!(ts.month(), Some(1));
20508 assert_eq!(ts.day(), Some(1));
20509 assert_eq!(ts.hour(), Some(0));
20510 assert_eq!(ts.minute(), Some(0));
20511 assert_eq!(ts.second(), Some(0));
20512 assert_eq!(ts.microsecond(), Some(0));
20513 assert_eq!(ts.nanosecond(), Some(0));
20514
20515 let ts2 = Timestamp::from_nanos(
20516 Timedelta::NANOS_PER_DAY * 365
20517 + Timedelta::NANOS_PER_HOUR * 14
20518 + Timedelta::NANOS_PER_MIN * 30
20519 + Timedelta::NANOS_PER_SEC * 45
20520 + 123_456_789,
20521 );
20522 assert_eq!(ts2.year(), Some(1971));
20523 assert_eq!(ts2.month(), Some(1));
20524 assert_eq!(ts2.day(), Some(1));
20525 assert_eq!(ts2.hour(), Some(14));
20526 assert_eq!(ts2.minute(), Some(30));
20527 assert_eq!(ts2.second(), Some(45));
20528 assert_eq!(ts2.microsecond(), Some(123456));
20529 assert_eq!(ts2.nanosecond(), Some(789));
20530
20531 assert_eq!(Timestamp::nat().year(), None);
20532 assert_eq!(Timestamp::nat().month(), None);
20533 assert_eq!(Timestamp::nat().day(), None);
20534 }
20535
20536 #[test]
20537 fn timestamp_dayofweek_dayofyear_quarter() {
20538 let ts = Timestamp::from_nanos(0);
20539 assert_eq!(ts.dayofweek(), Some(3));
20540 assert_eq!(ts.weekday(), Some(3));
20541 assert_eq!(ts.dayofyear(), Some(1));
20542 assert_eq!(ts.quarter(), Some(1));
20543
20544 let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
20545 assert_eq!(ts2.quarter(), Some(2));
20546
20547 let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20548 assert_eq!(ts3.dayofyear(), Some(1));
20549 assert_eq!(ts3.dayofweek(), Some(4));
20550
20551 assert_eq!(Timestamp::nat().dayofweek(), None);
20552 assert_eq!(Timestamp::nat().dayofyear(), None);
20553 assert_eq!(Timestamp::nat().quarter(), None);
20554 }
20555
20556 #[test]
20557 fn timestamp_is_boundary_methods() {
20558 let jan1 = Timestamp::from_nanos(0);
20559 assert_eq!(jan1.is_leap_year(), Some(false));
20560 assert_eq!(jan1.is_month_start(), Some(true));
20561 assert_eq!(jan1.is_month_end(), Some(false));
20562 assert_eq!(jan1.is_quarter_start(), Some(true));
20563 assert_eq!(jan1.is_quarter_end(), Some(false));
20564 assert_eq!(jan1.is_year_start(), Some(true));
20565 assert_eq!(jan1.is_year_end(), Some(false));
20566
20567 let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
20568 assert_eq!(dec31.is_month_start(), Some(false));
20569 assert_eq!(dec31.is_month_end(), Some(true));
20570 assert_eq!(dec31.is_quarter_end(), Some(true));
20571 assert_eq!(dec31.is_year_end(), Some(true));
20572
20573 assert_eq!(Timestamp::nat().is_leap_year(), None);
20574 assert_eq!(Timestamp::nat().is_month_start(), None);
20575 }
20576
20577 #[test]
20578 fn timestamp_days_in_month() {
20579 let jan = Timestamp::from_nanos(0);
20580 assert_eq!(jan.days_in_month(), Some(31));
20581 assert_eq!(jan.daysinmonth(), Some(31));
20582
20583 let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
20584 assert_eq!(feb_non_leap.days_in_month(), Some(28));
20585
20586 assert_eq!(Timestamp::nat().days_in_month(), None);
20587 }
20588
20589 #[test]
20590 fn timestamp_weekofyear() {
20591 let jan1 = Timestamp::from_nanos(0);
20592 assert_eq!(jan1.weekofyear(), Some(1));
20593 assert_eq!(jan1.week(), Some(1));
20594
20595 let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
20596 assert_eq!(jan8.weekofyear(), Some(2));
20597
20598 assert_eq!(Timestamp::nat().weekofyear(), None);
20599 assert_eq!(Timestamp::nat().week(), None);
20600 }
20601
20602 #[test]
20603 fn timestamp_weekofyear_iso_53_week_boundaries() {
20604 fn week_of(date_days: i64) -> Option<i64> {
20607 Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
20608 }
20609 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)); }
20623
20624 #[test]
20625 fn iso_weeks_in_year_53_week_years() {
20626 use super::iso_weeks_in_year;
20627 for y in [2004, 2009, 2015, 2020, 2026] {
20629 assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
20630 }
20631 for y in [2018, 2019, 2021, 2022, 2023, 2024] {
20632 assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
20633 }
20634 }
20635
20636 #[test]
20637 fn timestamp_to_unit() {
20638 let ts = Timestamp::from_nanos(1_000_000_000);
20639 assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
20640 assert_eq!(ts.to_unit("us"), Some(1_000_000));
20641 assert_eq!(ts.to_unit("ms"), Some(1_000));
20642 assert_eq!(ts.to_unit("s"), Some(1));
20643 assert_eq!(ts.to_unit("invalid"), None);
20644
20645 assert_eq!(Timestamp::nat().to_unit("ns"), None);
20646 }
20647
20648 #[test]
20649 fn timestamp_toordinal() {
20650 let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
20653 let ts = Timestamp::from_nanos(nanos_2026_01_01);
20654 assert_eq!(ts.toordinal(), Some(738886));
20655
20656 assert_eq!(Timestamp::nat().toordinal(), None);
20658 }
20659
20660 #[test]
20661 fn timestamp_fromordinal() {
20662 let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
20665 let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
20666 let ordinal = ts_orig.toordinal().unwrap();
20667
20668 let ts = Timestamp::fromordinal(ordinal);
20670 assert_eq!(ts.year(), ts_orig.year());
20671 assert_eq!(ts.month(), ts_orig.month());
20672 assert_eq!(ts.day(), ts_orig.day());
20673
20674 let nat = Timestamp::fromordinal(0);
20676 assert!(nat.is_nat());
20677 }
20678
20679 #[test]
20680 fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
20681 const EPOCH_ORDINAL: i64 = 719_163;
20682 let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
20683 let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
20684
20685 let max_valid = Timestamp::fromordinal(max_valid_ordinal);
20686 assert!(!max_valid.is_nat());
20687 assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
20688
20689 assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
20690 assert!(Timestamp::fromordinal(i64::MAX).is_nat());
20691 }
20692
20693 #[test]
20694 fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
20695 const EPOCH_ORDINAL: i64 = 719_163;
20696 const DAY: i64 = Timedelta::NANOS_PER_DAY;
20697
20698 fn next(seed: &mut u64) -> u64 {
20699 *seed = seed
20700 .wrapping_mul(3202034522624059733)
20701 .wrapping_add(4354685564936845319);
20702 *seed
20703 }
20704
20705 fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
20706 let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
20707 let ts = Timestamp::from_nanos(nanos);
20708 let expected_day_offset = nanos.div_euclid(DAY);
20709 let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
20710
20711 assert_eq!(
20712 ts.toordinal(),
20713 Some(expected_ordinal),
20714 "case {case}: toordinal"
20715 );
20716
20717 let midnight = Timestamp::fromordinal(expected_ordinal);
20718 assert_eq!(
20719 midnight.nanos,
20720 expected_day_offset * DAY,
20721 "case {case}: fromordinal nanos"
20722 );
20723 assert_eq!(
20724 midnight.toordinal(),
20725 Some(expected_ordinal),
20726 "case {case}: fromordinal roundtrip"
20727 );
20728 }
20729
20730 assert_eq!(Timestamp::nat().toordinal(), None);
20731 assert!(Timestamp::fromordinal(0).is_nat());
20732 assert!(Timestamp::fromordinal(-1).is_nat());
20733
20734 assert_ordinal_case(usize::MAX, -1, DAY - 1);
20735 assert_ordinal_case(usize::MAX - 1, 0, -1);
20736 assert_ordinal_case(usize::MAX - 2, 19_723, 0);
20737
20738 let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
20739 for case in 0..260 {
20740 let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
20741 let subday_nanos = match case % 7 {
20742 0 => 0,
20743 1 => DAY - 1,
20744 2 => -1,
20745 _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
20746 };
20747 assert_ordinal_case(case, day_offset, subday_nanos);
20748 }
20749 }
20750
20751 #[test]
20758 fn timestamp_parse_rejects_unrepresentable_years_94o1u() {
20759 for s in [
20760 "300000-01-01",
20761 "10000000-06-15T12:30:45",
20762 "999999999-01-01",
20763 "-300000-01-01",
20764 "-99999999-12-31T23:59:59",
20765 ] {
20766 let got = Timestamp::parse(s);
20767 assert!(
20768 got.is_err(),
20769 "parse({s:?}) is unrepresentable in i64 ns and must be Err, got {:?} \
20770 — this is the silent wrap",
20771 got.map(|ts| (ts.nanos, ts.year()))
20772 );
20773 }
20774
20775 let ok = Timestamp::parse("2262-01-01").expect("2262-01-01 is representable");
20778 assert_eq!(ok.year(), Some(2262));
20779 assert!(
20780 Timestamp::parse("2263-12-31T23:59:59").is_err(),
20781 "end of 2263 exceeds the i64 ns axis and must be Err"
20782 );
20783
20784 assert_eq!(Timestamp::parse("2024-01-15").unwrap().year(), Some(2024));
20788 assert_eq!(
20789 Timestamp::parse("2024-01-15T10:30:45").unwrap().hour(),
20790 Some(10)
20791 );
20792 assert_eq!(
20793 Timestamp::parse("2024-01-15 10:30:45").unwrap().minute(),
20794 Some(30)
20795 );
20796 assert_eq!(
20797 Timestamp::parse("2024-01-15T10:30:45.123456789")
20798 .unwrap()
20799 .nanosecond(),
20800 Some(789)
20801 );
20802 assert_eq!(
20803 Timestamp::parse("2024-01-15T00:00:00Z").unwrap().year(),
20804 Some(2024)
20805 );
20806 assert_eq!(Timestamp::parse("1900-01-01").unwrap().year(), Some(1900));
20808 }
20809
20810 #[test]
20811 fn timestamp_parse_iso8601_date_only() {
20812 let ts = Timestamp::parse("2024-01-15").unwrap();
20813 assert_eq!(ts.year(), Some(2024));
20814 assert_eq!(ts.month(), Some(1));
20815 assert_eq!(ts.day(), Some(15));
20816 assert_eq!(ts.hour(), Some(0));
20817 assert_eq!(ts.minute(), Some(0));
20818 assert_eq!(ts.second(), Some(0));
20819 }
20820
20821 #[test]
20822 fn timestamp_parse_iso8601_datetime() {
20823 let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
20824 assert_eq!(ts.year(), Some(2024));
20825 assert_eq!(ts.month(), Some(1));
20826 assert_eq!(ts.day(), Some(15));
20827 assert_eq!(ts.hour(), Some(10));
20828 assert_eq!(ts.minute(), Some(30));
20829 assert_eq!(ts.second(), Some(45));
20830 }
20831
20832 #[test]
20833 fn timestamp_parse_space_separator() {
20834 let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
20835 assert_eq!(ts.year(), Some(2024));
20836 assert_eq!(ts.hour(), Some(10));
20837 }
20838
20839 #[test]
20840 fn timestamp_parse_with_fractional_seconds() {
20841 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20842 assert_eq!(ts.second(), Some(45));
20843 assert_eq!(ts.microsecond(), Some(123456));
20844 assert_eq!(ts.nanosecond(), Some(789));
20845 }
20846
20847 #[test]
20848 fn timestamp_parse_utc_timezone() {
20849 let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
20850 assert_eq!(ts.tz, Some("UTC".to_string()));
20851 }
20852
20853 #[test]
20854 fn timestamp_parse_offset_timezone() {
20855 let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
20856 assert_eq!(ts.tz, Some("+05:30".to_string()));
20857 let utc = |text: &str| Timestamp::parse(text).unwrap().nanos;
20860 assert_eq!(ts.nanos, utc("2024-01-15T05:00:45"));
20861
20862 let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
20863 assert_eq!(ts.tz, Some("-05:30".to_string()));
20864 assert_eq!(ts.nanos, utc("2024-01-15T16:00:45"));
20865 assert_eq!(
20867 Timestamp::parse("2024-01-15T10:30:45Z").unwrap().nanos,
20868 utc("2024-01-15T10:30:45")
20869 );
20870 }
20871
20872 #[test]
20873 fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
20874 assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
20875 assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
20876 assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
20877 assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
20878 assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
20879 }
20880
20881 #[test]
20882 fn timestamp_parse_nat() {
20883 let ts = Timestamp::parse("NaT").unwrap();
20884 assert!(ts.is_nat());
20885 let ts2 = Timestamp::parse("nat").unwrap();
20886 assert!(ts2.is_nat());
20887 }
20888
20889 #[test]
20890 fn timestamp_parse_invalid() {
20891 assert!(Timestamp::parse("not a date").is_err());
20892 assert!(Timestamp::parse("2024-13-01").is_err()); assert!(Timestamp::parse("2024-01-32").is_err()); }
20895
20896 #[test]
20897 fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
20898 assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
20899 assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
20900 assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
20901 assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
20902 assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
20903
20904 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
20905 assert_eq!(ts.second(), Some(45));
20906 assert_eq!(ts.microsecond(), Some(123456));
20907 assert_eq!(ts.nanosecond(), Some(789));
20908 }
20909
20910 #[test]
20911 #[ignore = "foreground profile-first A/B"]
20912 fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
20913 use std::{hint::black_box, time::Instant};
20914
20915 const CALLS: usize = 131_072;
20916 const SAMPLES: usize = 12;
20917 type ParsedTime = Option<(u32, u32, u32, u64)>;
20918 const VALID: [&str; 16] = [
20919 "00:00:00.0",
20920 "01:02:03.1",
20921 "02:03:04.01",
20922 "03:04:05.001",
20923 "04:05:06.0001",
20924 "05:06:07.00001",
20925 "06:07:08.000001",
20926 "07:08:09.0000001",
20927 "08:09:10.00000001",
20928 "09:10:11.000000001",
20929 "10:11:12.123456789",
20930 "11:12:13.999999999",
20931 "12:13:14.123456789987",
20932 "13:14:15.000000000001",
20933 "14:15:16.101010101010",
20934 "23:59:59.987654321234",
20935 ];
20936
20937 #[inline(never)]
20938 fn former(s: &str) -> ParsedTime {
20939 let (time_str, frac_str) = match s.split_once('.') {
20940 Some((time, frac)) => (time, Some(frac)),
20941 None => (s, None),
20942 };
20943 let parts: Vec<&str> = time_str.split(':').collect();
20944 if parts.is_empty() || parts.len() > 3 {
20945 return None;
20946 }
20947 let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
20948 let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
20949 let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
20950
20951 if hour > 23 || minute > 59 || second > 59 {
20952 return None;
20953 }
20954
20955 let nanos = match frac_str {
20956 None => 0,
20957 Some(frac) => {
20958 if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
20959 return None;
20960 }
20961 let truncated = &frac[..frac.len().min(9)];
20962 let padded = format!("{truncated:0<9}");
20963 padded.parse::<u64>().ok()?
20964 }
20965 };
20966
20967 Some((hour, minute, second, nanos))
20968 }
20969
20970 #[inline(never)]
20971 fn candidate(s: &str) -> ParsedTime {
20972 Timestamp::parse_time(s)
20973 }
20974
20975 fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
20976 let started = Instant::now();
20977 for input in black_box(inputs) {
20978 black_box(parser(black_box(*input)));
20979 }
20980 started.elapsed().as_nanos()
20981 }
20982
20983 fn percentile(samples: &[u128], percent: usize) -> u128 {
20984 let mut sorted = samples.to_vec();
20985 sorted.sort_unstable();
20986 let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
20987 sorted[rank]
20988 }
20989
20990 let invalid = [
20991 "",
20992 "24:00:00.1",
20993 "12:60:00.1",
20994 "12:00:60.1",
20995 "12:00:00.",
20996 "12:00:00.abc",
20997 "12:00:00.-1",
20998 "12:00:00.123",
20999 "12:00:00.123456789x",
21000 "12:00:00.1.2",
21001 "12:00:00:01.1",
21002 ];
21003 for input in VALID.iter().chain(invalid.iter()) {
21004 assert_eq!(candidate(input), former(input), "input={input:?}");
21005 }
21006
21007 let inputs = (0..CALLS)
21008 .map(|index| VALID[index % VALID.len()])
21009 .collect::<Vec<_>>();
21010 for _ in 0..2 {
21011 black_box(elapsed(&inputs, former));
21012 black_box(elapsed(&inputs, candidate));
21013 }
21014
21015 let mut former_ns = Vec::with_capacity(SAMPLES);
21016 let mut candidate_ns = Vec::with_capacity(SAMPLES);
21017 for sample in 0..SAMPLES {
21018 if sample.is_multiple_of(2) {
21019 former_ns.push(elapsed(&inputs, former));
21020 candidate_ns.push(elapsed(&inputs, candidate));
21021 } else {
21022 candidate_ns.push(elapsed(&inputs, candidate));
21023 former_ns.push(elapsed(&inputs, former));
21024 }
21025 }
21026
21027 let former_p50 = percentile(&former_ns, 50);
21028 let former_p95 = percentile(&former_ns, 95);
21029 let former_p99 = percentile(&former_ns, 99);
21030 let candidate_p50 = percentile(&candidate_ns, 50);
21031 let candidate_p95 = percentile(&candidate_ns, 95);
21032 let candidate_p99 = percentile(&candidate_ns, 99);
21033 println!(
21034 "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:?}",
21035 former_p50 as f64 / candidate_p50 as f64,
21036 former_p95 as f64 / candidate_p95 as f64,
21037 former_p99 as f64 / candidate_p99 as f64,
21038 );
21039 }
21040
21041 #[test]
21042 fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
21043 fn next(seed: &mut u64) -> u64 {
21044 *seed = seed
21045 .wrapping_mul(3935559000370003845)
21046 .wrapping_add(2691343689449507681);
21047 *seed
21048 }
21049
21050 fn leap(year: i64) -> bool {
21051 (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
21052 }
21053
21054 fn month_len(year: i64, month: u32) -> u32 {
21055 match month {
21056 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
21057 4 | 6 | 9 | 11 => 30,
21058 2 if leap(year) => 29,
21059 2 => 28,
21060 _ => 0,
21061 }
21062 }
21063
21064 struct Components {
21065 year: i64,
21066 month: u32,
21067 day: u32,
21068 hour: u32,
21069 minute: u32,
21070 second: u32,
21071 nanos: u64,
21072 }
21073
21074 fn assert_components(case: usize, text: &str, expected: Components) {
21075 let ts = Timestamp::parse(text).expect("seeded valid timestamp");
21076 let Components {
21077 year,
21078 month,
21079 day,
21080 hour,
21081 minute,
21082 second,
21083 nanos,
21084 } = expected;
21085 assert_eq!(ts.year(), Some(year), "case {case}: year");
21086 assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
21087 assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
21088 assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
21089 assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
21090 assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
21091 assert_eq!(
21092 ts.microsecond(),
21093 Some((nanos / 1000) as i64),
21094 "case {case}: microsecond"
21095 );
21096 assert_eq!(
21097 ts.nanosecond(),
21098 Some((nanos % 1000) as i64),
21099 "case {case}: nanosecond"
21100 );
21101 }
21102
21103 assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
21104 assert!(
21105 Timestamp::parse("nAt")
21106 .expect("mixed-case NaT parses")
21107 .is_nat()
21108 );
21109 assert!(Timestamp::parse("1900-02-29").is_err());
21110 assert!(Timestamp::parse("2001-04-31").is_err());
21111 assert!(Timestamp::parse("2024-00-15").is_err());
21112
21113 assert_components(
21114 usize::MAX,
21115 "2000-02-29",
21116 Components {
21117 year: 2000,
21118 month: 2,
21119 day: 29,
21120 hour: 0,
21121 minute: 0,
21122 second: 0,
21123 nanos: 0,
21124 },
21125 );
21126 assert_components(
21127 usize::MAX - 1,
21128 "2024-02-29T23:59:59.000000001",
21129 Components {
21130 year: 2024,
21131 month: 2,
21132 day: 29,
21133 hour: 23,
21134 minute: 59,
21135 second: 59,
21136 nanos: 1,
21137 },
21138 );
21139
21140 let mut seed = 0x15e0_1d50_1f0a_cade_u64;
21141 for case in 0..260 {
21142 let year = 1900 + (next(&mut seed) % 201) as i64;
21143 let month = 1 + (next(&mut seed) % 12) as u32;
21144 let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
21145 let hour = (next(&mut seed) % 24) as u32;
21146 let minute = (next(&mut seed) % 60) as u32;
21147 let second = (next(&mut seed) % 60) as u32;
21148 let nanos = next(&mut seed) % 1_000_000_000;
21149
21150 match case % 4 {
21151 0 => {
21152 let text = format!("{year:04}-{month:02}-{day:02}");
21153 assert_components(
21154 case,
21155 &text,
21156 Components {
21157 year,
21158 month,
21159 day,
21160 hour: 0,
21161 minute: 0,
21162 second: 0,
21163 nanos: 0,
21164 },
21165 );
21166 }
21167 1 => {
21168 let text =
21169 format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
21170 assert_components(
21171 case,
21172 &text,
21173 Components {
21174 year,
21175 month,
21176 day,
21177 hour,
21178 minute,
21179 second,
21180 nanos: 0,
21181 },
21182 );
21183 }
21184 2 => {
21185 let text =
21186 format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
21187 assert_components(
21188 case,
21189 &text,
21190 Components {
21191 year,
21192 month,
21193 day,
21194 hour,
21195 minute,
21196 second,
21197 nanos: 0,
21198 },
21199 );
21200 }
21201 _ => {
21202 let text = format!(
21203 "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
21204 );
21205 assert_components(
21206 case,
21207 &text,
21208 Components {
21209 year,
21210 month,
21211 day,
21212 hour,
21213 minute,
21214 second,
21215 nanos,
21216 },
21217 );
21218 }
21219 }
21220 }
21221 }
21222
21223 #[test]
21224 fn period_parse_annual() {
21225 let p = Period::parse("2024").unwrap();
21226 assert_eq!(p.freq(), PeriodFreq::ANNUAL);
21227 assert_eq!(p.ordinal(), 2024 - 1970);
21228 }
21229
21230 #[test]
21231 fn period_parse_quarterly() {
21232 let p = Period::parse("2024Q1").unwrap();
21233 assert_eq!(p.freq(), PeriodFreq::QUARTERLY);
21234 assert_eq!(p.ordinal(), (2024 - 1970) * 4);
21235
21236 let p2 = Period::parse("2024q3").unwrap();
21237 assert_eq!(p2.freq(), PeriodFreq::QUARTERLY);
21238 assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
21239 }
21240
21241 #[test]
21242 fn period_parse_monthly() {
21243 let p = Period::parse("2024-01").unwrap();
21244 assert_eq!(p.freq(), PeriodFreq::Monthly);
21245 assert_eq!(p.ordinal(), (2024 - 1970) * 12);
21246
21247 let p2 = Period::parse("2024-12").unwrap();
21248 assert_eq!(p2.freq(), PeriodFreq::Monthly);
21249 assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
21250 }
21251
21252 #[test]
21253 fn period_parse_nat() {
21254 let p = Period::parse("NaT").unwrap();
21255 assert_eq!(p.ordinal(), i64::MIN);
21256 }
21257
21258 #[test]
21259 fn period_parse_invalid() {
21260 assert!(Period::parse("not a period").is_err());
21261 assert!(Period::parse("2024Q5").is_err()); assert!(Period::parse("2024-13").is_err()); }
21264
21265 #[test]
21266 fn interval_parse_basic() {
21267 let i = Interval::parse("[0, 1]").unwrap();
21268 assert_eq!(i.left, 0.0);
21269 assert_eq!(i.right, 1.0);
21270 assert_eq!(i.closed, IntervalClosed::Both);
21271
21272 let i2 = Interval::parse("(0, 1)").unwrap();
21273 assert_eq!(i2.left, 0.0);
21274 assert_eq!(i2.right, 1.0);
21275 assert_eq!(i2.closed, IntervalClosed::Neither);
21276
21277 let i3 = Interval::parse("[0, 1)").unwrap();
21278 assert_eq!(i3.closed, IntervalClosed::Left);
21279
21280 let i4 = Interval::parse("(0, 1]").unwrap();
21281 assert_eq!(i4.closed, IntervalClosed::Right);
21282 }
21283
21284 #[test]
21285 fn interval_parse_floats() {
21286 let i = Interval::parse("[-1.5, 2.5)").unwrap();
21287 assert_eq!(i.left, -1.5);
21288 assert_eq!(i.right, 2.5);
21289 assert_eq!(i.closed, IntervalClosed::Left);
21290 }
21291
21292 #[test]
21293 fn interval_parse_invalid() {
21294 assert!(Interval::parse("invalid").is_err());
21295 assert!(Interval::parse("[0]").is_err());
21296 assert!(Interval::parse("0, 1").is_err()); }
21298
21299 fn interval_parse_error_profile(s: &str) -> super::TypeError {
21300 super::TypeError::ValueNotParseable {
21301 value: s.to_string(),
21302 target: "Interval".to_string(),
21303 }
21304 }
21305
21306 #[inline(never)]
21307 fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
21308 let s = std::hint::black_box(s).trim();
21309 if s.len() < 5 {
21310 return Err(interval_parse_error_profile(s));
21311 }
21312
21313 let first_char = s.chars().next().unwrap();
21314 let last_char = s.chars().last().unwrap();
21315 let left_closed = match first_char {
21316 '[' => true,
21317 '(' => false,
21318 _ => return Err(interval_parse_error_profile(s)),
21319 };
21320 let right_closed = match last_char {
21321 ']' => true,
21322 ')' => false,
21323 _ => return Err(interval_parse_error_profile(s)),
21324 };
21325 let closed = match (left_closed, right_closed) {
21326 (true, true) => IntervalClosed::Both,
21327 (true, false) => IntervalClosed::Left,
21328 (false, true) => IntervalClosed::Right,
21329 (false, false) => IntervalClosed::Neither,
21330 };
21331
21332 let inner = &s[1..s.len() - 1];
21333 let parts: Vec<&str> = inner.split(',').collect();
21334 if parts.len() != 2 {
21335 return Err(interval_parse_error_profile(s));
21336 }
21337 let left = parts[0]
21338 .trim()
21339 .parse()
21340 .map_err(|_| interval_parse_error_profile(s))?;
21341 let right = parts[1]
21342 .trim()
21343 .parse()
21344 .map_err(|_| interval_parse_error_profile(s))?;
21345 Ok(Interval::new(left, right, closed))
21346 }
21347
21348 #[inline(never)]
21349 fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
21350 Interval::parse(std::hint::black_box(s))
21351 }
21352
21353 fn assert_interval_parse_profile_parity(s: &str) {
21354 match (
21355 interval_parse_former_profile(s),
21356 interval_parse_split_once_profile(s),
21357 ) {
21358 (Ok(former), Ok(candidate)) => {
21359 assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
21360 assert_eq!(
21361 former.right.to_bits(),
21362 candidate.right.to_bits(),
21363 "right: {s}"
21364 );
21365 assert_eq!(former.closed, candidate.closed, "closed: {s}");
21366 }
21367 (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
21368 (former, candidate) => assert_eq!(
21369 former.is_ok(),
21370 candidate.is_ok(),
21371 "parse result mismatch for {s}: {former:?} != {candidate:?}"
21372 ),
21373 }
21374 }
21375
21376 #[inline(never)]
21377 fn measure_interval_parser_profile(
21378 parser: fn(&str) -> Result<Interval, super::TypeError>,
21379 inputs: &[&str],
21380 rounds: usize,
21381 ) -> u128 {
21382 use std::{hint::black_box, time::Instant};
21383
21384 let started = Instant::now();
21385 let mut checksum = 0_u64;
21386 for _ in 0..rounds {
21387 for input in inputs {
21388 let parsed = parser(black_box(input)).expect("profile input must parse");
21389 let closed = match parsed.closed {
21390 IntervalClosed::Left => 1_u64,
21391 IntervalClosed::Right => 2,
21392 IntervalClosed::Both => 3,
21393 IntervalClosed::Neither => 4,
21394 };
21395 checksum = checksum
21396 .wrapping_add(parsed.left.to_bits().rotate_left(7))
21397 .wrapping_add(parsed.right.to_bits().rotate_right(11))
21398 .wrapping_add(closed);
21399 black_box(parsed);
21400 }
21401 }
21402 black_box(checksum);
21403 started.elapsed().as_nanos()
21404 }
21405
21406 #[test]
21407 #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
21408 fn profile_interval_parse_endpoint_split_ab_81jjv() {
21409 const VALID: [&str; 8] = [
21410 "[0, 1]",
21411 "(-0.0, 0.0]",
21412 " [ -1.5e3 , 2.75E-4 ) ",
21413 "(NaN, -0]",
21414 "[-inf, inf)",
21415 "[9.25, -7.5]",
21416 "(4.9406564584124654e-324, 1.7976931348623157e308)",
21417 "[-42, 17.125)",
21418 ];
21419 const INVALID: [&str; 12] = [
21420 "invalid",
21421 "[0]",
21422 "0, 1",
21423 "[0 1]",
21424 "[0, 1, 2]",
21425 "[0, 1,]",
21426 "[0,,1]",
21427 "[, 1]",
21428 "[0, ]",
21429 "{0, 1}",
21430 "[0, 1}",
21431 " ⟦0, 1⟧ ",
21432 ];
21433 const ROUNDS: usize = 16_384;
21434 const SAMPLES: usize = 10;
21435
21436 for input in VALID.iter().chain(INVALID.iter()) {
21437 assert_interval_parse_profile_parity(input);
21438 }
21439 for _ in 0..2 {
21440 measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
21441 measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
21442 }
21443
21444 let mut former_ns = Vec::with_capacity(SAMPLES);
21445 let mut candidate_ns = Vec::with_capacity(SAMPLES);
21446 for sample in 0..SAMPLES {
21447 if sample % 2 == 0 {
21448 former_ns.push(measure_interval_parser_profile(
21449 interval_parse_former_profile,
21450 &VALID,
21451 ROUNDS,
21452 ));
21453 candidate_ns.push(measure_interval_parser_profile(
21454 interval_parse_split_once_profile,
21455 &VALID,
21456 ROUNDS,
21457 ));
21458 } else {
21459 candidate_ns.push(measure_interval_parser_profile(
21460 interval_parse_split_once_profile,
21461 &VALID,
21462 ROUNDS,
21463 ));
21464 former_ns.push(measure_interval_parser_profile(
21465 interval_parse_former_profile,
21466 &VALID,
21467 ROUNDS,
21468 ));
21469 }
21470 }
21471 former_ns.sort_unstable();
21472 candidate_ns.sort_unstable();
21473 let former_p50 = former_ns[SAMPLES / 2];
21474 let candidate_p50 = candidate_ns[SAMPLES / 2];
21475 let former_p95 = former_ns[SAMPLES - 1];
21476 let candidate_p95 = candidate_ns[SAMPLES - 1];
21477 println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
21478 println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
21479 println!(
21480 "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
21481 former_p50 as f64 / candidate_p50 as f64
21482 );
21483 println!(
21484 "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
21485 former_p95 as f64 / candidate_p95 as f64
21486 );
21487 }
21488}
21489
21490#[cfg(test)]
21496mod float64_nullable_qkqfb {
21497 use super::{DType, NullKind, Scalar, cast_scalar, common_dtype};
21498
21499 #[test]
21510 fn the_two_float_flavours_have_different_missing_markers_qkqfb() {
21511 assert_eq!(
21512 Scalar::missing_for_dtype(DType::Float64Nullable),
21513 Scalar::Null(NullKind::Null),
21514 "the extension lane stores pd.NA"
21515 );
21516 assert_eq!(
21517 Scalar::missing_for_dtype(DType::Float64),
21518 Scalar::Null(NullKind::NaN),
21519 "the numpy lane stores a real NaN"
21520 );
21521 assert_ne!(
21524 Scalar::missing_for_dtype(DType::Float64Nullable),
21525 Scalar::missing_for_dtype(DType::Float64),
21526 );
21527 }
21528
21529 #[test]
21533 fn spelling_is_pandas_spelling_qkqfb() {
21534 assert_eq!(DType::Float64Nullable.name(), "Float64");
21535 assert_eq!(DType::Float64.name(), "float64");
21536 assert_ne!(DType::Float64Nullable.name(), DType::Float64.name());
21537 }
21538
21539 #[test]
21546 fn serde_round_trips_and_does_not_collide_with_numpy_float64_qkqfb() {
21547 let ext = serde_json::to_string(&DType::Float64Nullable).expect("serialize");
21548 let numpy = serde_json::to_string(&DType::Float64).expect("serialize");
21549 assert_eq!(ext, "\"Float64\"");
21550 assert_eq!(numpy, "\"float64\"");
21551 assert_ne!(ext, numpy);
21552
21553 assert_eq!(
21554 serde_json::from_str::<DType>(&ext).expect("deserialize"),
21555 DType::Float64Nullable
21556 );
21557 assert_eq!(
21558 serde_json::from_str::<DType>(&numpy).expect("deserialize"),
21559 DType::Float64
21560 );
21561 }
21562
21563 #[test]
21566 fn predicates_place_it_in_the_right_families_qkqfb() {
21567 assert!(DType::Float64Nullable.is_floating());
21568 assert!(DType::Float64Nullable.is_numeric());
21569 assert!(DType::Float64Nullable.is_any_real_numeric());
21570 assert!(DType::Float64Nullable.is_nullable());
21571 assert!(DType::Float64Nullable.is_extension());
21572 assert!(!DType::Float64Nullable.is_integer());
21575 assert!(!DType::Float64Nullable.is_signed_integer());
21576 assert!(!DType::Float64Nullable.is_bool());
21577 assert_eq!(DType::Float64Nullable.kind(), 'f');
21580 assert_eq!(DType::Float64Nullable.kind(), DType::Float64.kind());
21581 assert_eq!(DType::Float64Nullable.itemsize(), 8);
21582 }
21583
21584 #[test]
21587 fn nullable_pairing_is_an_involution_qkqfb() {
21588 assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
21589 assert_eq!(DType::Float64Nullable.to_non_nullable(), DType::Float64);
21590 assert_eq!(DType::Float64Nullable.to_nullable(), DType::Float64Nullable);
21592 assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
21593 assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
21595 assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
21596 }
21597
21598 #[test]
21608 fn the_nullable_float_absorbs_every_numeric_flavour_qkqfb() {
21609 for other in [
21610 DType::Float64,
21611 DType::Int64,
21612 DType::Int64Nullable,
21613 DType::Bool,
21614 DType::BoolNullable,
21615 DType::Float64Nullable,
21616 ] {
21617 assert_eq!(
21618 common_dtype(DType::Float64Nullable, other.clone()),
21619 Ok(DType::Float64Nullable),
21620 "Float64Nullable + {other:?}"
21621 );
21622 assert_eq!(
21626 common_dtype(other.clone(), DType::Float64Nullable),
21627 Ok(DType::Float64Nullable),
21628 "{other:?} + Float64Nullable"
21629 );
21630 }
21631 assert_eq!(
21633 common_dtype(DType::Null, DType::Float64Nullable),
21634 Ok(DType::Float64Nullable)
21635 );
21636 }
21637
21638 #[test]
21647 fn casts_preserve_values_and_convert_only_the_marker_qkqfb() {
21648 let present = Scalar::Float64(1.5);
21649 assert_eq!(
21650 cast_scalar(&present, DType::Float64Nullable),
21651 Ok(Scalar::Float64(1.5))
21652 );
21653 assert_eq!(
21654 cast_scalar(&Scalar::Float64(1.5), DType::Float64),
21655 Ok(Scalar::Float64(1.5))
21656 );
21657 assert_eq!(
21659 cast_scalar(&Scalar::Int64(1), DType::Float64Nullable),
21660 Ok(Scalar::Float64(1.0))
21661 );
21662 assert_eq!(
21663 cast_scalar(&Scalar::Bool(true), DType::Float64Nullable),
21664 Ok(Scalar::Float64(1.0))
21665 );
21666
21667 assert_eq!(
21670 cast_scalar(&Scalar::Null(NullKind::NaN), DType::Float64Nullable),
21671 Ok(Scalar::Null(NullKind::Null)),
21672 "numpy NaN entering an extension lane becomes pd.NA"
21673 );
21674 assert_eq!(
21675 cast_scalar(&Scalar::Null(NullKind::Null), DType::Float64),
21676 Ok(Scalar::Null(NullKind::NaN)),
21677 "pd.NA entering a numpy lane becomes NaN"
21678 );
21679 }
21680
21681 #[test]
21691 fn int64nullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
21692 assert_eq!(
21693 common_dtype(DType::Int64Nullable, DType::Float64),
21694 Ok(DType::Float64Nullable)
21695 );
21696 assert_eq!(
21697 common_dtype(DType::Float64, DType::Int64Nullable),
21698 Ok(DType::Float64Nullable)
21699 );
21700 }
21701
21702 #[test]
21710 fn boolnullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
21711 assert_eq!(
21712 common_dtype(DType::BoolNullable, DType::Float64),
21713 Ok(DType::Float64Nullable)
21714 );
21715 assert_eq!(
21716 common_dtype(DType::Bool, DType::Float64),
21717 Ok(DType::Float64),
21718 "numpy bool + numpy float stays entirely on the numpy side"
21719 );
21720 }
21721
21722 #[test]
21733 fn the_nullable_float_flip_is_associative_on_its_witness_triple_qkqfb() {
21734 let (bn, i64n, f64d) = (DType::BoolNullable, DType::Int64, DType::Float64);
21735
21736 let left = common_dtype(
21737 common_dtype(bn.clone(), i64n.clone()).unwrap(),
21738 f64d.clone(),
21739 )
21740 .unwrap();
21741 let right = common_dtype(bn, common_dtype(i64n, f64d).unwrap()).unwrap();
21742
21743 assert_eq!(left, right, "promotion order must not change the result");
21744 assert_eq!(left, DType::Float64Nullable);
21745 }
21746}
21747
21748#[cfg(test)]
21753mod sparse_dtype_pandas_name_3gxc6 {
21754 use super::{DType, Scalar, SparseDType};
21755
21756 fn name(value_dtype: DType, fill: Scalar) -> String {
21757 SparseDType::new(value_dtype, fill)
21758 .expect("sparse descriptor")
21759 .pandas_name()
21760 }
21761
21762 #[test]
21765 fn int64_fill_zero_is_the_fixture_row() {
21766 assert_eq!(name(DType::Int64, Scalar::Int64(0)), "Sparse[int64, 0]");
21767 }
21768
21769 #[test]
21772 fn the_fill_value_is_actually_rendered() {
21773 assert_eq!(name(DType::Int64, Scalar::Int64(7)), "Sparse[int64, 7]");
21774 assert_ne!(
21775 name(DType::Int64, Scalar::Int64(0)),
21776 name(DType::Int64, Scalar::Int64(7)),
21777 "two different fills must not collapse to one name"
21778 );
21779 }
21780
21781 #[test]
21783 fn float64_nan_fill_is_lowercase_nan() {
21784 assert_eq!(
21785 name(DType::Float64, Scalar::Float64(f64::NAN)),
21786 "Sparse[float64, nan]"
21787 );
21788 }
21789
21790 #[test]
21793 fn float64_zero_fill_keeps_its_trailing_point_zero() {
21794 assert_eq!(
21795 name(DType::Float64, Scalar::Float64(0.0)),
21796 "Sparse[float64, 0.0]"
21797 );
21798 assert_ne!(
21799 name(DType::Float64, Scalar::Float64(0.0)),
21800 name(DType::Int64, Scalar::Int64(0)),
21801 "float64 and int64 zero fills are different dtypes"
21802 );
21803 }
21804
21805 #[test]
21807 fn bool_fill_uses_python_capitalisation() {
21808 assert_eq!(
21809 name(DType::Bool, Scalar::Bool(false)),
21810 "Sparse[bool, False]"
21811 );
21812 assert_eq!(name(DType::Bool, Scalar::Bool(true)), "Sparse[bool, True]");
21813 }
21814
21815 #[test]
21818 fn utf8_subtype_renders_as_object() {
21819 let rendered = name(DType::Utf8, Scalar::Null(crate::NullKind::NaN));
21820 assert!(
21821 rendered.starts_with("Sparse[object, "),
21822 "expected an object subtype, got {rendered}"
21823 );
21824 }
21825
21826 #[test]
21829 fn no_constructible_descriptor_renders_the_bare_name() {
21830 for (dtype, fill) in [
21831 (DType::Int64, Scalar::Int64(0)),
21832 (DType::Float64, Scalar::Float64(1.5)),
21833 (DType::Bool, Scalar::Bool(true)),
21834 (DType::Utf8, Scalar::Utf8("x".to_owned())),
21835 ] {
21836 let rendered = name(dtype.clone(), fill);
21837 assert_ne!(rendered, "Sparse", "bare name regressed for {dtype:?}");
21838 assert!(
21839 rendered.starts_with("Sparse[") && rendered.ends_with(']'),
21840 "malformed sparse name {rendered}"
21841 );
21842 }
21843 }
21844
21845 #[test]
21846 fn test_dtype_from_str_and_display() {
21847 use std::str::FromStr;
21848
21849 use crate::DType;
21850
21851 assert_eq!(DType::from_str("int64").unwrap(), DType::Int64);
21852 assert_eq!(DType::from_str("Int64").unwrap(), DType::Int64Nullable);
21853 assert_eq!(DType::from_str("float64").unwrap(), DType::Float64);
21854 assert_eq!(DType::from_str("Float64").unwrap(), DType::Float64Nullable);
21855 assert_eq!(DType::from_str("bool").unwrap(), DType::Bool);
21856 assert_eq!(DType::from_str("boolean").unwrap(), DType::BoolNullable);
21857 assert_eq!(DType::from_str("string").unwrap(), DType::Utf8);
21858 assert_eq!(DType::from_str("category").unwrap(), DType::Categorical);
21859 assert_eq!(
21860 DType::from_str("timedelta64[ns]").unwrap(),
21861 DType::Timedelta64
21862 );
21863 assert_eq!(
21864 DType::from_str("datetime64[ns]").unwrap(),
21865 DType::Datetime64 { tz: None }
21866 );
21867 assert_eq!(
21868 DType::from_str("datetime64[ns, UTC]").unwrap(),
21869 DType::Datetime64 {
21870 tz: Some("UTC".to_string())
21871 }
21872 );
21873 assert_eq!(DType::from_str("period").unwrap(), DType::Period);
21874 assert_eq!(DType::from_str("interval").unwrap(), DType::Interval);
21875 assert_eq!(DType::from_str("sparse").unwrap(), DType::Sparse);
21876
21877 assert_eq!(format!("{}", DType::Int64), "int64");
21878 assert_eq!(
21879 format!(
21880 "{}",
21881 DType::Datetime64 {
21882 tz: Some("UTC".to_string())
21883 }
21884 ),
21885 "datetime64[ns, UTC]"
21886 );
21887 }
21888
21889 #[test]
21890 fn test_api_types_inspection_and_infer_dtype() {
21891 use crate::{
21892 DType, Scalar,
21893 api::types::{
21894 infer_dtype, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype,
21895 is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_int64_dtype,
21896 is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_object_dtype,
21897 is_period_dtype, is_scalar, is_signed_integer_dtype, is_sparse, is_string_dtype,
21898 is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype,
21899 },
21900 };
21901
21902 assert!(is_numeric_dtype(&DType::Int64));
21903 assert!(is_numeric_dtype(&DType::Float64));
21904 assert!(!is_numeric_dtype(&DType::Utf8));
21905 assert!(!is_numeric_dtype(&DType::Bool));
21906
21907 assert!(is_integer_dtype(&DType::Int64));
21908 assert!(is_integer_dtype(&DType::Int64Nullable));
21909 assert!(!is_integer_dtype(&DType::Float64));
21910
21911 assert!(is_int64_dtype(&DType::Int64));
21912 assert!(is_int64_dtype(&DType::Int64Nullable));
21913 assert!(!is_int64_dtype(&DType::Float64));
21914
21915 assert!(is_object_dtype(&DType::Utf8));
21916 assert!(!is_object_dtype(&DType::Int64));
21917
21918 assert!(is_dtype_equal(&DType::Int64, &DType::Int64));
21919 assert!(is_dtype_equal(&"int64", &DType::Int64));
21920 assert!(!is_dtype_equal(&DType::Int64, &DType::Float64));
21921
21922 assert!(is_signed_integer_dtype(&DType::Int64));
21923 assert!(!is_unsigned_integer_dtype(&DType::Int64));
21924
21925 assert!(is_float_dtype(&DType::Float64));
21926 assert!(is_bool_dtype(&DType::Bool));
21927 assert!(is_string_dtype(&DType::Utf8));
21928 assert!(is_datetime64_any_dtype(&DType::Datetime64 { tz: None }));
21929 assert!(is_timedelta64_dtype(&DType::Timedelta64));
21930 assert!(is_categorical_dtype(&DType::Categorical));
21931 assert!(is_period_dtype(&DType::Period));
21932 assert!(is_interval_dtype(&DType::Interval));
21933 assert!(is_sparse(&DType::Sparse));
21934 assert!(is_extension_array_dtype(&DType::Categorical));
21935 assert!(is_scalar(&Scalar::Int64(42)));
21936
21937 assert_eq!(pandas_dtype("float64").unwrap(), DType::Float64);
21938 assert!(pandas_dtype("invalid_dtype_xyz").is_err());
21939
21940 let ints = vec![Scalar::Int64(1), Scalar::Int64(2)];
21941 assert_eq!(infer_dtype(&ints, true), "integer");
21942
21943 let floats = vec![Scalar::Float64(1.0), Scalar::Float64(2.5)];
21944 assert_eq!(infer_dtype(&floats, true), "floating");
21945
21946 let bools = vec![Scalar::Bool(true), Scalar::Bool(false)];
21947 assert_eq!(infer_dtype(&bools, true), "boolean");
21948
21949 let strings = vec![Scalar::Utf8("a".to_string()), Scalar::Utf8("b".to_string())];
21950 assert_eq!(infer_dtype(&strings, true), "string");
21951
21952 let mixed = vec![Scalar::Int64(1), Scalar::Utf8("a".to_string())];
21953 assert_eq!(infer_dtype(&mixed, true), "mixed");
21954
21955 assert_eq!(infer_dtype(&[], true), "empty");
21956 }
21957
21958 #[test]
21959 fn test_na_nat_sentinels_and_eng_float_format() {
21960 use super::{
21961 NA, NAT, NaT, eng_float_format, get_eng_float_format, reset_eng_float_format,
21962 set_eng_float_format,
21963 };
21964
21965 assert!(NA.is_null());
21967 assert!(NAT.is_null());
21968 assert_eq!(NAT, NaT);
21969 assert_eq!(format!("{NA}"), "None");
21970 assert_eq!(format!("{NAT}"), "NaT");
21971
21972 assert_eq!(eng_float_format(1000.0, Some(3), false), "1.000E+03");
21974 assert_eq!(eng_float_format(0.005, Some(3), false), "5.000E-03");
21975 assert_eq!(eng_float_format(1234567.0, Some(3), false), "1.235E+06");
21976 assert_eq!(eng_float_format(-9876.54, Some(3), false), "-9.877E+03");
21977 assert_eq!(eng_float_format(0.0, Some(3), false), "0.000E+00");
21978
21979 assert_eq!(eng_float_format(1000.0, Some(3), true), "1.000k");
21981 assert_eq!(eng_float_format(0.005, Some(3), true), "5.000m");
21982 assert_eq!(eng_float_format(1234567.0, Some(3), true), "1.235M");
21983 assert_eq!(eng_float_format(-9876.54, Some(3), true), "-9.877k");
21984 assert_eq!(eng_float_format(0.0, Some(3), true), "0.000");
21985 assert_eq!(eng_float_format(1.5, Some(3), true), "1.500");
21986
21987 assert_eq!(eng_float_format(f64::NAN, Some(3), true), "NaN");
21989 assert_eq!(eng_float_format(f64::INFINITY, Some(3), true), "inf");
21990 assert_eq!(eng_float_format(f64::NEG_INFINITY, Some(3), true), "-inf");
21991
21992 reset_eng_float_format();
21994 assert_eq!(get_eng_float_format(), None);
21995 set_eng_float_format(4, true);
21996 assert_eq!(get_eng_float_format(), Some((4, true)));
21997 reset_eng_float_format();
21998 assert_eq!(get_eng_float_format(), None);
21999 }
22000
22001 #[test]
22002 fn test_options_system() {
22003 use super::{
22004 OptionError, OptionValue, describe_option, get_option, option_context, reset_option,
22005 set_option,
22006 };
22007
22008 reset_option(None).unwrap();
22010
22011 let max_rows = get_option("display.max_rows").unwrap();
22013 assert_eq!(max_rows.as_int(), Some(60));
22014 assert_eq!(max_rows, OptionValue::Int(60));
22015 assert!(!max_rows.is_none());
22016
22017 let min_rows = get_option("min_rows").unwrap();
22019 assert_eq!(min_rows.as_int(), Some(10));
22020
22021 set_option("display.max_rows", 100).unwrap();
22023 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
22024
22025 set_option("mode.sim_interactive", true).unwrap();
22026 assert_eq!(
22027 get_option("mode.sim_interactive").unwrap().as_bool(),
22028 Some(true)
22029 );
22030
22031 set_option("mode.chained_assignment", "raise").unwrap();
22032 assert_eq!(
22033 get_option("mode.chained_assignment").unwrap().as_str(),
22034 Some("raise")
22035 );
22036
22037 assert!(matches!(
22039 get_option("nonexistent.option"),
22040 Err(OptionError::NotFound { .. })
22041 ));
22042 assert!(matches!(
22043 get_option("display"),
22044 Err(OptionError::Ambiguous { .. })
22045 ));
22046
22047 let desc = describe_option(Some("max_rows")).unwrap();
22049 assert!(desc.contains("display.max_rows : [currently: 100]"));
22050
22051 let desc_all = describe_option(None).unwrap();
22052 assert!(desc_all.contains("display.width"));
22053 assert!(desc_all.contains("compute.use_bottleneck"));
22054
22055 {
22057 let _guard = option_context(&[
22058 ("display.max_rows", OptionValue::Int(999)),
22059 ("display.precision", OptionValue::Int(2)),
22060 ])
22061 .unwrap();
22062
22063 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(999));
22064 assert_eq!(get_option("display.precision").unwrap().as_int(), Some(2));
22065 }
22066 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
22068 assert_eq!(get_option("display.precision").unwrap().as_int(), Some(6));
22069
22070 reset_option(Some("display.max_rows")).unwrap();
22072 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(60));
22073
22074 reset_option(Some("all")).unwrap();
22075 assert_eq!(
22076 get_option("mode.chained_assignment").unwrap().as_str(),
22077 Some("warn")
22078 );
22079
22080 assert_eq!(
22082 get_option("mode.copy_on_write").unwrap().as_bool(),
22083 Some(false)
22084 );
22085 assert_eq!(
22086 get_option("mode.data_manager").unwrap().as_str(),
22087 Some("block")
22088 );
22089 assert_eq!(
22090 get_option("display.large_repr").unwrap().as_str(),
22091 Some("truncate")
22092 );
22093 assert_eq!(
22094 get_option("display.max_info_columns").unwrap().as_int(),
22095 Some(100)
22096 );
22097 assert_eq!(
22098 get_option("display.memory_usage").unwrap().as_bool(),
22099 Some(true)
22100 );
22101 assert_eq!(
22102 get_option("display.colheader_justify").unwrap().as_str(),
22103 Some("right")
22104 );
22105 assert!(get_option("display.chop_threshold").unwrap().is_none());
22106 assert_eq!(
22107 get_option("io.parquet.engine").unwrap().as_str(),
22108 Some("auto")
22109 );
22110 assert_eq!(
22111 get_option("plotting.backend").unwrap().as_str(),
22112 Some("matplotlib")
22113 );
22114 assert_eq!(
22115 get_option("plotting.matplotlib.register_converters")
22116 .unwrap()
22117 .as_bool(),
22118 Some(true)
22119 );
22120
22121 set_option("display.chop_threshold", ()).unwrap();
22123 assert!(get_option("display.chop_threshold").unwrap().is_none());
22124 }
22125
22126 #[test]
22127 fn test_scalar_typed_accessors() {
22128 use super::{Interval, IntervalClosed, Period, PeriodFreq, Scalar};
22129
22130 let s_i64 = Scalar::Int64(42);
22131 assert_eq!(s_i64.as_i64(), Some(42));
22132 assert_eq!(s_i64.as_int(), Some(42));
22133 assert_eq!(s_i64.as_f64(), None);
22134 assert_eq!(s_i64.as_float(), None);
22135 assert_eq!(s_i64.as_bool(), None);
22136 assert_eq!(s_i64.as_str(), None);
22137
22138 let s_f64 = Scalar::Float64(2.75);
22139 assert_eq!(s_f64.as_f64(), Some(2.75));
22140 assert_eq!(s_f64.as_float(), Some(2.75));
22141 assert_eq!(s_f64.as_i64(), None);
22142 assert_eq!(s_f64.as_int(), None);
22143
22144 let s_bool = Scalar::Bool(true);
22145 assert_eq!(s_bool.as_bool(), Some(true));
22146 assert_eq!(s_bool.as_int(), None);
22147
22148 let s_str = Scalar::Utf8("pandas".to_string());
22149 assert_eq!(s_str.as_str(), Some("pandas"));
22150 assert_eq!(s_str.as_bool(), None);
22151
22152 let s_dt = Scalar::Datetime64(1_000_000_000);
22153 assert_eq!(s_dt.as_datetime_nanos(), Some(1_000_000_000));
22154 assert_eq!(s_dt.as_str(), None);
22155
22156 let s_td = Scalar::Timedelta64(500_000);
22157 assert_eq!(s_td.as_timedelta_nanos(), Some(500_000));
22158 assert_eq!(s_td.as_int(), None);
22159
22160 let s_per = Scalar::Period(Period::new(2024, PeriodFreq::Daily));
22161 assert_eq!(s_per.as_period_ordinal(), Some(2024));
22162
22163 let s_iv = Scalar::Interval(Interval::new(0.0, 10.0, IntervalClosed::Both));
22164 assert_eq!(
22165 s_iv.as_interval(),
22166 Some(Interval::new(0.0, 10.0, IntervalClosed::Both))
22167 );
22168 }
22169
22170 #[test]
22171 fn test_api_submodules_and_types_inspectors() {
22172 use super::{
22173 DType, Scalar,
22174 api::{extensions, indexers, types},
22175 };
22176
22177 assert!(types::is_number(&Scalar::Int64(42)));
22179 assert!(types::is_number(&Scalar::Float64(42.5)));
22180 assert!(types::is_number(&Scalar::Bool(true)));
22181 assert!(!types::is_number(&Scalar::Utf8("pandas".into())));
22182
22183 assert!(types::is_bool(&Scalar::Bool(false)));
22184 assert!(!types::is_bool(&Scalar::Int64(0)));
22185
22186 assert!(types::is_integer(&Scalar::Int64(10)));
22187 assert!(!types::is_integer(&Scalar::Float64(10.0)));
22188
22189 assert!(types::is_float(&Scalar::Float64(10.0)));
22190 assert!(!types::is_float(&Scalar::Int64(10)));
22191
22192 assert!(types::is_float64_dtype(&DType::Float64));
22194 assert!(types::is_float64_dtype(&DType::Float64Nullable));
22195 assert!(!types::is_float64_dtype(&DType::Int64));
22196 assert!(!types::is_int32_dtype(&DType::Int64));
22197
22198 extensions::register_dataframe_accessor("geo");
22200 extensions::register_series_accessor("geo");
22201 extensions::register_index_accessor("geo");
22202
22203 let base = indexers::BaseIndexer::new(5, 1);
22205 assert_eq!(base.window_size, 5);
22206 assert_eq!(base.step, 1);
22207
22208 let fwd = indexers::FixedForwardWindowIndexer::new(3);
22209 assert_eq!(fwd.window_size, 3);
22210
22211 let var = indexers::VariableOffsetWindowIndexer::new(100);
22212 assert_eq!(var.index_offset, 100);
22213 }
22214
22215 #[test]
22216 fn test_extension_dtypes_and_parameterized_parsing() {
22217 use super::{
22218 AsDType, CategoricalDtype, DType, IntervalClosed, IntervalDtype, PeriodDtype, Scalar,
22219 SparseDType, api::types, pandas_dtype,
22220 };
22221
22222 let cat_default = CategoricalDtype::default();
22224 assert_eq!(cat_default.name(), "category");
22225 assert_eq!(cat_default.kind(), "O");
22226 assert!(!cat_default.ordered());
22227 assert_eq!(cat_default.categories(), None);
22228 assert_eq!(cat_default.as_dtype(), DType::Categorical);
22229 assert!(types::is_categorical_dtype(&cat_default));
22230 assert_eq!(
22231 cat_default.to_string(),
22232 "CategoricalDtype(categories=None, ordered=False)"
22233 );
22234
22235 let cat_custom =
22236 CategoricalDtype::new(Some(vec!["low".to_string(), "high".to_string()]), true);
22237 assert!(cat_custom.ordered());
22238 assert_eq!(
22239 cat_custom.categories(),
22240 Some(&["low".to_string(), "high".to_string()][..])
22241 );
22242 assert!(cat_custom.to_string().contains("ordered=True"));
22243
22244 let per_default = PeriodDtype::default();
22246 assert_eq!(per_default.freq(), "D");
22247 assert_eq!(per_default.name(), "period[D]");
22248 assert_eq!(per_default.kind(), "O");
22249 assert_eq!(per_default.as_dtype(), DType::Period);
22250 assert!(types::is_period_dtype(&per_default));
22251 assert_eq!(per_default.to_string(), "period[D]");
22252
22253 let per_custom = PeriodDtype::new("M");
22254 assert_eq!(per_custom.freq(), "M");
22255 assert_eq!(per_custom.to_string(), "period[M]");
22256
22257 let int_default = IntervalDtype::default();
22259 assert_eq!(*int_default.subtype(), DType::Float64);
22260 assert_eq!(int_default.closed(), Some(IntervalClosed::Right));
22261 assert_eq!(int_default.name(), "interval");
22262 assert_eq!(int_default.kind(), "O");
22263 assert_eq!(int_default.as_dtype(), DType::Interval);
22264 assert!(types::is_interval_dtype(&int_default));
22265 assert_eq!(int_default.to_string(), "interval[float64, right]");
22266
22267 let int_custom = IntervalDtype::new(DType::Int64, Some(IntervalClosed::Both));
22268 assert_eq!(*int_custom.subtype(), DType::Int64);
22269 assert_eq!(int_custom.closed(), Some(IntervalClosed::Both));
22270 assert_eq!(int_custom.to_string(), "interval[int64, both]");
22271
22272 let sp = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).unwrap();
22274 assert_eq!(sp.as_dtype(), DType::Sparse);
22275 assert!(types::is_sparse(&sp));
22276
22277 assert_eq!(pandas_dtype("period[D]").unwrap(), DType::Period);
22279 assert_eq!(pandas_dtype("Period[M]").unwrap(), DType::Period);
22280 assert_eq!(pandas_dtype("interval[float64]").unwrap(), DType::Interval);
22281 assert_eq!(pandas_dtype("Interval[int64]").unwrap(), DType::Interval);
22282 assert_eq!(pandas_dtype("sparse[float64]").unwrap(), DType::Sparse);
22283 assert_eq!(pandas_dtype("Sparse[int64, 0]").unwrap(), DType::Sparse);
22284 }
22285}
22286
22287#[cfg(test)]
22290mod numeric_width_fvsao23 {
22291 use super::{DType, NumericWidth, NumpyNumeric, numpy_pairwise_sum};
22292
22293 #[test]
22294 fn float32_sum_is_numpys_pairwise_sum_bit_for_bit() {
22295 let cases: [(usize, u32); 5] = [
22299 (5, 1_083_829_126),
22300 (64, 1_136_679_190),
22301 (129, 1_145_981_108),
22302 (1000, 1_170_926_592),
22303 (4097, 1_188_011_795),
22304 ];
22305 for (n, bits) in cases {
22306 #[allow(clippy::cast_precision_loss)] let values: Vec<f32> = (0..n)
22308 .map(|k| ((k * 37) % 1000) as f32 * 0.013_f32)
22309 .collect();
22310 assert_eq!(numpy_pairwise_sum(&values).to_bits(), bits, "n={n}");
22311 if n < 100 {
22312 #[allow(clippy::cast_possible_truncation)]
22313 let rounded_once = values.iter().map(|&v| f64::from(v)).sum::<f64>() as f32;
22314 assert_ne!(rounded_once.to_bits(), bits, "n={n}");
22315 }
22316 }
22317 assert_eq!(numpy_pairwise_sum::<f32>(&[]), 0.0);
22318 }
22319
22320 #[test]
22321 fn names_parse_and_round_trip() {
22322 for width in NumericWidth::ALL {
22323 for nullable in [false, true] {
22324 assert_eq!(
22325 NumericWidth::parse(width.name(nullable)),
22326 Some((width, nullable))
22327 );
22328 }
22329 }
22330 for (name, expected) in [
22331 ("<i4", (NumericWidth::Int32, false)),
22332 ("f4", (NumericWidth::Float32, false)),
22333 ("UInt8Dtype", (NumericWidth::UInt8, true)),
22334 ] {
22335 assert_eq!(NumericWidth::parse(name), Some(expected), "{name}");
22336 }
22337 for name in ["int64", "Int64", "float64", "i8", "f8", "int", "float"] {
22339 assert_eq!(NumericWidth::parse(name), None, "{name}");
22340 }
22341 }
22342
22343 #[test]
22344 fn wrapping_is_numpys_modular_cast_not_saturation() {
22345 assert_eq!(NumericWidth::Int8.wrap_int(300), Some(44));
22347 assert_eq!(NumericWidth::UInt8.wrap_int(-5), Some(251));
22349 assert_eq!(NumericWidth::UInt16.wrap_int(-5), Some(65531));
22350 assert_eq!(NumericWidth::UInt32.wrap_int(-5), Some(4_294_967_291));
22351 assert_eq!(NumericWidth::Int8.wrap_int(200), Some(-56));
22353 assert_eq!(
22354 NumericWidth::Int32.wrap_int(i64::from(i32::MAX) + 1),
22355 Some(i64::from(i32::MIN))
22356 );
22357 let product = 50_000_i64.wrapping_pow(5);
22359 assert_eq!(
22360 NumericWidth::Int32.wrap_int(product),
22361 Some(i64::from(50_000_i32.wrapping_pow(5)))
22362 );
22363 assert_eq!(NumericWidth::UInt64.wrap_int(-1), None);
22365 assert_eq!(NumericWidth::UInt64.wrap_int(7), Some(7));
22366 assert_eq!(NumericWidth::Float32.wrap_int(1), None);
22367 assert!(NumericWidth::Int8.holds_int(-128) && !NumericWidth::Int8.holds_int(128));
22368 }
22369
22370 #[test]
22371 fn float32_rounding_is_to_nearest_not_truncation() {
22372 assert_eq!(NumericWidth::round_f32(0.1), 0.100_000_001_490_116_12);
22374 let sum =
22377 NumericWidth::round_f32(NumericWidth::round_f32(0.1) + NumericWidth::round_f32(0.2));
22378 assert_eq!(sum, 0.300_000_011_920_928_96);
22379 assert_eq!(NumericWidth::round_f32(1.0 + 2f64.powi(-24)), 1.0);
22382 let above_tie = 1.0 + 3.0 * 2f64.powi(-25);
22383 assert_eq!(NumericWidth::round_f32(above_tie), 1.0 + 2f64.powi(-23));
22384 assert!(NumericWidth::round_f32(f64::NAN).is_nan());
22385 assert_eq!(NumericWidth::round_f32(1e300), f64::INFINITY);
22386 }
22387
22388 #[test]
22389 fn result_type_matches_numpy_promotion() {
22390 use NumpyNumeric::{Bool, Float, Int, UInt};
22391 let cases = [
22392 (Int(32), Int(64), Int(64)), (Int(8), UInt(8), Int(16)), (Int(16), UInt(8), Int(16)),
22395 (Int(8), UInt(16), Int(32)),
22396 (Int(32), UInt(32), Int(64)),
22397 (Int(64), UInt(64), Float(64)), (UInt(8), UInt(32), UInt(32)),
22399 (Float(32), Int(8), Float(32)), (Float(32), UInt(16), Float(32)),
22401 (Float(32), Int(32), Float(64)), (Float(32), Float(64), Float(64)),
22403 (Bool, Int(8), Int(8)),
22404 (Bool, Float(32), Float(32)),
22405 ];
22406 for (a, b, expected) in cases {
22407 assert_eq!(a.result_type(b), expected, "{a:?} {b:?}");
22408 assert_eq!(b.result_type(a), expected, "{b:?} {a:?}");
22409 }
22410 assert_eq!(Int(32).with_python_int(), Int(32));
22413 assert_eq!(Int(32).with_python_float(), Float(64));
22414 assert_eq!(Float(32).with_python_float(), Float(32));
22415 assert_eq!(Bool.with_python_int(), Int(64));
22416 }
22417
22418 #[test]
22419 fn columns_map_to_numpy_dtypes() {
22420 let cases = [
22421 (DType::Int64, None, Some(NumpyNumeric::Int(64))),
22422 (
22423 DType::Int64Nullable,
22424 Some(NumericWidth::UInt8),
22425 Some(NumpyNumeric::UInt(8)),
22426 ),
22427 (
22428 DType::Float64,
22429 Some(NumericWidth::Float32),
22430 Some(NumpyNumeric::Float(32)),
22431 ),
22432 (DType::Float64, Some(NumericWidth::Int8), None),
22434 (DType::Utf8, None, None),
22435 ];
22436 for (dtype, width, expected) in cases {
22437 assert_eq!(NumpyNumeric::of(&dtype, width), expected, "{dtype:?}");
22438 }
22439 for width in NumericWidth::ALL {
22440 assert_eq!(NumpyNumeric::of_width(width).width(), Some(width));
22441 assert!(width.fits_storage(&width.storage(false)));
22442 assert!(width.fits_storage(&width.storage(true)));
22443 }
22444 assert_eq!(NumpyNumeric::Int(64).width(), None);
22445 }
22446
22447 #[test]
22448 fn downcast_and_category_code_widths() {
22449 let int32_max_plus_one = i64::from(i32::MAX) + 1;
22452 let signed = [
22453 ((1, 2), Some(NumericWidth::Int8)),
22454 ((1, 300), Some(NumericWidth::Int16)),
22455 ((0, int32_max_plus_one), None),
22456 ];
22457 for ((low, high), expected) in signed {
22458 assert_eq!(NumericWidth::smallest_signed(low, high), expected);
22459 }
22460 let unsigned = [((1, 300), Some(NumericWidth::UInt16)), ((-1, 3), None)];
22461 for ((low, high), expected) in unsigned {
22462 assert_eq!(NumericWidth::smallest_unsigned(low, high), expected);
22463 }
22464 for (categories, expected) in [
22466 (2, NumericWidth::Int8),
22467 (126, NumericWidth::Int8),
22468 (127, NumericWidth::Int16),
22469 (200, NumericWidth::Int16),
22470 ] {
22471 assert_eq!(NumericWidth::for_category_codes(categories), Some(expected));
22472 }
22473 assert_eq!(NumericWidth::itemsize(NumericWidth::Int8), 1);
22474 assert_eq!(NumericWidth::Float32.itemsize(), 4);
22475 }
22476}
22477
22478#[cfg(test)]
22483mod pandas_reductions_9iim6 {
22484 use super::{MissingLayout, PandasReductions, ReductionValues};
22485
22486 #[allow(clippy::cast_precision_loss)] fn floats(n: usize) -> (Vec<f64>, Vec<u64>) {
22490 let mut present = vec![0_u64; n.div_ceil(64)];
22491 let values = (0..n)
22492 .map(|k| {
22493 if k % 11 != 3 {
22494 present[k / 64] |= 1 << (k % 64);
22495 }
22496 let base = ((k * 7919 + 13) % 100_003) as f64 / 7.0 - 7000.0;
22497 if k % 5 == 0 { base * 1e6 } else { base }
22498 })
22499 .collect();
22500 (values, present)
22501 }
22502
22503 fn ints(n: usize) -> Vec<i64> {
22505 (0..n)
22506 .map(|k| i64::try_from((k * 7919 + 13) % 100_003).unwrap() * 3_000_000_007)
22507 .collect()
22508 }
22509
22510 fn assert_bits(got: &[f64], expected: &[u64], case: &str) {
22511 let got: Vec<u64> = got.iter().map(|value| value.to_bits()).collect();
22512 assert_eq!(got, expected, "{case}");
22513 }
22514
22515 #[test]
22516 fn numpy_float64_with_nan_matches_pandas_bits() {
22517 let cases: [(usize, [u64; 7]); 7] = [
22519 (
22520 7,
22521 [
22522 0xc1ff_1185_2dcb_6db6,
22523 0xc1d4_b658_c932_4924,
22524 0x43db_301d_4a8d_87a3,
22525 0x41e4_db58_e2f1_458e,
22526 0x41d1_078f_09d3_9c5c,
22527 0xc002_1f47_ceae_1b43,
22528 0x4014_c8bc_93df_56e6,
22529 ],
22530 ),
22531 (
22532 8,
22533 [
22534 0xc1ff_1184_f43d_b6da,
22535 0xc1d1_c0de_426c_687d,
22536 0x43d7_9d3c_ecd2_da2b,
22537 0x41e3_7012_7d6c_71a5,
22538 0x41cd_631d_3379_9929,
22539 0xc003_b196_82f9_28dc,
22540 0x4018_9de2_eba9_5ecc,
22541 ],
22542 ),
22543 (
22544 127,
22545 [
22546 0x4200_324e_3389_2490,
22547 0x4192_0704_ad1e_360d,
22548 0x43c9_4a6b_3390_577d,
22549 0x41dc_72bf_d6fa_9808,
22550 0x41a5_38f5_8417_ae1e,
22551 0x3fd0_b6bf_045c_e4d5,
22552 0x4017_1585_bf13_21c4,
22553 ],
22554 ),
22555 (
22556 128,
22557 [
22558 0x4200_324d_7236_db6e,
22559 0x4191_df3a_f99d_a2ae,
22560 0x43c9_1234_ffb7_4a93,
22561 0x41dc_5310_c97c_292c,
22562 0x41a5_09f4_cfcf_9206,
22563 0x3fd0_d9df_0d68_00b0,
22564 0x4017_61b6_5653_ae82,
22565 ],
22566 ),
22567 (
22568 129,
22569 [
22570 0x4200_324c_d43e_db71,
22571 0x4191_b81f_8a1d_61da,
22572 0x43c8_daf6_85d3_386f,
22573 0x41dc_33ca_af49_8c24,
22574 0x41a4_dbc2_8609_a567,
22575 0x3fd0_fcc5_39d9_6901,
22576 0x4017_ade4_7855_7c25,
22577 ],
22578 ),
22579 (
22580 1000,
22581 [
22582 0x421a_d4f6_8061_248e,
22583 0x417e_39f9_3e1a_a248,
22584 0x43c7_9481_cba1_263b,
22585 0x41db_7825_28c0_37cc,
22586 0x418d_27ba_a0ea_2f9a,
22587 0x3fc8_e53a_e277_3d7f,
22588 0x4018_3c97_3603_dfd0,
22589 ],
22590 ),
22591 (
22592 100_000,
22593 [
22594 0x4283_088c_316e_46dc,
22595 0x417b_7135_0c27_1185,
22596 0x43c7_a0de_3b8e_ea34,
22597 0x41db_7f57_6673_8d6b,
22598 0x4157_58cc_33fd_4ae6,
22599 0x3fc7_f1cf_b14a_14c8,
22600 0x4018_06b5_f26a_c384,
22601 ],
22602 ),
22603 ];
22604 let all = |r: &PandasReductions<'_>| {
22605 [
22606 r.sum(),
22607 r.mean(),
22608 r.var(1),
22609 r.std(1),
22610 r.sem(1),
22611 r.skew(),
22612 r.kurt(),
22613 ]
22614 };
22615 for (n, expected) in cases {
22616 let (values, present) = floats(n);
22617 let r = PandasReductions::new(
22618 ReductionValues::Float(&values),
22619 Some(&present),
22620 MissingLayout::Numpy,
22621 );
22622 assert_bits(&all(&r), &expected, &format!("float64 n={n}"));
22623 let with_nan: Vec<f64> = values
22626 .iter()
22627 .enumerate()
22628 .map(|(k, &value)| if k % 11 == 3 { f64::NAN } else { value })
22629 .collect();
22630 let r = PandasReductions::numpy_nan_missing(ReductionValues::Float(&with_nan));
22631 assert_bits(&all(&r), &expected, &format!("float64 NaN n={n}"));
22632 let (head, tail) = with_nan.split_at(n / 3);
22633 let chunks = [head, tail];
22634 let r = PandasReductions::numpy_nan_missing(ReductionValues::FloatChunks(&chunks));
22635 assert_bits(&all(&r), &expected, &format!("float64 NaN chunks n={n}"));
22636 }
22637 let (values, present) = floats(100_000);
22639 let left_fold: f64 = values
22640 .iter()
22641 .enumerate()
22642 .filter(|&(k, _)| present[k / 64] >> (k % 64) & 1 == 1)
22643 .map(|(_, value)| value)
22644 .sum();
22645 assert_ne!(left_fold.to_bits(), 0x4283_088c_316e_46dc);
22646 }
22647
22648 #[test]
22649 fn numpy_int64_mean_sums_through_the_cast_buffer() {
22650 let cases: [(usize, [u64; 5]); 3] = [
22652 (
22653 129,
22654 [
22655 0x42e0_dda2_9987_3f9e,
22656 0x45b9_0e2a_887d_aeda,
22657 0x429c_34a1_c273_372f,
22658 0x3f95_9e9d_c69e_ec88,
22659 0xbff3_844b_ba13_eac1,
22660 ],
22661 ),
22662 (
22663 8193,
22664 [
22665 0x42e1_0d5b_e407_5aa7,
22666 0x45b8_3bf5_04f5_f2fc,
22667 0x426b_d893_c5c9_85b1,
22668 0x3f42_7452_ff15_86c7,
22669 0xbff3_318c_611b_b59c,
22670 ],
22671 ),
22672 (
22673 20_000,
22674 [
22675 0x42e1_0d17_ebf8_272d,
22676 0x45b8_3c24_c921_82b6,
22677 0x4261_d2a2_f139_68e2,
22678 0x3f31_a21c_d4bb_ff52,
22679 0xbff3_328c_4edc_26ee,
22680 ],
22681 ),
22682 ];
22683 for (n, expected) in cases {
22684 let values = ints(n);
22685 let r =
22686 PandasReductions::new(ReductionValues::Int(&values), None, MissingLayout::Numpy);
22687 let got = [r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()];
22688 assert_bits(&got, &expected, &format!("int64 n={n}"));
22689 let (head, tail) = values.split_at(n / 3);
22691 let (middle, rest) = tail.split_at(1);
22692 let chunks = [head, middle, &[][..], rest];
22693 let chunked = PandasReductions::new(
22694 ReductionValues::IntChunks(&chunks),
22695 None,
22696 MissingLayout::Numpy,
22697 );
22698 let got = [
22699 chunked.mean(),
22700 chunked.var(1),
22701 chunked.sem(1),
22702 chunked.skew(),
22703 chunked.kurt(),
22704 ];
22705 assert_bits(&got, &expected, &format!("int64 chunks n={n}"));
22706 }
22707 }
22708
22709 #[test]
22710 fn masked_columns_add_runs_of_present_values() {
22711 let cases: [(usize, [u64; 4]); 3] = [
22715 (
22716 129,
22717 [
22718 0x4200_324c_d43e_db6e,
22719 0x4191_b81f_8a1d_61d6,
22720 0x43c8_daf6_85d3_3872,
22721 0x41a4_dbc2_8609_a567,
22722 ],
22723 ),
22724 (
22725 1000,
22726 [
22727 0x421a_d4f6_8061_2492,
22728 0x417e_39f9_3e1a_a24c,
22729 0x43c7_9481_cba1_263a,
22730 0x418d_27ba_a0ea_2f9a,
22731 ],
22732 ),
22733 (
22734 100_000,
22735 [
22736 0x4283_088c_316e_46de,
22737 0x417b_7135_0c27_1188,
22738 0x43c7_a0de_3b8e_ea37,
22739 0x4157_58cc_33fd_4ae6,
22740 ],
22741 ),
22742 ];
22743 for (n, expected) in cases {
22744 let (values, present) = floats(n);
22745 let r = PandasReductions::new(
22746 ReductionValues::Float(&values),
22747 Some(&present),
22748 MissingLayout::Masked,
22749 );
22750 assert_bits(
22751 &[r.sum(), r.mean(), r.var(1), r.sem(1)],
22752 &expected,
22753 &format!("Float64 n={n}"),
22754 );
22755 let (head, tail) = values.split_at(n / 2 + 1);
22756 let chunks = [head, tail];
22757 let chunked = PandasReductions::new(
22758 ReductionValues::FloatChunks(&chunks),
22759 Some(&present),
22760 MissingLayout::Masked,
22761 );
22762 let got = [
22763 chunked.sum(),
22764 chunked.mean(),
22765 chunked.var(1),
22766 chunked.sem(1),
22767 ];
22768 assert_bits(&got, &expected, &format!("Float64 chunks n={n}"));
22769 }
22770 for (n, expected) in [
22773 (8193, [0x42e1_0f35_29c2_807b_u64, 0x45b8_39ed_8746_bdcc]),
22774 (20_000, [0x42e1_0cf2_cc56_752a, 0x45b8_3c63_72fc_fad5]),
22775 ] {
22776 let values = ints(n);
22777 let mut present = vec![0_u64; n.div_ceil(64)];
22778 for k in (0..n).filter(|k| k % 997 != 5) {
22779 present[k / 64] |= 1 << (k % 64);
22780 }
22781 let r = PandasReductions::new(
22782 ReductionValues::Int(&values),
22783 Some(&present),
22784 MissingLayout::Masked,
22785 );
22786 assert_bits(&[r.mean(), r.var(1)], &expected, &format!("Int64 n={n}"));
22787 }
22788 }
22789
22790 #[test]
22791 fn edge_cases_match_pandas() {
22792 let reductions = |values: &[f64], present: Option<&[u64]>| {
22793 let r = PandasReductions::new(
22794 ReductionValues::Float(values),
22795 present,
22796 MissingLayout::Numpy,
22797 );
22798 [r.sum(), r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()]
22799 };
22800 let constant = reductions(&[1.5; 10], None);
22803 assert_eq!(constant, [15.0, 1.5, 0.0, 0.0, 0.0, 0.0]);
22804 assert!(reductions(&[2.0; 3], None)[5].is_nan());
22805 assert!(reductions(&[1.0, 2.0], None)[4].is_nan());
22807 assert_eq!(
22808 reductions(&[1.0, 2.0, 4.0], None)[4],
22809 0.935_219_529_582_823_7
22810 );
22811 let empty = reductions(&[], None);
22813 assert_eq!(empty[0], 0.0);
22814 assert!(empty[1..].iter().all(|value| value.is_nan()));
22815 let all_missing = reductions(&[3.0; 5], Some(&[0]));
22816 assert_eq!(all_missing[0], 0.0);
22817 assert!(all_missing[1].is_nan());
22818 assert_eq!(
22820 reductions(&[-0.0; 10], None)[0].to_bits(),
22821 0.0_f64.to_bits()
22822 );
22823 let inf = reductions(&[1.0, f64::INFINITY, 2.0, 5.0], None);
22825 assert_eq!(inf[0], f64::INFINITY);
22826 assert!(inf[2..].iter().all(|value| value.is_nan()));
22827 }
22828}
22829
22830#[cfg(test)]
22834mod pandas_decimal_py3c0 {
22835 use super::{PandasDecimal, pandas_decimal_to_f64, pandas_int_to_f64};
22836
22837 fn bits(token: &str) -> u64 {
22838 match pandas_decimal_to_f64(token.as_bytes()) {
22839 PandasDecimal::Value(value) => value.to_bits(),
22840 other => panic!("{token:?}: {other:?}"),
22841 }
22842 }
22843
22844 #[test]
22845 fn tokens_convert_to_pandas_bits() {
22846 let cases = [
22847 ("9.890295358649789", 0x4023_c7d4_cb12_5ce4),
22848 ("0.8690736625851781286570704999", 0x3feb_cf73_91d3_c8f1),
22849 ("0.000000068288360759838675650889", 0x3e72_54bd_8bcd_610b),
22850 ("-0.0080749473608410608782560", 0xbf80_8999_16a7_63f3),
22851 ("99999999999999999", 0x4376_3457_85d8_a001),
22852 ("1234567890123456789012345", 0x44f0_56e0_f36a_6444),
22853 ("00000000000000000.5", 0x0000_0000_0000_0000),
22855 ("-00000000000000000.5", 0x8000_0000_0000_0000),
22856 ("1.5E+10", 0x420b_f08e_b000_0000),
22857 ("-.5e-3", 0xbf40_624d_d2f1_a9fc),
22858 ("5.", 0x4014_0000_0000_0000),
22859 ("1e-320", 0x0000_0000_0000_07e8),
22860 ("2.5e-310", 0x0000_2e05_5c9a_3f6c),
22861 ("-1e-400", 0x8000_0000_0000_0000),
22862 ("-1e-700", 0x0000_0000_0000_0000),
22864 ("1e-4294967296", 0x3ff0_0000_0000_0000),
22866 ("1.7976931348623157e308", 0x7fef_ffff_ffff_ffff),
22867 ("0.001e310", 0x7fac_7b1f_3cac_7433),
22868 ];
22869 for (token, expected) in cases {
22870 assert_eq!(bits(token), expected, "{token:?}");
22871 }
22872 let correctly_rounded: f64 = "9.890295358649789".parse().unwrap();
22874 assert_ne!(correctly_rounded.to_bits(), 0x4023_c7d4_cb12_5ce4);
22875 }
22876
22877 #[test]
22878 fn what_pandas_does_not_read_as_a_float() {
22879 for token in [
22880 "1e309",
22881 "0e400",
22882 "1.8e308",
22883 "1e+0000000000000000001",
22884 "1e-2147483649",
22885 "1e",
22886 "1e+",
22887 "1.5d3",
22888 "0x10",
22889 "1_000.5",
22890 "1..5",
22891 ] {
22892 assert_eq!(
22893 pandas_decimal_to_f64(token.as_bytes()),
22894 PandasDecimal::Rejected,
22895 "{token:?}"
22896 );
22897 }
22898 for token in ["inf", "-Infinity", "nan", ".", "-", "e5", "+.e1", "--1", ""] {
22899 assert_eq!(
22900 pandas_decimal_to_f64(token.as_bytes()),
22901 PandasDecimal::NotDecimal,
22902 "{token:?}"
22903 );
22904 }
22905 }
22906
22907 #[test]
22908 fn an_integer_in_a_float_column_takes_the_same_conversion() {
22909 assert_eq!(pandas_int_to_f64(-42).to_bits(), (-42.0_f64).to_bits());
22910 assert_eq!(
22911 pandas_int_to_f64(99_999_999_999_999_999).to_bits(),
22912 0x4376_3457_85d8_a001
22913 );
22914 assert_eq!(
22915 pandas_int_to_f64(-99_999_999_999_999_999).to_bits(),
22916 0xc376_3457_85d8_a001
22917 );
22918 }
22919}