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]
1260 #[allow(clippy::cast_precision_loss)] pub fn int64_mean_skipping(values: &[i64], missing: i64) -> f64 {
1262 let count = values.iter().filter(|&&value| value != missing).count();
1263 if count == 0 {
1264 return f64::NAN;
1265 }
1266 let mut total = 0.0;
1267 for chunk in values.chunks(NUMPY_CAST_BUFFER) {
1268 let fill = |start: usize, block: &mut [f64]| {
1269 for (slot, &value) in block.iter_mut().zip(&chunk[start..]) {
1270 *slot = if value == missing { 0.0 } else { value as f64 };
1271 }
1272 };
1273 total += numpy_pairwise_sum_by(chunk.len(), &fill);
1274 }
1275 total / count as f64
1276 }
1277
1278 #[must_use]
1280 #[allow(clippy::cast_precision_loss)] pub fn var(&self, ddof: usize) -> f64 {
1282 if self.count <= ddof {
1283 return f64::NAN;
1284 }
1285 let total = if self.layout == MissingLayout::Masked {
1288 self.mean_total()
1289 } else {
1290 self.total(false)
1291 };
1292 let mean = total / self.count as f64;
1293 let squares = self.add_reduce(
1294 |value| {
1295 let deviation = mean - value;
1296 deviation * deviation
1297 },
1298 false,
1299 );
1300 squares / (self.count - ddof) as f64
1301 }
1302
1303 #[must_use]
1305 pub fn std(&self, ddof: usize) -> f64 {
1306 self.var(ddof).sqrt()
1307 }
1308
1309 fn as_numpy(&self) -> Self {
1312 Self {
1313 layout: MissingLayout::Numpy,
1314 ..*self
1315 }
1316 }
1317
1318 #[must_use]
1320 #[allow(clippy::cast_precision_loss)] pub fn sem(&self, ddof: usize) -> f64 {
1322 self.as_numpy().var(ddof).sqrt() / (self.count as f64).sqrt()
1323 }
1324
1325 #[allow(clippy::cast_precision_loss)] fn central_moments(&self, fourth: bool) -> (f64, f64) {
1328 let numpy = self.as_numpy();
1329 let mean = numpy.total(false) / self.count as f64;
1330 let SumPair(m2, higher) = numpy.add_reduce(
1332 |value| {
1333 let deviation = value - mean;
1334 let square = deviation * deviation;
1335 let higher = if fourth {
1336 square * square
1337 } else {
1338 square * deviation
1339 };
1340 SumPair(square, higher)
1341 },
1342 false,
1343 );
1344 (m2, higher)
1345 }
1346
1347 #[must_use]
1350 #[allow(clippy::cast_precision_loss)] pub fn skew(&self) -> f64 {
1352 if self.count < 3 {
1353 return f64::NAN;
1354 }
1355 let (m2, m3) = self.central_moments(false);
1356 let (m2, m3) = (zero_out_fperr(m2), zero_out_fperr(m3));
1357 if m2 == 0.0 {
1358 return 0.0;
1359 }
1360 let count = self.count as f64;
1361 let half = std::hint::black_box(0.5);
1364 (count * (count - 1.0).powf(half) / (count - 2.0)) * (m3 / m2.powf(1.5))
1365 }
1366
1367 #[must_use]
1370 #[allow(clippy::cast_precision_loss)] pub fn kurt(&self) -> f64 {
1372 if self.count < 4 {
1373 return f64::NAN;
1374 }
1375 let (m2, m4) = self.central_moments(true);
1376 let count = self.count as f64;
1377 let numerator = zero_out_fperr(count * (count + 1.0) * (count - 1.0) * m4);
1378 let denominator = zero_out_fperr((count - 2.0) * (count - 3.0) * (m2 * m2));
1379 if denominator == 0.0 {
1380 return 0.0;
1381 }
1382 let adjustment = 3.0 * ((count - 1.0) * (count - 1.0)) / ((count - 2.0) * (count - 3.0));
1383 numerator / denominator - adjustment
1384 }
1385}
1386
1387#[derive(Debug, Clone, Copy, Default)]
1390struct SumPair<A, B = A>(A, B);
1391
1392impl<A: std::ops::Add<Output = A>, B: std::ops::Add<Output = B>> std::ops::Add for SumPair<A, B> {
1393 type Output = Self;
1394
1395 fn add(self, other: Self) -> Self {
1396 Self(self.0 + other.0, self.1 + other.1)
1397 }
1398}
1399
1400#[must_use]
1409pub const fn spread_float_bits(bits: u64) -> u64 {
1410 bits ^ (bits >> 32)
1411}
1412
1413fn zero_out_fperr(value: f64) -> f64 {
1415 if value.abs() < 1e-14 { 0.0 } else { value }
1416}
1417
1418#[derive(Debug, Clone, Copy, PartialEq)]
1422pub enum PandasDecimal {
1423 Value(f64),
1425 Rejected,
1429 NotDecimal,
1432}
1433
1434const PANDAS_DECIMAL_DIGITS: usize = 17;
1437
1438#[derive(Default)]
1442struct PandasSignificand {
1443 exact: u64,
1444 float: f64,
1445 rounding: bool,
1446 digits: usize,
1447}
1448
1449impl PandasSignificand {
1450 fn push(&mut self, digit: u8) {
1451 self.digits += 1;
1452 if !self.rounding {
1453 let next = self.exact * 10 + u64::from(digit);
1454 if next <= 1 << 53 {
1455 self.exact = next;
1456 return;
1457 }
1458 self.rounding = true;
1459 #[allow(clippy::cast_precision_loss)] let exact = self.exact as f64;
1461 self.float = exact;
1462 }
1463 self.float = self.float * 10.0 + f64::from(digit);
1464 }
1465
1466 #[allow(clippy::cast_precision_loss)] fn value(&self) -> f64 {
1468 if self.rounding {
1469 self.float
1470 } else {
1471 self.exact as f64
1472 }
1473 }
1474}
1475
1476static PANDAS_POW10: std::sync::LazyLock<[f64; 309]> = std::sync::LazyLock::new(|| {
1478 std::array::from_fn(|power| format!("1e{power}").parse().unwrap_or(f64::INFINITY))
1479});
1480
1481#[must_use]
1494pub fn pandas_decimal_to_f64(token: &[u8]) -> PandasDecimal {
1495 let (negative, body) = match token.first() {
1496 Some(b'-') => (true, &token[1..]),
1497 Some(b'+') => (false, &token[1..]),
1498 _ => (false, token),
1499 };
1500 let mut significand = PandasSignificand::default();
1501 let mut exponent = 0_i32;
1502 let mut pos = 0;
1503 while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1504 if significand.digits < PANDAS_DECIMAL_DIGITS {
1505 significand.push(byte - b'0');
1506 } else {
1507 exponent = exponent.wrapping_add(1);
1508 }
1509 pos += 1;
1510 }
1511 let mut seen_digit = pos > 0;
1512 if body.get(pos) == Some(&b'.') {
1513 pos += 1;
1514 while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1515 if significand.digits < PANDAS_DECIMAL_DIGITS {
1516 significand.push(byte - b'0');
1517 exponent = exponent.wrapping_sub(1);
1518 }
1519 seen_digit = true;
1520 pos += 1;
1521 }
1522 }
1523 if !seen_digit {
1524 return PandasDecimal::NotDecimal;
1525 }
1526 if let Some(b'e' | b'E') = body.get(pos) {
1527 pos += 1;
1528 let negative_exponent = match body.get(pos) {
1529 Some(b'-') => {
1530 pos += 1;
1531 true
1532 }
1533 Some(b'+') => {
1534 pos += 1;
1535 false
1536 }
1537 _ => false,
1538 };
1539 let start = pos;
1540 let mut written = 0_i32;
1541 while pos - start < PANDAS_DECIMAL_DIGITS
1542 && let Some(&byte @ b'0'..=b'9') = body.get(pos)
1543 {
1544 written = written
1545 .wrapping_mul(10)
1546 .wrapping_add(i32::from(byte - b'0'));
1547 pos += 1;
1548 }
1549 if pos == start {
1550 return PandasDecimal::Rejected;
1551 }
1552 exponent = exponent.wrapping_add(if negative_exponent {
1553 written.wrapping_neg()
1554 } else {
1555 written
1556 });
1557 }
1558 if pos != body.len() {
1559 return PandasDecimal::Rejected;
1560 }
1561 let value = significand.value();
1562 let pow10 = |power: i32| PANDAS_POW10[power.unsigned_abs() as usize];
1563 let magnitude = match exponent {
1564 309.. => return PandasDecimal::Rejected,
1565 0.. => value * pow10(exponent),
1566 -308.. => value / pow10(exponent),
1567 -616.. => value / pow10(-308 - exponent) / pow10(308),
1568 _ => return PandasDecimal::Value(0.0),
1569 };
1570 if magnitude.is_infinite() {
1571 return PandasDecimal::Rejected;
1572 }
1573 PandasDecimal::Value(if negative { -magnitude } else { magnitude })
1574}
1575
1576#[must_use]
1580#[allow(clippy::cast_precision_loss)] pub fn pandas_int_to_f64(value: i64) -> f64 {
1582 if value.unsigned_abs() <= 1 << 53 {
1583 return value as f64;
1584 }
1585 match pandas_decimal_to_f64(value.to_string().as_bytes()) {
1586 PandasDecimal::Value(parsed) => parsed,
1587 PandasDecimal::Rejected | PandasDecimal::NotDecimal => value as f64,
1589 }
1590}
1591
1592#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1595pub enum NumpyNumeric {
1596 Bool,
1597 Int(u8),
1598 UInt(u8),
1599 Float(u8),
1600}
1601
1602impl NumpyNumeric {
1603 #[must_use]
1607 pub const fn of(dtype: &DType, width: Option<NumericWidth>) -> Option<Self> {
1608 match (dtype, width) {
1609 (DType::Bool | DType::BoolNullable, None) => Some(Self::Bool),
1610 (DType::Int64 | DType::Int64Nullable, None) => Some(Self::Int(64)),
1611 (DType::Float64 | DType::Float64Nullable, None) => Some(Self::Float(64)),
1612 (DType::Int64 | DType::Int64Nullable, Some(width)) if !width.is_float() => {
1613 Some(Self::of_width(width))
1614 }
1615 (DType::Float64 | DType::Float64Nullable, Some(NumericWidth::Float32)) => {
1616 Some(Self::Float(32))
1617 }
1618 _ => None,
1619 }
1620 }
1621
1622 #[must_use]
1623 pub const fn of_width(width: NumericWidth) -> Self {
1624 match width {
1625 NumericWidth::Int8 => Self::Int(8),
1626 NumericWidth::Int16 => Self::Int(16),
1627 NumericWidth::Int32 => Self::Int(32),
1628 NumericWidth::UInt8 => Self::UInt(8),
1629 NumericWidth::UInt16 => Self::UInt(16),
1630 NumericWidth::UInt32 => Self::UInt(32),
1631 NumericWidth::UInt64 => Self::UInt(64),
1632 NumericWidth::Float32 => Self::Float(32),
1633 }
1634 }
1635
1636 #[must_use]
1639 pub const fn width(self) -> Option<NumericWidth> {
1640 match self {
1641 Self::Int(8) => Some(NumericWidth::Int8),
1642 Self::Int(16) => Some(NumericWidth::Int16),
1643 Self::Int(32) => Some(NumericWidth::Int32),
1644 Self::UInt(8) => Some(NumericWidth::UInt8),
1645 Self::UInt(16) => Some(NumericWidth::UInt16),
1646 Self::UInt(32) => Some(NumericWidth::UInt32),
1647 Self::UInt(64) => Some(NumericWidth::UInt64),
1648 Self::Float(32) => Some(NumericWidth::Float32),
1649 _ => None,
1650 }
1651 }
1652
1653 #[must_use]
1654 pub const fn is_float(self) -> bool {
1655 matches!(self, Self::Float(_))
1656 }
1657
1658 #[must_use]
1663 pub const fn result_type(self, other: Self) -> Self {
1664 const fn wider(a: u8, b: u8) -> u8 {
1665 if a > b { a } else { b }
1666 }
1667 match (self, other) {
1668 (Self::Bool, x) | (x, Self::Bool) => x,
1669 (Self::Int(a), Self::Int(b)) => Self::Int(wider(a, b)),
1670 (Self::UInt(a), Self::UInt(b)) => Self::UInt(wider(a, b)),
1671 (Self::Int(signed), Self::UInt(unsigned))
1672 | (Self::UInt(unsigned), Self::Int(signed)) => {
1673 if signed > unsigned {
1674 Self::Int(signed)
1675 } else if unsigned < 64 {
1676 Self::Int(wider(signed, unsigned * 2))
1677 } else {
1678 Self::Float(64)
1679 }
1680 }
1681 (Self::Float(a), Self::Float(b)) => Self::Float(wider(a, b)),
1682 (Self::Float(bits), Self::Int(int_bits) | Self::UInt(int_bits))
1683 | (Self::Int(int_bits) | Self::UInt(int_bits), Self::Float(bits)) => {
1684 if int_bits <= 16 {
1685 Self::Float(bits)
1686 } else {
1687 Self::Float(64)
1688 }
1689 }
1690 }
1691 }
1692
1693 #[must_use]
1697 pub const fn with_python_int(self) -> Self {
1698 match self {
1699 Self::Bool => Self::Int(64),
1700 other => other,
1701 }
1702 }
1703
1704 #[must_use]
1708 pub const fn with_python_float(self) -> Self {
1709 match self {
1710 Self::Float(bits) => Self::Float(bits),
1711 _ => Self::Float(64),
1712 }
1713 }
1714}
1715
1716pub trait AsDType {
1718 fn as_dtype(&self) -> DType;
1720}
1721
1722impl AsDType for DType {
1723 fn as_dtype(&self) -> DType {
1724 self.clone()
1725 }
1726}
1727
1728impl AsDType for &DType {
1729 fn as_dtype(&self) -> DType {
1730 (*self).clone()
1731 }
1732}
1733
1734impl AsDType for &str {
1735 fn as_dtype(&self) -> DType {
1736 self.parse::<DType>().unwrap_or(DType::Utf8)
1737 }
1738}
1739
1740impl AsDType for String {
1741 fn as_dtype(&self) -> DType {
1742 self.as_str().as_dtype()
1743 }
1744}
1745
1746pub mod api {
1747 pub mod types {
1750 use crate::{AsDType, DType, Scalar, TypeError};
1753
1754 #[must_use]
1756 pub fn is_bool_dtype(dtype: &impl AsDType) -> bool {
1757 dtype.as_dtype().is_bool()
1758 }
1759
1760 #[must_use]
1762 pub fn is_numeric_dtype(dtype: &impl AsDType) -> bool {
1763 dtype.as_dtype().is_numeric()
1764 }
1765
1766 #[must_use]
1768 pub fn is_integer_dtype(dtype: &impl AsDType) -> bool {
1769 dtype.as_dtype().is_integer()
1770 }
1771
1772 #[must_use]
1774 pub fn is_signed_integer_dtype(dtype: &impl AsDType) -> bool {
1775 dtype.as_dtype().is_signed_integer()
1776 }
1777
1778 #[must_use]
1780 pub fn is_unsigned_integer_dtype(_dtype: &impl AsDType) -> bool {
1781 false
1782 }
1783
1784 #[must_use]
1786 pub fn is_float_dtype(dtype: &impl AsDType) -> bool {
1787 dtype.as_dtype().is_floating()
1788 }
1789
1790 #[must_use]
1792 pub fn is_string_dtype(dtype: &impl AsDType) -> bool {
1793 dtype.as_dtype().is_string_dtype()
1794 }
1795
1796 #[must_use]
1798 pub fn is_datetime64_any_dtype(dtype: &impl AsDType) -> bool {
1799 dtype.as_dtype().is_datetime()
1800 }
1801
1802 #[must_use]
1804 pub fn is_datetime64_dtype(dtype: &impl AsDType) -> bool {
1805 dtype.as_dtype().is_datetime()
1806 }
1807
1808 #[must_use]
1810 pub fn is_datetime64_ns_dtype(dtype: &impl AsDType) -> bool {
1811 dtype.as_dtype().is_datetime()
1812 }
1813
1814 #[must_use]
1816 pub fn is_timedelta64_dtype(dtype: &impl AsDType) -> bool {
1817 dtype.as_dtype().is_timedelta()
1818 }
1819
1820 #[must_use]
1822 pub fn is_timedelta64_ns_dtype(dtype: &impl AsDType) -> bool {
1823 dtype.as_dtype().is_timedelta()
1824 }
1825
1826 #[must_use]
1828 pub fn is_period_dtype(dtype: &impl AsDType) -> bool {
1829 dtype.as_dtype().is_period()
1830 }
1831
1832 #[must_use]
1834 pub fn is_categorical_dtype(dtype: &impl AsDType) -> bool {
1835 dtype.as_dtype().is_categorical()
1836 }
1837
1838 #[must_use]
1840 pub fn is_interval_dtype(dtype: &impl AsDType) -> bool {
1841 dtype.as_dtype().is_interval()
1842 }
1843
1844 #[must_use]
1846 pub fn is_sparse(dtype: &impl AsDType) -> bool {
1847 dtype.as_dtype().is_sparse()
1848 }
1849
1850 #[must_use]
1852 pub fn is_extension_array_dtype(dtype: &impl AsDType) -> bool {
1853 dtype.as_dtype().is_extension()
1854 }
1855
1856 #[must_use]
1858 pub fn is_object_dtype(dtype: &impl AsDType) -> bool {
1859 dtype.as_dtype().is_object()
1860 }
1861
1862 #[must_use]
1864 pub fn is_int64_dtype(dtype: &impl AsDType) -> bool {
1865 matches!(dtype.as_dtype(), DType::Int64 | DType::Int64Nullable)
1866 }
1867
1868 #[must_use]
1870 pub fn is_dtype_equal(source: &impl AsDType, target: &impl AsDType) -> bool {
1871 source.as_dtype() == target.as_dtype()
1872 }
1873
1874 #[must_use]
1876 pub const fn is_scalar(_scalar: &Scalar) -> bool {
1877 true
1878 }
1879
1880 pub fn pandas_dtype(name: &str) -> Result<DType, TypeError> {
1886 name.parse::<DType>()
1887 }
1888
1889 #[must_use]
1891 pub fn infer_dtype(scalars: &[Scalar], skipna: bool) -> &'static str {
1892 if scalars.is_empty() {
1893 return "empty";
1894 }
1895 let mut has_int = false;
1896 let mut has_float = false;
1897 let mut has_bool = false;
1898 let mut has_str = false;
1899 let mut has_ts = false;
1900 let mut has_td = false;
1901 let mut has_period = false;
1902 let mut count = 0;
1903
1904 for s in scalars {
1905 if s.is_null() {
1906 if !skipna {
1907 return "mixed";
1908 }
1909 continue;
1910 }
1911 count += 1;
1912 match s {
1913 Scalar::Bool(_) => has_bool = true,
1914 Scalar::Int64(_) => has_int = true,
1915 Scalar::Float64(_) => has_float = true,
1916 Scalar::Utf8(_) => has_str = true,
1917 Scalar::Datetime64(_) => has_ts = true,
1918 Scalar::Timedelta64(_) => has_td = true,
1919 Scalar::Period(_) => has_period = true,
1920 _ => {}
1921 }
1922 }
1923
1924 if count == 0 {
1925 return "empty";
1926 }
1927 if has_bool && !has_int && !has_float && !has_str && !has_ts && !has_td && !has_period {
1928 return "boolean";
1929 }
1930 if has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td && !has_period {
1931 return "integer";
1932 }
1933 if (has_float || (has_int && has_float))
1934 && !has_bool
1935 && !has_str
1936 && !has_ts
1937 && !has_td
1938 && !has_period
1939 {
1940 return "floating";
1941 }
1942 if has_str && !has_int && !has_float && !has_bool && !has_ts && !has_td && !has_period {
1943 return "string";
1944 }
1945 if has_ts && !has_int && !has_float && !has_bool && !has_str && !has_td && !has_period {
1946 return "datetime64";
1947 }
1948 if has_td && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_period {
1949 return "timedelta64";
1950 }
1951 if has_period && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td {
1952 return "period";
1953 }
1954 "mixed"
1955 }
1956
1957 #[must_use]
1959 pub fn is_float64_dtype(dtype: &impl AsDType) -> bool {
1960 matches!(dtype.as_dtype(), DType::Float64 | DType::Float64Nullable)
1961 }
1962
1963 #[must_use]
1965 pub fn is_int32_dtype(_dtype: &impl AsDType) -> bool {
1966 false
1967 }
1968
1969 #[must_use]
1971 pub fn is_number(scalar: &Scalar) -> bool {
1972 scalar.is_numeric() || matches!(scalar, Scalar::Bool(_))
1973 }
1974
1975 #[must_use]
1977 pub fn is_bool(scalar: &Scalar) -> bool {
1978 matches!(scalar, Scalar::Bool(_))
1979 }
1980
1981 #[must_use]
1983 pub fn is_integer(scalar: &Scalar) -> bool {
1984 matches!(scalar, Scalar::Int64(_))
1985 }
1986
1987 #[must_use]
1989 pub fn is_float(scalar: &Scalar) -> bool {
1990 matches!(scalar, Scalar::Float64(_))
1991 }
1992 }
1993
1994 pub mod extensions {
1995 pub fn register_dataframe_accessor(_name: &str) {}
1999
2000 pub fn register_series_accessor(_name: &str) {}
2002
2003 pub fn register_index_accessor(_name: &str) {}
2005 }
2006
2007 pub mod indexers {
2008 #[derive(Debug, Clone, PartialEq, Eq, Default)]
2012 pub struct BaseIndexer {
2013 pub window_size: usize,
2014 pub step: usize,
2015 }
2016
2017 impl BaseIndexer {
2018 #[must_use]
2019 pub const fn new(window_size: usize, step: usize) -> Self {
2020 Self { window_size, step }
2021 }
2022 }
2023
2024 #[derive(Debug, Clone, PartialEq, Eq, Default)]
2026 pub struct FixedForwardWindowIndexer {
2027 pub window_size: usize,
2028 }
2029
2030 impl FixedForwardWindowIndexer {
2031 #[must_use]
2032 pub const fn new(window_size: usize) -> Self {
2033 Self { window_size }
2034 }
2035 }
2036
2037 #[derive(Debug, Clone, PartialEq, Eq, Default)]
2039 pub struct VariableOffsetWindowIndexer {
2040 pub index_offset: i64,
2041 }
2042
2043 impl VariableOffsetWindowIndexer {
2044 #[must_use]
2045 pub const fn new(index_offset: i64) -> Self {
2046 Self { index_offset }
2047 }
2048 }
2049 }
2050}
2051
2052pub use api::types::pandas_dtype;
2053
2054#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2055pub struct SparseDType {
2056 pub value_dtype: DType,
2057 pub fill_value: Scalar,
2058 #[serde(default, skip_serializing_if = "Option::is_none")]
2059 pub width: Option<NumericWidth>,
2060 #[serde(default, skip_serializing_if = "Option::is_none")]
2065 pub fill_numpy_dtype: Option<String>,
2066}
2067
2068impl SparseDType {
2069 pub fn new(value_dtype: DType, fill_value: Scalar) -> Result<Self, TypeError> {
2075 if matches!(value_dtype, DType::Null | DType::Sparse) {
2076 return Err(TypeError::InvalidSparseValueDType { dtype: value_dtype });
2077 }
2078
2079 let fill_value = if fill_value.is_missing() {
2080 Scalar::missing_for_dtype(value_dtype.clone())
2081 } else {
2082 cast_scalar_owned(fill_value, value_dtype.clone())?
2083 };
2084
2085 Ok(Self {
2086 value_dtype,
2087 fill_value,
2088 width: None,
2089 fill_numpy_dtype: None,
2090 })
2091 }
2092
2093 #[must_use]
2120 pub fn pandas_name(&self) -> String {
2121 let subtype = self
2122 .width
2123 .map_or(self.value_dtype.name(), |width| width.name(false));
2124 let fill = match &self.fill_value {
2125 Scalar::Utf8(value) if value.contains('\'') && !value.contains('"') => {
2126 format!("{value:?}")
2127 }
2128 Scalar::Utf8(value) => format!(
2129 "'{}'",
2130 value
2131 .replace('\\', "\\\\")
2132 .replace('\'', "\\'")
2133 .replace('\n', "\\n")
2134 .replace('\r', "\\r")
2135 .replace('\t', "\\t")
2136 ),
2137 value => scalar_to_string_for_astype(value.clone()),
2138 };
2139 format!("Sparse[{}, {}]", subtype, fill)
2140 }
2141}
2142
2143impl AsDType for SparseDType {
2144 fn as_dtype(&self) -> DType {
2145 DType::Sparse
2146 }
2147}
2148
2149#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
2153pub struct CategoricalDtype {
2154 pub categories: Option<Vec<String>>,
2155 pub ordered: bool,
2156}
2157
2158pub type CategoricalDType = CategoricalDtype;
2159
2160impl CategoricalDtype {
2161 #[must_use]
2163 pub const fn new(categories: Option<Vec<String>>, ordered: bool) -> Self {
2164 Self {
2165 categories,
2166 ordered,
2167 }
2168 }
2169
2170 #[must_use]
2172 pub fn categories(&self) -> Option<&[String]> {
2173 self.categories.as_deref()
2174 }
2175
2176 #[must_use]
2178 pub const fn ordered(&self) -> bool {
2179 self.ordered
2180 }
2181
2182 #[must_use]
2184 pub const fn name(&self) -> &'static str {
2185 "category"
2186 }
2187
2188 #[must_use]
2190 pub const fn kind(&self) -> &'static str {
2191 "O"
2192 }
2193}
2194
2195impl AsDType for CategoricalDtype {
2196 fn as_dtype(&self) -> DType {
2197 DType::Categorical
2198 }
2199}
2200
2201impl std::fmt::Display for CategoricalDtype {
2202 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2203 let ord_str = if self.ordered { "True" } else { "False" };
2204 match &self.categories {
2205 Some(cats) => write!(
2206 f,
2207 "CategoricalDtype(categories={cats:?}, ordered={ord_str})"
2208 ),
2209 None => write!(f, "CategoricalDtype(categories=None, ordered={ord_str})"),
2210 }
2211 }
2212}
2213
2214#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2218pub struct PeriodDtype {
2219 pub freq: String,
2220}
2221
2222pub type PeriodDType = PeriodDtype;
2223
2224impl PeriodDtype {
2225 #[must_use]
2227 pub fn new(freq: impl Into<String>) -> Self {
2228 Self { freq: freq.into() }
2229 }
2230
2231 #[must_use]
2233 pub fn freq(&self) -> &str {
2234 &self.freq
2235 }
2236
2237 #[must_use]
2239 pub fn name(&self) -> String {
2240 format!("period[{}]", self.freq)
2241 }
2242
2243 #[must_use]
2245 pub const fn kind(&self) -> &'static str {
2246 "O"
2247 }
2248}
2249
2250impl Default for PeriodDtype {
2251 fn default() -> Self {
2252 Self {
2253 freq: "D".to_string(),
2254 }
2255 }
2256}
2257
2258impl AsDType for PeriodDtype {
2259 fn as_dtype(&self) -> DType {
2260 DType::Period
2261 }
2262}
2263
2264impl std::fmt::Display for PeriodDtype {
2265 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2266 write!(f, "period[{}]", self.freq)
2267 }
2268}
2269
2270#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2274pub struct IntervalDtype {
2275 pub subtype: DType,
2276 pub closed: Option<IntervalClosed>,
2277}
2278
2279pub type IntervalDType = IntervalDtype;
2280
2281impl IntervalDtype {
2282 #[must_use]
2284 pub const fn new(subtype: DType, closed: Option<IntervalClosed>) -> Self {
2285 Self { subtype, closed }
2286 }
2287
2288 #[must_use]
2290 pub const fn subtype(&self) -> &DType {
2291 &self.subtype
2292 }
2293
2294 #[must_use]
2296 pub const fn closed(&self) -> Option<IntervalClosed> {
2297 self.closed
2298 }
2299
2300 #[must_use]
2302 pub const fn name(&self) -> &'static str {
2303 "interval"
2304 }
2305
2306 #[must_use]
2308 pub const fn kind(&self) -> &'static str {
2309 "O"
2310 }
2311}
2312
2313impl Default for IntervalDtype {
2314 fn default() -> Self {
2315 Self {
2316 subtype: DType::Float64,
2317 closed: Some(IntervalClosed::Right),
2318 }
2319 }
2320}
2321
2322impl AsDType for IntervalDtype {
2323 fn as_dtype(&self) -> DType {
2324 DType::Interval
2325 }
2326}
2327
2328impl std::fmt::Display for IntervalDtype {
2329 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2330 match self.closed {
2331 Some(c) => write!(f, "interval[{}, {c}]", self.subtype.name()),
2332 None => write!(f, "interval[{}]", self.subtype.name()),
2333 }
2334 }
2335}
2336
2337#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
2338#[serde(rename_all = "snake_case")]
2339pub enum NullKind {
2340 Null,
2341 NaN,
2342 NaT,
2343}
2344
2345mod float64_json {
2353 use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
2354
2355 pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
2356 if value.is_infinite() {
2357 serializer.serialize_str(if value.is_sign_positive() {
2358 "inf"
2359 } else {
2360 "-inf"
2361 })
2362 } else {
2363 serializer.serialize_f64(*value)
2364 }
2365 }
2366
2367 #[derive(Deserialize)]
2368 #[serde(untagged)]
2369 enum Repr {
2370 Number(f64),
2371 Text(String),
2372 Null(()),
2373 }
2374
2375 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
2376 match Repr::deserialize(deserializer)? {
2377 Repr::Number(value) => Ok(value),
2378 Repr::Text(text) => match text.as_str() {
2379 "inf" => Ok(f64::INFINITY),
2380 "-inf" => Ok(f64::NEG_INFINITY),
2381 other => Err(D::Error::custom(format!(
2382 "float64 value must be a number, \"inf\" or \"-inf\", got {other:?}"
2383 ))),
2384 },
2385 Repr::Null(()) => Ok(f64::NAN),
2386 }
2387 }
2388}
2389
2390#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2391#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
2392pub enum Scalar {
2393 Null(NullKind),
2394 Bool(bool),
2395 Int64(i64),
2396 Float64(#[serde(with = "float64_json")] f64),
2397 #[serde(alias = "string", alias = "str")]
2398 Utf8(String),
2399 Timedelta64(i64),
2400 Datetime64(i64),
2403 Period(Period),
2409 Interval(Interval),
2411 Object(ObjectValue),
2415}
2416
2417#[derive(Clone)]
2421pub enum ObjectValue {
2422 List(std::sync::Arc<[Scalar]>),
2424 Bytes(std::sync::Arc<[u8]>),
2428 Host(HostValue),
2430}
2431
2432pub trait HostObject: Send + Sync {
2435 fn host_eq(&self, other: &dyn HostObject) -> bool;
2437 fn host_repr(&self) -> String;
2439 fn host_str(&self) -> String;
2441 fn host_pprint(&self) -> String {
2445 self.host_str()
2446 }
2447 fn host_hash(&self) -> Option<u64>;
2449 fn host_cmp(&self, other: &dyn HostObject) -> Option<std::cmp::Ordering>;
2453 fn host_eq_scalar(&self, _other: &Scalar) -> bool {
2456 false
2457 }
2458 fn host_type_name(&self) -> String {
2461 "object".to_owned()
2462 }
2463 fn as_any(&self) -> &dyn std::any::Any;
2465 fn host_number(&self) -> Option<i64> {
2471 None
2472 }
2473}
2474
2475static LIVE_HOST_VALUES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2477
2478static HOST_LOCK_DECLARED: std::sync::atomic::AtomicBool =
2481 std::sync::atomic::AtomicBool::new(false);
2482
2483pub fn declare_host_lock() {
2487 HOST_LOCK_DECLARED.store(true, std::sync::atomic::Ordering::Relaxed);
2488}
2489
2490#[must_use]
2498pub fn host_values_block_workers() -> bool {
2499 workers_blocked(
2500 HOST_LOCK_DECLARED.load(std::sync::atomic::Ordering::Relaxed),
2501 LIVE_HOST_VALUES.load(std::sync::atomic::Ordering::Relaxed),
2502 )
2503}
2504
2505const fn workers_blocked(host_lock_declared: bool, live_host_values: usize) -> bool {
2507 host_lock_declared && live_host_values > 0
2508}
2509
2510struct HostSlot<T: ?Sized> {
2514 number: Option<i64>,
2516 object: T,
2517}
2518
2519impl<T: ?Sized> Drop for HostSlot<T> {
2520 fn drop(&mut self) {
2521 LIVE_HOST_VALUES.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2522 }
2523}
2524
2525#[derive(Clone)]
2527pub struct HostValue(std::sync::Arc<HostSlot<dyn HostObject>>);
2528
2529impl HostValue {
2530 #[must_use]
2531 pub fn new(object: impl HostObject + 'static) -> Self {
2532 LIVE_HOST_VALUES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2533 Self(std::sync::Arc::new(HostSlot {
2534 number: object.host_number(),
2535 object,
2536 }))
2537 }
2538
2539 #[must_use]
2540 pub fn object(&self) -> &dyn HostObject {
2541 &self.0.object
2542 }
2543
2544 #[must_use]
2546 pub fn number(&self) -> Option<i64> {
2547 self.0.number
2548 }
2549}
2550
2551impl PartialEq for HostValue {
2552 fn eq(&self, other: &Self) -> bool {
2553 std::sync::Arc::ptr_eq(&self.0, &other.0)
2554 || match (self.number(), other.number()) {
2555 (Some(left), Some(right)) => left == right,
2558 _ => self.object().host_eq(other.object()),
2559 }
2560 }
2561}
2562
2563impl std::fmt::Debug for HostValue {
2564 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2565 formatter.write_str(&self.object().host_repr())
2566 }
2567}
2568
2569impl ObjectValue {
2570 #[must_use]
2572 pub fn list(items: Vec<Scalar>) -> Self {
2573 Self::List(items.into())
2574 }
2575
2576 #[must_use]
2578 pub fn as_list(&self) -> Option<&[Scalar]> {
2579 match self {
2580 Self::List(items) => Some(items),
2581 Self::Bytes(_) | Self::Host(_) => None,
2582 }
2583 }
2584
2585 #[must_use]
2587 pub fn bytes(data: Vec<u8>) -> Self {
2588 Self::Bytes(data.into())
2589 }
2590
2591 #[must_use]
2593 pub fn as_bytes(&self) -> Option<&[u8]> {
2594 match self {
2595 Self::Bytes(data) => Some(data),
2596 Self::List(_) | Self::Host(_) => None,
2597 }
2598 }
2599
2600 #[must_use]
2602 pub fn repr(&self) -> String {
2603 match self {
2604 Self::List(items) => {
2605 let parts: Vec<String> = items.iter().map(Scalar::python_repr).collect();
2606 format!("[{}]", parts.join(", "))
2607 }
2608 Self::Bytes(data) => python_bytes_repr(data),
2609 Self::Host(value) => value.object().host_repr(),
2610 }
2611 }
2612
2613 #[must_use]
2616 pub fn pprint(&self) -> String {
2617 match self {
2618 Self::List(items) => {
2619 let parts: Vec<String> = items
2620 .iter()
2621 .map(|item| match item {
2622 Scalar::Utf8(text) => text.clone(),
2623 Scalar::Object(object) => object.pprint(),
2624 other => other.python_repr(),
2625 })
2626 .collect();
2627 format!("[{}]", parts.join(", "))
2628 }
2629 Self::Bytes(data) => python_bytes_repr(data),
2630 Self::Host(value) => value.object().host_pprint(),
2631 }
2632 }
2633
2634 #[must_use]
2637 pub fn type_name(&self) -> String {
2638 match self {
2639 Self::List(_) => "list".to_owned(),
2640 Self::Bytes(_) => "bytes".to_owned(),
2641 Self::Host(value) => value.object().host_type_name(),
2642 }
2643 }
2644
2645 #[must_use]
2649 pub fn python_eq_scalar(&self, other: &Scalar) -> bool {
2650 match self {
2651 Self::Host(value) => value.object().host_eq_scalar(other),
2652 Self::List(_) | Self::Bytes(_) => false,
2653 }
2654 }
2655
2656 #[must_use]
2660 pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2661 match (self, other) {
2662 (Self::Bytes(left), Self::Bytes(right)) => Some(left.cmp(right)),
2663 (Self::Host(left), Self::Host(right)) => {
2664 if left == right {
2665 Some(std::cmp::Ordering::Equal)
2666 } else {
2667 left.object().host_cmp(right.object())
2668 }
2669 }
2670 (Self::List(left), Self::List(right)) => {
2671 for (a, b) in left.iter().zip(right.iter()) {
2672 if a != b {
2673 let ordering = a.python_cmp(b)?;
2674 if ordering.is_ne() {
2675 return Some(ordering);
2676 }
2677 }
2678 }
2679 Some(left.len().cmp(&right.len()))
2680 }
2681 _ => None,
2682 }
2683 }
2684
2685 #[must_use]
2690 pub fn total_cmp(&self, other: &Self) -> std::cmp::Ordering {
2691 use std::cmp::Ordering;
2692 if self == other {
2693 return Ordering::Equal;
2694 }
2695 if let Some(ordering) = self.python_cmp(other).filter(|ordering| ordering.is_ne()) {
2696 return ordering;
2697 }
2698 let rank = |cell: &Self| match cell {
2699 Self::List(_) => 0_u8,
2700 Self::Bytes(_) => 1,
2701 Self::Host(_) => 2,
2702 };
2703 rank(self)
2704 .cmp(&rank(other))
2705 .then_with(|| self.repr().cmp(&other.repr()))
2706 .then_with(|| self.address().cmp(&other.address()))
2707 }
2708
2709 fn address(&self) -> usize {
2712 match self {
2713 Self::List(items) => items.as_ptr().addr(),
2714 Self::Bytes(data) => data.as_ptr().addr(),
2715 Self::Host(value) => std::sync::Arc::as_ptr(&value.0).cast::<()>().addr(),
2716 }
2717 }
2718}
2719
2720#[must_use]
2724pub fn python_bytes_repr(data: &[u8]) -> String {
2725 let quote = if data.contains(&b'\'') && !data.contains(&b'"') {
2726 b'"'
2727 } else {
2728 b'\''
2729 };
2730 let mut out = String::with_capacity(data.len() + 3);
2731 out.push('b');
2732 out.push(char::from(quote));
2733 for &byte in data {
2734 match byte {
2735 b'\\' => out.push_str("\\\\"),
2736 b'\t' => out.push_str("\\t"),
2737 b'\n' => out.push_str("\\n"),
2738 b'\r' => out.push_str("\\r"),
2739 _ if byte == quote => {
2740 out.push('\\');
2741 out.push(char::from(byte));
2742 }
2743 0x20..=0x7e => out.push(char::from(byte)),
2744 _ => out.push_str(&format!("\\x{byte:02x}")),
2745 }
2746 }
2747 out.push(char::from(quote));
2748 out
2749}
2750
2751impl PartialOrd for ObjectValue {
2752 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2753 Some(self.cmp(other))
2754 }
2755}
2756
2757impl Ord for ObjectValue {
2759 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2760 self.total_cmp(other)
2761 }
2762}
2763
2764impl PartialEq for ObjectValue {
2765 fn eq(&self, other: &Self) -> bool {
2766 match (self, other) {
2767 (Self::List(left), Self::List(right)) => left == right,
2768 (Self::Bytes(left), Self::Bytes(right)) => left == right,
2769 (Self::Host(left), Self::Host(right)) => left == right,
2770 _ => false,
2771 }
2772 }
2773}
2774
2775impl Eq for ObjectValue {}
2779
2780impl std::hash::Hash for ObjectValue {
2781 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2782 match self {
2783 Self::List(items) => {
2784 0_u8.hash(state);
2785 for item in items.iter() {
2786 item.python_repr().hash(state);
2787 }
2788 }
2789 Self::Bytes(data) => {
2790 2_u8.hash(state);
2791 data.hash(state);
2792 }
2793 Self::Host(value) => {
2794 1_u8.hash(state);
2795 if let Some(number) = value.number() {
2798 number.hash(state);
2799 return;
2800 }
2801 match value.object().host_hash() {
2802 Some(hash) => hash.hash(state),
2803 None => value.object().host_repr().hash(state),
2804 }
2805 }
2806 }
2807 }
2808}
2809
2810impl std::fmt::Debug for ObjectValue {
2811 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2812 formatter.write_str(&self.repr())
2813 }
2814}
2815
2816impl std::fmt::Display for ObjectValue {
2820 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2821 match self {
2822 Self::List(_) | Self::Bytes(_) => formatter.write_str(&self.repr()),
2823 Self::Host(value) => formatter.write_str(&value.object().host_str()),
2824 }
2825 }
2826}
2827
2828impl Serialize for ObjectValue {
2831 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2832 match self {
2833 Self::List(items) => items.as_ref().serialize(serializer),
2834 Self::Bytes(data) => SerializedObject::Bytes {
2835 bytes: data.to_vec(),
2836 }
2837 .serialize(serializer),
2838 Self::Host(_) => Err(serde::ser::Error::custom(
2839 "a host-language object cell cannot be serialized",
2840 )),
2841 }
2842 }
2843}
2844
2845#[derive(Serialize, Deserialize)]
2848#[serde(untagged)]
2849enum SerializedObject {
2850 List(Vec<Scalar>),
2851 Bytes { bytes: Vec<u8> },
2852}
2853
2854impl<'de> Deserialize<'de> for ObjectValue {
2855 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2856 Ok(match SerializedObject::deserialize(deserializer)? {
2857 SerializedObject::List(items) => Self::list(items),
2858 SerializedObject::Bytes { bytes } => Self::bytes(bytes),
2859 })
2860 }
2861}
2862
2863impl std::fmt::Display for Scalar {
2864 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2865 match self {
2866 Self::Null(NullKind::NaN) => write!(f, "NaN"),
2867 Self::Null(NullKind::NaT) => write!(f, "NaT"),
2868 Self::Null(NullKind::Null) => write!(f, "None"),
2869 Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
2870 Self::Int64(v) => write!(f, "{v}"),
2871 Self::Float64(v) => write!(f, "{v}"),
2872 Self::Utf8(s) => write!(f, "{s}"),
2873 Self::Timedelta64(nanos) => write!(f, "{}", Timedelta::format(*nanos)),
2874 Self::Datetime64(nanos) => {
2875 if *nanos == Timestamp::NAT {
2876 write!(f, "NaT")
2877 } else {
2878 write!(f, "Timestamp[{nanos}]")
2879 }
2880 }
2881 Self::Period(p) => {
2882 if p.ordinal == i64::MIN {
2883 write!(f, "NaT")
2884 } else {
2885 write!(f, "{}", p.calendar_string())
2886 }
2887 }
2888 Self::Interval(interval) => write!(f, "{interval}"),
2889 Self::Object(object) => write!(f, "{object}"),
2890 }
2891 }
2892}
2893
2894impl Scalar {
2895 #[must_use]
2902 pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2903 let numeric =
2904 |value: &Self| matches!(value, Self::Bool(_) | Self::Int64(_) | Self::Float64(_));
2905 match (self, other) {
2906 (Self::Utf8(a), Self::Utf8(b)) => Some(a.cmp(b)),
2907 (Self::Datetime64(a), Self::Datetime64(b))
2908 | (Self::Timedelta64(a), Self::Timedelta64(b)) => Some(a.cmp(b)),
2909 (Self::Period(a), Self::Period(b)) if a.freq == b.freq => {
2910 Some(a.ordinal.cmp(&b.ordinal))
2911 }
2912 (Self::Interval(a), Self::Interval(b)) => Some(
2913 a.left
2914 .partial_cmp(&b.left)?
2915 .then(a.right.partial_cmp(&b.right)?),
2916 ),
2917 (Self::Object(a), Self::Object(b)) => a.python_cmp(b),
2918 _ if numeric(self) && numeric(other) => {
2919 self.to_f64().ok()?.partial_cmp(&other.to_f64().ok()?)
2920 }
2921 _ => None,
2922 }
2923 }
2924
2925 #[must_use]
2930 pub fn python_cmp_type_names(&self, other: &Self) -> (String, String) {
2931 if let (Self::Object(ObjectValue::List(left)), Self::Object(ObjectValue::List(right))) =
2932 (self, other)
2933 && let Some((a, b)) = left.iter().zip(right.iter()).find(|(a, b)| a != b)
2934 {
2935 return a.python_cmp_type_names(b);
2936 }
2937 (self.python_type_name(), other.python_type_name())
2938 }
2939
2940 #[must_use]
2943 pub fn python_type_name(&self) -> String {
2944 match self {
2945 Self::Null(NullKind::NaN) | Self::Float64(_) => "float",
2946 Self::Null(NullKind::NaT) => "NaTType",
2947 Self::Null(NullKind::Null) => "NoneType",
2948 Self::Bool(_) => "bool",
2949 Self::Int64(_) => "int",
2950 Self::Utf8(_) => "str",
2951 Self::Timedelta64(_) => "Timedelta",
2952 Self::Datetime64(_) => "Timestamp",
2953 Self::Period(_) => "Period",
2954 Self::Interval(_) => "Interval",
2955 Self::Object(object) => return object.type_name(),
2956 }
2957 .to_owned()
2958 }
2959
2960 #[must_use]
2964 pub fn python_repr(&self) -> String {
2965 match self {
2966 Self::Null(NullKind::NaN) => "nan".to_owned(),
2967 Self::Null(NullKind::NaT) => "NaT".to_owned(),
2968 Self::Null(NullKind::Null) => "None".to_owned(),
2969 Self::Utf8(text) => {
2970 let quote = if text.contains('\'') && !text.contains('"') {
2971 '"'
2972 } else {
2973 '\''
2974 };
2975 let mut out = String::with_capacity(text.len() + 2);
2976 out.push(quote);
2977 for ch in text.chars() {
2978 match ch {
2979 '\\' => out.push_str("\\\\"),
2980 '\n' => out.push_str("\\n"),
2981 '\r' => out.push_str("\\r"),
2982 '\t' => out.push_str("\\t"),
2983 c if c == quote => {
2984 out.push('\\');
2985 out.push(c);
2986 }
2987 c => out.push(c),
2988 }
2989 }
2990 out.push(quote);
2991 out
2992 }
2993 Self::Float64(value) => {
2994 if value.is_nan() {
2995 "nan".to_owned()
2996 } else if value.is_infinite() {
2997 if *value > 0.0 { "inf" } else { "-inf" }.to_owned()
2998 } else if value.fract() == 0.0 && value.abs() < 1e16 {
2999 format!("{value:.1}")
3000 } else {
3001 format!("{value}")
3002 }
3003 }
3004 Self::Object(object) => object.repr(),
3005 other => other.to_string(),
3006 }
3007 }
3008}
3009
3010pub const NA: Scalar = Scalar::Null(NullKind::Null);
3012
3013pub const NAT: Scalar = Scalar::Null(NullKind::NaT);
3015
3016#[allow(non_upper_case_globals)]
3018pub const NaT: Scalar = NAT;
3019
3020impl From<bool> for Scalar {
3030 fn from(value: bool) -> Self {
3031 Self::Bool(value)
3032 }
3033}
3034
3035impl From<i64> for Scalar {
3036 fn from(value: i64) -> Self {
3037 Self::Int64(value)
3038 }
3039}
3040
3041impl From<f64> for Scalar {
3042 fn from(value: f64) -> Self {
3043 Self::Float64(value)
3044 }
3045}
3046
3047impl From<&str> for Scalar {
3048 fn from(value: &str) -> Self {
3049 Self::Utf8(value.to_owned())
3050 }
3051}
3052
3053impl From<String> for Scalar {
3054 fn from(value: String) -> Self {
3055 Self::Utf8(value)
3056 }
3057}
3058
3059impl Scalar {
3060 #[inline]
3061 const fn debug_variant_name(&self) -> &'static str {
3062 match self {
3063 Self::Null(_) => "Null",
3064 Self::Bool(_) => "Bool",
3065 Self::Int64(_) => "Int64",
3066 Self::Float64(_) => "Float64",
3067 Self::Utf8(_) => "Utf8",
3068 Self::Timedelta64(_) => "Timedelta64",
3069 Self::Datetime64(_) => "Datetime64",
3070 Self::Period(_) => "Period",
3071 Self::Interval(_) => "Interval",
3072 Self::Object(_) => "Object",
3073 }
3074 }
3075
3076 #[must_use]
3077 pub fn dtype(&self) -> DType {
3078 match self {
3079 Self::Null(_) => DType::Null,
3080 Self::Bool(_) => DType::Bool,
3081 Self::Int64(_) => DType::Int64,
3082 Self::Float64(_) => DType::Float64,
3083 Self::Utf8(_) => DType::Utf8,
3084 Self::Timedelta64(_) => DType::Timedelta64,
3085 Self::Datetime64(_) => DType::datetime64_naive(),
3086 Self::Period(_) => DType::Period,
3087 Self::Interval(_) => DType::Interval,
3088 Self::Object(_) => DType::Utf8,
3090 }
3091 }
3092
3093 #[must_use]
3094 pub fn is_missing(&self) -> bool {
3095 match self {
3096 Self::Null(_) => true,
3097 Self::Float64(v) => v.is_nan(),
3098 Self::Timedelta64(v) => *v == Timedelta::NAT,
3099 Self::Datetime64(v) => *v == Timestamp::NAT,
3100 Self::Period(p) => p.ordinal == i64::MIN,
3101 _ => false,
3102 }
3103 }
3104
3105 #[must_use]
3106 pub fn is_nan(&self) -> bool {
3107 matches!(self, Self::Null(NullKind::NaN)) || matches!(self, Self::Float64(v) if v.is_nan())
3108 }
3109
3110 #[must_use]
3112 pub const fn is_bool(&self) -> bool {
3113 matches!(self, Self::Bool(_))
3114 }
3115
3116 #[must_use]
3118 pub const fn is_integer(&self) -> bool {
3119 matches!(self, Self::Int64(_))
3120 }
3121
3122 #[must_use]
3124 pub const fn is_float(&self) -> bool {
3125 matches!(self, Self::Float64(_))
3126 }
3127
3128 #[must_use]
3130 pub const fn is_numeric(&self) -> bool {
3131 matches!(self, Self::Int64(_) | Self::Float64(_))
3132 }
3133
3134 #[must_use]
3136 pub const fn is_string(&self) -> bool {
3137 matches!(self, Self::Utf8(_))
3138 }
3139
3140 #[must_use]
3142 pub const fn is_datetime(&self) -> bool {
3143 matches!(self, Self::Datetime64(_))
3144 }
3145
3146 #[must_use]
3148 pub const fn is_timedelta(&self) -> bool {
3149 matches!(self, Self::Timedelta64(_))
3150 }
3151
3152 #[must_use]
3154 pub const fn is_period(&self) -> bool {
3155 matches!(self, Self::Period(_))
3156 }
3157
3158 #[must_use]
3160 pub const fn is_interval(&self) -> bool {
3161 matches!(self, Self::Interval(_))
3162 }
3163
3164 #[must_use]
3166 pub const fn as_i64(&self) -> Option<i64> {
3167 match self {
3168 Self::Int64(v) => Some(*v),
3169 _ => None,
3170 }
3171 }
3172
3173 #[must_use]
3175 pub const fn as_int(&self) -> Option<i64> {
3176 self.as_i64()
3177 }
3178
3179 #[must_use]
3181 pub const fn as_f64(&self) -> Option<f64> {
3182 match self {
3183 Self::Float64(v) => Some(*v),
3184 _ => None,
3185 }
3186 }
3187
3188 #[must_use]
3190 pub const fn as_float(&self) -> Option<f64> {
3191 self.as_f64()
3192 }
3193
3194 #[must_use]
3196 pub const fn as_bool(&self) -> Option<bool> {
3197 match self {
3198 Self::Bool(v) => Some(*v),
3199 _ => None,
3200 }
3201 }
3202
3203 #[must_use]
3205 pub fn as_str(&self) -> Option<&str> {
3206 match self {
3207 Self::Utf8(s) => Some(s.as_str()),
3208 _ => None,
3209 }
3210 }
3211
3212 #[must_use]
3214 pub const fn as_datetime_nanos(&self) -> Option<i64> {
3215 match self {
3216 Self::Datetime64(v) => Some(*v),
3217 _ => None,
3218 }
3219 }
3220
3221 #[must_use]
3223 pub const fn as_timedelta_nanos(&self) -> Option<i64> {
3224 match self {
3225 Self::Timedelta64(v) => Some(*v),
3226 _ => None,
3227 }
3228 }
3229
3230 #[must_use]
3232 pub const fn as_period_ordinal(&self) -> Option<i64> {
3233 match self {
3234 Self::Period(p) => Some(p.ordinal),
3235 _ => None,
3236 }
3237 }
3238
3239 #[must_use]
3241 pub const fn as_interval(&self) -> Option<Interval> {
3242 match self {
3243 Self::Interval(i) => Some(*i),
3244 _ => None,
3245 }
3246 }
3247
3248 #[must_use]
3249 pub fn missing_for_dtype(dtype: DType) -> Self {
3250 match dtype {
3251 DType::Float64 => Self::Null(NullKind::NaN),
3252 DType::Float64Nullable => Self::Null(NullKind::Null),
3260 DType::Timedelta64 => Self::Timedelta64(Timedelta::NAT),
3261 DType::Datetime64 { .. } => Self::Datetime64(Timestamp::NAT),
3262 DType::Period => Self::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
3263 DType::Null => Self::Null(NullKind::Null),
3264 DType::Bool
3265 | DType::BoolNullable
3266 | DType::Int64
3267 | DType::Int64Nullable
3268 | DType::Utf8
3269 | DType::Categorical
3270 | DType::Interval
3271 | DType::Sparse => Self::Null(NullKind::Null),
3272 }
3273 }
3274
3275 #[must_use]
3276 pub fn semantic_eq(&self, other: &Self) -> bool {
3277 match (self, other) {
3278 (Self::Float64(a), Self::Float64(b)) => {
3279 if a.is_nan() && b.is_nan() {
3280 return true;
3281 }
3282 if *a == *b {
3283 return true;
3284 }
3285 let diff = (*a - *b).abs();
3286 let max_abs = a.abs().max(b.abs());
3287 if max_abs == 0.0 {
3288 diff < f64::EPSILON
3289 } else {
3290 diff / max_abs < 1e-14
3291 }
3292 }
3293 (Self::Null(_), Self::Float64(v)) | (Self::Float64(v), Self::Null(_)) => v.is_nan(),
3294 (Self::Null(_), Self::Null(_)) => true,
3301 _ if self.is_missing() && other.is_missing() => true,
3328 (Self::Interval(a), Self::Interval(b)) => a == b && a.subtype == b.subtype,
3333 _ => self == other,
3334 }
3335 }
3336
3337 #[must_use]
3338 pub fn semantic_le(&self, other: &Self) -> bool {
3339 match self.semantic_cmp(other) {
3340 std::cmp::Ordering::Less | std::cmp::Ordering::Equal => true,
3341 std::cmp::Ordering::Greater => false,
3342 }
3343 }
3344
3345 #[must_use]
3346 pub fn semantic_ge(&self, other: &Self) -> bool {
3347 match self.semantic_cmp(other) {
3348 std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => true,
3349 std::cmp::Ordering::Less => false,
3350 }
3351 }
3352
3353 #[must_use]
3354 pub fn is_null(&self) -> bool {
3355 matches!(self, Self::Null(_))
3356 }
3357
3358 #[must_use]
3359 pub fn is_na(&self) -> bool {
3360 self.is_missing()
3361 }
3362
3363 #[must_use]
3365 pub fn isna(&self) -> bool {
3366 self.is_missing()
3367 }
3368
3369 #[must_use]
3371 pub fn isnull(&self) -> bool {
3372 self.is_null()
3373 }
3374
3375 #[must_use]
3377 pub fn notna(&self) -> bool {
3378 !self.is_missing()
3379 }
3380
3381 #[must_use]
3383 pub fn notnull(&self) -> bool {
3384 !self.is_missing()
3385 }
3386
3387 #[must_use]
3389 pub fn is_not_na(&self) -> bool {
3390 !self.is_missing()
3391 }
3392
3393 #[must_use]
3395 pub fn not_na(&self) -> bool {
3396 !self.is_missing()
3397 }
3398
3399 #[must_use]
3400 pub fn coalesce(&self, other: &Self) -> Self {
3401 if self.is_missing() {
3402 other.clone()
3403 } else {
3404 self.clone()
3405 }
3406 }
3407
3408 #[must_use]
3409 pub fn semantic_cmp(&self, other: &Self) -> std::cmp::Ordering {
3410 match (self, other) {
3411 (Self::Int64(a), Self::Int64(b)) => a.cmp(b),
3412 (Self::Float64(a), Self::Float64(b)) => {
3413 a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
3414 }
3415 (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
3416 (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
3417 (Self::Null(a), Self::Null(b)) => a.cmp(b),
3418 (Self::Timedelta64(a), Self::Timedelta64(b)) => {
3419 if *a == Timedelta::NAT || *b == Timedelta::NAT {
3420 std::cmp::Ordering::Equal
3421 } else {
3422 a.cmp(b)
3423 }
3424 }
3425 (Self::Datetime64(a), Self::Datetime64(b)) => {
3426 if *a == Timestamp::NAT || *b == Timestamp::NAT {
3427 std::cmp::Ordering::Equal
3428 } else {
3429 a.cmp(b)
3430 }
3431 }
3432 (Self::Period(a), Self::Period(b)) => {
3433 if a.ordinal == i64::MIN || b.ordinal == i64::MIN {
3434 std::cmp::Ordering::Equal
3435 } else {
3436 a.ordinal.cmp(&b.ordinal)
3437 }
3438 }
3439 (Self::Interval(a), Self::Interval(b)) => a
3440 .left
3441 .partial_cmp(&b.left)
3442 .unwrap_or(std::cmp::Ordering::Equal)
3443 .then_with(|| {
3444 a.right
3445 .partial_cmp(&b.right)
3446 .unwrap_or(std::cmp::Ordering::Equal)
3447 })
3448 .then_with(|| a.closed.cmp(&b.closed)),
3449 (Self::Object(a), Self::Object(b)) => a.cmp(b),
3451 (Self::Int64(a), Self::Float64(b)) => (*a as f64)
3453 .partial_cmp(b)
3454 .unwrap_or(std::cmp::Ordering::Equal),
3455 (Self::Float64(a), Self::Int64(b)) => a
3456 .partial_cmp(&(*b as f64))
3457 .unwrap_or(std::cmp::Ordering::Equal),
3458 (a, b) => a.debug_variant_name().cmp(b.debug_variant_name()),
3462 }
3463 }
3464
3465 pub fn to_f64(&self) -> Result<f64, TypeError> {
3466 match self {
3467 Self::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
3468 Self::Int64(v) => Ok(*v as f64),
3469 Self::Float64(v) => Ok(*v),
3470 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3471 Self::Utf8(v) => Err(TypeError::NonNumericValue {
3472 value: v.clone(),
3473 dtype: DType::Utf8,
3474 }),
3475 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3476 kind: NullKind::NaT,
3477 }),
3478 Self::Timedelta64(v) => Err(TypeError::NonNumericValue {
3479 value: Timedelta::format(*v),
3480 dtype: DType::Timedelta64,
3481 }),
3482 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3483 kind: NullKind::NaT,
3484 }),
3485 Self::Datetime64(v) => Err(TypeError::NonNumericValue {
3486 value: format!("Timestamp[{v}]"),
3487 dtype: DType::datetime64_naive(),
3488 }),
3489 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3490 kind: NullKind::NaT,
3491 }),
3492 Self::Period(p) => Err(TypeError::NonNumericValue {
3493 value: p.calendar_string(),
3494 dtype: DType::Period,
3495 }),
3496 Self::Interval(v) => Err(TypeError::NonNumericValue {
3497 value: v.to_string(),
3498 dtype: DType::Interval,
3499 }),
3500 Self::Object(object) => Err(TypeError::NonNumericValue {
3501 value: object.repr(),
3502 dtype: DType::Utf8,
3503 }),
3504 }
3505 }
3506
3507 pub fn to_i64(&self) -> Result<i64, TypeError> {
3509 match self {
3510 Self::Bool(v) => Ok(if *v { 1 } else { 0 }),
3511 Self::Int64(v) => Ok(*v),
3512 Self::Float64(v) => Ok(*v as i64),
3513 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3514 Self::Utf8(v) => Err(TypeError::NonNumericValue {
3515 value: v.clone(),
3516 dtype: DType::Utf8,
3517 }),
3518 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3519 kind: NullKind::NaT,
3520 }),
3521 Self::Timedelta64(v) => Ok(*v),
3522 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3523 kind: NullKind::NaT,
3524 }),
3525 Self::Datetime64(v) => Ok(*v),
3526 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3527 kind: NullKind::NaT,
3528 }),
3529 Self::Period(p) => Ok(p.ordinal),
3530 Self::Interval(v) => Err(TypeError::NonNumericValue {
3531 value: v.to_string(),
3532 dtype: DType::Interval,
3533 }),
3534 Self::Object(object) => Err(TypeError::NonNumericValue {
3535 value: object.repr(),
3536 dtype: DType::Utf8,
3537 }),
3538 }
3539 }
3540
3541 pub fn to_bool(&self) -> Result<bool, TypeError> {
3543 match self {
3544 Self::Bool(v) => Ok(*v),
3545 Self::Int64(v) => Ok(*v != 0),
3546 Self::Float64(v) => Ok(*v != 0.0 && !v.is_nan()),
3547 Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3548 Self::Utf8(v) => Ok(!v.is_empty()),
3549 Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3550 kind: NullKind::NaT,
3551 }),
3552 Self::Timedelta64(v) => Ok(*v != 0),
3553 Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3554 kind: NullKind::NaT,
3555 }),
3556 Self::Datetime64(v) => Ok(*v != 0),
3557 Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3558 kind: NullKind::NaT,
3559 }),
3560 Self::Period(p) => Ok(p.ordinal != 0),
3561 Self::Interval(_) => Ok(true),
3562 Self::Object(ObjectValue::List(items)) => Ok(!items.is_empty()),
3565 Self::Object(ObjectValue::Bytes(data)) => Ok(!data.is_empty()),
3566 Self::Object(ObjectValue::Host(_)) => Ok(true),
3567 }
3568 }
3569
3570 pub fn to_str(&self) -> String {
3572 match self {
3573 Self::Bool(v) => if *v { "True" } else { "False" }.to_string(),
3574 Self::Int64(v) => v.to_string(),
3575 Self::Float64(v) => {
3576 if v.is_nan() {
3577 "nan".to_string()
3578 } else if v.is_infinite() {
3579 if *v > 0.0 { "inf" } else { "-inf" }.to_string()
3580 } else {
3581 v.to_string()
3582 }
3583 }
3584 Self::Null(_) => "NaN".to_string(),
3585 Self::Utf8(v) => v.clone(),
3586 Self::Timedelta64(v) => Timedelta::format(*v),
3587 Self::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_string(),
3588 Self::Datetime64(v) => Timestamp::from_nanos(*v).isoformat(),
3589 Self::Period(p) if p.ordinal == i64::MIN => "NaT".to_string(),
3590 Self::Period(p) => p.calendar_string(),
3591 Self::Interval(v) => v.to_string(),
3592 Self::Object(object) => object.to_string(),
3593 }
3594 }
3595}
3596
3597#[derive(Debug, Error, Clone, PartialEq)]
3598pub enum TypeError {
3599 #[error("dtype coercion from {left:?} to {right:?} has no compatible common type")]
3600 IncompatibleDtypes { left: DType, right: DType },
3601 #[error("cannot cast scalar of dtype {from:?} to {to:?}")]
3602 InvalidCast { from: DType, to: DType },
3603 #[error("cannot cast float {value} to int64 without loss")]
3604 LossyFloatToInt { value: f64 },
3605 #[error("expected 0/1 for bool cast from int64 but found {value}")]
3606 InvalidBoolInt { value: i64 },
3607 #[error("expected 0.0/1.0 for bool cast from float64 but found {value}")]
3608 InvalidBoolFloat { value: f64 },
3609 #[error("value {value:?} has non-numeric dtype {dtype:?}")]
3610 NonNumericValue { value: String, dtype: DType },
3611 #[error("value is missing ({kind:?})")]
3612 ValueIsMissing { kind: NullKind },
3613 #[error("sparse value dtype cannot be {dtype:?}")]
3614 InvalidSparseValueDType { dtype: DType },
3615 #[error("interval_range step must be finite, positive, and not NaN (got {step})")]
3616 InvalidIntervalStep { step: f64 },
3617 #[error("interval_range step {step} does not evenly divide range end-start={span}")]
3618 IntervalStepDoesNotDivide { step: f64, span: f64 },
3619 #[error("interval_range requires exactly 3 of (start, end, periods, freq) to be specified")]
3620 IntervalRangeParameterCount,
3621 #[error("cannot parse '{value}' as {target}")]
3622 ValueNotParseable { value: String, target: String },
3623 #[error("{0}")]
3624 TimeZone(#[from] TimeZoneError),
3625 #[error("Cannot localize tz-aware Timestamp, use tz_convert for conversions")]
3626 AlreadyTzAware,
3627 #[error("Cannot convert tz-naive Timestamp, use tz_localize to localize")]
3628 TzNaiveCannotConvert,
3629}
3630
3631pub fn common_dtype(left: DType, right: DType) -> Result<DType, TypeError> {
3632 use DType::{
3633 Bool, BoolNullable, Categorical, Float64, Float64Nullable, Int64, Int64Nullable, Null,
3634 Sparse, Timedelta64,
3635 };
3636
3637 let out = match (&left, &right) {
3638 (a, b) if a == b => a.clone(),
3639 (Null, other) | (other, Null) => other.clone(),
3640 (Categorical, Categorical) => Categorical,
3641
3642 (Bool, Int64) | (Int64, Bool) => Int64,
3644 (Bool, Int64Nullable) | (Int64Nullable, Bool) => Int64Nullable,
3645 (BoolNullable, Int64) | (Int64, BoolNullable) => Int64Nullable,
3646 (BoolNullable, Int64Nullable) | (Int64Nullable, BoolNullable) => Int64Nullable,
3647 (Bool, BoolNullable) | (BoolNullable, Bool) => BoolNullable,
3648 (Bool, Float64) | (Float64, Bool) => Float64,
3649 (BoolNullable, Float64) | (Float64, BoolNullable) => Float64Nullable,
3655
3656 (Int64, Float64) | (Float64, Int64) => Float64,
3658 (Int64Nullable, Float64) | (Float64, Int64Nullable) => Float64Nullable,
3672 (Int64, Int64Nullable) | (Int64Nullable, Int64) => Int64Nullable,
3673
3674 (Float64Nullable, Float64) | (Float64, Float64Nullable) => Float64Nullable,
3691 (Float64Nullable, Int64) | (Int64, Float64Nullable) => Float64Nullable,
3692 (Float64Nullable, Int64Nullable) | (Int64Nullable, Float64Nullable) => Float64Nullable,
3693 (Float64Nullable, Bool) | (Bool, Float64Nullable) => Float64Nullable,
3694 (Float64Nullable, BoolNullable) | (BoolNullable, Float64Nullable) => Float64Nullable,
3695
3696 (Timedelta64, Timedelta64) => Timedelta64,
3698 (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
3699 if left_tz == right_tz =>
3700 {
3701 DType::Datetime64 {
3702 tz: left_tz.clone(),
3703 }
3704 }
3705
3706 (Sparse, _) | (_, Sparse) => {
3707 return Err(TypeError::IncompatibleDtypes {
3708 left: left.clone(),
3709 right: right.clone(),
3710 });
3711 }
3712 _ => {
3713 return Err(TypeError::IncompatibleDtypes { left, right });
3714 }
3715 };
3716
3717 Ok(out)
3718}
3719
3720pub fn infer_dtype(values: &[Scalar]) -> Result<DType, TypeError> {
3721 let mut current = DType::Null;
3722 let mut saw_utf8 = false;
3723 let mut saw_timedelta = false;
3724 let mut saw_datetime = false;
3725 let mut saw_non_utf8_non_null = false;
3726 let mut saw_bool = false;
3733 let mut saw_numeric = false;
3734 let mut period_freq: Option<PeriodFreq> = None;
3739
3740 for value in values {
3754 if let Scalar::Period(period) = value
3755 && period.ordinal != i64::MIN
3756 {
3757 match period_freq {
3758 None => period_freq = Some(period.freq),
3759 Some(freq) if freq != period.freq => {
3760 return Err(TypeError::IncompatibleDtypes {
3761 left: DType::Period,
3762 right: DType::Period,
3763 });
3764 }
3765 Some(_) => {}
3766 }
3767 }
3768 match value.dtype() {
3769 DType::Null => {}
3770 DType::Utf8 => saw_utf8 = true,
3771 DType::Bool => {
3772 saw_bool = true;
3773 saw_non_utf8_non_null = true;
3774 current = common_dtype(current, DType::Bool)?;
3775 }
3776 DType::Int64 | DType::Float64 => {
3777 saw_numeric = true;
3778 saw_non_utf8_non_null = true;
3779 current = common_dtype(current, value.dtype())?;
3780 }
3781 DType::Timedelta64 => {
3782 saw_timedelta = true;
3783 if current == DType::Null {
3784 current = DType::Timedelta64;
3785 } else if current != DType::Timedelta64 {
3786 return Err(TypeError::IncompatibleDtypes {
3787 left: current,
3788 right: DType::Timedelta64,
3789 });
3790 }
3791 }
3792 DType::Datetime64 { .. } => {
3793 saw_datetime = true;
3794 if current == DType::Null {
3795 current = DType::datetime64_naive();
3796 } else if !current.is_datetime() {
3797 return Err(TypeError::IncompatibleDtypes {
3798 left: current,
3799 right: DType::datetime64_naive(),
3800 });
3801 }
3802 }
3803 other => {
3804 saw_non_utf8_non_null = true;
3805 current = common_dtype(current, other)?;
3806 }
3807 }
3808
3809 if saw_bool && saw_numeric {
3810 return Ok(DType::Utf8);
3814 }
3815 if saw_utf8 && saw_non_utf8_non_null {
3816 return Ok(DType::Utf8);
3820 }
3821 if saw_timedelta && saw_non_utf8_non_null {
3822 return Err(TypeError::IncompatibleDtypes {
3823 left: DType::Timedelta64,
3824 right: current,
3825 });
3826 }
3827 if saw_datetime && saw_non_utf8_non_null {
3828 return Err(TypeError::IncompatibleDtypes {
3829 left: DType::datetime64_naive(),
3830 right: current,
3831 });
3832 }
3833 }
3834
3835 if saw_utf8 {
3836 Ok(DType::Utf8)
3837 } else {
3838 Ok(current)
3839 }
3840}
3841
3842pub fn cast_scalar_owned(value: Scalar, target: DType) -> Result<Scalar, TypeError> {
3845 let from = value.dtype();
3846 if from == target {
3847 return Ok(value);
3848 }
3849 if (from == DType::Int64 && target == DType::Int64Nullable)
3851 || (from == DType::Int64Nullable && target == DType::Int64)
3852 {
3853 return Ok(value);
3854 }
3855 if (from == DType::Bool && target == DType::BoolNullable)
3857 || (from == DType::BoolNullable && target == DType::Bool)
3858 {
3859 return Ok(value);
3860 }
3861 if (from == DType::Float64 && target == DType::Float64Nullable)
3869 || (from == DType::Float64Nullable && target == DType::Float64)
3870 {
3871 return Ok(value);
3872 }
3873 if from.is_datetime() && target.is_datetime() {
3877 return Ok(value);
3878 }
3879 if target == DType::Utf8 {
3880 return Ok(Scalar::Utf8(scalar_to_string_for_astype(value)));
3881 }
3882 if target == DType::Bool
3888 && let Scalar::Float64(v) = &value
3889 && v.is_nan()
3890 {
3891 return Ok(Scalar::Bool(true));
3892 }
3893 if target == DType::Bool {
3919 match &value {
3920 Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3921 return Ok(Scalar::Bool(*nanos != 0));
3922 }
3923 _ => {}
3924 }
3925 }
3926 if target == DType::Int64 {
3951 match &value {
3952 Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3953 return Ok(Scalar::Int64(*nanos));
3954 }
3955 _ => {}
3956 }
3957 }
3958 if value.is_missing() {
3959 return Ok(Scalar::missing_for_dtype(target));
3960 }
3961
3962 match target {
3965 DType::Null => Ok(Scalar::Null(NullKind::Null)),
3966 DType::Bool => match &value {
3967 Scalar::Int64(v) => Ok(Scalar::Bool(*v != 0)),
3970 Scalar::Float64(v) => Ok(Scalar::Bool(*v != 0.0)),
3973 _ => Err(TypeError::InvalidCast { from, to: target }),
3974 },
3975 DType::BoolNullable => match &value {
3976 Scalar::Bool(b) => Ok(Scalar::Bool(*b)),
3981 Scalar::Int64(0) => Ok(Scalar::Bool(false)),
3982 Scalar::Int64(1) => Ok(Scalar::Bool(true)),
3983 Scalar::Int64(v) => Err(TypeError::InvalidBoolInt { value: *v }),
3984 Scalar::Float64(v) if *v == 0.0 => Ok(Scalar::Bool(false)),
3985 Scalar::Float64(v) if *v == 1.0 => Ok(Scalar::Bool(true)),
3986 Scalar::Float64(v) => Err(TypeError::InvalidBoolFloat { value: *v }),
3987 _ => Err(TypeError::InvalidCast { from, to: target }),
3988 },
3989 DType::Int64 | DType::Int64Nullable => match &value {
3990 Scalar::Bool(v) => Ok(Scalar::Int64(i64::from(*v))),
3991 Scalar::Float64(v) => {
3992 if !v.is_finite() {
3999 return Err(TypeError::LossyFloatToInt { value: *v });
4000 }
4001 if *v < i64::MIN as f64 || *v >= 9223372036854775808.0 {
4002 return Err(TypeError::LossyFloatToInt { value: *v });
4003 }
4004 Ok(Scalar::Int64(*v as i64))
4005 }
4006 Scalar::Utf8(s) => {
4007 if let Ok(v) = s.parse::<i64>() {
4010 return Ok(Scalar::Int64(v));
4011 }
4012 if let Ok(f) = s.parse::<f64>()
4013 && f.is_finite()
4014 && f.fract() == 0.0
4015 && f >= i64::MIN as f64
4016 && f < 9223372036854775808.0
4017 {
4018 return Ok(Scalar::Int64(f as i64));
4019 }
4020 Err(TypeError::InvalidCast { from, to: target })
4021 }
4022 _ => Err(TypeError::InvalidCast { from, to: target }),
4023 },
4024 DType::Float64 | DType::Float64Nullable => match &value {
4028 Scalar::Bool(v) => Ok(Scalar::Float64(if *v { 1.0 } else { 0.0 })),
4029 Scalar::Int64(v) => Ok(Scalar::Float64(*v as f64)),
4030 Scalar::Utf8(s) => s
4031 .parse::<f64>()
4032 .map(Scalar::Float64)
4033 .map_err(|_| TypeError::InvalidCast { from, to: target }),
4034 _ => Err(TypeError::InvalidCast { from, to: target }),
4035 },
4036 DType::Utf8 => Ok(Scalar::Utf8(scalar_to_string_for_astype(value))),
4037 DType::Categorical => Err(TypeError::InvalidCast { from, to: target }),
4038 DType::Timedelta64 => match &value {
4039 Scalar::Bool(v) => Ok(Scalar::Timedelta64(i64::from(*v))),
4050 Scalar::Int64(v) => Ok(Scalar::Timedelta64(*v)),
4051 Scalar::Float64(v) => Ok(Scalar::Timedelta64(float_to_temporal_nanos(*v))),
4052 Scalar::Utf8(s) => Timedelta::parse(s)
4053 .map(Scalar::Timedelta64)
4054 .map_err(|_| TypeError::InvalidCast { from, to: target }),
4055 _ => Err(TypeError::InvalidCast { from, to: target }),
4056 },
4057 DType::Datetime64 { .. } => match &value {
4058 Scalar::Bool(v) => Ok(Scalar::Datetime64(i64::from(*v))),
4061 Scalar::Int64(v) => Ok(Scalar::Datetime64(*v)),
4062 Scalar::Float64(v) => Ok(Scalar::Datetime64(float_to_temporal_nanos(*v))),
4063 Scalar::Utf8(s) => Timestamp::parse(s)
4064 .map(|timestamp| Scalar::Datetime64(timestamp.nanos))
4065 .map_err(|_| TypeError::InvalidCast { from, to: target }),
4066 _ => Err(TypeError::InvalidCast { from, to: target }),
4067 },
4068 DType::Period => match &value {
4069 Scalar::Int64(v) => Ok(Scalar::Period(Period::new(*v, PeriodFreq::Daily))),
4072 Scalar::Utf8(s) => Period::parse(s)
4073 .map(Scalar::Period)
4074 .map_err(|_| TypeError::InvalidCast { from, to: target }),
4075 _ => Err(TypeError::InvalidCast { from, to: target }),
4076 },
4077 DType::Interval => match &value {
4078 Scalar::Utf8(s) => Interval::parse(s)
4079 .map(Scalar::Interval)
4080 .map_err(|_| TypeError::InvalidCast { from, to: target }),
4081 _ => Err(TypeError::InvalidCast { from, to: target }),
4082 },
4083 DType::Sparse => Err(TypeError::InvalidCast { from, to: target }),
4084 }
4085}
4086
4087fn float_to_temporal_nanos(value: f64) -> i64 {
4123 if value.is_finite() && value > (i64::MIN as f64) && value < (i64::MAX as f64) {
4126 value as i64
4128 } else {
4129 Timestamp::NAT
4132 }
4133}
4134
4135fn scalar_to_string_for_astype(value: Scalar) -> String {
4136 match value {
4137 Scalar::Null(NullKind::Null) => "None".to_owned(),
4138 Scalar::Null(NullKind::NaN) => "nan".to_owned(),
4139 Scalar::Null(NullKind::NaT) => "NaT".to_owned(),
4140 Scalar::Bool(true) => "True".to_owned(),
4141 Scalar::Bool(false) => "False".to_owned(),
4142 Scalar::Int64(v) => v.to_string(),
4143 Scalar::Float64(v) => float_to_string_for_astype(v),
4144 Scalar::Utf8(s) => s,
4145 Scalar::Timedelta64(v) if v == Timedelta::NAT => "NaT".to_owned(),
4146 Scalar::Timedelta64(v) => Timedelta::format(v),
4147 Scalar::Datetime64(v) if v == Timestamp::NAT => "NaT".to_owned(),
4148 Scalar::Datetime64(v) => timestamp_text(v),
4149 Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
4150 Scalar::Period(p) => p.calendar_string(),
4151 Scalar::Interval(v) => v.to_string(),
4152 Scalar::Object(object) => object.to_string(),
4154 }
4155}
4156
4157pub fn float_to_string_for_astype(value: f64) -> String {
4158 use std::fmt::Write as _;
4159
4160 if value.is_nan() {
4161 return "nan".to_owned();
4162 }
4163 if value.is_infinite() {
4164 return value.to_string(); }
4166 let mut rendered = String::with_capacity(32);
4178 let _ = write!(rendered, "{value:?}");
4179 let Some(exponent_marker) = rendered.find('e') else {
4180 return rendered;
4181 };
4182
4183 let sign_position = exponent_marker + 1;
4184 let digits_position = match rendered.as_bytes().get(sign_position) {
4185 Some(b'+' | b'-') => sign_position + 1,
4186 _ => {
4187 rendered.insert(sign_position, '+');
4188 sign_position + 1
4189 }
4190 };
4191 if rendered.len() - digits_position == 1 {
4192 rendered.insert(digits_position, '0');
4193 }
4194 rendered
4195}
4196
4197static ENG_FLOAT_ACCURACY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(3);
4198static ENG_FLOAT_USE_PREFIX: std::sync::atomic::AtomicBool =
4199 std::sync::atomic::AtomicBool::new(false);
4200static ENG_FLOAT_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
4201
4202pub fn eng_float_format(num: f64, accuracy: Option<usize>, use_eng_prefix: bool) -> String {
4204 if num.is_nan() {
4205 return "NaN".to_string();
4206 }
4207 if num.is_infinite() {
4208 return if num < 0.0 {
4209 "-inf".to_string()
4210 } else {
4211 "inf".to_string()
4212 };
4213 }
4214
4215 let sign = if num < 0.0 { -1.0 } else { 1.0 };
4216 let abs_num = num.abs();
4217
4218 let pow10 = if abs_num != 0.0 {
4219 let p = (abs_num.log10() / 3.0).floor() as i32 * 3;
4220 p.clamp(-24, 24)
4221 } else {
4222 0
4223 };
4224
4225 let prefix = if use_eng_prefix {
4226 match pow10 {
4227 -24 => "y",
4228 -21 => "z",
4229 -18 => "a",
4230 -15 => "f",
4231 -12 => "p",
4232 -9 => "n",
4233 -6 => "u",
4234 -3 => "m",
4235 0 => "",
4236 3 => "k",
4237 6 => "M",
4238 9 => "G",
4239 12 => "T",
4240 15 => "P",
4241 18 => "E",
4242 21 => "Z",
4243 24 => "Y",
4244 _ => "",
4245 }
4246 .to_string()
4247 } else if pow10 < 0 {
4248 format!("E-{:02}", -pow10)
4249 } else {
4250 format!("E+{:02}", pow10)
4251 };
4252
4253 let mant = (sign * abs_num) / 10f64.powi(pow10);
4254
4255 if let Some(acc) = accuracy {
4256 format!("{mant:.acc$}{prefix}", acc = acc)
4257 } else {
4258 format!("{mant}{prefix}")
4259 }
4260}
4261
4262pub fn set_eng_float_format(accuracy: usize, use_eng_prefix: bool) {
4265 use std::sync::atomic::Ordering;
4266 ENG_FLOAT_ACCURACY.store(accuracy, Ordering::Relaxed);
4267 ENG_FLOAT_USE_PREFIX.store(use_eng_prefix, Ordering::Relaxed);
4268 ENG_FLOAT_ACTIVE.store(true, Ordering::Relaxed);
4269}
4270
4271pub fn reset_eng_float_format() {
4273 use std::sync::atomic::Ordering;
4274 ENG_FLOAT_ACTIVE.store(false, Ordering::Relaxed);
4275}
4276
4277pub fn get_eng_float_format() -> Option<(usize, bool)> {
4279 use std::sync::atomic::Ordering;
4280 if ENG_FLOAT_ACTIVE.load(Ordering::Relaxed) {
4281 Some((
4282 ENG_FLOAT_ACCURACY.load(Ordering::Relaxed),
4283 ENG_FLOAT_USE_PREFIX.load(Ordering::Relaxed),
4284 ))
4285 } else {
4286 None
4287 }
4288}
4289
4290#[derive(Debug, Error, Clone, PartialEq, Eq)]
4294pub enum OptionError {
4295 #[error("no such option: '{pat}'")]
4296 NotFound { pat: String },
4297 #[error("option pattern '{pat}' matches multiple options: {matches:?}")]
4298 Ambiguous { pat: String, matches: Vec<String> },
4299 #[error("invalid option value for '{pat}': {reason}")]
4300 InvalidValue { pat: String, reason: String },
4301}
4302
4303#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4305pub enum OptionValue {
4306 None,
4307 Int(i64),
4308 Float(f64),
4309 Bool(bool),
4310 Str(String),
4311}
4312
4313impl OptionValue {
4314 #[must_use]
4315 pub const fn is_none(&self) -> bool {
4316 matches!(self, Self::None)
4317 }
4318
4319 #[must_use]
4320 pub const fn as_int(&self) -> Option<i64> {
4321 match self {
4322 Self::Int(i) => Some(*i),
4323 _ => None,
4324 }
4325 }
4326
4327 #[must_use]
4328 pub const fn as_float(&self) -> Option<f64> {
4329 match self {
4330 Self::Float(f) => Some(*f),
4331 _ => None,
4332 }
4333 }
4334
4335 #[must_use]
4336 pub const fn as_bool(&self) -> Option<bool> {
4337 match self {
4338 Self::Bool(b) => Some(*b),
4339 _ => None,
4340 }
4341 }
4342
4343 #[must_use]
4344 pub fn as_str(&self) -> Option<&str> {
4345 match self {
4346 Self::Str(s) => Some(s.as_str()),
4347 _ => None,
4348 }
4349 }
4350}
4351
4352impl std::fmt::Display for OptionValue {
4353 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4354 match self {
4355 Self::None => write!(f, "None"),
4356 Self::Int(i) => write!(f, "{i}"),
4357 Self::Float(fl) => write!(f, "{fl}"),
4358 Self::Bool(b) => write!(f, "{b}"),
4359 Self::Str(s) => write!(f, "{s}"),
4360 }
4361 }
4362}
4363
4364impl From<i64> for OptionValue {
4365 fn from(v: i64) -> Self {
4366 Self::Int(v)
4367 }
4368}
4369
4370impl From<i32> for OptionValue {
4371 fn from(v: i32) -> Self {
4372 Self::Int(i64::from(v))
4373 }
4374}
4375
4376impl From<usize> for OptionValue {
4377 fn from(v: usize) -> Self {
4378 Self::Int(i64::try_from(v).unwrap_or(i64::MAX))
4379 }
4380}
4381
4382impl From<f64> for OptionValue {
4383 fn from(v: f64) -> Self {
4384 Self::Float(v)
4385 }
4386}
4387
4388impl From<bool> for OptionValue {
4389 fn from(v: bool) -> Self {
4390 Self::Bool(v)
4391 }
4392}
4393
4394impl From<&str> for OptionValue {
4395 fn from(v: &str) -> Self {
4396 Self::Str(v.to_string())
4397 }
4398}
4399
4400impl From<String> for OptionValue {
4401 fn from(v: String) -> Self {
4402 Self::Str(v)
4403 }
4404}
4405
4406impl From<()> for OptionValue {
4407 fn from(_: ()) -> Self {
4408 Self::None
4409 }
4410}
4411
4412fn default_options_map() -> std::collections::BTreeMap<String, OptionValue> {
4413 let mut m = std::collections::BTreeMap::new();
4414 m.insert("display.max_rows".to_string(), OptionValue::Int(60));
4415 m.insert("display.min_rows".to_string(), OptionValue::Int(10));
4416 m.insert("display.max_columns".to_string(), OptionValue::Int(0));
4417 m.insert("display.width".to_string(), OptionValue::Int(80));
4418 m.insert("display.precision".to_string(), OptionValue::Int(6));
4419 m.insert("display.max_colwidth".to_string(), OptionValue::Int(50));
4420 m.insert(
4421 "display.show_dimensions".to_string(),
4422 OptionValue::Bool(true),
4423 );
4424 m.insert("display.float_format".to_string(), OptionValue::None);
4425 m.insert(
4426 "display.large_repr".to_string(),
4427 OptionValue::Str("truncate".to_string()),
4428 );
4429 m.insert(
4430 "display.max_info_columns".to_string(),
4431 OptionValue::Int(100),
4432 );
4433 m.insert(
4434 "display.max_info_rows".to_string(),
4435 OptionValue::Int(1690785),
4436 );
4437 m.insert("display.memory_usage".to_string(), OptionValue::Bool(true));
4438 m.insert(
4439 "display.colheader_justify".to_string(),
4440 OptionValue::Str("right".to_string()),
4441 );
4442 m.insert("display.chop_threshold".to_string(), OptionValue::None);
4443 m.insert(
4444 "display.date_dayfirst".to_string(),
4445 OptionValue::Bool(false),
4446 );
4447 m.insert(
4448 "display.date_yearfirst".to_string(),
4449 OptionValue::Bool(false),
4450 );
4451 m.insert(
4452 "display.encoding".to_string(),
4453 OptionValue::Str("utf-8".to_string()),
4454 );
4455 m.insert("mode.sim_interactive".to_string(), OptionValue::Bool(false));
4456 m.insert(
4457 "mode.chained_assignment".to_string(),
4458 OptionValue::Str("warn".to_string()),
4459 );
4460 m.insert("mode.use_inf_as_na".to_string(), OptionValue::Bool(false));
4461 m.insert("mode.copy_on_write".to_string(), OptionValue::Bool(false));
4462 m.insert(
4463 "mode.data_manager".to_string(),
4464 OptionValue::Str("block".to_string()),
4465 );
4466 m.insert(
4467 "compute.use_bottleneck".to_string(),
4468 OptionValue::Bool(true),
4469 );
4470 m.insert("compute.use_numba".to_string(), OptionValue::Bool(false));
4471 m.insert(
4472 "io.excel.zip.reader".to_string(),
4473 OptionValue::Str("zipfile".to_string()),
4474 );
4475 m.insert(
4476 "io.parquet.engine".to_string(),
4477 OptionValue::Str("auto".to_string()),
4478 );
4479 m.insert(
4480 "io.sql.engine".to_string(),
4481 OptionValue::Str("auto".to_string()),
4482 );
4483 m.insert(
4484 "plotting.backend".to_string(),
4485 OptionValue::Str("matplotlib".to_string()),
4486 );
4487 m.insert(
4488 "plotting.matplotlib.register_converters".to_string(),
4489 OptionValue::Bool(true),
4490 );
4491 m
4492}
4493
4494static GLOBAL_OPTIONS: std::sync::LazyLock<
4495 std::sync::Mutex<std::collections::BTreeMap<String, OptionValue>>,
4496> = std::sync::LazyLock::new(|| std::sync::Mutex::new(default_options_map()));
4497
4498fn resolve_option_key(
4499 pat: &str,
4500 map: &std::collections::BTreeMap<String, OptionValue>,
4501) -> Result<String, OptionError> {
4502 if map.contains_key(pat) {
4503 return Ok(pat.to_string());
4504 }
4505 let matches: Vec<String> = map
4506 .keys()
4507 .filter(|k| k.ends_with(pat) || k.contains(pat))
4508 .cloned()
4509 .collect();
4510 if matches.len() == 1 {
4511 Ok(matches[0].clone())
4512 } else if matches.is_empty() {
4513 Err(OptionError::NotFound {
4514 pat: pat.to_string(),
4515 })
4516 } else {
4517 Err(OptionError::Ambiguous {
4518 pat: pat.to_string(),
4519 matches,
4520 })
4521 }
4522}
4523
4524pub fn get_option(pat: &str) -> Result<OptionValue, OptionError> {
4530 let map = GLOBAL_OPTIONS
4531 .lock()
4532 .unwrap_or_else(std::sync::PoisonError::into_inner);
4533 let key = resolve_option_key(pat, &map)?;
4534 Ok(map.get(&key).cloned().unwrap_or(OptionValue::None))
4535}
4536
4537pub fn set_option(pat: &str, val: impl Into<OptionValue>) -> Result<(), OptionError> {
4543 let mut map = GLOBAL_OPTIONS
4544 .lock()
4545 .unwrap_or_else(std::sync::PoisonError::into_inner);
4546 let key = resolve_option_key(pat, &map)?;
4547 let v = val.into();
4548 map.insert(key, v);
4549 Ok(())
4550}
4551
4552pub fn reset_option(pat: Option<&str>) -> Result<(), OptionError> {
4559 let mut map = GLOBAL_OPTIONS
4560 .lock()
4561 .unwrap_or_else(std::sync::PoisonError::into_inner);
4562 let defaults = default_options_map();
4563 let p = pat.unwrap_or("all");
4564 if p == "all" {
4565 *map = defaults;
4566 return Ok(());
4567 }
4568 let key = resolve_option_key(p, &defaults)?;
4569 if let Some(def_val) = defaults.get(&key) {
4570 map.insert(key, def_val.clone());
4571 }
4572 Ok(())
4573}
4574
4575pub fn describe_option(pat: Option<&str>) -> Result<String, OptionError> {
4580 use std::fmt::Write as _;
4581 let map = GLOBAL_OPTIONS
4582 .lock()
4583 .unwrap_or_else(std::sync::PoisonError::into_inner);
4584 let mut out = String::with_capacity(map.len() * 40);
4585 let mut matched = 0;
4586 for (k, v) in map.iter() {
4587 if let Some(p) = pat
4588 && !k.contains(p)
4589 {
4590 continue;
4591 }
4592 if matched > 0 {
4593 out.push('\n');
4594 }
4595 let _ = write!(out, "{k} : [currently: {v}]");
4596 matched += 1;
4597 }
4598 if matched == 0
4599 && let Some(p) = pat
4600 {
4601 return Err(OptionError::NotFound { pat: p.to_string() });
4602 }
4603 Ok(out)
4604}
4605
4606#[derive(Debug)]
4608pub struct OptionContextGuard {
4609 saved: Vec<(String, OptionValue)>,
4610}
4611
4612impl Drop for OptionContextGuard {
4613 fn drop(&mut self) {
4614 let mut map = GLOBAL_OPTIONS
4615 .lock()
4616 .unwrap_or_else(std::sync::PoisonError::into_inner);
4617 for (k, old) in self.saved.drain(..) {
4618 map.insert(k, old);
4619 }
4620 }
4621}
4622
4623pub fn option_context(entries: &[(&str, OptionValue)]) -> Result<OptionContextGuard, OptionError> {
4628 let mut map = GLOBAL_OPTIONS
4629 .lock()
4630 .unwrap_or_else(std::sync::PoisonError::into_inner);
4631 let mut saved = Vec::with_capacity(entries.len());
4632 for (pat, new_val) in entries {
4633 let key = resolve_option_key(pat, &map)?;
4634 if let Some(old) = map.get(&key) {
4635 saved.push((key.clone(), old.clone()));
4636 }
4637 map.insert(key, new_val.clone());
4638 }
4639 Ok(OptionContextGuard { saved })
4640}
4641
4642pub fn cast_scalar(value: &Scalar, target: DType) -> Result<Scalar, TypeError> {
4644 cast_scalar_owned(value.clone(), target)
4645}
4646
4647#[derive(Debug, Error, Clone, PartialEq)]
4650pub enum TimedeltaError {
4651 #[error("invalid timedelta string: {0}")]
4652 InvalidFormat(String),
4653 #[error("overflow in timedelta computation")]
4654 Overflow,
4655}
4656
4657impl TimedeltaError {
4658 #[must_use]
4664 pub const fn pandas_error(&self) -> Option<PandasTemporalError> {
4665 match self {
4666 Self::Overflow => Some(PandasTemporalError::OutOfBoundsTimedelta),
4669 Self::InvalidFormat(_) => None,
4670 }
4671 }
4672}
4673
4674#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4675pub struct CategoricalMetadata {
4676 pub categories: Vec<Scalar>,
4678 pub ordered: bool,
4680}
4681
4682impl CategoricalMetadata {
4683 #[must_use]
4684 pub fn new(categories: Vec<Scalar>, ordered: bool) -> Self {
4685 Self {
4686 categories,
4687 ordered,
4688 }
4689 }
4690}
4691
4692#[derive(Debug, Clone, Copy, Default)]
4693pub struct TimedeltaComponents {
4694 pub days: i64,
4695 pub hours: i64,
4696 pub minutes: i64,
4697 pub seconds: i64,
4698 pub milliseconds: i64,
4699 pub microseconds: i64,
4700 pub nanoseconds: i64,
4701}
4702
4703#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4715pub enum PandasTemporalError {
4716 Overflow,
4720 OutOfBoundsDatetime,
4723 OutOfBoundsTimedelta,
4728 OverflowInTimedeltaOperation,
4731 ZeroDivision,
4740}
4741
4742#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4745pub struct TemporalFailure {
4746 pub op: &'static str,
4748 pub pandas_error: PandasTemporalError,
4750 pub operands: Option<(i64, i64)>,
4755}
4756
4757impl TemporalFailure {
4758 #[must_use]
4759 pub const fn new(op: &'static str, pandas_error: PandasTemporalError) -> Self {
4760 Self {
4761 op,
4762 pandas_error,
4763 operands: None,
4764 }
4765 }
4766
4767 #[must_use]
4769 pub const fn with_operands(mut self, lhs: i64, rhs: i64) -> Self {
4770 self.operands = Some((lhs, rhs));
4771 self
4772 }
4773}
4774
4775#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4785pub struct TemporalRecovery {
4786 pub op: &'static str,
4788 pub pandas_error: PandasTemporalError,
4790 pub operands: Option<(i64, i64)>,
4792 pub recovered_as: i64,
4794}
4795
4796pub mod overflow_audit {
4805 use std::cell::RefCell;
4806
4807 use super::TemporalRecovery;
4808
4809 thread_local! {
4810 static LOG: RefCell<Option<Vec<TemporalRecovery>>> = const { RefCell::new(None) };
4811 }
4812
4813 pub fn enable() {
4815 LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
4816 }
4817
4818 pub fn disable() {
4820 LOG.with(|log| *log.borrow_mut() = None);
4821 }
4822
4823 #[must_use]
4825 pub fn is_enabled() -> bool {
4826 LOG.with(|log| log.borrow().is_some())
4827 }
4828
4829 #[must_use]
4831 pub fn drain() -> Vec<TemporalRecovery> {
4832 LOG.with(|log| match log.borrow_mut().as_mut() {
4833 Some(entries) => std::mem::take(entries),
4834 None => Vec::new(),
4835 })
4836 }
4837
4838 pub(super) fn record(entry: TemporalRecovery) {
4840 LOG.with(|log| {
4841 if let Some(entries) = log.borrow_mut().as_mut() {
4842 entries.push(entry);
4843 }
4844 });
4845 }
4846}
4847
4848#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
4861pub enum OverflowPolicy {
4862 #[default]
4865 SurfaceNat,
4866 Strict,
4868 HardenedNat,
4876}
4877
4878impl OverflowPolicy {
4879 pub fn resolve<T>(
4887 self,
4888 outcome: Result<T, TemporalFailure>,
4889 nat: T,
4890 ) -> Result<T, TemporalFailure> {
4891 self.resolve_recording(outcome, nat, i64::MIN)
4892 }
4893
4894 pub fn resolve_recording<T>(
4903 self,
4904 outcome: Result<T, TemporalFailure>,
4905 nat: T,
4906 recovered_as: i64,
4907 ) -> Result<T, TemporalFailure> {
4908 match (self, outcome) {
4909 (_, Ok(value)) => Ok(value),
4910 (Self::SurfaceNat, Err(_)) => Ok(nat),
4911 (Self::Strict, Err(failure)) => Err(failure),
4912 (Self::HardenedNat, Err(failure)) => {
4913 overflow_audit::record(TemporalRecovery {
4915 op: failure.op,
4916 pandas_error: failure.pandas_error,
4917 operands: failure.operands,
4918 recovered_as,
4919 });
4920 Ok(nat)
4921 }
4922 }
4923 }
4924}
4925
4926pub struct Timedelta;
4927
4928impl Timedelta {
4929 pub const NANOS_PER_MICRO: i64 = 1_000;
4930 pub const NANOS_PER_MILLI: i64 = 1_000_000;
4931 pub const NANOS_PER_SEC: i64 = 1_000_000_000;
4932 pub const NANOS_PER_MIN: i64 = 60 * Self::NANOS_PER_SEC;
4933 pub const NANOS_PER_HOUR: i64 = 60 * Self::NANOS_PER_MIN;
4934 pub const NANOS_PER_DAY: i64 = 24 * Self::NANOS_PER_HOUR;
4935 pub const NANOS_PER_WEEK: i64 = 7 * Self::NANOS_PER_DAY;
4936
4937 pub const NAT: i64 = i64::MIN;
4938
4939 pub fn parse(s: &str) -> Result<i64, TimedeltaError> {
4940 let s = s.trim();
4941
4942 if s.eq_ignore_ascii_case("nat") {
4943 return Ok(Self::NAT);
4944 }
4945
4946 let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
4947 (true, rest.trim())
4948 } else {
4949 (false, s)
4950 };
4951
4952 if let Some(nanos) = Self::try_parse_time_format(s) {
4953 return Ok(if negative { -nanos } else { nanos });
4954 }
4955
4956 if let Some(nanos) = Self::try_parse_iso8601_duration(s) {
4957 return Ok(if negative { -nanos } else { nanos });
4958 }
4959
4960 let (units, clock) = Self::parse_compound(s)?;
4966 let units = if negative { -units } else { units };
4967 units.checked_add(clock).ok_or(TimedeltaError::Overflow)
4968 }
4969
4970 fn try_parse_iso8601_duration(s: &str) -> Option<i64> {
4978 let mut rest = s.strip_prefix('P')?;
4979 if rest.is_empty() {
4980 return None;
4981 }
4982 let mut total: i64 = 0;
4983 let mut saw_component = false;
4984 while !rest.is_empty() {
4985 if let Some(after_t) = rest.strip_prefix('T') {
4986 rest = after_t;
4987 continue;
4988 }
4989 let num_end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')?;
4990 if num_end == 0 {
4991 return None;
4992 }
4993 let num_str = &rest[..num_end];
4994 let unit = rest.as_bytes()[num_end];
4995 let is_fractional = num_str.contains('.');
4996 rest = &rest[num_end + 1..];
4997
4998 let (multiplier, frac_ok) = match unit {
4999 b'W' => (Self::NANOS_PER_WEEK, false),
5000 b'D' => (Self::NANOS_PER_DAY, false),
5001 b'H' => (Self::NANOS_PER_HOUR, false),
5002 b'M' => (Self::NANOS_PER_MIN, false),
5003 b'S' => (Self::NANOS_PER_SEC, true),
5004 _ => return None,
5005 };
5006 if is_fractional {
5007 if !frac_ok {
5008 return None;
5009 }
5010 let value: f64 = num_str.parse().ok()?;
5011 let product = value * multiplier as f64;
5012 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5013 return None;
5014 }
5015 total = total.checked_add(product.round() as i64)?;
5016 } else {
5017 let value: i64 = num_str.parse().ok()?;
5018 total = total.checked_add(value.checked_mul(multiplier)?)?;
5019 }
5020 saw_component = true;
5021 }
5022 saw_component.then_some(total)
5023 }
5024
5025 fn try_parse_time_format(s: &str) -> Option<i64> {
5026 let parts: Vec<&str> = s.split(':').collect();
5027 if parts.len() < 2 || parts.len() > 3 {
5028 return None;
5029 }
5030
5031 let hours: i64 = parts[0].parse().ok()?;
5032 let minutes: i64 = parts[1].parse().ok()?;
5033
5034 let (seconds, frac_nanos) = if parts.len() == 3 {
5035 if let Some((sec_str, frac_str)) = parts[2].split_once('.') {
5036 let sec: i64 = sec_str.parse().ok()?;
5037 if !frac_str.bytes().all(|byte| byte.is_ascii_digit()) {
5038 return None;
5039 }
5040 let mut frac = 0_i64;
5041 let taken = frac_str.len().min(9);
5042 for byte in frac_str.bytes().take(9) {
5043 frac = frac * 10 + i64::from(byte - b'0');
5044 }
5045 for _ in taken..9 {
5046 frac *= 10;
5047 }
5048 (sec, frac)
5049 } else {
5050 let sec: i64 = parts[2].parse().ok()?;
5051 (sec, 0)
5052 }
5053 } else {
5054 (0, 0)
5055 };
5056
5057 hours
5058 .checked_mul(Self::NANOS_PER_HOUR)?
5059 .checked_add(minutes.checked_mul(Self::NANOS_PER_MIN)?)?
5060 .checked_add(seconds.checked_mul(Self::NANOS_PER_SEC)?)?
5061 .checked_add(frac_nanos)
5062 }
5063
5064 fn parse_compound(s: &str) -> Result<(i64, i64), TimedeltaError> {
5070 let mut total: i64 = 0;
5071 let mut clock: i64 = 0;
5072 let mut remaining = s;
5073
5074 while !remaining.is_empty() {
5075 remaining = remaining.trim_start();
5076 if remaining.is_empty() {
5077 break;
5078 }
5079 if remaining.starts_with('-') {
5080 return Err(TimedeltaError::InvalidFormat(format!(
5081 "only leading negative signs are allowed: {s}"
5082 )));
5083 }
5084
5085 if remaining.contains(':')
5088 && let Some(time_nanos) = Self::try_parse_time_format(remaining)
5089 {
5090 clock = time_nanos;
5091 break;
5092 }
5093
5094 let num_end = remaining
5095 .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
5096 .unwrap_or(remaining.len());
5097
5098 if num_end == 0 {
5099 return Err(TimedeltaError::InvalidFormat(s.to_string()));
5100 }
5101
5102 let num_str = &remaining[..num_end];
5103 let num: f64 = num_str
5104 .parse()
5105 .map_err(|_| TimedeltaError::InvalidFormat(s.to_string()))?;
5106
5107 remaining = remaining[num_end..].trim_start();
5108
5109 let unit_end = remaining
5110 .find(|c: char| c.is_ascii_digit() || c.is_whitespace())
5111 .unwrap_or(remaining.len());
5112
5113 let unit = &remaining[..unit_end];
5114 remaining = &remaining[unit_end..];
5115
5116 let multiplier = Self::unit_to_nanos(unit)
5117 .ok_or_else(|| TimedeltaError::InvalidFormat(s.to_string()))?;
5118
5119 let product = num * multiplier as f64;
5124 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5125 return Err(TimedeltaError::Overflow);
5126 }
5127 let nanos = product.round() as i64;
5128 total = total.checked_add(nanos).ok_or(TimedeltaError::Overflow)?;
5129 }
5130
5131 Ok((total, clock))
5141 }
5142
5143 #[must_use]
5157 pub fn unit_to_nanos(unit: &str) -> Option<i64> {
5158 match unit.to_lowercase().as_str() {
5159 "w" | "week" | "weeks" => Some(Self::NANOS_PER_WEEK),
5160 "d" | "day" | "days" => Some(Self::NANOS_PER_DAY),
5161 "h" | "hr" | "hour" | "hours" => Some(Self::NANOS_PER_HOUR),
5162 "m" | "min" | "minute" | "minutes" | "t" => Some(Self::NANOS_PER_MIN),
5163 "s" | "sec" | "second" | "seconds" => Some(Self::NANOS_PER_SEC),
5164 "ms" | "milli" | "millis" | "millisecond" | "milliseconds" | "l" => {
5165 Some(Self::NANOS_PER_MILLI)
5166 }
5167 "us" | "µs" | "micro" | "micros" | "microsecond" | "microseconds" | "u" => {
5168 Some(Self::NANOS_PER_MICRO)
5169 }
5170 "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" | "n" => Some(1),
5171 "" => Some(Self::NANOS_PER_DAY),
5172 _ => None,
5173 }
5174 }
5175
5176 pub fn components(nanos: i64) -> TimedeltaComponents {
5177 if nanos == Self::NAT {
5178 return TimedeltaComponents::default();
5179 }
5180
5181 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5186 let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5187
5188 let hours = rem / Self::NANOS_PER_HOUR;
5189 let rem = rem % Self::NANOS_PER_HOUR;
5190
5191 let minutes = rem / Self::NANOS_PER_MIN;
5192 let rem = rem % Self::NANOS_PER_MIN;
5193
5194 let seconds = rem / Self::NANOS_PER_SEC;
5195 let rem = rem % Self::NANOS_PER_SEC;
5196
5197 let milliseconds = rem / Self::NANOS_PER_MILLI;
5198 let rem = rem % Self::NANOS_PER_MILLI;
5199
5200 let microseconds = rem / Self::NANOS_PER_MICRO;
5201 let nanoseconds = rem % Self::NANOS_PER_MICRO;
5202
5203 TimedeltaComponents {
5204 days,
5205 hours,
5206 minutes,
5207 seconds,
5208 milliseconds,
5209 microseconds,
5210 nanoseconds,
5211 }
5212 }
5213
5214 pub fn total_seconds(nanos: i64) -> f64 {
5215 if nanos == Self::NAT {
5216 f64::NAN
5217 } else {
5218 nanos as f64 / Self::NANOS_PER_SEC as f64
5219 }
5220 }
5221
5222 #[must_use]
5226 pub fn as_unit(nanos: i64, unit: &str) -> f64 {
5227 if nanos == Self::NAT {
5228 return f64::NAN;
5229 }
5230 let nanos_f = nanos as f64;
5231 match unit {
5232 "ns" | "nanoseconds" => nanos_f,
5233 "us" | "microseconds" => nanos_f / Self::NANOS_PER_MICRO as f64,
5234 "ms" | "milliseconds" => nanos_f / Self::NANOS_PER_MILLI as f64,
5235 "s" | "seconds" => nanos_f / Self::NANOS_PER_SEC as f64,
5236 "m" | "minutes" => nanos_f / Self::NANOS_PER_MIN as f64,
5237 "h" | "hours" => nanos_f / Self::NANOS_PER_HOUR as f64,
5238 "D" | "days" => nanos_f / Self::NANOS_PER_DAY as f64,
5239 _ => f64::NAN,
5240 }
5241 }
5242
5243 #[must_use]
5263 pub fn days(nanos: i64) -> Option<i64> {
5264 if nanos == Self::NAT {
5265 return None;
5266 }
5267 Some(nanos.div_euclid(Self::NANOS_PER_DAY))
5269 }
5270
5271 #[must_use]
5274 pub fn seconds(nanos: i64) -> Option<i64> {
5275 if nanos == Self::NAT {
5276 return None;
5277 }
5278 Some(nanos.rem_euclid(Self::NANOS_PER_DAY) / Self::NANOS_PER_SEC)
5280 }
5281
5282 #[must_use]
5285 pub fn microseconds(nanos: i64) -> Option<i64> {
5286 if nanos == Self::NAT {
5287 return None;
5288 }
5289 Some(nanos.rem_euclid(Self::NANOS_PER_SEC) / Self::NANOS_PER_MICRO)
5290 }
5291
5292 #[must_use]
5295 pub fn nanoseconds(nanos: i64) -> Option<i64> {
5296 if nanos == Self::NAT {
5297 return None;
5298 }
5299 Some(nanos.rem_euclid(Self::NANOS_PER_MICRO))
5300 }
5301
5302 #[must_use]
5308 pub const fn string_resolution(nanos: i64) -> TimedeltaStringResolution {
5309 if nanos == Self::NAT || nanos.rem_euclid(Self::NANOS_PER_DAY) == 0 {
5310 TimedeltaStringResolution::Days
5311 } else {
5312 TimedeltaStringResolution::Full
5313 }
5314 }
5315
5316 #[must_use]
5324 pub fn format_at_resolution(nanos: i64, resolution: TimedeltaStringResolution) -> String {
5325 if nanos == Self::NAT {
5326 return "NaT".to_string();
5327 }
5328 match resolution {
5329 TimedeltaStringResolution::Full => Self::format(nanos),
5330 TimedeltaStringResolution::Days => {
5333 format!("{} days", nanos.div_euclid(Self::NANOS_PER_DAY))
5334 }
5335 }
5336 }
5337
5338 pub fn format(nanos: i64) -> String {
5339 use std::fmt::Write as _;
5340
5341 if nanos == Self::NAT {
5342 return "NaT".to_string();
5343 }
5344
5345 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5351 let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5352 let hours = rem / Self::NANOS_PER_HOUR;
5353 let minutes = (rem % Self::NANOS_PER_HOUR) / Self::NANOS_PER_MIN;
5354 let seconds = (rem % Self::NANOS_PER_MIN) / Self::NANOS_PER_SEC;
5355 let frac = rem % Self::NANOS_PER_SEC;
5356
5357 let mut result = String::with_capacity(32);
5360 let _ = write!(result, "{days} days ");
5361 if days < 0 {
5363 result.push('+');
5364 }
5365 let _ = write!(result, "{hours:02}:{minutes:02}:{seconds:02}");
5366 if frac > 0 {
5367 if frac % 1_000 == 0 {
5371 let _ = write!(result, ".{:06}", frac / 1_000);
5372 } else {
5373 let _ = write!(result, ".{frac:09}");
5374 }
5375 }
5376 result
5377 }
5378
5379 pub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError> {
5396 let multiplier = Self::unit_to_nanos(unit)
5397 .ok_or_else(|| TimedeltaError::InvalidFormat(unit.to_string()))?;
5398 if value.is_nan() {
5399 return Ok(Self::NAT);
5400 }
5401 let product = value * multiplier as f64;
5402 if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5403 return Err(TimedeltaError::Overflow);
5404 }
5405 Ok(product.round() as i64)
5406 }
5407
5408 pub fn try_add(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5448 if a == Self::NAT || b == Self::NAT {
5449 return Ok(Self::NAT);
5450 }
5451 a.checked_add(b).ok_or(
5452 TemporalFailure::new("Timedelta::add", PandasTemporalError::Overflow)
5453 .with_operands(a, b),
5454 )
5455 }
5456
5457 #[must_use]
5459 pub fn add(a: i64, b: i64) -> i64 {
5460 Self::try_add(a, b).unwrap_or(Self::NAT)
5461 }
5462
5463 pub fn try_sub(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5468 if a == Self::NAT || b == Self::NAT {
5469 return Ok(Self::NAT);
5470 }
5471 a.checked_sub(b).ok_or(
5472 TemporalFailure::new("Timedelta::sub", PandasTemporalError::Overflow)
5473 .with_operands(a, b),
5474 )
5475 }
5476
5477 #[must_use]
5479 pub fn sub(a: i64, b: i64) -> i64 {
5480 Self::try_sub(a, b).unwrap_or(Self::NAT)
5481 }
5482
5483 #[must_use]
5501 pub fn neg(a: i64) -> i64 {
5502 if a == Self::NAT {
5503 return Self::NAT;
5504 }
5505 a.saturating_neg()
5506 }
5507
5508 #[must_use]
5515 pub fn abs(a: i64) -> i64 {
5516 if a == Self::NAT {
5517 return Self::NAT;
5518 }
5519 a.saturating_abs()
5520 }
5521
5522 #[must_use]
5528 pub fn mul_scalar(a: i64, factor: i64) -> i64 {
5529 Self::try_mul_scalar(a, factor).unwrap_or(Self::NAT)
5530 }
5531
5532 #[must_use]
5553 pub fn mul_scalar_with_policy(a: i64, factor: i64, policy: OverflowPolicy) -> i64 {
5554 if a == Self::NAT {
5555 return Self::NAT;
5556 }
5557 if matches!(policy, OverflowPolicy::Strict) {
5558 return a.wrapping_mul(factor);
5559 }
5560 policy
5561 .resolve_recording(Self::try_mul_scalar(a, factor), Self::NAT, Self::NAT)
5562 .unwrap_or(Self::NAT)
5563 }
5564
5565 pub fn try_mul_scalar(a: i64, factor: i64) -> Result<i64, TemporalFailure> {
5573 if a == Self::NAT {
5574 return Ok(Self::NAT);
5575 }
5576 a.checked_mul(factor).ok_or(
5577 TemporalFailure::new("Timedelta::mul_scalar", PandasTemporalError::Overflow)
5578 .with_operands(a, factor),
5579 )
5580 }
5581
5582 #[must_use]
5592 pub fn div_scalar(a: i64, divisor: i64) -> i64 {
5593 Self::try_div_scalar(a, divisor).unwrap_or(Self::NAT)
5594 }
5595
5596 pub fn try_div_scalar(a: i64, divisor: i64) -> Result<i64, TemporalFailure> {
5611 if divisor == 0 {
5612 return Err(TemporalFailure::new(
5613 "Timedelta::div_scalar",
5614 PandasTemporalError::ZeroDivision,
5615 )
5616 .with_operands(a, divisor));
5617 }
5618 if a == Self::NAT {
5619 return Ok(Self::NAT);
5620 }
5621 Ok(Self::div_scalar_inner(a, divisor))
5622 }
5623
5624 fn div_scalar_inner(a: i64, divisor: i64) -> i64 {
5625 let q = a / divisor;
5630 let r = a % divisor;
5631 if r != 0 && (r < 0) != (divisor < 0) {
5635 q - 1
5636 } else {
5637 q
5638 }
5639 }
5640
5641 #[must_use]
5645 pub fn div_timedelta(a: i64, b: i64) -> f64 {
5646 if a == Self::NAT || b == Self::NAT {
5647 return f64::NAN;
5648 }
5649 (a as f64) / (b as f64)
5650 }
5651
5652 #[must_use]
5660 pub fn isoformat(nanos: i64) -> String {
5661 use std::fmt::Write as _;
5662
5663 if nanos == Self::NAT {
5664 return "NaT".to_string();
5665 }
5666
5667 let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5668 let remaining = nanos.rem_euclid(Self::NANOS_PER_DAY);
5669
5670 let hours = remaining / Self::NANOS_PER_HOUR;
5671 let remaining = remaining % Self::NANOS_PER_HOUR;
5672
5673 let minutes = remaining / Self::NANOS_PER_MIN;
5674 let remaining = remaining % Self::NANOS_PER_MIN;
5675
5676 let seconds = remaining / Self::NANOS_PER_SEC;
5677 let sub_sec_nanos = remaining % Self::NANOS_PER_SEC;
5678
5679 let mut result = String::with_capacity(40);
5683 let _ = write!(result, "P{days}DT{hours}H{minutes}M{seconds}");
5685 if sub_sec_nanos != 0 {
5686 result.push('.');
5687 let _ = write!(result, "{sub_sec_nanos:09}");
5688 while result.ends_with('0') {
5689 result.pop();
5690 }
5691 }
5692 result.push('S');
5693 result
5694 }
5695
5696 #[must_use]
5700 pub fn floor(nanos: i64, freq: &str) -> i64 {
5701 if nanos == Self::NAT {
5702 return Self::NAT;
5703 }
5704 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5705 return Self::NAT;
5706 };
5707 if unit_nanos == 0 {
5708 return Self::NAT;
5709 }
5710 nanos
5711 .div_euclid(unit_nanos)
5712 .checked_mul(unit_nanos)
5713 .unwrap_or(Self::NAT)
5714 }
5715
5716 #[must_use]
5723 pub fn ceil(nanos: i64, freq: &str) -> i64 {
5724 if nanos == Self::NAT {
5725 return Self::NAT;
5726 }
5727 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5728 return Self::NAT;
5729 };
5730 if unit_nanos == 0 {
5731 return Self::NAT;
5732 }
5733 let remainder = nanos.rem_euclid(unit_nanos);
5734 if remainder == 0 {
5735 nanos
5736 } else {
5737 nanos
5738 .checked_add(unit_nanos - remainder)
5739 .unwrap_or(Self::NAT)
5740 }
5741 }
5742
5743 #[must_use]
5748 pub fn round(nanos: i64, freq: &str) -> i64 {
5749 if nanos == Self::NAT {
5750 return Self::NAT;
5751 }
5752 let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5753 return Self::NAT;
5754 };
5755 if unit_nanos == 0 {
5756 return Self::NAT;
5757 }
5758 let negative = nanos < 0;
5759 let abs_nanos = nanos.saturating_abs();
5760
5761 let quotient = abs_nanos / unit_nanos;
5762 let remainder = abs_nanos % unit_nanos;
5763 let half = unit_nanos / 2;
5764
5765 let round_up = || {
5773 quotient
5774 .checked_add(1)
5775 .and_then(|q| q.checked_mul(unit_nanos))
5776 };
5777 let rounded = if remainder > half {
5778 round_up()
5779 } else if remainder < half {
5780 Some(quotient * unit_nanos)
5781 } else {
5782 if quotient % 2 == 0 {
5784 Some(quotient * unit_nanos)
5785 } else {
5786 round_up()
5787 }
5788 };
5789
5790 match rounded {
5791 Some(rounded) => {
5794 if negative {
5795 -rounded
5796 } else {
5797 rounded
5798 }
5799 }
5800 None => Self::NAT,
5801 }
5802 }
5803}
5804
5805#[derive(Debug, Clone, PartialEq, Eq, Error)]
5813pub enum TimeZoneError {
5814 #[error("'{0}'")]
5817 Unknown(String),
5818 #[error("{0}")]
5821 NonExistent(String),
5822 #[error("Cannot infer dst time from {0}, try using the 'ambiguous' argument")]
5824 Ambiguous(String),
5825}
5826
5827enum Zone {
5829 Fixed(chrono::FixedOffset),
5830 Named(chrono_tz::Tz),
5831}
5832
5833impl Zone {
5834 fn parse(tz: &str) -> Result<Self, TimeZoneError> {
5838 use chrono::Offset;
5839 let name = tz.trim();
5840 if name == "UTC" || name == "Z" {
5841 return Ok(Self::Fixed(chrono::Utc.fix()));
5842 }
5843 let offset = name
5844 .strip_prefix("UTC")
5845 .filter(|rest| rest.starts_with(['+', '-']))
5846 .unwrap_or(name);
5847 let bytes = offset.as_bytes();
5848 if bytes.len() == 6
5849 && matches!(bytes[0], b'+' | b'-')
5850 && bytes[3] == b':'
5851 && [1, 2, 4, 5].iter().all(|&i| bytes[i].is_ascii_digit())
5852 {
5853 let hours: i32 = offset[1..3].parse().unwrap_or(24);
5854 let minutes: i32 = offset[4..6].parse().unwrap_or(60);
5855 let sign = if bytes[0] == b'-' { -1 } else { 1 };
5856 return (hours <= 23 && minutes <= 59)
5857 .then(|| chrono::FixedOffset::east_opt(sign * (hours * 3_600 + minutes * 60)))
5858 .flatten()
5859 .map(Self::Fixed)
5860 .ok_or_else(|| TimeZoneError::Unknown(name.to_owned()));
5861 }
5862 name.parse::<chrono_tz::Tz>()
5863 .map(Self::Named)
5864 .map_err(|_| TimeZoneError::Unknown(name.to_owned()))
5865 }
5866
5867 fn offset_seconds(&self, utc_nanos: i64) -> i32 {
5869 use chrono::{Offset, TimeZone};
5870 match self {
5871 Self::Fixed(offset) => offset.local_minus_utc(),
5872 Self::Named(zone) => {
5873 let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5874 zone.offset_from_utc_datetime(&utc).fix().local_minus_utc()
5875 }
5876 }
5877 }
5878}
5879
5880pub fn tz_validate(tz: &str) -> Result<(), TimeZoneError> {
5882 Zone::parse(tz).map(|_| ())
5883}
5884
5885pub fn tz_canonical_name(tz: &str) -> Result<String, TimeZoneError> {
5889 Ok(match Zone::parse(tz)? {
5890 Zone::Fixed(offset) if offset.local_minus_utc() == 0 => "UTC".to_owned(),
5891 Zone::Fixed(offset) => format!("UTC{offset}"),
5892 Zone::Named(_) => tz.trim().to_owned(),
5893 })
5894}
5895
5896pub fn tz_abbreviation(tz: &str, utc_nanos: i64) -> Result<String, TimeZoneError> {
5900 use chrono::TimeZone;
5901 match Zone::parse(tz)? {
5902 Zone::Named(zone) => {
5903 let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5904 let offset = zone.offset_from_utc_datetime(&utc);
5905 Ok(chrono_tz::OffsetName::abbreviation(&offset)
5906 .map_or_else(|| tz.trim().to_owned(), str::to_owned))
5907 }
5908 Zone::Fixed(_) => tz_canonical_name(tz),
5909 }
5910}
5911
5912pub fn tz_offset_seconds(tz: &str, utc_nanos: i64) -> Result<i32, TimeZoneError> {
5916 Ok(Zone::parse(tz)?.offset_seconds(utc_nanos))
5917}
5918
5919pub fn tz_utc_to_wall_nanos(tz: &str, utc_nanos: i64) -> Result<i64, TimeZoneError> {
5922 if utc_nanos == i64::MIN {
5923 return Ok(utc_nanos);
5924 }
5925 let offset = Zone::parse(tz)?.offset_seconds(utc_nanos);
5926 Ok(utc_nanos.saturating_add(i64::from(offset) * 1_000_000_000))
5927}
5928
5929pub fn tz_wall_to_utc_nanos(tz: &str, wall_nanos: i64) -> Result<i64, TimeZoneError> {
5934 tz_wall_to_utc_nanos_with(tz, wall_nanos, AmbiguousTime::Raise, NonexistentTime::Raise)
5935}
5936
5937#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5941pub enum AmbiguousTime {
5942 Raise,
5943 Earliest,
5944 Latest,
5945 NaT,
5946}
5947
5948#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5954pub enum NonexistentTime {
5955 Raise,
5956 ShiftForward,
5957 ShiftBackward,
5958 NaT,
5959 Shift(i64),
5960}
5961
5962pub fn tz_wall_to_utc_nanos_with(
5965 tz: &str,
5966 wall_nanos: i64,
5967 ambiguous: AmbiguousTime,
5968 nonexistent: NonexistentTime,
5969) -> Result<i64, TimeZoneError> {
5970 if wall_nanos == i64::MIN {
5971 return Ok(wall_nanos);
5972 }
5973 wall_to_utc_in(&Zone::parse(tz)?, wall_nanos, ambiguous, nonexistent)
5974}
5975
5976const NANOS_PER_HOUR: i64 = 3_600_000_000_000;
5977const NANOS_PER_SECOND: i64 = 1_000_000_000;
5978
5979pub fn tz_utc_to_wall_nanos_all(tz: &str, utc: &[i64]) -> Result<Vec<i64>, TimeZoneError> {
5989 let zone = Zone::parse(tz)?;
5990 let mut offsets = HourOffsets::new(&zone);
5991 Ok(utc
5992 .iter()
5993 .map(|&nanos| {
5994 if nanos == i64::MIN {
5995 nanos
5996 } else {
5997 nanos.saturating_add(i64::from(offsets.at(nanos)) * NANOS_PER_SECOND)
5998 }
5999 })
6000 .collect())
6001}
6002
6003pub fn tz_wall_to_utc_nanos_all(
6012 tz: &str,
6013 walls: &[i64],
6014 ambiguous: AmbiguousTime,
6015 nonexistent: NonexistentTime,
6016) -> Result<Vec<i64>, TimeZoneError> {
6017 let zone = Zone::parse(tz)?;
6018 let mut hour = i64::MIN;
6019 let mut checked = false;
6020 let mut simple: Option<i32> = None;
6021 walls
6022 .iter()
6023 .map(|&wall| {
6024 if wall == i64::MIN {
6025 return Ok(wall);
6026 }
6027 let at = wall.div_euclid(NANOS_PER_HOUR);
6028 if at == hour {
6029 if !checked {
6030 checked = true;
6031 simple = simple_local_hour(&zone, at);
6032 }
6033 if let Some(offset) = simple
6034 && let Some(utc) = wall.checked_sub(i64::from(offset) * NANOS_PER_SECOND)
6035 {
6036 return Ok(utc);
6037 }
6038 } else {
6039 hour = at;
6040 checked = false;
6041 simple = None;
6042 }
6043 wall_to_utc_in(&zone, wall, ambiguous, nonexistent)
6044 })
6045 .collect()
6046}
6047
6048struct HourOffsets<'a> {
6055 zone: &'a Zone,
6056 hour: i64,
6057 offset: i32,
6058 uniform: Option<bool>,
6060}
6061
6062impl<'a> HourOffsets<'a> {
6063 fn new(zone: &'a Zone) -> Self {
6064 Self {
6065 zone,
6066 hour: i64::MIN,
6067 offset: 0,
6068 uniform: None,
6069 }
6070 }
6071
6072 fn at(&mut self, utc: i64) -> i32 {
6073 if let Zone::Fixed(fixed) = self.zone {
6074 return fixed.local_minus_utc();
6075 }
6076 let hour = utc.div_euclid(NANOS_PER_HOUR);
6077 if hour != self.hour {
6078 self.hour = hour;
6079 self.uniform = None;
6080 self.offset = self.zone.offset_seconds(utc);
6081 return self.offset;
6082 }
6083 let uniform = *self.uniform.get_or_insert_with(|| {
6084 hour.checked_mul(NANOS_PER_HOUR).is_some_and(|start| {
6085 self.zone.offset_seconds(start) == self.offset
6086 && start
6087 .checked_add(NANOS_PER_HOUR - 1)
6088 .is_some_and(|end| self.zone.offset_seconds(end) == self.offset)
6089 })
6090 });
6091 if uniform {
6092 self.offset
6093 } else {
6094 self.zone.offset_seconds(utc)
6095 }
6096 }
6097}
6098
6099fn simple_local_hour(zone: &Zone, hour: i64) -> Option<i32> {
6104 let start = hour.checked_mul(NANOS_PER_HOUR)?;
6105 let end = start.checked_add(NANOS_PER_HOUR - 1)?;
6106 let first = single_local_offset(zone, start)?;
6107 (single_local_offset(zone, end)? == first).then_some(first)
6108}
6109
6110fn single_local_offset(zone: &Zone, wall_nanos: i64) -> Option<i32> {
6113 use chrono::{LocalResult, Offset, TimeZone};
6114 let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6115 match zone {
6116 Zone::Fixed(offset) => Some(offset.local_minus_utc()),
6117 Zone::Named(zone) => match zone.from_local_datetime(&naive) {
6118 LocalResult::Single(at) => Some(at.offset().fix().local_minus_utc()),
6119 _ => None,
6120 },
6121 }
6122}
6123
6124fn wall_text(wall_nanos: i64) -> String {
6128 let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6129 let seconds = naive.format("%Y-%m-%d %H:%M:%S");
6130 let nanos = wall_nanos.rem_euclid(NANOS_PER_SECOND);
6131 if nanos == 0 {
6132 format!("{seconds}")
6133 } else if nanos % 1_000 == 0 {
6134 format!("{seconds}.{:06}", nanos / 1_000)
6135 } else {
6136 format!("{seconds}.{nanos:09}")
6137 }
6138}
6139
6140fn pandas_shift_offset(zone: &Zone, moved: i64, forward: bool) -> i32 {
6146 const DAY: i64 = 86_400 * NANOS_PER_SECOND;
6147 let here = zone.offset_seconds(moved);
6148 let first = zone.offset_seconds(i64::MIN + 1);
6149 let in_force = if forward {
6150 here >= 0 || first > 0
6151 } else {
6152 first < 0
6153 };
6154 if in_force {
6155 return here;
6156 }
6157 (1..=1_100_i64)
6160 .filter_map(|day| moved.checked_add(day * DAY))
6161 .map(|at| zone.offset_seconds(at))
6162 .find(|&offset| offset != here)
6163 .unwrap_or(here)
6164}
6165
6166fn wall_to_utc_in(
6168 zone: &Zone,
6169 wall_nanos: i64,
6170 ambiguous: AmbiguousTime,
6171 nonexistent: NonexistentTime,
6172) -> Result<i64, TimeZoneError> {
6173 use chrono::{LocalResult, TimeZone};
6174 let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
6175 let local = match zone {
6176 Zone::Fixed(offset) => offset
6177 .from_local_datetime(&naive)
6178 .map(|at| at.fixed_offset()),
6179 Zone::Named(zone) => zone.from_local_datetime(&naive).map(|at| at.fixed_offset()),
6180 };
6181 let nanos_of = |at: chrono::DateTime<chrono::FixedOffset>| {
6182 at.timestamp_nanos_opt()
6183 .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))
6184 };
6185 match local {
6186 LocalResult::Single(at) => nanos_of(at),
6187 LocalResult::Ambiguous(earliest, latest) => match ambiguous {
6188 AmbiguousTime::Raise => Err(TimeZoneError::Ambiguous(wall_text(wall_nanos))),
6189 AmbiguousTime::Earliest => nanos_of(earliest),
6190 AmbiguousTime::Latest => nanos_of(latest),
6191 AmbiguousTime::NaT => Ok(i64::MIN),
6192 },
6193 LocalResult::None => match nonexistent {
6194 NonexistentTime::Raise => Err(TimeZoneError::NonExistent(wall_text(wall_nanos))),
6195 NonexistentTime::NaT => Ok(i64::MIN),
6196 NonexistentTime::Shift(delta) => {
6197 let shifted = wall_nanos
6198 .checked_add(delta)
6199 .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))?;
6200 if shifted == i64::MIN {
6201 return Ok(shifted);
6202 }
6203 wall_to_utc_in(zone, shifted, ambiguous, NonexistentTime::Raise)
6204 }
6205 NonexistentTime::ShiftForward | NonexistentTime::ShiftBackward => {
6206 let forward = nonexistent == NonexistentTime::ShiftForward;
6215 let into_hour = wall_nanos.rem_euclid(NANOS_PER_HOUR);
6216 let moved = if forward {
6217 wall_nanos.checked_add(NANOS_PER_HOUR - into_hour)
6218 } else {
6219 wall_nanos.checked_sub(into_hour + 1)
6220 };
6221 moved
6222 .and_then(|moved| {
6223 let offset = pandas_shift_offset(zone, moved, forward);
6224 moved.checked_sub(i64::from(offset) * NANOS_PER_SECOND)
6225 })
6226 .ok_or_else(|| TimeZoneError::NonExistent(wall_text(wall_nanos)))
6227 }
6228 },
6229 }
6230}
6231
6232#[must_use]
6242pub fn strftime_python(wall_nanos: i64, format: &str, zone: Option<(i32, &str)>) -> String {
6243 const DAYS: [&str; 7] = [
6244 "Sunday",
6245 "Monday",
6246 "Tuesday",
6247 "Wednesday",
6248 "Thursday",
6249 "Friday",
6250 "Saturday",
6251 ];
6252 const MONTHS: [&str; 12] = [
6253 "January",
6254 "February",
6255 "March",
6256 "April",
6257 "May",
6258 "June",
6259 "July",
6260 "August",
6261 "September",
6262 "October",
6263 "November",
6264 "December",
6265 ];
6266 let total_secs = wall_nanos.div_euclid(1_000_000_000);
6269 let sub_nanos = wall_nanos.rem_euclid(1_000_000_000);
6270 let days = total_secs.div_euclid(86_400);
6271 let secs_of_day = total_secs.rem_euclid(86_400);
6272 let (year, month, day) = civil_from_days(days);
6273 let (hour, minute, second) = (
6274 secs_of_day / 3_600,
6275 (secs_of_day % 3_600) / 60,
6276 secs_of_day % 60,
6277 );
6278 let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
6279 let weekday = (days + 4).rem_euclid(7); let yday = days - days_from_civil(year, 1, 1); let iso_weekday = if weekday == 0 { 7 } else { weekday };
6282 let (iso_year, iso_week) = {
6283 let week = (yday + 1 - iso_weekday + 10).div_euclid(7);
6284 if week < 1 {
6285 (year - 1, iso_weeks_in_year(year - 1))
6286 } else if week > iso_weeks_in_year(year) {
6287 (year + 1, 1)
6288 } else {
6289 (year, week)
6290 }
6291 };
6292 let month_name = MONTHS[(month as usize).saturating_sub(1) % 12];
6293 let day_name = DAYS[weekday as usize];
6294
6295 let mut out = String::with_capacity(format.len().saturating_add(16));
6296 let mut chars = format.chars().peekable();
6297 while let Some(ch) = chars.next() {
6298 if ch != '%' {
6299 out.push(ch);
6300 continue;
6301 }
6302 let flag = chars.next_if(|c| matches!(c, '-' | '_' | '0' | '^'));
6303 let Some(conversion) = chars.next() else {
6304 out.push('%');
6305 if let Some(flag) = flag {
6306 out.push(flag);
6307 }
6308 break;
6309 };
6310 let number = |value: i64, width: usize, pad: char| -> String {
6313 match flag.unwrap_or(pad) {
6314 '-' => value.to_string(),
6315 '_' | ' ' => format!("{value:>width$}"),
6316 _ => format!("{value:0width$}"),
6317 }
6318 };
6319 let text = |value: &str| -> String {
6320 if flag == Some('^') {
6321 value.to_uppercase()
6322 } else {
6323 value.to_owned()
6324 }
6325 };
6326 let piece = match conversion {
6327 'a' => text(&day_name[..3]),
6328 'A' => text(day_name),
6329 'b' | 'h' => text(&month_name[..3]),
6330 'B' => text(month_name),
6331 'c' => text(&strftime_python(wall_nanos, "%a %b %e %H:%M:%S %Y", zone)),
6332 'C' => number(year.div_euclid(100), 2, '0'),
6333 'd' => number(i64::from(day), 2, '0'),
6334 'D' | 'x' => strftime_python(wall_nanos, "%m/%d/%y", zone),
6335 'e' => number(i64::from(day), 2, ' '),
6336 'f' => number(sub_nanos / 1_000, 6, '0'),
6337 'F' => strftime_python(wall_nanos, "%Y-%m-%d", zone),
6338 'g' => number(iso_year.rem_euclid(100), 2, '0'),
6339 'G' => number(iso_year, 1, '0'),
6340 'H' => number(hour, 2, '0'),
6341 'I' => number(hour12, 2, '0'),
6342 'j' => number(yday + 1, 3, '0'),
6343 'k' => number(hour, 2, ' '),
6344 'l' => number(hour12, 2, ' '),
6345 'm' => number(i64::from(month), 2, '0'),
6346 'M' => number(minute, 2, '0'),
6347 'n' => "\n".to_owned(),
6348 'p' => text(if hour < 12 { "AM" } else { "PM" }),
6349 'P' => (if hour < 12 { "am" } else { "pm" }).to_owned(),
6350 'r' => strftime_python(wall_nanos, "%I:%M:%S %p", zone),
6351 'R' => strftime_python(wall_nanos, "%H:%M", zone),
6352 'S' => number(second, 2, '0'),
6353 't' => "\t".to_owned(),
6354 'T' | 'X' => strftime_python(wall_nanos, "%H:%M:%S", zone),
6355 'u' => number(iso_weekday, 1, '0'),
6356 'U' => number((yday + 7 - weekday).div_euclid(7), 2, '0'),
6357 'V' => number(iso_week, 2, '0'),
6358 'w' => number(weekday, 1, '0'),
6359 'W' => number(
6360 (yday + 7 - (weekday + 6).rem_euclid(7)).div_euclid(7),
6361 2,
6362 '0',
6363 ),
6364 'y' => number(year.rem_euclid(100), 2, '0'),
6365 'Y' => number(year, 1, '0'),
6366 'z' => zone.map_or_else(String::new, |(offset, _)| {
6367 let sign = if offset < 0 { '-' } else { '+' };
6368 let offset = offset.unsigned_abs();
6369 let (h, m, s) = (offset / 3_600, (offset % 3_600) / 60, offset % 60);
6370 if s == 0 {
6371 format!("{sign}{h:02}{m:02}")
6372 } else {
6373 format!("{sign}{h:02}{m:02}{s:02}")
6374 }
6375 }),
6376 'Z' => zone.map_or_else(String::new, |(_, name)| text(name)),
6377 '%' => "%".to_owned(),
6378 other => {
6379 out.push('%');
6381 if let Some(flag) = flag {
6382 out.push(flag);
6383 }
6384 out.push(other);
6385 continue;
6386 }
6387 };
6388 out.push_str(&piece);
6389 }
6390 out
6391}
6392
6393#[must_use]
6397pub fn strftime_in_zone(nanos: i64, format: &str, tz: Option<&str>) -> String {
6398 let aware = tz.and_then(|zone| {
6399 let offset = tz_offset_seconds(zone, nanos).ok()?;
6400 let name = tz_abbreviation(zone, nanos).ok()?;
6401 Some((offset, name))
6402 });
6403 match aware {
6404 Some((offset, name)) => strftime_python(
6405 nanos.saturating_add(i64::from(offset) * 1_000_000_000),
6406 format,
6407 Some((offset, &name)),
6408 ),
6409 None => strftime_python(nanos, format, None),
6410 }
6411}
6412
6413#[must_use]
6419pub fn timestamp_text(nanos: i64) -> String {
6420 let mut text = strftime_python(nanos, "%Y-%m-%d %H:%M:%S", None);
6421 let fraction = nanos.rem_euclid(1_000_000_000);
6422 if fraction % 1_000 != 0 {
6423 text.push_str(&format!(".{fraction:09}"));
6424 } else if fraction != 0 {
6425 text.push_str(&format!(".{:06}", fraction / 1_000));
6426 }
6427 text
6428}
6429
6430#[must_use]
6434pub fn timestamp_text_in_zone(nanos: i64, tz: &str) -> String {
6435 let offset = tz_offset_seconds(tz, nanos).unwrap_or(0);
6436 let mut text = timestamp_text(nanos.saturating_add(i64::from(offset) * 1_000_000_000));
6437 let sign = if offset < 0 { '-' } else { '+' };
6438 let minutes = offset.unsigned_abs() / 60;
6439 text.push_str(&format!("{sign}{:02}:{:02}", minutes / 60, minutes % 60));
6440 text
6441}
6442
6443#[must_use]
6451pub fn add_calendar_months_nanos(nanos: i64, months: i64) -> Option<i64> {
6452 const DAY: i64 = 86_400_000_000_000;
6453 let moved = add_calendar_months_days(nanos.div_euclid(DAY), months)?;
6454 i64::try_from(i128::from(moved) * i128::from(DAY) + i128::from(nanos.rem_euclid(DAY))).ok()
6455}
6456
6457#[must_use]
6462pub fn add_calendar_months_days(day: i64, months: i64) -> Option<i64> {
6463 if day.unsigned_abs() > 365_000_000 {
6466 return None;
6467 }
6468 let (year, month, day) = civil_from_days(day);
6469 let total = year
6470 .checked_mul(12)?
6471 .checked_add(i64::from(month) - 1)?
6472 .checked_add(months)?;
6473 let year = total.div_euclid(12);
6474 if year.unsigned_abs() > 1_000_000 {
6475 return None;
6476 }
6477 let month = u32::try_from(total.rem_euclid(12)).ok()? + 1;
6478 let day = day.min(days_in_month(year, month)?);
6479 Some(days_from_civil(year, month, day))
6480}
6481
6482fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
6486 let (month, day) = (i64::from(month), i64::from(day));
6487 let year = if month <= 2 { year - 1 } else { year };
6488 let era = if year >= 0 { year } else { year - 399 } / 400;
6489 let yoe = year - era * 400;
6490 let doy = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
6491 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
6492 era * 146_097 + doe - 719_468
6493}
6494
6495fn days_in_month(year: i64, month: u32) -> Option<u32> {
6504 if !(1..=12).contains(&month) {
6505 return None;
6506 }
6507 let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
6508 let days: [u32; 12] = [
6509 31,
6510 if is_leap { 29 } else { 28 },
6511 31,
6512 30,
6513 31,
6514 30,
6515 31,
6516 31,
6517 30,
6518 31,
6519 30,
6520 31,
6521 ];
6522 Some(days[(month - 1) as usize])
6523}
6524
6525fn iso_weeks_in_year(year: i64) -> i64 {
6532 fn p(y: i64) -> i64 {
6533 (y + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400)).rem_euclid(7)
6534 }
6535 if p(year) == 4 || p(year - 1) == 3 {
6536 53
6537 } else {
6538 52
6539 }
6540}
6541
6542#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
6548pub struct Timestamp {
6549 pub nanos: i64,
6551 #[serde(default, skip_serializing_if = "Option::is_none")]
6555 pub tz: Option<String>,
6556}
6557
6558#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6579pub enum TimedeltaStringResolution {
6580 Days,
6582 Full,
6584}
6585
6586#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6606pub enum DatetimeStringResolution {
6607 Date,
6609 Second,
6611 Milli,
6613 Micro,
6615 Nano,
6617}
6618
6619impl Timestamp {
6620 pub const NAT: i64 = i64::MIN;
6622
6623 #[must_use]
6626 pub const fn from_nanos(nanos: i64) -> Self {
6627 Self { nanos, tz: None }
6628 }
6629
6630 #[must_use]
6635 pub fn from_nanos_tz(nanos: i64, tz_name: impl Into<String>) -> Self {
6636 Self {
6637 nanos,
6638 tz: Some(tz_name.into()),
6639 }
6640 }
6641
6642 #[must_use]
6658 pub fn now() -> Self {
6659 use std::time::{SystemTime, UNIX_EPOCH};
6660 let duration = SystemTime::now()
6661 .duration_since(UNIX_EPOCH)
6662 .unwrap_or_default();
6663 let nanos = duration.as_nanos() as i64;
6664 Self { nanos, tz: None }
6665 }
6666
6667 #[must_use]
6669 pub fn utcnow() -> Self {
6670 Self::now()
6671 }
6672
6673 #[must_use]
6677 pub fn today() -> Self {
6678 let now = Self::now();
6679 now.normalize()
6680 }
6681
6682 #[must_use]
6684 pub const fn nat() -> Self {
6685 Self {
6686 nanos: Self::NAT,
6687 tz: None,
6688 }
6689 }
6690
6691 #[must_use]
6693 pub const fn is_nat(&self) -> bool {
6694 self.nanos == Self::NAT
6695 }
6696
6697 #[must_use]
6699 pub const fn value(&self) -> i64 {
6700 self.nanos
6701 }
6702
6703 #[must_use]
6708 pub const fn unit(&self) -> Option<&'static str> {
6709 if self.is_nat() { None } else { Some("ns") }
6710 }
6711
6712 #[must_use]
6716 pub const fn resolution(&self) -> Option<&'static str> {
6717 if self.is_nat() { None } else { Some("ns") }
6718 }
6719
6720 #[must_use]
6722 pub const fn asm8(&self) -> i64 {
6723 self.value()
6724 }
6725
6726 #[must_use]
6728 pub const fn to_datetime64(&self) -> i64 {
6729 self.value()
6730 }
6731
6732 #[must_use]
6734 pub const fn to_numpy(&self) -> i64 {
6735 self.value()
6736 }
6737
6738 pub fn timestamp(&self) -> Result<f64, TypeError> {
6744 if self.is_nat() {
6745 return Err(TypeError::ValueIsMissing {
6746 kind: NullKind::NaT,
6747 });
6748 }
6749 let seconds = self.nanos as f64 / 1_000_000_000.0;
6750 let rounded = format!("{seconds:.6}").parse().unwrap_or(seconds);
6751 Ok(rounded)
6752 }
6753
6754 #[must_use]
6762 pub fn add_timedelta(&self, td_nanos: i64) -> Self {
6763 self.try_add_timedelta(td_nanos)
6764 .unwrap_or_else(|_| Self::nat())
6765 }
6766
6767 pub fn try_add_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6778 if self.is_nat() || td_nanos == Timedelta::NAT {
6779 return Ok(Self::nat());
6780 }
6781 match self.nanos.checked_add(td_nanos) {
6782 Some(nanos) => Ok(Self {
6783 nanos,
6784 tz: self.tz.clone(),
6785 }),
6786 None => Err(TemporalFailure::new(
6790 "Timestamp::add_timedelta",
6791 PandasTemporalError::OutOfBoundsDatetime,
6792 )
6793 .with_operands(self.nanos, td_nanos)),
6794 }
6795 }
6796
6797 #[must_use]
6799 pub fn sub_timedelta(&self, td_nanos: i64) -> Self {
6800 self.try_sub_timedelta(td_nanos)
6801 .unwrap_or_else(|_| Self::nat())
6802 }
6803
6804 pub fn try_sub_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6810 if self.is_nat() || td_nanos == Timedelta::NAT {
6811 return Ok(Self::nat());
6812 }
6813 match self.nanos.checked_sub(td_nanos) {
6814 Some(nanos) => Ok(Self {
6815 nanos,
6816 tz: self.tz.clone(),
6817 }),
6818 None => Err(TemporalFailure::new(
6819 "Timestamp::sub_timedelta",
6820 PandasTemporalError::OutOfBoundsDatetime,
6821 )
6822 .with_operands(self.nanos, td_nanos)),
6823 }
6824 }
6825
6826 #[must_use]
6830 pub fn sub_timestamp(&self, other: &Self) -> i64 {
6831 self.try_sub_timestamp(other).unwrap_or(Timedelta::NAT)
6832 }
6833
6834 pub fn try_sub_timestamp(&self, other: &Self) -> Result<i64, TemporalFailure> {
6840 if self.is_nat() || other.is_nat() {
6841 return Ok(Timedelta::NAT);
6842 }
6843 self.nanos.checked_sub(other.nanos).ok_or(
6844 TemporalFailure::new(
6845 "Timestamp::sub_timestamp",
6846 PandasTemporalError::OutOfBoundsDatetime,
6847 )
6848 .with_operands(self.nanos, other.nanos),
6849 )
6850 }
6851
6852 #[must_use]
6857 pub fn semantic_eq(&self, other: &Self) -> bool {
6858 if self.is_nat() && other.is_nat() {
6859 return true;
6860 }
6861 if self.is_nat() || other.is_nat() {
6862 return false;
6863 }
6864 self.nanos == other.nanos && self.tz == other.tz
6865 }
6866
6867 #[must_use]
6880 pub fn floor_to(&self, unit_nanos: i64) -> Self {
6881 if self.is_nat() || unit_nanos <= 0 {
6882 return Self::nat();
6883 }
6884 let Some(nanos) = self.nanos.div_euclid(unit_nanos).checked_mul(unit_nanos) else {
6885 return Self::nat();
6886 };
6887 Self {
6888 nanos,
6889 tz: self.tz.clone(),
6890 }
6891 }
6892
6893 #[must_use]
6898 pub fn ceil_to(&self, unit_nanos: i64) -> Self {
6899 if self.is_nat() || unit_nanos <= 0 {
6900 return Self::nat();
6901 }
6902 let rem = self.nanos.rem_euclid(unit_nanos);
6903 let nanos = if rem == 0 {
6904 self.nanos
6905 } else {
6906 let Some(nanos) = self.nanos.checked_add(unit_nanos - rem) else {
6911 return Self::nat();
6912 };
6913 nanos
6914 };
6915 Self {
6916 nanos,
6917 tz: self.tz.clone(),
6918 }
6919 }
6920
6921 #[must_use]
6927 pub fn round_to(&self, unit_nanos: i64) -> Self {
6928 if self.is_nat() || unit_nanos <= 0 {
6929 return Self::nat();
6930 }
6931 let floor = self.nanos.div_euclid(unit_nanos);
6932 let rem = self.nanos.rem_euclid(unit_nanos);
6933 let half = unit_nanos / 2;
6934 let chosen_floor = if rem < half {
6935 floor
6936 } else if rem > half {
6937 floor + 1
6938 } else if unit_nanos % 2 != 0 {
6939 floor + 1
6941 } else {
6942 if floor % 2 == 0 { floor } else { floor + 1 }
6944 };
6945 let Some(nanos) = chosen_floor.checked_mul(unit_nanos) else {
6949 return Self::nat();
6950 };
6951 Self {
6952 nanos,
6953 tz: self.tz.clone(),
6954 }
6955 }
6956
6957 fn fixed_freq_nanos(freq: &str) -> Option<i64> {
6969 Timedelta::unit_to_nanos(freq).or_else(|| Timedelta::parse(freq).ok())
6970 }
6971
6972 #[must_use]
6976 pub fn floor_to_unit(&self, unit: &str) -> Self {
6977 match Self::fixed_freq_nanos(unit) {
6978 Some(unit_nanos) => self.floor_to(unit_nanos),
6979 None => Self::nat(),
6980 }
6981 }
6982
6983 #[must_use]
6987 pub fn ceil_to_unit(&self, unit: &str) -> Self {
6988 match Self::fixed_freq_nanos(unit) {
6989 Some(unit_nanos) => self.ceil_to(unit_nanos),
6990 None => Self::nat(),
6991 }
6992 }
6993
6994 #[must_use]
6998 pub fn round_to_unit(&self, unit: &str) -> Self {
6999 match Self::fixed_freq_nanos(unit) {
7000 Some(unit_nanos) => self.round_to(unit_nanos),
7001 None => Self::nat(),
7002 }
7003 }
7004
7005 #[must_use]
7007 pub fn floor(&self, freq: &str) -> Self {
7008 self.floor_to_unit(freq)
7009 }
7010
7011 #[must_use]
7013 pub fn ceil(&self, freq: &str) -> Self {
7014 self.ceil_to_unit(freq)
7015 }
7016
7017 #[must_use]
7019 pub fn round(&self, freq: &str) -> Self {
7020 self.round_to_unit(freq)
7021 }
7022
7023 #[must_use]
7030 pub fn wall_nanos(&self) -> i64 {
7031 if self.is_nat() {
7032 return Self::NAT;
7033 }
7034 let Some(tz) = self.tz.as_deref() else {
7035 return self.nanos;
7036 };
7037 tz_offset_seconds(tz, self.nanos)
7038 .ok()
7039 .and_then(|offset_secs| {
7040 self.nanos
7041 .checked_add(i64::from(offset_secs) * Timedelta::NANOS_PER_SEC)
7042 })
7043 .unwrap_or(self.nanos)
7044 }
7045
7046 #[must_use]
7050 pub fn year(&self) -> Option<i64> {
7051 if self.is_nat() {
7052 return None;
7053 }
7054 let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
7058 let days = days_since_epoch + 719_468;
7059 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7060 let doe = days - era * 146_097;
7061 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7062 let y = yoe + era * 400;
7063 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7064 let mp = (5 * doy + 2) / 153;
7065 let m = if mp < 10 { mp + 3 } else { mp - 9 };
7066 Some(if m <= 2 { y + 1 } else { y })
7067 }
7068
7069 #[must_use]
7073 pub fn month(&self) -> Option<i64> {
7074 if self.is_nat() {
7075 return None;
7076 }
7077 let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
7081 let days = days_since_epoch + 719_468;
7082 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7083 let doe = days - era * 146_097;
7084 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7085 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7086 let mp = (5 * doy + 2) / 153;
7087 Some(if mp < 10 { mp + 3 } else { mp - 9 })
7088 }
7089
7090 #[must_use]
7094 pub fn day(&self) -> Option<i64> {
7095 if self.is_nat() {
7096 return None;
7097 }
7098 let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
7102 let days = days_since_epoch + 719_468;
7103 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7104 let doe = days - era * 146_097;
7105 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7106 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7107 let mp = (5 * doy + 2) / 153;
7108 Some(doy - (153 * mp + 2) / 5 + 1)
7109 }
7110
7111 #[must_use]
7115 pub fn hour(&self) -> Option<i64> {
7116 if self.is_nat() {
7117 return None;
7118 }
7119 let secs_of_day =
7123 self.wall_nanos().rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7124 Some(secs_of_day / 3600)
7125 }
7126
7127 #[must_use]
7131 pub fn minute(&self) -> Option<i64> {
7132 if self.is_nat() {
7133 return None;
7134 }
7135 let secs_of_day =
7139 self.wall_nanos().rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7140 Some((secs_of_day % 3600) / 60)
7141 }
7142
7143 #[must_use]
7147 pub fn second(&self) -> Option<i64> {
7148 if self.is_nat() {
7149 return None;
7150 }
7151 let secs_of_day =
7155 self.wall_nanos().rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
7156 Some(secs_of_day % 60)
7157 }
7158
7159 #[must_use]
7163 pub fn microsecond(&self) -> Option<i64> {
7164 if self.is_nat() {
7165 return None;
7166 }
7167 let sub_nanos = self.wall_nanos().rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7170 Some((sub_nanos / 1000) as i64)
7171 }
7172
7173 #[must_use]
7177 pub fn nanosecond(&self) -> Option<i64> {
7178 if self.is_nat() {
7179 return None;
7180 }
7181 let sub_nanos = self.wall_nanos().rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7184 Some((sub_nanos % 1000) as i64)
7185 }
7186
7187 #[must_use]
7191 pub fn dayofweek(&self) -> Option<i64> {
7192 if self.is_nat() {
7193 return None;
7194 }
7195 let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
7197 let dow = ((days_since_epoch + 3) % 7 + 7) % 7;
7198 Some(dow)
7199 }
7200
7201 #[must_use]
7203 pub fn weekday(&self) -> Option<i64> {
7204 self.dayofweek()
7205 }
7206
7207 #[must_use]
7209 pub fn day_of_week(&self) -> Option<i64> {
7210 self.dayofweek()
7211 }
7212
7213 #[must_use]
7217 pub fn dayofyear(&self) -> Option<i64> {
7218 if self.is_nat() {
7219 return None;
7220 }
7221 let m = self.month()?;
7222 let d = self.day()?;
7223 let y = self.year()?;
7224 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7225 let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
7226 let base = days_before[(m - 1) as usize] + d;
7227 if is_leap && m > 2 {
7228 Some(base + 1)
7229 } else {
7230 Some(base)
7231 }
7232 }
7233
7234 #[must_use]
7236 pub fn day_of_year(&self) -> Option<i64> {
7237 self.dayofyear()
7238 }
7239
7240 #[must_use]
7244 pub fn toordinal(&self) -> Option<i64> {
7245 if self.is_nat() {
7246 return None;
7247 }
7248 let y = self.year()?;
7249 let m = self.month()?;
7250 let d = self.day()?;
7251 let y_minus_1 = y - 1;
7255 let mut ordinal = y_minus_1 * 365 + y_minus_1 / 4 - y_minus_1 / 100 + y_minus_1 / 400;
7256 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7257 let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
7258 ordinal += days_before[(m - 1) as usize];
7259 if is_leap && m > 2 {
7260 ordinal += 1;
7261 }
7262 ordinal += d;
7263 Some(ordinal)
7264 }
7265
7266 #[must_use]
7270 pub fn fromordinal(ordinal: i64) -> Self {
7271 if ordinal <= 0 {
7272 return Self {
7273 nanos: Self::NAT,
7274 tz: None,
7275 };
7276 }
7277 let days_since_epoch = ordinal - 719163;
7280 match days_since_epoch.checked_mul(Timedelta::NANOS_PER_DAY) {
7281 Some(nanos) => Self { nanos, tz: None },
7282 None => Self::nat(),
7283 }
7284 }
7285
7286 #[must_use]
7292 pub fn to_julian_date(&self) -> f64 {
7293 if self.is_nat() {
7294 return f64::NAN;
7295 }
7296 let ordinal = match self.toordinal() {
7300 Some(o) => o,
7301 None => return f64::NAN,
7302 };
7303 let h = self.hour().unwrap_or(0) as f64;
7305 let m = self.minute().unwrap_or(0) as f64;
7306 let s = self.second().unwrap_or(0) as f64;
7307 let us = self.microsecond().unwrap_or(0) as f64;
7308 let ns = self.nanosecond().unwrap_or(0) as f64;
7309 let frac_day =
7310 (h + m / 60.0 + s / 3600.0 + us / 3_600_000_000.0 + ns / 3_600_000_000_000.0) / 24.0;
7311 1721424.5 + ordinal as f64 + frac_day
7313 }
7314
7315 #[must_use]
7319 pub fn quarter(&self) -> Option<i64> {
7320 self.month().map(|m| (m - 1) / 3 + 1)
7321 }
7322
7323 #[must_use]
7327 pub fn weekofyear(&self) -> Option<i64> {
7328 if self.is_nat() {
7329 return None;
7330 }
7331 let doy = self.dayofyear()?;
7332 let dow = self.dayofweek()?;
7333 let year = self.year()?;
7334 let iso_dow = if dow == 6 { 7 } else { dow + 1 };
7335 let week = (doy - iso_dow + 10) / 7;
7336 if week < 1 {
7342 Some(iso_weeks_in_year(year - 1))
7343 } else if week > iso_weeks_in_year(year) {
7344 Some(1)
7345 } else {
7346 Some(week)
7347 }
7348 }
7349
7350 #[must_use]
7352 pub fn week(&self) -> Option<i64> {
7353 self.weekofyear()
7354 }
7355
7356 #[must_use]
7361 pub fn to_unit(&self, unit: &str) -> Option<i64> {
7362 if self.is_nat() {
7363 return None;
7364 }
7365 match unit {
7366 "ns" | "nanosecond" | "nanoseconds" => Some(self.nanos),
7367 "us" | "microsecond" | "microseconds" => Some(self.nanos / 1_000),
7368 "ms" | "millisecond" | "milliseconds" => Some(self.nanos / 1_000_000),
7369 "s" | "second" | "seconds" => Some(self.nanos / 1_000_000_000),
7370 _ => None,
7371 }
7372 }
7373
7374 #[must_use]
7378 pub fn is_leap_year(&self) -> Option<bool> {
7379 self.year()
7380 .map(|y| (y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
7381 }
7382
7383 #[must_use]
7387 pub fn is_month_start(&self) -> Option<bool> {
7388 self.day().map(|d| d == 1)
7389 }
7390
7391 #[must_use]
7395 pub fn is_month_end(&self) -> Option<bool> {
7396 let y = self.year()?;
7397 let m = self.month()?;
7398 let d = self.day()?;
7399 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7400 let days_in_month: [i64; 12] = [
7401 31,
7402 if is_leap { 29 } else { 28 },
7403 31,
7404 30,
7405 31,
7406 30,
7407 31,
7408 31,
7409 30,
7410 31,
7411 30,
7412 31,
7413 ];
7414 Some(d == days_in_month[(m - 1) as usize])
7415 }
7416
7417 #[must_use]
7421 pub fn is_quarter_start(&self) -> Option<bool> {
7422 let m = self.month()?;
7423 let d = self.day()?;
7424 Some(d == 1 && (m == 1 || m == 4 || m == 7 || m == 10))
7425 }
7426
7427 #[must_use]
7431 pub fn is_quarter_end(&self) -> Option<bool> {
7432 let m = self.month()?;
7433 let d = self.day()?;
7434 Some(
7435 (m == 3 && d == 31)
7436 || (m == 6 && d == 30)
7437 || (m == 9 && d == 30)
7438 || (m == 12 && d == 31),
7439 )
7440 }
7441
7442 #[must_use]
7446 pub fn is_year_start(&self) -> Option<bool> {
7447 let m = self.month()?;
7448 let d = self.day()?;
7449 Some(m == 1 && d == 1)
7450 }
7451
7452 #[must_use]
7456 pub fn is_year_end(&self) -> Option<bool> {
7457 let m = self.month()?;
7458 let d = self.day()?;
7459 Some(m == 12 && d == 31)
7460 }
7461
7462 #[must_use]
7466 pub fn days_in_month(&self) -> Option<i64> {
7467 let y = self.year()?;
7468 let m = self.month()?;
7469 let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7470 let days: [i64; 12] = [
7471 31,
7472 if is_leap { 29 } else { 28 },
7473 31,
7474 30,
7475 31,
7476 30,
7477 31,
7478 31,
7479 30,
7480 31,
7481 30,
7482 31,
7483 ];
7484 Some(days[(m - 1) as usize])
7485 }
7486
7487 #[must_use]
7489 pub fn daysinmonth(&self) -> Option<i64> {
7490 self.days_in_month()
7491 }
7492
7493 #[must_use]
7495 pub fn normalize(&self) -> Self {
7496 self.floor_to(Timedelta::NANOS_PER_DAY)
7497 }
7498
7499 #[must_use]
7503 #[allow(clippy::too_many_arguments)]
7504 pub fn replace(
7505 &self,
7506 year: Option<i64>,
7507 month: Option<i64>,
7508 day: Option<i64>,
7509 hour: Option<i64>,
7510 minute: Option<i64>,
7511 second: Option<i64>,
7512 microsecond: Option<i64>,
7513 nanosecond: Option<i64>,
7514 ) -> Self {
7515 if self.is_nat() {
7516 return self.clone();
7517 }
7518 let cur_year = self.year().unwrap_or(1970);
7519 let cur_month = self.month().unwrap_or(1);
7520 let cur_day = self.day().unwrap_or(1);
7521 let cur_hour = self.hour().unwrap_or(0);
7522 let cur_minute = self.minute().unwrap_or(0);
7523 let cur_second = self.second().unwrap_or(0);
7524 let cur_micro = self.microsecond().unwrap_or(0);
7525 let cur_nano = self.nanosecond().unwrap_or(0);
7526
7527 let y = year.unwrap_or(cur_year);
7528 let mo = month.unwrap_or(cur_month);
7529 let d = day.unwrap_or(cur_day);
7530 let h = hour.unwrap_or(cur_hour);
7531 let mi = minute.unwrap_or(cur_minute);
7532 let s = second.unwrap_or(cur_second);
7533 let us = microsecond.unwrap_or(cur_micro);
7534 let ns = nanosecond.unwrap_or(cur_nano);
7535
7536 if !(1..=12).contains(&mo)
7537 || !(1..=days_in_month(y, mo as u32).unwrap_or(0) as i64).contains(&d)
7538 || !(0..=23).contains(&h)
7539 || !(0..=59).contains(&mi)
7540 || !(0..=59).contains(&s)
7541 || !(0..=999_999).contains(&us)
7542 || !(0..=999).contains(&ns)
7543 {
7544 return Self::nat();
7545 }
7546
7547 let days_from_epoch = Self::days_from_ymd(y, mo, d);
7559 let secs = h * 3600 + mi * 60 + s;
7560 let Some(total_nanos) = days_from_epoch
7561 .checked_mul(Timedelta::NANOS_PER_DAY)
7562 .and_then(|nanos| {
7563 secs.checked_mul(Timedelta::NANOS_PER_SEC)
7564 .and_then(|s_nanos| nanos.checked_add(s_nanos))
7565 })
7566 .and_then(|nanos| {
7567 us.checked_mul(Timedelta::NANOS_PER_MICRO)
7568 .and_then(|us_nanos| nanos.checked_add(us_nanos))
7569 })
7570 .and_then(|nanos| nanos.checked_add(ns))
7571 else {
7572 return Self::nat();
7573 };
7574
7575 let utc_nanos = match self.tz.as_deref() {
7576 Some(tz) => match tz_wall_to_utc_nanos(tz, total_nanos) {
7577 Ok(utc) => utc,
7578 Err(TimeZoneError::Unknown(_)) => total_nanos,
7579 Err(TimeZoneError::NonExistent(_) | TimeZoneError::Ambiguous(_)) => {
7580 return Self::nat();
7581 }
7582 },
7583 None => total_nanos,
7584 };
7585
7586 Self {
7587 nanos: utc_nanos,
7588 tz: self.tz.clone(),
7589 }
7590 }
7591
7592 fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
7593 let y = if month <= 2 { year - 1 } else { year };
7594 let era = if y >= 0 { y } else { y - 399 } / 400;
7595 let yoe = y - era * 400;
7596 let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
7597 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
7598 era * 146097 + doe - 719468
7599 }
7600
7601 #[must_use]
7605 pub fn isoformat(&self) -> String {
7606 use std::fmt::Write as _;
7607
7608 if self.is_nat() {
7609 return "NaT".to_string();
7610 }
7611 let resolved_offset = self
7612 .tz
7613 .as_deref()
7614 .and_then(|tz| tz_offset_seconds(tz, self.nanos).ok())
7615 .and_then(|offset_secs| {
7616 self.nanos
7617 .checked_add(i64::from(offset_secs) * Timedelta::NANOS_PER_SEC)
7618 .map(|wall_nanos| (wall_nanos, offset_secs))
7619 });
7620 let display_nanos = resolved_offset.map_or(self.nanos, |(wall_nanos, _)| wall_nanos);
7621 let days_since_epoch = display_nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7624 let nanos_of_day = display_nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7625 let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7626 let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7627
7628 let days = days_since_epoch + 719_468;
7629 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7630 let doe = days - era * 146_097;
7631 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7632 let y = yoe + era * 400;
7633 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7634 let mp = (5 * doy + 2) / 153;
7635 let d = doy - (153 * mp + 2) / 5 + 1;
7636 let m = if mp < 10 { mp + 3 } else { mp - 9 };
7637 let year = if m <= 2 { y + 1 } else { y };
7638
7639 let hour = secs_of_day / 3600;
7640 let minute = (secs_of_day % 3600) / 60;
7641 let second = secs_of_day % 60;
7642
7643 let suffix_capacity = match (&self.tz, resolved_offset) {
7647 (Some(_), Some(_)) => 6,
7648 (Some(tz), None) => tz.len() + 2,
7649 (None, _) => 0,
7650 };
7651 let mut result = String::with_capacity(29 + suffix_capacity);
7652 if sub_nanos == 0 {
7653 let _ = write!(
7654 result,
7655 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}"
7656 );
7657 } else if sub_nanos.is_multiple_of(1_000) {
7658 let _ = write!(
7659 result,
7660 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{:06}",
7661 sub_nanos / 1_000
7662 );
7663 } else {
7664 let _ = write!(
7665 result,
7666 "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{sub_nanos:09}"
7667 );
7668 }
7669 match (&self.tz, resolved_offset) {
7670 (Some(_), Some((_, offset_secs))) => {
7671 let sign = if offset_secs < 0 { '-' } else { '+' };
7672 let total_minutes = offset_secs.unsigned_abs() / 60;
7673 let _ = write!(
7674 result,
7675 "{sign}{:02}:{:02}",
7676 total_minutes / 60,
7677 total_minutes % 60
7678 );
7679 }
7680 (Some(tz), None) => {
7681 result.push('[');
7682 result.push_str(tz);
7683 result.push(']');
7684 }
7685 (None, _) => {}
7686 }
7687 result
7688 }
7689
7690 #[must_use]
7692 pub fn to_iso8601(&self) -> String {
7693 self.isoformat()
7694 }
7695
7696 #[must_use]
7705 pub const fn string_resolution(nanos: i64) -> DatetimeStringResolution {
7706 if nanos == Self::NAT {
7707 return DatetimeStringResolution::Date;
7708 }
7709 if nanos.rem_euclid(Timedelta::NANOS_PER_DAY) == 0 {
7710 DatetimeStringResolution::Date
7711 } else if nanos.rem_euclid(Timedelta::NANOS_PER_SEC) == 0 {
7712 DatetimeStringResolution::Second
7713 } else if nanos.rem_euclid(Timedelta::NANOS_PER_MILLI) == 0 {
7714 DatetimeStringResolution::Milli
7715 } else if nanos.rem_euclid(Timedelta::NANOS_PER_MICRO) == 0 {
7716 DatetimeStringResolution::Micro
7717 } else {
7718 DatetimeStringResolution::Nano
7719 }
7720 }
7721
7722 #[must_use]
7742 pub fn format_at_resolution(nanos: i64, resolution: DatetimeStringResolution) -> String {
7743 use std::fmt::Write as _;
7744
7745 if nanos == Self::NAT {
7746 return "NaT".to_string();
7747 }
7748 let days_since_epoch = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7753 let nanos_of_day = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7754 let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7755 let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC);
7756 let (year, month, day) = civil_from_days(days_since_epoch);
7759
7760 let mut result = String::with_capacity(30);
7763 let _ = write!(result, "{year:04}-{month:02}-{day:02}");
7765 if matches!(resolution, DatetimeStringResolution::Date) {
7766 return result;
7767 }
7768 let _ = write!(
7769 result,
7770 " {:02}:{:02}:{:02}",
7771 secs_of_day / 3600,
7772 (secs_of_day % 3600) / 60,
7773 secs_of_day % 60
7774 );
7775 let (fraction, width) = match resolution {
7776 DatetimeStringResolution::Date | DatetimeStringResolution::Second => return result,
7777 DatetimeStringResolution::Milli => (sub_nanos / Timedelta::NANOS_PER_MILLI, 3_usize),
7778 DatetimeStringResolution::Micro => (sub_nanos / Timedelta::NANOS_PER_MICRO, 6_usize),
7779 DatetimeStringResolution::Nano => (sub_nanos, 9_usize),
7780 };
7781 let _ = write!(result, ".{fraction:0width$}", width = width);
7782 result
7783 }
7784
7785 pub fn parse(s: &str) -> Result<Self, TypeError> {
7798 let s = s.trim();
7799
7800 if s.eq_ignore_ascii_case("nat") {
7801 return Ok(Self::nat());
7802 }
7803
7804 let Some((datetime_part, tz)) = Self::split_timezone(s) else {
7805 return Err(TypeError::ValueNotParseable {
7806 value: s.to_string(),
7807 target: "Timestamp".to_string(),
7808 });
7809 };
7810
7811 let (date_part, time_part) = if datetime_part.contains('T') {
7812 datetime_part
7813 .split_once('T')
7814 .ok_or_else(|| TypeError::ValueNotParseable {
7815 value: s.to_string(),
7816 target: "Timestamp".to_string(),
7817 })?
7818 } else if datetime_part.contains(' ')
7819 && datetime_part.chars().filter(|&c| c == ' ').count() == 1
7820 {
7821 datetime_part
7822 .split_once(' ')
7823 .ok_or_else(|| TypeError::ValueNotParseable {
7824 value: s.to_string(),
7825 target: "Timestamp".to_string(),
7826 })?
7827 } else {
7828 (datetime_part, "00:00:00")
7829 };
7830
7831 let (year, month, day) =
7832 Self::parse_date(date_part).ok_or_else(|| TypeError::ValueNotParseable {
7833 value: s.to_string(),
7834 target: "Timestamp".to_string(),
7835 })?;
7836
7837 let (hour, minute, second, nanos) =
7838 Self::parse_time(time_part).ok_or_else(|| TypeError::ValueNotParseable {
7839 value: s.to_string(),
7840 target: "Timestamp".to_string(),
7841 })?;
7842
7843 let wall_nanos = Self::ymd_hms_to_nanos(year, month, day, hour, minute, second, nanos)
7846 .ok_or_else(|| TypeError::ValueNotParseable {
7847 value: s.to_string(),
7848 target: "Timestamp".to_string(),
7849 })?;
7850 let offset = tz
7854 .as_deref()
7855 .and_then(Self::fixed_utc_offset_seconds)
7856 .unwrap_or(0);
7857 let total_nanos = offset
7858 .checked_mul(1_000_000_000)
7859 .and_then(|offset| wall_nanos.checked_sub(offset))
7860 .ok_or_else(|| TypeError::ValueNotParseable {
7861 value: s.to_string(),
7862 target: "Timestamp".to_string(),
7863 })?;
7864
7865 Ok(if let Some(tz_name) = tz {
7866 Self::from_nanos_tz(total_nanos, tz_name)
7867 } else {
7868 Self::from_nanos(total_nanos)
7869 })
7870 }
7871
7872 fn split_timezone(s: &str) -> Option<(&str, Option<String>)> {
7873 if let Some(stripped) = s.strip_suffix('Z') {
7874 Some((stripped, Some("UTC".to_string())))
7875 } else if let Some(idx) = s.rfind('+') {
7876 if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7877 Some((&s[..idx], Some(s[idx..].to_string())))
7878 } else if idx > 10 {
7879 None
7880 } else {
7881 Some((s, None))
7882 }
7883 } else if let Some(idx) = s.rfind('-') {
7884 if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7885 Some((&s[..idx], Some(s[idx..].to_string())))
7886 } else if idx > 10 {
7887 None
7888 } else {
7889 Some((s, None))
7890 }
7891 } else {
7892 Some((s, None))
7893 }
7894 }
7895
7896 fn fixed_utc_offset_seconds(tz: &str) -> Option<i64> {
7897 if tz == "UTC" {
7898 return Some(0);
7899 }
7900 let offset = tz.strip_prefix("UTC").unwrap_or(tz);
7901 if !Self::is_timezone_offset(offset) {
7902 return None;
7903 }
7904 let sign = if offset.starts_with('+') { 1 } else { -1 };
7905 let hours = offset[1..3].parse::<i64>().ok()?;
7906 let minutes = offset[4..6].parse::<i64>().ok()?;
7907 Some(sign * (hours * 3_600 + minutes * 60))
7908 }
7909
7910 fn is_timezone_offset(s: &str) -> bool {
7911 let bytes = s.as_bytes();
7912 if bytes.len() != 6 || !matches!(bytes[0], b'+' | b'-') || bytes[3] != b':' {
7913 return false;
7914 }
7915 if !bytes[1..3].iter().all(u8::is_ascii_digit)
7916 || !bytes[4..6].iter().all(u8::is_ascii_digit)
7917 {
7918 return false;
7919 }
7920 let hour = u32::from(bytes[1] - b'0') * 10 + u32::from(bytes[2] - b'0');
7921 let minute = u32::from(bytes[4] - b'0') * 10 + u32::from(bytes[5] - b'0');
7922 hour <= 23 && minute <= 59
7923 }
7924
7925 fn parse_date(s: &str) -> Option<(i64, u32, u32)> {
7926 let parts: Vec<&str> = s.split('-').collect();
7927 if parts.len() != 3 {
7928 return None;
7929 }
7930 let year: i64 = parts[0].parse().ok()?;
7931 let month: u32 = parts[1].parse().ok()?;
7932 let day: u32 = parts[2].parse().ok()?;
7933 if !(1..=days_in_month(year, month)?).contains(&day) {
7934 return None;
7935 }
7936 Some((year, month, day))
7937 }
7938
7939 fn parse_time(s: &str) -> Option<(u32, u32, u32, u64)> {
7940 let (time_str, frac_str) = match s.split_once('.') {
7941 Some((time, frac)) => (time, Some(frac)),
7942 None => (s, None),
7943 };
7944 let parts: Vec<&str> = time_str.split(':').collect();
7945 if parts.is_empty() || parts.len() > 3 {
7946 return None;
7947 }
7948 let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
7949 let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
7950 let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
7951
7952 if hour > 23 || minute > 59 || second > 59 {
7953 return None;
7954 }
7955
7956 let nanos = match frac_str {
7957 None => 0,
7958 Some(frac) => {
7959 if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
7960 return None;
7961 }
7962 let digits = frac.len().min(9);
7963 let mut nanos = 0_u64;
7964 for byte in frac.bytes().take(digits) {
7965 nanos = nanos * 10 + u64::from(byte - b'0');
7966 }
7967 for _ in digits..9 {
7968 nanos *= 10;
7969 }
7970 nanos
7971 }
7972 };
7973
7974 Some((hour, minute, second, nanos))
7975 }
7976
7977 fn ymd_hms_to_nanos(
7999 year: i64,
8000 month: u32,
8001 day: u32,
8002 hour: u32,
8003 minute: u32,
8004 second: u32,
8005 sub_nanos: u64,
8006 ) -> Option<i64> {
8007 let m = month as i64;
8008 let d = day as i64;
8009
8010 let y = if m <= 2 { year.checked_sub(1)? } else { year };
8011 let era = if y >= 0 { y } else { y.checked_sub(399)? } / 400;
8012 let yoe = y.checked_sub(era.checked_mul(400)?)?;
8013 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
8014 let doe = yoe
8015 .checked_mul(365)?
8016 .checked_add(yoe / 4 - yoe / 100)?
8017 .checked_add(doy)?;
8018 let days_since_epoch = era
8019 .checked_mul(146_097)?
8020 .checked_add(doe)?
8021 .checked_sub(719_468)?;
8022
8023 let total_seconds = days_since_epoch
8024 .checked_mul(86400)?
8025 .checked_add(i64::from(hour) * 3600)?
8026 .checked_add(i64::from(minute) * 60)?
8027 .checked_add(i64::from(second))?;
8028 total_seconds
8029 .checked_mul(Timedelta::NANOS_PER_SEC)?
8030 .checked_add(sub_nanos as i64)
8031 }
8032
8033 #[must_use]
8040 pub fn strftime(&self, format: &str) -> String {
8041 if self.is_nat() {
8042 return "NaT".to_string();
8043 }
8044 strftime_in_zone(self.nanos, format, self.tz.as_deref())
8045 }
8046
8047 #[must_use]
8051 pub fn day_name(&self) -> String {
8052 const NAMES: [&str; 7] = [
8053 "Thursday",
8054 "Friday",
8055 "Saturday",
8056 "Sunday",
8057 "Monday",
8058 "Tuesday",
8059 "Wednesday",
8060 ];
8061 if self.is_nat() {
8062 return "NaT".to_string();
8063 }
8064 let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
8070 let dow = ((days_since_epoch % 7) + 7) % 7;
8071 NAMES[dow as usize].to_string()
8072 }
8073
8074 #[must_use]
8078 pub fn month_name(&self) -> String {
8079 const NAMES: [&str; 12] = [
8080 "January",
8081 "February",
8082 "March",
8083 "April",
8084 "May",
8085 "June",
8086 "July",
8087 "August",
8088 "September",
8089 "October",
8090 "November",
8091 "December",
8092 ];
8093 if self.is_nat() {
8094 return "NaT".to_string();
8095 }
8096 let days_since_epoch = self.wall_nanos().div_euclid(Timedelta::NANOS_PER_DAY);
8100 let days = days_since_epoch + 719_468;
8101 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
8102 let doe = days - era * 146_097;
8103 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
8104 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
8105 let mp = (5 * doy + 2) / 153;
8106 let m = if mp < 10 { mp + 3 } else { mp - 9 };
8107 NAMES[(m - 1) as usize].to_string()
8108 }
8109
8110 pub fn try_tz_localize_with(
8116 &self,
8117 tz: Option<&str>,
8118 ambiguous: AmbiguousTime,
8119 nonexistent: NonexistentTime,
8120 ) -> Result<Self, TypeError> {
8121 match (tz, &self.tz) {
8122 (Some(_), Some(_)) => Err(TypeError::AlreadyTzAware),
8123 (None, _) => {
8124 if self.is_nat() {
8125 return Ok(Self::nat());
8126 }
8127 Ok(Self::from_nanos(self.wall_nanos()))
8128 }
8129 (Some(zone), None) => {
8130 if self.is_nat() {
8131 return Ok(Self::nat());
8132 }
8133 let nanos = tz_wall_to_utc_nanos_with(zone, self.nanos, ambiguous, nonexistent)?;
8134 if nanos == Self::NAT {
8135 return Ok(Self::nat());
8136 }
8137 Ok(Self {
8138 nanos,
8139 tz: Some(zone.to_owned()),
8140 })
8141 }
8142 }
8143 }
8144
8145 pub fn try_tz_localize(&self, tz: Option<&str>) -> Result<Self, TypeError> {
8151 self.try_tz_localize_with(tz, AmbiguousTime::Raise, NonexistentTime::Raise)
8152 }
8153
8154 #[must_use]
8157 pub fn tz_localize(&self, tz: Option<&str>) -> Self {
8158 self.try_tz_localize(tz).unwrap_or_else(|_| Self::nat())
8159 }
8160
8161 pub fn try_tz_convert(&self, tz: Option<&str>) -> Result<Self, TypeError> {
8168 if self.is_nat() {
8169 return Ok(Self::nat());
8170 }
8171 if self.tz.is_none() {
8172 return Err(TypeError::TzNaiveCannotConvert);
8173 }
8174 match tz {
8175 Some(zone) => {
8176 tz_validate(zone)?;
8177 Ok(Self {
8178 nanos: self.nanos,
8179 tz: Some(zone.to_owned()),
8180 })
8181 }
8182 None => Ok(Self {
8183 nanos: self.nanos,
8184 tz: None,
8185 }),
8186 }
8187 }
8188
8189 #[must_use]
8192 pub fn tz_convert(&self, tz: &str) -> Self {
8193 self.try_tz_convert(Some(tz))
8194 .unwrap_or_else(|_| Self::nat())
8195 }
8196
8197 #[must_use]
8202 pub fn fromtimestamp(ts: f64, tz: Option<&str>) -> Self {
8203 if ts.is_nan() || ts.is_infinite() {
8204 return Self::nat();
8205 }
8206 let nanos_f64 = ts * 1_000_000_000.0;
8207 const MAX_NANOS: f64 = i64::MAX as f64;
8209 const MIN_NANOS: f64 = i64::MIN as f64;
8210 if !(MIN_NANOS..=MAX_NANOS).contains(&nanos_f64) {
8211 return Self::nat();
8212 }
8213 Self {
8214 nanos: nanos_f64 as i64,
8215 tz: tz.map(String::from),
8216 }
8217 }
8218
8219 #[must_use]
8226 pub fn from_millis(ms: i64, tz: Option<&str>) -> Self {
8227 let Some(nanos) = ms.checked_mul(1_000_000) else {
8228 return Self::nat();
8229 };
8230 Self {
8231 nanos,
8232 tz: tz.map(String::from),
8233 }
8234 }
8235
8236 #[must_use]
8240 pub fn from_micros(us: i64, tz: Option<&str>) -> Self {
8241 let Some(nanos) = us.checked_mul(1_000) else {
8242 return Self::nat();
8243 };
8244 Self {
8245 nanos,
8246 tz: tz.map(String::from),
8247 }
8248 }
8249
8250 #[must_use]
8252 pub fn tzinfo(&self) -> Option<&str> {
8253 self.tz.as_deref()
8254 }
8255
8256 #[must_use]
8261 pub fn tzname(&self) -> Option<String> {
8262 if self.is_nat() {
8263 return None;
8264 }
8265 let tz = self.tz.as_deref()?;
8266 Some(tz_abbreviation(tz, self.nanos).unwrap_or_else(|_| tz.to_owned()))
8267 }
8268
8269 pub fn to_period(&self, freq: &str) -> Result<Period, TypeError> {
8273 if self.is_nat() {
8274 return Err(TypeError::ValueIsMissing {
8275 kind: NullKind::NaT,
8276 });
8277 }
8278 let target_freq = PeriodFreq::parse(freq).ok_or_else(|| TypeError::ValueNotParseable {
8279 value: freq.to_owned(),
8280 target: "PeriodFreq".to_owned(),
8281 })?;
8282 let offset_secs = self
8283 .tz
8284 .as_deref()
8285 .and_then(|tz| {
8286 tz_offset_seconds(tz, self.nanos)
8287 .ok()
8288 .map(i64::from)
8289 .or_else(|| Self::fixed_utc_offset_seconds(tz))
8290 })
8291 .unwrap_or(0);
8292 let wall_nanos = offset_secs
8293 .checked_mul(Timedelta::NANOS_PER_SEC)
8294 .and_then(|offset_nanos| self.nanos.checked_add(offset_nanos))
8295 .ok_or_else(|| TypeError::ValueNotParseable {
8296 value: self.to_string(),
8297 target: format!("Period[{target_freq}]"),
8298 })?;
8299 Period::from_timestamp_nanos(wall_nanos, target_freq).ok_or_else(|| {
8300 TypeError::ValueNotParseable {
8301 value: self.to_string(),
8302 target: format!("Period[{target_freq}]"),
8303 }
8304 })
8305 }
8306}
8307
8308impl std::fmt::Display for Timestamp {
8309 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8312 if self.is_nat() {
8313 return f.write_str("NaT");
8314 }
8315 match &self.tz {
8316 Some(tz) => write!(f, "Timestamp[{}, {}]", self.nanos, tz),
8317 None => write!(f, "Timestamp[{}, UTC]", self.nanos),
8318 }
8319 }
8320}
8321
8322impl PartialOrd for Timestamp {
8323 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
8328 if self.is_nat() || other.is_nat() {
8329 return None;
8330 }
8331 Some(self.nanos.cmp(&other.nanos))
8332 }
8333}
8334
8335pub fn isna(values: &[Scalar]) -> Vec<bool> {
8338 values.iter().map(Scalar::is_missing).collect()
8339}
8340
8341pub fn isnull(values: &[Scalar]) -> Vec<bool> {
8342 isna(values)
8343}
8344
8345pub fn notna(values: &[Scalar]) -> Vec<bool> {
8346 values.iter().map(|v| !v.is_missing()).collect()
8347}
8348
8349pub fn notnull(values: &[Scalar]) -> Vec<bool> {
8350 notna(values)
8351}
8352
8353pub fn count_na(values: &[Scalar]) -> usize {
8354 values.iter().filter(|v| v.is_missing()).count()
8355}
8356
8357pub fn fill_na(values: &[Scalar], fill: &Scalar) -> Vec<Scalar> {
8358 values
8359 .iter()
8360 .map(|v| {
8361 if v.is_missing() {
8362 fill.clone()
8363 } else {
8364 v.clone()
8365 }
8366 })
8367 .collect()
8368}
8369
8370pub fn dropna(values: &[Scalar]) -> Vec<Scalar> {
8371 values.iter().filter(|v| !v.is_missing()).cloned().collect()
8372}
8373
8374fn collect_finite(values: &[Scalar]) -> Vec<f64> {
8377 values
8378 .iter()
8379 .filter(|v| !v.is_missing())
8380 .filter_map(|v| v.to_f64().ok())
8381 .collect()
8382}
8383
8384fn collect_timedelta_ns(values: &[Scalar]) -> Option<(i128, usize)> {
8392 let mut sum: i128 = 0;
8393 let mut count: usize = 0;
8394 let mut saw_timedelta = false;
8395 for v in values {
8396 match v {
8397 Scalar::Timedelta64(ns) => {
8398 saw_timedelta = true;
8399 if v.is_missing() {
8400 continue;
8401 }
8402 sum += i128::from(*ns);
8403 count += 1;
8404 }
8405 _ if v.is_missing() => continue,
8406 _ => return None,
8409 }
8410 }
8411 if saw_timedelta {
8412 Some((sum, count))
8413 } else {
8414 None
8415 }
8416}
8417
8418fn timedelta_ns_to_scalar(ns: i128) -> Scalar {
8437 if ns > i128::from(i64::MAX) || ns <= i128::from(i64::MIN) {
8438 return Scalar::Timedelta64(Timedelta::NAT);
8439 }
8440 Scalar::Timedelta64(ns as i64)
8441}
8442
8443pub fn nansum(values: &[Scalar]) -> Scalar {
8444 if let Some((sum, _)) = collect_timedelta_ns(values) {
8445 return timedelta_ns_to_scalar(sum);
8446 }
8447 let mut sum = 0.0_f64;
8452 for v in values {
8453 if v.is_missing() {
8454 continue;
8455 }
8456 if let Ok(x) = v.to_f64() {
8457 sum += x;
8458 }
8459 }
8460 Scalar::Float64(sum)
8461}
8462
8463#[must_use]
8500pub fn nansum_utf8(values: &[Scalar]) -> Scalar {
8501 let mut out: Option<String> = None;
8502 for v in values {
8503 if v.is_missing() {
8504 continue;
8505 }
8506 if let Scalar::Utf8(part) = v {
8507 out.get_or_insert_with(String::new).push_str(part);
8508 }
8509 }
8510 match out {
8511 Some(joined) => Scalar::Utf8(joined),
8512 None => Scalar::Int64(0),
8514 }
8515}
8516
8517pub fn nanmean(values: &[Scalar]) -> Scalar {
8518 if let Some((sum, count)) = collect_timedelta_ns(values) {
8519 if count == 0 {
8520 return Scalar::Timedelta64(Timedelta::NAT);
8521 }
8522 return timedelta_ns_to_scalar(sum / count as i128);
8525 }
8526 if let Some((sum, count)) = collect_datetime_ns(values) {
8533 if count == 0 {
8534 return Scalar::Datetime64(Timestamp::NAT);
8535 }
8536 let mean = sum / count as i128;
8537 if mean > i128::from(i64::MAX) || mean <= i128::from(i64::MIN) {
8538 return Scalar::Datetime64(Timestamp::NAT);
8539 }
8540 return Scalar::Datetime64(mean as i64);
8541 }
8542 let mut sum = 0.0_f64;
8546 let mut count = 0usize;
8547 for v in values {
8548 if v.is_missing() {
8549 continue;
8550 }
8551 if let Ok(x) = v.to_f64() {
8552 sum += x;
8553 count += 1;
8554 }
8555 }
8556 if count == 0 {
8557 return Scalar::Null(NullKind::NaN);
8558 }
8559 Scalar::Float64(sum / count as f64)
8560}
8561
8562pub fn nanany(values: &[Scalar]) -> Scalar {
8563 for v in values {
8564 if v.is_missing() {
8565 continue;
8566 }
8567 match v {
8568 Scalar::Bool(flag) if *flag => return Scalar::Bool(true),
8569 Scalar::Int64(val) if *val != 0 => return Scalar::Bool(true),
8570 Scalar::Float64(val) if !val.is_nan() && *val != 0.0 => return Scalar::Bool(true),
8571 Scalar::Utf8(val) if !val.is_empty() => return Scalar::Bool(true),
8572 Scalar::Timedelta64(ns) if *ns != 0 => return Scalar::Bool(true),
8575 _ => continue,
8576 }
8577 }
8578 Scalar::Bool(false)
8579}
8580
8581pub fn nanall(values: &[Scalar]) -> Scalar {
8582 for v in values {
8583 if v.is_missing() {
8584 continue;
8585 }
8586 match v {
8587 Scalar::Bool(flag) if !*flag => return Scalar::Bool(false),
8588 Scalar::Int64(val) if *val == 0 => return Scalar::Bool(false),
8589 Scalar::Float64(val) if val.is_nan() || *val == 0.0 => return Scalar::Bool(false),
8590 Scalar::Utf8(val) if val.is_empty() => return Scalar::Bool(false),
8591 Scalar::Timedelta64(ns) if *ns == 0 => return Scalar::Bool(false),
8594 _ => continue,
8595 }
8596 }
8597 Scalar::Bool(true)
8598}
8599
8600pub fn nancount(values: &[Scalar]) -> Scalar {
8601 let n = values.iter().filter(|v| !v.is_missing()).count();
8602 Scalar::Int64(n as i64)
8603}
8604
8605pub fn nanmin(values: &[Scalar]) -> Scalar {
8606 let mut min: Option<&Scalar> = None;
8607 for v in values {
8608 if v.is_missing() {
8609 continue;
8610 }
8611 match (min, v) {
8612 (None, _) => min = Some(v),
8613 (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8614 if b < a {
8615 min = Some(v)
8616 }
8617 }
8618 (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8619 if *b < *a {
8620 min = Some(v)
8621 }
8622 }
8623 (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8624 if b < a {
8625 min = Some(v)
8626 }
8627 }
8628 (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8629 if b < a {
8630 min = Some(v)
8631 }
8632 }
8633 (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8638 if b < a {
8639 min = Some(v)
8640 }
8641 }
8642 (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8647 if b < a {
8648 min = Some(v)
8649 }
8650 }
8651 (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8664 if a.freq != b.freq {
8665 return Scalar::Null(NullKind::NaN);
8666 }
8667 if b.ordinal < a.ordinal {
8668 min = Some(v)
8669 }
8670 }
8671 (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8686 if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8687 return Scalar::Null(NullKind::NaN);
8688 }
8689 if (b.left, b.right) < (a.left, a.right) {
8690 min = Some(v)
8691 }
8692 }
8693 (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8694 (Ok(af), Ok(bf)) if bf < af => min = Some(v),
8695 (Ok(_), Ok(_)) => {}
8696 _ => return Scalar::Null(NullKind::NaN),
8697 },
8698 }
8699 }
8700 match min {
8701 Some(v) => v.clone(),
8702 None => Scalar::Null(NullKind::NaN),
8703 }
8704}
8705
8706pub fn nanmax(values: &[Scalar]) -> Scalar {
8707 let mut max: Option<&Scalar> = None;
8708 for v in values {
8709 if v.is_missing() {
8710 continue;
8711 }
8712 match (max, v) {
8713 (None, _) => max = Some(v),
8714 (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8715 if b > a {
8716 max = Some(v)
8717 }
8718 }
8719 (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8720 if *b > *a {
8721 max = Some(v)
8722 }
8723 }
8724 (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8725 if b > a {
8726 max = Some(v)
8727 }
8728 }
8729 (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8730 if b > a {
8731 max = Some(v)
8732 }
8733 }
8734 (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8738 if b > a {
8739 max = Some(v)
8740 }
8741 }
8742 (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8744 if b > a {
8745 max = Some(v)
8746 }
8747 }
8748 (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8750 if a.freq != b.freq {
8751 return Scalar::Null(NullKind::NaN);
8752 }
8753 if b.ordinal > a.ordinal {
8754 max = Some(v)
8755 }
8756 }
8757 (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8760 if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8761 return Scalar::Null(NullKind::NaN);
8762 }
8763 if (b.left, b.right) > (a.left, a.right) {
8764 max = Some(v)
8765 }
8766 }
8767 (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8768 (Ok(af), Ok(bf)) if bf > af => max = Some(v),
8769 (Ok(_), Ok(_)) => {}
8770 _ => return Scalar::Null(NullKind::NaN),
8771 },
8772 }
8773 }
8774 match max {
8775 Some(v) => v.clone(),
8776 None => Scalar::Null(NullKind::NaN),
8777 }
8778}
8779
8780#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8792enum TemporalFamily {
8793 Timedelta,
8794 Datetime,
8795 Period(PeriodFreq),
8797}
8798
8799impl TemporalFamily {
8800 fn make(self, raw: i64) -> Scalar {
8802 match self {
8803 Self::Timedelta => Scalar::Timedelta64(raw),
8804 Self::Datetime => Scalar::Datetime64(raw),
8805 Self::Period(freq) => Scalar::Period(Period::new(raw, freq)),
8806 }
8807 }
8808
8809 fn nat(self) -> Scalar {
8811 self.make(i64::MIN)
8812 }
8813}
8814
8815fn collect_temporal_backing(values: &[Scalar]) -> Option<(Vec<f64>, TemporalFamily)> {
8830 let mut out = Vec::with_capacity(values.len());
8831 let mut family: Option<TemporalFamily> = None;
8832 for v in values {
8833 let (raw, this) = match v {
8834 Scalar::Timedelta64(ns) => (*ns, TemporalFamily::Timedelta),
8835 Scalar::Datetime64(ns) => (*ns, TemporalFamily::Datetime),
8836 Scalar::Period(p) => (p.ordinal, TemporalFamily::Period(p.freq)),
8837 _ if v.is_missing() => continue,
8838 _ => return None,
8839 };
8840 match family {
8842 Some(existing) if existing != this => return None,
8843 _ => family = Some(this),
8844 }
8845 if v.is_missing() {
8846 continue;
8847 }
8848 out.push(raw as f64);
8849 }
8850 family.map(|f| (out, f))
8851}
8852
8853fn collect_timedelta_ns_f64(values: &[Scalar]) -> Option<Vec<f64>> {
8860 match collect_temporal_backing(values) {
8861 Some((out, TemporalFamily::Timedelta)) => Some(out),
8862 _ => None,
8863 }
8864}
8865
8866fn float_ns_to_timedelta(value: f64) -> Scalar {
8868 float_ns_to_temporal(value, TemporalFamily::Timedelta)
8869}
8870
8871fn float_ns_to_temporal(value: f64, make: TemporalFamily) -> Scalar {
8874 if !value.is_finite() {
8875 return make.nat();
8876 }
8877 let clamped = value.clamp(i64::MIN as f64, i64::MAX as f64);
8878 make.make(clamped as i64)
8879}
8880
8881pub fn nanmedian(values: &[Scalar]) -> Scalar {
8882 let Some((_, make)) = collect_temporal_backing(values) else {
8896 return nanmedian_numeric(values);
8898 };
8899 let mut td: Vec<i64> = values
8900 .iter()
8901 .filter(|value| !value.is_missing())
8902 .filter_map(|value| match value {
8903 Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
8904 Scalar::Period(p) => Some(p.ordinal),
8905 _ => None,
8906 })
8907 .collect();
8908 if td.is_empty() {
8909 return nanmedian_numeric(values);
8917 }
8918 let n = td.len();
8921 let mid = n / 2;
8922 let (left, mid_ref, _right) = td.select_nth_unstable(mid);
8923 let mid_val = *mid_ref;
8924 let median_ns = if n.is_multiple_of(2) {
8925 let lower = left.iter().copied().fold(i64::MIN, i64::max);
8926 (i128::from(lower) + i128::from(mid_val)) / 2
8928 } else {
8929 i128::from(mid_val)
8930 };
8931 make.make(median_ns as i64)
8932}
8933
8934fn nanmedian_numeric(values: &[Scalar]) -> Scalar {
8938 let mut nums = collect_finite(values);
8939 if nums.is_empty() {
8940 return Scalar::Null(NullKind::NaN);
8941 }
8942 let n = nums.len();
8949 let mid = n / 2;
8950 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
8951 let (left, mid_ref, _right) = nums.select_nth_unstable_by(mid, cmp);
8952 let mid_val = *mid_ref;
8953 if n.is_multiple_of(2) {
8954 let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
8955 Scalar::Float64((lower + mid_val) / 2.0)
8956 } else {
8957 Scalar::Float64(mid_val)
8958 }
8959}
8960
8961pub fn nanvar(values: &[Scalar], ddof: usize) -> Scalar {
8962 if let Some(td) = collect_timedelta_ns_f64(values) {
8965 if td.len() <= ddof {
8966 return Scalar::Timedelta64(Timedelta::NAT);
8967 }
8968 let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8969 let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8970 return float_ns_to_timedelta(sum_sq / (td.len() - ddof) as f64);
8971 }
8972 let nums = collect_finite(values);
8973 if nums.len() <= ddof {
8974 return Scalar::Null(NullKind::NaN);
8975 }
8976 let mean: f64 = nums.iter().sum::<f64>() / nums.len() as f64;
8977 let sum_sq: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
8978 Scalar::Float64(sum_sq / (nums.len() - ddof) as f64)
8979}
8980
8981pub fn nanstd(values: &[Scalar], ddof: usize) -> Scalar {
8982 if let Some((td, family)) = collect_temporal_backing(values)
9001 && !matches!(family, TemporalFamily::Period(_))
9002 {
9003 if td.len() <= ddof {
9004 return Scalar::Timedelta64(Timedelta::NAT);
9005 }
9006 let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
9007 let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
9008 let var = sum_sq / (td.len() - ddof) as f64;
9009 return float_ns_to_timedelta(var.sqrt());
9010 }
9011 match nanvar(values, ddof) {
9012 Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
9013 other => other,
9014 }
9015}
9016
9017pub fn nansem(values: &[Scalar], ddof: usize) -> Scalar {
9023 if let Some(td) = collect_timedelta_ns_f64(values) {
9025 if td.len() <= ddof {
9026 return Scalar::Timedelta64(Timedelta::NAT);
9027 }
9028 let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
9029 let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
9030 let var = sum_sq / (td.len() - ddof) as f64;
9031 let std = var.sqrt();
9032 return float_ns_to_timedelta(std / (td.len() as f64).sqrt());
9033 }
9034 let nums = collect_finite(values);
9035 if nums.len() <= ddof {
9036 return Scalar::Null(NullKind::NaN);
9037 }
9038 let n = nums.len();
9039 let mean = nums.iter().sum::<f64>() / n as f64;
9040 let sum_sq = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
9041 let var = sum_sq / (n - ddof) as f64;
9042 let std = var.sqrt();
9043 Scalar::Float64(std / (n as f64).sqrt())
9044}
9045
9046pub fn nansem_grouped(values: &[Scalar], ddof: usize) -> Scalar {
9052 if collect_timedelta_ns_f64(values).is_some() {
9053 return nansem(values, ddof);
9054 }
9055 grouped_moments(values)
9056 .sem(ddof)
9057 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9058}
9059
9060#[derive(Clone, Copy, Debug, Default, PartialEq)]
9067pub struct KahanSum {
9068 sum: f64,
9069 compensation: f64,
9070}
9071
9072impl KahanSum {
9073 #[inline]
9075 pub fn add(&mut self, value: f64) {
9076 let y = value - self.compensation;
9077 let t = self.sum + y;
9078 self.compensation = t - self.sum - y;
9079 if self.compensation.is_nan() {
9080 self.compensation = 0.0;
9081 }
9082 self.sum = t;
9083 }
9084
9085 #[inline]
9087 #[must_use]
9088 pub fn sum(self) -> f64 {
9089 self.sum
9090 }
9091}
9092
9093#[derive(Clone, Copy, Debug, Default, PartialEq)]
9100pub struct WelfordVar {
9101 count: usize,
9102 mean: f64,
9103 m2: f64,
9104}
9105
9106impl WelfordVar {
9107 #[inline]
9109 pub fn add(&mut self, value: f64) {
9110 self.count += 1;
9111 let old = self.mean;
9112 self.mean += (value - old) / self.count as f64;
9113 self.m2 += (value - self.mean) * (value - old);
9114 }
9115
9116 #[must_use]
9118 pub fn count(self) -> usize {
9119 self.count
9120 }
9121
9122 #[must_use]
9124 pub fn var(self, ddof: usize) -> Option<f64> {
9125 (self.count > ddof).then(|| self.m2 / (self.count - ddof) as f64)
9126 }
9127
9128 #[must_use]
9130 pub fn std(self, ddof: usize) -> Option<f64> {
9131 self.var(ddof).map(f64::sqrt)
9132 }
9133
9134 #[must_use]
9136 pub fn sem(self, ddof: usize) -> Option<f64> {
9137 self.var(ddof).map(|var| (var / self.count as f64).sqrt())
9138 }
9139}
9140
9141#[derive(Clone, Copy, Debug, Default, PartialEq)]
9149pub struct SkewMoments {
9150 count: usize,
9151 m1: f64,
9152 m2: f64,
9153 m3: f64,
9154}
9155
9156impl SkewMoments {
9157 #[inline]
9159 pub fn add(&mut self, value: f64) {
9160 let before = self.count as f64;
9161 self.count += 1;
9162 let n = self.count as f64;
9163 let delta = value - self.m1;
9164 let delta_n = delta / n;
9165 let term1 = delta * delta_n * before;
9166 self.m1 += delta_n;
9167 self.m3 += term1 * delta_n * (n - 2.0) - 3.0 * delta_n * self.m2;
9168 self.m2 += term1;
9169 }
9170
9171 #[must_use]
9173 pub fn count(self) -> usize {
9174 self.count
9175 }
9176
9177 #[must_use]
9179 pub fn skew(self) -> Option<f64> {
9180 if self.count < 3 {
9181 return None;
9182 }
9183 if self.m2 == 0.0 {
9184 return Some(0.0);
9185 }
9186 let n = self.count as f64;
9187 let half = std::hint::black_box(0.5);
9191 Some((n * (n - 1.0).powf(half) / (n - 2.0)) * (self.m3 / self.m2.powf(1.5)))
9192 }
9193}
9194
9195#[must_use]
9198pub fn nanskew_grouped(values: &[Scalar]) -> Scalar {
9199 let mut moments = SkewMoments::default();
9200 for value in values {
9201 if value.is_missing() {
9202 continue;
9203 }
9204 if let Ok(x) = value.to_f64() {
9205 moments.add(x);
9206 }
9207 }
9208 moments
9209 .skew()
9210 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9211}
9212
9213fn grouped_moments(values: &[Scalar]) -> WelfordVar {
9215 let mut moments = WelfordVar::default();
9216 for value in values {
9217 if value.is_missing() {
9218 continue;
9219 }
9220 if let Ok(x) = value.to_f64() {
9221 moments.add(x);
9222 }
9223 }
9224 moments
9225}
9226
9227#[must_use]
9231pub fn nansum_grouped(values: &[Scalar]) -> Scalar {
9232 if collect_timedelta_ns(values).is_some() {
9233 return nansum(values);
9234 }
9235 let mut sum = KahanSum::default();
9236 for value in values {
9237 if value.is_missing() {
9238 continue;
9239 }
9240 if let Ok(x) = value.to_f64() {
9241 sum.add(x);
9242 }
9243 }
9244 Scalar::Float64(sum.sum())
9245}
9246
9247#[must_use]
9250pub fn nanmean_grouped(values: &[Scalar]) -> Scalar {
9251 if collect_timedelta_ns(values).is_some() || collect_datetime_ns(values).is_some() {
9252 return nanmean(values);
9253 }
9254 let mut sum = KahanSum::default();
9255 let mut count = 0_usize;
9256 for value in values {
9257 if value.is_missing() {
9258 continue;
9259 }
9260 if let Ok(x) = value.to_f64() {
9261 sum.add(x);
9262 count += 1;
9263 }
9264 }
9265 if count == 0 {
9266 return Scalar::Null(NullKind::NaN);
9267 }
9268 Scalar::Float64(sum.sum() / count as f64)
9269}
9270
9271#[must_use]
9274pub fn nanvar_grouped(values: &[Scalar], ddof: usize) -> Scalar {
9275 if collect_timedelta_ns_f64(values).is_some() {
9276 return nanvar(values, ddof);
9277 }
9278 grouped_moments(values)
9279 .var(ddof)
9280 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9281}
9282
9283#[must_use]
9286pub fn nanstd_grouped(values: &[Scalar], ddof: usize) -> Scalar {
9287 if collect_temporal_backing(values).is_some() {
9288 return nanstd(values, ddof);
9289 }
9290 grouped_moments(values)
9291 .std(ddof)
9292 .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
9293}
9294
9295pub fn nanptp(values: &[Scalar]) -> Scalar {
9300 if is_datetime_input(values) {
9308 let (mut lo, mut hi) = (i64::MAX, i64::MIN);
9309 for value in values {
9310 if value.is_missing() {
9311 continue;
9312 }
9313 if let Scalar::Datetime64(ns) = value {
9314 lo = lo.min(*ns);
9315 hi = hi.max(*ns);
9316 }
9317 }
9318 return timedelta_ns_to_scalar(i128::from(hi) - i128::from(lo));
9319 }
9320 let (mut td_lo, mut td_hi) = (i64::MAX, i64::MIN);
9324 let mut saw_timedelta = false;
9325 let mut all_timedelta = true;
9326 for value in values {
9327 if value.is_missing() {
9328 continue;
9329 }
9330 match value {
9331 Scalar::Timedelta64(ns) => {
9332 saw_timedelta = true;
9333 td_lo = td_lo.min(*ns);
9334 td_hi = td_hi.max(*ns);
9335 }
9336 _ => {
9337 all_timedelta = false;
9338 break;
9339 }
9340 }
9341 }
9342 if all_timedelta && saw_timedelta {
9343 return timedelta_ns_to_scalar(i128::from(td_hi) - i128::from(td_lo));
9347 }
9348 let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
9353 let mut seen = false;
9354 for v in values {
9355 if v.is_missing() {
9356 continue;
9357 }
9358 if let Ok(x) = v.to_f64() {
9359 seen = true;
9360 if x < lo {
9361 lo = x;
9362 }
9363 if x > hi {
9364 hi = x;
9365 }
9366 }
9367 }
9368 if !seen {
9369 return Scalar::Null(NullKind::NaN);
9370 }
9371 Scalar::Float64(hi - lo)
9372}
9373
9374pub fn nanskew(values: &[Scalar]) -> Scalar {
9380 let nums = collect_finite(values);
9381 let n = nums.len() as f64;
9382 if n < 3.0 {
9383 return Scalar::Null(NullKind::NaN);
9384 }
9385 let mean = nums.iter().sum::<f64>() / n;
9386 let (mut m2, mut m3) = (0.0_f64, 0.0_f64);
9390 for x in nums {
9391 let delta = x - mean;
9392 let d2 = delta * delta;
9398 m2 += d2;
9399 m3 += d2 * delta;
9400 }
9401 let s2 = m2 / (n - 1.0);
9402 if s2 == 0.0 {
9403 return Scalar::Float64(0.0);
9404 }
9405 let s3 = s2.powf(1.5);
9406 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
9407}
9408
9409pub fn nankurt(values: &[Scalar]) -> Scalar {
9416 let nums = collect_finite(values);
9417 let n = nums.len() as f64;
9418 if n < 4.0 {
9419 return Scalar::Null(NullKind::NaN);
9420 }
9421 let mean = nums.iter().sum::<f64>() / n;
9422 let (mut m2, mut m4) = (0.0_f64, 0.0_f64);
9426 for x in nums {
9427 let delta = x - mean;
9428 let d2 = delta * delta;
9431 m2 += d2;
9432 m4 += d2 * d2;
9433 }
9434 let s2 = m2 / (n - 1.0);
9435 if s2 == 0.0 {
9436 return Scalar::Float64(0.0);
9437 }
9438 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
9439 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
9440 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
9441}
9442
9443pub fn nanprod(values: &[Scalar]) -> Scalar {
9445 if is_timedelta_input(values) {
9452 return Scalar::Null(NullKind::NaN);
9453 }
9454 let mut prod = 1.0_f64;
9459 for v in values {
9460 if v.is_missing() {
9461 continue;
9462 }
9463 if let Ok(x) = v.to_f64() {
9464 prod *= x;
9465 }
9466 }
9467 Scalar::Float64(prod)
9468}
9469
9470fn is_timedelta_input(values: &[Scalar]) -> bool {
9476 let mut saw_td = false;
9477 for v in values {
9478 if v.is_missing() {
9479 continue;
9480 }
9481 match v {
9482 Scalar::Timedelta64(_) => saw_td = true,
9483 _ => return false,
9484 }
9485 }
9486 saw_td
9487}
9488
9489fn collect_datetime_ns(values: &[Scalar]) -> Option<(i128, usize)> {
9499 let mut sum: i128 = 0;
9500 let mut count: usize = 0;
9501 let mut saw_datetime = false;
9502 for v in values {
9503 match v {
9504 Scalar::Datetime64(ns) => {
9505 saw_datetime = true;
9506 if v.is_missing() {
9507 continue;
9508 }
9509 sum += i128::from(*ns);
9510 count += 1;
9511 }
9512 _ if v.is_missing() => continue,
9513 _ => return None,
9514 }
9515 }
9516 if saw_datetime {
9517 Some((sum, count))
9518 } else {
9519 None
9520 }
9521}
9522
9523fn is_datetime_input(values: &[Scalar]) -> bool {
9530 let mut saw_dt = false;
9531 for v in values {
9532 if v.is_missing() {
9533 continue;
9534 }
9535 match v {
9536 Scalar::Datetime64(_) => saw_dt = true,
9537 _ => return false,
9538 }
9539 }
9540 saw_dt
9541}
9542
9543fn is_int64_input(values: &[Scalar]) -> bool {
9545 let mut saw_int = false;
9546 for value in values {
9547 if value.is_missing() {
9548 continue;
9549 }
9550 match value {
9551 Scalar::Int64(_) => saw_int = true,
9552 _ => return false,
9553 }
9554 }
9555 saw_int
9556}
9557
9558fn is_interval_input(values: &[Scalar]) -> bool {
9561 let mut saw_interval = false;
9562 for v in values {
9563 if v.is_missing() {
9564 continue;
9565 }
9566 match v {
9567 Scalar::Interval(_) => saw_interval = true,
9568 _ => return false,
9569 }
9570 }
9571 saw_interval
9572}
9573
9574fn nanarg_interval(values: &[Scalar], find_max: bool) -> Option<usize> {
9586 let mut best: Option<(usize, (f64, f64))> = None;
9587 for (index, value) in values.iter().enumerate() {
9588 if value.is_missing() {
9589 continue;
9590 }
9591 let Scalar::Interval(iv) = value else {
9592 continue;
9593 };
9594 if iv.left.is_nan() || iv.right.is_nan() {
9595 return None;
9596 }
9597 let key = (iv.left, iv.right);
9598 match best {
9599 None => best = Some((index, key)),
9600 Some((_, current)) if (find_max && key > current) || (!find_max && key < current) => {
9603 best = Some((index, key));
9604 }
9605 _ => {}
9606 }
9607 }
9608 best.map(|(index, _)| index)
9609}
9610
9611fn nanarg_i64(values: &[Scalar], find_max: bool) -> Option<usize> {
9612 let mut best: Option<(usize, i64)> = None;
9613 for (index, value) in values.iter().enumerate() {
9614 if value.is_missing() {
9615 continue;
9616 }
9617 let candidate = match value {
9626 Scalar::Int64(raw) | Scalar::Timedelta64(raw) | Scalar::Datetime64(raw) => raw,
9627 Scalar::Period(p) => &p.ordinal,
9628 _ => continue,
9629 };
9630 match best {
9631 None => best = Some((index, *candidate)),
9632 Some((_, current))
9633 if (find_max && *candidate > current) || (!find_max && *candidate < current) =>
9634 {
9635 best = Some((index, *candidate));
9636 }
9637 _ => {}
9638 }
9639 }
9640 best.map(|(index, _)| index)
9641}
9642
9643fn timedelta_cumulative<F>(values: &[Scalar], init: i128, mut step: F) -> Vec<Scalar>
9648where
9649 F: FnMut(i128, i128) -> i128,
9650{
9651 let mut out = Vec::with_capacity(values.len());
9652 let mut running: i128 = init;
9653 for v in values {
9654 if v.is_missing() {
9655 out.push(Scalar::Null(NullKind::NaT));
9656 continue;
9657 }
9658 if let Scalar::Timedelta64(ns) = v {
9659 running = step(running, i128::from(*ns));
9666 out.push(timedelta_ns_to_scalar(running));
9667 } else {
9668 out.push(Scalar::Null(NullKind::NaT));
9669 }
9670 }
9671 out
9672}
9673
9674fn timedelta_cumulative_extrema<F>(
9682 values: &[Scalar],
9683 sentinel: i64,
9684 make: TemporalFamily,
9685 mut step: F,
9686) -> Vec<Scalar>
9687where
9688 F: FnMut(i64, i64) -> i64,
9689{
9690 let mut out = Vec::with_capacity(values.len());
9691 let mut running: Option<i64> = None;
9692 for v in values {
9693 if v.is_missing() {
9694 out.push(Scalar::Null(NullKind::NaT));
9695 continue;
9696 }
9697 let raw = match v {
9699 Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
9700 Scalar::Period(p) => Some(p.ordinal),
9701 _ => None,
9702 };
9703 if let Some(ns) = raw.as_ref() {
9704 let new_val = match running {
9705 Some(prev) => step(prev, *ns),
9706 None => *ns,
9707 };
9708 running = Some(new_val);
9709 out.push(make.make(new_val));
9710 } else {
9711 out.push(Scalar::Null(NullKind::NaT));
9712 }
9713 }
9714 let _ = sentinel; out
9716}
9717
9718#[must_use]
9739pub fn nancumsum_with_policy(values: &[Scalar], policy: OverflowPolicy) -> Vec<Scalar> {
9740 if !matches!(policy, OverflowPolicy::Strict) || !is_timedelta_input(values) {
9741 return nancumsum(values);
9742 }
9743 let mut out = Vec::with_capacity(values.len());
9744 let mut running: i64 = 0;
9745 for value in values {
9746 if value.is_missing() {
9747 out.push(Scalar::Null(NullKind::NaT));
9748 continue;
9749 }
9750 if let Scalar::Timedelta64(ns) = value {
9751 running = running.wrapping_add(*ns);
9754 out.push(Scalar::Timedelta64(running));
9755 } else {
9756 out.push(Scalar::Null(NullKind::NaT));
9757 }
9758 }
9759 out
9760}
9761
9762pub fn nancumsum(values: &[Scalar]) -> Vec<Scalar> {
9763 if is_timedelta_input(values) {
9767 return timedelta_cumulative(values, 0_i128, |acc, x| acc.saturating_add(x));
9768 }
9769 let mut out = Vec::with_capacity(values.len());
9770 let mut running = 0.0_f64;
9771 for v in values {
9772 if v.is_missing() {
9773 out.push(Scalar::Null(NullKind::NaN));
9774 continue;
9775 }
9776 match v.to_f64() {
9777 Ok(x) if !x.is_nan() => {
9778 running += x;
9779 out.push(Scalar::Float64(running));
9780 }
9781 _ => out.push(Scalar::Null(NullKind::NaN)),
9782 }
9783 }
9784 out
9785}
9786
9787pub fn nancumprod(values: &[Scalar]) -> Vec<Scalar> {
9792 let mut out = Vec::with_capacity(values.len());
9793 let mut running = 1.0_f64;
9794 for v in values {
9795 if v.is_missing() {
9796 out.push(Scalar::Null(NullKind::NaN));
9797 continue;
9798 }
9799 match v.to_f64() {
9800 Ok(x) if !x.is_nan() => {
9801 running *= x;
9802 out.push(Scalar::Float64(running));
9803 }
9804 _ => out.push(Scalar::Null(NullKind::NaN)),
9805 }
9806 }
9807 out
9808}
9809
9810pub fn nancummax(values: &[Scalar]) -> Vec<Scalar> {
9816 if let Some((_, family)) = collect_temporal_backing(values) {
9822 return timedelta_cumulative_extrema(values, i64::MAX, family, |acc, x| acc.max(x));
9823 }
9824 let mut out = Vec::with_capacity(values.len());
9825 let mut running: Option<f64> = None;
9826 for v in values {
9827 if v.is_missing() {
9828 out.push(Scalar::Null(NullKind::NaN));
9829 continue;
9830 }
9831 match v.to_f64() {
9832 Ok(x) if !x.is_nan() => {
9833 let new_val = match running {
9834 Some(prev) => prev.max(x),
9835 None => x,
9836 };
9837 running = Some(new_val);
9838 out.push(Scalar::Float64(new_val));
9839 }
9840 _ => out.push(Scalar::Null(NullKind::NaN)),
9841 }
9842 }
9843 out
9844}
9845
9846pub fn nancummin(values: &[Scalar]) -> Vec<Scalar> {
9850 if is_timedelta_input(values) {
9852 return timedelta_cumulative_extrema(
9853 values,
9854 i64::MIN,
9855 TemporalFamily::Timedelta,
9856 |acc, x| acc.min(x),
9857 );
9858 }
9859 if let Some((_, family)) = collect_temporal_backing(values) {
9861 return timedelta_cumulative_extrema(values, i64::MIN, family, |acc, x| acc.min(x));
9862 }
9863 let mut out = Vec::with_capacity(values.len());
9864 let mut running: Option<f64> = None;
9865 for v in values {
9866 if v.is_missing() {
9867 out.push(Scalar::Null(NullKind::NaN));
9868 continue;
9869 }
9870 match v.to_f64() {
9871 Ok(x) if !x.is_nan() => {
9872 let new_val = match running {
9873 Some(prev) => prev.min(x),
9874 None => x,
9875 };
9876 running = Some(new_val);
9877 out.push(Scalar::Float64(new_val));
9878 }
9879 _ => out.push(Scalar::Null(NullKind::NaN)),
9880 }
9881 }
9882 out
9883}
9884
9885pub fn nanquantile(values: &[Scalar], q: f64) -> Scalar {
9891 if !(0.0..=1.0).contains(&q) {
9892 return Scalar::Null(NullKind::NaN);
9893 }
9894 if let Some((mut td, make)) = collect_temporal_backing(values) {
9897 if td.is_empty() {
9898 return make.nat();
9899 }
9900 let n = td.len();
9901 if n == 1 {
9902 return float_ns_to_temporal(td[0], make);
9903 }
9904 let pos = q * (n - 1) as f64;
9905 let lo = pos.floor() as usize;
9906 let hi = pos.ceil() as usize;
9907 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9911 let (_left, lo_ref, right) = td.select_nth_unstable_by(lo, cmp);
9912 let lo_val = *lo_ref;
9913 let ns = if lo == hi {
9914 lo_val
9915 } else {
9916 let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9917 let weight = pos - lo as f64;
9918 lo_val + (hi_val - lo_val) * weight
9919 };
9920 return float_ns_to_temporal(ns, make);
9921 }
9922 let mut nums = collect_finite(values);
9923 if nums.is_empty() {
9924 return Scalar::Null(NullKind::NaN);
9925 }
9926 let n = nums.len();
9927 if n == 1 {
9928 return Scalar::Float64(nums[0]);
9929 }
9930 let pos = q * (n - 1) as f64;
9931 let lo = pos.floor() as usize;
9932 let hi = pos.ceil() as usize;
9933 let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9938 let (_left, lo_ref, right) = nums.select_nth_unstable_by(lo, cmp);
9939 let lo_val = *lo_ref;
9940 if lo == hi {
9941 return Scalar::Float64(lo_val);
9942 }
9943 let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9944 let weight = pos - lo as f64;
9945 Scalar::Float64(lo_val + (hi_val - lo_val) * weight)
9946}
9947
9948pub fn nanargmax(values: &[Scalar]) -> Option<usize> {
9953 if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9958 return nanarg_i64(values, true);
9959 }
9960 if is_interval_input(values) {
9964 return nanarg_interval(values, true);
9965 }
9966 let mut best: Option<(usize, f64)> = None;
9967 for (i, v) in values.iter().enumerate() {
9968 if v.is_missing() {
9969 continue;
9970 }
9971 if let Ok(x) = v.to_f64() {
9972 if x.is_nan() {
9973 continue;
9974 }
9975 match best {
9976 None => best = Some((i, x)),
9977 Some((_, cur)) if x > cur => best = Some((i, x)),
9978 _ => {}
9979 }
9980 }
9981 }
9982 best.map(|(i, _)| i)
9983}
9984
9985pub fn nanargmin(values: &[Scalar]) -> Option<usize> {
9989 if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9992 return nanarg_i64(values, false);
9993 }
9994 if is_interval_input(values) {
9996 return nanarg_interval(values, false);
9997 }
9998 let mut best: Option<(usize, f64)> = None;
9999 for (i, v) in values.iter().enumerate() {
10000 if v.is_missing() {
10001 continue;
10002 }
10003 if let Ok(x) = v.to_f64() {
10004 if x.is_nan() {
10005 continue;
10006 }
10007 match best {
10008 None => best = Some((i, x)),
10009 Some((_, cur)) if x < cur => best = Some((i, x)),
10010 _ => {}
10011 }
10012 }
10013 }
10014 best.map(|(i, _)| i)
10015}
10016
10017pub fn nannunique(values: &[Scalar]) -> Scalar {
10019 use rustc_hash::FxHashSet;
10020 #[derive(Hash, PartialEq, Eq)]
10021 enum ScalarKey<'a> {
10022 Bool(bool),
10023 Int64(i64),
10024 FloatBits(u64),
10025 Utf8(&'a str),
10026 Timedelta64(i64),
10027 Datetime64(i64),
10028 Period(i64, PeriodFreq),
10029 Interval(u64, u64, IntervalClosed),
10030 Object(String),
10033 }
10034
10035 let mut seen = FxHashSet::default();
10036 for val in values {
10037 if val.is_missing() {
10038 continue;
10039 }
10040 let key = match val {
10041 Scalar::Bool(v) => ScalarKey::Bool(*v),
10042 Scalar::Int64(v) => ScalarKey::Int64(*v),
10043 Scalar::Float64(v) => {
10044 let normalized = if *v == 0.0 { 0.0 } else { *v };
10045 ScalarKey::FloatBits(normalized.to_bits())
10046 }
10047 Scalar::Utf8(v) => ScalarKey::Utf8(v.as_str()),
10048 Scalar::Timedelta64(v) => ScalarKey::Timedelta64(*v),
10049 Scalar::Datetime64(v) => ScalarKey::Datetime64(*v),
10050 Scalar::Period(p) => ScalarKey::Period(p.ordinal, p.freq),
10051 Scalar::Interval(v) => ScalarKey::Interval(
10052 normalized_float_bits(v.left),
10053 normalized_float_bits(v.right),
10054 v.closed,
10055 ),
10056 Scalar::Object(object) => ScalarKey::Object(object.repr()),
10057 Scalar::Null(_) => continue,
10058 };
10059 seen.insert(key);
10060 }
10061 Scalar::Int64(seen.len() as i64)
10062}
10063
10064fn normalized_float_bits(value: f64) -> u64 {
10065 let normalized = if value == 0.0 { 0.0 } else { value };
10066 normalized.to_bits()
10067}
10068
10069#[derive(
10089 Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
10090)]
10091#[serde(rename_all = "snake_case")]
10092#[non_exhaustive]
10093pub enum IntervalClosed {
10094 Left,
10096 #[default]
10098 Right,
10099 Both,
10101 Neither,
10103}
10104
10105impl IntervalClosed {
10106 #[must_use]
10108 pub const fn left_closed(self) -> bool {
10109 matches!(self, Self::Left | Self::Both)
10110 }
10111
10112 #[must_use]
10114 pub const fn right_closed(self) -> bool {
10115 matches!(self, Self::Right | Self::Both)
10116 }
10117}
10118
10119impl std::fmt::Display for IntervalClosed {
10120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10121 match self {
10122 Self::Left => write!(f, "left"),
10123 Self::Right => write!(f, "right"),
10124 Self::Both => write!(f, "both"),
10125 Self::Neither => write!(f, "neither"),
10126 }
10127 }
10128}
10129
10130#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
10135#[serde(rename_all = "snake_case")]
10136pub enum IntervalSubtype {
10137 #[default]
10138 Float64,
10139 Int64,
10140}
10141
10142impl IntervalSubtype {
10143 #[must_use]
10145 pub const fn is_float(&self) -> bool {
10146 matches!(self, Self::Float64)
10147 }
10148
10149 #[must_use]
10151 pub const fn name(&self) -> &'static str {
10152 match self {
10153 Self::Float64 => "float64",
10154 Self::Int64 => "int64",
10155 }
10156 }
10157}
10158
10159#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
10166pub struct Interval {
10167 pub left: f64,
10168 pub right: f64,
10169 #[serde(default)]
10170 pub closed: IntervalClosed,
10171 #[serde(default, skip_serializing_if = "IntervalSubtype::is_float")]
10173 pub subtype: IntervalSubtype,
10174}
10175
10176impl PartialEq for Interval {
10177 fn eq(&self, other: &Self) -> bool {
10178 self.left == other.left && self.right == other.right && self.closed == other.closed
10179 }
10180}
10181
10182impl Eq for Interval {}
10186
10187impl Interval {
10188 fn endpoint_key(value: f64) -> f64 {
10190 if value == 0.0 { 0.0 } else { value }
10191 }
10192}
10193
10194impl std::hash::Hash for Interval {
10197 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
10198 Self::endpoint_key(self.left).to_bits().hash(state);
10199 Self::endpoint_key(self.right).to_bits().hash(state);
10200 self.closed.hash(state);
10201 }
10202}
10203
10204impl Ord for Interval {
10207 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
10208 Self::endpoint_key(self.left)
10209 .total_cmp(&Self::endpoint_key(other.left))
10210 .then_with(|| {
10211 Self::endpoint_key(self.right).total_cmp(&Self::endpoint_key(other.right))
10212 })
10213 .then_with(|| self.closed.cmp(&other.closed))
10214 }
10215}
10216
10217impl PartialOrd for Interval {
10218 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
10219 Some(self.cmp(other))
10220 }
10221}
10222
10223impl Interval {
10224 #[must_use]
10227 pub const fn new(left: f64, right: f64, closed: IntervalClosed) -> Self {
10228 Self {
10229 left,
10230 right,
10231 closed,
10232 subtype: IntervalSubtype::Float64,
10233 }
10234 }
10235
10236 #[must_use]
10239 pub fn with_int_endpoints(self) -> Self {
10240 if self.left.fract() == 0.0 && self.right.fract() == 0.0 {
10241 Self {
10242 subtype: IntervalSubtype::Int64,
10243 ..self
10244 }
10245 } else {
10246 self
10247 }
10248 }
10249
10250 #[must_use]
10252 pub fn length(&self) -> f64 {
10253 self.right - self.left
10254 }
10255
10256 #[must_use]
10258 pub fn mid(&self) -> f64 {
10259 (self.left + self.right) / 2.0
10260 }
10261
10262 #[must_use]
10265 pub fn is_empty(&self) -> bool {
10266 self.left == self.right && !matches!(self.closed, IntervalClosed::Both)
10267 }
10268
10269 #[must_use]
10271 pub const fn closed_left(&self) -> bool {
10272 self.closed.left_closed()
10273 }
10274
10275 #[must_use]
10277 pub const fn closed_right(&self) -> bool {
10278 self.closed.right_closed()
10279 }
10280
10281 #[must_use]
10283 pub const fn open_left(&self) -> bool {
10284 !self.closed.left_closed()
10285 }
10286
10287 #[must_use]
10289 pub const fn open_right(&self) -> bool {
10290 !self.closed.right_closed()
10291 }
10292
10293 #[must_use]
10298 pub fn contains(&self, value: f64) -> bool {
10299 if value.is_nan() {
10300 return false;
10301 }
10302 let left_ok = if self.closed.left_closed() {
10303 value >= self.left
10304 } else {
10305 value > self.left
10306 };
10307 let right_ok = if self.closed.right_closed() {
10308 value <= self.right
10309 } else {
10310 value < self.right
10311 };
10312 left_ok && right_ok
10313 }
10314
10315 #[must_use]
10322 pub fn overlaps(&self, other: &Self) -> bool {
10323 if self.left > other.right || other.left > self.right {
10324 return false;
10325 }
10326 if self.right == other.left {
10328 return self.closed.right_closed() && other.closed.left_closed();
10329 }
10330 if other.right == self.left {
10331 return other.closed.right_closed() && self.closed.left_closed();
10332 }
10333 true
10334 }
10335
10336 pub fn parse(s: &str) -> Result<Self, TypeError> {
10342 let s = s.trim();
10343 let (left_closed, after_left) = if let Some(rest) = s.strip_prefix('[') {
10344 (true, rest)
10345 } else if let Some(rest) = s.strip_prefix('(') {
10346 (false, rest)
10347 } else {
10348 return Err(TypeError::ValueNotParseable {
10349 value: s.to_string(),
10350 target: "Interval".to_string(),
10351 });
10352 };
10353
10354 let (right_closed, inner) = if let Some(rest) = after_left.strip_suffix(']') {
10355 (true, rest)
10356 } else if let Some(rest) = after_left.strip_suffix(')') {
10357 (false, rest)
10358 } else {
10359 return Err(TypeError::ValueNotParseable {
10360 value: s.to_string(),
10361 target: "Interval".to_string(),
10362 });
10363 };
10364
10365 let closed = match (left_closed, right_closed) {
10366 (true, true) => IntervalClosed::Both,
10367 (true, false) => IntervalClosed::Left,
10368 (false, true) => IntervalClosed::Right,
10369 (false, false) => IntervalClosed::Neither,
10370 };
10371
10372 let Some((left_text, right_text)) = inner.split_once(',') else {
10373 return Err(TypeError::ValueNotParseable {
10374 value: s.to_string(),
10375 target: "Interval".to_string(),
10376 });
10377 };
10378 if right_text.contains(',') {
10379 return Err(TypeError::ValueNotParseable {
10380 value: s.to_string(),
10381 target: "Interval".to_string(),
10382 });
10383 }
10384
10385 let left: f64 = left_text
10386 .trim()
10387 .parse()
10388 .map_err(|_| TypeError::ValueNotParseable {
10389 value: s.to_string(),
10390 target: "Interval".to_string(),
10391 })?;
10392
10393 let right: f64 = right_text
10394 .trim()
10395 .parse()
10396 .map_err(|_| TypeError::ValueNotParseable {
10397 value: s.to_string(),
10398 target: "Interval".to_string(),
10399 })?;
10400
10401 Ok(Self::new(left, right, closed))
10402 }
10403}
10404
10405impl std::fmt::Display for Interval {
10406 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10413 let left_bracket = if self.closed.left_closed() { '[' } else { '(' };
10414 let right_bracket = if self.closed.right_closed() { ']' } else { ')' };
10415 #[allow(clippy::cast_possible_truncation)] let endpoint = |value: f64| match self.subtype {
10418 IntervalSubtype::Int64 if value.fract() == 0.0 => format!("{}", value as i64),
10419 _ => float_to_string_for_astype(value),
10420 };
10421 write!(
10422 f,
10423 "{left_bracket}{}, {}{right_bracket}",
10424 endpoint(self.left),
10425 endpoint(self.right)
10426 )
10427 }
10428}
10429
10430#[must_use]
10448pub fn interval_range_by_periods(
10449 start: f64,
10450 end: f64,
10451 periods: usize,
10452 closed: IntervalClosed,
10453) -> Vec<Interval> {
10454 if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
10455 return Vec::new();
10456 }
10457 let step = (end - start) / (periods as f64);
10458 let mut out = Vec::with_capacity(periods);
10459 for i in 0..periods {
10460 let left = start + step * (i as f64);
10461 let right = if i + 1 == periods {
10463 end
10464 } else {
10465 start + step * ((i + 1) as f64)
10466 };
10467 out.push(Interval::new(left, right, closed));
10468 }
10469 out
10470}
10471
10472pub fn interval_range_by_step(
10483 start: f64,
10484 end: f64,
10485 step: f64,
10486 closed: IntervalClosed,
10487) -> Result<Vec<Interval>, TypeError> {
10488 if !step.is_finite() || !step.is_sign_positive() || step == 0.0 {
10489 return Err(TypeError::InvalidIntervalStep { step });
10490 }
10491 if !start.is_finite() || !end.is_finite() || start >= end {
10492 return Ok(Vec::new());
10493 }
10494 let span = end - start;
10495 let periods_f = span / step;
10496 let periods = periods_f.round() as i64;
10497 if periods <= 0 {
10498 return Ok(Vec::new());
10499 }
10500 let reconstructed = step * (periods as f64);
10501 if (span - reconstructed).abs() > span.abs() * 1e-9 + 1e-12 {
10503 return Err(TypeError::IntervalStepDoesNotDivide { step, span });
10504 }
10505 let periods = periods as usize;
10506 let mut out = Vec::with_capacity(periods);
10507 for i in 0..periods {
10508 let left = start + step * (i as f64);
10509 let right = if i + 1 == periods {
10510 end
10511 } else {
10512 start + step * ((i + 1) as f64)
10513 };
10514 out.push(Interval::new(left, right, closed));
10515 }
10516 Ok(out)
10517}
10518
10519pub fn interval_range(
10531 start: Option<f64>,
10532 end: Option<f64>,
10533 periods: Option<usize>,
10534 freq: Option<f64>,
10535 closed: Option<IntervalClosed>,
10536) -> Result<Vec<Interval>, TypeError> {
10537 let count = usize::from(start.is_some())
10538 + usize::from(end.is_some())
10539 + usize::from(periods.is_some())
10540 + usize::from(freq.is_some());
10541 if count != 3 {
10542 return Err(TypeError::IntervalRangeParameterCount);
10543 }
10544 let closed = closed.unwrap_or(IntervalClosed::Right);
10545
10546 match (start, end, periods, freq) {
10547 (Some(start), Some(end), Some(periods), None) => {
10548 Ok(interval_range_by_periods(start, end, periods, closed))
10549 }
10550 (Some(start), Some(end), None, Some(freq)) => {
10551 interval_range_by_step(start, end, freq, closed)
10552 }
10553 (Some(start), None, Some(periods), Some(freq)) => {
10554 if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10555 return Err(TypeError::InvalidIntervalStep { step: freq });
10556 }
10557 if !start.is_finite() || periods == 0 {
10558 return Ok(Vec::new());
10559 }
10560 let mut out = Vec::with_capacity(periods);
10561 for i in 0..periods {
10562 let left = start + freq * (i as f64);
10563 let right = start + freq * ((i + 1) as f64);
10564 out.push(Interval::new(left, right, closed));
10565 }
10566 Ok(out)
10567 }
10568 (None, Some(end), Some(periods), Some(freq)) => {
10569 if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10570 return Err(TypeError::InvalidIntervalStep { step: freq });
10571 }
10572 if !end.is_finite() || periods == 0 {
10573 return Ok(Vec::new());
10574 }
10575 let start = end - freq * (periods as f64);
10576 let mut out = Vec::with_capacity(periods);
10577 for i in 0..periods {
10578 let left = start + freq * (i as f64);
10579 let right = if i + 1 == periods {
10580 end
10581 } else {
10582 start + freq * ((i + 1) as f64)
10583 };
10584 out.push(Interval::new(left, right, closed));
10585 }
10586 Ok(out)
10587 }
10588 _ => Err(TypeError::IntervalRangeParameterCount),
10589 }
10590}
10591
10592#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10611#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
10612#[non_exhaustive]
10613pub enum PeriodFreq {
10614 Annual(u8),
10618 Quarterly(u8),
10622 Monthly,
10624 Weekly(u8),
10627 Daily,
10629 Business,
10631 Hourly,
10633 Minutely,
10635 Secondly,
10637 Milliseconds,
10639 Microseconds,
10641 Nanoseconds,
10643 Multiple(PeriodMultiple),
10646}
10647
10648#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10651#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
10652enum PeriodUnit {
10653 Annual(u8),
10654 Quarterly(u8),
10655 Monthly,
10656 Weekly(u8),
10657 Daily,
10658 Business,
10659 Hourly,
10660 Minutely,
10661 Secondly,
10662 Milliseconds,
10663 Microseconds,
10664 Nanoseconds,
10665}
10666
10667#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10669#[serde(try_from = "PeriodMultipleRepr")]
10670pub struct PeriodMultiple {
10671 unit: PeriodUnit,
10672 count: i64,
10673}
10674
10675#[derive(Deserialize)]
10676struct PeriodMultipleRepr {
10677 unit: PeriodUnit,
10678 count: i64,
10679}
10680
10681impl TryFrom<PeriodMultipleRepr> for PeriodMultiple {
10682 type Error = &'static str;
10683
10684 fn try_from(value: PeriodMultipleRepr) -> Result<Self, Self::Error> {
10685 if value.count <= 1 {
10686 return Err("a multiplied period frequency must span at least two base periods");
10687 }
10688 Ok(Self {
10689 unit: value.unit,
10690 count: value.count,
10691 })
10692 }
10693}
10694
10695const PERIOD_MONTHS: [&str; 12] = [
10697 "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
10698];
10699const PERIOD_WEEKDAYS: [&str; 7] = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];
10701
10702impl PeriodFreq {
10703 pub const ANNUAL: Self = Self::Annual(12);
10705 pub const QUARTERLY: Self = Self::Quarterly(12);
10707 pub const WEEKLY: Self = Self::Weekly(6);
10709
10710 #[must_use]
10713 pub const fn base(self) -> Self {
10714 match self {
10715 Self::Multiple(multiple) => match multiple.unit {
10716 PeriodUnit::Annual(month) => Self::Annual(month),
10717 PeriodUnit::Quarterly(month) => Self::Quarterly(month),
10718 PeriodUnit::Monthly => Self::Monthly,
10719 PeriodUnit::Weekly(day) => Self::Weekly(day),
10720 PeriodUnit::Daily => Self::Daily,
10721 PeriodUnit::Business => Self::Business,
10722 PeriodUnit::Hourly => Self::Hourly,
10723 PeriodUnit::Minutely => Self::Minutely,
10724 PeriodUnit::Secondly => Self::Secondly,
10725 PeriodUnit::Milliseconds => Self::Milliseconds,
10726 PeriodUnit::Microseconds => Self::Microseconds,
10727 PeriodUnit::Nanoseconds => Self::Nanoseconds,
10728 },
10729 base => base,
10730 }
10731 }
10732
10733 #[must_use]
10735 pub const fn multiplier(self) -> i64 {
10736 match self {
10737 Self::Multiple(multiple) => multiple.count,
10738 _ => 1,
10739 }
10740 }
10741
10742 #[must_use]
10745 pub const fn with_multiplier(self, count: i64) -> Option<Self> {
10746 if count < 1 {
10747 return None;
10748 }
10749 let base = self.base();
10750 if count == 1 {
10751 return Some(base);
10752 }
10753 let unit = match base {
10754 Self::Annual(month) => PeriodUnit::Annual(month),
10755 Self::Quarterly(month) => PeriodUnit::Quarterly(month),
10756 Self::Monthly => PeriodUnit::Monthly,
10757 Self::Weekly(day) => PeriodUnit::Weekly(day),
10758 Self::Daily => PeriodUnit::Daily,
10759 Self::Business => PeriodUnit::Business,
10760 Self::Hourly => PeriodUnit::Hourly,
10761 Self::Minutely => PeriodUnit::Minutely,
10762 Self::Secondly => PeriodUnit::Secondly,
10763 Self::Milliseconds => PeriodUnit::Milliseconds,
10764 Self::Microseconds => PeriodUnit::Microseconds,
10765 Self::Nanoseconds => PeriodUnit::Nanoseconds,
10766 Self::Multiple(_) => return None,
10767 };
10768 Some(Self::Multiple(PeriodMultiple { unit, count }))
10769 }
10770
10771 #[must_use]
10777 pub const fn fiscal_month_shift(self) -> i64 {
10778 match self.base() {
10779 Self::Annual(month) | Self::Quarterly(month) => (12 - (month as i64 % 12)) % 12,
10780 _ => 0,
10781 }
10782 }
10783
10784 #[must_use]
10789 pub const fn week_start_shift(self) -> i64 {
10790 match self.base() {
10791 Self::Weekly(day) => (day as i64 % 7 + 1) % 7,
10792 _ => 0,
10793 }
10794 }
10795
10796 fn parse_anchored(alias: &str) -> Option<Self> {
10799 let (prefix, anchor) = alias.split_once('-')?;
10800 let month = PERIOD_MONTHS.iter().position(|name| *name == anchor);
10801 let day = PERIOD_WEEKDAYS.iter().position(|name| *name == anchor);
10802 match (prefix, month, day) {
10803 ("A" | "Y", Some(month), _) => Some(Self::Annual(month as u8 + 1)),
10804 ("Q", Some(month), _) => Some(Self::Quarterly(month as u8 + 1)),
10805 ("W", _, Some(day)) => Some(Self::Weekly(day as u8)),
10806 _ => None,
10807 }
10808 }
10809
10810 pub fn parse(alias: &str) -> Option<Self> {
10818 let alias = alias.trim();
10819 let digits_end = alias
10820 .char_indices()
10821 .find(|&(position, ch)| {
10822 !(ch.is_ascii_digit() || (position == 0 && matches!(ch, '+' | '-')))
10823 })
10824 .map_or(alias.len(), |(position, _)| position);
10825 if digits_end > 0 {
10826 let count = alias[..digits_end].parse::<i64>().ok()?;
10827 return Self::parse_base(alias[digits_end..].trim())?.with_multiplier(count);
10828 }
10829 Self::parse_base(alias)
10830 }
10831
10832 fn parse_base(alias: &str) -> Option<Self> {
10833 if alias.eq_ignore_ascii_case("ms") && alias != "MS" {
10843 return Some(Self::Milliseconds);
10844 }
10845 match alias.to_ascii_uppercase().as_str() {
10846 "A" | "Y" | "ANNUAL" | "YEARLY" => Some(Self::ANNUAL),
10847 "Q" | "QUARTERLY" => Some(Self::QUARTERLY),
10848 "M" | "MONTHLY" => Some(Self::Monthly),
10849 "W" | "WEEKLY" => Some(Self::WEEKLY),
10850 "D" | "DAILY" => Some(Self::Daily),
10851 "B" | "BUSINESS" => Some(Self::Business),
10852 "H" | "HOURLY" => Some(Self::Hourly),
10853 "T" | "MIN" | "MINUTELY" => Some(Self::Minutely),
10854 "S" | "SECONDLY" => Some(Self::Secondly),
10855 "US" | "MICROSECOND" | "MICROSECONDS" => Some(Self::Microseconds),
10856 "NS" | "NANOSECOND" | "NANOSECONDS" => Some(Self::Nanoseconds),
10857 "MILLISECOND" | "MILLISECONDS" => Some(Self::Milliseconds),
10860 anchored => Self::parse_anchored(anchored),
10861 }
10862 }
10863
10864 #[must_use]
10866 pub fn alias(self) -> String {
10867 self.to_string()
10868 }
10869
10870 const fn base_alias(self) -> &'static str {
10871 const ANNUAL: [&str; 12] = [
10872 "Y-JAN", "Y-FEB", "Y-MAR", "Y-APR", "Y-MAY", "Y-JUN", "Y-JUL", "Y-AUG", "Y-SEP",
10873 "Y-OCT", "Y-NOV", "Y-DEC",
10874 ];
10875 const QUARTERLY: [&str; 12] = [
10876 "Q-JAN", "Q-FEB", "Q-MAR", "Q-APR", "Q-MAY", "Q-JUN", "Q-JUL", "Q-AUG", "Q-SEP",
10877 "Q-OCT", "Q-NOV", "Q-DEC",
10878 ];
10879 const WEEKLY: [&str; 7] = [
10880 "W-MON", "W-TUE", "W-WED", "W-THU", "W-FRI", "W-SAT", "W-SUN",
10881 ];
10882 match self {
10883 Self::Annual(month) => ANNUAL[(month as usize + 11) % 12],
10884 Self::Quarterly(month) => QUARTERLY[(month as usize + 11) % 12],
10885 Self::Monthly => "M",
10886 Self::Weekly(day) => WEEKLY[day as usize % 7],
10887 Self::Daily => "D",
10888 Self::Business => "B",
10889 Self::Hourly => "h",
10890 Self::Minutely => "min",
10891 Self::Secondly => "s",
10892 Self::Milliseconds => "ms",
10893 Self::Microseconds => "us",
10894 Self::Nanoseconds => "ns",
10895 Self::Multiple(_) => self.base().base_alias(),
10896 }
10897 }
10898
10899 #[must_use]
10918 pub const fn resolution(self) -> Option<&'static str> {
10919 match self {
10920 Self::Annual(_) => Some("year"),
10921 Self::Quarterly(_) => Some("quarter"),
10922 Self::Monthly => Some("month"),
10923 Self::Daily => Some("day"),
10924 Self::Hourly => Some("hour"),
10925 Self::Minutely => Some("minute"),
10926 Self::Secondly => Some("second"),
10927 Self::Milliseconds => Some("millisecond"),
10928 Self::Microseconds => Some("microsecond"),
10929 Self::Nanoseconds => Some("nanosecond"),
10930 Self::Weekly(_) | Self::Business => None,
10933 Self::Multiple(_) => None,
10934 }
10935 }
10936}
10937
10938impl std::fmt::Display for PeriodFreq {
10939 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10940 if self.multiplier() != 1 {
10941 write!(f, "{}", self.multiplier())?;
10942 }
10943 f.write_str(self.base_alias())
10944 }
10945}
10946
10947#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10955pub struct Period {
10956 pub ordinal: i64,
10957 pub freq: PeriodFreq,
10958}
10959
10960impl Period {
10961 #[must_use]
10962 pub const fn new(ordinal: i64, freq: PeriodFreq) -> Self {
10963 Self { ordinal, freq }
10964 }
10965
10966 #[must_use]
10969 pub const fn is_nat(&self) -> bool {
10970 self.ordinal == i64::MIN
10971 }
10972
10973 #[must_use]
10976 pub const fn ordinal(&self) -> i64 {
10977 self.ordinal
10978 }
10979
10980 #[must_use]
10982 pub const fn freq(&self) -> PeriodFreq {
10983 self.freq
10984 }
10985
10986 #[must_use]
10988 pub fn freqstr(&self) -> String {
10989 self.freq.alias()
10990 }
10991
10992 #[must_use]
10995 pub fn cmp_same_freq(&self, other: &Self) -> Option<std::cmp::Ordering> {
10996 if self.freq != other.freq {
10997 return None;
10998 }
10999 Some(self.ordinal.cmp(&other.ordinal))
11000 }
11001
11002 #[must_use]
11005 pub fn shift(&self, n: i64) -> Self {
11006 if self.is_nat() {
11007 return *self;
11008 }
11009 let ordinal = i128::from(self.ordinal) + i128::from(n) * i128::from(self.freq.multiplier());
11010 Self {
11011 ordinal: ordinal.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64,
11012 freq: self.freq,
11013 }
11014 }
11015
11016 #[must_use]
11019 pub fn diff(&self, other: &Self) -> Option<i64> {
11020 if self.freq != other.freq {
11021 return None;
11022 }
11023 Some(self.ordinal.saturating_sub(other.ordinal))
11024 }
11025
11026 const fn fixed_span_nanos(freq: PeriodFreq) -> Option<i64> {
11027 match freq.base() {
11028 PeriodFreq::Daily => Some(Timedelta::NANOS_PER_DAY),
11029 PeriodFreq::Hourly => Some(Timedelta::NANOS_PER_HOUR),
11030 PeriodFreq::Minutely => Some(Timedelta::NANOS_PER_MIN),
11031 PeriodFreq::Secondly => Some(Timedelta::NANOS_PER_SEC),
11032 PeriodFreq::Milliseconds => Some(Timedelta::NANOS_PER_MILLI),
11033 PeriodFreq::Microseconds => Some(Timedelta::NANOS_PER_MICRO),
11034 PeriodFreq::Nanoseconds => Some(1),
11035 _ => None,
11036 }
11037 }
11038
11039 #[must_use]
11042 pub fn from_timestamp_nanos(nanos: i64, freq: PeriodFreq) -> Option<Self> {
11043 Self::from_timestamp_nanos_with_business_roll(nanos, freq, true)
11044 }
11045
11046 fn from_timestamp_nanos_with_business_roll(
11047 nanos: i64,
11048 freq: PeriodFreq,
11049 roll_business_forward: bool,
11050 ) -> Option<Self> {
11051 if nanos == Timestamp::NAT {
11052 return None;
11053 }
11054 let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
11055 let (year, month, _day) = civil_from_days(days);
11056 let ordinal = match freq.base() {
11057 PeriodFreq::Annual(_) => {
11058 let months = year
11059 .checked_sub(1970)?
11060 .checked_mul(12)?
11061 .checked_add(i64::from(month) - 1)?
11062 .checked_add(freq.fiscal_month_shift())?;
11063 months.div_euclid(12)
11064 }
11065 PeriodFreq::Quarterly(_) => {
11066 let months = year
11067 .checked_sub(1970)?
11068 .checked_mul(12)?
11069 .checked_add(i64::from(month) - 1)?
11070 .checked_add(freq.fiscal_month_shift())?;
11071 months.div_euclid(3)
11072 }
11073 PeriodFreq::Monthly => year
11074 .checked_sub(1970)?
11075 .checked_mul(12)?
11076 .checked_add(i64::from(month) - 1)?,
11077 PeriodFreq::Weekly(_) => {
11078 const WEEK_ANCHOR_DAY: i64 = -10;
11079 days.checked_sub(WEEK_ANCHOR_DAY + freq.week_start_shift())?
11080 .div_euclid(7)
11081 }
11082 PeriodFreq::Daily => days,
11083 PeriodFreq::Business => {
11084 let dow = (days + 3).rem_euclid(7);
11085 let adjusted_days = match (dow, roll_business_forward) {
11086 (5, true) => days.checked_add(2)?,
11087 (6, true) => days.checked_add(1)?,
11088 (5, false) => days.checked_sub(1)?,
11089 (6, false) => days.checked_sub(2)?,
11090 _ => days,
11091 };
11092 let rem_ordinal = match adjusted_days.rem_euclid(7) {
11093 0 => 0,
11094 1 => 1,
11095 4 => 2,
11096 5 => 3,
11097 6 => 4,
11098 _ => return None,
11099 };
11100 adjusted_days
11101 .div_euclid(7)
11102 .checked_mul(5)?
11103 .checked_add(rem_ordinal)?
11104 }
11105 PeriodFreq::Hourly => nanos.div_euclid(Timedelta::NANOS_PER_HOUR),
11106 PeriodFreq::Minutely => nanos.div_euclid(Timedelta::NANOS_PER_MIN),
11107 PeriodFreq::Secondly => nanos.div_euclid(Timedelta::NANOS_PER_SEC),
11108 PeriodFreq::Milliseconds => nanos.div_euclid(Timedelta::NANOS_PER_MILLI),
11109 PeriodFreq::Microseconds => nanos.div_euclid(Timedelta::NANOS_PER_MICRO),
11110 PeriodFreq::Nanoseconds => nanos,
11111 PeriodFreq::Multiple(_) => return None,
11112 };
11113 (ordinal != i64::MIN).then_some(Self::new(ordinal, freq))
11114 }
11115
11116 pub fn now(freq: &str) -> Result<Self, TypeError> {
11118 Timestamp::now().to_period(freq)
11119 }
11120
11121 #[must_use]
11124 pub fn start_nanos(&self) -> Option<i64> {
11125 if self.is_nat() {
11126 return None;
11127 }
11128 let nanos = match self.freq.base() {
11129 PeriodFreq::Annual(_) | PeriodFreq::Quarterly(_) => {
11130 let months = if matches!(self.freq.base(), PeriodFreq::Annual(_)) {
11131 12_i64
11132 } else {
11133 3_i64
11134 };
11135 let month_ordinal = self
11136 .ordinal
11137 .checked_mul(months)?
11138 .checked_sub(self.freq.fiscal_month_shift())?;
11139 let year = 1970_i64.checked_add(month_ordinal.div_euclid(12))?;
11140 let month = u32::try_from(month_ordinal.rem_euclid(12) + 1).ok()?;
11141 days_from_civil(year, month, 1).checked_mul(Timedelta::NANOS_PER_DAY)?
11142 }
11143 PeriodFreq::Monthly => {
11144 let year = 1970_i64.checked_add(self.ordinal.div_euclid(12))?;
11145 let month = u32::try_from(self.ordinal.rem_euclid(12) + 1).ok()?;
11146 days_from_civil(year, month, 1).checked_mul(Timedelta::NANOS_PER_DAY)?
11147 }
11148 PeriodFreq::Weekly(_) => {
11149 const WEEK_ANCHOR_DAY: i64 = -10;
11150 let days = self
11151 .ordinal
11152 .checked_mul(7)?
11153 .checked_add(WEEK_ANCHOR_DAY + self.freq.week_start_shift())?;
11154 days.checked_mul(Timedelta::NANOS_PER_DAY)?
11155 }
11156 PeriodFreq::Daily => self.ordinal.checked_mul(Timedelta::NANOS_PER_DAY)?,
11157 PeriodFreq::Business => {
11158 const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
11159 let offset = WEEKDAY_OFFSET[self.ordinal.rem_euclid(5) as usize];
11160 let days = self
11161 .ordinal
11162 .div_euclid(5)
11163 .checked_mul(7)?
11164 .checked_add(offset)?;
11165 days.checked_mul(Timedelta::NANOS_PER_DAY)?
11166 }
11167 PeriodFreq::Hourly => self.ordinal.checked_mul(Timedelta::NANOS_PER_HOUR)?,
11168 PeriodFreq::Minutely => self.ordinal.checked_mul(Timedelta::NANOS_PER_MIN)?,
11169 PeriodFreq::Secondly => self.ordinal.checked_mul(Timedelta::NANOS_PER_SEC)?,
11170 PeriodFreq::Milliseconds => self.ordinal.checked_mul(Timedelta::NANOS_PER_MILLI)?,
11171 PeriodFreq::Microseconds => self.ordinal.checked_mul(Timedelta::NANOS_PER_MICRO)?,
11172 PeriodFreq::Nanoseconds => self.ordinal,
11173 PeriodFreq::Multiple(_) => return None,
11174 };
11175 (nanos != Timestamp::NAT).then_some(nanos)
11176 }
11177
11178 #[must_use]
11181 pub fn end_nanos(&self) -> Option<i64> {
11182 if self.is_nat() {
11183 return None;
11184 }
11185 if self.freq.base() == PeriodFreq::Business {
11186 let last = self.ordinal.checked_add(self.freq.multiplier() - 1)?;
11189 let start = Self::new(last, PeriodFreq::Business).start_nanos()?;
11190 let end = start.checked_add(Timedelta::NANOS_PER_DAY - 1)?;
11191 return (end != Timestamp::NAT).then_some(end);
11192 }
11193 let next = Self::new(self.ordinal.checked_add(self.freq.multiplier())?, self.freq);
11194 let end = next.start_nanos()?.checked_sub(1)?;
11195 (end != Timestamp::NAT).then_some(end)
11196 }
11197
11198 #[must_use]
11201 pub fn start_time(&self) -> Timestamp {
11202 self.start_nanos()
11203 .map_or_else(Timestamp::nat, Timestamp::from_nanos)
11204 }
11205
11206 #[must_use]
11209 pub fn end_time(&self) -> Timestamp {
11210 self.end_nanos()
11211 .map_or_else(Timestamp::nat, Timestamp::from_nanos)
11212 }
11213
11214 pub fn to_timestamp(&self, how: &str) -> Result<Timestamp, TypeError> {
11217 match how.trim().to_ascii_lowercase().as_str() {
11218 "" | "s" | "start" | "begin" | "b" => Ok(self.start_time()),
11219 "e" | "end" | "finish" => Ok(self.end_time()),
11220 _ => Err(TypeError::ValueNotParseable {
11221 value: how.to_owned(),
11222 target: "Period::to_timestamp how ('start' or 'end')".to_owned(),
11223 }),
11224 }
11225 }
11226
11227 pub fn asfreq(&self, freq: &str) -> Result<Self, TypeError> {
11230 self.asfreq_with_how(freq, "end")
11231 }
11232
11233 pub fn asfreq_with_how(&self, freq: &str, how: &str) -> Result<Self, TypeError> {
11236 let target_freq = PeriodFreq::parse(freq).ok_or_else(|| TypeError::ValueNotParseable {
11237 value: freq.to_owned(),
11238 target: "PeriodFreq".to_owned(),
11239 })?;
11240 let is_start = match how.trim().to_ascii_lowercase().as_str() {
11241 "" | "e" | "end" | "finish" => false,
11242 "s" | "start" | "begin" | "b" => true,
11243 _ => {
11244 return Err(TypeError::ValueNotParseable {
11245 value: how.to_owned(),
11246 target: "Period::asfreq how ('start' or 'end')".to_owned(),
11247 });
11248 }
11249 };
11250 if self.is_nat() {
11251 return Ok(Self::new(i64::MIN, target_freq));
11252 }
11253 let boundary_nanos = if is_start {
11254 self.start_nanos()
11255 } else {
11256 self.end_nanos()
11257 }
11258 .ok_or_else(|| TypeError::ValueNotParseable {
11259 value: self.to_string(),
11260 target: "Period boundary Timestamp".to_owned(),
11261 })?;
11262 let flips = target_freq.base() == PeriodFreq::Business
11266 && Self::fixed_span_nanos(self.freq).is_some();
11267 let roll_business_forward = if flips { !is_start } else { is_start };
11268 Self::from_timestamp_nanos_with_business_roll(
11269 boundary_nanos,
11270 target_freq,
11271 roll_business_forward,
11272 )
11273 .ok_or_else(|| TypeError::ValueNotParseable {
11274 value: self.to_string(),
11275 target: format!("Period[{target_freq}]"),
11276 })
11277 }
11278
11279 fn field_timestamp(&self) -> Timestamp {
11284 if self.is_nat() {
11285 return Timestamp::nat();
11286 }
11287 let base = Self::new(self.ordinal, self.freq.base());
11291 let nanos = match base.freq {
11292 PeriodFreq::Daily
11293 | PeriodFreq::Business
11294 | PeriodFreq::Hourly
11295 | PeriodFreq::Minutely
11296 | PeriodFreq::Secondly
11297 | PeriodFreq::Milliseconds
11298 | PeriodFreq::Microseconds
11299 | PeriodFreq::Nanoseconds => base.start_nanos(),
11300 PeriodFreq::Weekly(_)
11301 | PeriodFreq::Monthly
11302 | PeriodFreq::Quarterly(_)
11303 | PeriodFreq::Annual(_) => base
11304 .end_nanos()
11305 .map(|end| end - end.rem_euclid(Timedelta::NANOS_PER_DAY)),
11306 PeriodFreq::Multiple(_) => None,
11307 };
11308 nanos.map_or_else(Timestamp::nat, Timestamp::from_nanos)
11309 }
11310
11311 #[must_use]
11314 pub fn strftime(&self, fmt: &str) -> String {
11315 self.field_timestamp().strftime(fmt)
11316 }
11317
11318 #[must_use]
11320 pub fn year(&self) -> Option<i64> {
11321 self.field_timestamp().year()
11322 }
11323
11324 #[must_use]
11326 pub fn month(&self) -> Option<i64> {
11327 self.field_timestamp().month()
11328 }
11329
11330 #[must_use]
11332 pub fn day(&self) -> Option<i64> {
11333 self.field_timestamp().day()
11334 }
11335
11336 #[must_use]
11338 pub fn hour(&self) -> Option<i64> {
11339 self.field_timestamp().hour()
11340 }
11341
11342 #[must_use]
11344 pub fn minute(&self) -> Option<i64> {
11345 self.field_timestamp().minute()
11346 }
11347
11348 #[must_use]
11350 pub fn second(&self) -> Option<i64> {
11351 self.field_timestamp().second()
11352 }
11353
11354 #[must_use]
11357 pub fn quarter(&self) -> Option<i64> {
11358 if self.is_nat() {
11359 return None;
11360 }
11361 match self.freq.base() {
11362 PeriodFreq::Quarterly(_) => Some(self.ordinal.rem_euclid(4) + 1),
11363 _ => self.field_timestamp().quarter(),
11364 }
11365 }
11366
11367 #[must_use]
11369 pub fn qyear(&self) -> Option<i64> {
11370 if self.is_nat() {
11371 return None;
11372 }
11373 match self.freq.base() {
11374 PeriodFreq::Quarterly(_) => 1970_i64.checked_add(self.ordinal.div_euclid(4)),
11375 _ => self.year(),
11376 }
11377 }
11378
11379 #[must_use]
11381 pub fn dayofweek(&self) -> Option<i64> {
11382 self.field_timestamp().dayofweek()
11383 }
11384
11385 #[must_use]
11387 pub fn day_of_week(&self) -> Option<i64> {
11388 self.dayofweek()
11389 }
11390
11391 #[must_use]
11393 pub fn weekday(&self) -> Option<i64> {
11394 self.dayofweek()
11395 }
11396
11397 #[must_use]
11399 pub fn dayofyear(&self) -> Option<i64> {
11400 self.field_timestamp().dayofyear()
11401 }
11402
11403 #[must_use]
11405 pub fn day_of_year(&self) -> Option<i64> {
11406 self.dayofyear()
11407 }
11408
11409 #[must_use]
11411 pub fn days_in_month(&self) -> Option<i64> {
11412 self.field_timestamp().days_in_month()
11413 }
11414
11415 #[must_use]
11417 pub fn daysinmonth(&self) -> Option<i64> {
11418 self.days_in_month()
11419 }
11420
11421 #[must_use]
11423 pub fn week(&self) -> Option<i64> {
11424 self.field_timestamp().week()
11425 }
11426
11427 #[must_use]
11429 pub fn weekofyear(&self) -> Option<i64> {
11430 self.week()
11431 }
11432
11433 #[must_use]
11435 pub fn is_leap_year(&self) -> Option<bool> {
11436 self.field_timestamp().is_leap_year()
11437 }
11438
11439 pub fn parse(s: &str) -> Result<Self, TypeError> {
11446 let trimmed = s.trim();
11447 if trimmed.eq_ignore_ascii_case("nat") {
11448 return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
11449 }
11450
11451 if let Some((year, quarter)) = parse_quarter_period(trimmed) {
11452 let ordinal = year
11453 .checked_sub(1970)
11454 .and_then(|offset| offset.checked_mul(4))
11455 .and_then(|base| base.checked_add(i64::from(quarter) - 1))
11456 .ok_or_else(|| TypeError::ValueNotParseable {
11457 value: s.to_owned(),
11458 target: "Period".to_owned(),
11459 })?;
11460 return Ok(Self::new(ordinal, PeriodFreq::QUARTERLY));
11461 }
11462
11463 if let Some((year, month, day)) = parse_ymd_period(trimmed) {
11464 let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
11465 return Ok(Self::new(ordinal, PeriodFreq::Daily));
11466 }
11467
11468 if let Some((year, month)) = parse_year_month_period(trimmed) {
11469 let ordinal = year
11470 .checked_sub(1970)
11471 .and_then(|offset| offset.checked_mul(12))
11472 .and_then(|base| base.checked_add(i64::from(month) - 1))
11473 .ok_or_else(|| TypeError::ValueNotParseable {
11474 value: s.to_owned(),
11475 target: "Period".to_owned(),
11476 })?;
11477 return Ok(Self::new(ordinal, PeriodFreq::Monthly));
11478 }
11479
11480 if let Some(year) = parse_annual_period(trimmed) {
11481 let ordinal = year
11482 .checked_sub(1970)
11483 .ok_or_else(|| TypeError::ValueNotParseable {
11484 value: s.to_owned(),
11485 target: "Period".to_owned(),
11486 })?;
11487 return Ok(Self::new(ordinal, PeriodFreq::ANNUAL));
11488 }
11489
11490 Err(TypeError::ValueNotParseable {
11491 value: s.to_owned(),
11492 target: "Period".to_owned(),
11493 })
11494 }
11495
11496 #[must_use]
11521 pub fn calendar_string(&self) -> String {
11522 let mut rendered = String::new();
11523 let _ = self.write_calendar(&mut rendered);
11525 rendered
11526 }
11527
11528 fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
11529 if self.ordinal == i64::MIN {
11530 return rendered.write_str("NaT");
11531 }
11532 let ord = self.ordinal;
11533 match self.freq.base() {
11534 PeriodFreq::Annual(_) => {
11538 let year = 1970 + ord;
11539 write!(rendered, "{year}")
11540 }
11541 PeriodFreq::Quarterly(_) => {
11542 let year = 1970 + ord.div_euclid(4);
11543 let quarter = ord.rem_euclid(4) + 1;
11544 write!(rendered, "{year}Q{quarter}")
11545 }
11546 PeriodFreq::Monthly => {
11547 let year = 1970 + ord.div_euclid(12);
11548 let month = ord.rem_euclid(12) + 1;
11549 write!(rendered, "{year:04}-{month:02}")
11550 }
11551 PeriodFreq::Daily => {
11552 let (y, m, d) = civil_from_days(ord);
11553 write!(rendered, "{y:04}-{m:02}-{d:02}")
11554 }
11555 PeriodFreq::Business => {
11566 const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
11567 let offset = WEEKDAY_OFFSET[ord.rem_euclid(5) as usize];
11570 let days = ord.div_euclid(5).saturating_mul(7).saturating_add(offset);
11571 let (y, m, d) = civil_from_days(days);
11572 write!(rendered, "{y:04}-{m:02}-{d:02}")
11573 }
11574 PeriodFreq::Weekly(_) => {
11584 const WEEK_ANCHOR_DAY: i64 = -10;
11588 let start = ord
11589 .saturating_mul(7)
11590 .saturating_add(WEEK_ANCHOR_DAY + self.freq.week_start_shift());
11591 let (sy, sm, sd) = civil_from_days(start);
11592 let (ey, em, ed) = civil_from_days(start.saturating_add(6));
11593 write!(rendered, "{sy:04}-{sm:02}-{sd:02}/{ey:04}-{em:02}-{ed:02}")
11594 }
11595 PeriodFreq::Hourly => {
11596 let (y, m, d) = civil_from_days(ord.div_euclid(24));
11597 let hour = ord.rem_euclid(24);
11598 write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
11599 }
11600 PeriodFreq::Minutely => {
11601 let day = ord.div_euclid(1440);
11602 let mins = ord.rem_euclid(1440);
11603 let (y, m, d) = civil_from_days(day);
11604 write!(
11605 rendered,
11606 "{y:04}-{m:02}-{d:02} {:02}:{:02}",
11607 mins / 60,
11608 mins % 60
11609 )
11610 }
11611 PeriodFreq::Secondly => {
11612 let day = ord.div_euclid(86_400);
11613 let secs = ord.rem_euclid(86_400);
11614 let (y, m, d) = civil_from_days(day);
11615 write!(
11616 rendered,
11617 "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
11618 secs / 3600,
11619 (secs % 3600) / 60,
11620 secs % 60
11621 )
11622 }
11623 PeriodFreq::Milliseconds | PeriodFreq::Microseconds | PeriodFreq::Nanoseconds => {
11630 let (per_sec, width) = match self.freq.base() {
11631 PeriodFreq::Milliseconds => (1_000_i64, 3_usize),
11632 PeriodFreq::Microseconds => (1_000_000_i64, 6_usize),
11633 _ => (1_000_000_000_i64, 9_usize),
11634 };
11635 let per_day = 86_400 * per_sec;
11637 let day = ord.div_euclid(per_day);
11638 let rest = ord.rem_euclid(per_day);
11639 let secs = rest / per_sec;
11640 let frac = rest % per_sec;
11641 let (y, m, d) = civil_from_days(day);
11642 write!(
11643 rendered,
11644 "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{:0width$}",
11645 secs / 3600,
11646 (secs % 3600) / 60,
11647 secs % 60,
11648 frac,
11649 width = width
11650 )
11651 }
11652 PeriodFreq::Multiple(_) => Self::new(ord, self.freq.base()).write_calendar(rendered),
11653 }
11654 }
11655}
11656
11657#[must_use]
11662pub fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
11663 let days = days_since_epoch + 719_468;
11664 let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
11665 let doe = days - era * 146_097;
11666 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
11667 let y = yoe + era * 400;
11668 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
11669 let mp = (5 * doy + 2) / 153;
11670 let d = doy - (153 * mp + 2) / 5 + 1;
11671 let m = if mp < 10 { mp + 3 } else { mp - 9 };
11672 let year = if m <= 2 { y + 1 } else { y };
11673 (year, m as u32, d as u32)
11674}
11675
11676fn parse_annual_period(value: &str) -> Option<i64> {
11677 (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
11678 .then(|| value.parse::<i64>().ok())
11679 .flatten()
11680}
11681
11682fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
11683 let (year, month) = value.split_once('-')?;
11684 if year.len() != 4 || month.len() != 2 {
11685 return None;
11686 }
11687 let year = year.parse::<i64>().ok()?;
11688 let month = month.parse::<u32>().ok()?;
11689 (1..=12).contains(&month).then_some((year, month))
11690}
11691
11692fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
11693 let mut parts = value.split('-');
11694 let year = parts.next()?;
11695 let month = parts.next()?;
11696 let day = parts.next()?;
11697 if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
11698 return None;
11699 }
11700 let year = year.parse::<i64>().ok()?;
11701 let month = month.parse::<u32>().ok()?;
11702 let day = day.parse::<u32>().ok()?;
11703 (1..=days_in_month(year, month)?)
11704 .contains(&day)
11705 .then_some((year, month, day))
11706}
11707
11708fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
11709 let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
11710 if year.len() != 4 || quarter.len() != 1 {
11711 return None;
11712 }
11713 let year = year.parse::<i64>().ok()?;
11714 let quarter = quarter.parse::<u32>().ok()?;
11715 (1..=4).contains(&quarter).then_some((year, quarter))
11716}
11717
11718impl std::fmt::Display for Period {
11719 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11722 self.write_calendar(f)
11723 }
11724}
11725
11726#[must_use]
11745pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
11746 (0..periods).map(|i| start.shift(i as i64)).collect()
11747}
11748
11749#[cfg(test)]
11750mod tests {
11751 use super::{
11752 DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
11753 cast_scalar, common_dtype, infer_dtype,
11754 };
11755
11756 struct Named(&'static str);
11759
11760 impl super::HostObject for Named {
11761 fn host_eq(&self, other: &dyn super::HostObject) -> bool {
11762 other
11763 .as_any()
11764 .downcast_ref::<Named>()
11765 .is_some_and(|other| other.0 == self.0)
11766 }
11767 fn host_repr(&self) -> String {
11768 format!("Named({:?})", self.0)
11769 }
11770 fn host_str(&self) -> String {
11771 self.0.to_owned()
11772 }
11773 fn host_hash(&self) -> Option<u64> {
11774 (!self.0.is_empty()).then_some(self.0.len() as u64)
11775 }
11776 fn host_cmp(&self, other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
11778 let other = other.as_any().downcast_ref::<Named>()?;
11779 (!self.0.starts_with('!') && !other.0.starts_with('!')).then(|| self.0.cmp(other.0))
11780 }
11781 fn as_any(&self) -> &dyn std::any::Any {
11782 self
11783 }
11784 }
11785
11786 #[test]
11787 fn host_values_block_workers_only_under_a_declared_host_lock_4qg5w_13() {
11788 use std::sync::atomic::Ordering;
11789
11790 use super::{HostValue, LIVE_HOST_VALUES, workers_blocked};
11791 assert!(workers_blocked(true, 1));
11795 assert!(!workers_blocked(true, 0));
11796 assert!(!workers_blocked(false, 3));
11797 let first = HostValue::new(Named("held"));
11802 assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11803 let clone = first.clone();
11804 drop(first);
11805 assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
11806 assert_eq!(clone.object().host_str(), "held");
11807 }
11808
11809 #[test]
11810 fn object_cells_order_like_python_then_totally_fvsao_66() {
11811 use std::cmp::Ordering;
11812
11813 use super::{HostValue, ObjectValue};
11814 let host = |name: &'static str| ObjectValue::Host(HostValue::new(Named(name)));
11815 let list = |items: Vec<Scalar>| ObjectValue::list(items);
11816 assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11819 assert!(host("b") > host("a"));
11820 assert_eq!(host("a").cmp(&host("a")), Ordering::Equal);
11821 let one_ten = list(vec![Scalar::Int64(1), Scalar::Int64(10)]);
11824 let one_two = list(vec![Scalar::Int64(1), Scalar::Int64(2)]);
11825 assert_eq!(one_two.python_cmp(&one_ten), Some(Ordering::Less));
11826 assert!(list(vec![Scalar::Int64(1)]) < one_two);
11827 let mixed = list(vec![Scalar::Float64(1.0), Scalar::Int64(3)]);
11829 assert_eq!(one_two.python_cmp(&mixed), Some(Ordering::Less));
11830 assert_eq!(one_two.python_cmp(&host("a")), None);
11833 assert!(one_two < host("a"));
11834 assert_eq!(host("!z").python_cmp(&host("!a")), None);
11835 assert!(host("!a") < host("!z"));
11836 let text = list(vec![Scalar::Utf8("a".to_owned())]);
11837 assert_eq!(one_two.python_cmp(&text), None);
11838 assert_ne!(one_two.cmp(&text), Ordering::Equal);
11839 let nan = || list(vec![Scalar::Float64(f64::NAN)]);
11842 let (first, second) = (nan(), nan());
11843 assert_ne!(first, second);
11844 assert_ne!(first.cmp(&second), Ordering::Equal);
11845 assert_eq!(first.cmp(&second), second.cmp(&first).reverse());
11846 }
11847
11848 #[test]
11849 fn bytes_cells_print_order_and_serialize_like_python_bytes_4qg5w_8() {
11850 use std::cmp::Ordering;
11851
11852 use super::ObjectValue;
11853 let bytes = |data: &[u8]| Scalar::Object(ObjectValue::bytes(data.to_vec()));
11854 assert_eq!(bytes(b"ab").python_repr(), "b'ab'");
11857 assert_eq!(bytes(b"a'b").python_repr(), "b\"a'b\"");
11858 assert_eq!(bytes(b"a'\"").python_repr(), "b'a\\'\"'");
11859 assert_eq!(bytes(b"\x00\t\\\xff").python_repr(), "b'\\x00\\t\\\\\\xff'");
11860 assert_eq!(bytes(b"ab").python_type_name(), "bytes");
11861 assert_eq!(bytes(b"ab").python_cmp(&bytes(b"b")), Some(Ordering::Less));
11863 assert_eq!(bytes(b"a").python_cmp(&bytes(b"ab")), Some(Ordering::Less));
11864 assert_eq!(bytes(b"a").python_cmp(&Scalar::Utf8("a".to_owned())), None);
11865 assert_ne!(bytes(b"a"), Scalar::Utf8("a".to_owned()));
11866 assert!(!bytes(b"").to_bool().unwrap());
11867 let json = serde_json::to_string(&bytes(b"hi")).unwrap();
11869 assert_eq!(json, r#"{"kind":"object","value":{"bytes":[104,105]}}"#);
11870 let back: Scalar = serde_json::from_str(&json).unwrap();
11871 assert_eq!(back, bytes(b"hi"));
11872 let list: Scalar =
11874 serde_json::from_str(r#"{"kind":"object","value":[{"kind":"int64","value":1}]}"#)
11875 .unwrap();
11876 assert_eq!(
11877 list,
11878 Scalar::Object(ObjectValue::list(vec![Scalar::Int64(1)]))
11879 );
11880 }
11881
11882 #[test]
11883 fn values_order_and_name_their_types_as_python_does_fvsao_71() {
11884 use std::cmp::Ordering;
11885
11886 use super::{HostValue, ObjectValue};
11887 let text = |value: &str| Scalar::Utf8(value.to_owned());
11888 let host =
11889 |name: &'static str| Scalar::Object(ObjectValue::Host(HostValue::new(Named(name))));
11890 let list = |items: Vec<Scalar>| Scalar::Object(ObjectValue::list(items));
11891 assert_eq!(
11894 Scalar::Bool(true).python_cmp(&Scalar::Float64(1.5)),
11895 Some(Ordering::Less)
11896 );
11897 assert_eq!(
11898 Scalar::Int64(2).python_cmp(&Scalar::Float64(2.0)),
11899 Some(Ordering::Equal)
11900 );
11901 assert_eq!(text("b").python_cmp(&text("a")), Some(Ordering::Greater));
11902 assert_eq!(
11903 Scalar::Datetime64(5).python_cmp(&Scalar::Datetime64(9)),
11904 Some(Ordering::Less)
11905 );
11906 let interval = |left: f64, right: f64| {
11907 Scalar::Interval(Interval::new(left, right, IntervalClosed::Right))
11908 };
11909 assert_eq!(
11910 interval(0.0, 5.0).python_cmp(&interval(0.0, 2.0)),
11911 Some(Ordering::Greater)
11912 );
11913 assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
11914 assert_eq!(text("a").python_cmp(&Scalar::Int64(1)), None);
11917 assert_eq!(
11918 Scalar::Datetime64(1).python_cmp(&Scalar::Timedelta64(1)),
11919 None
11920 );
11921 assert_eq!(host("a").python_cmp(&Scalar::Int64(1)), None);
11922 assert_eq!(host("!a").python_cmp(&host("b")), None);
11923 assert_eq!(text("a").python_type_name(), "str");
11927 assert_eq!(Scalar::Bool(true).python_type_name(), "bool");
11928 assert_eq!(Scalar::Datetime64(1).python_type_name(), "Timestamp");
11929 assert_eq!(list(vec![]).python_type_name(), "list");
11930 assert_eq!(host("a").python_type_name(), "object");
11931 let (left, right) = list(vec![Scalar::Int64(1), Scalar::Int64(2)])
11932 .python_cmp_type_names(&list(vec![Scalar::Int64(1), text("x")]));
11933 assert_eq!((left.as_str(), right.as_str()), ("int", "str"));
11934 let (left, right) = text("a").python_cmp_type_names(&list(vec![]));
11935 assert_eq!((left.as_str(), right.as_str()), ("str", "list"));
11936 }
11937
11938 #[test]
11939 fn object_cells_print_compare_and_hash_like_python_fvsao_33() {
11940 use std::hash::{Hash, Hasher};
11941
11942 use super::{HostValue, ObjectValue};
11943 let hash = |value: &ObjectValue| {
11944 let mut hasher = std::collections::hash_map::DefaultHasher::new();
11945 value.hash(&mut hasher);
11946 hasher.finish()
11947 };
11948 let list = ObjectValue::list(vec![
11949 Scalar::Int64(1),
11950 Scalar::Utf8("a".to_owned()),
11951 Scalar::Null(NullKind::Null),
11952 Scalar::Float64(2.0),
11953 Scalar::Object(ObjectValue::list(vec![Scalar::Utf8("b".to_owned())])),
11954 ]);
11955 assert_eq!(list.repr(), "[1, 'a', None, 2.0, ['b']]");
11958 assert_eq!(list.to_string(), "[1, 'a', None, 2.0, ['b']]");
11959 assert_eq!(list.pprint(), "[1, a, None, 2.0, [b]]");
11960 assert_eq!(Scalar::Object(list.clone()).dtype(), DType::Utf8);
11962 assert!(!Scalar::Object(list.clone()).is_missing());
11963 let same = ObjectValue::list(list.as_list().unwrap().to_vec());
11966 assert_eq!(list, same);
11967 assert_eq!(hash(&list), hash(&same));
11968 let other = ObjectValue::list(vec![Scalar::Int64(1)]);
11969 assert_ne!(list, other);
11970 let host = ObjectValue::Host(HostValue::new(Named("x")));
11971 assert_ne!(list, host);
11972 assert_eq!(host, ObjectValue::Host(HostValue::new(Named("x"))));
11974 assert_ne!(host, ObjectValue::Host(HostValue::new(Named("y"))));
11975 assert_eq!(host.repr(), "Named(\"x\")");
11976 assert_eq!(host.to_string(), "x");
11977 assert!(
11979 !Scalar::Object(ObjectValue::list(Vec::new()))
11980 .to_bool()
11981 .unwrap()
11982 );
11983 assert!(Scalar::Object(host.clone()).to_bool().unwrap());
11984 assert!(Scalar::Object(list.clone()).to_f64().is_err());
11986 let json = serde_json::to_string(&Scalar::Object(other.clone())).unwrap();
11989 assert_eq!(
11990 serde_json::from_str::<Scalar>(&json).unwrap(),
11991 Scalar::Object(other)
11992 );
11993 assert!(serde_json::to_string(&Scalar::Object(host)).is_err());
11994 }
11995
11996 #[test]
11997 fn a_host_cell_displays_by_its_pprint_and_stringifies_by_its_str() {
11998 use super::{HostValue, ObjectValue};
11999
12000 struct Pair;
12002 impl super::HostObject for Pair {
12003 fn host_eq(&self, _other: &dyn super::HostObject) -> bool {
12004 false
12005 }
12006 fn host_repr(&self) -> String {
12007 "('a', 1)".to_owned()
12008 }
12009 fn host_str(&self) -> String {
12010 "('a', 1)".to_owned()
12011 }
12012 fn host_pprint(&self) -> String {
12013 "(a, 1)".to_owned()
12014 }
12015 fn host_hash(&self) -> Option<u64> {
12016 None
12017 }
12018 fn host_cmp(&self, _other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
12019 None
12020 }
12021 fn as_any(&self) -> &dyn std::any::Any {
12022 self
12023 }
12024 }
12025 let pair = ObjectValue::Host(HostValue::new(Pair));
12026 assert_eq!(pair.pprint(), "(a, 1)");
12027 let list = ObjectValue::list(vec![Scalar::Object(pair.clone())]);
12029 assert_eq!(list.pprint(), "[(a, 1)]");
12030 assert_eq!(pair.to_string(), "('a', 1)");
12032 let named = ObjectValue::Host(HostValue::new(Named("x")));
12034 assert_eq!(named.pprint(), "x");
12035 }
12036
12037 #[test]
12038 fn float64_json_spells_infinity_and_round_trips() {
12039 let json = |s: &Scalar| serde_json::to_string(s).expect("serialize");
12043 let back = |text: &str| serde_json::from_str::<Scalar>(text);
12044 assert_eq!(
12045 json(&Scalar::Float64(f64::INFINITY)),
12046 r#"{"kind":"float64","value":"inf"}"#
12047 );
12048 assert_eq!(
12049 json(&Scalar::Float64(f64::NEG_INFINITY)),
12050 r#"{"kind":"float64","value":"-inf"}"#
12051 );
12052 assert_eq!(
12054 json(&Scalar::Float64(1.5)),
12055 r#"{"kind":"float64","value":1.5}"#
12056 );
12057 assert_eq!(
12058 json(&Scalar::Float64(-0.0)),
12059 r#"{"kind":"float64","value":-0.0}"#
12060 );
12061 assert_eq!(
12062 json(&Scalar::Float64(f64::NAN)),
12063 r#"{"kind":"float64","value":null}"#
12064 );
12065 for value in [f64::INFINITY, f64::NEG_INFINITY, 1.5, -2.25e300] {
12066 let scalar = Scalar::Float64(value);
12067 assert_eq!(back(&json(&scalar)).expect("round trip"), scalar);
12068 }
12069 let negative_zero = back(r#"{"kind":"float64","value":-0.0}"#).expect("-0.0");
12070 assert!(matches!(negative_zero, Scalar::Float64(v) if v == 0.0 && v.is_sign_negative()));
12071 assert!(matches!(
12072 back(r#"{"kind":"float64","value":null}"#).expect("null"),
12073 Scalar::Float64(v) if v.is_nan()
12074 ));
12075 assert!(back(r#"{"kind":"float64","value":"Infinity"}"#).is_err());
12077 assert!(back(r#"{"kind":"float64","value":"1.5"}"#).is_err());
12078 }
12079
12080 #[test]
12090 fn semantic_cmp_cross_numeric_int_float_cdpai() {
12091 use std::cmp::Ordering;
12094 let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
12095 let mut next = || {
12096 st = st
12097 .wrapping_mul(6_364_136_223_846_793_005)
12098 .wrapping_add(1_442_695_040_888_963_407);
12099 (st >> 33) as u32
12100 };
12101 for _ in 0..3000u32 {
12102 let i = (next() % 21) as i64 - 10;
12103 let f = (next() % 400) as f64 / 20.0 - 10.0; let exp = (i as f64).partial_cmp(&f).unwrap();
12105 assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
12106 assert_eq!(
12107 Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
12108 exp.reverse()
12109 );
12110 }
12111 assert_eq!(
12113 Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
12114 Ordering::Equal
12115 );
12116 assert_eq!(
12117 Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
12118 Ordering::Equal
12119 );
12120 assert_eq!(
12121 Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
12122 Ordering::Less
12123 );
12124 assert_eq!(
12125 Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
12126 Ordering::Greater
12127 );
12128 }
12129
12130 #[test]
12131 fn semantic_cmp_nat_degeneracy_temporal_767ak() {
12132 use std::cmp::Ordering;
12133 const NAT: i64 = i64::MIN;
12134
12135 let td_nat = Scalar::Timedelta64(NAT);
12137 for v in [-3i64, 0, 5, 99] {
12138 let td = Scalar::Timedelta64(v);
12139 assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
12140 assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
12141 }
12142 assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
12143
12144 let dt_nat = Scalar::Datetime64(NAT);
12146 for v in [-3i64, 0, 5, 99] {
12147 let dt = Scalar::Datetime64(v);
12148 assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
12149 assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
12150 }
12151 assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
12152
12153 for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
12155 let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
12156 assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
12157 assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
12159 let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
12160 assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
12161 }
12162 }
12163
12164 fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
12165 [
12166 Scalar::Null(NullKind::Null),
12167 Scalar::Bool(true),
12168 Scalar::Int64(-7),
12169 Scalar::Float64(3.5),
12170 Scalar::Utf8("mixed".to_owned()),
12171 Scalar::Timedelta64(11),
12172 Scalar::Datetime64(1_735_732_800_123_456_789),
12173 Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
12174 Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
12175 ]
12176 }
12177
12178 fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
12179 !matches!(
12180 (left, right),
12181 (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
12182 )
12183 }
12184
12185 #[test]
12186 fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
12187 let values = semantic_cmp_cross_variant_values_d5ikg();
12188 for (left_index, left) in values.iter().enumerate() {
12189 for (right_index, right) in values.iter().enumerate() {
12190 if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12191 {
12192 assert_eq!(
12193 left.semantic_cmp(right),
12194 format!("{left:?}").cmp(&format!("{right:?}")),
12195 "cross-variant order mismatch: {left:?} vs {right:?}"
12196 );
12197 }
12198 }
12199 }
12200 }
12201
12202 #[test]
12203 #[ignore = "foreground release attribution harness"]
12204 fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
12205 use std::cmp::Ordering;
12206
12207 const BATCH: usize = 4_096;
12208 const BLOCKS: usize = 9;
12209
12210 fn former(left: &Scalar, right: &Scalar) -> Ordering {
12211 format!("{left:?}").cmp(&format!("{right:?}"))
12212 }
12213
12214 fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
12215 left.semantic_cmp(right)
12216 }
12217
12218 fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
12219 let mut less = 0usize;
12220 let started = std::time::Instant::now();
12221 for _ in 0..BATCH {
12222 for (left_index, left) in values.iter().enumerate() {
12223 for (right_index, right) in values.iter().enumerate() {
12224 if left_index != right_index
12225 && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12226 && compare(std::hint::black_box(left), std::hint::black_box(right))
12227 == Ordering::Less
12228 {
12229 less += 1;
12230 }
12231 }
12232 }
12233 }
12234 std::hint::black_box(less);
12235 started.elapsed().as_nanos()
12236 }
12237
12238 fn median(samples: &mut [u128]) -> u128 {
12239 samples.sort_unstable();
12240 samples[samples.len() / 2]
12241 }
12242
12243 let values = semantic_cmp_cross_variant_values_d5ikg();
12244
12245 for (left_index, left) in values.iter().enumerate() {
12246 for (right_index, right) in values.iter().enumerate() {
12247 if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
12248 {
12249 assert_eq!(
12250 former(left, right),
12251 candidate(left, right),
12252 "cross-variant order mismatch: {left:?} vs {right:?}"
12253 );
12254 }
12255 }
12256 }
12257
12258 std::hint::black_box(elapsed(&values, former));
12259 std::hint::black_box(elapsed(&values, candidate));
12260
12261 let mut former_samples = Vec::with_capacity(BLOCKS * 2);
12262 let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
12263 for block in 0..BLOCKS {
12264 if block.is_multiple_of(2) {
12265 former_samples.push(elapsed(&values, former));
12266 candidate_samples.push(elapsed(&values, candidate));
12267 candidate_samples.push(elapsed(&values, candidate));
12268 former_samples.push(elapsed(&values, former));
12269 } else {
12270 candidate_samples.push(elapsed(&values, candidate));
12271 former_samples.push(elapsed(&values, former));
12272 former_samples.push(elapsed(&values, former));
12273 candidate_samples.push(elapsed(&values, candidate));
12274 }
12275 }
12276
12277 let former_p50 = median(&mut former_samples);
12278 let candidate_p50 = median(&mut candidate_samples);
12279 eprintln!(
12280 "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
12281 former_p50 as f64 / candidate_p50 as f64
12282 );
12283 }
12284
12285 #[test]
12286 fn semantic_cmp_total_order_axioms_ay8o9() {
12287 use std::cmp::Ordering;
12288
12289 let mut state: u64 = 0xc0ff_eeba_df00_d123;
12290 let mut next = || {
12291 state = state
12292 .wrapping_mul(6_364_136_223_846_793_005)
12293 .wrapping_add(1_442_695_040_888_963_407);
12294 (state >> 33) as u32
12295 };
12296
12297 for iter in 0..6000u32 {
12298 let dt = next() % 4;
12299 let mk = |r: u32| match dt {
12301 0 => Scalar::Int64((r % 11) as i64 - 5),
12302 1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
12304 2 => Scalar::Utf8(format!("s{}", r % 5)),
12305 _ => Scalar::Bool(r.is_multiple_of(2)),
12306 };
12307 let a = mk(next());
12308 let b = mk(next());
12309 let c = mk(next());
12310 let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
12311
12312 assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
12314 assert_eq!(
12316 a.semantic_cmp(&b),
12317 b.semantic_cmp(&a).reverse(),
12318 "antisymmetric {ctx}"
12319 );
12320 let ab = a.semantic_cmp(&b);
12322 assert_eq!(
12323 a.semantic_le(&b),
12324 ab != Ordering::Greater,
12325 "le-consistent {ctx}"
12326 );
12327 assert_eq!(
12328 a.semantic_ge(&b),
12329 ab != Ordering::Less,
12330 "ge-consistent {ctx}"
12331 );
12332 assert_eq!(
12333 a.semantic_le(&b) && a.semantic_ge(&b),
12334 ab == Ordering::Equal,
12335 "le&ge<=>eq {ctx}"
12336 );
12337 if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
12339 assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
12340 }
12341 }
12342
12343 let nan = Scalar::Float64(f64::NAN);
12347 for v in [
12348 Scalar::Float64(-3.5),
12349 Scalar::Float64(0.0),
12350 Scalar::Float64(7.25),
12351 ] {
12352 assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
12353 assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
12354 }
12355 assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
12356 }
12357
12358 #[test]
12364 fn common_dtype_lattice_axioms_be314() {
12365 let all: [DType; 14] = [
12366 DType::Null,
12367 DType::Bool,
12368 DType::BoolNullable,
12369 DType::Int64,
12370 DType::Int64Nullable,
12371 DType::Float64,
12372 DType::Float64Nullable,
12375 DType::Utf8,
12376 DType::Categorical,
12377 DType::Timedelta64,
12378 DType::datetime64_naive(),
12379 DType::Period,
12380 DType::Interval,
12381 DType::Sparse,
12382 ];
12383
12384 for a in &all {
12385 assert_eq!(
12387 common_dtype(a.clone(), a.clone()),
12388 Ok(a.clone()),
12389 "idempotent {a:?}"
12390 );
12391 assert_eq!(
12393 common_dtype(DType::Null, a.clone()),
12394 Ok(a.clone()),
12395 "null-left identity {a:?}"
12396 );
12397 assert_eq!(
12398 common_dtype(a.clone(), DType::Null),
12399 Ok(a.clone()),
12400 "null-right identity {a:?}"
12401 );
12402
12403 for b in &all {
12404 assert_eq!(
12407 common_dtype(a.clone(), b.clone()).ok(),
12408 common_dtype(b.clone(), a.clone()).ok(),
12409 "commutative value {a:?},{b:?}"
12410 );
12411 assert_eq!(
12412 common_dtype(a.clone(), b.clone()).is_ok(),
12413 common_dtype(b.clone(), a.clone()).is_ok(),
12414 "commutative ok-ness {a:?},{b:?}"
12415 );
12416 }
12417 }
12418
12419 for a in &all {
12422 for b in &all {
12423 for c in &all {
12424 if let (Ok(ab), Ok(bc)) = (
12425 common_dtype(a.clone(), b.clone()),
12426 common_dtype(b.clone(), c.clone()),
12427 ) && let (Ok(left), Ok(right)) =
12428 (common_dtype(ab, c.clone()), common_dtype(a.clone(), bc))
12429 {
12430 assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
12431 }
12432 }
12433 }
12434 }
12435 }
12436
12437 #[test]
12440 fn infer_dtype_coercion_rules_e3sfq() {
12441 use DType::{Bool, Float64, Int64, Null, Utf8};
12442
12443 assert_eq!(infer_dtype(&[]), Ok(Null));
12445 assert_eq!(
12446 infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
12447 Ok(Null)
12448 );
12449
12450 let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
12452 let mut next = || {
12453 s = s
12454 .wrapping_mul(6_364_136_223_846_793_005)
12455 .wrapping_add(1_442_695_040_888_963_407);
12456 (s >> 33) as u32
12457 };
12458 for _ in 0..600u32 {
12459 let n = (next() % 6) as usize + 1;
12460 let ints: Vec<Scalar> = (0..n)
12461 .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
12462 .collect();
12463 assert_eq!(infer_dtype(&ints), Ok(Int64));
12464 let floats: Vec<Scalar> = (0..n)
12465 .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
12466 .collect();
12467 assert_eq!(infer_dtype(&floats), Ok(Float64));
12468 let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
12469 assert_eq!(infer_dtype(&bools), Ok(Bool));
12470 let strs: Vec<Scalar> = (0..n)
12471 .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
12472 .collect();
12473 assert_eq!(infer_dtype(&strs), Ok(Utf8));
12474 }
12475
12476 assert_eq!(
12478 infer_dtype(&[
12479 Scalar::Int64(1),
12480 Scalar::Null(NullKind::Null),
12481 Scalar::Int64(2)
12482 ]),
12483 Ok(Int64),
12484 "Int64 + nulls -> Int64"
12485 );
12486 assert_eq!(
12487 infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
12488 Ok(Float64),
12489 "Int64 + Float64 -> Float64"
12490 );
12491 assert_eq!(
12495 infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
12496 Ok(Utf8),
12497 "Bool + Int64 -> object bucket (pandas constructs object)"
12498 );
12499 assert_eq!(
12500 infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
12501 Ok(Utf8),
12502 "Utf8 + Int64 -> Utf8 (object fallback)"
12503 );
12504 }
12505
12506 #[test]
12511 fn missing_for_dtype_always_missing_1ews0() {
12512 let all: [DType; 14] = [
12513 DType::Null,
12514 DType::Bool,
12515 DType::BoolNullable,
12516 DType::Int64,
12517 DType::Int64Nullable,
12518 DType::Float64,
12519 DType::Float64Nullable,
12520 DType::Utf8,
12521 DType::Categorical,
12522 DType::Timedelta64,
12523 DType::datetime64_naive(),
12524 DType::Period,
12525 DType::Interval,
12526 DType::Sparse,
12527 ];
12528 for dt in &all {
12529 let m = Scalar::missing_for_dtype(dt.clone());
12530 assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
12531 for target in &all {
12532 let cast = cast_scalar(&m, target.clone()).expect("cast of missing");
12533 if target == &DType::Utf8 {
12534 assert!(
12537 matches!(cast, Scalar::Utf8(_)),
12538 "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
12539 );
12540 } else if matches!(dt, DType::Timedelta64 | DType::Datetime64 { .. })
12541 && matches!(target, DType::Bool | DType::Int64)
12542 {
12543 match target {
12559 DType::Bool => assert_eq!(
12560 cast,
12561 Scalar::Bool(true),
12562 "cast(missing {dt:?} -> Bool) is pandas' nonzero-truthy \
12563 read of the NaT bits"
12564 ),
12565 _ => assert_eq!(
12566 cast,
12567 Scalar::Int64(i64::MIN),
12568 "cast(missing {dt:?} -> Int64) is the NaT sentinel itself"
12569 ),
12570 }
12571 } else {
12572 assert!(
12575 cast.is_missing(),
12576 "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
12577 );
12578 }
12579 }
12580 }
12581 }
12582
12583 #[test]
12584 fn cast_scalar_bool_int_roundtrip_6w07b() {
12585 use super::cast_scalar;
12586 assert_eq!(
12588 cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
12589 Scalar::Int64(1)
12590 );
12591 assert_eq!(
12592 cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
12593 Scalar::Int64(0)
12594 );
12595 assert_eq!(
12596 cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
12597 Scalar::Bool(false)
12598 );
12599 let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
12600 let mut next = || {
12601 st = st
12602 .wrapping_mul(6_364_136_223_846_793_005)
12603 .wrapping_add(1_442_695_040_888_963_407);
12604 (st >> 33) as u32
12605 };
12606 for _ in 0..2000u32 {
12607 let v = (next() % 21) as i64 - 10;
12608 assert_eq!(
12609 cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
12610 Scalar::Bool(v != 0),
12611 "int->bool v={v}"
12612 );
12613 }
12614 }
12615
12616 #[test]
12618 fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
12619 use super::cast_scalar;
12620 let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
12623 let mut next = || {
12624 st = st
12625 .wrapping_mul(6_364_136_223_846_793_005)
12626 .wrapping_add(1_442_695_040_888_963_407);
12627 (st >> 33) as u32
12628 };
12629 for (f, exp) in [
12631 (-3.7, -3i64),
12632 (3.7, 3),
12633 (-3.2, -3),
12634 (3.2, 3),
12635 (-0.9, 0),
12636 (0.9, 0),
12637 (-5.0, -5),
12638 (5.0, 5),
12639 ] {
12640 assert_eq!(
12641 cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
12642 Scalar::Int64(exp),
12643 "cast {f}"
12644 );
12645 }
12646 for _ in 0..3000u32 {
12648 let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
12650 assert_eq!(
12651 got,
12652 Scalar::Int64(v.trunc() as i64),
12653 "trunc-toward-zero v={v}"
12654 );
12655 }
12656 }
12657
12658 #[test]
12667 fn cast_scalar_float_to_temporal_truncates_to_nanoseconds() {
12668 use super::{Timedelta, Timestamp, cast_scalar};
12669
12670 for (input, want) in [
12673 (1.5_f64, 1_i64),
12674 (-1.5, -1),
12675 (0.9, 0),
12676 (-0.9, 0),
12677 (2.5, 2),
12678 (-2.5, -2),
12679 (1.999_999, 1),
12680 (-1.999_999, -1),
12681 (2.0, 2),
12682 (1e18, 1_000_000_000_000_000_000),
12683 ] {
12684 assert_eq!(
12685 cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
12686 Scalar::Datetime64(want),
12687 "datetime64 cast of {input}"
12688 );
12689 assert_eq!(
12690 cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
12691 Scalar::Timedelta64(want),
12692 "timedelta64 cast of {input}"
12693 );
12694 }
12695
12696 for input in [
12700 f64::NAN,
12701 f64::INFINITY,
12702 f64::NEG_INFINITY,
12703 1e30,
12704 -1e30,
12705 9.3e18,
12706 -9.3e18,
12707 9_223_372_036_854_775_808.0, -9_223_372_036_854_775_808.0, ] {
12710 assert_eq!(
12711 cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
12712 Scalar::Datetime64(Timestamp::NAT),
12713 "datetime64 cast of {input} must be NaT"
12714 );
12715 assert_eq!(
12716 cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
12717 Scalar::Timedelta64(Timedelta::NAT),
12718 "timedelta64 cast of {input} must be NaT"
12719 );
12720 }
12721
12722 let just_inside = 9_223_372_036_854_774_784.0_f64; assert_eq!(
12726 cast_scalar(&Scalar::Float64(just_inside), DType::datetime64_naive()).unwrap(),
12727 Scalar::Datetime64(9_223_372_036_854_774_784),
12728 "the largest representable float must NOT be treated as NaT"
12729 );
12730
12731 assert_eq!(
12734 cast_scalar(&Scalar::Float64(1.5), DType::datetime64_naive()).unwrap(),
12735 Scalar::Datetime64(1)
12736 );
12737 assert_eq!(
12738 cast_scalar(&Scalar::Float64(1.5), DType::Int64).unwrap(),
12739 Scalar::Int64(1),
12740 "the SHARED cast truncates here too; it is the explicit constructor \
12741 that refuses, via Column::new's LossyFloatToInt pre-check"
12742 );
12743 }
12744
12745 #[test]
12750 fn cast_scalar_temporal_to_int64_is_raw_nanoseconds() {
12751 use super::{Timedelta, Timestamp, cast_scalar};
12752
12753 for nanos in [1_710_498_645_123_456_789_i64, 93_784_005_006_007, 0, -1] {
12756 assert_eq!(
12757 cast_scalar(&Scalar::Datetime64(nanos), DType::Int64).unwrap(),
12758 Scalar::Int64(nanos),
12759 "datetime64 -> int64 must be the raw nanos ({nanos})"
12760 );
12761 assert_eq!(
12762 cast_scalar(&Scalar::Timedelta64(nanos), DType::Int64).unwrap(),
12763 Scalar::Int64(nanos)
12764 );
12765 }
12766
12767 assert_eq!(
12773 cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Int64).unwrap(),
12774 Scalar::Int64(i64::MIN),
12775 "NaT -> int64 is the sentinel i64::MIN, not a missing value"
12776 );
12777 assert_eq!(
12778 cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Int64).unwrap(),
12779 Scalar::Int64(i64::MIN)
12780 );
12781
12782 for target in [DType::Int64Nullable, DType::Float64, DType::Float64Nullable] {
12791 assert!(
12792 cast_scalar(
12793 &Scalar::Datetime64(1_710_498_645_123_456_789),
12794 target.clone()
12795 )
12796 .is_err(),
12797 "datetime64 -> {target:?} must stay refused"
12798 );
12799 assert!(
12800 cast_scalar(&Scalar::Timedelta64(93_784_005_006_007), target.clone()).is_err(),
12801 "timedelta64 -> {target:?} must stay refused"
12802 );
12803 }
12804
12805 for (flag, want) in [(true, 1_i64), (false, 0)] {
12807 assert_eq!(
12808 cast_scalar(&Scalar::Bool(flag), DType::datetime64_naive()).unwrap(),
12809 Scalar::Datetime64(want)
12810 );
12811 assert_eq!(
12812 cast_scalar(&Scalar::Bool(flag), DType::Timedelta64).unwrap(),
12813 Scalar::Timedelta64(want)
12814 );
12815 }
12816 }
12817
12818 #[test]
12822 fn timestamp_string_resolution_and_formatting_match_pandas() {
12823 use super::{DatetimeStringResolution as Res, Timestamp};
12824
12825 const MIDNIGHT: i64 = 1_710_460_800_000_000_000; assert_eq!(Timestamp::string_resolution(MIDNIGHT), Res::Date);
12829 assert_eq!(
12830 Timestamp::string_resolution(MIDNIGHT + 37_845_000_000_000),
12831 Res::Second
12832 );
12833 assert_eq!(
12834 Timestamp::string_resolution(MIDNIGHT + 37_845_123_000_000),
12835 Res::Milli
12836 );
12837 assert_eq!(
12838 Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_000),
12839 Res::Micro
12840 );
12841 assert_eq!(
12842 Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_789),
12843 Res::Nano
12844 );
12845 assert_eq!(
12847 Timestamp::string_resolution(MIDNIGHT + 300_000_000_000),
12848 Res::Second
12849 );
12850 assert_eq!(Timestamp::string_resolution(Timestamp::NAT), Res::Date);
12853
12854 assert!(Res::Date < Res::Second);
12856 assert!(Res::Second < Res::Milli);
12857 assert!(Res::Milli < Res::Micro);
12858 assert!(Res::Micro < Res::Nano);
12859
12860 let value = MIDNIGHT + 37_845_123_456_789;
12862 assert_eq!(
12863 Timestamp::format_at_resolution(value, Res::Date),
12864 "2024-03-15"
12865 );
12866 assert_eq!(
12867 Timestamp::format_at_resolution(value, Res::Second),
12868 "2024-03-15 10:30:45"
12869 );
12870 assert_eq!(
12871 Timestamp::format_at_resolution(value, Res::Milli),
12872 "2024-03-15 10:30:45.123"
12873 );
12874 assert_eq!(
12875 Timestamp::format_at_resolution(value, Res::Micro),
12876 "2024-03-15 10:30:45.123456"
12877 );
12878 assert_eq!(
12879 Timestamp::format_at_resolution(value, Res::Nano),
12880 "2024-03-15 10:30:45.123456789"
12881 );
12882
12883 assert_eq!(
12886 Timestamp::format_at_resolution(MIDNIGHT, Res::Nano),
12887 "2024-03-15 00:00:00.000000000"
12888 );
12889
12890 assert_eq!(
12892 Timestamp::format_at_resolution(MIDNIGHT, Res::Second),
12893 "2024-03-15 00:00:00"
12894 );
12895
12896 for resolution in [Res::Date, Res::Second, Res::Milli, Res::Micro, Res::Nano] {
12898 assert_eq!(
12899 Timestamp::format_at_resolution(Timestamp::NAT, resolution),
12900 "NaT"
12901 );
12902 }
12903
12904 assert_eq!(
12907 Timestamp::format_at_resolution(-1, Res::Nano),
12908 "1969-12-31 23:59:59.999999999"
12909 );
12910
12911 assert_eq!(
12913 Timestamp::format_at_resolution(-9_223_372_036_854_775_806, Res::Nano),
12914 "1677-09-21 00:12:43.145224194"
12915 );
12916 assert_eq!(
12917 Timestamp::format_at_resolution(9_223_372_036_854_775_807, Res::Nano),
12918 "2262-04-11 23:47:16.854775807"
12919 );
12920 }
12921
12922 #[test]
12926 fn cast_scalar_temporal_to_bool_is_nonzero_on_the_nanos() {
12927 use super::{Timedelta, Timestamp, cast_scalar};
12928
12929 for (nanos, want) in [
12931 (0_i64, false),
12932 (1_710_498_645_123_456_789, true),
12933 (-1, true),
12934 (86_400_000_000_000, true),
12935 (1, true),
12936 ] {
12937 assert_eq!(
12938 cast_scalar(&Scalar::Datetime64(nanos), DType::Bool).unwrap(),
12939 Scalar::Bool(want),
12940 "datetime64 {nanos} -> bool"
12941 );
12942 assert_eq!(
12943 cast_scalar(&Scalar::Timedelta64(nanos), DType::Bool).unwrap(),
12944 Scalar::Bool(want),
12945 "timedelta64 {nanos} -> bool"
12946 );
12947 }
12948
12949 assert_eq!(
12953 cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Bool).unwrap(),
12954 Scalar::Bool(true),
12955 "NaT -> bool is true in pandas, not a missing value"
12956 );
12957 assert_eq!(
12958 cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Bool).unwrap(),
12959 Scalar::Bool(true)
12960 );
12961
12962 for nanos in [0_i64, 1, -1, 1_710_498_645_123_456_789] {
12973 assert!(
12974 cast_scalar(&Scalar::Datetime64(nanos), DType::BoolNullable).is_err(),
12975 "datetime64 {nanos} -> nullable boolean must stay refused"
12976 );
12977 assert!(
12978 cast_scalar(&Scalar::Timedelta64(nanos), DType::BoolNullable).is_err(),
12979 "timedelta64 {nanos} -> nullable boolean must stay refused"
12980 );
12981 }
12982 }
12983
12984 #[test]
12985 fn nancount_nunique_prod_any_all_mx60x() {
12986 use super::{nanall, nanany, nancount, nannunique, nanprod};
12987 let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
12990 let mut next = || {
12991 s = s
12992 .wrapping_mul(6_364_136_223_846_793_005)
12993 .wrapping_add(1_442_695_040_888_963_407);
12994 (s >> 33) as u32
12995 };
12996 let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
12997 let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
12998 for iter in 0..1000u32 {
12999 let n = (next() % 10) as usize + 1;
13000 let raw: Vec<f64> = (0..n)
13001 .map(|_| {
13002 if next() % 4 == 0 {
13003 f64::NAN
13004 } else {
13005 (next() % 5) as f64
13006 }
13007 })
13008 .collect();
13009 let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13010 if finite.is_empty() {
13011 continue;
13012 }
13013 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13014 let distinct: std::collections::HashSet<u64> =
13015 finite.iter().map(|x| x.to_bits()).collect();
13016 let prod: f64 = finite.iter().product();
13017 assert!(
13018 (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
13019 "nancount iter={iter}"
13020 );
13021 assert!(
13022 (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
13023 "nannunique iter={iter}"
13024 );
13025 assert!(
13026 (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
13027 "nanprod iter={iter}"
13028 );
13029 assert_eq!(
13030 asb(nanany(&scalars)),
13031 finite.iter().any(|&x| x != 0.0),
13032 "nanany iter={iter}"
13033 );
13034 assert_eq!(
13035 asb(nanall(&scalars)),
13036 finite.iter().all(|&x| x != 0.0),
13037 "nanall iter={iter}"
13038 );
13039 }
13040 }
13041
13042 #[test]
13043 fn nan_reduction_kernels_skip_correctness_1uagc() {
13044 use super::{nanmax, nanmedian, nanmin, nansum};
13045 let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
13048 let mut next = || {
13049 s = s
13050 .wrapping_mul(6_364_136_223_846_793_005)
13051 .wrapping_add(1_442_695_040_888_963_407);
13052 (s >> 33) as u32
13053 };
13054 let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
13055 for iter in 0..1000u32 {
13056 let n = (next() % 12) as usize + 1;
13057 let raw: Vec<f64> = (0..n)
13058 .map(|_| {
13059 if next() % 4 == 0 {
13060 f64::NAN
13061 } else {
13062 (next() % 200) as f64 - 100.0
13063 }
13064 })
13065 .collect();
13066 let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13067 if finite.is_empty() {
13068 continue;
13069 }
13070 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13071 let sum: f64 = finite.iter().sum();
13072 let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
13073 let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
13074 finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
13075 let m = finite.len();
13076 let med = if m % 2 == 1 {
13077 finite[m / 2]
13078 } else {
13079 (finite[m / 2 - 1] + finite[m / 2]) / 2.0
13080 };
13081 assert!(
13082 (val(nansum(&scalars)) - sum).abs() < 1e-7,
13083 "nansum iter={iter}"
13084 );
13085 assert!(
13086 (val(nanmin(&scalars)) - mn).abs() < 1e-9,
13087 "nanmin iter={iter}"
13088 );
13089 assert!(
13090 (val(nanmax(&scalars)) - mx).abs() < 1e-9,
13091 "nanmax iter={iter}"
13092 );
13093 assert!(
13094 (val(nanmedian(&scalars)) - med).abs() < 1e-9,
13095 "nanmedian iter={iter}"
13096 );
13097 }
13098 }
13099
13100 #[test]
13101 fn nanvar_ddof_nanstd_nan_skip_p00ag() {
13102 use super::{nanmean, nanstd, nanvar};
13103 let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
13106 let mut next = || {
13107 s = s
13108 .wrapping_mul(6_364_136_223_846_793_005)
13109 .wrapping_add(1_442_695_040_888_963_407);
13110 (s >> 33) as u32
13111 };
13112 let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
13113 for iter in 0..1000u32 {
13114 let n = (next() % 10) as usize + 2;
13115 let raw: Vec<f64> = (0..n)
13116 .map(|_| {
13117 if next() % 4 == 0 {
13118 f64::NAN
13119 } else {
13120 (next() % 200) as f64 / 7.0
13121 }
13122 })
13123 .collect();
13124 let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
13125 if finite.len() < 2 {
13126 continue;
13127 }
13128 let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
13129 let nf = finite.len() as f64;
13130 let mean = finite.iter().sum::<f64>() / nf;
13131 let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
13132 assert!(
13133 (val(nanmean(&scalars)) - mean).abs() < 1e-7,
13134 "nanmean iter={iter}"
13135 );
13136 assert!(
13137 (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
13138 "nanvar ddof0 iter={iter}"
13139 );
13140 assert!(
13141 (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
13142 "nanvar ddof1 iter={iter}"
13143 );
13144 assert!(
13145 (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
13146 "nanstd ddof1 iter={iter}"
13147 );
13148 }
13149 }
13150
13151 #[test]
13152 fn nanskew_nankurt_min_sample_and_known_xybnq() {
13153 use super::{nankurt, nanskew};
13156 let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
13157 let val = |s: Scalar| -> Option<f64> {
13158 if s.is_missing() {
13159 None
13160 } else {
13161 s.to_f64().ok()
13162 }
13163 };
13164
13165 assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
13167 let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
13168 assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
13169 let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
13170 assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
13171
13172 assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
13174 let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
13175 assert!(
13176 (k - (-1.2)).abs() < 1e-6,
13177 "pandas kurt([1..5]) == -1.2, got {k}"
13178 );
13179 }
13180
13181 #[test]
13182 #[ignore = "foreground release attribution harness"]
13183 fn nanskew_fused_moment_scan_ab_mavln() {
13184 const ROWS: usize = 100_000;
13185 const BATCH: usize = 8;
13186
13187 fn former(values: &[Scalar]) -> Scalar {
13188 let nums = super::collect_finite(values);
13189 let n = nums.len() as f64;
13190 if n < 3.0 {
13191 return Scalar::Null(NullKind::NaN);
13192 }
13193 let mean = nums.iter().sum::<f64>() / n;
13194 let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
13195 let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
13196 let s2 = m2 / (n - 1.0);
13197 if s2 == 0.0 {
13198 return Scalar::Float64(0.0);
13199 }
13200 let s3 = s2.powf(1.5);
13201 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
13202 }
13203
13204 fn assert_bits_eq(former: Scalar, candidate: Scalar) {
13205 match (former, candidate) {
13206 (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
13207 (a, b) => assert_eq!(a, b),
13208 }
13209 }
13210
13211 fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
13212 std::hint::black_box(skew(std::hint::black_box(values)));
13213 let started = std::time::Instant::now();
13214 for _ in 0..BATCH {
13215 std::hint::black_box(skew(std::hint::black_box(values)));
13216 }
13217 started.elapsed().as_nanos()
13218 }
13219
13220 fn median(samples: &mut [u128]) -> u128 {
13221 samples.sort_unstable();
13222 samples[samples.len() / 2]
13223 }
13224
13225 for values in [
13226 vec![],
13227 vec![Scalar::Int64(1), Scalar::Int64(2)],
13228 vec![Scalar::Int64(7); 16],
13229 vec![
13230 Scalar::Int64(-3),
13231 Scalar::Null(NullKind::NaN),
13232 Scalar::Float64(2.5),
13233 Scalar::Utf8("skip".to_owned()),
13234 Scalar::Int64(11),
13235 ],
13236 ] {
13237 assert_bits_eq(former(&values), super::nanskew(&values));
13238 }
13239
13240 let values = (0..ROWS)
13241 .map(|i| {
13242 if i % 257 == 0 {
13243 Scalar::Null(NullKind::NaN)
13244 } else {
13245 Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
13246 }
13247 })
13248 .collect::<Vec<_>>();
13249 assert_bits_eq(former(&values), super::nanskew(&values));
13250
13251 for _ in 0..2 {
13252 std::hint::black_box(elapsed(&values, former));
13253 std::hint::black_box(elapsed(&values, super::nanskew));
13254 }
13255
13256 let mut former_samples = Vec::with_capacity(18);
13257 let mut candidate_samples = Vec::with_capacity(18);
13258 for block in 0_usize..9 {
13259 if block.is_multiple_of(2) {
13260 former_samples.push(elapsed(&values, former));
13261 candidate_samples.push(elapsed(&values, super::nanskew));
13262 candidate_samples.push(elapsed(&values, super::nanskew));
13263 former_samples.push(elapsed(&values, former));
13264 } else {
13265 candidate_samples.push(elapsed(&values, super::nanskew));
13266 former_samples.push(elapsed(&values, former));
13267 former_samples.push(elapsed(&values, former));
13268 candidate_samples.push(elapsed(&values, super::nanskew));
13269 }
13270 }
13271
13272 let former_p50 = median(&mut former_samples);
13273 let candidate_p50 = median(&mut candidate_samples);
13274 eprintln!(
13275 "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
13276 former_p50 as f64 / candidate_p50 as f64,
13277 );
13278 eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
13279 eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
13280 }
13281
13282 #[test]
13283 #[ignore = "foreground performance probe"]
13284 fn nankurt_fused_moment_scan_ab_idka7() {
13285 const ROWS: usize = 65_536;
13286 const BATCH: usize = 4;
13287
13288 fn former(values: &[Scalar]) -> Scalar {
13289 let nums = super::collect_finite(values);
13290 let n = nums.len() as f64;
13291 if n < 4.0 {
13292 return Scalar::Null(NullKind::NaN);
13293 }
13294 let mean = nums.iter().sum::<f64>() / n;
13295 let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
13296 let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
13297 let s2 = m2 / (n - 1.0);
13298 if s2 == 0.0 {
13299 return Scalar::Float64(0.0);
13300 }
13301 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
13302 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
13303 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
13304 }
13305
13306 fn assert_bits_eq(former: Scalar, candidate: Scalar) {
13307 match (former, candidate) {
13308 (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
13309 (a, b) => assert_eq!(a, b),
13310 }
13311 }
13312
13313 fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
13314 let started = std::time::Instant::now();
13315 for _ in 0..BATCH {
13316 std::hint::black_box(kurt(std::hint::black_box(values)));
13317 }
13318 started.elapsed().as_nanos()
13319 }
13320
13321 fn median(samples: &mut [u128]) -> u128 {
13322 samples.sort_unstable();
13323 samples[samples.len() / 2]
13324 }
13325
13326 for values in [
13327 vec![],
13328 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13329 vec![Scalar::Int64(7); 16],
13330 vec![
13331 Scalar::Int64(-3),
13332 Scalar::Null(NullKind::NaN),
13333 Scalar::Float64(2.5),
13334 Scalar::Utf8("skip".to_owned()),
13335 Scalar::Int64(11),
13336 Scalar::Float64(-7.25),
13337 ],
13338 ] {
13339 assert_bits_eq(former(&values), super::nankurt(&values));
13340 }
13341
13342 let values = (0..ROWS)
13343 .map(|i| {
13344 if i % 257 == 0 {
13345 Scalar::Null(NullKind::NaN)
13346 } else {
13347 Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
13348 }
13349 })
13350 .collect::<Vec<_>>();
13351 assert_bits_eq(former(&values), super::nankurt(&values));
13352
13353 for _ in 0..2 {
13354 std::hint::black_box(elapsed(&values, former));
13355 std::hint::black_box(elapsed(&values, super::nankurt));
13356 }
13357
13358 let mut former_samples = Vec::with_capacity(10);
13359 let mut candidate_samples = Vec::with_capacity(10);
13360 for block in 0_usize..5 {
13361 if block.is_multiple_of(2) {
13362 former_samples.push(elapsed(&values, former));
13363 candidate_samples.push(elapsed(&values, super::nankurt));
13364 candidate_samples.push(elapsed(&values, super::nankurt));
13365 former_samples.push(elapsed(&values, former));
13366 } else {
13367 candidate_samples.push(elapsed(&values, super::nankurt));
13368 former_samples.push(elapsed(&values, former));
13369 former_samples.push(elapsed(&values, former));
13370 candidate_samples.push(elapsed(&values, super::nankurt));
13371 }
13372 }
13373
13374 let former_p50 = median(&mut former_samples);
13375 let candidate_p50 = median(&mut candidate_samples);
13376 eprintln!(
13377 "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
13378 former_p50 as f64 / candidate_p50 as f64,
13379 );
13380 eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
13381 eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
13382 }
13383
13384 #[test]
13387 fn cast_scalar_to_utf8_formatting_yes7i() {
13388 let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
13391 let mut next = || {
13392 st = st
13393 .wrapping_mul(6_364_136_223_846_793_005)
13394 .wrapping_add(1_442_695_040_888_963_407);
13395 (st >> 33) as u32
13396 };
13397 for _ in 0..3000u32 {
13398 let n = (next() % 4_000_001) as i64 - 2_000_000;
13399 assert_eq!(
13400 cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
13401 Scalar::Utf8(n.to_string())
13402 );
13403 }
13404 assert_eq!(
13405 cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
13406 Scalar::Utf8("True".to_string())
13407 );
13408 assert_eq!(
13409 cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
13410 Scalar::Utf8("False".to_string())
13411 );
13412 }
13413
13414 #[test]
13415 fn cast_scalar_coercion_rules_6a83t() {
13416 let mut state: u64 = 0x5a17_c0de_1234_abcd;
13417 let mut next = || {
13418 state = state
13419 .wrapping_mul(6_364_136_223_846_793_005)
13420 .wrapping_add(1_442_695_040_888_963_407);
13421 (state >> 33) as u32
13422 };
13423
13424 for _ in 0..4000u32 {
13425 let n = (next() % 21) as i64 - 10; let b = next() % 2 == 0;
13427 let f = f64::from((next() % 41) as i32 - 20) / 4.0; let i = Scalar::Int64(n);
13430 let bo = Scalar::Bool(b);
13431 let fl = Scalar::Float64(f);
13432
13433 assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
13435 assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
13436 assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
13437
13438 assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
13440 assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
13441
13442 assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
13444 assert_eq!(
13445 cast_scalar(&i, DType::Float64),
13446 Ok(Scalar::Float64(n as f64))
13447 );
13448
13449 assert_eq!(
13451 cast_scalar(&bo, DType::Int64),
13452 Ok(Scalar::Int64(i64::from(b)))
13453 );
13454 assert_eq!(
13455 cast_scalar(&bo, DType::Float64),
13456 Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
13457 );
13458
13459 assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
13461 }
13462 }
13463
13464 #[test]
13466 fn scalar_from_primitive_types() {
13467 assert_eq!(Scalar::from(true), Scalar::Bool(true));
13469 assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
13470 assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
13471 assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
13472 assert_eq!(
13473 Scalar::from(String::from("world")),
13474 Scalar::Utf8("world".to_owned())
13475 );
13476
13477 let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
13481 assert_eq!(mixed[0], Scalar::Int64(1));
13482 assert_eq!(mixed[1], Scalar::Float64(2.0));
13483 assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
13484 }
13485
13486 #[test]
13487 fn dtype_inference_routes_bool_numeric_mix_to_object_bucket_rh1od() {
13488 let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
13493 assert_eq!(
13494 infer_dtype(&values).expect("dtype should infer"),
13495 DType::Utf8
13496 );
13497 }
13498
13499 #[test]
13500 fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
13501 let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
13502 let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
13503 assert_eq!(left.dtype(), DType::Interval);
13504 assert!(!left.is_missing());
13505 assert_eq!(
13506 infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
13507 DType::Interval
13508 );
13509 assert_eq!(
13510 common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
13511 DType::Interval
13512 );
13513 assert_eq!(
13514 cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
13515 Scalar::Null(NullKind::Null)
13516 );
13517 assert_eq!(
13518 cast_scalar(&left, DType::Utf8).expect("interval string cast"),
13519 Scalar::Utf8("(0.0, 1.0]".to_owned())
13520 );
13521 assert_eq!(
13522 super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
13523 Scalar::Int64(2)
13524 );
13525 }
13526
13527 #[test]
13528 fn cast_scalar_parses_temporal_extension_strings_avm08() {
13529 let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
13530 .expect("timestamp parse")
13531 .nanos;
13532 assert_eq!(
13533 cast_scalar(
13534 &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
13535 DType::datetime64_naive()
13536 )
13537 .expect("datetime cast"),
13538 Scalar::Datetime64(expected_nanos)
13539 );
13540 assert_eq!(
13541 cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
13542 Scalar::Period(Period::new(216, PeriodFreq::QUARTERLY))
13543 );
13544 assert_eq!(
13545 cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
13546 .expect("interval cast"),
13547 Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
13548 );
13549 }
13550
13551 #[test]
13552 fn missing_values_get_target_missing_marker() {
13553 let missing = Scalar::Null(NullKind::Null);
13554 let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
13555 assert_eq!(cast, Scalar::Null(NullKind::NaN));
13556 }
13557
13558 #[test]
13559 fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
13560 let cases = [
13561 (Scalar::Bool(true), "True"),
13562 (Scalar::Bool(false), "False"),
13563 (Scalar::Int64(-7), "-7"),
13564 (Scalar::Float64(1.0), "1.0"),
13565 (Scalar::Float64(1.5), "1.5"),
13566 (Scalar::Float64(f64::NAN), "nan"),
13567 (Scalar::Null(NullKind::Null), "None"),
13568 (Scalar::Null(NullKind::NaN), "nan"),
13569 (Scalar::Null(NullKind::NaT), "NaT"),
13570 ];
13571
13572 for (value, expected) in cases {
13573 assert_eq!(
13574 cast_scalar(&value, DType::Utf8).expect("cast"),
13575 Scalar::Utf8(expected.to_owned())
13576 );
13577 }
13578 }
13579
13580 #[test]
13581 fn semantic_eq_treats_nan_as_equal() {
13582 let left = Scalar::Float64(f64::NAN);
13583 let right = Scalar::Null(NullKind::NaN);
13584 assert!(left.semantic_eq(&right));
13585 }
13586
13587 #[test]
13588 fn semantic_eq_treats_nan_as_missing_null() {
13589 let left = Scalar::Float64(f64::NAN);
13590 let right = Scalar::Null(NullKind::Null);
13591 assert!(left.semantic_eq(&right));
13592 }
13593
13594 #[test]
13613 fn semantic_eq_unifies_dtype_sentinel_missing_with_null_xwxci() {
13614 for sentinel in [
13615 Scalar::Timedelta64(Timedelta::NAT),
13616 Scalar::Datetime64(Timestamp::NAT),
13617 Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
13618 ] {
13619 assert!(sentinel.is_missing(), "{sentinel:?} must report missing");
13620 for marker in [
13621 Scalar::Null(NullKind::Null),
13622 Scalar::Null(NullKind::NaN),
13623 Scalar::Null(NullKind::NaT),
13624 ] {
13625 assert!(
13626 sentinel.semantic_eq(&marker),
13627 "{sentinel:?} vs {marker:?} are both missing"
13628 );
13629 assert!(marker.semantic_eq(&sentinel), "and symmetrically");
13630 }
13631 }
13632
13633 let present = Scalar::Timedelta64(-60);
13635 assert!(!Scalar::Timedelta64(Timedelta::NAT).semantic_eq(&present));
13636 assert!(!present.semantic_eq(&Scalar::Null(NullKind::Null)));
13637 assert!(!present.semantic_eq(&Scalar::Timedelta64(-61)));
13639 }
13640
13641 #[test]
13642 fn common_dtype_rejects_string_numeric_mix() {
13643 let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
13644 assert_eq!(
13645 err.to_string(),
13646 "dtype coercion from Utf8 to Int64 has no compatible common type"
13647 );
13648 let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
13649 assert_eq!(
13650 err.to_string(),
13651 "dtype coercion from Float64 to Utf8 has no compatible common type"
13652 );
13653 }
13654
13655 #[test]
13656 fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
13657 let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
13658
13659 assert_eq!(dtype.value_dtype, DType::Float64);
13660 assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
13661 }
13662
13663 #[test]
13664 fn sparse_dtype_rejects_sparse_value_dtype() {
13665 let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
13666
13667 assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
13668 }
13669
13670 #[test]
13671 fn common_dtype_rejects_sparse_dense_mix() {
13672 let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
13673
13674 assert_eq!(
13675 err.to_string(),
13676 "dtype coercion from Sparse to Int64 has no compatible common type"
13677 );
13678 }
13679
13680 #[test]
13683 fn nullable_int64_promotion_matrix() {
13684 assert_eq!(
13686 common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
13687 DType::Int64Nullable
13688 );
13689 assert_eq!(
13690 common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
13691 DType::Int64Nullable
13692 );
13693
13694 assert_eq!(
13701 common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
13702 DType::Float64Nullable
13703 );
13704 assert_eq!(
13705 common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
13706 DType::Float64Nullable
13707 );
13708
13709 assert_eq!(
13711 common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
13712 DType::Int64Nullable
13713 );
13714
13715 assert_eq!(
13717 common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
13718 DType::Int64Nullable
13719 );
13720
13721 assert_eq!(
13723 common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
13724 DType::Int64Nullable
13725 );
13726 }
13727
13728 #[test]
13729 fn nullable_bool_promotion_matrix() {
13730 assert_eq!(
13732 common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
13733 DType::BoolNullable
13734 );
13735 assert_eq!(
13736 common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
13737 DType::BoolNullable
13738 );
13739
13740 assert_eq!(
13747 common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
13748 DType::Float64Nullable
13749 );
13750
13751 assert_eq!(
13754 common_dtype(DType::Bool, DType::Float64).unwrap(),
13755 DType::Float64
13756 );
13757 }
13758
13759 #[test]
13760 fn dtype_is_nullable_helper() {
13761 assert!(DType::Int64Nullable.is_nullable());
13762 assert!(DType::BoolNullable.is_nullable());
13763 assert!(!DType::Int64.is_nullable());
13764 assert!(!DType::Bool.is_nullable());
13765 assert!(!DType::Float64.is_nullable());
13766 assert!(!DType::Utf8.is_nullable());
13767 }
13768
13769 #[test]
13770 fn dtype_to_nullable_conversions() {
13771 assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
13772 assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
13773 assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
13783 assert_eq!(
13784 DType::Float64Nullable.to_nullable(),
13785 DType::Float64Nullable,
13786 "idempotent: already nullable"
13787 );
13788 assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
13789 }
13790
13791 #[test]
13792 fn dtype_to_non_nullable_conversions() {
13793 assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
13794 assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
13795 assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
13797 }
13798
13799 #[test]
13800 fn nullable_dtype_name_reports_pandas_style() {
13801 assert_eq!(DType::Int64.name(), "int64");
13802 assert_eq!(DType::Int64Nullable.name(), "Int64"); assert_eq!(DType::Bool.name(), "bool");
13804 assert_eq!(DType::BoolNullable.name(), "boolean");
13805 }
13806
13807 #[test]
13808 fn cast_scalar_int64_nullable_identity() {
13809 let val = Scalar::Int64(42);
13810 let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
13812 assert_eq!(result, Scalar::Int64(42));
13813
13814 let result2 = cast_scalar(&val, DType::Int64).unwrap();
13816 assert_eq!(result2, Scalar::Int64(42));
13817 }
13818
13819 #[test]
13820 fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
13821 let cases: &[(f64, &str)] = &[
13826 (1.0, "1.0"),
13827 (2.5, "2.5"),
13828 (100.0, "100.0"),
13829 (0.1, "0.1"),
13830 (0.0001, "0.0001"),
13831 (1e16, "1e+16"),
13832 (1e20, "1e+20"),
13833 (1e-5, "1e-05"),
13834 (1e-7, "1e-07"),
13835 (f64::INFINITY, "inf"),
13836 (f64::NEG_INFINITY, "-inf"),
13837 ];
13838 for (v, expected) in cases {
13839 assert_eq!(
13840 cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13841 Scalar::Utf8((*expected).to_owned()),
13842 "float {v} -> str"
13843 );
13844 }
13845 }
13846
13847 fn float_to_string_for_astype_former(value: f64) -> String {
13848 if value.is_nan() {
13849 return "nan".to_owned();
13850 }
13851 if value.is_infinite() {
13852 return value.to_string();
13853 }
13854 let rendered = format!("{value:?}");
13855 match rendered.split_once('e') {
13856 None => rendered,
13857 Some((mantissa, exponent)) => {
13858 let (sign, digits) = match exponent.strip_prefix('-') {
13859 Some(digits) => ('-', digits),
13860 None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
13861 };
13862 format!("{mantissa}e{sign}{digits:0>2}")
13863 }
13864 }
13865 }
13866
13867 fn scientific_astype_values(len: usize) -> Vec<f64> {
13868 const EXPONENTS: [i32; 16] = [
13869 -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
13870 ];
13871 (0..len)
13872 .map(|position| {
13873 let mantissa = 1.0 + (position % 997) as f64 / 997.0;
13874 let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
13875 if position.is_multiple_of(2) {
13876 magnitude
13877 } else {
13878 -magnitude
13879 }
13880 })
13881 .collect()
13882 }
13883
13884 #[test]
13885 fn float_to_string_for_astype_in_place_matches_former() {
13886 let fixed = [
13887 f64::NAN,
13888 f64::INFINITY,
13889 f64::NEG_INFINITY,
13890 0.0,
13891 -0.0,
13892 f64::MIN_POSITIVE,
13893 f64::MAX,
13894 f64::MIN,
13895 1e16,
13896 -1e16,
13897 1e-5,
13898 -1e-5,
13899 1.234_567_890_123_456_8e20,
13900 -9.876_543_210_987_654e-123,
13901 ];
13902 for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
13903 assert_eq!(
13904 super::float_to_string_for_astype(value),
13905 float_to_string_for_astype_former(value),
13906 "value={value:?}"
13907 );
13908 }
13909 }
13910
13911 #[test]
13912 #[ignore = "foreground performance probe"]
13913 fn float_to_string_for_astype_in_place_ab() {
13914 use std::time::Instant;
13915
13916 const VALUES: usize = 16_384;
13917 const SAMPLES: usize = 10;
13918 let values = scientific_astype_values(VALUES);
13919 for &value in &values {
13920 let former = float_to_string_for_astype_former(value);
13921 assert!(former.contains('e'), "benchmark value must be scientific");
13922 assert_eq!(super::float_to_string_for_astype(value), former);
13923 }
13924
13925 for _ in 0..2 {
13926 for &value in &values {
13927 std::hint::black_box(float_to_string_for_astype_former(value));
13928 std::hint::black_box(super::float_to_string_for_astype(value));
13929 }
13930 }
13931
13932 let mut former_ns = Vec::with_capacity(SAMPLES);
13933 let mut public_ns = Vec::with_capacity(SAMPLES);
13934 for sample in 0..SAMPLES {
13935 let run = |formatter: fn(f64) -> String| {
13936 let started = Instant::now();
13937 for &value in std::hint::black_box(&values) {
13938 std::hint::black_box(formatter(std::hint::black_box(value)));
13939 }
13940 started.elapsed().as_nanos()
13941 };
13942 if sample.is_multiple_of(2) {
13943 former_ns.push(run(float_to_string_for_astype_former));
13944 public_ns.push(run(super::float_to_string_for_astype));
13945 } else {
13946 public_ns.push(run(super::float_to_string_for_astype));
13947 former_ns.push(run(float_to_string_for_astype_former));
13948 }
13949 }
13950
13951 former_ns.sort_unstable();
13952 public_ns.sort_unstable();
13953 let former_p50 = former_ns[SAMPLES / 2];
13954 let public_p50 = public_ns[SAMPLES / 2];
13955 println!(
13956 "float_to_string_for_astype_in_place_ab values={VALUES} former_p50_ns={former_p50} public_p50_ns={public_p50} speedup={:.6} former_samples={former_ns:?} public_samples={public_ns:?}",
13957 former_p50 as f64 / public_p50 as f64
13958 );
13959 }
13960
13961 #[test]
13962 fn cast_float_to_utf8_threshold_boundaries_match_python() {
13963 let cases: &[(f64, &str)] = &[
13968 (1e15, "1000000000000000.0"),
13969 (9_999_999_999_999_998.0, "9999999999999998.0"),
13970 (1_234_567_890_123_456.0, "1234567890123456.0"),
13971 (123_456_789_012_345.0, "123456789012345.0"),
13972 (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
13973 (1e16, "1e+16"),
13974 (1.5e16, "1.5e+16"),
13975 (1e17, "1e+17"),
13976 (1e-4, "0.0001"),
13977 (5e-5, "5e-05"),
13978 (-1e15, "-1000000000000000.0"),
13979 (-1e16, "-1e+16"),
13980 (-1e-5, "-1e-05"),
13981 ];
13982 for (v, expected) in cases {
13983 assert_eq!(
13984 cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
13985 Scalar::Utf8((*expected).to_owned()),
13986 "float {v} -> str"
13987 );
13988 }
13989 }
13990
13991 #[test]
13992 fn cast_to_bool_uses_pandas_nonzero_truthiness() {
13993 let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
13997 for (v, expected) in cases_int {
13998 assert_eq!(
13999 cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
14000 Scalar::Bool(*expected),
14001 "int {v} -> bool"
14002 );
14003 }
14004 let cases_float: &[(f64, bool)] = &[
14005 (0.0, false),
14006 (-0.0, false),
14007 (0.1, true),
14008 (2.5, true),
14009 (1.0, true),
14010 (f64::NAN, true),
14012 ];
14013 for (v, expected) in cases_float {
14014 assert_eq!(
14015 cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
14016 Scalar::Bool(*expected),
14017 "float {v} -> bool"
14018 );
14019 }
14020 }
14021
14022 #[test]
14023 fn nullable_dtype_is_extension() {
14024 assert!(DType::Int64Nullable.is_extension());
14025 assert!(DType::BoolNullable.is_extension());
14026 assert!(!DType::Int64.is_extension());
14027 assert!(!DType::Bool.is_extension());
14028 }
14029
14030 #[test]
14031 fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
14032 let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
14033 assert_eq!(
14034 infer_dtype(&values).expect("dtype should infer"),
14035 DType::Utf8
14036 );
14037 }
14038
14039 #[test]
14040 fn infer_dtype_routes_bool_numeric_mix_to_utf8_object_bucket_rh1od() {
14041 let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Bool(false)];
14047 assert_eq!(
14048 infer_dtype(&values).expect("dtype should infer"),
14049 DType::Utf8
14050 );
14051 let with_float = vec![Scalar::Int64(1), Scalar::Float64(2.5), Scalar::Bool(true)];
14052 assert_eq!(
14053 infer_dtype(&with_float).expect("dtype should infer"),
14054 DType::Utf8
14055 );
14056 let with_null = vec![
14057 Scalar::Bool(true),
14058 Scalar::Null(NullKind::Null),
14059 Scalar::Int64(2),
14060 ];
14061 assert_eq!(
14062 infer_dtype(&with_null).expect("dtype should infer"),
14063 DType::Utf8
14064 );
14065 }
14066
14067 #[test]
14068 fn infer_dtype_keeps_nonmixed_bool_and_numeric_paths_rh1od() {
14069 assert_eq!(
14073 infer_dtype(&[Scalar::Bool(true), Scalar::Bool(false)]).expect("dtype should infer"),
14074 DType::Bool
14075 );
14076 assert_eq!(
14077 infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]).expect("dtype should infer"),
14078 DType::Float64
14079 );
14080 }
14081
14082 #[test]
14085 fn is_null_detects_explicit_nulls() {
14086 assert!(Scalar::Null(NullKind::Null).is_null());
14087 assert!(Scalar::Null(NullKind::NaN).is_null());
14088 assert!(!Scalar::Int64(42).is_null());
14089 assert!(!Scalar::Float64(f64::NAN).is_null());
14090 }
14091
14092 #[test]
14093 fn is_na_matches_is_missing() {
14094 let vals = vec![
14095 Scalar::Null(NullKind::Null),
14096 Scalar::Float64(f64::NAN),
14097 Scalar::Int64(0),
14098 Scalar::Bool(false),
14099 ];
14100 for v in &vals {
14101 assert_eq!(v.is_na(), v.is_missing());
14102 }
14103 }
14104
14105 #[test]
14106 fn coalesce_picks_first_non_missing() {
14107 let null = Scalar::Null(NullKind::Null);
14108 let fill = Scalar::Int64(99);
14109 assert_eq!(null.coalesce(&fill), fill);
14110 assert_eq!(fill.coalesce(&null), fill);
14111 }
14112
14113 #[test]
14116 fn isna_notna_complement() {
14117 let vals = vec![
14118 Scalar::Int64(1),
14119 Scalar::Null(NullKind::Null),
14120 Scalar::Float64(f64::NAN),
14121 Scalar::Float64(3.0),
14122 ];
14123 let na = super::isna(&vals);
14124 let not = super::notna(&vals);
14125 assert_eq!(na, vec![false, true, true, false]);
14126 for (a, b) in na.iter().zip(not.iter()) {
14127 assert_ne!(a, b);
14128 }
14129 }
14130
14131 #[test]
14132 fn count_na_counts_missing() {
14133 let vals = vec![
14134 Scalar::Int64(1),
14135 Scalar::Null(NullKind::Null),
14136 Scalar::Float64(f64::NAN),
14137 ];
14138 assert_eq!(super::count_na(&vals), 2);
14139 }
14140
14141 #[test]
14142 fn fill_na_replaces_missing() {
14143 let vals = vec![
14144 Scalar::Int64(1),
14145 Scalar::Null(NullKind::Null),
14146 Scalar::Float64(f64::NAN),
14147 Scalar::Int64(4),
14148 ];
14149 let filled = super::fill_na(&vals, &Scalar::Int64(0));
14150 assert_eq!(filled[0], Scalar::Int64(1));
14151 assert_eq!(filled[1], Scalar::Int64(0));
14152 assert_eq!(filled[2], Scalar::Int64(0));
14153 assert_eq!(filled[3], Scalar::Int64(4));
14154 }
14155
14156 #[test]
14157 fn dropna_removes_missing() {
14158 let vals = vec![
14159 Scalar::Int64(1),
14160 Scalar::Null(NullKind::Null),
14161 Scalar::Int64(3),
14162 Scalar::Float64(f64::NAN),
14163 ];
14164 let kept = super::dropna(&vals);
14165 assert_eq!(kept.len(), 2);
14166 assert_eq!(kept[0], Scalar::Int64(1));
14167 assert_eq!(kept[1], Scalar::Int64(3));
14168 }
14169
14170 #[test]
14171 fn null_helpers_match_scalar_oracle_imt0c() {
14172 fn next(seed: &mut u64) -> u64 {
14175 *seed = seed
14176 .wrapping_mul(3202034522624059733)
14177 .wrapping_add(4354685564936845319);
14178 *seed
14179 }
14180
14181 fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
14182 let expected_missing = values.iter().filter(|value| value.is_missing()).count();
14183 let expected_dropped = values
14184 .iter()
14185 .filter(|value| !value.is_missing())
14186 .cloned()
14187 .collect::<Vec<_>>();
14188 let expected_filled = values
14189 .iter()
14190 .map(|value| {
14191 if value.is_missing() {
14192 fill.clone()
14193 } else {
14194 value.clone()
14195 }
14196 })
14197 .collect::<Vec<_>>();
14198
14199 assert_eq!(
14200 super::count_na(values),
14201 expected_missing,
14202 "case={case}: count_na mismatch for {values:?}"
14203 );
14204
14205 let dropped = super::dropna(values);
14206 assert_eq!(
14207 dropped.len(),
14208 expected_dropped.len(),
14209 "case={case}: dropna length mismatch for {values:?}"
14210 );
14211 for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
14212 {
14213 assert!(
14214 actual.semantic_eq(expected),
14215 "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
14216 );
14217 }
14218
14219 let filled = super::fill_na(values, fill);
14220 assert_eq!(
14221 filled.len(),
14222 expected_filled.len(),
14223 "case={case}: fill_na length mismatch for {values:?}"
14224 );
14225 for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
14226 assert!(
14227 actual.semantic_eq(expected),
14228 "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
14229 );
14230 }
14231 }
14232
14233 let all_missing = [
14234 Scalar::Null(NullKind::Null),
14235 Scalar::Null(NullKind::NaN),
14236 Scalar::Float64(f64::NAN),
14237 Scalar::Timedelta64(i64::MIN),
14238 ];
14239 assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
14240
14241 let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
14242 for case in 0..260 {
14243 let len = (next(&mut seed) % 83 + 1) as usize;
14244 let mut values = Vec::with_capacity(len);
14245 for pos in 0..len {
14246 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14247 values.push(match next(&mut seed) % 11 {
14248 0 => Scalar::Null(NullKind::Null),
14249 1 => Scalar::Null(NullKind::NaN),
14250 2 => Scalar::Float64(f64::NAN),
14251 3 => Scalar::Timedelta64(i64::MIN),
14252 4 => Scalar::Bool(raw & 1 == 0),
14253 5 => Scalar::Int64(raw),
14254 6 => Scalar::Float64(raw as f64 / 37.0),
14255 7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
14256 8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
14257 9 => Scalar::Utf8(String::new()),
14258 _ => Scalar::Timedelta64(raw),
14259 });
14260 }
14261
14262 let fill = match case % 5 {
14263 0 => Scalar::Bool(true),
14264 1 => Scalar::Int64(-777),
14265 2 => Scalar::Float64(12.5),
14266 3 => Scalar::Utf8("filled".into()),
14267 _ => Scalar::Timedelta64(123_456),
14268 };
14269 assert_null_helpers(case, &values, &fill);
14270 }
14271 }
14272
14273 #[test]
14276 fn nansum_skips_nulls() {
14277 let vals = vec![
14278 Scalar::Float64(1.0),
14279 Scalar::Null(NullKind::Null),
14280 Scalar::Float64(2.0),
14281 Scalar::Float64(f64::NAN),
14282 Scalar::Int64(7),
14283 ];
14284 assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
14285 }
14286
14287 #[test]
14288 fn nansum_empty_returns_zero() {
14289 assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
14290 }
14291
14292 #[test]
14293 fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
14294 fn next(seed: &mut u64) -> u64 {
14297 *seed = seed
14298 .wrapping_mul(6364136223846793005)
14299 .wrapping_add(1442695040888963407);
14300 *seed
14301 }
14302
14303 fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
14304 let mut sum = 0.0;
14305 let mut count = 0usize;
14306 for value in values {
14307 if value.is_missing() {
14308 continue;
14309 }
14310 if let Ok(value) = value.to_f64() {
14311 sum += value;
14312 count += 1;
14313 }
14314 }
14315 let mean = if count == 0 {
14316 Scalar::Null(NullKind::NaN)
14317 } else {
14318 Scalar::Float64(sum / count as f64)
14319 };
14320 (Scalar::Float64(sum), mean)
14321 }
14322
14323 fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
14324 let mut sum = 0_i128;
14325 let mut count = 0_i128;
14326 for value in values {
14327 if let Scalar::Timedelta64(ns) = value
14328 && !value.is_missing()
14329 {
14330 sum += i128::from(*ns);
14331 count += 1;
14332 }
14333 }
14334 if count == 0 {
14335 return (Scalar::Timedelta64(0), Scalar::Timedelta64(Timedelta::NAT));
14336 }
14337 (
14343 super::timedelta_ns_to_scalar(sum),
14344 super::timedelta_ns_to_scalar(sum / count),
14345 )
14346 }
14347
14348 fn assert_sum_mean(
14349 case: usize,
14350 family: &str,
14351 values: &[Scalar],
14352 expected_sum: Scalar,
14353 expected_mean: Scalar,
14354 ) {
14355 let actual_sum = super::nansum(values);
14356 let actual_mean = super::nanmean(values);
14357 assert!(
14358 actual_sum.semantic_eq(&expected_sum),
14359 "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
14360 );
14361 assert!(
14362 actual_mean.semantic_eq(&expected_mean),
14363 "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
14364 );
14365 }
14366
14367 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
14368 let (sum, mean) = expected_numeric(&all_missing);
14369 assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
14370
14371 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
14372 let (sum, mean) = expected_timedelta(&td_all_missing);
14373 assert_sum_mean(
14374 usize::MAX - 1,
14375 "timedelta_all_missing",
14376 &td_all_missing,
14377 sum,
14378 mean,
14379 );
14380
14381 let mut seed = 0x511d_ed5a_7a11_1a55_u64;
14382 for case in 0..260 {
14383 let len = (next(&mut seed) % 89 + 1) as usize;
14384
14385 let mut numeric = Vec::with_capacity(len);
14386 numeric.push(Scalar::Int64(case as i64 - 130));
14387 for _ in 1..len {
14388 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14389 numeric.push(match next(&mut seed) % 8 {
14390 0 => Scalar::Null(NullKind::Null),
14391 1 => Scalar::Null(NullKind::NaN),
14392 2 => Scalar::Float64(f64::NAN),
14393 3 => Scalar::Bool(raw & 1 == 0),
14394 4 => Scalar::Int64(raw % 257),
14395 5 => Scalar::Float64(raw as f64 / 67.0),
14396 6 => Scalar::Float64(0.0),
14397 _ => Scalar::Float64(-0.0),
14398 });
14399 }
14400 let (sum, mean) = expected_numeric(&numeric);
14401 assert_sum_mean(case, "numeric", &numeric, sum, mean);
14402
14403 let mut timedeltas = Vec::with_capacity(len);
14404 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
14405 for _ in 1..len {
14406 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14407 timedeltas.push(match next(&mut seed) % 7 {
14408 0 => Scalar::Null(NullKind::Null),
14409 1 => Scalar::Timedelta64(i64::MIN),
14410 _ => Scalar::Timedelta64(raw),
14411 });
14412 }
14413 let (sum, mean) = expected_timedelta(&timedeltas);
14414 assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
14415 }
14416 }
14417
14418 #[test]
14419 fn nannunique_merges_negative_zero_and_zero() {
14420 let vals = vec![
14421 Scalar::Float64(-0.0),
14422 Scalar::Float64(0.0),
14423 Scalar::Float64(1.0),
14424 ];
14425 assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
14426 }
14427
14428 #[test]
14429 fn nannunique_matches_scalar_bucket_oracle_elvbg() {
14430 fn next(seed: &mut u64) -> u64 {
14433 *seed = seed
14434 .wrapping_mul(2862933555777941757)
14435 .wrapping_add(3037000493);
14436 *seed
14437 }
14438
14439 fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
14440 match (left, right) {
14441 (Scalar::Float64(left), Scalar::Float64(right)) => {
14442 let left = if *left == 0.0 { 0.0 } else { *left };
14443 let right = if *right == 0.0 { 0.0 } else { *right };
14444 left.to_bits() == right.to_bits()
14445 }
14446 _ => left == right,
14447 }
14448 }
14449
14450 fn expected_nunique(values: &[Scalar]) -> i64 {
14451 let mut seen = Vec::<Scalar>::new();
14452 for value in values {
14453 if value.is_missing() {
14454 continue;
14455 }
14456 if !seen.iter().any(|existing| same_bucket(existing, value)) {
14457 seen.push(value.clone());
14458 }
14459 }
14460 seen.len() as i64
14461 }
14462
14463 fn assert_nannunique(case: usize, values: &[Scalar]) {
14464 assert_eq!(
14465 super::nannunique(values),
14466 Scalar::Int64(expected_nunique(values)),
14467 "case={case}: nannunique mismatch for {values:?}"
14468 );
14469 }
14470
14471 assert_nannunique(
14472 usize::MAX,
14473 &[
14474 Scalar::Float64(-0.0),
14475 Scalar::Float64(0.0),
14476 Scalar::Float64(f64::NAN),
14477 Scalar::Null(NullKind::Null),
14478 Scalar::Timedelta64(i64::MIN),
14479 ],
14480 );
14481
14482 let mut seed = 0x0e1b_60d0_b5e7_u64;
14483 for case in 0..320 {
14484 let len = (next(&mut seed) % 97 + 1) as usize;
14485 let mut values = Vec::with_capacity(len);
14486 for pos in 0..len {
14487 let raw = (next(&mut seed) % 1_001) as i64 - 500;
14488 values.push(match next(&mut seed) % 11 {
14489 0 => Scalar::Null(NullKind::Null),
14490 1 => Scalar::Null(NullKind::NaN),
14491 2 => Scalar::Float64(f64::NAN),
14492 3 => Scalar::Bool(raw & 1 == 0),
14493 4 => Scalar::Int64(raw % 37),
14494 5 => Scalar::Float64(raw as f64 / 19.0),
14495 6 => Scalar::Float64(0.0),
14496 7 => Scalar::Float64(-0.0),
14497 8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
14498 9 => Scalar::Utf8(String::new()),
14499 _ => Scalar::Timedelta64(raw % 41),
14500 });
14501 }
14502 assert_nannunique(case, &values);
14503 }
14504 }
14505
14506 #[test]
14507 fn nanmean_basic() {
14508 let vals = vec![
14509 Scalar::Float64(2.0),
14510 Scalar::Null(NullKind::Null),
14511 Scalar::Float64(4.0),
14512 ];
14513 assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
14514 }
14515
14516 #[test]
14517 fn nanmean_all_null_returns_nan() {
14518 let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
14519 assert!(super::nanmean(&vals).is_missing());
14520 }
14521
14522 #[test]
14523 fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
14524 let one_hour = 3_600 * 1_000_000_000_i64;
14528 let vals = vec![
14529 Scalar::Timedelta64(one_hour),
14530 Scalar::Timedelta64(2 * one_hour),
14531 Scalar::Timedelta64(3 * one_hour),
14532 ];
14533 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
14534 assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
14535 }
14536
14537 #[test]
14538 fn nansum_nanmean_timedelta64_skips_nat_620mj() {
14539 let one_hour = 3_600 * 1_000_000_000_i64;
14540 let vals = vec![
14541 Scalar::Timedelta64(Timedelta::NAT),
14542 Scalar::Timedelta64(one_hour),
14543 Scalar::Timedelta64(3 * one_hour),
14544 Scalar::Timedelta64(Timedelta::NAT),
14545 ];
14546 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
14548 assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
14549 }
14550
14551 #[test]
14558 fn nansum_timedelta_overflow_is_nat_not_fabricated_max_opz27() {
14559 let vals = vec![Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MAX)];
14560 let got = super::nansum(&vals);
14561 assert!(
14562 got.is_missing(),
14563 "overflowing sum must be missing, got {got:?}"
14564 );
14565 assert_eq!(got, Scalar::Timedelta64(Timedelta::NAT));
14566 assert_ne!(got, Scalar::Timedelta64(i64::MAX));
14567 }
14568
14569 #[test]
14574 fn nansum_timedelta_negative_overflow_is_nat_opz27() {
14575 let min_repr = i64::MIN + 1; let vals = vec![Scalar::Timedelta64(min_repr), Scalar::Timedelta64(min_repr)];
14577 assert_eq!(super::nansum(&vals), Scalar::Timedelta64(Timedelta::NAT));
14578
14579 let exact = vec![Scalar::Timedelta64(min_repr + 1), Scalar::Timedelta64(-1)];
14582 let got = super::nansum(&exact);
14583 assert_eq!(got, Scalar::Timedelta64(min_repr));
14584 assert!(!got.is_missing(), "Timedelta.min is representable, not NaT");
14585 }
14586
14587 #[test]
14591 fn nanptp_timedelta_overflow_is_nat_opz27() {
14592 let vals = vec![
14593 Scalar::Timedelta64(i64::MIN + 1),
14594 Scalar::Timedelta64(i64::MAX),
14595 ];
14596 let got = super::nanptp(&vals);
14597 assert!(
14598 got.is_missing(),
14599 "unrepresentable range must be NaT, got {got:?}"
14600 );
14601 assert_ne!(got, Scalar::Timedelta64(i64::MAX));
14602
14603 let hour = 3_600 * 1_000_000_000_i64;
14606 let ok = vec![Scalar::Timedelta64(hour), Scalar::Timedelta64(4 * hour)];
14607 assert_eq!(super::nanptp(&ok), Scalar::Timedelta64(3 * hour));
14608 }
14609
14610 #[test]
14615 fn nancumsum_timedelta_overflow_recovers_exact_value_opz27() {
14616 let vals = vec![
14617 Scalar::Timedelta64(i64::MAX),
14618 Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MIN + 1), ];
14621 let out = super::nancumsum(&vals);
14622 assert_eq!(out.len(), 3);
14623 assert_eq!(out[0], Scalar::Timedelta64(i64::MAX));
14624 assert!(
14625 out[1].is_missing(),
14626 "overflowed index must be NaT, got {:?}",
14627 out[1]
14628 );
14629 assert_eq!(
14630 out[2],
14631 Scalar::Timedelta64(i64::MAX),
14632 "exact i128 accumulation must recover; a clamped running sum cannot"
14633 );
14634 }
14635
14636 #[test]
14639 fn nancumsum_timedelta_exact_path_unchanged_opz27() {
14640 let sec = 1_000_000_000_i64;
14641 let vals = vec![
14642 Scalar::Timedelta64(sec),
14643 Scalar::Timedelta64(Timedelta::NAT),
14644 Scalar::Timedelta64(2 * sec),
14645 ];
14646 let out = super::nancumsum(&vals);
14647 assert_eq!(out[0], Scalar::Timedelta64(sec));
14648 assert!(out[1].is_missing());
14649 assert_eq!(out[2], Scalar::Timedelta64(3 * sec));
14650 }
14651
14652 const DAY_NS: i64 = 86_400 * 1_000_000_000;
14653 const DT_2020: i64 = 1_577_836_800_000_000_000;
14655
14656 #[test]
14664 fn datetime64_ordering_reductions_match_pandas_axhhk() {
14665 let d = Scalar::Datetime64;
14666 let vals = vec![
14667 d(DT_2020),
14668 d(DT_2020 + 60 * DAY_NS),
14669 d(DT_2020 + 31 * DAY_NS),
14670 ];
14671
14672 assert_eq!(super::nanmin(&vals), d(DT_2020));
14673 assert_eq!(super::nanmax(&vals), d(DT_2020 + 60 * DAY_NS));
14674 assert_eq!(super::nanargmin(&vals), Some(0));
14675 assert_eq!(super::nanargmax(&vals), Some(1));
14676
14677 let span = super::nanptp(&vals);
14679 assert_eq!(span, Scalar::Timedelta64(60 * DAY_NS));
14680 assert_eq!(span.dtype(), DType::Timedelta64);
14681
14682 assert_eq!(
14683 super::nancummax(&vals),
14684 vec![
14685 d(DT_2020),
14686 d(DT_2020 + 60 * DAY_NS),
14687 d(DT_2020 + 60 * DAY_NS)
14688 ]
14689 );
14690 assert_eq!(
14691 super::nancummin(&vals),
14692 vec![d(DT_2020), d(DT_2020), d(DT_2020)]
14693 );
14694 }
14695
14696 #[test]
14703 fn datetime64_min_max_size_dependence_pinned_axhhk() {
14704 let d = Scalar::Datetime64;
14705 let one = vec![d(DT_2020)];
14706 assert_eq!(super::nanmin(&one), d(DT_2020));
14707 assert_eq!(super::nanmax(&one), d(DT_2020));
14708
14709 let two = vec![d(DT_2020 + DAY_NS), d(DT_2020)];
14710 let got_min = super::nanmin(&two);
14711 assert!(
14712 !got_min.is_missing(),
14713 "2-element datetime min must not be missing, got {got_min:?}"
14714 );
14715 assert_eq!(got_min, d(DT_2020));
14716 assert_eq!(super::nanmax(&two), d(DT_2020 + DAY_NS));
14717 }
14718
14719 #[test]
14722 fn datetime64_reductions_skip_nat_and_guard_span_overflow_axhhk() {
14723 let d = Scalar::Datetime64;
14724 let with_nat = vec![
14725 d(Timestamp::NAT),
14726 d(DT_2020 + 31 * DAY_NS),
14727 d(DT_2020),
14728 d(Timestamp::NAT),
14729 ];
14730 assert_eq!(super::nanmin(&with_nat), d(DT_2020));
14731 assert_eq!(super::nanmax(&with_nat), d(DT_2020 + 31 * DAY_NS));
14732 assert_eq!(super::nanptp(&with_nat), Scalar::Timedelta64(31 * DAY_NS));
14733 assert_eq!(super::nanargmin(&with_nat), Some(2));
14735 assert_eq!(super::nanargmax(&with_nat), Some(1));
14736
14737 let huge = vec![d(i64::MIN + 1), d(i64::MAX)];
14739 let span = super::nanptp(&huge);
14740 assert!(span.is_missing(), "unrepresentable span must be NaT");
14741 assert_ne!(span, Scalar::Timedelta64(i64::MAX));
14742 }
14743
14744 #[test]
14751 fn datetime64_averaging_reductions_match_pandas_adv58() {
14752 let d = Scalar::Datetime64;
14753 let vals = vec![
14754 d(DT_2020),
14755 d(DT_2020 + 60 * DAY_NS),
14756 d(DT_2020 + 31 * DAY_NS),
14757 ];
14758 assert_eq!(super::nanmean(&vals), d(1_580_457_600_000_000_000));
14760 assert_eq!(super::nanmedian(&vals), d(1_580_515_200_000_000_000));
14761 assert_eq!(super::nanquantile(&vals, 0.5), d(1_580_515_200_000_000_000));
14762 assert_eq!(
14763 super::nanquantile(&vals, 0.25),
14764 d(1_579_176_000_000_000_000)
14765 );
14766 }
14767
14768 #[test]
14774 fn datetime64_mean_median_round_toward_zero_adv58() {
14775 let d = Scalar::Datetime64;
14776 for (a, b, want) in [
14777 (0_i64, 1_i64, 0_i64),
14778 (0, 3, 1),
14779 (1, 2, 1),
14780 (-1, 0, 0),
14781 (-3, 0, -1),
14782 (-2, -1, -1),
14783 (0, 2, 1),
14784 (-2, 0, -1),
14785 ] {
14786 let vals = vec![d(a), d(b)];
14787 assert_eq!(
14788 super::nanmean(&vals),
14789 d(want),
14790 "mean of [{a}, {b}] should be {want}"
14791 );
14792 assert_eq!(
14793 super::nanmedian(&vals),
14794 d(want),
14795 "median of [{a}, {b}] should be {want}"
14796 );
14797 }
14798 }
14799
14800 #[test]
14803 fn datetime64_averaging_skips_nat_adv58() {
14804 let d = Scalar::Datetime64;
14805 let vals = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14806 assert_eq!(super::nanmean(&vals), d(DT_2020 + DAY_NS));
14808 assert_eq!(super::nanmedian(&vals), d(DT_2020 + DAY_NS));
14809
14810 let all_nat = vec![d(Timestamp::NAT), d(Timestamp::NAT)];
14811 let got = super::nanmean(&all_nat);
14812 assert!(
14813 got.is_missing(),
14814 "all-NaT mean must be missing, got {got:?}"
14815 );
14816 assert_eq!(
14817 got.dtype(),
14818 DType::datetime64_naive(),
14819 "must stay Datetime64"
14820 );
14821 }
14822
14823 #[test]
14830 fn datetime64_averaging_is_exact_where_pandas_snaps_adv58() {
14831 let d = Scalar::Datetime64;
14832
14833 let constant = vec![d(DT_2020 + 1), d(DT_2020 + 1)];
14835 assert_eq!(super::nanmean(&constant), d(DT_2020 + 1));
14836 assert_eq!(super::nanmedian(&constant), d(DT_2020 + 1));
14837
14838 let odd = vec![d(DT_2020), d(DT_2020 + 129), d(DT_2020 + 258)];
14840 let med = super::nanmedian(&odd);
14841 assert_eq!(med, d(DT_2020 + 129));
14842 assert!(
14843 odd.contains(&med),
14844 "odd-count median must be one of the inputs; pandas returns B+256, which is not"
14845 );
14846 }
14847
14848 #[test]
14855 fn datetime64_std_matches_pandas_ddof_variants_40ujm() {
14856 let d = Scalar::Datetime64;
14857 let vals = vec![
14858 d(DT_2020),
14859 d(DT_2020 + 60 * DAY_NS),
14860 d(DT_2020 + 31 * DAY_NS),
14861 ];
14862 let s1 = super::nanstd(&vals, 1);
14864 assert_eq!(s1, Scalar::Timedelta64(2_592_479_955_563_784));
14865 assert_eq!(s1.dtype(), DType::Timedelta64);
14866 assert_eq!(
14867 super::nanstd(&vals, 0),
14868 Scalar::Timedelta64(2_116_751_019_841_492)
14869 );
14870 assert_eq!(
14871 super::nanstd(&vals, 2),
14872 Scalar::Timedelta64(3_666_320_313_338_702)
14873 );
14874 assert!(super::nanstd(&vals, 3).is_missing());
14876 }
14877
14878 #[test]
14882 fn datetime64_std_equals_timedelta64_std_on_same_ns_40ujm() {
14883 let offsets = [0_i64, 60 * DAY_NS, 31 * DAY_NS];
14884 let dt: Vec<Scalar> = offsets.iter().map(|o| Scalar::Datetime64(*o)).collect();
14885 let td: Vec<Scalar> = offsets.iter().map(|o| Scalar::Timedelta64(*o)).collect();
14886 assert_eq!(super::nanstd(&dt, 1), super::nanstd(&td, 1));
14887 assert_eq!(
14888 super::nanstd(&dt, 1),
14889 Scalar::Timedelta64(2_592_479_955_563_784)
14890 );
14891 }
14892
14893 #[test]
14897 fn datetime64_std_skips_nat_and_var_sem_stay_unsupported_40ujm() {
14898 let d = Scalar::Datetime64;
14899 let with_nat = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
14900 let without = vec![d(DT_2020), d(DT_2020 + 2 * DAY_NS)];
14901 assert_eq!(super::nanstd(&with_nat, 1), super::nanstd(&without, 1));
14903 assert_eq!(
14904 super::nanstd(&with_nat, 1),
14905 Scalar::Timedelta64(122_188_051_789_035)
14906 );
14907
14908 assert!(super::nanstd(&[d(DT_2020)], 1).is_missing());
14910 assert!(super::nanstd(&[d(Timestamp::NAT)], 1).is_missing());
14911
14912 let vals = vec![d(DT_2020), d(DT_2020 + 60 * DAY_NS)];
14916 assert!(super::nanvar(&vals, 1).is_missing());
14917 assert!(super::nansem(&vals, 1).is_missing());
14918 }
14919
14920 #[test]
14925 fn period_min_max_match_pandas_qoabs() {
14926 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14927 let vals = vec![p(600), p(602), p(601)];
14928 assert_eq!(super::nanmin(&vals), p(600));
14929 assert_eq!(super::nanmax(&vals), p(602));
14930
14931 assert_eq!(super::nanmin(&[p(600)]), p(600));
14935 let two = vec![p(602), p(600)];
14936 assert!(!super::nanmin(&two).is_missing());
14937 assert_eq!(super::nanmin(&two), p(600));
14938 assert_eq!(super::nanmax(&two), p(602));
14939 }
14940
14941 #[test]
14944 fn period_min_max_skip_nat_qoabs() {
14945 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14946 let nat = Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly));
14947 let vals = vec![nat.clone(), p(602), p(600), nat.clone()];
14948 assert_eq!(super::nanmin(&vals), p(600));
14949 assert_eq!(super::nanmax(&vals), p(602));
14950 assert!(super::nanmin(&[nat.clone(), nat]).is_missing());
14951 }
14952
14953 #[test]
14960 fn period_mixed_freq_is_not_ordered_qoabs() {
14961 let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
14962 let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
14963 let vals = vec![month.clone(), day.clone()];
14964 let got_min = super::nanmin(&vals);
14965 assert!(
14966 got_min.is_missing(),
14967 "mixed-freq Period min must not be ordered, got {got_min:?}"
14968 );
14969 assert_ne!(
14970 got_min, day,
14971 "must not rank the daily period by raw ordinal"
14972 );
14973 assert!(super::nanmax(&vals).is_missing());
14974 }
14975
14976 #[test]
14983 fn period_full_reduction_family_matches_pandas_d7zjp() {
14984 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
14985 let vals = vec![p(600), p(602), p(601)];
14986
14987 assert_eq!(super::nanmedian(&vals), p(601));
14988 assert_eq!(super::nanquantile(&vals, 0.5), p(601));
14989 assert_eq!(super::nanargmin(&vals), Some(0));
14990 assert_eq!(super::nanargmax(&vals), Some(1));
14991 assert_eq!(super::nancummax(&vals), vec![p(600), p(602), p(602)]);
14992 assert_eq!(super::nancummin(&vals), vec![p(600), p(600), p(600)]);
14993 }
14994
14995 #[test]
15000 fn period_even_count_median_truncates_toward_zero_d7zjp() {
15001 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
15002 assert_eq!(super::nanmedian(&[p(600), p(603)]), p(601));
15003 assert_eq!(super::nanmedian(&[p(600), p(601)]), p(600));
15004 }
15005
15006 #[test]
15012 fn period_mixed_freq_not_ordered_by_any_reduction_d7zjp() {
15013 let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
15014 let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
15015 let vals = vec![month, day];
15016
15017 assert!(super::nanmedian(&vals).is_missing());
15018 assert!(super::nanquantile(&vals, 0.5).is_missing());
15019 assert_eq!(super::nanargmin(&vals), None);
15020 assert_eq!(super::nanargmax(&vals), None);
15021 assert!(super::nancummax(&vals).iter().all(Scalar::is_missing));
15023 assert!(super::nancummin(&vals).iter().all(Scalar::is_missing));
15024 }
15025
15026 #[test]
15032 fn period_unsupported_reductions_stay_missing_d7zjp() {
15033 let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
15034 let vals = vec![p(600), p(602), p(601)];
15035 assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
15036 assert!(super::nanvar(&vals, 1).is_missing(), "pandas raises var");
15037 assert!(super::nansem(&vals, 1).is_missing(), "pandas raises sem");
15038 assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
15039 }
15040
15041 #[test]
15046 fn interval_min_max_match_pandas_srqdo() {
15047 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15048 let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
15049 assert_eq!(super::nanmin(&vals), iv(0.0, 1.0));
15050 assert_eq!(super::nanmax(&vals), iv(4.0, 5.0));
15051
15052 assert_eq!(super::nanmin(&[iv(2.0, 3.0)]), iv(2.0, 3.0));
15055 let two = vec![iv(4.0, 5.0), iv(0.0, 1.0)];
15056 assert!(!super::nanmin(&two).is_missing());
15057 assert_eq!(super::nanmin(&two), iv(0.0, 1.0));
15058 assert_eq!(super::nanmax(&two), iv(4.0, 5.0));
15059 }
15060
15061 #[test]
15066 fn interval_ties_on_left_order_by_right_srqdo() {
15067 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15068 let vals = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
15069 assert_eq!(super::nanmin(&vals), iv(0.0, 2.0));
15070 assert_eq!(super::nanmax(&vals), iv(0.0, 9.0));
15071 }
15072
15073 #[test]
15079 fn interval_nan_bound_is_not_ordered_srqdo() {
15080 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15081 let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
15082 assert!(super::nanmin(&vals).is_missing());
15083 assert!(super::nanmax(&vals).is_missing());
15084 }
15085
15086 #[test]
15090 fn interval_unsupported_reductions_stay_missing_srqdo() {
15091 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15092 let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
15093 assert!(super::nanmedian(&vals).is_missing(), "pandas raises median");
15094 assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
15095 assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
15096 assert!(
15097 super::nanquantile(&vals, 0.5).is_missing(),
15098 "pandas raises quantile"
15099 );
15100 assert!(
15101 super::nancummax(&vals).iter().all(Scalar::is_missing),
15102 "pandas NotImplementedErrors cummax"
15103 );
15104 }
15105
15106 #[test]
15110 fn interval_argmin_argmax_match_pandas_2h9dm() {
15111 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15112 let vals = vec![iv(4.0, 5.0), iv(0.0, 1.0), iv(2.0, 3.0)];
15114 assert_eq!(super::nanargmin(&vals), Some(1));
15115 assert_eq!(super::nanargmax(&vals), Some(0));
15116
15117 let tie = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
15120 assert_eq!(super::nanargmin(&tie), Some(1));
15121 assert_eq!(super::nanargmax(&tie), Some(2));
15122 }
15123
15124 #[test]
15129 fn interval_arg_first_occurrence_and_missing_2h9dm() {
15130 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15131 let dup = vec![iv(0.0, 1.0), iv(0.0, 1.0), iv(9.0, 9.0)];
15132 assert_eq!(
15133 super::nanargmin(&dup),
15134 Some(0),
15135 "first occurrence, not last"
15136 );
15137 assert_eq!(super::nanargmax(&dup), Some(2));
15138
15139 let with_missing = vec![iv(4.0, 5.0), Scalar::Null(NullKind::NaN), iv(0.0, 1.0)];
15140 assert_eq!(super::nanargmin(&with_missing), Some(2));
15141 assert_eq!(super::nanargmax(&with_missing), Some(0));
15142 }
15143
15144 #[test]
15148 fn interval_arg_nan_bound_declines_2h9dm() {
15149 let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
15150 let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
15151 assert_eq!(super::nanargmin(&vals), None);
15152 assert_eq!(super::nanargmax(&vals), None);
15153 }
15154
15155 #[test]
15162 fn overflow_policy_carrier_preserves_default_behavior_f29nz() {
15163 let mut state: u64 = 0x5DEE_CE66_D125_1F00;
15165 let mut next = || {
15166 state = state
15167 .wrapping_mul(6_364_136_223_846_793_005)
15168 .wrapping_add(1_442_695_040_888_963_407);
15169 state
15170 };
15171 let mut corpus: Vec<i64> = vec![
15173 0,
15174 1,
15175 -1,
15176 2,
15177 -2,
15178 i64::MAX,
15179 i64::MIN,
15180 i64::MIN + 1,
15181 i64::MAX - 1,
15182 i64::MAX / 2,
15183 -(i64::MAX / 2),
15184 ];
15185 for _ in 0..400 {
15186 let raw = next() as i64;
15187 corpus.push(raw);
15188 corpus.push(raw / 3);
15189 }
15190
15191 let policy = super::OverflowPolicy::default();
15192 assert_eq!(
15193 policy,
15194 super::OverflowPolicy::SurfaceNat,
15195 "default must not move"
15196 );
15197
15198 for &a in &corpus {
15199 for &b in &corpus {
15200 assert_eq!(
15202 Timedelta::add(a, b),
15203 policy
15204 .resolve(Timedelta::try_add(a, b), Timedelta::NAT)
15205 .expect("SurfaceNat never errors"),
15206 "add({a}, {b}) diverged"
15207 );
15208 assert_eq!(
15209 Timedelta::sub(a, b),
15210 policy
15211 .resolve(Timedelta::try_sub(a, b), Timedelta::NAT)
15212 .expect("SurfaceNat never errors"),
15213 "sub({a}, {b}) diverged"
15214 );
15215 assert_eq!(
15216 Timedelta::mul_scalar(a, b),
15217 policy
15218 .resolve(Timedelta::try_mul_scalar(a, b), Timedelta::NAT)
15219 .expect("SurfaceNat never errors"),
15220 "mul_scalar({a}, {b}) diverged"
15221 );
15222
15223 let ts = Timestamp::from_nanos(a);
15226 assert_eq!(
15227 ts.add_timedelta(b),
15228 ts.try_add_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
15229 "add_timedelta({a}, {b}) diverged"
15230 );
15231 assert_eq!(
15232 ts.sub_timedelta(b),
15233 ts.try_sub_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
15234 "sub_timedelta({a}, {b}) diverged"
15235 );
15236 let other = Timestamp::from_nanos(b);
15237 assert_eq!(
15238 ts.sub_timestamp(&other),
15239 ts.try_sub_timestamp(&other).unwrap_or(Timedelta::NAT),
15240 "sub_timestamp({a}, {b}) diverged"
15241 );
15242 }
15243 }
15244 }
15245
15246 #[test]
15251 fn overflow_policy_strict_reports_op_and_pandas_class_f29nz() {
15252 use super::{OverflowPolicy, PandasTemporalError};
15253
15254 let strict = OverflowPolicy::Strict;
15255
15256 let err = strict
15258 .resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT)
15259 .expect_err("must surface under Strict");
15260 assert_eq!(err.op, "Timedelta::add");
15261 assert_eq!(err.pandas_error, PandasTemporalError::Overflow);
15262
15263 let ts = Timestamp::from_nanos(i64::MAX);
15265 let err = strict
15266 .resolve(ts.try_add_timedelta(1), Timestamp::nat())
15267 .expect_err("must surface under Strict");
15268 assert_eq!(err.op, "Timestamp::add_timedelta");
15269 assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
15270
15271 let err = strict
15273 .resolve(
15274 Timestamp::from_nanos(i64::MIN + 1)
15275 .try_sub_timestamp(&Timestamp::from_nanos(i64::MAX)),
15276 Timedelta::NAT,
15277 )
15278 .expect_err("must surface under Strict");
15279 assert_eq!(err.op, "Timestamp::sub_timestamp");
15280 assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
15281
15282 assert_eq!(
15284 strict
15285 .resolve(Timedelta::try_add(Timedelta::NAT, 1), Timedelta::NAT)
15286 .expect("NaT propagation is not an overflow"),
15287 Timedelta::NAT
15288 );
15289 assert_eq!(
15291 strict
15292 .resolve(Timedelta::try_add(2, 3), Timedelta::NAT)
15293 .expect("no overflow"),
15294 5
15295 );
15296 }
15297
15298 #[test]
15306 fn timedelta_scalar_zero_division_taxonomy_t7ht2() {
15307 use super::{OverflowPolicy, PandasTemporalError};
15308
15309 let err = Timedelta::try_div_scalar(1_000_000_000, 0)
15311 .expect_err("scalar divide-by-zero must be reportable");
15312 assert_eq!(err.op, "Timedelta::div_scalar");
15313 assert_eq!(err.pandas_error, PandasTemporalError::ZeroDivision);
15314
15315 assert_eq!(Timedelta::div_scalar(1_000_000_000, 0), Timedelta::NAT);
15319 assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 0), Timedelta::NAT);
15320
15321 assert_eq!(
15324 OverflowPolicy::default()
15325 .resolve(Timedelta::try_div_scalar(1_000_000_000, 0), Timedelta::NAT)
15326 .expect("SurfaceNat never errors"),
15327 Timedelta::NAT
15328 );
15329
15330 assert_eq!(Timedelta::try_div_scalar(-7, 2), Ok(-4));
15333 assert_eq!(Timedelta::div_scalar(-7, 2), -4);
15334 assert_eq!(Timedelta::try_div_scalar(7, 2), Ok(3));
15335 assert_eq!(
15337 Timedelta::try_div_scalar(Timedelta::NAT, 2),
15338 Ok(Timedelta::NAT)
15339 );
15340 }
15341
15342 #[test]
15347 fn timedelta_constructor_error_maps_to_out_of_bounds_t7ht2() {
15348 use super::{PandasTemporalError, TimedeltaError};
15349
15350 assert_eq!(
15351 TimedeltaError::Overflow.pandas_error(),
15352 Some(PandasTemporalError::OutOfBoundsTimedelta)
15353 );
15354 assert_eq!(
15356 TimedeltaError::InvalidFormat("nonsense".into()).pandas_error(),
15357 None
15358 );
15359 assert!(Timedelta::from_unit(f64::INFINITY, "s").is_err());
15361 assert_eq!(
15362 Timedelta::from_unit(f64::INFINITY, "s")
15363 .unwrap_err()
15364 .pandas_error(),
15365 Some(PandasTemporalError::OutOfBoundsTimedelta)
15366 );
15367 }
15368
15369 #[test]
15375 fn hardened_audit_values_are_bit_identical_to_surface_nat_vllv6() {
15376 use super::{OverflowPolicy, overflow_audit};
15377
15378 overflow_audit::enable();
15379 let mut state: u64 = 0x1234_5678_9ABC_DEF0;
15380 let mut next = || {
15381 state = state
15382 .wrapping_mul(6_364_136_223_846_793_005)
15383 .wrapping_add(1_442_695_040_888_963_407);
15384 state
15385 };
15386 let mut corpus: Vec<i64> = vec![
15387 0,
15388 1,
15389 -1,
15390 2,
15391 -2,
15392 i64::MAX,
15393 i64::MIN,
15394 i64::MIN + 1,
15395 i64::MAX - 1,
15396 ];
15397 for _ in 0..120 {
15398 corpus.push(next() as i64);
15399 }
15400
15401 for &a in &corpus {
15402 for &b in &corpus {
15403 for op in [
15404 Timedelta::try_add as fn(i64, i64) -> Result<i64, super::TemporalFailure>,
15405 Timedelta::try_sub,
15406 Timedelta::try_mul_scalar,
15407 Timedelta::try_div_scalar,
15408 ] {
15409 let soft = OverflowPolicy::SurfaceNat
15410 .resolve(op(a, b), Timedelta::NAT)
15411 .expect("SurfaceNat never errors");
15412 let hard = OverflowPolicy::HardenedNat
15413 .resolve(op(a, b), Timedelta::NAT)
15414 .expect("HardenedNat never errors");
15415 assert_eq!(hard, soft, "HARDENED changed a value for ({a}, {b})");
15416 }
15417 }
15418 }
15419 overflow_audit::disable();
15420 }
15421
15422 #[test]
15427 fn hardened_audit_records_deterministic_recovery_entries_vllv6() {
15428 use super::{OverflowPolicy, PandasTemporalError, overflow_audit};
15429
15430 overflow_audit::enable();
15431 assert!(overflow_audit::is_enabled());
15432 assert!(overflow_audit::drain().is_empty(), "starts empty");
15433
15434 let _ =
15436 OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15437 let _ = OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(2, 3), Timedelta::NAT);
15438 let _ =
15439 OverflowPolicy::HardenedNat.resolve(Timedelta::try_div_scalar(5, 0), Timedelta::NAT);
15440
15441 let entries = overflow_audit::drain();
15442 assert_eq!(entries.len(), 2, "only the two failures are recorded");
15443
15444 assert_eq!(entries[0].op, "Timedelta::add");
15445 assert_eq!(entries[0].pandas_error, PandasTemporalError::Overflow);
15446 assert_eq!(entries[0].operands, Some((i64::MAX, 1)));
15447 assert_eq!(entries[0].recovered_as, i64::MIN);
15448
15449 assert_eq!(entries[1].op, "Timedelta::div_scalar");
15450 assert_eq!(entries[1].pandas_error, PandasTemporalError::ZeroDivision);
15451 assert_eq!(entries[1].operands, Some((5, 0)));
15452
15453 assert!(overflow_audit::drain().is_empty());
15455
15456 let _ = OverflowPolicy::SurfaceNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15458 let _ = OverflowPolicy::Strict.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15459 assert!(
15460 overflow_audit::drain().is_empty(),
15461 "SurfaceNat/Strict must not write to the audit trail"
15462 );
15463
15464 overflow_audit::disable();
15465 assert!(!overflow_audit::is_enabled());
15466 let _ =
15468 OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
15469 assert!(
15470 overflow_audit::drain().is_empty(),
15471 "disabled must not record"
15472 );
15473 }
15474
15475 #[test]
15493 fn strict_reproduces_pandas_silent_timedelta_wrap_s4lkx() {
15494 use super::{OverflowPolicy, nancumsum_with_policy};
15495
15496 assert_eq!(
15498 Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::Strict),
15499 -2,
15500 "STRICT must reproduce pandas' wrap, not repair it"
15501 );
15502
15503 let max = Scalar::Timedelta64(i64::MAX);
15506 let out = nancumsum_with_policy(
15507 &[max.clone(), max.clone(), max.clone()],
15508 OverflowPolicy::Strict,
15509 );
15510 assert_eq!(
15511 out,
15512 vec![
15513 Scalar::Timedelta64(i64::MAX),
15514 Scalar::Timedelta64(-2),
15515 Scalar::Timedelta64(i64::MAX - 2),
15516 ],
15517 "STRICT cumsum must reproduce pandas' int64 wraparound exactly"
15518 );
15519
15520 assert_eq!(
15522 Timedelta::mul_scalar_with_policy(Timedelta::NAT, 2, OverflowPolicy::Strict),
15523 Timedelta::NAT
15524 );
15525 }
15526
15527 #[test]
15533 fn non_strict_policies_still_refuse_to_wrap_s4lkx() {
15534 use super::{OverflowPolicy, nancumsum_with_policy, overflow_audit};
15535
15536 for policy in [OverflowPolicy::SurfaceNat, OverflowPolicy::HardenedNat] {
15537 assert_eq!(
15538 Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
15539 Timedelta::NAT,
15540 "{policy:?} must NOT wrap"
15541 );
15542 assert_ne!(
15543 Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
15544 -2,
15545 "{policy:?} must not reproduce the pandas quirk"
15546 );
15547 }
15548 assert_eq!(
15550 Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::default()),
15551 Timedelta::NAT
15552 );
15553
15554 let max = Scalar::Timedelta64(i64::MAX);
15556 let soft = nancumsum_with_policy(&[max.clone(), max.clone()], OverflowPolicy::SurfaceNat);
15557 assert!(soft[1].is_missing(), "non-STRICT cumsum must NaT, not wrap");
15558 assert_eq!(soft, super::nancumsum(&[max.clone(), max]));
15559
15560 overflow_audit::enable();
15563 let _ = Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::HardenedNat);
15564 assert_eq!(
15565 overflow_audit::drain().len(),
15566 1,
15567 "HARDENED must record the recovery it performed"
15568 );
15569 overflow_audit::disable();
15570 }
15571
15572 #[test]
15575 fn datetime64_mixed_input_still_falls_back_axhhk() {
15576 let vals = vec![Scalar::Datetime64(DT_2020), Scalar::Int64(5)];
15577 assert!(super::nanmin(&vals).is_missing());
15588 assert_eq!(super::nanptp(&vals), Scalar::Float64(0.0));
15589 }
15590
15591 #[test]
15592 fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
15593 let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
15597 assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
15599 }
15600
15601 #[test]
15602 fn nancount_counts_non_missing() {
15603 let vals = vec![
15604 Scalar::Int64(1),
15605 Scalar::Null(NullKind::Null),
15606 Scalar::Float64(3.0),
15607 ];
15608 assert_eq!(super::nancount(&vals), Scalar::Int64(2));
15609 }
15610
15611 #[test]
15612 fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
15613 fn next(seed: &mut u64) -> u64 {
15616 *seed = seed
15617 .wrapping_mul(6364136223846793005)
15618 .wrapping_add(1442695040888963407);
15619 *seed
15620 }
15621
15622 fn truthy(value: &Scalar) -> Option<bool> {
15623 if value.is_missing() {
15624 return None;
15625 }
15626 match value {
15627 Scalar::Bool(value) => Some(*value),
15628 Scalar::Int64(value) => Some(*value != 0),
15629 Scalar::Float64(value) => Some(*value != 0.0),
15630 Scalar::Utf8(value) => Some(!value.is_empty()),
15631 Scalar::Timedelta64(value) => Some(*value != 0),
15632 _ => None,
15633 }
15634 }
15635
15636 fn assert_nanops(case: usize, values: &[Scalar]) {
15637 let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
15638 let expected_any = truth_values.iter().any(|value| *value);
15639 let expected_all = !truth_values.iter().any(|value| !*value);
15640 let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
15641
15642 assert_eq!(
15643 super::nanany(values),
15644 Scalar::Bool(expected_any),
15645 "case={case}: nanany mismatch for {values:?}"
15646 );
15647 assert_eq!(
15648 super::nanall(values),
15649 Scalar::Bool(expected_all),
15650 "case={case}: nanall mismatch for {values:?}"
15651 );
15652 assert_eq!(
15653 super::nancount(values),
15654 Scalar::Int64(expected_count),
15655 "case={case}: nancount mismatch for {values:?}"
15656 );
15657 }
15658
15659 assert_nanops(
15660 usize::MAX,
15661 &[
15662 Scalar::Null(NullKind::Null),
15663 Scalar::Null(NullKind::NaN),
15664 Scalar::Float64(f64::NAN),
15665 Scalar::Timedelta64(i64::MIN),
15666 ],
15667 );
15668
15669 let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
15670 for case in 0..320 {
15671 let len = (next(&mut seed) % 89 + 1) as usize;
15672 let mut values = Vec::with_capacity(len);
15673 for pos in 0..len {
15674 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
15675 let value = match next(&mut seed) % 12 {
15676 0 => Scalar::Null(NullKind::Null),
15677 1 => Scalar::Null(NullKind::NaN),
15678 2 => Scalar::Float64(f64::NAN),
15679 3 => Scalar::Bool(raw & 1 == 0),
15680 4 => Scalar::Bool(false),
15681 5 => Scalar::Int64(raw % 17),
15682 6 => Scalar::Int64(0),
15683 7 => Scalar::Float64(raw as f64 / 23.0),
15684 8 => Scalar::Float64(0.0),
15685 9 => Scalar::Utf8(if raw & 1 == 0 {
15686 String::new()
15687 } else {
15688 format!("nanops_{case}_{pos}")
15689 }),
15690 10 => Scalar::Timedelta64(raw),
15691 _ => Scalar::Timedelta64(0),
15692 };
15693 values.push(value);
15694 }
15695 assert_nanops(case, &values);
15696 }
15697 }
15698
15699 #[test]
15700 fn nanmin_basic() {
15701 let vals = vec![
15702 Scalar::Float64(5.0),
15703 Scalar::Null(NullKind::Null),
15704 Scalar::Float64(2.0),
15705 Scalar::Float64(8.0),
15706 ];
15707 assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
15708 }
15709
15710 #[test]
15711 fn nanmax_basic() {
15712 let vals = vec![
15713 Scalar::Float64(5.0),
15714 Scalar::Float64(f64::NAN),
15715 Scalar::Float64(8.0),
15716 ];
15717 assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
15718 }
15719
15720 #[test]
15721 fn nanmin_nanmax_empty_returns_nan() {
15722 assert!(super::nanmin(&[]).is_missing());
15723 assert!(super::nanmax(&[]).is_missing());
15724 }
15725
15726 #[test]
15727 fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
15728 fn next(seed: &mut u64) -> u64 {
15731 *seed = seed
15732 .wrapping_mul(6364136223846793005)
15733 .wrapping_add(1442695040888963407);
15734 *seed
15735 }
15736
15737 fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
15738 match (left, right) {
15739 (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
15740 (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
15741 (Scalar::Float64(left), Scalar::Float64(right)) => {
15742 left.partial_cmp(right).expect("finite floats")
15743 }
15744 (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
15745 (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
15746 _ => std::cmp::Ordering::Equal,
15749 }
15750 }
15751
15752 fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
15753 let present = values
15754 .iter()
15755 .filter(|value| !value.is_missing())
15756 .cloned()
15757 .collect::<Vec<_>>();
15758 let actual_min = super::nanmin(values);
15759 let actual_max = super::nanmax(values);
15760 if present.is_empty() {
15761 assert!(
15762 actual_min.is_missing(),
15763 "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
15764 );
15765 assert!(
15766 actual_max.is_missing(),
15767 "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
15768 );
15769 return;
15770 }
15771
15772 let is_expected_family = |value: &Scalar| match family {
15773 "int" => matches!(value, Scalar::Int64(_)),
15774 "float" => matches!(value, Scalar::Float64(_)),
15775 "bool" => matches!(value, Scalar::Bool(_)),
15776 "utf8" => matches!(value, Scalar::Utf8(_)),
15777 "timedelta" => matches!(value, Scalar::Timedelta64(_)),
15778 _ => false,
15779 };
15780 assert!(
15781 present.iter().all(is_expected_family),
15782 "case={case} family={family}: mixed family escaped generator: {values:?}"
15783 );
15784
15785 let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
15786 let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
15787 assert!(
15788 actual_min.semantic_eq(expected_min.expect("min")),
15789 "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
15790 expected_min.expect("min")
15791 );
15792 assert!(
15793 actual_max.semantic_eq(expected_max.expect("max")),
15794 "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
15795 expected_max.expect("max")
15796 );
15797 }
15798
15799 let all_missing = [
15800 Scalar::Null(NullKind::Null),
15801 Scalar::Null(NullKind::NaN),
15802 Scalar::Float64(f64::NAN),
15803 Scalar::Timedelta64(i64::MIN),
15804 ];
15805 assert_minmax(usize::MAX, "all_missing", &all_missing);
15806
15807 let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
15808 for case in 0..240 {
15809 let len = (next(&mut seed) % 73 + 1) as usize;
15810
15811 let mut ints = Vec::with_capacity(len);
15812 ints.push(Scalar::Int64(case as i64 - 120));
15813 for _ in 1..len {
15814 let raw = (next(&mut seed) % 1_001) as i64 - 500;
15815 ints.push(match next(&mut seed) % 6 {
15816 0 => Scalar::Null(NullKind::Null),
15817 1 => Scalar::Null(NullKind::NaN),
15818 _ => Scalar::Int64(raw),
15819 });
15820 }
15821 assert_minmax(case, "int", &ints);
15822
15823 let mut floats = Vec::with_capacity(len);
15824 floats.push(Scalar::Float64(case as f64 / 11.0));
15825 for _ in 1..len {
15826 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15827 floats.push(match next(&mut seed) % 8 {
15828 0 | 1 => Scalar::Float64(f64::NAN),
15829 2 => Scalar::Float64(f64::INFINITY),
15830 3 => Scalar::Float64(f64::NEG_INFINITY),
15831 4 => Scalar::Float64(0.0),
15832 5 => Scalar::Float64(-0.0),
15833 _ => Scalar::Float64(raw as f64 / 41.0),
15834 });
15835 }
15836 assert_minmax(case, "float", &floats);
15837
15838 let mut bools = Vec::with_capacity(len);
15839 bools.push(Scalar::Bool(case & 1 == 0));
15840 for _ in 1..len {
15841 bools.push(match next(&mut seed) % 5 {
15842 0 => Scalar::Null(NullKind::Null),
15843 1 => Scalar::Null(NullKind::NaN),
15844 raw => Scalar::Bool(raw & 1 == 0),
15845 });
15846 }
15847 assert_minmax(case, "bool", &bools);
15848
15849 let mut utf8 = Vec::with_capacity(len);
15850 utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
15851 for pos in 1..len {
15852 utf8.push(match next(&mut seed) % 7 {
15853 0 => Scalar::Null(NullKind::Null),
15854 1 => Scalar::Null(NullKind::NaN),
15855 raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
15856 });
15857 }
15858 assert_minmax(case, "utf8", &utf8);
15859
15860 let mut timedeltas = Vec::with_capacity(len);
15861 timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15862 for _ in 1..len {
15863 let raw = (next(&mut seed) % 1_003) as i64 - 501;
15864 timedeltas.push(match next(&mut seed) % 7 {
15865 0 => Scalar::Null(NullKind::Null),
15866 1 => Scalar::Timedelta64(i64::MIN),
15867 _ => Scalar::Timedelta64(raw),
15868 });
15869 }
15870 assert_minmax(case, "timedelta", &timedeltas);
15871 }
15872 }
15873
15874 #[test]
15875 fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
15876 let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
15877 assert!(super::nanmin(&vals).is_missing());
15878 assert!(super::nanmax(&vals).is_missing());
15879
15880 let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
15881 assert!(super::nanmin(&vals2).is_missing());
15882 assert!(super::nanmax(&vals2).is_missing());
15883 }
15884
15885 #[test]
15886 fn nanmin_nanmax_compatible_numeric_types_ok() {
15887 let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
15888 assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
15889 assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
15890 }
15891
15892 #[test]
15893 fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
15894 let one_hour = 3_600 * 1_000_000_000_i64;
15898 let vals = vec![
15899 Scalar::Timedelta64(3 * one_hour),
15900 Scalar::Timedelta64(one_hour),
15901 Scalar::Timedelta64(2 * one_hour),
15902 ];
15903 assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15904 assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
15905 }
15906
15907 #[test]
15908 fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
15909 let one_hour = 3_600 * 1_000_000_000_i64;
15910 let vals = vec![
15911 Scalar::Timedelta64(Timedelta::NAT),
15912 Scalar::Timedelta64(one_hour),
15913 Scalar::Timedelta64(2 * one_hour),
15914 Scalar::Timedelta64(Timedelta::NAT),
15915 ];
15916 assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
15917 assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
15918 }
15919
15920 #[test]
15921 fn nanmedian_odd_count() {
15922 let vals = vec![
15923 Scalar::Float64(3.0),
15924 Scalar::Null(NullKind::Null),
15925 Scalar::Float64(1.0),
15926 Scalar::Float64(2.0),
15927 ];
15928 assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
15929 }
15930
15931 #[test]
15932 fn nanmedian_even_count() {
15933 let vals = vec![
15934 Scalar::Float64(1.0),
15935 Scalar::Float64(3.0),
15936 Scalar::Float64(2.0),
15937 Scalar::Float64(4.0),
15938 ];
15939 assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
15940 }
15941
15942 #[test]
15943 fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
15944 fn next(seed: &mut u64) -> u64 {
15947 *seed = seed
15948 .wrapping_mul(6364136223846793005)
15949 .wrapping_add(1442695040888963407);
15950 *seed
15951 }
15952
15953 fn expected_numeric(values: &[Scalar]) -> Scalar {
15954 let mut finite = values
15955 .iter()
15956 .filter(|value| !value.is_missing())
15957 .filter_map(|value| value.to_f64().ok())
15958 .filter(|value| !value.is_nan())
15959 .collect::<Vec<_>>();
15960 if finite.is_empty() {
15961 return Scalar::Null(NullKind::NaN);
15962 }
15963 finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
15964 let mid = finite.len() / 2;
15965 if finite.len().is_multiple_of(2) {
15966 Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
15967 } else {
15968 Scalar::Float64(finite[mid])
15969 }
15970 }
15971
15972 fn expected_timedelta(values: &[Scalar]) -> Scalar {
15973 let mut finite = values
15974 .iter()
15975 .filter_map(|value| match value {
15976 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns),
15977 _ => None,
15978 })
15979 .collect::<Vec<_>>();
15980 if finite.is_empty() {
15981 return Scalar::Null(NullKind::NaN);
15982 }
15983 finite.sort_unstable();
15984 let mid = finite.len() / 2;
15985 let median = if finite.len().is_multiple_of(2) {
15986 (i128::from(finite[mid - 1]) + i128::from(finite[mid])) / 2
15987 } else {
15988 i128::from(finite[mid])
15989 };
15990 Scalar::Timedelta64(median as i64)
15991 }
15992
15993 fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
15994 let actual = super::nanmedian(values);
15995 assert!(
15996 actual.semantic_eq(&expected),
15997 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
15998 );
15999 }
16000
16001 assert_median(
16002 usize::MAX,
16003 "numeric_all_missing",
16004 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
16005 Scalar::Null(NullKind::NaN),
16006 );
16007 assert_median(
16008 usize::MAX - 1,
16009 "timedelta_all_missing",
16010 &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
16011 Scalar::Null(NullKind::NaN),
16012 );
16013 let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
16014 assert_median(
16015 usize::MAX - 2,
16016 "timedelta_odd_median_beyond_f64_exactness",
16017 &[
16018 Scalar::Timedelta64(beyond_f64_exact_ns),
16019 Scalar::Timedelta64(beyond_f64_exact_ns + 1),
16020 Scalar::Timedelta64(beyond_f64_exact_ns + 2),
16021 Scalar::Timedelta64(Timedelta::NAT),
16022 ],
16023 Scalar::Timedelta64(beyond_f64_exact_ns + 1),
16024 );
16025
16026 let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
16027 for case in 0..220 {
16028 let len = (next(&mut seed) % 79 + 1) as usize;
16029
16030 let mut numeric = Vec::with_capacity(len);
16031 numeric.push(Scalar::Int64(case as i64 - 110));
16032 for _ in 1..len {
16033 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16034 numeric.push(match next(&mut seed) % 8 {
16035 0 => Scalar::Null(NullKind::Null),
16036 1 => Scalar::Null(NullKind::NaN),
16037 2 => Scalar::Float64(f64::NAN),
16038 3 => Scalar::Bool(raw & 1 == 0),
16039 4 => Scalar::Int64(raw % 251),
16040 5 => Scalar::Float64(raw as f64 / 61.0),
16041 6 => Scalar::Float64(0.0),
16042 _ => Scalar::Float64(-0.0),
16043 });
16044 }
16045 assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
16046
16047 let mut timedeltas = Vec::with_capacity(len);
16048 timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
16049 for _ in 1..len {
16050 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16051 timedeltas.push(match next(&mut seed) % 7 {
16052 0 => Scalar::Null(NullKind::Null),
16053 1 => Scalar::Timedelta64(i64::MIN),
16054 _ => Scalar::Timedelta64(raw),
16055 });
16056 }
16057 assert_median(
16058 case,
16059 "timedelta",
16060 &timedeltas,
16061 expected_timedelta(&timedeltas),
16062 );
16063 }
16064 }
16065
16066 #[test]
16067 fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
16068 fn next(seed: &mut u64) -> u64 {
16071 *seed = seed
16072 .wrapping_mul(2862933555777941757)
16073 .wrapping_add(3037000493);
16074 *seed
16075 }
16076
16077 fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
16078 values
16079 .iter()
16080 .filter(|value| !value.is_missing())
16081 .filter_map(|value| value.to_f64().ok())
16082 .collect()
16083 }
16084
16085 fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
16086 values
16087 .iter()
16088 .filter_map(|value| match value {
16089 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
16090 _ => None,
16091 })
16092 .collect()
16093 }
16094
16095 fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
16096 if samples.len() <= ddof {
16097 return None;
16098 }
16099 let mean = samples.iter().sum::<f64>() / samples.len() as f64;
16100 let sum_sq = samples
16101 .iter()
16102 .map(|value| (value - mean).powi(2))
16103 .sum::<f64>();
16104 let var = sum_sq / (samples.len() - ddof) as f64;
16105 let std = var.sqrt();
16106 let sem = std / (samples.len() as f64).sqrt();
16107 Some((var, std, sem))
16108 }
16109
16110 fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
16111 let samples = numeric_samples(values);
16112 let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
16113 let missing = Scalar::Null(NullKind::NaN);
16114 return (missing.clone(), missing.clone(), missing);
16115 };
16116 (
16117 Scalar::Float64(var),
16118 Scalar::Float64(std),
16119 Scalar::Float64(sem),
16120 )
16121 }
16122
16123 fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
16124 let samples = timedelta_samples(values);
16125 if samples.is_empty() {
16126 let missing = Scalar::Timedelta64(Timedelta::NAT);
16127 return (missing.clone(), missing.clone(), missing);
16128 }
16129 let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
16130 let missing = Scalar::Timedelta64(i64::MIN);
16131 return (missing.clone(), missing.clone(), missing);
16132 };
16133 (
16134 Scalar::Timedelta64(var as i64),
16135 Scalar::Timedelta64(std as i64),
16136 Scalar::Timedelta64(sem as i64),
16137 )
16138 }
16139
16140 fn assert_reductions(
16141 case: usize,
16142 family: &str,
16143 values: &[Scalar],
16144 ddof: usize,
16145 expected: (Scalar, Scalar, Scalar),
16146 ) {
16147 let (expected_var, expected_std, expected_sem) = expected;
16148 let actual_var = super::nanvar(values, ddof);
16149 let actual_std = super::nanstd(values, ddof);
16150 let actual_sem = super::nansem(values, ddof);
16151 assert!(
16152 actual_var.semantic_eq(&expected_var),
16153 "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
16154 );
16155 assert!(
16156 actual_std.semantic_eq(&expected_std),
16157 "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
16158 );
16159 assert!(
16160 actual_sem.semantic_eq(&expected_sem),
16161 "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
16162 );
16163 }
16164
16165 let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16166 assert_reductions(
16167 usize::MAX,
16168 "numeric_all_missing",
16169 &numeric_all_missing,
16170 0,
16171 expected_numeric(&numeric_all_missing, 0),
16172 );
16173
16174 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16175 assert_reductions(
16176 usize::MAX - 1,
16177 "timedelta_all_missing",
16178 &td_all_missing,
16179 0,
16180 expected_timedelta(&td_all_missing, 0),
16181 );
16182
16183 let mut seed = 0x7a11_c0de_5eed_0421_u64;
16184 for case in 0..240 {
16185 let len = (next(&mut seed) % 83 + 1) as usize;
16186 let ddof = (next(&mut seed) % 4) as usize;
16187
16188 let mut numeric = Vec::with_capacity(len);
16189 numeric.push(Scalar::Float64(case as f64 / 13.0));
16190 for _ in 1..len {
16191 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16192 numeric.push(match next(&mut seed) % 8 {
16193 0 => Scalar::Null(NullKind::Null),
16194 1 => Scalar::Null(NullKind::NaN),
16195 2 => Scalar::Float64(f64::NAN),
16196 3 => Scalar::Bool(raw & 1 == 0),
16197 4 => Scalar::Int64(raw % 251),
16198 5 => Scalar::Float64(raw as f64 / 73.0),
16199 6 => Scalar::Float64(0.0),
16200 _ => Scalar::Float64(-0.0),
16201 });
16202 }
16203 assert_reductions(
16204 case,
16205 "numeric",
16206 &numeric,
16207 ddof,
16208 expected_numeric(&numeric, ddof),
16209 );
16210
16211 let mut timedeltas = Vec::with_capacity(len);
16212 timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
16213 for _ in 1..len {
16214 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16215 timedeltas.push(match next(&mut seed) % 7 {
16216 0 => Scalar::Null(NullKind::Null),
16217 1 => Scalar::Timedelta64(i64::MIN),
16218 _ => Scalar::Timedelta64(raw),
16219 });
16220 }
16221 assert_reductions(
16222 case,
16223 "timedelta",
16224 &timedeltas,
16225 ddof,
16226 expected_timedelta(&timedeltas, ddof),
16227 );
16228 }
16229 }
16230
16231 #[test]
16232 fn nanvar_population() {
16233 let vals = vec![
16234 Scalar::Float64(2.0),
16235 Scalar::Float64(4.0),
16236 Scalar::Float64(4.0),
16237 Scalar::Float64(4.0),
16238 Scalar::Float64(5.0),
16239 Scalar::Float64(5.0),
16240 Scalar::Float64(7.0),
16241 Scalar::Float64(9.0),
16242 ];
16243 let var = super::nanvar(&vals, 0);
16244 assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
16245 if let Scalar::Float64(v) = var {
16246 assert!((v - 4.0).abs() < 1e-10);
16247 }
16248 }
16249
16250 #[test]
16251 fn nanvar_sample_ddof1() {
16252 let vals = vec![
16253 Scalar::Float64(2.0),
16254 Scalar::Float64(4.0),
16255 Scalar::Float64(4.0),
16256 Scalar::Float64(4.0),
16257 Scalar::Float64(5.0),
16258 Scalar::Float64(5.0),
16259 Scalar::Float64(7.0),
16260 Scalar::Float64(9.0),
16261 ];
16262 let var = super::nanvar(&vals, 1);
16263 assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
16264 if let Scalar::Float64(v) = var {
16265 assert!((v - 32.0 / 7.0).abs() < 1e-10);
16266 }
16267 }
16268
16269 #[test]
16270 fn nanvar_insufficient_values_returns_nan() {
16271 let vals = vec![Scalar::Float64(5.0)];
16272 assert!(super::nanvar(&vals, 1).is_missing());
16273 }
16274
16275 #[test]
16276 fn nanstd_is_sqrt_of_var() {
16277 let vals = vec![
16278 Scalar::Float64(2.0),
16279 Scalar::Float64(4.0),
16280 Scalar::Float64(4.0),
16281 Scalar::Float64(4.0),
16282 Scalar::Float64(5.0),
16283 Scalar::Float64(5.0),
16284 Scalar::Float64(7.0),
16285 Scalar::Float64(9.0),
16286 ];
16287 let std = super::nanstd(&vals, 0);
16288 assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
16289 if let Scalar::Float64(v) = std {
16290 assert!((v - 2.0).abs() < 1e-10);
16291 }
16292 }
16293
16294 #[test]
16295 fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
16296 let one_hour = 3_600 * 1_000_000_000_i64;
16299 let vals = vec![
16300 Scalar::Timedelta64(one_hour),
16301 Scalar::Timedelta64(2 * one_hour),
16302 Scalar::Timedelta64(3 * one_hour),
16303 ];
16304 assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
16305 }
16306
16307 #[test]
16308 fn nanstd_timedelta64_preserves_dtype_j8ntk() {
16309 let one_hour: i64 = 3_600 * 1_000_000_000;
16313 let vals = vec![
16314 Scalar::Timedelta64(one_hour),
16315 Scalar::Timedelta64(2 * one_hour),
16316 Scalar::Timedelta64(3 * one_hour),
16317 ];
16318 let std = super::nanstd(&vals, 0);
16319 assert!(matches!(std, Scalar::Timedelta64(_)));
16320 if let Scalar::Timedelta64(ns) = std {
16321 let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
16322 assert!(
16323 (ns as f64 - expected).abs() < 1e6,
16324 "expected ~{expected} ns, got {ns}"
16325 );
16326 }
16327 }
16328
16329 #[test]
16330 fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
16331 let one_hour = 3_600 * 1_000_000_000_i64;
16332 let vals = vec![Scalar::Timedelta64(one_hour)];
16333 assert_eq!(super::nanstd(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
16335 assert_eq!(super::nansem(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
16336 }
16337
16338 #[test]
16339 fn nanops_with_mixed_types() {
16340 let vals = vec![
16341 Scalar::Bool(true),
16342 Scalar::Int64(3),
16343 Scalar::Float64(6.0),
16344 Scalar::Null(NullKind::Null),
16345 ];
16346 assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
16347 assert_eq!(super::nancount(&vals), Scalar::Int64(3));
16348 }
16349
16350 #[test]
16351 fn nanops_all_missing_returns_identity() {
16352 let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16353 assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
16354 assert!(super::nanmean(&vals).is_missing());
16355 assert!(super::nanmedian(&vals).is_missing());
16356 assert!(super::nanvar(&vals, 0).is_missing());
16357 assert!(super::nanstd(&vals, 0).is_missing());
16358 }
16359
16360 #[test]
16363 fn timedelta_parse_simple_units() {
16364 use super::Timedelta;
16365 assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
16366 assert_eq!(
16367 Timedelta::parse("2h").unwrap(),
16368 2 * Timedelta::NANOS_PER_HOUR
16369 );
16370 assert_eq!(
16371 Timedelta::parse("30m").unwrap(),
16372 30 * Timedelta::NANOS_PER_MIN
16373 );
16374 assert_eq!(
16375 Timedelta::parse("45s").unwrap(),
16376 45 * Timedelta::NANOS_PER_SEC
16377 );
16378 assert_eq!(
16379 Timedelta::parse("100ms").unwrap(),
16380 100 * Timedelta::NANOS_PER_MILLI
16381 );
16382 assert_eq!(
16383 Timedelta::parse("500us").unwrap(),
16384 500 * Timedelta::NANOS_PER_MICRO
16385 );
16386 assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
16387 }
16388
16389 #[test]
16390 fn timedelta_parse_zero_valued_compound() {
16391 use super::Timedelta;
16392 for s in [
16399 "0 seconds",
16400 "0 second",
16401 "0 sec",
16402 "0s",
16403 "0 days",
16404 "0d",
16405 "0 hours",
16406 "0.0 hours",
16407 "0 minutes",
16408 "0ms",
16409 "0us",
16410 "0ns",
16411 "0",
16412 "0 days 0 seconds",
16413 ] {
16414 assert_eq!(Timedelta::parse(s).unwrap(), 0, "parse({s:?}) should be 0");
16415 }
16416 assert_eq!(Timedelta::parse("-0 seconds").unwrap(), 0);
16418 assert!(Timedelta::parse("0 fortnights").is_err());
16421 assert!(Timedelta::parse("seconds").is_err());
16422 }
16423
16424 #[test]
16425 fn timedelta_parse_compound() {
16426 use super::Timedelta;
16427 let expected = Timedelta::NANOS_PER_DAY
16428 + 2 * Timedelta::NANOS_PER_HOUR
16429 + 30 * Timedelta::NANOS_PER_MIN;
16430 assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
16431 assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
16432 }
16433
16434 #[test]
16435 fn timedelta_parse_leading_sign_spares_the_clock_part() {
16436 use super::Timedelta;
16437 const S: i64 = Timedelta::NANOS_PER_SEC;
16438 assert_eq!(Timedelta::parse("-1 days 02:03:04").unwrap(), -79_016 * S);
16441 assert_eq!(Timedelta::parse("-1 days +02:03:04").unwrap(), -79_016 * S);
16442 assert_eq!(
16443 Timedelta::parse("-3 days +23:59:59.5").unwrap(),
16444 -172_800 * S - S / 2
16445 );
16446 assert_eq!(Timedelta::parse("-0 days 01:00:00").unwrap(), 3_600 * S);
16447 assert_eq!(Timedelta::parse("-1d2h").unwrap(), -93_600 * S);
16449 assert_eq!(Timedelta::parse("-02:03:04").unwrap(), -7_384 * S);
16450 assert!(Timedelta::parse("-1 days -02:03:04").is_err());
16452 assert!(Timedelta::parse("1 days -02:00:00").is_err());
16453 }
16454
16455 #[test]
16456 fn timedelta_parse_iso8601_matches_pandas_tdiso() {
16457 use super::Timedelta;
16458 assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
16460 assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
16461 assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
16462 assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
16463 assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
16464 assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
16465 assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
16467 assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
16468 assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
16469 assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
16470 assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
16471 assert!(Timedelta::parse("P1Y").is_err());
16473 assert!(Timedelta::parse("p1d").is_err());
16474 assert!(Timedelta::parse("P").is_err());
16475 assert!(Timedelta::parse("PT").is_err());
16476 }
16477
16478 #[test]
16479 fn timedelta_parse_time_format() {
16480 use super::Timedelta;
16481 let expected = Timedelta::NANOS_PER_HOUR
16482 + 30 * Timedelta::NANOS_PER_MIN
16483 + 45 * Timedelta::NANOS_PER_SEC;
16484 assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
16485 }
16486
16487 #[test]
16488 fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
16489 use super::{Timedelta, TimedeltaError};
16490 let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
16491 .expect_err("non-ASCII fractional seconds must reject");
16492 assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
16493 }
16494
16495 #[test]
16496 fn timedelta_parse_time_format_rejects_overflow_without_panic() {
16497 use super::{Timedelta, TimedeltaError};
16498 let err = Timedelta::parse("9223372036854775807:00")
16499 .expect_err("oversized hour component must reject");
16500 assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
16501 }
16502
16503 #[test]
16504 fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
16505 use super::{Timedelta, TimedeltaError};
16512 let huge = format!("{} days", "9".repeat(18));
16513 assert!(matches!(
16514 Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
16515 TimedeltaError::Overflow
16516 ));
16517 }
16518
16519 #[test]
16520 fn timedelta_parse_nat() {
16521 use super::Timedelta;
16522 assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
16523 assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
16524 }
16525
16526 #[test]
16527 fn timedelta_parse_negative() {
16528 use super::Timedelta;
16529 assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
16530 }
16531
16532 #[test]
16533 fn timedelta_components() {
16534 use super::Timedelta;
16535 let nanos = Timedelta::NANOS_PER_DAY
16536 + Timedelta::NANOS_PER_HOUR
16537 + Timedelta::NANOS_PER_MIN
16538 + Timedelta::NANOS_PER_SEC
16539 + Timedelta::NANOS_PER_MILLI
16540 + 2 * Timedelta::NANOS_PER_MICRO
16541 + 3;
16542 let comp = Timedelta::components(nanos);
16543 assert_eq!(comp.days, 1);
16544 assert_eq!(comp.hours, 1);
16545 assert_eq!(comp.minutes, 1);
16546 assert_eq!(comp.seconds, 1);
16547 assert_eq!(comp.milliseconds, 1);
16548 assert_eq!(comp.microseconds, 2);
16549 assert_eq!(comp.nanoseconds, 3);
16550 }
16551
16552 #[test]
16553 fn timedelta_negative_components_floor_div() {
16554 use super::Timedelta;
16555 let neg_1s = -Timedelta::NANOS_PER_SEC;
16558 assert_eq!(Timedelta::days(neg_1s), Some(-1));
16559 assert_eq!(Timedelta::seconds(neg_1s), Some(86399));
16560 assert_eq!(Timedelta::microseconds(neg_1s), Some(0));
16561 assert_eq!(Timedelta::nanoseconds(neg_1s), Some(0));
16562 let comp = Timedelta::components(neg_1s);
16563 assert_eq!(
16564 (
16565 comp.days,
16566 comp.hours,
16567 comp.minutes,
16568 comp.seconds,
16569 comp.milliseconds,
16570 comp.microseconds,
16571 comp.nanoseconds
16572 ),
16573 (-1, 23, 59, 59, 0, 0, 0)
16574 );
16575
16576 let neg = -86_401 * Timedelta::NANOS_PER_SEC;
16578 assert_eq!(Timedelta::days(neg), Some(-2));
16579 assert_eq!(Timedelta::seconds(neg), Some(86399));
16580 }
16581
16582 #[test]
16597 fn timedelta_components_are_missing_for_nat_not_zero_406ni() {
16598 use super::Timedelta;
16599 assert_eq!(Timedelta::days(Timedelta::NAT), None);
16600 assert_eq!(Timedelta::seconds(Timedelta::NAT), None);
16601 assert_eq!(Timedelta::microseconds(Timedelta::NAT), None);
16602 assert_eq!(Timedelta::nanoseconds(Timedelta::NAT), None);
16603
16604 let one_day = Timedelta::NANOS_PER_DAY;
16609 assert_eq!(Timedelta::days(one_day), Some(1));
16610 assert_eq!(Timedelta::seconds(one_day), Some(0));
16611 assert_eq!(Timedelta::microseconds(one_day), Some(0));
16612 assert_eq!(Timedelta::nanoseconds(one_day), Some(0));
16613 }
16614
16615 #[test]
16616 fn timedelta_total_seconds() {
16617 use super::Timedelta;
16618 let nanos = 90_000_000_000i64; assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
16620 assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
16621 }
16622
16623 #[test]
16624 fn timedelta_format_basic() {
16625 use super::Timedelta;
16626 assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
16627 assert_eq!(
16628 Timedelta::format(Timedelta::NANOS_PER_DAY),
16629 "1 days 00:00:00"
16630 );
16631 assert_eq!(
16632 Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
16633 "1 days 02:00:00"
16634 );
16635 }
16636
16637 #[test]
16638 fn timedelta_format_subsecond_matches_pandas() {
16639 use super::Timedelta;
16640 assert_eq!(
16644 Timedelta::format(1_500_000_000), "0 days 00:00:01.500000"
16646 );
16647 assert_eq!(
16648 Timedelta::format(1_000_000), "0 days 00:00:00.001000"
16650 );
16651 assert_eq!(
16652 Timedelta::format(123_456_000), "0 days 00:00:00.123456"
16654 );
16655 assert_eq!(
16657 Timedelta::format(500), "0 days 00:00:00.000000500"
16659 );
16660 assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
16661 }
16662
16663 #[test]
16664 fn timedelta_format_negative_uses_python_borrow_form() {
16665 use super::Timedelta;
16666 assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
16670 assert_eq!(
16671 Timedelta::format(-Timedelta::NANOS_PER_DAY),
16672 "-1 days +00:00:00"
16673 );
16674 assert_eq!(
16675 Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
16676 "-2 days +23:00:00"
16677 );
16678 assert_eq!(
16679 Timedelta::format(-1_500_000_000),
16680 "-1 days +23:59:58.500000"
16681 );
16682 assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
16683 assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
16684 }
16685
16686 #[test]
16687 #[ignore = "foreground release attribution harness"]
16688 fn timedelta_format_single_buffer_ab_5ro9h() {
16689 use std::{hint::black_box, time::Instant};
16690
16691 use super::Timedelta;
16692
16693 fn former(nanos: i64) -> String {
16694 if nanos == Timedelta::NAT {
16695 return "NaT".to_string();
16696 }
16697
16698 let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
16699 let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
16700 let hours = rem / Timedelta::NANOS_PER_HOUR;
16701 let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
16702 let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
16703 let frac = rem % Timedelta::NANOS_PER_SEC;
16704
16705 let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
16706 let sep = if days < 0 { "+" } else { "" };
16707 if frac > 0 {
16708 if frac % 1_000 == 0 {
16709 format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
16710 } else {
16711 format!("{days} days {sep}{time_part}.{frac:09}")
16712 }
16713 } else {
16714 format!("{days} days {sep}{time_part}")
16715 }
16716 }
16717
16718 fn candidate(nanos: i64) -> String {
16719 Timedelta::format(nanos)
16720 }
16721
16722 fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
16723 let started = Instant::now();
16724 let mut digest = 0_usize;
16725 for &value in values {
16726 digest = digest.wrapping_add(black_box(format(black_box(value))).len());
16727 }
16728 black_box(digest);
16729 started.elapsed().as_nanos()
16730 }
16731
16732 fn median(samples: &mut [u128]) -> u128 {
16733 samples.sort_unstable();
16734 samples[samples.len() / 2]
16735 }
16736
16737 let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
16738 let values: Vec<i64> = (0..16_384)
16739 .map(|i| {
16740 seed = seed
16741 .wrapping_mul(6_364_136_223_846_793_005)
16742 .wrapping_add(1_442_695_040_888_963_407);
16743 let magnitude = (seed & i64::MAX as u64) as i64;
16744 match i % 4 {
16745 0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16746 1 => magnitude,
16747 2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16748 _ => -magnitude,
16749 }
16750 })
16751 .collect();
16752
16753 for &value in &[
16754 Timedelta::NAT,
16755 0,
16756 1,
16757 -1,
16758 Timedelta::NANOS_PER_DAY,
16759 -Timedelta::NANOS_PER_DAY,
16760 i64::MAX,
16761 i64::MIN + 1,
16762 ] {
16763 assert_eq!(former(value), candidate(value));
16764 }
16765 for &value in &values {
16766 assert_eq!(former(value), candidate(value));
16767 }
16768
16769 for _ in 0..2 {
16770 black_box(elapsed(&values, former));
16771 black_box(elapsed(&values, candidate));
16772 }
16773
16774 let mut former_samples = Vec::with_capacity(18);
16775 let mut candidate_samples = Vec::with_capacity(18);
16776 for block in 0_usize..9 {
16777 if block.is_multiple_of(2) {
16778 former_samples.push(elapsed(&values, former));
16779 candidate_samples.push(elapsed(&values, candidate));
16780 candidate_samples.push(elapsed(&values, candidate));
16781 former_samples.push(elapsed(&values, former));
16782 } else {
16783 candidate_samples.push(elapsed(&values, candidate));
16784 former_samples.push(elapsed(&values, former));
16785 former_samples.push(elapsed(&values, former));
16786 candidate_samples.push(elapsed(&values, candidate));
16787 }
16788 }
16789
16790 let former_p50 = median(&mut former_samples);
16791 let candidate_p50 = median(&mut candidate_samples);
16792 eprintln!(
16793 "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
16794 values.len(),
16795 former_p50 as f64 / candidate_p50 as f64,
16796 );
16797 eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
16798 eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
16799 }
16800
16801 #[test]
16802 fn timedelta_isoformat_basic() {
16803 use super::Timedelta;
16804 assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
16805 assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
16806 assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
16807 assert_eq!(
16808 Timedelta::isoformat(
16809 Timedelta::NANOS_PER_DAY
16810 + 2 * Timedelta::NANOS_PER_HOUR
16811 + 30 * Timedelta::NANOS_PER_MIN
16812 + 45 * Timedelta::NANOS_PER_SEC
16813 ),
16814 "P1DT2H30M45S"
16815 );
16816 assert_eq!(
16817 Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
16818 "P0DT0H0M1.5S"
16819 );
16820 assert_eq!(
16825 Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
16826 "P-2DT23H0M0S"
16827 );
16828 assert_eq!(Timedelta::isoformat(-1), "P-1DT23H59M59.999999999S");
16829 }
16830
16831 #[test]
16832 #[ignore = "foreground release attribution harness"]
16833 fn timedelta_isoformat_single_buffer_ab_7jra1() {
16834 use std::{hint::black_box, time::Instant};
16835
16836 use super::Timedelta;
16837
16838 fn former_impl(nanos: i64) -> String {
16839 if nanos == Timedelta::NAT {
16840 return "NaT".to_string();
16841 }
16842
16843 let negative = nanos < 0;
16844 let abs_nanos = nanos.saturating_abs();
16845 let days = abs_nanos / Timedelta::NANOS_PER_DAY;
16846 let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
16847 let hours = remaining / Timedelta::NANOS_PER_HOUR;
16848 let remaining = remaining % Timedelta::NANOS_PER_HOUR;
16849 let minutes = remaining / Timedelta::NANOS_PER_MIN;
16850 let remaining = remaining % Timedelta::NANOS_PER_MIN;
16851 let seconds = remaining / Timedelta::NANOS_PER_SEC;
16852 let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
16853
16854 let mut result = String::new();
16855 if negative {
16856 result.push('-');
16857 }
16858
16859 result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
16860
16861 if sub_sec_nanos == 0 {
16862 result.push_str(&format!("{seconds}S"));
16863 } else {
16864 let frac = format!("{sub_sec_nanos:09}");
16865 let trimmed = frac.trim_end_matches('0');
16866 result.push_str(&format!("{seconds}.{trimmed}S"));
16867 }
16868
16869 result
16870 }
16871
16872 fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
16873 let start = Instant::now();
16874 let mut digest = 0_usize;
16875 for &value in values {
16876 digest = digest.wrapping_add(black_box(format(black_box(value))).len());
16877 }
16878 black_box(digest);
16879 start.elapsed().as_nanos()
16880 }
16881
16882 fn median(values: &mut [u128]) -> u128 {
16883 values.sort_unstable();
16884 values[values.len() / 2]
16885 }
16886
16887 let mut seed = 0x7d5a_4c31_91e2_b607_u64;
16888 let values: Vec<i64> = (0..16_384)
16889 .map(|i| {
16890 seed = seed
16891 .wrapping_mul(6_364_136_223_846_793_005)
16892 .wrapping_add(1_442_695_040_888_963_407);
16893 let magnitude =
16894 (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
16895 match i % 4 {
16896 0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
16897 1 => magnitude,
16898 2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
16899 _ => -magnitude,
16900 }
16901 })
16902 .collect();
16903
16904 for &value in &[Timedelta::NAT, 0, 1, Timedelta::NANOS_PER_DAY, i64::MAX] {
16908 assert_eq!(former_impl(value), Timedelta::isoformat(value));
16909 }
16910 for &value in values.iter().filter(|value| **value >= 0) {
16911 assert_eq!(former_impl(value), Timedelta::isoformat(value));
16912 }
16913
16914 for _ in 0..2 {
16915 black_box(elapsed(&values, former_impl));
16916 black_box(elapsed(&values, Timedelta::isoformat));
16917 }
16918
16919 let mut former = Vec::with_capacity(18);
16920 let mut candidate = Vec::with_capacity(18);
16921 for block in 0..9 {
16922 if block % 2 == 0 {
16923 former.push(elapsed(&values, former_impl));
16924 candidate.push(elapsed(&values, Timedelta::isoformat));
16925 candidate.push(elapsed(&values, Timedelta::isoformat));
16926 former.push(elapsed(&values, former_impl));
16927 } else {
16928 candidate.push(elapsed(&values, Timedelta::isoformat));
16929 former.push(elapsed(&values, former_impl));
16930 former.push(elapsed(&values, former_impl));
16931 candidate.push(elapsed(&values, Timedelta::isoformat));
16932 }
16933 }
16934
16935 let former_p50 = median(&mut former);
16936 let candidate_p50 = median(&mut candidate);
16937 eprintln!(
16938 "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
16939 values.len(),
16940 former_p50,
16941 candidate_p50,
16942 former_p50 as f64 / candidate_p50 as f64,
16943 former_p50 as f64 / values.len() as f64,
16944 candidate_p50 as f64 / values.len() as f64,
16945 );
16946 eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
16947 eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
16948 }
16949
16950 #[test]
16951 fn timedelta_floor_ceil_round() {
16952 use super::Timedelta;
16953 let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
16954
16955 assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
16957 assert_eq!(Timedelta::floor(nanos, "d"), 0);
16958
16959 assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16961 assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
16962
16963 assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
16965
16966 assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
16968 assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
16969 assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
16970
16971 assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
16973 }
16974
16975 #[test]
16976 fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
16977 use super::Timedelta;
16978
16979 assert_eq!(
16980 Timedelta::floor(-1, "s"),
16981 -Timedelta::NANOS_PER_SEC,
16982 "floor(-1ns, 1s)"
16983 );
16984 assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
16985 assert_eq!(
16986 Timedelta::floor(-1_500_000_000, "s"),
16987 -2 * Timedelta::NANOS_PER_SEC
16988 );
16989 assert_eq!(
16990 Timedelta::ceil(-1_500_000_000, "s"),
16991 -Timedelta::NANOS_PER_SEC
16992 );
16993 assert_eq!(
16994 Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
16995 -Timedelta::NANOS_PER_SEC
16996 );
16997 assert_eq!(
16998 Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
16999 -Timedelta::NANOS_PER_SEC
17000 );
17001 assert_eq!(
17002 Timedelta::floor(1_500_000_000, "s"),
17003 Timedelta::NANOS_PER_SEC
17004 );
17005 assert_eq!(
17006 Timedelta::ceil(1_500_000_000, "s"),
17007 2 * Timedelta::NANOS_PER_SEC
17008 );
17009 }
17010
17011 #[test]
17012 fn timedelta_scalar_dtype() {
17013 let td = Scalar::Timedelta64(86_400_000_000_000);
17014 assert_eq!(td.dtype(), DType::Timedelta64);
17015 }
17016
17017 #[test]
17018 fn timedelta_scalar_is_missing() {
17019 use super::Timedelta;
17020 let valid = Scalar::Timedelta64(1000);
17021 let nat = Scalar::Timedelta64(Timedelta::NAT);
17022 assert!(!valid.is_missing());
17023 assert!(nat.is_missing());
17024 }
17025
17026 #[test]
17027 fn dtype_utf8_deserializes_legacy_aliases() {
17028 let dtype: DType = serde_json::from_str("\"str\"").unwrap();
17029 assert_eq!(dtype, DType::Utf8);
17030
17031 let dtype: DType = serde_json::from_str("\"string\"").unwrap();
17032 assert_eq!(dtype, DType::Utf8);
17033 }
17034
17035 #[test]
17036 fn datetime64_dtype_carries_timezone_00ze3() {
17037 let naive = DType::datetime64_naive();
17038 assert_eq!(naive.timezone(), None);
17039 assert_eq!(naive.display_name(), "datetime64[ns]");
17040
17041 let aware = DType::datetime64_tz("America/New_York");
17042 assert_eq!(aware.timezone(), Some("America/New_York"));
17043 assert_eq!(aware.display_name(), "datetime64[ns, America/New_York]");
17044 assert_ne!(aware, naive, "timezone must participate in dtype identity");
17045
17046 let json = serde_json::to_string(&aware).expect("serialize timezone dtype");
17047 assert_eq!(
17048 serde_json::from_str::<DType>(&json).expect("deserialize timezone dtype"),
17049 aware
17050 );
17051 }
17052
17053 #[test]
17054 fn scalar_utf8_deserializes_legacy_aliases() {
17055 let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
17056 assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
17057
17058 let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
17059 assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
17060 }
17061
17062 #[test]
17063 fn nancumsum_skips_nulls_and_accumulates() {
17064 let values = vec![
17065 Scalar::Float64(1.0),
17066 Scalar::Null(NullKind::NaN),
17067 Scalar::Float64(2.0),
17068 Scalar::Float64(3.0),
17069 ];
17070 let out = super::nancumsum(&values);
17071 assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
17072 assert!(out[1].is_missing());
17073 assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
17074 assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
17075 }
17076
17077 #[test]
17078 fn nancumprod_skips_nulls_and_multiplies() {
17079 let values = vec![
17080 Scalar::Float64(2.0),
17081 Scalar::Null(NullKind::NaN),
17082 Scalar::Float64(3.0),
17083 Scalar::Float64(4.0),
17084 ];
17085 let out = super::nancumprod(&values);
17086 assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17087 assert!(out[1].is_missing());
17088 assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
17089 assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
17090 }
17091
17092 #[test]
17093 fn nancummax_tracks_running_max() {
17094 let values = vec![
17095 Scalar::Float64(1.0),
17096 Scalar::Float64(3.0),
17097 Scalar::Null(NullKind::NaN),
17098 Scalar::Float64(2.0),
17099 Scalar::Float64(5.0),
17100 ];
17101 let out = super::nancummax(&values);
17102 assert_eq!(out[0], Scalar::Float64(1.0));
17103 assert_eq!(out[1], Scalar::Float64(3.0));
17104 assert!(out[2].is_missing());
17105 assert_eq!(out[3], Scalar::Float64(3.0));
17106 assert_eq!(out[4], Scalar::Float64(5.0));
17107 }
17108
17109 #[test]
17110 fn nancummin_tracks_running_min() {
17111 let values = vec![
17112 Scalar::Float64(5.0),
17113 Scalar::Float64(3.0),
17114 Scalar::Null(NullKind::NaN),
17115 Scalar::Float64(4.0),
17116 Scalar::Float64(1.0),
17117 ];
17118 let out = super::nancummin(&values);
17119 assert_eq!(out[0], Scalar::Float64(5.0));
17120 assert_eq!(out[1], Scalar::Float64(3.0));
17121 assert!(out[2].is_missing());
17122 assert_eq!(out[3], Scalar::Float64(3.0));
17123 assert_eq!(out[4], Scalar::Float64(1.0));
17124 }
17125
17126 #[test]
17127 fn nancumsum_timedelta64_preserves_dtype_x0x91() {
17128 let one_hour = 3_600 * 1_000_000_000_i64;
17131 let values = vec![
17132 Scalar::Timedelta64(one_hour),
17133 Scalar::Timedelta64(2 * one_hour),
17134 Scalar::Timedelta64(3 * one_hour),
17135 ];
17136 let out = super::nancumsum(&values);
17137 assert_eq!(out[0], Scalar::Timedelta64(one_hour));
17138 assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
17139 assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
17140 }
17141
17142 #[test]
17143 fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
17144 let one_hour = 3_600 * 1_000_000_000_i64;
17145 let values = vec![
17146 Scalar::Timedelta64(2 * one_hour),
17147 Scalar::Timedelta64(5 * one_hour),
17148 Scalar::Timedelta64(one_hour),
17149 Scalar::Timedelta64(3 * one_hour),
17150 ];
17151 let mx = super::nancummax(&values);
17152 assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
17153 assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
17154 assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
17155 assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
17156
17157 let mn = super::nancummin(&values);
17158 assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
17159 assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
17160 assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
17161 assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
17162 }
17163
17164 #[test]
17165 fn nancumulative_timedelta64_skips_nat_x0x91() {
17166 let one_hour = 3_600 * 1_000_000_000_i64;
17167 let values = vec![
17168 Scalar::Timedelta64(one_hour),
17169 Scalar::Timedelta64(Timedelta::NAT),
17170 Scalar::Timedelta64(2 * one_hour),
17171 ];
17172 let cs = super::nancumsum(&values);
17173 assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
17174 assert!(cs[1].is_missing());
17175 assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
17176 }
17177
17178 #[test]
17179 fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
17180 fn next(seed: &mut u64) -> u64 {
17183 *seed = seed
17184 .wrapping_mul(3202034522624059733)
17185 .wrapping_add(4354685564936845319);
17186 *seed
17187 }
17188
17189 fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
17190 assert_eq!(
17191 actual.len(),
17192 expected.len(),
17193 "case={case} family={family} op={op}: length mismatch"
17194 );
17195 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
17196 assert!(
17197 actual.semantic_eq(expected),
17198 "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
17199 );
17200 }
17201 }
17202
17203 fn expected_numeric(
17204 values: &[Scalar],
17205 ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
17206 let mut sum = Vec::with_capacity(values.len());
17207 let mut prod = Vec::with_capacity(values.len());
17208 let mut max = Vec::with_capacity(values.len());
17209 let mut min = Vec::with_capacity(values.len());
17210 let mut running_sum = 0.0_f64;
17211 let mut running_prod = 1.0_f64;
17212 let mut running_max: Option<f64> = None;
17213 let mut running_min: Option<f64> = None;
17214
17215 for value in values {
17216 if value.is_missing() {
17217 sum.push(Scalar::Null(NullKind::NaN));
17218 prod.push(Scalar::Null(NullKind::NaN));
17219 max.push(Scalar::Null(NullKind::NaN));
17220 min.push(Scalar::Null(NullKind::NaN));
17221 continue;
17222 }
17223 let Ok(value) = value.to_f64() else {
17224 sum.push(Scalar::Null(NullKind::NaN));
17225 prod.push(Scalar::Null(NullKind::NaN));
17226 max.push(Scalar::Null(NullKind::NaN));
17227 min.push(Scalar::Null(NullKind::NaN));
17228 continue;
17229 };
17230 if value.is_nan() {
17231 sum.push(Scalar::Null(NullKind::NaN));
17232 prod.push(Scalar::Null(NullKind::NaN));
17233 max.push(Scalar::Null(NullKind::NaN));
17234 min.push(Scalar::Null(NullKind::NaN));
17235 continue;
17236 }
17237 running_sum += value;
17238 running_prod *= value;
17239 running_max = Some(running_max.map_or(value, |current| current.max(value)));
17240 running_min = Some(running_min.map_or(value, |current| current.min(value)));
17241 sum.push(Scalar::Float64(running_sum));
17242 prod.push(Scalar::Float64(running_prod));
17243 max.push(Scalar::Float64(running_max.expect("initialized")));
17244 min.push(Scalar::Float64(running_min.expect("initialized")));
17245 }
17246
17247 (sum, prod, max, min)
17248 }
17249
17250 fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
17251 let mut sum = Vec::with_capacity(values.len());
17252 let mut max = Vec::with_capacity(values.len());
17253 let mut min = Vec::with_capacity(values.len());
17254 let mut running_sum = 0_i128;
17255 let mut running_max: Option<i64> = None;
17256 let mut running_min: Option<i64> = None;
17257
17258 for value in values {
17259 if value.is_missing() {
17260 sum.push(Scalar::Null(NullKind::NaT));
17261 max.push(Scalar::Null(NullKind::NaT));
17262 min.push(Scalar::Null(NullKind::NaT));
17263 continue;
17264 }
17265 let Scalar::Timedelta64(ns) = value else {
17266 sum.push(Scalar::Null(NullKind::NaT));
17267 max.push(Scalar::Null(NullKind::NaT));
17268 min.push(Scalar::Null(NullKind::NaT));
17269 continue;
17270 };
17271 running_sum = running_sum.saturating_add(i128::from(*ns));
17272 running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
17273 running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
17274 sum.push(super::timedelta_ns_to_scalar(running_sum));
17277 max.push(Scalar::Timedelta64(running_max.expect("initialized")));
17278 min.push(Scalar::Timedelta64(running_min.expect("initialized")));
17279 }
17280
17281 (sum, max, min)
17282 }
17283
17284 let mut seed = 0xc0de_c63a_5eed_0421_u64;
17285 for case in 0..260 {
17286 let len = (next(&mut seed) % 89 + 1) as usize;
17287
17288 let mut numeric = Vec::with_capacity(len);
17289 numeric.push(Scalar::Int64(case as i64 - 130));
17290 for _ in 1..len {
17291 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17292 numeric.push(match next(&mut seed) % 8 {
17293 0 => Scalar::Null(NullKind::Null),
17294 1 => Scalar::Null(NullKind::NaN),
17295 2 => Scalar::Float64(f64::NAN),
17296 3 => Scalar::Bool(raw & 1 == 0),
17297 4 => Scalar::Int64(raw % 251),
17298 5 => Scalar::Float64(raw as f64 / 79.0),
17299 6 => Scalar::Float64(0.0),
17300 _ => Scalar::Float64(-0.0),
17301 });
17302 }
17303 let (sum, prod, max, min) = expected_numeric(&numeric);
17304 assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
17305 assert_vec(
17306 case,
17307 "numeric",
17308 "cumprod",
17309 &super::nancumprod(&numeric),
17310 &prod,
17311 );
17312 assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
17313 assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
17314
17315 let mut timedeltas = Vec::with_capacity(len);
17316 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17317 for _ in 1..len {
17318 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17319 timedeltas.push(match next(&mut seed) % 7 {
17320 0 => Scalar::Null(NullKind::Null),
17321 1 => Scalar::Timedelta64(i64::MIN),
17322 _ => Scalar::Timedelta64(raw),
17323 });
17324 }
17325 let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
17326 assert_vec(
17327 case,
17328 "timedelta",
17329 "cumsum",
17330 &super::nancumsum(&timedeltas),
17331 &td_sum,
17332 );
17333 assert_vec(
17334 case,
17335 "timedelta",
17336 "cummax",
17337 &super::nancummax(&timedeltas),
17338 &td_max,
17339 );
17340 assert_vec(
17341 case,
17342 "timedelta",
17343 "cummin",
17344 &super::nancummin(&timedeltas),
17345 &td_min,
17346 );
17347 }
17348 }
17349
17350 #[test]
17351 fn nanquantile_linear_interpolation_matches_numpy() {
17352 let values = vec![
17353 Scalar::Float64(1.0),
17354 Scalar::Float64(2.0),
17355 Scalar::Float64(3.0),
17356 Scalar::Float64(4.0),
17357 Scalar::Float64(5.0),
17358 ];
17359 let q = super::nanquantile(&values, 0.5);
17361 assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
17362 let q25 = super::nanquantile(&values, 0.25);
17364 assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17365 }
17366
17367 #[test]
17368 fn nanquantile_ignores_nulls() {
17369 let values = vec![
17370 Scalar::Float64(1.0),
17371 Scalar::Null(NullKind::NaN),
17372 Scalar::Float64(3.0),
17373 ];
17374 let q = super::nanquantile(&values, 0.5);
17375 assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
17376 }
17377
17378 #[test]
17379 fn nanquantile_empty_and_out_of_range_yield_null() {
17380 assert!(super::nanquantile(&[], 0.5).is_missing());
17381 assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
17382 assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
17383 }
17384
17385 #[test]
17386 fn nanquantile_timedelta64_preserves_dtype_5djk7() {
17387 let one_hour: i64 = 3_600 * 1_000_000_000;
17390 let vals = vec![
17391 Scalar::Timedelta64(one_hour),
17392 Scalar::Timedelta64(2 * one_hour),
17393 Scalar::Timedelta64(3 * one_hour),
17394 Scalar::Timedelta64(4 * one_hour),
17395 Scalar::Timedelta64(5 * one_hour),
17396 ];
17397 assert_eq!(
17398 super::nanquantile(&vals, 0.5),
17399 Scalar::Timedelta64(3 * one_hour)
17400 );
17401 assert_eq!(
17402 super::nanquantile(&vals, 0.0),
17403 Scalar::Timedelta64(one_hour)
17404 );
17405 assert_eq!(
17406 super::nanquantile(&vals, 1.0),
17407 Scalar::Timedelta64(5 * one_hour)
17408 );
17409 }
17410
17411 #[test]
17412 fn nanquantile_timedelta64_linear_interpolation_5djk7() {
17413 let one_hour: i64 = 3_600 * 1_000_000_000;
17414 let vals = vec![
17415 Scalar::Timedelta64(one_hour),
17416 Scalar::Timedelta64(3 * one_hour),
17417 ];
17418 assert_eq!(
17420 super::nanquantile(&vals, 0.5),
17421 Scalar::Timedelta64(2 * one_hour)
17422 );
17423 }
17424
17425 #[test]
17426 fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
17427 fn next(seed: &mut u64) -> u64 {
17430 *seed = seed
17431 .wrapping_mul(3202034522624059733)
17432 .wrapping_add(4354685564936845319);
17433 *seed
17434 }
17435
17436 fn interpolated(sorted: &[f64], q: f64) -> f64 {
17437 if sorted.len() == 1 {
17438 return sorted[0];
17439 }
17440 let pos = q * (sorted.len() - 1) as f64;
17441 let lo = pos.floor() as usize;
17442 let hi = pos.ceil() as usize;
17443 if lo == hi {
17444 sorted[lo]
17445 } else {
17446 let weight = pos - lo as f64;
17447 sorted[lo] + (sorted[hi] - sorted[lo]) * weight
17448 }
17449 }
17450
17451 fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
17452 if !(0.0..=1.0).contains(&q) {
17453 return Scalar::Null(NullKind::NaN);
17454 }
17455 let mut samples = values
17456 .iter()
17457 .filter(|value| !value.is_missing())
17458 .filter_map(|value| value.to_f64().ok())
17459 .collect::<Vec<_>>();
17460 if samples.is_empty() {
17461 return Scalar::Null(NullKind::NaN);
17462 }
17463 samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
17464 Scalar::Float64(interpolated(&samples, q))
17465 }
17466
17467 fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
17468 if !(0.0..=1.0).contains(&q) {
17469 return Scalar::Null(NullKind::NaN);
17470 }
17471 let mut samples = values
17472 .iter()
17473 .filter_map(|value| match value {
17474 Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
17475 _ => None,
17476 })
17477 .collect::<Vec<_>>();
17478 if samples.is_empty() {
17479 return Scalar::Timedelta64(Timedelta::NAT);
17482 }
17483 samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
17484 Scalar::Timedelta64(interpolated(&samples, q) as i64)
17485 }
17486
17487 fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
17488 let actual = super::nanquantile(values, q);
17489 assert!(
17490 actual.semantic_eq(&expected),
17491 "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
17492 );
17493 }
17494
17495 let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17496 assert_quantile(
17497 usize::MAX,
17498 "numeric_all_missing",
17499 &numeric_all_missing,
17500 0.5,
17501 expected_numeric(&numeric_all_missing, 0.5),
17502 );
17503 assert_quantile(
17504 usize::MAX - 1,
17505 "numeric_out_of_range",
17506 &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
17507 1.25,
17508 Scalar::Null(NullKind::NaN),
17509 );
17510
17511 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17512 assert_quantile(
17513 usize::MAX - 2,
17514 "timedelta_all_missing",
17515 &td_all_missing,
17516 0.5,
17517 expected_timedelta(&td_all_missing, 0.5),
17518 );
17519 assert_quantile(
17520 usize::MAX - 3,
17521 "timedelta_out_of_range",
17522 &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
17523 -0.25,
17524 Scalar::Null(NullKind::NaN),
17525 );
17526
17527 let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
17528 for case in 0..260 {
17529 let len = (next(&mut seed) % 83 + 1) as usize;
17530 let q = match next(&mut seed) % 8 {
17531 0 => 0.0,
17532 1 => 0.25,
17533 2 => 0.5,
17534 3 => 0.75,
17535 4 => 1.0,
17536 _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
17537 };
17538
17539 let mut numeric = Vec::with_capacity(len);
17540 numeric.push(Scalar::Int64(case as i64 - 130));
17541 for _ in 1..len {
17542 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17543 numeric.push(match next(&mut seed) % 8 {
17544 0 => Scalar::Null(NullKind::Null),
17545 1 => Scalar::Null(NullKind::NaN),
17546 2 => Scalar::Float64(f64::NAN),
17547 3 => Scalar::Bool(raw & 1 == 0),
17548 4 => Scalar::Int64(raw % 251),
17549 5 => Scalar::Float64(raw as f64 / 67.0),
17550 6 => Scalar::Float64(0.0),
17551 _ => Scalar::Float64(-0.0),
17552 });
17553 }
17554 assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
17555
17556 let mut timedeltas = Vec::with_capacity(len);
17557 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17558 for _ in 1..len {
17559 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17560 timedeltas.push(match next(&mut seed) % 7 {
17561 0 => Scalar::Null(NullKind::Null),
17562 1 => Scalar::Timedelta64(i64::MIN),
17563 _ => Scalar::Timedelta64(raw),
17564 });
17565 }
17566 assert_quantile(
17567 case,
17568 "timedelta",
17569 &timedeltas,
17570 q,
17571 expected_timedelta(&timedeltas, q),
17572 );
17573 }
17574 }
17575
17576 #[test]
17577 fn nanargmax_returns_first_position() {
17578 let values = vec![
17579 Scalar::Float64(1.0),
17580 Scalar::Null(NullKind::NaN),
17581 Scalar::Float64(4.0),
17582 Scalar::Float64(4.0),
17583 Scalar::Float64(2.0),
17584 ];
17585 assert_eq!(super::nanargmax(&values), Some(2));
17586 }
17587
17588 #[test]
17589 fn nanargmin_returns_first_position() {
17590 let values = vec![
17591 Scalar::Float64(3.0),
17592 Scalar::Null(NullKind::NaN),
17593 Scalar::Float64(1.0),
17594 Scalar::Float64(1.0),
17595 ];
17596 assert_eq!(super::nanargmin(&values), Some(2));
17597 }
17598
17599 #[test]
17600 fn nanargmax_all_missing_returns_none() {
17601 let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
17602 assert_eq!(super::nanargmax(&values), None);
17603 assert_eq!(super::nanargmin(&values), None);
17604 }
17605
17606 #[test]
17607 fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
17608 fn next(seed: &mut u64) -> u64 {
17611 *seed = seed
17612 .wrapping_mul(2862933555777941757)
17613 .wrapping_add(3037000493);
17614 *seed
17615 }
17616
17617 fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
17618 let mut best: Option<(usize, f64)> = None;
17619 for (idx, value) in values.iter().enumerate() {
17620 if value.is_missing() {
17621 continue;
17622 }
17623 let Ok(value) = value.to_f64() else {
17624 continue;
17625 };
17626 if value.is_nan() {
17627 continue;
17628 }
17629 match best {
17630 None => best = Some((idx, value)),
17631 Some((_, current))
17632 if (find_max && value > current) || (!find_max && value < current) =>
17633 {
17634 best = Some((idx, value));
17635 }
17636 _ => {}
17637 }
17638 }
17639 best.map(|(idx, _)| idx)
17640 }
17641
17642 fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
17643 let mut best: Option<(usize, i64)> = None;
17644 for (idx, value) in values.iter().enumerate() {
17645 if value.is_missing() {
17646 continue;
17647 }
17648 let Scalar::Timedelta64(ns) = value else {
17649 continue;
17650 };
17651 match best {
17652 None => best = Some((idx, *ns)),
17653 Some((_, current))
17654 if (find_max && *ns > current) || (!find_max && *ns < current) =>
17655 {
17656 best = Some((idx, *ns));
17657 }
17658 _ => {}
17659 }
17660 }
17661 best.map(|(idx, _)| idx)
17662 }
17663
17664 fn assert_args(
17665 case: usize,
17666 family: &str,
17667 values: &[Scalar],
17668 expected_min: Option<usize>,
17669 expected_max: Option<usize>,
17670 ) {
17671 assert_eq!(
17672 super::nanargmin(values),
17673 expected_min,
17674 "case={case} family={family}: nanargmin mismatch for {values:?}"
17675 );
17676 assert_eq!(
17677 super::nanargmax(values),
17678 expected_max,
17679 "case={case} family={family}: nanargmax mismatch for {values:?}"
17680 );
17681 }
17682
17683 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17684 assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
17685 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17686 assert_args(
17687 usize::MAX - 1,
17688 "timedelta_all_missing",
17689 &td_all_missing,
17690 None,
17691 None,
17692 );
17693 let positive_int64_endpoint = [
17694 Scalar::Int64(i64::MAX - 1),
17695 Scalar::Null(NullKind::Null),
17696 Scalar::Int64(i64::MAX),
17697 ];
17698 assert_args(
17699 usize::MAX - 2,
17700 "int64_positive_endpoint_exact_order",
17701 &positive_int64_endpoint,
17702 Some(0),
17703 Some(2),
17704 );
17705 let negative_int64_endpoint = [
17706 Scalar::Int64(i64::MIN + 2),
17707 Scalar::Null(NullKind::NaN),
17708 Scalar::Int64(i64::MIN + 1),
17709 ];
17710 assert_args(
17711 usize::MAX - 3,
17712 "int64_negative_endpoint_exact_order",
17713 &negative_int64_endpoint,
17714 Some(2),
17715 Some(0),
17716 );
17717
17718 let mut seed = 0xa126_5eed_ed9e_u64;
17719 for case in 0..260 {
17720 let len = (next(&mut seed) % 83 + 1) as usize;
17721
17722 let mut numeric = Vec::with_capacity(len);
17723 numeric.push(Scalar::Int64(case as i64 - 130));
17724 if len > 1 {
17725 numeric.push(Scalar::Int64(case as i64 - 130));
17726 }
17727 for _ in numeric.len()..len {
17728 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17729 numeric.push(match next(&mut seed) % 9 {
17730 0 => Scalar::Null(NullKind::Null),
17731 1 => Scalar::Null(NullKind::NaN),
17732 2 => Scalar::Float64(f64::NAN),
17733 3 => Scalar::Bool(raw & 1 == 0),
17734 4 => Scalar::Int64(raw % 211),
17735 5 => Scalar::Float64(raw as f64 / 47.0),
17736 6 => Scalar::Float64(0.0),
17737 7 => Scalar::Float64(-0.0),
17738 _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
17739 });
17740 }
17741 assert_args(
17742 case,
17743 "numeric",
17744 &numeric,
17745 expected_numeric(&numeric, false),
17746 expected_numeric(&numeric, true),
17747 );
17748
17749 let mut timedeltas = Vec::with_capacity(len);
17750 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17751 if len > 1 {
17752 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17753 }
17754 for _ in timedeltas.len()..len {
17755 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17756 timedeltas.push(match next(&mut seed) % 7 {
17757 0 => Scalar::Null(NullKind::Null),
17758 1 => Scalar::Timedelta64(i64::MIN),
17759 _ => Scalar::Timedelta64(raw),
17760 });
17761 }
17762 assert_args(
17763 case,
17764 "timedelta",
17765 &timedeltas,
17766 expected_timedelta(&timedeltas, false),
17767 expected_timedelta(&timedeltas, true),
17768 );
17769 }
17770 }
17771
17772 #[test]
17773 fn nansem_matches_std_over_sqrt_n() {
17774 let values = vec![
17775 Scalar::Float64(2.0),
17776 Scalar::Float64(4.0),
17777 Scalar::Float64(4.0),
17778 Scalar::Float64(4.0),
17779 Scalar::Float64(5.0),
17780 Scalar::Float64(5.0),
17781 Scalar::Float64(7.0),
17782 Scalar::Float64(9.0),
17783 ];
17784 let sem = super::nansem(&values, 1);
17786 assert!(matches!(sem, Scalar::Float64(_)));
17787 let Scalar::Float64(v) = sem else {
17788 return;
17789 };
17790 assert!((v - 0.7559289460184544).abs() < 1e-9);
17791 }
17792
17793 #[test]
17794 fn nansem_grouped_is_sqrt_var_over_n_7hxqv() {
17795 let values = [
17798 Scalar::Float64(1.0),
17799 Scalar::Null(NullKind::NaN),
17800 Scalar::Float64(4.0),
17801 ];
17802 assert_eq!(super::nansem_grouped(&values, 1), Scalar::Float64(1.5));
17803 assert_eq!(
17805 super::nansem(&values, 1),
17806 Scalar::Float64(1.499_999_999_999_999_8)
17807 );
17808 assert!(super::nansem_grouped(&values[..1], 1).is_missing());
17809 }
17810
17811 #[test]
17812 fn grouped_reducers_add_as_pandas_group_kernels_xhogl() {
17813 let tenths: Vec<Scalar> = (0..10).map(|_| Scalar::Float64(0.1)).collect();
17817 assert_eq!(super::nansum_grouped(&tenths), Scalar::Float64(1.0));
17818 assert_eq!(super::nanmean_grouped(&tenths), Scalar::Float64(0.1));
17819 assert_eq!(super::nanvar_grouped(&tenths, 1), Scalar::Float64(0.0));
17820 assert_eq!(super::nanstd_grouped(&tenths, 1), Scalar::Float64(0.0));
17821 assert_eq!(
17823 super::nansum(&tenths),
17824 Scalar::Float64(0.999_999_999_999_999_9)
17825 );
17826 let mut sum = super::KahanSum::default();
17828 for value in [1.0, f64::INFINITY, 2.0] {
17829 sum.add(value);
17830 }
17831 assert_eq!(sum.sum(), f64::INFINITY);
17832 let gapped = [
17834 Scalar::Float64(1.0),
17835 Scalar::Null(NullKind::NaN),
17836 Scalar::Float64(4.0),
17837 ];
17838 assert_eq!(super::nanmean_grouped(&gapped), Scalar::Float64(2.5));
17839 assert_eq!(super::nanvar_grouped(&gapped, 1), Scalar::Float64(4.5));
17840 assert!(super::nanvar_grouped(&gapped[..1], 1).is_missing());
17841 let spans = [Scalar::Timedelta64(1), Scalar::Timedelta64(2)];
17843 assert_eq!(super::nansum_grouped(&spans), super::nansum(&spans));
17844 }
17845
17846 #[test]
17847 fn grouped_skew_is_pandas_online_group_skew_vjfq9() {
17848 let group = [
17851 Scalar::Float64(1.0),
17852 Scalar::Null(NullKind::NaN),
17853 Scalar::Float64(4.0),
17854 Scalar::Float64(8.0),
17855 ];
17856 assert_eq!(
17857 super::nanskew_grouped(&group),
17858 Scalar::Float64(0.423_273_160_268_006_15)
17859 );
17860 let long: Vec<Scalar> = (0..2922_i32)
17863 .map(|i| Scalar::Float64(f64::from((i * 7919) % 1000) / 7.0))
17864 .collect();
17865 let glibc_pow = Scalar::Float64(-0.002_284_383_734_800_801_4);
17866 if cfg!(all(target_os = "linux", target_env = "gnu")) {
17872 assert_eq!(super::nanskew_grouped(&long), glibc_pow);
17873 } else {
17874 let sqrt = Scalar::Float64(-0.002_284_383_734_800_802);
17875 assert!([glibc_pow, sqrt].contains(&super::nanskew_grouped(&long)));
17876 }
17877 let constant = [7.0; 3].map(Scalar::Float64);
17880 assert_eq!(super::nanskew_grouped(&constant), Scalar::Float64(0.0));
17881 assert!(super::nanskew_grouped(&group[..2]).is_missing());
17882 let with_inf = [1.0, f64::INFINITY, 2.0, 5.0].map(Scalar::Float64);
17883 assert!(super::nanskew_grouped(&with_inf).is_missing());
17884 }
17885
17886 #[test]
17887 fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
17888 fn former(values: &[Scalar], ddof: usize) -> Scalar {
17889 let nums = super::collect_finite(values);
17890 if nums.len() <= ddof {
17891 return Scalar::Null(NullKind::NaN);
17892 }
17893 match super::nanstd(values, ddof) {
17894 Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17895 other => other,
17896 }
17897 }
17898
17899 fn assert_same_bits(values: &[Scalar], ddof: usize) {
17900 let expected = former(values, ddof);
17901 let actual = super::nansem(values, ddof);
17902 match (&expected, &actual) {
17903 (Scalar::Float64(expected), Scalar::Float64(actual)) => {
17904 assert_eq!(
17905 actual.to_bits(),
17906 expected.to_bits(),
17907 "values={values:?} ddof={ddof}"
17908 );
17909 }
17910 _ => assert!(
17911 actual.semantic_eq(&expected),
17912 "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
17913 ),
17914 }
17915 }
17916
17917 let mut generated = Vec::with_capacity(4_096);
17918 for idx in 0..4_096_i64 {
17919 generated.push(match idx % 257 {
17920 0 => Scalar::Null(NullKind::NaN),
17921 1 => Scalar::Float64(-0.0),
17922 2 => Scalar::Float64(0.0),
17923 _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
17924 _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
17925 });
17926 }
17927
17928 let cases = [
17929 Vec::new(),
17930 vec![Scalar::Int64(1)],
17931 vec![
17932 Scalar::Null(NullKind::Null),
17933 Scalar::Float64(f64::NAN),
17934 Scalar::Int64(i64::MIN),
17935 Scalar::Int64(i64::MAX),
17936 Scalar::Float64(-0.0),
17937 Scalar::Float64(0.0),
17938 ],
17939 generated,
17940 ];
17941 for values in &cases {
17942 for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
17943 assert_same_bits(values, ddof);
17944 }
17945 }
17946 }
17947
17948 #[test]
17949 #[ignore = "foreground release A/B harness"]
17950 fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
17951 const ROWS: usize = 262_144;
17952 const BATCH: usize = 8;
17953 const BLOCKS: usize = 9;
17954 const PRECONDITION_CALLS: usize = 2;
17955
17956 fn former(values: &[Scalar], ddof: usize) -> Scalar {
17957 let nums = super::collect_finite(values);
17958 if nums.len() <= ddof {
17959 return Scalar::Null(NullKind::NaN);
17960 }
17961 match super::nanstd(values, ddof) {
17962 Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
17963 other => other,
17964 }
17965 }
17966
17967 fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
17968 let values = std::hint::black_box(values);
17969 if candidate {
17970 super::nansem(values, 1)
17971 } else {
17972 former(values, 1)
17973 }
17974 }
17975
17976 fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
17977 for _ in 0..PRECONDITION_CALLS {
17978 std::hint::black_box(evaluate(values, candidate));
17979 }
17980 let started = std::time::Instant::now();
17981 for _ in 0..BATCH {
17982 std::hint::black_box(evaluate(values, candidate));
17983 }
17984 started.elapsed().as_nanos()
17985 }
17986
17987 fn median(mut samples: Vec<u128>) -> u128 {
17988 samples.sort_unstable();
17989 samples[samples.len() / 2]
17990 }
17991
17992 fn spread(a: u128, b: u128) -> f64 {
17993 a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
17994 }
17995
17996 let values = (0..ROWS)
17997 .map(|idx| {
17998 if idx % 257 == 0 {
17999 Scalar::Null(NullKind::NaN)
18000 } else {
18001 Scalar::Int64((idx % 8_191) as i64 - 4_095)
18002 }
18003 })
18004 .collect::<Vec<_>>();
18005
18006 let expected_bits = match former(&values, 1) {
18007 Scalar::Float64(value) => Some(value.to_bits()),
18008 _ => None,
18009 };
18010 let actual_bits = match super::nansem(&values, 1) {
18011 Scalar::Float64(value) => Some(value.to_bits()),
18012 _ => None,
18013 };
18014 assert!(
18015 expected_bits.is_some(),
18016 "numeric nansem must return Float64"
18017 );
18018 assert_eq!(actual_bits, expected_bits, "A/B output bits");
18019
18020 std::hint::black_box(evaluate(&values, false));
18021 std::hint::black_box(evaluate(&values, true));
18022
18023 let body_started = std::time::Instant::now();
18024 let mut former_a = Vec::with_capacity(BLOCKS);
18025 let mut former_b = Vec::with_capacity(BLOCKS);
18026 let mut candidate_a = Vec::with_capacity(BLOCKS);
18027 let mut candidate_b = Vec::with_capacity(BLOCKS);
18028 for block in 0..BLOCKS {
18029 let order = if block % 2 == 0 {
18030 [(false, 0), (true, 0), (true, 1), (false, 1)]
18031 } else {
18032 [(true, 1), (false, 1), (false, 0), (true, 0)]
18033 };
18034 for (candidate, duplicate) in order {
18035 let elapsed = elapsed_ns(&values, candidate);
18036 match (candidate, duplicate) {
18037 (false, 0) => former_a.push(elapsed),
18038 (false, _) => former_b.push(elapsed),
18039 (true, 0) => candidate_a.push(elapsed),
18040 (true, _) => candidate_b.push(elapsed),
18041 }
18042 }
18043 }
18044
18045 let former_a = median(former_a) / BATCH as u128;
18046 let former_b = median(former_b) / BATCH as u128;
18047 let candidate_a = median(candidate_a) / BATCH as u128;
18048 let candidate_b = median(candidate_b) / BATCH as u128;
18049 let former_mean = (former_a + former_b) as f64 / 2.0;
18050 let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
18051 println!(
18052 "NANSEM_SINGLE_BUFFER_AB rows={ROWS} former_a_ns={former_a} former_b_ns={former_b} candidate_a_ns={candidate_a} candidate_b_ns={candidate_b} former_spread={:.6} candidate_spread={:.6} speedup={:.6} body_seconds={:.6}",
18053 spread(former_a, former_b),
18054 spread(candidate_a, candidate_b),
18055 former_mean / candidate_mean,
18056 body_started.elapsed().as_secs_f64()
18057 );
18058 }
18059
18060 #[test]
18061 fn nansem_empty_returns_null() {
18062 assert!(super::nansem(&[], 1).is_missing());
18063 assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
18064 }
18065
18066 #[test]
18067 fn nanptp_returns_max_minus_min() {
18068 let values = vec![
18069 Scalar::Float64(3.0),
18070 Scalar::Null(NullKind::NaN),
18071 Scalar::Float64(7.0),
18072 Scalar::Float64(1.0),
18073 ];
18074 assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
18075 }
18076
18077 #[test]
18078 fn nanptp_empty_returns_null() {
18079 assert!(super::nanptp(&[]).is_missing());
18080 assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
18081 }
18082
18083 #[test]
18084 fn nanptp_timedelta64_preserves_dtype_u2g0r() {
18085 let one_hour: i64 = 3_600 * 1_000_000_000;
18087 let values = vec![
18088 Scalar::Timedelta64(one_hour),
18089 Scalar::Timedelta64(5 * one_hour),
18090 Scalar::Timedelta64(2 * one_hour),
18091 ];
18092 assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
18093 }
18094
18095 #[test]
18096 fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
18097 fn next(seed: &mut u64) -> u64 {
18100 *seed = seed
18101 .wrapping_mul(3202034522624059733)
18102 .wrapping_add(4354685564936845319);
18103 *seed
18104 }
18105
18106 fn expected_numeric(values: &[Scalar]) -> Scalar {
18107 let mut lo = f64::INFINITY;
18108 let mut hi = f64::NEG_INFINITY;
18109 let mut seen = false;
18110 for value in values {
18111 if value.is_missing() {
18112 continue;
18113 }
18114 if let Ok(value) = value.to_f64() {
18115 seen = true;
18116 lo = lo.min(value);
18117 hi = hi.max(value);
18118 }
18119 }
18120 if seen {
18121 Scalar::Float64(hi - lo)
18122 } else {
18123 Scalar::Null(NullKind::NaN)
18124 }
18125 }
18126
18127 fn expected_timedelta(values: &[Scalar]) -> Scalar {
18128 let mut lo = i64::MAX;
18129 let mut hi = i64::MIN;
18130 let mut seen = false;
18131 for value in values {
18132 if let Scalar::Timedelta64(ns) = value
18133 && !value.is_missing()
18134 {
18135 seen = true;
18136 lo = lo.min(*ns);
18137 hi = hi.max(*ns);
18138 }
18139 }
18140 if seen {
18141 Scalar::Timedelta64(hi - lo)
18142 } else {
18143 Scalar::Null(NullKind::NaN)
18144 }
18145 }
18146
18147 fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
18148 let actual = super::nanptp(values);
18149 assert!(
18150 actual.semantic_eq(&expected),
18151 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
18152 );
18153 }
18154
18155 assert_ptp(
18156 usize::MAX,
18157 "numeric_all_missing",
18158 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
18159 Scalar::Null(NullKind::NaN),
18160 );
18161 assert_ptp(
18162 usize::MAX - 1,
18163 "timedelta_all_missing",
18164 &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
18165 Scalar::Null(NullKind::NaN),
18166 );
18167 let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
18168 assert_ptp(
18169 usize::MAX - 2,
18170 "timedelta_one_ns_range_beyond_f64_exactness",
18171 &[
18172 Scalar::Timedelta64(beyond_f64_exact_ns),
18173 Scalar::Timedelta64(beyond_f64_exact_ns - 1),
18174 Scalar::Timedelta64(Timedelta::NAT),
18175 ],
18176 Scalar::Timedelta64(1),
18177 );
18178
18179 let mut seed = 0xa22f_17ed_57a7_15e5_u64;
18180 for case in 0..260 {
18181 let len = (next(&mut seed) % 83 + 1) as usize;
18182
18183 let mut numeric = Vec::with_capacity(len);
18184 numeric.push(Scalar::Int64(case as i64 - 130));
18185 for _ in 1..len {
18186 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
18187 numeric.push(match next(&mut seed) % 9 {
18188 0 => Scalar::Null(NullKind::Null),
18189 1 => Scalar::Null(NullKind::NaN),
18190 2 => Scalar::Float64(f64::NAN),
18191 3 => Scalar::Bool(raw & 1 == 0),
18192 4 => Scalar::Int64(raw),
18193 5 => Scalar::Float64(raw as f64 / 53.0),
18194 6 => Scalar::Float64(0.0),
18195 7 => Scalar::Float64(-0.0),
18196 _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
18197 });
18198 }
18199 assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
18200
18201 let mut timedeltas = Vec::with_capacity(len);
18202 timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
18203 for _ in 1..len {
18204 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
18205 timedeltas.push(match next(&mut seed) % 7 {
18206 0 => Scalar::Null(NullKind::Null),
18207 1 => Scalar::Timedelta64(i64::MIN),
18208 _ => Scalar::Timedelta64(raw),
18209 });
18210 }
18211 assert_ptp(
18212 case,
18213 "timedelta",
18214 &timedeltas,
18215 expected_timedelta(&timedeltas),
18216 );
18217 }
18218 }
18219
18220 #[test]
18221 fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
18222 let one_hour: i64 = 3_600 * 1_000_000_000;
18225 let values = vec![
18226 Scalar::Timedelta64(2 * one_hour),
18227 Scalar::Timedelta64(5 * one_hour),
18228 Scalar::Timedelta64(one_hour),
18229 Scalar::Timedelta64(3 * one_hour),
18230 ];
18231 assert_eq!(super::nanargmax(&values), Some(1));
18232 assert_eq!(super::nanargmin(&values), Some(2));
18233 }
18234
18235 #[test]
18236 fn nanprod_timedelta64_returns_null_szq6a() {
18237 let one_hour: i64 = 3_600 * 1_000_000_000;
18241 let values = vec![
18242 Scalar::Timedelta64(2 * one_hour),
18243 Scalar::Timedelta64(3 * one_hour),
18244 ];
18245 assert!(super::nanprod(&values).is_missing());
18246 }
18247
18248 #[test]
18249 fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
18250 fn next(seed: &mut u64) -> u64 {
18253 *seed = seed
18254 .wrapping_mul(6364136223846793005)
18255 .wrapping_add(1442695040888963407);
18256 *seed
18257 }
18258
18259 fn expected_numeric(values: &[Scalar]) -> Scalar {
18260 let mut product = 1.0_f64;
18261 for value in values {
18262 if value.is_missing() {
18263 continue;
18264 }
18265 if let Ok(value) = value.to_f64() {
18266 product *= value;
18267 }
18268 }
18269 Scalar::Float64(product)
18270 }
18271
18272 fn expected_timedelta(values: &[Scalar]) -> Scalar {
18273 if values
18274 .iter()
18275 .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
18276 {
18277 Scalar::Null(NullKind::NaN)
18278 } else {
18279 Scalar::Float64(1.0)
18280 }
18281 }
18282
18283 fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
18284 let actual = super::nanprod(values);
18285 assert!(
18286 actual.semantic_eq(&expected),
18287 "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
18288 );
18289 }
18290
18291 let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
18292 assert_prod(
18293 usize::MAX,
18294 "numeric_all_missing",
18295 &all_missing,
18296 Scalar::Float64(1.0),
18297 );
18298
18299 let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
18300 assert_prod(
18301 usize::MAX - 1,
18302 "timedelta_all_missing",
18303 &td_all_missing,
18304 expected_timedelta(&td_all_missing),
18305 );
18306
18307 let mut seed = 0x6e0d_9938_a11c_0de5_u64;
18308 for case in 0..280 {
18309 let len = (next(&mut seed) % 89 + 1) as usize;
18310
18311 let mut numeric = Vec::with_capacity(len);
18312 numeric.push(Scalar::Int64((case % 17) as i64 - 8));
18313 for _ in 1..len {
18314 let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
18315 numeric.push(match next(&mut seed) % 9 {
18316 0 => Scalar::Null(NullKind::Null),
18317 1 => Scalar::Null(NullKind::NaN),
18318 2 => Scalar::Float64(f64::NAN),
18319 3 => Scalar::Bool(raw & 1 == 0),
18320 4 => Scalar::Int64(raw % 19),
18321 5 => Scalar::Float64(raw as f64 / 97.0),
18322 6 => Scalar::Float64(0.0),
18323 7 => Scalar::Float64(-0.0),
18324 _ => Scalar::Float64(1.0),
18325 });
18326 }
18327 assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
18328
18329 let mut timedeltas = Vec::with_capacity(len);
18330 timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
18331 for _ in 1..len {
18332 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
18333 timedeltas.push(match next(&mut seed) % 7 {
18334 0 => Scalar::Null(NullKind::Null),
18335 1 => Scalar::Timedelta64(i64::MIN),
18336 _ => Scalar::Timedelta64(raw),
18337 });
18338 }
18339 assert_prod(
18340 case,
18341 "timedelta",
18342 &timedeltas,
18343 expected_timedelta(&timedeltas),
18344 );
18345 }
18346 }
18347
18348 #[test]
18349 fn nanskew_symmetric_distribution_near_zero() {
18350 let values = vec![
18351 Scalar::Float64(1.0),
18352 Scalar::Float64(2.0),
18353 Scalar::Float64(3.0),
18354 Scalar::Float64(4.0),
18355 Scalar::Float64(5.0),
18356 ];
18357 let skew = super::nanskew(&values);
18359 assert!(matches!(skew, Scalar::Float64(_)));
18360 let Scalar::Float64(v) = skew else {
18361 return;
18362 };
18363 assert!(v.abs() < 1e-9);
18364 }
18365
18366 #[test]
18367 fn nanskew_too_few_values_returns_null() {
18368 assert!(super::nanskew(&[]).is_missing());
18369 assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
18370 }
18371
18372 #[test]
18373 fn nankurt_symmetric_uniform_distribution() {
18374 let values = vec![
18375 Scalar::Float64(1.0),
18376 Scalar::Float64(2.0),
18377 Scalar::Float64(3.0),
18378 Scalar::Float64(4.0),
18379 Scalar::Float64(5.0),
18380 ];
18381 let kurt = super::nankurt(&values);
18383 assert!(matches!(kurt, Scalar::Float64(_)));
18384 let Scalar::Float64(v) = kurt else {
18385 return;
18386 };
18387 assert!((v + 1.2).abs() < 1e-9);
18388 }
18389
18390 #[test]
18391 fn nankurt_too_few_values_returns_null() {
18392 let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
18393 assert!(super::nankurt(&vals).is_missing());
18394 }
18395
18396 #[test]
18397 fn nanskew_constant_series_returns_zero() {
18398 let values = vec![
18399 Scalar::Float64(5.0),
18400 Scalar::Float64(5.0),
18401 Scalar::Float64(5.0),
18402 ];
18403 assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
18404 assert_eq!(
18405 super::nankurt(&[
18406 Scalar::Float64(5.0),
18407 Scalar::Float64(5.0),
18408 Scalar::Float64(5.0),
18409 Scalar::Float64(5.0),
18410 ]),
18411 Scalar::Float64(0.0)
18412 );
18413 }
18414
18415 #[test]
18416 fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
18417 fn next(seed: &mut u64) -> u64 {
18420 *seed = seed
18421 .wrapping_mul(2862933555777941757)
18422 .wrapping_add(3037000493);
18423 *seed
18424 }
18425
18426 fn samples(values: &[Scalar]) -> Vec<f64> {
18427 values
18428 .iter()
18429 .filter(|value| !value.is_missing())
18430 .filter_map(|value| value.to_f64().ok())
18431 .collect()
18432 }
18433
18434 fn expected_skew(values: &[Scalar]) -> Scalar {
18435 let samples = samples(values);
18436 let n = samples.len() as f64;
18437 if n < 3.0 {
18438 return Scalar::Null(NullKind::NaN);
18439 }
18440 let mean = samples.iter().sum::<f64>() / n;
18441 let m2 = samples
18442 .iter()
18443 .map(|value| (value - mean).powi(2))
18444 .sum::<f64>();
18445 let m3 = samples
18446 .iter()
18447 .map(|value| (value - mean).powi(3))
18448 .sum::<f64>();
18449 let s2 = m2 / (n - 1.0);
18450 if s2 == 0.0 {
18451 return Scalar::Float64(0.0);
18452 }
18453 Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
18454 }
18455
18456 fn expected_kurt(values: &[Scalar]) -> Scalar {
18457 let samples = samples(values);
18458 let n = samples.len() as f64;
18459 if n < 4.0 {
18460 return Scalar::Null(NullKind::NaN);
18461 }
18462 let mean = samples.iter().sum::<f64>() / n;
18463 let m2 = samples
18464 .iter()
18465 .map(|value| (value - mean).powi(2))
18466 .sum::<f64>();
18467 let m4 = samples
18468 .iter()
18469 .map(|value| (value - mean).powi(4))
18470 .sum::<f64>();
18471 let s2 = m2 / (n - 1.0);
18472 if s2 == 0.0 {
18473 return Scalar::Float64(0.0);
18474 }
18475 let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
18476 let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
18477 Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
18478 }
18479
18480 fn assert_moments(case: usize, values: &[Scalar]) {
18481 let expected_skew = expected_skew(values);
18482 let expected_kurt = expected_kurt(values);
18483 let actual_skew = super::nanskew(values);
18484 let actual_kurt = super::nankurt(values);
18485 assert!(
18486 actual_skew.semantic_eq(&expected_skew),
18487 "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
18488 );
18489 assert!(
18490 actual_kurt.semantic_eq(&expected_kurt),
18491 "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
18492 );
18493 }
18494
18495 assert_moments(
18496 usize::MAX,
18497 &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
18498 );
18499 assert_moments(
18500 usize::MAX - 1,
18501 &[
18502 Scalar::Float64(7.0),
18503 Scalar::Float64(7.0),
18504 Scalar::Float64(7.0),
18505 Scalar::Float64(7.0),
18506 ],
18507 );
18508
18509 let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
18510 for case in 0..260 {
18511 let len = (next(&mut seed) % 89 + 1) as usize;
18512 let mut values = Vec::with_capacity(len);
18513 if case % 11 == 0 {
18514 values.extend((0..len).map(|_| Scalar::Float64(3.0)));
18515 } else {
18516 values.push(Scalar::Float64(case as f64 / 19.0));
18517 for _ in 1..len {
18518 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
18519 values.push(match next(&mut seed) % 8 {
18520 0 => Scalar::Null(NullKind::Null),
18521 1 => Scalar::Null(NullKind::NaN),
18522 2 => Scalar::Float64(f64::NAN),
18523 3 => Scalar::Bool(raw & 1 == 0),
18524 4 => Scalar::Int64(raw % 251),
18525 5 => Scalar::Float64(raw as f64 / 83.0),
18526 6 => Scalar::Float64(0.0),
18527 _ => Scalar::Float64(-0.0),
18528 });
18529 }
18530 }
18531 assert_moments(case, &values);
18532 }
18533 }
18534
18535 #[test]
18538 fn interval_default_closed_is_right() {
18539 assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
18540 }
18541
18542 #[test]
18543 fn interval_left_and_right_closed_helpers() {
18544 assert!(IntervalClosed::Left.left_closed());
18545 assert!(!IntervalClosed::Left.right_closed());
18546 assert!(!IntervalClosed::Right.left_closed());
18547 assert!(IntervalClosed::Right.right_closed());
18548 assert!(IntervalClosed::Both.left_closed());
18549 assert!(IntervalClosed::Both.right_closed());
18550 assert!(!IntervalClosed::Neither.left_closed());
18551 assert!(!IntervalClosed::Neither.right_closed());
18552 }
18553
18554 #[test]
18555 fn interval_display_matches_pandas_notation() {
18556 assert_eq!(
18557 Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
18558 "(0.0, 5.0]"
18559 );
18560 assert_eq!(
18561 Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
18562 "[0.0, 5.0)"
18563 );
18564 assert_eq!(
18565 Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
18566 "[0.0, 5.0]"
18567 );
18568 assert_eq!(
18569 Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
18570 "(0.0, 5.0)"
18571 );
18572 assert_eq!(
18573 Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
18574 "(2.5, 3.5]"
18575 );
18576 assert_eq!(
18577 Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
18578 "(-1.0, 0.0]"
18579 );
18580 assert_eq!(
18581 Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
18582 "(1e+20, 2e+20]"
18583 );
18584 }
18585
18586 #[test]
18587 fn interval_length_and_mid() {
18588 let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
18589 assert_eq!(i.length(), 8.0);
18590 assert_eq!(i.mid(), 6.0);
18591 }
18592
18593 #[test]
18594 fn interval_contains_matches_closed_policy() {
18595 let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
18596 assert!(!right.contains(0.0));
18597 assert!(right.contains(2.5));
18598 assert!(right.contains(5.0));
18599
18600 let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
18601 assert!(left.contains(0.0));
18602 assert!(left.contains(2.5));
18603 assert!(!left.contains(5.0));
18604
18605 let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
18606 assert!(both.contains(0.0));
18607 assert!(both.contains(5.0));
18608
18609 let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
18610 assert!(!neither.contains(0.0));
18611 assert!(!neither.contains(5.0));
18612 assert!(neither.contains(2.5));
18613 }
18614
18615 #[test]
18616 fn interval_contains_nan_returns_false() {
18617 let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
18618 assert!(!i.contains(f64::NAN));
18619 }
18620
18621 #[test]
18622 fn interval_is_empty_matches_pandas() {
18623 assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
18625 assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
18626 assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
18627 assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
18629 assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
18631 }
18632
18633 #[test]
18634 fn interval_overlaps_disjoint_returns_false() {
18635 let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
18636 let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
18637 assert!(!a.overlaps(&b));
18638 assert!(!b.overlaps(&a));
18639 }
18640
18641 #[test]
18642 fn interval_overlaps_nested_returns_true() {
18643 let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
18644 let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
18645 assert!(outer.overlaps(&inner));
18646 assert!(inner.overlaps(&outer));
18647 }
18648
18649 #[test]
18650 fn interval_overlaps_touching_respects_closed_policy() {
18651 let right_right = (
18653 Interval::new(0.0, 1.0, IntervalClosed::Right),
18654 Interval::new(1.0, 2.0, IntervalClosed::Right),
18655 );
18656 assert!(!right_right.0.overlaps(&right_right.1));
18658
18659 let both_both = (
18661 Interval::new(0.0, 1.0, IntervalClosed::Both),
18662 Interval::new(1.0, 2.0, IntervalClosed::Both),
18663 );
18664 assert!(both_both.0.overlaps(&both_both.1));
18665 }
18666
18667 #[test]
18668 fn interval_roundtrips_through_serde_json() {
18669 let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
18670 let json = serde_json::to_string(&i).expect("serialize");
18671 let back: Interval = serde_json::from_str(&json).expect("deserialize");
18672 assert_eq!(i, back);
18673 }
18674
18675 #[test]
18676 fn interval_serde_default_closed_is_right_when_missing() {
18677 let back: Interval =
18679 serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
18680 assert_eq!(back.closed, IntervalClosed::Right);
18681 }
18682
18683 #[test]
18686 fn period_freq_parses_canonical_aliases() {
18687 assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
18688 assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
18689 assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
18690 assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
18691 assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
18692 assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
18693 assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
18694 assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
18695 assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
18696 assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
18697 assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
18698 }
18699
18700 #[test]
18701 fn period_freq_parse_is_case_insensitive() {
18702 assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::QUARTERLY));
18703 assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
18704 }
18705
18706 #[test]
18707 fn period_freq_rejects_unknown_aliases() {
18708 assert_eq!(PeriodFreq::parse("nanosec"), None);
18709 assert_eq!(PeriodFreq::parse(""), None);
18710 assert_eq!(PeriodFreq::parse("xyz"), None);
18711 }
18712
18713 #[test]
18714 fn period_freq_alias_roundtrip() {
18715 for freq in [
18716 PeriodFreq::ANNUAL,
18717 PeriodFreq::QUARTERLY,
18718 PeriodFreq::Monthly,
18719 PeriodFreq::WEEKLY,
18720 PeriodFreq::Daily,
18721 PeriodFreq::Business,
18722 PeriodFreq::Hourly,
18723 PeriodFreq::Minutely,
18724 PeriodFreq::Secondly,
18725 PeriodFreq::Milliseconds,
18726 PeriodFreq::Microseconds,
18727 PeriodFreq::Nanoseconds,
18728 ] {
18729 assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18730 }
18731 }
18732
18733 #[test]
18738 fn anchored_period_freqs_parse_print_and_shift_39h5n() {
18739 for month in 1..=12_u8 {
18740 for freq in [PeriodFreq::Annual(month), PeriodFreq::Quarterly(month)] {
18741 assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18742 }
18743 }
18744 for day in 0..7_u8 {
18745 assert_eq!(
18746 PeriodFreq::parse(&PeriodFreq::Weekly(day).alias()),
18747 Some(PeriodFreq::Weekly(day))
18748 );
18749 }
18750 assert_eq!(PeriodFreq::parse("Y-JUN"), Some(PeriodFreq::Annual(6)));
18751 assert_eq!(PeriodFreq::parse("A-JUN"), Some(PeriodFreq::Annual(6)));
18752 assert_eq!(PeriodFreq::parse("q-jan"), Some(PeriodFreq::Quarterly(1)));
18753 assert_eq!(PeriodFreq::parse("W-MON"), Some(PeriodFreq::Weekly(0)));
18754 assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18755 assert_eq!(PeriodFreq::parse("Q-XYZ"), None);
18757 assert_eq!(PeriodFreq::parse("M-JAN"), None);
18758 assert_eq!(PeriodFreq::parse("W-JAN"), None);
18759 assert_eq!(PeriodFreq::Annual(6).fiscal_month_shift(), 6);
18760 assert_eq!(PeriodFreq::Quarterly(1).fiscal_month_shift(), 11);
18761 assert_eq!(PeriodFreq::QUARTERLY.fiscal_month_shift(), 0);
18762 assert_eq!(PeriodFreq::Weekly(0).week_start_shift(), 1);
18763 assert_eq!(PeriodFreq::WEEKLY.week_start_shift(), 0);
18764 assert_eq!(
18765 Period::new(2827, PeriodFreq::Weekly(0)).to_string(),
18766 "2024-02-27/2024-03-04"
18767 );
18768 assert_eq!(
18769 Period::new(2826, PeriodFreq::Weekly(5)).to_string(),
18770 "2024-02-25/2024-03-02"
18771 );
18772 assert_eq!(
18773 Period::new(220, PeriodFreq::Quarterly(1)).to_string(),
18774 "2025Q1"
18775 );
18776 }
18777
18778 #[test]
18782 fn period_freq_subsecond_units_match_pandas() {
18783 assert_eq!(PeriodFreq::Milliseconds.alias(), "ms");
18785 assert_eq!(PeriodFreq::Microseconds.alias(), "us");
18786 assert_eq!(PeriodFreq::Nanoseconds.alias(), "ns");
18787 assert_eq!(PeriodFreq::Milliseconds.resolution(), Some("millisecond"));
18788 assert_eq!(PeriodFreq::Microseconds.resolution(), Some("microsecond"));
18789 assert_eq!(PeriodFreq::Nanoseconds.resolution(), Some("nanosecond"));
18790
18791 assert_eq!(PeriodFreq::parse("ms"), Some(PeriodFreq::Milliseconds));
18794 assert_eq!(PeriodFreq::parse("Ms"), Some(PeriodFreq::Milliseconds));
18795 assert_eq!(PeriodFreq::parse("mS"), Some(PeriodFreq::Milliseconds));
18796 assert_eq!(PeriodFreq::parse("MS"), None);
18797 assert_eq!(PeriodFreq::parse("us"), Some(PeriodFreq::Microseconds));
18799 assert_eq!(PeriodFreq::parse("US"), Some(PeriodFreq::Microseconds));
18800 assert_eq!(PeriodFreq::parse("ns"), Some(PeriodFreq::Nanoseconds));
18801 assert_eq!(PeriodFreq::parse("NS"), Some(PeriodFreq::Nanoseconds));
18802
18803 assert_eq!(
18806 Period::new(1_710_498_645_123, PeriodFreq::Milliseconds).calendar_string(),
18807 "2024-03-15 10:30:45.123"
18808 );
18809 assert_eq!(
18810 Period::new(1_710_498_645_123_456, PeriodFreq::Microseconds).calendar_string(),
18811 "2024-03-15 10:30:45.123456"
18812 );
18813 assert_eq!(
18814 Period::new(1_710_498_645_123_456_789, PeriodFreq::Nanoseconds).calendar_string(),
18815 "2024-03-15 10:30:45.123456789"
18816 );
18817
18818 assert_eq!(
18822 Period::new(0, PeriodFreq::Milliseconds).calendar_string(),
18823 "1970-01-01 00:00:00.000"
18824 );
18825 assert_eq!(
18826 Period::new(-1, PeriodFreq::Milliseconds).calendar_string(),
18827 "1969-12-31 23:59:59.999"
18828 );
18829 assert_eq!(
18830 Period::new(-1_000, PeriodFreq::Microseconds).calendar_string(),
18831 "1969-12-31 23:59:59.999000"
18832 );
18833 assert_eq!(
18834 Period::new(-999_999, PeriodFreq::Nanoseconds).calendar_string(),
18835 "1969-12-31 23:59:59.999000001"
18836 );
18837 }
18838
18839 #[test]
18840 fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
18841 assert_eq!(PeriodFreq::ANNUAL.alias(), "Y-DEC");
18842 assert_eq!(PeriodFreq::QUARTERLY.alias(), "Q-DEC");
18843 assert_eq!(PeriodFreq::WEEKLY.alias(), "W-SUN");
18844
18845 assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
18846 assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
18847 assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::ANNUAL));
18848 assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
18849 assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
18850 assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
18851 assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::WEEKLY));
18852 }
18853
18854 #[test]
18855 fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
18856 assert_eq!(PeriodFreq::Hourly.alias(), "h");
18857 assert_eq!(PeriodFreq::Minutely.alias(), "min");
18858 assert_eq!(PeriodFreq::Secondly.alias(), "s");
18859
18860 assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
18861 assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
18862 assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
18863 }
18864
18865 #[test]
18869 fn period_freq_resolution_is_the_component_word_not_the_alias() {
18870 assert_eq!(PeriodFreq::ANNUAL.resolution(), Some("year"));
18871 assert_eq!(PeriodFreq::QUARTERLY.resolution(), Some("quarter"));
18872 assert_eq!(PeriodFreq::Monthly.resolution(), Some("month"));
18873 assert_eq!(PeriodFreq::Daily.resolution(), Some("day"));
18874 assert_eq!(PeriodFreq::Hourly.resolution(), Some("hour"));
18875 assert_eq!(PeriodFreq::Minutely.resolution(), Some("minute"));
18876 assert_eq!(PeriodFreq::Secondly.resolution(), Some("second"));
18877
18878 assert_eq!(PeriodFreq::WEEKLY.resolution(), None);
18880 assert_eq!(PeriodFreq::Business.resolution(), None);
18881
18882 for freq in [
18887 PeriodFreq::ANNUAL,
18888 PeriodFreq::QUARTERLY,
18889 PeriodFreq::Monthly,
18890 PeriodFreq::WEEKLY,
18891 PeriodFreq::Daily,
18892 PeriodFreq::Business,
18893 PeriodFreq::Hourly,
18894 PeriodFreq::Minutely,
18895 PeriodFreq::Secondly,
18896 ] {
18897 assert_ne!(
18898 Some(freq.alias().as_str()),
18899 freq.resolution(),
18900 "{freq:?} reports its alias as its resolution again"
18901 );
18902 }
18903 }
18904
18905 #[test]
18906 fn period_scalar_accessors_match_pandas_star8() {
18907 let period = Period::new(600, PeriodFreq::Monthly);
18908
18909 assert_eq!(period.ordinal(), 600);
18910 assert_eq!(period.freq(), PeriodFreq::Monthly);
18911 assert_eq!(period.freqstr(), "M");
18912 }
18913
18914 #[test]
18915 fn period_multiplied_frequencies_parse_and_roundtrip_tus8r() {
18916 for (alias, canonical, base, multiplier) in [
18917 ("2D", "2D", PeriodFreq::Daily, 2),
18918 ("+3H", "3h", PeriodFreq::Hourly, 3),
18919 ("15min", "15min", PeriodFreq::Minutely, 15),
18920 ("2W-FRI", "2W-FRI", PeriodFreq::Weekly(4), 2),
18921 ("2M", "2M", PeriodFreq::Monthly, 2),
18922 ("2Q-JAN", "2Q-JAN", PeriodFreq::Quarterly(1), 2),
18923 ("2Y-JUN", "2Y-JUN", PeriodFreq::Annual(6), 2),
18924 ("2B", "2B", PeriodFreq::Business, 2),
18925 ("2ms", "2ms", PeriodFreq::Milliseconds, 2),
18926 ("3us", "3us", PeriodFreq::Microseconds, 3),
18927 ("4ns", "4ns", PeriodFreq::Nanoseconds, 4),
18928 ] {
18929 let freq = PeriodFreq::parse(alias).expect("valid multiplied frequency");
18930 assert_eq!(freq.base(), base, "{alias}");
18931 assert_eq!(freq.multiplier(), multiplier, "{alias}");
18932 assert_eq!(freq.alias(), canonical, "{alias}");
18933 assert_eq!(PeriodFreq::parse(&freq.alias()), Some(freq));
18934 assert_eq!(freq.resolution(), None);
18935 let encoded = serde_json::to_string(&freq).expect("serializable frequency");
18936 assert_eq!(serde_json::from_str::<PeriodFreq>(&encoded).unwrap(), freq);
18937 }
18938 assert_eq!(PeriodFreq::parse("1D"), Some(PeriodFreq::Daily));
18939 for invalid in ["0D", "-1D", "2MS", "2 3D", "2", "9223372036854775808D"] {
18940 assert_eq!(PeriodFreq::parse(invalid), None, "{invalid}");
18941 }
18942 assert!(
18943 serde_json::from_str::<PeriodFreq>(r#"{"MULTIPLE":{"unit":"DAILY","count":0}}"#,)
18944 .is_err()
18945 );
18946 }
18947
18948 #[test]
18952 fn period_multiplied_boundaries_and_labels_match_pandas_tus8r() {
18953 let nanos = 1_709_128_079_123_456_789;
18954 for (alias, ordinal, label, start, end) in [
18955 (
18956 "2D",
18957 19_781,
18958 "2024-02-28",
18959 1_709_078_400_000_000_000,
18960 1_709_251_199_999_999_999,
18961 ),
18962 (
18963 "3h",
18964 474_757,
18965 "2024-02-28 13:00",
18966 1_709_125_200_000_000_000,
18967 1_709_135_999_999_999_999,
18968 ),
18969 (
18970 "15min",
18971 28_485_467,
18972 "2024-02-28 13:47",
18973 1_709_128_020_000_000_000,
18974 1_709_128_919_999_999_999,
18975 ),
18976 (
18977 "2W-FRI",
18978 2_826,
18979 "2024-02-24/2024-03-01",
18980 1_708_732_800_000_000_000,
18981 1_709_942_399_999_999_999,
18982 ),
18983 (
18984 "2M",
18985 649,
18986 "2024-02",
18987 1_706_745_600_000_000_000,
18988 1_711_929_599_999_999_999,
18989 ),
18990 (
18991 "2Q-JAN",
18992 220,
18993 "2025Q1",
18994 1_706_745_600_000_000_000,
18995 1_722_470_399_999_999_999,
18996 ),
18997 (
18998 "2Y-JUN",
18999 54,
19000 "2024",
19001 1_688_169_600_000_000_000,
19002 1_751_327_999_999_999_999,
19003 ),
19004 (
19005 "2B",
19006 14_129,
19007 "2024-02-28",
19008 1_709_078_400_000_000_000,
19009 1_709_251_199_999_999_999,
19010 ),
19011 (
19012 "2ms",
19013 1_709_128_079_123,
19014 "2024-02-28 13:47:59.123",
19015 1_709_128_079_123_000_000,
19016 1_709_128_079_124_999_999,
19017 ),
19018 (
19019 "3us",
19020 1_709_128_079_123_456,
19021 "2024-02-28 13:47:59.123456",
19022 1_709_128_079_123_456_000,
19023 1_709_128_079_123_458_999,
19024 ),
19025 (
19026 "4ns",
19027 nanos,
19028 "2024-02-28 13:47:59.123456789",
19029 nanos,
19030 nanos + 3,
19031 ),
19032 ] {
19033 let freq = PeriodFreq::parse(alias).expect("valid multiplied frequency");
19034 let period = Period::from_timestamp_nanos(nanos, freq).expect("in-range timestamp");
19035 assert_eq!(period.ordinal, ordinal, "{alias}");
19036 assert_eq!(period.to_string(), label, "{alias}");
19037 assert_eq!(period.start_nanos(), Some(start), "{alias}");
19038 assert_eq!(period.end_nanos(), Some(end), "{alias}");
19039 assert_eq!(period.shift(1).ordinal, ordinal + freq.multiplier());
19040 assert_eq!(period.shift(-1).ordinal, ordinal - freq.multiplier());
19041 assert_eq!(period.shift(1).diff(&period), Some(freq.multiplier()));
19042 assert_eq!(
19043 period.asfreq(alias).unwrap().ordinal,
19044 ordinal + freq.multiplier() - 1
19045 );
19046 assert_eq!(period.asfreq_with_how(alias, "start").unwrap(), period);
19047 }
19048
19049 let business = Period::new(14_091, PeriodFreq::parse("2B").unwrap());
19052 assert_eq!(business.end_nanos(), Some(1_704_758_399_999_999_999));
19053 assert_eq!(business.shift(1).to_string(), "2024-01-09");
19054 let month = Period::new(649, PeriodFreq::parse("2M").unwrap());
19055 assert_eq!(
19056 (month.year(), month.month(), month.day()),
19057 (Some(2024), Some(2), Some(29))
19058 );
19059 let quarter = Period::new(220, PeriodFreq::parse("2Q-JAN").unwrap());
19060 assert_eq!(
19061 (quarter.year(), quarter.quarter(), quarter.qyear()),
19062 (Some(2024), Some(1), Some(2025))
19063 );
19064 }
19065
19066 #[test]
19067 fn period_multiplied_ranges_keep_negative_ordinals_and_nat_tus8r() {
19068 let freq = PeriodFreq::parse("3h").unwrap();
19069 let before_epoch = Period::from_timestamp_nanos(-1, freq).unwrap();
19070 assert_eq!(before_epoch.ordinal, -1);
19071 assert_eq!(before_epoch.start_nanos(), Some(-3_600_000_000_000));
19072 assert_eq!(before_epoch.end_nanos(), Some(7_199_999_999_999));
19073 assert_eq!(
19074 super::period_range(before_epoch, 3)
19075 .iter()
19076 .map(|period| period.ordinal)
19077 .collect::<Vec<_>>(),
19078 vec![-1, 2, 5],
19079 );
19080 assert!(super::period_range(before_epoch, 0).is_empty());
19081 let nat = Period::new(i64::MIN, freq);
19082 assert!(nat.shift(1).is_nat());
19083 assert!(nat.asfreq("2D").unwrap().is_nat());
19084 assert_eq!(nat.end_nanos(), None);
19085 assert_eq!(Period::new(i64::MAX, freq).end_nanos(), None);
19086 assert_eq!(Period::new(-100, freq).shift(i64::MAX).ordinal, i64::MAX);
19087 }
19088
19089 #[test]
19090 fn period_parse_common_pandas_ordinals_avm08() {
19091 assert_eq!(
19092 Period::parse("2024").unwrap(),
19093 Period::new(54, PeriodFreq::ANNUAL)
19094 );
19095 assert_eq!(
19096 Period::parse("2024Q1").unwrap(),
19097 Period::new(216, PeriodFreq::QUARTERLY)
19098 );
19099 assert_eq!(
19100 Period::parse("2024-01").unwrap(),
19101 Period::new(648, PeriodFreq::Monthly)
19102 );
19103 assert_eq!(
19104 Period::parse("2024-01-15").unwrap(),
19105 Period::new(19_737, PeriodFreq::Daily)
19106 );
19107 assert!(Period::parse("216").is_err());
19108 }
19109
19110 #[test]
19111 fn period_shift_advances_ordinal() {
19112 let q1 = Period::new(216, PeriodFreq::QUARTERLY);
19113 let q2 = q1.shift(1);
19114 assert_eq!(q2.ordinal, 217);
19115 assert_eq!(q2.freq, PeriodFreq::QUARTERLY);
19116 let q0 = q1.shift(-1);
19117 assert_eq!(q0.ordinal, 215);
19118 }
19119
19120 #[test]
19121 fn period_shift_saturates_on_overflow() {
19122 let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
19123 assert_eq!(p.shift(100).ordinal, i64::MAX);
19124 let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
19125 assert_eq!(p.shift(-100).ordinal, i64::MIN);
19126 }
19127
19128 #[test]
19129 fn period_diff_returns_period_count() {
19130 let a = Period::new(216, PeriodFreq::QUARTERLY);
19131 let b = Period::new(220, PeriodFreq::QUARTERLY);
19132 assert_eq!(b.diff(&a), Some(4));
19133 assert_eq!(a.diff(&b), Some(-4));
19134 }
19135
19136 #[test]
19137 fn period_diff_rejects_mismatched_freq() {
19138 let monthly = Period::new(100, PeriodFreq::Monthly);
19139 let quarterly = Period::new(100, PeriodFreq::QUARTERLY);
19140 assert_eq!(monthly.diff(&quarterly), None);
19141 assert_eq!(quarterly.diff(&monthly), None);
19142 }
19143
19144 #[test]
19145 fn period_cmp_same_freq_respects_ordinal_order() {
19146 use std::cmp::Ordering;
19147 let a = Period::new(10, PeriodFreq::Monthly);
19148 let b = Period::new(20, PeriodFreq::Monthly);
19149 assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
19150 assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
19151 assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
19152 }
19153
19154 #[test]
19155 fn period_cmp_cross_freq_returns_none() {
19156 let m = Period::new(1, PeriodFreq::Monthly);
19157 let q = Period::new(1, PeriodFreq::QUARTERLY);
19158 assert_eq!(m.cmp_same_freq(&q), None);
19159 }
19160
19161 #[test]
19162 fn period_arithmetic_matches_seeded_oracles_bac28() {
19163 use std::cmp::Ordering;
19164
19165 fn next(seed: &mut u64) -> u64 {
19166 *seed = seed
19167 .wrapping_mul(2862933555777941757)
19168 .wrapping_add(3037000493);
19169 *seed
19170 }
19171
19172 fn freq_for(raw: u64) -> PeriodFreq {
19173 match raw % 12 {
19176 0 => PeriodFreq::ANNUAL,
19177 1 => PeriodFreq::QUARTERLY,
19178 2 => PeriodFreq::Monthly,
19179 3 => PeriodFreq::WEEKLY,
19180 4 => PeriodFreq::Daily,
19181 5 => PeriodFreq::Business,
19182 6 => PeriodFreq::Hourly,
19183 7 => PeriodFreq::Minutely,
19184 8 => PeriodFreq::Secondly,
19185 9 => PeriodFreq::Milliseconds,
19186 10 => PeriodFreq::Microseconds,
19187 _ => PeriodFreq::Nanoseconds,
19188 }
19189 }
19190
19191 fn different_freq(freq: PeriodFreq) -> PeriodFreq {
19192 match freq {
19193 PeriodFreq::Annual(_) => PeriodFreq::QUARTERLY,
19194 PeriodFreq::Quarterly(_) => PeriodFreq::Monthly,
19195 PeriodFreq::Monthly => PeriodFreq::WEEKLY,
19196 PeriodFreq::Weekly(_) => PeriodFreq::Daily,
19197 PeriodFreq::Daily => PeriodFreq::Business,
19198 PeriodFreq::Business => PeriodFreq::Hourly,
19199 PeriodFreq::Hourly => PeriodFreq::Minutely,
19200 PeriodFreq::Minutely => PeriodFreq::Secondly,
19201 PeriodFreq::Secondly => PeriodFreq::Milliseconds,
19205 PeriodFreq::Milliseconds => PeriodFreq::Microseconds,
19206 PeriodFreq::Microseconds => PeriodFreq::Nanoseconds,
19207 PeriodFreq::Nanoseconds => PeriodFreq::ANNUAL,
19208 PeriodFreq::Multiple(_) => freq.base(),
19209 }
19210 }
19211
19212 fn assert_period_case(
19213 case: usize,
19214 freq: PeriodFreq,
19215 ordinal: i64,
19216 shift_by: i64,
19217 other_ordinal: i64,
19218 ) {
19219 let period = Period::new(ordinal, freq);
19220 let shifted = period.shift(shift_by);
19221 assert_eq!(
19222 shifted.ordinal,
19223 ordinal.saturating_add(shift_by),
19224 "case {case}: shift ordinal"
19225 );
19226 assert_eq!(shifted.freq, freq, "case {case}: shift freq");
19227
19228 let same_freq_other = Period::new(other_ordinal, freq);
19229 assert_eq!(
19230 period.diff(&same_freq_other),
19231 Some(ordinal.saturating_sub(other_ordinal)),
19232 "case {case}: same-freq diff"
19233 );
19234 assert_eq!(
19235 period.cmp_same_freq(&same_freq_other),
19236 Some(ordinal.cmp(&other_ordinal)),
19237 "case {case}: same-freq cmp"
19238 );
19239
19240 let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
19241 assert_eq!(
19242 period.diff(&cross_freq_other),
19243 None,
19244 "case {case}: cross-freq diff"
19245 );
19246 assert_eq!(
19247 period.cmp_same_freq(&cross_freq_other),
19248 None,
19249 "case {case}: cross-freq cmp"
19250 );
19251 }
19252
19253 assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
19254 assert_period_case(
19255 usize::MAX - 1,
19256 PeriodFreq::Daily,
19257 i64::MIN + 2,
19258 -10,
19259 i64::MAX,
19260 );
19261 assert_eq!(
19262 Period::new(10, PeriodFreq::Monthly)
19263 .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
19264 Some(Ordering::Equal)
19265 );
19266
19267 let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
19268 for case in 0..260 {
19269 let freq = freq_for(next(&mut seed));
19270 let ordinal = match case % 53 {
19271 0 => i64::MAX - (next(&mut seed) % 8) as i64,
19272 1 => i64::MIN + (next(&mut seed) % 8) as i64,
19273 _ => (next(&mut seed) % 200_001) as i64 - 100_000,
19274 };
19275 let shift_by = match case % 47 {
19276 0 => 512,
19277 1 => -512,
19278 _ => (next(&mut seed) % 4097) as i64 - 2048,
19279 };
19280 let other_ordinal = match case % 41 {
19281 0 => i64::MAX,
19282 1 => i64::MIN,
19283 _ => (next(&mut seed) % 200_001) as i64 - 100_000,
19284 };
19285 assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
19286 }
19287 }
19288
19289 #[test]
19290 fn period_display_is_pandas_calendar_string() {
19291 assert_eq!(
19293 Period::new(216, PeriodFreq::QUARTERLY).to_string(),
19294 "2024Q1"
19295 );
19296 assert_eq!(Period::new(54, PeriodFreq::ANNUAL).to_string(), "2024");
19298 assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
19300 assert_eq!(
19302 Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
19303 "2024-01-15"
19304 );
19305 assert_eq!(
19306 Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
19307 "NaT"
19308 );
19309 }
19310
19311 #[test]
19319 fn weekly_and_business_periods_do_not_index_days() {
19320 for (ordinal, want) in [
19325 (0_i64, "1969-12-22/1969-12-28"),
19326 (1, "1969-12-29/1970-01-04"),
19327 (2829, "2024-03-11/2024-03-17"),
19328 (1540, "1999-06-28/1999-07-04"),
19329 (15237, "2261-12-30/2262-01-05"),
19330 (-1, "1969-12-15/1969-12-21"),
19332 (-2829, "1915-10-04/1915-10-10"),
19333 ] {
19334 assert_eq!(
19335 Period::new(ordinal, PeriodFreq::WEEKLY).to_string(),
19336 want,
19337 "weekly ordinal {ordinal}"
19338 );
19339 }
19340
19341 for (ordinal, want) in [
19345 (0_i64, "1970-01-01"), (1, "1970-01-02"), (2, "1970-01-05"), (3, "1970-01-06"),
19349 (4, "1970-01-07"),
19350 (5, "1970-01-08"),
19351 (14141, "2024-03-15"),
19352 (76179, "2262-01-01"),
19353 (7697, "1999-07-05"),
19356 (-1, "1969-12-31"),
19357 (-5, "1969-12-25"),
19358 (-6, "1969-12-24"),
19359 ] {
19360 assert_eq!(
19361 Period::new(ordinal, PeriodFreq::Business).to_string(),
19362 want,
19363 "business ordinal {ordinal}"
19364 );
19365 }
19366
19367 for ordinal in -400_i64..400 {
19371 let rendered = Period::new(ordinal, PeriodFreq::Business).to_string();
19372 let later = Period::new(ordinal + 5, PeriodFreq::Business).to_string();
19373 assert_ne!(rendered, later, "business ordinals must not repeat");
19374 }
19375
19376 assert_eq!(Period::new(i64::MIN, PeriodFreq::WEEKLY).to_string(), "NaT");
19377 assert_eq!(
19378 Period::new(i64::MIN, PeriodFreq::Business).to_string(),
19379 "NaT"
19380 );
19381 }
19382
19383 fn period_display_former_profile(period: &Period) -> String {
19384 let calendar = period.calendar_string();
19385 let mut rendered = String::new();
19386 rendered.push_str(&calendar);
19387 rendered
19388 }
19389
19390 fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
19391 use std::{hint::black_box, time::Instant};
19392
19393 let started = Instant::now();
19394 let mut checksum = 0usize;
19395 for period in periods {
19396 let rendered = render(black_box(period));
19397 checksum = checksum.wrapping_add(rendered.len());
19398 drop(black_box(rendered));
19399 }
19400 black_box(checksum);
19401 started.elapsed().as_nanos()
19402 }
19403
19404 #[test]
19405 #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
19406 fn profile_period_display_direct_sink_ab_6pqra() {
19407 const FREQUENCIES: [PeriodFreq; 9] = [
19408 PeriodFreq::ANNUAL,
19409 PeriodFreq::QUARTERLY,
19410 PeriodFreq::Monthly,
19411 PeriodFreq::WEEKLY,
19412 PeriodFreq::Daily,
19413 PeriodFreq::Business,
19414 PeriodFreq::Hourly,
19415 PeriodFreq::Minutely,
19416 PeriodFreq::Secondly,
19417 ];
19418 const SAMPLES: usize = 10;
19419
19420 let periods = (0..65_536)
19421 .map(|index| {
19422 let ordinal = if index % 4093 == 0 {
19423 i64::MIN
19424 } else {
19425 ((index as i64 * 7_919) % 4_000_001) - 2_000_000
19426 };
19427 Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
19428 })
19429 .collect::<Vec<_>>();
19430
19431 for period in &periods {
19432 assert_eq!(period_display_former_profile(period), period.to_string());
19433 }
19434
19435 for _ in 0..2 {
19436 measure_period_renderer(&periods, period_display_former_profile);
19437 measure_period_renderer(&periods, Period::to_string);
19438 }
19439
19440 let mut former_ns = Vec::with_capacity(SAMPLES);
19441 let mut public_ns = Vec::with_capacity(SAMPLES);
19442 for sample in 0..SAMPLES {
19443 if sample % 2 == 0 {
19444 former_ns.push(measure_period_renderer(
19445 &periods,
19446 period_display_former_profile,
19447 ));
19448 public_ns.push(measure_period_renderer(&periods, Period::to_string));
19449 } else {
19450 public_ns.push(measure_period_renderer(&periods, Period::to_string));
19451 former_ns.push(measure_period_renderer(
19452 &periods,
19453 period_display_former_profile,
19454 ));
19455 }
19456 }
19457 former_ns.sort_unstable();
19458 public_ns.sort_unstable();
19459 let former_p50 = former_ns[SAMPLES / 2];
19460 let public_p50 = public_ns[SAMPLES / 2];
19461 let former_p95 = former_ns[SAMPLES - 1];
19462 let public_p95 = public_ns[SAMPLES - 1];
19463 println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
19464 println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
19465 println!(
19466 "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
19467 former_p50 as f64 / public_p50 as f64
19468 );
19469 println!(
19470 "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
19471 former_p95 as f64 / public_p95 as f64
19472 );
19473 }
19474
19475 #[cfg(test)]
19476 fn fp_days(ymd: &str) -> i64 {
19477 Period::parse(ymd).expect("daily period").ordinal
19478 }
19479
19480 #[test]
19481 fn period_roundtrips_through_serde_json() {
19482 let p = Period::new(42, PeriodFreq::WEEKLY);
19483 let json = serde_json::to_string(&p).expect("serialize");
19484 let back: Period = serde_json::from_str(&json).expect("deserialize");
19485 assert_eq!(p, back);
19486 }
19487
19488 use super::period_range;
19491
19492 #[test]
19493 fn period_range_zero_periods_is_empty() {
19494 let start = Period::new(216, PeriodFreq::QUARTERLY);
19495 assert!(period_range(start, 0).is_empty());
19496 }
19497
19498 #[test]
19499 fn period_range_single_period_returns_start_only() {
19500 let start = Period::new(216, PeriodFreq::QUARTERLY);
19501 let r = period_range(start, 1);
19502 assert_eq!(r.len(), 1);
19503 assert_eq!(r[0], start);
19504 }
19505
19506 #[test]
19507 fn period_range_increments_ordinal_by_one_per_step() {
19508 let start = Period::new(216, PeriodFreq::QUARTERLY);
19509 let r = period_range(start, 4);
19510 assert_eq!(r.len(), 4);
19511 assert_eq!(r[0].ordinal, 216);
19512 assert_eq!(r[1].ordinal, 217);
19513 assert_eq!(r[2].ordinal, 218);
19514 assert_eq!(r[3].ordinal, 219);
19515 }
19516
19517 #[test]
19518 fn period_range_preserves_frequency() {
19519 let start = Period::new(0, PeriodFreq::Monthly);
19520 let r = period_range(start, 12);
19521 assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
19522 }
19523
19524 #[test]
19525 fn period_range_negative_starting_ordinal_works() {
19526 let start = Period::new(-3, PeriodFreq::ANNUAL);
19528 let r = period_range(start, 5);
19529 assert_eq!(
19530 r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
19531 vec![-3, -2, -1, 0, 1]
19532 );
19533 }
19534
19535 #[test]
19536 fn period_range_large_n_does_not_panic() {
19537 let start = Period::new(0, PeriodFreq::Monthly);
19539 let r = period_range(start, 1024);
19540 assert_eq!(r.len(), 1024);
19541 assert_eq!(r[1023].ordinal, 1023);
19542 }
19543
19544 #[test]
19545 fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
19546 fn next(seed: &mut u64) -> u64 {
19547 *seed = seed
19548 .wrapping_mul(6364136223846793005)
19549 .wrapping_add(1442695040888963407);
19550 *seed
19551 }
19552
19553 fn freq_for(raw: u64) -> PeriodFreq {
19554 match raw % 12 {
19557 0 => PeriodFreq::ANNUAL,
19558 1 => PeriodFreq::QUARTERLY,
19559 2 => PeriodFreq::Monthly,
19560 3 => PeriodFreq::WEEKLY,
19561 4 => PeriodFreq::Daily,
19562 5 => PeriodFreq::Business,
19563 6 => PeriodFreq::Hourly,
19564 7 => PeriodFreq::Minutely,
19565 8 => PeriodFreq::Secondly,
19566 9 => PeriodFreq::Milliseconds,
19567 10 => PeriodFreq::Microseconds,
19568 _ => PeriodFreq::Nanoseconds,
19569 }
19570 }
19571
19572 fn assert_oracle_case(case: usize, start: Period, periods: usize) {
19573 let got = period_range(start, periods);
19574 assert_eq!(got.len(), periods, "case {case}: length");
19575
19576 for (position, period) in got.iter().enumerate() {
19577 let expected_ordinal = start.ordinal.saturating_add(position as i64);
19578 assert_eq!(
19579 period.ordinal, expected_ordinal,
19580 "case {case}: ordinal at {position}"
19581 );
19582 assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
19583 }
19584 }
19585
19586 assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
19587 assert_oracle_case(
19588 usize::MAX - 1,
19589 Period::new(i64::MAX - 3, PeriodFreq::Daily),
19590 8,
19591 );
19592
19593 let mut seed = 0x9e21_0d1c_5eed_0421_u64;
19594 for case in 0..260 {
19595 let freq = freq_for(next(&mut seed));
19596 let periods = (next(&mut seed) % 80) as usize;
19597 let start_ordinal = if case % 37 == 0 {
19598 i64::MAX - 7
19599 } else {
19600 (next(&mut seed) % 20_001) as i64 - 10_000
19601 };
19602 assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
19603 }
19604 }
19605
19606 use super::{TypeError, interval_range, interval_range_by_periods, interval_range_by_step};
19609
19610 #[test]
19611 fn interval_range_by_periods_matches_pandas_default_case() {
19612 let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
19614 assert_eq!(bins.len(), 5);
19615 for (i, bin) in bins.iter().enumerate() {
19616 assert_eq!(bin.left, (i as f64) * 2.0);
19617 assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
19618 assert_eq!(bin.closed, IntervalClosed::Right);
19619 }
19620 }
19621
19622 #[test]
19623 fn interval_range_by_periods_final_edge_is_exact_end() {
19624 let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
19626 assert_eq!(bins.last().unwrap().right, 1.0);
19627 }
19628
19629 #[test]
19630 fn interval_range_by_periods_zero_periods_is_empty() {
19631 assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
19632 }
19633
19634 #[test]
19635 fn interval_range_by_periods_reversed_range_is_empty() {
19636 assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
19638 }
19639
19640 #[test]
19641 fn interval_range_by_periods_preserves_closed_policy() {
19642 for closed in [
19643 IntervalClosed::Left,
19644 IntervalClosed::Right,
19645 IntervalClosed::Both,
19646 IntervalClosed::Neither,
19647 ] {
19648 let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
19649 assert!(bins.iter().all(|b| b.closed == closed));
19650 }
19651 }
19652
19653 #[test]
19654 fn interval_range_by_step_matches_pandas_default_case() {
19655 let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
19657 assert_eq!(bins.len(), 5);
19658 assert_eq!(bins[0].left, 0.0);
19659 assert_eq!(bins[4].right, 10.0);
19660 }
19661
19662 #[test]
19663 fn interval_range_by_step_rejects_non_positive_step() {
19664 assert!(matches!(
19665 interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
19666 Err(TypeError::InvalidIntervalStep { .. })
19667 ));
19668 assert!(matches!(
19669 interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
19670 Err(TypeError::InvalidIntervalStep { .. })
19671 ));
19672 assert!(matches!(
19673 interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
19674 Err(TypeError::InvalidIntervalStep { .. })
19675 ));
19676 assert!(matches!(
19677 interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
19678 Err(TypeError::InvalidIntervalStep { .. })
19679 ));
19680 }
19681
19682 #[test]
19683 fn interval_range_by_step_rejects_non_dividing_step() {
19684 assert!(matches!(
19687 interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
19688 Err(TypeError::IntervalStepDoesNotDivide { .. })
19689 ));
19690 }
19691
19692 #[test]
19693 fn interval_range_by_step_reversed_range_is_empty() {
19694 let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
19695 assert!(bins.is_empty());
19696 }
19697
19698 #[test]
19699 fn interval_range_by_step_degenerate_zero_span_is_empty() {
19700 let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
19701 assert!(bins.is_empty());
19702 }
19703
19704 #[test]
19705 fn interval_range_by_step_accepts_float_step_within_tolerance() {
19706 let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
19708 assert_eq!(bins.len(), 10);
19709 assert_eq!(bins.last().unwrap().right, 1.0);
19710 }
19711
19712 #[test]
19713 fn interval_range_unified_api_tests() {
19714 let r1 = interval_range(Some(0.0), Some(10.0), Some(5), None, None).expect("ok");
19716 assert_eq!(r1.len(), 5);
19717 assert_eq!(r1[0].left, 0.0);
19718 assert_eq!(r1[0].right, 2.0);
19719 assert_eq!(r1[4].right, 10.0);
19720 assert_eq!(r1[0].closed, IntervalClosed::Right);
19721
19722 let r2 = interval_range(Some(0.0), Some(10.0), None, Some(2.0), None).expect("ok");
19724 assert_eq!(r2.len(), 5);
19725 assert_eq!(r2[0].left, 0.0);
19726 assert_eq!(r2[4].right, 10.0);
19727
19728 let r3 = interval_range(
19730 Some(0.0),
19731 None,
19732 Some(5),
19733 Some(2.0),
19734 Some(IntervalClosed::Both),
19735 )
19736 .expect("ok");
19737 assert_eq!(r3.len(), 5);
19738 assert_eq!(r3[0].left, 0.0);
19739 assert_eq!(r3[4].right, 10.0);
19740 assert_eq!(r3[0].closed, IntervalClosed::Both);
19741
19742 let r4 = interval_range(
19744 None,
19745 Some(10.0),
19746 Some(5),
19747 Some(2.0),
19748 Some(IntervalClosed::Left),
19749 )
19750 .expect("ok");
19751 assert_eq!(r4.len(), 5);
19752 assert_eq!(r4[0].left, 0.0);
19753 assert_eq!(r4[4].right, 10.0);
19754 assert_eq!(r4[0].closed, IntervalClosed::Left);
19755
19756 assert!(matches!(
19758 interval_range(None, None, None, None, None),
19759 Err(TypeError::IntervalRangeParameterCount)
19760 ));
19761 assert!(matches!(
19762 interval_range(Some(0.0), Some(10.0), None, None, None),
19763 Err(TypeError::IntervalRangeParameterCount)
19764 ));
19765 assert!(matches!(
19766 interval_range(Some(0.0), Some(10.0), Some(5), Some(2.0), None),
19767 Err(TypeError::IntervalRangeParameterCount)
19768 ));
19769
19770 assert!(matches!(
19772 interval_range(Some(0.0), None, Some(5), Some(-1.0), None),
19773 Err(TypeError::InvalidIntervalStep { .. })
19774 ));
19775 assert!(matches!(
19776 interval_range(Some(0.0), None, Some(5), Some(0.0), None),
19777 Err(TypeError::InvalidIntervalStep { .. })
19778 ));
19779 }
19780
19781 #[test]
19782 fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
19783 fn next(seed: &mut u64) -> u64 {
19786 *seed = seed
19787 .wrapping_mul(2862933555777941757)
19788 .wrapping_add(3037000493);
19789 *seed
19790 }
19791
19792 fn closed_for(raw: u64) -> IntervalClosed {
19793 match raw % 4 {
19794 0 => IntervalClosed::Left,
19795 1 => IntervalClosed::Right,
19796 2 => IntervalClosed::Both,
19797 _ => IntervalClosed::Neither,
19798 }
19799 }
19800
19801 fn assert_interval(
19802 case: usize,
19803 kind: &str,
19804 pos: usize,
19805 actual: &Interval,
19806 expected: &Interval,
19807 ) {
19808 assert!(
19809 (actual.left - expected.left).abs() < 1e-12,
19810 "case={case} kind={kind} pos={pos}: expected left {}, got {}",
19811 expected.left,
19812 actual.left
19813 );
19814 assert!(
19815 (actual.right - expected.right).abs() < 1e-12,
19816 "case={case} kind={kind} pos={pos}: expected right {}, got {}",
19817 expected.right,
19818 actual.right
19819 );
19820 assert_eq!(
19821 actual.closed, expected.closed,
19822 "case={case} kind={kind} pos={pos}: closed mismatch"
19823 );
19824 }
19825
19826 fn expected_by_periods(
19827 start: f64,
19828 end: f64,
19829 periods: usize,
19830 closed: IntervalClosed,
19831 ) -> Vec<Interval> {
19832 if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
19833 return Vec::new();
19834 }
19835 let step = (end - start) / periods as f64;
19836 (0..periods)
19837 .map(|pos| {
19838 let left = start + step * pos as f64;
19839 let right = if pos + 1 == periods {
19840 end
19841 } else {
19842 start + step * (pos + 1) as f64
19843 };
19844 Interval::new(left, right, closed)
19845 })
19846 .collect()
19847 }
19848
19849 fn expected_by_step(
19850 start: f64,
19851 end: f64,
19852 step: f64,
19853 closed: IntervalClosed,
19854 ) -> Vec<Interval> {
19855 if start >= end {
19856 return Vec::new();
19857 }
19858 let count = ((end - start) / step).round() as usize;
19859 (0..count)
19860 .map(|pos| {
19861 let left = start + step * pos as f64;
19862 let right = if pos + 1 == count {
19863 end
19864 } else {
19865 start + step * (pos + 1) as f64
19866 };
19867 Interval::new(left, right, closed)
19868 })
19869 .collect()
19870 }
19871
19872 assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
19873 assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
19874 assert!(
19875 interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
19876 .expect("zero span")
19877 .is_empty()
19878 );
19879
19880 let mut seed = 0x171e_7a11_c0de_5eed_u64;
19881 for case in 0..220 {
19882 let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
19883 let periods = (next(&mut seed) % 24 + 1) as usize;
19884 let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
19885 let end = start + width;
19886 let closed = closed_for(next(&mut seed));
19887
19888 let actual = interval_range_by_periods(start, end, periods, closed);
19889 let expected = expected_by_periods(start, end, periods, closed);
19890 assert_eq!(
19891 actual.len(),
19892 expected.len(),
19893 "case={case} periods: length mismatch"
19894 );
19895 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
19896 assert_interval(case, "periods", pos, actual, expected);
19897 }
19898
19899 let step_count = (next(&mut seed) % 20 + 1) as usize;
19900 let step = (next(&mut seed) % 25 + 1) as f64;
19901 let step_end = start + step * step_count as f64;
19902 let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
19903 let expected = expected_by_step(start, step_end, step, closed);
19904 assert_eq!(
19905 actual.len(),
19906 expected.len(),
19907 "case={case} step: length mismatch"
19908 );
19909 for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
19910 assert_interval(case, "step", pos, actual, expected);
19911 }
19912 }
19913 }
19914
19915 use super::Timedelta;
19918
19919 #[test]
19920 fn timedelta_add_sums_non_nat() {
19921 let one_hour = Timedelta::NANOS_PER_HOUR;
19922 let one_day = Timedelta::NANOS_PER_DAY;
19923 assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
19924 }
19925
19926 #[test]
19927 fn timedelta_add_propagates_nat() {
19928 assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
19929 assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
19930 assert_eq!(
19931 Timedelta::add(Timedelta::NAT, Timedelta::NAT),
19932 Timedelta::NAT
19933 );
19934 }
19935
19936 #[test]
19937 fn timedelta_add_returns_nat_on_overflow() {
19938 assert_eq!(Timedelta::add(i64::MAX - 10, 100), Timedelta::NAT);
19945 assert_eq!(Timedelta::add(i64::MIN + 10, -100), Timedelta::NAT);
19948 }
19949
19950 #[test]
19951 fn timedelta_sub_subtracts_non_nat() {
19952 let one_hour = Timedelta::NANOS_PER_HOUR;
19953 assert_eq!(
19954 Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
19955 one_hour - Timedelta::NANOS_PER_MIN
19956 );
19957 }
19958
19959 #[test]
19960 fn timedelta_sub_propagates_nat() {
19961 assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
19962 assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
19963 }
19964
19965 #[test]
19966 fn timedelta_neg_flips_sign_non_nat() {
19967 assert_eq!(Timedelta::neg(5), -5);
19968 assert_eq!(Timedelta::neg(-5), 5);
19969 assert_eq!(Timedelta::neg(0), 0);
19970 }
19971
19972 #[test]
19973 fn timedelta_neg_preserves_nat() {
19974 assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
19975 }
19976
19977 #[test]
19978 fn timedelta_abs_returns_magnitude() {
19979 assert_eq!(Timedelta::abs(-5), 5);
19980 assert_eq!(Timedelta::abs(5), 5);
19981 assert_eq!(Timedelta::abs(0), 0);
19982 assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
19983 }
19984
19985 #[test]
19986 fn neg_and_abs_at_the_representable_floor_are_not_overflow_fyr1z() {
19987 const MAX: i64 = i64::MAX;
20005 const MIN_OK: i64 = i64::MIN + 1; assert_eq!(MIN_OK, -MAX);
20010 assert_eq!(Timedelta::NAT, i64::MIN);
20011
20012 assert_eq!(Timedelta::neg(MIN_OK), MAX);
20014 assert_eq!(Timedelta::neg(MAX), MIN_OK);
20015 assert_eq!(Timedelta::abs(MIN_OK), MAX);
20016 assert_eq!(Timedelta::abs(MAX), MAX);
20017
20018 assert_eq!(Timedelta::neg(Timedelta::neg(MIN_OK)), MIN_OK);
20022 assert_ne!(Timedelta::neg(MIN_OK), Timedelta::NAT);
20023 assert_ne!(Timedelta::abs(MIN_OK), Timedelta::NAT);
20024
20025 assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
20028 assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
20029 }
20030
20031 #[test]
20032 fn overflow_divergence_surface_is_only_where_pandas_refuses_fyr1z() {
20033 const MAX: i64 = i64::MAX;
20045 const MIN_OK: i64 = i64::MIN + 1;
20046
20047 assert_eq!(Timedelta::div_scalar(MAX, 0), Timedelta::NAT);
20052 assert_eq!(Timedelta::div_scalar(MIN_OK, 0), Timedelta::NAT);
20053 assert_eq!(Timedelta::div_scalar(0, 0), Timedelta::NAT);
20054
20055 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());
20065 assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(2).is_nat());
20066
20067 assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
20071 assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
20072 assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
20073
20074 assert_eq!(Timedelta::div_scalar(MAX, 1), MAX);
20076 assert_eq!(Timedelta::div_scalar(-100, 3), -34); assert_eq!(Timedelta::div_scalar(100, -3), -34);
20078 assert_eq!(Timedelta::sub(MIN_OK + 2, 1), MIN_OK + 1);
20079 }
20080
20081 #[test]
20082 fn timedelta_mul_scalar_scales() {
20083 let three_hours = Timedelta::NANOS_PER_HOUR * 3;
20084 assert_eq!(
20085 Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
20086 three_hours
20087 );
20088 assert_eq!(Timedelta::mul_scalar(100, 0), 0);
20089 assert_eq!(Timedelta::mul_scalar(100, -2), -200);
20090 }
20091
20092 #[test]
20093 fn timedelta_mul_scalar_returns_nat_on_overflow() {
20094 assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), Timedelta::NAT);
20097 assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), Timedelta::NAT);
20098 }
20099
20100 #[test]
20101 fn from_unit_nan_is_nat_and_overflow_is_err_8v92m() {
20102 use super::TimedeltaError;
20103
20104 assert_eq!(Timedelta::from_unit(f64::NAN, "s"), Ok(Timedelta::NAT));
20122 assert_ne!(Timedelta::from_unit(f64::NAN, "s"), Ok(0));
20123 assert_eq!(Timedelta::from_unit(f64::NAN, "D"), Ok(Timedelta::NAT));
20124
20125 assert_eq!(
20127 Timedelta::from_unit(f64::INFINITY, "s"),
20128 Err(TimedeltaError::Overflow)
20129 );
20130 assert_eq!(
20131 Timedelta::from_unit(f64::NEG_INFINITY, "s"),
20132 Err(TimedeltaError::Overflow)
20133 );
20134 assert_eq!(
20135 Timedelta::from_unit(1e30, "s"),
20136 Err(TimedeltaError::Overflow)
20137 );
20138 assert_eq!(
20139 Timedelta::from_unit(1e30, "D"),
20140 Err(TimedeltaError::Overflow)
20141 );
20142
20143 assert_eq!(Timedelta::from_unit(1.5, "s"), Ok(1_500_000_000));
20146 assert_eq!(Timedelta::from_unit(0.0, "s"), Ok(0));
20147 assert_eq!(Timedelta::from_unit(-2.5, "s"), Ok(-2_500_000_000));
20148 assert_eq!(Timedelta::from_unit(1.0, "D"), Ok(Timedelta::NANOS_PER_DAY));
20149 assert_eq!(
20150 Timedelta::from_unit(3.0, "h"),
20151 Ok(3 * Timedelta::NANOS_PER_HOUR)
20152 );
20153 let big_days = 100_000.0_f64;
20156 let expected = (big_days * Timedelta::NANOS_PER_DAY as f64).round() as i64;
20157 assert_eq!(Timedelta::from_unit(big_days, "D"), Ok(expected));
20158 assert!(expected > 0, "fixture must stay in range to be a control");
20159
20160 assert!(matches!(
20163 Timedelta::from_unit(1.0, "nonsense-unit"),
20164 Err(TimedeltaError::InvalidFormat(_))
20165 ));
20166 assert!(matches!(
20167 Timedelta::from_unit(f64::NAN, "nonsense-unit"),
20168 Err(TimedeltaError::InvalidFormat(_)),
20169 ));
20170
20171 let huge = format!("{} days", "9".repeat(18));
20176 assert!(matches!(
20177 Timedelta::parse(&huge),
20178 Err(TimedeltaError::Overflow)
20179 ));
20180 assert!(matches!(
20181 Timedelta::parse("1e100 days"),
20182 Err(TimedeltaError::InvalidFormat(_))
20183 ));
20184 }
20185
20186 #[test]
20187 fn rounding_and_ms_us_overflow_never_fabricates_a_finite_value_kyd16() {
20188 const MAX: i64 = i64::MAX;
20207 const MIN_OK: i64 = i64::MIN + 1;
20208 const DAY: i64 = Timedelta::NANOS_PER_DAY;
20209
20210 let rounded = Timedelta::round(MAX, "D");
20212 assert_eq!(
20213 rounded,
20214 Timedelta::NAT,
20215 "rounding i64::MAX up to a whole day overflows; the old unchecked \
20216 multiply panicked in debug and wrapped in release"
20217 );
20218 assert!(
20222 rounded == Timedelta::NAT || rounded > 0,
20223 "a positive duration must never round to a negative one"
20224 );
20225 assert_eq!(Timedelta::round(MIN_OK, "D"), Timedelta::NAT);
20226
20227 assert_eq!(Timedelta::ceil(MAX, "D"), Timedelta::NAT);
20229 assert_eq!(Timedelta::floor(MIN_OK, "D"), Timedelta::NAT);
20230 assert!(Timestamp::from_nanos(MAX).ceil_to(DAY).is_nat());
20231 assert!(Timestamp::from_nanos(MAX).round_to(DAY).is_nat());
20232 assert!(Timestamp::from_nanos(MIN_OK).floor_to(DAY).is_nat());
20233 assert!(Timestamp::from_nanos(MIN_OK).round_to(DAY).is_nat());
20234
20235 assert!(Timestamp::from_millis(MAX, None).is_nat());
20237 assert!(Timestamp::from_millis(MIN_OK, None).is_nat());
20238 assert!(Timestamp::from_micros(MAX, None).is_nat());
20239 assert!(Timestamp::from_micros(MIN_OK, Some("US/Eastern")).is_nat());
20240
20241 let max_floor = Timestamp::from_nanos(MAX).floor_to(DAY);
20248 assert!(!max_floor.is_nat(), "Timestamp.max.floor(D) must succeed");
20249 assert_eq!(max_floor.nanos, (MAX / DAY) * DAY);
20250 assert_eq!(Timedelta::floor(MAX, "D"), (MAX / DAY) * DAY);
20251 assert_eq!(
20252 Timedelta::ceil(MIN_OK, "D"),
20253 (MIN_OK.div_euclid(DAY) + 1) * DAY
20254 );
20255
20256 let hour = Timedelta::NANOS_PER_HOUR;
20258 assert_eq!(Timedelta::floor(90 * 60 * 1_000_000_000, "h"), hour);
20259 assert_eq!(Timedelta::ceil(90 * 60 * 1_000_000_000, "h"), 2 * hour);
20260 assert_eq!(Timedelta::round(90 * 60 * 1_000_000_000, "h"), 2 * hour);
20261 assert_eq!(Timedelta::round(-90 * 60 * 1_000_000_000, "h"), -2 * hour);
20262 assert_eq!(Timedelta::round(29 * 60 * 1_000_000_000, "h"), 0);
20263 assert_eq!(Timestamp::from_millis(1_500, None).nanos, 1_500_000_000);
20264 assert_eq!(Timestamp::from_micros(-2_000, None).nanos, -2_000_000);
20265 assert_eq!(
20266 Timestamp::from_nanos(hour + 1).floor_to(hour).nanos,
20267 hour,
20268 "in-range floor unchanged"
20269 );
20270 assert_eq!(
20271 Timestamp::from_nanos(hour + 1).ceil_to(hour).nanos,
20272 2 * hour,
20273 "in-range ceil unchanged"
20274 );
20275
20276 assert_eq!(Timedelta::round(Timedelta::NAT, "D"), Timedelta::NAT);
20278 assert_eq!(Timedelta::floor(Timedelta::NAT, "D"), Timedelta::NAT);
20279 assert_eq!(Timedelta::ceil(1_000, "nonsense-unit"), Timedelta::NAT);
20280 assert!(Timestamp::nat().ceil_to(DAY).is_nat());
20281 assert!(Timestamp::from_nanos(0).round_to(0).is_nat());
20282 assert_eq!(
20284 Timestamp::from_nanos_tz(hour + 1, "US/Eastern")
20285 .ceil_to(hour)
20286 .tz
20287 .as_deref(),
20288 Some("US/Eastern")
20289 );
20290 }
20291
20292 #[test]
20293 fn timedelta_mul_scalar_propagates_nat() {
20294 assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
20295 }
20296
20297 #[test]
20298 fn arithmetic_overflow_never_fabricates_a_finite_value_lgyy8() {
20299 const MAX: i64 = i64::MAX;
20314 const MIN_OK: i64 = i64::MIN + 1; assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
20318 assert_eq!(Timedelta::add(MAX - 10, 100), Timedelta::NAT);
20319 assert_eq!(Timedelta::sub(MAX, -1), Timedelta::NAT);
20320 assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
20321 assert_eq!(Timedelta::mul_scalar(MAX / 2 + 2, 2), Timedelta::NAT);
20322 assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
20323 assert!(Timestamp::from_nanos(MAX).sub_timedelta(-1).is_nat());
20324 assert_eq!(
20328 Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(MIN_OK)),
20329 Timedelta::NAT
20330 );
20331
20332 assert_eq!(Timedelta::add(MIN_OK, -1), Timedelta::NAT);
20334 assert_eq!(Timedelta::add(MIN_OK, -2), Timedelta::NAT);
20335 assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
20336 assert_eq!(Timedelta::mul_scalar(MIN_OK, 2), Timedelta::NAT);
20337 assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
20338 assert!(Timestamp::from_nanos(MIN_OK).add_timedelta(-1).is_nat());
20339 assert_eq!(
20340 Timestamp::from_nanos(MIN_OK).sub_timestamp(&Timestamp::from_nanos(MAX)),
20341 Timedelta::NAT
20342 );
20343
20344 assert_eq!(Timedelta::add(MAX - 1, 1), MAX);
20350 assert_eq!(Timedelta::add(MAX, 0), MAX);
20351 assert_eq!(Timedelta::sub(MAX, 1), MAX - 1);
20352 assert_eq!(Timedelta::add(MIN_OK + 1, -1), MIN_OK);
20353 assert_eq!(Timedelta::mul_scalar(MAX / 2, 2), (MAX / 2) * 2);
20354 assert_eq!(Timedelta::mul_scalar(MIN_OK, 1), MIN_OK);
20355 assert_eq!(Timestamp::from_nanos(MAX - 1).add_timedelta(1).nanos, MAX);
20356 assert_eq!(
20357 Timestamp::from_nanos(MIN_OK + 1).sub_timedelta(1).nanos,
20358 MIN_OK
20359 );
20360 assert_eq!(
20361 Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(0)),
20362 MAX
20363 );
20364 assert_eq!(Timedelta::add(1_000, 2_345), 3_345);
20366 assert_eq!(Timedelta::sub(1_000, 2_345), -1_345);
20367 assert_eq!(Timedelta::mul_scalar(-7, 6), -42);
20368
20369 assert_eq!(MIN_OK - 1, i64::MIN);
20376 assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
20377 assert_eq!(Timedelta::add(MIN_OK, 0), MIN_OK);
20378
20379 assert!(Timestamp::nat().add_timedelta(1).is_nat());
20382 assert!(
20383 Timestamp::from_nanos(0)
20384 .add_timedelta(Timedelta::NAT)
20385 .is_nat()
20386 );
20387 let tzed = Timestamp::from_nanos_tz(MAX, "US/Eastern");
20388 let overflowed = tzed.add_timedelta(1);
20389 assert!(overflowed.is_nat());
20390 assert_eq!(overflowed.tz, None, "an overflow NaT carries no zone");
20391 assert_eq!(
20393 Timestamp::from_nanos_tz(0, "US/Eastern")
20394 .add_timedelta(Timedelta::NANOS_PER_DAY)
20395 .tz
20396 .as_deref(),
20397 Some("US/Eastern")
20398 );
20399 }
20400
20401 #[test]
20402 fn timedelta_div_scalar_floor_divides() {
20403 assert_eq!(Timedelta::div_scalar(100, 3), 33);
20405 assert_eq!(Timedelta::div_scalar(-100, 3), -34);
20406 assert_eq!(Timedelta::div_scalar(100, -3), -34);
20407 assert_eq!(Timedelta::div_scalar(-100, -3), 33);
20408 }
20409
20410 #[test]
20411 fn timedelta_div_scalar_zero_divisor_returns_nat() {
20412 assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
20413 }
20414
20415 #[test]
20416 fn timedelta_div_scalar_min_neg_one_propagates_nat() {
20417 assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
20420 assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
20422 }
20423
20424 #[test]
20425 fn timedelta_div_scalar_propagates_nat() {
20426 assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
20427 }
20428
20429 #[test]
20430 fn timedelta_div_timedelta_returns_float_ratio() {
20431 let two_hours = Timedelta::NANOS_PER_HOUR * 2;
20432 let one_hour = Timedelta::NANOS_PER_HOUR;
20433 assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
20434 assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
20435 }
20436
20437 #[test]
20438 fn timedelta_div_timedelta_nat_returns_nan() {
20439 assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
20440 assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
20441 }
20442
20443 use super::Timestamp;
20446
20447 #[test]
20448 fn timestamp_from_nanos_is_naive_utc() {
20449 let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
20450 assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
20451 assert_eq!(ts.tz, None);
20452 assert!(!ts.is_nat());
20453 }
20454
20455 #[test]
20456 fn timestamp_from_nanos_tz_carries_tz_name() {
20457 let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
20458 assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
20459 }
20460
20461 #[test]
20462 fn timestamp_now_returns_current_time() {
20463 let before = std::time::SystemTime::now()
20464 .duration_since(std::time::UNIX_EPOCH)
20465 .unwrap()
20466 .as_nanos() as i64;
20467 let ts = Timestamp::now();
20468 let after = std::time::SystemTime::now()
20469 .duration_since(std::time::UNIX_EPOCH)
20470 .unwrap()
20471 .as_nanos() as i64;
20472 assert!(ts.nanos >= before);
20473 assert!(ts.nanos <= after);
20474 assert!(!ts.is_nat());
20475 }
20476
20477 #[test]
20478 fn timestamp_today_returns_midnight() {
20479 let ts = Timestamp::today();
20480 assert!(!ts.is_nat());
20481 assert_eq!(ts.hour(), Some(0));
20483 assert_eq!(ts.minute(), Some(0));
20484 assert_eq!(ts.second(), Some(0));
20485 }
20486
20487 #[test]
20488 fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
20489 let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
20490 let one_day = Timedelta::NANOS_PER_DAY;
20491 let shifted = ts.add_timedelta(one_day);
20492 assert_eq!(shifted.nanos, one_day);
20493 assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
20494 }
20495
20496 #[test]
20497 fn timestamp_add_timedelta_returns_nat_on_overflow() {
20498 let ts = Timestamp::from_nanos(i64::MAX - 10);
20502 assert!(ts.add_timedelta(100).is_nat());
20503 }
20504
20505 #[test]
20506 fn timestamp_add_timedelta_propagates_nat() {
20507 assert!(Timestamp::nat().add_timedelta(100).is_nat());
20509 assert!(
20511 Timestamp::from_nanos(0)
20512 .add_timedelta(Timedelta::NAT)
20513 .is_nat()
20514 );
20515 }
20516
20517 #[test]
20518 fn timestamp_sub_timedelta_shifts_backward() {
20519 let ts = Timestamp::from_nanos(1_000);
20520 let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
20521 assert_eq!(shifted.nanos, 0);
20522 }
20523
20524 #[test]
20525 fn timestamp_sub_timestamp_returns_timedelta_nanos() {
20526 let t0 = Timestamp::from_nanos(0);
20527 let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
20528 assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
20529 assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
20530 }
20531
20532 #[test]
20533 fn timestamp_sub_timestamp_nat_propagates() {
20534 let ts = Timestamp::from_nanos(1_000);
20535 assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
20536 assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
20537 }
20538
20539 #[test]
20540 fn timestamp_semantic_eq_treats_two_nat_as_equal() {
20541 assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
20542 assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
20543 assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
20544 }
20545
20546 #[test]
20547 fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
20548 use std::cmp::Ordering;
20549 let a = Timestamp::from_nanos(0);
20550 let b = Timestamp::from_nanos(100);
20551 assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
20552 assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
20553 assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
20554 assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
20555 assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
20556 }
20557
20558 #[test]
20559 fn time_zone_offsets_and_wall_clock_conversions_follow_pandas() {
20560 use crate::{
20561 TimeZoneError, tz_abbreviation, tz_canonical_name, tz_offset_seconds,
20562 tz_utc_to_wall_nanos, tz_validate, tz_wall_to_utc_nanos,
20563 };
20564 let hour = 3_600_000_000_000_i64;
20565 let instant = 1_710_081_000_000_000_000_i64;
20568 assert_eq!(tz_offset_seconds("Asia/Tokyo", instant), Ok(9 * 3_600));
20569 assert_eq!(tz_offset_seconds("US/Eastern", instant), Ok(-4 * 3_600));
20570 assert_eq!(
20571 tz_offset_seconds("US/Eastern", instant - 24 * hour),
20572 Ok(-5 * 3_600)
20573 );
20574 assert_eq!(tz_offset_seconds("+05:30", 0), Ok(19_800));
20575 assert_eq!(tz_offset_seconds("UTC+05:30", 0), Ok(19_800));
20576 assert_eq!(tz_offset_seconds("-03:00", 0), Ok(-10_800));
20577 assert_eq!(tz_offset_seconds("UTC", instant), Ok(0));
20578 assert_eq!(
20579 tz_utc_to_wall_nanos("Asia/Tokyo", instant),
20580 Ok(instant + 9 * hour)
20581 );
20582 let wall_noon = 19_723 * 24 * hour + 12 * hour;
20584 assert_eq!(
20585 tz_wall_to_utc_nanos("US/Eastern", wall_noon),
20586 Ok(wall_noon + 5 * hour)
20587 );
20588 assert_eq!(
20589 tz_utc_to_wall_nanos("US/Eastern", wall_noon + 5 * hour),
20590 Ok(wall_noon)
20591 );
20592 assert_eq!(tz_wall_to_utc_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
20594 assert_eq!(tz_utc_to_wall_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
20595 let skipped = 19_792 * 24 * hour + 2 * hour + 30 * 60_000_000_000;
20599 assert_eq!(
20600 tz_wall_to_utc_nanos("US/Eastern", skipped),
20601 Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
20602 );
20603 let repeated = 20_030 * 24 * hour + hour + 30 * 60_000_000_000;
20604 assert_eq!(
20605 tz_wall_to_utc_nanos("US/Eastern", repeated),
20606 Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
20607 );
20608 assert_eq!(
20609 tz_offset_seconds("Mars/Olympus", 0),
20610 Err(TimeZoneError::Unknown("Mars/Olympus".to_owned()))
20611 );
20612 assert!(tz_validate("+24:00").is_err());
20613 assert!(tz_validate("+5:30").is_err());
20614 assert!(tz_validate("Europe/Paris").is_ok());
20615 assert_eq!(tz_canonical_name("+05:30").as_deref(), Ok("UTC+05:30"));
20617 assert_eq!(tz_canonical_name("UTC-03:00").as_deref(), Ok("UTC-03:00"));
20618 assert_eq!(tz_canonical_name("+00:00").as_deref(), Ok("UTC"));
20619 assert_eq!(tz_canonical_name("Z").as_deref(), Ok("UTC"));
20620 assert_eq!(tz_canonical_name("US/Eastern").as_deref(), Ok("US/Eastern"));
20621 assert_eq!(tz_abbreviation("US/Eastern", instant).as_deref(), Ok("EDT"));
20623 assert_eq!(
20624 tz_abbreviation("US/Eastern", instant - 24 * hour).as_deref(),
20625 Ok("EST")
20626 );
20627 assert_eq!(tz_abbreviation("+05:30", 0).as_deref(), Ok("UTC+05:30"));
20628 }
20629
20630 #[test]
20637 fn tz_localize_policies_follow_pandas_84w06() {
20638 use super::{
20639 AmbiguousTime as A, NonexistentTime as N, TimeZoneError,
20640 tz_wall_to_utc_nanos_with as at,
20641 };
20642 let hour = 3_600_000_000_000_i64;
20643 let minute = 60_000_000_000_i64;
20644 let skipped = 19_792 * 24 * hour + 2 * hour + 30 * minute;
20645 let transition = 19_792 * 24 * hour + 7 * hour;
20646 let zone = "America/New_York";
20647 assert_eq!(at(zone, skipped, A::Raise, N::ShiftForward), Ok(transition));
20648 assert_eq!(
20649 at(zone, skipped, A::Raise, N::ShiftBackward),
20650 Ok(transition - 1)
20651 );
20652 assert_eq!(at(zone, skipped, A::Raise, N::NaT), Ok(i64::MIN));
20653 assert_eq!(
20654 at(zone, skipped, A::Raise, N::Shift(hour)),
20655 Ok(transition + 30 * minute)
20656 );
20657 let repeated = 20_030 * 24 * hour + hour + 30 * minute;
20658 assert_eq!(
20659 at(zone, repeated, A::Earliest, N::Raise),
20660 Ok(repeated + 4 * hour)
20661 );
20662 assert_eq!(
20663 at(zone, repeated, A::Latest, N::Raise),
20664 Ok(repeated + 5 * hour)
20665 );
20666 assert_eq!(at(zone, repeated, A::NaT, N::Raise), Ok(i64::MIN));
20667 let noon = 19_723 * 24 * hour + 12 * hour;
20670 assert_eq!(at(zone, noon, A::NaT, N::NaT), Ok(noon + 5 * hour));
20671 assert_eq!(
20672 at(zone, skipped, A::NaT, N::Raise),
20673 Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
20674 );
20675 assert_eq!(
20676 at(zone, repeated, A::Raise, N::NaT),
20677 Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
20678 );
20679 }
20680
20681 #[test]
20689 fn batch_tz_conversions_match_each_value_6pqf3() {
20690 use super::{
20691 AmbiguousTime as A, NonexistentTime as N, TimeZoneError, tz_utc_to_wall_nanos,
20692 tz_utc_to_wall_nanos_all, tz_wall_to_utc_nanos_all, tz_wall_to_utc_nanos_with,
20693 };
20694 const HOUR: i64 = 3_600_000_000_000;
20695 const MINUTE: i64 = 60_000_000_000;
20696 const DAY: i64 = 24 * HOUR;
20697 let (year_start, year_end) = (19_723 * DAY, 20_089 * DAY);
20698 let mut values: Vec<i64> = (year_start..year_end)
20699 .step_by(usize::try_from(37 * MINUTE).unwrap())
20700 .collect();
20701 for hour in (year_start..year_end).step_by(usize::try_from(HOUR).unwrap()) {
20702 values.extend([hour - 1, hour, hour + 1]);
20703 }
20704 for change_day in [19_792, 20_030, 19_813, 20_023, 19_820, 20_002] {
20705 values.extend((0..2 * 24 * 60).map(|minute| (change_day - 1) * DAY + minute * MINUTE));
20706 }
20707 let mut state = 0x2545_f491_4f6c_dd1d_u64;
20708 for _ in 0..3_000 {
20709 state = state
20710 .wrapping_mul(6_364_136_223_846_793_005)
20711 .wrapping_add(1_442_695_040_888_963_407);
20712 values.push(i64::try_from(state >> 2).unwrap() - 2_000_000_000_000_000_000);
20713 }
20714 values.extend([i64::MIN, 19_792 * DAY, i64::MIN]);
20715 let policies = [
20716 (A::NaT, N::NaT),
20717 (A::Earliest, N::ShiftForward),
20718 (A::Latest, N::ShiftBackward),
20719 (A::NaT, N::Shift(30 * MINUTE)),
20720 ];
20721 for zone in [
20722 "US/Eastern",
20723 "Europe/London",
20724 "Australia/Lord_Howe",
20725 "+05:30",
20726 "UTC",
20727 ] {
20728 let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20729 .iter()
20730 .map(|&nanos| tz_utc_to_wall_nanos(zone, nanos))
20731 .collect();
20732 assert_eq!(
20733 tz_utc_to_wall_nanos_all(zone, &values),
20734 one_by_one,
20735 "{zone}"
20736 );
20737 for (ambiguous, nonexistent) in policies {
20738 let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20739 .iter()
20740 .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, ambiguous, nonexistent))
20741 .collect();
20742 assert_eq!(
20743 tz_wall_to_utc_nanos_all(zone, &values, ambiguous, nonexistent),
20744 one_by_one,
20745 "{zone} {ambiguous:?} {nonexistent:?}"
20746 );
20747 }
20748 let one_by_one: Result<Vec<i64>, TimeZoneError> = values
20749 .iter()
20750 .map(|&wall| tz_wall_to_utc_nanos_with(zone, wall, A::Raise, N::Raise))
20751 .collect();
20752 assert_eq!(
20753 tz_wall_to_utc_nanos_all(zone, &values, A::Raise, N::Raise),
20754 one_by_one,
20755 "{zone} raise"
20756 );
20757 }
20758 let skipped = 19_792 * DAY + 2 * HOUR + 30 * MINUTE;
20759 let run: Vec<i64> = (0..8)
20761 .map(|step| 19_792 * DAY + HOUR + 10 * MINUTE + step * 20 * MINUTE)
20762 .collect();
20763 assert_eq!(
20764 tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::Raise),
20765 Err(TimeZoneError::NonExistent("2024-03-10 02:10:00".to_owned()))
20766 );
20767 let placed = tz_wall_to_utc_nanos_all("US/Eastern", &run, A::Raise, N::NaT).unwrap();
20768 let expected: Vec<i64> = run
20769 .iter()
20770 .enumerate()
20771 .map(|(step, &wall)| match step {
20772 0..3 => wall + 5 * HOUR,
20773 3..6 => i64::MIN,
20774 _ => wall + 4 * HOUR,
20775 })
20776 .collect();
20777 assert_eq!(placed, expected);
20778 let howe = 20_002 * DAY + 2 * HOUR + 10 * MINUTE;
20782 assert_eq!(
20783 tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftForward),
20784 Ok(vec![20_002 * DAY - 8 * HOUR])
20785 );
20786 assert_eq!(
20787 tz_wall_to_utc_nanos_all("Australia/Lord_Howe", &[howe], A::Raise, N::ShiftBackward),
20788 Ok(vec![20_002 * DAY - 8 * HOUR - 30 * MINUTE - 1])
20789 );
20790 for (wall, text) in [
20791 (skipped + 500_000_000, "2024-03-10 02:30:00.500000"),
20792 (skipped + 1, "2024-03-10 02:30:00.000000001"),
20793 ] {
20794 assert_eq!(
20795 tz_wall_to_utc_nanos_all("US/Eastern", &[wall], A::Raise, N::Raise),
20796 Err(TimeZoneError::NonExistent(text.to_owned()))
20797 );
20798 }
20799 }
20800
20801 #[test]
20802 fn timestamp_display_matches_phase2_debug_format() {
20803 assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
20804 assert_eq!(
20805 Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
20806 "Timestamp[42, US/Eastern]"
20807 );
20808 assert_eq!(Timestamp::nat().to_string(), "NaT");
20809 }
20810
20811 #[test]
20812 fn a_naive_timestamp_cell_casts_to_its_str_srzqw() {
20813 let text = |nanos: i64| cast_scalar(&Scalar::Datetime64(nanos), DType::Utf8);
20817 let midnight = 1_711_929_600_000_000_000;
20818 assert_eq!(
20819 text(midnight),
20820 Ok(Scalar::Utf8("2024-04-01 00:00:00".into()))
20821 );
20822 assert_eq!(
20823 text(midnight + 1_000),
20824 Ok(Scalar::Utf8("2024-04-01 00:00:00.000001".into()))
20825 );
20826 assert_eq!(
20827 text(midnight + 1),
20828 Ok(Scalar::Utf8("2024-04-01 00:00:00.000000001".into()))
20829 );
20830 assert_eq!(
20831 text(-1),
20832 Ok(Scalar::Utf8("1969-12-31 23:59:59.999999999".into()))
20833 );
20834 assert_eq!(text(Timestamp::NAT), Ok(Scalar::Utf8("NaT".into())));
20835 assert_eq!(
20837 crate::timestamp_text_in_zone(midnight, "US/Eastern"),
20838 "2024-03-31 20:00:00-04:00"
20839 );
20840 }
20841
20842 #[test]
20843 fn timestamp_value_and_unit_match_pandas_l0edr() {
20844 let ts = Timestamp::from_nanos(1_000_000_123);
20845 assert_eq!(ts.value(), 1_000_000_123);
20846 assert_eq!(ts.unit(), Some("ns"));
20847
20848 let nat = Timestamp::nat();
20849 assert_eq!(nat.value(), Timestamp::NAT);
20850 assert_eq!(nat.unit(), None);
20851 }
20852
20853 #[test]
20854 fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
20855 let ts = Timestamp::from_nanos(1_000_000_123);
20856 assert_eq!(ts.asm8(), ts.value());
20857 assert_eq!(ts.to_datetime64(), ts.value());
20858 assert_eq!(ts.to_numpy(), ts.value());
20859
20860 let nat = Timestamp::nat();
20861 assert_eq!(nat.asm8(), Timestamp::NAT);
20862 assert_eq!(nat.to_datetime64(), Timestamp::NAT);
20863 assert_eq!(nat.to_numpy(), Timestamp::NAT);
20864 }
20865
20866 #[test]
20867 fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
20868 assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
20869 assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
20870 assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
20871 assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
20872 assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
20873
20874 assert!(matches!(
20875 Timestamp::from_nanos(-500).timestamp(),
20876 Ok(value) if value == -0.0 && value.is_sign_negative()
20877 ));
20878 assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
20879 assert_eq!(
20880 Timestamp::nat().timestamp(),
20881 Err(TypeError::ValueIsMissing {
20882 kind: NullKind::NaT,
20883 })
20884 );
20885 }
20886
20887 #[test]
20888 fn timestamp_roundtrips_through_serde_json() {
20889 let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
20890 let json = serde_json::to_string(&naive).expect("serialize");
20891 let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
20892 assert_eq!(naive, back);
20893
20894 let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
20895 let json = serde_json::to_string(&tz_aware).expect("serialize");
20896 let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
20897 assert_eq!(tz_aware, back);
20898 }
20899
20900 #[test]
20901 fn timestamp_is_send_and_sync() {
20902 fn assert_send_sync<T: Send + Sync>() {}
20903 assert_send_sync::<Timestamp>();
20904 }
20905
20906 #[test]
20909 fn timestamp_pre_epoch_accessors_floor_not_truncate() {
20910 let ts = Timestamp::from_nanos(-1);
20914 assert_eq!(ts.year(), Some(1969));
20915 assert_eq!(ts.month(), Some(12));
20916 assert_eq!(ts.day(), Some(31));
20917 assert_eq!(ts.hour(), Some(23));
20918 assert_eq!(ts.minute(), Some(59));
20919 assert_eq!(ts.second(), Some(59));
20920 assert_eq!(ts.microsecond(), Some(999_999));
20921 assert_eq!(ts.nanosecond(), Some(999));
20922 assert_eq!(ts.dayofweek(), Some(2));
20924
20925 let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
20927 assert_eq!(noon.year(), Some(1969));
20928 assert_eq!(noon.month(), Some(12));
20929 assert_eq!(noon.day(), Some(31));
20930 assert_eq!(noon.hour(), Some(12));
20931
20932 let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
20934 assert_eq!(midnight.year(), Some(1969));
20935 assert_eq!(midnight.day(), Some(31));
20936 assert_eq!(midnight.hour(), Some(0));
20937 }
20938
20939 #[test]
20940 fn timestamp_floor_to_rounds_down() {
20941 let h = Timedelta::NANOS_PER_HOUR;
20943 let twelve_h = h * 12;
20944 let twelve_thirty_four =
20945 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20946 let ts = Timestamp::from_nanos(twelve_thirty_four);
20947 let floored = ts.floor_to(h);
20948 assert_eq!(floored.nanos, twelve_h);
20949 }
20950
20951 #[test]
20952 fn timestamp_floor_to_handles_already_aligned() {
20953 let h = Timedelta::NANOS_PER_HOUR;
20955 let twelve_h = h * 12;
20956 let ts = Timestamp::from_nanos(twelve_h);
20957 assert_eq!(ts.floor_to(h).nanos, twelve_h);
20958 }
20959
20960 #[test]
20961 fn timestamp_floor_to_handles_negative_nanos() {
20962 let ts = Timestamp::from_nanos(-100);
20966 assert_eq!(ts.floor_to(60).nanos, -120);
20967 }
20968
20969 #[test]
20970 fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
20971 let ts = Timestamp::from_nanos(i64::MIN + 1);
20972 assert!(ts.floor_to(10).is_nat());
20973
20974 let safe = Timestamp::from_nanos(i64::MIN + 10);
20975 assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
20976
20977 let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
20978 assert_eq!(tz.nanos, -120);
20979 assert_eq!(tz.tz.as_deref(), Some("UTC"));
20980 }
20981
20982 #[test]
20983 fn timestamp_ceil_to_rounds_up() {
20984 let h = Timedelta::NANOS_PER_HOUR;
20986 let twelve_h = h * 12;
20987 let thirteen_h = h * 13;
20988 let twelve_thirty_four =
20989 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
20990 let ts = Timestamp::from_nanos(twelve_thirty_four);
20991 assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
20992 }
20993
20994 #[test]
20995 fn timestamp_ceil_to_no_op_on_aligned() {
20996 let h = Timedelta::NANOS_PER_HOUR;
20997 let twelve_h = h * 12;
20998 let ts = Timestamp::from_nanos(twelve_h);
20999 assert_eq!(ts.ceil_to(h).nanos, twelve_h);
21000 }
21001
21002 #[test]
21003 fn timestamp_round_to_rounds_to_nearest() {
21004 let h = Timedelta::NANOS_PER_HOUR;
21006 let twelve_h = h * 12;
21007 let twelve_thirty_one_sec =
21008 twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
21009 let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
21010 assert_eq!(ts.round_to(h).nanos, h * 13);
21011
21012 let twelve_twenty_nine_sec =
21014 twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
21015 let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
21016 assert_eq!(ts.round_to(h).nanos, twelve_h);
21017 }
21018
21019 #[test]
21020 fn timestamp_round_to_bankers_tie_to_even() {
21021 assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
21027 assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
21028 assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
21029 assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
21030 }
21031
21032 #[test]
21033 fn timestamp_round_to_zero_unit_returns_nat() {
21034 let ts = Timestamp::from_nanos(100);
21035 assert!(ts.round_to(0).is_nat());
21036 assert!(ts.floor_to(0).is_nat());
21037 assert!(ts.ceil_to(0).is_nat());
21038 }
21039
21040 #[test]
21041 fn timestamp_round_to_negative_unit_returns_nat() {
21042 let ts = Timestamp::from_nanos(100);
21043 assert!(ts.round_to(-10).is_nat());
21044 assert!(ts.floor_to(-10).is_nat());
21045 assert!(ts.ceil_to(-10).is_nat());
21046 }
21047
21048 #[test]
21049 fn timestamp_rounding_propagates_nat() {
21050 let nat = Timestamp::nat();
21051 assert!(nat.floor_to(60).is_nat());
21052 assert!(nat.ceil_to(60).is_nat());
21053 assert!(nat.round_to(60).is_nat());
21054 }
21055
21056 #[test]
21057 fn timestamp_rounding_preserves_tz() {
21058 let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
21059 assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
21060 assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
21061 assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
21062 }
21063
21064 #[test]
21067 fn timestamp_floor_to_unit_h_rounds_to_hour() {
21068 let h = Timedelta::NANOS_PER_HOUR;
21069 let twelve_h = h * 12;
21070 let twelve_thirty_four =
21071 twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
21072 let ts = Timestamp::from_nanos(twelve_thirty_four);
21073 assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
21074 assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
21075 assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
21076 assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
21077 assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
21078 }
21079
21080 #[test]
21081 fn timestamp_ceil_to_unit_d_rounds_to_day() {
21082 let h = Timedelta::NANOS_PER_HOUR;
21084 let d = Timedelta::NANOS_PER_DAY;
21085 let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
21086 let ts = Timestamp::from_nanos(twelve_thirty_four);
21087 assert_eq!(ts.ceil_to_unit("D").nanos, d);
21088 assert_eq!(ts.ceil_to_unit("day").nanos, d);
21089 assert_eq!(ts.ceil_to_unit("days").nanos, d);
21090 }
21091
21092 #[test]
21093 fn timestamp_round_to_unit_min_rounds_to_minute() {
21094 let m = Timedelta::NANOS_PER_MIN;
21096 let twelve_thirty_four_thirty_one =
21097 Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
21098 let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
21099 let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
21100 assert_eq!(ts.round_to_unit("min").nanos, expected);
21101 assert_eq!(ts.round_to_unit("T").nanos, expected); assert_eq!(ts.round_to_unit("minute").nanos, expected);
21103 }
21104
21105 #[test]
21106 fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
21107 let ts = Timestamp::from_nanos(
21108 Timedelta::NANOS_PER_HOUR * 12
21109 + Timedelta::NANOS_PER_MIN * 34
21110 + Timedelta::NANOS_PER_SEC * 31,
21111 );
21112
21113 assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
21114 assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
21115 assert_eq!(ts.round("min"), ts.round_to_unit("min"));
21116 }
21117
21118 #[test]
21119 fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
21120 let ts = Timestamp::from_nanos_tz(
21121 Timedelta::NANOS_PER_DAY * 3
21122 + Timedelta::NANOS_PER_HOUR * 12
21123 + Timedelta::NANOS_PER_MIN * 34,
21124 "US/Eastern",
21125 );
21126 let normalized = ts.normalize();
21127
21128 assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
21129 assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
21130 assert!(Timestamp::nat().normalize().is_nat());
21131 for nanos in [
21132 i64::MIN + 1,
21133 -Timedelta::NANOS_PER_DAY - 1,
21134 -Timedelta::NANOS_PER_DAY,
21135 -1,
21136 0,
21137 Timedelta::NANOS_PER_DAY - 1,
21138 Timedelta::NANOS_PER_DAY,
21139 i64::MAX,
21140 ] {
21141 let timestamp = Timestamp::from_nanos(nanos);
21142 assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
21143 }
21144 }
21145
21146 #[test]
21147 #[ignore = "foreground profile-first A/B"]
21148 fn timestamp_normalize_direct_day_profile_dk721() {
21149 use std::{hint::black_box, time::Instant};
21150
21151 fn former(timestamp: &Timestamp) -> Timestamp {
21152 timestamp.floor_to_unit("D")
21153 }
21154
21155 fn candidate(timestamp: &Timestamp) -> Timestamp {
21156 timestamp.normalize()
21157 }
21158
21159 fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
21160 let started = Instant::now();
21161 let mut checksum = 0_u64;
21162 for timestamp in input {
21163 let normalized = normalize(black_box(timestamp));
21164 checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
21165 }
21166 black_box(checksum);
21167 started.elapsed().as_nanos()
21168 }
21169
21170 fn percentile(samples: &mut [u128], percent: usize) -> u128 {
21171 samples.sort_unstable();
21172 let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
21173 samples[rank]
21174 }
21175
21176 let parity_cases = [
21177 Timestamp::nat(),
21178 Timestamp::from_nanos(i64::MIN + 1),
21179 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
21180 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
21181 Timestamp::from_nanos(-1),
21182 Timestamp::from_nanos(0),
21183 Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
21184 Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
21185 Timestamp::from_nanos(i64::MAX),
21186 Timestamp::from_nanos_tz(-1, "US/Eastern"),
21187 Timestamp::from_nanos_tz(
21188 Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
21189 "Asia/Tokyo",
21190 ),
21191 ];
21192 for timestamp in &parity_cases {
21193 assert_eq!(former(timestamp), candidate(timestamp));
21194 assert_eq!(timestamp.normalize(), former(timestamp));
21195 }
21196
21197 const ROWS: usize = 16_384;
21198 const SAMPLES: usize = 20;
21199 let input = (0..ROWS)
21200 .map(|index| {
21201 let day = index as i64 % 4_096 - 2_048;
21202 let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
21203 % Timedelta::NANOS_PER_DAY as u64) as i64;
21204 Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
21205 })
21206 .collect::<Vec<_>>();
21207 for timestamp in &input {
21208 assert_eq!(former(timestamp), candidate(timestamp));
21209 }
21210
21211 for _ in 0..3 {
21212 black_box(elapsed(&input, former));
21213 black_box(elapsed(&input, candidate));
21214 }
21215
21216 let mut former_ns = Vec::with_capacity(SAMPLES);
21217 let mut candidate_ns = Vec::with_capacity(SAMPLES);
21218 for sample in 0..SAMPLES {
21219 if sample % 2 == 0 {
21220 former_ns.push(elapsed(&input, former));
21221 candidate_ns.push(elapsed(&input, candidate));
21222 } else {
21223 candidate_ns.push(elapsed(&input, candidate));
21224 former_ns.push(elapsed(&input, former));
21225 }
21226 }
21227
21228 let mut former_sorted = former_ns.clone();
21229 let mut candidate_sorted = candidate_ns.clone();
21230 let former_p50 = percentile(&mut former_sorted, 50);
21231 let former_p95 = percentile(&mut former_sorted, 95);
21232 let former_p99 = percentile(&mut former_sorted, 99);
21233 let candidate_p50 = percentile(&mut candidate_sorted, 50);
21234 let candidate_p95 = percentile(&mut candidate_sorted, 95);
21235 let candidate_p99 = percentile(&mut candidate_sorted, 99);
21236 println!(
21237 "TIMESTAMP_NORMALIZE_DIRECT_DAY rows={ROWS} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup_p50={:.6} former_p95_ns={former_p95} candidate_p95_ns={candidate_p95} speedup_p95={:.6} former_p99_ns={former_p99} candidate_p99_ns={candidate_p99} speedup_p99={:.6} former_samples={former_ns:?} candidate_samples={candidate_ns:?}",
21238 former_p50 as f64 / candidate_p50 as f64,
21239 former_p95 as f64 / candidate_p95 as f64,
21240 former_p99 as f64 / candidate_p99 as f64,
21241 );
21242 }
21243
21244 #[test]
21245 fn timestamp_unit_rounding_unknown_unit_returns_nat() {
21246 let ts = Timestamp::from_nanos(100);
21247 assert!(ts.floor_to_unit("fortnight").is_nat());
21248 assert!(ts.ceil_to_unit("century").is_nat());
21249 assert!(ts.round_to_unit("xyz").is_nat());
21250 }
21251
21252 #[test]
21255 fn timestamp_rounding_reads_a_multiple_of_a_unit_3agof() {
21256 let (min, sec) = (Timedelta::NANOS_PER_MIN, Timedelta::NANOS_PER_SEC);
21257 let base = 1_710_460_800 * sec; let ts = Timestamp::from_nanos(base + 13 * Timedelta::NANOS_PER_HOUR + 47 * min + 21 * sec);
21259 let at = |minutes: i64, seconds: i64| base + minutes * min + seconds * sec;
21260 assert_eq!(ts.round("15min").nanos, at(13 * 60 + 45, 0));
21261 assert_eq!(ts.floor("15min").nanos, at(13 * 60 + 45, 0));
21262 assert_eq!(ts.ceil("15min").nanos, at(14 * 60, 0));
21263 assert_eq!(ts.round("30s").nanos, at(13 * 60 + 47, 30));
21264 assert_eq!(ts.ceil("1D").nanos, base + Timedelta::NANOS_PER_DAY);
21265 assert_eq!(ts.floor("7D").nanos, 19_796 * Timedelta::NANOS_PER_DAY);
21268 assert!(ts.round("ME").is_nat());
21270 }
21271
21272 #[test]
21273 fn timestamp_unit_rounding_propagates_nat() {
21274 let nat = Timestamp::nat();
21275 assert!(nat.floor_to_unit("H").is_nat());
21276 assert!(nat.ceil_to_unit("H").is_nat());
21277 assert!(nat.round_to_unit("H").is_nat());
21278 }
21279
21280 #[test]
21281 fn timestamp_unit_rounding_preserves_tz() {
21282 let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
21283 assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21284 assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21285 assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
21286 }
21287
21288 #[test]
21289 fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
21290 assert_eq!(
21292 Timedelta::unit_to_nanos("W"),
21293 Some(Timedelta::NANOS_PER_WEEK)
21294 );
21295 assert_eq!(
21296 Timedelta::unit_to_nanos("D"),
21297 Some(Timedelta::NANOS_PER_DAY)
21298 );
21299 assert_eq!(
21300 Timedelta::unit_to_nanos("H"),
21301 Some(Timedelta::NANOS_PER_HOUR)
21302 );
21303 assert_eq!(
21304 Timedelta::unit_to_nanos("min"),
21305 Some(Timedelta::NANOS_PER_MIN)
21306 );
21307 assert_eq!(
21308 Timedelta::unit_to_nanos("s"),
21309 Some(Timedelta::NANOS_PER_SEC)
21310 );
21311 assert_eq!(
21312 Timedelta::unit_to_nanos("ms"),
21313 Some(Timedelta::NANOS_PER_MILLI)
21314 );
21315 assert_eq!(
21316 Timedelta::unit_to_nanos("us"),
21317 Some(Timedelta::NANOS_PER_MICRO)
21318 );
21319 assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
21320 assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
21322 assert_eq!(Timedelta::unit_to_nanos("century"), None);
21324 }
21325
21326 #[test]
21327 fn timestamp_isoformat_basic() {
21328 let ts = Timestamp::from_nanos(0);
21329 assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
21330
21331 let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
21332 assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
21333
21334 let ts_fixed_offset = Timestamp::from_nanos_tz(0, "UTC+05:30");
21335 assert_eq!(
21336 ts_fixed_offset.isoformat(),
21337 "1970-01-01T05:30:00+05:30",
21338 "a fixed-offset timestamp must render local wall time rather than a UTC instant with an annotation"
21339 );
21340
21341 let ts_tz = Timestamp::from_nanos_tz(
21342 Timedelta::NANOS_PER_DAY
21343 + Timedelta::NANOS_PER_HOUR * 14
21344 + Timedelta::NANOS_PER_MIN * 30,
21345 "America/New_York",
21346 );
21347 assert_eq!(ts_tz.isoformat(), "1970-01-02T09:30:00-05:00");
21348
21349 assert_eq!(Timestamp::nat().isoformat(), "NaT");
21350 }
21351
21352 #[test]
21353 fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
21354 assert_eq!(
21355 Timestamp::from_nanos(-1).isoformat(),
21356 "1969-12-31T23:59:59.999999999"
21357 );
21358 assert_eq!(
21359 Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
21360 "1969-12-31T23:59:59"
21361 );
21362 assert_eq!(
21363 Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
21364 "1969-12-31T00:00:00"
21365 );
21366 assert_eq!(
21367 Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
21368 "1969-12-31T23:59:59.999999999+00:00"
21369 );
21370 }
21371
21372 #[test]
21373 fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
21374 assert_eq!(
21375 Timestamp::from_nanos(123_456_789).isoformat(),
21376 "1970-01-01T00:00:00.123456789"
21377 );
21378 assert_eq!(
21379 Timestamp::from_nanos(123_456_000).isoformat(),
21380 "1970-01-01T00:00:00.123456"
21381 );
21382 assert_eq!(
21383 Timestamp::from_nanos(123_000_000).isoformat(),
21384 "1970-01-01T00:00:00.123000"
21385 );
21386 assert_eq!(
21387 Timestamp::from_nanos_tz(1, "UTC").isoformat(),
21388 "1970-01-01T00:00:00.000000001+00:00"
21389 );
21390 }
21391
21392 fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
21393 if timestamp.is_nat() {
21394 return "NaT".to_owned();
21395 }
21396 let Some(tz) = ×tamp.tz else {
21397 return Timestamp::from_nanos(timestamp.nanos).isoformat();
21398 };
21399 if let Ok(offset_secs) = crate::tz_offset_seconds(tz, timestamp.nanos)
21400 && let Some(display_nanos) = timestamp
21401 .nanos
21402 .checked_add(i64::from(offset_secs) * Timedelta::NANOS_PER_SEC)
21403 {
21404 let base = Timestamp::from_nanos(display_nanos).isoformat();
21405 let sign = if offset_secs < 0 { '-' } else { '+' };
21406 let total_minutes = offset_secs.unsigned_abs() / 60;
21407 return format!(
21408 "{base}{sign}{:02}:{:02}",
21409 total_minutes / 60,
21410 total_minutes % 60
21411 );
21412 }
21413 let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
21414 format!("{base}[{tz}]")
21415 }
21416
21417 #[test]
21418 fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
21419 let nanos = [
21420 Timestamp::NAT,
21421 -Timedelta::NANOS_PER_DAY - 1,
21422 -Timedelta::NANOS_PER_SEC,
21423 -1,
21424 0,
21425 1,
21426 123_456_000,
21427 123_456_789,
21428 i64::MAX,
21429 ];
21430 let timezones = [
21431 None,
21432 Some("UTC"),
21433 Some("America/New_York"),
21434 Some(""),
21435 Some("Etc/Γ"),
21436 ];
21437 for value in nanos {
21438 for timezone in timezones {
21439 let timestamp = Timestamp {
21440 nanos: value,
21441 tz: timezone.map(str::to_owned),
21442 };
21443 assert_eq!(
21444 timestamp.isoformat(),
21445 timestamp_isoformat_former_q8g50(×tamp),
21446 "nanos={value} timezone={timezone:?}"
21447 );
21448 }
21449 }
21450 }
21451
21452 #[test]
21453 #[ignore = "foreground release A/B only"]
21454 fn timestamp_isoformat_one_buffer_ab_q8g50() {
21455 use std::{hint::black_box, time::Instant};
21456
21457 const ITEMS: usize = 8_192;
21458 const SAMPLES: usize = 10;
21459
21460 fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
21461 let started = Instant::now();
21462 let mut checksum = 0usize;
21463 for timestamp in black_box(values) {
21464 checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
21465 }
21466 black_box(checksum);
21467 started.elapsed().as_nanos()
21468 }
21469
21470 let values = (0..ITEMS)
21471 .map(|idx| {
21472 let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
21473 let timezone = if idx.is_multiple_of(2) {
21474 "UTC"
21475 } else {
21476 "America/New_York"
21477 };
21478 Timestamp::from_nanos_tz(nanos, timezone)
21479 })
21480 .collect::<Vec<_>>();
21481 for timestamp in &values {
21482 assert_eq!(
21483 timestamp.isoformat(),
21484 timestamp_isoformat_former_q8g50(timestamp)
21485 );
21486 }
21487
21488 black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
21489 black_box(elapsed(&values, Timestamp::isoformat));
21490
21491 let mut former_ns = Vec::with_capacity(SAMPLES);
21492 let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
21493 for sample in 0..SAMPLES {
21494 if sample.is_multiple_of(2) {
21495 former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
21496 one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
21497 } else {
21498 one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
21499 former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
21500 }
21501 }
21502 former_ns.sort_unstable();
21503 one_buffer_ns.sort_unstable();
21504 let former_p50 = former_ns[SAMPLES / 2];
21505 let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
21506 println!(
21507 "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
21508 former_p50 as f64 / one_buffer_p50 as f64
21509 );
21510 println!("former_samples_ns={former_ns:?}");
21511 println!("one_buffer_samples_ns={one_buffer_ns:?}");
21512 }
21513
21514 #[test]
21515 fn timestamp_strftime_basic() {
21516 let ts = Timestamp::from_nanos(
21517 Timedelta::NANOS_PER_DAY * 365
21518 + Timedelta::NANOS_PER_HOUR * 9
21519 + Timedelta::NANOS_PER_MIN * 15,
21520 );
21521 assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
21522 assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
21523 assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
21524 assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%Y|%01|%Q|%|λ");
21527 assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
21528 }
21529
21530 #[test]
21531 fn strftime_follows_python_directives_and_zones() {
21532 let ts = Timestamp::from_nanos(
21535 Timedelta::NANOS_PER_DAY * 365
21536 + Timedelta::NANOS_PER_HOUR * 9
21537 + Timedelta::NANOS_PER_MIN * 15,
21538 );
21539 assert_eq!(
21540 ts.strftime("%-d %_m %^a %e %k %l %P %C %g %D %F %T %R %r %h %n %t|"),
21541 "1 1 FRI 1 9 9 am 19 70 01/01/71 1971-01-01 09:15:00 09:15 09:15:00 AM Jan \n \t|"
21542 );
21543 assert_eq!(
21544 ts.strftime("%a %A %b %B %c|%x %X|%I %p %j %U %W %w %y"),
21545 "Fri Friday Jan January Fri Jan 1 09:15:00 1971|01/01/71 09:15:00|09 AM 001 00 00 5 71"
21546 );
21547 let sunday = Timestamp::parse("2021-01-03").expect("date");
21549 assert_eq!(sunday.strftime("%G-%V-%u %U %W %j"), "2020-53-7 01 00 003");
21550 let fraction = Timestamp::parse("2024-03-05 14:07:09.123456789").expect("ts");
21552 assert_eq!(fraction.strftime("%f|%z|%Z|abc%"), "123456|||abc%");
21553 let eastern = Timestamp::from_nanos_tz(fraction.nanos, "US/Eastern");
21555 assert_eq!(
21556 eastern.strftime("%Y-%m-%d %H:%M %z %Z"),
21557 "2024-03-05 09:07 -0500 EST"
21558 );
21559 assert_eq!(
21560 crate::strftime_in_zone(fraction.nanos, "%H:%M %z", Some("+05:30")),
21561 "19:37 +0530"
21562 );
21563 }
21564
21565 #[test]
21566 fn timestamp_strftime_floors_pre_epoch_instants_1pmlp() {
21567 let apollo = Timestamp::parse("1969-07-20T20:17:40").unwrap();
21568 assert_eq!(
21569 apollo.strftime("%Y-%m-%d %H:%M:%S.%f"),
21570 "1969-07-20 20:17:40.000000"
21571 );
21572
21573 let one_ns_before_epoch = Timestamp::from_nanos(-1);
21576 assert_eq!(
21577 one_ns_before_epoch.strftime("%Y-%m-%d %H:%M:%S.%f"),
21578 "1969-12-31 23:59:59.999999"
21579 );
21580 }
21581
21582 #[test]
21583 #[ignore = "foreground normal-release attribution harness"]
21584 fn timestamp_strftime_one_buffer_profile_8qzbo() {
21585 use std::{hint::black_box, time::Instant};
21586
21587 const ITEMS: usize = 8_192;
21588 const SAMPLES: usize = 10;
21589 const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
21590
21591 fn former(timestamp: &Timestamp, format: &str) -> String {
21592 if timestamp.is_nat() {
21593 return "NaT".to_string();
21594 }
21595 let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
21596 let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
21597
21598 let days_since_epoch = total_secs / 86400;
21599 let secs_of_day = (total_secs % 86400 + 86400) % 86400;
21600 let days = days_since_epoch + 719_468;
21601 let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
21602 let doe = days - era * 146_097;
21603 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
21604 let y = yoe + era * 400;
21605 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
21606 let mp = (5 * doy + 2) / 153;
21607 let d = doy - (153 * mp + 2) / 5 + 1;
21608 let m = if mp < 10 { mp + 3 } else { mp - 9 };
21609 let year = if m <= 2 { y + 1 } else { y };
21610 let hour = secs_of_day / 3600;
21611 let minute = (secs_of_day % 3600) / 60;
21612 let second = secs_of_day % 60;
21613 let micros = sub_nanos / 1000;
21614
21615 format
21616 .replace("%Y", &format!("{year:04}"))
21617 .replace("%m", &format!("{m:02}"))
21618 .replace("%d", &format!("{d:02}"))
21619 .replace("%H", &format!("{hour:02}"))
21620 .replace("%M", &format!("{minute:02}"))
21621 .replace("%S", &format!("{second:02}"))
21622 .replace("%f", &format!("{micros:06}"))
21623 }
21624
21625 fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
21626 let started = Instant::now();
21627 let mut digest = 0_usize;
21628 for timestamp in timestamps {
21629 let value = formatter(black_box(timestamp), black_box(FORMAT));
21630 digest = digest.wrapping_add(value.len());
21631 digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
21632 black_box(value);
21633 }
21634 black_box(digest);
21635 started.elapsed().as_nanos()
21636 }
21637
21638 fn percentile(samples: &mut [u128], pct: usize) -> u128 {
21639 samples.sort_unstable();
21640 let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
21641 samples[rank]
21642 }
21643
21644 let edge_timestamps = [
21645 Timestamp::nat(),
21646 Timestamp::from_nanos(i64::MIN + 1),
21647 Timestamp::from_nanos(-1_234_567_890),
21648 Timestamp::from_nanos(0),
21649 Timestamp::from_nanos(1_735_732_800_123_456_789),
21650 Timestamp::from_nanos(i64::MAX),
21651 ];
21652 let edge_formats = [
21653 "",
21654 "%Y-%m-%d %H:%M:%S.%f",
21655 "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
21656 "%%Y|%%%m|%Q|%|λ",
21657 FORMAT,
21658 ];
21659 for timestamp in &edge_timestamps {
21660 for format in edge_formats {
21661 assert_eq!(former(timestamp, format), timestamp.strftime(format));
21662 }
21663 }
21664
21665 let timestamps = (0..ITEMS)
21666 .map(|index| {
21667 let centered = index as i64 - ITEMS as i64 / 2;
21668 Timestamp::from_nanos(centered * 987_654_321_123_456)
21669 })
21670 .collect::<Vec<_>>();
21671 for timestamp in ×tamps {
21672 assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
21673 }
21674
21675 black_box(elapsed(×tamps, former));
21676 black_box(elapsed(×tamps, Timestamp::strftime));
21677
21678 let mut former_samples = Vec::with_capacity(SAMPLES);
21679 let mut public_samples = Vec::with_capacity(SAMPLES);
21680 for sample in 0..SAMPLES {
21681 if sample.is_multiple_of(2) {
21682 former_samples.push(elapsed(×tamps, former));
21683 public_samples.push(elapsed(×tamps, Timestamp::strftime));
21684 } else {
21685 public_samples.push(elapsed(×tamps, Timestamp::strftime));
21686 former_samples.push(elapsed(×tamps, former));
21687 }
21688 }
21689 let former_p50 = percentile(&mut former_samples, 50);
21690 let former_p95 = percentile(&mut former_samples, 95);
21691 let public_p50 = percentile(&mut public_samples, 50);
21692 let public_p95 = percentile(&mut public_samples, 95);
21693 println!(
21694 "TIMESTAMP_STRFTIME_AB items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} former_p95_ns={former_p95} public_p50_ns={public_p50} public_p95_ns={public_p95} p50_speedup={:.6} p95_speedup={:.6}",
21695 former_p50 as f64 / public_p50 as f64,
21696 former_p95 as f64 / public_p95 as f64,
21697 );
21698 println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
21699 println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
21700 }
21701
21702 #[test]
21703 fn timestamp_day_name_and_month_name() {
21704 let ts = Timestamp::from_nanos(0);
21705 assert_eq!(ts.day_name(), "Thursday");
21706 assert_eq!(ts.month_name(), "January");
21707
21708 let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
21709 assert_eq!(ts2.day_name(), "Friday");
21710 assert_eq!(ts2.month_name(), "January");
21711
21712 assert_eq!(Timestamp::nat().day_name(), "NaT");
21713 assert_eq!(Timestamp::nat().month_name(), "NaT");
21714 }
21715
21716 #[test]
21717 fn timestamp_replace_validates_components_zw0y2() {
21718 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
21719 let replaced = ts.replace(
21720 Some(2024),
21721 Some(2),
21722 Some(29),
21723 Some(23),
21724 Some(59),
21725 Some(58),
21726 Some(987_654),
21727 Some(321),
21728 );
21729 assert_eq!(replaced.year(), Some(2024));
21730 assert_eq!(replaced.month(), Some(2));
21731 assert_eq!(replaced.day(), Some(29));
21732 assert_eq!(replaced.hour(), Some(23));
21733 assert_eq!(replaced.minute(), Some(59));
21734 assert_eq!(replaced.second(), Some(58));
21735 assert_eq!(replaced.microsecond(), Some(987_654));
21736 assert_eq!(replaced.nanosecond(), Some(321));
21737
21738 let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
21739 assert_eq!(
21740 tz.replace(None, Some(2), Some(29), None, None, None, None, None)
21741 .tz
21742 .as_deref(),
21743 Some("UTC")
21744 );
21745
21746 assert!(
21747 ts.replace(None, Some(13), None, None, None, None, None, None)
21748 .is_nat()
21749 );
21750 assert!(
21751 ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
21752 .is_nat()
21753 );
21754 assert!(
21755 ts.replace(None, None, None, Some(24), None, None, None, None)
21756 .is_nat()
21757 );
21758 assert!(
21759 ts.replace(None, None, None, None, Some(60), None, None, None)
21760 .is_nat()
21761 );
21762 assert!(
21763 ts.replace(None, None, None, None, None, Some(60), None, None)
21764 .is_nat()
21765 );
21766 assert!(
21767 ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
21768 .is_nat()
21769 );
21770 assert!(
21771 ts.replace(None, None, None, None, None, None, None, Some(1_000))
21772 .is_nat()
21773 );
21774 assert!(
21775 Timestamp::nat()
21776 .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
21777 .is_nat()
21778 );
21779 }
21780
21781 #[test]
21788 fn timestamp_replace_returns_nat_on_nanosecond_overflow_dzz6x() {
21789 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
21790
21791 for year in [3000, 10_000, 300_000, i64::MAX / 400] {
21792 let out = ts.replace(Some(year), None, None, None, None, None, None, None);
21793 assert!(
21794 out.is_nat(),
21795 "replace(year={year}) is unrepresentable in i64 ns and must be \
21796 NaT, got nanos={:?} (year {:?}) — this is the silent wrap",
21797 out.nanos,
21798 out.year()
21799 );
21800 }
21801 for year in [-3000, -100_000, i64::MIN / 400] {
21802 let out = ts.replace(Some(year), None, None, None, None, None, None, None);
21803 assert!(out.is_nat(), "replace(year={year}) must be NaT");
21804 }
21805
21806 let in_range = ts.replace(
21811 Some(2262),
21812 Some(1),
21813 Some(1),
21814 Some(0),
21815 Some(0),
21816 Some(0),
21817 Some(0),
21818 Some(0),
21819 );
21820 assert!(
21821 !in_range.is_nat(),
21822 "2262-01-01 is representable and must survive"
21823 );
21824 assert_eq!(in_range.year(), Some(2262));
21825 assert!(
21826 ts.replace(
21827 Some(2263),
21828 Some(12),
21829 Some(31),
21830 Some(23),
21831 Some(59),
21832 Some(59),
21833 Some(999_999),
21834 Some(999)
21835 )
21836 .is_nat(),
21837 "end of 2263 exceeds the i64 ns axis and must be NaT"
21838 );
21839
21840 let unchanged = ts.replace(
21844 Some(1999),
21845 Some(6),
21846 Some(30),
21847 Some(12),
21848 Some(1),
21849 Some(2),
21850 Some(3),
21851 Some(4),
21852 );
21853 assert_eq!(unchanged.year(), Some(1999));
21854 assert_eq!(unchanged.month(), Some(6));
21855 assert_eq!(unchanged.day(), Some(30));
21856 assert_eq!(unchanged.hour(), Some(12));
21857 assert_eq!(unchanged.minute(), Some(1));
21858 assert_eq!(unchanged.second(), Some(2));
21859 assert_eq!(unchanged.microsecond(), Some(3));
21860 assert_eq!(unchanged.nanosecond(), Some(4));
21861 let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
21862 assert_eq!(
21863 tz.replace(Some(1999), None, None, None, None, None, None, None)
21864 .tz
21865 .as_deref(),
21866 Some("UTC")
21867 );
21868 }
21869
21870 #[test]
21871 fn timestamp_component_accessors() {
21872 let ts = Timestamp::from_nanos(0);
21873 assert_eq!(ts.year(), Some(1970));
21874 assert_eq!(ts.month(), Some(1));
21875 assert_eq!(ts.day(), Some(1));
21876 assert_eq!(ts.hour(), Some(0));
21877 assert_eq!(ts.minute(), Some(0));
21878 assert_eq!(ts.second(), Some(0));
21879 assert_eq!(ts.microsecond(), Some(0));
21880 assert_eq!(ts.nanosecond(), Some(0));
21881
21882 let ts2 = Timestamp::from_nanos(
21883 Timedelta::NANOS_PER_DAY * 365
21884 + Timedelta::NANOS_PER_HOUR * 14
21885 + Timedelta::NANOS_PER_MIN * 30
21886 + Timedelta::NANOS_PER_SEC * 45
21887 + 123_456_789,
21888 );
21889 assert_eq!(ts2.year(), Some(1971));
21890 assert_eq!(ts2.month(), Some(1));
21891 assert_eq!(ts2.day(), Some(1));
21892 assert_eq!(ts2.hour(), Some(14));
21893 assert_eq!(ts2.minute(), Some(30));
21894 assert_eq!(ts2.second(), Some(45));
21895 assert_eq!(ts2.microsecond(), Some(123456));
21896 assert_eq!(ts2.nanosecond(), Some(789));
21897
21898 assert_eq!(Timestamp::nat().year(), None);
21899 assert_eq!(Timestamp::nat().month(), None);
21900 assert_eq!(Timestamp::nat().day(), None);
21901 }
21902
21903 #[test]
21904 fn timestamp_dayofweek_dayofyear_quarter() {
21905 let ts = Timestamp::from_nanos(0);
21906 assert_eq!(ts.dayofweek(), Some(3));
21907 assert_eq!(ts.weekday(), Some(3));
21908 assert_eq!(ts.dayofyear(), Some(1));
21909 assert_eq!(ts.quarter(), Some(1));
21910
21911 let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
21912 assert_eq!(ts2.quarter(), Some(2));
21913
21914 let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
21915 assert_eq!(ts3.dayofyear(), Some(1));
21916 assert_eq!(ts3.dayofweek(), Some(4));
21917
21918 assert_eq!(Timestamp::nat().dayofweek(), None);
21919 assert_eq!(Timestamp::nat().dayofyear(), None);
21920 assert_eq!(Timestamp::nat().quarter(), None);
21921 }
21922
21923 #[test]
21924 fn timestamp_is_boundary_methods() {
21925 let jan1 = Timestamp::from_nanos(0);
21926 assert_eq!(jan1.is_leap_year(), Some(false));
21927 assert_eq!(jan1.is_month_start(), Some(true));
21928 assert_eq!(jan1.is_month_end(), Some(false));
21929 assert_eq!(jan1.is_quarter_start(), Some(true));
21930 assert_eq!(jan1.is_quarter_end(), Some(false));
21931 assert_eq!(jan1.is_year_start(), Some(true));
21932 assert_eq!(jan1.is_year_end(), Some(false));
21933
21934 let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
21935 assert_eq!(dec31.is_month_start(), Some(false));
21936 assert_eq!(dec31.is_month_end(), Some(true));
21937 assert_eq!(dec31.is_quarter_end(), Some(true));
21938 assert_eq!(dec31.is_year_end(), Some(true));
21939
21940 assert_eq!(Timestamp::nat().is_leap_year(), None);
21941 assert_eq!(Timestamp::nat().is_month_start(), None);
21942 }
21943
21944 #[test]
21945 fn timestamp_days_in_month() {
21946 let jan = Timestamp::from_nanos(0);
21947 assert_eq!(jan.days_in_month(), Some(31));
21948 assert_eq!(jan.daysinmonth(), Some(31));
21949
21950 let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
21951 assert_eq!(feb_non_leap.days_in_month(), Some(28));
21952
21953 assert_eq!(Timestamp::nat().days_in_month(), None);
21954 }
21955
21956 #[test]
21957 fn timestamp_weekofyear() {
21958 let jan1 = Timestamp::from_nanos(0);
21959 assert_eq!(jan1.weekofyear(), Some(1));
21960 assert_eq!(jan1.week(), Some(1));
21961
21962 let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
21963 assert_eq!(jan8.weekofyear(), Some(2));
21964
21965 assert_eq!(Timestamp::nat().weekofyear(), None);
21966 assert_eq!(Timestamp::nat().week(), None);
21967 }
21968
21969 #[test]
21970 fn timestamp_weekofyear_iso_53_week_boundaries() {
21971 fn week_of(date_days: i64) -> Option<i64> {
21974 Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
21975 }
21976 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)); }
21990
21991 #[test]
21992 fn iso_weeks_in_year_53_week_years() {
21993 use super::iso_weeks_in_year;
21994 for y in [2004, 2009, 2015, 2020, 2026] {
21996 assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
21997 }
21998 for y in [2018, 2019, 2021, 2022, 2023, 2024] {
21999 assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
22000 }
22001 }
22002
22003 #[test]
22004 fn timestamp_to_unit() {
22005 let ts = Timestamp::from_nanos(1_000_000_000);
22006 assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
22007 assert_eq!(ts.to_unit("us"), Some(1_000_000));
22008 assert_eq!(ts.to_unit("ms"), Some(1_000));
22009 assert_eq!(ts.to_unit("s"), Some(1));
22010 assert_eq!(ts.to_unit("invalid"), None);
22011
22012 assert_eq!(Timestamp::nat().to_unit("ns"), None);
22013 }
22014
22015 #[test]
22016 fn timestamp_toordinal() {
22017 let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
22020 let ts = Timestamp::from_nanos(nanos_2026_01_01);
22021 assert_eq!(ts.toordinal(), Some(738886));
22022
22023 assert_eq!(Timestamp::nat().toordinal(), None);
22025 }
22026
22027 #[test]
22028 fn timestamp_fromordinal() {
22029 let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
22032 let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
22033 let ordinal = ts_orig.toordinal().unwrap();
22034
22035 let ts = Timestamp::fromordinal(ordinal);
22037 assert_eq!(ts.year(), ts_orig.year());
22038 assert_eq!(ts.month(), ts_orig.month());
22039 assert_eq!(ts.day(), ts_orig.day());
22040
22041 let nat = Timestamp::fromordinal(0);
22043 assert!(nat.is_nat());
22044 }
22045
22046 #[test]
22047 fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
22048 const EPOCH_ORDINAL: i64 = 719_163;
22049 let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
22050 let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
22051
22052 let max_valid = Timestamp::fromordinal(max_valid_ordinal);
22053 assert!(!max_valid.is_nat());
22054 assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
22055
22056 assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
22057 assert!(Timestamp::fromordinal(i64::MAX).is_nat());
22058 }
22059
22060 #[test]
22061 fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
22062 const EPOCH_ORDINAL: i64 = 719_163;
22063 const DAY: i64 = Timedelta::NANOS_PER_DAY;
22064
22065 fn next(seed: &mut u64) -> u64 {
22066 *seed = seed
22067 .wrapping_mul(3202034522624059733)
22068 .wrapping_add(4354685564936845319);
22069 *seed
22070 }
22071
22072 fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
22073 let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
22074 let ts = Timestamp::from_nanos(nanos);
22075 let expected_day_offset = nanos.div_euclid(DAY);
22076 let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
22077
22078 assert_eq!(
22079 ts.toordinal(),
22080 Some(expected_ordinal),
22081 "case {case}: toordinal"
22082 );
22083
22084 let midnight = Timestamp::fromordinal(expected_ordinal);
22085 assert_eq!(
22086 midnight.nanos,
22087 expected_day_offset * DAY,
22088 "case {case}: fromordinal nanos"
22089 );
22090 assert_eq!(
22091 midnight.toordinal(),
22092 Some(expected_ordinal),
22093 "case {case}: fromordinal roundtrip"
22094 );
22095 }
22096
22097 assert_eq!(Timestamp::nat().toordinal(), None);
22098 assert!(Timestamp::fromordinal(0).is_nat());
22099 assert!(Timestamp::fromordinal(-1).is_nat());
22100
22101 assert_ordinal_case(usize::MAX, -1, DAY - 1);
22102 assert_ordinal_case(usize::MAX - 1, 0, -1);
22103 assert_ordinal_case(usize::MAX - 2, 19_723, 0);
22104
22105 let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
22106 for case in 0..260 {
22107 let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
22108 let subday_nanos = match case % 7 {
22109 0 => 0,
22110 1 => DAY - 1,
22111 2 => -1,
22112 _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
22113 };
22114 assert_ordinal_case(case, day_offset, subday_nanos);
22115 }
22116 }
22117
22118 #[test]
22125 fn timestamp_parse_rejects_unrepresentable_years_94o1u() {
22126 for s in [
22127 "300000-01-01",
22128 "10000000-06-15T12:30:45",
22129 "999999999-01-01",
22130 "-300000-01-01",
22131 "-99999999-12-31T23:59:59",
22132 ] {
22133 let got = Timestamp::parse(s);
22134 assert!(
22135 got.is_err(),
22136 "parse({s:?}) is unrepresentable in i64 ns and must be Err, got {:?} \
22137 — this is the silent wrap",
22138 got.map(|ts| (ts.nanos, ts.year()))
22139 );
22140 }
22141
22142 let ok = Timestamp::parse("2262-01-01").expect("2262-01-01 is representable");
22145 assert_eq!(ok.year(), Some(2262));
22146 assert!(
22147 Timestamp::parse("2263-12-31T23:59:59").is_err(),
22148 "end of 2263 exceeds the i64 ns axis and must be Err"
22149 );
22150
22151 assert_eq!(Timestamp::parse("2024-01-15").unwrap().year(), Some(2024));
22155 assert_eq!(
22156 Timestamp::parse("2024-01-15T10:30:45").unwrap().hour(),
22157 Some(10)
22158 );
22159 assert_eq!(
22160 Timestamp::parse("2024-01-15 10:30:45").unwrap().minute(),
22161 Some(30)
22162 );
22163 assert_eq!(
22164 Timestamp::parse("2024-01-15T10:30:45.123456789")
22165 .unwrap()
22166 .nanosecond(),
22167 Some(789)
22168 );
22169 assert_eq!(
22170 Timestamp::parse("2024-01-15T00:00:00Z").unwrap().year(),
22171 Some(2024)
22172 );
22173 assert_eq!(Timestamp::parse("1900-01-01").unwrap().year(), Some(1900));
22175 }
22176
22177 #[test]
22178 fn timestamp_parse_iso8601_date_only() {
22179 let ts = Timestamp::parse("2024-01-15").unwrap();
22180 assert_eq!(ts.year(), Some(2024));
22181 assert_eq!(ts.month(), Some(1));
22182 assert_eq!(ts.day(), Some(15));
22183 assert_eq!(ts.hour(), Some(0));
22184 assert_eq!(ts.minute(), Some(0));
22185 assert_eq!(ts.second(), Some(0));
22186 }
22187
22188 #[test]
22189 fn timestamp_parse_iso8601_datetime() {
22190 let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
22191 assert_eq!(ts.year(), Some(2024));
22192 assert_eq!(ts.month(), Some(1));
22193 assert_eq!(ts.day(), Some(15));
22194 assert_eq!(ts.hour(), Some(10));
22195 assert_eq!(ts.minute(), Some(30));
22196 assert_eq!(ts.second(), Some(45));
22197 }
22198
22199 #[test]
22200 fn timestamp_parse_space_separator() {
22201 let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
22202 assert_eq!(ts.year(), Some(2024));
22203 assert_eq!(ts.hour(), Some(10));
22204 }
22205
22206 #[test]
22207 fn timestamp_parse_with_fractional_seconds() {
22208 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
22209 assert_eq!(ts.second(), Some(45));
22210 assert_eq!(ts.microsecond(), Some(123456));
22211 assert_eq!(ts.nanosecond(), Some(789));
22212 }
22213
22214 #[test]
22215 fn timestamp_parse_utc_timezone() {
22216 let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
22217 assert_eq!(ts.tz, Some("UTC".to_string()));
22218 }
22219
22220 #[test]
22221 fn timestamp_parse_offset_timezone() {
22222 let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
22223 assert_eq!(ts.tz, Some("+05:30".to_string()));
22224 let utc = |text: &str| Timestamp::parse(text).unwrap().nanos;
22227 assert_eq!(ts.nanos, utc("2024-01-15T05:00:45"));
22228
22229 let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
22230 assert_eq!(ts.tz, Some("-05:30".to_string()));
22231 assert_eq!(ts.nanos, utc("2024-01-15T16:00:45"));
22232 assert_eq!(
22234 Timestamp::parse("2024-01-15T10:30:45Z").unwrap().nanos,
22235 utc("2024-01-15T10:30:45")
22236 );
22237 }
22238
22239 #[test]
22240 fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
22241 assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
22242 assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
22243 assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
22244 assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
22245 assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
22246 }
22247
22248 #[test]
22249 fn timestamp_parse_nat() {
22250 let ts = Timestamp::parse("NaT").unwrap();
22251 assert!(ts.is_nat());
22252 let ts2 = Timestamp::parse("nat").unwrap();
22253 assert!(ts2.is_nat());
22254 }
22255
22256 #[test]
22257 fn timestamp_parse_invalid() {
22258 assert!(Timestamp::parse("not a date").is_err());
22259 assert!(Timestamp::parse("2024-13-01").is_err()); assert!(Timestamp::parse("2024-01-32").is_err()); }
22262
22263 #[test]
22264 fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
22265 assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
22266 assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
22267 assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
22268 assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
22269 assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
22270
22271 let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
22272 assert_eq!(ts.second(), Some(45));
22273 assert_eq!(ts.microsecond(), Some(123456));
22274 assert_eq!(ts.nanosecond(), Some(789));
22275 }
22276
22277 #[test]
22278 #[ignore = "foreground profile-first A/B"]
22279 fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
22280 use std::{hint::black_box, time::Instant};
22281
22282 const CALLS: usize = 131_072;
22283 const SAMPLES: usize = 12;
22284 type ParsedTime = Option<(u32, u32, u32, u64)>;
22285 const VALID: [&str; 16] = [
22286 "00:00:00.0",
22287 "01:02:03.1",
22288 "02:03:04.01",
22289 "03:04:05.001",
22290 "04:05:06.0001",
22291 "05:06:07.00001",
22292 "06:07:08.000001",
22293 "07:08:09.0000001",
22294 "08:09:10.00000001",
22295 "09:10:11.000000001",
22296 "10:11:12.123456789",
22297 "11:12:13.999999999",
22298 "12:13:14.123456789987",
22299 "13:14:15.000000000001",
22300 "14:15:16.101010101010",
22301 "23:59:59.987654321234",
22302 ];
22303
22304 #[inline(never)]
22305 fn former(s: &str) -> ParsedTime {
22306 let (time_str, frac_str) = match s.split_once('.') {
22307 Some((time, frac)) => (time, Some(frac)),
22308 None => (s, None),
22309 };
22310 let parts: Vec<&str> = time_str.split(':').collect();
22311 if parts.is_empty() || parts.len() > 3 {
22312 return None;
22313 }
22314 let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
22315 let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
22316 let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
22317
22318 if hour > 23 || minute > 59 || second > 59 {
22319 return None;
22320 }
22321
22322 let nanos = match frac_str {
22323 None => 0,
22324 Some(frac) => {
22325 if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
22326 return None;
22327 }
22328 let truncated = &frac[..frac.len().min(9)];
22329 let padded = format!("{truncated:0<9}");
22330 padded.parse::<u64>().ok()?
22331 }
22332 };
22333
22334 Some((hour, minute, second, nanos))
22335 }
22336
22337 #[inline(never)]
22338 fn candidate(s: &str) -> ParsedTime {
22339 Timestamp::parse_time(s)
22340 }
22341
22342 fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
22343 let started = Instant::now();
22344 for input in black_box(inputs) {
22345 black_box(parser(black_box(*input)));
22346 }
22347 started.elapsed().as_nanos()
22348 }
22349
22350 fn percentile(samples: &[u128], percent: usize) -> u128 {
22351 let mut sorted = samples.to_vec();
22352 sorted.sort_unstable();
22353 let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
22354 sorted[rank]
22355 }
22356
22357 let invalid = [
22358 "",
22359 "24:00:00.1",
22360 "12:60:00.1",
22361 "12:00:60.1",
22362 "12:00:00.",
22363 "12:00:00.abc",
22364 "12:00:00.-1",
22365 "12:00:00.123",
22366 "12:00:00.123456789x",
22367 "12:00:00.1.2",
22368 "12:00:00:01.1",
22369 ];
22370 for input in VALID.iter().chain(invalid.iter()) {
22371 assert_eq!(candidate(input), former(input), "input={input:?}");
22372 }
22373
22374 let inputs = (0..CALLS)
22375 .map(|index| VALID[index % VALID.len()])
22376 .collect::<Vec<_>>();
22377 for _ in 0..2 {
22378 black_box(elapsed(&inputs, former));
22379 black_box(elapsed(&inputs, candidate));
22380 }
22381
22382 let mut former_ns = Vec::with_capacity(SAMPLES);
22383 let mut candidate_ns = Vec::with_capacity(SAMPLES);
22384 for sample in 0..SAMPLES {
22385 if sample.is_multiple_of(2) {
22386 former_ns.push(elapsed(&inputs, former));
22387 candidate_ns.push(elapsed(&inputs, candidate));
22388 } else {
22389 candidate_ns.push(elapsed(&inputs, candidate));
22390 former_ns.push(elapsed(&inputs, former));
22391 }
22392 }
22393
22394 let former_p50 = percentile(&former_ns, 50);
22395 let former_p95 = percentile(&former_ns, 95);
22396 let former_p99 = percentile(&former_ns, 99);
22397 let candidate_p50 = percentile(&candidate_ns, 50);
22398 let candidate_p95 = percentile(&candidate_ns, 95);
22399 let candidate_p99 = percentile(&candidate_ns, 99);
22400 println!(
22401 "TIMESTAMP_FRACTION_PARSE calls={CALLS} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup_p50={:.6} former_p95_ns={former_p95} candidate_p95_ns={candidate_p95} speedup_p95={:.6} former_p99_ns={former_p99} candidate_p99_ns={candidate_p99} speedup_p99={:.6} former_samples={former_ns:?} candidate_samples={candidate_ns:?}",
22402 former_p50 as f64 / candidate_p50 as f64,
22403 former_p95 as f64 / candidate_p95 as f64,
22404 former_p99 as f64 / candidate_p99 as f64,
22405 );
22406 }
22407
22408 #[test]
22409 fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
22410 fn next(seed: &mut u64) -> u64 {
22411 *seed = seed
22412 .wrapping_mul(3935559000370003845)
22413 .wrapping_add(2691343689449507681);
22414 *seed
22415 }
22416
22417 fn leap(year: i64) -> bool {
22418 (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
22419 }
22420
22421 fn month_len(year: i64, month: u32) -> u32 {
22422 match month {
22423 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
22424 4 | 6 | 9 | 11 => 30,
22425 2 if leap(year) => 29,
22426 2 => 28,
22427 _ => 0,
22428 }
22429 }
22430
22431 struct Components {
22432 year: i64,
22433 month: u32,
22434 day: u32,
22435 hour: u32,
22436 minute: u32,
22437 second: u32,
22438 nanos: u64,
22439 }
22440
22441 fn assert_components(case: usize, text: &str, expected: Components) {
22442 let ts = Timestamp::parse(text).expect("seeded valid timestamp");
22443 let Components {
22444 year,
22445 month,
22446 day,
22447 hour,
22448 minute,
22449 second,
22450 nanos,
22451 } = expected;
22452 assert_eq!(ts.year(), Some(year), "case {case}: year");
22453 assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
22454 assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
22455 assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
22456 assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
22457 assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
22458 assert_eq!(
22459 ts.microsecond(),
22460 Some((nanos / 1000) as i64),
22461 "case {case}: microsecond"
22462 );
22463 assert_eq!(
22464 ts.nanosecond(),
22465 Some((nanos % 1000) as i64),
22466 "case {case}: nanosecond"
22467 );
22468 }
22469
22470 assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
22471 assert!(
22472 Timestamp::parse("nAt")
22473 .expect("mixed-case NaT parses")
22474 .is_nat()
22475 );
22476 assert!(Timestamp::parse("1900-02-29").is_err());
22477 assert!(Timestamp::parse("2001-04-31").is_err());
22478 assert!(Timestamp::parse("2024-00-15").is_err());
22479
22480 assert_components(
22481 usize::MAX,
22482 "2000-02-29",
22483 Components {
22484 year: 2000,
22485 month: 2,
22486 day: 29,
22487 hour: 0,
22488 minute: 0,
22489 second: 0,
22490 nanos: 0,
22491 },
22492 );
22493 assert_components(
22494 usize::MAX - 1,
22495 "2024-02-29T23:59:59.000000001",
22496 Components {
22497 year: 2024,
22498 month: 2,
22499 day: 29,
22500 hour: 23,
22501 minute: 59,
22502 second: 59,
22503 nanos: 1,
22504 },
22505 );
22506
22507 let mut seed = 0x15e0_1d50_1f0a_cade_u64;
22508 for case in 0..260 {
22509 let year = 1900 + (next(&mut seed) % 201) as i64;
22510 let month = 1 + (next(&mut seed) % 12) as u32;
22511 let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
22512 let hour = (next(&mut seed) % 24) as u32;
22513 let minute = (next(&mut seed) % 60) as u32;
22514 let second = (next(&mut seed) % 60) as u32;
22515 let nanos = next(&mut seed) % 1_000_000_000;
22516
22517 match case % 4 {
22518 0 => {
22519 let text = format!("{year:04}-{month:02}-{day:02}");
22520 assert_components(
22521 case,
22522 &text,
22523 Components {
22524 year,
22525 month,
22526 day,
22527 hour: 0,
22528 minute: 0,
22529 second: 0,
22530 nanos: 0,
22531 },
22532 );
22533 }
22534 1 => {
22535 let text =
22536 format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
22537 assert_components(
22538 case,
22539 &text,
22540 Components {
22541 year,
22542 month,
22543 day,
22544 hour,
22545 minute,
22546 second,
22547 nanos: 0,
22548 },
22549 );
22550 }
22551 2 => {
22552 let text =
22553 format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
22554 assert_components(
22555 case,
22556 &text,
22557 Components {
22558 year,
22559 month,
22560 day,
22561 hour,
22562 minute,
22563 second,
22564 nanos: 0,
22565 },
22566 );
22567 }
22568 _ => {
22569 let text = format!(
22570 "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
22571 );
22572 assert_components(
22573 case,
22574 &text,
22575 Components {
22576 year,
22577 month,
22578 day,
22579 hour,
22580 minute,
22581 second,
22582 nanos,
22583 },
22584 );
22585 }
22586 }
22587 }
22588 }
22589
22590 #[test]
22591 fn period_parse_annual() {
22592 let p = Period::parse("2024").unwrap();
22593 assert_eq!(p.freq(), PeriodFreq::ANNUAL);
22594 assert_eq!(p.ordinal(), 2024 - 1970);
22595 }
22596
22597 #[test]
22598 fn period_parse_quarterly() {
22599 let p = Period::parse("2024Q1").unwrap();
22600 assert_eq!(p.freq(), PeriodFreq::QUARTERLY);
22601 assert_eq!(p.ordinal(), (2024 - 1970) * 4);
22602
22603 let p2 = Period::parse("2024q3").unwrap();
22604 assert_eq!(p2.freq(), PeriodFreq::QUARTERLY);
22605 assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
22606 }
22607
22608 #[test]
22609 fn period_parse_monthly() {
22610 let p = Period::parse("2024-01").unwrap();
22611 assert_eq!(p.freq(), PeriodFreq::Monthly);
22612 assert_eq!(p.ordinal(), (2024 - 1970) * 12);
22613
22614 let p2 = Period::parse("2024-12").unwrap();
22615 assert_eq!(p2.freq(), PeriodFreq::Monthly);
22616 assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
22617 }
22618
22619 #[test]
22620 fn period_parse_nat() {
22621 let p = Period::parse("NaT").unwrap();
22622 assert_eq!(p.ordinal(), i64::MIN);
22623 }
22624
22625 #[test]
22626 fn period_parse_invalid() {
22627 assert!(Period::parse("not a period").is_err());
22628 assert!(Period::parse("2024Q5").is_err()); assert!(Period::parse("2024-13").is_err()); }
22631
22632 #[test]
22633 fn interval_parse_basic() {
22634 let i = Interval::parse("[0, 1]").unwrap();
22635 assert_eq!(i.left, 0.0);
22636 assert_eq!(i.right, 1.0);
22637 assert_eq!(i.closed, IntervalClosed::Both);
22638
22639 let i2 = Interval::parse("(0, 1)").unwrap();
22640 assert_eq!(i2.left, 0.0);
22641 assert_eq!(i2.right, 1.0);
22642 assert_eq!(i2.closed, IntervalClosed::Neither);
22643
22644 let i3 = Interval::parse("[0, 1)").unwrap();
22645 assert_eq!(i3.closed, IntervalClosed::Left);
22646
22647 let i4 = Interval::parse("(0, 1]").unwrap();
22648 assert_eq!(i4.closed, IntervalClosed::Right);
22649 }
22650
22651 #[test]
22652 fn interval_parse_floats() {
22653 let i = Interval::parse("[-1.5, 2.5)").unwrap();
22654 assert_eq!(i.left, -1.5);
22655 assert_eq!(i.right, 2.5);
22656 assert_eq!(i.closed, IntervalClosed::Left);
22657 }
22658
22659 #[test]
22660 fn interval_parse_invalid() {
22661 assert!(Interval::parse("invalid").is_err());
22662 assert!(Interval::parse("[0]").is_err());
22663 assert!(Interval::parse("0, 1").is_err()); }
22665
22666 fn interval_parse_error_profile(s: &str) -> super::TypeError {
22667 super::TypeError::ValueNotParseable {
22668 value: s.to_string(),
22669 target: "Interval".to_string(),
22670 }
22671 }
22672
22673 #[inline(never)]
22674 fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
22675 let s = std::hint::black_box(s).trim();
22676 if s.len() < 5 {
22677 return Err(interval_parse_error_profile(s));
22678 }
22679
22680 let first_char = s.chars().next().unwrap();
22681 let last_char = s.chars().last().unwrap();
22682 let left_closed = match first_char {
22683 '[' => true,
22684 '(' => false,
22685 _ => return Err(interval_parse_error_profile(s)),
22686 };
22687 let right_closed = match last_char {
22688 ']' => true,
22689 ')' => false,
22690 _ => return Err(interval_parse_error_profile(s)),
22691 };
22692 let closed = match (left_closed, right_closed) {
22693 (true, true) => IntervalClosed::Both,
22694 (true, false) => IntervalClosed::Left,
22695 (false, true) => IntervalClosed::Right,
22696 (false, false) => IntervalClosed::Neither,
22697 };
22698
22699 let inner = &s[1..s.len() - 1];
22700 let parts: Vec<&str> = inner.split(',').collect();
22701 if parts.len() != 2 {
22702 return Err(interval_parse_error_profile(s));
22703 }
22704 let left = parts[0]
22705 .trim()
22706 .parse()
22707 .map_err(|_| interval_parse_error_profile(s))?;
22708 let right = parts[1]
22709 .trim()
22710 .parse()
22711 .map_err(|_| interval_parse_error_profile(s))?;
22712 Ok(Interval::new(left, right, closed))
22713 }
22714
22715 #[inline(never)]
22716 fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
22717 Interval::parse(std::hint::black_box(s))
22718 }
22719
22720 fn assert_interval_parse_profile_parity(s: &str) {
22721 match (
22722 interval_parse_former_profile(s),
22723 interval_parse_split_once_profile(s),
22724 ) {
22725 (Ok(former), Ok(candidate)) => {
22726 assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
22727 assert_eq!(
22728 former.right.to_bits(),
22729 candidate.right.to_bits(),
22730 "right: {s}"
22731 );
22732 assert_eq!(former.closed, candidate.closed, "closed: {s}");
22733 }
22734 (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
22735 (former, candidate) => assert_eq!(
22736 former.is_ok(),
22737 candidate.is_ok(),
22738 "parse result mismatch for {s}: {former:?} != {candidate:?}"
22739 ),
22740 }
22741 }
22742
22743 #[inline(never)]
22744 fn measure_interval_parser_profile(
22745 parser: fn(&str) -> Result<Interval, super::TypeError>,
22746 inputs: &[&str],
22747 rounds: usize,
22748 ) -> u128 {
22749 use std::{hint::black_box, time::Instant};
22750
22751 let started = Instant::now();
22752 let mut checksum = 0_u64;
22753 for _ in 0..rounds {
22754 for input in inputs {
22755 let parsed = parser(black_box(input)).expect("profile input must parse");
22756 let closed = match parsed.closed {
22757 IntervalClosed::Left => 1_u64,
22758 IntervalClosed::Right => 2,
22759 IntervalClosed::Both => 3,
22760 IntervalClosed::Neither => 4,
22761 };
22762 checksum = checksum
22763 .wrapping_add(parsed.left.to_bits().rotate_left(7))
22764 .wrapping_add(parsed.right.to_bits().rotate_right(11))
22765 .wrapping_add(closed);
22766 black_box(parsed);
22767 }
22768 }
22769 black_box(checksum);
22770 started.elapsed().as_nanos()
22771 }
22772
22773 #[test]
22774 #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
22775 fn profile_interval_parse_endpoint_split_ab_81jjv() {
22776 const VALID: [&str; 8] = [
22777 "[0, 1]",
22778 "(-0.0, 0.0]",
22779 " [ -1.5e3 , 2.75E-4 ) ",
22780 "(NaN, -0]",
22781 "[-inf, inf)",
22782 "[9.25, -7.5]",
22783 "(4.9406564584124654e-324, 1.7976931348623157e308)",
22784 "[-42, 17.125)",
22785 ];
22786 const INVALID: [&str; 12] = [
22787 "invalid",
22788 "[0]",
22789 "0, 1",
22790 "[0 1]",
22791 "[0, 1, 2]",
22792 "[0, 1,]",
22793 "[0,,1]",
22794 "[, 1]",
22795 "[0, ]",
22796 "{0, 1}",
22797 "[0, 1}",
22798 " ⟦0, 1⟧ ",
22799 ];
22800 const ROUNDS: usize = 16_384;
22801 const SAMPLES: usize = 10;
22802
22803 for input in VALID.iter().chain(INVALID.iter()) {
22804 assert_interval_parse_profile_parity(input);
22805 }
22806 for _ in 0..2 {
22807 measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
22808 measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
22809 }
22810
22811 let mut former_ns = Vec::with_capacity(SAMPLES);
22812 let mut candidate_ns = Vec::with_capacity(SAMPLES);
22813 for sample in 0..SAMPLES {
22814 if sample % 2 == 0 {
22815 former_ns.push(measure_interval_parser_profile(
22816 interval_parse_former_profile,
22817 &VALID,
22818 ROUNDS,
22819 ));
22820 candidate_ns.push(measure_interval_parser_profile(
22821 interval_parse_split_once_profile,
22822 &VALID,
22823 ROUNDS,
22824 ));
22825 } else {
22826 candidate_ns.push(measure_interval_parser_profile(
22827 interval_parse_split_once_profile,
22828 &VALID,
22829 ROUNDS,
22830 ));
22831 former_ns.push(measure_interval_parser_profile(
22832 interval_parse_former_profile,
22833 &VALID,
22834 ROUNDS,
22835 ));
22836 }
22837 }
22838 former_ns.sort_unstable();
22839 candidate_ns.sort_unstable();
22840 let former_p50 = former_ns[SAMPLES / 2];
22841 let candidate_p50 = candidate_ns[SAMPLES / 2];
22842 let former_p95 = former_ns[SAMPLES - 1];
22843 let candidate_p95 = candidate_ns[SAMPLES - 1];
22844 println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
22845 println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
22846 println!(
22847 "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
22848 former_p50 as f64 / candidate_p50 as f64
22849 );
22850 println!(
22851 "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
22852 former_p95 as f64 / candidate_p95 as f64
22853 );
22854 }
22855}
22856
22857#[cfg(test)]
22863mod float64_nullable_qkqfb {
22864 use super::{DType, NullKind, Scalar, cast_scalar, common_dtype};
22865
22866 #[test]
22877 fn the_two_float_flavours_have_different_missing_markers_qkqfb() {
22878 assert_eq!(
22879 Scalar::missing_for_dtype(DType::Float64Nullable),
22880 Scalar::Null(NullKind::Null),
22881 "the extension lane stores pd.NA"
22882 );
22883 assert_eq!(
22884 Scalar::missing_for_dtype(DType::Float64),
22885 Scalar::Null(NullKind::NaN),
22886 "the numpy lane stores a real NaN"
22887 );
22888 assert_ne!(
22891 Scalar::missing_for_dtype(DType::Float64Nullable),
22892 Scalar::missing_for_dtype(DType::Float64),
22893 );
22894 }
22895
22896 #[test]
22900 fn spelling_is_pandas_spelling_qkqfb() {
22901 assert_eq!(DType::Float64Nullable.name(), "Float64");
22902 assert_eq!(DType::Float64.name(), "float64");
22903 assert_ne!(DType::Float64Nullable.name(), DType::Float64.name());
22904 }
22905
22906 #[test]
22913 fn serde_round_trips_and_does_not_collide_with_numpy_float64_qkqfb() {
22914 let ext = serde_json::to_string(&DType::Float64Nullable).expect("serialize");
22915 let numpy = serde_json::to_string(&DType::Float64).expect("serialize");
22916 assert_eq!(ext, "\"Float64\"");
22917 assert_eq!(numpy, "\"float64\"");
22918 assert_ne!(ext, numpy);
22919
22920 assert_eq!(
22921 serde_json::from_str::<DType>(&ext).expect("deserialize"),
22922 DType::Float64Nullable
22923 );
22924 assert_eq!(
22925 serde_json::from_str::<DType>(&numpy).expect("deserialize"),
22926 DType::Float64
22927 );
22928 }
22929
22930 #[test]
22933 fn predicates_place_it_in_the_right_families_qkqfb() {
22934 assert!(DType::Float64Nullable.is_floating());
22935 assert!(DType::Float64Nullable.is_numeric());
22936 assert!(DType::Float64Nullable.is_any_real_numeric());
22937 assert!(DType::Float64Nullable.is_nullable());
22938 assert!(DType::Float64Nullable.is_extension());
22939 assert!(!DType::Float64Nullable.is_integer());
22942 assert!(!DType::Float64Nullable.is_signed_integer());
22943 assert!(!DType::Float64Nullable.is_bool());
22944 assert_eq!(DType::Float64Nullable.kind(), 'f');
22947 assert_eq!(DType::Float64Nullable.kind(), DType::Float64.kind());
22948 assert_eq!(DType::Float64Nullable.itemsize(), 8);
22949 }
22950
22951 #[test]
22954 fn nullable_pairing_is_an_involution_qkqfb() {
22955 assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
22956 assert_eq!(DType::Float64Nullable.to_non_nullable(), DType::Float64);
22957 assert_eq!(DType::Float64Nullable.to_nullable(), DType::Float64Nullable);
22959 assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
22960 assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
22962 assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
22963 }
22964
22965 #[test]
22975 fn the_nullable_float_absorbs_every_numeric_flavour_qkqfb() {
22976 for other in [
22977 DType::Float64,
22978 DType::Int64,
22979 DType::Int64Nullable,
22980 DType::Bool,
22981 DType::BoolNullable,
22982 DType::Float64Nullable,
22983 ] {
22984 assert_eq!(
22985 common_dtype(DType::Float64Nullable, other.clone()),
22986 Ok(DType::Float64Nullable),
22987 "Float64Nullable + {other:?}"
22988 );
22989 assert_eq!(
22993 common_dtype(other.clone(), DType::Float64Nullable),
22994 Ok(DType::Float64Nullable),
22995 "{other:?} + Float64Nullable"
22996 );
22997 }
22998 assert_eq!(
23000 common_dtype(DType::Null, DType::Float64Nullable),
23001 Ok(DType::Float64Nullable)
23002 );
23003 }
23004
23005 #[test]
23014 fn casts_preserve_values_and_convert_only_the_marker_qkqfb() {
23015 let present = Scalar::Float64(1.5);
23016 assert_eq!(
23017 cast_scalar(&present, DType::Float64Nullable),
23018 Ok(Scalar::Float64(1.5))
23019 );
23020 assert_eq!(
23021 cast_scalar(&Scalar::Float64(1.5), DType::Float64),
23022 Ok(Scalar::Float64(1.5))
23023 );
23024 assert_eq!(
23026 cast_scalar(&Scalar::Int64(1), DType::Float64Nullable),
23027 Ok(Scalar::Float64(1.0))
23028 );
23029 assert_eq!(
23030 cast_scalar(&Scalar::Bool(true), DType::Float64Nullable),
23031 Ok(Scalar::Float64(1.0))
23032 );
23033
23034 assert_eq!(
23037 cast_scalar(&Scalar::Null(NullKind::NaN), DType::Float64Nullable),
23038 Ok(Scalar::Null(NullKind::Null)),
23039 "numpy NaN entering an extension lane becomes pd.NA"
23040 );
23041 assert_eq!(
23042 cast_scalar(&Scalar::Null(NullKind::Null), DType::Float64),
23043 Ok(Scalar::Null(NullKind::NaN)),
23044 "pd.NA entering a numpy lane becomes NaN"
23045 );
23046 }
23047
23048 #[test]
23058 fn int64nullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
23059 assert_eq!(
23060 common_dtype(DType::Int64Nullable, DType::Float64),
23061 Ok(DType::Float64Nullable)
23062 );
23063 assert_eq!(
23064 common_dtype(DType::Float64, DType::Int64Nullable),
23065 Ok(DType::Float64Nullable)
23066 );
23067 }
23068
23069 #[test]
23077 fn boolnullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
23078 assert_eq!(
23079 common_dtype(DType::BoolNullable, DType::Float64),
23080 Ok(DType::Float64Nullable)
23081 );
23082 assert_eq!(
23083 common_dtype(DType::Bool, DType::Float64),
23084 Ok(DType::Float64),
23085 "numpy bool + numpy float stays entirely on the numpy side"
23086 );
23087 }
23088
23089 #[test]
23100 fn the_nullable_float_flip_is_associative_on_its_witness_triple_qkqfb() {
23101 let (bn, i64n, f64d) = (DType::BoolNullable, DType::Int64, DType::Float64);
23102
23103 let left = common_dtype(
23104 common_dtype(bn.clone(), i64n.clone()).unwrap(),
23105 f64d.clone(),
23106 )
23107 .unwrap();
23108 let right = common_dtype(bn, common_dtype(i64n, f64d).unwrap()).unwrap();
23109
23110 assert_eq!(left, right, "promotion order must not change the result");
23111 assert_eq!(left, DType::Float64Nullable);
23112 }
23113}
23114
23115#[cfg(test)]
23120mod sparse_dtype_pandas_name_3gxc6 {
23121 use super::{DType, Scalar, SparseDType};
23122
23123 fn name(value_dtype: DType, fill: Scalar) -> String {
23124 SparseDType::new(value_dtype, fill)
23125 .expect("sparse descriptor")
23126 .pandas_name()
23127 }
23128
23129 #[test]
23132 fn int64_fill_zero_is_the_fixture_row() {
23133 assert_eq!(name(DType::Int64, Scalar::Int64(0)), "Sparse[int64, 0]");
23134 }
23135
23136 #[test]
23139 fn the_fill_value_is_actually_rendered() {
23140 assert_eq!(name(DType::Int64, Scalar::Int64(7)), "Sparse[int64, 7]");
23141 assert_ne!(
23142 name(DType::Int64, Scalar::Int64(0)),
23143 name(DType::Int64, Scalar::Int64(7)),
23144 "two different fills must not collapse to one name"
23145 );
23146 }
23147
23148 #[test]
23150 fn float64_nan_fill_is_lowercase_nan() {
23151 assert_eq!(
23152 name(DType::Float64, Scalar::Float64(f64::NAN)),
23153 "Sparse[float64, nan]"
23154 );
23155 }
23156
23157 #[test]
23160 fn float64_zero_fill_keeps_its_trailing_point_zero() {
23161 assert_eq!(
23162 name(DType::Float64, Scalar::Float64(0.0)),
23163 "Sparse[float64, 0.0]"
23164 );
23165 assert_ne!(
23166 name(DType::Float64, Scalar::Float64(0.0)),
23167 name(DType::Int64, Scalar::Int64(0)),
23168 "float64 and int64 zero fills are different dtypes"
23169 );
23170 }
23171
23172 #[test]
23174 fn bool_fill_uses_python_capitalisation() {
23175 assert_eq!(
23176 name(DType::Bool, Scalar::Bool(false)),
23177 "Sparse[bool, False]"
23178 );
23179 assert_eq!(name(DType::Bool, Scalar::Bool(true)), "Sparse[bool, True]");
23180 }
23181
23182 #[test]
23185 fn utf8_subtype_renders_as_object() {
23186 let rendered = name(DType::Utf8, Scalar::Null(crate::NullKind::NaN));
23187 assert!(
23188 rendered.starts_with("Sparse[object, "),
23189 "expected an object subtype, got {rendered}"
23190 );
23191 }
23192
23193 #[test]
23196 fn no_constructible_descriptor_renders_the_bare_name() {
23197 for (dtype, fill) in [
23198 (DType::Int64, Scalar::Int64(0)),
23199 (DType::Float64, Scalar::Float64(1.5)),
23200 (DType::Bool, Scalar::Bool(true)),
23201 (DType::Utf8, Scalar::Utf8("x".to_owned())),
23202 ] {
23203 let rendered = name(dtype.clone(), fill);
23204 assert_ne!(rendered, "Sparse", "bare name regressed for {dtype:?}");
23205 assert!(
23206 rendered.starts_with("Sparse[") && rendered.ends_with(']'),
23207 "malformed sparse name {rendered}"
23208 );
23209 }
23210 }
23211
23212 #[test]
23213 fn test_dtype_from_str_and_display() {
23214 use std::str::FromStr;
23215
23216 use crate::DType;
23217
23218 assert_eq!(DType::from_str("int64").unwrap(), DType::Int64);
23219 assert_eq!(DType::from_str("Int64").unwrap(), DType::Int64Nullable);
23220 assert_eq!(DType::from_str("float64").unwrap(), DType::Float64);
23221 assert_eq!(DType::from_str("Float64").unwrap(), DType::Float64Nullable);
23222 assert_eq!(DType::from_str("bool").unwrap(), DType::Bool);
23223 assert_eq!(DType::from_str("boolean").unwrap(), DType::BoolNullable);
23224 assert_eq!(DType::from_str("string").unwrap(), DType::Utf8);
23225 assert_eq!(DType::from_str("category").unwrap(), DType::Categorical);
23226 assert_eq!(
23227 DType::from_str("timedelta64[ns]").unwrap(),
23228 DType::Timedelta64
23229 );
23230 assert_eq!(
23231 DType::from_str("datetime64[ns]").unwrap(),
23232 DType::Datetime64 { tz: None }
23233 );
23234 assert_eq!(
23235 DType::from_str("datetime64[ns, UTC]").unwrap(),
23236 DType::Datetime64 {
23237 tz: Some("UTC".to_string())
23238 }
23239 );
23240 assert_eq!(DType::from_str("period").unwrap(), DType::Period);
23241 assert_eq!(DType::from_str("interval").unwrap(), DType::Interval);
23242 assert_eq!(DType::from_str("sparse").unwrap(), DType::Sparse);
23243
23244 assert_eq!(format!("{}", DType::Int64), "int64");
23245 assert_eq!(
23246 format!(
23247 "{}",
23248 DType::Datetime64 {
23249 tz: Some("UTC".to_string())
23250 }
23251 ),
23252 "datetime64[ns, UTC]"
23253 );
23254 }
23255
23256 #[test]
23257 fn test_api_types_inspection_and_infer_dtype() {
23258 use crate::{
23259 DType, Scalar,
23260 api::types::{
23261 infer_dtype, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype,
23262 is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_int64_dtype,
23263 is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_object_dtype,
23264 is_period_dtype, is_scalar, is_signed_integer_dtype, is_sparse, is_string_dtype,
23265 is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype,
23266 },
23267 };
23268
23269 assert!(is_numeric_dtype(&DType::Int64));
23270 assert!(is_numeric_dtype(&DType::Float64));
23271 assert!(!is_numeric_dtype(&DType::Utf8));
23272 assert!(!is_numeric_dtype(&DType::Bool));
23273
23274 assert!(is_integer_dtype(&DType::Int64));
23275 assert!(is_integer_dtype(&DType::Int64Nullable));
23276 assert!(!is_integer_dtype(&DType::Float64));
23277
23278 assert!(is_int64_dtype(&DType::Int64));
23279 assert!(is_int64_dtype(&DType::Int64Nullable));
23280 assert!(!is_int64_dtype(&DType::Float64));
23281
23282 assert!(is_object_dtype(&DType::Utf8));
23283 assert!(!is_object_dtype(&DType::Int64));
23284
23285 assert!(is_dtype_equal(&DType::Int64, &DType::Int64));
23286 assert!(is_dtype_equal(&"int64", &DType::Int64));
23287 assert!(!is_dtype_equal(&DType::Int64, &DType::Float64));
23288
23289 assert!(is_signed_integer_dtype(&DType::Int64));
23290 assert!(!is_unsigned_integer_dtype(&DType::Int64));
23291
23292 assert!(is_float_dtype(&DType::Float64));
23293 assert!(is_bool_dtype(&DType::Bool));
23294 assert!(is_string_dtype(&DType::Utf8));
23295 assert!(is_datetime64_any_dtype(&DType::Datetime64 { tz: None }));
23296 assert!(is_timedelta64_dtype(&DType::Timedelta64));
23297 assert!(is_categorical_dtype(&DType::Categorical));
23298 assert!(is_period_dtype(&DType::Period));
23299 assert!(is_interval_dtype(&DType::Interval));
23300 assert!(is_sparse(&DType::Sparse));
23301 assert!(is_extension_array_dtype(&DType::Categorical));
23302 assert!(is_scalar(&Scalar::Int64(42)));
23303
23304 assert_eq!(pandas_dtype("float64").unwrap(), DType::Float64);
23305 assert!(pandas_dtype("invalid_dtype_xyz").is_err());
23306
23307 let ints = vec![Scalar::Int64(1), Scalar::Int64(2)];
23308 assert_eq!(infer_dtype(&ints, true), "integer");
23309
23310 let floats = vec![Scalar::Float64(1.0), Scalar::Float64(2.5)];
23311 assert_eq!(infer_dtype(&floats, true), "floating");
23312
23313 let bools = vec![Scalar::Bool(true), Scalar::Bool(false)];
23314 assert_eq!(infer_dtype(&bools, true), "boolean");
23315
23316 let strings = vec![Scalar::Utf8("a".to_string()), Scalar::Utf8("b".to_string())];
23317 assert_eq!(infer_dtype(&strings, true), "string");
23318
23319 let mixed = vec![Scalar::Int64(1), Scalar::Utf8("a".to_string())];
23320 assert_eq!(infer_dtype(&mixed, true), "mixed");
23321
23322 assert_eq!(infer_dtype(&[], true), "empty");
23323 }
23324
23325 #[test]
23326 fn test_na_nat_sentinels_and_eng_float_format() {
23327 use super::{
23328 NA, NAT, NaT, eng_float_format, get_eng_float_format, reset_eng_float_format,
23329 set_eng_float_format,
23330 };
23331
23332 assert!(NA.is_null());
23334 assert!(NAT.is_null());
23335 assert_eq!(NAT, NaT);
23336 assert_eq!(format!("{NA}"), "None");
23337 assert_eq!(format!("{NAT}"), "NaT");
23338
23339 assert_eq!(eng_float_format(1000.0, Some(3), false), "1.000E+03");
23341 assert_eq!(eng_float_format(0.005, Some(3), false), "5.000E-03");
23342 assert_eq!(eng_float_format(1234567.0, Some(3), false), "1.235E+06");
23343 assert_eq!(eng_float_format(-9876.54, Some(3), false), "-9.877E+03");
23344 assert_eq!(eng_float_format(0.0, Some(3), false), "0.000E+00");
23345
23346 assert_eq!(eng_float_format(1000.0, Some(3), true), "1.000k");
23348 assert_eq!(eng_float_format(0.005, Some(3), true), "5.000m");
23349 assert_eq!(eng_float_format(1234567.0, Some(3), true), "1.235M");
23350 assert_eq!(eng_float_format(-9876.54, Some(3), true), "-9.877k");
23351 assert_eq!(eng_float_format(0.0, Some(3), true), "0.000");
23352 assert_eq!(eng_float_format(1.5, Some(3), true), "1.500");
23353
23354 assert_eq!(eng_float_format(f64::NAN, Some(3), true), "NaN");
23356 assert_eq!(eng_float_format(f64::INFINITY, Some(3), true), "inf");
23357 assert_eq!(eng_float_format(f64::NEG_INFINITY, Some(3), true), "-inf");
23358
23359 reset_eng_float_format();
23361 assert_eq!(get_eng_float_format(), None);
23362 set_eng_float_format(4, true);
23363 assert_eq!(get_eng_float_format(), Some((4, true)));
23364 reset_eng_float_format();
23365 assert_eq!(get_eng_float_format(), None);
23366 }
23367
23368 #[test]
23369 fn test_options_system() {
23370 use super::{
23371 OptionError, OptionValue, describe_option, get_option, option_context, reset_option,
23372 set_option,
23373 };
23374
23375 reset_option(None).unwrap();
23377
23378 let max_rows = get_option("display.max_rows").unwrap();
23380 assert_eq!(max_rows.as_int(), Some(60));
23381 assert_eq!(max_rows, OptionValue::Int(60));
23382 assert!(!max_rows.is_none());
23383
23384 let min_rows = get_option("min_rows").unwrap();
23386 assert_eq!(min_rows.as_int(), Some(10));
23387
23388 set_option("display.max_rows", 100).unwrap();
23390 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
23391
23392 set_option("mode.sim_interactive", true).unwrap();
23393 assert_eq!(
23394 get_option("mode.sim_interactive").unwrap().as_bool(),
23395 Some(true)
23396 );
23397
23398 set_option("mode.chained_assignment", "raise").unwrap();
23399 assert_eq!(
23400 get_option("mode.chained_assignment").unwrap().as_str(),
23401 Some("raise")
23402 );
23403
23404 assert!(matches!(
23406 get_option("nonexistent.option"),
23407 Err(OptionError::NotFound { .. })
23408 ));
23409 assert!(matches!(
23410 get_option("display"),
23411 Err(OptionError::Ambiguous { .. })
23412 ));
23413
23414 let desc = describe_option(Some("max_rows")).unwrap();
23416 assert!(desc.contains("display.max_rows : [currently: 100]"));
23417
23418 let desc_all = describe_option(None).unwrap();
23419 assert!(desc_all.contains("display.width"));
23420 assert!(desc_all.contains("compute.use_bottleneck"));
23421
23422 {
23424 let _guard = option_context(&[
23425 ("display.max_rows", OptionValue::Int(999)),
23426 ("display.precision", OptionValue::Int(2)),
23427 ])
23428 .unwrap();
23429
23430 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(999));
23431 assert_eq!(get_option("display.precision").unwrap().as_int(), Some(2));
23432 }
23433 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
23435 assert_eq!(get_option("display.precision").unwrap().as_int(), Some(6));
23436
23437 reset_option(Some("display.max_rows")).unwrap();
23439 assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(60));
23440
23441 reset_option(Some("all")).unwrap();
23442 assert_eq!(
23443 get_option("mode.chained_assignment").unwrap().as_str(),
23444 Some("warn")
23445 );
23446
23447 assert_eq!(
23449 get_option("mode.copy_on_write").unwrap().as_bool(),
23450 Some(false)
23451 );
23452 assert_eq!(
23453 get_option("mode.data_manager").unwrap().as_str(),
23454 Some("block")
23455 );
23456 assert_eq!(
23457 get_option("display.large_repr").unwrap().as_str(),
23458 Some("truncate")
23459 );
23460 assert_eq!(
23461 get_option("display.max_info_columns").unwrap().as_int(),
23462 Some(100)
23463 );
23464 assert_eq!(
23465 get_option("display.memory_usage").unwrap().as_bool(),
23466 Some(true)
23467 );
23468 assert_eq!(
23469 get_option("display.colheader_justify").unwrap().as_str(),
23470 Some("right")
23471 );
23472 assert!(get_option("display.chop_threshold").unwrap().is_none());
23473 assert_eq!(
23474 get_option("io.parquet.engine").unwrap().as_str(),
23475 Some("auto")
23476 );
23477 assert_eq!(
23478 get_option("plotting.backend").unwrap().as_str(),
23479 Some("matplotlib")
23480 );
23481 assert_eq!(
23482 get_option("plotting.matplotlib.register_converters")
23483 .unwrap()
23484 .as_bool(),
23485 Some(true)
23486 );
23487
23488 set_option("display.chop_threshold", ()).unwrap();
23490 assert!(get_option("display.chop_threshold").unwrap().is_none());
23491 }
23492
23493 #[test]
23494 fn test_scalar_typed_accessors() {
23495 use super::{Interval, IntervalClosed, Period, PeriodFreq, Scalar};
23496
23497 let s_i64 = Scalar::Int64(42);
23498 assert_eq!(s_i64.as_i64(), Some(42));
23499 assert_eq!(s_i64.as_int(), Some(42));
23500 assert_eq!(s_i64.as_f64(), None);
23501 assert_eq!(s_i64.as_float(), None);
23502 assert_eq!(s_i64.as_bool(), None);
23503 assert_eq!(s_i64.as_str(), None);
23504
23505 let s_f64 = Scalar::Float64(2.75);
23506 assert_eq!(s_f64.as_f64(), Some(2.75));
23507 assert_eq!(s_f64.as_float(), Some(2.75));
23508 assert_eq!(s_f64.as_i64(), None);
23509 assert_eq!(s_f64.as_int(), None);
23510
23511 let s_bool = Scalar::Bool(true);
23512 assert_eq!(s_bool.as_bool(), Some(true));
23513 assert_eq!(s_bool.as_int(), None);
23514
23515 let s_str = Scalar::Utf8("pandas".to_string());
23516 assert_eq!(s_str.as_str(), Some("pandas"));
23517 assert_eq!(s_str.as_bool(), None);
23518
23519 let s_dt = Scalar::Datetime64(1_000_000_000);
23520 assert_eq!(s_dt.as_datetime_nanos(), Some(1_000_000_000));
23521 assert_eq!(s_dt.as_str(), None);
23522
23523 let s_td = Scalar::Timedelta64(500_000);
23524 assert_eq!(s_td.as_timedelta_nanos(), Some(500_000));
23525 assert_eq!(s_td.as_int(), None);
23526
23527 let s_per = Scalar::Period(Period::new(2024, PeriodFreq::Daily));
23528 assert_eq!(s_per.as_period_ordinal(), Some(2024));
23529
23530 let s_iv = Scalar::Interval(Interval::new(0.0, 10.0, IntervalClosed::Both));
23531 assert_eq!(
23532 s_iv.as_interval(),
23533 Some(Interval::new(0.0, 10.0, IntervalClosed::Both))
23534 );
23535 }
23536
23537 #[test]
23538 fn test_api_submodules_and_types_inspectors() {
23539 use super::{
23540 DType, Scalar,
23541 api::{extensions, indexers, types},
23542 };
23543
23544 assert!(types::is_number(&Scalar::Int64(42)));
23546 assert!(types::is_number(&Scalar::Float64(42.5)));
23547 assert!(types::is_number(&Scalar::Bool(true)));
23548 assert!(!types::is_number(&Scalar::Utf8("pandas".into())));
23549
23550 assert!(types::is_bool(&Scalar::Bool(false)));
23551 assert!(!types::is_bool(&Scalar::Int64(0)));
23552
23553 assert!(types::is_integer(&Scalar::Int64(10)));
23554 assert!(!types::is_integer(&Scalar::Float64(10.0)));
23555
23556 assert!(types::is_float(&Scalar::Float64(10.0)));
23557 assert!(!types::is_float(&Scalar::Int64(10)));
23558
23559 assert!(types::is_float64_dtype(&DType::Float64));
23561 assert!(types::is_float64_dtype(&DType::Float64Nullable));
23562 assert!(!types::is_float64_dtype(&DType::Int64));
23563 assert!(!types::is_int32_dtype(&DType::Int64));
23564
23565 extensions::register_dataframe_accessor("geo");
23567 extensions::register_series_accessor("geo");
23568 extensions::register_index_accessor("geo");
23569
23570 let base = indexers::BaseIndexer::new(5, 1);
23572 assert_eq!(base.window_size, 5);
23573 assert_eq!(base.step, 1);
23574
23575 let fwd = indexers::FixedForwardWindowIndexer::new(3);
23576 assert_eq!(fwd.window_size, 3);
23577
23578 let var = indexers::VariableOffsetWindowIndexer::new(100);
23579 assert_eq!(var.index_offset, 100);
23580 }
23581
23582 #[test]
23583 fn test_extension_dtypes_and_parameterized_parsing() {
23584 use super::{
23585 AsDType, CategoricalDtype, DType, IntervalClosed, IntervalDtype, PeriodDtype, Scalar,
23586 SparseDType, api::types, pandas_dtype,
23587 };
23588
23589 let cat_default = CategoricalDtype::default();
23591 assert_eq!(cat_default.name(), "category");
23592 assert_eq!(cat_default.kind(), "O");
23593 assert!(!cat_default.ordered());
23594 assert_eq!(cat_default.categories(), None);
23595 assert_eq!(cat_default.as_dtype(), DType::Categorical);
23596 assert!(types::is_categorical_dtype(&cat_default));
23597 assert_eq!(
23598 cat_default.to_string(),
23599 "CategoricalDtype(categories=None, ordered=False)"
23600 );
23601
23602 let cat_custom =
23603 CategoricalDtype::new(Some(vec!["low".to_string(), "high".to_string()]), true);
23604 assert!(cat_custom.ordered());
23605 assert_eq!(
23606 cat_custom.categories(),
23607 Some(&["low".to_string(), "high".to_string()][..])
23608 );
23609 assert!(cat_custom.to_string().contains("ordered=True"));
23610
23611 let per_default = PeriodDtype::default();
23613 assert_eq!(per_default.freq(), "D");
23614 assert_eq!(per_default.name(), "period[D]");
23615 assert_eq!(per_default.kind(), "O");
23616 assert_eq!(per_default.as_dtype(), DType::Period);
23617 assert!(types::is_period_dtype(&per_default));
23618 assert_eq!(per_default.to_string(), "period[D]");
23619
23620 let per_custom = PeriodDtype::new("M");
23621 assert_eq!(per_custom.freq(), "M");
23622 assert_eq!(per_custom.to_string(), "period[M]");
23623
23624 let int_default = IntervalDtype::default();
23626 assert_eq!(*int_default.subtype(), DType::Float64);
23627 assert_eq!(int_default.closed(), Some(IntervalClosed::Right));
23628 assert_eq!(int_default.name(), "interval");
23629 assert_eq!(int_default.kind(), "O");
23630 assert_eq!(int_default.as_dtype(), DType::Interval);
23631 assert!(types::is_interval_dtype(&int_default));
23632 assert_eq!(int_default.to_string(), "interval[float64, right]");
23633
23634 let int_custom = IntervalDtype::new(DType::Int64, Some(IntervalClosed::Both));
23635 assert_eq!(*int_custom.subtype(), DType::Int64);
23636 assert_eq!(int_custom.closed(), Some(IntervalClosed::Both));
23637 assert_eq!(int_custom.to_string(), "interval[int64, both]");
23638
23639 let sp = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).unwrap();
23641 assert_eq!(sp.as_dtype(), DType::Sparse);
23642 assert!(types::is_sparse(&sp));
23643
23644 assert_eq!(pandas_dtype("period[D]").unwrap(), DType::Period);
23646 assert_eq!(pandas_dtype("Period[M]").unwrap(), DType::Period);
23647 assert_eq!(pandas_dtype("interval[float64]").unwrap(), DType::Interval);
23648 assert_eq!(pandas_dtype("Interval[int64]").unwrap(), DType::Interval);
23649 assert_eq!(pandas_dtype("sparse[float64]").unwrap(), DType::Sparse);
23650 assert_eq!(pandas_dtype("Sparse[int64, 0]").unwrap(), DType::Sparse);
23651 }
23652}
23653
23654#[cfg(test)]
23657mod numeric_width_fvsao23 {
23658 use super::{DType, NumericWidth, NumpyNumeric, numpy_pairwise_sum};
23659
23660 #[test]
23661 fn float32_sum_is_numpys_pairwise_sum_bit_for_bit() {
23662 let cases: [(usize, u32); 5] = [
23666 (5, 1_083_829_126),
23667 (64, 1_136_679_190),
23668 (129, 1_145_981_108),
23669 (1000, 1_170_926_592),
23670 (4097, 1_188_011_795),
23671 ];
23672 for (n, bits) in cases {
23673 #[allow(clippy::cast_precision_loss)] let values: Vec<f32> = (0..n)
23675 .map(|k| ((k * 37) % 1000) as f32 * 0.013_f32)
23676 .collect();
23677 assert_eq!(numpy_pairwise_sum(&values).to_bits(), bits, "n={n}");
23678 if n < 100 {
23679 #[allow(clippy::cast_possible_truncation)]
23680 let rounded_once = values.iter().map(|&v| f64::from(v)).sum::<f64>() as f32;
23681 assert_ne!(rounded_once.to_bits(), bits, "n={n}");
23682 }
23683 }
23684 assert_eq!(numpy_pairwise_sum::<f32>(&[]), 0.0);
23685 }
23686
23687 #[test]
23688 fn names_parse_and_round_trip() {
23689 for width in NumericWidth::ALL {
23690 for nullable in [false, true] {
23691 assert_eq!(
23692 NumericWidth::parse(width.name(nullable)),
23693 Some((width, nullable))
23694 );
23695 }
23696 }
23697 for (name, expected) in [
23698 ("<i4", (NumericWidth::Int32, false)),
23699 ("f4", (NumericWidth::Float32, false)),
23700 ("UInt8Dtype", (NumericWidth::UInt8, true)),
23701 ] {
23702 assert_eq!(NumericWidth::parse(name), Some(expected), "{name}");
23703 }
23704 for name in ["int64", "Int64", "float64", "i8", "f8", "int", "float"] {
23706 assert_eq!(NumericWidth::parse(name), None, "{name}");
23707 }
23708 }
23709
23710 #[test]
23711 fn wrapping_is_numpys_modular_cast_not_saturation() {
23712 assert_eq!(NumericWidth::Int8.wrap_int(300), Some(44));
23714 assert_eq!(NumericWidth::UInt8.wrap_int(-5), Some(251));
23716 assert_eq!(NumericWidth::UInt16.wrap_int(-5), Some(65531));
23717 assert_eq!(NumericWidth::UInt32.wrap_int(-5), Some(4_294_967_291));
23718 assert_eq!(NumericWidth::Int8.wrap_int(200), Some(-56));
23720 assert_eq!(
23721 NumericWidth::Int32.wrap_int(i64::from(i32::MAX) + 1),
23722 Some(i64::from(i32::MIN))
23723 );
23724 let product = 50_000_i64.wrapping_pow(5);
23726 assert_eq!(
23727 NumericWidth::Int32.wrap_int(product),
23728 Some(i64::from(50_000_i32.wrapping_pow(5)))
23729 );
23730 assert_eq!(NumericWidth::UInt64.wrap_int(-1), None);
23732 assert_eq!(NumericWidth::UInt64.wrap_int(7), Some(7));
23733 assert_eq!(NumericWidth::Float32.wrap_int(1), None);
23734 assert!(NumericWidth::Int8.holds_int(-128) && !NumericWidth::Int8.holds_int(128));
23735 }
23736
23737 #[test]
23738 fn float32_rounding_is_to_nearest_not_truncation() {
23739 assert_eq!(NumericWidth::round_f32(0.1), 0.100_000_001_490_116_12);
23741 let sum =
23744 NumericWidth::round_f32(NumericWidth::round_f32(0.1) + NumericWidth::round_f32(0.2));
23745 assert_eq!(sum, 0.300_000_011_920_928_96);
23746 assert_eq!(NumericWidth::round_f32(1.0 + 2f64.powi(-24)), 1.0);
23749 let above_tie = 1.0 + 3.0 * 2f64.powi(-25);
23750 assert_eq!(NumericWidth::round_f32(above_tie), 1.0 + 2f64.powi(-23));
23751 assert!(NumericWidth::round_f32(f64::NAN).is_nan());
23752 assert_eq!(NumericWidth::round_f32(1e300), f64::INFINITY);
23753 }
23754
23755 #[test]
23756 fn result_type_matches_numpy_promotion() {
23757 use NumpyNumeric::{Bool, Float, Int, UInt};
23758 let cases = [
23759 (Int(32), Int(64), Int(64)), (Int(8), UInt(8), Int(16)), (Int(16), UInt(8), Int(16)),
23762 (Int(8), UInt(16), Int(32)),
23763 (Int(32), UInt(32), Int(64)),
23764 (Int(64), UInt(64), Float(64)), (UInt(8), UInt(32), UInt(32)),
23766 (Float(32), Int(8), Float(32)), (Float(32), UInt(16), Float(32)),
23768 (Float(32), Int(32), Float(64)), (Float(32), Float(64), Float(64)),
23770 (Bool, Int(8), Int(8)),
23771 (Bool, Float(32), Float(32)),
23772 ];
23773 for (a, b, expected) in cases {
23774 assert_eq!(a.result_type(b), expected, "{a:?} {b:?}");
23775 assert_eq!(b.result_type(a), expected, "{b:?} {a:?}");
23776 }
23777 assert_eq!(Int(32).with_python_int(), Int(32));
23780 assert_eq!(Int(32).with_python_float(), Float(64));
23781 assert_eq!(Float(32).with_python_float(), Float(32));
23782 assert_eq!(Bool.with_python_int(), Int(64));
23783 }
23784
23785 #[test]
23786 fn columns_map_to_numpy_dtypes() {
23787 let cases = [
23788 (DType::Int64, None, Some(NumpyNumeric::Int(64))),
23789 (
23790 DType::Int64Nullable,
23791 Some(NumericWidth::UInt8),
23792 Some(NumpyNumeric::UInt(8)),
23793 ),
23794 (
23795 DType::Float64,
23796 Some(NumericWidth::Float32),
23797 Some(NumpyNumeric::Float(32)),
23798 ),
23799 (DType::Float64, Some(NumericWidth::Int8), None),
23801 (DType::Utf8, None, None),
23802 ];
23803 for (dtype, width, expected) in cases {
23804 assert_eq!(NumpyNumeric::of(&dtype, width), expected, "{dtype:?}");
23805 }
23806 for width in NumericWidth::ALL {
23807 assert_eq!(NumpyNumeric::of_width(width).width(), Some(width));
23808 assert!(width.fits_storage(&width.storage(false)));
23809 assert!(width.fits_storage(&width.storage(true)));
23810 }
23811 assert_eq!(NumpyNumeric::Int(64).width(), None);
23812 }
23813
23814 #[test]
23815 fn downcast_and_category_code_widths() {
23816 let int32_max_plus_one = i64::from(i32::MAX) + 1;
23819 let signed = [
23820 ((1, 2), Some(NumericWidth::Int8)),
23821 ((1, 300), Some(NumericWidth::Int16)),
23822 ((0, int32_max_plus_one), None),
23823 ];
23824 for ((low, high), expected) in signed {
23825 assert_eq!(NumericWidth::smallest_signed(low, high), expected);
23826 }
23827 let unsigned = [((1, 300), Some(NumericWidth::UInt16)), ((-1, 3), None)];
23828 for ((low, high), expected) in unsigned {
23829 assert_eq!(NumericWidth::smallest_unsigned(low, high), expected);
23830 }
23831 for (categories, expected) in [
23833 (2, NumericWidth::Int8),
23834 (126, NumericWidth::Int8),
23835 (127, NumericWidth::Int16),
23836 (200, NumericWidth::Int16),
23837 ] {
23838 assert_eq!(NumericWidth::for_category_codes(categories), Some(expected));
23839 }
23840 assert_eq!(NumericWidth::itemsize(NumericWidth::Int8), 1);
23841 assert_eq!(NumericWidth::Float32.itemsize(), 4);
23842 }
23843}
23844
23845#[cfg(test)]
23850mod pandas_reductions_9iim6 {
23851 use super::{MissingLayout, PandasReductions, ReductionValues};
23852
23853 #[allow(clippy::cast_precision_loss)] fn floats(n: usize) -> (Vec<f64>, Vec<u64>) {
23857 let mut present = vec![0_u64; n.div_ceil(64)];
23858 let values = (0..n)
23859 .map(|k| {
23860 if k % 11 != 3 {
23861 present[k / 64] |= 1 << (k % 64);
23862 }
23863 let base = ((k * 7919 + 13) % 100_003) as f64 / 7.0 - 7000.0;
23864 if k % 5 == 0 { base * 1e6 } else { base }
23865 })
23866 .collect();
23867 (values, present)
23868 }
23869
23870 fn ints(n: usize) -> Vec<i64> {
23872 (0..n)
23873 .map(|k| i64::try_from((k * 7919 + 13) % 100_003).unwrap() * 3_000_000_007)
23874 .collect()
23875 }
23876
23877 fn assert_bits(got: &[f64], expected: &[u64], case: &str) {
23878 let got: Vec<u64> = got.iter().map(|value| value.to_bits()).collect();
23879 assert_eq!(got, expected, "{case}");
23880 }
23881
23882 #[test]
23883 fn numpy_float64_with_nan_matches_pandas_bits() {
23884 let cases: [(usize, [u64; 7]); 7] = [
23886 (
23887 7,
23888 [
23889 0xc1ff_1185_2dcb_6db6,
23890 0xc1d4_b658_c932_4924,
23891 0x43db_301d_4a8d_87a3,
23892 0x41e4_db58_e2f1_458e,
23893 0x41d1_078f_09d3_9c5c,
23894 0xc002_1f47_ceae_1b43,
23895 0x4014_c8bc_93df_56e6,
23896 ],
23897 ),
23898 (
23899 8,
23900 [
23901 0xc1ff_1184_f43d_b6da,
23902 0xc1d1_c0de_426c_687d,
23903 0x43d7_9d3c_ecd2_da2b,
23904 0x41e3_7012_7d6c_71a5,
23905 0x41cd_631d_3379_9929,
23906 0xc003_b196_82f9_28dc,
23907 0x4018_9de2_eba9_5ecc,
23908 ],
23909 ),
23910 (
23911 127,
23912 [
23913 0x4200_324e_3389_2490,
23914 0x4192_0704_ad1e_360d,
23915 0x43c9_4a6b_3390_577d,
23916 0x41dc_72bf_d6fa_9808,
23917 0x41a5_38f5_8417_ae1e,
23918 0x3fd0_b6bf_045c_e4d5,
23919 0x4017_1585_bf13_21c4,
23920 ],
23921 ),
23922 (
23923 128,
23924 [
23925 0x4200_324d_7236_db6e,
23926 0x4191_df3a_f99d_a2ae,
23927 0x43c9_1234_ffb7_4a93,
23928 0x41dc_5310_c97c_292c,
23929 0x41a5_09f4_cfcf_9206,
23930 0x3fd0_d9df_0d68_00b0,
23931 0x4017_61b6_5653_ae82,
23932 ],
23933 ),
23934 (
23935 129,
23936 [
23937 0x4200_324c_d43e_db71,
23938 0x4191_b81f_8a1d_61da,
23939 0x43c8_daf6_85d3_386f,
23940 0x41dc_33ca_af49_8c24,
23941 0x41a4_dbc2_8609_a567,
23942 0x3fd0_fcc5_39d9_6901,
23943 0x4017_ade4_7855_7c25,
23944 ],
23945 ),
23946 (
23947 1000,
23948 [
23949 0x421a_d4f6_8061_248e,
23950 0x417e_39f9_3e1a_a248,
23951 0x43c7_9481_cba1_263b,
23952 0x41db_7825_28c0_37cc,
23953 0x418d_27ba_a0ea_2f9a,
23954 0x3fc8_e53a_e277_3d7f,
23955 0x4018_3c97_3603_dfd0,
23956 ],
23957 ),
23958 (
23959 100_000,
23960 [
23961 0x4283_088c_316e_46dc,
23962 0x417b_7135_0c27_1185,
23963 0x43c7_a0de_3b8e_ea34,
23964 0x41db_7f57_6673_8d6b,
23965 0x4157_58cc_33fd_4ae6,
23966 0x3fc7_f1cf_b14a_14c8,
23967 0x4018_06b5_f26a_c384,
23968 ],
23969 ),
23970 ];
23971 let all = |r: &PandasReductions<'_>| {
23972 [
23973 r.sum(),
23974 r.mean(),
23975 r.var(1),
23976 r.std(1),
23977 r.sem(1),
23978 r.skew(),
23979 r.kurt(),
23980 ]
23981 };
23982 for (n, expected) in cases {
23983 let (values, present) = floats(n);
23984 let r = PandasReductions::new(
23985 ReductionValues::Float(&values),
23986 Some(&present),
23987 MissingLayout::Numpy,
23988 );
23989 assert_bits(&all(&r), &expected, &format!("float64 n={n}"));
23990 let with_nan: Vec<f64> = values
23993 .iter()
23994 .enumerate()
23995 .map(|(k, &value)| if k % 11 == 3 { f64::NAN } else { value })
23996 .collect();
23997 let r = PandasReductions::numpy_nan_missing(ReductionValues::Float(&with_nan));
23998 assert_bits(&all(&r), &expected, &format!("float64 NaN n={n}"));
23999 let (head, tail) = with_nan.split_at(n / 3);
24000 let chunks = [head, tail];
24001 let r = PandasReductions::numpy_nan_missing(ReductionValues::FloatChunks(&chunks));
24002 assert_bits(&all(&r), &expected, &format!("float64 NaN chunks n={n}"));
24003 }
24004 let (values, present) = floats(100_000);
24006 let left_fold: f64 = values
24007 .iter()
24008 .enumerate()
24009 .filter(|&(k, _)| present[k / 64] >> (k % 64) & 1 == 1)
24010 .map(|(_, value)| value)
24011 .sum();
24012 assert_ne!(left_fold.to_bits(), 0x4283_088c_316e_46dc);
24013 }
24014
24015 #[test]
24016 fn numpy_int64_mean_sums_through_the_cast_buffer() {
24017 let cases: [(usize, [u64; 5]); 3] = [
24019 (
24020 129,
24021 [
24022 0x42e0_dda2_9987_3f9e,
24023 0x45b9_0e2a_887d_aeda,
24024 0x429c_34a1_c273_372f,
24025 0x3f95_9e9d_c69e_ec88,
24026 0xbff3_844b_ba13_eac1,
24027 ],
24028 ),
24029 (
24030 8193,
24031 [
24032 0x42e1_0d5b_e407_5aa7,
24033 0x45b8_3bf5_04f5_f2fc,
24034 0x426b_d893_c5c9_85b1,
24035 0x3f42_7452_ff15_86c7,
24036 0xbff3_318c_611b_b59c,
24037 ],
24038 ),
24039 (
24040 20_000,
24041 [
24042 0x42e1_0d17_ebf8_272d,
24043 0x45b8_3c24_c921_82b6,
24044 0x4261_d2a2_f139_68e2,
24045 0x3f31_a21c_d4bb_ff52,
24046 0xbff3_328c_4edc_26ee,
24047 ],
24048 ),
24049 ];
24050 for (n, expected) in cases {
24051 let values = ints(n);
24052 let r =
24053 PandasReductions::new(ReductionValues::Int(&values), None, MissingLayout::Numpy);
24054 let got = [r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()];
24055 assert_bits(&got, &expected, &format!("int64 n={n}"));
24056 let (head, tail) = values.split_at(n / 3);
24058 let (middle, rest) = tail.split_at(1);
24059 let chunks = [head, middle, &[][..], rest];
24060 let chunked = PandasReductions::new(
24061 ReductionValues::IntChunks(&chunks),
24062 None,
24063 MissingLayout::Numpy,
24064 );
24065 let got = [
24066 chunked.mean(),
24067 chunked.var(1),
24068 chunked.sem(1),
24069 chunked.skew(),
24070 chunked.kurt(),
24071 ];
24072 assert_bits(&got, &expected, &format!("int64 chunks n={n}"));
24073 }
24074 }
24075
24076 #[test]
24077 fn masked_columns_add_runs_of_present_values() {
24078 let cases: [(usize, [u64; 4]); 3] = [
24082 (
24083 129,
24084 [
24085 0x4200_324c_d43e_db6e,
24086 0x4191_b81f_8a1d_61d6,
24087 0x43c8_daf6_85d3_3872,
24088 0x41a4_dbc2_8609_a567,
24089 ],
24090 ),
24091 (
24092 1000,
24093 [
24094 0x421a_d4f6_8061_2492,
24095 0x417e_39f9_3e1a_a24c,
24096 0x43c7_9481_cba1_263a,
24097 0x418d_27ba_a0ea_2f9a,
24098 ],
24099 ),
24100 (
24101 100_000,
24102 [
24103 0x4283_088c_316e_46de,
24104 0x417b_7135_0c27_1188,
24105 0x43c7_a0de_3b8e_ea37,
24106 0x4157_58cc_33fd_4ae6,
24107 ],
24108 ),
24109 ];
24110 for (n, expected) in cases {
24111 let (values, present) = floats(n);
24112 let r = PandasReductions::new(
24113 ReductionValues::Float(&values),
24114 Some(&present),
24115 MissingLayout::Masked,
24116 );
24117 assert_bits(
24118 &[r.sum(), r.mean(), r.var(1), r.sem(1)],
24119 &expected,
24120 &format!("Float64 n={n}"),
24121 );
24122 let (head, tail) = values.split_at(n / 2 + 1);
24123 let chunks = [head, tail];
24124 let chunked = PandasReductions::new(
24125 ReductionValues::FloatChunks(&chunks),
24126 Some(&present),
24127 MissingLayout::Masked,
24128 );
24129 let got = [
24130 chunked.sum(),
24131 chunked.mean(),
24132 chunked.var(1),
24133 chunked.sem(1),
24134 ];
24135 assert_bits(&got, &expected, &format!("Float64 chunks n={n}"));
24136 }
24137 for (n, expected) in [
24140 (8193, [0x42e1_0f35_29c2_807b_u64, 0x45b8_39ed_8746_bdcc]),
24141 (20_000, [0x42e1_0cf2_cc56_752a, 0x45b8_3c63_72fc_fad5]),
24142 ] {
24143 let values = ints(n);
24144 let mut present = vec![0_u64; n.div_ceil(64)];
24145 for k in (0..n).filter(|k| k % 997 != 5) {
24146 present[k / 64] |= 1 << (k % 64);
24147 }
24148 let r = PandasReductions::new(
24149 ReductionValues::Int(&values),
24150 Some(&present),
24151 MissingLayout::Masked,
24152 );
24153 assert_bits(&[r.mean(), r.var(1)], &expected, &format!("Int64 n={n}"));
24154 }
24155 }
24156
24157 #[test]
24158 fn edge_cases_match_pandas() {
24159 let reductions = |values: &[f64], present: Option<&[u64]>| {
24160 let r = PandasReductions::new(
24161 ReductionValues::Float(values),
24162 present,
24163 MissingLayout::Numpy,
24164 );
24165 [r.sum(), r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()]
24166 };
24167 let constant = reductions(&[1.5; 10], None);
24170 assert_eq!(constant, [15.0, 1.5, 0.0, 0.0, 0.0, 0.0]);
24171 assert!(reductions(&[2.0; 3], None)[5].is_nan());
24172 assert!(reductions(&[1.0, 2.0], None)[4].is_nan());
24174 assert_eq!(
24175 reductions(&[1.0, 2.0, 4.0], None)[4],
24176 0.935_219_529_582_823_7
24177 );
24178 let empty = reductions(&[], None);
24180 assert_eq!(empty[0], 0.0);
24181 assert!(empty[1..].iter().all(|value| value.is_nan()));
24182 let all_missing = reductions(&[3.0; 5], Some(&[0]));
24183 assert_eq!(all_missing[0], 0.0);
24184 assert!(all_missing[1].is_nan());
24185 assert_eq!(
24187 reductions(&[-0.0; 10], None)[0].to_bits(),
24188 0.0_f64.to_bits()
24189 );
24190 let inf = reductions(&[1.0, f64::INFINITY, 2.0, 5.0], None);
24192 assert_eq!(inf[0], f64::INFINITY);
24193 assert!(inf[2..].iter().all(|value| value.is_nan()));
24194 }
24195
24196 #[test]
24197 fn int64_mean_skipping_is_the_filled_mean_vk7y9() {
24198 const NAT: i64 = i64::MIN;
24202 let nanos: Vec<i64> = (0..20_000_i64)
24203 .map(|k| {
24204 if k % 13 == 5 {
24205 NAT
24206 } else {
24207 1_577_836_800_000_000_000 + k * 3_600_000_000_123
24208 }
24209 })
24210 .collect();
24211 let mut present = vec![0_u64; nanos.len().div_ceil(64)];
24212 let filled: Vec<i64> = nanos
24213 .iter()
24214 .enumerate()
24215 .map(|(i, &ns)| {
24216 if ns == NAT {
24217 0
24218 } else {
24219 present[i / 64] |= 1 << (i % 64);
24220 ns
24221 }
24222 })
24223 .collect();
24224 let expected = PandasReductions::new(
24225 ReductionValues::Int(&filled),
24226 Some(&present),
24227 MissingLayout::Numpy,
24228 )
24229 .mean();
24230 assert_eq!(
24231 PandasReductions::int64_mean_skipping(&nanos, NAT).to_bits(),
24232 expected.to_bits()
24233 );
24234 assert!(PandasReductions::int64_mean_skipping(&[NAT, NAT], NAT).is_nan());
24236 assert!(PandasReductions::int64_mean_skipping(&[], NAT).is_nan());
24237 }
24238}
24239
24240#[cfg(test)]
24244mod pandas_decimal_py3c0 {
24245 use super::{PandasDecimal, pandas_decimal_to_f64, pandas_int_to_f64};
24246
24247 fn bits(token: &str) -> u64 {
24248 match pandas_decimal_to_f64(token.as_bytes()) {
24249 PandasDecimal::Value(value) => value.to_bits(),
24250 other => panic!("{token:?}: {other:?}"),
24251 }
24252 }
24253
24254 #[test]
24255 fn tokens_convert_to_pandas_bits() {
24256 let cases = [
24257 ("9.890295358649789", 0x4023_c7d4_cb12_5ce4),
24258 ("0.8690736625851781286570704999", 0x3feb_cf73_91d3_c8f1),
24259 ("0.000000068288360759838675650889", 0x3e72_54bd_8bcd_610b),
24260 ("-0.0080749473608410608782560", 0xbf80_8999_16a7_63f3),
24261 ("99999999999999999", 0x4376_3457_85d8_a001),
24262 ("1234567890123456789012345", 0x44f0_56e0_f36a_6444),
24263 ("00000000000000000.5", 0x0000_0000_0000_0000),
24265 ("-00000000000000000.5", 0x8000_0000_0000_0000),
24266 ("1.5E+10", 0x420b_f08e_b000_0000),
24267 ("-.5e-3", 0xbf40_624d_d2f1_a9fc),
24268 ("5.", 0x4014_0000_0000_0000),
24269 ("1e-320", 0x0000_0000_0000_07e8),
24270 ("2.5e-310", 0x0000_2e05_5c9a_3f6c),
24271 ("-1e-400", 0x8000_0000_0000_0000),
24272 ("-1e-700", 0x0000_0000_0000_0000),
24274 ("1e-4294967296", 0x3ff0_0000_0000_0000),
24276 ("1.7976931348623157e308", 0x7fef_ffff_ffff_ffff),
24277 ("0.001e310", 0x7fac_7b1f_3cac_7433),
24278 ];
24279 for (token, expected) in cases {
24280 assert_eq!(bits(token), expected, "{token:?}");
24281 }
24282 let correctly_rounded: f64 = "9.890295358649789".parse().unwrap();
24284 assert_ne!(correctly_rounded.to_bits(), 0x4023_c7d4_cb12_5ce4);
24285 }
24286
24287 #[test]
24288 fn what_pandas_does_not_read_as_a_float() {
24289 for token in [
24290 "1e309",
24291 "0e400",
24292 "1.8e308",
24293 "1e+0000000000000000001",
24294 "1e-2147483649",
24295 "1e",
24296 "1e+",
24297 "1.5d3",
24298 "0x10",
24299 "1_000.5",
24300 "1..5",
24301 ] {
24302 assert_eq!(
24303 pandas_decimal_to_f64(token.as_bytes()),
24304 PandasDecimal::Rejected,
24305 "{token:?}"
24306 );
24307 }
24308 for token in ["inf", "-Infinity", "nan", ".", "-", "e5", "+.e1", "--1", ""] {
24309 assert_eq!(
24310 pandas_decimal_to_f64(token.as_bytes()),
24311 PandasDecimal::NotDecimal,
24312 "{token:?}"
24313 );
24314 }
24315 }
24316
24317 #[test]
24318 fn an_integer_in_a_float_column_takes_the_same_conversion() {
24319 assert_eq!(pandas_int_to_f64(-42).to_bits(), (-42.0_f64).to_bits());
24320 assert_eq!(
24321 pandas_int_to_f64(99_999_999_999_999_999).to_bits(),
24322 0x4376_3457_85d8_a001
24323 );
24324 assert_eq!(
24325 pandas_int_to_f64(-99_999_999_999_999_999).to_bits(),
24326 0xc376_3457_85d8_a001
24327 );
24328 }
24329
24330 #[test]
24337 fn calendar_months_match_chrono_relativedelta_4g57c() {
24338 use chrono::{Datelike, NaiveDate};
24339
24340 use super::add_calendar_months_nanos;
24341 let reference = |nanos: i64, months: i64| -> Option<i64> {
24342 let at = chrono::DateTime::from_timestamp(
24343 nanos.div_euclid(1_000_000_000),
24344 u32::try_from(nanos.rem_euclid(1_000_000_000)).ok()?,
24345 )?
24346 .naive_utc();
24347 let total = i64::from(at.year())
24348 .checked_mul(12)?
24349 .checked_add(i64::from(at.month0()))?
24350 .checked_add(months)?;
24351 let year = i32::try_from(total.div_euclid(12)).ok()?;
24352 let month = u32::try_from(total.rem_euclid(12)).ok()? + 1;
24353 let last = (28..=31)
24354 .rev()
24355 .find(|day| NaiveDate::from_ymd_opt(year, month, *day).is_some())?;
24356 NaiveDate::from_ymd_opt(year, month, at.day().min(last))?
24357 .and_time(at.time())
24358 .and_utc()
24359 .timestamp_nanos_opt()
24360 };
24361 let day_nanos = 86_400_000_000_000_i64;
24362 let mut checked = 0;
24363 for year in [1678, 1699, 1900, 1969, 1970, 2000, 2023, 2024, 2100, 2261] {
24364 for month in 1..=12 {
24365 for day in [1, 15, 27, 28, 29, 30, 31] {
24366 let Some(date) = NaiveDate::from_ymd_opt(year, month, day) else {
24367 continue;
24368 };
24369 let Some(midnight) = date
24370 .and_hms_opt(0, 0, 0)
24371 .and_then(|at| at.and_utc().timestamp_nanos_opt())
24372 else {
24373 continue;
24374 };
24375 for time in [0, 1, 37_123_456_789, day_nanos - 1] {
24376 let nanos = midnight + time;
24377 for months in [-2400, -13, -12, -1, 0, 1, 2, 11, 12, 25, 1200] {
24378 assert_eq!(
24379 add_calendar_months_nanos(nanos, months),
24380 reference(nanos, months),
24381 "{nanos} + {months} months"
24382 );
24383 checked += 1;
24384 }
24385 }
24386 }
24387 }
24388 }
24389 assert!(checked > 30_000, "{checked}");
24390 let last = i64::MAX - 1;
24392 assert_eq!(add_calendar_months_nanos(last, 1), None);
24393 assert_eq!(reference(last, 1), None);
24394 assert_eq!(add_calendar_months_nanos(i64::MIN + 1, -1), None);
24395 assert_eq!(add_calendar_months_nanos(0, i64::MAX), None);
24396 assert_eq!(add_calendar_months_nanos(0, i64::MIN), None);
24397 assert_eq!(add_calendar_months_nanos(0, 12 * 400), None);
24398 assert_eq!(super::add_calendar_months_days(i64::MAX, 1), None);
24399 assert_eq!(super::add_calendar_months_days(0, i64::MAX), None);
24400 let jan31 = 19_753 * day_nanos;
24402 assert_eq!(
24403 add_calendar_months_nanos(jan31, 1),
24404 Some(19_782 * day_nanos)
24405 );
24406 }
24407
24408 #[test]
24414 fn numbered_host_values_compare_and_hash_by_number_jq8qb() {
24415 use std::hash::{Hash, Hasher};
24416
24417 use super::{HostObject, HostValue, ObjectValue};
24418
24419 struct Numbered(Option<i64>, &'static str);
24420 impl HostObject for Numbered {
24421 fn host_eq(&self, other: &dyn HostObject) -> bool {
24422 other
24423 .as_any()
24424 .downcast_ref::<Self>()
24425 .is_some_and(|other| other.1 == self.1)
24426 }
24427 fn host_repr(&self) -> String {
24428 self.1.to_owned()
24429 }
24430 fn host_str(&self) -> String {
24431 self.1.to_owned()
24432 }
24433 fn host_hash(&self) -> Option<u64> {
24434 Some(self.1.len() as u64)
24435 }
24436 fn host_cmp(&self, _other: &dyn HostObject) -> Option<std::cmp::Ordering> {
24437 None
24438 }
24439 fn as_any(&self) -> &dyn std::any::Any {
24440 self
24441 }
24442 fn host_number(&self) -> Option<i64> {
24443 self.0
24444 }
24445 }
24446 let hash = |value: &ObjectValue| {
24447 let mut hasher = std::hash::DefaultHasher::new();
24448 value.hash(&mut hasher);
24449 hasher.finish()
24450 };
24451 let cell = |number, name| ObjectValue::Host(HostValue::new(Numbered(number, name)));
24452 assert_eq!(cell(Some(7), "a"), cell(Some(7), "b"));
24453 assert_eq!(hash(&cell(Some(7), "a")), hash(&cell(Some(7), "bb")));
24454 assert_ne!(cell(Some(7), "a"), cell(Some(8), "a"));
24455 assert_eq!(cell(Some(7), "a"), cell(None, "a"));
24456 assert_ne!(cell(Some(7), "a"), cell(None, "b"));
24457 assert_eq!(cell(None, "a"), cell(None, "a"));
24458 assert_ne!(cell(None, "a"), cell(None, "b"));
24459 assert_eq!(hash(&cell(None, "ab")), hash(&cell(None, "cd")));
24460 }
24461
24462 #[test]
24463 fn interval_parse_rejects_multibyte_and_malformed_inputs_without_panic_4qg5w_13() {
24464 use super::{Interval, IntervalClosed, TypeError};
24465 for bad in [
24466 "",
24467 " ",
24468 "€€",
24469 "€€€€€",
24470 "[αβγ]",
24471 "(α, β]",
24472 "[1, 2, 3]",
24473 "[1 2]",
24474 "]1, 2[",
24475 ] {
24476 let err = Interval::parse(bad).expect_err("malformed interval must return Err");
24477 assert!(matches!(err, TypeError::ValueNotParseable { .. }));
24478 }
24479 let parsed = Interval::parse(" [1.5, 3.5) ").expect("valid interval");
24481 assert_eq!(parsed.left, 1.5);
24482 assert_eq!(parsed.right, 3.5);
24483 assert_eq!(parsed.closed, IntervalClosed::Left);
24484 }
24485
24486 #[test]
24487 fn period_scalar_calendar_asfreq_to_timestamp_and_interval_closed_open_match_pandas_uo1wg() {
24488 use super::{Interval, IntervalClosed, Period, PeriodFreq, Timestamp};
24489
24490 let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
24492 assert!(!right.closed_left());
24493 assert!(right.closed_right());
24494 assert!(right.open_left());
24495 assert!(!right.open_right());
24496
24497 let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
24498 assert!(left.closed_left());
24499 assert!(!left.closed_right());
24500 assert!(!left.open_left());
24501 assert!(left.open_right());
24502
24503 let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
24504 assert!(both.closed_left());
24505 assert!(both.closed_right());
24506 assert!(!both.open_left());
24507 assert!(!both.open_right());
24508
24509 let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
24510 assert!(!neither.closed_left());
24511 assert!(!neither.closed_right());
24512 assert!(neither.open_left());
24513 assert!(neither.open_right());
24514
24515 let p_m = Period::parse("2024-03").expect("2024-03");
24517 assert_eq!(p_m.year(), Some(2024));
24518 assert_eq!(p_m.month(), Some(3));
24519 assert_eq!(p_m.day(), Some(31));
24520 assert_eq!(p_m.hour(), Some(0));
24521 assert_eq!(p_m.minute(), Some(0));
24522 assert_eq!(p_m.second(), Some(0));
24523 assert_eq!(p_m.quarter(), Some(1));
24524 assert_eq!(p_m.qyear(), Some(2024));
24525 assert_eq!(p_m.weekday(), Some(6));
24526 assert_eq!(p_m.dayofweek(), Some(6));
24527 assert_eq!(p_m.day_of_week(), Some(6));
24528 assert_eq!(p_m.dayofyear(), Some(91));
24529 assert_eq!(p_m.day_of_year(), Some(91));
24530 assert_eq!(p_m.days_in_month(), Some(31));
24531 assert_eq!(p_m.daysinmonth(), Some(31));
24532 assert_eq!(p_m.week(), Some(13));
24533 assert_eq!(p_m.weekofyear(), Some(13));
24534 assert_eq!(p_m.is_leap_year(), Some(true));
24535 assert_eq!(p_m.start_time().value(), 1_709_251_200_000_000_000);
24536 assert_eq!(p_m.end_time().value(), 1_711_929_599_999_999_999);
24537 assert_eq!(p_m.to_timestamp("start").unwrap(), p_m.start_time());
24538 assert_eq!(p_m.to_timestamp("end").unwrap(), p_m.end_time());
24539 assert_eq!(
24540 p_m.asfreq("D").unwrap(),
24541 Period::parse("2024-03-31").unwrap()
24542 );
24543 assert_eq!(
24544 p_m.asfreq_with_how("D", "start").unwrap(),
24545 Period::parse("2024-03-01").unwrap()
24546 );
24547 assert_eq!(p_m.strftime("%Y-%m-%d"), "2024-03-31");
24548
24549 let ts_feb = Timestamp::parse("2024-02-15").unwrap();
24551 let p_qjan = ts_feb.to_period("Q-JAN").unwrap();
24552 assert_eq!(p_qjan.to_string(), "2025Q1");
24553 assert_eq!(p_qjan.year(), Some(2024));
24554 assert_eq!(p_qjan.qyear(), Some(2025));
24555 assert_eq!(p_qjan.quarter(), Some(1));
24556 assert_eq!(p_qjan.month(), Some(4));
24557 assert_eq!(p_qjan.day(), Some(30));
24558 assert_eq!(p_qjan.days_in_month(), Some(30));
24559 assert_eq!(p_qjan.start_time().value(), 1_706_745_600_000_000_000);
24560 assert_eq!(p_qjan.end_time().value(), 1_714_521_599_999_999_999);
24561 assert_eq!(p_qjan.strftime("%Y-%m-%d"), "2024-04-30");
24562
24563 let p_fri = Timestamp::parse("2024-03-15")
24565 .unwrap()
24566 .to_period("B")
24567 .unwrap();
24568 assert_eq!(p_fri.day(), Some(15));
24569 assert_eq!(p_fri.weekday(), Some(4));
24570 assert_eq!(
24571 p_fri.end_time().value(),
24572 p_fri.start_time().value() + 86_400_000_000_000 - 1
24573 );
24574 assert_eq!(
24575 p_fri.asfreq_with_how("D", "E").unwrap(),
24576 Period::parse("2024-03-15").unwrap()
24577 );
24578
24579 let p_now = Period::now("D").expect("Period::now(D)");
24581 assert_eq!(p_now.freq(), PeriodFreq::Daily);
24582 assert!(!p_now.is_nat());
24583
24584 let p_nat = Period::new(i64::MIN, PeriodFreq::Monthly);
24586 assert!(p_nat.is_nat());
24587 assert_eq!(p_nat.year(), None);
24588 assert_eq!(p_nat.qyear(), None);
24589 assert_eq!(p_nat.quarter(), None);
24590 assert_eq!(p_nat.is_leap_year(), None);
24591 assert!(p_nat.start_time().is_nat());
24592 assert!(p_nat.end_time().is_nat());
24593 assert_eq!(p_nat.strftime("%Y-%m-%d"), "NaT");
24594 assert!(p_nat.asfreq("D").unwrap().is_nat());
24595 assert_eq!(p_nat.asfreq("D").unwrap().freq(), PeriodFreq::Daily);
24596 assert!(p_m.asfreq("NOT_A_FREQ").is_err());
24597 assert!(p_m.asfreq_with_how("D", "middle").is_err());
24598 assert!(p_m.to_timestamp("middle").is_err());
24599 assert!(Timestamp::nat().to_period("D").is_err());
24600 }
24601
24602 #[test]
24603 fn timestamp_tz_localize_convert_isoformat_tzname_and_getters_match_pandas_sddfo() {
24604 use crate::{TimeZoneError, Timestamp, TypeError};
24605
24606 let ts_naive = Timestamp::parse("2024-01-01T03:30:00").unwrap();
24608 assert_eq!(ts_naive.value(), 1_704_079_800_000_000_000);
24609 assert_eq!(ts_naive.tzname(), None);
24610
24611 let ts_ny = ts_naive.tz_localize(Some("America/New_York"));
24612 assert_eq!(ts_ny.value(), 1_704_097_800_000_000_000);
24613 assert_eq!(ts_ny.isoformat(), "2024-01-01T03:30:00-05:00");
24614 assert_eq!(ts_ny.tzname().as_deref(), Some("EST"));
24615 assert_eq!(ts_ny.year(), Some(2024));
24616 assert_eq!(ts_ny.month(), Some(1));
24617 assert_eq!(ts_ny.day(), Some(1));
24618 assert_eq!(ts_ny.hour(), Some(3));
24619 assert_eq!(ts_ny.minute(), Some(30));
24620
24621 let ts_utc = Timestamp::parse("2024-01-01T03:30:00Z").unwrap();
24623 let ts_from_utc = ts_utc.tz_convert("America/New_York");
24624 assert_eq!(ts_from_utc.value(), 1_704_079_800_000_000_000);
24625 assert_eq!(ts_from_utc.isoformat(), "2023-12-31T22:30:00-05:00");
24626 assert_eq!(ts_from_utc.tzname().as_deref(), Some("EST"));
24627 assert_eq!(ts_from_utc.year(), Some(2023));
24628 assert_eq!(ts_from_utc.month(), Some(12));
24629 assert_eq!(ts_from_utc.day(), Some(31));
24630 assert_eq!(ts_from_utc.hour(), Some(22));
24631 assert_eq!(ts_from_utc.minute(), Some(30));
24632 assert_eq!(ts_from_utc.dayofweek(), Some(6));
24633 assert_eq!(ts_from_utc.day_name(), "Sunday");
24634 assert_eq!(ts_from_utc.month_name(), "December");
24635 assert_eq!(ts_from_utc.toordinal(), Some(738_885));
24636 assert_eq!(ts_from_utc.is_year_end(), Some(true));
24637 assert_eq!(ts_from_utc.is_year_start(), Some(false));
24638
24639 let stripped = ts_from_utc.tz_localize(None);
24641 assert_eq!(stripped.tzinfo(), None);
24642 assert_eq!(stripped.value(), 1_704_061_800_000_000_000);
24643 assert_eq!(stripped.isoformat(), "2023-12-31T22:30:00");
24644
24645 let ts_summer = Timestamp::parse("2024-07-01T12:00:00")
24647 .unwrap()
24648 .tz_localize(Some("America/New_York"));
24649 assert_eq!(ts_summer.isoformat(), "2024-07-01T12:00:00-04:00");
24650 assert_eq!(ts_summer.tzname().as_deref(), Some("EDT"));
24651
24652 let replaced = ts_from_utc.replace(Some(2025), None, None, None, None, None, None, None);
24654 assert_eq!(replaced.value(), 1_767_238_200_000_000_000);
24655 assert_eq!(replaced.isoformat(), "2025-12-31T22:30:00-05:00");
24656
24657 assert_eq!(
24659 ts_ny.try_tz_localize(Some("UTC")),
24660 Err(TypeError::AlreadyTzAware)
24661 );
24662 assert!(ts_ny.tz_localize(Some("UTC")).is_nat());
24663 assert_eq!(
24664 ts_naive.try_tz_convert(Some("UTC")),
24665 Err(TypeError::TzNaiveCannotConvert)
24666 );
24667 assert!(ts_naive.tz_convert("UTC").is_nat());
24668 assert!(matches!(
24669 ts_naive.try_tz_localize(Some("Mars/Olympus")),
24670 Err(TypeError::TimeZone(TimeZoneError::Unknown(_)))
24671 ));
24672 assert!(matches!(
24673 ts_ny.try_tz_convert(Some("Mars/Olympus")),
24674 Err(TypeError::TimeZone(TimeZoneError::Unknown(_)))
24675 ));
24676 }
24677}